@nestjs/observe 0.3.26 → 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.
Files changed (59) hide show
  1. package/README.md +38 -2
  2. package/dist/agent/observe-agent.shared-buffer.js +5 -0
  3. package/dist/agent/telemetry-wire-contract.js +3 -3
  4. package/dist/cli/link.js +24 -2
  5. package/dist/cli/package-manager.d.ts +6 -0
  6. package/dist/cli/package-manager.js +60 -3
  7. package/dist/cli/project-files.d.ts +25 -5
  8. package/dist/cli/project-files.js +98 -15
  9. package/dist/custom-metrics/summary.js +17 -10
  10. package/dist/instrument/create-instance-decorator.instrument.js +364 -38
  11. package/dist/instrument/raw-receiver.d.ts +6 -0
  12. package/dist/instrument/raw-receiver.js +32 -0
  13. package/dist/interfaces/observe-options.interface.d.ts +14 -5
  14. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  15. package/dist/otlp/otlp-span.mapper.js +19 -1
  16. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  17. package/dist/otlp/otlp-trace-exporter.service.js +232 -38
  18. package/dist/outgoing/http.integration.js +36 -11
  19. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  20. package/dist/outgoing/mongodb.integration.js +93 -18
  21. package/dist/outgoing/mssql.integration.js +9 -4
  22. package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
  23. package/dist/outgoing/sql-statement.util.js +36 -10
  24. package/dist/protocols/bull-observe-agent.service.js +21 -0
  25. package/dist/protocols/deferred-trace-completion.d.ts +8 -2
  26. package/dist/protocols/deferred-trace-completion.js +40 -3
  27. package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
  28. package/dist/protocols/graphql-observe-agent.service.js +188 -14
  29. package/dist/protocols/graphql-operation-parser.js +45 -14
  30. package/dist/protocols/http-observe-agent.service.d.ts +14 -7
  31. package/dist/protocols/http-observe-agent.service.js +57 -14
  32. package/dist/protocols/job-trace-runner.d.ts +7 -0
  33. package/dist/protocols/job-trace-runner.js +72 -8
  34. package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
  35. package/dist/protocols/rpc-observe-agent.service.js +146 -10
  36. package/dist/protocols/ws-observe-agent.service.js +1 -1
  37. package/dist/services/logger-patcher.service.js +13 -3
  38. package/dist/services/operation-trace.registry.d.ts +13 -0
  39. package/dist/services/operation-trace.registry.js +195 -65
  40. package/dist/services/stdout-forwarder.service.js +22 -2
  41. package/dist/services/tracer.service.d.ts +19 -14
  42. package/dist/services/tracer.service.js +57 -34
  43. package/dist/utils/capture-request.util.js +36 -8
  44. package/dist/utils/context-accessor.util.d.ts +16 -0
  45. package/dist/utils/context-accessor.util.js +28 -0
  46. package/dist/utils/default-trace-id-generator.util.js +5 -7
  47. package/dist/utils/error-stack.util.d.ts +13 -0
  48. package/dist/utils/error-stack.util.js +166 -0
  49. package/dist/utils/log-line.parser.d.ts +8 -0
  50. package/dist/utils/log-line.parser.js +13 -4
  51. package/dist/utils/log-redactor.js +184 -10
  52. package/dist/utils/redact-url-query.d.ts +16 -5
  53. package/dist/utils/redact-url-query.js +20 -7
  54. package/dist/utils/source-context.util.d.ts +6 -0
  55. package/dist/utils/source-context.util.js +68 -33
  56. package/dist/utils/source-map-resolver.util.js +25 -4
  57. package/dist/utils/store-copy.util.d.ts +10 -0
  58. package/dist/utils/store-copy.util.js +43 -0
  59. package/package.json +1 -1
@@ -1,6 +1,11 @@
1
1
  import { Reflector } from "@nestjs/core";
2
+ import { X509Certificate } from "node:crypto";
3
+ import { Stream } from "node:stream";
2
4
  import { types } from "node:util";
