@newrelic/browser-agent 1.312.1 → 1.313.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/cjs/common/config/init-types.js +3 -2
  3. package/dist/cjs/common/config/init.js +10 -8
  4. package/dist/cjs/common/constants/env.cdn.js +1 -1
  5. package/dist/cjs/common/constants/env.npm.js +1 -1
  6. package/dist/cjs/common/timing/time-keeper.js +28 -1
  7. package/dist/cjs/common/util/short-circuit.js +13 -0
  8. package/dist/cjs/common/util/submit-data.js +2 -9
  9. package/dist/cjs/common/v2/script-correlation.js +50 -0
  10. package/dist/cjs/common/v2/script-tracker.js +278 -0
  11. package/dist/cjs/common/{util/v2.js → v2/utils.js} +4 -4
  12. package/dist/cjs/common/wrap/wrap-fetch.js +2 -2
  13. package/dist/cjs/common/wrap/wrap-function.js +2 -2
  14. package/dist/cjs/common/wrap/wrap-xhr.js +2 -2
  15. package/dist/cjs/features/ajax/aggregate/index.js +4 -4
  16. package/dist/cjs/features/generic_events/aggregate/index.js +21 -2
  17. package/dist/cjs/features/generic_events/instrument/index.js +24 -21
  18. package/dist/cjs/features/jserrors/aggregate/index.js +206 -40
  19. package/dist/cjs/features/logging/aggregate/index.js +4 -4
  20. package/dist/cjs/features/metrics/instrument/index.js +1 -8
  21. package/dist/cjs/features/session_trace/aggregate/index.js +3 -4
  22. package/dist/cjs/features/session_trace/aggregate/trace/storage.js +2 -2
  23. package/dist/cjs/interfaces/registered-entity.js +7 -20
  24. package/dist/cjs/loaders/api/register-api-types.js +8 -8
  25. package/dist/cjs/loaders/api/register.js +49 -43
  26. package/dist/esm/common/config/init-types.js +3 -2
  27. package/dist/esm/common/config/init.js +10 -8
  28. package/dist/esm/common/constants/env.cdn.js +1 -1
  29. package/dist/esm/common/constants/env.npm.js +1 -1
  30. package/dist/esm/common/timing/time-keeper.js +28 -1
  31. package/dist/esm/common/util/short-circuit.js +6 -0
  32. package/dist/esm/common/util/submit-data.js +2 -9
  33. package/dist/esm/common/v2/script-correlation.js +43 -0
  34. package/dist/esm/common/v2/script-tracker.js +270 -0
  35. package/dist/esm/common/{util/v2.js → v2/utils.js} +4 -4
  36. package/dist/esm/common/wrap/wrap-fetch.js +1 -1
  37. package/dist/esm/common/wrap/wrap-function.js +1 -1
  38. package/dist/esm/common/wrap/wrap-xhr.js +1 -1
  39. package/dist/esm/features/ajax/aggregate/index.js +1 -1
  40. package/dist/esm/features/generic_events/aggregate/index.js +20 -1
  41. package/dist/esm/features/generic_events/instrument/index.js +24 -21
  42. package/dist/esm/features/jserrors/aggregate/index.js +205 -39
  43. package/dist/esm/features/logging/aggregate/index.js +1 -1
  44. package/dist/esm/features/metrics/instrument/index.js +2 -9
  45. package/dist/esm/features/session_trace/aggregate/index.js +4 -5
  46. package/dist/esm/features/session_trace/aggregate/trace/storage.js +2 -2
  47. package/dist/esm/interfaces/registered-entity.js +7 -20
  48. package/dist/esm/loaders/api/register-api-types.js +8 -8
  49. package/dist/esm/loaders/api/register.js +46 -41
  50. package/dist/tsconfig.tsbuildinfo +1 -1
  51. package/dist/types/common/config/init-types.d.ts +10 -8
  52. package/dist/types/common/config/init-types.d.ts.map +1 -1
  53. package/dist/types/common/config/init.d.ts.map +1 -1
  54. package/dist/types/common/timing/time-keeper.d.ts.map +1 -1
  55. package/dist/types/common/util/short-circuit.d.ts +8 -0
  56. package/dist/types/common/util/short-circuit.d.ts.map +1 -0
  57. package/dist/types/common/util/submit-data.d.ts.map +1 -1
  58. package/dist/types/common/v2/script-correlation.d.ts +38 -0
  59. package/dist/types/common/v2/script-correlation.d.ts.map +1 -0
  60. package/dist/types/common/{util → v2}/script-tracker.d.ts +3 -0
  61. package/dist/types/common/v2/script-tracker.d.ts.map +1 -0
  62. package/dist/types/common/{util/v2.d.ts → v2/utils.d.ts} +1 -1
  63. package/dist/types/common/v2/utils.d.ts.map +1 -0
  64. package/dist/types/features/generic_events/aggregate/index.d.ts.map +1 -1
  65. package/dist/types/features/generic_events/instrument/index.d.ts +1 -1
  66. package/dist/types/features/generic_events/instrument/index.d.ts.map +1 -1
  67. package/dist/types/features/jserrors/aggregate/index.d.ts +25 -16
  68. package/dist/types/features/jserrors/aggregate/index.d.ts.map +1 -1
  69. package/dist/types/features/metrics/instrument/index.d.ts.map +1 -1
  70. package/dist/types/features/session_trace/aggregate/index.d.ts.map +1 -1
  71. package/dist/types/interfaces/registered-entity.d.ts +0 -10
  72. package/dist/types/interfaces/registered-entity.d.ts.map +1 -1
  73. package/dist/types/loaders/api/register-api-types.d.ts +15 -15
  74. package/dist/types/loaders/api/register-api-types.d.ts.map +1 -1
  75. package/dist/types/loaders/api/register.d.ts +6 -0
  76. package/dist/types/loaders/api/register.d.ts.map +1 -1
  77. package/package.json +1 -1
  78. package/src/common/config/init-types.js +3 -2
  79. package/src/common/config/init.js +6 -4
  80. package/src/common/timing/time-keeper.js +30 -1
  81. package/src/common/util/short-circuit.js +6 -0
  82. package/src/common/util/submit-data.js +2 -8
  83. package/src/common/v2/script-correlation.js +44 -0
  84. package/src/common/v2/script-tracker.js +260 -0
  85. package/src/common/{util/v2.js → v2/utils.js} +4 -4
  86. package/src/common/wrap/wrap-fetch.js +1 -1
  87. package/src/common/wrap/wrap-function.js +1 -1
  88. package/src/common/wrap/wrap-xhr.js +1 -1
  89. package/src/features/ajax/aggregate/index.js +1 -1
  90. package/src/features/generic_events/aggregate/index.js +20 -1
  91. package/src/features/generic_events/instrument/index.js +25 -22
  92. package/src/features/jserrors/aggregate/index.js +200 -43
  93. package/src/features/logging/aggregate/index.js +1 -1
  94. package/src/features/metrics/instrument/index.js +2 -13
  95. package/src/features/session_trace/aggregate/index.js +4 -6
  96. package/src/features/session_trace/aggregate/trace/storage.js +2 -2
  97. package/src/interfaces/registered-entity.js +8 -20
  98. package/src/loaders/api/register-api-types.js +8 -8
  99. package/src/loaders/api/register.js +42 -34
  100. package/dist/cjs/common/util/script-tracker.js +0 -204
  101. package/dist/esm/common/util/script-tracker.js +0 -196
  102. package/dist/types/common/util/script-tracker.d.ts.map +0 -1
  103. package/dist/types/common/util/v2.d.ts.map +0 -1
  104. package/src/common/util/script-tracker.js +0 -189
