autotel-devtools 22.0.0 → 23.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +183 -28
  2. package/dist/cli.cjs +80 -13
  3. package/dist/cli.js +80 -13
  4. package/dist/compile-JDFHUCo5.d.cts +177 -0
  5. package/dist/compile-JDFHUCo5.d.ts +177 -0
  6. package/dist/{error-aggregator-D8VKciLY.d.ts → error-aggregator-B52JI8jL.d.ts} +1 -1
  7. package/dist/{error-aggregator-DCEKMOm3.d.cts → error-aggregator-DSwUvgFF.d.cts} +1 -1
  8. package/dist/exporter-C88W22vY.d.ts +576 -0
  9. package/dist/exporter-OoWkSMCR.d.cts +576 -0
  10. package/dist/fullpage.global.js +39 -0
  11. package/dist/grpc-D0B3P9sI.cjs +82 -0
  12. package/dist/grpc-DY-C1jSU.js +77 -0
  13. package/dist/http-1afd_01N.cjs +3991 -0
  14. package/dist/http-gk1xapnA.js +3825 -0
  15. package/dist/index.cjs +25 -7
  16. package/dist/index.d.cts +30 -3
  17. package/dist/index.d.ts +30 -3
  18. package/dist/index.js +25 -7
  19. package/dist/{listen-DBfsfcdd.js → listen-D-lLgfro.js} +5 -2
  20. package/dist/{listen-CEJ3nYJf.cjs → listen-l09RRHht.cjs} +5 -2
  21. package/dist/parse-BRlosZft.cjs +642 -0
  22. package/dist/parse-D_RmPPQs.js +612 -0
  23. package/dist/query/index.cjs +8 -0
  24. package/dist/query/index.d.cts +16 -0
  25. package/dist/query/index.d.ts +16 -0
  26. package/dist/query/index.js +3 -0
  27. package/dist/server/exporter.d.cts +1 -1
  28. package/dist/server/exporter.d.ts +1 -1
  29. package/dist/server/index.cjs +6 -2
  30. package/dist/server/index.d.cts +19 -6
  31. package/dist/server/index.d.ts +18 -5
  32. package/dist/server/index.js +3 -2
  33. package/dist/types-B0tjwFqj.d.cts +107 -0
  34. package/dist/types-DM8y4A9Z.d.ts +107 -0
  35. package/dist/widget.global.js +15 -24
  36. package/dist/wire/index.cjs +7 -0
  37. package/dist/wire/index.d.cts +26 -0
  38. package/dist/wire/index.d.ts +26 -0
  39. package/dist/wire/index.js +3 -0
  40. package/dist/wire-2Rmfg6IT.js +51 -0
  41. package/dist/wire-CHU1PkMo.cjs +75 -0
  42. package/package.json +21 -5
  43. package/dist/exporter-Dt4kx128.d.cts +0 -207
  44. package/dist/exporter-Due9Rd4s.d.ts +0 -207
  45. package/dist/http-CNZMrnzv.js +0 -1453
  46. package/dist/http-CXSzX4ee.cjs +0 -1607
