@zharp/node 0.1.0 → 0.3.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/index.js CHANGED
@@ -33,7 +33,7 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
33
33
 
34
34
  // src/zharp.ts
35
35
  var import_node_module = require("module");
36
- var import_api3 = require("@opentelemetry/api");
36
+ var import_api4 = require("@opentelemetry/api");
37
37
  var import_core = require("@opentelemetry/core");
38
38
  var import_resources = require("@opentelemetry/resources");
39
39
  var import_sdk_node = require("@opentelemetry/sdk-node");
@@ -106,6 +106,602 @@ function warn(message) {
106
106
  console.warn(`[Zharp] ${message}`);
107
107
  }
108
108
 
109
+ // ../../internal/src/bodies.ts
110
+ var DEFAULT_MAX_BODY = 32 * 1024;
111
+ var MAX_BODY = 128 * 1024;
112
+ var FILTERED = "[Filtered]";
113
+ function rawLimit(settings) {
114
+ return Math.max(64 * 1024, settings.maxSize * 2);
115
+ }
116
+ var BODY_ATTRIBUTES = {
117
+ request: "http.request.body",
118
+ requestTruncated: "http.request.body.truncated",
119
+ requestType: "http.request.header.content-type",
120
+ response: "http.response.body",
121
+ responseTruncated: "http.response.body.truncated",
122
+ responseType: "http.response.header.content-type"
123
+ };
124
+ function bodySettings(option, env) {
125
+ let value = option;
126
+ if (value === void 0 && env) {
127
+ const e = env.trim().toLowerCase();
128
+ if (e === "errors" || e === "all") value = e;
129
+ else if (/^(true|1|yes|on)$/.test(e)) value = true;
130
+ }
131
+ if (!value) return null;
132
+ const o = value === true ? {} : typeof value === "string" ? { mode: value } : value;
133
+ const size = typeof o.maxSize === "number" && o.maxSize > 0 ? Math.min(Math.floor(o.maxSize), MAX_BODY) : DEFAULT_MAX_BODY;
134
+ return { mode: o.mode === "all" ? "all" : "errors", maxSize: size, extraKeys: o.redactKeys ?? [], urls: o.urls };
135
+ }
136
+ function wanted(settings, status) {
137
+ return settings.mode === "all" || !status || status >= 400;
138
+ }
139
+ var mime = (contentType) => (contentType ?? "").split(";")[0].trim().toLowerCase();
140
+ function isEventStream(contentType) {
141
+ return mime(contentType) === "text/event-stream";
142
+ }
143
+ function isMultipart(contentType) {
144
+ return mime(contentType) === "multipart/form-data";
145
+ }
146
+ function isTextual(contentType) {
147
+ const type = mime(contentType);
148
+ if (!type) return true;
149
+ if (type === "text/event-stream") return false;
150
+ return type.startsWith("text/") || type.endsWith("+json") || type.endsWith("+xml") || /^application\/(json|xml|x-www-form-urlencoded|graphql|javascript|x-ndjson|ld\+json)$/.test(type);
151
+ }
152
+ function isForm(contentType) {
153
+ return mime(contentType) === "application/x-www-form-urlencoded";
154
+ }
155
+ function formatSize(bytes) {
156
+ if (bytes < 1024) return `${bytes} B`;
157
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
158
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
159
+ }
160
+ function fileLabel(name, type, size, partial = false) {
161
+ const parts = [`file ${name || "blob"}`];
162
+ if (type) parts.push(type);
163
+ if (size !== void 0) parts.push(formatSize(size) + (partial ? "+" : ""));
164
+ return `[${parts.join(" \xB7 ")}]`;
165
+ }
166
+ function describeBody(contentType, size, partial = false) {
167
+ if (isEventStream(contentType)) return "[event stream]";
168
+ const parts = ["binary"];
169
+ const type = mime(contentType);
170
+ if (type) parts.push(type);
171
+ if (size !== void 0 && size > 0) parts.push(formatSize(size) + (partial ? "+" : ""));
172
+ return `[${parts.join(" \xB7 ")}]`;
173
+ }
174
+ var CONTAINS = [
175
+ "password",
176
+ "passwd",
177
+ "passphrase",
178
+ "secret",
179
+ "token",
180
+ "apikey",
181
+ "accesskey",
182
+ "privatekey",
183
+ "authorization",
184
+ "cookie",
185
+ "creditcard",
186
+ "cardnumber",
187
+ "cvv",
188
+ "cvc",
189
+ "ssn",
190
+ "iban",
191
+ "sessionid",
192
+ "signature",
193
+ "credential"
194
+ ];
195
+ var EXACT = ["auth", "pin", "pwd", "otp", "card", "pan", "jwt", "sid", "codeverifier"];
196
+ var URL_EXACT = ["key", "sig", "code", "state", "session"];
197
+ var normalize = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, "");
198
+ function isSecretKey(key, extra = []) {
199
+ const k = normalize(key);
200
+ if (!k) return false;
201
+ if (EXACT.includes(k) || CONTAINS.some((c) => k.includes(c))) return true;
202
+ return extra.some((p) => p instanceof RegExp ? p.test(key) : normalize(p) === k);
203
+ }
204
+ var DATA_URI = /^data:([\w.+-]+\/[\w.+-]+)?(?:;[\w=.+-]+)*;base64,([A-Za-z0-9+/=\s]*)$/;
205
+ var BASE64 = /^[A-Za-z0-9+/_-]{256,}={0,2}$/;
206
+ function shorten(value) {
207
+ if (value.length < 256) return value;
208
+ const uri = DATA_URI.exec(value);
209
+ if (uri) return `[${uri[1] || "data"} \xB7 ${formatSize(Math.floor(uri[2].length * 3 / 4))}]`;
210
+ if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
211
+ return value;
212
+ }
213
+ function filterAll(value, depth2) {
214
+ if (depth2 > 20) return FILTERED;
215
+ if (value === null || value === "") return value;
216
+ if (Array.isArray(value)) return value.map((v) => filterAll(v, depth2 + 1));
217
+ if (typeof value === "object") {
218
+ const out = {};
219
+ for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth2 + 1);
220
+ return out;
221
+ }
222
+ return FILTERED;
223
+ }
224
+ function redactValue(value, extra, depth2 = 0) {
225
+ if (typeof value === "string") return shorten(value);
226
+ if (depth2 > 20 || value === null || typeof value !== "object") return value;
227
+ if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth2 + 1));
228
+ const out = {};
229
+ for (const [k, v] of Object.entries(value)) {
230
+ out[k] = isSecretKey(k, extra) ? filterAll(v, depth2 + 1) : redactValue(v, extra, depth2 + 1);
231
+ }
232
+ return out;
233
+ }
234
+ function redactLoose(text, extra) {
235
+ const runs = /"((?:data:[\w.+-]+\/[\w.+-]+(?:;[\w=.+-]+)*;base64,)?[A-Za-z0-9+/_=-]{256,})("?)/g;
236
+ return text.replace(runs, (match, run, close) => {
237
+ const short = shorten(run);
238
+ if (short === run) return match;
239
+ return close ? `"${short}"` : `"${short.slice(0, -1)}+]"`;
240
+ }).replace(
241
+ /("([^"\\]{1,100})"\s*:\s*)("(?:[^"\\]|\\.)*"?|-?\d[\d.eE+-]*|true|false)/g,
242
+ (match, prefix, key) => isSecretKey(key, extra) ? `${prefix}"${FILTERED}"` : match
243
+ );
244
+ }
245
+ function redactForm(text, extra) {
246
+ return text.split("&").map((pair) => {
247
+ const eq = pair.indexOf("=");
248
+ if (eq < 0) return pair;
249
+ let key = pair.slice(0, eq);
250
+ try {
251
+ key = decodeURIComponent(key.replace(/\+/g, " "));
252
+ } catch {
253
+ }
254
+ if (isSecretKey(key, extra)) return `${pair.slice(0, eq)}=${FILTERED}`;
255
+ const value = pair.slice(eq + 1);
256
+ return value.length >= 256 ? `${pair.slice(0, eq)}=${shortenEncoded(value)}` : pair;
257
+ }).join("&");
258
+ }
259
+ function shortenEncoded(value) {
260
+ try {
261
+ const decoded = decodeURIComponent(value.replace(/\+/g, " "));
262
+ const short = shorten(decoded);
263
+ return short === decoded ? value : short;
264
+ } catch {
265
+ return value;
266
+ }
267
+ }
268
+ function formatBody(text, contentType, settings, cut = false) {
269
+ if (text == null) return null;
270
+ let body = String(text);
271
+ if (!body.trim()) return null;
272
+ if (isForm(contentType)) body = redactForm(body, settings.extraKeys);
273
+ else {
274
+ let parsed2;
275
+ let ok = false;
276
+ const trimmed = body.trim();
277
+ if (!cut && (trimmed[0] === "{" || trimmed[0] === "[")) {
278
+ try {
279
+ parsed2 = JSON.parse(trimmed);
280
+ ok = true;
281
+ } catch {
282
+ }
283
+ }
284
+ body = ok ? JSON.stringify(redactValue(parsed2, settings.extraKeys)) : redactLoose(body, settings.extraKeys);
285
+ }
286
+ const truncated = cut || body.length > settings.maxSize;
287
+ return { value: body.length > settings.maxSize ? body.slice(0, settings.maxSize) : body, truncated };
288
+ }
289
+ function typeKey(side) {
290
+ return side === "request" ? BODY_ATTRIBUTES.requestType : BODY_ATTRIBUTES.responseType;
291
+ }
292
+ function bodyAttributes(side, text, contentType, settings, cut = false) {
293
+ if (!isTextual(contentType) && !isMultipart(contentType)) return {};
294
+ const formatted = formatBody(text, contentType, settings, cut);
295
+ if (!formatted) return {};
296
+ const attributes = { [BODY_ATTRIBUTES[side]]: formatted.value };
297
+ if (formatted.truncated) attributes[side === "request" ? BODY_ATTRIBUTES.requestTruncated : BODY_ATTRIBUTES.responseTruncated] = true;
298
+ if (contentType) attributes[typeKey(side)] = contentType;
299
+ return attributes;
300
+ }
301
+ function describedAttributes(side, contentType, size, partial = false) {
302
+ const attributes = { [BODY_ATTRIBUTES[side]]: describeBody(contentType, size, partial) };
303
+ if (contentType) attributes[typeKey(side)] = contentType;
304
+ return attributes;
305
+ }
306
+ function redactUrl(url, extra = []) {
307
+ if (!url) return url;
308
+ let out = url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
309
+ const q = out.indexOf("?");
310
+ if (q < 0) return out;
311
+ const hash = out.indexOf("#", q);
312
+ const query = out.slice(q + 1, hash < 0 ? void 0 : hash);
313
+ const redacted = redactQuery(query, extra);
314
+ if (redacted !== query) out = out.slice(0, q + 1) + redacted + (hash < 0 ? "" : out.slice(hash));
315
+ return out;
316
+ }
317
+ function redactQuery(query, extra = []) {
318
+ if (!query) return query;
319
+ return query.split("&").map((pair) => {
320
+ const eq = pair.indexOf("=");
321
+ if (eq < 0) return pair;
322
+ let key = pair.slice(0, eq);
323
+ try {
324
+ key = decodeURIComponent(key.replace(/\+/g, " "));
325
+ } catch {
326
+ }
327
+ const secret = isSecretKey(key, extra) || URL_EXACT.includes(normalize(key));
328
+ return secret && eq < pair.length - 1 ? `${pair.slice(0, eq)}=${FILTERED}` : pair;
329
+ }).join("&");
330
+ }
331
+ function urlMatches(url, patterns) {
332
+ let host = "";
333
+ let hostname = "";
334
+ try {
335
+ const parsed2 = new URL(url);
336
+ host = parsed2.host;
337
+ hostname = parsed2.hostname;
338
+ } catch {
339
+ }
340
+ return patterns.some((p) => {
341
+ if (p instanceof RegExp) return p.test(url);
342
+ if (!p) return false;
343
+ if (p.includes("://")) return url.startsWith(p);
344
+ return host === p || hostname === p;
345
+ });
346
+ }
347
+
348
+ // src/bodies.ts
349
+ var import_node_http = require("http");
350
+ var import_node_zlib = require("zlib");
351
+ var TAP = /* @__PURE__ */ Symbol.for("zharp.body");
352
+ var MAX_FIELDS = 200;
353
+ var Multipart = class {
354
+ constructor(boundary, maxText) {
355
+ this.maxText = maxText;
356
+ this.first = Buffer.from(`--${boundary}`);
357
+ this.delimiter = Buffer.from(`\r
358
+ --${boundary}`);
359
+ }
360
+ maxText;
361
+ buf = Buffer.alloc(0);
362
+ state = "start";
363
+ first;
364
+ delimiter;
365
+ part = null;
366
+ count = 0;
367
+ fields = {};
368
+ cut = false;
369
+ push(chunk) {
370
+ if (this.state === "done") return;
371
+ this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
372
+ for (; ; ) {
373
+ if (this.state === "start") {
374
+ const i = this.buf.indexOf(this.first);
375
+ if (i < 0) {
376
+ if (this.buf.length > 64 * 1024) this.state = "done";
377
+ return;
378
+ }
379
+ this.buf = this.buf.subarray(i + this.first.length);
380
+ this.state = "after";
381
+ }
382
+ if (this.state === "after") {
383
+ if (this.buf.length < 2) return;
384
+ if (this.buf[0] === 45 && this.buf[1] === 45) {
385
+ this.state = "done";
386
+ this.buf = Buffer.alloc(0);
387
+ return;
388
+ }
389
+ if (this.buf[0] === 13 && this.buf[1] === 10) this.buf = this.buf.subarray(2);
390
+ this.state = "headers";
391
+ }
392
+ if (this.state === "headers") {
393
+ const i = this.buf.indexOf("\r\n\r\n");
394
+ if (i < 0) {
395
+ if (this.buf.length > 16 * 1024) this.state = "done";
396
+ return;
397
+ }
398
+ this.part = parsePartHeaders(this.buf.subarray(0, i).toString("utf8"));
399
+ this.buf = this.buf.subarray(i + 4);
400
+ this.state = "body";
401
+ }
402
+ if (this.state === "body") {
403
+ const i = this.buf.indexOf(this.delimiter);
404
+ if (i >= 0) {
405
+ this.consume(this.buf.subarray(0, i));
406
+ this.finish(false);
407
+ this.buf = this.buf.subarray(i + this.delimiter.length);
408
+ this.state = "after";
409
+ if (this.count >= MAX_FIELDS) {
410
+ this.state = "done";
411
+ this.cut = true;
412
+ return;
413
+ }
414
+ continue;
415
+ }
416
+ const keep = this.delimiter.length - 1;
417
+ if (this.buf.length > keep) {
418
+ this.consume(this.buf.subarray(0, this.buf.length - keep));
419
+ this.buf = Buffer.from(this.buf.subarray(this.buf.length - keep));
420
+ }
421
+ return;
422
+ }
423
+ return;
424
+ }
425
+ }
426
+ consume(bytes) {
427
+ const part = this.part;
428
+ if (!part || !bytes.length) return;
429
+ part.size += bytes.length;
430
+ if (part.filename !== void 0) return;
431
+ const room = this.maxText - part.kept;
432
+ if (room > 0) {
433
+ const slice = bytes.subarray(0, room);
434
+ part.text.push(Buffer.from(slice));
435
+ part.kept += slice.length;
436
+ }
437
+ }
438
+ finish(partial) {
439
+ const part = this.part;
440
+ this.part = null;
441
+ if (!part) return;
442
+ let value;
443
+ if (part.filename !== void 0) value = fileLabel(part.filename, part.type, part.size, partial);
444
+ else {
445
+ value = Buffer.concat(part.text).toString("utf8").replace(/�$/, "");
446
+ if (part.size > part.kept || partial) this.cut = true;
447
+ }
448
+ const existing = this.fields[part.name];
449
+ this.fields[part.name] = existing === void 0 ? value : Array.isArray(existing) ? [...existing, value] : [existing, value];
450
+ this.count++;
451
+ }
452
+ /** The fields so far, including a part the stream stopped inside. */
453
+ result() {
454
+ if (this.part) {
455
+ this.consume(this.state === "body" ? this.buf : Buffer.alloc(0));
456
+ this.buf = Buffer.alloc(0);
457
+ this.finish(true);
458
+ this.cut = true;
459
+ }
460
+ return { json: JSON.stringify(this.fields), cut: this.cut };
461
+ }
462
+ };
463
+ function parsePartHeaders(head) {
464
+ const disposition = /^content-disposition:(.*)$/im.exec(head)?.[1] ?? "";
465
+ const name = /\bname="([^"]*)"/i.exec(disposition)?.[1] ?? /\bname=([^;\s]+)/i.exec(disposition)?.[1] ?? "";
466
+ const filenameStar = /\bfilename\*=(?:UTF-8'')?([^;\s]+)/i.exec(disposition)?.[1];
467
+ let filename = /\bfilename="([^"]*)"/i.exec(disposition)?.[1];
468
+ if (filenameStar) {
469
+ try {
470
+ filename = decodeURIComponent(filenameStar);
471
+ } catch {
472
+ filename = filenameStar;
473
+ }
474
+ }
475
+ const type = /^content-type:\s*(.*)$/im.exec(head)?.[1]?.trim();
476
+ return { name, filename, type: filename !== void 0 ? type : void 0, size: 0, text: [], kept: 0 };
477
+ }
478
+ function boundaryOf(contentType) {
479
+ const m = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType ?? "");
480
+ return m ? m[1] ?? m[2] : void 0;
481
+ }
482
+ var Tap = class {
483
+ /** `typeOf` is asked once, at the first byte, when the content type is surely set. */
484
+ constructor(settings, typeOf2) {
485
+ this.settings = settings;
486
+ this.typeOf = typeOf2;
487
+ }
488
+ settings;
489
+ typeOf;
490
+ chunks = [];
491
+ kept = 0;
492
+ /** Every byte seen, kept or not. */
493
+ total = 0;
494
+ cut = false;
495
+ mode;
496
+ multipart;
497
+ add(chunk, encoding) {
498
+ if (chunk == null || typeof chunk === "function") return;
499
+ let buf;
500
+ if (typeof chunk === "string") buf = Buffer.from(chunk, typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8");
501
+ else if (chunk instanceof Uint8Array) buf = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
502
+ else return;
503
+ if (!buf.length) return;
504
+ this.total += buf.length;
505
+ if (this.mode === void 0) {
506
+ const type = this.typeOf();
507
+ const boundary = isMultipart(type) ? boundaryOf(type) : void 0;
508
+ if (boundary) {
509
+ this.mode = "multipart";
510
+ this.multipart = new Multipart(boundary, this.settings.maxSize);
511
+ } else this.mode = isTextual(type) ? "text" : "count";
512
+ }
513
+ if (this.mode === "multipart") return this.multipart.push(Buffer.from(buf));
514
+ if (this.mode === "count" || this.cut) return;
515
+ const room = rawLimit(this.settings) - this.kept;
516
+ if (buf.length > room) {
517
+ this.cut = true;
518
+ buf = buf.subarray(0, Math.max(0, room));
519
+ }
520
+ if (buf.length) {
521
+ this.chunks.push(Buffer.from(buf));
522
+ this.kept += buf.length;
523
+ }
524
+ }
525
+ /** The text, inflated if it was compressed; null when it cannot be read as text. */
526
+ text(encoding) {
527
+ let raw = Buffer.concat(this.chunks);
528
+ const enc = (encoding ?? "").toLowerCase().trim();
529
+ try {
530
+ const flush = { finishFlush: import_node_zlib.constants.Z_SYNC_FLUSH };
531
+ if (enc === "gzip" || enc === "x-gzip") raw = (0, import_node_zlib.gunzipSync)(raw, flush);
532
+ else if (enc === "deflate") raw = (0, import_node_zlib.inflateSync)(raw, flush);
533
+ else if (enc === "br") raw = (0, import_node_zlib.brotliDecompressSync)(raw, { finishFlush: import_node_zlib.constants.BROTLI_OPERATION_FLUSH });
534
+ else if (enc && enc !== "identity") return null;
535
+ } catch {
536
+ return null;
537
+ }
538
+ return raw.toString("utf8").replace(/�$/, "");
539
+ }
540
+ };
541
+ function sideAttributes(side, tap, type, encoding, settings) {
542
+ if (!tap || !tap.total) return {};
543
+ if (tap.multipart) {
544
+ const { json, cut } = tap.multipart.result();
545
+ return bodyAttributes(side, json, type, settings, cut);
546
+ }
547
+ if (!isTextual(type)) return describedAttributes(side, type, tap.total);
548
+ const text = tap.text(encoding);
549
+ if (text == null) return describedAttributes(side, type, tap.total);
550
+ return bodyAttributes(side, text, type, settings, tap.cut);
551
+ }
552
+ function tapReadable(stream, tap) {
553
+ const emit = stream.emit;
554
+ stream.emit = function(event, ...args) {
555
+ if (event === "data") {
556
+ try {
557
+ tap.add(args[0]);
558
+ } catch {
559
+ }
560
+ }
561
+ return emit.call(this, event, ...args);
562
+ };
563
+ stream[TAP] = tap;
564
+ }
565
+ function tapWritable(stream, tap) {
566
+ const target = stream;
567
+ const write = target.write;
568
+ const end = target.end;
569
+ target.write = function(...args) {
570
+ try {
571
+ tap.add(args[0], args[1]);
572
+ } catch {
573
+ }
574
+ return write.apply(this, args);
575
+ };
576
+ target.end = function(...args) {
577
+ try {
578
+ tap.add(args[0], args[1]);
579
+ } catch {
580
+ }
581
+ return end.apply(this, args);
582
+ };
583
+ stream[TAP] = tap;
584
+ }
585
+ var tapOf = (stream) => stream?.[TAP];
586
+ function header(value) {
587
+ if (value == null) return void 0;
588
+ return Array.isArray(value) ? String(value[0]) : String(value);
589
+ }
590
+ function incomingUrl(req) {
591
+ const proto = req.socket?.encrypted ? "https" : "http";
592
+ return `${proto}://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
593
+ }
594
+ function sentHeader(res, name) {
595
+ const set = header(res.getHeader(name));
596
+ if (set) return set;
597
+ const head = res._header;
598
+ if (typeof head !== "string") return void 0;
599
+ const match = head.match(new RegExp(`^${name}:[ \\t]*(.*)$`, "im"));
600
+ return match ? match[1].trim() : void 0;
601
+ }
602
+ function outgoingUrl(req) {
603
+ const r = req;
604
+ return `${r.protocol ?? "http:"}//${r.host ?? "localhost"}${r.path ?? "/"}`;
605
+ }
606
+ function withBodyCapture(settings, config = {}) {
607
+ const allowed = (url) => !settings.urls || urlMatches(url, settings.urls);
608
+ return {
609
+ ...config,
610
+ requestHook(span, request) {
611
+ config.requestHook?.(span, request);
612
+ try {
613
+ if (request instanceof import_node_http.IncomingMessage) {
614
+ if (allowed(incomingUrl(request))) tapReadable(request, new Tap(settings, () => header(request.headers["content-type"])));
615
+ } else if (request instanceof import_node_http.ClientRequest) {
616
+ if (allowed(outgoingUrl(request))) tapWritable(request, new Tap(settings, () => header(request.getHeader("content-type"))));
617
+ }
618
+ } catch {
619
+ }
620
+ },
621
+ responseHook(span, response) {
622
+ config.responseHook?.(span, response);
623
+ try {
624
+ if (response instanceof import_node_http.ServerResponse) {
625
+ if (tapOf(response.req) || allowed(incomingUrl(response.req))) tapWritable(response, new Tap(settings, () => sentHeader(response, "content-type")));
626
+ } else if (response instanceof import_node_http.IncomingMessage) {
627
+ const req = response.req;
628
+ if (!req || tapOf(req) || allowed(outgoingUrl(req))) tapReadable(response, new Tap(settings, () => header(response.headers["content-type"])));
629
+ }
630
+ } catch {
631
+ }
632
+ },
633
+ applyCustomAttributesOnSpan(span, request, response) {
634
+ config.applyCustomAttributesOnSpan?.(span, request, response);
635
+ try {
636
+ const status = Number(response?.statusCode) || 0;
637
+ if (!wanted(settings, status)) return;
638
+ const attributes = {};
639
+ if (request instanceof import_node_http.ClientRequest) {
640
+ Object.assign(
641
+ attributes,
642
+ sideAttributes("request", tapOf(request), header(request.getHeader("content-type")), header(request.getHeader("content-encoding")), settings)
643
+ );
644
+ const res = response;
645
+ Object.assign(
646
+ attributes,
647
+ sideAttributes("response", tapOf(res), header(res?.headers?.["content-type"]), header(res?.headers?.["content-encoding"]), settings)
648
+ );
649
+ } else if (request instanceof import_node_http.IncomingMessage) {
650
+ const sentType = header(request.headers["content-type"]);
651
+ const sent = tapOf(request);
652
+ if (sent && sent.total) {
653
+ Object.assign(attributes, sideAttributes("request", sent, sentType, header(request.headers["content-encoding"]), settings));
654
+ } else {
655
+ const parsed2 = request.body;
656
+ if (parsed2 != null && (typeof parsed2 === "string" || typeof parsed2 === "object" && !Buffer.isBuffer(parsed2))) {
657
+ const text = typeof parsed2 === "string" ? parsed2 : JSON.stringify(parsed2);
658
+ Object.assign(attributes, bodyAttributes("request", text, isTextual(sentType) ? sentType : "application/json", settings));
659
+ }
660
+ }
661
+ const res = response;
662
+ Object.assign(attributes, sideAttributes("response", tapOf(res), sentHeader(res, "content-type"), sentHeader(res, "content-encoding"), settings));
663
+ }
664
+ if (Object.keys(attributes).length) span.setAttributes(attributes);
665
+ } catch {
666
+ }
667
+ }
668
+ };
669
+ }
670
+
671
+ // src/urls.ts
672
+ var URL_KEYS = ["url.full", "http.url", "http.target"];
673
+ var UrlRedactionSpanProcessor = class {
674
+ onStart() {
675
+ }
676
+ onEnding(span) {
677
+ try {
678
+ const attributes = span.attributes ?? {};
679
+ for (const key of URL_KEYS) {
680
+ const value = attributes[key];
681
+ if (typeof value === "string") {
682
+ const redacted = redactUrl(value);
683
+ if (redacted !== value) span.setAttribute(key, redacted);
684
+ }
685
+ }
686
+ const query = attributes["url.query"];
687
+ if (typeof query === "string") {
688
+ const bare = query.startsWith("?") ? query.slice(1) : query;
689
+ const redacted = redactQuery(bare);
690
+ if (redacted !== bare) span.setAttribute("url.query", (query.startsWith("?") ? "?" : "") + redacted);
691
+ }
692
+ } catch {
693
+ }
694
+ }
695
+ onEnd(_span) {
696
+ }
697
+ forceFlush() {
698
+ return Promise.resolve();
699
+ }
700
+ shutdown() {
701
+ return Promise.resolve();
702
+ }
703
+ };
704
+
109
705
  // src/context.ts
110
706
  var import_api = require("@opentelemetry/api");
111
707
  var BAGGAGE_KEYS = ["enduser.id", "session.id"];
@@ -216,6 +812,44 @@ var ContextLogProcessor = class {
216
812
  // src/console.ts
217
813
  var import_node_util = require("util");
218
814
  var import_api2 = require("@opentelemetry/api");
815
+
816
+ // src/capture-state.ts
817
+ var depth = 0;
818
+ function quiet(fn) {
819
+ depth++;
820
+ try {
821
+ return fn();
822
+ } finally {
823
+ depth--;
824
+ }
825
+ }
826
+ var isQuiet = () => depth > 0;
827
+ var RECENT_MS = 3e3;
828
+ var RECENT_MAX = 500;
829
+ var recent = [];
830
+ var normalise = (text) => text.replace(/\s+/g, " ").trim();
831
+ function rememberSent(body) {
832
+ if (typeof body !== "string") return;
833
+ const text = normalise(body);
834
+ if (text.length < 4) return;
835
+ recent.push({ at: Date.now(), text });
836
+ if (recent.length > RECENT_MAX) recent.splice(0, recent.length - RECENT_MAX);
837
+ }
838
+ function alreadySent(line) {
839
+ const now = Date.now();
840
+ while (recent.length && now - recent[0].at > RECENT_MS) recent.shift();
841
+ if (!recent.length) return false;
842
+ const text = normalise(line);
843
+ for (let i = recent.length - 1; i >= 0; i--) {
844
+ if (text.includes(recent[i].text)) {
845
+ recent.splice(i, 1);
846
+ return true;
847
+ }
848
+ }
849
+ return false;
850
+ }
851
+
852
+ // src/console.ts
219
853
  var LEVELS = [
220
854
  ["debug", import_api2.SeverityNumber.DEBUG, "DEBUG"],
221
855
  ["trace", import_api2.SeverityNumber.TRACE, "TRACE"],
@@ -232,7 +866,7 @@ function captureConsole(logger) {
232
866
  if (typeof original !== "function" || original.__zharp) continue;
233
867
  originals.set(method, original);
234
868
  const patched = function(...args) {
235
- original.apply(this ?? console, args);
869
+ quiet(() => original.apply(this ?? console, args));
236
870
  if (emitting) return;
237
871
  emitting = true;
238
872
  try {
@@ -253,6 +887,207 @@ function captureConsole(logger) {
253
887
  };
254
888
  }
255
889
 
890
+ // src/stdout.ts
891
+ var import_api3 = require("@opentelemetry/api");
892
+ var LEVELS2 = {
893
+ trace: [import_api3.SeverityNumber.TRACE, "TRACE"],
894
+ verbose: [import_api3.SeverityNumber.DEBUG, "DEBUG"],
895
+ debug: [import_api3.SeverityNumber.DEBUG, "DEBUG"],
896
+ log: [import_api3.SeverityNumber.INFO, "INFO"],
897
+ info: [import_api3.SeverityNumber.INFO, "INFO"],
898
+ notice: [import_api3.SeverityNumber.INFO, "INFO"],
899
+ warn: [import_api3.SeverityNumber.WARN, "WARN"],
900
+ warning: [import_api3.SeverityNumber.WARN, "WARN"],
901
+ error: [import_api3.SeverityNumber.ERROR, "ERROR"],
902
+ err: [import_api3.SeverityNumber.ERROR, "ERROR"],
903
+ crit: [import_api3.SeverityNumber.FATAL, "FATAL"],
904
+ critical: [import_api3.SeverityNumber.FATAL, "FATAL"],
905
+ fatal: [import_api3.SeverityNumber.FATAL, "FATAL"],
906
+ emerg: [import_api3.SeverityNumber.FATAL, "FATAL"],
907
+ alert: [import_api3.SeverityNumber.FATAL, "FATAL"]
908
+ };
909
+ var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "debug"], [0, "trace"]];
910
+ var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
911
+ var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
912
+ var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
913
+ var MAX_LINE = 32 * 1024;
914
+ var FLUSH_MS = 200;
915
+ function levelOf(value) {
916
+ if (typeof value === "number") {
917
+ const found = NUMERIC.find(([n]) => value >= n);
918
+ return found ? LEVELS2[found[1]] : null;
919
+ }
920
+ return typeof value === "string" ? LEVELS2[value.toLowerCase()] ?? null : null;
921
+ }
922
+ function parseLine(raw) {
923
+ const line = raw.replace(ANSI, "").replace(/\s+$/, "");
924
+ if (line.startsWith("{") && line.endsWith("}")) {
925
+ try {
926
+ const record = JSON.parse(line);
927
+ const message = record.msg ?? record.message ?? record.event;
928
+ return {
929
+ level: levelOf(record.level ?? record.severity ?? record.lvl),
930
+ body: typeof message === "string" ? message : line,
931
+ attributes: {}
932
+ };
933
+ } catch {
934
+ }
935
+ }
936
+ const nest = NEST.exec(line);
937
+ if (nest) {
938
+ return {
939
+ level: LEVELS2[nest[1].toLowerCase()],
940
+ body: nest[3],
941
+ attributes: nest[2] ? { "log.logger": nest[2] } : {}
942
+ };
943
+ }
944
+ const word = WORD.exec(line.slice(0, 120));
945
+ return { level: word ? LEVELS2[word[1].toLowerCase()] ?? null : null, body: line, attributes: {} };
946
+ }
947
+ var SentLineProcessor = class {
948
+ onEmit(record) {
949
+ const source = record.attributes?.["log.source"];
950
+ if (source !== "stdout" && source !== "stderr") rememberSent(record.body);
951
+ }
952
+ forceFlush() {
953
+ return Promise.resolve();
954
+ }
955
+ shutdown() {
956
+ return Promise.resolve();
957
+ }
958
+ };
959
+ function captureOutput(logger) {
960
+ const undo = [];
961
+ for (const [stream, name, fallback] of [
962
+ [process.stdout, "stdout", LEVELS2.info],
963
+ [process.stderr, "stderr", LEVELS2.warn]
964
+ ]) {
965
+ if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
966
+ const original = stream.write;
967
+ let pending = "";
968
+ let pendingContext;
969
+ let timer;
970
+ const emitLine = (line, ctx) => {
971
+ if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
972
+ const parsed2 = parseLine(line.length > MAX_LINE ? line.slice(0, MAX_LINE) : line);
973
+ if (!parsed2.body.trim()) return;
974
+ const [severityNumber, severityText] = parsed2.level ?? fallback;
975
+ quiet(() => logger.emit({
976
+ severityNumber,
977
+ severityText,
978
+ body: parsed2.body,
979
+ attributes: { "log.source": name, "log.iostream": name, ...parsed2.attributes },
980
+ ...ctx ? { context: ctx } : {}
981
+ }));
982
+ };
983
+ const flush = () => {
984
+ timer = void 0;
985
+ const line = pending;
986
+ const ctx = pendingContext;
987
+ pending = "";
988
+ pendingContext = void 0;
989
+ emitLine(line, ctx);
990
+ };
991
+ const take = (chunk, encoding) => {
992
+ if (isQuiet()) return;
993
+ const text = typeof chunk === "string" ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : "utf8") : "";
994
+ if (!text) return;
995
+ if (!pending) pendingContext = import_api3.context.active();
996
+ pending += text;
997
+ const lines = pending.split("\n");
998
+ pending = lines.pop() ?? "";
999
+ const ctx = pendingContext;
1000
+ if (pending) pendingContext = import_api3.context.active();
1001
+ for (const line of lines) emitLine(line, ctx);
1002
+ if (pending.length > MAX_LINE) flush();
1003
+ else if (pending && !timer) {
1004
+ timer = setTimeout(flush, FLUSH_MS);
1005
+ timer.unref?.();
1006
+ }
1007
+ };
1008
+ const patched = function(chunk, encoding, callback) {
1009
+ try {
1010
+ take(chunk, encoding);
1011
+ } catch {
1012
+ }
1013
+ return original.call(this ?? stream, chunk, encoding, callback);
1014
+ };
1015
+ patched.__zharp = true;
1016
+ stream.write = patched;
1017
+ undo.push(() => {
1018
+ if (timer) clearTimeout(timer);
1019
+ if (pending) flush();
1020
+ stream.write = original;
1021
+ });
1022
+ }
1023
+ return () => undo.forEach((fn) => fn());
1024
+ }
1025
+ function stampOutput() {
1026
+ const undo = [];
1027
+ for (const stream of [process.stdout, process.stderr]) {
1028
+ if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
1029
+ const original = stream.write;
1030
+ const patched = function(chunk, encoding, callback) {
1031
+ let out = chunk;
1032
+ try {
1033
+ out = stamped(chunk, encoding);
1034
+ } catch {
1035
+ }
1036
+ return original.call(this ?? stream, out, encoding, callback);
1037
+ };
1038
+ patched.__zharpStamp = true;
1039
+ stream.write = patched;
1040
+ undo.push(() => {
1041
+ stream.write = original;
1042
+ });
1043
+ }
1044
+ return () => undo.forEach((fn) => fn());
1045
+ }
1046
+ function stamped(chunk, encoding) {
1047
+ const span = import_api3.trace.getActiveSpan()?.spanContext();
1048
+ if (!span || !(0, import_api3.isSpanContextValid)(span)) return chunk;
1049
+ const isBytes = chunk instanceof Uint8Array;
1050
+ if (typeof chunk !== "string" && !isBytes) return chunk;
1051
+ const enc = typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8";
1052
+ if (isBytes && enc !== "utf8") return chunk;
1053
+ const text = isBytes ? Buffer.from(chunk).toString("utf8") : chunk;
1054
+ if (!text.includes("\n")) return chunk;
1055
+ const parts = text.split("\n");
1056
+ let last = -1;
1057
+ for (let i = parts.length - 2; i >= 0; i--) {
1058
+ if (parts[i].trim()) {
1059
+ last = i;
1060
+ break;
1061
+ }
1062
+ }
1063
+ let changed = false;
1064
+ for (let i = 0; i < parts.length - 1; i++) {
1065
+ if (i !== last && !parts[i].trimStart().startsWith("{")) continue;
1066
+ const next = stampLine(parts[i], span.traceId, span.spanId);
1067
+ if (next !== parts[i]) {
1068
+ parts[i] = next;
1069
+ changed = true;
1070
+ }
1071
+ }
1072
+ if (!changed) return chunk;
1073
+ const joined = parts.join("\n");
1074
+ return isBytes ? Buffer.from(joined, "utf8") : joined;
1075
+ }
1076
+ function stampLine(line, traceId, spanId) {
1077
+ const cr = line.endsWith("\r") ? "\r" : "";
1078
+ const body = cr ? line.slice(0, -1) : line;
1079
+ const trimmed = body.trimEnd();
1080
+ if (!trimmed.trim() || body.includes("trace_id") || body.includes("[Zharp]")) return line;
1081
+ if (trimmed.endsWith("}")) {
1082
+ if (!trimmed.trimStart().startsWith("{")) return line;
1083
+ const close = trimmed.lastIndexOf("}");
1084
+ const inner = trimmed.slice(trimmed.indexOf("{") + 1, close).trim();
1085
+ const fields = `"trace_id":"${traceId}","span_id":"${spanId}"`;
1086
+ return `${trimmed.slice(0, close)}${inner ? "," : ""}${fields}}${body.slice(trimmed.length)}${cr}`;
1087
+ }
1088
+ return `${trimmed} trace_id=${traceId} span_id=${spanId}${body.slice(trimmed.length)}${cr}`;
1089
+ }
1090
+
256
1091
  // ../../internal/src/debug-ids.ts
257
1092
  var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
258
1093
  var files = /* @__PURE__ */ new Map();
@@ -400,7 +1235,7 @@ Caused by: ${cause.stack}`;
400
1235
  }
401
1236
 
402
1237
  // src/version.ts
403
- var VERSION = "0.1.0";
1238
+ var VERSION = "0.3.0";
404
1239
 
405
1240
  // src/zharp.ts
406
1241
  var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
@@ -461,22 +1296,27 @@ var ZharpNode = class {
461
1296
  const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
462
1297
  const tracing = tracingEnabled(options.tracing);
463
1298
  this.tracing = tracing;
1299
+ const sendLogs = switchOn(options.logs, "ZHARP_LOGS", false);
1300
+ const correlation = switchOn(options.logCorrelation, "ZHARP_LOG_CORRELATION", true);
1301
+ const bridges = logBridges(sendLogs, correlation, options.instrumentations);
464
1302
  if (options.debug) {
465
1303
  const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };
466
1304
  const prefixed = Object.fromEntries(
467
1305
  Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
468
1306
  );
469
- import_api3.diag.setLogger(prefixed, import_api3.DiagLogLevel.DEBUG);
1307
+ import_api4.diag.setLogger(prefixed, import_api4.DiagLogLevel.DEBUG);
470
1308
  }
471
1309
  registerEsmHook();
472
1310
  const headers = { Authorization: `Bearer ${key}` };
473
1311
  const exporterOptions = { headers, compression: "gzip" };
474
1312
  this.spanProcessors = tracing ? [
475
1313
  new ContextSpanProcessor(this.store),
1314
+ new UrlRedactionSpanProcessor(),
476
1315
  new DebugIdSpanProcessor(),
477
1316
  new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
478
1317
  ] : [new ContextSpanProcessor(this.store)];
479
1318
  this.logProcessors = [
1319
+ new SentLineProcessor(),
480
1320
  new ContextLogProcessor(this.store),
481
1321
  new DebugIdLogProcessor(),
482
1322
  new import_sdk_logs.BatchLogRecordProcessor({ exporter: new import_exporter_logs_otlp_proto.OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) })
@@ -494,6 +1334,7 @@ var ZharpNode = class {
494
1334
  const propagator = new import_core.CompositePropagator({
495
1335
  propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
496
1336
  });
1337
+ const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
497
1338
  const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
498
1339
  this.sdk = new import_sdk_node.NodeSDK({
499
1340
  resource,
@@ -512,14 +1353,24 @@ var ZharpNode = class {
512
1353
  "@opentelemetry/instrumentation-dns": { enabled: false },
513
1354
  "@opentelemetry/instrumentation-net": { enabled: false },
514
1355
  "@opentelemetry/instrumentation-fs": { enabled: false },
515
- ...options.instrumentations
516
- }) : logsOnlyInstrumentations(options),
1356
+ ...options.instrumentations,
1357
+ ...bridges,
1358
+ ...bodies && {
1359
+ "@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
1360
+ }
1361
+ }) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
517
1362
  ...options.extraInstrumentations ?? []
518
1363
  ]
519
1364
  });
520
1365
  this.sdk.start();
521
- this.logger = import_api3.logs.getLogger("@zharp/node", VERSION);
522
- if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
1366
+ this.logger = import_api4.logs.getLogger("@zharp/node", VERSION);
1367
+ if (correlation) this.teardowns.push(stampOutput());
1368
+ if (sendLogs) {
1369
+ if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
1370
+ if (options.captureOutput !== false && nodeEnv("ZHARP_CAPTURE_OUTPUT") !== "false") {
1371
+ this.teardowns.push(captureOutput(this.logger));
1372
+ }
1373
+ }
523
1374
  if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());
524
1375
  this.teardowns.push(this.flushOnExit());
525
1376
  announce(`Application monitoring active${tracing ? "" : " (logs only)"} \u2014 ${describeTarget(service, environment)}`);
@@ -560,11 +1411,11 @@ var ZharpNode = class {
560
1411
  * throw or rejection marks the span as failed and is passed on unchanged.
561
1412
  */
562
1413
  startSpan(name, fn, options = {}) {
563
- if (!this.tracing) return fn(import_api3.trace.wrapSpanContext(import_api3.trace.getActiveSpan()?.spanContext() ?? import_api3.INVALID_SPAN_CONTEXT));
564
- const tracer = import_api3.trace.getTracer("@zharp/node", VERSION);
1414
+ if (!this.tracing) return fn(import_api4.trace.wrapSpanContext(import_api4.trace.getActiveSpan()?.spanContext() ?? import_api4.INVALID_SPAN_CONTEXT));
1415
+ const tracer = import_api4.trace.getTracer("@zharp/node", VERSION);
565
1416
  return tracer.startActiveSpan(name, options, (span) => {
566
1417
  const fail = (error) => {
567
- span.setStatus({ code: import_api3.SpanStatusCode.ERROR, message: asError(error).message });
1418
+ span.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: asError(error).message });
568
1419
  span.end();
569
1420
  };
570
1421
  let result;
@@ -641,7 +1492,7 @@ var ZharpNode = class {
641
1492
  body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
642
1493
  attributes: { ...attributes, ...exception }
643
1494
  });
644
- if (!handled) import_api3.trace.getActiveSpan()?.setStatus({ code: import_api3.SpanStatusCode.ERROR, message: error.message });
1495
+ if (!handled) import_api4.trace.getActiveSpan()?.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: error.message });
645
1496
  } catch {
646
1497
  }
647
1498
  }
@@ -745,6 +1596,25 @@ function registerEsmHook() {
745
1596
  } catch {
746
1597
  }
747
1598
  }
1599
+ function switchOn(option, variable, fallback) {
1600
+ if (typeof option === "boolean") return option;
1601
+ const value = nodeEnv(variable);
1602
+ if (value && /^(true|1|yes|on)$/i.test(value)) return true;
1603
+ if (value && /^(false|0|no|off)$/i.test(value)) return false;
1604
+ return fallback;
1605
+ }
1606
+ function logBridges(sendLogs, correlation, own = {}) {
1607
+ const config = (name) => ({
1608
+ disableLogSending: !sendLogs,
1609
+ disableLogCorrelation: !correlation,
1610
+ ...own[name]
1611
+ });
1612
+ return {
1613
+ "@opentelemetry/instrumentation-pino": config("@opentelemetry/instrumentation-pino"),
1614
+ "@opentelemetry/instrumentation-winston": config("@opentelemetry/instrumentation-winston"),
1615
+ "@opentelemetry/instrumentation-bunyan": config("@opentelemetry/instrumentation-bunyan")
1616
+ };
1617
+ }
748
1618
  function tracingEnabled(option) {
749
1619
  if (typeof option === "boolean") return option;
750
1620
  const value = nodeEnv("ZHARP_TRACING");