@@ -17,8 +17,9 @@ import { AggregateBase } from '../../utils/aggregate-base';
17
17
  import { now } from '../../../common/timing/now';
18
18
  import { applyFnToProps } from '../../../common/util/traverse';
19
19
  import { evaluateInternalError } from './internal-errors';
20
- import { getVersion2Attributes } from '../../../common/util/v2';
20
+ import { getRegisteredTargetsFromFilename, getVersion2Attributes, getVersion2DuplicationAttributes, shouldDuplicate } from '../../../common/v2/utils';
21
21
  import { buildCauseString } from './cause-string';
22
+ import { ShortCircuit } from '../../../common/util/short-circuit';
22
23
 
23
24
  /**
24
25
  * @typedef {import('./compute-stack-trace.js').StackInfo} StackInfo
@@ -35,8 +36,8 @@ export class Aggregate extends AggregateBase {
35
36
  this.observedAt = {};
36
37
  this.pageviewReported = {};
37
38
  this.errorOnPage = false;
38
- register('err', (...args) => this.storeError(...args), this.featureName, this.ee);
39
- register('ierr', (...args) => this.storeError(...args), this.featureName, this.ee);
39
+ register('err', this.processError.bind(this), this.featureName, this.ee);
40
+ register('ierr', this.processError.bind(this), this.featureName, this.ee);
40
41
  register('returnJserror', (jsErrorEvent, softNavAttrs) => this.#storeJserrorForHarvest(jsErrorEvent, softNavAttrs), this.featureName, this.ee);
41
42
 
42
43
  // 0 == off, 1 == on
@@ -68,60 +69,162 @@ export class Aggregate extends AggregateBase {
68
69
  }
69
70
 
70
71
  /**
71
- * Builds a standardized stack trace string from the frames in the given `stackInfo` object, with each frame separated
72
- * by a newline character. Lines take the form `<functionName>@<url>:<lineNumber>`.
72
+ * Main entry point for processing JavaScript errors. This method orchestrates the complete error processing pipeline.
73
73
  *
74
- * @param {StackInfo} stackInfo - An object specifying a stack string and individual frames.
75
- * @returns {string} A canonical stack string built from the URLs and function names in the given `stackInfo` object.
74
+ * Processing Flow:
75
+ * 1. Filter the error through the customer's onerror handler (if configured and not internal)
76
+ * 2. Compute the stack trace from the error object
77
+ * 3. Evaluate if the error should be swallowed (internal errors, known issues, etc.)
78
+ * 4. Derive target(s) for the error (MFE detection for v2 endpoints, or default target) - Note: "undefined" indicates the default target will be used
79
+ * 5. Store the error for each derived target. During storage (#storeJserrorForHarvest), duplication for MFE <-> container will be handled
80
+ *
81
+ * Important: "ShortCircuit" Pattern:
82
+ * Several steps in the pipeline can throw a ShortCircuit error to halt processing without
83
+ * treating it as a reportable error. This pattern is used when:
84
+ * - The customer's onerror handler returns a truthy value (excluding fingerprinting objects)
85
+ * - The error is identified as an internal error that shouldn't be reported
86
+ *
87
+ * When a ShortCircuit is thrown, processing stops immediately and the error is not stored.
88
+ * Any other thrown error is re-thrown as it represents an actual problem in the agent code.
89
+ *
90
+ * @param {Error|UncaughtError} err - The error instance to be processed
91
+ * @param {number} [time] - The relative ms (to origin) timestamp of occurrence. Defaults to now()
92
+ * @param {boolean} [internal=false] - If the error was "caught" and deemed "internal" before reporting to the jserrors feature
93
+ * @param {object} [customAttributes] - Any custom attributes to be included in the error payload
94
+ * @param {boolean} [hasReplay=false] - A flag indicating if the error occurred during a replay session
95
+ * @param {string} [swallowReason] - A string indicating pre-defined reason if swallowing the error. Mainly used by internal error supportability metrics
96
+ * @param {object} [target] - The target to buffer and harvest to. If undefined, the default configuration target is used
97
+ * @returns {void}
76
98
  */
