@zharp/node 0.1.0 → 0.2.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
@@ -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, depth) {
214
+ if (depth > 20) return FILTERED;
215
+ if (value === null || value === "") return value;
216
+ if (Array.isArray(value)) return value.map((v) => filterAll(v, depth + 1));
217
+ if (typeof value === "object") {
218
+ const out = {};
219
+ for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth + 1);
220
+ return out;
221
+ }
222
+ return FILTERED;
223
+ }
224
+ function redactValue(value, extra, depth = 0) {
225
+ if (typeof value === "string") return shorten(value);
226
+ if (depth > 20 || value === null || typeof value !== "object") return value;
227
+ if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth + 1));
228
+ const out = {};
229
+ for (const [k, v] of Object.entries(value)) {
230
+ out[k] = isSecretKey(k, extra) ? filterAll(v, depth + 1) : redactValue(v, extra, depth + 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"];
@@ -400,7 +996,7 @@ Caused by: ${cause.stack}`;
400
996
  }
401
997
 
402
998
  // src/version.ts
403
- var VERSION = "0.1.0";
999
+ var VERSION = "0.2.0";
404
1000
 
405
1001
  // src/zharp.ts
406
1002
  var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
@@ -473,6 +1069,7 @@ var ZharpNode = class {
473
1069
  const exporterOptions = { headers, compression: "gzip" };
474
1070
  this.spanProcessors = tracing ? [
475
1071
  new ContextSpanProcessor(this.store),
1072
+ new UrlRedactionSpanProcessor(),
476
1073
  new DebugIdSpanProcessor(),
477
1074
  new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
478
1075
  ] : [new ContextSpanProcessor(this.store)];
@@ -494,6 +1091,7 @@ var ZharpNode = class {
494
1091
  const propagator = new import_core.CompositePropagator({
495
1092
  propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
496
1093
  });
1094
+ const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
497
1095
  const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
498
1096
  this.sdk = new import_sdk_node.NodeSDK({
499
1097
  resource,
@@ -512,7 +1110,10 @@ var ZharpNode = class {
512
1110
  "@opentelemetry/instrumentation-dns": { enabled: false },
513
1111
  "@opentelemetry/instrumentation-net": { enabled: false },
514
1112
  "@opentelemetry/instrumentation-fs": { enabled: false },
515
- ...options.instrumentations
1113
+ ...options.instrumentations,
1114
+ ...bodies && {
1115
+ "@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
1116
+ }
516
1117
  }) : logsOnlyInstrumentations(options),
517
1118
  ...options.extraInstrumentations ?? []
518
1119
  ]