@nestjs/observe 0.3.25 → 0.3.27
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 +55 -2
- package/dist/agent/detached-observe-worker.js +50 -6
- package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
- package/dist/agent/observe-agent.shared-buffer.js +201 -19
- package/dist/agent/observe-agent.worker.d.ts +22 -2
- package/dist/agent/observe-agent.worker.js +43 -7
- package/dist/agent/telemetry-wire-contract.js +10 -4
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +51 -4
- package/dist/cli/observe-cli.js +1 -19
- package/dist/cli/open-url.d.ts +27 -0
- package/dist/cli/open-url.js +63 -0
- package/dist/cli/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +62 -1
- package/dist/cli/project-files.js +229 -7
- package/dist/cli/project-setup.d.ts +6 -0
- package/dist/cli/project-setup.js +14 -1
- package/dist/cli/wire-application.js +6 -0
- package/dist/custom-metrics/counter.d.ts +13 -2
- package/dist/custom-metrics/counter.js +33 -16
- package/dist/custom-metrics/finite-value.util.d.ts +14 -0
- package/dist/custom-metrics/finite-value.util.js +33 -1
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +41 -17
- package/dist/custom-metrics/label-values.util.d.ts +37 -0
- package/dist/custom-metrics/label-values.util.js +51 -0
- package/dist/custom-metrics/summary.d.ts +23 -0
- package/dist/custom-metrics/summary.js +90 -12
- package/dist/instrument/create-instance-decorator.instrument.js +504 -116
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +17 -6
- package/dist/objectives/objectives.registry.js +12 -0
- package/dist/observe.module.js +119 -3
- package/dist/otlp/otlp-encoders.js +22 -5
- package/dist/otlp/otlp-span.mapper.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +26 -4
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +295 -43
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +49 -17
- package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
- package/dist/outgoing/llm/llm-providers.d.ts +16 -4
- package/dist/outgoing/llm/llm-providers.js +72 -22
- package/dist/outgoing/llm/llm-usage.d.ts +11 -6
- package/dist/outgoing/llm/llm-usage.js +72 -25
- package/dist/outgoing/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +25 -6
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
- package/dist/outgoing/outgoing-span.recorder.js +17 -3
- package/dist/outgoing/pg.integration.d.ts +3 -2
- package/dist/outgoing/pg.integration.js +39 -11
- package/dist/outgoing/sql-statement.util.js +139 -21
- package/dist/outgoing/undici.integration.d.ts +13 -0
- package/dist/outgoing/undici.integration.js +68 -0
- package/dist/protocols/bull-observe-agent.service.js +23 -12
- package/dist/protocols/deferred-trace-completion.d.ts +17 -3
- package/dist/protocols/deferred-trace-completion.js +76 -9
- package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
- package/dist/protocols/graphql-observe-agent.service.js +354 -19
- package/dist/protocols/graphql-operation-parser.js +111 -26
- package/dist/protocols/http-observe-agent.service.d.ts +50 -9
- package/dist/protocols/http-observe-agent.service.js +220 -59
- package/dist/protocols/job-trace-runner.d.ts +42 -3
- package/dist/protocols/job-trace-runner.js +197 -36
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
- package/dist/protocols/rpc-observe-agent.service.js +332 -56
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +227 -21
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +16 -7
- package/dist/services/operation-trace.registry.d.ts +58 -1
- package/dist/services/operation-trace.registry.js +576 -63
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +308 -51
- package/dist/services/tracer.service.d.ts +39 -11
- package/dist/services/tracer.service.js +145 -36
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +128 -12
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +22 -0
- package/dist/utils/log-line.parser.js +20 -7
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +690 -65
- package/dist/utils/operation-state.util.d.ts +39 -0
- package/dist/utils/operation-state.util.js +50 -0
- package/dist/utils/redact-url-query.d.ts +37 -4
- package/dist/utils/redact-url-query.js +197 -32
- package/dist/utils/sensitive-keys.d.ts +4 -1
- package/dist/utils/sensitive-keys.js +48 -10
- package/dist/utils/shared-hook-slot.util.d.ts +48 -0
- package/dist/utils/shared-hook-slot.util.js +103 -0
- package/dist/utils/source-context.util.d.ts +14 -0
- package/dist/utils/source-context.util.js +142 -43
- package/dist/utils/source-map-resolver.util.js +33 -6
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- package/dist/utils/trace-context.util.js +21 -6
- package/package.json +2 -2
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { Reflector } from "@nestjs/core";
|
|
2
|
+
import { X509Certificate } from "node:crypto";
|
|
3
|
+
import { Stream } from "node:stream";
|
|
4
|
+
import { types } from "node:util";
|
|
2
5
|
import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
6
|
+
import { copyStore } from "../utils/store-copy.util.js";
|
|
7
|
+
import { rewriteStackFrames } from "../utils/error-stack.util.js";
|
|
8
|
+
import { registerRawReceiver } from "./raw-receiver.js";
|
|
3
9
|
/**
|
|
4
10
|
* Stand-in "class name" for instrumented standalone functions. Unlike methods,
|
|
5
11
|
* they have no enclosing class to borrow a name from, so every span they emit
|
|
@@ -49,20 +55,85 @@ function isFrameworkNoise(instance) {
|
|
|
49
55
|
* `MongoClient.startSession` spans are not.
|
|
50
56
|
*
|
|
51
57
|
* Matched by name and shape only: the driver is an optional peer, never
|
|
52
|
-
* imported here, and an application may carry more than one copy of it.
|
|
58
|
+
* imported here, and an application may carry more than one copy of it. The
|
|
59
|
+
* name is looked for on every class up the prototype chain, so a provider
|
|
60
|
+
* class that extends either one - `class MongoService extends MongoClient` -
|
|
61
|
+
* is left alone too, for the same reason.
|
|
53
62
|
*/
|
|
54
63
|
function isMongoDriverHandle(instance) {
|
|
55
64
|
const candidate = instance;
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
65
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
66
|
+
const name = Object.hasOwn(proto, "constructor")
|
|
67
|
+
? proto.constructor?.name
|
|
68
|
+
: undefined;
|
|
69
|
+
if (name === "MongoClient" &&
|
|
70
|
+
typeof candidate.startSession === "function" &&
|
|
71
|
+
typeof candidate.db === "function") {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
if (name === "Db" &&
|
|
75
|
+
typeof candidate.collection === "function" &&
|
|
76
|
+
typeof candidate.databaseName === "string") {
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Whether an instance is data and nothing else: an object literal, a
|
|
84
|
+
* null-prototype record or an array with no function and no accessor among
|
|
85
|
+
* its own members - the options object or list behind a `useValue`, or what a
|
|
86
|
+
* `useFactory` returns.
|
|
87
|
+
*
|
|
88
|
+
* It has no method of its own to trace, and a proxy around it breaks what the
|
|
89
|
+
* value itself supports: the structured clone algorithm consults no trap and
|
|
90
|
+
* refuses a proxy whatever its target is, so `structuredClone`, `postMessage`,
|
|
91
|
+
* `workerData` and `v8.serialize` all threw on an injected options object.
|
|
92
|
+
* What it inherits from `Object` or `Array` (`columns.map`) is no longer
|
|
93
|
+
* traced either.
|
|
94
|
+
*
|
|
95
|
+
* Members are read as descriptors, so no getter runs here; an accessor may
|
|
96
|
+
* hand out a function, and so counts as one. A proxy is never data: it
|
|
97
|
+
* answers these questions with its traps - a nestjs-cls proxy provider reads
|
|
98
|
+
* as `{}` until a request resolves it - and could not be cloned to begin with.
|
|
99
|
+
*/
|
|
100
|
+
function isPlainData(instance) {
|
|
101
|
+
if (types.isProxy(instance)) {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
const proto = Object.getPrototypeOf(instance);
|
|
105
|
+
if (proto !== null &&
|
|
106
|
+
proto !== Object.prototype &&
|
|
107
|
+
proto !== Array.prototype) {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
for (const key of Reflect.ownKeys(instance)) {
|
|
111
|
+
const own = Reflect.getOwnPropertyDescriptor(instance, key);
|
|
112
|
+
if (own === undefined ||
|
|
113
|
+
own.get !== undefined ||
|
|
114
|
+
own.set !== undefined ||
|
|
115
|
+
typeof own.value === "function") {
|
|
64
116
|
return false;
|
|
117
|
+
}
|
|
65
118
|
}
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Whether an instance is a key or a certificate of `node:crypto`: a
|
|
123
|
+
* `KeyObject`, a Web Crypto `CryptoKey` or an `X509Certificate`.
|
|
124
|
+
*
|
|
125
|
+
* Node recognises each by a brand of its own (`#slots in key`, an internal
|
|
126
|
+
* slot) wherever one is handed in as an argument - to `createHmac`, `sign`,
|
|
127
|
+
* `subtle.sign`, `cert.checkIssued`, and through them `jsonwebtoken` - and no
|
|
128
|
+
* proxy carries it, so an injected key failed every call it was given to
|
|
129
|
+
* ("The "key" argument must be of type ... KeyObject"). Its methods run
|
|
130
|
+
* against the raw instance either way; handed out as a proxy, it is no longer
|
|
131
|
+
* the object Node made.
|
|
132
|
+
*/
|
|
133
|
+
function isCryptoHandle(instance) {
|
|
134
|
+
return (types.isKeyObject(instance) ||
|
|
135
|
+
types.isCryptoKey(instance) ||
|
|
136
|
+
instance instanceof X509Certificate);
|
|
66
137
|
}
|
|
67
138
|
/**
|
|
68
139
|
* Library classes traced only in part, each with a method only it has, which
|
|
@@ -108,13 +179,26 @@ const PARTLY_TRACED_CLASSES = new Map([
|
|
|
108
179
|
},
|
|
109
180
|
],
|
|
110
181
|
]);
|
|
111
|
-
/**
|
|
182
|
+
/**
|
|
183
|
+
* The methods a prototype's class keeps traced, if it is one of those.
|
|
184
|
+
*
|
|
185
|
+
* The marker has to be the class's own, and new with it. A subclass an
|
|
186
|
+
* application names after the class it extends (`import { ValidationPipe as
|
|
187
|
+
* NestValidationPipe }`) inherits the marker, or overrides it, and is still
|
|
188
|
+
* the application's: taken for the library's, its methods were handed out
|
|
189
|
+
* unwrapped, and one that reads a private member (`this.#x`) threw on the
|
|
190
|
+
* proxy it then ran against.
|
|
191
|
+
*/
|
|
112
192
|
function partlyTracedMethodsOf(proto) {
|
|
113
193
|
const candidate = proto;
|
|
114
194
|
const entry = PARTLY_TRACED_CLASSES.get(candidate.constructor?.name ?? "");
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
195
|
+
if (entry === undefined ||
|
|
196
|
+
!Object.hasOwn(proto, entry.marker) ||
|
|
197
|
+
typeof candidate[entry.marker] !== "function") {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
const parent = Object.getPrototypeOf(proto);
|
|
201
|
+
return parent === null || !(entry.marker in parent) ? entry.traced : null;
|
|
118
202
|
}
|
|
119
203
|
/** Whether an instance is one of those classes, or extends one. */
|
|
120
204
|
function extendsPartlyTracedClass(instance) {
|
|
@@ -146,7 +230,9 @@ function isLibraryInternal(target, methodName) {
|
|
|
146
230
|
}
|
|
147
231
|
export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
148
232
|
/**
|
|
149
|
-
* Builds the tracing wrapper shared by methods and standalone functions
|
|
233
|
+
* Builds the tracing wrapper shared by methods and standalone functions:
|
|
234
|
+
* called with the receiver and the arguments of the call it stands in for,
|
|
235
|
+
* as the `apply` trap that dispatches to it is handed them.
|
|
150
236
|
*
|
|
151
237
|
* Every function this creates is named `<className>.<methodName>`, so the
|
|
152
238
|
* frames instrumentation contributes to a stack trace read like the call the
|
|
@@ -160,6 +246,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
160
246
|
// "Object.<name>".
|
|
161
247
|
const call = spec.call;
|
|
162
248
|
const callUntraced = spec.callUntraced;
|
|
249
|
+
const isAsync = spec.isAsync;
|
|
163
250
|
const endStep = (requestId, stepId) => operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId);
|
|
164
251
|
const recordError = (requestId, stepId, err) => {
|
|
165
252
|
// Before the registry records the step: `internalEndTraceStep` copies
|
|
@@ -176,7 +263,13 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
176
263
|
const callTraced = named(frameName, (thisArg, args, requestId, stepId) => {
|
|
177
264
|
try {
|
|
178
265
|
const result = call(thisArg, args);
|
|
179
|
-
|
|
266
|
+
// Only a promise with the native `then` is chained or watched. A
|
|
267
|
+
// `then` the promise brought itself is the caller's to call: on a
|
|
268
|
+
// lazy promise (`p-lazy`, a postgres.js query) that call is what
|
|
269
|
+
// starts the work, and the caller may never make it. Such a
|
|
270
|
+
// promise is handed back like any other thenable, and its span
|
|
271
|
+
// ends with the call.
|
|
272
|
+
if (result instanceof Promise && hasNativeThen(result)) {
|
|
180
273
|
// Closing the span is a side effect: a registry failure must
|
|
181
274
|
// leave the caller with the value or rejection it would have
|
|
182
275
|
// seen without the span.
|
|
@@ -188,18 +281,24 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
188
281
|
ignoreFailure(() => recordError(requestId, stepId, err));
|
|
189
282
|
throw err;
|
|
190
283
|
};
|
|
191
|
-
//
|
|
192
|
-
// the caller's own `.then` would:
|
|
193
|
-
//
|
|
194
|
-
|
|
284
|
+
// The promise of a native `async` method is swapped for a chained
|
|
285
|
+
// one, just as the caller's own `.then` would: nothing but the
|
|
286
|
+
// caller can hold it, so a rejection the caller drops still
|
|
287
|
+
// raises `unhandledRejection`, as without the span.
|
|
288
|
+
if (isAsync) {
|
|
195
289
|
return result.then(settled, failed);
|
|
196
290
|
}
|
|
197
|
-
//
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
//
|
|
202
|
-
//
|
|
291
|
+
// Any other promise is handed back as-is and watched on a side
|
|
292
|
+
// branch, the way `OutgoingSpanRecorder.endWhenSettled` watches
|
|
293
|
+
// outgoing calls. It may be held elsewhere - a `.catch` the method
|
|
294
|
+
// attached itself, an in-flight promise callers share, the
|
|
295
|
+
// callback ioredis answers a command through - and a chained copy
|
|
296
|
+
// rejected where those handlers do not reach: dropped by the
|
|
297
|
+
// caller, it was an unhandled rejection, and under Node's default
|
|
298
|
+
// it ended a process that handled the failure. Handed back, it
|
|
299
|
+
// also keeps what it carries beyond its value (`kill()` on an
|
|
300
|
+
// `execa` child, a subclass that keeps the native `then`).
|
|
301
|
+
// Watching marks it handled, so a rejection nobody handles no
|
|
203
302
|
// longer raises `unhandledRejection`; the span still records it.
|
|
204
303
|
result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
|
|
205
304
|
return result;
|
|
@@ -212,44 +311,48 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
212
311
|
// Re-throw the error to maintain original behavior
|
|
213
312
|
throw err;
|
|
214
313
|
}
|
|
215
|
-
finally {
|
|
216
|
-
spec.setActive(false);
|
|
217
|
-
}
|
|
218
314
|
});
|
|
219
|
-
//
|
|
220
|
-
//
|
|
221
|
-
|
|
315
|
+
// The receiver the call was made with is handed on, not read off `this`:
|
|
316
|
+
// the wrapper is called as a plain function, so V8 prints its frame as
|
|
317
|
+
// top-level, under the name above.
|
|
318
|
+
return named(frameName, (thisArg, args) => {
|
|
222
319
|
// Already tracing this callable, invoke it as-is
|
|
223
320
|
if (spec.isActive()) {
|
|
224
|
-
return callUntraced(
|
|
321
|
+
return callUntraced(thisArg, args);
|
|
225
322
|
}
|
|
226
323
|
const store = als.getStore();
|
|
227
324
|
const requestId = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(options.traceIdKey);
|
|
228
325
|
if (!requestId) {
|
|
229
|
-
return callUntraced(
|
|
326
|
+
return callUntraced(thisArg, args);
|
|
230
327
|
}
|
|
328
|
+
// Cleared in the frame that set it, whatever throws in between: opening
|
|
329
|
+
// the step, copying the store and entering it can each run out of
|
|
330
|
+
// stack, and a flag left set sent every later call of this method, from
|
|
331
|
+
// any request, down the untraced path until the process restarted.
|
|
231
332
|
spec.setActive(true);
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
finally {
|
|
244
|
-
spec.setActive(false);
|
|
333
|
+
try {
|
|
334
|
+
const callerId = store?.get(CALLER_METADATA_KEY);
|
|
335
|
+
const newStepId = operationTraceRegistry.internalStartTraceStep(requestId, className, methodName, callerId);
|
|
336
|
+
// No step means the registry holds no snapshot for this trace id -
|
|
337
|
+
// the request was dropped by `http.ignore` or sampled out, but its
|
|
338
|
+
// store still carries the id, which log correlation needs there - or
|
|
339
|
+
// the operation has opened as many spans as one may. Nothing was
|
|
340
|
+
// opened, so nothing must be closed; without this bail-out every
|
|
341
|
+
// provider call on an ignored route logged a registry error.
|
|
342
|
+
if (newStepId === undefined) {
|
|
343
|
+
return callUntraced(thisArg, args);
|
|
245
344
|
}
|
|
345
|
+
// Everything the caller's context holds, with this span as the caller
|
|
346
|
+
// of whatever it calls. A copy, so the caller's context still names
|
|
347
|
+
// the caller once this call returns. Only the caller is the span's
|
|
348
|
+
// own: an attribute set in the call is written through to the
|
|
349
|
+
// caller's context too - see `copyStore`.
|
|
350
|
+
const spanStore = copyStore(store, [CALLER_METADATA_KEY, newStepId]);
|
|
351
|
+
return als.run(spanStore, callTraced, thisArg, args, requestId, newStepId);
|
|
352
|
+
}
|
|
353
|
+
finally {
|
|
354
|
+
spec.setActive(false);
|
|
246
355
|
}
|
|
247
|
-
// Everything the caller's context holds, with this span as the caller
|
|
248
|
-
// of whatever it calls. A copy, so the caller's context still names the
|
|
249
|
-
// caller once this call returns.
|
|
250
|
-
const spanStore = new Map(store);
|
|
251
|
-
spanStore.set(CALLER_METADATA_KEY, newStepId);
|
|
252
|
-
return als.run(spanStore, callTraced, this, args, requestId, newStepId);
|
|
253
356
|
});
|
|
254
357
|
};
|
|
255
358
|
const instrumentFunction = (fn) => {
|
|
@@ -271,6 +374,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
271
374
|
spanId: `${className}#${methodName}`,
|
|
272
375
|
isActive: () => active,
|
|
273
376
|
setActive: (value) => (active = value),
|
|
377
|
+
isAsync: types.isAsyncFunction(fn),
|
|
274
378
|
call: invoke,
|
|
275
379
|
callUntraced: invoke,
|
|
276
380
|
});
|
|
@@ -279,7 +383,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
279
383
|
// static properties, `instanceof` and reflect-metadata lookups. Only
|
|
280
384
|
// `apply` is trapped, so `new fn()` still constructs the original.
|
|
281
385
|
return new Proxy(fn, {
|
|
282
|
-
apply: named(frameName, (_target, thisArg, args) =>
|
|
386
|
+
apply: named(frameName, (_target, thisArg, args) => tracedFn(thisArg, args)),
|
|
283
387
|
});
|
|
284
388
|
};
|
|
285
389
|
const instrumentObject = (instance) => {
|
|
@@ -301,16 +405,29 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
301
405
|
let slotBacked;
|
|
302
406
|
let bareBuiltIn;
|
|
303
407
|
let partlyTraced;
|
|
408
|
+
let nodeStream;
|
|
409
|
+
let classInstance;
|
|
304
410
|
try {
|
|
305
411
|
// Inspected here, inside the guard, for the same reason as the checks
|
|
306
412
|
// below: reading a provider's constructor can run a trap that throws.
|
|
307
|
-
|
|
413
|
+
//
|
|
414
|
+
// A frozen object is handed back as it is: a proxy has to answer a read
|
|
415
|
+
// of each of its members with the member itself, so there is nothing
|
|
416
|
+
// it could trace - see `isReadOnlyDataProperty`. So is plain data, which
|
|
417
|
+
// has nothing to trace and which a proxy keeps from being cloned, and
|
|
418
|
+
// a key or certificate of Node's own.
|
|
419
|
+
if (isFrameworkNoise(instance) ||
|
|
420
|
+
Object.isFrozen(instance) ||
|
|
421
|
+
isPlainData(instance) ||
|
|
422
|
+
isCryptoHandle(instance)) {
|
|
308
423
|
return instance;
|
|
309
424
|
}
|
|
310
|
-
hasPrivateMembers =
|
|
425
|
+
hasPrivateMembers = usesPrivateMembers(instance);
|
|
311
426
|
slotBacked = isSlotBackedBuiltIn(instance);
|
|
312
427
|
bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
|
|
313
428
|
partlyTraced = extendsPartlyTracedClass(instance);
|
|
429
|
+
nodeStream = isNodeStream(instance);
|
|
430
|
+
classInstance = isClassInstance(instance);
|
|
314
431
|
}
|
|
315
432
|
catch {
|
|
316
433
|
// Reading the prototype ran a trap that threw (nestjs-cls proxy
|
|
@@ -328,23 +445,54 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
328
445
|
}
|
|
329
446
|
// Slot-backed subclasses share the private-member trade-off: methods run
|
|
330
447
|
// against the raw instance so the natives they inherit keep working.
|
|
331
|
-
|
|
448
|
+
//
|
|
449
|
+
// So does a Node stream, for what it is fed by. The HTTP parser, zlib, a
|
|
450
|
+
// socket's handle or the generator behind `Readable.from` holds the raw
|
|
451
|
+
// stream and emits on it, and Node tells a stream's listeners apart by
|
|
452
|
+
// identity: the async iterator's "readable" listener compares its `this`
|
|
453
|
+
// with the stream the iterator was made on. Made on the proxy by a traced
|
|
454
|
+
// call, it never woke up, so `for await` over an injected request body
|
|
455
|
+
// hung - and threw "callback is not a function" outside any request,
|
|
456
|
+
// ending the process, once the client closed its socket.
|
|
457
|
+
const requiresRawReceiver = hasPrivateMembers || slotBacked || nodeStream;
|
|
332
458
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
333
459
|
const methodRefsCache = new WeakMap();
|
|
334
460
|
// Functions read off the instance that are handed out as they are:
|
|
335
461
|
// constructors and callable objects.
|
|
336
462
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
337
463
|
const passedThrough = new WeakSet();
|
|
338
|
-
|
|
464
|
+
// And the instance's own functions, see the `get` trap.
|
|
465
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
466
|
+
const ownFunctions = new WeakSet();
|
|
467
|
+
const ownFunctionsPassThrough = classInstance && !requiresRawReceiver;
|
|
468
|
+
const proxy = new Proxy(instance, {
|
|
339
469
|
// Runs for every property read through the proxy - each `this.field`
|
|
340
470
|
// and `this.dependency.method` inside a traced call - so the common
|
|
341
|
-
// answers come first: a
|
|
342
|
-
// wrapped.
|
|
471
|
+
// answers come first: a read by something other than the proxy, a value
|
|
472
|
+
// that is no method, then a method already wrapped.
|
|
343
473
|
get: (target, prop, receiver) => {
|
|
474
|
+
// An object that inherits from the proxy - what a traced method
|
|
475
|
+
// derives from `this` with `Object.create(this)`, as pino's
|
|
476
|
+
// `logger.child()` does - reads its property as it would without the
|
|
477
|
+
// proxy, accessors against itself, and calls its methods with itself
|
|
478
|
+
// as `this`. Wrapped and cached, the first such object to read a
|
|
479
|
+
// method was the `this` of every later call of it, from any request.
|
|
480
|
+
if (receiver !== proxy) {
|
|
481
|
+
return Reflect.get(target, prop, receiver);
|
|
482
|
+
}
|
|
344
483
|
const attributeValue = Reflect.get(target, prop);
|
|
345
484
|
if (typeof attributeValue !== "function" || prop === "constructor") {
|
|
346
485
|
return attributeValue;
|
|
347
486
|
}
|
|
487
|
+
// A member the instance can never change is handed out as it is and
|
|
488
|
+
// runs untraced: the engine accepts no other answer. Asked ahead of
|
|
489
|
+
// both caches, which go by the function: the same one may also sit
|
|
490
|
+
// under a writable key, and an instance can be frozen after its
|
|
491
|
+
// method was wrapped.
|
|
492
|
+
const own = Reflect.getOwnPropertyDescriptor(target, prop);
|
|
493
|
+
if (isReadOnlyDataProperty(own)) {
|
|
494
|
+
return attributeValue;
|
|
495
|
+
}
|
|
348
496
|
// When "originalMethod" is already proxied, return the cached version
|
|
349
497
|
const cached = methodRefsCache.get(attributeValue);
|
|
350
498
|
if (cached) {
|
|
@@ -353,6 +501,31 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
353
501
|
if (passedThrough.has(attributeValue)) {
|
|
354
502
|
return attributeValue;
|
|
355
503
|
}
|
|
504
|
+
// A function a class instance holds itself - an arrow-function field,
|
|
505
|
+
// a method its constructor bound, a callback it stored - was made with
|
|
506
|
+
// the raw instance in hand, and the class compares it by identity
|
|
507
|
+
// from code that never reads it through the proxy. mssql's
|
|
508
|
+
// `Transaction` adds `this._abort` to the pooled connection in
|
|
509
|
+
// `_begin` and removes it inside `_abort`, an arrow function whose
|
|
510
|
+
// `this` is the raw instance: wrapped, the listener stayed, and the
|
|
511
|
+
// next rollback on that connection ended the process. Such a function
|
|
512
|
+
// is handed out as it is, and gets no span of its own.
|
|
513
|
+
//
|
|
514
|
+
// Remembered apart from `passedThrough` and honoured only for a read
|
|
515
|
+
// of an own property, so the same function read under a prototype
|
|
516
|
+
// name is still a method. Not for a class whose methods run against
|
|
517
|
+
// the raw instance: those never read their functions through here,
|
|
518
|
+
// and a plain function it holds relies on the wrapper for that
|
|
519
|
+
// receiver.
|
|
520
|
+
if (own !== undefined && ownFunctionsPassThrough) {
|
|
521
|
+
if (ownFunctions.has(attributeValue)) {
|
|
522
|
+
return attributeValue;
|
|
523
|
+
}
|
|
524
|
+
if (isInstanceOwnFunction(target, prop, attributeValue)) {
|
|
525
|
+
ownFunctions.add(attributeValue);
|
|
526
|
+
return attributeValue;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
356
529
|
const shouldProxy =
|
|
357
530
|
// A constructor held in a field - pg-pool's `this.Promise` - is
|
|
358
531
|
// invoked with `new` and read for statics (`this.Promise.reject`);
|
|
@@ -385,18 +558,19 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
385
558
|
const originalMethod = requiresRawReceiver
|
|
386
559
|
? attributeValue
|
|
387
560
|
: Reflect.get(target, prop, receiver);
|
|
388
|
-
const tracedReceiver = requiresRawReceiver ? target :
|
|
561
|
+
const tracedReceiver = requiresRawReceiver ? target : proxy;
|
|
389
562
|
// The wrapper is made once per method of this instance and cached
|
|
390
563
|
// below, so a flag of its own guards exactly that callable - checked
|
|
391
564
|
// and flipped on every traced call, where a lookup keyed by instance
|
|
392
565
|
// and name used to be.
|
|
393
566
|
let active = false;
|
|
394
|
-
const
|
|
567
|
+
const tracedFn = createTracedWrapper({
|
|
395
568
|
className,
|
|
396
569
|
methodName,
|
|
397
570
|
spanId: generateSpanId(target, methodName),
|
|
398
571
|
isActive: () => active,
|
|
399
572
|
setActive: (value) => (active = value),
|
|
573
|
+
isAsync: types.isAsyncFunction(originalMethod),
|
|
400
574
|
// Traced calls run against the proxy so that a method calling into
|
|
401
575
|
// itself (`this.other()`) is instrumented as a nested step - except
|
|
402
576
|
// for private-member classes, whose brand checks only the raw
|
|
@@ -404,32 +578,55 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
404
578
|
call: named(frameName, (_thisArg, args) => originalMethod.apply(tracedReceiver, args)),
|
|
405
579
|
callUntraced: named(frameName, (_thisArg, args) => originalMethod.apply(target, args)),
|
|
406
580
|
});
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
//
|
|
412
|
-
|
|
413
|
-
//
|
|
414
|
-
//
|
|
415
|
-
//
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
581
|
+
// A method read off the provider is not always called on it. ioredis
|
|
582
|
+
// copies a client's custom commands onto every `Pipeline` it makes
|
|
583
|
+
// (`this[name] = redis[name]`), and each queues on the `this` it is
|
|
584
|
+
// called with: run against the client regardless, a command written
|
|
585
|
+
// into `multi()` was sent at once, outside the transaction. Called on
|
|
586
|
+
// another object, the method runs as it would without the proxy -
|
|
587
|
+
// against that object, untraced. Called on the provider, or on
|
|
588
|
+
// nothing, it is traced against the receiver chosen above.
|
|
589
|
+
//
|
|
590
|
+
// Bound, so V8 prints the trap's frame as top-level, under its name:
|
|
591
|
+
// called as the handler's `apply`, it would carry "[as apply]".
|
|
592
|
+
const apply = named(frameName, (_target, thisArg, args) => thisArg === proxy ||
|
|
593
|
+
thisArg === target ||
|
|
594
|
+
thisArg === undefined ||
|
|
595
|
+
thisArg === null
|
|
596
|
+
? tracedFn(thisArg, args)
|
|
597
|
+
: Reflect.apply(originalMethod, thisArg, args)).bind(undefined);
|
|
598
|
+
// A proxy of the method itself, so `name`, `length` and everything
|
|
599
|
+
// else read off it are the original's, to anything reflecting over it
|
|
600
|
+
// (DI, decorators, arity checks). Metadata is held by identity, so it
|
|
601
|
+
// is copied onto the proxy.
|
|
602
|
+
const wrapped = new Proxy(originalMethod, { apply });
|
|
424
603
|
const metadataKeys = Reflect.getMetadataKeys(originalMethod);
|
|
425
604
|
for (const key of metadataKeys) {
|
|
426
605
|
const metadata = Reflect.getMetadata(key, originalMethod);
|
|
427
|
-
Reflect.defineMetadata(key, metadata,
|
|
606
|
+
Reflect.defineMetadata(key, metadata, wrapped);
|
|
428
607
|
}
|
|
429
|
-
methodRefsCache.set(attributeValue,
|
|
430
|
-
return
|
|
608
|
+
methodRefsCache.set(attributeValue, wrapped);
|
|
609
|
+
return wrapped;
|
|
431
610
|
},
|
|
611
|
+
// An assignment made on the provider runs a setter against the raw
|
|
612
|
+
// instance, as a read runs a getter: one that writes `this.#x` threw
|
|
613
|
+
// "Cannot write private member" with the proxy as `this`. Only for the
|
|
614
|
+
// classes whose methods get the raw instance; an object that inherits
|
|
615
|
+
// from the proxy assigns to itself, as it would without it.
|
|
616
|
+
...(requiresRawReceiver && {
|
|
617
|
+
set: (target, prop, value, receiver) => receiver === proxy
|
|
618
|
+
? Reflect.set(target, prop, value)
|
|
619
|
+
: Reflect.set(target, prop, value, receiver),
|
|
620
|
+
}),
|
|
432
621
|
});
|
|
622
|
+
// The raw instance only reaches the methods read through the proxy. A
|
|
623
|
+
// caller that reads one off the class prototype and applies it to the
|
|
624
|
+
// proxy - as `@nestjs/graphql` does with a resolver's - has to be handed
|
|
625
|
+
// the instance, and finds it through `rawReceiverOf`.
|
|
626
|
+
if (requiresRawReceiver) {
|
|
627
|
+
registerRawReceiver(proxy, instance);
|
|
628
|
+
}
|
|
629
|
+
return proxy;
|
|
433
630
|
};
|
|
434
631
|
return (instance) => {
|
|
435
632
|
if (typeof instance === "function") {
|
|
@@ -442,17 +639,80 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
442
639
|
};
|
|
443
640
|
}
|
|
444
641
|
/**
|
|
445
|
-
* Whether a
|
|
446
|
-
*
|
|
447
|
-
*
|
|
642
|
+
* Whether a property is an own data property that is neither writable nor
|
|
643
|
+
* configurable: what `Object.freeze` makes of every member, and what
|
|
644
|
+
* `Object.defineProperty(obj, key, { value })` creates by default.
|
|
645
|
+
*
|
|
646
|
+
* A proxy's `get` trap has to answer a read of such a property with the
|
|
647
|
+
* target's own value. The engine compares the two after the trap returns and
|
|
648
|
+
* throws a TypeError when they differ ("'get' on proxy: property ... is a
|
|
649
|
+
* read-only and non-configurable data property on the proxy target but the
|
|
650
|
+
* proxy did not return its actual value"), so a traced wrapper in its place
|
|
651
|
+
* failed the read itself, before anything was called.
|
|
448
652
|
*
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
* a context, which every traced call runs in.
|
|
653
|
+
* A method found on the prototype has no own descriptor, so a class instance
|
|
654
|
+
* keeps its spans.
|
|
452
655
|
*/
|
|
453
|
-
function
|
|
454
|
-
return (
|
|
455
|
-
|
|
656
|
+
function isReadOnlyDataProperty(own) {
|
|
657
|
+
return (own !== undefined && own.configurable === false && own.writable === false);
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Whether an instance was built by a class, or anything else that hands it a
|
|
661
|
+
* prototype of its own - as opposed to an object literal, a null-prototype
|
|
662
|
+
* object, an ES module namespace or an array, whose own functions are the
|
|
663
|
+
* methods a caller means to trace, and which have no constructor that could
|
|
664
|
+
* have kept a reference to one of them.
|
|
665
|
+
*/
|
|
666
|
+
function isClassInstance(instance) {
|
|
667
|
+
const proto = Object.getPrototypeOf(instance);
|
|
668
|
+
return (proto !== null && proto !== Object.prototype && !Array.isArray(instance));
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* Whether a function an instance holds as an own property is the instance's
|
|
672
|
+
* own, rather than a method of its class held a second time.
|
|
673
|
+
*
|
|
674
|
+
* Not when the prototype chain holds that very function, under any name
|
|
675
|
+
* (`this.build = this.render`): it is a method, and one wrapper stands in for
|
|
676
|
+
* it whichever name it is read by. Nor when the class has a method of the
|
|
677
|
+
* same name that carries metadata (`this.create = this.create.bind(this)` in
|
|
678
|
+
* a controller): Nest reads such a handler off the instance, and unwrapped, a
|
|
679
|
+
* request it served without calling anything else had no span, and was
|
|
680
|
+
* dropped for it.
|
|
681
|
+
*
|
|
682
|
+
* Read as descriptors, so no getter runs; asked once per function, since the
|
|
683
|
+
* answer is kept.
|
|
684
|
+
*/
|
|
685
|
+
function isInstanceOwnFunction(instance, prop, fn) {
|
|
686
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
687
|
+
const sameName = Reflect.getOwnPropertyDescriptor(proto, prop)?.value;
|
|
688
|
+
if (typeof sameName === "function" &&
|
|
689
|
+
Reflect.getMetadataKeys(sameName).length > 0) {
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
for (const key of Reflect.ownKeys(proto)) {
|
|
693
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(proto, key);
|
|
694
|
+
if (descriptor?.value === fn ||
|
|
695
|
+
descriptor?.get === fn ||
|
|
696
|
+
descriptor?.set === fn) {
|
|
697
|
+
return false;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return true;
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Whether `promise.then` is the native method: no override on a subclass, no
|
|
705
|
+
* `then` of the promise's own. Calling the native one only registers the
|
|
706
|
+
* callbacks; calling anything else runs code the promise brought with it.
|
|
707
|
+
*/
|
|
708
|
+
function hasNativeThen(promise) {
|
|
709
|
+
try {
|
|
710
|
+
return promise.then === Promise.prototype.then;
|
|
711
|
+
}
|
|
712
|
+
catch {
|
|
713
|
+
// A `then` getter that throws: nothing to watch it by.
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
456
716
|
}
|
|
457
717
|
/** Runs span bookkeeping whose failure must not reach the caller. */
|
|
458
718
|
function ignoreFailure(fn) {
|
|
@@ -485,22 +745,54 @@ function named(name, fn) {
|
|
|
485
745
|
* Only the topmost match is rewritten. Every wrapper on the way out relabels
|
|
486
746
|
* its own frame, and inner calls unwind before outer ones, so two classes that
|
|
487
747
|
* happen to share a method name each end up with the right label.
|
|
748
|
+
*
|
|
749
|
+
* An error with a long `name` and `message` is left as it is - see
|
|
750
|
+
* `MAX_RELABELLED_HEADER_LENGTH`.
|
|
488
751
|
*/
|
|
489
752
|
function relabelProxyFrame(err, className, methodName) {
|
|
490
|
-
|
|
491
|
-
|
|
753
|
+
// The label is cosmetic, so nothing here may take the place of the error
|
|
754
|
+
// the method threw: a `stack` that is a getter can throw on being read, as
|
|
755
|
+
// a read-only one throws on being written.
|
|
756
|
+
try {
|
|
757
|
+
// Measured first: reading `stack` is what writes it out.
|
|
758
|
+
if (!(err instanceof Error) ||
|
|
759
|
+
stackHeaderLength(err) > MAX_RELABELLED_HEADER_LENGTH) {
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
// `async` prefixes the type name on frames resumed from an await. Spaces
|
|
763
|
+
// and tabs only after the newline, not `\s`: a newline matched there too,
|
|
764
|
+
// and a message of newlines then rescanned the run after each one.
|
|
765
|
+
const frame = new RegExp(`(\\n[ \\t]*at (?:async )?)Proxy\\.${escapeRegExp(methodName)}\\b`);
|
|
766
|
+
// Not `err.stack` read and assigned back: that read would fix the
|
|
767
|
+
// error's message in its stack, whatever a caller does to the message
|
|
768
|
+
// afterwards - see `readStack`.
|
|
769
|
+
rewriteStackFrames(err, (stack) => stack.replace(frame, `$1${className}.${methodName}`));
|
|
492
770
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
if (!frame.test(err.stack)) {
|
|
496
|
-
return;
|
|
771
|
+
catch {
|
|
772
|
+
// Left as it is.
|
|
497
773
|
}
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* The longest `name` plus `message` of an error whose stack is relabelled.
|
|
777
|
+
*
|
|
778
|
+
* V8 writes an error's stack out when it is first read, opening it with the
|
|
779
|
+
* two. Until then a message that quotes the request - `Unknown id ${id}` - is
|
|
780
|
+
* a reference to the text it quotes, however long, and the frames are held in
|
|
781
|
+
* a compact form. Searching the stack writes all of it out, and the copy stays
|
|
782
|
+
* on the error as long as anything holds it: one call per element of a
|
|
783
|
+
* client's array, each failing with a long quote, then held by
|
|
784
|
+
* `Promise.allSettled`, held a copy each. The label is cosmetic, so an error
|
|
785
|
+
* past this keeps `Proxy.` rather than cost that.
|
|
786
|
+
*/
|
|
787
|
+
const MAX_RELABELLED_HEADER_LENGTH = 1024;
|
|
788
|
+
function stackHeaderLength(err) {
|
|
498
789
|
try {
|
|
499
|
-
err.
|
|
790
|
+
return ((typeof err.name === "string" ? err.name.length : 0) +
|
|
791
|
+
(typeof err.message === "string" ? err.message.length : 0));
|
|
500
792
|
}
|
|
501
793
|
catch {
|
|
502
|
-
//
|
|
503
|
-
|
|
794
|
+
// A getter that throws; leave such an error alone.
|
|
795
|
+
return Infinity;
|
|
504
796
|
}
|
|
505
797
|
}
|
|
506
798
|
function escapeRegExp(value) {
|
|
@@ -558,6 +850,9 @@ function isCallableObject(fn) {
|
|
|
558
850
|
* `%TypedArray%.prototype` (reached via `Uint8Array`'s parent) covers every
|
|
559
851
|
* typed array - and, through it, Node's `Buffer`. `Array` is deliberately
|
|
560
852
|
* absent: its methods are generic and proxy-safe.
|
|
853
|
+
*
|
|
854
|
+
* The `Intl` services are read off the namespace instead of being spelled
|
|
855
|
+
* out, see `intlServicePrototypes()`.
|
|
561
856
|
*/
|
|
562
857
|
const SLOT_BACKED_PROTOTYPES = new Set([
|
|
563
858
|
Map.prototype,
|
|
@@ -575,7 +870,33 @@ const SLOT_BACKED_PROTOTYPES = new Set([
|
|
|
575
870
|
WeakRef.prototype,
|
|
576
871
|
FinalizationRegistry.prototype,
|
|
577
872
|
Object.getPrototypeOf(Uint8Array.prototype),
|
|
873
|
+
...intlServicePrototypes(),
|
|
578
874
|
]);
|
|
875
|
+
/**
|
|
876
|
+
* Prototypes of the `Intl` services (`NumberFormat`, `DateTimeFormat`,
|
|
877
|
+
* `Collator`, `PluralRules`, `Locale`, ...). Their methods, and the `format`
|
|
878
|
+
* and `compare` accessors that hand out a bound function, read
|
|
879
|
+
* `[[InitializedNumberFormat]]` and the like off their receiver, so a
|
|
880
|
+
* formatter registered as a provider threw "called on incompatible receiver"
|
|
881
|
+
* on its first use.
|
|
882
|
+
*
|
|
883
|
+
* Which services there are depends on the runtime - `DurationFormat` only
|
|
884
|
+
* arrived in Node 23, and a Node built without ICU has no `Intl` at all - so
|
|
885
|
+
* the constructors are collected from the namespace. Its plain functions
|
|
886
|
+
* (`getCanonicalLocales`, `supportedValuesOf`) have no `prototype`.
|
|
887
|
+
*/
|
|
888
|
+
function intlServicePrototypes() {
|
|
889
|
+
if (typeof Intl === "undefined") {
|
|
890
|
+
return [];
|
|
891
|
+
}
|
|
892
|
+
return Object.getOwnPropertyNames(Intl).flatMap((name) => {
|
|
893
|
+
const service = Reflect.get(Intl, name);
|
|
894
|
+
const prototype = typeof service === "function" ? service.prototype : undefined;
|
|
895
|
+
return typeof prototype === "object" && prototype !== null
|
|
896
|
+
? [prototype]
|
|
897
|
+
: [];
|
|
898
|
+
});
|
|
899
|
+
}
|
|
579
900
|
/**
|
|
580
901
|
* Whether the instance's prototype chain passes through a slot-backed
|
|
581
902
|
* built-in, meaning its (inherited) native methods would throw if invoked with
|
|
@@ -591,6 +912,26 @@ function isSlotBackedBuiltIn(instance) {
|
|
|
591
912
|
}
|
|
592
913
|
return false;
|
|
593
914
|
}
|
|
915
|
+
/**
|
|
916
|
+
* Whether an instance is a Node stream: a `Readable`, `Writable` or anything
|
|
917
|
+
* built on them (an `IncomingMessage`, a socket, a zlib or file stream), and
|
|
918
|
+
* the legacy `Stream` under an `OutgoingMessage`.
|
|
919
|
+
*
|
|
920
|
+
* Matched by shape as well as by class: `readable-stream` is the same code
|
|
921
|
+
* published to npm, its current major no longer extends Node's `Stream`, and
|
|
922
|
+
* its async iterator makes the same identity check. The state object is what
|
|
923
|
+
* every copy's methods reach for first.
|
|
924
|
+
*/
|
|
925
|
+
function isNodeStream(instance) {
|
|
926
|
+
if (instance instanceof Stream) {
|
|
927
|
+
return true;
|
|
928
|
+
}
|
|
929
|
+
const candidate = instance;
|
|
930
|
+
return ((typeof candidate._readableState === "object" &&
|
|
931
|
+
candidate._readableState !== null) ||
|
|
932
|
+
(typeof candidate._writableState === "object" &&
|
|
933
|
+
candidate._writableState !== null));
|
|
934
|
+
}
|
|
594
935
|
/**
|
|
595
936
|
* Whether a constructor is engine- or platform-provided rather than user
|
|
596
937
|
* code. A slot-backed instance whose entire chain is native (`new Map()`,
|
|
@@ -610,11 +951,26 @@ function isNativeFunction(fn) {
|
|
|
610
951
|
return true;
|
|
611
952
|
}
|
|
612
953
|
}
|
|
613
|
-
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
614
954
|
const privateMemberCache = new WeakMap();
|
|
615
955
|
/**
|
|
616
|
-
*
|
|
617
|
-
*
|
|
956
|
+
* What a compiler leaves of `#name` when the target is below ES2022: the
|
|
957
|
+
* member moves into a `WeakMap` or `WeakSet` keyed by the instance, and every
|
|
958
|
+
* access goes through a helper that checks its receiver against it. That is
|
|
959
|
+
* the same brand check, with no `#` left in the class source.
|
|
960
|
+
*
|
|
961
|
+
* Covers the helpers of tsc and tslib (`__classPrivateFieldGet`), Babel and
|
|
962
|
+
* oxc (`_classPrivateFieldGet2`, `_assertClassBrand`), SWC
|
|
963
|
+
* (`_class_private_field_get`) and esbuild (`__privateGet`). Matched anywhere
|
|
964
|
+
* in a name, since an imported helper is reached through a namespace or under
|
|
965
|
+
* a numbered alias (`tslib_1.__classPrivateFieldGet`). Not the loose-mode
|
|
966
|
+
* helpers of Babel and SWC (`_classPrivateFieldLooseBase`): loose mode keeps
|
|
967
|
+
* the member on the instance under a string key, which reads through the
|
|
968
|
+
* proxy like any other property.
|
|
969
|
+
*/
|
|
970
|
+
const COMPILED_PRIVATE_MEMBER = /classPrivate(?:Field|Method|Getter|Setter)(?!Loose)|assertClassBrand|class_private_(?:field|method)_(?!loose)|__private(?:Get|Set|Add|Method|In|Wrapper)\b/;
|
|
971
|
+
/**
|
|
972
|
+
* Whether any class in the instance's prototype chain declares private
|
|
973
|
+
* members (`#field`, `#method()`), native or compiled away.
|
|
618
974
|
*
|
|
619
975
|
* Detection reads the class source: private members can only be touched from
|
|
620
976
|
* inside the lexical class body, so a class whose text contains no `#name`
|
|
@@ -622,34 +978,66 @@ const privateMemberCache = new WeakMap();
|
|
|
622
978
|
* false-positive, which merely selects the raw-instance receiver - every call
|
|
623
979
|
* still works, only nested self-call spans are lost - so the cheap test is
|
|
624
980
|
* safe to lean on.
|
|
981
|
+
*
|
|
982
|
+
* A compiled class is told by its helper calls, under the same trade-off:
|
|
983
|
+
* they stay in the class body, where the `#name` was. A `WeakMap` keyed by
|
|
984
|
+
* `this` that an application writes by hand leaves no such trace, and is not
|
|
985
|
+
* covered.
|
|
625
986
|
*/
|
|
626
|
-
function
|
|
987
|
+
function usesPrivateMembers(instance) {
|
|
627
988
|
let proto = Object.getPrototypeOf(instance);
|
|
628
989
|
while (proto && proto !== Object.prototype) {
|
|
629
|
-
|
|
630
|
-
if (
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
if (hasPrivate) {
|
|
637
|
-
return true;
|
|
638
|
-
}
|
|
990
|
+
let hasPrivate = privateMemberCache.get(proto);
|
|
991
|
+
if (hasPrivate === undefined) {
|
|
992
|
+
hasPrivate = prototypeUsesPrivateMembers(proto);
|
|
993
|
+
privateMemberCache.set(proto, hasPrivate);
|
|
994
|
+
}
|
|
995
|
+
if (hasPrivate) {
|
|
996
|
+
return true;
|
|
639
997
|
}
|
|
640
998
|
proto = Object.getPrototypeOf(proto);
|
|
641
999
|
}
|
|
642
1000
|
return false;
|
|
643
1001
|
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Whether the class a prototype belongs to declares native private members.
|
|
1004
|
+
*
|
|
1005
|
+
* `constructor` leads to that class only while it is the one the class
|
|
1006
|
+
* definition put there, which is when its `prototype` is this very object. A
|
|
1007
|
+
* helper that mixes classes in by copying the own properties of their
|
|
1008
|
+
* prototypes - the TypeScript handbook's `applyMixins`, ioredis's
|
|
1009
|
+
* `applyMixin` - copies `constructor` along, and the receiving prototype then
|
|
1010
|
+
* names the last class mixed in, whose source says nothing about the one
|
|
1011
|
+
* being inspected. That one's own body can no longer be reached from here,
|
|
1012
|
+
* but its methods and accessors can: each one's text is a part of the class
|
|
1013
|
+
* body, and a brand check made on `this` shows in it.
|
|
1014
|
+
*/
|
|
1015
|
+
function prototypeUsesPrivateMembers(proto) {
|
|
1016
|
+
const ctor = Object.hasOwn(proto, "constructor")
|
|
1017
|
+
? Object.getOwnPropertyDescriptor(proto, "constructor")?.value
|
|
1018
|
+
: undefined;
|
|
1019
|
+
if (typeof ctor === "function" && ctor.prototype === proto) {
|
|
1020
|
+
return ctor !== Object && declaresPrivateMembers(ctor);
|
|
1021
|
+
}
|
|
1022
|
+
return Reflect.ownKeys(proto).some((key) => {
|
|
1023
|
+
if (key === "constructor") {
|
|
1024
|
+
return false;
|
|
1025
|
+
}
|
|
1026
|
+
// Read as descriptors, so that no getter runs.
|
|
1027
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(proto, key);
|
|
1028
|
+
return [descriptor?.value, descriptor?.get, descriptor?.set].some((member) => typeof member === "function" && declaresPrivateMembers(member));
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
644
1031
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
645
|
-
function declaresPrivateMembers(
|
|
1032
|
+
function declaresPrivateMembers(fn) {
|
|
646
1033
|
try {
|
|
1034
|
+
const source = Function.prototype.toString.call(fn);
|
|
647
1035
|
// `#` starting a private name is never preceded by an identifier
|
|
648
1036
|
// character; `obj.#x` and `#x in obj` and declarations all match.
|
|
649
|
-
return /(^|[^\w$])#[\w$]/.test(
|
|
1037
|
+
return (/(^|[^\w$])#[\w$]/.test(source) || COMPILED_PRIVATE_MEMBER.test(source));
|
|
650
1038
|
}
|
|
651
1039
|
catch {
|
|
652
|
-
// A
|
|
1040
|
+
// A function whose source is unavailable (bound functions, some
|
|
653
1041
|
// natives) cannot be a class body with private members.
|
|
654
1042
|
return false;
|
|
655
1043
|
}
|