@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
@@ -16,7 +16,7 @@ var _traverse = require("../../../common/util/traverse");
16
16
  var _userActionsAggregator = require("./user-actions/user-actions-aggregator");
17
17
  var _iframe = require("../../../common/dom/iframe");
18
18
  var _typeCheck = require("../../../common/util/type-check");
19
- var _v = require("../../../common/util/v2");
19
+ var _utils = require("../../../common/v2/utils");
20
20
  /**
21
21
  * Copyright 2020-2026 New Relic, Inc. All rights reserved.
22
22
  * SPDX-License-Identifier: Apache-2.0
@@ -270,6 +270,25 @@ class Aggregate extends _aggregateBase.AggregateBase {
270
270
  this.addEvent(event);
271
271
  }, this.featureName, this.ee);
272
272
  }
273
+ if (!agentRef.init.feature_flags.includes('no_spv')) {
274
+ (0, _registerHandler.registerHandler)('spv', evt => {
275
+ this.addEvent({
276
+ eventType: 'SecurityPolicyViolation',
277
+ timestamp: this.#toEpoch(evt.timeStamp),
278
+ blockedUri: evt.blockedURI,
279
+ documentUri: evt.documentURI,
280
+ effectiveDirective: evt.effectiveDirective,
281
+ originalPolicy: evt.originalPolicy,
282
+ sourceFile: evt.sourceFile,
283
+ statusCode: evt.statusCode,
284
+ lineNumber: evt.lineNumber,
285
+ columnNumber: evt.columnNumber,
286
+ disposition: evt.disposition,
287
+ sample: evt.sample,
288
+ referrer: evt.referrer
289
+ });
290
+ }, this.featureName, this.ee);
291
+ }
273
292
  this.drain();
274
293
  });
275
294
  }
@@ -305,7 +324,7 @@ class Aggregate extends _aggregateBase.AggregateBase {
305
324
  pageUrl: (0, _cleanUrl.cleanURL)('' + _runtime.initialLocation),
306
325
  currentUrl: (0, _cleanUrl.cleanURL)('' + location),
307
326
  /** Specific attributes only supplied if harvesting to endpoint version 2 */
308
- ...(0, _v.getVersion2Attributes)(target, this)
327
+ ...(0, _utils.getVersion2Attributes)(target, this)
309
328
  };
