@nestjs/observe 0.0.1 → 0.1.1
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 +16 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.js +98 -1
- package/dist/agent/observe-agent.shared-buffer.d.ts +82 -0
- package/dist/agent/observe-agent.shared-buffer.js +94 -3
- package/dist/agent/observe-agent.worker.d.ts +28 -0
- package/dist/agent/observe-agent.worker.js +59 -5
- package/dist/custom-metrics/counter.d.ts +124 -0
- package/dist/custom-metrics/counter.js +93 -0
- package/dist/custom-metrics/gauge.d.ts +116 -0
- package/dist/custom-metrics/gauge.js +55 -0
- package/dist/custom-metrics/summary.d.ts +102 -0
- package/dist/custom-metrics/summary.js +100 -0
- package/dist/encoders/custom-metrics.encoder.js +18 -0
- package/dist/encoders/remap-keys.util.d.ts +11 -0
- package/dist/encoders/remap-keys.util.js +15 -0
- package/dist/encoders/trace.encoder.d.ts +7 -0
- package/dist/encoders/trace.encoder.js +12 -0
- package/dist/instrument/create-instance-decorator.instrument.d.ts +8 -0
- package/dist/instrument/create-instance-decorator.instrument.js +67 -0
- package/dist/interfaces/custom-metric.interface.d.ts +74 -0
- package/dist/interfaces/graphql.interfaces.d.ts +16 -0
- package/dist/interfaces/job-snapshot.interface.d.ts +70 -0
- package/dist/interfaces/node-runtime-metrics.interface.d.ts +5 -0
- package/dist/interfaces/observe-options.interface.d.ts +358 -0
- package/dist/interfaces/request-snapshot.interface.d.ts +62 -0
- package/dist/interfaces/trace-events.interfaces.d.ts +51 -0
- package/dist/interfaces/trace-span.interface.d.ts +29 -0
- package/dist/observe.module.js +29 -0
- package/dist/profiling/cpu-profiler.service.d.ts +65 -0
- package/dist/profiling/cpu-profiler.service.js +80 -0
- package/dist/profiling/fold-profile.util.d.ts +20 -0
- package/dist/profiling/fold-profile.util.js +0 -0
- package/dist/profiling/profile-uploader.d.ts +26 -0
- package/dist/profiling/profile-uploader.js +52 -0
- package/dist/profiling/span-slice-recorder.d.ts +51 -0
- package/dist/profiling/span-slice-recorder.js +77 -0
- package/dist/protocols/graphql-observe-agent.service.d.ts +128 -0
- package/dist/protocols/graphql-observe-agent.service.js +166 -0
- package/dist/protocols/graphql-operation-parser.d.ts +26 -0
- package/dist/protocols/graphql-operation-parser.js +66 -0
- package/dist/protocols/http-observe-agent.service.d.ts +19 -0
- package/dist/protocols/http-observe-agent.service.js +34 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +8 -0
- package/dist/protocols/queue-observe-agent.service.js +32 -0
- package/dist/protocols/rpc-observe-agent.service.d.ts +7 -0
- package/dist/protocols/rpc-observe-agent.service.js +12 -0
- package/dist/services/logger-patcher.service.d.ts +4 -0
- package/dist/services/logger-patcher.service.js +13 -1
- package/dist/services/node-runtime-metrics.service.js +24 -8
- package/dist/services/operation-trace.registry.d.ts +56 -1
- package/dist/services/operation-trace.registry.js +145 -6
- package/dist/services/stdout-forwarder.service.d.ts +19 -0
- package/dist/services/stdout-forwarder.service.js +62 -0
- package/dist/services/trace-sampler.service.d.ts +6 -0
- package/dist/services/trace-sampler.service.js +3 -3
- package/dist/services/tracer.service.d.ts +91 -0
- package/dist/services/tracer.service.js +56 -1
- package/dist/trace-span.delegate.d.ts +11 -0
- package/dist/trace-span.delegate.js +11 -0
- package/dist/types/path-value.type.d.ts +4 -0
- package/dist/utils/default-trace-id-generator.util.js +11 -0
- package/dist/utils/log-line.parser.d.ts +14 -0
- package/dist/utils/log-line.parser.js +37 -0
- package/dist/utils/log-redactor.js +65 -0
- package/dist/utils/redact-url-query.d.ts +17 -0
- package/dist/utils/redact-url-query.js +38 -0
- package/dist/utils/source-context.util.d.ts +22 -0
- package/dist/utils/source-context.util.js +60 -0
- package/dist/utils/source-map-resolver.util.d.ts +13 -0
- package/dist/utils/source-map-resolver.util.js +26 -28
- package/package.json +1 -1
|
@@ -1,4 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strips secrets out of log lines before they leave the process.
|
|
3
|
+
*
|
|
4
|
+
* This is the only point where redaction can be done safely. Once a line has
|
|
5
|
+
* been written to the shared buffer it is going to be shipped, stored, and
|
|
6
|
+
* indexed on someone else's disk; scrubbing server-side would mean the secret
|
|
7
|
+
* had already crossed the network and been persisted. So this runs in the
|
|
8
|
+
* emitting process, on the way into the buffer, and never after.
|
|
9
|
+
*
|
|
10
|
+
* The default patterns are deliberately high-precision rather than exhaustive.
|
|
11
|
+
* A redactor that mangles ordinary log content gets switched off, and a
|
|
12
|
+
* switched-off redactor protects nothing - so the defaults only match things
|
|
13
|
+
* that are unambiguously credentials. Anything domain-specific belongs in
|
|
14
|
+
* `patterns`.
|
|
15
|
+
*
|
|
16
|
+
* Note what this is not: it is a safety net for secrets that leak into logs by
|
|
17
|
+
* accident, not a guarantee that none can. Deliberately logging a credential in
|
|
18
|
+
* a shape nothing here matches will still ship it.
|
|
19
|
+
*/
|
|
1
20
|
const DEFAULT_REPLACEMENT = "[REDACTED]";
|
|
21
|
+
/**
|
|
22
|
+
* Attribute keys whose values are masked outright, whatever they contain.
|
|
23
|
+
* Matched case-insensitively, ignoring `-` and `_`.
|
|
24
|
+
*/
|
|
2
25
|
const DEFAULT_SENSITIVE_KEYS = [
|
|
3
26
|
"password",
|
|
4
27
|
"passwd",
|
|
@@ -20,6 +43,11 @@ const DEFAULT_SENSITIVE_KEYS = [
|
|
|
20
43
|
"cookie",
|
|
21
44
|
"setcookie",
|
|
22
45
|
];
|
|
46
|
+
/**
|
|
47
|
+
* Key names recognised inside free text, as `key=value` or `"key": "value"`.
|
|
48
|
+
* Kept in step with DEFAULT_SENSITIVE_KEYS but spelled for a regex, where the
|
|
49
|
+
* separators are still present.
|
|
50
|
+
*/
|
|
23
51
|
const TEXT_KEY_ALTERNATION = [
|
|
24
52
|
"password",
|
|
25
53
|
"passwd",
|
|
@@ -42,28 +70,53 @@ const TEXT_KEY_ALTERNATION = [
|
|
|
42
70
|
].join("|");
|
|
43
71
|
function buildDefaultRules() {
|
|
44
72
|
return [
|
|
73
|
+
// PEM blocks first: they span lines and would otherwise be partially eaten
|
|
74
|
+
// by the narrower rules below.
|
|
45
75
|
{
|
|
46
76
|
pattern: /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g,
|
|
47
77
|
replace: (replacement) => replacement,
|
|
48
78
|
},
|
|
79
|
+
// Authorization schemes: `Bearer eyJ...`, `Basic dXNlcjpwYXNz`.
|
|
80
|
+
//
|
|
81
|
+
// Must precede the key=value rule. That rule's value stops at whitespace, so
|
|
82
|
+
// on `Authorization: Basic dXNlcjpwYXNz` it would consume only the word
|
|
83
|
+
// "Basic" and leave the credential itself sitting in the line.
|
|
49
84
|
{
|
|
50
85
|
pattern: /\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]{8,}/gi,
|
|
51
86
|
replace: (replacement, scheme) => `${scheme} ${replacement}`,
|
|
52
87
|
},
|
|
88
|
+
// key=value / "key": "value". Keeps the key so the line still says what was
|
|
89
|
+
// removed - a log reading `password=[REDACTED]` is far more useful than one
|
|
90
|
+
// where the whole pair vanished.
|
|
91
|
+
//
|
|
92
|
+
// The value alternation matches a scheme-prefixed credential before the bare
|
|
93
|
+
// form, so an already-masked `Authorization: Bearer [REDACTED]` collapses to
|
|
94
|
+
// a single `[REDACTED]` rather than stacking two.
|
|
53
95
|
{
|
|
54
96
|
pattern: new RegExp(`((?:${TEXT_KEY_ALTERNATION})"?\\s*[:=]\\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic|Token)\\s+\\S+|[^\\s,;&}"']+)`, "gi"),
|
|
55
97
|
replace: (replacement, prefix) => `${prefix}${replacement}`,
|
|
56
98
|
},
|
|
99
|
+
// Bare JWTs - they show up outside any header often enough to matter.
|
|
57
100
|
{
|
|
58
101
|
pattern: /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
|
|
59
102
|
replace: (replacement) => replacement,
|
|
60
103
|
},
|
|
104
|
+
// AWS access key ids. Distinctive enough to match on sight; the matching
|
|
105
|
+
// secret key has no distinguishing shape and is left to the key=value rule.
|
|
61
106
|
{
|
|
62
107
|
pattern: /\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ABIA|ACCA)[0-9A-Z]{16}\b/g,
|
|
63
108
|
replace: (replacement) => replacement,
|
|
64
109
|
},
|
|
65
110
|
];
|
|
66
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Card numbers, validated rather than pattern-matched.
|
|
114
|
+
*
|
|
115
|
+
* A bare 13-19 digit run matches plenty of innocent things - order ids, trace
|
|
116
|
+
* ids, timestamps concatenated together - so the digits are Luhn-checked before
|
|
117
|
+
* anything is masked. That turns a rule which would otherwise shred numeric log
|
|
118
|
+
* data into one that only fires on something genuinely card-shaped.
|
|
119
|
+
*/
|
|
67
120
|
const CARD_CANDIDATE = /\b\d(?:[ -]?\d){12,18}\b/g;
|
|
68
121
|
function isLuhnValid(digits) {
|
|
69
122
|
let sum = 0;
|
|
@@ -81,6 +134,12 @@ function isLuhnValid(digits) {
|
|
|
81
134
|
}
|
|
82
135
|
return sum % 10 === 0;
|
|
83
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Longest attribute tree the walker will descend.
|
|
139
|
+
*
|
|
140
|
+
* Attributes come from JSON.parse so they cannot be cyclic, but they can be
|
|
141
|
+
* arbitrarily deep, and this runs on every log line.
|
|
142
|
+
*/
|
|
84
143
|
const MAX_ATTRIBUTE_DEPTH = 8;
|
|
85
144
|
export class LogRedactor {
|
|
86
145
|
rules;
|
|
@@ -92,6 +151,8 @@ export class LogRedactor {
|
|
|
92
151
|
this.redactCards = options.useDefaultPatterns !== false;
|
|
93
152
|
const defaults = options.useDefaultPatterns === false ? [] : buildDefaultRules();
|
|
94
153
|
const extra = (options.patterns ?? []).map((pattern) => ({
|
|
154
|
+
// Rebuilt with the global flag: a caller-supplied pattern without /g would
|
|
155
|
+
// silently redact only the first occurrence in a line.
|
|
95
156
|
pattern: pattern.global
|
|
96
157
|
? pattern
|
|
97
158
|
: new RegExp(pattern.source, pattern.flags + "g"),
|
|
@@ -104,6 +165,7 @@ export class LogRedactor {
|
|
|
104
165
|
let output = message;
|
|
105
166
|
for (const rule of this.rules) {
|
|
106
167
|
output = output.replace(rule.pattern, (...args) => {
|
|
168
|
+
// String.replace passes offset and the whole string after the groups.
|
|
107
169
|
const groups = args.slice(1, -2).map((group) => group ?? "");
|
|
108
170
|
return rule.replace(this.replacement, ...groups);
|
|
109
171
|
});
|
|
@@ -137,6 +199,9 @@ export class LogRedactor {
|
|
|
137
199
|
if (value && typeof value === "object") {
|
|
138
200
|
return Object.fromEntries(Object.entries(value).map(([key, item]) => [
|
|
139
201
|
key,
|
|
202
|
+
// A sensitive key masks its value whatever the shape - an object under
|
|
203
|
+
// `credentials` is exactly what must not be walked into and partially
|
|
204
|
+
// preserved.
|
|
140
205
|
this.sensitiveKeys.has(normaliseKey(key))
|
|
141
206
|
? this.replacement
|
|
142
207
|
: this.redactValue(item, depth + 1),
|
|
@@ -1,2 +1,19 @@
|
|
|
1
1
|
export declare const REDACTED = "[REDACTED]";
|
|
2
|
+
/**
|
|
3
|
+
* Masks the values of sensitive query parameters in a request URL.
|
|
4
|
+
*
|
|
5
|
+
* Applied by default, unlike `queryParamsObfuscateRegex`, which is opt-in and
|
|
6
|
+
* so protects only the deployments that already know to ask. The URL of a
|
|
7
|
+
* request is stored on every row of `request_telemetry` and rendered in the UI,
|
|
8
|
+
* and the things routinely carried in a query string - password reset tokens,
|
|
9
|
+
* invite tokens, OAuth codes, signed URL signatures - are exactly the things
|
|
10
|
+
* that must not be readable there weeks later.
|
|
11
|
+
*
|
|
12
|
+
* Keys are kept and only values replaced: knowing a request carried a `token`
|
|
13
|
+
* is useful when reading a trace, and knowing which token is not.
|
|
14
|
+
*
|
|
15
|
+
* Values are not inspected, only keys. A regex hunting for token-shaped strings
|
|
16
|
+
* anywhere in a URL mangles ordinary path segments and ids, and a redactor that
|
|
17
|
+
* mangles real data is one somebody switches off.
|
|
18
|
+
*/
|
|
2
19
|
export declare function redactUrlQuery(url: string): string;
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Query-string keys whose values never belong in stored telemetry.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately the same list the log redactor works from, spelled for query
|
|
5
|
+
* parameters: a password-reset link is as sensitive in a URL as the same token
|
|
6
|
+
* is in a log line, and two lists that drift apart mean one of the two paths
|
|
7
|
+
* quietly stops protecting something.
|
|
8
|
+
*
|
|
9
|
+
* Matched case-insensitively, ignoring `-` and `_`, so `access_token`,
|
|
10
|
+
* `accessToken` and `access-token` are one entry.
|
|
11
|
+
*/
|
|
1
12
|
const SENSITIVE_QUERY_KEYS = new Set([
|
|
2
13
|
"password",
|
|
3
14
|
"passwd",
|
|
@@ -26,6 +37,23 @@ export const REDACTED = "[REDACTED]";
|
|
|
26
37
|
function normaliseKey(key) {
|
|
27
38
|
return key.toLowerCase().replace(/[-_]/g, "");
|
|
28
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Masks the values of sensitive query parameters in a request URL.
|
|
42
|
+
*
|
|
43
|
+
* Applied by default, unlike `queryParamsObfuscateRegex`, which is opt-in and
|
|
44
|
+
* so protects only the deployments that already know to ask. The URL of a
|
|
45
|
+
* request is stored on every row of `request_telemetry` and rendered in the UI,
|
|
46
|
+
* and the things routinely carried in a query string - password reset tokens,
|
|
47
|
+
* invite tokens, OAuth codes, signed URL signatures - are exactly the things
|
|
48
|
+
* that must not be readable there weeks later.
|
|
49
|
+
*
|
|
50
|
+
* Keys are kept and only values replaced: knowing a request carried a `token`
|
|
51
|
+
* is useful when reading a trace, and knowing which token is not.
|
|
52
|
+
*
|
|
53
|
+
* Values are not inspected, only keys. A regex hunting for token-shaped strings
|
|
54
|
+
* anywhere in a URL mangles ordinary path segments and ids, and a redactor that
|
|
55
|
+
* mangles real data is one somebody switches off.
|
|
56
|
+
*/
|
|
29
57
|
export function redactUrlQuery(url) {
|
|
30
58
|
const separator = url.indexOf("?");
|
|
31
59
|
if (separator === -1) {
|
|
@@ -33,11 +61,19 @@ export function redactUrlQuery(url) {
|
|
|
33
61
|
}
|
|
34
62
|
const path = url.slice(0, separator);
|
|
35
63
|
const rest = url.slice(separator + 1);
|
|
64
|
+
// The fragment is not sent to a server, but `req.url` is not the only caller
|
|
65
|
+
// this may ever have, and splitting it off keeps it out of the query parse.
|
|
36
66
|
const hashAt = rest.indexOf("#");
|
|
37
67
|
const query = hashAt === -1 ? rest : rest.slice(0, hashAt);
|
|
38
68
|
const fragment = hashAt === -1 ? "" : rest.slice(hashAt);
|
|
69
|
+
// Parsed and re-serialised rather than pattern-replaced: the parser is what
|
|
70
|
+
// knows that `?a=1&token=x` and `?a=1;token=x` differ, and that a value may
|
|
71
|
+
// contain an escaped `&`.
|
|
39
72
|
const params = new URLSearchParams(query);
|
|
40
73
|
let redactedAny = false;
|
|
74
|
+
// The spread is load-bearing: `params.set` below mutates the same object the
|
|
75
|
+
// iterator walks, so the keys have to be materialised before the loop starts.
|
|
76
|
+
// oxlint-disable-next-line unicorn/no-useless-spread
|
|
41
77
|
for (const key of [...params.keys()]) {
|
|
42
78
|
if (SENSITIVE_QUERY_KEYS.has(normaliseKey(key))) {
|
|
43
79
|
params.set(key, REDACTED);
|
|
@@ -45,6 +81,8 @@ export function redactUrlQuery(url) {
|
|
|
45
81
|
}
|
|
46
82
|
}
|
|
47
83
|
if (!redactedAny) {
|
|
84
|
+
// Returned untouched so a URL with nothing to hide is stored exactly as it
|
|
85
|
+
// arrived, rather than in URLSearchParams' normalised spelling.
|
|
48
86
|
return url;
|
|
49
87
|
}
|
|
50
88
|
return `${path}?${params.toString()}${fragment}`;
|
|
@@ -1,9 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A slice of source around a stack frame, for rendering the throw site.
|
|
3
|
+
*/
|
|
1
4
|
export interface CodeFrame {
|
|
5
|
+
/** Absolute path of the file the frame points at. */
|
|
2
6
|
file: string;
|
|
7
|
+
/** 1-based line the frame points at - the line to highlight. */
|
|
3
8
|
line: number;
|
|
9
|
+
/** 1-based line number that `lines[0]` corresponds to. */
|
|
4
10
|
firstLine: number;
|
|
11
|
+
/** Source lines, `firstLine` through `firstLine + lines.length - 1`. */
|
|
5
12
|
lines: string[];
|
|
6
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* Reads source around each in-app frame of a stack trace.
|
|
16
|
+
*
|
|
17
|
+
* Only the machine running the code can read its own files, so this has to happen
|
|
18
|
+
* agent-side at throw time - the position in a frame is already exact (the app
|
|
19
|
+
* runs with source-map support, so frames resolve to TypeScript), but the file
|
|
20
|
+
* contents are not something the server can recover.
|
|
21
|
+
*
|
|
22
|
+
* Deliberately bounded: in-app frames only, a handful of lines either side, and a
|
|
23
|
+
* cap on how many frames are attached, because whatever this returns is shipped to
|
|
24
|
+
* the server and stored in the telemetry database.
|
|
25
|
+
*
|
|
26
|
+
* Never throws - source context is a nicety and must not be able to break the
|
|
27
|
+
* request that was already failing.
|
|
28
|
+
*/
|
|
7
29
|
export declare function collectCodeFrames(stack: string | undefined, options?: {
|
|
8
30
|
linesOfContext?: number;
|
|
9
31
|
maxFrames?: number;
|
|
@@ -2,21 +2,56 @@ import { readFileSync } from "fs";
|
|
|
2
2
|
import { resolve, sep } from "path";
|
|
3
3
|
import { resolveOriginalPosition } from "./source-map-resolver.util.js";
|
|
4
4
|
const DEFAULT_LINES_OF_CONTEXT = 5;
|
|
5
|
+
/**
|
|
6
|
+
* Frames worth reading source for. Everything below the app - dependencies and
|
|
7
|
+
* the Node internals - is noise on a stack view and would balloon the payload.
|
|
8
|
+
*/
|
|
5
9
|
const IGNORED_FRAME_PATTERNS = [
|
|
6
10
|
/[\\/]node_modules[\\/]/,
|
|
7
11
|
/^node:/,
|
|
8
12
|
/^internal[\\/]/,
|
|
9
13
|
/^\s*$/,
|
|
10
14
|
];
|
|
15
|
+
/**
|
|
16
|
+
* Cap on distinct files held in memory. Source files do not change while the
|
|
17
|
+
* process runs, so entries never need invalidating; this only bounds a pathological
|
|
18
|
+
* process that throws from thousands of distinct files.
|
|
19
|
+
*/
|
|
11
20
|
const MAX_CACHED_FILES = 200;
|
|
12
21
|
const MAX_LINES_OF_CONTEXT = 50;
|
|
13
22
|
const MAX_FRAMES = 20;
|
|
23
|
+
/**
|
|
24
|
+
* Files already read, including ones that failed (cached as null) so a bundled or
|
|
25
|
+
* deleted file is not retried on every single throw.
|
|
26
|
+
*/
|
|
14
27
|
const sourceCache = new Map();
|
|
28
|
+
/**
|
|
29
|
+
* V8 stack frame lines, both shapes:
|
|
30
|
+
* at fn (/abs/path/file.ts:42:31)
|
|
31
|
+
* at /abs/path/file.ts:42:31
|
|
32
|
+
*/
|
|
15
33
|
const FRAME_PATTERN = /^\s*at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?\s*$/;
|
|
16
34
|
function isIgnored(file) {
|
|
17
35
|
return IGNORED_FRAME_PATTERNS.some((pattern) => pattern.test(file));
|
|
18
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Extensions a stack frame can legitimately point at. An allowlist rather than
|
|
39
|
+
* a denylist, because the set of files that must never be read (`.env`, key
|
|
40
|
+
* material, arbitrary system files) is open-ended and the set of files V8 can
|
|
41
|
+
* actually be executing is not.
|
|
42
|
+
*/
|
|
19
43
|
const READABLE_EXTENSIONS = /\.(?:js|cjs|mjs|jsx|ts|cts|mts|tsx)$/;
|
|
44
|
+
/**
|
|
45
|
+
* Whether a frame's path is one this module is willing to read and ship.
|
|
46
|
+
*
|
|
47
|
+
* A stack string is not a trusted input: `Error#stack` is message plus frames,
|
|
48
|
+
* the message routinely interpolates user data, and a multi-line value there
|
|
49
|
+
* puts attacker-chosen text on its own line where it parses exactly like a
|
|
50
|
+
* frame. An unrestricted reader would turn that into "log a crafted string,
|
|
51
|
+
* receive any file on the host in the telemetry store". So only files under
|
|
52
|
+
* the application's own root, with an extension the runtime can execute, are
|
|
53
|
+
* eligible - which is also precisely the set of files worth rendering.
|
|
54
|
+
*/
|
|
20
55
|
function isReadableSourcePath(file) {
|
|
21
56
|
if (!READABLE_EXTENSIONS.test(file)) {
|
|
22
57
|
return false;
|
|
@@ -36,6 +71,8 @@ function parseFrames(stack) {
|
|
|
36
71
|
if (isIgnored(file)) {
|
|
37
72
|
continue;
|
|
38
73
|
}
|
|
74
|
+
// Only absolute paths can be read back off disk. Anything else (an eval
|
|
75
|
+
// frame, a bundled virtual path) has no file to open.
|
|
39
76
|
if (!file.startsWith("/") && !/^[a-zA-Z]:[\\/]/.test(file)) {
|
|
40
77
|
continue;
|
|
41
78
|
}
|
|
@@ -55,6 +92,8 @@ function readSource(file) {
|
|
|
55
92
|
lines = readFileSync(file, "utf8").split("\n");
|
|
56
93
|
}
|
|
57
94
|
catch {
|
|
95
|
+
// Unreadable for any reason - bundled away, permissions, deleted since
|
|
96
|
+
// build. Cached as a miss so it is not retried on the next throw.
|
|
58
97
|
lines = null;
|
|
59
98
|
}
|
|
60
99
|
if (sourceCache.size >= MAX_CACHED_FILES) {
|
|
@@ -66,6 +105,21 @@ function readSource(file) {
|
|
|
66
105
|
sourceCache.set(file, lines);
|
|
67
106
|
return lines;
|
|
68
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Reads source around each in-app frame of a stack trace.
|
|
110
|
+
*
|
|
111
|
+
* Only the machine running the code can read its own files, so this has to happen
|
|
112
|
+
* agent-side at throw time - the position in a frame is already exact (the app
|
|
113
|
+
* runs with source-map support, so frames resolve to TypeScript), but the file
|
|
114
|
+
* contents are not something the server can recover.
|
|
115
|
+
*
|
|
116
|
+
* Deliberately bounded: in-app frames only, a handful of lines either side, and a
|
|
117
|
+
* cap on how many frames are attached, because whatever this returns is shipped to
|
|
118
|
+
* the server and stored in the telemetry database.
|
|
119
|
+
*
|
|
120
|
+
* Never throws - source context is a nicety and must not be able to break the
|
|
121
|
+
* request that was already failing.
|
|
122
|
+
*/
|
|
69
123
|
export function collectCodeFrames(stack, options = {}) {
|
|
70
124
|
if (!stack) {
|
|
71
125
|
return undefined;
|
|
@@ -98,11 +152,15 @@ export function collectCodeFrames(stack, options = {}) {
|
|
|
98
152
|
if (options.sourceMaps) {
|
|
99
153
|
const original = resolveOriginalPosition(frame.file, frame.line, frame.column);
|
|
100
154
|
if (original) {
|
|
155
|
+
// Re-apply the in-app filter to the mapped path: a frame in
|
|
156
|
+
// dist/main.js can map back into node_modules, and that is still noise.
|
|
101
157
|
if (isIgnored(original.file)) {
|
|
102
158
|
continue;
|
|
103
159
|
}
|
|
104
160
|
file = original.file;
|
|
105
161
|
line = original.line;
|
|
162
|
+
// Prefer the map's embedded copy - it is the source this build was
|
|
163
|
+
// compiled from, and it works when the source tree is not deployed.
|
|
106
164
|
source = original.content ?? null;
|
|
107
165
|
}
|
|
108
166
|
}
|
|
@@ -111,8 +169,10 @@ export function collectCodeFrames(stack, options = {}) {
|
|
|
111
169
|
continue;
|
|
112
170
|
}
|
|
113
171
|
if (line > source.length) {
|
|
172
|
+
// Position does not fit the file - stale build against changed source.
|
|
114
173
|
continue;
|
|
115
174
|
}
|
|
175
|
+
// Frame lines are 1-based; array indices are 0-based.
|
|
116
176
|
const firstLine = Math.max(1, line - linesOfContext);
|
|
117
177
|
const lastLine = Math.min(source.length, line + linesOfContext);
|
|
118
178
|
codeFrames.push({
|
|
@@ -1,7 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A stack frame position mapped back to the source it was compiled from.
|
|
3
|
+
*/
|
|
1
4
|
export interface OriginalPosition {
|
|
5
|
+
/** Absolute path of the original file, or the map-relative path if it cannot be resolved. */
|
|
2
6
|
file: string;
|
|
7
|
+
/** 1-based line in the original file. */
|
|
3
8
|
line: number;
|
|
9
|
+
/** Original source text, when the map carries `sourcesContent`. */
|
|
4
10
|
content?: string[];
|
|
5
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Maps a compiled frame position back to the original source.
|
|
14
|
+
*
|
|
15
|
+
* Returns undefined when there is no usable map, leaving the caller to fall back
|
|
16
|
+
* to the compiled file - a degraded but still truthful result.
|
|
17
|
+
*/
|
|
6
18
|
export declare function resolveOriginalPosition(file: string, line: number, column: number): OriginalPosition | undefined;
|
|
19
|
+
/** Testing seam - the caches are process-lifetime otherwise. */
|
|
7
20
|
export declare function resetSourceMapCache(): void;
|
|
@@ -1,30 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* `@jridgewell/trace-mapping` is imported statically rather than pulled in on
|
|
3
|
+
* first use through `createRequire(import.meta.url)`. The shim was valid only
|
|
4
|
+
* under ESM: consumers whose test runner transpiles this package down to
|
|
5
|
+
* CommonJS got `const require = ...` on top of the module-scope `require`,
|
|
6
|
+
* which is a redeclaration - the package failed to load at all under Jest.
|
|
7
|
+
* It is a hard dependency with no import-time side effects, so binding it
|
|
8
|
+
* eagerly costs one module parse and keeps this file loadable either way.
|
|
9
|
+
*/
|
|
10
|
+
import { originalPositionFor, sourceContentFor, TraceMap, } from "@jridgewell/trace-mapping";
|
|
2
11
|
import { readFileSync } from "node:fs";
|
|
3
12
|
import { dirname, resolve } from "node:path";
|
|
4
|
-
const require = createRequire(import.meta.url);
|
|
5
13
|
const SOURCE_MAPPING_URL_PATTERN = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/gm;
|
|
6
14
|
const INLINE_MAP_PREFIX = "data:application/json";
|
|
15
|
+
/** Parsed maps by compiled-file path; null marks "looked, found none". */
|
|
7
16
|
const mapCache = new Map();
|
|
8
|
-
let traceMappingModule = null;
|
|
9
|
-
let traceMappingLoadAttempted = false;
|
|
10
|
-
function loadTraceMapping() {
|
|
11
|
-
if (traceMappingLoadAttempted) {
|
|
12
|
-
return traceMappingModule;
|
|
13
|
-
}
|
|
14
|
-
traceMappingLoadAttempted = true;
|
|
15
|
-
try {
|
|
16
|
-
traceMappingModule = require("@jridgewell/trace-mapping");
|
|
17
|
-
}
|
|
18
|
-
catch {
|
|
19
|
-
traceMappingModule = null;
|
|
20
|
-
}
|
|
21
|
-
return traceMappingModule;
|
|
22
|
-
}
|
|
23
17
|
function readMapFor(file) {
|
|
24
|
-
const traceMapping = loadTraceMapping();
|
|
25
|
-
if (!traceMapping) {
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
18
|
let compiled;
|
|
29
19
|
try {
|
|
30
20
|
compiled = readFileSync(file, "utf8");
|
|
@@ -32,6 +22,7 @@ function readMapFor(file) {
|
|
|
32
22
|
catch {
|
|
33
23
|
return null;
|
|
34
24
|
}
|
|
25
|
+
// Last occurrence wins: a bundle can contain the string in its own payload.
|
|
35
26
|
let url;
|
|
36
27
|
for (const match of compiled.matchAll(SOURCE_MAPPING_URL_PATTERN)) {
|
|
37
28
|
url = match[1];
|
|
@@ -61,7 +52,7 @@ function readMapFor(file) {
|
|
|
61
52
|
}
|
|
62
53
|
try {
|
|
63
54
|
return {
|
|
64
|
-
tracer: new
|
|
55
|
+
tracer: new TraceMap(JSON.parse(rawMap)),
|
|
65
56
|
mapDir,
|
|
66
57
|
};
|
|
67
58
|
}
|
|
@@ -77,23 +68,29 @@ function getMap(file) {
|
|
|
77
68
|
mapCache.set(file, loaded);
|
|
78
69
|
return loaded;
|
|
79
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Maps a compiled frame position back to the original source.
|
|
73
|
+
*
|
|
74
|
+
* Returns undefined when there is no usable map, leaving the caller to fall back
|
|
75
|
+
* to the compiled file - a degraded but still truthful result.
|
|
76
|
+
*/
|
|
80
77
|
export function resolveOriginalPosition(file, line, column) {
|
|
81
|
-
const traceMapping = loadTraceMapping();
|
|
82
|
-
if (!traceMapping) {
|
|
83
|
-
return undefined;
|
|
84
|
-
}
|
|
85
78
|
const map = getMap(file);
|
|
86
79
|
if (!map) {
|
|
87
80
|
return undefined;
|
|
88
81
|
}
|
|
89
|
-
const position =
|
|
82
|
+
const position = originalPositionFor(map.tracer, {
|
|
90
83
|
line,
|
|
84
|
+
// Stack columns are 1-based, source map columns are 0-based.
|
|
91
85
|
column: Math.max(0, column - 1),
|
|
92
86
|
});
|
|
93
87
|
if (!position.source || position.line === null) {
|
|
94
88
|
return undefined;
|
|
95
89
|
}
|
|
96
|
-
|
|
90
|
+
// `sourcesContent` is the reliable path: the original text is embedded in the
|
|
91
|
+
// map, so it works even when the source tree is absent at runtime (a container
|
|
92
|
+
// shipping only dist, for instance).
|
|
93
|
+
const embedded = sourceContentFor(map.tracer, position.source);
|
|
97
94
|
return {
|
|
98
95
|
file: position.source.startsWith("/")
|
|
99
96
|
? position.source
|
|
@@ -102,6 +99,7 @@ export function resolveOriginalPosition(file, line, column) {
|
|
|
102
99
|
content: embedded ? embedded.split("\n") : undefined,
|
|
103
100
|
};
|
|
104
101
|
}
|
|
102
|
+
/** Testing seam - the caches are process-lifetime otherwise. */
|
|
105
103
|
export function resetSourceMapCache() {
|
|
106
104
|
mapCache.clear();
|
|
107
105
|
}
|
package/package.json
CHANGED