autotel-devtools 22.0.0 → 23.0.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-BrEcnzoT.d.ts +546 -0
  9. package/dist/exporter-C4uKgo7l.d.cts +546 -0
  10. package/dist/fullpage.global.js +39 -0
  11. package/dist/grpc-CSWjMRiB.cjs +82 -0
  12. package/dist/grpc-CZEDUYCM.js +77 -0
  13. package/dist/http-Cqm_MAtc.cjs +3942 -0
  14. package/dist/http-Dbd9TIYU.js +3776 -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
@@ -1,1607 +0,0 @@
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_json_fields = require('./json-fields-DZFlNqT2.cjs');
29
- const require_trace_root = require('./trace-root-BMa667jK.cjs');
30
- const require_resource_utils = require('./resource-utils-DjHJB6uc.cjs');
31
- let node_http = require("node:http");
32
- let ws = require("ws");
33
- let autotel_agents = require("autotel-agents");
34
- let node_fs = require("node:fs");
35
- let node_path = require("node:path");
36
- node_path = __toESM(node_path, 1);
37
- let node_url = require("node:url");
38
- let protobufjs = require("protobufjs");
39
- protobufjs = __toESM(protobufjs, 1);
40
-
41
- //#region src/server/error-aggregator.ts
42
- var ErrorAggregator = class {
43
- errorGroups = /* @__PURE__ */ new Map();
44
- options;
45
- constructor(options = {}) {
46
- this.options = {
47
- maxGroups: options.maxGroups ?? 100,
48
- maxAffectedTraces: options.maxAffectedTraces ?? 10,
49
- maxAffectedSpans: options.maxAffectedSpans ?? 5,
50
- stackFramesForFingerprint: options.stackFramesForFingerprint ?? 5
51
- };
52
- }
53
- /**
54
- * Add an error occurrence to the aggregator
55
- */
56
- addError(occurrence) {
57
- const fingerprint = this.generateFingerprint(occurrence);
58
- const existing = this.errorGroups.get(fingerprint);
59
- if (existing) {
60
- existing.count++;
61
- existing.lastSeen = occurrence.timestamp;
62
- if (!existing.affectedTraces.includes(occurrence.traceId)) {
63
- existing.affectedTraces.push(occurrence.traceId);
64
- if (existing.affectedTraces.length > this.options.maxAffectedTraces) existing.affectedTraces.shift();
65
- }
66
- if (!existing.affectedSpans.includes(occurrence.spanName)) {
67
- existing.affectedSpans.push(occurrence.spanName);
68
- if (existing.affectedSpans.length > this.options.maxAffectedSpans) existing.affectedSpans.shift();
69
- }
70
- return existing;
71
- }
72
- const newGroup = {
73
- fingerprint,
74
- type: occurrence.error.type,
75
- message: occurrence.error.message,
76
- stackTrace: this.normalizeStackTrace(occurrence.error.stackTrace),
77
- count: 1,
78
- firstSeen: occurrence.timestamp,
79
- lastSeen: occurrence.timestamp,
80
- affectedTraces: [occurrence.traceId],
81
- affectedSpans: [occurrence.spanName],
82
- service: occurrence.service,
83
- attributes: occurrence.attributes
84
- };
85
- if (this.errorGroups.size >= this.options.maxGroups) this.evictOldestGroup();
86
- this.errorGroups.set(fingerprint, newGroup);
87
- return newGroup;
88
- }
89
- /**
90
- * Extract errors from a trace and add them to the aggregator
91
- */
92
- addErrorsFromTrace(trace) {
93
- const addedGroups = [];
94
- for (const span of trace.spans) if (span.status.code === "ERROR") {
95
- const occurrence = this.extractErrorFromSpan(span, trace);
96
- if (occurrence) {
97
- const group = this.addError(occurrence);
98
- addedGroups.push(group);
99
- }
100
- }
101
- return addedGroups;
102
- }
103
- /**
104
- * Extract error occurrence from a span
105
- */
106
- extractErrorFromSpan(span, trace) {
107
- const exceptionEvent = span.events?.find((e) => e.name === "exception");
108
- const errorType = require_json_fields.stringAttr(span.attributes, "exception.type", "error.type") ?? require_json_fields.stringAttr(exceptionEvent?.attributes, "exception.type") ?? "Error";
109
- const errorMessage = span.status.message || require_json_fields.stringAttr(span.attributes, "exception.message", "error.message") || "Unknown error";
110
- const stackTrace = require_json_fields.stringAttr(span.attributes, "exception.stacktrace", "exception.stack", "error.stack") ?? this.extractStackFromEvents(span);
111
- return {
112
- traceId: trace.traceId,
113
- spanId: span.spanId,
114
- spanName: span.name,
115
- service: trace.service,
116
- timestamp: span.endTime,
117
- error: {
118
- type: errorType,
119
- message: errorMessage,
120
- stackTrace,
121
- fingerprint: require_json_fields.stringAttr(span.attributes, "exception.fingerprint") ?? require_json_fields.stringAttr(exceptionEvent?.attributes, "exception.fingerprint")
122
- },
123
- attributes: this.extractRelevantAttributes(span.attributes)
124
- };
125
- }
126
- /**
127
- * Extract stack trace from span events (exception events)
128
- */
129
- extractStackFromEvents(span) {
130
- if (!span.events) return void 0;
131
- const exceptionEvent = span.events.find((e) => e.name === "exception");
132
- if (exceptionEvent?.attributes) return require_json_fields.stringAttr(exceptionEvent.attributes, "exception.stacktrace", "exception.stack");
133
- }
134
- /**
135
- * Extract relevant attributes for error context
136
- */
137
- extractRelevantAttributes(attributes) {
138
- const relevant = {};
139
- for (const key of [
140
- "http.method",
141
- "http.url",
142
- "http.route",
143
- "http.status_code",
144
- "db.system",
145
- "db.operation",
146
- "rpc.method",
147
- "rpc.service",
148
- "code.function",
149
- "code.filepath",
150
- "user.id",
151
- "operation.name"
152
- ]) if (key in attributes) relevant[key] = attributes[key];
153
- return relevant;
154
- }
155
- /**
156
- * Generate a fingerprint for error grouping
157
- *
158
- * Uses error type + first N stack frames (normalized)
159
- */
160
- generateFingerprint(occurrence) {
161
- if (occurrence.error.fingerprint) return occurrence.error.fingerprint;
162
- const parts = [occurrence.error.type];
163
- if (occurrence.error.stackTrace) {
164
- const frames = this.extractStackFrames(occurrence.error.stackTrace, this.options.stackFramesForFingerprint);
165
- parts.push(...frames);
166
- } else parts.push(this.normalizeMessage(occurrence.error.message));
167
- return this.simpleHash(parts.join("|"));
168
- }
169
- /**
170
- * Extract and normalize stack frames from a stack trace
171
- */
172
- extractStackFrames(stackTrace, count) {
173
- const lines = stackTrace.split("\n");
174
- const frames = [];
175
- for (const line of lines) {
176
- if (frames.length >= count) break;
177
- const trimmed = line.trim();
178
- const nodeMatch = trimmed.match(/^at\s+(.+?)\s+\((.+?):(\d+):\d+\)$/);
179
- if (nodeMatch) {
180
- frames.push(`${nodeMatch[1]}@${this.normalizeFilePath(nodeMatch[2])}`);
181
- continue;
182
- }
183
- const anonMatch = trimmed.match(/^at\s+(.+?):(\d+):\d+$/);
184
- if (anonMatch) {
185
- frames.push(`anonymous@${this.normalizeFilePath(anonMatch[1])}`);
186
- continue;
187
- }
188
- const browserMatch = trimmed.match(/^(.+?)@(.+?):(\d+):\d+$/);
189
- if (browserMatch) {
190
- frames.push(`${browserMatch[1]}@${this.normalizeFilePath(browserMatch[2])}`);
191
- continue;
192
- }
193
- }
194
- return frames;
195
- }
196
- /**
197
- * Normalize file path by removing absolute path prefixes and node_modules paths
198
- */
199
- normalizeFilePath(filePath) {
200
- const nodeModulesMatch = filePath.match(/node_modules\/(@[^/]+\/[^/]+|[^/]+)/);
201
- if (nodeModulesMatch) return `[npm]/${nodeModulesMatch[1]}`;
202
- return filePath.replace(/^.*?\/src\//, "src/").replace(/^.*?\/dist\//, "dist/").replace(/^.*?\/lib\//, "lib/").replace(/^file:\/\//, "");
203
- }
204
- /**
205
- * Normalize error message by removing dynamic parts
206
- */
207
- normalizeMessage(message) {
208
- 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);
209
- }
210
- /**
211
- * Normalize stack trace for display
212
- */
213
- normalizeStackTrace(stackTrace) {
214
- if (!stackTrace) return void 0;
215
- return stackTrace.split("\n").slice(0, 10).join("\n");
216
- }
217
- /**
218
- * Simple hash function for fingerprinting
219
- */
220
- simpleHash(str) {
221
- let hash = 0;
222
- for (let i = 0; i < str.length; i++) {
223
- const char = str.charCodeAt(i);
224
- hash = (hash << 5) - hash + char;
225
- hash = hash & hash;
226
- }
227
- return Math.abs(hash).toString(16).padStart(8, "0");
228
- }
229
- /**
230
- * Evict the oldest error group
231
- */
232
- evictOldestGroup() {
233
- let oldest = null;
234
- for (const [fingerprint, group] of this.errorGroups) if (!oldest || group.lastSeen < oldest.lastSeen) oldest = {
235
- fingerprint,
236
- lastSeen: group.lastSeen
237
- };
238
- if (oldest) this.errorGroups.delete(oldest.fingerprint);
239
- }
240
- /**
241
- * Get all error groups, sorted by most recent
242
- */
243
- getErrorGroups() {
244
- return [...this.errorGroups.values()].sort((a, b) => b.lastSeen - a.lastSeen);
245
- }
246
- /**
247
- * Get error groups sorted by count (most frequent first)
248
- */
249
- getErrorGroupsByFrequency() {
250
- return [...this.errorGroups.values()].sort((a, b) => b.count - a.count);
251
- }
252
- /**
253
- * Get a specific error group by fingerprint
254
- */
255
- getErrorGroup(fingerprint) {
256
- return this.errorGroups.get(fingerprint);
257
- }
258
- /**
259
- * Get error groups for a specific service
260
- */
261
- getErrorGroupsByService(service) {
262
- return this.getErrorGroups().filter((g) => g.service === service);
263
- }
264
- /**
265
- * Get total error count across all groups
266
- */
267
- getTotalErrorCount() {
268
- let total = 0;
269
- for (const group of this.errorGroups.values()) total += group.count;
270
- return total;
271
- }
272
- /**
273
- * Get error statistics
274
- */
275
- getStats() {
276
- const oneHourAgo = Date.now() - 3600 * 1e3;
277
- let recentErrors = 0;
278
- const typeCount = /* @__PURE__ */ new Map();
279
- for (const group of this.errorGroups.values()) {
280
- if (group.lastSeen > oneHourAgo) recentErrors += group.count;
281
- typeCount.set(group.type, (typeCount.get(group.type) || 0) + group.count);
282
- }
283
- const topErrorTypes = [...typeCount.entries()].map(([type, count]) => ({
284
- type,
285
- count
286
- })).sort((a, b) => b.count - a.count).slice(0, 5);
287
- return {
288
- totalGroups: this.errorGroups.size,
289
- totalErrors: this.getTotalErrorCount(),
290
- recentErrors,
291
- topErrorTypes
292
- };
293
- }
294
- /**
295
- * Clear all error groups
296
- */
297
- clear() {
298
- this.errorGroups.clear();
299
- }
300
- /**
301
- * Clear old error groups (not seen in given time window)
302
- */
303
- clearOlderThan(maxAgeMs) {
304
- const cutoff = Date.now() - maxAgeMs;
305
- let cleared = 0;
306
- for (const [fingerprint, group] of this.errorGroups) if (group.lastSeen < cutoff) {
307
- this.errorGroups.delete(fingerprint);
308
- cleared++;
309
- }
310
- return cleared;
311
- }
312
- };
313
-
314
- //#endregion
315
- //#region src/server/telemetry-limits.ts
316
- const defaultLimit = 100;
317
- function parseLimit(value) {
318
- if (!value) return void 0;
319
- const parsed = Number.parseInt(value, 10);
320
- return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
321
- }
322
- function resolveTelemetryLimits(args = {}) {
323
- const env = args.env ?? process.env;
324
- const fallback = args.maxHistory ?? defaultLimit;
325
- return {
326
- maxTraceCount: args.maxTraceCount ?? parseLimit(env.AUTOTEL_MAX_TRACE_COUNT) ?? fallback,
327
- maxLogCount: args.maxLogCount ?? parseLimit(env.AUTOTEL_MAX_LOG_COUNT) ?? fallback,
328
- maxMetricCount: args.maxMetricCount ?? parseLimit(env.AUTOTEL_MAX_METRIC_COUNT) ?? fallback
329
- };
330
- }
331
- function appendWithLimit(items, item, limit) {
332
- if (limit <= 0) return [];
333
- const next = [...items, item];
334
- return next.length > limit ? next.slice(next.length - limit) : next;
335
- }
336
- function appendManyWithLimit(items, incoming, limit) {
337
- if (limit <= 0 || incoming.length === 0) return limit <= 0 ? [] : items;
338
- const next = [...items, ...incoming];
339
- return next.length > limit ? next.slice(next.length - limit) : next;
340
- }
341
- function applyTelemetryLimits(data, limits) {
342
- return {
343
- ...data,
344
- traces: data.traces.slice(-limits.maxTraceCount),
345
- logs: data.logs.slice(-limits.maxLogCount),
346
- metrics: data.metrics.slice(-limits.maxMetricCount)
347
- };
348
- }
349
-
350
- //#endregion
351
- //#region src/server/origin-guard.ts
352
- const LOOPBACK_IPV6 = /* @__PURE__ */ new Set(["::1", "0:0:0:0:0:0:0:1"]);
353
- /** True for `localhost`, any `127.x.x.x`, and IPv6 loopback. Case-insensitive. */
354
- function isLoopbackHostname(hostname) {
355
- const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
356
- return h === "localhost" || /^127\./.test(h) || LOOPBACK_IPV6.has(h);
357
- }
358
- /** Hostname from a `Host` header (`host`, `host:port`, `[::1]:port`). */
359
- function hostnameFromHostHeader(host) {
360
- const h = host.trim();
361
- if (h.startsWith("[")) {
362
- const end = h.indexOf("]");
363
- return end > 0 ? h.slice(1, end) : h;
364
- }
365
- const colon = h.indexOf(":");
366
- return colon === -1 ? h : h.slice(0, colon);
367
- }
368
- /** True when the `Host` header names a loopback host. */
369
- function hostHeaderIsLoopback(host) {
370
- return isLoopbackHostname(hostnameFromHostHeader(host));
371
- }
372
- /** True when an `Origin` header names a loopback origin. A malformed or opaque
373
- * origin (e.g. the literal `null` from a sandboxed iframe) is treated as
374
- * non-loopback. */
375
- function originIsLoopback(origin) {
376
- try {
377
- return isLoopbackHostname(new URL(origin).hostname);
378
- } catch {
379
- return false;
380
- }
381
- }
382
- /**
383
- * Decide whether a request to a sensitive (read/mutate) endpoint is allowed.
384
- * - A present, non-loopback `Origin` is always rejected (cross-origin read).
385
- * - When `loopbackOnly`, a present, non-loopback `Host` is rejected (DNS
386
- * rebinding). Skipped when the receiver is bound to a non-loopback host.
387
- */
388
- function allowSensitiveRequest(headers, loopbackOnly) {
389
- const { origin, host } = headers;
390
- if (origin && origin.length > 0 && !originIsLoopback(origin)) return false;
391
- if (loopbackOnly && host && host.length > 0 && !hostHeaderIsLoopback(host)) return false;
392
- return true;
393
- }
394
-
395
- //#endregion
396
- //#region src/server/server.ts
397
- var DevtoolsServer = class {
398
- wss;
399
- clients = /* @__PURE__ */ new Set();
400
- httpServer;
401
- traces = [];
402
- logs = [];
403
- metrics = [];
404
- agentSessions = /* @__PURE__ */ new Map();
405
- errorAggregator = new ErrorAggregator();
406
- limits;
407
- verbose;
408
- _port;
409
- onData;
410
- constructor(options = {}) {
411
- this.limits = resolveTelemetryLimits(options);
412
- this.verbose = options.verbose ?? false;
413
- this._port = options.port ?? 4318;
414
- this.onData = options.onData;
415
- this.httpServer = options.server ?? (0, node_http.createServer)();
416
- const loopbackOnly = options.host == null || hostHeaderIsLoopback(options.host);
417
- this.wss = new ws.WebSocketServer({
418
- server: this.httpServer,
419
- path: options.path ?? "/ws",
420
- verifyClient: ({ origin, req }) => allowSensitiveRequest({
421
- origin,
422
- host: req.headers.host
423
- }, loopbackOnly)
424
- });
425
- this.wss.on("error", (err) => {
426
- if (this.httpServer.listening) throw err;
427
- });
428
- this.wss.on("connection", (ws$1) => {
429
- this.clients.add(ws$1);
430
- this.log(`Client connected (${this.clients.size} total)`);
431
- const data = this.getCurrentData();
432
- if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0 || (data.agents?.length ?? 0) > 0) ws$1.send(JSON.stringify(data));
433
- ws$1.on("close", () => {
434
- this.clients.delete(ws$1);
435
- this.log(`Client disconnected (${this.clients.size} total)`);
436
- });
437
- });
438
- if (!options.server) this.httpServer.listen(this._port, () => {
439
- const addr = this.httpServer.address();
440
- if (addr && typeof addr === "object") this._port = addr.port;
441
- this.log(`WebSocket server listening on port ${this._port}`);
442
- });
443
- }
444
- get port() {
445
- const addr = this.httpServer.address();
446
- if (addr && typeof addr === "object") return addr.port;
447
- return this._port;
448
- }
449
- get clientCount() {
450
- return this.clients.size;
451
- }
452
- addTrace(trace) {
453
- const existing = this.traces.find((t) => t.traceId === trace.traceId);
454
- const merged = existing ?? trace;
455
- if (existing) {
456
- const existingSpanIds = new Set(existing.spans.map((s) => s.spanId));
457
- for (const span of trace.spans) if (!existingSpanIds.has(span.spanId)) existing.spans.push(span);
458
- existing.startTime = Math.min(existing.startTime, trace.startTime);
459
- existing.endTime = Math.max(existing.endTime, trace.endTime);
460
- existing.duration = existing.endTime - existing.startTime;
461
- if (trace.status === "ERROR") existing.status = "ERROR";
462
- existing.spans.sort((a, b) => a.startTime - b.startTime);
463
- const { rootSpan, partial } = require_trace_root.pickRoot(existing.spans);
464
- existing.rootSpan = rootSpan;
465
- if (partial) existing.partial = true;
466
- else {
467
- delete existing.partial;
468
- const rootService = rootSpan.attributes?.["service.name"];
469
- if (typeof rootService === "string" && rootService.length > 0) existing.service = rootService;
470
- }
471
- } else this.traces = appendWithLimit(this.traces, trace, this.limits.maxTraceCount);
472
- this.errorAggregator.addErrorsFromTrace(trace);
473
- this.broadcast({
474
- traces: [merged],
475
- metrics: [],
476
- logs: [],
477
- errors: this.errorAggregator.getErrorGroups()
478
- });
479
- }
480
- addTraces(traces) {
481
- for (const trace of traces) this.addTrace(trace);
482
- }
483
- addLog(log) {
484
- this.logs = appendWithLimit(this.logs, log, this.limits.maxLogCount);
485
- this.broadcast({
486
- traces: [],
487
- metrics: [],
488
- logs: [log],
489
- errors: this.errorAggregator.getErrorGroups()
490
- });
491
- }
492
- addLogs(logs) {
493
- this.logs = appendManyWithLimit(this.logs, logs, this.limits.maxLogCount);
494
- this.broadcast({
495
- traces: [],
496
- metrics: [],
497
- logs,
498
- errors: this.errorAggregator.getErrorGroups()
499
- });
500
- }
501
- addMetric(metric) {
502
- this.metrics = appendWithLimit(this.metrics, metric, this.limits.maxMetricCount);
503
- this.broadcast({
504
- traces: [],
505
- metrics: [metric],
506
- logs: [],
507
- errors: this.errorAggregator.getErrorGroups()
508
- });
509
- }
510
- /** Fold decoded agent log events into sessions and broadcast the full set. */
511
- ingestAgentEvents(records) {
512
- if (records.length === 0) return;
513
- (0, autotel_agents.ingestAgentEvents)(this.agentSessions, records);
514
- this.broadcastAgents();
515
- }
516
- /** Fold decoded agent metric records into sessions and broadcast the full set. */
517
- ingestAgentMetrics(records) {
518
- if (records.length === 0) return;
519
- (0, autotel_agents.ingestAgentMetrics)(this.agentSessions, records);
520
- this.broadcastAgents();
521
- }
522
- broadcastAgents() {
523
- this.broadcast({
524
- traces: [],
525
- metrics: [],
526
- logs: [],
527
- errors: this.errorAggregator.getErrorGroups(),
528
- agents: [...this.agentSessions.values()]
529
- });
530
- }
531
- getCurrentData() {
532
- return {
533
- traces: this.traces,
534
- metrics: this.metrics,
535
- logs: this.logs,
536
- errors: this.errorAggregator.getErrorGroups(),
537
- agents: [...this.agentSessions.values()]
538
- };
539
- }
540
- clearData() {
541
- this.traces = [];
542
- this.logs = [];
543
- this.metrics = [];
544
- this.agentSessions.clear();
545
- this.errorAggregator.clear();
546
- }
547
- broadcast(data) {
548
- const msg = JSON.stringify(data);
549
- for (const client of this.clients) if (client.readyState === ws.WebSocket.OPEN) client.send(msg);
550
- if (this.onData) try {
551
- this.onData(data);
552
- } catch {}
553
- }
554
- log(message) {
555
- if (this.verbose) console.log(`[autotel-devtools] ${message}`);
556
- }
557
- async close() {
558
- for (const client of this.clients) client.close();
559
- this.clients.clear();
560
- this.wss.close();
561
- await new Promise((resolve) => this.httpServer.close(() => resolve()));
562
- }
563
- };
564
-
565
- //#endregion
566
- //#region src/server/otlp-types.ts
567
- /**
568
- * An exporter's payload, read as the envelope it claims to be.
569
- *
570
- * SAFETY: this is the one place the receiver trusts the wire. Every field of
571
- * every envelope above is optional, so a payload that is not what it claims
572
- * reads back as empty arrays and undefined fields rather than throwing - which
573
- * is what the callers below rely on when they find no spans to add.
574
- */
575
- function otlpEnvelope(payload) {
576
- if (typeof payload !== "object" || payload === null) return void 0;
577
- return payload;
578
- }
579
-
580
- //#endregion
581
- //#region src/server/otlp.ts
582
- function resolveOtlpValue(v) {
583
- if (!v) return void 0;
584
- if (v.stringValue !== void 0) return v.stringValue;
585
- if (v.boolValue !== void 0) return v.boolValue;
586
- if (v.intValue !== void 0) return Number(v.intValue);
587
- if (v.doubleValue !== void 0) return v.doubleValue;
588
- if (v.bytesValue !== void 0) return v.bytesValue;
589
- if (v.arrayValue?.values) return v.arrayValue.values.map(resolveOtlpValue);
590
- if (v.kvlistValue?.values) return flattenAttributes(v.kvlistValue.values);
591
- }
592
- function flattenAttributes(attrs) {
593
- const out = {};
594
- if (!attrs) return out;
595
- for (const { key, value } of attrs) out[key] = resolveOtlpValue(value);
596
- return out;
597
- }
598
- /**
599
- * A log record's body: the text it carried, or the structure it carried when
600
- * the sender used an OTLP kvlist or array rather than a string.
601
- */
602
- function logBody(body) {
603
- const text = require_json_fields.asString(body);
604
- if (text !== void 0) return text;
605
- if (body === void 0 || body === null) return "";
606
- const structured = require_json_fields.asObject(body);
607
- if (!structured) return String(body);
608
- return structured;
609
- }
610
- /**
611
- * Attributes handed to the agent layer, whose `Attributes` is OTel's own -
612
- * scalars and arrays of scalars, nothing nested.
613
- *
614
- * SAFETY: a coding agent's metrics and events carry scalar attributes only,
615
- * so the two shapes agree in practice. A sender that nests one anyway is
616
- * rendered by the Agents tab as whatever it is rather than being dropped.
617
- */
618
- function agentAttributes(attributes) {
619
- return attributes;
620
- }
621
- function nanoToMs(nano) {
622
- if (!nano) return 0;
623
- const ns = BigInt(nano);
624
- const ms = ns / 1000000n;
625
- const remNs = ns % 1000000n;
626
- return Number(ms) + Number(remNs) / 1e6;
627
- }
628
- const SPAN_KIND_MAP = /* @__PURE__ */ new Map([
629
- [0, "INTERNAL"],
630
- [1, "INTERNAL"],
631
- [2, "SERVER"],
632
- [3, "CLIENT"],
633
- [4, "PRODUCER"],
634
- [5, "CONSUMER"],
635
- ["SPAN_KIND_INTERNAL", "INTERNAL"],
636
- ["SPAN_KIND_SERVER", "SERVER"],
637
- ["SPAN_KIND_CLIENT", "CLIENT"],
638
- ["SPAN_KIND_PRODUCER", "PRODUCER"],
639
- ["SPAN_KIND_CONSUMER", "CONSUMER"]
640
- ]);
641
- function normalizeHexId(id) {
642
- if (!id) return "";
643
- 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 {
644
- return Buffer.from(id, "base64").toString("hex");
645
- } catch {}
646
- return id;
647
- }
648
- function parseOtlpTraces(payload) {
649
- const resourceSpans = otlpEnvelope(payload)?.resourceSpans;
650
- if (!resourceSpans || resourceSpans.length === 0) return [];
651
- const traceMap = /* @__PURE__ */ new Map();
652
- for (const rs of resourceSpans) {
653
- const resourceAttrs = flattenAttributes(rs.resource?.attributes);
654
- const service = String(resourceAttrs["service.name"] || "unknown");
655
- for (const ss of rs.scopeSpans ?? []) {
656
- const scope = ss.scope?.name ? {
657
- name: ss.scope.name,
658
- version: ss.scope.version || void 0
659
- } : void 0;
660
- for (const span of ss.spans || []) {
661
- const traceId = normalizeHexId(span.traceId);
662
- if (!traceId) continue;
663
- const startMs = nanoToMs(span.startTimeUnixNano);
664
- const endMs = nanoToMs(span.endTimeUnixNano);
665
- const statusCode = span.status?.code;
666
- let status = "UNSET";
667
- if (statusCode === 1 || statusCode === "STATUS_CODE_OK") status = "OK";
668
- if (statusCode === 2 || statusCode === "STATUS_CODE_ERROR") status = "ERROR";
669
- const spanData = {
670
- traceId,
671
- spanId: normalizeHexId(span.spanId),
672
- parentSpanId: normalizeHexId(span.parentSpanId) || void 0,
673
- name: span.name || "unknown",
674
- kind: SPAN_KIND_MAP.get(span.kind ?? 0) ?? "INTERNAL",
675
- startTime: startMs,
676
- endTime: endMs,
677
- duration: endMs - startMs,
678
- attributes: {
679
- ...resourceAttrs,
680
- ...flattenAttributes(span.attributes)
681
- },
682
- status: {
683
- code: status,
684
- message: span.status?.message
685
- },
686
- events: (span.events ?? []).map((e) => ({
687
- name: e.name || "",
688
- timestamp: nanoToMs(e.timeUnixNano),
689
- attributes: flattenAttributes(e.attributes)
690
- })),
691
- links: (span.links ?? []).map((l) => ({
692
- traceId: normalizeHexId(l.traceId),
693
- spanId: normalizeHexId(l.spanId),
694
- attributes: flattenAttributes(l.attributes)
695
- })),
696
- scope
697
- };
698
- const existing = traceMap.get(traceId);
699
- if (existing) existing.spans.push(spanData);
700
- else traceMap.set(traceId, {
701
- spans: [spanData],
702
- service
703
- });
704
- }
705
- }
706
- }
707
- const traces = [];
708
- for (const [traceId, { spans, service }] of traceMap) {
709
- const sorted = spans.sort((a, b) => a.startTime - b.startTime);
710
- const { rootSpan, partial } = require_trace_root.pickRoot(sorted);
711
- const startTime = Math.min(...sorted.map((s) => s.startTime));
712
- const endTime = Math.max(...sorted.map((s) => s.endTime));
713
- const hasError = sorted.some((s) => s.status.code === "ERROR");
714
- const trace = {
715
- traceId,
716
- correlationId: traceId.slice(0, 16),
717
- rootSpan,
718
- spans: sorted,
719
- startTime,
720
- endTime,
721
- duration: endTime - startTime,
722
- status: hasError ? "ERROR" : "OK",
723
- service
724
- };
725
- if (partial) trace.partial = true;
726
- traces.push(trace);
727
- }
728
- return traces;
729
- }
730
- function parseOtlpLogs(payload) {
731
- const resourceLogs = otlpEnvelope(payload)?.resourceLogs;
732
- if (!resourceLogs) return [];
733
- const logs = [];
734
- for (const rl of resourceLogs) {
735
- const resourceAttrs = flattenAttributes(rl.resource?.attributes);
736
- for (const sl of rl.scopeLogs ?? []) for (const rec of sl.logRecords ?? []) {
737
- const timestamp = nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano);
738
- const traceId = normalizeHexId(rec.traceId) || void 0;
739
- const spanId = normalizeHexId(rec.spanId) || void 0;
740
- const body = rec.body ? resolveOtlpValue(rec.body) : "";
741
- logs.push({
742
- id: `${traceId || "no-trace"}:${spanId || "no-span"}:${timestamp}:${rec.severityNumber || 0}`,
743
- traceId,
744
- spanId,
745
- resourceName: require_resource_utils.getResourceName(resourceAttrs),
746
- severityText: rec.severityText,
747
- severityNumber: rec.severityNumber,
748
- body: logBody(body),
749
- timestamp,
750
- attributes: flattenAttributes(rec.attributes),
751
- resource: resourceAttrs
752
- });
753
- }
754
- }
755
- return logs;
756
- }
757
- function countOtlpMetrics(payload) {
758
- const resourceMetrics = otlpEnvelope(payload)?.resourceMetrics;
759
- if (!resourceMetrics) return 0;
760
- let count = 0;
761
- for (const rm of resourceMetrics) for (const sm of rm.scopeMetrics ?? []) count += (sm.metrics ?? []).length;
762
- return count;
763
- }
764
- function extractDataPoints(metric) {
765
- const points = [];
766
- const numberPoints = metric.sum?.dataPoints ?? metric.gauge?.dataPoints;
767
- if (Array.isArray(numberPoints)) for (const dp of numberPoints) {
768
- const value = dp.asDouble !== void 0 ? Number(dp.asDouble) : dp.asInt !== void 0 ? Number(dp.asInt) : 0;
769
- points.push({
770
- value,
771
- attributes: agentAttributes(flattenAttributes(dp.attributes)),
772
- timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano)
773
- });
774
- }
775
- const histPoints = metric.histogram?.dataPoints;
776
- if (Array.isArray(histPoints)) for (const dp of histPoints) points.push({
777
- value: dp.count !== void 0 ? Number(dp.count) : 0,
778
- attributes: agentAttributes(flattenAttributes(dp.attributes)),
779
- timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano)
780
- });
781
- return points;
782
- }
783
- /**
784
- * Parse OTLP metrics into structured records with data points + attributes,
785
- * for the agent layer (and richer metric views). Works for both OTLP/JSON and
786
- * decoded OTLP/protobuf — they share the same camelCase shape.
787
- */
788
- function readTemporality(metric) {
789
- const raw = metric.sum?.aggregationTemporality ?? metric.histogram?.aggregationTemporality;
790
- if (raw === 2 || raw === "AGGREGATION_TEMPORALITY_CUMULATIVE") return "cumulative";
791
- if (raw === 1 || raw === "AGGREGATION_TEMPORALITY_DELTA") return "delta";
792
- }
793
- function parseOtlpMetrics(payload) {
794
- const resourceMetrics = otlpEnvelope(payload)?.resourceMetrics;
795
- if (!resourceMetrics) return [];
796
- const records = [];
797
- for (const rm of resourceMetrics) {
798
- const resource = agentAttributes(flattenAttributes(rm.resource?.attributes));
799
- for (const sm of rm.scopeMetrics ?? []) {
800
- const scope = sm.scope?.name ? {
801
- name: sm.scope.name,
802
- version: sm.scope.version || void 0
803
- } : void 0;
804
- for (const metric of sm.metrics ?? []) records.push({
805
- name: metric.name ?? "",
806
- unit: metric.unit || void 0,
807
- description: metric.description || void 0,
808
- temporality: readTemporality(metric),
809
- dataPoints: extractDataPoints(metric),
810
- resource,
811
- scope
812
- });
813
- }
814
- }
815
- return records;
816
- }
817
- /**
818
- * Parse OTLP logs into `AgentRawEvent`s for the agent layer. Keeps the
819
- * instrumentation scope and event name (Claude Code emits its events as logs,
820
- * with the unprefixed name in the `event.name` attribute). Distinct from
821
- * `parseOtlpLogs`, which feeds the generic Logs tab.
822
- */
823
- function parseOtlpAgentEvents(payload) {
824
- const resourceLogs = otlpEnvelope(payload)?.resourceLogs;
825
- if (!resourceLogs) return [];
826
- const events = [];
827
- for (const rl of resourceLogs) {
828
- const resource = agentAttributes(flattenAttributes(rl.resource?.attributes));
829
- for (const sl of rl.scopeLogs ?? []) {
830
- const scope = sl.scope?.name ? {
831
- name: sl.scope.name,
832
- version: sl.scope.version || void 0
833
- } : void 0;
834
- for (const rec of sl.logRecords ?? []) {
835
- const attributes = agentAttributes(flattenAttributes(rec.attributes));
836
- const eventName = rec.eventName || String(attributes["event.name"] ?? "");
837
- events.push({
838
- eventName,
839
- timestamp: nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano),
840
- body: rec.body ? resolveOtlpValue(rec.body) : void 0,
841
- attributes,
842
- resource,
843
- scope
844
- });
845
- }
846
- }
847
- }
848
- return events;
849
- }
850
- async function readJsonBody(req) {
851
- return new Promise((resolve, reject) => {
852
- const chunks = [];
853
- req.on("data", (chunk) => chunks.push(chunk));
854
- req.on("end", () => {
855
- try {
856
- resolve(JSON.parse(Buffer.concat(chunks).toString()));
857
- } catch {
858
- reject(/* @__PURE__ */ new Error("Invalid JSON"));
859
- }
860
- });
861
- req.on("error", reject);
862
- });
863
- }
864
- async function readRawBody(req) {
865
- return new Promise((resolve, reject) => {
866
- const chunks = [];
867
- req.on("data", (chunk) => chunks.push(chunk));
868
- req.on("end", () => resolve(Buffer.concat(chunks)));
869
- req.on("error", reject);
870
- });
871
- }
872
- /**
873
- * True for OTLP/protobuf bodies. The OpenTelemetry Python/Java/Go SDKs default to
874
- * `http/protobuf` over OTLP HTTP, sending `application/x-protobuf`; some clients use
875
- * `application/protobuf`. Anything else (JSON, unset) is treated as OTLP/JSON.
876
- */
877
- function isProtobufContentType(contentType) {
878
- if (!contentType) return false;
879
- const value = contentType.toLowerCase();
880
- return value.includes("application/x-protobuf") || value.includes("application/protobuf");
881
- }
882
- function sendJson(res, status, data) {
883
- const body = JSON.stringify(data);
884
- res.writeHead(status, {
885
- "Content-Type": "application/json",
886
- "Content-Length": Buffer.byteLength(body)
887
- });
888
- res.end(body);
889
- }
890
-
891
- //#endregion
892
- //#region src/server/otlp-proto.ts
893
- const COMMON_PROTO = `
894
- syntax = "proto3";
895
- package opentelemetry.proto.common.v1;
896
-
897
- message AnyValue {
898
- oneof value {
899
- string string_value = 1;
900
- bool bool_value = 2;
901
- int64 int_value = 3;
902
- double double_value = 4;
903
- ArrayValue array_value = 5;
904
- KeyValueList kvlist_value = 6;
905
- bytes bytes_value = 7;
906
- }
907
- }
908
- message ArrayValue { repeated AnyValue values = 1; }
909
- message KeyValueList { repeated KeyValue values = 1; }
910
- message KeyValue {
911
- string key = 1;
912
- AnyValue value = 2;
913
- }
914
- message InstrumentationScope {
915
- string name = 1;
916
- string version = 2;
917
- repeated KeyValue attributes = 3;
918
- uint32 dropped_attributes_count = 4;
919
- }
920
- `;
921
- const RESOURCE_PROTO = `
922
- syntax = "proto3";
923
- package opentelemetry.proto.resource.v1;
924
-
925
- message Resource {
926
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 1;
927
- uint32 dropped_attributes_count = 2;
928
- }
929
- `;
930
- const TRACE_PROTO = `
931
- syntax = "proto3";
932
- package opentelemetry.proto.trace.v1;
933
-
934
- message ResourceSpans {
935
- opentelemetry.proto.resource.v1.Resource resource = 1;
936
- repeated ScopeSpans scope_spans = 2;
937
- string schema_url = 3;
938
- }
939
- message ScopeSpans {
940
- opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
941
- repeated Span spans = 2;
942
- string schema_url = 3;
943
- }
944
- message Span {
945
- bytes trace_id = 1;
946
- bytes span_id = 2;
947
- string trace_state = 3;
948
- bytes parent_span_id = 4;
949
- fixed32 flags = 16;
950
- string name = 5;
951
- SpanKind kind = 6;
952
- fixed64 start_time_unix_nano = 7;
953
- fixed64 end_time_unix_nano = 8;
954
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 9;
955
- uint32 dropped_attributes_count = 10;
956
- repeated Event events = 11;
957
- uint32 dropped_events_count = 12;
958
- repeated Link links = 13;
959
- uint32 dropped_links_count = 14;
960
- Status status = 15;
961
-
962
- enum SpanKind {
963
- SPAN_KIND_UNSPECIFIED = 0;
964
- SPAN_KIND_INTERNAL = 1;
965
- SPAN_KIND_SERVER = 2;
966
- SPAN_KIND_CLIENT = 3;
967
- SPAN_KIND_PRODUCER = 4;
968
- SPAN_KIND_CONSUMER = 5;
969
- }
970
- message Event {
971
- fixed64 time_unix_nano = 1;
972
- string name = 2;
973
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 3;
974
- uint32 dropped_attributes_count = 4;
975
- }
976
- message Link {
977
- bytes trace_id = 1;
978
- bytes span_id = 2;
979
- string trace_state = 3;
980
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 4;
981
- uint32 dropped_attributes_count = 5;
982
- fixed32 flags = 6;
983
- }
984
- }
985
- message Status {
986
- reserved 1;
987
- string message = 2;
988
- StatusCode code = 3;
989
-
990
- enum StatusCode {
991
- STATUS_CODE_UNSET = 0;
992
- STATUS_CODE_OK = 1;
993
- STATUS_CODE_ERROR = 2;
994
- }
995
- }
996
- message ExportTraceServiceRequest {
997
- repeated ResourceSpans resource_spans = 1;
998
- }
999
- `;
1000
- const LOGS_PROTO = `
1001
- syntax = "proto3";
1002
- package opentelemetry.proto.logs.v1;
1003
-
1004
- enum SeverityNumber {
1005
- SEVERITY_NUMBER_UNSPECIFIED = 0;
1006
- SEVERITY_NUMBER_TRACE = 1;
1007
- SEVERITY_NUMBER_TRACE2 = 2;
1008
- SEVERITY_NUMBER_TRACE3 = 3;
1009
- SEVERITY_NUMBER_TRACE4 = 4;
1010
- SEVERITY_NUMBER_DEBUG = 5;
1011
- SEVERITY_NUMBER_DEBUG2 = 6;
1012
- SEVERITY_NUMBER_DEBUG3 = 7;
1013
- SEVERITY_NUMBER_DEBUG4 = 8;
1014
- SEVERITY_NUMBER_INFO = 9;
1015
- SEVERITY_NUMBER_INFO2 = 10;
1016
- SEVERITY_NUMBER_INFO3 = 11;
1017
- SEVERITY_NUMBER_INFO4 = 12;
1018
- SEVERITY_NUMBER_WARN = 13;
1019
- SEVERITY_NUMBER_WARN2 = 14;
1020
- SEVERITY_NUMBER_WARN3 = 15;
1021
- SEVERITY_NUMBER_WARN4 = 16;
1022
- SEVERITY_NUMBER_ERROR = 17;
1023
- SEVERITY_NUMBER_ERROR2 = 18;
1024
- SEVERITY_NUMBER_ERROR3 = 19;
1025
- SEVERITY_NUMBER_ERROR4 = 20;
1026
- SEVERITY_NUMBER_FATAL = 21;
1027
- SEVERITY_NUMBER_FATAL2 = 22;
1028
- SEVERITY_NUMBER_FATAL3 = 23;
1029
- SEVERITY_NUMBER_FATAL4 = 24;
1030
- }
1031
- message ResourceLogs {
1032
- opentelemetry.proto.resource.v1.Resource resource = 1;
1033
- repeated ScopeLogs scope_logs = 2;
1034
- string schema_url = 3;
1035
- }
1036
- message ScopeLogs {
1037
- opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
1038
- repeated LogRecord log_records = 2;
1039
- string schema_url = 3;
1040
- }
1041
- message LogRecord {
1042
- reserved 4;
1043
- fixed64 time_unix_nano = 1;
1044
- fixed64 observed_time_unix_nano = 11;
1045
- SeverityNumber severity_number = 2;
1046
- string severity_text = 3;
1047
- opentelemetry.proto.common.v1.AnyValue body = 5;
1048
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 6;
1049
- uint32 dropped_attributes_count = 7;
1050
- fixed32 flags = 8;
1051
- bytes trace_id = 9;
1052
- bytes span_id = 10;
1053
- }
1054
- message ExportLogsServiceRequest {
1055
- repeated ResourceLogs resource_logs = 1;
1056
- }
1057
- `;
1058
- const METRICS_PROTO = `
1059
- syntax = "proto3";
1060
- package opentelemetry.proto.metrics.v1;
1061
-
1062
- enum AggregationTemporality {
1063
- AGGREGATION_TEMPORALITY_UNSPECIFIED = 0;
1064
- AGGREGATION_TEMPORALITY_DELTA = 1;
1065
- AGGREGATION_TEMPORALITY_CUMULATIVE = 2;
1066
- }
1067
- message ResourceMetrics {
1068
- opentelemetry.proto.resource.v1.Resource resource = 1;
1069
- repeated ScopeMetrics scope_metrics = 2;
1070
- string schema_url = 3;
1071
- }
1072
- message ScopeMetrics {
1073
- opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
1074
- repeated Metric metrics = 2;
1075
- string schema_url = 3;
1076
- }
1077
- message Metric {
1078
- string name = 1;
1079
- string description = 2;
1080
- string unit = 3;
1081
- oneof data {
1082
- Gauge gauge = 5;
1083
- Sum sum = 7;
1084
- Histogram histogram = 9;
1085
- }
1086
- }
1087
- message Gauge {
1088
- repeated NumberDataPoint data_points = 1;
1089
- }
1090
- message Sum {
1091
- repeated NumberDataPoint data_points = 1;
1092
- AggregationTemporality aggregation_temporality = 2;
1093
- bool is_monotonic = 3;
1094
- }
1095
- message Histogram {
1096
- repeated HistogramDataPoint data_points = 1;
1097
- AggregationTemporality aggregation_temporality = 2;
1098
- }
1099
- message NumberDataPoint {
1100
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 7;
1101
- fixed64 start_time_unix_nano = 2;
1102
- fixed64 time_unix_nano = 3;
1103
- oneof value {
1104
- double as_double = 4;
1105
- sfixed64 as_int = 6;
1106
- }
1107
- }
1108
- message HistogramDataPoint {
1109
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 9;
1110
- fixed64 start_time_unix_nano = 2;
1111
- fixed64 time_unix_nano = 3;
1112
- fixed64 count = 4;
1113
- double sum = 5;
1114
- repeated fixed64 bucket_counts = 6;
1115
- repeated double explicit_bounds = 7;
1116
- }
1117
- message ExportMetricsServiceRequest {
1118
- repeated ResourceMetrics resource_metrics = 1;
1119
- }
1120
- `;
1121
- const TO_OBJECT_OPTIONS = {
1122
- longs: String,
1123
- bytes: String,
1124
- defaults: false
1125
- };
1126
- let cachedRoot = null;
1127
- function getRoot() {
1128
- if (cachedRoot) return cachedRoot;
1129
- const root = new protobufjs.default.Root();
1130
- for (const source of [
1131
- COMMON_PROTO,
1132
- RESOURCE_PROTO,
1133
- TRACE_PROTO,
1134
- LOGS_PROTO,
1135
- METRICS_PROTO
1136
- ]) protobufjs.default.parse(source, root, { keepCase: false });
1137
- root.resolveAll();
1138
- cachedRoot = root;
1139
- return root;
1140
- }
1141
- function decodeRequest(typeName, body) {
1142
- const messageType = getRoot().lookupType(typeName);
1143
- const message = messageType.decode(body);
1144
- return messageType.toObject(message, TO_OBJECT_OPTIONS);
1145
- }
1146
- /** Decode an OTLP/protobuf `ExportTraceServiceRequest` into the OTLP/JSON object shape. */
1147
- function decodeOtlpTraceRequest(body) {
1148
- return decodeRequest("opentelemetry.proto.trace.v1.ExportTraceServiceRequest", body);
1149
- }
1150
- /** Decode an OTLP/protobuf `ExportLogsServiceRequest` into the OTLP/JSON object shape. */
1151
- function decodeOtlpLogsRequest(body) {
1152
- return decodeRequest("opentelemetry.proto.logs.v1.ExportLogsServiceRequest", body);
1153
- }
1154
- /** Decode an OTLP/protobuf `ExportMetricsServiceRequest` into the OTLP/JSON object shape. */
1155
- function decodeOtlpMetricsRequest(body) {
1156
- return decodeRequest("opentelemetry.proto.metrics.v1.ExportMetricsServiceRequest", body);
1157
- }
1158
-
1159
- //#endregion
1160
- //#region src/server/identity.ts
1161
- /** Value of the `x-autotel-devtools` response header and the /healthz `service` field. */
1162
- const DEVTOOLS_IDENTITY = "autotel-devtools";
1163
- /**
1164
- * Probe `host:port` over HTTP and classify what is listening. Used when our
1165
- * requested port is busy: it lets us tell "a stale autotel-devtools is still
1166
- * up" (benign) apart from "a foreign collector owns this port" — the latter is
1167
- * the silent footgun where apps keep exporting OTLP to the busy port and reach
1168
- * the wrong process, so the devtools UI stays empty and the app sees errors.
1169
- */
1170
- async function probePortHolder(host, port, timeoutMs = 500) {
1171
- const authority = host.includes(":") ? `[${host}]` : host;
1172
- const controller = new AbortController();
1173
- const timer = setTimeout(() => controller.abort(), timeoutMs);
1174
- try {
1175
- const res = await fetch(`http://${authority}:${port}/healthz`, { signal: controller.signal });
1176
- if (res.headers.get("x-autotel-devtools")) return "autotel-devtools";
1177
- try {
1178
- const body = await res.json();
1179
- if (body && body.service === "autotel-devtools") return "autotel-devtools";
1180
- } catch {}
1181
- return "foreign";
1182
- } catch {
1183
- return "none";
1184
- } finally {
1185
- clearTimeout(timer);
1186
- }
1187
- }
1188
-
1189
- //#endregion
1190
- //#region src/server/source-file.ts
1191
- /** Refuse to slurp something huge just because a span named it. */
1192
- const MAX_BYTES = 2e6;
1193
- const DISABLED = /* @__PURE__ */ new Set([
1194
- "false",
1195
- "0",
1196
- "off",
1197
- "no",
1198
- ""
1199
- ]);
1200
- /**
1201
- * Decide what `GET /source` may read, from `AUTOTEL_DEVTOOLS_SOURCE_ROOT`.
1202
- *
1203
- * Defaults **on**, at the working directory: devtools is a local tool whose
1204
- * whole point is showing you your own code, and requiring a flag for that would
1205
- * mean nobody ever sees the feature. The blast radius stays small because two
1206
- * other things still hold — the receiver is bound to loopback, and nothing
1207
- * outside this directory is reachable. Set the variable to `false` to turn it
1208
- * off outright.
1209
- *
1210
- * A non-loopback bind (`--host 0.0.0.0`) removes the first of those, and the
1211
- * Origin guard does not replace it: a request with no `Origin` at all — any
1212
- * `curl` on the network — passes. The root holds whatever else lives in the
1213
- * project, `.env` included, so the default flips to **off** there. An explicit
1214
- * root is still honoured: exposing it on purpose is the caller's call.
1215
- */
1216
- function resolveSourceRoot(configured, cwd, loopbackOnly = true) {
1217
- if (configured === void 0) return loopbackOnly ? cwd : void 0;
1218
- if (DISABLED.has(configured.trim().toLowerCase())) return void 0;
1219
- return configured;
1220
- }
1221
- /**
1222
- * Resolve `requested` against `root`, or return `null` if it escapes.
1223
- *
1224
- * Containment is judged on **real** paths so a symlink inside the root that
1225
- * points outside it is rejected — lexical `..` stripping alone cannot see that.
1226
- * The value returned is the *lexical* resolution, because the real one differs
1227
- * from the caller's path whenever an ancestor is a symlink (on macOS both
1228
- * `/tmp` and `/var` are), and a caller comparing paths should not have to know.
1229
- */
1230
- function resolveWithinRoot(root, requested) {
1231
- const lexicalRoot = node_path.default.resolve(root);
1232
- const realRoot = safeRealpath(lexicalRoot);
1233
- if (realRoot === null) return null;
1234
- const lexicalTarget = node_path.default.resolve(lexicalRoot, requested);
1235
- const realTarget = safeRealpath(lexicalTarget);
1236
- if (realTarget === null) return null;
1237
- if (!isInside(realRoot, realTarget)) return null;
1238
- return lexicalTarget;
1239
- }
1240
- /** True when `target` is `root` itself or sits beneath it. */
1241
- function isInside(root, target) {
1242
- if (target === root) return true;
1243
- return target.startsWith(root.endsWith(node_path.default.sep) ? root : root + node_path.default.sep);
1244
- }
1245
- function safeRealpath(p) {
1246
- try {
1247
- return (0, node_fs.realpathSync)(p);
1248
- } catch {
1249
- return null;
1250
- }
1251
- }
1252
- /**
1253
- * Read `context` lines either side of `line` from a file inside `root`.
1254
- * Returns `null` when the path escapes the root, is not a readable file, or is
1255
- * too large — the caller cannot distinguish those, which is the point.
1256
- */
1257
- function readSourceWindow(root, requested, line, context) {
1258
- const resolved = resolveWithinRoot(root, requested);
1259
- if (resolved === null) return null;
1260
- let text;
1261
- try {
1262
- const stat = (0, node_fs.statSync)(resolved);
1263
- if (!stat.isFile() || stat.size > MAX_BYTES) return null;
1264
- text = (0, node_fs.readFileSync)(resolved, "utf8");
1265
- } catch {
1266
- return null;
1267
- }
1268
- const all = text.split("\n");
1269
- if (all.at(-1) === "") all.pop();
1270
- const startLine = Math.max(1, line - context);
1271
- const endLine = Math.min(all.length, line + context);
1272
- if (startLine > all.length) return null;
1273
- return {
1274
- file: node_path.default.relative(node_path.default.resolve(root), resolved),
1275
- line,
1276
- startLine,
1277
- lines: all.slice(startLine - 1, endLine)
1278
- };
1279
- }
1280
-
1281
- //#endregion
1282
- //#region src/server/http.ts
1283
- function sendOtlpError(res, req, e) {
1284
- sendJson(res, 400, {
1285
- error: "Invalid OTLP payload",
1286
- message: e instanceof Error ? e.message : String(e),
1287
- contentType: req.headers["content-type"] ?? null
1288
- });
1289
- }
1290
- const PROTOBUF_DECODERS = {
1291
- traces: decodeOtlpTraceRequest,
1292
- logs: decodeOtlpLogsRequest,
1293
- metrics: decodeOtlpMetricsRequest
1294
- };
1295
- async function readOtlpPayload(req, signal) {
1296
- if (isProtobufContentType(req.headers["content-type"])) return PROTOBUF_DECODERS[signal](await readRawBody(req));
1297
- return readJsonBody(req);
1298
- }
1299
- function findPackageRoot() {
1300
- let dir = (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
1301
- for (let i = 0; i < 5; i++) {
1302
- if ((0, node_fs.existsSync)((0, node_path.resolve)(dir, "package.json"))) return dir;
1303
- dir = (0, node_path.dirname)(dir);
1304
- }
1305
- return dir;
1306
- }
1307
- 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>";
1308
- /**
1309
- * The title is user-supplied (`--title` / `AUTOTEL_DEVTOOLS_TITLE`) and lands
1310
- * inside `<title>`, where an unescaped `<` would close the element early.
1311
- */
1312
- function escapeHtml(value) {
1313
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
1314
- }
1315
- function renderFullpageHtml(title = "autotel-devtools") {
1316
- 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>`;
1317
- }
1318
- let cachedVersion = null;
1319
- function getVersion() {
1320
- if (cachedVersion !== null) return cachedVersion;
1321
- let version = "unknown";
1322
- try {
1323
- const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.resolve)(findPackageRoot(), "package.json"), "utf8"));
1324
- if (typeof pkg.version === "string") version = pkg.version;
1325
- } catch {}
1326
- cachedVersion = version;
1327
- return version;
1328
- }
1329
- let cachedWidgetJs = null;
1330
- function getWidgetJs() {
1331
- if (!cachedWidgetJs) {
1332
- const pkgRoot = findPackageRoot();
1333
- const candidates = [(0, node_path.resolve)(pkgRoot, "dist", "widget.global.js"), (0, node_path.resolve)(pkgRoot, "widget.global.js")];
1334
- for (const candidate of candidates) try {
1335
- cachedWidgetJs = (0, node_fs.readFileSync)(candidate, "utf8");
1336
- break;
1337
- } catch {}
1338
- if (!cachedWidgetJs) cachedWidgetJs = "// widget bundle not found - run pnpm build first";
1339
- }
1340
- return cachedWidgetJs;
1341
- }
1342
- function attachDevtoolsRoutes(httpServer, devtools, options = {}) {
1343
- const loopbackOnly = options.loopbackOnly ?? true;
1344
- const sourceRoot = options.sourceRoot;
1345
- const fullpageHtml = renderFullpageHtml(options.title);
1346
- httpServer.on("request", async (req, res) => {
1347
- if (req.headers.upgrade?.toLowerCase() === "websocket") return;
1348
- res.setHeader("Access-Control-Allow-Origin", "*");
1349
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1350
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
1351
- res.setHeader("x-autotel-devtools", getVersion());
1352
- res.setHeader("Access-Control-Expose-Headers", "x-autotel-devtools");
1353
- if (req.method === "OPTIONS") {
1354
- res.writeHead(204);
1355
- res.end();
1356
- return;
1357
- }
1358
- const url = req.url || "/";
1359
- if (req.method === "GET" && url === "/") {
1360
- res.writeHead(200, {
1361
- "Content-Type": "text/html; charset=utf-8",
1362
- "Content-Length": Buffer.byteLength(fullpageHtml)
1363
- });
1364
- res.end(fullpageHtml);
1365
- return;
1366
- }
1367
- if (req.method === "GET" && url.startsWith("/widget.js")) {
1368
- const js = getWidgetJs();
1369
- res.writeHead(200, {
1370
- "Content-Type": "application/javascript; charset=utf-8",
1371
- "Content-Length": Buffer.byteLength(js)
1372
- });
1373
- res.end(js);
1374
- return;
1375
- }
1376
- if (req.method === "GET" && (url === "/favicon.svg" || url === "/favicon.ico")) {
1377
- res.writeHead(200, {
1378
- "Content-Type": "image/svg+xml; charset=utf-8",
1379
- "Cache-Control": "public, max-age=86400",
1380
- "Content-Length": Buffer.byteLength(DEVTOOLS_FAVICON_SVG)
1381
- });
1382
- res.end(DEVTOOLS_FAVICON_SVG);
1383
- return;
1384
- }
1385
- if (req.method === "GET" && url.split("?")[0] === "/source") {
1386
- if (!sourceRoot) {
1387
- sendJson(res, 404, { error: "Not found" });
1388
- return;
1389
- }
1390
- if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
1391
- sendJson(res, 403, { error: "Forbidden" });
1392
- return;
1393
- }
1394
- const query = new URL(url, "http://localhost").searchParams;
1395
- const file = query.get("file");
1396
- const line = Number(query.get("line"));
1397
- const context = Math.min(Math.max(Number(query.get("context") ?? 5) || 0, 0), 50);
1398
- if (!file || !Number.isInteger(line) || line < 1) {
1399
- sendJson(res, 400, { error: "file and a positive integer line are required" });
1400
- return;
1401
- }
1402
- const window = readSourceWindow(sourceRoot, file, line, context);
1403
- if (window === null) {
1404
- sendJson(res, 404, { error: "Not found" });
1405
- return;
1406
- }
1407
- sendJson(res, 200, { ...window });
1408
- return;
1409
- }
1410
- if (req.method === "GET" && url === "/healthz") {
1411
- sendJson(res, 200, {
1412
- ok: true,
1413
- service: DEVTOOLS_IDENTITY,
1414
- version: getVersion(),
1415
- clients: devtools.clientCount
1416
- });
1417
- return;
1418
- }
1419
- if (req.method === "GET" && url === "/v1/traces") {
1420
- if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
1421
- sendJson(res, 403, { error: "Forbidden" });
1422
- return;
1423
- }
1424
- const data = devtools.getCurrentData();
1425
- sendJson(res, 200, {
1426
- traces: data.traces,
1427
- count: data.traces.length
1428
- });
1429
- return;
1430
- }
1431
- if (req.method === "DELETE" && url === "/v1/traces") {
1432
- if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
1433
- sendJson(res, 403, { error: "Forbidden" });
1434
- return;
1435
- }
1436
- devtools.clearData();
1437
- sendJson(res, 200, { cleared: true });
1438
- return;
1439
- }
1440
- if (req.method === "POST" && url === "/v1/traces") {
1441
- try {
1442
- const traces = parseOtlpTraces(await readOtlpPayload(req, "traces"));
1443
- devtools.addTraces(traces);
1444
- sendJson(res, 200, { acceptedTraces: traces.length });
1445
- } catch (e) {
1446
- sendOtlpError(res, req, e);
1447
- }
1448
- return;
1449
- }
1450
- if (req.method === "POST" && url === "/v1/logs") {
1451
- try {
1452
- const payload = await readOtlpPayload(req, "logs");
1453
- const logs = parseOtlpLogs(payload);
1454
- devtools.addLogs(logs);
1455
- devtools.ingestAgentEvents(parseOtlpAgentEvents(payload));
1456
- sendJson(res, 200, { acceptedLogs: logs.length });
1457
- } catch (e) {
1458
- sendOtlpError(res, req, e);
1459
- }
1460
- return;
1461
- }
1462
- if (req.method === "POST" && url === "/v1/metrics") {
1463
- try {
1464
- const payload = await readOtlpPayload(req, "metrics");
1465
- devtools.ingestAgentMetrics(parseOtlpMetrics(payload));
1466
- sendJson(res, 200, { acceptedMetrics: countOtlpMetrics(payload) });
1467
- } catch (e) {
1468
- sendOtlpError(res, req, e);
1469
- }
1470
- return;
1471
- }
1472
- sendJson(res, 404, { error: "Not found" });
1473
- });
1474
- }
1475
- function createDevtoolsHttpServer(devtools, _options = {}) {
1476
- const server = (0, node_http.createServer)();
1477
- attachDevtoolsRoutes(server, devtools);
1478
- return server;
1479
- }
1480
-
1481
- //#endregion
1482
- Object.defineProperty(exports, 'DEVTOOLS_IDENTITY', {
1483
- enumerable: true,
1484
- get: function () {
1485
- return DEVTOOLS_IDENTITY;
1486
- }
1487
- });
1488
- Object.defineProperty(exports, 'DevtoolsServer', {
1489
- enumerable: true,
1490
- get: function () {
1491
- return DevtoolsServer;
1492
- }
1493
- });
1494
- Object.defineProperty(exports, 'ErrorAggregator', {
1495
- enumerable: true,
1496
- get: function () {
1497
- return ErrorAggregator;
1498
- }
1499
- });
1500
- Object.defineProperty(exports, 'allowSensitiveRequest', {
1501
- enumerable: true,
1502
- get: function () {
1503
- return allowSensitiveRequest;
1504
- }
1505
- });
1506
- Object.defineProperty(exports, 'appendManyWithLimit', {
1507
- enumerable: true,
1508
- get: function () {
1509
- return appendManyWithLimit;
1510
- }
1511
- });
1512
- Object.defineProperty(exports, 'appendWithLimit', {
1513
- enumerable: true,
1514
- get: function () {
1515
- return appendWithLimit;
1516
- }
1517
- });
1518
- Object.defineProperty(exports, 'applyTelemetryLimits', {
1519
- enumerable: true,
1520
- get: function () {
1521
- return applyTelemetryLimits;
1522
- }
1523
- });
1524
- Object.defineProperty(exports, 'attachDevtoolsRoutes', {
1525
- enumerable: true,
1526
- get: function () {
1527
- return attachDevtoolsRoutes;
1528
- }
1529
- });
1530
- Object.defineProperty(exports, 'createDevtoolsHttpServer', {
1531
- enumerable: true,
1532
- get: function () {
1533
- return createDevtoolsHttpServer;
1534
- }
1535
- });
1536
- Object.defineProperty(exports, 'decodeOtlpLogsRequest', {
1537
- enumerable: true,
1538
- get: function () {
1539
- return decodeOtlpLogsRequest;
1540
- }
1541
- });
1542
- Object.defineProperty(exports, 'decodeOtlpMetricsRequest', {
1543
- enumerable: true,
1544
- get: function () {
1545
- return decodeOtlpMetricsRequest;
1546
- }
1547
- });
1548
- Object.defineProperty(exports, 'decodeOtlpTraceRequest', {
1549
- enumerable: true,
1550
- get: function () {
1551
- return decodeOtlpTraceRequest;
1552
- }
1553
- });
1554
- Object.defineProperty(exports, 'hostHeaderIsLoopback', {
1555
- enumerable: true,
1556
- get: function () {
1557
- return hostHeaderIsLoopback;
1558
- }
1559
- });
1560
- Object.defineProperty(exports, 'isLoopbackHostname', {
1561
- enumerable: true,
1562
- get: function () {
1563
- return isLoopbackHostname;
1564
- }
1565
- });
1566
- Object.defineProperty(exports, 'isProtobufContentType', {
1567
- enumerable: true,
1568
- get: function () {
1569
- return isProtobufContentType;
1570
- }
1571
- });
1572
- Object.defineProperty(exports, 'originIsLoopback', {
1573
- enumerable: true,
1574
- get: function () {
1575
- return originIsLoopback;
1576
- }
1577
- });
1578
- Object.defineProperty(exports, 'parseOtlpLogs', {
1579
- enumerable: true,
1580
- get: function () {
1581
- return parseOtlpLogs;
1582
- }
1583
- });
1584
- Object.defineProperty(exports, 'parseOtlpTraces', {
1585
- enumerable: true,
1586
- get: function () {
1587
- return parseOtlpTraces;
1588
- }
1589
- });
1590
- Object.defineProperty(exports, 'probePortHolder', {
1591
- enumerable: true,
1592
- get: function () {
1593
- return probePortHolder;
1594
- }
1595
- });
1596
- Object.defineProperty(exports, 'resolveSourceRoot', {
1597
- enumerable: true,
1598
- get: function () {
1599
- return resolveSourceRoot;
1600
- }
1601
- });
1602
- Object.defineProperty(exports, 'resolveTelemetryLimits', {
1603
- enumerable: true,
1604
- get: function () {
1605
- return resolveTelemetryLimits;
1606
- }
1607
- });