310
329
  const eventAttributes = {
311
330
  /** Agent-level custom attributes */
@@ -31,9 +31,10 @@ class Instrument extends _instrumentBase.InstrumentBase {
31
31
  constructor(agentRef) {
32
32
  super(agentRef, _constants.FEATURE_NAME);
33
33
  const websocketsEnabled = agentRef.init.feature_flags.includes('websockets');
34
+ const securityPolicyViolationEnabled = !agentRef.init.feature_flags.includes('no_spv');
34
35
 
35
36
  /** config values that gate whether the generic events aggregator should be imported at all */
36
- const genericEventSourceConfigs = [agentRef.init.page_action.enabled, agentRef.init.performance.capture_marks, agentRef.init.performance.capture_measures, agentRef.init.performance.resources.enabled, agentRef.init.user_actions.enabled, websocketsEnabled];
37
+ const genericEventSourceConfigs = [agentRef.init.page_action.enabled, agentRef.init.performance.capture_marks, agentRef.init.performance.capture_measures, agentRef.init.performance.resources.enabled, agentRef.init.user_actions.enabled, websocketsEnabled, securityPolicyViolationEnabled];
37
38
 
38
39
  /** feature specific APIs */
39
40
  (0, _addPageAction.setupAddPageActionAPI)(agentRef);
@@ -41,8 +42,24 @@ class Instrument extends _instrumentBase.InstrumentBase {
41
42
  (0, _finished.setupFinishedAPI)(agentRef);
42
43
  (0, _register.setupRegisterAPI)(agentRef);
43
44
  (0, _measure.setupMeasureAPI)(agentRef);
44
- let historyEE, websocketsEE;
45
- if (websocketsEnabled) websocketsEE = (0, _wrapWebsocket.wrapWebSocket)(this.ee);
45
+ this.removeOnAbort = new AbortController();
46
+ this.abortHandler = () => {
47
+ this.removeOnAbort.abort();
48
+ this.abortHandler = undefined; // weakly allow this abort op to run only once
49
+ };
50
+ let historyEE;
51
+ if (websocketsEnabled) {
52
+ // this can apply outside browser scope such as in worker
53
+ const websocketsEE = (0, _wrapWebsocket.wrapWebSocket)(this.ee);
54
+ websocketsEE.on('ws', nrData => {
55
+ (0, _handle.handle)('ws-complete', [nrData], undefined, this.featureName, this.ee);
56
+ });
57
+ }
58
+ if (securityPolicyViolationEnabled) {
59
+ _runtime.globalScope.addEventListener('securitypolicyviolation', evt => {
60
+ (0, _handle.handle)('spv', [evt], undefined, _features.FEATURE_NAMES.genericEvents, this.ee);
61
+ }, (0, _eventListenerOpts.eventListenerOpts)(false, this.removeOnAbort.signal));
62
+ }
46
63
  if (_runtime.isBrowserScope) {
47
64
  (0, _wrapFetch.wrapFetch)(this.ee, agentRef);
48
65
  (0, _wrapXhr.wrapXhr)(this.ee, agentRef);
@@ -61,7 +78,7 @@ class Instrument extends _instrumentBase.InstrumentBase {
61
78
  );
62
79
  _runtime.globalScope.addEventListener('error', () => {
63
80
  (0, _handle.handle)('uaErr', [], undefined, _features.FEATURE_NAMES.genericEvents, this.ee);
64
- }, (0, _eventListenerOpts.eventListenerOpts)(false, this.removeOnAbort?.signal));
81
+ }, (0, _eventListenerOpts.eventListenerOpts)(false, this.removeOnAbort.signal));
65
82
  this.ee.on('open-xhr-start', (args, xhr) => {
66
83
  if (!isInternalTraffic(args[1])) {
67
84
  xhr.addEventListener('readystatechange', () => {
@@ -69,7 +86,7 @@ class Instrument extends _instrumentBase.InstrumentBase {
69
86
  // HEADERS_RECEIVED
70
87
  (0, _handle.handle)('uaXhr', [], undefined, _features.FEATURE_NAMES.genericEvents, this.ee);
71
88
  }
72
- });
89
+ }, (0, _eventListenerOpts.eventListenerOpts)(undefined, this.removeOnAbort.signal));
73
90
  }
74
91
  });
75
92
  this.ee.on('fetch-start', fetchArguments => {
@@ -83,8 +100,8 @@ class Instrument extends _instrumentBase.InstrumentBase {
83
100
  }
84
101
  historyEE.on('pushState-end', navigationChange);
85
102
  historyEE.on('replaceState-end', navigationChange);
86
- window.addEventListener('hashchange', navigationChange, (0, _eventListenerOpts.eventListenerOpts)(true, this.removeOnAbort?.signal));
87
- window.addEventListener('popstate', navigationChange, (0, _eventListenerOpts.eventListenerOpts)(true, this.removeOnAbort?.signal));
103
+ window.addEventListener('hashchange', navigationChange, (0, _eventListenerOpts.eventListenerOpts)(true, this.removeOnAbort.signal));
104
+ window.addEventListener('popstate', navigationChange, (0, _eventListenerOpts.eventListenerOpts)(true, this.removeOnAbort.signal));
88
105
  function navigationChange() {
89
106
  historyEE.emit('navChange');
90
107
  }
@@ -101,20 +118,6 @@ class Instrument extends _instrumentBase.InstrumentBase {
101
118
  });
102
119
  }
103
120
  }
104
- if (websocketsEnabled) {
105
- // this can apply outside browser scope such as in worker
106
- websocketsEE.on('ws', nrData => {
107
- (0, _handle.handle)('ws-complete', [nrData], undefined, this.featureName, this.ee);
108
- });
109
- }
110
- try {
111
- this.removeOnAbort = new AbortController();
112
- } catch (e) {}
113
- this.abortHandler = () => {
114
- this.removeOnAbort?.abort();
115
- this.abortHandler = undefined; // weakly allow this abort op to run only once
116
- };
117
-
118
121
  /** If any of the sources are active, import the aggregator. otherwise deregister */
119
122
  if (genericEventSourceConfigs.some(x => x)) this.importAggregator(agentRef, () => Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "generic_events-aggregate" */'../aggregate'))));else this.deregisterDrain();
120
123
  }
@@ -18,8 +18,9 @@ var _aggregateBase = require("../../utils/aggregate-base");
18
18
  var _now = require("../../../common/timing/now");
19
19
  var _traverse = require("../../../common/util/traverse");
20
20
  var _internalErrors = require("./internal-errors");
21
- var _v = require("../../../common/util/v2");
21
+ var _utils = require("../../../common/v2/utils");
22
22
  var _causeString = require("./cause-string");