77
- buildCanonicalStackString(stackInfo) {
78
- var canonicalStackString = '';
79
- for (var i = 0; i < stackInfo.frames.length; i++) {
80
- var frame = stackInfo.frames[i];
81
- var func = canonicalFunctionName(frame.func);
82
- if (canonicalStackString) canonicalStackString += '\n';
83
- if (func) canonicalStackString += func + '@';
84
- if (typeof frame.url === 'string') canonicalStackString += frame.url;
85
- if (frame.line) canonicalStackString += ':' + frame.line;
99
+ processError(err, time, internal, customAttributes, hasReplay, swallowReason, target) {
100
+ if (!err) return;
101
+ time = time || now();
102
+ try {
103
+ const filterOutput = this.#filterError(err, internal);
104
+ const stackInfo = computeStackTrace(err);
105
+ this.#swallowError(stackInfo, internal, swallowReason);
106
+ this.#deriveTargets(stackInfo, target).forEach(target => {
107
+ this.#storeError(err, time, stackInfo, filterOutput, customAttributes, hasReplay, target);
108
+ });
109
+ } catch (e) {
110
+ if (!(e instanceof ShortCircuit)) {
111
+ throw e;
112
+ }
86
113
  }
87
- return canonicalStackString;
88
114
  }
89
115
 
90
116
  /**
117
+ * Filters an error through the customer's configured onerror handler.
91
118
  *
92
- * @param {Error|UncaughtError} err The error instance to be processed
93
- * @param {number} time the relative ms (to origin) timestamp of occurrence
94
- * @param {boolean=} internal if the error was "caught" and deemed "internal" before reporting to the jserrors feature
95
- * @param {object=} customAttributes any custom attributes to be included in the error payload
96
- * @param {boolean=} hasReplay a flag indicating if the error occurred during a replay session
97
- * @param {string=} swallowReason a string indicating pre-defined reason if swallowing the error. Mainly used by the internal error SMs.
98
- * @param {object=} target the target to buffer and harvest to, if undefined the default configuration target is used
99
- * @returns
119
+ * If the customer has configured a custom onerror handler and the error is not internal,
120
+ * this method invokes that handler. The handler's return value determines whether the error
121
+ * should be reported:
122
+ * - Falsey values (false, null, undefined, etc.) Report the error normally
123
+ * - Truthy non-object values Don't report (throws ShortCircuit)
124
+ * - Object with 'group' property (non-empty string) Report with fingerprinting label
125
+ * - Any other truthy value Don't report (throws ShortCircuit)
126
+ *
127
+ * @param {Error|UncaughtError} err - The error to filter
128
+ * @param {boolean} internal - Whether this is an internal error (internal errors skip filtering)
129
+ * @returns {undefined|object} The filter output. If an object with 'group' property, contains fingerprinting data
130
+ * @throws {ShortCircuit} When the error should not be reported based on the filter output
100
131
  */