3
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";
4
9
  /**
5
10
  * Stand-in "class name" for instrumented standalone functions. Unlike methods,
6
11
  * they have no enclosing class to borrow a name from, so every span they emit
@@ -74,6 +79,62 @@ function isMongoDriverHandle(instance) {
74
79
  }
75
80
  return false;
76
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") {
116
+ return false;
117
+ }
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);
137
+ }
77
138
  /**
78
139
  * Library classes traced only in part, each with a method only it has, which
79
140
  * tells it from an application's own class of the same name - `ValidationPipe`
@@ -118,13 +179,26 @@ const PARTLY_TRACED_CLASSES = new Map([
118
179
  },
119
180
  ],
120
181
  ]);
121
- /** The methods a prototype's class keeps traced, if it is one of those. */
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
+ */
122
192
  function partlyTracedMethodsOf(proto) {
123
193
  const candidate = proto;
124
194
  const entry = PARTLY_TRACED_CLASSES.get(candidate.constructor?.name ?? "");
125
- return entry !== undefined && typeof candidate[entry.marker] === "function"
126
- ? entry.traced
127
- : null;
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;
128
202
  }
129
203
  /** Whether an instance is one of those classes, or extends one. */
130
204
  function extendsPartlyTracedClass(instance) {
@@ -189,7 +263,13 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
189
263
  const callTraced = named(frameName, (thisArg, args, requestId, stepId) => {
190
264
  try {
191
265
  const result = call(thisArg, args);
192
- if (result instanceof Promise) {
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)) {
193
273
  // Closing the span is a side effect: a registry failure must
194
274
  // leave the caller with the value or rejection it would have
195
275
  // seen without the span.
@@ -216,8 +296,8 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
216
296
  // rejected where those handlers do not reach: dropped by the
217
297
  // caller, it was an unhandled rejection, and under Node's default
218
298
  // it ended a process that handled the failure. Handed back, it
219
- // also keeps what it carries beyond its value (`json()` on a
220
- // `got` request, `kill()` on an `execa` child, a subclass).
299
+ // also keeps what it carries beyond its value (`kill()` on an
300
+ // `execa` child, a subclass that keeps the native `then`).
221
301
  // Watching marks it handled, so a rejection nobody handles no
222
302
  // longer raises `unhandledRejection`; the span still records it.
223
303
  result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
@@ -264,9 +344,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
264
344
  }
265
345
  // Everything the caller's context holds, with this span as the caller
266
346
  // of whatever it calls. A copy, so the caller's context still names
267
- // the caller once this call returns.
268
- const spanStore = new Map(store);
269
- spanStore.set(CALLER_METADATA_KEY, newStepId);
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]);
270
351
  return als.run(spanStore, callTraced, thisArg, args, requestId, newStepId);
271
352
  }
272
353
  finally {
@@ -324,16 +405,29 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
324
405
  let slotBacked;
325
406
  let bareBuiltIn;
326
407
  let partlyTraced;
408
+ let nodeStream;
409
+ let classInstance;
327
410
  try {
328
411
  // Inspected here, inside the guard, for the same reason as the checks
329
412
  // below: reading a provider's constructor can run a trap that throws.
330
- if (isFrameworkNoise(instance)) {
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)) {
331
423
  return instance;
332
424
  }
333
- hasPrivateMembers = usesNativePrivateMembers(instance);
425
+ hasPrivateMembers = usesPrivateMembers(instance);
334
426
  slotBacked = isSlotBackedBuiltIn(instance);
335
427
  bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
336
428
  partlyTraced = extendsPartlyTracedClass(instance);
429
+ nodeStream = isNodeStream(instance);
430
+ classInstance = isClassInstance(instance);
337
431
  }
338
432
  catch {
339
433
  // Reading the prototype ran a trap that threw (nestjs-cls proxy
@@ -351,13 +445,26 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
351
445
  }
352
446
  // Slot-backed subclasses share the private-member trade-off: methods run
353
447
  // against the raw instance so the natives they inherit keep working.