23
+ var _shortCircuit = require("../../../common/util/short-circuit");
23
24
  /**
24
25
  * Copyright 2020-2026 New Relic, Inc. All rights reserved.
25
26
  * SPDX-License-Identifier: Apache-2.0
@@ -40,8 +41,8 @@ class Aggregate extends _aggregateBase.AggregateBase {
40
41
  this.observedAt = {};
41
42
  this.pageviewReported = {};
42
43
  this.errorOnPage = false;
43
- (0, _registerHandler.registerHandler)('err', (...args) => this.storeError(...args), this.featureName, this.ee);
44
- (0, _registerHandler.registerHandler)('ierr', (...args) => this.storeError(...args), this.featureName, this.ee);
44
+ (0, _registerHandler.registerHandler)('err', this.processError.bind(this), this.featureName, this.ee);
45
+ (0, _registerHandler.registerHandler)('ierr', this.processError.bind(this), this.featureName, this.ee);
45
46
  (0, _registerHandler.registerHandler)('returnJserror', (jsErrorEvent, softNavAttrs) => this.#storeJserrorForHarvest(jsErrorEvent, softNavAttrs), this.featureName, this.ee);
46
47
 
47
48
  // 0 == off, 1 == on
@@ -73,60 +74,162 @@ class Aggregate extends _aggregateBase.AggregateBase {
73
74
  }
74
75
 
75
76
  /**
76
- * Builds a standardized stack trace string from the frames in the given `stackInfo` object, with each frame separated
77
- * by a newline character. Lines take the form `<functionName>@<url>:<lineNumber>`.
77
+ * Main entry point for processing JavaScript errors. This method orchestrates the complete error processing pipeline.
78
78
  *
79
- * @param {StackInfo} stackInfo - An object specifying a stack string and individual frames.
80
- * @returns {string} A canonical stack string built from the URLs and function names in the given `stackInfo` object.
79
+ * Processing Flow:
80
+ * 1. Filter the error through the customer's onerror handler (if configured and not internal)
81
+ * 2. Compute the stack trace from the error object
82
+ * 3. Evaluate if the error should be swallowed (internal errors, known issues, etc.)
83
+ * 4. Derive target(s) for the error (MFE detection for v2 endpoints, or default target) - Note: "undefined" indicates the default target will be used
84
+ * 5. Store the error for each derived target. During storage (#storeJserrorForHarvest), duplication for MFE <-> container will be handled
85
+ *
86
+ * Important: "ShortCircuit" Pattern:
87
+ * Several steps in the pipeline can throw a ShortCircuit error to halt processing without
88
+ * treating it as a reportable error. This pattern is used when:
89
+ * - The customer's onerror handler returns a truthy value (excluding fingerprinting objects)
90
+ * - The error is identified as an internal error that shouldn't be reported
91
+ *
92
+ * When a ShortCircuit is thrown, processing stops immediately and the error is not stored.
93
+ * Any other thrown error is re-thrown as it represents an actual problem in the agent code.
94
+ *
95
+ * @param {Error|UncaughtError} err - The error instance to be processed
96
+ * @param {number} [time] - The relative ms (to origin) timestamp of occurrence. Defaults to now()
97
+ * @param {boolean} [internal=false] - If the error was "caught" and deemed "internal" before reporting to the jserrors feature
98
+ * @param {object} [customAttributes] - Any custom attributes to be included in the error payload
99
+ * @param {boolean} [hasReplay=false] - A flag indicating if the error occurred during a replay session
100
+ * @param {string} [swallowReason] - A string indicating pre-defined reason if swallowing the error. Mainly used by internal error supportability metrics
101
+ * @param {object} [target] - The target to buffer and harvest to. If undefined, the default configuration target is used
102
+ * @returns {void}
81
103
  */
82
- buildCanonicalStackString(stackInfo) {
83
- var canonicalStackString = '';
84
- for (var i = 0; i < stackInfo.frames.length; i++) {
85
- var frame = stackInfo.frames[i];
86
- var func = (0, _canonicalFunctionName.canonicalFunctionName)(frame.func);
87
- if (canonicalStackString) canonicalStackString += '\n';
88
- if (func) canonicalStackString += func + '@';
89
- if (typeof frame.url === 'string') canonicalStackString += frame.url;
90
- if (frame.line) canonicalStackString += ':' + frame.line;
104
+ processError(err, time, internal, customAttributes, hasReplay, swallowReason, target) {
105
+ if (!err) return;
106
+ time = time || (0, _now.now)();
107
+ try {
108
+ const filterOutput = this.#filterError(err, internal);
109
+ const stackInfo = (0, _computeStackTrace.computeStackTrace)(err);
110
+ this.#swallowError(stackInfo, internal, swallowReason);
111
+ this.#deriveTargets(stackInfo, target).forEach(target => {
112
+ this.#storeError(err, time, stackInfo, filterOutput, customAttributes, hasReplay, target);
113
+ });
114
+ } catch (e) {
115
+ if (!(e instanceof _shortCircuit.ShortCircuit)) {
116
+ throw e;
117
+ }
91
118
  }
92
- return canonicalStackString;
93
119
  }
