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