354
- const requiresRawReceiver = hasPrivateMembers || slotBacked;
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;
355
458
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
356
459
  const methodRefsCache = new WeakMap();
357
460
  // Functions read off the instance that are handed out as they are:
358
461
  // constructors and callable objects.
359
462
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
360
463
  const passedThrough = new WeakSet();
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;
361
468
  const proxy = new Proxy(instance, {
362
469
  // Runs for every property read through the proxy - each `this.field`
363
470
  // and `this.dependency.method` inside a traced call - so the common
@@ -377,6 +484,15 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
377
484
  if (typeof attributeValue !== "function" || prop === "constructor") {
378
485
  return attributeValue;
379
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
+ }
380
496
  // When "originalMethod" is already proxied, return the cached version
381
497
  const cached = methodRefsCache.get(attributeValue);
382
498
  if (cached) {
@@ -385,6 +501,31 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
385
501
  if (passedThrough.has(attributeValue)) {
386
502
  return attributeValue;
387
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
+ }
388
529
  const shouldProxy =
389
530
  // A constructor held in a field - pg-pool's `this.Promise` - is
390
531
  // invoked with `new` and read for statics (`this.Promise.reject`);
@@ -467,7 +608,24 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
467
608
  methodRefsCache.set(attributeValue, wrapped);
468
609
  return wrapped;
469
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
+ }),
470
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
+ }
471
629
  return proxy;
472
630
  };
473
631
  return (instance) => {
@@ -480,6 +638,82 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
480
638
  return instance;
481
639
  };
482
640
  }
641
+ /**
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.
652
+ *
653
+ * A method found on the prototype has no own descriptor, so a class instance
654
+ * keeps its spans.
655
+ */
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
+ }
716
+ }
483
717
  /** Runs span bookkeeping whose failure must not reach the caller. */