94
120
 
95
121
  /**
122
+ * Filters an error through the customer's configured onerror handler.
96
123
  *
97
- * @param {Error|UncaughtError} err The error instance to be processed
98
- * @param {number} time the relative ms (to origin) timestamp of occurrence
99
- * @param {boolean=} internal if the error was "caught" and deemed "internal" before reporting to the jserrors feature
100
- * @param {object=} customAttributes any custom attributes to be included in the error payload
101
- * @param {boolean=} hasReplay a flag indicating if the error occurred during a replay session
102
- * @param {string=} swallowReason a string indicating pre-defined reason if swallowing the error. Mainly used by the internal error SMs.
103
- * @param {object=} target the target to buffer and harvest to, if undefined the default configuration target is used
104
- * @returns
124
+ * If the customer has configured a custom onerror handler and the error is not internal,
125
+ * this method invokes that handler. The handler's return value determines whether the error
126
+ * should be reported:
127
+ * - Falsey values (false, null, undefined, etc.) Report the error normally
128
+ * - Truthy non-object values Don't report (throws ShortCircuit)
129
+ * - Object with 'group' property (non-empty string) Report with fingerprinting label
130
+ * - Any other truthy value Don't report (throws ShortCircuit)
131
+ *
132
+ * @param {Error|UncaughtError} err - The error to filter
133
+ * @param {boolean} internal - Whether this is an internal error (internal errors skip filtering)
134
+ * @returns {undefined|object} The filter output. If an object with 'group' property, contains fingerprinting data
135
+ * @throws {ShortCircuit} When the error should not be reported based on the filter output
105
136
  */
106
- storeError(err, time, internal, customAttributes, hasReplay, swallowReason, target) {
107
- if (!err) return;
108
- // are we in an interaction
109
- time = time || (0, _now.now)();
137
+ #filterError(err, internal) {
110
138
  let filterOutput;
111
139
  if (!internal && this.agentRef.runtime.onerror) {
112
140
  filterOutput = this.agentRef.runtime.onerror(err);
113
141
  if (filterOutput && !(typeof filterOutput.group === 'string' && filterOutput.group.length)) {
114
142
  // All truthy values mean don't report (store) the error, per backwards-compatible usage,
115
143
  // - EXCEPT if a fingerprinting label is returned, via an object with key of 'group' and value of non-empty string
116
- return;
144
+ throw new _shortCircuit.ShortCircuit();
117
145
  }
118
146
  // Again as with previous usage, all falsey values would include the error.
119
147
  }
120
- var stackInfo = (0, _computeStackTrace.computeStackTrace)(err);
148
+ return filterOutput;
149
+ }
150
+
151
+ /**
152
+ * Evaluates whether an error should be swallowed (not reported) based on internal error criteria.
153
+ *
154
+ * This method uses the evaluateInternalError function to determine if the error matches known
155
+ * internal error patterns (e.g., errors from the agent itself, known browser issues, etc.).
156
+ * If the error should be swallowed, a supportability metric is recorded and processing is halted.
157
+ *
158
+ * @param {StackInfo} stackInfo - The computed stack trace information
159
+ * @param {boolean} internal - Whether the error was marked as internal
160
+ * @param {string} [swallowReason] - Optional pre-determined reason for swallowing
161
+ * @returns {void}
162
+ * @throws {ShortCircuit} When the error should be swallowed and not reported
163
+ */
164
+ #swallowError(stackInfo, internal, swallowReason) {
121
165
  const {
122
166
  shouldSwallow,
123
167
  reason
124
168
  } = (0, _internalErrors.evaluateInternalError)(stackInfo, internal, swallowReason);
125
169
  if (shouldSwallow) {
126
170
  this.reportSupportabilityMetric('Internal/Error/' + reason);
127
- return;
171
+ throw new _shortCircuit.ShortCircuit();
128
172
  }