101
- storeError(err, time, internal, customAttributes, hasReplay, swallowReason, target) {
102
- if (!err) return;
103
- // are we in an interaction
104
- time = time || now();
132
+ #filterError(err, internal) {
105
133
  let filterOutput;
106
134
  if (!internal && this.agentRef.runtime.onerror) {
107
135
  filterOutput = this.agentRef.runtime.onerror(err);
108
136
  if (filterOutput && !(typeof filterOutput.group === 'string' && filterOutput.group.length)) {
109
137
  // All truthy values mean don't report (store) the error, per backwards-compatible usage,
110
138
  // - EXCEPT if a fingerprinting label is returned, via an object with key of 'group' and value of non-empty string
111
- return;
139
+ throw new ShortCircuit();
112
140
  }
113
141
  // Again as with previous usage, all falsey values would include the error.
114
142
  }
115
- var stackInfo = computeStackTrace(err);
143
+ return filterOutput;
144
+ }
145
+
146
+ /**
147
+ * Evaluates whether an error should be swallowed (not reported) based on internal error criteria.
148
+ *
149
+ * This method uses the evaluateInternalError function to determine if the error matches known
150
+ * internal error patterns (e.g., errors from the agent itself, known browser issues, etc.).
151
+ * If the error should be swallowed, a supportability metric is recorded and processing is halted.
152
+ *
153
+ * @param {StackInfo} stackInfo - The computed stack trace information
154
+ * @param {boolean} internal - Whether the error was marked as internal
155
+ * @param {string} [swallowReason] - Optional pre-determined reason for swallowing
156
+ * @returns {void}
157
+ * @throws {ShortCircuit} When the error should be swallowed and not reported
158
+ */
159
+ #swallowError(stackInfo, internal, swallowReason) {
116
160
  const {
117
161
  shouldSwallow,
118
162
  reason
119
163
  } = evaluateInternalError(stackInfo, internal, swallowReason);
120
164
  if (shouldSwallow) {
121
165
  this.reportSupportabilityMetric('Internal/Error/' + reason);
122
- return;
166
+ throw new ShortCircuit();
123
167
  }
124
- var canonicalStackString = this.buildCanonicalStackString(stackInfo);
168
+ }
169
+
170
+ /**
171
+ * Derives the appropriate targets for reporting the given stack information.
172
+ *
173
+ * Targets represent the entities that should receive the error data. This is particularly
174
+ * important for Micro Frontend (MFE) scenarios where errors may need to be reported to
175
+ * different applications.
176
+ *
177
+ * Logic:
178
+ * - If a target is explicitly provided (e.g., from the register API), use it
179
+ * - For v2 endpoints without an explicit target, scan stack frames to detect MFE sources
180
+ * - If no MFE is detected or v2 is not enabled, use undefined (default target)
181
+ *
182
+ * @param {StackInfo} stackInfo - The computed stack trace information containing frames
183
+ * @param {object} [target] - Explicitly provided target, typically from the register API
184
+ * @returns {Array<object|undefined>} Array of targets to report the error to. Always contains at least one element.
185
+ */
186
+ #deriveTargets(stackInfo, target) {
187
+ const targets = [];
188
+ if (target) {
189
+ // reported by the register API directly
190
+ targets.push(target);
191
+ } else {
192
+ // we dont know if this is MFE yet, we need to figure it out.
193
+ if (this.harvestEndpointVersion === 2) {
194
+ for (const frame of stackInfo.frames) {
195
+ targets.push(...getRegisteredTargetsFromFilename(frame.url, this.agentRef));
196
+ if (targets.length) break;
197
+ }
198
+ }
199
+ if (!targets.length) targets.push(undefined);
200
+ }
201
+ return targets;
202
+ }
203
+
204
+ /**
205
+ * Stores error data for eventual harvesting and transmission to the backend.
206
+ *
207
+ * This method processes the error through several stages:
208
+ * 1. Build canonical stack string for cross-browser error grouping
209
+ * 2. Build cause chain string if the error has a cause property
210
+ * 3. Create params object with error metadata (stack hash, class, message, etc.)
211
+ * 4. Create bucket hash for internal deduplication
212
+ * 5. Store stack trace on first occurrence of this error
213
+ * 6. Add custom attributes and send to other features (trace, replay)
214
+ * 7. Route through soft nav if enabled, or directly to harvest storage
215
+ * 8. Handle MFE duplication for v2 endpoints if needed
216
+ *
217
+ * @param {Error|UncaughtError} err - The error instance to be processed
218
+ * @param {number} time - The relative ms (to origin) timestamp of occurrence
219
+ * @param {StackInfo} stackInfo - The computed stack trace information
220
+ * @param {object} [filterOutput] - Output from the customer's onerror handler, may contain fingerprinting group
221
+ * @param {object} [customAttributes] - Any custom attributes to be included in the error payload
222
+ * @param {boolean} [hasReplay=false] - A flag indicating if the error occurred during a replay session
223
+ * @param {object} [target] - The target to buffer and harvest to. If undefined, the default configuration target is used
224
+ * @returns {void}
225
+ */
226
+ #storeError(err, time, stackInfo, filterOutput, customAttributes, hasReplay, target) {
227
+ var canonicalStackString = this.#buildCanonicalStackString(stackInfo);
125
228
  const causeStackString = buildCauseString(err);
