@zharp/node 0.3.0 → 0.5.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/README.md +22 -1
- package/dist/index.d.mts +107 -2
- package/dist/index.d.ts +107 -2
- package/dist/index.js +1279 -79
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1246 -53
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -6,16 +6,20 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
6
6
|
});
|
|
7
7
|
|
|
8
8
|
// src/zharp.ts
|
|
9
|
-
import { register as registerLoader } from "module";
|
|
9
|
+
import { createRequire, isBuiltin, register as registerLoader } from "module";
|
|
10
|
+
import { join } from "path";
|
|
10
11
|
import {
|
|
12
|
+
context as context2,
|
|
11
13
|
DiagLogLevel,
|
|
12
14
|
diag,
|
|
13
15
|
INVALID_SPAN_CONTEXT,
|
|
14
16
|
logs,
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
propagation as propagation2,
|
|
18
|
+
SpanKind as SpanKind2,
|
|
19
|
+
SpanStatusCode as SpanStatusCode2,
|
|
20
|
+
trace as trace4
|
|
17
21
|
} from "@opentelemetry/api";
|
|
18
|
-
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
22
|
+
import { CompositePropagator, unsuppressTracing, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
19
23
|
import { envDetector, hostDetector, resourceFromAttributes } from "@opentelemetry/resources";
|
|
20
24
|
import { NodeSDK } from "@opentelemetry/sdk-node";
|
|
21
25
|
import {
|
|
@@ -654,6 +658,577 @@ function withBodyCapture(settings, config = {}) {
|
|
|
654
658
|
};
|
|
655
659
|
}
|
|
656
660
|
|
|
661
|
+
// src/headers.ts
|
|
662
|
+
import { ClientRequest as ClientRequest2, IncomingMessage as IncomingMessage2, ServerResponse as ServerResponse2 } from "http";
|
|
663
|
+
|
|
664
|
+
// ../../internal/src/headers.ts
|
|
665
|
+
var SECRET = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", "x-csrf-token", "x-xsrf-token"]);
|
|
666
|
+
var MAX_HEADERS = 40;
|
|
667
|
+
var MAX_VALUE = 512;
|
|
668
|
+
function headerSettings(option, env) {
|
|
669
|
+
if (option === false || env === "false" || env === "0") return null;
|
|
670
|
+
return { redact: typeof option === "object" && option?.redact ? option.redact : [] };
|
|
671
|
+
}
|
|
672
|
+
function shown(name, value, settings) {
|
|
673
|
+
if (value === void 0 || value === null) return null;
|
|
674
|
+
if (SECRET.has(name) || isSecretKey(name, settings.redact)) return FILTERED;
|
|
675
|
+
const text = Array.isArray(value) ? value.join(", ") : String(value);
|
|
676
|
+
return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}\u2026` : text;
|
|
677
|
+
}
|
|
678
|
+
function headerAttributes(side, headers, settings) {
|
|
679
|
+
const out = {};
|
|
680
|
+
if (!headers) return out;
|
|
681
|
+
const entries = typeof headers[Symbol.iterator] === "function" ? [...headers] : Object.entries(headers);
|
|
682
|
+
let count = 0;
|
|
683
|
+
for (const [rawName, value] of entries) {
|
|
684
|
+
if (count >= MAX_HEADERS) break;
|
|
685
|
+
const name = rawName.toLowerCase();
|
|
686
|
+
const text = shown(name, value, settings);
|
|
687
|
+
if (text === null) continue;
|
|
688
|
+
out[`http.${side}.header.${name}`] = text;
|
|
689
|
+
count++;
|
|
690
|
+
}
|
|
691
|
+
return out;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// src/headers.ts
|
|
695
|
+
function withHeaderCapture(settings, config = {}) {
|
|
696
|
+
return {
|
|
697
|
+
...config,
|
|
698
|
+
applyCustomAttributesOnSpan(span, request, response) {
|
|
699
|
+
config.applyCustomAttributesOnSpan?.(span, request, response);
|
|
700
|
+
try {
|
|
701
|
+
if (request instanceof IncomingMessage2) {
|
|
702
|
+
span.setAttributes(headerAttributes("request", request.headers, settings));
|
|
703
|
+
if (response instanceof ServerResponse2) span.setAttributes(headerAttributes("response", response.getHeaders(), settings));
|
|
704
|
+
} else if (request instanceof ClientRequest2) {
|
|
705
|
+
span.setAttributes(headerAttributes("request", request.getHeaders(), settings));
|
|
706
|
+
if (response instanceof IncomingMessage2) span.setAttributes(headerAttributes("response", response.headers, settings));
|
|
707
|
+
}
|
|
708
|
+
} catch {
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// src/db-errors.ts
|
|
715
|
+
import { context, createContextKey, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
716
|
+
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from "@opentelemetry/instrumentation";
|
|
717
|
+
|
|
718
|
+
// src/version.ts
|
|
719
|
+
var VERSION = "0.5.0";
|
|
720
|
+
|
|
721
|
+
// src/source.ts
|
|
722
|
+
import { readFileSync, statSync } from "fs";
|
|
723
|
+
import { dirname, isAbsolute, resolve } from "path";
|
|
724
|
+
import { fileURLToPath } from "url";
|
|
725
|
+
import * as nodeModule from "module";
|
|
726
|
+
var SOURCE_CONTEXT_ATTRIBUTE = "zharp.source_context";
|
|
727
|
+
var AROUND = 5;
|
|
728
|
+
var MAX_FRAMES = 5;
|
|
729
|
+
var MAX_LINE = 300;
|
|
730
|
+
var MAX_BYTES = 12e3;
|
|
731
|
+
var MAX_FILE = 5e6;
|
|
732
|
+
var MAX_MAP = 3e7;
|
|
733
|
+
var MAX_CACHED = 50;
|
|
734
|
+
var enabled = true;
|
|
735
|
+
function setSourceContext(on) {
|
|
736
|
+
enabled = on;
|
|
737
|
+
}
|
|
738
|
+
var files = /* @__PURE__ */ new Map();
|
|
739
|
+
var maps = /* @__PURE__ */ new Map();
|
|
740
|
+
function remember(cache, key, value) {
|
|
741
|
+
if (cache.size >= MAX_CACHED) cache.delete(cache.keys().next().value);
|
|
742
|
+
cache.set(key, value);
|
|
743
|
+
return value;
|
|
744
|
+
}
|
|
745
|
+
function toPath(file) {
|
|
746
|
+
if (file.startsWith("file://")) {
|
|
747
|
+
try {
|
|
748
|
+
return fileURLToPath(file);
|
|
749
|
+
} catch {
|
|
750
|
+
return null;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return isAbsolute(file) ? file : null;
|
|
754
|
+
}
|
|
755
|
+
function isApp(path) {
|
|
756
|
+
return !/[\\/]node_modules[\\/]/.test(path) && !path.startsWith("node:") && !/[\\/]@zharp[\\/]/.test(path);
|
|
757
|
+
}
|
|
758
|
+
function linesOf(path, text) {
|
|
759
|
+
if (files.has(path)) return files.get(path);
|
|
760
|
+
let content = text ?? null;
|
|
761
|
+
if (content === null) {
|
|
762
|
+
try {
|
|
763
|
+
if (statSync(path).size > MAX_FILE) return remember(files, path, null);
|
|
764
|
+
content = readFileSync(path, "utf8");
|
|
765
|
+
} catch {
|
|
766
|
+
return remember(files, path, null);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
return remember(files, path, content.split(/\r\n|\n|\r/));
|
|
770
|
+
}
|
|
771
|
+
function mapOf(path) {
|
|
772
|
+
if (maps.has(path)) return maps.get(path);
|
|
773
|
+
const SourceMap2 = nodeModule.SourceMap;
|
|
774
|
+
const lines = linesOf(path);
|
|
775
|
+
if (!SourceMap2 || !lines) return remember(maps, path, null);
|
|
776
|
+
try {
|
|
777
|
+
let payload = null;
|
|
778
|
+
let mapPath = `${path}.map`;
|
|
779
|
+
const tail = lines.slice(-5).join("\n");
|
|
780
|
+
const url = /[#@]\s*sourceMappingURL=(\S+)\s*$/m.exec(tail)?.[1];
|
|
781
|
+
if (url?.startsWith("data:")) {
|
|
782
|
+
const base64 = /;base64,(.*)$/.exec(url)?.[1];
|
|
783
|
+
payload = base64 ? JSON.parse(Buffer.from(base64, "base64").toString("utf8")) : null;
|
|
784
|
+
mapPath = path;
|
|
785
|
+
} else {
|
|
786
|
+
if (url) mapPath = resolve(dirname(path), decodeURIComponent(url));
|
|
787
|
+
if (statSync(mapPath).size > MAX_MAP) return remember(maps, path, null);
|
|
788
|
+
payload = JSON.parse(readFileSync(mapPath, "utf8"));
|
|
789
|
+
}
|
|
790
|
+
if (!payload || !Array.isArray(payload.sources)) return remember(maps, path, null);
|
|
791
|
+
return remember(maps, path, {
|
|
792
|
+
map: new SourceMap2(payload),
|
|
793
|
+
dir: dirname(mapPath),
|
|
794
|
+
sources: payload.sources,
|
|
795
|
+
sourceRoot: typeof payload.sourceRoot === "string" ? payload.sourceRoot : "",
|
|
796
|
+
contents: Array.isArray(payload.sourcesContent) ? payload.sourcesContent : []
|
|
797
|
+
});
|
|
798
|
+
} catch {
|
|
799
|
+
return remember(maps, path, null);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
function original(path, line, column) {
|
|
803
|
+
const loaded = mapOf(path);
|
|
804
|
+
if (!loaded) return null;
|
|
805
|
+
const entry = loaded.map.findEntry(line - 1, Math.max(0, column - 1));
|
|
806
|
+
if (!entry?.originalSource || entry.originalLine === void 0) return null;
|
|
807
|
+
const index = loaded.sources.findIndex((s) => s === entry.originalSource || entry.originalSource.endsWith(s));
|
|
808
|
+
const source = entry.originalSource.replace(/^webpack:\/\/[^/]*\//, "").replace(/^file:\/\//, "");
|
|
809
|
+
const file = isAbsolute(source) ? source : resolve(loaded.dir, loaded.sourceRoot, source);
|
|
810
|
+
return { file, line: entry.originalLine + 1, column: (entry.originalColumn ?? 0) + 1, text: index >= 0 ? loaded.contents[index] ?? null : null };
|
|
811
|
+
}
|
|
812
|
+
var FRAME = /^(\s*at (?:async )?(?:.*? \()?)((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/]).*?):(\d+):(\d+)(\)?)\s*$/;
|
|
813
|
+
function sourced(stack) {
|
|
814
|
+
if (!enabled || !stack) return { stack, context: null };
|
|
815
|
+
const out = [];
|
|
816
|
+
const seen = /* @__PURE__ */ new Set();
|
|
817
|
+
let mapped = 0;
|
|
818
|
+
const lines = stack.split("\n").map((text) => {
|
|
819
|
+
const m = FRAME.exec(text);
|
|
820
|
+
if (!m) return text;
|
|
821
|
+
const path = toPath(m[2]);
|
|
822
|
+
if (!path || !isApp(path) || mapped > 40) return text;
|
|
823
|
+
let file = m[2];
|
|
824
|
+
let line = Number(m[3]);
|
|
825
|
+
let column = Number(m[4]);
|
|
826
|
+
let content = null;
|
|
827
|
+
const from = /\.(c|m)?js$/.test(path) ? original(path, line, column) : null;
|
|
828
|
+
mapped++;
|
|
829
|
+
if (from && isApp(from.file)) {
|
|
830
|
+
file = from.file;
|
|
831
|
+
line = from.line;
|
|
832
|
+
column = from.column;
|
|
833
|
+
content = linesOf(from.file, from.text);
|
|
834
|
+
text = `${m[1]}${file}:${line}:${column}${m[5]}`;
|
|
835
|
+
} else if (!from) {
|
|
836
|
+
const built = linesOf(path);
|
|
837
|
+
const tail = built ? built.slice(-5).join("\n") : "";
|
|
838
|
+
content = /[#@]\s*(?:sourceMappingURL|debugId)=/.test(tail) ? null : built;
|
|
839
|
+
}
|
|
840
|
+
const key = `${file}:${line}`;
|
|
841
|
+
if (content && out.length < MAX_FRAMES && !seen.has(key) && content[line - 1] !== void 0) {
|
|
842
|
+
seen.add(key);
|
|
843
|
+
const cut = (s) => s.length > MAX_LINE ? `${s.slice(0, MAX_LINE - 1)}\u2026` : s;
|
|
844
|
+
out.push({
|
|
845
|
+
file,
|
|
846
|
+
line,
|
|
847
|
+
pre: content.slice(Math.max(0, line - 1 - AROUND), line - 1).map(cut),
|
|
848
|
+
code: cut(content[line - 1]),
|
|
849
|
+
post: content.slice(line, line + AROUND).map(cut)
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
return text;
|
|
853
|
+
});
|
|
854
|
+
while (out.length) {
|
|
855
|
+
const json = JSON.stringify(out);
|
|
856
|
+
if (Buffer.byteLength(json) <= MAX_BYTES) return { stack: lines.join("\n"), context: json };
|
|
857
|
+
out.pop();
|
|
858
|
+
}
|
|
859
|
+
return { stack: lines.join("\n"), context: null };
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// src/db-errors.ts
|
|
863
|
+
var SQLSTATE = {
|
|
864
|
+
"23505": "UniqueViolation",
|
|
865
|
+
"23503": "ForeignKeyViolation",
|
|
866
|
+
"23502": "NotNullViolation",
|
|
867
|
+
"23514": "CheckViolation",
|
|
868
|
+
"23P01": "ExclusionViolation",
|
|
869
|
+
"22001": "StringDataRightTruncation",
|
|
870
|
+
"22003": "NumericValueOutOfRange",
|
|
871
|
+
"22P02": "InvalidTextRepresentation",
|
|
872
|
+
"22007": "InvalidDatetimeFormat",
|
|
873
|
+
"22008": "DatetimeFieldOverflow",
|
|
874
|
+
"22012": "DivisionByZero",
|
|
875
|
+
"42P01": "UndefinedTable",
|
|
876
|
+
"42703": "UndefinedColumn",
|
|
877
|
+
"42883": "UndefinedFunction",
|
|
878
|
+
"42601": "SyntaxError",
|
|
879
|
+
"42501": "InsufficientPrivilege",
|
|
880
|
+
"40001": "SerializationFailure",
|
|
881
|
+
"40P01": "DeadlockDetected",
|
|
882
|
+
"55P03": "LockNotAvailable",
|
|
883
|
+
"57014": "QueryCanceled",
|
|
884
|
+
"53300": "TooManyConnections",
|
|
885
|
+
"08006": "ConnectionFailure",
|
|
886
|
+
"08001": "ConnectionRefused",
|
|
887
|
+
"28P01": "InvalidPassword",
|
|
888
|
+
"3D000": "InvalidCatalogName"
|
|
889
|
+
};
|
|
890
|
+
var SYSTEM_NAMES = { postgresql: "Postgres", mysql: "MySQL", mariadb: "MariaDB", mongodb: "Mongo", redis: "Redis", mssql: "SqlServer", oracle: "Oracle", sqlite: "Sqlite" };
|
|
891
|
+
function dbErrorType(system, code, name) {
|
|
892
|
+
if (code && system === "postgresql" && SQLSTATE[code]) return SQLSTATE[code];
|
|
893
|
+
if (code && /^ER_[A-Z_]+$/.test(code)) return code;
|
|
894
|
+
if (name && !/^(error|Error|DatabaseError)$/.test(name)) return name;
|
|
895
|
+
return `${SYSTEM_NAMES[system] ?? "Database"}Error`;
|
|
896
|
+
}
|
|
897
|
+
function callSiteFrames(stack) {
|
|
898
|
+
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));
|
|
899
|
+
const firstApp = frames.findIndex((line) => !/[\\/]node_modules[\\/]/.test(line));
|
|
900
|
+
return (firstApp > 0 ? frames.slice(firstApp) : frames).slice(0, 40);
|
|
901
|
+
}
|
|
902
|
+
var CALL_SITE = createContextKey("zharp.db.callSite");
|
|
903
|
+
function stackFrom(fn) {
|
|
904
|
+
const limit = Error.stackTraceLimit;
|
|
905
|
+
Error.stackTraceLimit = 60;
|
|
906
|
+
const holder = {};
|
|
907
|
+
Error.captureStackTrace(holder, fn);
|
|
908
|
+
Error.stackTraceLimit = limit;
|
|
909
|
+
return holder.stack;
|
|
910
|
+
}
|
|
911
|
+
var attr = (attributes, ...names) => {
|
|
912
|
+
for (const name of names) {
|
|
913
|
+
const value = attributes[name];
|
|
914
|
+
if (value !== void 0 && value !== null && value !== "") return String(value);
|
|
915
|
+
}
|
|
916
|
+
return null;
|
|
917
|
+
};
|
|
918
|
+
function reportOf(failure) {
|
|
919
|
+
const error = failure.error;
|
|
920
|
+
const code = (error?.code !== void 0 ? String(error.code) : null) ?? failure.code;
|
|
921
|
+
const type = dbErrorType(failure.system, code, error?.name);
|
|
922
|
+
const message = error?.message || failure.scrubbed?.replace(/^.*?error of type '[^']*' occurred/i, `${SYSTEM_NAMES[failure.system] ?? "Database"} error`) || "The query failed";
|
|
923
|
+
const { stack, context: context3 } = sourced([`${type}: ${message}`, ...failure.frames].join("\n"));
|
|
924
|
+
const attributes = {
|
|
925
|
+
...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {},
|
|
926
|
+
"zharp.mechanism": "db",
|
|
927
|
+
"db.system": failure.system,
|
|
928
|
+
...failure.statement ? { "db.statement": failure.statement.slice(0, 4e3) } : {},
|
|
929
|
+
...failure.database ? { "db.name": failure.database } : {},
|
|
930
|
+
...code ? { "db.error.code": code } : {},
|
|
931
|
+
...error?.constraint ? { "db.error.constraint": error.constraint } : {}
|
|
932
|
+
};
|
|
933
|
+
return { type, message, stack, attributes, spanContext: failure.spanContext };
|
|
934
|
+
}
|
|
935
|
+
var LONE_WAIT_MS = 1500;
|
|
936
|
+
var MAX_PENDING = 200;
|
|
937
|
+
var DbErrorSpanProcessor = class _DbErrorSpanProcessor {
|
|
938
|
+
constructor(send) {
|
|
939
|
+
this.send = send;
|
|
940
|
+
}
|
|
941
|
+
send;
|
|
942
|
+
callSites = /* @__PURE__ */ new WeakMap();
|
|
943
|
+
/** Failures not yet reported, by trace. */
|
|
944
|
+
pending = /* @__PURE__ */ new Map();
|
|
945
|
+
onStart(span, parentContext) {
|
|
946
|
+
const attributes = span.attributes ?? {};
|
|
947
|
+
if (!attr(attributes, "db.system", "db.system.name")) return;
|
|
948
|
+
const carried = (parentContext ?? context.active()).getValue(CALL_SITE);
|
|
949
|
+
const entry = {
|
|
950
|
+
frames: callSiteFrames(carried ?? stackFrom(_DbErrorSpanProcessor.prototype.onStart))
|
|
951
|
+
};
|
|
952
|
+
this.callSites.set(span, entry);
|
|
953
|
+
const record = span.recordException.bind(span);
|
|
954
|
+
span.recordException = (exception, time) => {
|
|
955
|
+
if (entry.exception === void 0) entry.exception = exception;
|
|
956
|
+
else record(exception, time);
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
onEnd(span) {
|
|
960
|
+
const entry = this.callSites.get(span);
|
|
961
|
+
if (entry && span.status.code === SpanStatusCode.ERROR) {
|
|
962
|
+
const attributes = span.attributes ?? {};
|
|
963
|
+
const exception = entry.exception;
|
|
964
|
+
const failure = {
|
|
965
|
+
spanContext: span.spanContext(),
|
|
966
|
+
traceId: span.spanContext().traceId,
|
|
967
|
+
system: attr(attributes, "db.system", "db.system.name") ?? "database",
|
|
968
|
+
statement: attr(attributes, "db.statement", "db.query.text"),
|
|
969
|
+
database: attr(attributes, "db.name", "db.namespace"),
|
|
970
|
+
code: attr(attributes, "error.type", "db.response.status_code"),
|
|
971
|
+
frames: entry.frames,
|
|
972
|
+
scrubbed: typeof exception === "string" ? exception : exception?.message ?? span.status.message ?? null,
|
|
973
|
+
...exception instanceof Error ? { error: exception } : {}
|
|
974
|
+
};
|
|
975
|
+
this.add(failure);
|
|
976
|
+
}
|
|
977
|
+
const root = span.kind === SpanKind.SERVER || !span.parentSpanContext || !!span.parentSpanContext.isRemote;
|
|
978
|
+
if (root) {
|
|
979
|
+
const traceId = span.spanContext().traceId;
|
|
980
|
+
if (!this.pending.has(traceId)) return;
|
|
981
|
+
if (entry || span.status.code === SpanStatusCode.ERROR) setTimeout(() => this.flush(traceId), LONE_WAIT_MS).unref?.();
|
|
982
|
+
else this.flush(traceId);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
add(failure) {
|
|
986
|
+
const list = this.pending.get(failure.traceId) ?? [];
|
|
987
|
+
list.push(failure);
|
|
988
|
+
this.pending.set(failure.traceId, list);
|
|
989
|
+
if (this.pending.size > MAX_PENDING) this.flush(this.pending.keys().next().value);
|
|
990
|
+
}
|
|
991
|
+
/** The driver's error, seen by the query wrapper: joined to the trace's latest failure. */
|
|
992
|
+
attach(traceId, error) {
|
|
993
|
+
if (!traceId || !(error instanceof Error)) return;
|
|
994
|
+
const list = this.pending.get(traceId);
|
|
995
|
+
if (!list || list.some((f) => f.error === error)) return;
|
|
996
|
+
const failure = [...list].reverse().find((f) => !f.error && !f.done);
|
|
997
|
+
if (failure) failure.error = error;
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* `error` is being reported (by a framework's handler, as unhandled, or by captureError): the
|
|
1001
|
+
* failed query it came from, if any, so its details go into that one report and it isn't sent
|
|
1002
|
+
* again. Matched by the error itself, or what wraps it (`driverError`, `cause`); `latest` also
|
|
1003
|
+
* takes the request's latest failure whose driver error was never seen.
|
|
1004
|
+
*/
|
|
1005
|
+
consume(traceId, error, latest = false) {
|
|
1006
|
+
const inner = (candidate) => {
|
|
1007
|
+
if (!candidate || typeof candidate !== "object") return [];
|
|
1008
|
+
const c = candidate;
|
|
1009
|
+
return [candidate, c.driverError, c.cause, c.originalError].filter(Boolean);
|
|
1010
|
+
};
|
|
1011
|
+
const wanted2 = inner(error);
|
|
1012
|
+
const lists = traceId ? [this.pending.get(traceId) ?? []] : [...this.pending.values()];
|
|
1013
|
+
for (const list of lists) {
|
|
1014
|
+
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);
|
|
1015
|
+
if (failure) {
|
|
1016
|
+
failure.done = true;
|
|
1017
|
+
return failure;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
return null;
|
|
1021
|
+
}
|
|
1022
|
+
flush(traceId) {
|
|
1023
|
+
const list = this.pending.get(traceId);
|
|
1024
|
+
if (!list) return;
|
|
1025
|
+
this.pending.delete(traceId);
|
|
1026
|
+
for (const failure of list) if (!failure.done) this.send(failure);
|
|
1027
|
+
}
|
|
1028
|
+
forceFlush() {
|
|
1029
|
+
for (const traceId of [...this.pending.keys()]) this.flush(traceId);
|
|
1030
|
+
return Promise.resolve();
|
|
1031
|
+
}
|
|
1032
|
+
shutdown() {
|
|
1033
|
+
return this.forceFlush();
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
var DbDriverErrorsInstrumentation = class extends InstrumentationBase {
|
|
1037
|
+
constructor(onError) {
|
|
1038
|
+
super("@zharp/node/db-driver-errors", VERSION, {});
|
|
1039
|
+
this.onError = onError;
|
|
1040
|
+
}
|
|
1041
|
+
onError;
|
|
1042
|
+
init() {
|
|
1043
|
+
const onError = (traceId, err) => {
|
|
1044
|
+
try {
|
|
1045
|
+
this.onError(traceId, err);
|
|
1046
|
+
} catch {
|
|
1047
|
+
}
|
|
1048
|
+
};
|
|
1049
|
+
const wrapQuery = (original2) => {
|
|
1050
|
+
const run = (self, args) => {
|
|
1051
|
+
const traceId = trace.getActiveSpan()?.spanContext().traceId;
|
|
1052
|
+
const callback = args.findIndex((a) => typeof a === "function");
|
|
1053
|
+
if (callback >= 0) {
|
|
1054
|
+
const cb = args[callback];
|
|
1055
|
+
args[callback] = function(err, ...rest) {
|
|
1056
|
+
if (err) onError(traceId, err);
|
|
1057
|
+
return cb.call(this, err, ...rest);
|
|
1058
|
+
};
|
|
1059
|
+
return original2.apply(self, args);
|
|
1060
|
+
}
|
|
1061
|
+
const result = original2.apply(self, args);
|
|
1062
|
+
if (!result || typeof result.then !== "function" || typeof result.submit === "function") return result;
|
|
1063
|
+
result.then(void 0, (err) => onError(traceId, err));
|
|
1064
|
+
return result;
|
|
1065
|
+
};
|
|
1066
|
+
return function query(...args) {
|
|
1067
|
+
const active = context.active();
|
|
1068
|
+
if (active.getValue(CALL_SITE) !== void 0) return run(this, args);
|
|
1069
|
+
return context.with(active.setValue(CALL_SITE, stackFrom(query)), () => run(this, args));
|
|
1070
|
+
};
|
|
1071
|
+
};
|
|
1072
|
+
const patch = (moduleExports) => {
|
|
1073
|
+
for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
|
|
1074
|
+
if (target?.query && !target.query.__zharpWrapped) {
|
|
1075
|
+
const wrapped = wrapQuery(target.query);
|
|
1076
|
+
wrapped.__zharpWrapped = true;
|
|
1077
|
+
wrapped.__zharpOriginal = target.query;
|
|
1078
|
+
target.query = wrapped;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
return moduleExports;
|
|
1082
|
+
};
|
|
1083
|
+
const unpatch = (moduleExports) => {
|
|
1084
|
+
for (const target of [moduleExports?.Client?.prototype, moduleExports?.Pool?.prototype]) {
|
|
1085
|
+
if (target?.query?.__zharpOriginal) target.query = target.query.__zharpOriginal;
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
return [new InstrumentationNodeModuleDefinition("pg", [">=8 <9"], patch, unpatch)];
|
|
1089
|
+
}
|
|
1090
|
+
};
|
|
1091
|
+
|
|
1092
|
+
// src/framework-errors.ts
|
|
1093
|
+
import { InstrumentationBase as InstrumentationBase2, InstrumentationNodeModuleDefinition as InstrumentationNodeModuleDefinition2, InstrumentationNodeModuleFile } from "@opentelemetry/instrumentation";
|
|
1094
|
+
function statusOf(error) {
|
|
1095
|
+
if (!error || typeof error !== "object") return 500;
|
|
1096
|
+
const e = error;
|
|
1097
|
+
try {
|
|
1098
|
+
if (typeof e.getStatus === "function") {
|
|
1099
|
+
const status = Number(e.getStatus());
|
|
1100
|
+
if (Number.isFinite(status)) return status;
|
|
1101
|
+
}
|
|
1102
|
+
} catch {
|
|
1103
|
+
}
|
|
1104
|
+
for (const value of [e.status, e.statusCode]) {
|
|
1105
|
+
const status = Number(value);
|
|
1106
|
+
if (Number.isInteger(status) && status >= 100 && status < 600) return status;
|
|
1107
|
+
}
|
|
1108
|
+
return 500;
|
|
1109
|
+
}
|
|
1110
|
+
var WRAPPED = /* @__PURE__ */ Symbol.for("zharp.frameworkErrors");
|
|
1111
|
+
var FrameworkErrorsInstrumentation = class extends InstrumentationBase2 {
|
|
1112
|
+
constructor(sink) {
|
|
1113
|
+
super("@zharp/node/framework-errors", VERSION, {});
|
|
1114
|
+
this.sink = sink;
|
|
1115
|
+
}
|
|
1116
|
+
sink;
|
|
1117
|
+
init() {
|
|
1118
|
+
const report = (error, mechanism) => {
|
|
1119
|
+
try {
|
|
1120
|
+
if (statusOf(error) >= 500) this.sink(error, mechanism);
|
|
1121
|
+
} catch {
|
|
1122
|
+
}
|
|
1123
|
+
};
|
|
1124
|
+
const nest = new InstrumentationNodeModuleFile(
|
|
1125
|
+
"@nestjs/core/exceptions/exceptions-handler.js",
|
|
1126
|
+
[">=8 <13"],
|
|
1127
|
+
(moduleExports) => {
|
|
1128
|
+
const proto = moduleExports?.ExceptionsHandler?.prototype;
|
|
1129
|
+
if (proto?.next && !proto.next[WRAPPED]) {
|
|
1130
|
+
const original2 = proto.next;
|
|
1131
|
+
const next = function(exception, ...rest) {
|
|
1132
|
+
report(exception, "nestjs");
|
|
1133
|
+
return original2.call(this, exception, ...rest);
|
|
1134
|
+
};
|
|
1135
|
+
next[WRAPPED] = original2;
|
|
1136
|
+
proto.next = next;
|
|
1137
|
+
}
|
|
1138
|
+
return moduleExports;
|
|
1139
|
+
},
|
|
1140
|
+
(moduleExports) => {
|
|
1141
|
+
const proto = moduleExports?.ExceptionsHandler?.prototype;
|
|
1142
|
+
if (proto?.next?.[WRAPPED]) proto.next = proto.next[WRAPPED];
|
|
1143
|
+
}
|
|
1144
|
+
);
|
|
1145
|
+
const finalhandler = new InstrumentationNodeModuleDefinition2(
|
|
1146
|
+
"finalhandler",
|
|
1147
|
+
[">=1 <3"],
|
|
1148
|
+
(moduleExports) => {
|
|
1149
|
+
if (typeof moduleExports !== "function" || moduleExports[WRAPPED]) return moduleExports;
|
|
1150
|
+
const original2 = moduleExports;
|
|
1151
|
+
const wrapped = function(...args) {
|
|
1152
|
+
const done = original2.apply(this, args);
|
|
1153
|
+
return function(err, ...rest) {
|
|
1154
|
+
if (err) report(err, "express");
|
|
1155
|
+
return done.call(this, err, ...rest);
|
|
1156
|
+
};
|
|
1157
|
+
};
|
|
1158
|
+
Object.assign(wrapped, original2);
|
|
1159
|
+
wrapped[WRAPPED] = original2;
|
|
1160
|
+
return wrapped;
|
|
1161
|
+
},
|
|
1162
|
+
(moduleExports) => moduleExports?.[WRAPPED] ?? moduleExports
|
|
1163
|
+
);
|
|
1164
|
+
return [new InstrumentationNodeModuleDefinition2("@nestjs/core", [">=8 <13"], void 0, void 0, [nest]), finalhandler];
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
var RecordedExceptionsProcessor = class {
|
|
1168
|
+
constructor(report) {
|
|
1169
|
+
this.report = report;
|
|
1170
|
+
}
|
|
1171
|
+
report;
|
|
1172
|
+
pending = /* @__PURE__ */ new Map();
|
|
1173
|
+
onStart(span) {
|
|
1174
|
+
const scope = span.instrumentationScope?.name ?? span.instrumentationLibrary?.name ?? "";
|
|
1175
|
+
if (!scope.startsWith("@opentelemetry/instrumentation-") && scope !== "next.js") return;
|
|
1176
|
+
if (span.attributes?.["db.system"] || span.attributes?.["db.system.name"]) return;
|
|
1177
|
+
const original2 = span.recordException.bind(span);
|
|
1178
|
+
span.recordException = (exception, time) => {
|
|
1179
|
+
try {
|
|
1180
|
+
if (!exception || typeof exception !== "object") return original2(exception, time);
|
|
1181
|
+
const name = typeof exception.name === "string" && exception.name !== "error" ? exception.name : exception.constructor?.name || "Error";
|
|
1182
|
+
span.addEvent("exception", {
|
|
1183
|
+
"exception.type": name,
|
|
1184
|
+
"exception.message": String(exception.message ?? ""),
|
|
1185
|
+
...typeof exception.stack === "string" ? { "exception.stacktrace": exception.stack } : {},
|
|
1186
|
+
"zharp.deferred": "true"
|
|
1187
|
+
}, time);
|
|
1188
|
+
const traceId = span.spanContext().traceId;
|
|
1189
|
+
const list = this.pending.get(traceId) ?? [];
|
|
1190
|
+
if (!list.some((p) => p.error === exception)) list.push({ error: exception, spanContext: span.spanContext(), scope: mechanismOf(scope) });
|
|
1191
|
+
this.pending.set(traceId, list);
|
|
1192
|
+
if (this.pending.size > 500) this.pending.delete(this.pending.keys().next().value);
|
|
1193
|
+
} catch {
|
|
1194
|
+
original2(exception, time);
|
|
1195
|
+
}
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
onEnd(span) {
|
|
1199
|
+
const parent = span.parentSpanContext;
|
|
1200
|
+
const isRoot = span.kind === 1 || !parent || parent.isRemote;
|
|
1201
|
+
if (!isRoot) return;
|
|
1202
|
+
const traceId = span.spanContext().traceId;
|
|
1203
|
+
const list = this.pending.get(traceId);
|
|
1204
|
+
if (!list) return;
|
|
1205
|
+
this.pending.delete(traceId);
|
|
1206
|
+
const status = Number(span.attributes?.["http.response.status_code"] ?? span.attributes?.["http.status_code"]);
|
|
1207
|
+
const failed = Number.isFinite(status) && status > 0 ? status >= 500 : span.status?.code === 2;
|
|
1208
|
+
if (!failed) return;
|
|
1209
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1210
|
+
for (const p of list) {
|
|
1211
|
+
if (seen.has(p.error)) continue;
|
|
1212
|
+
seen.add(p.error);
|
|
1213
|
+
if (statusOf(p.error) < 500) continue;
|
|
1214
|
+
this.report(p.error, p.spanContext, p.scope);
|
|
1215
|
+
break;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
forceFlush() {
|
|
1219
|
+
return Promise.resolve();
|
|
1220
|
+
}
|
|
1221
|
+
shutdown() {
|
|
1222
|
+
this.pending.clear();
|
|
1223
|
+
return Promise.resolve();
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
function mechanismOf(scope) {
|
|
1227
|
+
const name = scope.replace("@opentelemetry/instrumentation-", "").replace(/-core$/, "");
|
|
1228
|
+
if (name === "router") return "express";
|
|
1229
|
+
return name === "next.js" ? "nextjs" : name;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
657
1232
|
// src/urls.ts
|
|
658
1233
|
var URL_KEYS = ["url.full", "http.url", "http.target"];
|
|
659
1234
|
var UrlRedactionSpanProcessor = class {
|
|
@@ -689,7 +1264,7 @@ var UrlRedactionSpanProcessor = class {
|
|
|
689
1264
|
};
|
|
690
1265
|
|
|
691
1266
|
// src/context.ts
|
|
692
|
-
import { context as otelContext, propagation, trace } from "@opentelemetry/api";
|
|
1267
|
+
import { context as otelContext, propagation, trace as trace2 } from "@opentelemetry/api";
|
|
693
1268
|
var BAGGAGE_KEYS = ["enduser.id", "session.id"];
|
|
694
1269
|
function userAttributes(user) {
|
|
695
1270
|
const out = { "enduser.id": String(user.id) };
|
|
@@ -706,7 +1281,7 @@ var ContextStore = class {
|
|
|
706
1281
|
localRoots = /* @__PURE__ */ new Map();
|
|
707
1282
|
/** Set the user for the request in progress, or for the whole process outside one. */
|
|
708
1283
|
setUser(user) {
|
|
709
|
-
const span =
|
|
1284
|
+
const span = trace2.getActiveSpan();
|
|
710
1285
|
const traceId = span?.spanContext().traceId;
|
|
711
1286
|
if (!span || !traceId) {
|
|
712
1287
|
this.globalUser = user;
|
|
@@ -726,7 +1301,7 @@ var ContextStore = class {
|
|
|
726
1301
|
return user ? { ...this.tags, ...user } : { ...this.tags };
|
|
727
1302
|
}
|
|
728
1303
|
noteStart(span, parent) {
|
|
729
|
-
const parentSpan =
|
|
1304
|
+
const parentSpan = trace2.getSpanContext(parent);
|
|
730
1305
|
if (!parentSpan || parentSpan.isRemote) {
|
|
731
1306
|
const { traceId, spanId } = span.spanContext();
|
|
732
1307
|
if (!this.localRoots.has(traceId)) this.localRoots.set(traceId, { spanId, span });
|
|
@@ -779,7 +1354,7 @@ var ContextLogProcessor = class {
|
|
|
779
1354
|
onEmit(record, ctx) {
|
|
780
1355
|
try {
|
|
781
1356
|
const active = ctx ?? otelContext.active();
|
|
782
|
-
const traceId = record.spanContext?.traceId ??
|
|
1357
|
+
const traceId = record.spanContext?.traceId ?? trace2.getSpanContext(active)?.traceId;
|
|
783
1358
|
const add = { ...this.store.attributesFor(traceId), ...fromBaggage(active) };
|
|
784
1359
|
for (const [key, value] of Object.entries(add)) {
|
|
785
1360
|
if (record.attributes[key] === void 0) record.setAttribute(key, value);
|
|
@@ -848,11 +1423,11 @@ var emitting = false;
|
|
|
848
1423
|
function captureConsole(logger) {
|
|
849
1424
|
const originals = /* @__PURE__ */ new Map();
|
|
850
1425
|
for (const [method, severityNumber, severityText] of LEVELS) {
|
|
851
|
-
const
|
|
852
|
-
if (typeof
|
|
853
|
-
originals.set(method,
|
|
1426
|
+
const original2 = console[method];
|
|
1427
|
+
if (typeof original2 !== "function" || original2.__zharp) continue;
|
|
1428
|
+
originals.set(method, original2);
|
|
854
1429
|
const patched = function(...args) {
|
|
855
|
-
quiet(() =>
|
|
1430
|
+
quiet(() => original2.apply(this ?? console, args));
|
|
856
1431
|
if (emitting) return;
|
|
857
1432
|
emitting = true;
|
|
858
1433
|
try {
|
|
@@ -869,12 +1444,12 @@ function captureConsole(logger) {
|
|
|
869
1444
|
console[method] = patched;
|
|
870
1445
|
}
|
|
871
1446
|
return () => {
|
|
872
|
-
for (const [method,
|
|
1447
|
+
for (const [method, original2] of originals) console[method] = original2;
|
|
873
1448
|
};
|
|
874
1449
|
}
|
|
875
1450
|
|
|
876
1451
|
// src/stdout.ts
|
|
877
|
-
import { context as otelContext2, isSpanContextValid, SeverityNumber as SeverityNumber2, trace as
|
|
1452
|
+
import { context as otelContext2, isSpanContextValid, SeverityNumber as SeverityNumber2, trace as trace3 } from "@opentelemetry/api";
|
|
878
1453
|
var LEVELS2 = {
|
|
879
1454
|
trace: [SeverityNumber2.TRACE, "TRACE"],
|
|
880
1455
|
verbose: [SeverityNumber2.DEBUG, "DEBUG"],
|
|
@@ -896,7 +1471,7 @@ var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "d
|
|
|
896
1471
|
var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
897
1472
|
var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
|
|
898
1473
|
var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
|
|
899
|
-
var
|
|
1474
|
+
var MAX_LINE2 = 32 * 1024;
|
|
900
1475
|
var FLUSH_MS = 200;
|
|
901
1476
|
function levelOf(value) {
|
|
902
1477
|
if (typeof value === "number") {
|
|
@@ -949,13 +1524,13 @@ function captureOutput(logger) {
|
|
|
949
1524
|
[process.stderr, "stderr", LEVELS2.warn]
|
|
950
1525
|
]) {
|
|
951
1526
|
if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
|
|
952
|
-
const
|
|
1527
|
+
const original2 = stream.write;
|
|
953
1528
|
let pending = "";
|
|
954
1529
|
let pendingContext;
|
|
955
1530
|
let timer;
|
|
956
1531
|
const emitLine = (line, ctx) => {
|
|
957
1532
|
if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
|
|
958
|
-
const parsed2 = parseLine(line.length >
|
|
1533
|
+
const parsed2 = parseLine(line.length > MAX_LINE2 ? line.slice(0, MAX_LINE2) : line);
|
|
959
1534
|
if (!parsed2.body.trim()) return;
|
|
960
1535
|
const [severityNumber, severityText] = parsed2.level ?? fallback;
|
|
961
1536
|
quiet(() => logger.emit({
|
|
@@ -985,7 +1560,7 @@ function captureOutput(logger) {
|
|
|
985
1560
|
const ctx = pendingContext;
|
|
986
1561
|
if (pending) pendingContext = otelContext2.active();
|
|
987
1562
|
for (const line of lines) emitLine(line, ctx);
|
|
988
|
-
if (pending.length >
|
|
1563
|
+
if (pending.length > MAX_LINE2) flush();
|
|
989
1564
|
else if (pending && !timer) {
|
|
990
1565
|
timer = setTimeout(flush, FLUSH_MS);
|
|
991
1566
|
timer.unref?.();
|
|
@@ -996,14 +1571,14 @@ function captureOutput(logger) {
|
|
|
996
1571
|
take(chunk, encoding);
|
|
997
1572
|
} catch {
|
|
998
1573
|
}
|
|
999
|
-
return
|
|
1574
|
+
return original2.call(this ?? stream, chunk, encoding, callback);
|
|
1000
1575
|
};
|
|
1001
1576
|
patched.__zharp = true;
|
|
1002
1577
|
stream.write = patched;
|
|
1003
1578
|
undo.push(() => {
|
|
1004
1579
|
if (timer) clearTimeout(timer);
|
|
1005
1580
|
if (pending) flush();
|
|
1006
|
-
stream.write =
|
|
1581
|
+
stream.write = original2;
|
|
1007
1582
|
});
|
|
1008
1583
|
}
|
|
1009
1584
|
return () => undo.forEach((fn) => fn());
|
|
@@ -1012,25 +1587,25 @@ function stampOutput() {
|
|
|
1012
1587
|
const undo = [];
|
|
1013
1588
|
for (const stream of [process.stdout, process.stderr]) {
|
|
1014
1589
|
if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
|
|
1015
|
-
const
|
|
1590
|
+
const original2 = stream.write;
|
|
1016
1591
|
const patched = function(chunk, encoding, callback) {
|
|
1017
1592
|
let out = chunk;
|
|
1018
1593
|
try {
|
|
1019
1594
|
out = stamped(chunk, encoding);
|
|
1020
1595
|
} catch {
|
|
1021
1596
|
}
|
|
1022
|
-
return
|
|
1597
|
+
return original2.call(this ?? stream, out, encoding, callback);
|
|
1023
1598
|
};
|
|
1024
1599
|
patched.__zharpStamp = true;
|
|
1025
1600
|
stream.write = patched;
|
|
1026
1601
|
undo.push(() => {
|
|
1027
|
-
stream.write =
|
|
1602
|
+
stream.write = original2;
|
|
1028
1603
|
});
|
|
1029
1604
|
}
|
|
1030
1605
|
return () => undo.forEach((fn) => fn());
|
|
1031
1606
|
}
|
|
1032
1607
|
function stamped(chunk, encoding) {
|
|
1033
|
-
const span =
|
|
1608
|
+
const span = trace3.getActiveSpan()?.spanContext();
|
|
1034
1609
|
if (!span || !isSpanContextValid(span)) return chunk;
|
|
1035
1610
|
const isBytes = chunk instanceof Uint8Array;
|
|
1036
1611
|
if (typeof chunk !== "string" && !isBytes) return chunk;
|
|
@@ -1076,7 +1651,7 @@ function stampLine(line, traceId, spanId) {
|
|
|
1076
1651
|
|
|
1077
1652
|
// ../../internal/src/debug-ids.ts
|
|
1078
1653
|
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
1079
|
-
var
|
|
1654
|
+
var files2 = /* @__PURE__ */ new Map();
|
|
1080
1655
|
var parsed = /* @__PURE__ */ new Set();
|
|
1081
1656
|
function registry() {
|
|
1082
1657
|
const g2 = typeof globalThis !== "undefined" ? globalThis : void 0;
|
|
@@ -1092,7 +1667,8 @@ function frameFile(line) {
|
|
|
1092
1667
|
match = /^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(text);
|
|
1093
1668
|
return match ? clean(match[1]) : void 0;
|
|
1094
1669
|
}
|
|
1095
|
-
function clean(
|
|
1670
|
+
function clean(raw) {
|
|
1671
|
+
const file = raw.replace(/^address at /, "");
|
|
1096
1672
|
if (!file || file.includes("eval at ") || file === "<anonymous>" || file === "native") return void 0;
|
|
1097
1673
|
return file;
|
|
1098
1674
|
}
|
|
@@ -1115,7 +1691,7 @@ function refresh() {
|
|
|
1115
1691
|
for (const line of stack.split("\n")) {
|
|
1116
1692
|
const file = frameFile(line);
|
|
1117
1693
|
if (file) {
|
|
1118
|
-
|
|
1694
|
+
files2.set(file, id);
|
|
1119
1695
|
break;
|
|
1120
1696
|
}
|
|
1121
1697
|
}
|
|
@@ -1125,10 +1701,10 @@ function debugIdsFor(stack) {
|
|
|
1125
1701
|
if (!stack) return void 0;
|
|
1126
1702
|
try {
|
|
1127
1703
|
refresh();
|
|
1128
|
-
if (
|
|
1704
|
+
if (files2.size === 0) return void 0;
|
|
1129
1705
|
let out;
|
|
1130
1706
|
for (const file of stackFiles(stack)) {
|
|
1131
|
-
const id =
|
|
1707
|
+
const id = files2.get(file);
|
|
1132
1708
|
if (id) (out ??= {})[file] = id;
|
|
1133
1709
|
}
|
|
1134
1710
|
return out;
|
|
@@ -1211,17 +1787,284 @@ function exceptionAttributes(error, handled) {
|
|
|
1211
1787
|
const cause = error.cause;
|
|
1212
1788
|
if (cause instanceof Error && cause.stack) stack += `
|
|
1213
1789
|
Caused by: ${cause.stack}`;
|
|
1790
|
+
const { stack: readable, context: context3 } = sourced(stack);
|
|
1214
1791
|
return {
|
|
1215
1792
|
"exception.type": type,
|
|
1216
1793
|
"exception.message": message,
|
|
1217
|
-
"exception.stacktrace":
|
|
1794
|
+
"exception.stacktrace": readable,
|
|
1218
1795
|
"zharp.handled": handled ? "true" : "false",
|
|
1219
|
-
|
|
1796
|
+
// From the stack as it ran: frames resolved here keep their bundle's ID for uploaded maps.
|
|
1797
|
+
...debugIdAttributes(stack),
|
|
1798
|
+
...context3 ? { [SOURCE_CONTEXT_ATTRIBUTE]: context3 } : {}
|
|
1220
1799
|
};
|
|
1221
1800
|
}
|
|
1222
1801
|
|
|
1223
|
-
// src/
|
|
1224
|
-
|
|
1802
|
+
// src/serverless.ts
|
|
1803
|
+
import { randomUUID } from "crypto";
|
|
1804
|
+
var DEFAULT_FLUSH_MS = 2e3;
|
|
1805
|
+
var headerGetter = {
|
|
1806
|
+
get(carrier, key) {
|
|
1807
|
+
return header2(carrier, key);
|
|
1808
|
+
},
|
|
1809
|
+
keys(carrier) {
|
|
1810
|
+
if (!carrier || typeof carrier !== "object") return [];
|
|
1811
|
+
if (typeof carrier.keys === "function" && typeof carrier.get === "function") {
|
|
1812
|
+
try {
|
|
1813
|
+
return [...carrier.keys()];
|
|
1814
|
+
} catch {
|
|
1815
|
+
return [];
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
return Object.keys(carrier);
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
function header2(carrier, name) {
|
|
1822
|
+
if (!carrier || typeof carrier !== "object") return void 0;
|
|
1823
|
+
const c = carrier;
|
|
1824
|
+
if (typeof c.get === "function" && typeof c.has === "function") {
|
|
1825
|
+
try {
|
|
1826
|
+
return c.get(name) ?? void 0;
|
|
1827
|
+
} catch {
|
|
1828
|
+
return void 0;
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
const wanted2 = name.toLowerCase();
|
|
1832
|
+
for (const key of Object.keys(c)) {
|
|
1833
|
+
if (key.toLowerCase() !== wanted2) continue;
|
|
1834
|
+
const value = c[key];
|
|
1835
|
+
if (Array.isArray(value)) return value.join(",");
|
|
1836
|
+
return value == null ? void 0 : String(value);
|
|
1837
|
+
}
|
|
1838
|
+
return void 0;
|
|
1839
|
+
}
|
|
1840
|
+
function pathOf(url) {
|
|
1841
|
+
if (typeof url !== "string" || !url) return void 0;
|
|
1842
|
+
try {
|
|
1843
|
+
return new URL(url, "http://x").pathname;
|
|
1844
|
+
} catch {
|
|
1845
|
+
return url.split("?")[0];
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
function clean2(attrs) {
|
|
1849
|
+
const out = {};
|
|
1850
|
+
for (const [key, value] of Object.entries(attrs)) {
|
|
1851
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
1852
|
+
out[key] = typeof value === "number" || typeof value === "boolean" ? value : String(value);
|
|
1853
|
+
}
|
|
1854
|
+
return out;
|
|
1855
|
+
}
|
|
1856
|
+
var STREAMING = /* @__PURE__ */ Symbol.for("aws.lambda.runtime.handler.streaming");
|
|
1857
|
+
var isStreamingLambda = (handler) => handler?.[STREAMING] === "response";
|
|
1858
|
+
function lambdaInvocation(event, ctx, coldstart) {
|
|
1859
|
+
const rc = event?.requestContext;
|
|
1860
|
+
const v2 = rc?.http && typeof rc.http.method === "string";
|
|
1861
|
+
const v1 = typeof event?.httpMethod === "string" && (rc || event.headers);
|
|
1862
|
+
const http = !!(v2 || v1);
|
|
1863
|
+
const functionName = ctx?.functionName ?? process.env.AWS_LAMBDA_FUNCTION_NAME;
|
|
1864
|
+
const arn = ctx?.invokedFunctionArn;
|
|
1865
|
+
const base = {
|
|
1866
|
+
"faas.trigger": lambdaTrigger(event, http),
|
|
1867
|
+
"faas.invocation_id": ctx?.awsRequestId,
|
|
1868
|
+
"faas.coldstart": coldstart,
|
|
1869
|
+
"faas.name": functionName,
|
|
1870
|
+
"faas.version": ctx?.functionVersion ?? process.env.AWS_LAMBDA_FUNCTION_VERSION,
|
|
1871
|
+
"cloud.provider": "aws",
|
|
1872
|
+
"cloud.platform": "aws_lambda",
|
|
1873
|
+
"cloud.region": process.env.AWS_REGION,
|
|
1874
|
+
"cloud.resource_id": arn,
|
|
1875
|
+
"cloud.account.id": arn?.split(":")[4]
|
|
1876
|
+
};
|
|
1877
|
+
if (!http) {
|
|
1878
|
+
const source = lambdaSource(event);
|
|
1879
|
+
return {
|
|
1880
|
+
name: functionName ?? "lambda",
|
|
1881
|
+
attributes: clean2({ ...base, ...source ? { "faas.event_source": source } : {} }),
|
|
1882
|
+
http: false,
|
|
1883
|
+
mechanism: "aws-lambda"
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
const method = v2 ? rc.http.method : event.httpMethod;
|
|
1887
|
+
const path = v2 ? rc.http.path ?? event.rawPath : event.path;
|
|
1888
|
+
const routeKey = rc?.routeKey && rc.routeKey !== "$default" ? rc.routeKey.split(" ").slice(-1)[0] : void 0;
|
|
1889
|
+
const route = routeKey ?? (typeof event.resource === "string" && !event.resource.includes("{proxy+}") ? event.resource : void 0);
|
|
1890
|
+
return {
|
|
1891
|
+
name: `${method} ${route ?? path ?? "/"}`,
|
|
1892
|
+
attributes: clean2({
|
|
1893
|
+
...base,
|
|
1894
|
+
"http.request.method": method,
|
|
1895
|
+
"url.path": path,
|
|
1896
|
+
"http.route": route,
|
|
1897
|
+
"url.scheme": header2(event.headers, "x-forwarded-proto"),
|
|
1898
|
+
"server.address": header2(event.headers, "host") ?? rc?.domainName,
|
|
1899
|
+
"user_agent.original": v2 ? rc.http.userAgent : header2(event.headers, "user-agent"),
|
|
1900
|
+
"client.address": v2 ? rc.http.sourceIp : rc?.identity?.sourceIp
|
|
1901
|
+
}),
|
|
1902
|
+
// REST API events may carry the same header in both maps; the single-value one is enough.
|
|
1903
|
+
carrier: event.headers ?? event.multiValueHeaders,
|
|
1904
|
+
http: true,
|
|
1905
|
+
mechanism: "aws-lambda"
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
function lambdaSource(event) {
|
|
1909
|
+
const record = Array.isArray(event?.Records) ? event.Records[0] : void 0;
|
|
1910
|
+
return record?.eventSource ?? record?.EventSource ?? (typeof event?.source === "string" ? event.source : void 0);
|
|
1911
|
+
}
|
|
1912
|
+
function lambdaTrigger(event, http) {
|
|
1913
|
+
if (http || event?.requestContext?.elb) return "http";
|
|
1914
|
+
const source = lambdaSource(event) ?? "";
|
|
1915
|
+
if (/^aws:(sqs|sns|kinesis|kafka)$/.test(source) || source === "aws:mq" || event?.eventSource === "aws:kafka") return "pubsub";
|
|
1916
|
+
if (/^aws:(s3|dynamodb)$/.test(source)) return "datasource";
|
|
1917
|
+
if (event?.["detail-type"] === "Scheduled Event" || source === "aws.scheduler") return "timer";
|
|
1918
|
+
return "other";
|
|
1919
|
+
}
|
|
1920
|
+
function lambdaStatus(result, event) {
|
|
1921
|
+
if (result && typeof result === "object" && typeof result.statusCode === "number") return result.statusCode;
|
|
1922
|
+
if (event?.requestContext?.http) return 200;
|
|
1923
|
+
return void 0;
|
|
1924
|
+
}
|
|
1925
|
+
function azureInvocation(args, coldstart) {
|
|
1926
|
+
const v4 = args[1] && typeof args[1] === "object" && typeof args[1].invocationId === "string";
|
|
1927
|
+
const v3 = !v4 && args[0] && typeof args[0] === "object" && typeof args[0].invocationId === "string";
|
|
1928
|
+
if (!v4 && !v3) return null;
|
|
1929
|
+
const ctx = v4 ? args[1] : args[0];
|
|
1930
|
+
const triggerType = v4 ? ctx.options?.trigger?.type : (ctx.bindingDefinitions ?? []).find((b) => b?.direction === "in" && /Trigger$/.test(b?.type ?? ""))?.type;
|
|
1931
|
+
const functionName = ctx.functionName ?? ctx.executionContext?.functionName;
|
|
1932
|
+
const request = v4 ? triggerType === "httpTrigger" ? args[0] : void 0 : ctx.req ?? (triggerType === "httpTrigger" ? args[1] : void 0);
|
|
1933
|
+
const http = !!request && typeof request.method === "string";
|
|
1934
|
+
const base = {
|
|
1935
|
+
"faas.trigger": azureTrigger(triggerType, http),
|
|
1936
|
+
"faas.invocation_id": ctx.invocationId,
|
|
1937
|
+
"faas.coldstart": coldstart,
|
|
1938
|
+
"faas.name": functionName,
|
|
1939
|
+
"cloud.provider": "azure",
|
|
1940
|
+
"cloud.platform": "azure_functions",
|
|
1941
|
+
"cloud.region": process.env.REGION_NAME
|
|
1942
|
+
};
|
|
1943
|
+
if (!http) {
|
|
1944
|
+
return { name: functionName ?? "function", attributes: clean2(base), http: false, mechanism: "azure-functions" };
|
|
1945
|
+
}
|
|
1946
|
+
const path = pathOf(request.url) ?? pathOf(request.originalUrl);
|
|
1947
|
+
return {
|
|
1948
|
+
name: `${request.method} ${path ?? "/"}`,
|
|
1949
|
+
attributes: clean2({
|
|
1950
|
+
...base,
|
|
1951
|
+
"http.request.method": request.method,
|
|
1952
|
+
"url.path": path,
|
|
1953
|
+
"user_agent.original": header2(request.headers, "user-agent")
|
|
1954
|
+
}),
|
|
1955
|
+
carrier: request.headers,
|
|
1956
|
+
http: true,
|
|
1957
|
+
mechanism: "azure-functions"
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
function azureTrigger(type, http) {
|
|
1961
|
+
if (http || type === "httpTrigger") return "http";
|
|
1962
|
+
if (type === "timerTrigger") return "timer";
|
|
1963
|
+
if (type && /^(queue|serviceBus|eventHub|eventGrid|kafka|rabbitMQ|webPubSub|signalR)/i.test(type)) return "pubsub";
|
|
1964
|
+
if (type && /^(blob|cosmosDB|sql|mysql)/i.test(type)) return "datasource";
|
|
1965
|
+
return "other";
|
|
1966
|
+
}
|
|
1967
|
+
function azureStatus(result, args) {
|
|
1968
|
+
const v4 = args[1] && typeof args[1]?.invocationId === "string";
|
|
1969
|
+
const response = v4 ? result : args[0]?.res ?? result;
|
|
1970
|
+
const status = response?.status ?? response?.statusCode;
|
|
1971
|
+
const n = typeof status === "string" ? Number(status) : status;
|
|
1972
|
+
return typeof n === "number" && Number.isFinite(n) ? n : 200;
|
|
1973
|
+
}
|
|
1974
|
+
var gcfName = () => process.env.K_SERVICE ?? process.env.FUNCTION_TARGET ?? process.env.FUNCTION_NAME;
|
|
1975
|
+
var gcfBase = (coldstart) => ({
|
|
1976
|
+
"faas.coldstart": coldstart,
|
|
1977
|
+
"faas.name": gcfName(),
|
|
1978
|
+
"faas.version": process.env.K_REVISION,
|
|
1979
|
+
"cloud.provider": "gcp",
|
|
1980
|
+
"cloud.platform": "gcp_cloud_functions",
|
|
1981
|
+
"cloud.region": process.env.FUNCTION_REGION
|
|
1982
|
+
});
|
|
1983
|
+
var isHttpPair = (req, res) => !!req && typeof req === "object" && typeof req.method === "string" && !!req.headers && !!res && typeof res.end === "function";
|
|
1984
|
+
function gcfHttpInvocation(req, coldstart) {
|
|
1985
|
+
const path = pathOf(req.originalUrl ?? req.url);
|
|
1986
|
+
const id = header2(req.headers, "function-execution-id") ?? header2(req.headers, "x-cloud-trace-context")?.split("/")[0] ?? randomUUID();
|
|
1987
|
+
return {
|
|
1988
|
+
name: `${req.method} ${path ?? "/"}`,
|
|
1989
|
+
attributes: clean2({
|
|
1990
|
+
...gcfBase(coldstart),
|
|
1991
|
+
"faas.trigger": "http",
|
|
1992
|
+
"faas.invocation_id": id,
|
|
1993
|
+
"http.request.method": req.method,
|
|
1994
|
+
"url.path": path,
|
|
1995
|
+
"server.address": header2(req.headers, "host"),
|
|
1996
|
+
"user_agent.original": header2(req.headers, "user-agent")
|
|
1997
|
+
}),
|
|
1998
|
+
carrier: req.headers,
|
|
1999
|
+
http: true,
|
|
2000
|
+
mechanism: "gcp-functions"
|
|
2001
|
+
};
|
|
2002
|
+
}
|
|
2003
|
+
function gcfEventInvocation(args, coldstart) {
|
|
2004
|
+
const ce = args[0] && typeof args[0] === "object" && typeof args[0].specversion === "string" ? args[0] : void 0;
|
|
2005
|
+
const legacy = !ce && args[1] && typeof args[1] === "object" ? args[1] : void 0;
|
|
2006
|
+
const type = ce?.type ?? legacy?.eventType ?? legacy?.type ?? "";
|
|
2007
|
+
const trigger = /pubsub/i.test(type) ? "pubsub" : /storage|firestore|firebase|datastore|database/i.test(type) ? "datasource" : /scheduler/i.test(type) ? "timer" : "other";
|
|
2008
|
+
return {
|
|
2009
|
+
name: gcfName() ?? "function",
|
|
2010
|
+
attributes: clean2({
|
|
2011
|
+
...gcfBase(coldstart),
|
|
2012
|
+
"faas.trigger": trigger,
|
|
2013
|
+
"faas.invocation_id": ce?.id ?? legacy?.eventId ?? randomUUID(),
|
|
2014
|
+
"cloudevents.event_type": type || void 0,
|
|
2015
|
+
"cloudevents.event_source": ce?.source
|
|
2016
|
+
}),
|
|
2017
|
+
// The CloudEvents distributed tracing extension.
|
|
2018
|
+
carrier: ce ? { traceparent: ce.traceparent, tracestate: ce.tracestate } : void 0,
|
|
2019
|
+
http: false,
|
|
2020
|
+
mechanism: "gcp-functions"
|
|
2021
|
+
};
|
|
2022
|
+
}
|
|
2023
|
+
function serverlessResource() {
|
|
2024
|
+
const env = process.env;
|
|
2025
|
+
if (env.AWS_LAMBDA_FUNCTION_NAME) {
|
|
2026
|
+
const memory = Number(env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE);
|
|
2027
|
+
return clean2({
|
|
2028
|
+
"cloud.provider": "aws",
|
|
2029
|
+
"cloud.platform": "aws_lambda",
|
|
2030
|
+
"cloud.region": env.AWS_REGION,
|
|
2031
|
+
"faas.name": env.AWS_LAMBDA_FUNCTION_NAME,
|
|
2032
|
+
"faas.version": env.AWS_LAMBDA_FUNCTION_VERSION,
|
|
2033
|
+
"faas.instance": env.AWS_LAMBDA_LOG_STREAM_NAME,
|
|
2034
|
+
"faas.max_memory": Number.isFinite(memory) && memory > 0 ? memory * 1024 * 1024 : void 0
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
if (env.FUNCTIONS_WORKER_RUNTIME && (env.WEBSITE_SITE_NAME || env.AzureWebJobsStorage || env.FUNCTIONS_EXTENSION_VERSION)) {
|
|
2038
|
+
return clean2({
|
|
2039
|
+
"cloud.provider": "azure",
|
|
2040
|
+
"cloud.platform": "azure_functions",
|
|
2041
|
+
"cloud.region": env.REGION_NAME,
|
|
2042
|
+
"faas.instance": env.WEBSITE_INSTANCE_ID
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
if (env.FUNCTION_TARGET && (env.K_SERVICE || env.FUNCTION_NAME)) {
|
|
2046
|
+
return clean2({
|
|
2047
|
+
"cloud.provider": "gcp",
|
|
2048
|
+
"cloud.platform": "gcp_cloud_functions",
|
|
2049
|
+
"cloud.region": env.FUNCTION_REGION,
|
|
2050
|
+
"faas.name": gcfName(),
|
|
2051
|
+
"faas.version": env.K_REVISION
|
|
2052
|
+
});
|
|
2053
|
+
}
|
|
2054
|
+
return {};
|
|
2055
|
+
}
|
|
2056
|
+
function serverlessName() {
|
|
2057
|
+
return process.env.AWS_LAMBDA_FUNCTION_NAME ?? process.env.WEBSITE_SITE_NAME ?? (process.env.FUNCTION_TARGET ? gcfName() : void 0);
|
|
2058
|
+
}
|
|
2059
|
+
function sameShape(wrapper, handler) {
|
|
2060
|
+
try {
|
|
2061
|
+
Object.defineProperty(wrapper, "length", { value: handler.length });
|
|
2062
|
+
Object.defineProperty(wrapper, "name", { value: handler.name });
|
|
2063
|
+
for (const key of Object.getOwnPropertySymbols(handler)) wrapper[key] = handler[key];
|
|
2064
|
+
} catch {
|
|
2065
|
+
}
|
|
2066
|
+
return wrapper;
|
|
2067
|
+
}
|
|
1225
2068
|
|
|
1226
2069
|
// src/zharp.ts
|
|
1227
2070
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
@@ -1237,6 +2080,15 @@ var ZharpNode = class {
|
|
|
1237
2080
|
tracing = true;
|
|
1238
2081
|
/** Errors already sent, so one that is both rejected and then thrown is reported once. */
|
|
1239
2082
|
reported = /* @__PURE__ */ new WeakSet();
|
|
2083
|
+
/** Failed queries waiting to be reported, once and with their call site. */
|
|
2084
|
+
dbErrors = null;
|
|
2085
|
+
/** No invocation has run in this process yet: the next one is the cold start. */
|
|
2086
|
+
cold = true;
|
|
2087
|
+
/**
|
|
2088
|
+
* A Cloud Function is wrapped: its wrapper makes each request's span (and flushes before the
|
|
2089
|
+
* response), so the http server instrumentation leaves incoming requests alone.
|
|
2090
|
+
*/
|
|
2091
|
+
wrapsHttp = false;
|
|
1240
2092
|
/** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
|
|
1241
2093
|
log = {
|
|
1242
2094
|
trace: (m, a) => this.emit("trace", m, a),
|
|
@@ -1276,7 +2128,7 @@ var ZharpNode = class {
|
|
|
1276
2128
|
warn("No key found \u2014 pass Zharp.init({ key }) or set ZHARP_API_KEY. Nothing will be sent.");
|
|
1277
2129
|
return;
|
|
1278
2130
|
}
|
|
1279
|
-
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName()) ?? "node-app";
|
|
2131
|
+
const service = pick(options.service, nodeEnv("ZHARP_SERVICE"), nodeEnv("OTEL_SERVICE_NAME"), packageName(), serverlessName()) ?? "node-app";
|
|
1280
2132
|
const environment = pick(options.environment, nodeEnv("ZHARP_ENV"), nodeEnv("NODE_ENV"));
|
|
1281
2133
|
const release = pick(options.release, nodeEnv("ZHARP_RELEASE"), nodeEnv("ZHARP_VERSION"));
|
|
1282
2134
|
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
@@ -1295,8 +2147,15 @@ var ZharpNode = class {
|
|
|
1295
2147
|
registerEsmHook();
|
|
1296
2148
|
const headers = { Authorization: `Bearer ${key}` };
|
|
1297
2149
|
const exporterOptions = { headers, compression: "gzip" };
|
|
2150
|
+
setSourceContext(switchOn(options.captureSourceContext, "ZHARP_CAPTURE_SOURCE_CONTEXT", true));
|
|
2151
|
+
const queryErrors = tracing && switchOn(options.captureQueryErrors, "ZHARP_CAPTURE_QUERY_ERRORS", true);
|
|
2152
|
+
this.dbErrors = queryErrors ? new DbErrorSpanProcessor((failure) => this.sendQueryError(failure, true, "error", { "zharp.mechanism": "db" })) : null;
|
|
1298
2153
|
this.spanProcessors = tracing ? [
|
|
1299
2154
|
new ContextSpanProcessor(this.store),
|
|
2155
|
+
// Before the database processor: a request that failed claims its query's error first.
|
|
2156
|
+
...options.captureUncaught !== false ? [new RecordedExceptionsProcessor((error, spanContext, mechanism) => context2.with(trace4.setSpanContext(context2.active(), spanContext), () => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true)))] : [],
|
|
2157
|
+
// Before the exporter: it keeps the query's scrubbed exception off the span.
|
|
2158
|
+
...this.dbErrors ? [this.dbErrors] : [],
|
|
1300
2159
|
new UrlRedactionSpanProcessor(),
|
|
1301
2160
|
new DebugIdSpanProcessor(),
|
|
1302
2161
|
new BatchSpanProcessor({ exporter: new OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
@@ -1315,13 +2174,20 @@ var ZharpNode = class {
|
|
|
1315
2174
|
"telemetry.sdk.language": "nodejs",
|
|
1316
2175
|
"telemetry.sdk.version": VERSION,
|
|
1317
2176
|
"process.runtime.name": "nodejs",
|
|
1318
|
-
"process.runtime.version": process.versions.node
|
|
2177
|
+
"process.runtime.version": process.versions.node,
|
|
2178
|
+
// Lambda, Azure Functions, Cloud Functions: cloud.provider, cloud.platform, faas.name…
|
|
2179
|
+
...serverlessResource()
|
|
1319
2180
|
});
|
|
1320
2181
|
const propagator = new CompositePropagator({
|
|
1321
2182
|
propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
|
|
1322
2183
|
});
|
|
1323
2184
|
const bodies = bodySettings(options.captureBodies, nodeEnv("ZHARP_CAPTURE_BODIES"));
|
|
2185
|
+
const headerCapture = headerSettings(options.captureHeaders, nodeEnv("ZHARP_CAPTURE_HEADERS"));
|
|
2186
|
+
const ownHttp = this.withWrappedRequests(options.instrumentations?.["@opentelemetry/instrumentation-http"]);
|
|
2187
|
+
const withBodies = bodies ? withBodyCapture(bodies, ownHttp) : ownHttp;
|
|
2188
|
+
const httpConfig = headerCapture ? withHeaderCapture(headerCapture, withBodies) : withBodies;
|
|
1324
2189
|
const rate = typeof options.sampleRate === "number" ? Math.min(1, Math.max(0, options.sampleRate)) : 1;
|
|
2190
|
+
let instrumentations = [];
|
|
1325
2191
|
this.sdk = new NodeSDK({
|
|
1326
2192
|
resource,
|
|
1327
2193
|
// Host and OTEL_RESOURCE_ATTRIBUTES only. The process detector would send the command line,
|
|
@@ -1333,22 +2199,27 @@ var ZharpNode = class {
|
|
|
1333
2199
|
logRecordProcessors: this.logProcessors,
|
|
1334
2200
|
// Without this the SDK would start an OTLP metrics exporter pointed at localhost:4318.
|
|
1335
2201
|
metricReaders: [],
|
|
1336
|
-
instrumentations: [
|
|
2202
|
+
instrumentations: instrumentations = [
|
|
1337
2203
|
...tracing ? getNodeAutoInstrumentations({
|
|
1338
2204
|
// A span per DNS lookup, socket and file read buries the requests that matter.
|
|
1339
2205
|
"@opentelemetry/instrumentation-dns": { enabled: false },
|
|
1340
2206
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1341
2207
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
2208
|
+
// Zharp.lambda() makes the invocation's span and flushes before returning; this one
|
|
2209
|
+
// would wrap the handler again (a second span) from _HANDLER, when it can find it.
|
|
2210
|
+
"@opentelemetry/instrumentation-aws-lambda": { enabled: false },
|
|
1342
2211
|
...options.instrumentations,
|
|
1343
2212
|
...bridges,
|
|
1344
|
-
...
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
2213
|
+
...httpConfig && { "@opentelemetry/instrumentation-http": httpConfig }
|
|
2214
|
+
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges, "@opentelemetry/instrumentation-http": ownHttp } }),
|
|
2215
|
+
...this.dbErrors ? [new DbDriverErrorsInstrumentation((traceId, error) => this.dbErrors?.attach(traceId, error))] : [],
|
|
2216
|
+
...tracing && options.captureUncaught !== false ? [new FrameworkErrorsInstrumentation((error, mechanism) => this.report(error, false, "error", { "zharp.mechanism": mechanism }, true))] : [],
|
|
1348
2217
|
...options.extraInstrumentations ?? []
|
|
1349
2218
|
]
|
|
1350
2219
|
});
|
|
1351
2220
|
this.sdk.start();
|
|
2221
|
+
if (tracing) preloadCommonJsFrameworks();
|
|
2222
|
+
if (isBun()) patchWithoutHooks(instrumentations);
|
|
1352
2223
|
this.logger = logs.getLogger("@zharp/node", VERSION);
|
|
1353
2224
|
if (correlation) this.teardowns.push(stampOutput());
|
|
1354
2225
|
if (sendLogs) {
|
|
@@ -1392,16 +2263,36 @@ var ZharpNode = class {
|
|
|
1392
2263
|
captureError(error, attributes) {
|
|
1393
2264
|
this.report(error, true, "error", attributes);
|
|
1394
2265
|
}
|
|
2266
|
+
/**
|
|
2267
|
+
* Next.js (15+): errors a route handler, server component, server action or middleware threw,
|
|
2268
|
+
* which Next answers with an error page and only prints. Export it from instrumentation.ts:
|
|
2269
|
+
*
|
|
2270
|
+
* export const onRequestError = Zharp.onRequestError;
|
|
2271
|
+
*
|
|
2272
|
+
* Each is reported once as a crash, with the request's path, method and route. A bound function,
|
|
2273
|
+
* so it can be exported as it is.
|
|
2274
|
+
*/
|
|
2275
|
+
onRequestError = (error, request, context3) => {
|
|
2276
|
+
this.report(error, false, "error", {
|
|
2277
|
+
"zharp.mechanism": "nextjs",
|
|
2278
|
+
...request?.method ? { "http.request.method": request.method } : {},
|
|
2279
|
+
...request?.path ? { "url.path": request.path } : {},
|
|
2280
|
+
...context3?.routePath ? { "http.route": context3.routePath } : {},
|
|
2281
|
+
...context3?.routeType ? { "next.route_type": context3.routeType } : {},
|
|
2282
|
+
...context3?.routerKind ? { "next.router_kind": context3.routerKind } : {},
|
|
2283
|
+
...context3?.renderSource ? { "next.render_source": context3.renderSource } : {}
|
|
2284
|
+
}, true);
|
|
2285
|
+
};
|
|
1395
2286
|
/**
|
|
1396
2287
|
* Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
|
|
1397
2288
|
* throw or rejection marks the span as failed and is passed on unchanged.
|
|
1398
2289
|
*/
|
|
1399
2290
|
startSpan(name, fn, options = {}) {
|
|
1400
|
-
if (!this.tracing) return fn(
|
|
1401
|
-
const tracer =
|
|
2291
|
+
if (!this.tracing) return fn(trace4.wrapSpanContext(trace4.getActiveSpan()?.spanContext() ?? INVALID_SPAN_CONTEXT));
|
|
2292
|
+
const tracer = trace4.getTracer("@zharp/node", VERSION);
|
|
1402
2293
|
return tracer.startActiveSpan(name, options, (span) => {
|
|
1403
2294
|
const fail = (error) => {
|
|
1404
|
-
span.setStatus({ code:
|
|
2295
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message: asError(error).message });
|
|
1405
2296
|
span.end();
|
|
1406
2297
|
};
|
|
1407
2298
|
let result;
|
|
@@ -1431,7 +2322,208 @@ var ZharpNode = class {
|
|
|
1431
2322
|
async flush(timeoutMs = 5e3) {
|
|
1432
2323
|
const all = Promise.all([...this.spanProcessors, ...this.logProcessors].map((p) => p.forceFlush().catch(() => {
|
|
1433
2324
|
})));
|
|
1434
|
-
await Promise.race([all, new Promise((
|
|
2325
|
+
await Promise.race([all, new Promise((resolve2) => setTimeout(resolve2, timeoutMs).unref())]);
|
|
2326
|
+
}
|
|
2327
|
+
// ── serverless ────────────────────────────────────────────────────────
|
|
2328
|
+
//
|
|
2329
|
+
// Each wrapper returns a function of the same shape as the handler: same arguments, same
|
|
2330
|
+
// result. Every invocation is one SERVER span (continuing the caller's trace when the trigger
|
|
2331
|
+
// carries a `traceparent`), an error the handler throws is reported once and thrown on, and
|
|
2332
|
+
// everything is flushed — within `flushTimeout` — before the result goes back, because the
|
|
2333
|
+
// platform freezes the process as soon as it has it.
|
|
2334
|
+
/**
|
|
2335
|
+
* An AWS Lambda handler (async, callback, or `awslambda.streamifyResponse`):
|
|
2336
|
+
*
|
|
2337
|
+
* export const handler = Zharp.lambda(async (event, context) => { … });
|
|
2338
|
+
*/
|
|
2339
|
+
lambda(handler, options = {}) {
|
|
2340
|
+
const self = this;
|
|
2341
|
+
const streaming = isStreamingLambda(handler);
|
|
2342
|
+
return sameShape(function zharpLambda(...args) {
|
|
2343
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2344
|
+
const event = args[0];
|
|
2345
|
+
const ctx = streaming ? args[2] : args[1];
|
|
2346
|
+
const budget = () => {
|
|
2347
|
+
const limit = options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2348
|
+
const left = typeof ctx?.getRemainingTimeInMillis === "function" ? Number(ctx.getRemainingTimeInMillis()) : NaN;
|
|
2349
|
+
return Number.isFinite(left) ? Math.max(0, Math.min(limit, left - 100)) : limit;
|
|
2350
|
+
};
|
|
2351
|
+
const invocation = lambdaInvocation(event, ctx, self.takeColdstart());
|
|
2352
|
+
const callback = !streaming && handler.length >= 3 ? 2 : null;
|
|
2353
|
+
return self.runInvocation(invocation, budget, (result) => invocation.http ? lambdaStatus(result, event) : void 0, handler, this, args, callback);
|
|
2354
|
+
}, handler);
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* An Azure Functions handler, v4 programming model (`(request, context)`, any trigger) or v3
|
|
2358
|
+
* (`(context, req)`):
|
|
2359
|
+
*
|
|
2360
|
+
* app.http('orders', { handler: Zharp.azureFunction(async (request, context) => { … }) });
|
|
2361
|
+
*/
|
|
2362
|
+
azureFunction(handler, options = {}) {
|
|
2363
|
+
const self = this;
|
|
2364
|
+
return sameShape(function zharpAzureFunction(...args) {
|
|
2365
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2366
|
+
const invocation = azureInvocation(args, self.takeColdstart());
|
|
2367
|
+
if (!invocation) return handler.apply(this, args);
|
|
2368
|
+
const budget = () => options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2369
|
+
return self.runInvocation(invocation, budget, (result) => invocation.http ? azureStatus(result, args) : void 0, handler, this, args, null);
|
|
2370
|
+
}, handler);
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* A Google Cloud Function: an HTTP function `(req, res)`, a CloudEvent function `(cloudEvent)`,
|
|
2374
|
+
* or a background function `(data, context)`.
|
|
2375
|
+
*
|
|
2376
|
+
* functions.http('orders', Zharp.cloudFunction((req, res) => { … }));
|
|
2377
|
+
*
|
|
2378
|
+
* An HTTP function's response is held until everything is sent — Cloud Functions may stop
|
|
2379
|
+
* the instance's CPU the moment the response is out.
|
|
2380
|
+
*/
|
|
2381
|
+
cloudFunction(handler, options = {}) {
|
|
2382
|
+
const self = this;
|
|
2383
|
+
this.wrapsHttp = true;
|
|
2384
|
+
const budget = () => options.flushTimeout ?? DEFAULT_FLUSH_MS;
|
|
2385
|
+
return sameShape(function zharpCloudFunction(...args) {
|
|
2386
|
+
if (!self.sdk) return handler.apply(this, args);
|
|
2387
|
+
if (isHttpPair(args[0], args[1])) return self.runHttpFunction(gcfHttpInvocation(args[0], self.takeColdstart()), budget, handler, this, args);
|
|
2388
|
+
const cloudEvent = args[0] && typeof args[0] === "object" && typeof args[0].specversion === "string";
|
|
2389
|
+
const callback = cloudEvent ? handler.length >= 2 ? 1 : null : handler.length >= 3 ? 2 : null;
|
|
2390
|
+
return self.runInvocation(gcfEventInvocation(args, self.takeColdstart()), budget, () => void 0, handler, this, args, callback);
|
|
2391
|
+
}, handler);
|
|
2392
|
+
}
|
|
2393
|
+
/** The first invocation in the process is the cold start (not under provisioned concurrency). */
|
|
2394
|
+
takeColdstart() {
|
|
2395
|
+
if (!this.cold) return false;
|
|
2396
|
+
this.cold = false;
|
|
2397
|
+
return process.env.AWS_LAMBDA_INITIALIZATION_TYPE !== "provisioned-concurrency";
|
|
2398
|
+
}
|
|
2399
|
+
/** The http instrumentation's config, leaving incoming requests to a wrapped Cloud Function. */
|
|
2400
|
+
withWrappedRequests(config) {
|
|
2401
|
+
const own = config?.ignoreIncomingRequestHook;
|
|
2402
|
+
return {
|
|
2403
|
+
...config,
|
|
2404
|
+
ignoreIncomingRequestHook: (request) => this.wrapsHttp || !!own?.(request)
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
/** The invocation's span, in a context of its own: the caller's trace, or a new one. */
|
|
2408
|
+
beginInvocation(invocation) {
|
|
2409
|
+
let base = unsuppressTracing(context2.active());
|
|
2410
|
+
if (invocation.carrier) base = propagation2.extract(base, invocation.carrier, headerGetter);
|
|
2411
|
+
const span = trace4.getTracer("@zharp/node", VERSION).startSpan(invocation.name, { kind: SpanKind2.SERVER, attributes: invocation.attributes }, base);
|
|
2412
|
+
return { span, ctx: trace4.setSpan(base, span) };
|
|
2413
|
+
}
|
|
2414
|
+
/** Report what the handler threw, in its invocation, and fail the span. Once per error. */
|
|
2415
|
+
invocationFailed(span, ctx, invocation, error) {
|
|
2416
|
+
try {
|
|
2417
|
+
context2.with(ctx, () => this.report(error, false, "error", { "zharp.mechanism": invocation.mechanism }));
|
|
2418
|
+
const e = asError(error);
|
|
2419
|
+
span.setStatus({ code: SpanStatusCode2.ERROR, message: e.message });
|
|
2420
|
+
span.setAttribute("error.type", e.name || "Error");
|
|
2421
|
+
} catch {
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
/** End the invocation's span, then send everything waiting, within the budget. */
|
|
2425
|
+
async endInvocation(span, status, budgetMs) {
|
|
2426
|
+
try {
|
|
2427
|
+
if (status !== void 0) {
|
|
2428
|
+
span.setAttribute("http.response.status_code", status);
|
|
2429
|
+
if (status >= 500) span.setStatus({ code: SpanStatusCode2.ERROR });
|
|
2430
|
+
}
|
|
2431
|
+
span.end();
|
|
2432
|
+
} catch {
|
|
2433
|
+
}
|
|
2434
|
+
if (budgetMs > 0) await this.flush(budgetMs).catch(() => {
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* Run a handler as one invocation. Its result (a value, a promise, or what it passes to its
|
|
2439
|
+
* callback) comes back unchanged — after the span has ended and been flushed.
|
|
2440
|
+
*/
|
|
2441
|
+
runInvocation(invocation, budget, statusOf2, handler, thisArg, args, callbackIndex) {
|
|
2442
|
+
let span;
|
|
2443
|
+
let ctx;
|
|
2444
|
+
try {
|
|
2445
|
+
({ span, ctx } = this.beginInvocation(invocation));
|
|
2446
|
+
} catch {
|
|
2447
|
+
return handler.apply(thisArg, args);
|
|
2448
|
+
}
|
|
2449
|
+
let done = null;
|
|
2450
|
+
const finish = (failed, error, result2) => {
|
|
2451
|
+
if (done) return done;
|
|
2452
|
+
if (failed) this.invocationFailed(span, ctx, invocation, error);
|
|
2453
|
+
let status;
|
|
2454
|
+
try {
|
|
2455
|
+
status = failed ? void 0 : statusOf2(result2);
|
|
2456
|
+
} catch {
|
|
2457
|
+
status = void 0;
|
|
2458
|
+
}
|
|
2459
|
+
return done = this.endInvocation(span, status, budget());
|
|
2460
|
+
};
|
|
2461
|
+
const usesCallback = callbackIndex !== null && typeof args[callbackIndex] === "function";
|
|
2462
|
+
if (usesCallback) {
|
|
2463
|
+
const index = callbackIndex;
|
|
2464
|
+
const callback = args[index];
|
|
2465
|
+
args = [...args];
|
|
2466
|
+
args[index] = function(error, ...rest) {
|
|
2467
|
+
const failed = error !== void 0 && error !== null;
|
|
2468
|
+
finish(failed, error, rest[0]).then(() => callback.call(this, error, ...rest));
|
|
2469
|
+
};
|
|
2470
|
+
}
|
|
2471
|
+
let result;
|
|
2472
|
+
try {
|
|
2473
|
+
result = context2.with(ctx, () => handler.apply(thisArg, args));
|
|
2474
|
+
} catch (error) {
|
|
2475
|
+
return finish(true, error, void 0).then(() => {
|
|
2476
|
+
throw error;
|
|
2477
|
+
});
|
|
2478
|
+
}
|
|
2479
|
+
if (result && typeof result.then === "function") {
|
|
2480
|
+
return Promise.resolve(result).then(
|
|
2481
|
+
(value) => finish(false, void 0, value).then(() => value),
|
|
2482
|
+
(error) => finish(true, error, void 0).then(() => {
|
|
2483
|
+
throw error;
|
|
2484
|
+
})
|
|
2485
|
+
);
|
|
2486
|
+
}
|
|
2487
|
+
if (usesCallback) return result;
|
|
2488
|
+
return finish(false, void 0, result).then(() => result);
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* An HTTP function `(req, res)`: the invocation ends with the response. `res.end` is held
|
|
2492
|
+
* until the span has ended and everything is flushed, then goes out as the handler wrote it.
|
|
2493
|
+
*/
|
|
2494
|
+
runHttpFunction(invocation, budget, handler, thisArg, args) {
|
|
2495
|
+
const self = this;
|
|
2496
|
+
let span;
|
|
2497
|
+
let ctx;
|
|
2498
|
+
try {
|
|
2499
|
+
({ span, ctx } = this.beginInvocation(invocation));
|
|
2500
|
+
} catch {
|
|
2501
|
+
return handler.apply(thisArg, args);
|
|
2502
|
+
}
|
|
2503
|
+
const res = args[1];
|
|
2504
|
+
const end = res.end;
|
|
2505
|
+
res.end = function zharpEnd(...endArgs) {
|
|
2506
|
+
res.end = end;
|
|
2507
|
+
const status = typeof res.statusCode === "number" ? res.statusCode : void 0;
|
|
2508
|
+
const send = () => end.apply(res, endArgs);
|
|
2509
|
+
self.endInvocation(span, status, budget()).then(send, send);
|
|
2510
|
+
return res;
|
|
2511
|
+
};
|
|
2512
|
+
const failed = (error) => this.invocationFailed(span, ctx, invocation, error);
|
|
2513
|
+
let result;
|
|
2514
|
+
try {
|
|
2515
|
+
result = context2.with(ctx, () => handler.apply(thisArg, args));
|
|
2516
|
+
} catch (error) {
|
|
2517
|
+
failed(error);
|
|
2518
|
+
throw error;
|
|
2519
|
+
}
|
|
2520
|
+
if (result && typeof result.then === "function") {
|
|
2521
|
+
return Promise.resolve(result).then(void 0, (error) => {
|
|
2522
|
+
failed(error);
|
|
2523
|
+
throw error;
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
return result;
|
|
1435
2527
|
}
|
|
1436
2528
|
/** Flush, stop, and put back everything that was patched. */
|
|
1437
2529
|
async shutdown() {
|
|
@@ -1463,14 +2555,20 @@ var ZharpNode = class {
|
|
|
1463
2555
|
} catch {
|
|
1464
2556
|
}
|
|
1465
2557
|
}
|
|
1466
|
-
report(value, handled, level, attributes) {
|
|
2558
|
+
report(value, handled, level, attributes, fromFramework = false) {
|
|
1467
2559
|
try {
|
|
1468
2560
|
if (!this.logger) return;
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
2561
|
+
if (value && typeof value === "object" && this.reported.has(value)) return;
|
|
2562
|
+
const traceId = trace4.getActiveSpan()?.spanContext().traceId;
|
|
2563
|
+
const failure = this.dbErrors?.consume(traceId, value, fromFramework);
|
|
2564
|
+
if (failure) {
|
|
2565
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
2566
|
+
this.sendQueryError(failure, handled, level, attributes);
|
|
2567
|
+
if (!handled) trace4.getActiveSpan()?.setStatus({ code: SpanStatusCode2.ERROR, message: failure.error?.message ?? "The query failed" });
|
|
2568
|
+
return;
|
|
1473
2569
|
}
|
|
2570
|
+
const error = asError(value);
|
|
2571
|
+
if (value && typeof value === "object") this.reported.add(value);
|
|
1474
2572
|
const exception = exceptionAttributes(error, handled);
|
|
1475
2573
|
this.logger.emit({
|
|
1476
2574
|
severityNumber: SEVERITY[level],
|
|
@@ -1478,7 +2576,33 @@ var ZharpNode = class {
|
|
|
1478
2576
|
body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
|
|
1479
2577
|
attributes: { ...attributes, ...exception }
|
|
1480
2578
|
});
|
|
1481
|
-
if (!handled)
|
|
2579
|
+
if (!handled) trace4.getActiveSpan()?.setStatus({ code: SpanStatusCode2.ERROR, message: error.message });
|
|
2580
|
+
} catch {
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
/** A failed query as an error, in the query's own span so the error shows the query. */
|
|
2584
|
+
sendQueryError(failure, handled, level = "error", attributes) {
|
|
2585
|
+
try {
|
|
2586
|
+
if (!this.logger) return;
|
|
2587
|
+
if (failure.error) {
|
|
2588
|
+
if (this.reported.has(failure.error) && handled) return;
|
|
2589
|
+
this.reported.add(failure.error);
|
|
2590
|
+
}
|
|
2591
|
+
const report = reportOf(failure);
|
|
2592
|
+
this.logger.emit({
|
|
2593
|
+
severityNumber: SEVERITY[level],
|
|
2594
|
+
severityText: level.toUpperCase(),
|
|
2595
|
+
body: `${report.type}: ${report.message}`,
|
|
2596
|
+
attributes: {
|
|
2597
|
+
...report.attributes,
|
|
2598
|
+
...attributes,
|
|
2599
|
+
"exception.type": report.type,
|
|
2600
|
+
"exception.message": report.message,
|
|
2601
|
+
"exception.stacktrace": report.stack,
|
|
2602
|
+
"zharp.handled": handled ? "true" : "false"
|
|
2603
|
+
},
|
|
2604
|
+
context: trace4.setSpanContext(context2.active(), report.spanContext)
|
|
2605
|
+
});
|
|
1482
2606
|
} catch {
|
|
1483
2607
|
}
|
|
1484
2608
|
}
|
|
@@ -1573,14 +2697,83 @@ function safeJson(value) {
|
|
|
1573
2697
|
return String(value);
|
|
1574
2698
|
}
|
|
1575
2699
|
}
|
|
2700
|
+
var ESM_HOOK_EXCLUDE = ["connect", "@hapi/hapi"];
|
|
2701
|
+
function preloadCommonJsFrameworks() {
|
|
2702
|
+
let appRequire;
|
|
2703
|
+
try {
|
|
2704
|
+
appRequire = createRequire(join(process.cwd(), "noop.js"));
|
|
2705
|
+
} catch {
|
|
2706
|
+
return;
|
|
2707
|
+
}
|
|
2708
|
+
for (const name of ESM_HOOK_EXCLUDE) {
|
|
2709
|
+
try {
|
|
2710
|
+
appRequire(name);
|
|
2711
|
+
} catch {
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
var isBun = () => typeof globalThis.Bun !== "undefined";
|
|
2716
|
+
function patchWithoutHooks(instrumentations) {
|
|
2717
|
+
let appRequire;
|
|
2718
|
+
try {
|
|
2719
|
+
appRequire = createRequire(join(process.cwd(), "noop.js"));
|
|
2720
|
+
} catch {
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2723
|
+
for (const instrumentation of instrumentations) {
|
|
2724
|
+
let definitions = [];
|
|
2725
|
+
for (const flag of ["_httpPatched", "_httpsPatched"]) if (instrumentation && flag in instrumentation) instrumentation[flag] = false;
|
|
2726
|
+
try {
|
|
2727
|
+
definitions = instrumentation?.getModuleDefinitions?.() ?? [];
|
|
2728
|
+
} catch {
|
|
2729
|
+
continue;
|
|
2730
|
+
}
|
|
2731
|
+
for (const definition of definitions) {
|
|
2732
|
+
let exported;
|
|
2733
|
+
try {
|
|
2734
|
+
exported = appRequire(definition.name);
|
|
2735
|
+
} catch {
|
|
2736
|
+
continue;
|
|
2737
|
+
}
|
|
2738
|
+
let version;
|
|
2739
|
+
try {
|
|
2740
|
+
version = definition.name.includes(":") || !definition.name.includes("/") && isBuiltin(definition.name) ? process.versions.node : appRequire(`${definition.name}/package.json`).version;
|
|
2741
|
+
} catch {
|
|
2742
|
+
version = void 0;
|
|
2743
|
+
}
|
|
2744
|
+
try {
|
|
2745
|
+
definition.patch?.(exported, version);
|
|
2746
|
+
} catch {
|
|
2747
|
+
}
|
|
2748
|
+
for (const file of definition.files ?? []) {
|
|
2749
|
+
try {
|
|
2750
|
+
file.patch?.(appRequire(file.name), version);
|
|
2751
|
+
} catch {
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
1576
2757
|
function registerEsmHook() {
|
|
1577
2758
|
const g2 = globalThis;
|
|
1578
2759
|
if (g2.__ZHARP_ESM_HOOK__) return;
|
|
1579
2760
|
g2.__ZHARP_ESM_HOOK__ = true;
|
|
1580
2761
|
try {
|
|
1581
|
-
registerLoader?.("@opentelemetry/instrumentation/hook.mjs", import.meta.url);
|
|
2762
|
+
registerLoader?.("@opentelemetry/instrumentation/hook.mjs", import.meta.url, esmHookOptions());
|
|
2763
|
+
} catch {
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
function esmHookOptions() {
|
|
2767
|
+
try {
|
|
2768
|
+
const otel = createRequire(createRequire(import.meta.url).resolve("@opentelemetry/instrumentation"));
|
|
2769
|
+
const { createAddHookMessageChannel } = otel("import-in-the-middle");
|
|
2770
|
+
if (typeof createAddHookMessageChannel === "function") {
|
|
2771
|
+
const { registerOptions } = createAddHookMessageChannel();
|
|
2772
|
+
return { data: { ...registerOptions.data, exclude: ESM_HOOK_EXCLUDE }, transferList: registerOptions.transferList };
|
|
2773
|
+
}
|
|
1582
2774
|
} catch {
|
|
1583
2775
|
}
|
|
2776
|
+
return { data: { exclude: ESM_HOOK_EXCLUDE } };
|
|
1584
2777
|
}
|
|
1585
2778
|
function switchOn(option, variable, fallback) {
|
|
1586
2779
|
if (typeof option === "boolean") return option;
|
|
@@ -1637,8 +2830,8 @@ var ExtractOnlyPropagator = class {
|
|
|
1637
2830
|
inner;
|
|
1638
2831
|
inject() {
|
|
1639
2832
|
}
|
|
1640
|
-
extract(
|
|
1641
|
-
return this.inner.extract(
|
|
2833
|
+
extract(context3, carrier, getter) {
|
|
2834
|
+
return this.inner.extract(context3, carrier, getter);
|
|
1642
2835
|
}
|
|
1643
2836
|
fields() {
|
|
1644
2837
|
return [];
|