129
- var canonicalStackString = this.buildCanonicalStackString(stackInfo);
173
+ }
174
+
175
+ /**
176
+ * Derives the appropriate targets for reporting the given stack information.
177
+ *
178
+ * Targets represent the entities that should receive the error data. This is particularly
179
+ * important for Micro Frontend (MFE) scenarios where errors may need to be reported to
180
+ * different applications.
181
+ *
182
+ * Logic:
183
+ * - If a target is explicitly provided (e.g., from the register API), use it
184
+ * - For v2 endpoints without an explicit target, scan stack frames to detect MFE sources
185
+ * - If no MFE is detected or v2 is not enabled, use undefined (default target)
186
+ *
187
+ * @param {StackInfo} stackInfo - The computed stack trace information containing frames
188
+ * @param {object} [target] - Explicitly provided target, typically from the register API
189
+ * @returns {Array<object|undefined>} Array of targets to report the error to. Always contains at least one element.
190
+ */
191
+ #deriveTargets(stackInfo, target) {
192
+ const targets = [];
193
+ if (target) {
194
+ // reported by the register API directly
195
+ targets.push(target);
196
+ } else {
197
+ // we dont know if this is MFE yet, we need to figure it out.
198
+ if (this.harvestEndpointVersion === 2) {
199
+ for (const frame of stackInfo.frames) {
200
+ targets.push(...(0, _utils.getRegisteredTargetsFromFilename)(frame.url, this.agentRef));
201
+ if (targets.length) break;
202
+ }
203
+ }
204
+ if (!targets.length) targets.push(undefined);
205
+ }
206
+ return targets;
207
+ }
208
+
209
+ /**
210
+ * Stores error data for eventual harvesting and transmission to the backend.
211
+ *
212
+ * This method processes the error through several stages:
213
+ * 1. Build canonical stack string for cross-browser error grouping
214
+ * 2. Build cause chain string if the error has a cause property
215
+ * 3. Create params object with error metadata (stack hash, class, message, etc.)
216
+ * 4. Create bucket hash for internal deduplication
217
+ * 5. Store stack trace on first occurrence of this error
218
+ * 6. Add custom attributes and send to other features (trace, replay)
219
+ * 7. Route through soft nav if enabled, or directly to harvest storage
220
+ * 8. Handle MFE duplication for v2 endpoints if needed
221
+ *
222
+ * @param {Error|UncaughtError} err - The error instance to be processed
223
+ * @param {number} time - The relative ms (to origin) timestamp of occurrence
224
+ * @param {StackInfo} stackInfo - The computed stack trace information
225
+ * @param {object} [filterOutput] - Output from the customer's onerror handler, may contain fingerprinting group
226
+ * @param {object} [customAttributes] - Any custom attributes to be included in the error payload
227
+ * @param {boolean} [hasReplay=false] - A flag indicating if the error occurred during a replay session
228
+ * @param {object} [target] - The target to buffer and harvest to. If undefined, the default configuration target is used
229
+ * @returns {void}
230
+ */
231
+ #storeError(err, time, stackInfo, filterOutput, customAttributes, hasReplay, target) {
232
+ var canonicalStackString = this.#buildCanonicalStackString(stackInfo);
130
233
  const causeStackString = (0, _causeString.buildCauseString)(err);