126
229
  const params = {
127
230
  stackHash: stringHashCode(canonicalStackString),
@@ -144,7 +247,7 @@ export class Aggregate extends AggregateBase {
144
247
  * the canonical stack trace excludes items like the column number increasing the hit-rate of different errors potentially
145
248
  * bucketing and ultimately resulting in the loss of data in NR1.
146
249
  */
147
- var bucketHash = stringHashCode("".concat(stackInfo.name, "_").concat(stackInfo.message, "_").concat(stackInfo.stackString, "_").concat(params.hasReplay ? 1 : 0, "_").concat(target?.id || 'container'));
250
+ var bucketHash = stringHashCode("".concat(stackInfo.name, "_").concat(stackInfo.message, "_").concat(stackInfo.stackString, "_").concat(params.hasReplay ? 1 : 0, "_").concat(target?.id || 'container', "_").concat(target?.instance || ''));
148
251
  if (!this.stackReported[bucketHash]) {
149
252
  this.stackReported[bucketHash] = true;
150
253
  params.stack_trace = truncateSize(stackInfo.stackString);
@@ -184,27 +287,90 @@ export class Aggregate extends AggregateBase {
184
287
  // pass the error to soft nav for evaluation - it will return it via 'returnJserror' when interaction is resolved
185
288
  handle('jserror', [jsErrorEvent], undefined, FEATURE_NAMES.softNav, this.ee);
186
289
  } else {
187
- this.#storeJserrorForHarvest(jsErrorEvent, false);
290
+ this.#storeJserrorForHarvest(jsErrorEvent);
188
291
  }
189
292
  }
190
293
 
191
294
  // always add directly if scoped to a sub-entity, the other pathways above will be deterministic if the main agent should procede
192
- if (target) this.#storeJserrorForHarvest([...jsErrorEvent, target], false, params._softNavAttributes);
295
+ if (target) this.#storeJserrorForHarvest(jsErrorEvent, {}, target);
296
+ }
297
+
298
+ /**
299
+ * Builds a standardized (canonical) stack trace string from the frames in the given `stackInfo` object.
300
+ *
301
+ * The canonical format is used for cross-browser error grouping in NR1, as different browsers
302
+ * format stack traces differently. Each frame is separated by a newline character and takes
303
+ * the form: `<functionName>@<url>:<lineNumber>`
304
+ *
305
+ * Note: Column numbers are intentionally excluded from the canonical format to improve
306
+ * grouping accuracy, as the same error across different minified builds might have different
307
+ * column numbers but should still be grouped together.
308
+ *
309
+ * Example output:
310
+ * ```
311
+ * handleClick@https://example.com/app.js:42
312
+ * EventEmitter.emit@https://example.com/vendor.js:1337
313
+ * ```
314
+ *
315
+ * @param {StackInfo} stackInfo - An object containing parsed stack frames from computeStackTrace
316
+ * @returns {string} A canonical stack string built from the URLs and function names in the given `stackInfo` object
317
+ */
318
+ #buildCanonicalStackString(stackInfo) {
319
+ var canonicalStackString = '';
320
+ for (var i = 0; i < stackInfo.frames.length; i++) {
321
+ var frame = stackInfo.frames[i];
322
+ var func = canonicalFunctionName(frame.func);
323
+ if (canonicalStackString) canonicalStackString += '\n';
324
+ if (func) canonicalStackString += func + '@';
325
+ if (typeof frame.url === 'string') canonicalStackString += frame.url;
326
+ if (frame.line) canonicalStackString += ':' + frame.line;
327
+ }
328
+ return canonicalStackString;
193
329
  }
194
- #storeJserrorForHarvest(errorInfoArr, softNavCustomAttrs = {}) {
195
- let [type, bucketHash, params, newMetrics, localAttrs, target] = errorInfoArr;
330
+
331
+ /**
332
+ * Adds a processed error to the harvest buffer with all custom attributes merged.
333
+ *
334
+ * This is the final step before an error is stored to be sent to the backend. It handles:
335
+ * - Merging all custom attributes (global, soft nav, MFE, and local)
336
+ * - Creating a unique aggregate hash for deduplication
337
+ * - Adding the error to the events buffer for harvest
338
+ * - Duplicating the error for MFE scenarios when needed (v2 endpoints)
339
+ *
340
+ * Custom Attribute Precedence (lowest to highest):
341
+ * 1. Global jsAttributes from agent config
342
+ * 2. Soft navigation attributes (if from a soft nav interaction)
343
+ * 3. MFE v2 attributes (source/parent metadata)
344
+ * 4. Local custom attributes passed with the specific error
345
+ *
346
+ * @param {Array} errorInfoArr - Array containing [type, bucketHash, params, metrics, customAttributes, target]
347
+ * @param {object} [attrs={}] - Additional attributes to merge (e.g., from soft nav interactions)
348
+ * @returns {void}
349
+ */
350
+ #storeJserrorForHarvest(errorInfoArr, attrs = {}, target) {
351
+ let [type, bucketHash, params, newMetrics, localAttrs] = errorInfoArr;
196
352
  const allCustomAttrs = {
197
353
  /** MFE specific attributes if in "multiple" mode (ie consumer version 2) */
198
354
  ...getVersion2Attributes(target, this)
199
355
  };