@@ -0,0 +1,3825 @@
1
+ import { i as encodeTraces } from "./wire-2Rmfg6IT.js";
2
+ import { i as asString, o as stringAttr, t as asObject } from "./json-fields-CPjKZ2WH.js";
3
+ import { t as pickRoot } from "./trace-root-EHnvuA7f.js";
4
+ import { a as compileWhere, t as parse } from "./parse-D_RmPPQs.js";
5
+ import { t as getResourceName } from "./resource-utils-B4UVvfnH.js";
6
+ import { createServer } from "node:http";
7
+ import { WebSocket, WebSocketServer } from "ws";
8
+ import { ingestAgentEvents, ingestAgentMetrics } from "autotel-agents";
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { createHash } from "node:crypto";
11
+ import { gzipSync } from "node:zlib";
12
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
13
+ import path, { dirname, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import protobuf from "protobufjs";
16
+
17
+ //#region src/server/error-aggregator.ts
18
+ var ErrorAggregator = class {
19
+ errorGroups = /* @__PURE__ */ new Map();
20
+ options;
21
+ constructor(options = {}) {
22
+ this.options = {
23
+ maxGroups: options.maxGroups ?? 100,
24
+ maxAffectedTraces: options.maxAffectedTraces ?? 10,
25
+ maxAffectedSpans: options.maxAffectedSpans ?? 5,
26
+ stackFramesForFingerprint: options.stackFramesForFingerprint ?? 5
27
+ };
28
+ }
29
+ /**
30
+ * Add an error occurrence to the aggregator
31
+ */
32
+ addError(occurrence) {
33
+ const fingerprint = this.generateFingerprint(occurrence);
34
+ const existing = this.errorGroups.get(fingerprint);
35
+ if (existing) {
36
+ existing.count++;
37
+ existing.lastSeen = occurrence.timestamp;
38
+ if (!existing.affectedTraces.includes(occurrence.traceId)) {
39
+ existing.affectedTraces.push(occurrence.traceId);
40
+ if (existing.affectedTraces.length > this.options.maxAffectedTraces) existing.affectedTraces.shift();
41
+ }
42
+ if (!existing.affectedSpans.includes(occurrence.spanName)) {
43
+ existing.affectedSpans.push(occurrence.spanName);
44
+ if (existing.affectedSpans.length > this.options.maxAffectedSpans) existing.affectedSpans.shift();
45
+ }
46
+ return existing;
47
+ }
48
+ const newGroup = {
49
+ fingerprint,
50
+ type: occurrence.error.type,
51
+ message: occurrence.error.message,
52
+ stackTrace: this.normalizeStackTrace(occurrence.error.stackTrace),
53
+ count: 1,
54
+ firstSeen: occurrence.timestamp,
55
+ lastSeen: occurrence.timestamp,
56
+ affectedTraces: [occurrence.traceId],
57
+ affectedSpans: [occurrence.spanName],
58
+ service: occurrence.service,
59
+ attributes: occurrence.attributes
60
+ };
61
+ if (this.errorGroups.size >= this.options.maxGroups) this.evictOldestGroup();
62
+ this.errorGroups.set(fingerprint, newGroup);
63
+ return newGroup;
64
+ }
65
+ /**
66
+ * Extract errors from a trace and add them to the aggregator
67
+ */
68
+ addErrorsFromTrace(trace) {
69
+ const addedGroups = [];
70
+ for (const span of trace.spans) if (span.status.code === "ERROR") {
71
+ const occurrence = this.extractErrorFromSpan(span, trace);
72
+ if (occurrence) {
73
+ const group = this.addError(occurrence);
74
+ addedGroups.push(group);
75
+ }
76
+ }
77
+ return addedGroups;
78
+ }
79
+ /**
80
+ * Extract error occurrence from a span
81
+ */
82
+ extractErrorFromSpan(span, trace) {
83
+ const exceptionEvent = span.events?.find((e) => e.name === "exception");
84
+ const errorType = stringAttr(span.attributes, "exception.type", "error.type") ?? stringAttr(exceptionEvent?.attributes, "exception.type") ?? "Error";
85
+ const errorMessage = span.status.message || stringAttr(span.attributes, "exception.message", "error.message") || "Unknown error";
86
+ const stackTrace = stringAttr(span.attributes, "exception.stacktrace", "exception.stack", "error.stack") ?? this.extractStackFromEvents(span);
87
+ return {
88
+ traceId: trace.traceId,
89
+ spanId: span.spanId,
90
+ spanName: span.name,
91
+ service: trace.service,
92
+ timestamp: span.endTime,
93
+ error: {
94
+ type: errorType,
95
+ message: errorMessage,
96
+ stackTrace,
97
+ fingerprint: stringAttr(span.attributes, "exception.fingerprint") ?? stringAttr(exceptionEvent?.attributes, "exception.fingerprint")
98
+ },
99
+ attributes: this.extractRelevantAttributes(span.attributes)
100
+ };
101
+ }
102
+ /**
103
+ * Extract stack trace from span events (exception events)
104
+ */
105
+ extractStackFromEvents(span) {
106
+ if (!span.events) return void 0;
107
+ const exceptionEvent = span.events.find((e) => e.name === "exception");
108
+ if (exceptionEvent?.attributes) return stringAttr(exceptionEvent.attributes, "exception.stacktrace", "exception.stack");
109
+ }
110
+ /**
111
+ * Extract relevant attributes for error context
112
+ */
113
+ extractRelevantAttributes(attributes) {
114
+ const relevant = {};
115
+ for (const key of [
116
+ "http.method",
117
+ "http.url",
118
+ "http.route",
119
+ "http.status_code",
120
+ "db.system",
121
+ "db.operation",
122
+ "rpc.method",
123
+ "rpc.service",
124
+ "code.function",
125
+ "code.filepath",
126
+ "user.id",
127
+ "operation.name"
128
+ ]) if (key in attributes) relevant[key] = attributes[key];
129
+ return relevant;
130
+ }
131
+ /**
132
+ * Generate a fingerprint for error grouping
133
+ *
134
+ * Uses error type + first N stack frames (normalized)
135
+ */
136
+ generateFingerprint(occurrence) {
137
+ if (occurrence.error.fingerprint) return occurrence.error.fingerprint;
138
+ const parts = [occurrence.error.type];
139
+ if (occurrence.error.stackTrace) {
140
+ const frames = this.extractStackFrames(occurrence.error.stackTrace, this.options.stackFramesForFingerprint);
141
+ parts.push(...frames);
142
+ } else parts.push(this.normalizeMessage(occurrence.error.message));
143
+ return this.simpleHash(parts.join("|"));
144
+ }
145
+ /**
146
+ * Extract and normalize stack frames from a stack trace
147
+ */
148
+ extractStackFrames(stackTrace, count) {
149
+ const lines = stackTrace.split("\n");
150
+ const frames = [];
151
+ for (const line of lines) {
152
+ if (frames.length >= count) break;
153
+ const trimmed = line.trim();
154
+ const nodeMatch = trimmed.match(/^at\s+(.+?)\s+\((.+?):(\d+):\d+\)$/);
155
+ if (nodeMatch) {
156
+ frames.push(`${nodeMatch[1]}@${this.normalizeFilePath(nodeMatch[2])}`);
157
+ continue;
158
+ }
159
+ const anonMatch = trimmed.match(/^at\s+(.+?):(\d+):\d+$/);
160
+ if (anonMatch) {
161
+ frames.push(`anonymous@${this.normalizeFilePath(anonMatch[1])}`);
162
+ continue;
163
+ }
164
+ const browserMatch = trimmed.match(/^(.+?)@(.+?):(\d+):\d+$/);
165
+ if (browserMatch) {
166
+ frames.push(`${browserMatch[1]}@${this.normalizeFilePath(browserMatch[2])}`);
167
+ continue;
168
+ }
169
+ }
170
+ return frames;
171
+ }
172
+ /**
173
+ * Normalize file path by removing absolute path prefixes and node_modules paths
174
+ */
175
+ normalizeFilePath(filePath) {
176
+ const nodeModulesMatch = filePath.match(/node_modules\/(@[^/]+\/[^/]+|[^/]+)/);
177
+ if (nodeModulesMatch) return `[npm]/${nodeModulesMatch[1]}`;
178
+ return filePath.replace(/^.*?\/src\//, "src/").replace(/^.*?\/dist\//, "dist/").replace(/^.*?\/lib\//, "lib/").replace(/^file:\/\//, "");
179
+ }
180
+ /**
181
+ * Normalize error message by removing dynamic parts
182
+ */
183
+ normalizeMessage(message) {
184
+ return message.replaceAll(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "[UUID]").replaceAll(/\b[0-9a-f]{16,}\b/gi, "[ID]").replaceAll(/\d+/g, "[N]").replaceAll(/"[^"]*"/g, "\"[STR]\"").replaceAll(/'[^']*'/g, "'[STR]'").slice(0, 200);
185
+ }
186
+ /**
187
+ * Normalize stack trace for display
188
+ */
189
+ normalizeStackTrace(stackTrace) {
190
+ if (!stackTrace) return void 0;
191
+ return stackTrace.split("\n").slice(0, 10).join("\n");
192
+ }
193
+ /**
194
+ * Simple hash function for fingerprinting
195
+ */
196
+ simpleHash(str) {
197
+ let hash = 0;
198
+ for (let i = 0; i < str.length; i++) {
199
+ const char = str.charCodeAt(i);
200
+ hash = (hash << 5) - hash + char;
201
+ hash = hash & hash;
202
+ }
203
+ return Math.abs(hash).toString(16).padStart(8, "0");
204
+ }
205
+ /**
206
+ * Evict the oldest error group
207
+ */
208
+ evictOldestGroup() {
209
+ let oldest = null;
210
+ for (const [fingerprint, group] of this.errorGroups) if (!oldest || group.lastSeen < oldest.lastSeen) oldest = {
211
+ fingerprint,
212
+ lastSeen: group.lastSeen
213
+ };
214
+ if (oldest) this.errorGroups.delete(oldest.fingerprint);
215
+ }
216
+ /**
217
+ * Get all error groups, sorted by most recent
218
+ */
219
+ getErrorGroups() {
220
+ return [...this.errorGroups.values()].sort((a, b) => b.lastSeen - a.lastSeen);
221
+ }
222
+ /**
223
+ * Get error groups sorted by count (most frequent first)
224
+ */
225
+ getErrorGroupsByFrequency() {
226
+ return [...this.errorGroups.values()].sort((a, b) => b.count - a.count);
227
+ }
228
+ /**
229
+ * Get a specific error group by fingerprint
230
+ */
231
+ getErrorGroup(fingerprint) {
232
+ return this.errorGroups.get(fingerprint);
233
+ }
234
+ /**
235
+ * Get error groups for a specific service
236
+ */
237
+ getErrorGroupsByService(service) {
238
+ return this.getErrorGroups().filter((g) => g.service === service);
239
+ }
240
+ /**
241
+ * Get total error count across all groups
242
+ */
243
+ getTotalErrorCount() {
244
+ let total = 0;
245
+ for (const group of this.errorGroups.values()) total += group.count;
246
+ return total;
247
+ }
248
+ /**
249
+ * Get error statistics
250
+ */
251
+ getStats() {
252
+ const oneHourAgo = Date.now() - 3600 * 1e3;
253
+ let recentErrors = 0;
254
+ const typeCount = /* @__PURE__ */ new Map();
255
+ for (const group of this.errorGroups.values()) {
256
+ if (group.lastSeen > oneHourAgo) recentErrors += group.count;
257
+ typeCount.set(group.type, (typeCount.get(group.type) || 0) + group.count);
258
+ }
259
+ const topErrorTypes = [...typeCount.entries()].map(([type, count]) => ({
260
+ type,
261
+ count
262
+ })).sort((a, b) => b.count - a.count).slice(0, 5);
263
+ return {
264
+ totalGroups: this.errorGroups.size,
265
+ totalErrors: this.getTotalErrorCount(),
266
+ recentErrors,
267
+ topErrorTypes
268
+ };
269
+ }
270
+ /**
271
+ * Clear all error groups
272
+ */
273
+ clear() {
274
+ this.errorGroups.clear();
275
+ }
276
+ /**
277
+ * Clear old error groups (not seen in given time window)
278
+ */
279
+ clearOlderThan(maxAgeMs) {
280
+ const cutoff = Date.now() - maxAgeMs;
281
+ let cleared = 0;
282
+ for (const [fingerprint, group] of this.errorGroups) if (group.lastSeen < cutoff) {
283
+ this.errorGroups.delete(fingerprint);
284
+ cleared++;
285
+ }
286
+ return cleared;
287
+ }
288
+ };
289
+
290
+ //#endregion
291
+ //#region src/server/telemetry-limits.ts
292
+ const defaultLimit = 100;
293
+ function parseLimit(value) {
294
+ if (!value) return void 0;
295
+ const parsed = Number.parseInt(value, 10);
296
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
297
+ }
298
+ function resolveTelemetryLimits(args = {}) {
299
+ const env = args.env ?? process.env;
300
+ const fallback = args.maxHistory ?? defaultLimit;
301
+ return {
302
+ maxTraceCount: args.maxTraceCount ?? parseLimit(env.AUTOTEL_MAX_TRACE_COUNT) ?? fallback,
303
+ maxLogCount: args.maxLogCount ?? parseLimit(env.AUTOTEL_MAX_LOG_COUNT) ?? fallback
304
+ };
305
+ }
306
+ function appendWithLimit(items, item, limit) {
307
+ if (limit <= 0) return [];
308
+ const next = [...items, item];
309
+ return next.length > limit ? next.slice(next.length - limit) : next;
310
+ }
311
+ function appendManyWithLimit(items, incoming, limit) {
312
+ if (limit <= 0 || incoming.length === 0) return limit <= 0 ? [] : items;
313
+ const next = [...items, ...incoming];
314
+ return next.length > limit ? next.slice(next.length - limit) : next;
315
+ }
316
+ function applyTelemetryLimits(data, limits) {
317
+ return {
318
+ ...data,
319
+ traces: data.traces.slice(-limits.maxTraceCount),
320
+ logs: data.logs.slice(-limits.maxLogCount)
321
+ };
322
+ }
323
+
324
+ //#endregion
325
+ //#region src/server/origin-guard.ts
326
+ const LOOPBACK_IPV6 = /* @__PURE__ */ new Set(["::1", "0:0:0:0:0:0:0:1"]);
327
+ /** True for `localhost`, any `127.x.x.x`, and IPv6 loopback. Case-insensitive. */
328
+ function isLoopbackHostname(hostname) {
329
+ const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
330
+ return h === "localhost" || /^127\./.test(h) || LOOPBACK_IPV6.has(h);
331
+ }
332
+ /** Hostname from a `Host` header (`host`, `host:port`, `[::1]:port`). */
333
+ function hostnameFromHostHeader(host) {
334
+ const h = host.trim();
335
+ if (h.startsWith("[")) {
336
+ const end = h.indexOf("]");
337
+ return end > 0 ? h.slice(1, end) : h;
338
+ }
339
+ const colon = h.indexOf(":");
340
+ return colon === -1 ? h : h.slice(0, colon);
341
+ }
342
+ /** True when the `Host` header names a loopback host. */
343
+ function hostHeaderIsLoopback(host) {
344
+ return isLoopbackHostname(hostnameFromHostHeader(host));
345
+ }
346
+ /** True when an `Origin` header names a loopback origin. A malformed or opaque
347
+ * origin (e.g. the literal `null` from a sandboxed iframe) is treated as
348
+ * non-loopback. */
349
+ function originIsLoopback(origin) {
350
+ try {
351
+ return isLoopbackHostname(new URL(origin).hostname);
352
+ } catch {
353
+ return false;
354
+ }
355
+ }
356
+ /**
357
+ * Decide whether a request to a sensitive (read/mutate) endpoint is allowed.
358
+ * - A present, non-loopback `Origin` is always rejected (cross-origin read).
359
+ * - When `loopbackOnly`, a present, non-loopback `Host` is rejected (DNS
360
+ * rebinding). Skipped when the receiver is bound to a non-loopback host.
361
+ */
362
+ function allowSensitiveRequest(headers, loopbackOnly) {
363
+ const { origin, host } = headers;
364
+ if (origin && origin.length > 0 && !originIsLoopback(origin)) return false;
365
+ if (loopbackOnly && host && host.length > 0 && !hostHeaderIsLoopback(host)) return false;
366
+ return true;
367
+ }
368
+
369
+ //#endregion
370
+ //#region src/server/metric-reduction.ts
371
+ const DEFAULT_MAX_EXEMPLARS = 32;
372
+ /** Reduce a metric series to a chart-sized result before it crosses the wire. */
373
+ function reduceMetricPoints(points, kind, maxPoints, options = {}) {
374
+ const maxExemplars = options.maxExemplars ?? DEFAULT_MAX_EXEMPLARS;
375
+ const limit = Math.max(4, Math.floor(maxPoints));
376
+ if (points.length <= limit) return capExemplars(points, maxExemplars);
377
+ if (kind === "histogram" || kind === "exponentialHistogram" || kind === "summary") {
378
+ if (options.temporality === "cumulative") return sampleCumulativeSnapshots(points, limit, maxExemplars);
379
+ return mergeDistributionBuckets(points, limit, maxExemplars);
380
+ }
381
+ return capExemplars(m4(points, limit), maxExemplars);
382
+ }
383
+ /** Cumulative points are complete snapshots; summing them double-counts. */
384
+ function sampleCumulativeSnapshots(points, limit, maxExemplars) {
385
+ const bucketSize = Math.ceil(points.length / limit);
386
+ const snapshots = [];
387
+ for (let start = 0; start < points.length; start += bucketSize) snapshots.push(points[Math.min(start + bucketSize, points.length) - 1]);
388
+ return capExemplars(snapshots, maxExemplars);
389
+ }
390
+ /** First/min/max/last sampling preserves spikes and troughs in every time bucket. */
391
+ function m4(points, limit) {
392
+ const bucketSize = Math.max(1, Math.ceil(points.length / Math.max(1, Math.floor(limit / 4))));
393
+ const selected = [];
394
+ for (let start = 0; start < points.length; start += bucketSize) {
395
+ const bucket = points.slice(start, start + bucketSize);
396
+ const byValue = [...bucket].sort((a, b) => (a.value ?? 0) - (b.value ?? 0));
397
+ const candidates = [
398
+ bucket[0],
399
+ byValue[0],
400
+ byValue[byValue.length - 1],
401
+ bucket[bucket.length - 1]
402
+ ];
403
+ const unique = /* @__PURE__ */ new Map();
404
+ for (const point of candidates) unique.set(point.timestamp, point);
405
+ selected.push(...[...unique.values()].sort((a, b) => a.timestamp - b.timestamp));
406
+ }
407
+ return selected.slice(0, limit);
408
+ }
409
+ function mergeDistributionBuckets(points, limit, maxExemplars) {
410
+ const bucketSize = Math.ceil(points.length / limit);
411
+ const out = [];
412
+ let remainingExemplars = maxExemplars;
413
+ for (let start = 0; start < points.length; start += bucketSize) {
414
+ const merged = mergePoints(points.slice(start, start + bucketSize), remainingExemplars);
415
+ remainingExemplars -= merged.exemplars?.length ?? 0;
416
+ out.push(merged);
417
+ }
418
+ return out;
419
+ }
420
+ function mergePoints(points, maxExemplars) {
421
+ const last = points[points.length - 1];
422
+ const counts = points.map((point) => point.count ?? 0);
423
+ const totalCount = counts.reduce((sum, value) => sum + value, 0);
424
+ const result = {
425
+ ...last,
426
+ startTimestamp: points[0].startTimestamp,
427
+ count: totalCount,
428
+ sum: sumDefined(points.map((point) => point.sum)),
429
+ min: minDefined(points.map((point) => point.min)),
430
+ max: maxDefined(points.map((point) => point.max)),
431
+ exemplars: maxExemplars <= 0 ? [] : points.flatMap((point) => point.exemplars ?? []).slice(-maxExemplars)
432
+ };
433
+ if (sameArrays(points.map((point) => point.explicitBounds))) result.bucketCounts = sumArrays(points.map((point) => point.bucketCounts));
434
+ if (points.every((point) => point.scale === last.scale)) {
435
+ result.zeroCount = points.reduce((sum, point) => sum + (point.zeroCount ?? 0), 0);
436
+ result.positive = mergeExponential(points.map((point) => point.positive));
437
+ result.negative = mergeExponential(points.map((point) => point.negative));
438
+ }
439
+ if (last.quantiles) result.quantiles = last.quantiles.map(({ quantile }) => {
440
+ let weight = 0;
441
+ let value = 0;
442
+ for (let index = 0; index < points.length; index++) {
443
+ const found = points[index].quantiles?.find((item) => item.quantile === quantile);
444
+ if (!found) continue;
445
+ const pointWeight = counts[index] || 1;
446
+ weight += pointWeight;
447
+ value += found.value * pointWeight;
448
+ }
449
+ return {
450
+ quantile,
451
+ value: weight === 0 ? 0 : value / weight
452
+ };
453
+ });
454
+ return result;
455
+ }
456
+ function mergeExponential(values) {
457
+ const buckets = values.filter((value) => value !== void 0);
458
+ if (buckets.length === 0) return void 0;
459
+ const start = Math.min(...buckets.map((bucket) => bucket.offset));
460
+ const end = Math.max(...buckets.map((bucket) => bucket.offset + bucket.bucketCounts.length));
461
+ const bucketCounts = Array.from({ length: end - start }, () => 0);
462
+ for (const bucket of buckets) for (let index = 0; index < bucket.bucketCounts.length; index++) bucketCounts[bucket.offset - start + index] += bucket.bucketCounts[index];
463
+ return {
464
+ offset: start,
465
+ bucketCounts
466
+ };
467
+ }
468
+ function sameArrays(values) {
469
+ const first = JSON.stringify(values[0]);
470
+ return values.every((value) => JSON.stringify(value) === first);
471
+ }
472
+ function sumArrays(values) {
473
+ if (values.some((value) => value === void 0)) return void 0;
474
+ return values.reduce((sum, value) => value.map((item, index) => item + (sum[index] ?? 0)), []);
475
+ }
476
+ function sumDefined(values) {
477
+ const found = values.filter((value) => value !== void 0);
478
+ return found.length === 0 ? void 0 : found.reduce((sum, value) => sum + value, 0);
479
+ }
480
+ function minDefined(values) {
481
+ const found = values.filter((value) => value !== void 0);
482
+ return found.length === 0 ? void 0 : Math.min(...found);
483
+ }
484
+ function maxDefined(values) {
485
+ const found = values.filter((value) => value !== void 0);
486
+ return found.length === 0 ? void 0 : Math.max(...found);
487
+ }
488
+ function capExemplars(points, max) {
489
+ let remaining = max;
490
+ return points.map((point) => {
491
+ if (!point.exemplars) return point;
492
+ const exemplars = point.exemplars.slice(0, remaining);
493
+ remaining -= exemplars.length;
494
+ return {
495
+ ...point,
496
+ exemplars
497
+ };
498
+ });
499
+ }
500
+
501
+ //#endregion
502
+ //#region src/widget/timeWindow.ts
503
+ const PRESETS = [
504
+ {
505
+ id: "all",
506
+ label: "All time",
507
+ durationMs: null
508
+ },
509
+ {
510
+ id: "5m",
511
+ label: "Last 5m",
512
+ durationMs: 5 * 6e4
513
+ },
514
+ {
515
+ id: "15m",
516
+ label: "Last 15m",
517
+ durationMs: 15 * 6e4
518
+ },
519
+ {
520
+ id: "30m",
521
+ label: "Last 30m",
522
+ durationMs: 30 * 6e4
523
+ },
524
+ {
525
+ id: "1h",
526
+ label: "Last 1h",
527
+ durationMs: 60 * 6e4
528
+ },
529
+ {
530
+ id: "3h",
531
+ label: "Last 3h",
532
+ durationMs: 180 * 6e4
533
+ },
534
+ {
535
+ id: "6h",
536
+ label: "Last 6h",
537
+ durationMs: 360 * 6e4
538
+ },
539
+ {
540
+ id: "24h",
541
+ label: "Last 24h",
542
+ durationMs: 1440 * 6e4
543
+ },
544
+ {
545
+ id: "7d",
546
+ label: "Last 7d",
547
+ durationMs: 10080 * 6e4
548
+ }
549
+ ];
550
+ /**
551
+ * Typed as the preset arm rather than the union: `serializeWindow` compares
552
+ * against `DEFAULT_SELECTION.preset`, which the widened union does not expose.
553
+ */
554
+ const DEFAULT_SELECTION = {
555
+ type: "preset",
556
+ preset: "all"
557
+ };
558
+ const PRESET_BY_ID = new Map(PRESETS.map((p) => [p.id, p]));
559
+ /**
560
+ * Serialize for the URL hash, or `null` when the selection is the default.
561
+ *
562
+ * Omitting the default keeps shared links free of parameters that say nothing.
563
+ */
564
+ function serializeWindow(selection) {
565
+ if (selection.type === "preset") return selection.preset === DEFAULT_SELECTION.preset ? null : selection.preset;
566
+ return `custom:${selection.start}:${selection.end}`;
567
+ }
568
+
569
+ //#endregion
570
+ //#region src/server/store/store.ts
571
+ /**
572
+ * Telemetry store, backed by `node:sqlite`.
573
+ *
574
+ * `node:sqlite` is in the standard library on Node 24, which this package
575
+ * already requires — so persistence, indexes and a real query engine cost no
576
+ * dependency at all. The store is what lets the viewer hold more than a
577
+ * screenful of telemetry, survive a restart, and answer a query without
578
+ * shipping every span to the browser first.
579
+ *
580
+ * Layout: `traces` holds one row per trace (the list view reads only this), and
581
+ * `spans` holds the detail. `service` is denormalised onto each span row so a
582
+ * span-level filter (`service = api AND duration > 100`) never needs a join.
583
+ *
584
+ * Concurrency: sqlite serialises writes itself and every method here is
585
+ * synchronous, so there is no interleaving to guard. WAL is enabled so a long
586
+ * read cannot block ingest.
587
+ */
588
+ /**
589
+ * How far either side of a trace the deep-linked window reaches.
590
+ *
591
+ * A window of exactly the trace's own bounds is a correct answer that reads
592
+ * badly: the trace touches both edges with nothing around it. A minute of air
593
+ * shows what else was happening, and gives a zero-duration trace a window with
594
+ * width at all.
595
+ */
596
+ const DEEP_LINK_PAD_MS = 6e4;
597
+ /**
598
+ * A link back into the viewer, pointing at a trace and optionally one span.
599
+ *
600
+ * **The window is the part that is easy to leave out and expensive to omit.**
601
+ * A link is read later than it is made, by an agent handing one to a person or
602
+ * a person pasting one into an incident channel, and by then the viewer's
603
+ * default range has rolled past the trace. The telemetry is still there and
604
+ * the view is not looking at it, which reads as "the tool lost my data".
605
+ *
606
+ * Serialized with the widget's own `serializeWindow`, and pinned by a test
607
+ * that parses the result with the widget's own `parseNavHash`, so the two ends
608
+ * cannot drift into agreeing on nothing.
609
+ */
610
+ function traceDeepLink(traceId, bounds, spanId) {
611
+ const params = new URLSearchParams({
612
+ tab: "traces",
613
+ trace: traceId
614
+ });
615
+ if (spanId) params.set("span", spanId);
616
+ params.set("window", serializeWindow({
617
+ type: "custom",
618
+ start: Number(bounds.start_time) - DEEP_LINK_PAD_MS,
619
+ end: Number(bounds.end_time) + DEEP_LINK_PAD_MS
620
+ }) ?? "");
621
+ return `/#${params.toString()}`;
622
+ }
623
+ /**
624
+ * Shape of the schema this build knows how to read.
625
+ *
626
+ * Bump it whenever a change to the DDL cannot be reached by the migrations in
627
+ * this file. A `--db` file written by a newer build is refused rather than
628
+ * queried, because the alternative is an opaque "no such column" thrown from
629
+ * whichever query happens to run first.
630
+ *
631
+ * `0` means a file written before this guard existed. Those are adopted and
632
+ * stamped, since the migrations above already cover every shape they can be in.
633
+ */
634
+ const SCHEMA_VERSION = 1;
635
+ const DEFAULT_MAX_TRACES = 1e5;
636
+ const DEFAULT_MAX_METRIC_POINTS = 5e3;
637
+ const DEFAULT_MAX_LOGS = 1e5;
638
+ const DEFAULT_LIMIT = 100;
639
+ const MAX_QUERY_PAGE_SIZE = 1e3;
640
+ /**
641
+ * Spans scanned per side of a comparison.
642
+ *
643
+ * A cohort is a statistical population, not a page: the fractions are only as
644
+ * honest as the sample, so this is deliberately far larger than a list page.
645
+ */
646
+ const COHORT_ROW_LIMIT = 2e4;
647
+ /**
648
+ * Query vocabulary for logs.
649
+ *
650
+ * `severity` and `severity_number` are both exposed deliberately: the text is
651
+ * what people read, but "error and above" is a numeric comparison and string
652
+ * ordering cannot express it. Anything not named here is a log attribute.
653
+ */
654
+ const LOG_SCHEMA = {
655
+ columns: {
656
+ service: {
657
+ column: "service",
658
+ type: "string"
659
+ },
660
+ severity: {
661
+ column: "severity_text",
662
+ type: "string"
663
+ },
664
+ severity_number: {
665
+ column: "severity_number",
666
+ type: "number"
667
+ },
668
+ trace_id: {
669
+ column: "trace_id",
670
+ type: "string"
671
+ },
672
+ span_id: {
673
+ column: "span_id",
674
+ type: "string"
675
+ },
676
+ body: {
677
+ column: "body_text",
678
+ type: "string"
679
+ }
680
+ },
681
+ attributesColumn: "attributes",
682
+ freeTextColumns: [
683
+ "body",
684
+ "service",
685
+ "severity",
686
+ "trace_id"
687
+ ],
688
+ attributeIndex: {
689
+ table: "attribute_occurrences",
690
+ signal: "logs",
691
+ entitySql: "id"
692
+ }
693
+ };
694
+ /**
695
+ * Query vocabulary for spans.
696
+ *
697
+ * Anything not named here is treated as a span attribute, so every attribute a
698
+ * service emits is queryable without being declared.
699
+ */
700
+ /**
701
+ * Ties a child row to the span row being filtered.
702
+ *
703
+ * `s` is the alias `queryTraces` gives the spans table, the same coupling
704
+ * `attributeIndex.entitySql` already carries: these are trusted SQL fragments
705
+ * that must stay in step with the FROM clause the store writes. The event and
706
+ * link tests fail if the alias moves, which is what keeps them in step.
707
+ */
708
+ const SPAN_ROW_JOIN = "rel.trace_id = s.trace_id AND rel.span_id = s.span_id";
709
+ const SPAN_SCHEMA = {
710
+ columns: {
711
+ service: {
712
+ column: "service",
713
+ type: "string"
714
+ },
715
+ name: {
716
+ column: "name",
717
+ type: "string"
718
+ },
719
+ kind: {
720
+ column: "kind",
721
+ type: "string"
722
+ },
723
+ duration: {
724
+ column: "duration",
725
+ type: "number"
726
+ },
727
+ status: {
728
+ column: "status_code",
729
+ type: "string"
730
+ },
731
+ trace_id: {
732
+ column: "trace_id",
733
+ type: "string"
734
+ },
735
+ span_id: {
736
+ column: "span_id",
737
+ type: "string"
738
+ },
739
+ parent_span_id: {
740
+ column: "parent_span_id",
741
+ type: "string"
742
+ }
743
+ },
744
+ attributesColumn: "attributes",
745
+ freeTextColumns: [
746
+ "name",
747
+ "service",
748
+ "trace_id"
749
+ ],
750
+ attributeIndex: {
751
+ table: "attribute_occurrences",
752
+ signal: "traces",
753
+ entitySql: "(trace_id || ':' || span_id)"
754
+ },
755
+ related: {
756
+ "event.name": {
757
+ table: "span_events",
758
+ column: "name",
759
+ joinSql: SPAN_ROW_JOIN
760
+ },
761
+ "link.trace_id": {
762
+ table: "span_links",
763
+ column: "linked_trace_id",
764
+ joinSql: SPAN_ROW_JOIN
765
+ },
766
+ "link.span_id": {
767
+ table: "span_links",
768
+ column: "linked_span_id",
769
+ joinSql: SPAN_ROW_JOIN
770
+ }
771
+ }
772
+ };
773
+ const METRIC_SCHEMA = {
774
+ columns: {
775
+ name: {
776
+ column: "name",
777
+ type: "string"
778
+ },
779
+ kind: {
780
+ column: "kind",
781
+ type: "string"
782
+ },
783
+ unit: {
784
+ column: "unit",
785
+ type: "string"
786
+ },
787
+ description: {
788
+ column: "description",
789
+ type: "string"
790
+ },
791
+ service: {
792
+ column: "service",
793
+ type: "string"
794
+ }
795
+ },
796
+ attributesColumn: "resource",
797
+ freeTextColumns: [
798
+ "name",
799
+ "description",
800
+ "unit",
801
+ "service"
802
+ ]
803
+ };
804
+ const SPANS_TABLE_DDL = `
805
+ CREATE TABLE IF NOT EXISTS spans (
806
+ span_id TEXT NOT NULL,
807
+ trace_id TEXT NOT NULL,
808
+ parent_span_id TEXT,
809
+ name TEXT NOT NULL,
810
+ kind TEXT NOT NULL,
811
+ service TEXT,
812
+ start_time INTEGER NOT NULL,
813
+ end_time INTEGER NOT NULL,
814
+ duration INTEGER NOT NULL,
815
+ status_code TEXT NOT NULL,
816
+ status_message TEXT,
817
+ attributes TEXT NOT NULL DEFAULT '{}',
818
+ events TEXT,
819
+ links TEXT,
820
+ scope TEXT,
821
+ PRIMARY KEY (trace_id, span_id)
822
+ );
823
+ `;
824
+ const DDL = `
825
+ PRAGMA journal_mode = WAL;
826
+ PRAGMA synchronous = NORMAL;
827
+
828
+ CREATE TABLE IF NOT EXISTS traces (
829
+ trace_id TEXT PRIMARY KEY,
830
+ correlation_id TEXT,
831
+ service TEXT,
832
+ root_span_id TEXT,
833
+ start_time INTEGER NOT NULL,
834
+ end_time INTEGER NOT NULL,
835
+ duration INTEGER NOT NULL,
836
+ status TEXT NOT NULL,
837
+ partial INTEGER NOT NULL DEFAULT 0
838
+ );
839
+
840
+ ${SPANS_TABLE_DDL}
841
+
842
+ CREATE TABLE IF NOT EXISTS metric_series (
843
+ series_id TEXT PRIMARY KEY,
844
+ name TEXT NOT NULL,
845
+ unit TEXT,
846
+ description TEXT,
847
+ kind TEXT NOT NULL,
848
+ temporality TEXT,
849
+ monotonic INTEGER,
850
+ service TEXT NOT NULL,
851
+ scope_name TEXT,
852
+ scope_version TEXT,
853
+ resource TEXT NOT NULL DEFAULT '{}',
854
+ attributes TEXT NOT NULL DEFAULT '{}'
855
+ );
856
+
857
+ CREATE TABLE IF NOT EXISTS metric_points (
858
+ series_id TEXT NOT NULL,
859
+ timestamp INTEGER NOT NULL,
860
+ start_timestamp INTEGER,
861
+ value REAL,
862
+ count REAL,
863
+ sum REAL,
864
+ min REAL,
865
+ max REAL,
866
+ bucket_counts TEXT,
867
+ explicit_bounds TEXT,
868
+ exp_scale INTEGER,
869
+ zero_count REAL,
870
+ zero_threshold REAL,
871
+ positive_buckets TEXT,
872
+ negative_buckets TEXT,
873
+ quantiles TEXT,
874
+ exemplars TEXT,
875
+ PRIMARY KEY (series_id, timestamp)
876
+ );
877
+
878
+ CREATE TABLE IF NOT EXISTS logs (
879
+ id TEXT PRIMARY KEY,
880
+ timestamp INTEGER NOT NULL,
881
+ service TEXT,
882
+ severity_text TEXT,
883
+ severity_number INTEGER,
884
+ trace_id TEXT,
885
+ span_id TEXT,
886
+ -- The body as displayed: what free-text search matches against.
887
+ body_text TEXT NOT NULL DEFAULT '',
888
+ -- The body as sent. Structured bodies must survive as structure; a JSON body
889
+ -- flattened to text is a log nobody can read.
890
+ body_json TEXT,
891
+ attributes TEXT NOT NULL DEFAULT '{}',
892
+ resource TEXT
893
+ );
894
+
895
+ CREATE TABLE IF NOT EXISTS attribute_values (
896
+ signal TEXT NOT NULL,
897
+ key TEXT NOT NULL,
898
+ value_json TEXT NOT NULL,
899
+ value_text TEXT NOT NULL,
900
+ seen_count INTEGER NOT NULL DEFAULT 1,
901
+ last_seen INTEGER NOT NULL,
902
+ PRIMARY KEY (signal, key, value_json)
903
+ );
904
+
905
+ -- Span events and links, normalized so they can be filtered.
906
+ --
907
+ -- The JSON on the span row stays: it is the payload the waterfall renders, and
908
+ -- these two tables are the query index over it, the same split that
909
+ -- attribute_occurrences already makes against the attributes blob. Both are
910
+ -- written and deleted with their span, and backfilled on open for a --db
911
+ -- file written before they existed.
912
+ CREATE TABLE IF NOT EXISTS span_events (
913
+ trace_id TEXT NOT NULL,
914
+ span_id TEXT NOT NULL,
915
+ idx INTEGER NOT NULL,
916
+ name TEXT NOT NULL,
917
+ timestamp INTEGER,
918
+ PRIMARY KEY (trace_id, span_id, idx)
919
+ );
920
+
921
+ CREATE TABLE IF NOT EXISTS span_links (
922
+ trace_id TEXT NOT NULL,
923
+ span_id TEXT NOT NULL,
924
+ idx INTEGER NOT NULL,
925
+ linked_trace_id TEXT NOT NULL,
926
+ linked_span_id TEXT NOT NULL,
927
+ PRIMARY KEY (trace_id, span_id, idx)
928
+ );
929
+
930
+ CREATE TABLE IF NOT EXISTS attribute_occurrences (
931
+ signal TEXT NOT NULL,
932
+ entity_id TEXT NOT NULL,
933
+ key TEXT NOT NULL,
934
+ value_json TEXT NOT NULL,
935
+ PRIMARY KEY (signal, entity_id, key)
936
+ );
937
+
938
+ CREATE INDEX IF NOT EXISTS idx_traces_start ON traces(start_time DESC);
939
+ CREATE INDEX IF NOT EXISTS idx_logs_time ON logs(timestamp DESC);
940
+ CREATE INDEX IF NOT EXISTS idx_logs_trace ON logs(trace_id);
941
+ CREATE INDEX IF NOT EXISTS idx_logs_severity ON logs(severity_number, timestamp DESC);
942
+ CREATE INDEX IF NOT EXISTS idx_series_name ON metric_series(name);
943
+ CREATE INDEX IF NOT EXISTS idx_points_time ON metric_points(series_id, timestamp);
944
+ CREATE INDEX IF NOT EXISTS idx_spans_trace ON spans(trace_id);
945
+ CREATE INDEX IF NOT EXISTS idx_spans_start ON spans(start_time DESC);
946
+ CREATE INDEX IF NOT EXISTS idx_spans_service ON spans(service, start_time DESC);
947
+ CREATE INDEX IF NOT EXISTS idx_spans_duration ON spans(duration DESC);
948
+ CREATE INDEX IF NOT EXISTS idx_attribute_value ON attribute_values(signal, value_text, key);
949
+ CREATE INDEX IF NOT EXISTS idx_attribute_equality ON attribute_occurrences(signal, key, value_json, entity_id);
950
+ CREATE INDEX IF NOT EXISTS idx_span_events_name ON span_events(name);
951
+ CREATE INDEX IF NOT EXISTS idx_span_links_target ON span_links(linked_trace_id);
952
+ `;
953
+ var DevtoolsStore = class {
954
+ db;
955
+ maxTraces;
956
+ maxMetricPoints;
957
+ maxLogs;
958
+ maxBytes;
959
+ constructor(options = {}) {
960
+ this.db = new DatabaseSync(options.path ?? ":memory:");
961
+ this.maxTraces = options.maxTraces ?? DEFAULT_MAX_TRACES;
962
+ this.maxMetricPoints = options.maxMetricPoints ?? DEFAULT_MAX_METRIC_POINTS;
963
+ this.maxLogs = options.maxLogs ?? DEFAULT_MAX_LOGS;
964
+ this.maxBytes = options.maxBytes ?? (options.path ? 2 * 1024 ** 3 : 512 * 1024 ** 2);
965
+ this.guardSchemaVersion(options.path);
966
+ this.migrateSpanIdentity();
967
+ this.db.exec(DDL);
968
+ this.migrateMetricFidelity();
969
+ this.backfillAttributeDictionary();
970
+ this.backfillSpanChildren();
971
+ this.registerRegexp();
972
+ this.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
973
+ }
974
+ /** Refuse a file this build cannot read, before any query touches it. */
975
+ guardSchemaVersion(path) {
976
+ const found = pragmaNumber(this.db, "user_version");
977
+ if (found === 0 || found === SCHEMA_VERSION) return;
978
+ this.db.close();
979
+ throw new Error(`${path ?? ":memory:"} was written by a different autotel-devtools schema (found version ${found}, this build reads ${SCHEMA_VERSION}). Point --db at another file, or delete this one to start fresh.`);
980
+ }
981
+ /** Upgrade databases created before span identity included the trace id. */
982
+ migrateSpanIdentity() {
983
+ if (!this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'spans'").get()) return;
984
+ if (this.db.prepare("PRAGMA table_info(spans)").all().filter((column) => Number(column.pk) > 0).sort((left, right) => Number(left.pk) - Number(right.pk)).map((column) => column.name).join(",") === "trace_id,span_id") return;
985
+ this.db.exec("BEGIN");
986
+ try {
987
+ this.db.exec("ALTER TABLE spans RENAME TO spans_legacy_span_id_pk");
988
+ this.db.exec(SPANS_TABLE_DDL);
989
+ this.db.exec(`
990
+ INSERT INTO spans (span_id, trace_id, parent_span_id, name, kind, service,
991
+ start_time, end_time, duration, status_code,
992
+ status_message, attributes, events, links, scope)
993
+ SELECT span_id, trace_id, parent_span_id, name, kind, service,
994
+ start_time, end_time, duration, status_code,
995
+ status_message, attributes, events, links, scope
996
+ FROM spans_legacy_span_id_pk
997
+ `);
998
+ this.db.exec("DROP TABLE spans_legacy_span_id_pk");
999
+ this.db.exec("COMMIT");
1000
+ } catch (error) {
1001
+ this.db.exec("ROLLBACK");
1002
+ throw error;
1003
+ }
1004
+ }
1005
+ /** Add lossless metric fields to databases created by earlier releases. */
1006
+ migrateMetricFidelity() {
1007
+ const hadResource = this.hasColumn("metric_series", "resource");
1008
+ this.addColumnIfMissing("metric_series", "resource", "TEXT NOT NULL DEFAULT '{}'");
1009
+ this.addColumnIfMissing("metric_points", "exp_scale", "INTEGER");
1010
+ this.addColumnIfMissing("metric_points", "zero_count", "REAL");
1011
+ this.addColumnIfMissing("metric_points", "zero_threshold", "REAL");
1012
+ this.addColumnIfMissing("metric_points", "positive_buckets", "TEXT");
1013
+ this.addColumnIfMissing("metric_points", "negative_buckets", "TEXT");
1014
+ if (!hadResource) this.migrateLegacyMetricSeriesIdentity();
1015
+ }
1016
+ hasColumn(table, column) {
1017
+ return this.db.prepare(`PRAGMA table_info(${table})`).all().some((item) => item.name === column);
1018
+ }
1019
+ addColumnIfMissing(table, column, declaration) {
1020
+ if (this.hasColumn(table, column)) return;
1021
+ this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${declaration}`);
1022
+ }
1023
+ migrateLegacyMetricSeriesIdentity() {
1024
+ const rows = this.db.prepare("SELECT * FROM metric_series").all();
1025
+ if (rows.length === 0) return;
1026
+ const updatePoints = this.db.prepare("UPDATE metric_points SET series_id = ? WHERE series_id = ?");
1027
+ const updateSeries = this.db.prepare("UPDATE metric_series SET series_id = ?, resource = ? WHERE series_id = ?");
1028
+ this.db.exec("BEGIN");
1029
+ try {
1030
+ for (const row of rows) {
1031
+ const resource = { "service.name": row.service };
1032
+ const nextId = seriesIdentity({
1033
+ name: row.name,
1034
+ unit: row.unit ?? void 0,
1035
+ kind: row.kind,
1036
+ temporality: row.temporality ?? void 0,
1037
+ monotonic: row.monotonic === null ? void 0 : row.monotonic === 1,
1038
+ service: row.service,
1039
+ scope: row.scope_name ? {
1040
+ name: row.scope_name,
1041
+ version: row.scope_version ?? void 0
1042
+ } : void 0,
1043
+ resource,
1044
+ points: []
1045
+ }, parseJson(row.attributes) ?? {});
1046
+ updatePoints.run(nextId, row.series_id);
1047
+ updateSeries.run(nextId, stableJson(resource), row.series_id);
1048
+ }
1049
+ this.db.exec("COMMIT");
1050
+ } catch (error) {
1051
+ this.db.exec("ROLLBACK");
1052
+ throw error;
1053
+ }
1054
+ }
1055
+ /**
1056
+ * SQLite parses `REGEXP` but ships no implementation — using it without
1057
+ * registering one is a runtime error, not a syntax error. The language offers
1058
+ * regex matching, so the function has to exist.
1059
+ *
1060
+ * An invalid pattern matches nothing rather than throwing: the user is
1061
+ * probably mid-typing, and a thrown error would blank the whole result list.
1062
+ */
1063
+ registerRegexp() {
1064
+ this.db.function("regexp", (pattern, value) => {
1065
+ if (value == null) return 0;
1066
+ try {
1067
+ return new RegExp(String(pattern)).test(String(value)) ? 1 : 0;
1068
+ } catch {
1069
+ return 0;
1070
+ }
1071
+ });
1072
+ }
1073
+ ingestTraces(traces) {
1074
+ if (traces.length === 0) return;
1075
+ const upsertTrace = this.db.prepare(`
1076
+ INSERT INTO traces (trace_id, correlation_id, service, root_span_id,
1077
+ start_time, end_time, duration, status, partial)
1078
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1079
+ ON CONFLICT(trace_id) DO UPDATE SET
1080
+ -- A trace grows as spans arrive: widen the bounds rather than replacing
1081
+ -- them, so a late span cannot shrink the trace it belongs to.
1082
+ start_time = min(start_time, excluded.start_time),
1083
+ end_time = max(end_time, excluded.end_time),
1084
+ duration = max(end_time, excluded.end_time) - min(start_time, excluded.start_time),
1085
+ status = CASE WHEN excluded.status = 'ERROR' THEN 'ERROR' ELSE status END,
1086
+ service = COALESCE(excluded.service, service),
1087
+ root_span_id = CASE
1088
+ WHEN traces.partial = 1 AND excluded.partial = 0
1089
+ THEN COALESCE(excluded.root_span_id, root_span_id)
1090
+ ELSE COALESCE(root_span_id, excluded.root_span_id)
1091
+ END,
1092
+ -- Once the true root has arrived, a delayed partial replay cannot make
1093
+ -- the stored trace provisional again.
1094
+ partial = min(partial, excluded.partial)
1095
+ `);
1096
+ const upsertSpan = this.db.prepare(`
1097
+ INSERT INTO spans (span_id, trace_id, parent_span_id, name, kind, service,
1098
+ start_time, end_time, duration, status_code,
1099
+ status_message, attributes, events, links, scope)
1100
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1101
+ ON CONFLICT(trace_id, span_id) DO UPDATE SET
1102
+ name = excluded.name,
1103
+ end_time = excluded.end_time,
1104
+ duration = excluded.duration,
1105
+ status_code = excluded.status_code,
1106
+ status_message = excluded.status_message,
1107
+ attributes = excluded.attributes,
1108
+ events = excluded.events,
1109
+ links = excluded.links
1110
+ `);
1111
+ const upsertAttribute = this.attributeUpsert();
1112
+ const upsertOccurrence = this.attributeOccurrenceUpsert();
1113
+ const clearOccurrences = this.db.prepare("DELETE FROM attribute_occurrences WHERE signal = 'traces' AND entity_id = ?");
1114
+ const clearEvents = this.db.prepare("DELETE FROM span_events WHERE trace_id = ? AND span_id = ?");
1115
+ const clearLinks = this.db.prepare("DELETE FROM span_links WHERE trace_id = ? AND span_id = ?");
1116
+ const insertEvent = this.db.prepare("INSERT INTO span_events (trace_id, span_id, idx, name, timestamp) VALUES (?, ?, ?, ?, ?)");
1117
+ const insertLink = this.db.prepare("INSERT INTO span_links (trace_id, span_id, idx, linked_trace_id, linked_span_id) VALUES (?, ?, ?, ?, ?)");
1118
+ this.db.exec("BEGIN");
1119
+ try {
1120
+ for (const trace of traces) {
1121
+ upsertTrace.run(trace.traceId, trace.correlationId ?? null, trace.service ?? null, trace.rootSpan?.spanId ?? null, trace.startTime, trace.endTime, trace.duration, trace.status, trace.partial ? 1 : 0);
1122
+ for (const span of trace.spans ?? []) {
1123
+ upsertSpan.run(span.spanId, span.traceId, span.parentSpanId ?? null, span.name, span.kind, spanService(span, trace.service), span.startTime, span.endTime, span.duration, span.status?.code ?? "UNSET", span.status?.message ?? null, JSON.stringify(span.attributes ?? {}), span.events?.length ? JSON.stringify(span.events) : null, span.links?.length ? JSON.stringify(span.links) : null, span.scope ? JSON.stringify(span.scope) : null);
1124
+ const entityId = `${span.traceId}:${span.spanId}`;
1125
+ clearOccurrences.run(entityId);
1126
+ this.indexAttributes(upsertAttribute, upsertOccurrence, "traces", entityId, span.attributes ?? {}, span.startTime);
1127
+ clearEvents.run(span.traceId, span.spanId);
1128
+ span.events?.forEach((event, index) => {
1129
+ insertEvent.run(span.traceId, span.spanId, index, event.name, event.timestamp ?? null);
1130
+ });
1131
+ clearLinks.run(span.traceId, span.spanId);
1132
+ span.links?.forEach((link, index) => {
1133
+ insertLink.run(span.traceId, span.spanId, index, link.traceId, link.spanId);
1134
+ });
1135
+ }
1136
+ }
1137
+ this.db.exec("COMMIT");
1138
+ } catch (error) {
1139
+ this.db.exec("ROLLBACK");
1140
+ throw error;
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Find traces matching a query.
1145
+ *
1146
+ * The filter runs against *spans* and the results are traces: a trace matches
1147
+ * when any of its spans does. That is what makes `http.status_code = 500`
1148
+ * useful — the attribute is on one span, but the thing you want to open is
1149
+ * the trace containing it.
1150
+ */
1151
+ queryTraces(args) {
1152
+ const parsed = parse(args.query ?? "");
1153
+ if (!parsed.ok) return {
1154
+ traces: [],
1155
+ nextCursor: null,
1156
+ errors: parsed.errors
1157
+ };
1158
+ const { sql: whereSql, params } = compileWhere(parsed.node, SPAN_SCHEMA);
1159
+ const limit = Math.min(MAX_QUERY_PAGE_SIZE, Math.max(1, args.limit ?? DEFAULT_LIMIT));
1160
+ const clauses = [`s.trace_id = t.trace_id`, whereSql];
1161
+ const queryParams = [...params];
1162
+ if (args.window) {
1163
+ clauses.push("t.start_time >= ? AND t.start_time <= ?");
1164
+ queryParams.push(args.window.start, args.window.end);
1165
+ }
1166
+ const cursor = decodeCursor(args.cursor);
1167
+ if (cursor) {
1168
+ clauses.push("(t.start_time < ? OR (t.start_time = ? AND t.trace_id < ?))");
1169
+ queryParams.push(cursor.startTime, cursor.startTime, cursor.traceId);
1170
+ }
1171
+ const rows = this.db.prepare(`SELECT t.* FROM traces t
1172
+ WHERE EXISTS (SELECT 1 FROM spans s WHERE ${clauses.join(" AND ")})
1173
+ ORDER BY t.start_time DESC, t.trace_id DESC
1174
+ LIMIT ?`).all(...queryParams, limit + 1);
1175
+ const hasMore = rows.length > limit;
1176
+ const page = hasMore ? rows.slice(0, limit) : rows;
1177
+ const last = page[page.length - 1];
1178
+ return {
1179
+ traces: this.hydrateTracePage(page),
1180
+ nextCursor: hasMore && last ? encodeCursor({
1181
+ startTime: Number(last.start_time),
1182
+ traceId: last.trace_id
1183
+ }) : null
1184
+ };
1185
+ }
1186
+ ingestLogs(logs) {
1187
+ if (logs.length === 0) return;
1188
+ const upsert = this.db.prepare(`
1189
+ INSERT INTO logs (id, timestamp, service, severity_text, severity_number,
1190
+ trace_id, span_id, body_text, body_json, attributes,
1191
+ resource)
1192
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1193
+ ON CONFLICT(id) DO NOTHING
1194
+ `);
1195
+ const upsertAttribute = this.attributeUpsert();
1196
+ const upsertOccurrence = this.attributeOccurrenceUpsert();
1197
+ this.db.exec("BEGIN");
1198
+ try {
1199
+ for (const log of logs) {
1200
+ const structured = typeof log.body === "object" && log.body !== null;
1201
+ const inserted = upsert.run(log.id, log.timestamp, log.resourceName ?? null, log.severityText ?? null, log.severityNumber ?? null, log.traceId ?? null, log.spanId ?? null, structured ? JSON.stringify(log.body) : String(log.body ?? ""), structured ? JSON.stringify(log.body) : null, JSON.stringify(log.attributes ?? {}), log.resource ? JSON.stringify(log.resource) : null);
1202
+ if (Number(inserted.changes) === 0) continue;
1203
+ this.indexAttributes(upsertAttribute, upsertOccurrence, "logs", log.id, log.attributes ?? {}, log.timestamp);
1204
+ }
1205
+ this.db.exec("COMMIT");
1206
+ } catch (error) {
1207
+ this.db.exec("ROLLBACK");
1208
+ throw error;
1209
+ }
1210
+ }
1211
+ queryLogs(args) {
1212
+ const parsed = parse(args.query ?? "");
1213
+ if (!parsed.ok) return {
1214
+ logs: [],
1215
+ nextCursor: null,
1216
+ errors: parsed.errors
1217
+ };
1218
+ const { sql: whereSql, params } = compileWhere(parsed.node, LOG_SCHEMA);
1219
+ const limit = Math.min(MAX_QUERY_PAGE_SIZE, Math.max(1, args.limit ?? DEFAULT_LIMIT));
1220
+ const clauses = [whereSql];
1221
+ const queryParams = [...params];
1222
+ if (args.window) {
1223
+ clauses.push("timestamp >= ? AND timestamp <= ?");
1224
+ queryParams.push(args.window.start, args.window.end);
1225
+ }
1226
+ const cursor = decodeCursor(args.cursor);
1227
+ if (cursor) {
1228
+ clauses.push("(timestamp < ? OR (timestamp = ? AND id < ?))");
1229
+ queryParams.push(cursor.startTime, cursor.startTime, cursor.traceId);
1230
+ }
1231
+ const rows = this.db.prepare(`SELECT * FROM logs
1232
+ WHERE ${clauses.join(" AND ")}
1233
+ ORDER BY timestamp DESC, id DESC
1234
+ LIMIT ?`).all(...queryParams, limit + 1);
1235
+ const hasMore = rows.length > limit;
1236
+ const page = hasMore ? rows.slice(0, limit) : rows;
1237
+ const last = page[page.length - 1];
1238
+ return {
1239
+ logs: page.map(hydrateLog),
1240
+ nextCursor: hasMore && last ? encodeCursor({
1241
+ startTime: Number(last.timestamp),
1242
+ traceId: last.id
1243
+ }) : null
1244
+ };
1245
+ }
1246
+ countLogs() {
1247
+ const row = this.db.prepare("SELECT count(*) AS n FROM logs").get();
1248
+ return Number(row.n);
1249
+ }
1250
+ /**
1251
+ * Store metric points, grouped into series.
1252
+ *
1253
+ * One series is one chart line: `(name, kind, unit, service, scope, point
1254
+ * attributes)`. Both directions of getting this wrong are bad — too coarse
1255
+ * and every line collapses into one meaningless average, too fine and one
1256
+ * logical series sprouts a new line on every export — so the identity is a
1257
+ * content hash over exactly those fields, with attribute keys sorted so an
1258
+ * exporter's key ordering cannot split a series in two.
1259
+ */
1260
+ ingestMetrics(streams) {
1261
+ if (streams.length === 0) return;
1262
+ const upsertSeries = this.db.prepare(`
1263
+ INSERT INTO metric_series (series_id, name, unit, description, kind,
1264
+ temporality, monotonic, service, scope_name,
1265
+ scope_version, resource, attributes)
1266
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1267
+ ON CONFLICT(series_id) DO UPDATE SET
1268
+ -- Description and unit can be filled in by a later export; the identity
1269
+ -- fields cannot change without producing a different series_id.
1270
+ description = COALESCE(excluded.description, description),
1271
+ unit = COALESCE(excluded.unit, unit),
1272
+ temporality = COALESCE(excluded.temporality, temporality)
1273
+ `);
1274
+ const upsertPoint = this.db.prepare(`
1275
+ INSERT INTO metric_points (series_id, timestamp, start_timestamp, value,
1276
+ count, sum, min, max, bucket_counts,
1277
+ explicit_bounds, exp_scale, zero_count,
1278
+ zero_threshold, positive_buckets,
1279
+ negative_buckets, quantiles, exemplars)
1280
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1281
+ ON CONFLICT(series_id, timestamp) DO UPDATE SET
1282
+ value = excluded.value,
1283
+ count = excluded.count,
1284
+ sum = excluded.sum,
1285
+ min = excluded.min,
1286
+ max = excluded.max,
1287
+ bucket_counts = excluded.bucket_counts,
1288
+ explicit_bounds = excluded.explicit_bounds,
1289
+ exp_scale = excluded.exp_scale,
1290
+ zero_count = excluded.zero_count,
1291
+ zero_threshold = excluded.zero_threshold,
1292
+ positive_buckets = excluded.positive_buckets,
1293
+ negative_buckets = excluded.negative_buckets,
1294
+ quantiles = excluded.quantiles,
1295
+ exemplars = excluded.exemplars
1296
+ `);
1297
+ this.db.exec("BEGIN");
1298
+ try {
1299
+ for (const stream of streams) for (const point of stream.points) {
1300
+ const seriesId = seriesIdentity(stream, point.attributes);
1301
+ upsertSeries.run(seriesId, stream.name, stream.unit ?? null, stream.description ?? null, stream.kind, stream.temporality ?? null, stream.monotonic === void 0 ? null : stream.monotonic ? 1 : 0, stream.service, stream.scope?.name ?? null, stream.scope?.version ?? null, stableJson(stream.resource), stableJson(point.attributes));
1302
+ upsertPoint.run(seriesId, point.timestamp, point.startTimestamp ?? null, point.value ?? null, point.count ?? null, point.sum ?? null, point.min ?? null, point.max ?? null, point.bucketCounts ? JSON.stringify(point.bucketCounts) : null, point.explicitBounds ? JSON.stringify(point.explicitBounds) : null, point.scale ?? null, point.zeroCount ?? null, point.zeroThreshold ?? null, point.positive ? JSON.stringify(point.positive) : null, point.negative ? JSON.stringify(point.negative) : null, point.quantiles ? JSON.stringify(point.quantiles) : null, point.exemplars ? JSON.stringify(point.exemplars) : null);
1303
+ }
1304
+ this.db.exec("COMMIT");
1305
+ } catch (error) {
1306
+ this.db.exec("ROLLBACK");
1307
+ throw error;
1308
+ }
1309
+ }
1310
+ /** Every metric name held, for the catalogue the Metrics tab lists. */
1311
+ listMetricNames() {
1312
+ return this.queryMetricCatalog("").metrics;
1313
+ }
1314
+ queryMetricCatalog(query) {
1315
+ const parsed = parse(query);
1316
+ if (!parsed.ok) return {
1317
+ metrics: [],
1318
+ errors: parsed.errors
1319
+ };
1320
+ const compiled = compileWhere(parsed.node, METRIC_SCHEMA);
1321
+ return { metrics: this.db.prepare(`SELECT name, kind, unit, description, count(*) AS series_count
1322
+ FROM metric_series
1323
+ WHERE ${compiled.sql}
1324
+ GROUP BY name, kind
1325
+ ORDER BY name ASC`).all(...compiled.params).map((row) => ({
1326
+ name: row.name,
1327
+ kind: row.kind,
1328
+ unit: row.unit ?? void 0,
1329
+ description: row.description ?? void 0,
1330
+ seriesCount: Number(row.series_count)
1331
+ })) };
1332
+ }
1333
+ /**
1334
+ * The series for one metric, with their points.
1335
+ *
1336
+ * A series whose points all fall outside the window is omitted rather than
1337
+ * returned empty: an empty line in the legend claims data exists where none
1338
+ * does, and the caller cannot tell the two apart.
1339
+ */
1340
+ queryMetricSeries(args) {
1341
+ const seriesRows = this.db.prepare("SELECT * FROM metric_series WHERE name = ? ORDER BY series_id ASC").all(args.name);
1342
+ const pointsSql = args.window ? `SELECT * FROM metric_points
1343
+ WHERE series_id = ? AND timestamp >= ? AND timestamp <= ?
1344
+ ORDER BY timestamp ASC` : `SELECT * FROM metric_points WHERE series_id = ? ORDER BY timestamp ASC`;
1345
+ const pointsStmt = this.db.prepare(pointsSql);
1346
+ const out = [];
1347
+ for (const row of seriesRows) {
1348
+ const pointRows = args.window ? pointsStmt.all(row.series_id, args.window.start, args.window.end) : pointsStmt.all(row.series_id);
1349
+ if (pointRows.length === 0) continue;
1350
+ out.push({
1351
+ seriesId: row.series_id,
1352
+ name: row.name,
1353
+ unit: row.unit ?? void 0,
1354
+ description: row.description ?? void 0,
1355
+ kind: row.kind,
1356
+ temporality: row.temporality ?? void 0,
1357
+ monotonic: row.monotonic === null ? void 0 : row.monotonic === 1,
1358
+ service: row.service,
1359
+ scope: row.scope_name ? {
1360
+ name: row.scope_name,
1361
+ version: row.scope_version ?? void 0
1362
+ } : void 0,
1363
+ resource: parseJson(row.resource) ?? {},
1364
+ attributes: parseJson(row.attributes) ?? {},
1365
+ points: reduceMetricPoints(pointRows.map(hydratePoint), row.kind, Math.max(4, Math.min(args.maxPoints ?? 2e3, 2e4)), { temporality: row.temporality ?? void 0 })
1366
+ });
1367
+ }
1368
+ return out;
1369
+ }
1370
+ getTrace(traceId) {
1371
+ const row = this.db.prepare("SELECT * FROM traces WHERE trace_id = ?").get(traceId);
1372
+ return row ? this.hydrateTrace(row) : null;
1373
+ }
1374
+ describeTrace(traceId) {
1375
+ const trace = this.db.prepare("SELECT * FROM traces WHERE trace_id = ?").get(traceId);
1376
+ if (!trace) return null;
1377
+ const spans = this.db.prepare(`
1378
+ SELECT span_id, name, service, duration, status_code, attributes
1379
+ FROM spans WHERE trace_id = ? ORDER BY duration DESC
1380
+ `).all(traceId);
1381
+ const operations = /* @__PURE__ */ new Map();
1382
+ const services = /* @__PURE__ */ new Set();
1383
+ const models = /* @__PURE__ */ new Set();
1384
+ let errors = 0;
1385
+ let llmSpans = 0;
1386
+ let totalTokens = 0;
1387
+ for (const span of spans) {
1388
+ operations.set(span.name, (operations.get(span.name) ?? 0) + 1);
1389
+ services.add(span.service ?? "unknown");
1390
+ if (span.status_code === "ERROR") errors++;
1391
+ const attributes = parseJson(span.attributes) ?? {};
1392
+ const model = attributes["gen_ai.response.model"] ?? attributes["gen_ai.request.model"];
1393
+ if (typeof model === "string") {
1394
+ models.add(model);
1395
+ llmSpans++;
1396
+ }
1397
+ const tokens = attributes["gen_ai.usage.total_tokens"] ?? Number(attributes["gen_ai.usage.input_tokens"] ?? 0) + Number(attributes["gen_ai.usage.output_tokens"] ?? 0);
1398
+ totalTokens += Number(tokens) || 0;
1399
+ }
1400
+ return {
1401
+ traceId,
1402
+ serviceName: trace.service ?? "unknown",
1403
+ durationMs: Number(trace.duration),
1404
+ statusCode: trace.status,
1405
+ spanCount: spans.length,
1406
+ errorSpanCount: errors,
1407
+ serviceCount: services.size,
1408
+ llmSpanCount: llmSpans,
1409
+ totalTokens,
1410
+ modelsUsed: [...models].sort(),
1411
+ topOperations: [...operations].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([operation, count]) => ({
1412
+ operation,
1413
+ count
1414
+ })),
1415
+ slowestSpans: spans.slice(0, 5).map((span) => ({
1416
+ spanId: span.span_id,
1417
+ name: span.name,
1418
+ service: span.service ?? "unknown",
1419
+ durationMs: Number(span.duration),
1420
+ deepLink: traceDeepLink(traceId, trace, span.span_id)
1421
+ })),
1422
+ deepLink: traceDeepLink(traceId, trace)
1423
+ };
1424
+ }
1425
+ findSlowest(limit = 10) {
1426
+ return this.db.prepare("SELECT trace_id FROM traces ORDER BY duration DESC LIMIT ?").all(Math.max(1, Math.min(limit, 100))).flatMap((row) => {
1427
+ const projection = this.describeTrace(row.trace_id);
1428
+ return projection ? [projection] : [];
1429
+ });
1430
+ }
1431
+ countSpans() {
1432
+ const row = this.db.prepare("SELECT count(*) AS n FROM spans").get();
1433
+ return Number(row.n);
1434
+ }
1435
+ countTraces() {
1436
+ const row = this.db.prepare("SELECT count(*) AS n FROM traces").get();
1437
+ return Number(row.n);
1438
+ }
1439
+ /**
1440
+ * One row per matching span, for a cohort comparison.
1441
+ *
1442
+ * Attributes plus the first-class columns, because "the slow ones are all
1443
+ * `service=payments`" is exactly the shape of answer wanted and `service` is
1444
+ * a column rather than an attribute. Ids are left out: they take a distinct
1445
+ * value per span, so they can never describe a group, and including them
1446
+ * only gives the ranking noise to wade through.
1447
+ *
1448
+ * Throws on a query that does not parse. Returning an empty cohort instead
1449
+ * would surface as "no difference found", which is a different and much
1450
+ * more misleading answer than "your query is wrong".
1451
+ */
1452
+ cohortRows(args) {
1453
+ const parsed = parse(args.query ?? "");
1454
+ if (!parsed.ok) throw new Error(`Cohort query did not parse: ${parsed.errors.map((e) => e.message).join("; ")}`);
1455
+ const { sql: whereSql, params } = compileWhere(parsed.node, SPAN_SCHEMA);
1456
+ const clauses = [whereSql];
1457
+ const queryParams = [...params];
1458
+ if (args.window) {
1459
+ clauses.push("s.start_time >= ? AND s.start_time <= ?");
1460
+ queryParams.push(args.window.start, args.window.end);
1461
+ }
1462
+ return this.db.prepare(`SELECT s.service, s.name, s.kind, s.duration, s.status_code, s.attributes
1463
+ FROM spans s
1464
+ WHERE ${clauses.join(" AND ")}
1465
+ ORDER BY s.start_time DESC
1466
+ LIMIT ?`).all(...queryParams, Math.min(args.limit ?? COHORT_ROW_LIMIT, COHORT_ROW_LIMIT)).map((row) => ({
1467
+ ...parseJson(row.attributes) ?? {},
1468
+ service: row.service ?? "unknown",
1469
+ name: row.name,
1470
+ kind: row.kind,
1471
+ status: row.status_code
1472
+ }));
1473
+ }
1474
+ /**
1475
+ * What the store has actually seen, for the coverage join.
1476
+ *
1477
+ * Both routes in are counted: the `http.route` attribute a framework
1478
+ * integration sets, and the span name, which is what `trace('name', fn)`
1479
+ * produces and is all a non-HTTP entry point ever has. Counting is cheap
1480
+ * here because `attribute_values` already carries per-value totals.
1481
+ */
1482
+ observedSpans() {
1483
+ const routeRows = this.db.prepare(`SELECT value_text AS value, seen_count AS count FROM attribute_values
1484
+ WHERE signal = 'traces' AND key = 'http.route'`).all();
1485
+ const nameRows = this.db.prepare("SELECT name, count(*) AS count FROM spans GROUP BY name").all();
1486
+ return {
1487
+ routeCounts: Object.fromEntries(routeRows.map((row) => [row.value, Number(row.count)])),
1488
+ spanNameCounts: Object.fromEntries(nameRows.map((row) => [row.name, Number(row.count)]))
1489
+ };
1490
+ }
1491
+ /** Query fields currently present, for editor completion. */
1492
+ listQueryFields(signal, limit = 200) {
1493
+ const schema = signal === "traces" ? SPAN_SCHEMA : LOG_SCHEMA;
1494
+ const table = signal === "traces" ? "spans" : "logs";
1495
+ const rows = this.db.prepare(`SELECT DISTINCT json_each.key AS key
1496
+ FROM ${table}, json_each(${table}.attributes)
1497
+ WHERE json_valid(${table}.attributes)
1498
+ ORDER BY key ASC
1499
+ LIMIT ?`).all(Math.max(1, Math.min(limit, 500)));
1500
+ return [.../* @__PURE__ */ new Set([...Object.keys(schema.columns), ...rows.map((row) => row.key)])];
1501
+ }
1502
+ /**
1503
+ * Values of one attribute paired with another on the same entity.
1504
+ *
1505
+ * `searchAttributes` matches on value text, which cannot answer "what arms
1506
+ * does this experiment have". Pairing two keys across the same span can, and
1507
+ * that is what turns a pair of cohorts into something the viewer offers
1508
+ * rather than something the reader has to type.
1509
+ *
1510
+ * Rows arrive grouped by `key`, each group's values commonest first, so a
1511
+ * caller can build the groups in one pass and take the two commonest as a
1512
+ * default pair.
1513
+ *
1514
+ * The join runs over `attribute_occurrences`, not the `attribute_values`
1515
+ * dictionary: occurrences are deleted with their span, so retention prunes
1516
+ * them, and they carry the entity a value was seen on, so an arm is only
1517
+ * offered for the experiment it actually ran under. The dictionary can do
1518
+ * neither — it counts values for the lifetime of the database and forgets
1519
+ * which span each came from, which would offer arms belonging to a different
1520
+ * experiment and experiments whose spans are long gone.
1521
+ */
1522
+ pairedAttributeValues(signal, key, pairedKey, limit = 200) {
1523
+ return this.db.prepare(`
1524
+ SELECT a.value_json AS value_json, b.value_json AS paired_json, count(*) AS count
1525
+ FROM attribute_occurrences a
1526
+ JOIN attribute_occurrences b
1527
+ ON b.signal = a.signal AND b.entity_id = a.entity_id AND b.key = ?
1528
+ WHERE a.signal = ? AND a.key = ?
1529
+ GROUP BY a.value_json, b.value_json
1530
+ ORDER BY value_json ASC, count DESC, paired_json ASC
1531
+ LIMIT ?
1532
+ `).all(pairedKey, signal, key, Math.max(1, Math.min(limit, 500))).map((row) => ({
1533
+ value: JSON.parse(row.value_json),
1534
+ paired: JSON.parse(row.paired_json),
1535
+ count: Number(row.count)
1536
+ }));
1537
+ }
1538
+ searchAttributes(signal, value, limit = 50) {
1539
+ return this.db.prepare(`
1540
+ SELECT key, value_json, seen_count
1541
+ FROM attribute_values
1542
+ WHERE signal = ? AND value_text LIKE ? ESCAPE '\\'
1543
+ ORDER BY seen_count DESC, key ASC
1544
+ LIMIT ?
1545
+ `).all(signal, `%${escapeLike(value)}%`, Math.max(1, Math.min(limit, 200))).map((row) => ({
1546
+ key: row.key,
1547
+ value: parseJson(row.value_json),
1548
+ count: Number(row.seen_count)
1549
+ }));
1550
+ }
1551
+ attributeUpsert() {
1552
+ return this.db.prepare(`
1553
+ INSERT INTO attribute_values (signal, key, value_json, value_text, last_seen)
1554
+ VALUES (?, ?, ?, ?, ?)
1555
+ ON CONFLICT(signal, key, value_json) DO UPDATE SET
1556
+ seen_count = seen_count + 1,
1557
+ last_seen = max(last_seen, excluded.last_seen)
1558
+ `);
1559
+ }
1560
+ attributeOccurrenceUpsert() {
1561
+ return this.db.prepare(`
1562
+ INSERT INTO attribute_occurrences(signal, entity_id, key, value_json)
1563
+ VALUES (?, ?, ?, ?)
1564
+ ON CONFLICT(signal, entity_id, key) DO UPDATE SET value_json = excluded.value_json
1565
+ `);
1566
+ }
1567
+ indexAttributes(statement, occurrence, signal, entityId, attributes, timestamp) {
1568
+ for (const [key, value] of Object.entries(attributes)) {
1569
+ const encoded = JSON.stringify(value);
1570
+ statement.run(signal, key, encoded, String(value), timestamp);
1571
+ occurrence.run(signal, entityId, key, encoded);
1572
+ }
1573
+ }
1574
+ /**
1575
+ * Index the events and links already sitting in the span JSON.
1576
+ *
1577
+ * A `--db` file written before these tables existed holds spans whose events
1578
+ * no query can reach. Reading them out of the JSON on open is what makes
1579
+ * `event.name = …` work against telemetry captured yesterday. Keyed on the
1580
+ * table being empty while spans exist, so it runs once rather than on every
1581
+ * open.
1582
+ */
1583
+ backfillSpanChildren() {
1584
+ const pending = this.db.prepare(`SELECT (SELECT count(*) FROM spans WHERE events IS NOT NULL OR links IS NOT NULL) AS carriers,
1585
+ (SELECT count(*) FROM span_events) AS events,
1586
+ (SELECT count(*) FROM span_links) AS links`).get();
1587
+ if (Number(pending.carriers) === 0) return;
1588
+ if (Number(pending.events) > 0 || Number(pending.links) > 0) return;
1589
+ this.db.exec(`
1590
+ INSERT OR IGNORE INTO span_events(trace_id, span_id, idx, name, timestamp)
1591
+ SELECT spans.trace_id, spans.span_id, json_each.key,
1592
+ json_extract(json_each.value, '$.name'),
1593
+ json_extract(json_each.value, '$.timestamp')
1594
+ FROM spans, json_each(spans.events)
1595
+ WHERE spans.events IS NOT NULL AND json_valid(spans.events)
1596
+ AND json_extract(json_each.value, '$.name') IS NOT NULL;
1597
+ INSERT OR IGNORE INTO span_links(trace_id, span_id, idx, linked_trace_id, linked_span_id)
1598
+ SELECT spans.trace_id, spans.span_id, json_each.key,
1599
+ json_extract(json_each.value, '$.traceId'),
1600
+ json_extract(json_each.value, '$.spanId')
1601
+ FROM spans, json_each(spans.links)
1602
+ WHERE spans.links IS NOT NULL AND json_valid(spans.links)
1603
+ AND json_extract(json_each.value, '$.traceId') IS NOT NULL;
1604
+ `);
1605
+ }
1606
+ backfillAttributeDictionary() {
1607
+ const row = this.db.prepare("SELECT count(*) AS n FROM attribute_values").get();
1608
+ if (Number(row.n) === 0) this.db.exec(`
1609
+ INSERT OR IGNORE INTO attribute_values(signal, key, value_json, value_text, seen_count, last_seen)
1610
+ SELECT 'traces', json_each.key, json_quote(json_each.value), CAST(json_each.value AS TEXT), count(*), max(spans.start_time)
1611
+ FROM spans, json_each(spans.attributes) GROUP BY json_each.key, json_quote(json_each.value);
1612
+ INSERT OR IGNORE INTO attribute_values(signal, key, value_json, value_text, seen_count, last_seen)
1613
+ SELECT 'logs', json_each.key, json_quote(json_each.value), CAST(json_each.value AS TEXT), count(*), max(logs.timestamp)
1614
+ FROM logs, json_each(logs.attributes) GROUP BY json_each.key, json_quote(json_each.value);
1615
+ `);
1616
+ const occurrences = this.db.prepare("SELECT count(*) AS n FROM attribute_occurrences").get();
1617
+ if (Number(occurrences.n) === 0) this.db.exec(`
1618
+ INSERT OR IGNORE INTO attribute_occurrences(signal, entity_id, key, value_json)
1619
+ SELECT 'traces', spans.trace_id || ':' || spans.span_id, json_each.key, json_quote(json_each.value)
1620
+ FROM spans, json_each(spans.attributes);
1621
+ INSERT OR IGNORE INTO attribute_occurrences(signal, entity_id, key, value_json)
1622
+ SELECT 'logs', logs.id, json_each.key, json_quote(json_each.value)
1623
+ FROM logs, json_each(logs.attributes);
1624
+ `);
1625
+ }
1626
+ /**
1627
+ * Prune the oldest traces past the row cap, and their spans with them.
1628
+ *
1629
+ * Spans are deleted in the same transaction as their traces: a pruned trace
1630
+ * that left its spans behind would leave rows that no query can reach and no
1631
+ * later sweep would find, since every sweep starts from `traces`.
1632
+ */
1633
+ enforceRetention() {
1634
+ this.enforceMetricRetention();
1635
+ this.enforceLogRetention();
1636
+ if (this.maxTraces <= 0) {
1637
+ this.enforceByteRetention();
1638
+ return;
1639
+ }
1640
+ const total = this.countTraces();
1641
+ if (total <= this.maxTraces) {
1642
+ this.enforceByteRetention();
1643
+ return;
1644
+ }
1645
+ const excess = total - this.maxTraces;
1646
+ this.db.exec("BEGIN");
1647
+ try {
1648
+ const doomed = this.db.prepare(`SELECT trace_id FROM traces
1649
+ ORDER BY start_time ASC, trace_id ASC
1650
+ LIMIT ?`).all(excess);
1651
+ const deleteSpans = this.db.prepare("DELETE FROM spans WHERE trace_id = ?");
1652
+ const deleteTrace = this.db.prepare("DELETE FROM traces WHERE trace_id = ?");
1653
+ for (const { trace_id } of doomed) {
1654
+ deleteSpans.run(trace_id);
1655
+ deleteTrace.run(trace_id);
1656
+ }
1657
+ this.db.exec("COMMIT");
1658
+ } catch (error) {
1659
+ this.db.exec("ROLLBACK");
1660
+ throw error;
1661
+ }
1662
+ this.removeOrphanedAttributes();
1663
+ this.enforceByteRetention();
1664
+ }
1665
+ getStats() {
1666
+ const pageCount = pragmaNumber(this.db, "page_count");
1667
+ const freePages = pragmaNumber(this.db, "freelist_count");
1668
+ const pageSize = pragmaNumber(this.db, "page_size");
1669
+ const metric = this.db.prepare("SELECT count(DISTINCT series_id) AS series, count(*) AS points FROM metric_points").get();
1670
+ return {
1671
+ bytesUsed: Math.max(0, pageCount - freePages) * pageSize,
1672
+ maxBytes: this.maxBytes,
1673
+ traceCount: this.countTraces(),
1674
+ spanCount: this.countSpans(),
1675
+ logCount: this.countLogs(),
1676
+ metricSeriesCount: Number(metric.series),
1677
+ metricPointCount: Number(metric.points)
1678
+ };
1679
+ }
1680
+ enforceByteRetention() {
1681
+ if (this.maxBytes <= 0) return;
1682
+ for (let pass = 0; pass < 100 && this.getStats().bytesUsed > this.maxBytes; pass++) {
1683
+ const before = this.getStats();
1684
+ if (before.traceCount + before.logCount + before.metricPointCount === 0) break;
1685
+ this.db.exec("BEGIN");
1686
+ try {
1687
+ const traceBatch = Math.max(1, Math.ceil(before.traceCount * .05));
1688
+ this.db.prepare(`DELETE FROM spans WHERE trace_id IN (
1689
+ SELECT trace_id FROM traces ORDER BY start_time ASC LIMIT ?
1690
+ )`).run(traceBatch);
1691
+ this.db.prepare(`DELETE FROM traces WHERE trace_id IN (
1692
+ SELECT trace_id FROM traces ORDER BY start_time ASC LIMIT ?
1693
+ )`).run(traceBatch);
1694
+ this.db.prepare(`DELETE FROM logs WHERE id IN (
1695
+ SELECT id FROM logs ORDER BY timestamp ASC LIMIT ?
1696
+ )`).run(Math.max(1, Math.ceil(before.logCount * .05)));
1697
+ this.db.prepare(`DELETE FROM metric_points WHERE rowid IN (
1698
+ SELECT rowid FROM metric_points ORDER BY timestamp ASC LIMIT ?
1699
+ )`).run(Math.max(1, Math.ceil(before.metricPointCount * .05)));
1700
+ this.db.exec(`DELETE FROM metric_series WHERE series_id NOT IN (
1701
+ SELECT DISTINCT series_id FROM metric_points
1702
+ )`);
1703
+ this.db.exec("COMMIT");
1704
+ } catch (error) {
1705
+ this.db.exec("ROLLBACK");
1706
+ throw error;
1707
+ }
1708
+ this.removeOrphanedAttributes();
1709
+ }
1710
+ }
1711
+ /**
1712
+ * Trim each series to its newest `maxMetricPoints`.
1713
+ *
1714
+ * Per series, not globally: a global cap would let one chatty instrument
1715
+ * evict every other series, blanking the quiet chart someone was watching.
1716
+ */
1717
+ enforceMetricRetention() {
1718
+ if (this.maxMetricPoints <= 0) return;
1719
+ this.db.exec("BEGIN");
1720
+ try {
1721
+ this.db.prepare(`DELETE FROM metric_points
1722
+ WHERE rowid IN (
1723
+ SELECT rowid FROM (
1724
+ SELECT rowid,
1725
+ row_number() OVER (
1726
+ PARTITION BY series_id ORDER BY timestamp DESC
1727
+ ) AS rn
1728
+ FROM metric_points
1729
+ ) WHERE rn > ?
1730
+ )`).run(this.maxMetricPoints);
1731
+ this.db.exec("COMMIT");
1732
+ } catch (error) {
1733
+ this.db.exec("ROLLBACK");
1734
+ throw error;
1735
+ }
1736
+ }
1737
+ /** Trim the log table to its newest `maxLogs` rows. */
1738
+ enforceLogRetention() {
1739
+ if (this.maxLogs <= 0) return;
1740
+ const total = this.countLogs();
1741
+ if (total <= this.maxLogs) return;
1742
+ this.db.prepare(`DELETE FROM logs WHERE id IN (
1743
+ SELECT id FROM logs ORDER BY timestamp ASC, id ASC LIMIT ?
1744
+ )`).run(total - this.maxLogs);
1745
+ this.removeOrphanedAttributes();
1746
+ }
1747
+ removeOrphanedAttributes() {
1748
+ this.db.exec(`
1749
+ DELETE FROM attribute_occurrences
1750
+ WHERE signal = 'logs' AND entity_id NOT IN (SELECT id FROM logs);
1751
+ DELETE FROM attribute_occurrences
1752
+ WHERE signal = 'traces' AND entity_id NOT IN (
1753
+ SELECT trace_id || ':' || span_id FROM spans
1754
+ );
1755
+ DELETE FROM span_events WHERE trace_id || ':' || span_id NOT IN (
1756
+ SELECT trace_id || ':' || span_id FROM spans
1757
+ );
1758
+ DELETE FROM span_links WHERE trace_id || ':' || span_id NOT IN (
1759
+ SELECT trace_id || ':' || span_id FROM spans
1760
+ );
1761
+ `);
1762
+ }
1763
+ clear() {
1764
+ this.db.exec("DELETE FROM spans; DELETE FROM traces; DELETE FROM logs; DELETE FROM metric_points; DELETE FROM metric_series; DELETE FROM attribute_values; DELETE FROM attribute_occurrences; DELETE FROM span_events; DELETE FROM span_links;");
1765
+ }
1766
+ clearSignal(signal) {
1767
+ if (signal === "traces") this.db.exec("DELETE FROM spans; DELETE FROM traces; DELETE FROM attribute_values WHERE signal = 'traces'; DELETE FROM attribute_occurrences WHERE signal = 'traces'; DELETE FROM span_events; DELETE FROM span_links;");
1768
+ else if (signal === "logs") this.db.exec("DELETE FROM logs; DELETE FROM attribute_values WHERE signal = 'logs'; DELETE FROM attribute_occurrences WHERE signal = 'logs';");
1769
+ else this.db.exec("DELETE FROM metric_points; DELETE FROM metric_series;");
1770
+ }
1771
+ deleteMetric(name) {
1772
+ const ids = this.db.prepare("SELECT series_id FROM metric_series WHERE name = ?").all(name);
1773
+ const removePoints = this.db.prepare("DELETE FROM metric_points WHERE series_id = ?");
1774
+ this.db.exec("BEGIN");
1775
+ try {
1776
+ for (const { series_id: id } of ids) removePoints.run(id);
1777
+ this.db.prepare("DELETE FROM metric_series WHERE name = ?").run(name);
1778
+ this.db.exec("COMMIT");
1779
+ return ids.length;
1780
+ } catch (error) {
1781
+ this.db.exec("ROLLBACK");
1782
+ throw error;
1783
+ }
1784
+ }
1785
+ deleteTraces(traceIds) {
1786
+ const ids = [...new Set(traceIds)].slice(0, 1e3);
1787
+ const removeSpans = this.db.prepare("DELETE FROM spans WHERE trace_id = ?");
1788
+ const removeTrace = this.db.prepare("DELETE FROM traces WHERE trace_id = ?");
1789
+ let deleted = 0;
1790
+ this.db.exec("BEGIN");
1791
+ try {
1792
+ for (const id of ids) {
1793
+ removeSpans.run(id);
1794
+ deleted += Number(removeTrace.run(id).changes);
1795
+ }
1796
+ this.db.exec("COMMIT");
1797
+ } catch (error) {
1798
+ this.db.exec("ROLLBACK");
1799
+ throw error;
1800
+ }
1801
+ this.removeOrphanedAttributes();
1802
+ return deleted;
1803
+ }
1804
+ close() {
1805
+ try {
1806
+ this.db.close();
1807
+ } catch {}
1808
+ }
1809
+ /**
1810
+ * Hydrate a page of traces with one span query rather than one per trace.
1811
+ *
1812
+ * A list of 100 traces was 101 statements: the page, then a `SELECT` per
1813
+ * trace. Grouping in memory costs the same rows and one round of planning.
1814
+ * Ordering is `trace_id, start_time` so each group arrives already in the
1815
+ * order a waterfall draws it, which is what the list-hydration test pins.
1816
+ */
1817
+ hydrateTracePage(rows) {
1818
+ if (rows.length === 0) return [];
1819
+ const placeholders = rows.map(() => "?").join(", ");
1820
+ const spanRows = this.db.prepare(`SELECT * FROM spans WHERE trace_id IN (${placeholders})
1821
+ ORDER BY trace_id ASC, start_time ASC`).all(...rows.map((row) => row.trace_id));
1822
+ const byTrace = /* @__PURE__ */ new Map();
1823
+ for (const spanRow of spanRows) {
1824
+ const list = byTrace.get(spanRow.trace_id);
1825
+ if (list) list.push(hydrateSpan(spanRow));
1826
+ else byTrace.set(spanRow.trace_id, [hydrateSpan(spanRow)]);
1827
+ }
1828
+ return rows.map((row) => this.assembleTrace(row, byTrace.get(row.trace_id) ?? []));
1829
+ }
1830
+ hydrateTrace(row) {
1831
+ const spanRows = this.db.prepare("SELECT * FROM spans WHERE trace_id = ? ORDER BY start_time ASC").all(row.trace_id);
1832
+ return this.assembleTrace(row, spanRows.map(hydrateSpan));
1833
+ }
1834
+ /** The row-to-trace mapping, shared by the single and batched paths. */
1835
+ assembleTrace(row, spans) {
1836
+ return {
1837
+ traceId: row.trace_id,
1838
+ correlationId: row.correlation_id ?? row.trace_id,
1839
+ service: row.service ?? "unknown",
1840
+ spans,
1841
+ rootSpan: spans.find((s) => s.spanId === row.root_span_id) ?? spans[0],
1842
+ startTime: Number(row.start_time),
1843
+ endTime: Number(row.end_time),
1844
+ duration: Number(row.duration),
1845
+ status: row.status,
1846
+ partial: row.partial === 1
1847
+ };
1848
+ }
1849
+ };
1850
+ function hydrateLog(row) {
1851
+ const structured = row.body_json ? parseJson(row.body_json) : void 0;
1852
+ return {
1853
+ id: row.id,
1854
+ timestamp: Number(row.timestamp),
1855
+ body: structured ?? row.body_text,
1856
+ resourceName: row.service ?? void 0,
1857
+ severityText: row.severity_text ?? void 0,
1858
+ severityNumber: row.severity_number ?? void 0,
1859
+ traceId: row.trace_id ?? void 0,
1860
+ spanId: row.span_id ?? void 0,
1861
+ attributes: parseJson(row.attributes) ?? {},
1862
+ resource: parseJson(row.resource)
1863
+ };
1864
+ }
1865
+ function hydratePoint(row) {
1866
+ return {
1867
+ timestamp: Number(row.timestamp),
1868
+ startTimestamp: row.start_timestamp === null ? void 0 : Number(row.start_timestamp),
1869
+ attributes: {},
1870
+ value: row.value ?? void 0,
1871
+ count: row.count ?? void 0,
1872
+ sum: row.sum ?? void 0,
1873
+ min: row.min ?? void 0,
1874
+ max: row.max ?? void 0,
1875
+ bucketCounts: parseJson(row.bucket_counts),
1876
+ explicitBounds: parseJson(row.explicit_bounds),
1877
+ scale: row.exp_scale ?? void 0,
1878
+ zeroCount: row.zero_count ?? void 0,
1879
+ zeroThreshold: row.zero_threshold ?? void 0,
1880
+ positive: parseJson(row.positive_buckets),
1881
+ negative: parseJson(row.negative_buckets),
1882
+ quantiles: parseJson(row.quantiles),
1883
+ exemplars: parseJson(row.exemplars)
1884
+ };
1885
+ }
1886
+ /**
1887
+ * Content hash identifying one series.
1888
+ *
1889
+ * Attribute keys are sorted before hashing so an exporter that emits the same
1890
+ * attributes in a different order — which nothing forbids — cannot split one
1891
+ * logical series into two chart lines.
1892
+ */
1893
+ function seriesIdentity(stream, attributes) {
1894
+ return createHash("sha256").update([
1895
+ stream.name,
1896
+ stream.kind,
1897
+ stream.unit ?? "",
1898
+ stream.service,
1899
+ stream.scope?.name ?? "",
1900
+ stream.scope?.version ?? "",
1901
+ stableJson(stream.resource),
1902
+ stableJson(attributes)
1903
+ ].join("\0")).digest("hex").slice(0, 32);
1904
+ }
1905
+ /** JSON with keys sorted, so equal maps always serialize identically. */
1906
+ function stableJson(value) {
1907
+ const sorted = {};
1908
+ for (const key of Object.keys(value).sort()) sorted[key] = value[key];
1909
+ return JSON.stringify(sorted);
1910
+ }
1911
+ function hydrateSpan(row) {
1912
+ return {
1913
+ spanId: row.span_id,
1914
+ traceId: row.trace_id,
1915
+ parentSpanId: row.parent_span_id ?? void 0,
1916
+ name: row.name,
1917
+ kind: row.kind,
1918
+ startTime: Number(row.start_time),
1919
+ endTime: Number(row.end_time),
1920
+ duration: Number(row.duration),
1921
+ attributes: parseJson(row.attributes) ?? {},
1922
+ status: {
1923
+ code: row.status_code,
1924
+ message: row.status_message ?? void 0
1925
+ },
1926
+ events: parseJson(row.events) ?? [],
1927
+ links: parseJson(row.links) ?? void 0,
1928
+ scope: parseJson(row.scope) ?? void 0
1929
+ };
1930
+ }
1931
+ /** Prefer the service that produced the span, falling back to its trace root. */
1932
+ function spanService(span, traceService) {
1933
+ const service = span.attributes?.["service.name"];
1934
+ return typeof service === "string" && service.length > 0 ? service : traceService ?? null;
1935
+ }
1936
+ /**
1937
+ * Decode stored JSON, tolerating corruption.
1938
+ *
1939
+ * A single unparseable attribute blob should cost one span its attributes, not
1940
+ * fail the whole query — which is what a throw here would do.
1941
+ */
1942
+ function parseJson(text) {
1943
+ if (!text) return void 0;
1944
+ try {
1945
+ return JSON.parse(text);
1946
+ } catch {
1947
+ return;
1948
+ }
1949
+ }
1950
+ function pragmaNumber(db, name) {
1951
+ const row = db.prepare(`PRAGMA ${name}`).get();
1952
+ return Number(Object.values(row)[0] ?? 0);
1953
+ }
1954
+ function escapeLike(value) {
1955
+ return value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
1956
+ }
1957
+ function encodeCursor(cursor) {
1958
+ return Buffer.from(`${cursor.startTime}:${cursor.traceId}`).toString("base64url");
1959
+ }
1960
+ /** Decode a cursor, treating anything malformed as "start from the beginning". */
1961
+ function decodeCursor(raw) {
1962
+ if (!raw) return null;
1963
+ try {
1964
+ const text = Buffer.from(raw, "base64url").toString("utf8");
1965
+ const separator = text.indexOf(":");
1966
+ if (separator < 0) return null;
1967
+ const startTime = Number(text.slice(0, separator));
1968
+ const traceId = text.slice(separator + 1);
1969
+ if (!Number.isFinite(startTime) || !traceId) return null;
1970
+ return {
1971
+ startTime,
1972
+ traceId
1973
+ };
1974
+ } catch {
1975
+ return null;
1976
+ }
1977
+ }
1978
+
1979
+ //#endregion
1980
+ //#region src/server/otlp-types.ts
1981
+ /**
1982
+ * An exporter's payload, read as the envelope it claims to be.
1983
+ *
1984
+ * SAFETY: this is the one place the receiver trusts the wire. Every field of
1985
+ * every envelope above is optional, so a payload that is not what it claims
1986
+ * reads back as empty arrays and undefined fields rather than throwing - which
1987
+ * is what the callers below rely on when they find no spans to add.
1988
+ */
1989
+ function otlpEnvelope(payload) {
1990
+ if (typeof payload !== "object" || payload === null) return void 0;
1991
+ return payload;
1992
+ }
1993
+
1994
+ //#endregion
1995
+ //#region src/server/otlp.ts
1996
+ function resolveOtlpValue(v) {
1997
+ if (!v) return void 0;
1998
+ if (v.stringValue !== void 0) return v.stringValue;
1999
+ if (v.boolValue !== void 0) return v.boolValue;
2000
+ if (v.intValue !== void 0) return Number(v.intValue);
2001
+ if (v.doubleValue !== void 0) return v.doubleValue;
2002
+ if (v.bytesValue !== void 0) return v.bytesValue;
2003
+ if (v.arrayValue?.values) return v.arrayValue.values.map(resolveOtlpValue);
2004
+ if (v.kvlistValue?.values) return flattenAttributes(v.kvlistValue.values);
2005
+ }
2006
+ function flattenAttributes(attrs) {
2007
+ const out = {};
2008
+ if (!attrs) return out;
2009
+ for (const { key, value } of attrs) out[key] = resolveOtlpValue(value);
2010
+ return out;
2011
+ }
2012
+ /**
2013
+ * A log record's body: the text it carried, or the structure it carried when
2014
+ * the sender used an OTLP kvlist or array rather than a string.
2015
+ */
2016
+ function logBody(body) {
2017
+ const text = asString(body);
2018
+ if (text !== void 0) return text;
2019
+ if (body === void 0 || body === null) return "";
2020
+ const structured = asObject(body);
2021
+ if (!structured) return String(body);
2022
+ return structured;
2023
+ }
2024
+ /**
2025
+ * Attributes handed to the agent layer, whose `Attributes` is OTel's own -
2026
+ * scalars and arrays of scalars, nothing nested.
2027
+ *
2028
+ * SAFETY: a coding agent's metrics and events carry scalar attributes only,
2029
+ * so the two shapes agree in practice. A sender that nests one anyway is
2030
+ * rendered by the Agents tab as whatever it is rather than being dropped.
2031
+ */
2032
+ function agentAttributes(attributes) {
2033
+ return attributes;
2034
+ }
2035
+ function nanoToMs(nano) {
2036
+ if (!nano) return 0;
2037
+ const ns = BigInt(nano);
2038
+ const ms = ns / 1000000n;
2039
+ const remNs = ns % 1000000n;
2040
+ return Number(ms) + Number(remNs) / 1e6;
2041
+ }
2042
+ const SPAN_KIND_MAP = /* @__PURE__ */ new Map([
2043
+ [0, "INTERNAL"],
2044
+ [1, "INTERNAL"],
2045
+ [2, "SERVER"],
2046
+ [3, "CLIENT"],
2047
+ [4, "PRODUCER"],
2048
+ [5, "CONSUMER"],
2049
+ ["SPAN_KIND_INTERNAL", "INTERNAL"],
2050
+ ["SPAN_KIND_SERVER", "SERVER"],
2051
+ ["SPAN_KIND_CLIENT", "CLIENT"],
2052
+ ["SPAN_KIND_PRODUCER", "PRODUCER"],
2053
+ ["SPAN_KIND_CONSUMER", "CONSUMER"]
2054
+ ]);
2055
+ function normalizeHexId(id) {
2056
+ if (!id) return "";
2057
+ if (/^[A-Za-z0-9+/=]+$/.test(id) && !/^[0-9a-f]+$/i.test(id) && (id.length === 12 || id.length === 24 || id.length === 28 || id.length === 44 || id.length === 48)) try {
2058
+ return Buffer.from(id, "base64").toString("hex");
2059
+ } catch {}
2060
+ return id;
2061
+ }
2062
+ function parseOtlpTraces(payload) {
2063
+ const resourceSpans = otlpEnvelope(payload)?.resourceSpans;
2064
+ if (!resourceSpans || resourceSpans.length === 0) return [];
2065
+ const traceMap = /* @__PURE__ */ new Map();
2066
+ for (const rs of resourceSpans) {
2067
+ const resourceAttrs = flattenAttributes(rs.resource?.attributes);
2068
+ const service = String(resourceAttrs["service.name"] || "unknown");
2069
+ for (const ss of rs.scopeSpans ?? []) {
2070
+ const scope = ss.scope?.name ? {
2071
+ name: ss.scope.name,
2072
+ version: ss.scope.version || void 0
2073
+ } : void 0;
2074
+ for (const span of ss.spans || []) {
2075
+ const traceId = normalizeHexId(span.traceId);
2076
+ if (!traceId) continue;
2077
+ const startMs = nanoToMs(span.startTimeUnixNano);
2078
+ const endMs = nanoToMs(span.endTimeUnixNano);
2079
+ const statusCode = span.status?.code;
2080
+ let status = "UNSET";
2081
+ if (statusCode === 1 || statusCode === "STATUS_CODE_OK") status = "OK";
2082
+ if (statusCode === 2 || statusCode === "STATUS_CODE_ERROR") status = "ERROR";
2083
+ const spanData = {
2084
+ traceId,
2085
+ spanId: normalizeHexId(span.spanId),
2086
+ parentSpanId: normalizeHexId(span.parentSpanId) || void 0,
2087
+ name: span.name || "unknown",
2088
+ kind: SPAN_KIND_MAP.get(span.kind ?? 0) ?? "INTERNAL",
2089
+ startTime: startMs,
2090
+ endTime: endMs,
2091
+ duration: endMs - startMs,
2092
+ attributes: {
2093
+ ...resourceAttrs,
2094
+ ...flattenAttributes(span.attributes)
2095
+ },
2096
+ status: {
2097
+ code: status,
2098
+ message: span.status?.message
2099
+ },
2100
+ events: (span.events ?? []).map((e) => ({
2101
+ name: e.name || "",
2102
+ timestamp: nanoToMs(e.timeUnixNano),
2103
+ attributes: flattenAttributes(e.attributes)
2104
+ })),
2105
+ links: (span.links ?? []).map((l) => ({
2106
+ traceId: normalizeHexId(l.traceId),
2107
+ spanId: normalizeHexId(l.spanId),
2108
+ attributes: flattenAttributes(l.attributes)
2109
+ })),
2110
+ scope
2111
+ };
2112
+ const existing = traceMap.get(traceId);
2113
+ if (existing) existing.spans.push(spanData);
2114
+ else traceMap.set(traceId, {
2115
+ spans: [spanData],
2116
+ service
2117
+ });
2118
+ }
2119
+ }
2120
+ }
2121
+ const traces = [];
2122
+ for (const [traceId, { spans, service }] of traceMap) {
2123
+ const sorted = spans.sort((a, b) => a.startTime - b.startTime);
2124
+ const { rootSpan, partial } = pickRoot(sorted);
2125
+ const startTime = Math.min(...sorted.map((s) => s.startTime));
2126
+ const endTime = Math.max(...sorted.map((s) => s.endTime));
2127
+ const hasError = sorted.some((s) => s.status.code === "ERROR");
2128
+ const trace = {
2129
+ traceId,
2130
+ correlationId: traceId.slice(0, 16),
2131
+ rootSpan,
2132
+ spans: sorted,
2133
+ startTime,
2134
+ endTime,
2135
+ duration: endTime - startTime,
2136
+ status: hasError ? "ERROR" : "OK",
2137
+ service
2138
+ };
2139
+ if (partial) trace.partial = true;
2140
+ traces.push(trace);
2141
+ }
2142
+ return traces;
2143
+ }
2144
+ function parseOtlpLogs(payload) {
2145
+ const resourceLogs = otlpEnvelope(payload)?.resourceLogs;
2146
+ if (!resourceLogs) return [];
2147
+ const logs = [];
2148
+ for (const rl of resourceLogs) {
2149
+ const resourceAttrs = flattenAttributes(rl.resource?.attributes);
2150
+ for (const sl of rl.scopeLogs ?? []) for (const rec of sl.logRecords ?? []) {
2151
+ const timestamp = nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano);
2152
+ const traceId = normalizeHexId(rec.traceId) || void 0;
2153
+ const spanId = normalizeHexId(rec.spanId) || void 0;
2154
+ const body = rec.body ? resolveOtlpValue(rec.body) : "";
2155
+ logs.push({
2156
+ id: `${traceId || "no-trace"}:${spanId || "no-span"}:${timestamp}:${rec.severityNumber || 0}`,
2157
+ traceId,
2158
+ spanId,
2159
+ resourceName: getResourceName(resourceAttrs),
2160
+ severityText: rec.severityText,
2161
+ severityNumber: rec.severityNumber,
2162
+ body: logBody(body),
2163
+ timestamp,
2164
+ attributes: flattenAttributes(rec.attributes),
2165
+ resource: resourceAttrs
2166
+ });
2167
+ }
2168
+ }
2169
+ return logs;
2170
+ }
2171
+ function countOtlpMetrics(payload) {
2172
+ const resourceMetrics = otlpEnvelope(payload)?.resourceMetrics;
2173
+ if (!resourceMetrics) return 0;
2174
+ let count = 0;
2175
+ for (const rm of resourceMetrics) for (const sm of rm.scopeMetrics ?? []) count += (sm.metrics ?? []).length;
2176
+ return count;
2177
+ }
2178
+ function extractDataPoints(metric) {
2179
+ const points = [];
2180
+ const numberPoints = metric.sum?.dataPoints ?? metric.gauge?.dataPoints;
2181
+ if (Array.isArray(numberPoints)) for (const dp of numberPoints) {
2182
+ const value = dp.asDouble !== void 0 ? Number(dp.asDouble) : dp.asInt !== void 0 ? Number(dp.asInt) : 0;
2183
+ points.push({
2184
+ value,
2185
+ attributes: agentAttributes(flattenAttributes(dp.attributes)),
2186
+ timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano)
2187
+ });
2188
+ }
2189
+ const histPoints = metric.histogram?.dataPoints;
2190
+ if (Array.isArray(histPoints)) for (const dp of histPoints) points.push({
2191
+ value: dp.count !== void 0 ? Number(dp.count) : 0,
2192
+ attributes: agentAttributes(flattenAttributes(dp.attributes)),
2193
+ timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano)
2194
+ });
2195
+ return points;
2196
+ }
2197
+ /**
2198
+ * Parse OTLP metrics into structured records with data points + attributes,
2199
+ * for the agent layer (and richer metric views). Works for both OTLP/JSON and
2200
+ * decoded OTLP/protobuf — they share the same camelCase shape.
2201
+ */
2202
+ function readTemporality$1(metric) {
2203
+ const raw = metric.sum?.aggregationTemporality ?? metric.histogram?.aggregationTemporality;
2204
+ if (raw === 2 || raw === "AGGREGATION_TEMPORALITY_CUMULATIVE") return "cumulative";
2205
+ if (raw === 1 || raw === "AGGREGATION_TEMPORALITY_DELTA") return "delta";
2206
+ }
2207
+ function parseOtlpMetrics(payload) {
2208
+ const resourceMetrics = otlpEnvelope(payload)?.resourceMetrics;
2209
+ if (!resourceMetrics) return [];
2210
+ const records = [];
2211
+ for (const rm of resourceMetrics) {
2212
+ const resource = agentAttributes(flattenAttributes(rm.resource?.attributes));
2213
+ for (const sm of rm.scopeMetrics ?? []) {
2214
+ const scope = sm.scope?.name ? {
2215
+ name: sm.scope.name,
2216
+ version: sm.scope.version || void 0
2217
+ } : void 0;
2218
+ for (const metric of sm.metrics ?? []) records.push({
2219
+ name: metric.name ?? "",
2220
+ unit: metric.unit || void 0,
2221
+ description: metric.description || void 0,
2222
+ temporality: readTemporality$1(metric),
2223
+ dataPoints: extractDataPoints(metric),
2224
+ resource,
2225
+ scope
2226
+ });
2227
+ }
2228
+ }
2229
+ return records;
2230
+ }
2231
+ /**
2232
+ * Parse OTLP logs into `AgentRawEvent`s for the agent layer. Keeps the
2233
+ * instrumentation scope and event name (Claude Code emits its events as logs,
2234
+ * with the unprefixed name in the `event.name` attribute). Distinct from
2235
+ * `parseOtlpLogs`, which feeds the generic Logs tab.
2236
+ */
2237
+ function parseOtlpAgentEvents(payload) {
2238
+ const resourceLogs = otlpEnvelope(payload)?.resourceLogs;
2239
+ if (!resourceLogs) return [];
2240
+ const events = [];
2241
+ for (const rl of resourceLogs) {
2242
+ const resource = agentAttributes(flattenAttributes(rl.resource?.attributes));
2243
+ for (const sl of rl.scopeLogs ?? []) {
2244
+ const scope = sl.scope?.name ? {
2245
+ name: sl.scope.name,
2246
+ version: sl.scope.version || void 0
2247
+ } : void 0;
2248
+ for (const rec of sl.logRecords ?? []) {
2249
+ const attributes = agentAttributes(flattenAttributes(rec.attributes));
2250
+ const eventName = rec.eventName || String(attributes["event.name"] ?? "");
2251
+ events.push({
2252
+ eventName,
2253
+ timestamp: nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano),
2254
+ body: rec.body ? resolveOtlpValue(rec.body) : void 0,
2255
+ attributes,
2256
+ resource,
2257
+ scope
2258
+ });
2259
+ }
2260
+ }
2261
+ }
2262
+ return events;
2263
+ }
2264
+ async function readJsonBody(req) {
2265
+ return new Promise((resolve, reject) => {
2266
+ const chunks = [];
2267
+ req.on("data", (chunk) => chunks.push(chunk));
2268
+ req.on("end", () => {
2269
+ try {
2270
+ resolve(JSON.parse(Buffer.concat(chunks).toString()));
2271
+ } catch {
2272
+ reject(/* @__PURE__ */ new Error("Invalid JSON"));
2273
+ }
2274
+ });
2275
+ req.on("error", reject);
2276
+ });
2277
+ }
2278
+ async function readRawBody(req) {
2279
+ return new Promise((resolve, reject) => {
2280
+ const chunks = [];
2281
+ req.on("data", (chunk) => chunks.push(chunk));
2282
+ req.on("end", () => resolve(Buffer.concat(chunks)));
2283
+ req.on("error", reject);
2284
+ });
2285
+ }
2286
+ /**
2287
+ * True for OTLP/protobuf bodies. The OpenTelemetry Python/Java/Go SDKs default to
2288
+ * `http/protobuf` over OTLP HTTP, sending `application/x-protobuf`; some clients use
2289
+ * `application/protobuf`. Anything else (JSON, unset) is treated as OTLP/JSON.
2290
+ */
2291
+ function isProtobufContentType(contentType) {
2292
+ if (!contentType) return false;
2293
+ const value = contentType.toLowerCase();
2294
+ return value.includes("application/x-protobuf") || value.includes("application/protobuf");
2295
+ }
2296
+ /**
2297
+ * Below this, gzip costs more than it saves: the header alone is 18 bytes and
2298
+ * a small body already fits one segment.
2299
+ */
2300
+ const GZIP_MIN_BYTES = 1024;
2301
+ /**
2302
+ * Send JSON, gzipped when the client accepts it and the body is big enough.
2303
+ *
2304
+ * A trace payload is mostly repeated keys and near-identical ids and strings,
2305
+ * which is the shape deflate handles best: a 4,891-span trace measures 2,078
2306
+ * KiB raw against 41 KiB gzipped. Reshaping the payload to dedupe scopes and
2307
+ * drop the repeated trace id was measured against this and is not worth doing,
2308
+ * since deflate already removes what such a dedupe removes.
2309
+ *
2310
+ * `res.req` is Node's own back-reference to the request, so the negotiation
2311
+ * needs nothing threaded through the twenty-odd call sites.
2312
+ */
2313
+ function sendJson(res, status, data) {
2314
+ const body = Buffer.from(JSON.stringify(data), "utf8");
2315
+ if (String(res.req?.headers["accept-encoding"] ?? "").includes("gzip") && body.byteLength >= GZIP_MIN_BYTES) {
2316
+ const packed = gzipSync(body);
2317
+ res.writeHead(status, {
2318
+ "Content-Type": "application/json",
2319
+ "Content-Encoding": "gzip",
2320
+ Vary: "Accept-Encoding",
2321
+ "Content-Length": packed.byteLength
2322
+ });
2323
+ res.end(packed);
2324
+ return;
2325
+ }
2326
+ res.writeHead(status, {
2327
+ "Content-Type": "application/json",
2328
+ Vary: "Accept-Encoding",
2329
+ "Content-Length": body.byteLength
2330
+ });
2331
+ res.end(body);
2332
+ }
2333
+
2334
+ //#endregion
2335
+ //#region src/server/metric-streams.ts
2336
+ /** The aggregation arms of a Metric's oneof, in the order we probe them. */
2337
+ const ARMS = [
2338
+ ["gauge", "gauge"],
2339
+ ["sum", "sum"],
2340
+ ["histogram", "histogram"],
2341
+ ["exponentialHistogram", "exponentialHistogram"],
2342
+ ["summary", "summary"]
2343
+ ];
2344
+ function parseOtlpMetricStreams(payload) {
2345
+ const resourceMetrics = otlpEnvelope(payload)?.resourceMetrics;
2346
+ if (!Array.isArray(resourceMetrics)) return [];
2347
+ const streams = [];
2348
+ for (const rm of resourceMetrics) {
2349
+ const resource = flattenAttributes(rm.resource?.attributes);
2350
+ const service = String(resource["service.name"] ?? "unknown");
2351
+ for (const sm of rm.scopeMetrics ?? []) {
2352
+ const scope = sm.scope?.name ? {
2353
+ name: sm.scope.name,
2354
+ version: sm.scope.version || void 0
2355
+ } : void 0;
2356
+ for (const metric of sm.metrics ?? []) {
2357
+ const found = findAggregation(metric);
2358
+ if (!found) continue;
2359
+ const points = (found.aggregation.dataPoints ?? []).map((dp) => readPoint(dp, found.kind));
2360
+ if (points.length === 0) continue;
2361
+ streams.push({
2362
+ name: metric.name ?? "",
2363
+ unit: metric.unit || void 0,
2364
+ description: metric.description || void 0,
2365
+ kind: found.kind,
2366
+ temporality: readTemporality(found.aggregation),
2367
+ monotonic: found.aggregation.isMonotonic,
2368
+ service,
2369
+ scope,
2370
+ resource,
2371
+ points
2372
+ });
2373
+ }
2374
+ }
2375
+ }
2376
+ return streams;
2377
+ }
2378
+ function findAggregation(metric) {
2379
+ for (const [kind, key] of ARMS) {
2380
+ const aggregation = metric[key];
2381
+ if (aggregation) return {
2382
+ kind,
2383
+ aggregation
2384
+ };
2385
+ }
2386
+ }
2387
+ function readPoint(dp, kind) {
2388
+ const point = {
2389
+ timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano),
2390
+ startTimestamp: dp.startTimeUnixNano ? nanoToMs(dp.startTimeUnixNano) : void 0,
2391
+ attributes: flattenAttributes(dp.attributes)
2392
+ };
2393
+ if (kind === "gauge" || kind === "sum") point.value = readNumber(dp.asDouble) ?? readNumber(dp.asInt) ?? 0;
2394
+ if (kind !== "gauge" && kind !== "sum") {
2395
+ point.count = readNumber(dp.count);
2396
+ point.sum = readNumber(dp.sum);
2397
+ point.min = readNumber(dp.min);
2398
+ point.max = readNumber(dp.max);
2399
+ }
2400
+ if (Array.isArray(dp.bucketCounts)) point.bucketCounts = dp.bucketCounts.map((n) => readNumber(n) ?? 0);
2401
+ if (Array.isArray(dp.explicitBounds)) point.explicitBounds = dp.explicitBounds.map((n) => readNumber(n) ?? 0);
2402
+ if (kind === "exponentialHistogram") {
2403
+ point.scale = readNumber(dp.scale);
2404
+ point.zeroCount = readNumber(dp.zeroCount);
2405
+ point.zeroThreshold = readNumber(dp.zeroThreshold);
2406
+ point.positive = readExponentialBuckets(dp.positive);
2407
+ point.negative = readExponentialBuckets(dp.negative);
2408
+ }
2409
+ if (Array.isArray(dp.quantileValues) && dp.quantileValues.length > 0) point.quantiles = dp.quantileValues.map((q) => ({
2410
+ quantile: q.quantile ?? 0,
2411
+ value: q.value ?? 0
2412
+ }));
2413
+ if (Array.isArray(dp.exemplars) && dp.exemplars.length > 0) point.exemplars = dp.exemplars.map((ex) => ({
2414
+ value: readNumber(ex.asDouble) ?? readNumber(ex.asInt) ?? 0,
2415
+ timestamp: nanoToMs(ex.timeUnixNano),
2416
+ traceId: normalizeHexId(ex.traceId) || void 0,
2417
+ spanId: normalizeHexId(ex.spanId) || void 0
2418
+ }));
2419
+ return point;
2420
+ }
2421
+ function readExponentialBuckets(buckets) {
2422
+ if (!buckets || !Array.isArray(buckets.bucketCounts)) return void 0;
2423
+ return {
2424
+ offset: buckets.offset ?? 0,
2425
+ bucketCounts: buckets.bucketCounts.map((count) => readNumber(count) ?? 0)
2426
+ };
2427
+ }
2428
+ /**
2429
+ * Read an OTLP number.
2430
+ *
2431
+ * int64 arrives as a string in OTLP/JSON (it does not survive JSON) and as a
2432
+ * number once protobuf is decoded, so both spellings have to work.
2433
+ */
2434
+ function readNumber(raw) {
2435
+ if (raw === void 0 || raw === null || raw === "") return void 0;
2436
+ const value = Number(raw);
2437
+ return Number.isFinite(value) ? value : void 0;
2438
+ }
2439
+ /** 1 = DELTA, 2 = CUMULATIVE; the string enum spelling is handled too. */
2440
+ function readTemporality(aggregation) {
2441
+ const raw = aggregation.aggregationTemporality;
2442
+ if (raw === 2 || raw === "AGGREGATION_TEMPORALITY_CUMULATIVE") return "cumulative";
2443
+ if (raw === 1 || raw === "AGGREGATION_TEMPORALITY_DELTA") return "delta";
2444
+ }
2445
+
2446
+ //#endregion
2447
+ //#region src/server/server.ts
2448
+ /** How often the store is pruned past its caps. */
2449
+ const DEFAULT_RETENTION_INTERVAL_MS = 3e4;
2450
+ /**
2451
+ * Traces read when aggregating errors.
2452
+ *
2453
+ * Deliberately large: an error group's count is only right if every occurrence
2454
+ * in the window is seen, and a page-sized read would under-report the common
2455
+ * failures most — the ones with occurrences past the page boundary.
2456
+ */
2457
+ var DevtoolsServer = class {
2458
+ wss;
2459
+ wsPath;
2460
+ loopbackOnly;
2461
+ clients = /* @__PURE__ */ new Set();
2462
+ httpServer;
2463
+ traces = [];
2464
+ logs = [];
2465
+ agentSessions = /* @__PURE__ */ new Map();
2466
+ errorAggregator = new ErrorAggregator();
2467
+ limits;
2468
+ verbose;
2469
+ _port;
2470
+ onData;
2471
+ /**
2472
+ * Durable store. The in-memory `traces`/`logs` arrays above remain the live
2473
+ * tail — what a freshly-connected client is handed and what streams over WS —
2474
+ * while the store answers queries and outlives the process. Both are written
2475
+ * on every ingest; neither is derived from the other.
2476
+ */
2477
+ store;
2478
+ retentionTimer = null;
2479
+ constructor(options = {}) {
2480
+ this.limits = resolveTelemetryLimits(options);
2481
+ this.verbose = options.verbose ?? false;
2482
+ this._port = options.port ?? 4318;
2483
+ this.onData = options.onData;
2484
+ this.store = new DevtoolsStore({
2485
+ path: options.dbPath,
2486
+ maxTraces: options.maxTraces,
2487
+ maxLogs: options.maxLogs,
2488
+ maxBytes: options.maxDbBytes
2489
+ });
2490
+ this.startRetentionLoop(options.retentionIntervalMs);
2491
+ this.httpServer = options.server ?? createServer();
2492
+ const loopbackOnly = options.host == null || hostHeaderIsLoopback(options.host);
2493
+ this.wsPath = options.path ?? "/ws";
2494
+ this.loopbackOnly = loopbackOnly;
2495
+ this.wss = new WebSocketServer({
2496
+ noServer: true,
2497
+ perMessageDeflate: { threshold: 1024 }
2498
+ });
2499
+ this.attachWebSocket(this.httpServer);
2500
+ this.wss.on("error", (err) => {
2501
+ if (this.httpServer.listening) throw err;
2502
+ });
2503
+ this.wss.on("connection", (ws) => {
2504
+ this.clients.add(ws);
2505
+ this.log(`Client connected (${this.clients.size} total)`);
2506
+ const data = this.getCurrentData();
2507
+ if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0 || (data.agents?.length ?? 0) > 0) ws.send(JSON.stringify(data));
2508
+ ws.on("close", () => {
2509
+ this.clients.delete(ws);
2510
+ this.log(`Client disconnected (${this.clients.size} total)`);
2511
+ });
2512
+ });
2513
+ if (!options.server) {
2514
+ const listening = () => {
2515
+ const addr = this.httpServer.address();
2516
+ if (addr && typeof addr === "object") this._port = addr.port;
2517
+ this.log(`WebSocket server listening on port ${this._port}`);
2518
+ };
2519
+ if (options.host == null) this.httpServer.listen(this._port, listening);
2520
+ else this.httpServer.listen(this._port, options.host, listening);
2521
+ }
2522
+ }
2523
+ get port() {
2524
+ const addr = this.httpServer.address();
2525
+ if (addr && typeof addr === "object") return addr.port;
2526
+ return this._port;
2527
+ }
2528
+ get clientCount() {
2529
+ return this.clients.size;
2530
+ }
2531
+ addTrace(trace) {
2532
+ const existing = this.traces.find((t) => t.traceId === trace.traceId);
2533
+ const merged = existing ?? trace;
2534
+ let newSpans = trace.spans;
2535
+ if (existing) {
2536
+ const existingSpanIds = new Set(existing.spans.map((s) => s.spanId));
2537
+ newSpans = [];
2538
+ for (const span of trace.spans) if (!existingSpanIds.has(span.spanId)) {
2539
+ existing.spans.push(span);
2540
+ newSpans.push(span);
2541
+ }
2542
+ existing.startTime = Math.min(existing.startTime, trace.startTime);
2543
+ existing.endTime = Math.max(existing.endTime, trace.endTime);
2544
+ existing.duration = existing.endTime - existing.startTime;
2545
+ if (trace.status === "ERROR") existing.status = "ERROR";
2546
+ existing.spans.sort((a, b) => a.startTime - b.startTime);
2547
+ const { rootSpan, partial } = pickRoot(existing.spans);
2548
+ existing.rootSpan = rootSpan;
2549
+ if (partial) existing.partial = true;
2550
+ else {
2551
+ delete existing.partial;
2552
+ const rootService = rootSpan.attributes?.["service.name"];
2553
+ if (typeof rootService === "string" && rootService.length > 0) existing.service = rootService;
2554
+ }
2555
+ } else this.traces = appendWithLimit(this.traces, trace, this.limits.maxTraceCount);
2556
+ if (newSpans.length > 0) this.errorAggregator.addErrorsFromTrace({
2557
+ ...trace,
2558
+ spans: newSpans
2559
+ });
2560
+ this.store.ingestTraces([merged]);
2561
+ this.broadcast({
2562
+ traces: [merged],
2563
+ logs: [],
2564
+ errors: this.errorAggregator.getErrorGroups()
2565
+ });
2566
+ }
2567
+ addTraces(traces) {
2568
+ for (const trace of traces) this.addTrace(trace);
2569
+ }
2570
+ addLog(log) {
2571
+ this.logs = appendWithLimit(this.logs, log, this.limits.maxLogCount);
2572
+ this.store.ingestLogs([log]);
2573
+ this.broadcast({
2574
+ traces: [],
2575
+ logs: [log],
2576
+ errors: this.errorAggregator.getErrorGroups()
2577
+ });
2578
+ }
2579
+ addLogs(logs) {
2580
+ this.logs = appendManyWithLimit(this.logs, logs, this.limits.maxLogCount);
2581
+ this.store.ingestLogs(logs);
2582
+ this.broadcast({
2583
+ traces: [],
2584
+ logs,
2585
+ errors: this.errorAggregator.getErrorGroups()
2586
+ });
2587
+ }
2588
+ /** Ingest one decoded OTLP request, regardless of its transport. */
2589
+ /**
2590
+ * Serve the live tail on another HTTP listener.
2591
+ *
2592
+ * A loopback bind produces two listeners, one per IP family, because
2593
+ * `localhost` resolves to `::1` on macOS and `127.0.0.1` elsewhere. The HTTP
2594
+ * routes were attached to both from the start and the WebSocket was not, so
2595
+ * the widget connected over one address and silently failed over the other:
2596
+ * telemetry visible, live tail dead, and nothing in the UI saying why.
2597
+ *
2598
+ * Both listeners hand their upgrades to the same `WebSocketServer`, so there
2599
+ * is still one client set and one broadcast.
2600
+ */
2601
+ attachWebSocket(server) {
2602
+ server.on("upgrade", (req, socket, head) => {
2603
+ if ((req.url ?? "/").split("?")[0] !== this.wsPath) {
2604
+ socket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
2605
+ socket.destroy();
2606
+ return;
2607
+ }
2608
+ if (!allowSensitiveRequest({
2609
+ origin: req.headers.origin,
2610
+ host: req.headers.host
2611
+ }, this.loopbackOnly)) {
2612
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
2613
+ socket.destroy();
2614
+ return;
2615
+ }
2616
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
2617
+ this.wss.emit("connection", ws, req);
2618
+ });
2619
+ });
2620
+ }
2621
+ ingestOtlp(signal, payload) {
2622
+ if (signal === "traces") {
2623
+ const traces = parseOtlpTraces(payload);
2624
+ this.addTraces(traces);
2625
+ return traces.length;
2626
+ }
2627
+ if (signal === "logs") {
2628
+ const logs = parseOtlpLogs(payload);
2629
+ this.addLogs(logs);
2630
+ this.ingestAgentEvents(parseOtlpAgentEvents(payload));
2631
+ return logs.length;
2632
+ }
2633
+ this.ingestAgentMetrics(parseOtlpMetrics(payload));
2634
+ this.ingestMetricStreams(parseOtlpMetricStreams(payload));
2635
+ return countOtlpMetrics(payload);
2636
+ }
2637
+ /** Fold decoded agent log events into sessions and broadcast the full set. */
2638
+ ingestAgentEvents(records) {
2639
+ if (records.length === 0) return;
2640
+ ingestAgentEvents(this.agentSessions, records);
2641
+ this.broadcastAgents();
2642
+ }
2643
+ /**
2644
+ * Store decoded metric streams for the Metrics tab.
2645
+ *
2646
+ * Separate from `ingestAgentMetrics`: that folds the same OTLP batch into
2647
+ * coding-agent sessions through a counter-shaped model, while this keeps the
2648
+ * full data points — buckets, quantiles, exemplars — that charts need.
2649
+ */
2650
+ ingestMetricStreams(streams) {
2651
+ if (streams.length === 0) return;
2652
+ this.store.ingestMetrics(streams);
2653
+ }
2654
+ /** Metric catalogue: every metric name held, with its kind and series count. */
2655
+ listMetricNames() {
2656
+ return this.store.listMetricNames();
2657
+ }
2658
+ queryMetricCatalog(query) {
2659
+ return this.store.queryMetricCatalog(query);
2660
+ }
2661
+ /** The series for one metric, with their points. */
2662
+ queryMetricSeries(args) {
2663
+ return this.store.queryMetricSeries(args);
2664
+ }
2665
+ /** Fold decoded agent metric records into sessions and broadcast the full set. */
2666
+ ingestAgentMetrics(records) {
2667
+ if (records.length === 0) return;
2668
+ ingestAgentMetrics(this.agentSessions, records);
2669
+ this.broadcastAgents();
2670
+ }
2671
+ broadcastAgents() {
2672
+ this.broadcast({
2673
+ traces: [],
2674
+ logs: [],
2675
+ errors: this.errorAggregator.getErrorGroups(),
2676
+ agents: [...this.agentSessions.values()]
2677
+ });
2678
+ }
2679
+ /**
2680
+ * Run a query against the durable store.
2681
+ *
2682
+ * Distinct from `getCurrentData()`, which returns the live tail: this reaches
2683
+ * the whole retained history, which is normally far larger than the tail and
2684
+ * is the only way to see anything from before the process restarted.
2685
+ */
2686
+ queryTraces(args) {
2687
+ return this.store.queryTraces(args);
2688
+ }
2689
+ /** Route and span-name counts, for the instrumentation coverage join. */
2690
+ observedSpans() {
2691
+ return this.store.observedSpans();
2692
+ }
2693
+ /** One row per matching span, as the population for a cohort comparison. */
2694
+ cohortRows(args) {
2695
+ return this.store.cohortRows(args);
2696
+ }
2697
+ /**
2698
+ * Aggregate errors from the store for a window and query.
2699
+ *
2700
+ * A fresh aggregator over whatever the store returns, rather than a second
2701
+ * implementation: the grouping, fingerprinting and sampling rules are the
2702
+ * same ones the live path uses, so the two cannot describe the same failure
2703
+ * differently.
2704
+ *
2705
+ * The live `errorAggregator` stays as it is — it backs the WS full-state
2706
+ * broadcast, which has no window and needs none.
2707
+ */
2708
+ queryErrors(args) {
2709
+ const aggregator = new ErrorAggregator();
2710
+ const seenCursors = /* @__PURE__ */ new Set();
2711
+ let cursor = args.cursor;
2712
+ do {
2713
+ const result = this.store.queryTraces({
2714
+ ...args,
2715
+ cursor
2716
+ });
2717
+ if (result.errors) return {
2718
+ errors: [],
2719
+ errors_parse: result.errors
2720
+ };
2721
+ for (const trace of result.traces) aggregator.addErrorsFromTrace(trace);
2722
+ cursor = result.nextCursor ?? void 0;
2723
+ if (cursor && seenCursors.has(cursor)) break;
2724
+ if (cursor) seenCursors.add(cursor);
2725
+ } while (cursor);
2726
+ return { errors: aggregator.getErrorGroups() };
2727
+ }
2728
+ /** Run a log query against the durable store. */
2729
+ queryLogs(args) {
2730
+ return this.store.queryLogs(args);
2731
+ }
2732
+ listQueryFields(signal) {
2733
+ return this.store.listQueryFields(signal);
2734
+ }
2735
+ pairedAttributeValues(signal, key, pairedKey, limit) {
2736
+ return this.store.pairedAttributeValues(signal, key, pairedKey, limit);
2737
+ }
2738
+ searchAttributes(signal, value, limit) {
2739
+ return this.store.searchAttributes(signal, value, limit);
2740
+ }
2741
+ getStoreStats() {
2742
+ return this.store.getStats();
2743
+ }
2744
+ describeTrace(traceId) {
2745
+ return this.store.describeTrace(traceId);
2746
+ }
2747
+ findSlowestTraces(limit) {
2748
+ return this.store.findSlowest(limit);
2749
+ }
2750
+ /** Prune the store to its retention cap. Safe to call on a timer. */
2751
+ enforceRetention() {
2752
+ this.store.enforceRetention();
2753
+ }
2754
+ /**
2755
+ * Prune periodically for the life of the server.
2756
+ *
2757
+ * `unref` matters: without it this timer alone keeps the Node process alive,
2758
+ * so a CLI that has finished its work would hang instead of exiting. A
2759
+ * failure is logged rather than thrown — an interval callback that throws
2760
+ * takes the process down, and a missed prune is not worth that.
2761
+ */
2762
+ startRetentionLoop(intervalMs = DEFAULT_RETENTION_INTERVAL_MS) {
2763
+ if (intervalMs <= 0) return;
2764
+ this.retentionTimer = setInterval(() => {
2765
+ try {
2766
+ this.store.enforceRetention();
2767
+ } catch (error) {
2768
+ this.log(`retention failed: ${String(error)}`);
2769
+ }
2770
+ }, intervalMs);
2771
+ this.retentionTimer.unref?.();
2772
+ }
2773
+ getCurrentData() {
2774
+ return {
2775
+ traces: this.traces,
2776
+ logs: this.logs,
2777
+ errors: this.errorAggregator.getErrorGroups(),
2778
+ agents: [...this.agentSessions.values()]
2779
+ };
2780
+ }
2781
+ clearData() {
2782
+ this.traces = [];
2783
+ this.logs = [];
2784
+ this.agentSessions.clear();
2785
+ this.errorAggregator.clear();
2786
+ this.store.clear();
2787
+ }
2788
+ clearSignal(signal) {
2789
+ this.store.clearSignal(signal);
2790
+ if (signal === "traces") {
2791
+ this.traces = [];
2792
+ this.errorAggregator.clear();
2793
+ } else if (signal === "logs") this.logs = [];
2794
+ }
2795
+ deleteMetric(name) {
2796
+ return this.store.deleteMetric(name);
2797
+ }
2798
+ deleteTraces(traceIds) {
2799
+ const ids = new Set(traceIds);
2800
+ this.traces = this.traces.filter((trace) => !ids.has(trace.traceId));
2801
+ const deleted = this.store.deleteTraces(traceIds);
2802
+ this.errorAggregator.clear();
2803
+ let cursor;
2804
+ do {
2805
+ const page = this.store.queryTraces({
2806
+ query: "",
2807
+ limit: 1e3,
2808
+ cursor
2809
+ });
2810
+ for (const trace of page.traces) this.errorAggregator.addErrorsFromTrace(trace);
2811
+ cursor = page.nextCursor ?? void 0;
2812
+ } while (cursor);
2813
+ return deleted;
2814
+ }
2815
+ broadcast(data) {
2816
+ const msg = JSON.stringify(data.traces?.length ? {
2817
+ ...data,
2818
+ traces: encodeTraces(data.traces)
2819
+ } : data);
2820
+ for (const client of this.clients) if (client.readyState === WebSocket.OPEN) client.send(msg);
2821
+ if (this.onData) try {
2822
+ this.onData(data);
2823
+ } catch {}
2824
+ }
2825
+ log(message) {
2826
+ if (this.verbose) console.log(`[autotel-devtools] ${message}`);
2827
+ }
2828
+ async close() {
2829
+ if (this.retentionTimer) {
2830
+ clearInterval(this.retentionTimer);
2831
+ this.retentionTimer = null;
2832
+ }
2833
+ for (const client of this.clients) client.close();
2834
+ this.clients.clear();
2835
+ this.wss.close();
2836
+ await new Promise((resolve) => this.httpServer.close(() => resolve()));
2837
+ this.store.close();
2838
+ }
2839
+ };
2840
+
2841
+ //#endregion
2842
+ //#region src/server/otlp-proto.ts
2843
+ const COMMON_PROTO = `
2844
+ syntax = "proto3";
2845
+ package opentelemetry.proto.common.v1;
2846
+
2847
+ message AnyValue {
2848
+ oneof value {
2849
+ string string_value = 1;
2850
+ bool bool_value = 2;
2851
+ int64 int_value = 3;
2852
+ double double_value = 4;
2853
+ ArrayValue array_value = 5;
2854
+ KeyValueList kvlist_value = 6;
2855
+ bytes bytes_value = 7;
2856
+ }
2857
+ }
2858
+ message ArrayValue { repeated AnyValue values = 1; }
2859
+ message KeyValueList { repeated KeyValue values = 1; }
2860
+ message KeyValue {
2861
+ string key = 1;
2862
+ AnyValue value = 2;
2863
+ }
2864
+ message InstrumentationScope {
2865
+ string name = 1;
2866
+ string version = 2;
2867
+ repeated KeyValue attributes = 3;
2868
+ uint32 dropped_attributes_count = 4;
2869
+ }
2870
+ `;
2871
+ const RESOURCE_PROTO = `
2872
+ syntax = "proto3";
2873
+ package opentelemetry.proto.resource.v1;
2874
+
2875
+ message Resource {
2876
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 1;
2877
+ uint32 dropped_attributes_count = 2;
2878
+ }
2879
+ `;
2880
+ const TRACE_PROTO = `
2881
+ syntax = "proto3";
2882
+ package opentelemetry.proto.trace.v1;
2883
+
2884
+ message ResourceSpans {
2885
+ opentelemetry.proto.resource.v1.Resource resource = 1;
2886
+ repeated ScopeSpans scope_spans = 2;
2887
+ string schema_url = 3;
2888
+ }
2889
+ message ScopeSpans {
2890
+ opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
2891
+ repeated Span spans = 2;
2892
+ string schema_url = 3;
2893
+ }
2894
+ message Span {
2895
+ bytes trace_id = 1;
2896
+ bytes span_id = 2;
2897
+ string trace_state = 3;
2898
+ bytes parent_span_id = 4;
2899
+ fixed32 flags = 16;
2900
+ string name = 5;
2901
+ SpanKind kind = 6;
2902
+ fixed64 start_time_unix_nano = 7;
2903
+ fixed64 end_time_unix_nano = 8;
2904
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 9;
2905
+ uint32 dropped_attributes_count = 10;
2906
+ repeated Event events = 11;
2907
+ uint32 dropped_events_count = 12;
2908
+ repeated Link links = 13;
2909
+ uint32 dropped_links_count = 14;
2910
+ Status status = 15;
2911
+
2912
+ enum SpanKind {
2913
+ SPAN_KIND_UNSPECIFIED = 0;
2914
+ SPAN_KIND_INTERNAL = 1;
2915
+ SPAN_KIND_SERVER = 2;
2916
+ SPAN_KIND_CLIENT = 3;
2917
+ SPAN_KIND_PRODUCER = 4;
2918
+ SPAN_KIND_CONSUMER = 5;
2919
+ }
2920
+ message Event {
2921
+ fixed64 time_unix_nano = 1;
2922
+ string name = 2;
2923
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 3;
2924
+ uint32 dropped_attributes_count = 4;
2925
+ }
2926
+ message Link {
2927
+ bytes trace_id = 1;
2928
+ bytes span_id = 2;
2929
+ string trace_state = 3;
2930
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 4;
2931
+ uint32 dropped_attributes_count = 5;
2932
+ fixed32 flags = 6;
2933
+ }
2934
+ }
2935
+ message Status {
2936
+ reserved 1;
2937
+ string message = 2;
2938
+ StatusCode code = 3;
2939
+
2940
+ enum StatusCode {
2941
+ STATUS_CODE_UNSET = 0;
2942
+ STATUS_CODE_OK = 1;
2943
+ STATUS_CODE_ERROR = 2;
2944
+ }
2945
+ }
2946
+ message ExportTraceServiceRequest {
2947
+ repeated ResourceSpans resource_spans = 1;
2948
+ }
2949
+ `;
2950
+ const LOGS_PROTO = `
2951
+ syntax = "proto3";
2952
+ package opentelemetry.proto.logs.v1;
2953
+
2954
+ enum SeverityNumber {
2955
+ SEVERITY_NUMBER_UNSPECIFIED = 0;
2956
+ SEVERITY_NUMBER_TRACE = 1;
2957
+ SEVERITY_NUMBER_TRACE2 = 2;
2958
+ SEVERITY_NUMBER_TRACE3 = 3;
2959
+ SEVERITY_NUMBER_TRACE4 = 4;
2960
+ SEVERITY_NUMBER_DEBUG = 5;
2961
+ SEVERITY_NUMBER_DEBUG2 = 6;
2962
+ SEVERITY_NUMBER_DEBUG3 = 7;
2963
+ SEVERITY_NUMBER_DEBUG4 = 8;
2964
+ SEVERITY_NUMBER_INFO = 9;
2965
+ SEVERITY_NUMBER_INFO2 = 10;
2966
+ SEVERITY_NUMBER_INFO3 = 11;
2967
+ SEVERITY_NUMBER_INFO4 = 12;
2968
+ SEVERITY_NUMBER_WARN = 13;
2969
+ SEVERITY_NUMBER_WARN2 = 14;
2970
+ SEVERITY_NUMBER_WARN3 = 15;
2971
+ SEVERITY_NUMBER_WARN4 = 16;
2972
+ SEVERITY_NUMBER_ERROR = 17;
2973
+ SEVERITY_NUMBER_ERROR2 = 18;
2974
+ SEVERITY_NUMBER_ERROR3 = 19;
2975
+ SEVERITY_NUMBER_ERROR4 = 20;
2976
+ SEVERITY_NUMBER_FATAL = 21;
2977
+ SEVERITY_NUMBER_FATAL2 = 22;
2978
+ SEVERITY_NUMBER_FATAL3 = 23;
2979
+ SEVERITY_NUMBER_FATAL4 = 24;
2980
+ }
2981
+ message ResourceLogs {
2982
+ opentelemetry.proto.resource.v1.Resource resource = 1;
2983
+ repeated ScopeLogs scope_logs = 2;
2984
+ string schema_url = 3;
2985
+ }
2986
+ message ScopeLogs {
2987
+ opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
2988
+ repeated LogRecord log_records = 2;
2989
+ string schema_url = 3;
2990
+ }
2991
+ message LogRecord {
2992
+ reserved 4;
2993
+ fixed64 time_unix_nano = 1;
2994
+ fixed64 observed_time_unix_nano = 11;
2995
+ SeverityNumber severity_number = 2;
2996
+ string severity_text = 3;
2997
+ opentelemetry.proto.common.v1.AnyValue body = 5;
2998
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 6;
2999
+ uint32 dropped_attributes_count = 7;
3000
+ fixed32 flags = 8;
3001
+ bytes trace_id = 9;
3002
+ bytes span_id = 10;
3003
+ }
3004
+ message ExportLogsServiceRequest {
3005
+ repeated ResourceLogs resource_logs = 1;
3006
+ }
3007
+ `;
3008
+ const METRICS_PROTO = `
3009
+ syntax = "proto3";
3010
+ package opentelemetry.proto.metrics.v1;
3011
+
3012
+ enum AggregationTemporality {
3013
+ AGGREGATION_TEMPORALITY_UNSPECIFIED = 0;
3014
+ AGGREGATION_TEMPORALITY_DELTA = 1;
3015
+ AGGREGATION_TEMPORALITY_CUMULATIVE = 2;
3016
+ }
3017
+ message ResourceMetrics {
3018
+ opentelemetry.proto.resource.v1.Resource resource = 1;
3019
+ repeated ScopeMetrics scope_metrics = 2;
3020
+ string schema_url = 3;
3021
+ }
3022
+ message ScopeMetrics {
3023
+ opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
3024
+ repeated Metric metrics = 2;
3025
+ string schema_url = 3;
3026
+ }
3027
+ message Metric {
3028
+ string name = 1;
3029
+ string description = 2;
3030
+ string unit = 3;
3031
+ oneof data {
3032
+ Gauge gauge = 5;
3033
+ Sum sum = 7;
3034
+ Histogram histogram = 9;
3035
+ ExponentialHistogram exponential_histogram = 10;
3036
+ Summary summary = 11;
3037
+ }
3038
+ }
3039
+ message Gauge {
3040
+ repeated NumberDataPoint data_points = 1;
3041
+ }
3042
+ message Sum {
3043
+ repeated NumberDataPoint data_points = 1;
3044
+ AggregationTemporality aggregation_temporality = 2;
3045
+ bool is_monotonic = 3;
3046
+ }
3047
+ message Histogram {
3048
+ repeated HistogramDataPoint data_points = 1;
3049
+ AggregationTemporality aggregation_temporality = 2;
3050
+ }
3051
+ message ExponentialHistogram {
3052
+ repeated ExponentialHistogramDataPoint data_points = 1;
3053
+ AggregationTemporality aggregation_temporality = 2;
3054
+ }
3055
+ message Summary {
3056
+ repeated SummaryDataPoint data_points = 1;
3057
+ }
3058
+ message NumberDataPoint {
3059
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 7;
3060
+ fixed64 start_time_unix_nano = 2;
3061
+ fixed64 time_unix_nano = 3;
3062
+ oneof value {
3063
+ double as_double = 4;
3064
+ sfixed64 as_int = 6;
3065
+ }
3066
+ repeated Exemplar exemplars = 5;
3067
+ uint32 flags = 8;
3068
+ }
3069
+ message HistogramDataPoint {
3070
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 9;
3071
+ fixed64 start_time_unix_nano = 2;
3072
+ fixed64 time_unix_nano = 3;
3073
+ uint64 count = 4;
3074
+ double sum = 5;
3075
+ repeated uint64 bucket_counts = 6;
3076
+ repeated double explicit_bounds = 7;
3077
+ repeated Exemplar exemplars = 8;
3078
+ uint32 flags = 10;
3079
+ double min = 11;
3080
+ double max = 12;
3081
+ }
3082
+ message ExponentialHistogramDataPoint {
3083
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 1;
3084
+ fixed64 start_time_unix_nano = 2;
3085
+ fixed64 time_unix_nano = 3;
3086
+ uint64 count = 4;
3087
+ double sum = 5;
3088
+ sint32 scale = 6;
3089
+ uint64 zero_count = 7;
3090
+ Buckets positive = 8;
3091
+ Buckets negative = 9;
3092
+ uint32 flags = 10;
3093
+ repeated Exemplar exemplars = 11;
3094
+ double min = 12;
3095
+ double max = 13;
3096
+ double zero_threshold = 14;
3097
+
3098
+ message Buckets {
3099
+ sint32 offset = 1;
3100
+ repeated uint64 bucket_counts = 2;
3101
+ }
3102
+ }
3103
+ message SummaryDataPoint {
3104
+ repeated opentelemetry.proto.common.v1.KeyValue attributes = 7;
3105
+ fixed64 start_time_unix_nano = 2;
3106
+ fixed64 time_unix_nano = 3;
3107
+ uint64 count = 4;
3108
+ double sum = 5;
3109
+ repeated ValueAtQuantile quantile_values = 6;
3110
+ uint32 flags = 8;
3111
+
3112
+ message ValueAtQuantile {
3113
+ double quantile = 1;
3114
+ double value = 2;
3115
+ }
3116
+ }
3117
+ message Exemplar {
3118
+ repeated opentelemetry.proto.common.v1.KeyValue filtered_attributes = 7;
3119
+ fixed64 time_unix_nano = 2;
3120
+ oneof value {
3121
+ double as_double = 3;
3122
+ sfixed64 as_int = 6;
3123
+ }
3124
+ bytes span_id = 4;
3125
+ bytes trace_id = 5;
3126
+ }
3127
+ message ExportMetricsServiceRequest {
3128
+ repeated ResourceMetrics resource_metrics = 1;
3129
+ }
3130
+ `;
3131
+ const TO_OBJECT_OPTIONS = {
3132
+ longs: String,
3133
+ bytes: String,
3134
+ defaults: false
3135
+ };
3136
+ let cachedRoot = null;
3137
+ function getRoot() {
3138
+ if (cachedRoot) return cachedRoot;
3139
+ const root = new protobuf.Root();
3140
+ for (const source of [
3141
+ COMMON_PROTO,
3142
+ RESOURCE_PROTO,
3143
+ TRACE_PROTO,
3144
+ LOGS_PROTO,
3145
+ METRICS_PROTO
3146
+ ]) protobuf.parse(source, root, { keepCase: false });
3147
+ root.resolveAll();
3148
+ cachedRoot = root;
3149
+ return root;
3150
+ }
3151
+ function decodeRequest(typeName, body) {
3152
+ const messageType = getRoot().lookupType(typeName);
3153
+ const message = messageType.decode(body);
3154
+ return messageType.toObject(message, TO_OBJECT_OPTIONS);
3155
+ }
3156
+ /** Decode an OTLP/protobuf `ExportTraceServiceRequest` into the OTLP/JSON object shape. */
3157
+ function decodeOtlpTraceRequest(body) {
3158
+ return decodeRequest("opentelemetry.proto.trace.v1.ExportTraceServiceRequest", body);
3159
+ }
3160
+ /** Decode an OTLP/protobuf `ExportLogsServiceRequest` into the OTLP/JSON object shape. */
3161
+ function decodeOtlpLogsRequest(body) {
3162
+ return decodeRequest("opentelemetry.proto.logs.v1.ExportLogsServiceRequest", body);
3163
+ }
3164
+ /** Decode an OTLP/protobuf `ExportMetricsServiceRequest` into the OTLP/JSON object shape. */
3165
+ function decodeOtlpMetricsRequest(body) {
3166
+ return decodeRequest("opentelemetry.proto.metrics.v1.ExportMetricsServiceRequest", body);
3167
+ }
3168
+
3169
+ //#endregion
3170
+ //#region src/server/identity.ts
3171
+ /** Value of the `x-autotel-devtools` response header and the /healthz `service` field. */
3172
+ const DEVTOOLS_IDENTITY = "autotel-devtools";
3173
+ /**
3174
+ * Probe `host:port` over HTTP and classify what is listening. Used when our
3175
+ * requested port is busy: it lets us tell "a stale autotel-devtools is still
3176
+ * up" (benign) apart from "a foreign collector owns this port" — the latter is
3177
+ * the silent footgun where apps keep exporting OTLP to the busy port and reach
3178
+ * the wrong process, so the devtools UI stays empty and the app sees errors.
3179
+ */
3180
+ async function probePortHolder(host, port, timeoutMs = 500) {
3181
+ const authority = host.includes(":") ? `[${host}]` : host;
3182
+ const controller = new AbortController();
3183
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
3184
+ try {
3185
+ const res = await fetch(`http://${authority}:${port}/healthz`, { signal: controller.signal });
3186
+ if (res.headers.get("x-autotel-devtools")) return "autotel-devtools";
3187
+ try {
3188
+ const body = await res.json();
3189
+ if (body && body.service === "autotel-devtools") return "autotel-devtools";
3190
+ } catch {}
3191
+ return "foreign";
3192
+ } catch {
3193
+ return "none";
3194
+ } finally {
3195
+ clearTimeout(timer);
3196
+ }
3197
+ }
3198
+
3199
+ //#endregion
3200
+ //#region src/server/source-file.ts
3201
+ /** Refuse to slurp something huge just because a span named it. */
3202
+ const MAX_BYTES = 2e6;
3203
+ const DISABLED = /* @__PURE__ */ new Set([
3204
+ "false",
3205
+ "0",
3206
+ "off",
3207
+ "no",
3208
+ ""
3209
+ ]);
3210
+ /**
3211
+ * Decide what `GET /source` may read, from `AUTOTEL_DEVTOOLS_SOURCE_ROOT`.
3212
+ *
3213
+ * Defaults **on**, at the working directory: devtools is a local tool whose
3214
+ * whole point is showing you your own code, and requiring a flag for that would
3215
+ * mean nobody ever sees the feature. The blast radius stays small because two
3216
+ * other things still hold — the receiver is bound to loopback, and nothing
3217
+ * outside this directory is reachable. Set the variable to `false` to turn it
3218
+ * off outright.
3219
+ *
3220
+ * A non-loopback bind (`--host 0.0.0.0`) removes the first of those, and the
3221
+ * Origin guard does not replace it: a request with no `Origin` at all — any
3222
+ * `curl` on the network — passes. The root holds whatever else lives in the
3223
+ * project, `.env` included, so the default flips to **off** there. An explicit
3224
+ * root is still honoured: exposing it on purpose is the caller's call.
3225
+ */
3226
+ function resolveSourceRoot(configured, cwd, loopbackOnly = true) {
3227
+ if (configured === void 0) return loopbackOnly ? cwd : void 0;
3228
+ if (DISABLED.has(configured.trim().toLowerCase())) return void 0;
3229
+ return configured;
3230
+ }
3231
+ /**
3232
+ * Resolve `requested` against `root`, or return `null` if it escapes.
3233
+ *
3234
+ * Containment is judged on **real** paths so a symlink inside the root that
3235
+ * points outside it is rejected — lexical `..` stripping alone cannot see that.
3236
+ * The value returned is the *lexical* resolution, because the real one differs
3237
+ * from the caller's path whenever an ancestor is a symlink (on macOS both
3238
+ * `/tmp` and `/var` are), and a caller comparing paths should not have to know.
3239
+ */
3240
+ function resolveWithinRoot(root, requested) {
3241
+ const lexicalRoot = path.resolve(root);
3242
+ const realRoot = safeRealpath(lexicalRoot);
3243
+ if (realRoot === null) return null;
3244
+ const lexicalTarget = path.resolve(lexicalRoot, requested);
3245
+ const realTarget = safeRealpath(lexicalTarget);
3246
+ if (realTarget === null) return null;
3247
+ if (!isInside(realRoot, realTarget)) return null;
3248
+ return lexicalTarget;
3249
+ }
3250
+ /** True when `target` is `root` itself or sits beneath it. */
3251
+ function isInside(root, target) {
3252
+ if (target === root) return true;
3253
+ return target.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
3254
+ }
3255
+ function safeRealpath(p) {
3256
+ try {
3257
+ return realpathSync(p);
3258
+ } catch {
3259
+ return null;
3260
+ }
3261
+ }
3262
+ /**
3263
+ * Read `context` lines either side of `line` from a file inside `root`.
3264
+ * Returns `null` when the path escapes the root, is not a readable file, or is
3265
+ * too large — the caller cannot distinguish those, which is the point.
3266
+ */
3267
+ function readSourceWindow(root, requested, line, context) {
3268
+ const resolved = resolveWithinRoot(root, requested);
3269
+ if (resolved === null) return null;
3270
+ let text;
3271
+ try {
3272
+ const stat = statSync(resolved);
3273
+ if (!stat.isFile() || stat.size > MAX_BYTES) return null;
3274
+ text = readFileSync(resolved, "utf8");
3275
+ } catch {
3276
+ return null;
3277
+ }
3278
+ const all = text.split("\n");
3279
+ if (all.at(-1) === "") all.pop();
3280
+ const startLine = Math.max(1, line - context);
3281
+ const endLine = Math.min(all.length, line + context);
3282
+ if (startLine > all.length) return null;
3283
+ return {
3284
+ file: path.relative(path.resolve(root), resolved),
3285
+ line,
3286
+ startLine,
3287
+ lines: all.slice(startLine - 1, endLine)
3288
+ };
3289
+ }
3290
+
3291
+ //#endregion
3292
+ //#region src/server/coverage/coverage.ts
3293
+ /**
3294
+ * The names a span could plausibly carry for this route.
3295
+ *
3296
+ * `http.route` is the semconv attribute a framework integration sets. The span
3297
+ * *name* is the other route in, and for an HTTP handler the convention is
3298
+ * `"{method} {route}"`, which is what `trace()` and every framework middleware
3299
+ * produce. A non-HTTP entry point has no method, so its own name is the only
3300
+ * thing to match.
3301
+ */
3302
+ function candidateNames(route) {
3303
+ if (!route.method) return [route.path];
3304
+ return [`${route.method.toUpperCase()} ${route.path}`];
3305
+ }
3306
+ function joinCoverage(routes, observed) {
3307
+ const entries = routes.map((route) => {
3308
+ const byRoute = route.method ? 0 : observed.routeCounts[route.path] ?? 0;
3309
+ const byRouteAny = observed.routeCounts[route.path] ?? 0;
3310
+ const byName = candidateNames(route).reduce((total, name) => total + (observed.spanNameCounts[name] ?? 0), 0);
3311
+ const namedAnyMethod = Object.keys(observed.spanNameCounts).some((name) => name.endsWith(` ${route.path}`));
3312
+ const spanCount = byName > 0 ? byName : namedAnyMethod ? 0 : byRoute || byRouteAny;
3313
+ return {
3314
+ ...route,
3315
+ seen: spanCount > 0,
3316
+ spanCount
3317
+ };
3318
+ });
3319
+ entries.sort((left, right) => Number(left.seen) - Number(right.seen));
3320
+ return {
3321
+ entries,
3322
+ seenCount: entries.filter((entry) => entry.seen).length,
3323
+ total: entries.length
3324
+ };
3325
+ }
3326
+
3327
+ //#endregion
3328
+ //#region src/server/http.ts
3329
+ function sendOtlpError(res, req, e) {
3330
+ sendJson(res, 400, {
3331
+ error: "Invalid OTLP payload",
3332
+ message: e instanceof Error ? e.message : String(e),
3333
+ contentType: req.headers["content-type"] ?? null
3334
+ });
3335
+ }
3336
+ const PROTOBUF_DECODERS = {
3337
+ traces: decodeOtlpTraceRequest,
3338
+ logs: decodeOtlpLogsRequest,
3339
+ metrics: decodeOtlpMetricsRequest
3340
+ };
3341
+ async function readOtlpPayload(req, signal) {
3342
+ if (isProtobufContentType(req.headers["content-type"])) return PROTOBUF_DECODERS[signal](await readRawBody(req));
3343
+ return readJsonBody(req);
3344
+ }
3345
+ function findPackageRoot() {
3346
+ let dir = dirname(fileURLToPath(import.meta.url));
3347
+ for (let i = 0; i < 5; i++) {
3348
+ if (existsSync(resolve(dir, "package.json"))) return dir;
3349
+ dir = dirname(dir);
3350
+ }
3351
+ return dir;
3352
+ }
3353
+ const DEVTOOLS_FAVICON_SVG = "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 64 64\"><rect width=\"64\" height=\"64\" rx=\"14\" fill=\"#0f172a\"/><text x=\"32\" y=\"41\" text-anchor=\"middle\" font-size=\"32\">🛰️</text></svg>";
3354
+ /**
3355
+ * The title is user-supplied (`--title` / `AUTOTEL_DEVTOOLS_TITLE`) and lands
3356
+ * inside `<title>`, where an unescaped `<` would close the element early.
3357
+ */
3358
+ function escapeHtml(value) {
3359
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
3360
+ }
3361
+ function renderFullpageHtml(title = "autotel-devtools") {
3362
+ return `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>${escapeHtml(title)}</title><link rel="icon" href="/favicon.svg" type="image/svg+xml"><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%;width:100%;overflow:hidden}</style></head><body><script src="/widget.js?mode=fullpage"><\/script></body></html>`;
3363
+ }
3364
+ let cachedVersion = null;
3365
+ function getVersion() {
3366
+ if (cachedVersion !== null) return cachedVersion;
3367
+ let version = "unknown";
3368
+ try {
3369
+ const pkg = JSON.parse(readFileSync(resolve(findPackageRoot(), "package.json"), "utf8"));
3370
+ if (typeof pkg.version === "string") version = pkg.version;
3371
+ } catch {}
3372
+ cachedVersion = version;
3373
+ return version;
3374
+ }
3375
+ const widgetJsCache = /* @__PURE__ */ new Map();
3376
+ /**
3377
+ * The browser bundle for one surface.
3378
+ *
3379
+ * Two are built: `fullpage.global.js` carries every view, while
3380
+ * `widget.global.js` is the reduced set for embedding in someone else's page.
3381
+ * Serving the right one is what makes the split worth anything — handing the
3382
+ * full bundle to an embedder would ship them the views the split exists to
3383
+ * spare them.
3384
+ *
3385
+ * The full-page bundle falls back to the widget one when it is missing, so a
3386
+ * partially-built checkout still serves a working UI rather than a comment.
3387
+ */
3388
+ function getWidgetJs(surface) {
3389
+ const cached = widgetJsCache.get(surface);
3390
+ if (cached) return cached;
3391
+ const pkgRoot = findPackageRoot();
3392
+ const candidates = (surface === "fullpage" ? ["fullpage.global.js", "widget.global.js"] : ["widget.global.js"]).flatMap((name) => [resolve(pkgRoot, "dist", name), resolve(pkgRoot, name)]);
3393
+ let contents = null;
3394
+ for (const candidate of candidates) try {
3395
+ contents = readFileSync(candidate, "utf8");
3396
+ break;
3397
+ } catch {}
3398
+ const resolved = contents ?? "// widget bundle not found - run pnpm build first";
3399
+ widgetJsCache.set(surface, resolved);
3400
+ return resolved;
3401
+ }
3402
+ function attachDevtoolsRoutes(httpServer, devtools, options = {}) {
3403
+ const loopbackOnly = options.loopbackOnly ?? true;
3404
+ const sourceRoot = options.sourceRoot;
3405
+ const fullpageHtml = renderFullpageHtml(options.title);
3406
+ httpServer.on("request", async (req, res) => {
3407
+ if (req.headers.upgrade?.toLowerCase() === "websocket") return;
3408
+ res.setHeader("Access-Control-Allow-Origin", "*");
3409
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
3410
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
3411
+ res.setHeader("x-autotel-devtools", getVersion());
3412
+ res.setHeader("Access-Control-Expose-Headers", "x-autotel-devtools");
3413
+ if (req.method === "OPTIONS") {
3414
+ res.writeHead(204);
3415
+ res.end();
3416
+ return;
3417
+ }
3418
+ const url = req.url || "/";
3419
+ if (req.method === "GET" && url === "/") {
3420
+ res.writeHead(200, {
3421
+ "Content-Type": "text/html; charset=utf-8",
3422
+ "Content-Length": Buffer.byteLength(fullpageHtml)
3423
+ });
3424
+ res.end(fullpageHtml);
3425
+ return;
3426
+ }
3427
+ if (req.method === "GET" && url.startsWith("/widget.js")) {
3428
+ const js = getWidgetJs(url.includes("mode=fullpage") ? "fullpage" : "widget");
3429
+ res.writeHead(200, {
3430
+ "Content-Type": "application/javascript; charset=utf-8",
3431
+ "Content-Length": Buffer.byteLength(js)
3432
+ });
3433
+ res.end(js);
3434
+ return;
3435
+ }
3436
+ if (req.method === "GET" && (url === "/favicon.svg" || url === "/favicon.ico")) {
3437
+ res.writeHead(200, {
3438
+ "Content-Type": "image/svg+xml; charset=utf-8",
3439
+ "Cache-Control": "public, max-age=86400",
3440
+ "Content-Length": Buffer.byteLength(DEVTOOLS_FAVICON_SVG)
3441
+ });
3442
+ res.end(DEVTOOLS_FAVICON_SVG);
3443
+ return;
3444
+ }
3445
+ if (req.method === "GET" && url.split("?")[0] === "/api/query/attributes") {
3446
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3447
+ sendJson(res, 403, { error: "Forbidden" });
3448
+ return;
3449
+ }
3450
+ const params = new URL(url, "http://localhost").searchParams;
3451
+ const signal = params.get("signal") === "logs" ? "logs" : "traces";
3452
+ const key = params.get("key");
3453
+ const pair = params.get("pair");
3454
+ if (key !== null && pair !== null) {
3455
+ sendJson(res, 200, { pairs: devtools.pairedAttributeValues(signal, key, pair) });
3456
+ return;
3457
+ }
3458
+ sendJson(res, 200, { attributes: devtools.searchAttributes(signal, params.get("value") ?? "") });
3459
+ return;
3460
+ }
3461
+ if (req.method === "GET" && url.split("?")[0] === "/source") {
3462
+ if (!sourceRoot) {
3463
+ sendJson(res, 404, { error: "Not found" });
3464
+ return;
3465
+ }
3466
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3467
+ sendJson(res, 403, { error: "Forbidden" });
3468
+ return;
3469
+ }
3470
+ const query = new URL(url, "http://localhost").searchParams;
3471
+ const file = query.get("file");
3472
+ const line = Number(query.get("line"));
3473
+ const context = Math.min(Math.max(Number(query.get("context") ?? 5) || 0, 0), 50);
3474
+ if (!file || !Number.isInteger(line) || line < 1) {
3475
+ sendJson(res, 400, { error: "file and a positive integer line are required" });
3476
+ return;
3477
+ }
3478
+ const window = readSourceWindow(sourceRoot, file, line, context);
3479
+ if (window === null) {
3480
+ sendJson(res, 404, { error: "Not found" });
3481
+ return;
3482
+ }
3483
+ sendJson(res, 200, { ...window });
3484
+ return;
3485
+ }
3486
+ if (req.method === "GET" && url === "/healthz") {
3487
+ sendJson(res, 200, {
3488
+ ok: true,
3489
+ service: DEVTOOLS_IDENTITY,
3490
+ version: getVersion(),
3491
+ clients: devtools.clientCount
3492
+ });
3493
+ return;
3494
+ }
3495
+ if (req.method === "GET" && url === "/v1/traces") {
3496
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3497
+ sendJson(res, 403, { error: "Forbidden" });
3498
+ return;
3499
+ }
3500
+ const data = devtools.getCurrentData();
3501
+ sendJson(res, 200, {
3502
+ traces: data.traces,
3503
+ count: data.traces.length
3504
+ });
3505
+ return;
3506
+ }
3507
+ if (req.method === "DELETE" && url === "/v1/traces") {
3508
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3509
+ sendJson(res, 403, { error: "Forbidden" });
3510
+ return;
3511
+ }
3512
+ devtools.clearData();
3513
+ sendJson(res, 200, { cleared: true });
3514
+ return;
3515
+ }
3516
+ if (req.method === "DELETE" && (url === "/v1/logs" || url === "/v1/metrics")) {
3517
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3518
+ sendJson(res, 403, { error: "Forbidden" });
3519
+ return;
3520
+ }
3521
+ const signal = url.endsWith("/logs") ? "logs" : "metrics";
3522
+ devtools.clearSignal(signal);
3523
+ sendJson(res, 200, {
3524
+ cleared: true,
3525
+ signal
3526
+ });
3527
+ return;
3528
+ }
3529
+ if (req.method === "DELETE" && url === "/api/traces") {
3530
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3531
+ sendJson(res, 403, { error: "Forbidden" });
3532
+ return;
3533
+ }
3534
+ const body = await readJsonBody(req);
3535
+ const traceIds = Array.isArray(body.traceIds) ? body.traceIds.filter((id) => typeof id === "string") : [];
3536
+ sendJson(res, 200, { deleted: devtools.deleteTraces(traceIds) });
3537
+ return;
3538
+ }
3539
+ if (req.method === "POST" && url === "/v1/traces") {
3540
+ try {
3541
+ const payload = await readOtlpPayload(req, "traces");
3542
+ sendJson(res, 200, { acceptedTraces: devtools.ingestOtlp("traces", payload) });
3543
+ } catch (e) {
3544
+ sendOtlpError(res, req, e);
3545
+ }
3546
+ return;
3547
+ }
3548
+ if (req.method === "POST" && url === "/v1/logs") {
3549
+ try {
3550
+ const payload = await readOtlpPayload(req, "logs");
3551
+ sendJson(res, 200, { acceptedLogs: devtools.ingestOtlp("logs", payload) });
3552
+ } catch (e) {
3553
+ sendOtlpError(res, req, e);
3554
+ }
3555
+ return;
3556
+ }
3557
+ if (req.method === "POST" && url === "/v1/metrics") {
3558
+ try {
3559
+ const payload = await readOtlpPayload(req, "metrics");
3560
+ sendJson(res, 200, { acceptedMetrics: devtools.ingestOtlp("metrics", payload) });
3561
+ } catch (e) {
3562
+ sendOtlpError(res, req, e);
3563
+ }
3564
+ return;
3565
+ }
3566
+ if (req.method === "GET" && (url === "/api/query/traces/fields" || url === "/api/query/logs/fields")) {
3567
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3568
+ sendJson(res, 403, { error: "Forbidden" });
3569
+ return;
3570
+ }
3571
+ const signal = url.includes("/logs/") ? "logs" : "traces";
3572
+ sendJson(res, 200, { fields: devtools.listQueryFields(signal) });
3573
+ return;
3574
+ }
3575
+ if (req.method === "POST" && url === "/api/query/traces") {
3576
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3577
+ sendJson(res, 403, { error: "Forbidden" });
3578
+ return;
3579
+ }
3580
+ try {
3581
+ const body = await readJsonBody(req);
3582
+ const result = devtools.queryTraces({
3583
+ query: body.query ?? "",
3584
+ window: body.window,
3585
+ limit: body.limit,
3586
+ cursor: body.cursor
3587
+ });
3588
+ if (result.errors) {
3589
+ sendJson(res, 400, { errors: result.errors });
3590
+ return;
3591
+ }
3592
+ sendJson(res, 200, {
3593
+ traces: result.traces,
3594
+ nextCursor: result.nextCursor
3595
+ });
3596
+ } catch (e) {
3597
+ sendJson(res, 400, {
3598
+ error: "Invalid query request",
3599
+ message: e instanceof Error ? e.message : String(e)
3600
+ });
3601
+ }
3602
+ return;
3603
+ }
3604
+ if (req.method === "GET" && url === "/api/coverage") {
3605
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3606
+ sendJson(res, 403, { error: "Forbidden" });
3607
+ return;
3608
+ }
3609
+ if (!sourceRoot) {
3610
+ sendJson(res, 404, {
3611
+ error: "Coverage unavailable",
3612
+ message: "No source root configured, so `autotel.map.json` cannot be located."
3613
+ });
3614
+ return;
3615
+ }
3616
+ const mapPath = resolve(sourceRoot, "autotel.map.json");
3617
+ if (!existsSync(mapPath)) {
3618
+ sendJson(res, 404, {
3619
+ error: "No instrumentation map",
3620
+ message: "Run `npx autotel map` to record this project's entry points, then reload."
3621
+ });
3622
+ return;
3623
+ }
3624
+ try {
3625
+ sendJson(res, 200, joinCoverage(JSON.parse(readFileSync(mapPath, "utf8")).routes ?? [], devtools.observedSpans()));
3626
+ } catch (e) {
3627
+ sendJson(res, 400, {
3628
+ error: "Unreadable instrumentation map",
3629
+ message: e instanceof Error ? e.message : String(e)
3630
+ });
3631
+ }
3632
+ return;
3633
+ }
3634
+ if (req.method === "POST" && url === "/api/analysis/compare") {
3635
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3636
+ sendJson(res, 403, { error: "Forbidden" });
3637
+ return;
3638
+ }
3639
+ let compareCohorts;
3640
+ try {
3641
+ ({compareCohorts} = await import("autotel/analysis"));
3642
+ } catch {
3643
+ sendJson(res, 501, {
3644
+ error: "Comparison unavailable",
3645
+ message: "Install `autotel` alongside autotel-devtools to compare cohorts."
3646
+ });
3647
+ return;
3648
+ }
3649
+ try {
3650
+ const body = await readJsonBody(req);
3651
+ const outlier = devtools.cohortRows({
3652
+ query: body.outlier?.query ?? "",
3653
+ window: body.outlier?.window
3654
+ });
3655
+ const baseline = devtools.cohortRows({
3656
+ query: body.baseline?.query ?? "",
3657
+ window: body.baseline?.window
3658
+ });
3659
+ sendJson(res, 200, {
3660
+ differences: compareCohorts({
3661
+ outlier,
3662
+ baseline,
3663
+ ignoreFields: body.ignoreFields,
3664
+ limit: body.limit
3665
+ }),
3666
+ outlierCount: outlier.length,
3667
+ baselineCount: baseline.length
3668
+ });
3669
+ } catch (e) {
3670
+ sendJson(res, 400, {
3671
+ error: "Invalid comparison request",
3672
+ message: e instanceof Error ? e.message : String(e)
3673
+ });
3674
+ }
3675
+ return;
3676
+ }
3677
+ if (req.method === "POST" && url === "/api/query/logs") {
3678
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3679
+ sendJson(res, 403, { error: "Forbidden" });
3680
+ return;
3681
+ }
3682
+ try {
3683
+ const body = await readJsonBody(req);
3684
+ const result = devtools.queryLogs({
3685
+ query: body.query ?? "",
3686
+ window: body.window,
3687
+ limit: body.limit,
3688
+ cursor: body.cursor
3689
+ });
3690
+ if (result.errors) {
3691
+ sendJson(res, 400, { errors: result.errors });
3692
+ return;
3693
+ }
3694
+ sendJson(res, 200, {
3695
+ logs: result.logs,
3696
+ nextCursor: result.nextCursor
3697
+ });
3698
+ } catch (e) {
3699
+ sendJson(res, 400, {
3700
+ error: "Invalid query request",
3701
+ message: e instanceof Error ? e.message : String(e)
3702
+ });
3703
+ }
3704
+ return;
3705
+ }
3706
+ if (req.method === "POST" && url === "/api/query/errors") {
3707
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3708
+ sendJson(res, 403, { error: "Forbidden" });
3709
+ return;
3710
+ }
3711
+ try {
3712
+ const body = await readJsonBody(req);
3713
+ const result = devtools.queryErrors({
3714
+ query: body.query ?? "",
3715
+ window: body.window,
3716
+ limit: body.limit
3717
+ });
3718
+ if (result.errors_parse) {
3719
+ sendJson(res, 400, { errors: result.errors_parse });
3720
+ return;
3721
+ }
3722
+ sendJson(res, 200, { errors: result.errors });
3723
+ } catch (e) {
3724
+ sendJson(res, 400, {
3725
+ error: "Invalid query request",
3726
+ message: e instanceof Error ? e.message : String(e)
3727
+ });
3728
+ }
3729
+ return;
3730
+ }
3731
+ if (req.method === "GET" && url === "/api/metrics") {
3732
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3733
+ sendJson(res, 403, { error: "Forbidden" });
3734
+ return;
3735
+ }
3736
+ sendJson(res, 200, { metrics: devtools.listMetricNames() });
3737
+ return;
3738
+ }
3739
+ if (req.method === "GET" && url.split("?")[0] === "/api/metrics") {
3740
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3741
+ sendJson(res, 403, { error: "Forbidden" });
3742
+ return;
3743
+ }
3744
+ const query = new URL(url, "http://localhost").searchParams.get("q") ?? "";
3745
+ const result = devtools.queryMetricCatalog(query);
3746
+ if (result.errors) sendJson(res, 400, { errors: result.errors });
3747
+ else sendJson(res, 200, { metrics: result.metrics });
3748
+ return;
3749
+ }
3750
+ if (req.method === "DELETE" && url.split("?")[0] === "/api/metrics") {
3751
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3752
+ sendJson(res, 403, { error: "Forbidden" });
3753
+ return;
3754
+ }
3755
+ const name = new URL(url, "http://localhost").searchParams.get("name");
3756
+ if (!name) {
3757
+ sendJson(res, 400, { error: "A metric name is required" });
3758
+ return;
3759
+ }
3760
+ sendJson(res, 200, { deletedSeries: devtools.deleteMetric(name) });
3761
+ return;
3762
+ }
3763
+ if (req.method === "GET" && url === "/api/stats") {
3764
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3765
+ sendJson(res, 403, { error: "Forbidden" });
3766
+ return;
3767
+ }
3768
+ sendJson(res, 200, devtools.getStoreStats());
3769
+ return;
3770
+ }
3771
+ if (req.method === "GET" && url.split("?")[0] === "/api/traces/slowest") {
3772
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3773
+ sendJson(res, 403, { error: "Forbidden" });
3774
+ return;
3775
+ }
3776
+ const limit = Number(new URL(url, "http://localhost").searchParams.get("limit") ?? 10);
3777
+ sendJson(res, 200, { traces: devtools.findSlowestTraces(limit) });
3778
+ return;
3779
+ }
3780
+ const summaryMatch = req.method === "GET" && url.match(/^\/api\/traces\/([^/?]+)\/summary$/);
3781
+ if (summaryMatch) {
3782
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3783
+ sendJson(res, 403, { error: "Forbidden" });
3784
+ return;
3785
+ }
3786
+ const summary = devtools.describeTrace(decodeURIComponent(summaryMatch[1]));
3787
+ if (!summary) sendJson(res, 404, { error: "Trace not found" });
3788
+ else sendJson(res, 200, summary);
3789
+ return;
3790
+ }
3791
+ if (req.method === "POST" && url === "/api/query/metrics") {
3792
+ if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
3793
+ sendJson(res, 403, { error: "Forbidden" });
3794
+ return;
3795
+ }
3796
+ try {
3797
+ const body = await readJsonBody(req);
3798
+ if (!body.name) {
3799
+ sendJson(res, 400, { error: "A metric name is required" });
3800
+ return;
3801
+ }
3802
+ sendJson(res, 200, { series: devtools.queryMetricSeries({
3803
+ name: body.name,
3804
+ window: body.window,
3805
+ maxPoints: body.maxPoints
3806
+ }) });
3807
+ } catch (e) {
3808
+ sendJson(res, 400, {
3809
+ error: "Invalid metrics query",
3810
+ message: e instanceof Error ? e.message : String(e)
3811
+ });
3812
+ }
3813
+ return;
3814
+ }
3815
+ sendJson(res, 404, { error: "Not found" });
3816
+ });
3817
+ }
3818
+ function createDevtoolsHttpServer(devtools, _options = {}) {
3819
+ const server = createServer();
3820
+ attachDevtoolsRoutes(server, devtools);
3821
+ return server;
3822
+ }
3823
+
3824
+ //#endregion
3825
+ export { ErrorAggregator as C, resolveTelemetryLimits as S, isLoopbackHostname as _, probePortHolder as a, appendWithLimit as b, decodeOtlpTraceRequest as c, parseOtlpLogs as d, parseOtlpTraces as f, hostHeaderIsLoopback as g, allowSensitiveRequest as h, DEVTOOLS_IDENTITY as i, DevtoolsServer as l, SPAN_SCHEMA as m, createDevtoolsHttpServer as n, decodeOtlpLogsRequest as o, DevtoolsStore as p, resolveSourceRoot as r, decodeOtlpMetricsRequest as s, attachDevtoolsRoutes as t, isProtobufContentType as u, originIsLoopback as v, applyTelemetryLimits as x, appendManyWithLimit as y };