131
234
  const params = {
132
235
  stackHash: (0, _stringHashCode.stringHashCode)(canonicalStackString),
@@ -149,7 +252,7 @@ class Aggregate extends _aggregateBase.AggregateBase {
149
252
  * the canonical stack trace excludes items like the column number increasing the hit-rate of different errors potentially
150
253
  * bucketing and ultimately resulting in the loss of data in NR1.
151
254
  */
152
- var bucketHash = (0, _stringHashCode.stringHashCode)("".concat(stackInfo.name, "_").concat(stackInfo.message, "_").concat(stackInfo.stackString, "_").concat(params.hasReplay ? 1 : 0, "_").concat(target?.id || 'container'));
255
+ var bucketHash = (0, _stringHashCode.stringHashCode)("".concat(stackInfo.name, "_").concat(stackInfo.message, "_").concat(stackInfo.stackString, "_").concat(params.hasReplay ? 1 : 0, "_").concat(target?.id || 'container', "_").concat(target?.instance || ''));
153
256
  if (!this.stackReported[bucketHash]) {
154
257
  this.stackReported[bucketHash] = true;
155
258
  params.stack_trace = (0, _formatStackTrace.truncateSize)(stackInfo.stackString);
@@ -189,27 +292,90 @@ class Aggregate extends _aggregateBase.AggregateBase {
189
292
  // pass the error to soft nav for evaluation - it will return it via 'returnJserror' when interaction is resolved
190
293
  (0, _handle.handle)('jserror', [jsErrorEvent], undefined, _features.FEATURE_NAMES.softNav, this.ee);
191
294
  } else {
192
- this.#storeJserrorForHarvest(jsErrorEvent, false);
295
+ this.#storeJserrorForHarvest(jsErrorEvent);
193
296
  }
194
297
  }
195
298
 
196
299
  // always add directly if scoped to a sub-entity, the other pathways above will be deterministic if the main agent should procede
197
- if (target) this.#storeJserrorForHarvest([...jsErrorEvent, target], false, params._softNavAttributes);
300
+ if (target) this.#storeJserrorForHarvest(jsErrorEvent, {}, target);
301
+ }
302
+
303
+ /**
304
+ * Builds a standardized (canonical) stack trace string from the frames in the given `stackInfo` object.
305
+ *
306
+ * The canonical format is used for cross-browser error grouping in NR1, as different browsers
307
+ * format stack traces differently. Each frame is separated by a newline character and takes
308
+ * the form: `<functionName>@<url>:<lineNumber>`
309
+ *
310
+ * Note: Column numbers are intentionally excluded from the canonical format to improve
311
+ * grouping accuracy, as the same error across different minified builds might have different
312
+ * column numbers but should still be grouped together.
313
+ *
314
+ * Example output:
315
+ * ```
316
+ * handleClick@https://example.com/app.js:42
317
+ * EventEmitter.emit@https://example.com/vendor.js:1337
318
+ * ```
319
+ *
320
+ * @param {StackInfo} stackInfo - An object containing parsed stack frames from computeStackTrace
321
+ * @returns {string} A canonical stack string built from the URLs and function names in the given `stackInfo` object
322
+ */
323
+ #buildCanonicalStackString(stackInfo) {
324
+ var canonicalStackString = '';
325
+ for (var i = 0; i < stackInfo.frames.length; i++) {
326
+ var frame = stackInfo.frames[i];
327
+ var func = (0, _canonicalFunctionName.canonicalFunctionName)(frame.func);
328
+ if (canonicalStackString) canonicalStackString += '\n';
329
+ if (func) canonicalStackString += func + '@';
330
+ if (typeof frame.url === 'string') canonicalStackString += frame.url;
331
+ if (frame.line) canonicalStackString += ':' + frame.line;
332
+ }
333
+ return canonicalStackString;
198
334
  }
199
- #storeJserrorForHarvest(errorInfoArr, softNavCustomAttrs = {}) {
200
- let [type, bucketHash, params, newMetrics, localAttrs, target] = errorInfoArr;
335
+
336
+ /**
337
+ * Adds a processed error to the harvest buffer with all custom attributes merged.
338
+ *
339
+ * This is the final step before an error is stored to be sent to the backend. It handles:
340
+ * - Merging all custom attributes (global, soft nav, MFE, and local)
341
+ * - Creating a unique aggregate hash for deduplication
342
+ * - Adding the error to the events buffer for harvest
343
+ * - Duplicating the error for MFE scenarios when needed (v2 endpoints)
344
+ *
345
+ * Custom Attribute Precedence (lowest to highest):
346
+ * 1. Global jsAttributes from agent config
347
+ * 2. Soft navigation attributes (if from a soft nav interaction)
348
+ * 3. MFE v2 attributes (source/parent metadata)
349
+ * 4. Local custom attributes passed with the specific error
350
+ *
351
+ * @param {Array} errorInfoArr - Array containing [type, bucketHash, params, metrics, customAttributes, target]
352
+ * @param {object} [attrs={}] - Additional attributes to merge (e.g., from soft nav interactions)
353
+ * @returns {void}
354
+ */
355
+ #storeJserrorForHarvest(errorInfoArr, attrs = {}, target) {
356
+ let [type, bucketHash, params, newMetrics, localAttrs] = errorInfoArr;
201
357
  const allCustomAttrs = {
202
358
  /** MFE specific attributes if in "multiple" mode (ie consumer version 2) */
203
- ...(0, _v.getVersion2Attributes)(target, this)
359
+ ...(0, _utils.getVersion2Attributes)(target, this)
204
360
  };
205
361
  Object.entries(this.agentRef.info.jsAttributes).forEach(([k, v]) => setCustom(k, v));
206
- 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
362
+ 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
207
363
  if (params.browserInteractionId) bucketHash += params.browserInteractionId;
