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