200
356
  Object.entries(this.agentRef.info.jsAttributes).forEach(([k, v]) => setCustom(k, v));
201
- Object.entries(softNavCustomAttrs).forEach(([k, v]) => setCustom(k, v)); // when an ixn finishes, it'll pass attrs specific to the ixn; if no associated ixn, this defaults to empty
357
+ Object.entries(attrs).forEach(([k, v]) => setCustom(k, v)); // when an ixn finishes, it'll pass attrs specific to the ixn; if no associated ixn, this defaults to empty
202
358
  if (params.browserInteractionId) bucketHash += params.browserInteractionId;
203
359
  if (localAttrs) Object.entries(localAttrs).forEach(([k, v]) => setCustom(k, v)); // local custom attrs are applied in either case with the highest precedence
204
360
 
205
361
  const jsAttributesHash = stringHashCode(stringify(allCustomAttrs));
206
362
  const aggregateHash = bucketHash + ':' + jsAttributesHash;
207
363
  this.events.add([type, aggregateHash, params, newMetrics, allCustomAttrs]);
364
+ if (shouldDuplicate(target, this)) {
365
+ // Clone the array with new object references to prevent deduplication in the shared aggregator
366
+ this.#storeJserrorForHarvest([type, bucketHash, {
367
+ ...params
368
+ }, {
369
+ ...newMetrics
370
+ }, localAttrs && {
371
+ ...localAttrs
372
+ }], getVersion2DuplicationAttributes(target, this));
373
+ }
208
374
  function setCustom(key, val) {
209
375
  allCustomAttrs[key] = val && typeof val === 'object' ? stringify(val) : val;
210
376
  }
@@ -13,7 +13,7 @@ import { applyFnToProps } from '../../../common/util/traverse';
13
13
  import { SESSION_EVENT_TYPES, SESSION_EVENTS } from '../../../common/session/constants';
14
14
  import { ABORT_REASONS } from '../../session_replay/constants';
15
15
  import { canEnableSessionTracking } from '../../utils/feature-gates';
16
- import { getVersion2Attributes, getVersion2DuplicationAttributes, shouldDuplicate } from '../../../common/util/v2';
16
+ import { getVersion2Attributes, getVersion2DuplicationAttributes, shouldDuplicate } from '../../../common/v2/utils';
17
17
  const LOGGING_EVENT = 'Logging/Event/';
18
18
  export class Aggregate extends AggregateBase {
19
19
  static featureName = FEATURE_NAME;
@@ -1,21 +1,14 @@
1
1
  /**
2
- * Copyright 2020-2025 New Relic, Inc. All rights reserved.
2
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
5
 
6
- import { isBrowserScope } from '../../../common/constants/runtime';
7
- import { handle } from '../../../common/event-emitter/handle';
8
6
  import { InstrumentBase } from '../../utils/instrument-base';
9
- import { FEATURE_NAME, SUPPORTABILITY_METRIC_CHANNEL } from '../constants';
7
+ import { FEATURE_NAME } from '../constants';
10
8
  export class Instrument extends InstrumentBase {
11
9
  static featureName = FEATURE_NAME;
12
10
  constructor(agentRef) {
13
11
  super(agentRef, FEATURE_NAME);
14
- if (isBrowserScope) {
15
- document.addEventListener('securitypolicyviolation', e => {
16
- handle(SUPPORTABILITY_METRIC_CHANNEL, ['Generic/CSPViolation/Detected'], undefined, this.featureName, this.ee);
17
- });
18
- }
19
12
  this.importAggregator(agentRef, () => import(/* webpackChunkName: "metrics-aggregate" */'../aggregate'));
20
13
  }
21
14
  }
@@ -7,7 +7,7 @@ import { FEATURE_NAME } from '../constants';
7
7
  import { AggregateBase } from '../../utils/aggregate-base';
8
8
  import { TraceStorage } from './trace/storage';
9
9
  import { obj as encodeObj } from '../../../common/url/encode';
10
- import { globalScope, getNavigationEntry } from '../../../common/constants/runtime';
10
+ import { globalScope } from '../../../common/constants/runtime';
11
11
  import { MODE, SESSION_EVENTS } from '../../../common/session/constants';
12
12
  import { applyFnToProps } from '../../../common/util/traverse';
13
13
  import { cleanURL } from '../../../common/url/clean-url';
