@zharp/node 0.3.0 → 0.4.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
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -33,7 +43,7 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
33
43
 
34
44
  // src/zharp.ts
35
45
  var import_node_module = require("module");
36
- var import_api4 = require("@opentelemetry/api");
46
+ var import_api5 = require("@opentelemetry/api");
37
47
  var import_core = require("@opentelemetry/core");
38
48
  var import_resources = require("@opentelemetry/resources");
39
49
  var import_sdk_node = require("@opentelemetry/sdk-node");
@@ -668,6 +678,571 @@ function withBodyCapture(settings, config = {}) {
668
678
  };
669
679
  }
670
680
 
681
+ // src/headers.ts
682
+ var import_node_http2 = require("http");
683
+ var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
684
+ var MAX_HEADERS = 40;
685
+ var MAX_VALUE = 512;
686
+ function headerSettings(option, env) {
687
+ if (option === false || env === "false" || env === "0") return null;
688
+ return { redact: typeof option === "object" && option?.redact ? option.redact : [] };
689
+ }
690
+ function shown(name, value, settings) {
691
+ if (value === void 0 || value === null) return null;
692
+ if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;
693
+ const text = Array.isArray(value) ? value.join(", ") : String(value);
694
+ return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}\u2026` : text;
695
+ }
696
+ function headerAttributes(side, headers, settings) {
697
+ const out = {};
698
+ let count = 0;
699
+ for (const [rawName, value] of Object.entries(headers ?? {})) {
700
+ if (count >= MAX_HEADERS) break;
701
+ const name = rawName.toLowerCase();
702
+ const text = shown(name, value, settings);
703
+ if (text === null) continue;
704
+ out[`http.${side}.header.${name}`] = text;
705
+ count++;
706
+ }
707
+ return out;
708
+ }
709
+ function withHeaderCapture(settings, config = {}) {
710
+ return {
711
+ ...config,
712
+ applyCustomAttributesOnSpan(span, request, response) {
713
+ config.applyCustomAttributesOnSpan?.(span, request, response);
714
+ try {
715
+ if (request instanceof import_node_http2.IncomingMessage) {
716
+ span.setAttributes(headerAttributes("request", request.headers, settings));
717
+ if (response instanceof import_node_http2.ServerResponse) span.setAttributes(headerAttributes("response", response.getHeaders(), settings));
718
+ } else if (request instanceof import_node_http2.ClientRequest) {
719
+ span.setAttributes(headerAttributes("request", request.getHeaders(), settings));
720
+ if (response instanceof import_node_http2.IncomingMessage) span.setAttributes(headerAttributes("response", response.headers, settings));
721
+ }
722
+ } catch {
723
+ }
724
+ }
725
+ };
726
+ }
727
+
728
+ // src/db-errors.ts
729
+ var import_api = require("@opentelemetry/api");
730
+ var import_instrumentation = require("@opentelemetry/instrumentation");
731
+
732
+ // src/version.ts
733
+ var VERSION = "0.4.0";
734
+
735
+ // src/source.ts
736
+ var import_node_fs = require("fs");
737
+ var import_node_path = require("path");
738
+ var import_node_url = require("url");
739
+ var nodeModule = __toESM(require("module"));
740
+ var SOURCE_CONTEXT_ATTRIBUTE = "zharp.source_context";
741
+ var AROUND = 5;
742
+ var MAX_FRAMES = 5;
743
+ var MAX_LINE = 300;
744
+ var MAX_BYTES = 12e3;
745
+ var MAX_FILE = 5e6;
746
+ var MAX_MAP = 3e7;
747
+ var MAX_CACHED = 50;
748
+ var enabled = true;
749
+ function setSourceContext(on) {
750
+ enabled = on;
751
+ }
752
+ var files = /* @__PURE__ */ new Map();
753
+ var maps = /* @__PURE__ */ new Map();
754
+ function remember(cache, key, value) {
755
+ if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value);
756
+ cache.set(key, value);
757
+ return value;
758
+ }
759
+ function toPath(file) {
760
+ if (file.startsWith("file://")) {
761
+ try {
762
+ return (0, import_node_url.fileURLToPath)(file);
763
+ } catch {
764
+ return null;
765
+ }
766
+ }
767
+ return (0, import_node_path.isAbsolute)(file) ? file : null;
768
+ }
769
+ function isApp(path) {
770
+ return !/[\\/]node_modules[\\/]/.test(path) && !path.startsWith("node:") && !/[\\/]@zharp[\\/]/.test(path);
771
+ }
772
+ function linesOf(path, text) {
773
+ if (files.has(path)) return files.get(path);
774
+ let content = text ?? null;
775
+ if (content === null) {
776
+ try {
777
+ if ((0, import_node_fs.statSync)(path).size > MAX_FILE) return remember(files, path, null);
778
+ content = (0, import_node_fs.readFileSync)(path, "utf8");
779
+ } catch {
780
+ return remember(files, path, null);
781
+ }
782
+ }
783
+ return remember(files, path, content.split(/\r\n|\n|\r/));
784
+ }
785
+ function mapOf(path) {
786
+ if (maps.has(path)) return maps.get(path);
787
+ const SourceMap2 = nodeModule.SourceMap;
788
+ const lines = linesOf(path);
789
+ if (!SourceMap2 || !lines) return remember(maps, path, null);
790
+ try {
791
+ let payload = null;
792
+ let mapPath = `${path}.map`;
793
+ const tail = lines.slice(-5).join("\n");
794
+ const url = /[#@]\s*sourceMappingURL=(\S+)\s*$/m.exec(tail)?.[1];
795
+ if (url?.startsWith("data:")) {
796
+ const base64 = /;base64,(.*)$/.exec(url)?.[1];
797
+ payload = base64 ? JSON.parse(Buffer.from(base64, "base64").toString("utf8")) : null;
798
+ mapPath = path;
799
+ } else {
800
+ if (url) mapPath = (0, import_node_path.resolve)((0, import_node_path.dirname)(path), decodeURIComponent(url));
801
+ if ((0, import_node_fs.statSync)(mapPath).size > MAX_MAP) return remember(maps, path, null);
802
+ payload = JSON.parse((0, import_node_fs.readFileSync)(mapPath, "utf8"));
803
+ }
804
+ if (!payload || !Array.isArray(payload.sources)) return remember(maps, path, null);
805
+ return remember(maps, path, {
806
+ map: new SourceMap2(payload),
807
+ dir: (0, import_node_path.dirname)(mapPath),
808
+ sources: payload.sources,
809
+ sourceRoot: typeof payload.sourceRoot === "string" ? payload.sourceRoot : "",
810
+ contents: Array.isArray(payload.sourcesContent) ? payload.sourcesContent : []
811
+ });
812
+ } catch {
813
+ return remember(maps, path, null);
814
+ }
815
+ }
816
+ function original(path, line, column) {
817
+ const loaded = mapOf(path);
818
+ if (!loaded) return null;
819
+ const entry = loaded.map.findEntry(line - 1, Math.max(0, column - 1));
820
+ if (!entry?.originalSource || entry.originalLine === void 0) return null;
821
+ const index = loaded.sources.findIndex((s) => s === entry.originalSource || entry.originalSource.endsWith(s));
822
+ const source = entry.originalSource.replace(/^webpack:\/\/[^/]*\//, "").replace(/^file:\/\//, "");
823
+ const file = (0, import_node_path.isAbsolute)(source) ? source : (0, import_node_path.resolve)(loaded.dir, loaded.sourceRoot, source);
824
+ return { file, line: entry.originalLine + 1, column: (entry.originalColumn ?? 0) + 1, text: index >= 0 ? loaded.contents[index] ?? null : null };
825
+ }
826
+ var FRAME = /^(\s*at (?:async )?(?:.*? \()?)((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/]).*?):(\d+):(\d+)(\)?)\s*$/;
827
+ function sourced(stack) {
828
+ if (!enabled || !stack) return { stack, context: null };
829
+ const out = [];
830
+ const seen = /* @__PURE__ */ new Set();
831
+ let mapped = 0;
832
+ const lines = stack.split("\n").map((text) => {
833
+ const m = FRAME.exec(text);
834
+ if (!m) return text;
835
+ const path = toPath(m[2]);
836
+ if (!path || !isApp(path) || mapped > 40) return text;
837
+ let file = m[2];
838
+ let line = Number(m[3]);
839
+ let column = Number(m[4]);
840
+ let content = null;
841
+ const from = /\.(c|m)?js$/.test(path) ? original(path, line, column) : null;
842
+ mapped++;
843
+ if (from && isApp(from.file)) {
844
+ file = from.file;
845
+ line = from.line;
846
+ column = from.column;
847
+ content = linesOf(from.file, from.text);
848
+ text = `${m[1]}${file}:${line}:${column}${m[5]}`;
849
+ } else if (!from) {
850
+ const built = linesOf(path);
851
+ const tail = built ? built.slice(-5).join("\n") : "";
852
+ content = /[#@]\s*(?:sourceMappingURL|debugId)=/.test(tail) ? null : built;
853
+ }
854
+ const key = `${file}:${line}`;
855
+ if (content && out.length < MAX_FRAMES && !seen.has(key) && content[line - 1] !== void 0) {
856
+ seen.add(key);
857
+ const cut = (s) => s.length > MAX_LINE ? `${s.slice(0, MAX_LINE - 1)}\u2026` : s;
858
+ out.push({
859
+ file,
860
+ line,
861
+ pre: content.slice(Math.max(0, line - 1 - AROUND), line - 1).map(cut),
862
+ code: cut(content[line - 1]),
863
+ post: content.slice(line, line + AROUND).map(cut)
864
+ });
865
+ }
866
+ return text;
867
+ });
868
+ while (out.length) {
869
+ const json = JSON.stringify(out);
870
+ if (Buffer.byteLength(json) <= MAX_BYTES) return { stack: lines.join("\n"), context: json };
871
+ out.pop();
872
+ }
873
+ return { stack: lines.join("\n"), context: null };
874
+ }
875
+
876
+ // src/db-errors.ts
877
+ var SQLSTATE = {
878
+ "23505": "UniqueViolation",
879
+ "23503": "ForeignKeyViolation",
880
+ "23502": "NotNullViolation",
881
+ "23514": "CheckViolation",
882
+ "23P01": "ExclusionViolation",
883
+ "22001": "StringDataRightTruncation",
884
+ "22003": "NumericValueOutOfRange",
885
+ "22P02": "InvalidTextRepresentation",
886
+ "22007": "InvalidDatetimeFormat",
887
+ "22008": "DatetimeFieldOverflow",
888
+ "22012": "DivisionByZero",
889
+ "42P01": "UndefinedTable",
890
+ "42703": "UndefinedColumn",
891
+ "42883": "UndefinedFunction",
892
+ "42601": "SyntaxError",
893
+ "42501": "InsufficientPrivilege",
894
+ "40001": "SerializationFailure",
895
+ "40P01": "DeadlockDetected",
896
+ "55P03": "LockNotAvailable",
897
+ "57014": "QueryCanceled",
898
+ "53300": "TooManyConnections",
899
+ "08006": "ConnectionFailure",
900
+ "08001": "ConnectionRefused",
901
+ "28P01": "InvalidPassword",
902
+ "3D000": "InvalidCatalogName"
903
+ };
904
+ var SYSTEM_NAMES = { postgresql: "Postgres", mysql: "MySQL", mariadb: "MariaDB", mongodb: "Mongo", redis: "Redis", mssql: "SqlServer", oracle: "Oracle", sqlite: "Sqlite" };
905
+ function dbErrorType(system, code, name) {
906
+ if (code && system === "postgresql" && SQLSTATE[code]) return SQLSTATE[code];
907
+ if (code && /^ER_[A-Z_]+$/.test(code)) return code;
908
+ if (name && !/^(error|Error|DatabaseError)$/.test(name)) return name;
909
+ return `${SYSTEM_NAMES[system] ?? "Database"}Error`;
910
+ }
911
+ function callSiteFrames(stack) {
912
+ const frames = (stack ?? "").split("\n").slice(1).filter((line) => /^\s+at /.test(line)).filter((line) => !/[\\/]@opentelemetry[\\/]|[\\/]@zharp[\\/]|\(node:|\bnode:internal\b|[\\/]require-in-the-middle[\\/]|[\\/]import-in-the-middle[\\/]/.test(line));
913
+ const firstApp = frames.findIndex((line) => !/[\\/]node_modules[\\/]/.test(line));
914
+ return (firstApp > 0 ? frames.slice(firstApp) : frames).slice(0, 40);
915
+ }
916
+ var CALL_SITE = (0, import_api.createContextKey)("zharp.db.callSite");
917
+ function stackFrom(fn) {
918
+ const limit = Error.stackTraceLimit;
919
+ Error.stackTraceLimit = 60;
920
+ const holder = {};
921
+ Error.captureStackTrace(holder, fn);
922
+ Error.stackTraceLimit = limit;
923
+ return holder.stack;
924
+ }
925
+ var attr = (attributes, ...names) => {
926
+ for (const name of names) {
927
+ const value = attributes[name];
928
+ if (value !== void 0 && value !== null && value !== "") return String(value);
929
+ }
930
+ return null;
931
+ };
932
+ function reportOf(failure) {
933
+ const error = failure.error;
934
+ const code = (error?.code !== void 0 ? String(error.code) : null) ?? failure.code;
935
+ const type = dbErrorType(failure.system, code, error?.name);
936
+ const message = error?.message || failure.scrubbed?.replace(/^.*?error of type '[^']*' occurred/i, `${SYSTEM_NAMES[failure.system] ?? "Database"} error`) || "The query failed";
937
+ const { stack, context: context3 } = sourced([`${type}: ${message}`, ...failure.frames].join("\n"));
938
+ const attributes = {
939
+ ...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {},
940
+ "zharp.mechanism": "db",
941
+ "db.system": failure.system,
942
+ ...failure.statement ? { "db.statement": failure.statement.slice(0, 4e3) } : {},
943
+ ...failure.database ? { "db.name": failure.database } : {},
944
+ ...code ? { "db.error.code": code } : {},
945
+ ...error?.constraint ? { "db.error.constraint": error.constraint } : {}
946
+ };
947
+ return { type, message, stack, attributes, spanContext: failure.spanContext };
948
+ }
949
+ var LONE_WAIT_MS = 1500;
950
+ var MAX_PENDING = 200;
951
+ var DbErrorSpanProcessor = class _DbErrorSpanProcessor {
952
+ constructor(send) {
953
+ this.send = send;
954
+ }
955
+ send;
956
+ callSites = /* @__PURE__ */ new WeakMap();
957
+ /** Failures not yet reported, by trace. */
958
+ pending = /* @__PURE__ */ new Map();
959
+ onStart(span, parentContext) {
960
+ const attributes = span.attributes ?? {};
961
+ if (!attr(attributes, "db.system", "db.system.name")) return;
962
+ const carried = (parentContext ?? import_api.context.active()).getValue(CALL_SITE);
963
+ const entry = {
964
+ frames: callSiteFrames(carried ?? stackFrom(_DbErrorSpanProcessor.prototype.onStart))
965
+ };
966
+ this.callSites.set(span, entry);
967
+ const record = span.recordException.bind(span);
968
+ span.recordException = (exception, time) => {
969
+ if (entry.exception === void 0) entry.exception = exception;
970
+ else record(exception, time);
971
+ };
972
+ }
973
+ onEnd(span) {
974
+ const entry = this.callSites.get(span);
975
+ if (entry && span.status.code === import_api.SpanStatusCode.ERROR) {
976
+ const attributes = span.attributes ?? {};
977
+ const exception = entry.exception;
978
+ const failure = {
979
+ spanContext: span.spanContext(),
980
+ traceId: span.spanContext().traceId,
981
+ system: attr(attributes, "db.system", "db.system.name") ?? "database",
982
+ statement: attr(attributes, "db.statement", "db.query.text"),
983
+ database: attr(attributes, "db.name", "db.namespace"),
984
+ code: attr(attributes, "error.type", "db.response.status_code"),
985
+ frames: entry.frames,
986
+ scrubbed: typeof exception === "string" ? exception : exception?.message ?? span.status.message ?? null,
987
+ ...exception instanceof Error ? { error: exception } : {}
988
+ };
989
+ this.add(failure);
990
+ }
991
+ const root = span.kind === import_api.SpanKind.SERVER || !span.parentSpanContext || !!span.parentSpanContext.isRemote;
992
+ if (root) {
993
+ const traceId = span.spanContext().traceId;
994
+ if (!this.pending.has(traceId)) return;
995
+ if (entry || span.status.code === import_api.SpanStatusCode.ERROR) setTimeout(() => this.flush(traceId), LONE_WAIT_MS).unref?.();
996
+ else this.flush(traceId);
997
+ }
998
+ }
999
+ add(failure) {
1000
+ const list = this.pending.get(failure.traceId) ?? [];
1001
+ list.push(failure);
1002
+ this.pending.set(failure.traceId, list);
1003
+ if (this.pending.size > MAX_PENDING) this.flush(this.pending.keys().next().value);
1004
+ }
1005
+ /** The driver's error, seen by the query wrapper: joined to the trace's latest failure. */
1006
+ attach(traceId, error) {
1007
+ if (!traceId || !(error instanceof Error)) return;
1008
+ const list = this.pending.get(traceId);
1009
+ if (!list || list.some((f) => f.error === error)) return;
1010
+ const failure = [...list].reverse().find((f) => !f.error && !f.done);
1011
+ if (failure) failure.error = error;
1012
+ }
1013
+ /**
1014
+ * `error` is being reported (by a framework's handler, as unhandled, or by captureError): the
1015
+ * failed query it came from, if any, so its details go into that one report and it isn't sent
1016
+ * again. Matched by the error itself, or what wraps it (`driverError`, `cause`); `latest` also
1017
+ * takes the request's latest failure whose driver error was never seen.
1018
+ */
1019
+ consume(traceId, error, latest = false) {
1020
+ const inner = (candidate) => {
1021
+ if (!candidate || typeof candidate !== "object") return [];
1022
+ const c = candidate;
1023
+ return [candidate, c.driverError, c.cause, c.originalError].filter(Boolean);
1024
+ };
1025
+ const wanted2 = inner(error);
1026
+ const lists = traceId ? [this.pending.get(traceId) ?? []] : [...this.pending.values()];
1027
+ for (const list of lists) {
1028
+ const failure = list.find((f) => !f.done && f.error && wanted2.includes(f.error)) ?? (latest && traceId ? [...list].reverse().find((f) => !f.done && !f.error) : void 0);
1029
+ if (failure) {
1030
+ failure.done = true;
1031
+ return failure;
1032
+ }
1033
+ }
1034
+ return null;
1035
+ }
1036
+ flush(traceId) {
1037
+ const list = this.pending.get(traceId);
1038
+ if (!list) return;
1039
+ this.pending.delete(traceId);
1040
+ for (const failure of list) if (!failure.done) this.send(failure);
1041
+ }
1042
+ forceFlush() {
1043
+ for (const traceId of [...this.pending.keys()]) this.flush(traceId);
1044
+ return Promise.resolve();
1045
+ }
1046
+ shutdown() {
1047
+ return this.forceFlush();
1048
+ }
1049
+ };
1050
+ var DbDriverErrorsInstrumentation = class extends import_instrumentation.InstrumentationBase {
1051
+ constructor(onError) {
1052
+ super("@zharp/node/db-driver-errors", VERSION, {});
1053
+ this.onError = onError;
1054
+ }
1055
+ onError;
1056
+ init() {
1057
+ const onError = (traceId, err) => {
1058
+ try {
1059
+ this.onError(traceId, err);
1060
+ } catch {
1061
+ }
1062
+ };
1063
+ const wrapQuery = (original2) => {
1064
+ const run = (self, args) => {
1065
+ const traceId = import_api.trace.getActiveSpan()?.spanContext().traceId;
1066
+ const callback = args.findIndex((a) => typeof a === "function");
1067
+ if (callback >= 0) {
1068
+ const cb = args[callback];
1069
+ args[callback] = function(err, ...rest) {
1070
+ if (err) onError(traceId, err);
1071
+ return cb.call(this, err, ...rest);
1072
+ };
1073
+ return original2.apply(self, args);
1074
+ }
1075
+ const result = original2.apply(self, args);
1076
+ if (!result || typeof result.then !== "function" || typeof result.submit === "function") return result;
1077
+ result.then(void 0, (err) => onError(traceId, err));
1078
+ return result;
1079
+ };
1080
+ return function query(...args) {
1081
+ const active = import_api.context.active();
1082
+ if (active.getValue(CALL_SITE) !== void 0) return run(this, args);
1083
+ return import_api.context.with(active.setValue(CALL_SITE, stackFrom(query)), () => run(this, args));
1084
+ };
1085
+ };
1086
+ const patch = (moduleExports) => {
1087
+ for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
1088
+ if (target?.query && !target.query.__zharpWrapped) {
1089
+ const wrapped = wrapQuery(target.query);
1090
+ wrapped.__zharpWrapped = true;
1091
+ wrapped.__zharpOriginal = target.query;
1092
+ target.query = wrapped;
1093
+ }
1094
+ }
1095
+ return moduleExports;
1096
+ };
1097
+ const unpatch = (moduleExports) => {
1098
+ for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
1099
+ if (target?.query?.__zharpOriginal) target.query = target.query.__zharpOriginal;
1100
+ }
1101
+ };
1102
+ return [new import_instrumentation.InstrumentationNodeModuleDefinition("pg", [">=8 <9"], patch, unpatch)];
1103
+ }
1104
+ };
1105
+
1106
+ // src/framework-errors.ts
1107
+ var import_instrumentation2 = require("@opentelemetry/instrumentation");
1108
+ function statusOf(error) {
1109
+ if (!error || typeof error !== "object") return 500;
1110
+ const e = error;
1111
+ try {
1112
+ if (typeof e.getStatus === "function") {
1113
+ const status = Number(e.getStatus());
1114
+ if (Number.isFinite(status)) return status;
1115
+ }
1116
+ } catch {
1117
+ }
1118
+ for (const value of [e.status, e.statusCode]) {
1119
+ const status = Number(value);
1120
+ if (Number.isInteger(status) && status >= 100 && status < 600) return status;
1121
+ }
1122
+ return 500;
1123
+ }
1124
+ var WRAPPED = /* @__PURE__ */ Symbol.for("zharp.frameworkErrors");
1125
+ var FrameworkErrorsInstrumentation = class extends import_instrumentation2.InstrumentationBase {
1126
+ constructor(sink) {
1127
+ super("@zharp/node/framework-errors", VERSION, {});
1128
+ this.sink = sink;
1129
+ }
1130
+ sink;
1131
+ init() {
1132
+ const report = (error, mechanism) => {
1133
+ try {
1134
+ if (statusOf(error) >= 500) this.sink(error, mechanism);
1135
+ } catch {
1136
+ }
1137
+ };
1138
+ const nest = new import_instrumentation2.InstrumentationNodeModuleFile(
1139
+ "@nestjs/core/exceptions/exceptions-handler.js",
1140
+ [">=8 <13"],
1141
+ (moduleExports) => {
1142
+ const proto = moduleExports?.ExceptionsHandler?.prototype;
1143
+ if (proto?.next && !proto.next[WRAPPED]) {
1144
+ const original2 = proto.next;
1145
+ const next = function(exception, ...rest) {
1146
+ report(exception, "nestjs");
1147
+ return original2.call(this, exception, ...rest);
1148
+ };
1149
+ next[WRAPPED] = original2;
1150
+ proto.next = next;
1151
+ }
1152
+ return moduleExports;
1153
+ },
1154
+ (moduleExports) => {
1155
+ const proto = moduleExports?.ExceptionsHandler?.prototype;
1156
+ if (proto?.next?.[WRAPPED]) proto.next = proto.next[WRAPPED];
1157
+ }
1158
+ );
1159
+ const finalhandler = new import_instrumentation2.InstrumentationNodeModuleDefinition(
1160
+ "finalhandler",
1161
+ [">=1 <3"],
1162
+ (moduleExports) => {
1163
+ if (typeof moduleExports !== "function" || moduleExports[WRAPPED]) return moduleExports;
1164
+ const original2 = moduleExports;
1165
+ const wrapped = function(...args) {
1166
+ const done = original2.apply(this, args);
1167
+ return function(err, ...rest) {
1168
+ if (err) report(err, "express");
1169
+ return done.call(this, err, ...rest);
1170
+ };
1171
+ };
1172
+ Object.assign(wrapped, original2);
1173
+ wrapped[WRAPPED] = original2;
1174
+ return wrapped;
1175
+ },
1176
+ (moduleExports) => moduleExports?.[WRAPPED] ?? moduleExports
1177
+ );
1178
+ return [new import_instrumentation2.InstrumentationNodeModuleDefinition("@nestjs/core", [">=8 <13"], void 0, void 0, [nest]), finalhandler];
1179
+ }
1180
+ };
1181
+ var RecordedExceptionsProcessor = class {
1182
+ constructor(report) {
1183
+ this.report = report;
1184
+ }
1185
+ report;
1186
+ pending = /* @__PURE__ */ new Map();
1187
+ onStart(span) {
1188
+ const scope = span.instrumentationScope?.name ?? span.instrumentationLibrary?.name ?? "";
1189
+ if (!scope.startsWith("@opentelemetry/instrumentation-") && scope !== "next.js") return;
1190
+ if (span.attributes?.["db.system"] || span.attributes?.["db.system.name"]) return;
1191
+ const original2 = span.recordException.bind(span);
1192
+ span.recordException = (exception, time) => {
1193
+ try {
1194
+ if (!exception || typeof exception !== "object") return original2(exception, time);
1195
+ const name = typeof exception.name === "string" && exception.name !== "error" ? exception.name : exception.constructor?.name || "Error";
1196
+ span.addEvent("exception", {
1197
+ "exception.type": name,
1198
+ "exception.message": String(exception.message ?? ""),
1199
+ ...typeof exception.stack === "string" ? { "exception.stacktrace": exception.stack } : {},
1200
+ "zharp.deferred": "true"
1201
+ }, time);
1202
+ const traceId = span.spanContext().traceId;
1203
+ const list = this.pending.get(traceId) ?? [];
1204
+ if (!list.some((p) => p.error === exception)) list.push({ error: exception, spanContext: span.spanContext(), scope: mechanismOf(scope) });
1205
+ this.pending.set(traceId, list);
1206
+ if (this.pending.size > 500) this.pending.delete(this.pending.keys().next().value);
1207
+ } catch {
1208
+ original2(exception, time);
1209
+ }
1210
+ };
1211
+ }
1212
+ onEnd(span) {
1213
+ const parent = span.parentSpanContext;
1214
+ const isRoot = span.kind === 1 || !parent || parent.isRemote;
1215
+ if (!isRoot) return;
1216
+ const traceId = span.spanContext().traceId;
1217
+ const list = this.pending.get(traceId);
1218
+ if (!list) return;
1219
+ this.pending.delete(traceId);
1220
+ const status = Number(span.attributes?.["http.response.status_code"] ?? span.attributes?.["http.status_code"]);
1221
+ const failed = Number.isFinite(status) && status > 0 ? status >= 500 : span.status?.code === 2;
1222
+ if (!failed) return;
1223
+ const seen = /* @__PURE__ */ new Set();
1224
+ for (const p of list) {
1225
+ if (seen.has(p.error)) continue;
1226
+ seen.add(p.error);
1227
+ if (statusOf(p.error) < 500) continue;
1228
+ this.report(p.error, p.spanContext, p.scope);
1229
+ break;
1230
+ }
1231
+ }
1232
+ forceFlush() {
1233
+ return Promise.resolve();
1234
+ }
1235
+ shutdown() {
1236
+ this.pending.clear();
1237
+ return Promise.resolve();
1238
+ }
1239
+ };
1240
+ function mechanismOf(scope) {
1241
+ const name = scope.replace("@opentelemetry/instrumentation-", "").replace(/-core$/, "");
1242
+ if (name === "router") return "express";
1243
+ return name === "next.js" ? "nextjs" : name;
1244
+ }
1245
+
671
1246
  // src/urls.ts
672
1247
  var URL_KEYS = ["url.full", "http.url", "http.target"];
673
1248
  var UrlRedactionSpanProcessor = class {
@@ -703,7 +1278,7 @@ var UrlRedactionSpanProcessor = class {
703
1278
  };
704
1279
 
705
1280
  // src/context.ts
706
- var import_api = require("@opentelemetry/api");
1281
+ var import_api2 = require("@opentelemetry/api");
707
1282
  var BAGGAGE_KEYS = ["enduser.id", "session.id"];
708
1283
  function userAttributes(user) {
709
1284
  const out = { "enduser.id": String(user.id) };
@@ -720,7 +1295,7 @@ var ContextStore = class {
720
1295
  localRoots = /* @__PURE__ */ new Map();
721
1296
  /** Set the user for the request in progress, or for the whole process outside one. */
722
1297
  setUser(user) {
723
- const span = import_api.trace.getActiveSpan();
1298
+ const span = import_api2.trace.getActiveSpan();
724
1299
  const traceId = span?.spanContext().traceId;
725
1300
  if (!span || !traceId) {
726
1301
  this.globalUser = user;
@@ -740,7 +1315,7 @@ var ContextStore = class {
740
1315
  return user ? { ...this.tags, ...user } : { ...this.tags };
741
1316
  }
742
1317
  noteStart(span, parent) {
743
- const parentSpan = import_api.trace.getSpanContext(parent);
1318
+ const parentSpan = import_api2.trace.getSpanContext(parent);
744
1319
  if (!parentSpan || parentSpan.isRemote) {
745
1320
  const { traceId, spanId } = span.spanContext();
746
1321
  if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
@@ -755,7 +1330,7 @@ var ContextStore = class {
755
1330
  };
756
1331
  function fromBaggage(ctx) {
757
1332
  const out = {};
758
- const baggage = import_api.propagation.getBaggage(ctx);
1333
+ const baggage = import_api2.propagation.getBaggage(ctx);
759
1334
  if (!baggage) return out;
760
1335
  for (const key of BAGGAGE_KEYS) {
761
1336
  const value = baggage.getEntry(key)?.value;
@@ -792,8 +1367,8 @@ var ContextLogProcessor = class {
792
1367
  store;
793
1368
  onEmit(record, ctx) {
794
1369
  try {
795
- const active = ctx ?? import_api.context.active();
796
- const traceId = record.spanContext?.traceId ?? import_api.trace.getSpanContext(active)?.traceId;
1370
+ const active = ctx ?? import_api2.context.active();
1371
+ const traceId = record.spanContext?.traceId ?? import_api2.trace.getSpanContext(active)?.traceId;
797
1372
  const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
798
1373
  for (const [key, value] of Object.entries(add)) {
799
1374
  if (record.attributes[key] === void 0) record.setAttribute(key, value);
@@ -811,7 +1386,7 @@ var ContextLogProcessor = class {
811
1386
 
812
1387
  // src/console.ts
813
1388
  var import_node_util = require("util");
814
- var import_api2 = require("@opentelemetry/api");
1389
+ var import_api3 = require("@opentelemetry/api");
815
1390
 
816
1391
  // src/capture-state.ts
817
1392
  var depth = 0;
@@ -851,22 +1426,22 @@ function alreadySent(line) {
851
1426
 
852
1427
  // src/console.ts
853
1428
  var LEVELS = [
854
- ["debug", import_api2.SeverityNumber.DEBUG, "DEBUG"],
855
- ["trace", import_api2.SeverityNumber.TRACE, "TRACE"],
856
- ["log", import_api2.SeverityNumber.INFO, "INFO"],
857
- ["info", import_api2.SeverityNumber.INFO, "INFO"],
858
- ["warn", import_api2.SeverityNumber.WARN, "WARN"],
859
- ["error", import_api2.SeverityNumber.ERROR, "ERROR"]
1429
+ ["debug", import_api3.SeverityNumber.DEBUG, "DEBUG"],
1430
+ ["trace", import_api3.SeverityNumber.TRACE, "TRACE"],
1431
+ ["log", import_api3.SeverityNumber.INFO, "INFO"],
1432
+ ["info", import_api3.SeverityNumber.INFO, "INFO"],
1433
+ ["warn", import_api3.SeverityNumber.WARN, "WARN"],
1434
+ ["error", import_api3.SeverityNumber.ERROR, "ERROR"]
860
1435
  ];
861
1436
  var emitting = false;
862
1437
  function captureConsole(logger) {
863
1438
  const originals = /* @__PURE__ */ new Map();
864
1439
  for (const [method, severityNumber, severityText] of LEVELS) {
865
- const original = console[method];
866
- if (typeof original !== "function" || original.__zharp) continue;
867
- originals.set(method, original);
1440
+ const original2 = console[method];
1441
+ if (typeof original2 !== "function" || original2.__zharp) continue;
1442
+ originals.set(method, original2);
868
1443
  const patched = function(...args) {
869
- quiet(() => original.apply(this ?? console, args));
1444
+ quiet(() => original2.apply(this ?? console, args));
870
1445
  if (emitting) return;
871
1446
  emitting = true;
872
1447
  try {
@@ -883,34 +1458,34 @@ function captureConsole(logger) {
883
1458
  console[method] = patched;
884
1459
  }
885
1460
  return () => {
886
- for (const [method, original] of originals) console[method] = original;
1461
+ for (const [method, original2] of originals) console[method] = original2;
887
1462
  };
888
1463
  }
889
1464
 
890
1465
  // src/stdout.ts
891
- var import_api3 = require("@opentelemetry/api");
1466
+ var import_api4 = require("@opentelemetry/api");
892
1467
  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"]
1468
+ trace: [import_api4.SeverityNumber.TRACE, "TRACE"],
1469
+ verbose: [import_api4.SeverityNumber.DEBUG, "DEBUG"],
1470
+ debug: [import_api4.SeverityNumber.DEBUG, "DEBUG"],
1471
+ log: [import_api4.SeverityNumber.INFO, "INFO"],
1472
+ info: [import_api4.SeverityNumber.INFO, "INFO"],
1473
+ notice: [import_api4.SeverityNumber.INFO, "INFO"],
1474
+ warn: [import_api4.SeverityNumber.WARN, "WARN"],
1475
+ warning: [import_api4.SeverityNumber.WARN, "WARN"],
1476
+ error: [import_api4.SeverityNumber.ERROR, "ERROR"],
1477
+ err: [import_api4.SeverityNumber.ERROR, "ERROR"],
1478
+ crit: [import_api4.SeverityNumber.FATAL, "FATAL"],
1479
+ critical: [import_api4.SeverityNumber.FATAL, "FATAL"],
1480
+ fatal: [import_api4.SeverityNumber.FATAL, "FATAL"],
1481
+ emerg: [import_api4.SeverityNumber.FATAL, "FATAL"],
1482
+ alert: [import_api4.SeverityNumber.FATAL, "FATAL"]
908
1483
  };
909
1484
  var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "debug"], [0, "trace"]];
910
1485
  var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
911
1486
  var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
912
1487
  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;
1488
+ var MAX_LINE2 = 32 * 1024;
914
1489
  var FLUSH_MS = 200;
915
1490
  function levelOf(value) {
916
1491
  if (typeof value === "number") {
@@ -963,13 +1538,13 @@ function captureOutput(logger) {
963
1538
  [process.stderr, "stderr", LEVELS2.warn]
964
1539
  ]) {
965
1540
  if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
966
- const original = stream.write;
1541
+ const original2 = stream.write;
967
1542
  let pending = "";
968
1543
  let pendingContext;
969
1544
  let timer;
970
1545
  const emitLine = (line, ctx) => {
971
1546
  if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
972
- const parsed2 = parseLine(line.length > MAX_LINE ? line.slice(0, MAX_LINE) : line);
1547
+ const parsed2 = parseLine(line.length > MAX_LINE2 ? line.slice(0, MAX_LINE2) : line);
973
1548
  if (!parsed2.body.trim()) return;
974
1549
  const [severityNumber, severityText] = parsed2.level ?? fallback;
975
1550
  quiet(() => logger.emit({
@@ -992,14 +1567,14 @@ function captureOutput(logger) {
992
1567
  if (isQuiet()) return;
993
1568
  const text = typeof chunk === "string" ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : "utf8") : "";
994
1569
  if (!text) return;
995
- if (!pending) pendingContext = import_api3.context.active();
1570
+ if (!pending) pendingContext = import_api4.context.active();
996
1571
  pending += text;
997
1572
  const lines = pending.split("\n");
998
1573
  pending = lines.pop() ?? "";
999
1574
  const ctx = pendingContext;
1000
- if (pending) pendingContext = import_api3.context.active();
1575
+ if (pending) pendingContext = import_api4.context.active();
1001
1576
  for (const line of lines) emitLine(line, ctx);
1002
- if (pending.length > MAX_LINE) flush();
1577
+ if (pending.length > MAX_LINE2) flush();
1003
1578
  else if (pending && !timer) {
1004
1579
  timer = setTimeout(flush, FLUSH_MS);
1005
1580
  timer.unref?.();
@@ -1010,14 +1585,14 @@ function captureOutput(logger) {
1010
1585
  take(chunk, encoding);
1011
1586
  } catch {
1012
1587
  }
1013
- return original.call(this ?? stream, chunk, encoding, callback);
1588
+ return original2.call(this ?? stream, chunk, encoding, callback);
1014
1589
  };
1015
1590
  patched.__zharp = true;
1016
1591
  stream.write = patched;
1017
1592
  undo.push(() => {
1018
1593
  if (timer) clearTimeout(timer);
1019
1594
  if (pending) flush();
1020
- stream.write = original;
1595
+ stream.write = original2;
1021
1596
  });
1022
1597
  }
1023
1598
  return () => undo.forEach((fn) => fn());
@@ -1026,26 +1601,26 @@ function stampOutput() {
1026
1601
  const undo = [];
1027
1602
  for (const stream of [process.stdout, process.stderr]) {
1028
1603
  if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
1029
- const original = stream.write;
1604
+ const original2 = stream.write;
1030
1605
  const patched = function(chunk, encoding, callback) {
1031
1606
  let out = chunk;
1032
1607
  try {
1033
1608
  out = stamped(chunk, encoding);
1034
1609
  } catch {
1035
1610
  }
1036
- return original.call(this ?? stream, out, encoding, callback);
1611
+ return original2.call(this ?? stream, out, encoding, callback);
1037
1612
  };
1038
1613
  patched.__zharpStamp = true;
1039
1614
  stream.write = patched;
1040
1615
  undo.push(() => {
1041
- stream.write = original;
1616
+ stream.write = original2;
1042
1617
  });
1043
1618
  }
1044
1619
  return () => undo.forEach((fn) => fn());
1045
1620
  }
1046
1621
  function stamped(chunk, encoding) {
1047
- const span = import_api3.trace.getActiveSpan()?.spanContext();
1048
- if (!span || !(0, import_api3.isSpanContextValid)(span)) return chunk;
1622
+ const span = import_api4.trace.getActiveSpan()?.spanContext();
1623
+ if (!span || !(0, import_api4.isSpanContextValid)(span)) return chunk;
1049
1624
  const isBytes = chunk instanceof Uint8Array;
1050
1625
  if (typeof chunk !== "string" && !isBytes) return chunk;
1051
1626
  const enc = typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8";
@@ -1090,7 +1665,7 @@ function stampLine(line, traceId, spanId) {
1090
1665
 
1091
1666
  // ../../internal/src/debug-ids.ts
1092
1667
  var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
1093
- var files = /* @__PURE__ */ new Map();
1668
+ var files2 = /* @__PURE__ */ new Map();
1094
1669
  var parsed = /* @__PURE__ */ new Set();
1095
1670
  function registry() {
1096
1671
  const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
@@ -1129,7 +1704,7 @@ function refresh() {
1129
1704
  for (const line of stack.split("\n")) {
1130
1705
  const file = frameFile(line);
1131
1706
  if (file) {
1132
- files.set(file, id);
1707
+ files2.set(file, id);
1133
1708
  break;
1134
1709
  }
1135
1710
  }
@@ -1139,10 +1714,10 @@ function debugIdsFor(stack) {
1139
1714
  if (!stack) return void 0;
1140
1715
  try {
1141
1716
  refresh();
1142
- if (files.size === 0) return void 0;
1717
+ if (files2.size === 0) return void 0;
1143
1718
  let out;
1144
1719
  for (const file of stackFiles(stack)) {
1145
- const id = files.get(file);
1720
+ const id = files2.get(file);
1146
1721
  if (id) (out ??= {})[file] = id;
1147
1722
  }
1148
1723
  return out;
@@ -1225,18 +1800,18 @@ function exceptionAttributes(error, handled) {
1225
1800
  const cause = error.cause;
1226
1801
  if (cause instanceof Error && cause.stack) stack += `
