@refactorlabs/recount 0.5.5

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.
package/dist/index.js ADDED
@@ -0,0 +1,950 @@
1
+ import { __privateAdd, __privateGet, __privateSet, runWithTrace, getActiveTrace, runWithSpanName, __privateMethod } from './chunk-XKR3GXTH.js';
2
+
3
+ // src/lib/http.ts
4
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
5
+ function inferContentType(ct) {
6
+ if (ct.includes("application/json")) {
7
+ return "json";
8
+ }
9
+ if (ct.includes("application/x-www-form-urlencoded") || ct.includes("multipart/form-data")) {
10
+ return "form";
11
+ }
12
+ if (ct.startsWith("text/")) {
13
+ return "text";
14
+ }
15
+ return null;
16
+ }
17
+ function headersToRecord(headers) {
18
+ const out = {};
19
+ headers.forEach((v, k) => {
20
+ out[k] = v;
21
+ });
22
+ return out;
23
+ }
24
+ function initToRecord(headers) {
25
+ if (!headers) {
26
+ return {};
27
+ }
28
+ if (headers instanceof Headers) {
29
+ return headersToRecord(headers);
30
+ }
31
+ if (Array.isArray(headers)) {
32
+ return Object.fromEntries(headers);
33
+ }
34
+ return { ...headers };
35
+ }
36
+ function parseRequestBody(body, contentType) {
37
+ if (body == null) {
38
+ return null;
39
+ }
40
+ if (body instanceof URLSearchParams) {
41
+ return Object.fromEntries(body);
42
+ }
43
+ if (typeof body !== "string") {
44
+ return null;
45
+ }
46
+ if (contentType === "json") {
47
+ try {
48
+ return JSON.parse(body);
49
+ } catch {
50
+ return body;
51
+ }
52
+ }
53
+ if (contentType === "form") {
54
+ return Object.fromEntries(new URLSearchParams(body));
55
+ }
56
+ return body;
57
+ }
58
+ async function parseResponseBody(response, contentType) {
59
+ if (contentType === "json") {
60
+ try {
61
+ return await response.json();
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ if (contentType === "text" || contentType === "form") {
67
+ return response.text();
68
+ }
69
+ return null;
70
+ }
71
+ async function executeFetch(url, init2, recordSpan) {
72
+ const method = init2?.method?.toUpperCase() ?? "GET";
73
+ const reqHeaders = initToRecord(init2?.headers);
74
+ const reqContentType = inferContentType(
75
+ reqHeaders["content-type"] ?? reqHeaders["Content-Type"] ?? ""
76
+ );
77
+ const reqBody = parseRequestBody(init2?.body, reqContentType);
78
+ const start = Date.now();
79
+ const response = await globalThis.fetch(url, init2);
80
+ const durationMs = Date.now() - start;
81
+ const resContentType = inferContentType(
82
+ response.headers.get("content-type") ?? ""
83
+ );
84
+ const resBody = await parseResponseBody(response, resContentType);
85
+ recordSpan(
86
+ {
87
+ method: HTTP_METHODS.has(method) ? method : "GET",
88
+ url: url.toString(),
89
+ headers: reqHeaders,
90
+ content_type: reqContentType,
91
+ body: reqBody
92
+ },
93
+ {
94
+ status: response.status,
95
+ headers: headersToRecord(response.headers),
96
+ content_type: resContentType,
97
+ body: resBody
98
+ },
99
+ durationMs
100
+ );
101
+ return resBody;
102
+ }
103
+
104
+ // src/lib/redact.ts
105
+ var REDACTED = { __redacted: true };
106
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
107
+ "authorization",
108
+ "cookie",
109
+ "set-cookie",
110
+ "x-api-key",
111
+ "x-auth-token",
112
+ "x-api-secret",
113
+ "x-access-token",
114
+ "proxy-authorization"
115
+ ]);
116
+ function redactHeaders(headers) {
117
+ return Object.fromEntries(
118
+ Object.entries(headers).map(
119
+ ([k, v]) => SENSITIVE_HEADERS.has(k.toLowerCase()) ? [k, REDACTED] : [k, v]
120
+ )
121
+ );
122
+ }
123
+ function redactAt(obj, paths, currentPath) {
124
+ if (Array.isArray(obj)) {
125
+ return obj.map((item) => redactAt(item, paths, currentPath));
126
+ }
127
+ if (obj !== null && typeof obj === "object") {
128
+ return Object.fromEntries(
129
+ Object.entries(obj).map(([k, v]) => {
130
+ const childPath = [...currentPath, k.toLowerCase()];
131
+ const matches = paths.some(
132
+ (p) => p.length === childPath.length && p.every((seg, i) => seg === childPath[i])
133
+ );
134
+ if (matches) {
135
+ return [k, REDACTED];
136
+ }
137
+ return [k, redactAt(v, paths, childPath)];
138
+ })
139
+ );
140
+ }
141
+ return obj;
142
+ }
143
+ function redactObject(obj, fields) {
144
+ if (fields.length === 0) return obj;
145
+ const paths = fields.map((f) => f.toLowerCase().split("."));
146
+ return redactAt(obj, paths, []);
147
+ }
148
+
149
+ // src/trace.ts
150
+ var NOOP_RESULT = { traceId: "" };
151
+ function reservoirSample(items, k) {
152
+ if (k >= items.length) return items.slice();
153
+ const indexed = items.map((item, i) => ({ item, i, key: Math.random() }));
154
+ indexed.sort((a, b) => b.key - a.key);
155
+ return indexed.slice(0, k).sort((a, b) => a.i - b.i).map(({ item }) => item);
156
+ }
157
+ var _buffer;
158
+ var SpanGroup = class {
159
+ constructor() {
160
+ __privateAdd(this, _buffer, []);
161
+ }
162
+ span(type, name, options) {
163
+ __privateGet(this, _buffer).push({ type, name, opts: options });
164
+ return this;
165
+ }
166
+ addMessage(name, text, opts) {
167
+ return this.span("message", name, { text, ...opts });
168
+ }
169
+ _flush(push, options) {
170
+ const { limit, sample, sampleThreshold } = options ?? {};
171
+ let items = __privateGet(this, _buffer).filter(
172
+ ({ type, opts }) => type === "group" || type === "message" || opts?.input !== void 0 || opts?.output !== void 0
173
+ );
174
+ if (sample !== void 0) {
175
+ const threshold = sampleThreshold ?? sample;
176
+ if (items.length > threshold) {
177
+ items = reservoirSample(items, sample);
178
+ }
179
+ } else if (limit !== void 0) {
180
+ items = items.slice(0, limit);
181
+ }
182
+ for (const { type, name, opts } of items) {
183
+ push(type, name, opts);
184
+ }
185
+ }
186
+ };
187
+ _buffer = new WeakMap();
188
+ var _client, _name, _options, _spans, _startTime, _disabled, _log, _metadata, _environment, _Trace_instances, pushSpan_fn, applyRedaction_fn;
189
+ var Trace = class {
190
+ constructor(client, name, options = {}, disabled = false, log = () => {
191
+ }) {
192
+ __privateAdd(this, _Trace_instances);
193
+ __privateAdd(this, _client);
194
+ __privateAdd(this, _name);
195
+ __privateAdd(this, _options);
196
+ __privateAdd(this, _spans, []);
197
+ __privateAdd(this, _startTime);
198
+ __privateAdd(this, _disabled);
199
+ __privateAdd(this, _log);
200
+ __privateAdd(this, _metadata);
201
+ __privateAdd(this, _environment);
202
+ __privateSet(this, _client, client);
203
+ __privateSet(this, _name, name);
204
+ __privateSet(this, _options, options);
205
+ __privateSet(this, _startTime, Date.now());
206
+ __privateSet(this, _disabled, disabled);
207
+ __privateSet(this, _log, log);
208
+ __privateSet(this, _metadata, { ...options.metadata });
209
+ __privateSet(this, _environment, options.environment);
210
+ }
211
+ span(type, name, options) {
212
+ if (!__privateGet(this, _disabled)) {
213
+ __privateMethod(this, _Trace_instances, pushSpan_fn).call(this, type, name, options);
214
+ }
215
+ return this;
216
+ }
217
+ group(name, builder, options) {
218
+ if (!__privateGet(this, _disabled)) {
219
+ const groupOrder = __privateGet(this, _spans).length;
220
+ __privateGet(this, _log).call(this, `span type=group name=${name}`);
221
+ const g = new SpanGroup();
222
+ try {
223
+ builder(g);
224
+ } catch {
225
+ }
226
+ __privateGet(this, _spans).push({
227
+ type: "group",
228
+ name,
229
+ order: groupOrder,
230
+ ...options?.description !== void 0 && {
231
+ description: options.description
232
+ }
233
+ });
234
+ const spanCountBeforeFlush = __privateGet(this, _spans).length;
235
+ g._flush(
236
+ (type, spanName, opts) => __privateMethod(this, _Trace_instances, pushSpan_fn).call(this, type, spanName, opts, groupOrder),
237
+ options
238
+ );
239
+ if (__privateGet(this, _spans).length === spanCountBeforeFlush) {
240
+ __privateGet(this, _spans).splice(groupOrder, 1);
241
+ __privateGet(this, _log).call(this, `span type=group name=${name} dropped (no children)`);
242
+ }
243
+ }
244
+ return this;
245
+ }
246
+ addMessage(name, text, opts) {
247
+ return this.span("message", name, { text, ...opts });
248
+ }
249
+ addMetadata(data) {
250
+ Object.assign(__privateGet(this, _metadata), data);
251
+ return this;
252
+ }
253
+ setEnvironment(environment) {
254
+ __privateSet(this, _environment, environment);
255
+ return this;
256
+ }
257
+ fetch(name, url, init2, options) {
258
+ return executeFetch(url, init2, (input, output, durationMs) => {
259
+ this.span("http", name, {
260
+ input,
261
+ output,
262
+ durationMs,
263
+ redact: options?.redact
264
+ });
265
+ });
266
+ }
267
+ async end() {
268
+ if (__privateGet(this, _disabled)) {
269
+ return NOOP_RESULT;
270
+ }
271
+ if (__privateGet(this, _spans).length === 0) {
272
+ __privateGet(this, _log).call(this, "end: no spans, skipping ingest");
273
+ return NOOP_RESULT;
274
+ }
275
+ try {
276
+ return await __privateGet(this, _client).ingest({
277
+ ...__privateGet(this, _options),
278
+ name: __privateGet(this, _name),
279
+ environment: __privateGet(this, _environment),
280
+ durationMs: Date.now() - __privateGet(this, _startTime),
281
+ spans: __privateGet(this, _spans),
282
+ metadata: Object.keys(__privateGet(this, _metadata)).length > 0 ? __privateGet(this, _metadata) : void 0
283
+ });
284
+ } catch (err) {
285
+ __privateGet(this, _log).call(this, `ingest error: ${err instanceof Error ? err.message : String(err)}`);
286
+ return NOOP_RESULT;
287
+ }
288
+ }
289
+ };
290
+ _client = new WeakMap();
291
+ _name = new WeakMap();
292
+ _options = new WeakMap();
293
+ _spans = new WeakMap();
294
+ _startTime = new WeakMap();
295
+ _disabled = new WeakMap();
296
+ _log = new WeakMap();
297
+ _metadata = new WeakMap();
298
+ _environment = new WeakMap();
299
+ _Trace_instances = new WeakSet();
300
+ pushSpan_fn = function(type, name, options, parentOrder) {
301
+ if (type !== "group" && type !== "message") {
302
+ if (options?.input === void 0 && options?.output === void 0) {
303
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (no input or output)`);
304
+ return;
305
+ }
306
+ }
307
+ if (type === "message") {
308
+ __privateGet(this, _spans).push({
309
+ type: "message",
310
+ name,
311
+ ...options?.text !== void 0 && { text: options.text },
312
+ level: options?.level ?? "info",
313
+ order: __privateGet(this, _spans).length,
314
+ ...parentOrder !== void 0 && { parentOrder },
315
+ ...options?.description !== void 0 && {
316
+ description: options.description
317
+ },
318
+ ...options?.alerts && { alerts: options.alerts },
319
+ ...options?.durationMs !== void 0 && {
320
+ durationMs: options.durationMs
321
+ },
322
+ ...options?.public !== void 0 && { public: options.public }
323
+ });
324
+ } else {
325
+ __privateGet(this, _spans).push({
326
+ type,
327
+ name,
328
+ order: __privateGet(this, _spans).length,
329
+ ...parentOrder !== void 0 && { parentOrder },
330
+ ...__privateMethod(this, _Trace_instances, applyRedaction_fn).call(this, type, options)
331
+ });
332
+ }
333
+ __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
334
+ };
335
+ applyRedaction_fn = function(type, options) {
336
+ if (!options) return {};
337
+ const { redact, redactParams, ...rest } = options;
338
+ let { input, output } = rest;
339
+ if (type === "http") {
340
+ if (input && typeof input === "object" && !Array.isArray(input)) {
341
+ const inp = input;
342
+ if (inp.headers && typeof inp.headers === "object") {
343
+ input = {
344
+ ...inp,
345
+ headers: redactHeaders(inp.headers)
346
+ };
347
+ }
348
+ }
349
+ if (output && typeof output === "object" && !Array.isArray(output)) {
350
+ const out = output;
351
+ if (out.headers && typeof out.headers === "object") {
352
+ output = {
353
+ ...out,
354
+ headers: redactHeaders(out.headers)
355
+ };
356
+ }
357
+ }
358
+ }
359
+ if (redact && redact.length > 0) {
360
+ input = input != null ? redactObject(input, redact) : input;
361
+ output = output != null ? redactObject(output, redact) : output;
362
+ }
363
+ if (redactParams?.length && input != null && !Array.isArray(input)) {
364
+ const inp = input;
365
+ if (Array.isArray(inp.params)) {
366
+ input = {
367
+ ...inp,
368
+ params: inp.params.map(
369
+ (p) => redactParams.includes(p) ? REDACTED : p
370
+ )
371
+ };
372
+ }
373
+ }
374
+ return { ...rest, input, output };
375
+ };
376
+
377
+ // src/lib/error.ts
378
+ var RecountError = class extends Error {
379
+ constructor(status, message) {
380
+ super(message);
381
+ this.name = "RecountError";
382
+ this.status = status;
383
+ }
384
+ };
385
+
386
+ // src/client.ts
387
+ var DEFAULT_API_URL = "https://api.recount.refactor.gg";
388
+ var NOOP_RESULT2 = { traceId: "" };
389
+ var MAX_RETRIES = 2;
390
+ var BASE_RETRY_MS = 1e3;
391
+ var MAX_RETRY_DELAY_MS = 6e4;
392
+ function retryDelayMs(res, attempt) {
393
+ const header = res.headers.get("retry-after");
394
+ if (header) {
395
+ const seconds = Number(header);
396
+ if (!isNaN(seconds))
397
+ return Math.min(MAX_RETRY_DELAY_MS, Math.max(0, seconds * 1e3));
398
+ const date = Date.parse(header);
399
+ if (!isNaN(date))
400
+ return Math.min(MAX_RETRY_DELAY_MS, Math.max(0, date - Date.now()));
401
+ }
402
+ return BASE_RETRY_MS * 2 ** (attempt - 1);
403
+ }
404
+ var _apiKey, _apiUrl, _environment2, _disabled2, _log2;
405
+ var Recount = class {
406
+ constructor(options = {}) {
407
+ __privateAdd(this, _apiKey);
408
+ __privateAdd(this, _apiUrl);
409
+ __privateAdd(this, _environment2);
410
+ __privateAdd(this, _disabled2);
411
+ __privateAdd(this, _log2);
412
+ const debug = options.debug ?? !!process.env.RECOUNT_DEBUG;
413
+ __privateSet(this, _log2, debug ? (msg) => console.log(`[recount] ${msg}`) : () => {
414
+ });
415
+ const apiKey = options.apiKey ?? process.env.RECOUNT_API_KEY;
416
+ if (!apiKey) {
417
+ console.warn("Recount: no API key found - tracing disabled.");
418
+ __privateSet(this, _disabled2, true);
419
+ __privateSet(this, _apiKey, "");
420
+ __privateSet(this, _apiUrl, "");
421
+ __privateSet(this, _environment2, void 0);
422
+ return;
423
+ }
424
+ __privateSet(this, _disabled2, false);
425
+ __privateSet(this, _apiKey, apiKey);
426
+ __privateSet(this, _apiUrl, options.apiUrl ?? process.env.RECOUNT_API_URL ?? DEFAULT_API_URL);
427
+ __privateSet(this, _environment2, options.environment ?? process.env.RECOUNT_ENVIRONMENT ?? void 0);
428
+ const masked = __privateGet(this, _apiKey).length > 8 ? `${__privateGet(this, _apiKey).slice(0, 4)}...` : "[redacted]";
429
+ __privateGet(this, _log2).call(this, `initialized url=${__privateGet(this, _apiUrl)} key=${masked}`);
430
+ }
431
+ startTrace(name, options = {}) {
432
+ __privateGet(this, _log2).call(this, `trace started name=${name}`);
433
+ const traceOptions = __privateGet(this, _environment2) !== void 0 && options.environment === void 0 ? { environment: __privateGet(this, _environment2), ...options } : options;
434
+ return new Trace(this, name, traceOptions, __privateGet(this, _disabled2), __privateGet(this, _log2));
435
+ }
436
+ async ingest(payload) {
437
+ if (__privateGet(this, _disabled2)) {
438
+ return NOOP_RESULT2;
439
+ }
440
+ if (!payload.spans.length) {
441
+ console.warn("Recount: trace has no spans and will not be ingested.");
442
+ return NOOP_RESULT2;
443
+ }
444
+ __privateGet(this, _log2).call(this, `ingest name=${payload.name} spans=${payload.spans.length}`);
445
+ let body;
446
+ try {
447
+ body = JSON.stringify(payload);
448
+ } catch (err) {
449
+ __privateGet(this, _log2).call(this, `ingest serialize error: ${err instanceof Error ? err.message : String(err)}`);
450
+ return NOOP_RESULT2;
451
+ }
452
+ const headers = {
453
+ "Content-Type": "application/json",
454
+ "x-api-key": __privateGet(this, _apiKey)
455
+ };
456
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
457
+ try {
458
+ const res = await globalThis.fetch(`${__privateGet(this, _apiUrl)}/ingest`, {
459
+ method: "POST",
460
+ headers,
461
+ body
462
+ });
463
+ if (res.status === 429 && attempt < MAX_RETRIES) {
464
+ const delay = retryDelayMs(res, attempt + 1);
465
+ __privateGet(this, _log2).call(this, `429 rate limited attempt=${attempt + 1}/${MAX_RETRIES + 1} retrying in ${delay}ms`);
466
+ await res.body?.cancel().catch(() => {
467
+ });
468
+ await new Promise((r) => setTimeout(r, delay));
469
+ continue;
470
+ }
471
+ if (!res.ok) {
472
+ const text = await res.text().catch(() => res.statusText);
473
+ __privateGet(this, _log2).call(this, `ingest error status=${res.status} message=${text}`);
474
+ return NOOP_RESULT2;
475
+ }
476
+ const json = await res.json();
477
+ __privateGet(this, _log2).call(this, `ingested traceId=${json.data.trace.id}`);
478
+ return { traceId: json.data.trace.id };
479
+ } catch (err) {
480
+ __privateGet(this, _log2).call(this, `ingest failed (network error): ${err instanceof Error ? err.message : String(err)}`);
481
+ return NOOP_RESULT2;
482
+ }
483
+ }
484
+ return NOOP_RESULT2;
485
+ }
486
+ };
487
+ _apiKey = new WeakMap();
488
+ _apiUrl = new WeakMap();
489
+ _environment2 = new WeakMap();
490
+ _disabled2 = new WeakMap();
491
+ _log2 = new WeakMap();
492
+
493
+ // src/lib/table.ts
494
+ function spanCell(value, span) {
495
+ return { __cellSpan: true, span, value };
496
+ }
497
+ function roundValue(value, decimals) {
498
+ if (typeof value === "number") {
499
+ return +value.toFixed(decimals);
500
+ }
501
+ return value;
502
+ }
503
+ var TableBuilder = class {
504
+ constructor(title) {
505
+ this._rawKeys = [];
506
+ this._rawRows = [];
507
+ this._labels = {};
508
+ this._valueTransforms = {};
509
+ this._columnSpans = {};
510
+ this._columnHighlights = {};
511
+ this._cellHighlightFns = {};
512
+ this._extraRows = [];
513
+ this._redactFields = /* @__PURE__ */ new Set();
514
+ this._title = title;
515
+ }
516
+ redact(fields) {
517
+ this._redactFields = new Set(fields.map((f) => f.toLowerCase()));
518
+ return this;
519
+ }
520
+ _shouldRedact(key) {
521
+ return this._redactFields.has(key.toLowerCase());
522
+ }
523
+ fromObject(data) {
524
+ if (data == null || typeof data !== "object" || Array.isArray(data)) {
525
+ if (process.env.RECOUNT_DEBUG) {
526
+ console.log("[recount] table: fromObject expects a plain object");
527
+ }
528
+ return this;
529
+ }
530
+ this._source = "object";
531
+ this._rawKeys = Object.keys(data);
532
+ this._rawRows = Object.entries(data).map(([k, v]) => [k, v]);
533
+ return this;
534
+ }
535
+ fromRecords(data) {
536
+ this._source = "records";
537
+ if (!Array.isArray(data) || data.length === 0) {
538
+ this._rawKeys = [];
539
+ this._rawRows = [];
540
+ return this;
541
+ }
542
+ const first = data[0];
543
+ if (first == null || typeof first !== "object") {
544
+ if (process.env.RECOUNT_DEBUG) {
545
+ console.log("[recount] table: fromRecords expects an array of objects");
546
+ }
547
+ this._rawKeys = [];
548
+ this._rawRows = [];
549
+ return this;
550
+ }
551
+ this._rawKeys = Object.keys(first);
552
+ this._rawRows = data.filter((r) => r != null && typeof r === "object").map((r) => this._rawKeys.map((k) => r[k]));
553
+ return this;
554
+ }
555
+ pick(...keys) {
556
+ this._pick = keys;
557
+ return this;
558
+ }
559
+ label(map) {
560
+ Object.assign(this._labels, map);
561
+ return this;
562
+ }
563
+ round(decimals) {
564
+ this._round = decimals;
565
+ return this;
566
+ }
567
+ transformValues(map) {
568
+ Object.assign(this._valueTransforms, map);
569
+ return this;
570
+ }
571
+ spanColumn(key, span) {
572
+ this._columnSpans[key] = span;
573
+ return this;
574
+ }
575
+ highlightColumn(key, highlight) {
576
+ this._columnHighlights[key] = highlight;
577
+ return this;
578
+ }
579
+ highlightRows(fn) {
580
+ this._rowHighlightFn = fn;
581
+ return this;
582
+ }
583
+ highlightCells(key, fn) {
584
+ this._cellHighlightFns[key] = fn;
585
+ return this;
586
+ }
587
+ appendRow(cells, highlight) {
588
+ this._extraRows.push({ cells, ...highlight && { highlight } });
589
+ return this;
590
+ }
591
+ summary(stats) {
592
+ this._summary = stats;
593
+ return this;
594
+ }
595
+ build() {
596
+ return this._build();
597
+ }
598
+ buildSection() {
599
+ const result = this._build();
600
+ return {
601
+ ...result.title !== void 0 && { title: result.title },
602
+ rows: result.rows,
603
+ ...result.rowHighlights && { rowHighlights: result.rowHighlights },
604
+ ...result.cellHighlights && { cellHighlights: result.cellHighlights },
605
+ ...result.summary && { summary: result.summary }
606
+ };
607
+ }
608
+ _build() {
609
+ try {
610
+ if (!this._source) {
611
+ if (process.env.RECOUNT_DEBUG) {
612
+ console.log(
613
+ "[recount] table: call fromObject() or fromRecords() before build()"
614
+ );
615
+ }
616
+ return { columns: [], rows: [] };
617
+ }
618
+ if (this._source === "object") {
619
+ return this._buildFromObject();
620
+ }
621
+ return this._buildFromRecords();
622
+ } catch {
623
+ if (process.env.RECOUNT_DEBUG) {
624
+ console.log("[recount] table: build() encountered an unexpected error");
625
+ }
626
+ return { columns: [], rows: [] };
627
+ }
628
+ }
629
+ _resolveLabel(key) {
630
+ return this._labels[key] ?? key;
631
+ }
632
+ _resolveColumn(key, label) {
633
+ const span = this._columnSpans[key];
634
+ const highlight = this._columnHighlights[key];
635
+ if (span !== void 0 || highlight !== void 0) {
636
+ return {
637
+ label,
638
+ ...span !== void 0 && { span },
639
+ ...highlight !== void 0 && { highlight }
640
+ };
641
+ }
642
+ return label;
643
+ }
644
+ _mergeRowHighlights(highlights, rowCount) {
645
+ if (!highlights && !this._extraRows.some((r) => r.highlight))
646
+ return void 0;
647
+ return [
648
+ ...highlights ?? Array(rowCount).fill(null),
649
+ ...this._extraRows.map((r) => r.highlight ?? null)
650
+ ];
651
+ }
652
+ _buildRowHighlights(activeKeys) {
653
+ if (!this._rowHighlightFn) {
654
+ return void 0;
655
+ }
656
+ const keyToIndex = new Map(this._rawKeys.map((k, i) => [k, i]));
657
+ return this._rawRows.map((row) => {
658
+ const obj = Object.fromEntries(
659
+ activeKeys.map((k) => [k, row[keyToIndex.get(k)]])
660
+ );
661
+ return this._rowHighlightFn(obj);
662
+ });
663
+ }
664
+ _buildFromObject() {
665
+ const pick = this._pick ? new Set(this._pick) : null;
666
+ let rows = this._rawRows.filter(([k]) => !pick || pick.has(k));
667
+ if (pick) {
668
+ const order = this._pick;
669
+ rows = order.filter((k) => rows.some(([rk]) => rk === k)).map((k) => rows.find(([rk]) => rk === k));
670
+ }
671
+ const finalRows = rows.map(([k, v]) => {
672
+ const key = k;
673
+ if (this._shouldRedact(key)) {
674
+ return [this._resolveLabel(key), REDACTED];
675
+ }
676
+ const transformed = this._valueTransforms[key] ? this._valueTransforms[key](v) : v;
677
+ return [
678
+ this._resolveLabel(key),
679
+ this._round !== void 0 ? roundValue(transformed, this._round) : transformed
680
+ ];
681
+ });
682
+ const allRows = this._extraRows.length ? [...finalRows, ...this._extraRows.map((r) => r.cells)] : finalRows;
683
+ const rowHighlights = this._rowHighlightFn ? rows.map(([k, v]) => this._rowHighlightFn({ [k]: v })) : void 0;
684
+ const allRowHighlights = this._mergeRowHighlights(
685
+ rowHighlights,
686
+ finalRows.length
687
+ );
688
+ return {
689
+ title: this._title,
690
+ columns: ["Key", "Value"],
691
+ rows: allRows,
692
+ ...allRowHighlights && { rowHighlights: allRowHighlights },
693
+ ...this._summary && { summary: this._summary }
694
+ };
695
+ }
696
+ _buildFromRecords() {
697
+ const activeKeys = this._pick ?? this._rawKeys;
698
+ const columns = activeKeys.map(
699
+ (k) => this._resolveColumn(k, this._resolveLabel(k))
700
+ );
701
+ const keyToIndex = new Map(this._rawKeys.map((k, i) => [k, i]));
702
+ const rows = this._rawRows.map(
703
+ (row) => activeKeys.map((k) => {
704
+ if (this._shouldRedact(k)) return REDACTED;
705
+ const raw = row[keyToIndex.get(k)];
706
+ const value = this._valueTransforms[k] ? this._valueTransforms[k](raw) : raw;
707
+ return this._round !== void 0 ? roundValue(value, this._round) : value;
708
+ })
709
+ );
710
+ const rowHighlights = this._buildRowHighlights(activeKeys);
711
+ const hasCellFns = Object.keys(this._cellHighlightFns).length > 0;
712
+ const cellHighlights = hasCellFns ? rows.map(
713
+ (row) => activeKeys.map(
714
+ (k, j) => this._cellHighlightFns[k] ? this._cellHighlightFns[k](row[j]) : null
715
+ )
716
+ ) : void 0;
717
+ const allRows = this._extraRows.length ? [...rows, ...this._extraRows.map((r) => r.cells)] : rows;
718
+ const allRowHighlights = this._mergeRowHighlights(
719
+ rowHighlights,
720
+ rows.length
721
+ );
722
+ const allCellHighlights = cellHighlights ? [...cellHighlights, ...this._extraRows.map(() => [])] : void 0;
723
+ return {
724
+ title: this._title,
725
+ columns,
726
+ rows: allRows,
727
+ ...allRowHighlights && { rowHighlights: allRowHighlights },
728
+ ...allCellHighlights && { cellHighlights: allCellHighlights },
729
+ ...this._summary && { summary: this._summary }
730
+ };
731
+ }
732
+ };
733
+ function table(title) {
734
+ return new TableBuilder(title);
735
+ }
736
+ function tableFromObject({
737
+ title,
738
+ data
739
+ }) {
740
+ return table(title).fromObject(data).build();
741
+ }
742
+ function tableFromRecords({
743
+ title,
744
+ data
745
+ }) {
746
+ return table(title).fromRecords(data).build();
747
+ }
748
+ function isTableBuilderLike(s) {
749
+ return typeof s.buildSection === "function";
750
+ }
751
+ function tableSections({
752
+ title,
753
+ columns,
754
+ sections
755
+ }) {
756
+ let resolvedColumns = columns;
757
+ let cachedFirst;
758
+ if (!resolvedColumns) {
759
+ const first = sections[0];
760
+ if (isTableBuilderLike(first)) {
761
+ const built = first.build();
762
+ resolvedColumns = built.columns;
763
+ cachedFirst = {
764
+ ...built.title !== void 0 && { title: built.title },
765
+ rows: built.rows,
766
+ ...built.rowHighlights && { rowHighlights: built.rowHighlights },
767
+ ...built.cellHighlights && { cellHighlights: built.cellHighlights },
768
+ ...built.summary && { summary: built.summary }
769
+ };
770
+ } else {
771
+ throw new Error(
772
+ "tableSections: columns is required when sections are plain objects"
773
+ );
774
+ }
775
+ }
776
+ const resolved = sections.map((s, i) => {
777
+ if (i === 0 && cachedFirst !== void 0) return cachedFirst;
778
+ return isTableBuilderLike(s) ? s.buildSection() : s;
779
+ });
780
+ return {
781
+ ...title !== void 0 && { title },
782
+ columns: resolvedColumns,
783
+ sections: resolved
784
+ };
785
+ }
786
+
787
+ // src/lib/chart.ts
788
+ var ChartBuilder = class {
789
+ constructor(type, title) {
790
+ this._labels = [];
791
+ this._series = [];
792
+ this._referenceLines = [];
793
+ this._type = type;
794
+ this._title = title;
795
+ }
796
+ labels(labels) {
797
+ this._labels = labels;
798
+ return this;
799
+ }
800
+ series(nameOrData, data) {
801
+ if (typeof nameOrData === "string") {
802
+ this._series.push({ name: nameOrData, data });
803
+ } else {
804
+ this._series.push({ data: nameOrData });
805
+ }
806
+ return this;
807
+ }
808
+ fromRecords(data, labelKey, seriesKeys) {
809
+ this._labels = data.map((r) => String(r[labelKey]));
810
+ this._series = seriesKeys.map((k) => ({
811
+ name: String(k),
812
+ data: data.map((r) => Number(r[k]))
813
+ }));
814
+ return this;
815
+ }
816
+ referenceLine(value, label) {
817
+ this._referenceLines.push({ value, label });
818
+ return this;
819
+ }
820
+ build() {
821
+ return this._build();
822
+ }
823
+ _build() {
824
+ return {
825
+ title: this._title,
826
+ type: this._type,
827
+ labels: this._labels,
828
+ series: this._series,
829
+ ...this._referenceLines.length > 0 && {
830
+ referenceLines: this._referenceLines
831
+ }
832
+ };
833
+ }
834
+ };
835
+ function chart(type, title) {
836
+ return new ChartBuilder(type, title);
837
+ }
838
+ function chartFromRecords({
839
+ type,
840
+ title,
841
+ data,
842
+ labelKey,
843
+ seriesKeys
844
+ }) {
845
+ return chart(type, title).fromRecords(data, labelKey, seriesKeys).build();
846
+ }
847
+
848
+ // src/index.ts
849
+ var _client2;
850
+ function getClient() {
851
+ if (!_client2) {
852
+ _client2 = new Recount();
853
+ }
854
+ return _client2;
855
+ }
856
+ function init(options = {}) {
857
+ _client2 = new Recount(options);
858
+ }
859
+ async function startTrace(name, optionsOrFn, fn) {
860
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
861
+ const callback = typeof optionsOrFn === "function" ? optionsOrFn : fn;
862
+ const trace = getClient().startTrace(name, options);
863
+ try {
864
+ return await runWithTrace(trace, callback);
865
+ } finally {
866
+ await trace.end();
867
+ }
868
+ }
869
+ function addSpan(type, name, a, b) {
870
+ if (typeof a === "function") {
871
+ return runSpanCallback(type, name, {}, a);
872
+ }
873
+ if (typeof b === "function") {
874
+ return runSpanCallback(type, name, a ?? {}, b);
875
+ }
876
+ getActiveTrace()?.span(type, name, a ?? {});
877
+ }
878
+ async function runSpanCallback(type, name, opts, fn) {
879
+ const { input, ...spanOpts } = opts;
880
+ const start = Date.now();
881
+ try {
882
+ const result = await fn();
883
+ getActiveTrace()?.span(type, name, {
884
+ ...spanOpts,
885
+ ...input != null ? { input } : {},
886
+ output: result != null ? result : void 0,
887
+ durationMs: Date.now() - start
888
+ });
889
+ return result;
890
+ } catch (err) {
891
+ getActiveTrace()?.span(type, name, {
892
+ ...spanOpts,
893
+ ...input != null ? { input } : {},
894
+ durationMs: Date.now() - start
895
+ });
896
+ throw err;
897
+ }
898
+ }
899
+ function addGroup(name, builder, options) {
900
+ getActiveTrace()?.group(name, builder, options);
901
+ }
902
+ function addMessage(name, text, opts) {
903
+ getActiveTrace()?.addMessage(name, text, opts);
904
+ }
905
+ function named(name, fn) {
906
+ return runWithSpanName(name, fn);
907
+ }
908
+ function addMetadata(data) {
909
+ getActiveTrace()?.addMetadata(data);
910
+ }
911
+ function fetch(name, url, init2, options) {
912
+ const active = getActiveTrace();
913
+ return executeFetch(url, init2, (input, output, durationMs) => {
914
+ active?.span("http", name, {
915
+ input,
916
+ output,
917
+ durationMs,
918
+ redact: options?.redact
919
+ });
920
+ });
921
+ }
922
+ var recount = {
923
+ // SDK lifecycle
924
+ init,
925
+ Recount,
926
+ RecountError,
927
+ // Tracing
928
+ startTrace,
929
+ named,
930
+ addSpan,
931
+ addGroup,
932
+ addMessage,
933
+ addMetadata,
934
+ fetch,
935
+ // Builders
936
+ table,
937
+ tableFromObject,
938
+ tableFromRecords,
939
+ tableSections,
940
+ spanCell,
941
+ chart,
942
+ chartFromRecords,
943
+ // Constants & sentinels
944
+ REDACTED
945
+ };
946
+ var index_default = recount;
947
+
948
+ export { SpanGroup, index_default as default };
949
+ //# sourceMappingURL=index.js.map
950
+ //# sourceMappingURL=index.js.map