484
718
  function ignoreFailure(fn) {
485
719
  try {
@@ -525,18 +759,14 @@ function relabelProxyFrame(err, className, methodName) {
525
759
  stackHeaderLength(err) > MAX_RELABELLED_HEADER_LENGTH) {
526
760
  return;
527
761
  }
528
- const stack = err.stack;
529
- if (typeof stack !== "string") {
530
- return;
531
- }
532
762
  // `async` prefixes the type name on frames resumed from an await. Spaces
533
763
  // and tabs only after the newline, not `\s`: a newline matched there too,
534
764
  // and a message of newlines then rescanned the run after each one.
535
765
  const frame = new RegExp(`(\\n[ \\t]*at (?:async )?)Proxy\\.${escapeRegExp(methodName)}\\b`);
536
- if (!frame.test(stack)) {
537
- return;
538
- }
539
- err.stack = stack.replace(frame, `$1${className}.${methodName}`);
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}`));
540
770
  }
541
771
  catch {
542
772
  // Left as it is.
@@ -620,6 +850,9 @@ function isCallableObject(fn) {
620
850
  * `%TypedArray%.prototype` (reached via `Uint8Array`'s parent) covers every
621
851
  * typed array - and, through it, Node's `Buffer`. `Array` is deliberately
622
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()`.
623
856
  */
624
857
  const SLOT_BACKED_PROTOTYPES = new Set([
625
858
  Map.prototype,
@@ -637,7 +870,33 @@ const SLOT_BACKED_PROTOTYPES = new Set([
637
870
  WeakRef.prototype,
638
871
  FinalizationRegistry.prototype,
639
872
  Object.getPrototypeOf(Uint8Array.prototype),
873
+ ...intlServicePrototypes(),
640
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
+ }
641
900
  /**
642
901
  * Whether the instance's prototype chain passes through a slot-backed
643
902
  * built-in, meaning its (inherited) native methods would throw if invoked with
@@ -653,6 +912,26 @@ function isSlotBackedBuiltIn(instance) {
653
912
  }
654
913
  return false;
655
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
+ }
656
935
  /**
657
936
  * Whether a constructor is engine- or platform-provided rather than user
658
937
  * code. A slot-backed instance whose entire chain is native (`new Map()`,
@@ -672,11 +951,26 @@ function isNativeFunction(fn) {
672
951
  return true;
673
952
  }
674
953
  }
675
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
676
954
  const privateMemberCache = new WeakMap();
677
955
  /**
678
- * Whether any class in the instance's prototype chain declares native private
679
- * members (`#field`, `#method()`).
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.
680
974
  *
681
975
  * Detection reads the class source: private members can only be touched from
682
976
  * inside the lexical class body, so a class whose text contains no `#name`
@@ -684,34 +978,66 @@ const privateMemberCache = new WeakMap();
684
978
  * false-positive, which merely selects the raw-instance receiver - every call
685
979
  * still works, only nested self-call spans are lost - so the cheap test is
686
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.
687
986
  */
688
- function usesNativePrivateMembers(instance) {
987
+ function usesPrivateMembers(instance) {
689
988
  let proto = Object.getPrototypeOf(instance);
690
989
  while (proto && proto !== Object.prototype) {
691
- const ctor = proto.constructor;
692
- if (typeof ctor === "function" && ctor !== Object) {
693
- let hasPrivate = privateMemberCache.get(ctor);
694
- if (hasPrivate === undefined) {
695
- hasPrivate = declaresPrivateMembers(ctor);
696
- privateMemberCache.set(ctor, hasPrivate);
697
- }
698
- if (hasPrivate) {
699
- return true;
700
- }
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;
701
997
  }
702
998
  proto = Object.getPrototypeOf(proto);
703
999
  }
704
1000
  return false;
705
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
+ }
706
1031
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
707
- function declaresPrivateMembers(ctor) {
1032
+ function declaresPrivateMembers(fn) {
708
1033
  try {
1034
+ const source = Function.prototype.toString.call(fn);
709
1035
  // `#` starting a private name is never preceded by an identifier
710
1036
  // character; `obj.#x` and `#x in obj` and declarations all match.
711
- return /(^|[^\w$])#[\w$]/.test(Function.prototype.toString.call(ctor));
1037
+ return (/(^|[^\w$])#[\w$]/.test(source) || COMPILED_PRIVATE_MEMBER.test(source));
712
1038
  }
713
1039
  catch {
714
- // A constructor whose source is unavailable (bound functions, some
1040
+ // A function whose source is unavailable (bound functions, some
715
1041
  // natives) cannot be a class body with private members.
716
1042
  return false;
717
1043
  }
@@ -0,0 +1,6 @@
1
+ export declare function registerRawReceiver(proxy: object, instance: object): void;
2
+ /**
3
+ * The instance a provider's prototype methods have to be applied to, when
4
+ * that is not the provider itself - `undefined` for anything else.
5
+ */
6
+ export declare function rawReceiverOf(provider: object): object | undefined;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The instance behind each proxy the instance decorator hands out for a class
3
+ * whose methods only the instance itself can be the receiver of: one with
4
+ * private members, or one built on a slot-backed built-in.
5
+ *
6
+ * The proxy runs every method read through it against that instance. A
7
+ * method read anywhere else - off the class prototype - and applied to the
8
+ * proxy gets no such help, and throws on its first `this.#x`. Whoever has to
9
+ * apply one that way asks here for the receiver to use instead.
10
+ *
11
+ * Kept out of the decorator's module, which the package exports in full: the
12
+ * instance behind a proxy is the agent's to hand over, not an application's
13
+ * to look up. Module-level and weak, so a proxy names its instance for as
14
+ * long as the two live, whichever agent made it.
15
+ */
16
+ const rawReceivers = new WeakMap();
17
+ export function registerRawReceiver(proxy, instance) {
18
+ rawReceivers.set(proxy, instance);
19
+ }
20
+ /**
21
+ * The instance a provider's prototype methods have to be applied to, when
22
+ * that is not the provider itself - `undefined` for anything else.
23
+ */
24
+ export function rawReceiverOf(provider) {
25
+ let receiver = rawReceivers.get(provider);
26
+ // A provider handed out a second time (`useExisting`, a factory returning
27
+ // another provider) is a proxy of the first proxy.
28
+ while (receiver !== undefined && rawReceivers.has(receiver)) {
29
+ receiver = rawReceivers.get(receiver);
30
+ }
31
+ return receiver;
32
+ }
@@ -16,7 +16,9 @@ export interface RedactionOptions {
16
16
  * knows about - internal token prefixes, customer identifiers, and so on.
17
17
  *
18
18
  * Patterns are applied with the global flag whether or not you set it, so a
19
- * pattern cannot silently mask just the first occurrence in a line.
19
+ * pattern cannot silently mask just the first occurrence in a line. Each is
20
+ * applied as a copy, so the `lastIndex` of a pattern your own code steps
21
+ * through with `exec()` is never moved.
20
22
  */
21
23
  patterns?: RegExp[];
22
24
  /**
@@ -38,7 +40,8 @@ export interface RedactionOptions {
38
40
  replacement?: string;
39
41
  /**
40
42
  * Whether to apply the built-in patterns - bearer tokens, JWTs, AWS key ids,
41
- * PEM private keys, `key=value` secrets and Luhn-valid card numbers.
43
+ * PEM private keys, `key=value` secrets, the password in a URL
44
+ * (`scheme://user:password@host`) and Luhn-valid card numbers.
42
45
  *
43
46
  * Disable only if you are replacing them wholesale with `patterns`; there is
44
47
  * no supported configuration in which forwarding logs unredacted is a good
@@ -51,7 +54,9 @@ export interface CreateObserveModuleOptions {
51
54
  /**
52
55
  * The trace ID key used to identify the trace in the context.
53
56
  * This key is used to store the trace ID in the context for later retrieval.
54
- * If not provided, the default key 'traceId' will be used.
57
+ * If not provided, the default key 'traceId' will be used. An attribute of
58
+ * the same name returned by a `setAttributes` callback is ignored, with a
59
+ * warning, so a sender cannot choose the trace id.
55
60
  * @default 'traceId'
56
61
  */
57
62
  traceIdKey?: string;
@@ -576,7 +581,10 @@ export interface ObserveOptions {
576
581
  *
577
582
  * Matching on a field name skips the whole operation the field leads, not
578
583
  * just that field: an operation is measured end to end, so it is traced or
579
- * it is not.
584
+ * it is not. Over HTTP the request's trace is dropped with it, provider and
585
+ * outgoing spans included, unless the request already names an operation
586
+ * of its own; in a batch, the first operation decides for the request.
587
+ * `setAttributes` still runs for an ignored operation.
580
588
  * @example (info) => info.fieldName === 'healthcheck'
581
589
  */
582
590
  ignore?: (info: GraphQLResolveInfoLike) => boolean;
@@ -604,7 +612,8 @@ export interface ObserveOptions {
604
612
  * Only consulted for operations that are *not* already inside an HTTP
605
613
  * trace - a query over HTTP takes its user id from `http.getUserId`, which
606
614
  * sees the whole request. This covers the transports that have no such
607
- * hook, subscriptions over a websocket in particular.
615
+ * hook. Operations Apollo runs over `graphql-ws` are not traced yet, so
616
+ * it is not consulted for those.
608
617
  * @example (context) => context.req?.user?.id
609
618
  * @default undefined
610
619
  */
@@ -67,6 +67,8 @@ export declare function jobSnapshotSpans(snapshot: JobSnapshot, context: TraceCo
67
67
  /**
68
68
  * Attributes from a flat record, in its order, without the keys that hold
69
69
  * nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
70
+ * A string longer than `MAX_ATTRIBUTE_VALUE_LENGTH` is cut to a copy of its
71
+ * head that ends in a hash of the whole (see `fitToLength`).
70
72
  */
71
73
  export declare function toAttributes(record: Record<string, OtlpAttributeValue | undefined | null>): {
72
74
  attributes: OtlpAttribute[];