1227
1802
  Caused by: ${cause.stack}`;
1803
+ const { stack: readable, context: context3 } = sourced(stack);
1228
1804
  return {
1229
1805
  "exception.type": type,
1230
1806
  "exception.message": message,
1231
- "exception.stacktrace": stack,
1807
+ "exception.stacktrace": readable,
1232
1808
  "zharp.handled": handled ? "true" : "false",
1233
- ...debugIdAttributes(stack)
1809
+ // From the stack as it ran: frames resolved here keep their bundle's ID for uploaded maps.
1810
+ ...debugIdAttributes(stack),
1811
+ ...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {}
1234
1812
  };
1235
1813
  }
1236
1814
 
1237
- // src/version.ts
1238
- var VERSION = "0.3.0";
1239
-
1240
1815
  // src/zharp.ts
1241
1816
  var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
1242
1817
  var EXIT_FLUSH_MS = 2e3;
@@ -1251,6 +1826,8 @@ var ZharpNode = class {
1251
1826
  tracing = true;
1252
1827
  /** Errors already sent, so one that is both rejected and then thrown is reported once. */
1253
1828
  reported = /* @__PURE__ */ new WeakSet();
1829
+ /** Failed queries waiting to be reported, once and with their call site. */
1830
+ dbErrors = null;
1254
1831
  /** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
1255
1832
  log = {
1256
1833
  trace: (m, a) => this.emit("trace", m, a),
@@ -1304,13 +1881,20 @@ var ZharpNode = class {
1304
1881
  const prefixed = Object.fromEntries(
1305
1882
  Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
1306
1883
  );
1307
- import_api4.diag.setLogger(prefixed, import_api4.DiagLogLevel.DEBUG);
1884
+ import_api5.diag.setLogger(prefixed, import_api5.DiagLogLevel.DEBUG);
1308
1885
  }
1309
1886
  registerEsmHook();
1310
1887
  const headers = { Authorization: `Bearer ${key}` };
1311
1888
  const exporterOptions = { headers, compression: "gzip" };
1889
+ setSourceContext(switchOn(options.captureSourceContext, "ZHARP_CAPTURE_SOURCE_CONTEXT", true));
1890
+ const queryErrors = tracing && switchOn(options.captureQueryErrors, "ZHARP_CAPTURE_QUERY_ERRORS", true);
1891
+ this.dbErrors = queryErrors ? new DbErrorSpanProcessor((failure) => this.sendQueryError(failure, true, "error", { "zharp.mechanism": "db" })) : null;
1312
1892
  this.spanProcessors = tracing ? [
1313
1893
  new ContextSpanProcessor(this.store),
1894
+ // Before the database processor: a request that failed claims its query's error first.
1895
+ ...options.captureUncaught !== false ? [new RecordedExceptionsProcessor((error, spanContext, mechanism) => import_api5.context.with(import_api5.trace.setSpanContext(import_api5.context.active(), spanContext), () => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true)))] : [],
1896
+ // Before the exporter: it keeps the query's scrubbed exception off the span.
1897
+ ...this.dbErrors ? [this.dbErrors] : [],
1314
1898
  new UrlRedactionSpanProcessor(),
1315
1899
  new DebugIdSpanProcessor(),
1316
1900
  new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
@@ -1335,6 +1919,10 @@ var ZharpNode = class {
1335
1919
  propagators: [new import_core.W3CTraceContextPropagator(), new import_core.W3CBaggagePropagator()]
1336
1920
  });
1337
1921
  const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
1922
+ const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
1923
+ const ownHttp = options.instrumentations?.["@opentelemetry/instrumentation-http"];
1924
+ const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
1925
+ const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
1338
1926
  const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
1339
1927
  this.sdk = new import_sdk_node.NodeSDK({
1340
1928
  resource,
@@ -1355,15 +1943,15 @@ var ZharpNode = class {
1355
1943
  "@opentelemetry/instrumentation-fs": { enabled: false },
1356
1944
  ...options.instrumentations,
1357
1945
  ...bridges,
1358
- ...bodies && {
1359
- "@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
1360
- }
1946
+ ...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
1361
1947
  }) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
1948
+ ...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
1949
+ ...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
1362
1950
  ...options.extraInstrumentations ?? []
1363
1951
  ]
1364
1952
  });
1365
1953
  this.sdk.start();
1366
- this.logger = import_api4.logs.getLogger("@zharp/node", VERSION);
1954
+ this.logger = import_api5.logs.getLogger("@zharp/node", VERSION);
1367
1955
  if (correlation) this.teardowns.push(stampOutput());
1368
1956
  if (sendLogs) {
1369
1957
  if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
@@ -1406,16 +1994,36 @@ var ZharpNode = class {
1406
1994
  captureError(error, attributes) {
1407
1995
  this.report(error, true, "error", attributes);
1408
1996
  }
1997
+ /**
1998
+ * Next.js (15+): errors a route handler, server component, server action or middleware threw,
1999
+ * which Next answers with an error page and only prints. Export it from instrumentation.ts:
2000
+ *
2001
+ * export const onRequestError = Zharp.onRequestError;
2002
+ *
2003
+ * Each is reported once as a crash, with the request's path, method and route. A bound function,
2004
+ * so it can be exported as it is.
2005
+ */
2006
+ onRequestError = (error, request, context3) => {
2007
+ this.report(error, false, "error", {
2008
+ "zharp.mechanism": "nextjs",
2009
+ ...request?.method ? { "http.request.method": request.method } : {},
2010
+ ...request?.path ? { "url.path": request.path } : {},
2011
+ ...context3?.routePath ? { "http.route": context3.routePath } : {},
2012
+ ...context3?.routeType ? { "next.route_type": context3.routeType } : {},
2013
+ ...context3?.routerKind ? { "next.router_kind": context3.routerKind } : {},
2014
+ ...context3?.renderSource ? { "next.render_source": context3.renderSource } : {}
2015
+ }, true);
2016
+ };
1409
2017
  /**
1410
2018
  * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
1411
2019
  * throw or rejection marks the span as failed and is passed on unchanged.
1412
2020
  */
1413
2021
  startSpan(name, fn, options = {}) {
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);
2022
+ if (!this.tracing) return fn(import_api5.trace.wrapSpanContext(import_api5.trace.getActiveSpan()?.spanContext() ?? import_api5.INVALID_SPAN_CONTEXT));
2023
+ const tracer = import_api5.trace.getTracer("@zharp/node", VERSION);
1416
2024
  return tracer.startActiveSpan(name, options, (span) => {
1417
2025
  const fail = (error) => {
1418
- span.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: asError(error).message });
2026
+ span.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: asError(error).message });
1419
2027
  span.end();
1420
2028
  };
1421
2029
  let result;
@@ -1445,7 +2053,7 @@ var ZharpNode = class {
1445
2053
  async flush(timeoutMs = 5e3) {
1446
2054
  const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
1447
2055
  })));
1448
- await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())]);
2056
+ await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
1449
2057
  }
1450
2058
  /** Flush, stop, and put back everything that was patched. */
1451
2059
  async shutdown() {
@@ -1477,14 +2085,20 @@ var ZharpNode = class {
1477
2085
  } catch {
1478
2086
  }
1479
2087
  }
1480
- report(value, handled, level, attributes) {
2088
+ report(value, handled, level, attributes, fromFramework = false) {
1481
2089
  try {
1482
2090
  if (!this.logger) return;
1483
- const error = asError(value);
1484
- if (value && typeof value === "object") {
1485
- if (this.reported.has(value)) return;
1486
- this.reported.add(value);
2091
+ if (value && typeof value === "object" && this.reported.has(value)) return;
2092
+ const traceId = import_api5.trace.getActiveSpan()?.spanContext().traceId;
2093
+ const failure = this.dbErrors?.consume(traceId, value, fromFramework);
2094
+ if (failure) {
2095
+ if (value && typeof value === "object") this.reported.add(value);
2096
+ this.sendQueryError(failure, handled, level, attributes);
2097
+ if (!handled) import_api5.trace.getActiveSpan()?.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: failure.error?.message ?? "The query failed" });
2098
+ return;
1487
2099
  }
2100
+ const error = asError(value);
2101
+ if (value && typeof value === "object") this.reported.add(value);
1488
2102
  const exception = exceptionAttributes(error, handled);
1489
2103
  this.logger.emit({
1490
2104
  severityNumber: SEVERITY[level],
@@ -1492,7 +2106,33 @@ var ZharpNode = class {
1492
2106
  body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
1493
2107
  attributes: { ...attributes, ...exception }
1494
2108
  });
1495
- if (!handled) import_api4.trace.getActiveSpan()?.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: error.message });
2109
+ if (!handled) import_api5.trace.getActiveSpan()?.setStatus({ code: import_api5.SpanStatusCode.ERROR, message: error.message });
2110
+ } catch {
2111
+ }
2112
+ }
2113
+ /** A failed query as an error, in the query's own span so the error shows the query. */
2114
+ sendQueryError(failure, handled, level = "error", attributes) {
2115
+ try {
2116
+ if (!this.logger) return;
2117
+ if (failure.error) {
2118
+ if (this.reported.has(failure.error) && handled) return;
2119
+ this.reported.add(failure.error);
2120
+ }
2121
+ const report = reportOf(failure);
2122
+ this.logger.emit({
2123
+ severityNumber: SEVERITY[level],
2124
+ severityText: level.toUpperCase(),
2125
+ body: `${report.type}: ${report.message}`,
2126
+ attributes: {
2127
+ ...report.attributes,
2128
+ ...attributes,
2129
+ "exception.type": report.type,
2130
+ "exception.message": report.message,
2131
+ "exception.stacktrace": report.stack,
2132
+ "zharp.handled": handled ? "true" : "false"
2133
+ },
2134
+ context: import_api5.trace.setSpanContext(import_api5.context.active(), report.spanContext)
2135
+ });
1496
2136
  } catch {
1497
2137
  }
1498
2138
  }
@@ -1651,8 +2291,8 @@ var ExtractOnlyPropagator = class {
1651
2291
  inner;
1652
2292
  inject() {
1653
2293
  }
1654
- extract(context, carrier, getter) {
1655
- return this.inner.extract(context, carrier, getter);
2294
+ extract(context3, carrier, getter) {
2295
+ return this.inner.extract(context3, carrier, getter);
1656
2296
  }
1657
2297
  fields() {
1658
2298
  return [];