@intellectual-frontiers/telemetry 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/otel.js ADDED
@@ -0,0 +1,686 @@
1
+ // Spec: 0001-telemetry FR-001
2
+ /**
3
+ * The OpenTelemetry data model, written from the OpenTelemetry specification itself (commons 0001-telemetry FR-001 to FR-008): attribute
4
+ * values and log bodies, trace and span ids as brands made only from bytes the caller gives (the kernel has no randomness of its own), W3C
5
+ * Trace Context Level 2 `traceparent` and `tracestate`, resources, scopes, finished spans, log records and metric points, the
6
+ * configuration read from the `OTEL_*` environment variables (given as a record: the kernel reads no environment), redaction of what must
7
+ * never leave a process, the attribute, event and link limits, and the samplers OpenTelemetry names.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { formatTraceparent, parseTraceparent, redactUrl, resolveConfig } from "./otel.ts";
12
+ * const parent = parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
13
+ * if (parent.kind === "ok") formatTraceparent(parent.value); // the same header back
14
+ * redactUrl("https://user:pw@host/x?token=abc&page=2"); // "https://REDACTED:REDACTED@host/x?token=REDACTED&page=2"
15
+ * resolveConfig({ OTEL_SERVICE_NAME: "build" }).config.resource; // { "service.name": "build" }
16
+ * ```
17
+ *
18
+ * @module
19
+ */
20
+ import { absurd, err, ok } from "@intellectual-frontiers/core";
21
+ import { fromBase64 } from "@intellectual-frontiers/formats/base64";
22
+ import { toHex } from "@intellectual-frontiers/formats/hex";
23
+ const TRACE_ID = /^[0-9a-f]{32}$/;
24
+ const SPAN_ID = /^[0-9a-f]{16}$/;
25
+ const ZEROS = /^0+$/;
26
+ /** A trace id from 16 bytes a caller gives (`traceIdFrom(random(16))`); other lengths and all zeros are refused (FR-002). */
27
+ export function traceIdFrom(bytes) {
28
+ if (bytes.length !== 16)
29
+ return err(`a trace id is 16 bytes, not ${bytes.length}`);
30
+ return parseTraceId(toHex(bytes));
31
+ }
32
+ /** A span id from 8 bytes a caller gives (`spanIdFrom(random(8))`); other lengths and all zeros are refused (FR-002). */
33
+ export function spanIdFrom(bytes) {
34
+ if (bytes.length !== 8)
35
+ return err(`a span id is 8 bytes, not ${bytes.length}`);
36
+ return parseSpanId(toHex(bytes));
37
+ }
38
+ /** A trace id from its text: 32 lower-case hexadecimal digits, not all zeros. */
39
+ export function parseTraceId(text) {
40
+ if (!TRACE_ID.test(text))
41
+ return err("a trace id is 32 lower-case hexadecimal digits");
42
+ if (ZEROS.test(text))
43
+ return err("a trace id of all zeros is not valid");
44
+ // The one place a TraceId is made, after its validation.
45
+ return ok(text);
46
+ }
47
+ /** A span id from its text: 16 lower-case hexadecimal digits, not all zeros. */
48
+ export function parseSpanId(text) {
49
+ if (!SPAN_ID.test(text))
50
+ return err("a span id is 16 lower-case hexadecimal digits");
51
+ if (ZEROS.test(text))
52
+ return err("a span id of all zeros is not valid");
53
+ // The one place a SpanId is made, after its validation.
54
+ return ok(text);
55
+ }
56
+ /** The `sampled` trace flag. */
57
+ export const SAMPLED = 0x01;
58
+ /** The `random` trace flag of Level 2: the trace id's right-most 7 bytes are random. */
59
+ export const RANDOM = 0x02;
60
+ /** The trace flags this version of Trace Context defines; the others are written as zero. */
61
+ const KNOWN_FLAGS = SAMPLED | RANDOM;
62
+ /** The most members a `tracestate` keeps. */
63
+ export const TRACESTATE_MAX_MEMBERS = 32;
64
+ /** Whether a context's `sampled` flag is set. */
65
+ export function isSampled(context) {
66
+ return (context.traceFlags & SAMPLED) === SAMPLED;
67
+ }
68
+ const HEX2 = /^[0-9a-f]{2}$/;
69
+ /**
70
+ * A `traceparent` header read (FR-003): version `00` exactly as written (55 characters, lower-case hexadecimal, ids not all zeros),
71
+ * version `ff` refused, a later version read by its first four fields. The context is remote and its trace state empty; the flags this
72
+ * version does not define are dropped.
73
+ */
74
+ export function parseTraceparent(header) {
75
+ const h = header.replace(/^[ \t]+|[ \t]+$/g, "");
76
+ const version = h.slice(0, 2);
77
+ if (!HEX2.test(version) || h[2] !== "-")
78
+ return err("the version is not two lower-case hexadecimal digits and a dash");
79
+ if (version === "ff")
80
+ return err("the version ff is not valid");
81
+ if (version === "00" ? h.length !== 55 : h.length < 55 || (h.length > 55 && h[55] !== "-")) {
82
+ return err("the header does not have the length of its version");
83
+ }
84
+ if (h[35] !== "-" || h[52] !== "-")
85
+ return err("the fields are not separated by dashes");
86
+ const traceId = parseTraceId(h.slice(3, 35));
87
+ if (traceId.kind === "err")
88
+ return traceId;
89
+ const spanId = parseSpanId(h.slice(36, 52));
90
+ if (spanId.kind === "err")
91
+ return spanId;
92
+ const flags = h.slice(53, 55);
93
+ if (!HEX2.test(flags))
94
+ return err("the trace flags are not two lower-case hexadecimal digits");
95
+ return ok({
96
+ traceId: traceId.value,
97
+ spanId: spanId.value,
98
+ traceFlags: Number.parseInt(flags, 16) & KNOWN_FLAGS,
99
+ traceState: [],
100
+ isRemote: true,
101
+ });
102
+ }
103
+ /** A `traceparent` header (version `00`) for a context. */
104
+ export function formatTraceparent(context) {
105
+ const flags = (context.traceFlags & KNOWN_FLAGS).toString(16).padStart(2, "0");
106
+ return `00-${context.traceId}-${context.spanId}-${flags}`;
107
+ }
108
+ const KEY_CHAR = "[a-z0-9_\\-*/]";
109
+ const TRACESTATE_KEY = new RegExp(`^(?:[a-z]${KEY_CHAR}{0,255}|[a-z0-9]${KEY_CHAR}{0,240}@[a-z]${KEY_CHAR}{0,13})$`);
110
+ const TRACESTATE_VALUE = /^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;
111
+ /** Whether a key is a `tracestate` key of the grammar. */
112
+ export function isTraceStateKey(key) {
113
+ return TRACESTATE_KEY.test(key);
114
+ }
115
+ /** Whether a value is a `tracestate` value of the grammar. */
116
+ export function isTraceStateValue(value) {
117
+ return TRACESTATE_VALUE.test(value);
118
+ }
119
+ /**
120
+ * A `tracestate` header read (FR-003): members split on commas with optional white space, a member that breaks the grammar or repeats a
121
+ * key dropped (never the header), at most 32 members kept. Several header fields are read joined with commas.
122
+ */
123
+ export function parseTracestate(header) {
124
+ const out = [];
125
+ const seen = new Set();
126
+ for (const raw of header.split(",")) {
127
+ if (out.length >= TRACESTATE_MAX_MEMBERS)
128
+ break;
129
+ const member = raw.replace(/^[ \t]+|[ \t]+$/g, "");
130
+ if (member === "")
131
+ continue;
132
+ const eq = member.indexOf("=");
133
+ if (eq < 0)
134
+ continue;
135
+ const key = member.slice(0, eq);
136
+ const value = member.slice(eq + 1);
137
+ if (!isTraceStateKey(key) || !isTraceStateValue(value) || seen.has(key))
138
+ continue;
139
+ seen.add(key);
140
+ out.push({ key, value });
141
+ }
142
+ return out;
143
+ }
144
+ /** A `tracestate` header: the members newest first, as they are held. */
145
+ export function formatTracestate(state) {
146
+ return state
147
+ .slice(0, TRACESTATE_MAX_MEMBERS)
148
+ .map((m) => `${m.key}=${m.value}`)
149
+ .join(",");
150
+ }
151
+ /** The value of a key in a trace state. */
152
+ export function traceStateGet(state, key) {
153
+ return state.find((m) => m.key === key)?.value;
154
+ }
155
+ /** A trace state with a key set: the member moved to the front (newest), the oldest dropped beyond 32; a key or value of no grammar refused. */
156
+ export function traceStateSet(state, key, value) {
157
+ if (!isTraceStateKey(key))
158
+ return err(`${JSON.stringify(key)} is not a tracestate key`);
159
+ if (!isTraceStateValue(value))
160
+ return err(`${JSON.stringify(value)} is not a tracestate value`);
161
+ return ok([{ key, value }, ...state.filter((m) => m.key !== key)].slice(0, TRACESTATE_MAX_MEMBERS));
162
+ }
163
+ /** A trace state without a key. */
164
+ export function traceStateDelete(state, key) {
165
+ return state.filter((m) => m.key !== key);
166
+ }
167
+ /**
168
+ * The context carried by a `traceparent` and a `tracestate` (an HTTP request's headers, or the `TRACEPARENT` and `TRACESTATE` of the
169
+ * environment): undefined when there is no valid `traceparent`, whose `tracestate` is then ignored too.
170
+ */
171
+ export function extractContext(traceparent, tracestate) {
172
+ if (traceparent === undefined)
173
+ return undefined;
174
+ const parent = parseTraceparent(traceparent);
175
+ if (parent.kind === "err")
176
+ return undefined;
177
+ return { ...parent.value, traceState: tracestate === undefined ? [] : parseTracestate(tracestate) };
178
+ }
179
+ /** The first severity number of each range of the log data model. */
180
+ export const SEVERITY = { TRACE: 1, DEBUG: 5, INFO: 9, WARN: 13, ERROR: 17, FATAL: 21 };
181
+ /** Whether a number is a severity number (an integer from 1 to 24). */
182
+ export function isSeverityNumber(n) {
183
+ return Number.isInteger(n) && n >= 1 && n <= 24;
184
+ }
185
+ /** The short name the log data model gives a severity number: `INFO`, `INFO2`, ... `FATAL4`. */
186
+ export function severityText(n) {
187
+ const names = ["TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"];
188
+ const range = names[Math.floor((n - 1) / 4)] ?? "FATAL";
189
+ const step = (n - 1) % 4;
190
+ return step === 0 ? range : `${range}${step + 1}`;
191
+ }
192
+ /** OpenTelemetry's default explicit bucket bounds for a histogram (FR-013). */
193
+ export const DEFAULT_HISTOGRAM_BOUNDS = [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000];
194
+ /** OpenTelemetry's default limits: no value length limit, 128 attributes, events and links. */
195
+ export const DEFAULT_LIMITS = { attributeValueLength: Infinity, attributeCount: 128, eventCount: 128, linkCount: 128 };
196
+ function cut(s, length) {
197
+ if (s.length <= length)
198
+ return s;
199
+ // Cut by code points, so that a surrogate pair is never split.
200
+ return Array.from(s).slice(0, length).join("");
201
+ }
202
+ /** A value cut to the value length limit: a string, or each string of an array of strings; other values unchanged. */
203
+ export function truncateValue(value, length) {
204
+ if (!Number.isFinite(length))
205
+ return value;
206
+ if (typeof value === "string")
207
+ return cut(value, length);
208
+ if (Array.isArray(value) && value.every((v) => typeof v === "string"))
209
+ return value.map((v) => cut(v, length));
210
+ return value;
211
+ }
212
+ /**
213
+ * Attributes added to others under the limits (FR-007): a value cut to the length limit, an existing key replaced, a new key beyond the
214
+ * count dropped and counted.
215
+ */
216
+ export function mergeAttributes(current, added, limits) {
217
+ const out = { ...current };
218
+ let count = Object.keys(out).length;
219
+ let dropped = 0;
220
+ for (const [key, value] of Object.entries(added)) {
221
+ if (!Object.hasOwn(out, key)) {
222
+ if (count >= limits.attributeCount) {
223
+ dropped++;
224
+ continue;
225
+ }
226
+ count++;
227
+ }
228
+ out[key] = truncateValue(value, limits.attributeValueLength);
229
+ }
230
+ return { attributes: out, dropped };
231
+ }
232
+ /** Attributes under the limits: what `mergeAttributes` gives from none. */
233
+ export function limitAttributes(attributes, limits) {
234
+ return mergeAttributes({}, attributes, limits);
235
+ }
236
+ /** OpenTelemetry's default sampler: `parentbased_always_on`. */
237
+ export const DEFAULT_SAMPLER = { kind: "parentbased", root: { kind: "always_on" } };
238
+ const TWO_56 = 2 ** 56;
239
+ /**
240
+ * The rejection threshold of `TraceIdRatioBased` for a ratio: a trace is sampled where its trace id's right-most 56 bits, read as an
241
+ * unsigned integer, are at least the threshold (`(1 - ratio) * 2^56`). Every process of a trace decides alike from the id alone.
242
+ */
243
+ export function ratioThreshold(ratio) {
244
+ const r = Number.isFinite(ratio) ? Math.min(1, Math.max(0, ratio)) : 1;
245
+ return BigInt(Math.round((1 - r) * TWO_56));
246
+ }
247
+ /** Whether a sampler samples a new span of a trace, given its parent (FR-008). */
248
+ export function shouldSample(sampler, traceId, parent) {
249
+ switch (sampler.kind) {
250
+ case "always_on":
251
+ return true;
252
+ case "always_off":
253
+ return false;
254
+ case "traceidratio":
255
+ return BigInt(`0x${traceId.slice(18)}`) >= ratioThreshold(sampler.ratio);
256
+ case "parentbased":
257
+ return parent === undefined ? shouldSample(sampler.root, traceId, undefined) : isSampled(parent);
258
+ default:
259
+ return absurd(sampler);
260
+ }
261
+ }
262
+ // ---------------------------------------------------------------------------------------------------------------------------------
263
+ // Redaction (FR-006)
264
+ // ---------------------------------------------------------------------------------------------------------------------------------
265
+ /** What a redacted secret is written as. */
266
+ export const REDACTED = "REDACTED";
267
+ const CREDENTIAL_PARTS = [
268
+ "token",
269
+ "secret",
270
+ "password",
271
+ "passwd",
272
+ "passphrase",
273
+ "signature",
274
+ "credential",
275
+ "apikey",
276
+ "auth",
277
+ "cookie",
278
+ "jwt",
279
+ ];
280
+ const CREDENTIAL_WORDS = new Set(["key", "code", "sig", "pwd", "pass", "session", "sid", "otp", "awsaccesskeyid", "sas", "se", "sp", "sv"]);
281
+ /** Whether a query parameter's or a field's name says it holds a credential (`token`, `key`, `secret`, `password`, `signature`, `code`, ...). */
282
+ export function isCredentialName(name) {
283
+ const n = name.toLowerCase();
284
+ if (CREDENTIAL_PARTS.some((p) => n.includes(p)))
285
+ return true;
286
+ return n.split(/[^a-z0-9]+/).some((w) => CREDENTIAL_WORDS.has(w) || (w.length > 3 && w.endsWith("key")));
287
+ }
288
+ function decodedName(name) {
289
+ try {
290
+ return decodeURIComponent(name.replaceAll("+", " "));
291
+ }
292
+ catch {
293
+ return name;
294
+ }
295
+ }
296
+ const URL_HEAD = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/?#]*)/;
297
+ /**
298
+ * A URL with its secrets replaced (FR-006): the user and password of its authority, and the value of each query parameter whose name says
299
+ * it is a credential, become `REDACTED`. The rest of the text is kept as written.
300
+ */
301
+ export function redactUrl(url) {
302
+ let out = url;
303
+ const head = URL_HEAD.exec(out);
304
+ if (head !== null) {
305
+ const scheme = head[1] ?? "";
306
+ const authority = head[2] ?? "";
307
+ const at = authority.lastIndexOf("@");
308
+ if (at >= 0) {
309
+ const userinfo = authority.slice(0, at);
310
+ const replaced = userinfo.includes(":") ? `${REDACTED}:${REDACTED}` : REDACTED;
311
+ out = `${scheme}${replaced}@${authority.slice(at + 1)}${out.slice(head[0].length)}`;
312
+ }
313
+ }
314
+ const q = out.indexOf("?");
315
+ if (q < 0)
316
+ return out;
317
+ const hash = out.indexOf("#", q);
318
+ const end = hash < 0 ? out.length : hash;
319
+ const query = out
320
+ .slice(q + 1, end)
321
+ .split("&")
322
+ .map((pair) => {
323
+ const eq = pair.indexOf("=");
324
+ if (eq < 0)
325
+ return pair;
326
+ return isCredentialName(decodedName(pair.slice(0, eq))) ? `${pair.slice(0, eq)}=${REDACTED}` : pair;
327
+ })
328
+ .join("&");
329
+ return `${out.slice(0, q + 1)}${query}${out.slice(end)}`;
330
+ }
331
+ const URL_IN_TEXT = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>`]+/g;
332
+ const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g;
333
+ const BEARER = /\b(Bearer)[ \t]+[A-Za-z0-9._~+/-]{8,}=*/gi;
334
+ const BASIC = /\b(Basic)[ \t]+([A-Za-z0-9+/]{4,}={0,2})/gi;
335
+ // `Authorization: <scheme> <credential>` (or `=`), quoted or not: the scheme kept, the credential replaced up to a space, quote, `,` or `;`.
336
+ const AUTHORIZATION = /\b((?:proxy-)?authorization["']?[ \t]*[:=][ \t]*["']?)(?:([A-Za-z][A-Za-z0-9-]*)[ \t]+)?([^\s"',;]+)/gi;
337
+ // `name=value`, `name: value`, `"name": "value"`: the name an identifier (with `-` and `.`), the value quoted or up to a delimiter.
338
+ const PAIR = /(["']?)\b([A-Za-z_][A-Za-z0-9_.-]*)\1([ \t]*[:=][ \t]*)("[^"\n]*"|'[^'\n]*'|[^\s"',;&)}\]]+)/g;
339
+ const SECRET_NAME_ENDINGS = [
340
+ "token",
341
+ "secret",
342
+ "password",
343
+ "passwd",
344
+ "passphrase",
345
+ "apikey",
346
+ "accesskey",
347
+ "secretkey",
348
+ "privatekey",
349
+ "credential",
350
+ "signature",
351
+ ];
352
+ const KNOWN_TOKENS = [
353
+ /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g, // GitHub
354
+ /\bgithub_pat_[A-Za-z0-9_]{30,}\b/g,
355
+ /\bglpat-[A-Za-z0-9_-]{20,}/g, // GitLab
356
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}/g, // Slack
357
+ /\bxapp-[0-9]-[A-Za-z0-9-]{10,}/g,
358
+ /\bya29\.[A-Za-z0-9._-]{20,}/g, // Google access, refresh and client secret, API key
359
+ /(?<![A-Za-z0-9])1\/\/[A-Za-z0-9_-]{30,}/g,
360
+ /\bGOCSPX-[A-Za-z0-9_-]{20,}/g,
361
+ /\bAIza[0-9A-Za-z_-]{35}\b/g,
362
+ /\bcf[au]t_[A-Za-z0-9_-]{20,}/g, // Cloudflare account and user API tokens
363
+ /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g, // Anthropic, OpenAI
364
+ /\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}/g, // Stripe
365
+ /\bnpm_[A-Za-z0-9]{36}\b/g, // npm
366
+ /\bdo[opr]_v1_[a-f0-9]{64}\b/g, // DigitalOcean
367
+ /\bdckr_pat_[A-Za-z0-9_-]{20,}/g, // Docker
368
+ /\bhf_[A-Za-z]{30,}\b/g, // Hugging Face
369
+ /\blin_(?:api|oauth)_[A-Za-z0-9]{30,}\b/g, // Linear
370
+ /\bAT(?:ATT|BB)[A-Za-z0-9_=-]{20,}/g, // Atlassian, Bitbucket
371
+ /\beyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]+/g, // JSON Web Token
372
+ /\$(?:6|5|y|gy|2[aby])\$[^\s:"']{8,}/g, // crypt password hashes
373
+ ];
374
+ function isBasicCredential(token) {
375
+ const bytes = fromBase64(token);
376
+ if (bytes.kind === "err")
377
+ return false;
378
+ return new TextDecoder().decode(bytes.value).includes(":");
379
+ }
380
+ /**
381
+ * Whether a field's name in text says its value is a secret (FR-006): it ends in `token`, `secret`, `password`, `passwd`, `passphrase`,
382
+ * `apikey`, `accesskey`, `secretkey`, `privatekey`, `credential` or `signature`, with case, `-`, `_` and `.` ignored (`api_token`,
383
+ * `AWS_SECRET_ACCESS_KEY`, `X-Amz-Signature`, `clientSecret`), but not `max_tokens` or `token_type`. Narrower than
384
+ * {@link isCredentialName}, which judges a URL's query parameters, because prose is full of `code=` and `key:`.
385
+ */
386
+ export function isSecretFieldName(name) {
387
+ const n = name.toLowerCase().replace(/[-_.]/g, "");
388
+ return SECRET_NAME_ENDINGS.some((e) => n.endsWith(e));
389
+ }
390
+ /**
391
+ * Text with its secrets replaced (FR-006), the one redaction for signals and for what a harness mails: each exact secret named in
392
+ * `secrets` (four characters or more; a shorter one would garble the text and hide nothing), a private key block, each URL as
393
+ * `redactUrl` writes it, a bearer token, a basic credential (base64 of `user:pass`), the credential of an `Authorization` header with any
394
+ * scheme, the value of a `name=value` or `name: value` pair whose name {@link isSecretFieldName} judges secret (quoted or bare, in prose,
395
+ * JSON, YAML or an environment file), and the token formats that announce themselves (GitHub, GitLab, Slack, Google, Cloudflare,
396
+ * Anthropic, OpenAI, Stripe, npm, DigitalOcean, Docker, Hugging Face, Linear, Atlassian, JSON Web Tokens) and crypt password hashes
397
+ * become `REDACTED`.
398
+ */
399
+ export function redactText(text, secrets = []) {
400
+ let out = text;
401
+ const exact = [...new Set(secrets)].filter((s) => s.length >= 4).sort((a, b) => b.length - a.length);
402
+ for (const s of exact)
403
+ out = out.split(s).join(REDACTED);
404
+ out = out.replace(PRIVATE_KEY, REDACTED);
405
+ out = out.replace(URL_IN_TEXT, (u) => redactUrl(u));
406
+ out = out.replace(AUTHORIZATION, (_m, head, scheme) => `${head}${scheme === undefined ? "" : `${scheme} `}${REDACTED}`);
407
+ out = out.replace(BEARER, (_m, word) => `${word} ${REDACTED}`);
408
+ out = out.replace(BASIC, (m, word, token) => (isBasicCredential(token) ? `${word} ${REDACTED}` : m));
409
+ out = out.replace(PAIR, (m, quote, name, sep, value) => {
410
+ if (!isSecretFieldName(name))
411
+ return m;
412
+ const q = value.startsWith('"') || value.startsWith("'") ? value.charAt(0) : "";
413
+ return `${quote}${name}${quote}${sep}${q}${REDACTED}${q}`;
414
+ });
415
+ for (const re of KNOWN_TOKENS)
416
+ out = out.replace(re, REDACTED);
417
+ return out;
418
+ }
419
+ /** An attribute value with its secrets replaced: `redactText` on a string and on each string of an array. */
420
+ export function redactValue(value) {
421
+ if (typeof value === "string")
422
+ return redactText(value);
423
+ if (Array.isArray(value) && value.every((v) => typeof v === "string"))
424
+ return value.map((v) => redactText(v));
425
+ return value;
426
+ }
427
+ /** A log body with its secrets replaced, at every depth. */
428
+ export function redactAnyValue(value) {
429
+ if (typeof value === "string")
430
+ return redactText(value);
431
+ if (value instanceof Uint8Array || typeof value !== "object")
432
+ return value;
433
+ if (Array.isArray(value))
434
+ return value.map((v) => redactAnyValue(v));
435
+ const out = {};
436
+ for (const [k, v] of Object.entries(value)) {
437
+ Object.defineProperty(out, k, { value: redactAnyValue(v), enumerable: true, writable: true, configurable: true });
438
+ }
439
+ return out;
440
+ }
441
+ /** Attributes with the secret ones left out (never written, FR-006) and every other string redacted by `redactText`. */
442
+ export function redactAttributes(attributes, secretKeys = []) {
443
+ const secret = new Set(secretKeys);
444
+ const out = {};
445
+ for (const [key, value] of Object.entries(attributes))
446
+ if (!secret.has(key))
447
+ out[key] = redactValue(value);
448
+ return out;
449
+ }
450
+ /**
451
+ * A command line as it may be recorded (FR-006): the program's name (its last path segment) and the names of its options alone, never a
452
+ * value, an operand or a subcommand. `--opt=value` is kept as `--opt`, a short option as its first letter (`-pSECRET` as `-p`), and
453
+ * nothing after `--`.
454
+ */
455
+ export function commandShape(argv) {
456
+ const [program, ...rest] = argv;
457
+ if (program === undefined)
458
+ return [];
459
+ const out = [program.split(/[/\\]/).pop() ?? program];
460
+ for (const arg of rest) {
461
+ if (arg === "--")
462
+ break;
463
+ if (arg.startsWith("--"))
464
+ out.push(arg.split("=")[0] ?? arg);
465
+ else if (arg.startsWith("-") && arg.length > 1 && !/^-[0-9.]/.test(arg))
466
+ out.push(arg.slice(0, 2));
467
+ }
468
+ return out;
469
+ }
470
+ /** The endpoint an OTLP/HTTP exporter uses where none is configured. */
471
+ export const DEFAULT_OTLP_ENDPOINT = "http://localhost:4318";
472
+ /** The path of each signal under a base endpoint. */
473
+ export const SIGNAL_PATHS = { traces: "v1/traces", logs: "v1/logs", metrics: "v1/metrics" };
474
+ const SIGNAL_VARIABLE = { traces: "TRACES", logs: "LOGS", metrics: "METRICS" };
475
+ const LOG_LEVELS = ["none", "error", "warn", "info", "debug", "verbose", "all"];
476
+ function isUrl(text) {
477
+ try {
478
+ const u = new URL(text);
479
+ return u.protocol === "http:" || u.protocol === "https:";
480
+ }
481
+ catch {
482
+ return false;
483
+ }
484
+ }
485
+ /** A base endpoint with a signal's path appended, with one `/` between them. */
486
+ export function signalEndpoint(base, signal) {
487
+ return `${base.endsWith("/") ? base : `${base}/`}${SIGNAL_PATHS[signal]}`;
488
+ }
489
+ /** `key=value` pairs separated by commas, values percent-decoded; undefined where one pair is not valid. */
490
+ function keyValues(text) {
491
+ const out = {};
492
+ for (const raw of text.split(",")) {
493
+ const pair = raw.trim();
494
+ if (pair === "")
495
+ continue;
496
+ const eq = pair.indexOf("=");
497
+ if (eq <= 0)
498
+ return undefined;
499
+ const key = pair.slice(0, eq).trim();
500
+ if (key === "")
501
+ return undefined;
502
+ try {
503
+ out[decodeURIComponent(key)] = decodeURIComponent(pair.slice(eq + 1).trim());
504
+ }
505
+ catch {
506
+ return undefined;
507
+ }
508
+ }
509
+ return out;
510
+ }
511
+ /**
512
+ * The configuration of the OpenTelemetry environment variables, from a record of them (FR-005): the kernel reads no environment. A value
513
+ * that is not valid is a warning and its default is used; an empty value counts as unset; no vendor's variable is read. A protocol other
514
+ * than `http/json` is a warning and disables the export of that signal.
515
+ */
516
+ export function resolveConfig(env) {
517
+ const warnings = [];
518
+ const get = (name) => {
519
+ const v = env[name]?.trim();
520
+ return v === undefined || v === "" ? undefined : v;
521
+ };
522
+ const bool = (name) => {
523
+ const v = get(name);
524
+ if (v === undefined)
525
+ return false;
526
+ if (v.toLowerCase() === "true")
527
+ return true;
528
+ if (v.toLowerCase() !== "false")
529
+ warnings.push(`${name}=${v} is not true or false; false is used`);
530
+ return false;
531
+ };
532
+ const int = (name, fallback, min = 0) => {
533
+ const v = get(name);
534
+ if (v === undefined)
535
+ return fallback;
536
+ if (!/^[0-9]+$/.test(v) || Number(v) < min || !Number.isSafeInteger(Number(v))) {
537
+ warnings.push(`${name}=${v} is not an integer of at least ${min}; ${fallback} is used`);
538
+ return fallback;
539
+ }
540
+ return Number(v);
541
+ };
542
+ const disabled = bool("OTEL_SDK_DISABLED");
543
+ const resource = {};
544
+ const attrs = get("OTEL_RESOURCE_ATTRIBUTES");
545
+ if (attrs !== undefined) {
546
+ const parsed = keyValues(attrs);
547
+ if (parsed === undefined)
548
+ warnings.push("OTEL_RESOURCE_ATTRIBUTES is not a list of key=value pairs; it is ignored");
549
+ else
550
+ Object.assign(resource, parsed);
551
+ }
552
+ const serviceName = get("OTEL_SERVICE_NAME");
553
+ if (serviceName !== undefined)
554
+ resource["service.name"] = serviceName;
555
+ const genericHeaders = (() => {
556
+ const v = get("OTEL_EXPORTER_OTLP_HEADERS");
557
+ if (v === undefined)
558
+ return {};
559
+ const parsed = keyValues(v);
560
+ if (parsed === undefined)
561
+ warnings.push("OTEL_EXPORTER_OTLP_HEADERS is not a list of key=value pairs; it is ignored");
562
+ return parsed ?? {};
563
+ })();
564
+ const genericEndpoint = (() => {
565
+ const v = get("OTEL_EXPORTER_OTLP_ENDPOINT");
566
+ if (v === undefined || isUrl(v))
567
+ return v;
568
+ warnings.push(`OTEL_EXPORTER_OTLP_ENDPOINT=${redactUrl(v)} is not an http or https URL; it is ignored`);
569
+ return undefined;
570
+ })();
571
+ const genericTimeout = int("OTEL_EXPORTER_OTLP_TIMEOUT", 10000);
572
+ const genericProtocol = get("OTEL_EXPORTER_OTLP_PROTOCOL");
573
+ const exporter = (signal) => {
574
+ const S = SIGNAL_VARIABLE[signal];
575
+ let enabled = true;
576
+ const protocolName = get(`OTEL_EXPORTER_OTLP_${S}_PROTOCOL`) === undefined ? "OTEL_EXPORTER_OTLP_PROTOCOL" : `OTEL_EXPORTER_OTLP_${S}_PROTOCOL`;
577
+ const protocol = get(`OTEL_EXPORTER_OTLP_${S}_PROTOCOL`) ?? genericProtocol ?? "http/json";
578
+ if (protocol !== "http/json") {
579
+ warnings.push(`${protocolName}=${protocol} is not supported (only http/json is); ${signal} are not exported`);
580
+ enabled = false;
581
+ }
582
+ const exporterName = get(`OTEL_${S}_EXPORTER`) ?? "otlp";
583
+ const names = exporterName.split(",").map((n) => n.trim());
584
+ if (names.includes("none"))
585
+ enabled = false;
586
+ else if (!names.includes("otlp")) {
587
+ warnings.push(`OTEL_${S}_EXPORTER=${exporterName} is not supported (only otlp and none are); ${signal} are not exported`);
588
+ enabled = false;
589
+ }
590
+ let endpoint = genericEndpoint === undefined ? undefined : signalEndpoint(genericEndpoint, signal);
591
+ const own = get(`OTEL_EXPORTER_OTLP_${S}_ENDPOINT`);
592
+ if (own !== undefined) {
593
+ if (isUrl(own))
594
+ endpoint = own;
595
+ else
596
+ warnings.push(`OTEL_EXPORTER_OTLP_${S}_ENDPOINT=${redactUrl(own)} is not an http or https URL; it is ignored`);
597
+ }
598
+ let headers = genericHeaders;
599
+ const ownHeaders = get(`OTEL_EXPORTER_OTLP_${S}_HEADERS`);
600
+ if (ownHeaders !== undefined) {
601
+ const parsed = keyValues(ownHeaders);
602
+ if (parsed === undefined)
603
+ warnings.push(`OTEL_EXPORTER_OTLP_${S}_HEADERS is not a list of key=value pairs; it is ignored`);
604
+ else
605
+ headers = parsed;
606
+ }
607
+ const timeoutMs = int(`OTEL_EXPORTER_OTLP_${S}_TIMEOUT`, genericTimeout);
608
+ return { enabled: enabled && !disabled, endpoint, headers, timeoutMs };
609
+ };
610
+ const ratio = (() => {
611
+ const v = get("OTEL_TRACES_SAMPLER_ARG");
612
+ if (v === undefined)
613
+ return 1;
614
+ const n = Number(v);
615
+ if (!/^[0-9.eE+-]+$/.test(v) || !Number.isFinite(n) || n < 0 || n > 1) {
616
+ warnings.push(`OTEL_TRACES_SAMPLER_ARG=${v} is not a ratio from 0 to 1; 1 is used`);
617
+ return 1;
618
+ }
619
+ return n;
620
+ })();
621
+ const sampler = (() => {
622
+ const v = get("OTEL_TRACES_SAMPLER");
623
+ switch (v) {
624
+ case undefined:
625
+ return DEFAULT_SAMPLER;
626
+ case "always_on":
627
+ return { kind: "always_on" };
628
+ case "always_off":
629
+ return { kind: "always_off" };
630
+ case "traceidratio":
631
+ return { kind: "traceidratio", ratio };
632
+ case "parentbased_always_on":
633
+ return { kind: "parentbased", root: { kind: "always_on" } };
634
+ case "parentbased_always_off":
635
+ return { kind: "parentbased", root: { kind: "always_off" } };
636
+ case "parentbased_traceidratio":
637
+ return { kind: "parentbased", root: { kind: "traceidratio", ratio } };
638
+ default:
639
+ warnings.push(`OTEL_TRACES_SAMPLER=${v} is not supported; parentbased_always_on is used`);
640
+ return DEFAULT_SAMPLER;
641
+ }
642
+ })();
643
+ const batch = (prefix, scheduleDelay) => {
644
+ const maxQueueSize = int(`${prefix}_MAX_QUEUE_SIZE`, 2048, 1);
645
+ let maxExportBatchSize = int(`${prefix}_MAX_EXPORT_BATCH_SIZE`, Math.min(512, maxQueueSize), 1);
646
+ if (maxExportBatchSize > maxQueueSize) {
647
+ warnings.push(`${prefix}_MAX_EXPORT_BATCH_SIZE is more than ${prefix}_MAX_QUEUE_SIZE; ${maxQueueSize} is used`);
648
+ maxExportBatchSize = maxQueueSize;
649
+ }
650
+ return {
651
+ scheduleDelayMs: int(`${prefix}_SCHEDULE_DELAY`, scheduleDelay),
652
+ exportTimeoutMs: int(`${prefix}_EXPORT_TIMEOUT`, 30000),
653
+ maxQueueSize,
654
+ maxExportBatchSize,
655
+ };
656
+ };
657
+ const valueLength = get("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") === undefined ? Infinity : int("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", Infinity);
658
+ const limits = {
659
+ attributeValueLength: valueLength,
660
+ attributeCount: int("OTEL_ATTRIBUTE_COUNT_LIMIT", 128),
661
+ eventCount: int("OTEL_SPAN_EVENT_COUNT_LIMIT", 128),
662
+ linkCount: int("OTEL_SPAN_LINK_COUNT_LIMIT", 128),
663
+ };
664
+ const logLevel = (() => {
665
+ const v = get("OTEL_LOG_LEVEL")?.toLowerCase();
666
+ if (v === undefined)
667
+ return "info";
668
+ const found = LOG_LEVELS.find((l) => l === v);
669
+ if (found === undefined)
670
+ warnings.push(`OTEL_LOG_LEVEL=${v} is not one of ${LOG_LEVELS.join(", ")}; info is used`);
671
+ return found ?? "info";
672
+ })();
673
+ const config = {
674
+ disabled,
675
+ resource,
676
+ exporters: { traces: exporter("traces"), logs: exporter("logs"), metrics: exporter("metrics") },
677
+ sampler,
678
+ spanBatch: batch("OTEL_BSP", 5000),
679
+ logBatch: batch("OTEL_BLRP", 1000),
680
+ metricExportIntervalMs: int("OTEL_METRIC_EXPORT_INTERVAL", 60000),
681
+ metricExportTimeoutMs: int("OTEL_METRIC_EXPORT_TIMEOUT", 30000),
682
+ limits,
683
+ logLevel,
684
+ };
685
+ return { config, warnings };
686
+ }