208
364
  if (localAttrs) Object.entries(localAttrs).forEach(([k, v]) => setCustom(k, v)); // local custom attrs are applied in either case with the highest precedence
209
365
 
210
366
  const jsAttributesHash = (0, _stringHashCode.stringHashCode)((0, _stringify.stringify)(allCustomAttrs));
211
367
  const aggregateHash = bucketHash + ':' + jsAttributesHash;
212
368
  this.events.add([type, aggregateHash, params, newMetrics, allCustomAttrs]);
369
+ if ((0, _utils.shouldDuplicate)(target, this)) {
370
+ // Clone the array with new object references to prevent deduplication in the shared aggregator
371
+ this.#storeJserrorForHarvest([type, bucketHash, {
372
+ ...params
373
+ }, {
374
+ ...newMetrics
375
+ }, localAttrs && {
376
+ ...localAttrs
377
+ }], (0, _utils.getVersion2DuplicationAttributes)(target, this));
378
+ }
213
379
  function setCustom(key, val) {
214
380
  allCustomAttrs[key] = val && typeof val === 'object' ? (0, _stringify.stringify)(val) : val;
215
381
  }
@@ -15,7 +15,7 @@ var _traverse = require("../../../common/util/traverse");
15
15
  var _constants2 = require("../../../common/session/constants");
16
16
  var _constants3 = require("../../session_replay/constants");
17
17
  var _featureGates = require("../../utils/feature-gates");
18
- var _v = require("../../../common/util/v2");
18
+ var _utils2 = require("../../../common/v2/utils");
19
19
  /**
20
20
  * Copyright 2020-2026 New Relic, Inc. All rights reserved.
21
21
  * SPDX-License-Identifier: Apache-2.0
@@ -106,11 +106,11 @@ class Aggregate extends _aggregateBase.AggregateBase {
106
106
  };
107
107
  addEvent({
108
108
  ...attributes,
109
- ...(0, _v.getVersion2Attributes)(target, this)
109
+ ...(0, _utils2.getVersion2Attributes)(target, this)
110
110
  });
111
- if ((0, _v.shouldDuplicate)(target, this)) addEvent({
111
+ if ((0, _utils2.shouldDuplicate)(target, this)) addEvent({
112
112
  ...attributes,
113
- ...(0, _v.getVersion2DuplicationAttributes)(target, this)
113
+ ...(0, _utils2.getVersion2DuplicationAttributes)(target, this)
114
114
  });
115
115
  }
116
116
  serializer(eventBuffer) {
@@ -4,23 +4,16 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Metrics = exports.Instrument = void 0;
7
- var _runtime = require("../../../common/constants/runtime");
8
- var _handle = require("../../../common/event-emitter/handle");
9
7
  var _instrumentBase = require("../../utils/instrument-base");
10
8
  var _constants = require("../constants");
11
9
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /**
12
- * Copyright 2020-2025 New Relic, Inc. All rights reserved.
10
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
13
11
  * SPDX-License-Identifier: Apache-2.0
14
12
  */
15
13
  class Instrument extends _instrumentBase.InstrumentBase {
16
14
  static featureName = _constants.FEATURE_NAME;
17
15
  constructor(agentRef) {
18
16
  super(agentRef, _constants.FEATURE_NAME);
19
- if (_runtime.isBrowserScope) {
20
- document.addEventListener('securitypolicyviolation', e => {
21
- (0, _handle.handle)(_constants.SUPPORTABILITY_METRIC_CHANNEL, ['Generic/CSPViolation/Detected'], undefined, this.featureName, this.ee);
22
- });
23
- }
24
17
  this.importAggregator(agentRef, () => Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "metrics-aggregate" */'../aggregate'))));
25
18
  }
26
19
  }