@@ -39,6 +39,7 @@ export class Aggregate extends AggregateBase {
39
39
  this.entitled ??= stEntitled;
40
40
  if (!this.entitled) this.blocked = true;
41
41
  if (this.blocked) return this.deregisterDrain();
42
+ this.timeKeeper ??= this.agentRef.runtime.timeKeeper;
42
43
  if (!this.initialized) {
43
44
  this.initialized = true;
44
45
  /** Store session identifiers at initialization time to be cross-checked later at harvest time for session changes that are subject to race conditions */
@@ -58,9 +59,8 @@ export class Aggregate extends AggregateBase {
58
59
  // if another page's session entity has expired, or another page has transitioned to off and this one hasn't... we can just abort straight away here
59
60
  if (this.sessionId !== sessionState.value || eventType === 'cross-tab' && sessionState.sessionTraceMode === MODE.OFF) this.abort(2);
60
61
  });
61
- const navEntry = getNavigationEntry();
62
- if (navEntry) {
63
- this.traceStorage.storeTiming(navEntry);
62
+ if (typeof PerformanceNavigationTiming !== 'undefined' && globalScope.performance?.getEntriesByType('navigation')?.length > 0) {
63
+ this.traceStorage.storeTiming(globalScope.performance.getEntriesByType('navigation')[0]);
64
64
  } else {
65
65
  this.traceStorage.storeTiming(globalScope.performance?.timing, true);
66
66
  }
@@ -73,7 +73,6 @@ export class Aggregate extends AggregateBase {
73
73
  /** If the mode is off, we do not want to hold up draining for other features, so we deregister the feature for now.
74
74
  * If it drains later (due to a mode change), data and handlers will instantly drain instead of waiting for the registry. */
75
75
  if (this.mode === MODE.OFF) return this.deregisterDrain();
76
- this.timeKeeper ??= this.agentRef.runtime.timeKeeper;
77
76
 
78
77
  /** The handlers set up by the Inst file */
79
78
  registerHandler('bst', (...args) => this.traceStorage.storeEvent(...args), this.featureName, this.ee);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Copyright 2020-2025 New Relic, Inc. All rights reserved.
2
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
5
  import { MODE } from '../../../../common/session/constants';
@@ -178,7 +178,7 @@ export class TraceStorage {
178
178
  // that are in the future (Microsoft Edge seems to sometimes produce these)
179
179
  if (!(typeof val === 'number' && val >= 0)) continue;
180
180
  val = Math.round(val);
181
- if (this.parent.timeKeeper && this.parent.timeKeeper.ready && isAbsoluteTimestamp) {
181
+ if (isAbsoluteTimestamp && this.parent.timeKeeper?.ready) {
182
182
  val = this.parent.timeKeeper.convertAbsoluteTimestamp(Math.floor(this.parent.timeKeeper.correctAbsoluteTimestamp(val)));
183
183
  }
184
184
  if (!this.#storeSTN(new TraceNode(key, val, val, 'document', 'timing'))) allStored = false;
@@ -18,18 +18,18 @@ import { warn } from '../common/util/console';
18
18
  * An interface for registering an external caller to report through the base agent to a different target than the base agent.
19
19
  */
20
20
  export class RegisteredEntity {
21
- /** @type {RegisterAPIMetadata} */
22
- metadata = {
23
- target: {},
24
- timings: {},
25
- customAttributes: {}
26
- };
27
-
28
21
  /**
29
22
  *
30
23
  * @param {RegisterAPIConstructor} opts The options for setting up the registered entity.
31
24
  */
32
25
  constructor(opts) {
26
+ // Initialize metadata as an own property to ensure it exists even when agent is missing
27
+ /** @type {RegisterAPIMetadata} */
28
+ this.metadata = {
29
+ target: (/** @type {import('../loaders/api/register-api-types').RegisterAPITarget} */{}),
30
+ timings: (/** @type {import('../loaders/api/register-api-types').RegisterAPITimings} */{}),
31
+ customAttributes: {}
32
+ };
33
33
  try {
34
34
  if (!window?.newrelic) return warn(51);
35
35
  Object.assign(this, window?.newrelic?.register(opts) || {});
@@ -49,19 +49,6 @@ export class RegisteredEntity {
49
49
  warn(35, 'addPageAction');
50
50
  }
51
51
 
52
- /**
53
- * @experimental
54
- * IMPORTANT: This feature is being developed for use internally and is not in a public-facing production-ready state.
55
- * It is not recommended for use in production environments and will not receive support for issues.
56
- *
57
- * Registers an external caller to report through the base agent to a different target than the base agent. Will be related to this registered entity when called through this access point.
58
- * @param {import('../loaders/api/register-api-types').RegisterAPIConstructor} target the target object to report data to
59
- @returns {import('../loaders/api/register-api-types').RegisterAPI} Returns an object that contains the available API methods and configurations to use with the external caller. See loaders/api/api.js for more information.
60
- */
61
- register(target) {
62
- warn(35, 'register');
63
- }
64
-
65
52
  /**
66
53
  * @experimental
67
54
  * IMPORTANT: This feature is being developed for use internally and is not in a public-facing production-ready state.
@@ -8,7 +8,6 @@
8
8
  * @property {(name: string, attributes?: object) => void} addPageAction - Add a page action for the registered entity.
9
9
  * @property {(message: string, options?: { customAttributes?: object, level?: 'ERROR' | 'TRACE' | 'DEBUG' | 'INFO' | 'WARN'}) => void} log - Capture a log for the registered entity.
10
10
  * @property {(error: Error | string, customAttributes?: object) => void} noticeError - Notice an error for the registered entity.
11
- * @property {(target: RegisterAPIConstructor) => RegisterAPI} register - Record a custom event for the registered entity.
12
11
  * @property {() => void} deregister - Deregister the registered entity, which blocks its use and captures end of life timings.
13
12
  * @property {(eventType: string, attributes?: Object) => void} recordCustomEvent - Record a custom event for the registered entity.
14
13
  * @property {(eventType: string, options?: {start?: number|PerformanceMark, end?: number|PerformanceMark, customAttributes?: object}) => ({start: number, end: number, duration: number, customAttributes: object})} measure - Measures a task that is recorded as a BrowserPerformance event.
@@ -23,15 +22,15 @@
23
22
  * @property {string} id - The unique id for the registered entity. This will be assigned to any synthesized entities.
24
23
  * @property {string} name - The readable name for the registered entity. This will be assigned to any synthesized entities.
25
24
  * @property {{[key: string]: any}} [tags] - The tags for the registered entity as key-value pairs. This will be assigned to any synthesized entities. Tags are converted to source.* attributes (e.g., {environment: 'production'} becomes source.environment: 'production').
26
- * @property {boolean} [isolated] - When true, each registration creates an isolated instance. When false, multiple registrations with the same id and isolated: false will share a single instance, including all custom attributes, ids, names, and metadata. Calling deregister on a shared instance will deregister it for all entities using the instance. Defaults to true.
25
+ * @property {RegisterAPITarget} [parent] - The parent target for the registered entity. If none was supplied, it will assume the entity guid from the main agent.
27
26
  * @property {string} [parentId] - The parentId for the registered entity. If none was supplied, it will assume the entity guid from the main agent.
28
27
  */
29
28
 
30
29
  /**
31
30
  * @typedef {Object} RegisterAPIMetadata
32
31
  * @property {Object} customAttributes - The custom attributes for the registered entity.
33
- * @property {RegisterAPITimings} timings - The timing metrics for the registered entity.
34
- * @property {RegisterAPITarget} target - The options for the registered entity.
32
+ * @property {Partial<RegisterAPITimings>} timings - The timing metrics for the registered entity.
33
+ * @property {Partial<RegisterAPITarget>} target - The options for the registered entity.
35
34
  */
36
35
 
37
36
  /**
@@ -40,17 +39,18 @@
40
39
  * @property {string} name - The name returned for the registered entity.
41
40
  * @property {{[key: string]: any}} [tags] - The tags for the registered entity as key-value pairs.
42
41
  * @property {string} [parentId] - The parentId for the registered entity. If none was supplied, it will assume the entity guid from the main agent.
43
- * @property {boolean} [isolated] - When true, each registration creates an isolated instance. When false, multiple registrations with the same id and isolated: false will share a single instance, including all custom attributes, ids, names, and metadata. Calling deregister on a shared instance will deregister it for all entities using the instance. Defaults to true.
44
42
  */
45
43
 
46
44
  /**
47
45
  * @typedef {Object} RegisterAPITimings
48
46
  * @property {number} registeredAt - The timestamp when the registered entity was created.
49
47
  * @property {number} [reportedAt] - The timestamp when the registered entity was deregistered.
50
- * @property {number} fetchStart - The timestamp when the registered entity began fetching.
51
- * @property {number} fetchEnd - The timestamp when the registered entity finished fetching.
48
+ * @property {number} fetchStart - The timestamp when the registered entity began fetching (performance.start).
49
+ * @property {number} fetchEnd - The timestamp when the registered entity finished fetching (performance.end).
50
+ * @property {number} scriptStart - The timestamp when script initialization began (max of dom.start or performance.end, or performance.end if no dom.start).
51
+ * @property {number} scriptEnd - The timestamp when script loading completed (dom.end or registeredAt if no dom.end).
52
52
  * @property {Object} [asset] - The asset path (if found) for the registered entity.
53
- * @property {string} type - The type of timing associated with the registered entity, 'script' or 'link' if found with the performance resource API, 'inline' if found to be associated with the root document URL, or 'unknown' if no associated resource could be found.
53
+ * @property {string} type - The type of timing associated with the registered entity, 'script' or 'link' if found with the performance resource API, 'fetch' for dynamic imports, 'inline' if found to be associated with the root document URL, or 'unknown' if no associated resource could be found.
54
54
  */
55
55
 
56
56
  export default {};