@@ -45,6 +45,7 @@ class Aggregate extends _aggregateBase.AggregateBase {
45
45
  this.entitled ??= stEntitled;
46
46
  if (!this.entitled) this.blocked = true;
47
47
  if (this.blocked) return this.deregisterDrain();
48
+ this.timeKeeper ??= this.agentRef.runtime.timeKeeper;
48
49
  if (!this.initialized) {
49
50
  this.initialized = true;
50
51
  /** Store session identifiers at initialization time to be cross-checked later at harvest time for session changes that are subject to race conditions */
@@ -64,9 +65,8 @@ class Aggregate extends _aggregateBase.AggregateBase {
64
65
  // 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
65
66
  if (this.sessionId !== sessionState.value || eventType === 'cross-tab' && sessionState.sessionTraceMode === _constants2.MODE.OFF) this.abort(2);
66
67
  });
67
- const navEntry = (0, _runtime.getNavigationEntry)();
68
- if (navEntry) {
69
- this.traceStorage.storeTiming(navEntry);
68
+ if (typeof PerformanceNavigationTiming !== 'undefined' && _runtime.globalScope.performance?.getEntriesByType('navigation')?.length > 0) {
69
+ this.traceStorage.storeTiming(_runtime.globalScope.performance.getEntriesByType('navigation')[0]);
70
70
  } else {
71
71
  this.traceStorage.storeTiming(_runtime.globalScope.performance?.timing, true);
72
72
  }
@@ -79,7 +79,6 @@ class Aggregate extends _aggregateBase.AggregateBase {
79
79
  /** If the mode is off, we do not want to hold up draining for other features, so we deregister the feature for now.
80
80
  * If it drains later (due to a mode change), data and handlers will instantly drain instead of waiting for the registry. */
81
81
  if (this.mode === _constants2.MODE.OFF) return this.deregisterDrain();
82
- this.timeKeeper ??= this.agentRef.runtime.timeKeeper;
83
82
 
84
83
  /** The handlers set up by the Inst file */
85
84
  (0, _registerHandler.registerHandler)('bst', (...args) => this.traceStorage.storeEvent(...args), this.featureName, this.ee);
@@ -12,7 +12,7 @@ var _constants2 = require("../../constants");
12
12
  var _node = require("./node");
13
13
  var _utils = require("./utils");
14
14
  /**
15
- * Copyright 2020-2025 New Relic, Inc. All rights reserved.
15
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
16
16
  * SPDX-License-Identifier: Apache-2.0
17
17
  */
18
18
 
@@ -185,7 +185,7 @@ class TraceStorage {
185
185
  // that are in the future (Microsoft Edge seems to sometimes produce these)
186
186
  if (!(typeof val === 'number' && val >= 0)) continue;
187
187
  val = Math.round(val);
188
- if (this.parent.timeKeeper && this.parent.timeKeeper.ready && isAbsoluteTimestamp) {
188
+ if (isAbsoluteTimestamp && this.parent.timeKeeper?.ready) {
189
189
  val = this.parent.timeKeeper.convertAbsoluteTimestamp(Math.floor(this.parent.timeKeeper.correctAbsoluteTimestamp(val)));
190
190
  }
191
191
  if (!this.#storeSTN(new _node.TraceNode(key, val, val, 'document', 'timing'))) allStored = false;
@@ -24,18 +24,18 @@ var _console = require("../common/util/console");
24
24
  * An interface for registering an external caller to report through the base agent to a different target than the base agent.
25
25
  */
26
26
  class RegisteredEntity {
27
- /** @type {RegisterAPIMetadata} */
28
- metadata = {
29
- target: {},
30
- timings: {},
31
- customAttributes: {}
32
- };
33
-
34
27
  /**
35
28
  *
36
29
  * @param {RegisterAPIConstructor} opts The options for setting up the registered entity.
37
30
  */
38
31
  constructor(opts) {
32
+ // Initialize metadata as an own property to ensure it exists even when agent is missing
33
+ /** @type {RegisterAPIMetadata} */
34
+ this.metadata = {
35
+ target: (/** @type {import('../loaders/api/register-api-types').RegisterAPITarget} */{}),
36
+ timings: (/** @type {import('../loaders/api/register-api-types').RegisterAPITimings} */{}),
37
+ customAttributes: {}
38
+ };
39
39
  try {
40
40
  if (!window?.newrelic) return (0, _console.warn)(51);
41
41
  Object.assign(this, window?.newrelic?.register(opts) || {});
@@ -55,19 +55,6 @@ class RegisteredEntity {
55
55
  (0, _console.warn)(35, 'addPageAction');
56
56
  }
57
57
 
58
- /**
59
- * @experimental
60
- * IMPORTANT: This feature is being developed for use internally and is not in a public-facing production-ready state.
61
- * It is not recommended for use in production environments and will not receive support for issues.
62
- *
63
- * 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.
64
- * @param {import('../loaders/api/register-api-types').RegisterAPIConstructor} target the target object to report data to
65
- @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.
66
- */
67
- register(target) {
68
- (0, _console.warn)(35, 'register');
69
- }
70
-
71
58
  /**
72
59
  * @experimental
73
60
  * IMPORTANT: This feature is being developed for use internally and is not in a public-facing production-ready state.