@newrelic/browser-agent 1.317.0 → 1.318.0-rc.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 (78) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/cjs/common/config/configurable.js +1 -1
  3. package/dist/cjs/common/config/init-types.js +2 -0
  4. package/dist/cjs/common/config/init.js +3 -0
  5. package/dist/cjs/common/constants/env.cdn.js +1 -1
  6. package/dist/cjs/common/constants/env.npm.js +1 -1
  7. package/dist/cjs/common/harvest/harvester.js +3 -219
  8. package/dist/cjs/common/harvest/send.js +232 -0
  9. package/dist/cjs/common/harvest/types.js +9 -5
  10. package/dist/cjs/common/session/session-entity.js +8 -8
  11. package/dist/cjs/common/v2/mfe-vitals.js +303 -0
  12. package/dist/cjs/features/generic_events/aggregate/index.js +1 -1
  13. package/dist/cjs/features/generic_events/instrument/index.js +1 -1
  14. package/dist/cjs/features/logging/aggregate/index.js +5 -5
  15. package/dist/cjs/features/page_view_event/aggregate/index.js +65 -30
  16. package/dist/cjs/features/session_replay/aggregate/index.js +32 -28
  17. package/dist/cjs/features/session_trace/aggregate/index.js +29 -27
  18. package/dist/cjs/features/session_trace/constants.js +17 -3
  19. package/dist/cjs/features/utils/aggregate-base.js +2 -0
  20. package/dist/cjs/loaders/api/register.js +27 -4
  21. package/dist/esm/common/config/configurable.js +1 -1
  22. package/dist/esm/common/config/init-types.js +2 -0
  23. package/dist/esm/common/config/init.js +3 -0
  24. package/dist/esm/common/constants/env.cdn.js +1 -1
  25. package/dist/esm/common/constants/env.npm.js +1 -1
  26. package/dist/esm/common/harvest/harvester.js +3 -219
  27. package/dist/esm/common/harvest/send.js +226 -0
  28. package/dist/esm/common/harvest/types.js +9 -5
  29. package/dist/esm/common/session/session-entity.js +9 -9
  30. package/dist/esm/common/v2/mfe-vitals.js +298 -0
  31. package/dist/esm/features/generic_events/aggregate/index.js +1 -1
  32. package/dist/esm/features/generic_events/instrument/index.js +1 -1
  33. package/dist/esm/features/logging/aggregate/index.js +5 -5
  34. package/dist/esm/features/page_view_event/aggregate/index.js +64 -29
  35. package/dist/esm/features/session_replay/aggregate/index.js +32 -28
  36. package/dist/esm/features/session_trace/aggregate/index.js +30 -28
  37. package/dist/esm/features/session_trace/constants.js +16 -2
  38. package/dist/esm/features/utils/aggregate-base.js +2 -0
  39. package/dist/esm/loaders/api/register.js +27 -4
  40. package/dist/tsconfig.tsbuildinfo +1 -1
  41. package/dist/types/common/config/init-types.d.ts +6 -0
  42. package/dist/types/common/config/init.d.ts.map +1 -1
  43. package/dist/types/common/harvest/harvester.d.ts +0 -17
  44. package/dist/types/common/harvest/harvester.d.ts.map +1 -1
  45. package/dist/types/common/harvest/send.d.ts +9 -0
  46. package/dist/types/common/harvest/send.d.ts.map +1 -0
  47. package/dist/types/common/harvest/types.d.ts +39 -10
  48. package/dist/types/common/harvest/types.d.ts.map +1 -1
  49. package/dist/types/common/session/session-entity.d.ts.map +1 -1
  50. package/dist/types/common/v2/mfe-vitals.d.ts +14 -0
  51. package/dist/types/common/v2/mfe-vitals.d.ts.map +1 -0
  52. package/dist/types/features/page_view_event/aggregate/index.d.ts +1 -0
  53. package/dist/types/features/page_view_event/aggregate/index.d.ts.map +1 -1
  54. package/dist/types/features/session_replay/aggregate/index.d.ts +2 -2
  55. package/dist/types/features/session_replay/aggregate/index.d.ts.map +1 -1
  56. package/dist/types/features/session_trace/aggregate/index.d.ts +1 -1
  57. package/dist/types/features/session_trace/aggregate/index.d.ts.map +1 -1
  58. package/dist/types/features/session_trace/constants.d.ts +17 -0
  59. package/dist/types/features/utils/aggregate-base.d.ts.map +1 -1
  60. package/dist/types/loaders/api/register.d.ts.map +1 -1
  61. package/package.json +2 -2
  62. package/src/common/config/configurable.js +1 -1
  63. package/src/common/config/init-types.js +2 -0
  64. package/src/common/config/init.js +2 -1
  65. package/src/common/harvest/harvester.js +3 -202
  66. package/src/common/harvest/send.js +209 -0
  67. package/src/common/harvest/types.js +9 -5
  68. package/src/common/session/session-entity.js +8 -9
  69. package/src/common/v2/mfe-vitals.js +285 -0
  70. package/src/features/generic_events/aggregate/index.js +1 -1
  71. package/src/features/generic_events/instrument/index.js +1 -1
  72. package/src/features/logging/aggregate/index.js +5 -5
  73. package/src/features/page_view_event/aggregate/index.js +52 -27
  74. package/src/features/session_replay/aggregate/index.js +30 -27
  75. package/src/features/session_trace/aggregate/index.js +31 -28
  76. package/src/features/session_trace/constants.js +7 -1
  77. package/src/features/utils/aggregate-base.js +2 -0
  78. package/src/loaders/api/register.js +25 -4
package/CHANGELOG.md CHANGED
@@ -3,6 +3,15 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [1.318.0](https://github.com/newrelic/newrelic-browser-agent/compare/v1.317.0...v1.318.0) (2026-07-08)
7
+
8
+
9
+ ### Features
10
+
11
+ * Add websocket init config ([#1803](https://github.com/newrelic/newrelic-browser-agent/issues/1803)) ([aa4d2f3](https://github.com/newrelic/newrelic-browser-agent/commit/aa4d2f330fb832e0bbbdd8ed88702621f7564abf))
12
+ * Improve agent startup ([#1760](https://github.com/newrelic/newrelic-browser-agent/issues/1760)) ([d75f4bf](https://github.com/newrelic/newrelic-browser-agent/commit/d75f4bf7758f29e7096a84b8c55ed3d2b135caed))
13
+ * MFE core web-vitals detection ([#1768](https://github.com/newrelic/newrelic-browser-agent/issues/1768)) ([8559842](https://github.com/newrelic/newrelic-browser-agent/commit/8559842cc233db8875f283c301c0e8b062689e05))
14
+
6
15
  ## [1.317.0](https://github.com/newrelic/newrelic-browser-agent/compare/v1.316.0...v1.317.0) (2026-06-18)
7
16
 
8
17
 
@@ -24,7 +24,7 @@ function getModeledObject(obj, model) {
24
24
  output[key] = null;
25
25
  continue;
26
26
  }
27
- if (Array.isArray(obj[key]) && Array.isArray(model[key])) output[key] = Array.from(new Set([...obj[key], ...model[key]]));else if (obj[key] instanceof Map || obj[key] instanceof Set || obj[key] instanceof Date || obj[key] instanceof RegExp) output[key] = obj[key];else if (typeof obj[key] === 'object' && typeof model[key] === 'object') output[key] = getModeledObject(obj[key], model[key]);else output[key] = obj[key];
27
+ if (Array.isArray(obj[key]) && Array.isArray(model[key])) output[key] = Array.from(new Set([...obj[key], ...model[key]]));else if (obj[key] instanceof Map || obj[key] instanceof Set || obj[key] instanceof Date || obj[key] instanceof RegExp) output[key] = obj[key];else if (typeof obj[key] === 'object' && model[key] !== null && typeof model[key] === 'object') output[key] = getModeledObject(obj[key], model[key]);else output[key] = obj[key];
28
28
  } catch (e) {
29
29
  if (!output[key]) (0, _console.warn)(1, e);
30
30
  }
@@ -93,5 +93,7 @@ exports.default = void 0;
93
93
  * @property {Object} [user_actions]
94
94
  * @property {boolean} [user_actions.enabled] - Must be true to allow UserAction events to be captured.
95
95
  * @property {Array<string>} [user_actions.elementAttributes] - List of HTML Element properties to be captured with UserAction events' target elements. This may help to identify the source element being interacted with in the UI.
96
+ * @property {Object} [web_sockets]
97
+ * @property {boolean} [web_sockets.enabled] - Turn on/off the web sockets feature (off by default).
96
98
  */
97
99
  var _default = exports.default = {};
@@ -204,6 +204,9 @@ const InitModelFn = () => {
204
204
  user_actions: {
205
205
  enabled: true,
206
206
  elementAttributes: ['id', 'className', 'tagName', 'type']
207
+ },
208
+ web_sockets: {
209
+ enabled: false
207
210
  }
208
211
  };
209
212
  };
@@ -17,7 +17,7 @@ exports.VERSION = exports.RRWEB_VERSION = exports.RRWEB_PACKAGE_NAME = exports.D
17
17
  /**
18
18
  * Exposes the version of the agent
19
19
  */
20
- const VERSION = exports.VERSION = "1.317.0";
20
+ const VERSION = exports.VERSION = "1.318.0-rc.0";
21
21
 
22
22
  /**
23
23
  * Exposes the build type of the agent
@@ -17,7 +17,7 @@ exports.VERSION = exports.RRWEB_VERSION = exports.RRWEB_PACKAGE_NAME = exports.D
17
17
  /**
18
18
  * Exposes the version of the agent
19
19
  */
20
- const VERSION = exports.VERSION = "1.317.0";
20
+ const VERSION = exports.VERSION = "1.318.0-rc.0";
21
21
 
22
22
  /**
23
23
  * Exposes the build type of the agent
@@ -4,21 +4,12 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Harvester = void 0;
7
- exports.send = send;
8
7
  var _constants = require("../../features/metrics/constants");
9
8
  var _features = require("../../loaders/features/features");
10
- var _env = require("../constants/env.npm");
11
- var _runtime = require("../constants/runtime");
12
9
  var _handle = require("../event-emitter/handle");
13
- var _eventListenerOpts = require("../event-listener/event-listener-opts");
14
- var _now = require("../timing/now");
15
10
  var _eol = require("../unload/eol");
16
- var _cleanUrl = require("../url/clean-url");
17
- var _encode = require("../url/encode");
18
- var _console = require("../util/console");
19
- var _stringify = require("../util/stringify");
20
11
  var _submitData = require("../util/submit-data");
21
- var _globalEvent = require("../dispatch/global-event");
12
+ var _send = require("./send");
22
13
  var _obfuscate = require("../util/obfuscate");
23
14
  /**
24
15
  * Copyright 2020-2026 New Relic, Inc. All rights reserved.
@@ -79,7 +70,7 @@ class Harvester {
79
70
  const shouldRetryOnFail = !localOpts.isFinalHarvest && submitMethod === _submitData.xhr; // always retry all features harvests except for final
80
71
  output.payload = aggregateInst.makeHarvestPayload(shouldRetryOnFail, localOpts);
81
72
  if (!output.payload) return output;
82
- send(this.agentRef, {
73
+ (0, _send.send)(this.agentRef, {
83
74
  endpoint: _features.FEATURE_TO_ENDPOINT[aggregateInst.featureName],
84
75
  payload: output.payload,
85
76
  localOpts,
@@ -114,211 +105,4 @@ class Harvester {
114
105
  }
115
106
  }
116
107
  }
117
-
118
- /**
119
- * @typedef {import('./types.js').NetworkSendSpec} NetworkSendSpec
120
- */
121
- exports.Harvester = Harvester;
122
- const warnings = {};
123
- /**
124
- * Initiate a harvest call.
125
- * @param {NetworkSendSpec} param0 Specification for sending data
126
- * @returns {boolean} True if a network call was made. Note that this does not mean or guarantee that it was successful.
127
- */
128
- function send(agentRef, {
129
- endpoint,
130
- payload,
131
- localOpts = {},
132
- submitMethod,
133
- cbFinished,
134
- raw,
135
- featureName,
136
- endpointVersion = 1,
137
- harvesterObfuscator
138
- }) {
139
- if (!agentRef.info.errorBeacon) return false;
140
- let {
141
- body,
142
- qs
143
- } = cleanPayload(payload);
144
- if (Object.keys(body).length === 0 && !localOpts.sendEmptyBody) {
145
- // if there's no body to send, just run onfinish stuff and return
146
- if (cbFinished) cbFinished({
147
- sent: false
148
- });
149
- return false;
150
- }
151
- const protocol = agentRef.init.ssl === false ? 'http' : 'https';
152
- const perceivedBeacon = agentRef.init.proxy.beacon || agentRef.info.errorBeacon;
153
- const url = raw ? "".concat(protocol, "://").concat(perceivedBeacon, "/").concat(endpoint) : "".concat(protocol, "://").concat(perceivedBeacon).concat(endpoint !== _features.RUM ? '/' + endpoint : '', "/").concat(endpointVersion, "/").concat(agentRef.info.licenseKey);
154
- const baseParams = !raw ? baseQueryString(agentRef, qs, endpoint, harvesterObfuscator) : '';
155
- let payloadParams = (0, _encode.obj)(qs, agentRef.runtime.maxBytes);
156
- if (baseParams === '' && payloadParams.startsWith('&')) {
157
- payloadParams = payloadParams.substring(1);
158
- }
159
- const fullUrl = "".concat(url, "?").concat(baseParams).concat(payloadParams);
160
- const gzip = !!qs?.attributes?.includes('gzip');
161
-
162
- // all gzipped data is already in the correct format and needs no transformation
163
- // all features going to 'events' endpoint should already be serialized & stringified
164
- let stringBody = gzip || endpoint === _features.EVENTS ? body : (0, _stringify.stringify)(body);
165
-
166
- // If body is null, undefined, or an empty object or array after stringifying, send an empty string instead.
167
- if (!stringBody || stringBody.length === 0 || stringBody === '{}' || stringBody === '[]') stringBody = '';
168
-
169
- // Warn--once per endpoint--if the agent tries to send large payloads
170
- if (endpoint !== _features.BLOBS && stringBody.length > 750000 && (warnings[endpoint] = (warnings[endpoint] || 0) + 1) === 1) (0, _console.warn)(28, endpoint);
171
- const headers = [{
172
- key: 'content-type',
173
- value: 'text/plain'
174
- }];
175
-
176
- /* Since workers don't support sendBeacon right now, they can only use XHR method.
177
- Because they still do permit synch XHR, the idea is that at final harvest time (worker is closing),
178
- we just make a BLOCKING request--trivial impact--with the remaining data as a temp fill-in for sendBeacon.
179
- Following the removal of img-element method. */
180
- let result = submitMethod({
181
- url: fullUrl,
182
- body: stringBody,
183
- sync: localOpts.isFinalHarvest && _runtime.isWorkerScope,
184
- headers
185
- });
186
- if (!localOpts.isFinalHarvest && cbFinished) {
187
- // final harvests don't hold onto buffer data (shouldRetryOnFail is false), so cleanup isn't needed
188
- if (submitMethod === _submitData.xhr) {
189
- result.addEventListener('loadend', function () {
190
- // `this` here in block refers to the XHR object in this scope, do not change the anon function to an arrow function
191
- // status 0 refers to a local error, such as CORS or network failure, or a blocked request by the browser (e.g. adblocker)
192
- const cbResult = {
193
- sent: this.status !== 0,
194
- status: this.status,
195
- retry: shouldRetry(this.status),
196
- fullUrl,
197
- xhr: this,
198
- responseText: this.responseText
199
- };
200
- cbFinished(cbResult);
201
-
202
- /** temporary audit of consistency of harvest metadata flags */
203
- if (!shouldRetry(this.status)) trackHarvestMetadata();
204
- }, (0, _eventListenerOpts.eventListenerOpts)(false));
205
- } else if (submitMethod === _submitData.xhrFetch) {
206
- result.then(async function (response) {
207
- const status = response.status;
208
- const cbResult = {
209
- sent: true,
210
- status,
211
- retry: shouldRetry(status),
212
- fullUrl,
213
- fetchResponse: response,
214
- responseText: await response.text()
215
- };
216
- cbFinished(cbResult);
217
- /** temporary audit of consistency of harvest metadata flags */
218
- if (!shouldRetry(status)) trackHarvestMetadata();
219
- });
220
- }
221
- function trackHarvestMetadata() {
222
- try {
223
- if (featureName === _features.FEATURE_NAMES.jserrors && !body?.err) return;
224
- const hasReplay = baseParams.includes('hr=1');
225
- const hasTrace = baseParams.includes('ht=1');
226
- const hasError = qs?.attributes?.includes('hasError=true');
227
- (0, _handle.handle)('harvest-metadata', [{
228
- [featureName]: {
229
- ...(hasReplay && {
230
- hasReplay
231
- }),
232
- ...(hasTrace && {
233
- hasTrace
234
- }),
235
- ...(hasError && {
236
- hasError
237
- })
238
- }
239
- }], undefined, _features.FEATURE_NAMES.metrics, agentRef.ee);
240
- } catch (err) {
241
- // do nothing
242
- }
243
- }
244
- }
245
- (0, _globalEvent.dispatchGlobalEvent)({
246
- drained: !!agentRef.runtime?.activatedFeatures,
247
- type: 'data',
248
- name: 'harvest',
249
- feature: featureName,
250
- data: {
251
- endpoint,
252
- headers,
253
- payload,
254
- submitMethod: getSubmitMethodName(),
255
- raw,
256
- synchronousXhr: !!(localOpts.isFinalHarvest && _runtime.isWorkerScope)
257
- }
258
- });
259
- return true;
260
- function shouldRetry(status) {
261
- switch (status) {
262
- case 408:
263
- case 429:
264
- case 500:
265
- return true;
266
- }
267
- return status >= 502 && status <= 504 || status >= 512 && status <= 530;
268
- }
269
- function getSubmitMethodName() {
270
- if (submitMethod === _submitData.xhr) return 'xhr';
271
- if (submitMethod === _submitData.xhrFetch) return 'fetch';
272
- return 'beacon';
273
- }
274
- }
275
-
276
- /**
277
- * Cleans and returns a payload object containing a body and qs
278
- * object with key/value pairs. KV pairs where the value is null,
279
- * undefined, or an empty string are removed to save on transmission
280
- * size.
281
- * @param {HarvestPayload} payload Payload to be sent to the endpoint.
282
- * @returns {HarvestPayload} Cleaned payload payload to be sent to the endpoint.
283
- */
284
- function cleanPayload(payload = {}) {
285
- const clean = input => {
286
- if (typeof Uint8Array !== 'undefined' && input instanceof Uint8Array || Array.isArray(input)) return input;
287
- if (typeof input === 'string') return input;
288
- return Object.entries(input || {}).reduce((accumulator, [key, value]) => {
289
- if (typeof value === 'number' || typeof value === 'string' && value.length > 0 || typeof value === 'object' && Object.keys(value || {}).length > 0) {
290
- accumulator[key] = value;
291
- }
292
- return accumulator;
293
- }, {});
294
- };
295
- return {
296
- body: clean(payload.body),
297
- qs: clean(payload.qs)
298
- };
299
- }
300
-
301
- // The stuff that gets sent every time.
302
- function baseQueryString(agentRef, qs, endpoint, harvesterObfuscator) {
303
- const cleanedURL = (0, _cleanUrl.cleanURL)('' + _runtime.globalScope.location);
304
- const ref = harvesterObfuscator?.obfuscateString(cleanedURL) ?? cleanedURL;
305
- const session = agentRef.runtime.session;
306
- const hr = !!session?.state.sessionReplaySentFirstChunk && session?.state.sessionReplayMode === 1 && endpoint !== _features.JSERRORS;
307
- const ht = !!session?.state.traceHarvestStarted && session?.state.sessionTraceMode === 1 && ![_features.LOGS, _features.BLOBS].includes(endpoint);
308
- const qps = ['a=' + agentRef.info.applicationID, (0, _encode.param)('sa', agentRef.info.sa ? '' + agentRef.info.sa : ''), (0, _encode.param)('v', _env.VERSION), transactionNameParam(), (0, _encode.param)('ct', agentRef.runtime.customTransaction), '&rst=' + (0, _now.now)(), '&ck=0',
309
- // ck param DEPRECATED - still expected by backend
310
- '&s=' + (session?.state.value || '0'),
311
- // the 0 id encaps all untrackable and default traffic
312
- (0, _encode.param)('ref', ref), (0, _encode.param)('ptid', agentRef.runtime.ptid ? '' + agentRef.runtime.ptid : '')];
313
- if (hr) qps.push((0, _encode.param)('hr', '1', qs));
314
- if (ht) qps.push((0, _encode.param)('ht', '1', qs));
315
- return qps.join('');
316
-
317
- // Constructs the transaction name param for the beacon URL.
318
- // Prefers the obfuscated transaction name over the plain text.
319
- // Falls back to making up a name.
320
- function transactionNameParam() {
321
- if (agentRef.info.transactionName) return (0, _encode.param)('to', agentRef.info.transactionName);
322
- return (0, _encode.param)('t', agentRef.info.tNamePlain || 'Unnamed Transaction');
323
- }
324
- }
108
+ exports.Harvester = Harvester;
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.send = send;
7
+ var _features = require("../../loaders/features/features");
8
+ var _env = require("../constants/env.npm");
9
+ var _runtime = require("../constants/runtime");
10
+ var _handle = require("../event-emitter/handle");
11
+ var _eventListenerOpts = require("../event-listener/event-listener-opts");
12
+ var _now = require("../timing/now");
13
+ var _cleanUrl = require("../url/clean-url");
14
+ var _encode = require("../url/encode");
15
+ var _console = require("../util/console");
16
+ var _stringify = require("../util/stringify");
17
+ var _submitData = require("../util/submit-data");
18
+ var _globalEvent = require("../dispatch/global-event");
19
+ /**
20
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
21
+ * SPDX-License-Identifier: Apache-2.0
22
+ */
23
+
24
+ /**
25
+ * @typedef {import('./types.js').NetworkSendSpec} NetworkSendSpec
26
+ */
27
+
28
+ const warnings = {};
29
+
30
+ /**
31
+ * Initiate a harvest call.
32
+ * @param {object} agentRef The initialized agent reference
33
+ * @param {NetworkSendSpec} spec Specification for sending data
34
+ * @returns {boolean} True if a network call was made. Note that this does not mean or guarantee that it was successful.
35
+ */
36
+ function send(agentRef, {
37
+ endpoint,
38
+ payload,
39
+ localOpts = {},
40
+ submitMethod,
41
+ cbFinished,
42
+ raw,
43
+ featureName,
44
+ endpointVersion = 1,
45
+ harvesterObfuscator
46
+ }) {
47
+ if (!agentRef.info.errorBeacon) return false;
48
+ let {
49
+ body,
50
+ qs
51
+ } = cleanPayload(payload);
52
+ if (Object.keys(body).length === 0 && !localOpts.sendEmptyBody) {
53
+ // if there's no body to send, just run onfinish stuff and return
54
+ if (cbFinished) cbFinished({
55
+ sent: false
56
+ });
57
+ return false;
58
+ }
59
+ const protocol = agentRef.init.ssl === false ? 'http' : 'https';
60
+ const perceivedBeacon = agentRef.init.proxy.beacon || agentRef.info.errorBeacon;
61
+ const url = raw ? "".concat(protocol, "://").concat(perceivedBeacon, "/").concat(endpoint) : "".concat(protocol, "://").concat(perceivedBeacon).concat(endpoint !== _features.RUM ? '/' + endpoint : '', "/").concat(endpointVersion, "/").concat(agentRef.info.licenseKey);
62
+ const baseParams = !raw ? baseQueryString(agentRef, qs, endpoint, harvesterObfuscator) : '';
63
+ let payloadParams = (0, _encode.obj)(qs, agentRef.runtime.maxBytes);
64
+ if (baseParams === '' && payloadParams.startsWith('&')) {
65
+ payloadParams = payloadParams.substring(1);
66
+ }
67
+ const fullUrl = "".concat(url, "?").concat(baseParams).concat(payloadParams);
68
+ const gzip = !!qs?.attributes?.includes('gzip');
69
+
70
+ // all gzipped data is already in the correct format and needs no transformation
71
+ // all features going to 'events' endpoint should already be serialized & stringified
72
+ let stringBody = gzip || endpoint === _features.EVENTS ? body : (0, _stringify.stringify)(body);
73
+
74
+ // If body is null, undefined, or an empty object or array after stringifying, send an empty string instead.
75
+ if (!stringBody || stringBody.length === 0 || stringBody === '{}' || stringBody === '[]') stringBody = '';
76
+
77
+ // Warn--once per endpoint--if the agent tries to send large payloads
78
+ if (endpoint !== _features.BLOBS && stringBody.length > 750000 && (warnings[endpoint] = (warnings[endpoint] || 0) + 1) === 1) (0, _console.warn)(28, endpoint);
79
+ const headers = [{
80
+ key: 'content-type',
81
+ value: 'text/plain'
82
+ }];
83
+
84
+ /* Since workers don't support sendBeacon right now, they can only use XHR method.
85
+ Because they still do permit synch XHR, the idea is that at final harvest time (worker is closing),
86
+ we just make a BLOCKING request--trivial impact--with the remaining data as a temp fill-in for sendBeacon.
87
+ Following the removal of img-element method. */
88
+ let result = submitMethod({
89
+ url: fullUrl,
90
+ body: stringBody,
91
+ sync: localOpts.isFinalHarvest && _runtime.isWorkerScope,
92
+ headers
93
+ });
94
+ if (!localOpts.isFinalHarvest && cbFinished) {
95
+ // final harvests don't hold onto buffer data (shouldRetryOnFail is false), so cleanup isn't needed
96
+ if (submitMethod === _submitData.xhr) {
97
+ result.addEventListener('loadend', function () {
98
+ // `this` here in block refers to the XHR object in this scope, do not change the anon function to an arrow function
99
+ // status 0 refers to a local error, such as CORS or network failure, or a blocked request by the browser (e.g. adblocker)
100
+ const cbResult = {
101
+ sent: this.status !== 0,
102
+ status: this.status,
103
+ retry: shouldRetry(this.status),
104
+ fullUrl,
105
+ xhr: this,
106
+ responseText: this.responseText
107
+ };
108
+ cbFinished(cbResult);
109
+
110
+ /** temporary audit of consistency of harvest metadata flags */
111
+ if (!shouldRetry(this.status)) trackHarvestMetadata();
112
+ }, (0, _eventListenerOpts.eventListenerOpts)(false));
113
+ } else if (submitMethod === _submitData.xhrFetch) {
114
+ result.then(async function (response) {
115
+ const status = response.status;
116
+ const cbResult = {
117
+ sent: true,
118
+ status,
119
+ retry: shouldRetry(status),
120
+ fullUrl,
121
+ fetchResponse: response,
122
+ responseText: await response.text()
123
+ };
124
+ cbFinished(cbResult);
125
+ /** temporary audit of consistency of harvest metadata flags */
126
+ if (!shouldRetry(status)) trackHarvestMetadata();
127
+ });
128
+ }
129
+ function trackHarvestMetadata() {
130
+ try {
131
+ if (featureName === _features.FEATURE_NAMES.jserrors && !body?.err) return;
132
+ const hasReplay = baseParams.includes('hr=1');
133
+ const hasTrace = baseParams.includes('ht=1');
134
+ const hasError = qs?.attributes?.includes('hasError=true');
135
+ (0, _handle.handle)('harvest-metadata', [{
136
+ [featureName]: {
137
+ ...(hasReplay && {
138
+ hasReplay
139
+ }),
140
+ ...(hasTrace && {
141
+ hasTrace
142
+ }),
143
+ ...(hasError && {
144
+ hasError
145
+ })
146
+ }
147
+ }], undefined, _features.FEATURE_NAMES.metrics, agentRef.ee);
148
+ } catch (err) {
149
+ // do nothing
150
+ }
151
+ }
152
+ }
153
+ (0, _globalEvent.dispatchGlobalEvent)({
154
+ drained: !!agentRef.runtime?.activatedFeatures,
155
+ type: 'data',
156
+ name: 'harvest',
157
+ feature: featureName,
158
+ data: {
159
+ endpoint,
160
+ headers,
161
+ payload,
162
+ submitMethod: getSubmitMethodName(),
163
+ raw,
164
+ synchronousXhr: !!(localOpts.isFinalHarvest && _runtime.isWorkerScope)
165
+ }
166
+ });
167
+ return true;
168
+ function shouldRetry(status) {
169
+ switch (status) {
170
+ case 408:
171
+ case 429:
172
+ case 500:
173
+ return true;
174
+ }
175
+ return status >= 502 && status <= 504 || status >= 512 && status <= 530;
176
+ }
177
+ function getSubmitMethodName() {
178
+ if (submitMethod === _submitData.xhr) return 'xhr';
179
+ if (submitMethod === _submitData.xhrFetch) return 'fetch';
180
+ return 'beacon';
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Cleans and returns a payload object containing a body and qs
186
+ * object with key/value pairs. KV pairs where the value is null,
187
+ * undefined, or an empty string are removed to save on transmission
188
+ * size.
189
+ * @param {HarvestPayload} payload Payload to be sent to the endpoint.
190
+ * @returns {HarvestPayload} Cleaned payload payload to be sent to the endpoint.
191
+ */
192
+ function cleanPayload(payload = {}) {
193
+ const clean = input => {
194
+ if (typeof Uint8Array !== 'undefined' && input instanceof Uint8Array || Array.isArray(input)) return input;
195
+ if (typeof input === 'string') return input;
196
+ return Object.entries(input || {}).reduce((accumulator, [key, value]) => {
197
+ if (typeof value === 'number' || typeof value === 'string' && value.length > 0 || typeof value === 'object' && Object.keys(value || {}).length > 0) {
198
+ accumulator[key] = value;
199
+ }
200
+ return accumulator;
201
+ }, {});
202
+ };
203
+ return {
204
+ body: clean(payload.body),
205
+ qs: clean(payload.qs)
206
+ };
207
+ }
208
+
209
+ // The stuff that gets sent every time.
210
+ function baseQueryString(agentRef, qs, endpoint, harvesterObfuscator) {
211
+ const cleanedURL = (0, _cleanUrl.cleanURL)('' + _runtime.globalScope.location);
212
+ const ref = harvesterObfuscator?.obfuscateString(cleanedURL) ?? cleanedURL;
213
+ const session = agentRef.runtime.session;
214
+ const hr = !!session?.state.sessionReplaySentFirstChunk && session?.state.sessionReplayMode === 1 && endpoint !== _features.JSERRORS;
215
+ const ht = !!session?.state.traceHarvestStarted && session?.state.sessionTraceMode === 1 && ![_features.LOGS, _features.BLOBS].includes(endpoint);
216
+ const qps = ['a=' + agentRef.info.applicationID, (0, _encode.param)('sa', agentRef.info.sa ? '' + agentRef.info.sa : ''), (0, _encode.param)('v', _env.VERSION), transactionNameParam(), (0, _encode.param)('ct', agentRef.runtime.customTransaction), '&rst=' + (0, _now.now)(), '&ck=0',
217
+ // ck param DEPRECATED - still expected by backend
218
+ '&s=' + (session?.state.value || '0'),
219
+ // the 0 id encaps all untrackable and default traffic
220
+ (0, _encode.param)('ref', ref), (0, _encode.param)('ptid', agentRef.runtime.ptid ? '' + agentRef.runtime.ptid : '')];
221
+ if (hr) qps.push((0, _encode.param)('hr', '1', qs));
222
+ if (ht) qps.push((0, _encode.param)('ht', '1', qs));
223
+ return qps.join('');
224
+
225
+ // Constructs the transaction name param for the beacon URL.
226
+ // Prefers the obfuscated transaction name over the plain text.
227
+ // Falls back to making up a name.
228
+ function transactionNameParam() {
229
+ if (agentRef.info.transactionName) return (0, _encode.param)('to', agentRef.info.transactionName);
230
+ return (0, _encode.param)('t', agentRef.info.tNamePlain || 'Unnamed Transaction');
231
+ }
232
+ }
@@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.unused = void 0;
7
7
  /**
8
- * Copyright 2020-2025 New Relic, Inc. All rights reserved.
8
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
9
9
  * SPDX-License-Identifier: Apache-2.0
10
10
  */
11
11
 
@@ -29,11 +29,15 @@ exports.unused = void 0;
29
29
  * @typedef {object} NetworkSendSpec
30
30
  * @property {HarvestEndpointIdentifier} endpoint The endpoint to use (jserrors, events, resources etc.)
31
31
  * @property {HarvestPayload} payload Object representing payload.
32
- * @property {object} localOpts Additional options for sending data
33
- * @property {boolean} localOpts.isFinalHarvest Specify whether the call is a final harvest during page unload.
34
- * @property {boolean} localOpts.sendEmptyBody Specify whether the call should be made even if the body is empty. Useful for rum calls.
35
- * @property {boolean} localOpts.forceNoRetry Don't save the buffered data in the case of a need to retry the transmission.
32
+ * @property {object} [localOpts] Additional options for sending data
33
+ * @property {boolean} [localOpts.isFinalHarvest] Specify whether the call is a final harvest during page unload.
34
+ * @property {boolean} [localOpts.sendEmptyBody] Specify whether the call should be made even if the body is empty. Useful for rum calls.
35
+ * @property {boolean} [localOpts.forceNoRetry] Don't save the buffered data in the case of a need to retry the transmission.
36
36
  * @property {import('../util/submit-data.js').NetworkMethods} submitMethod The network method to use {@link ../util/submit-data.js}
37
+ * @property {function(object): void} [cbFinished] Callback invoked with the result once the network request completes. Receives an object with sent, status, retry, fullUrl, responseText, and either xhr or fetchResponse.
38
+ * @property {boolean} [raw] If true, skips standard versioned URL path construction and uses a bare endpoint URL.
39
+ * @property {string} [featureName] The feature name associated with this harvest, used for metadata tracking and the global harvest event.
40
+ * @property {number} [endpointVersion] The endpoint version included in the URL path. Defaults to 1.
37
41
  */
38
42
 
39
43
  const unused = exports.unused = {};
@@ -17,30 +17,31 @@ var _handle = require("../event-emitter/handle");
17
17
  var _constants2 = require("../../features/metrics/constants");
18
18
  var _features = require("../../loaders/features/features");
19
19
  var _eventListenerOpts = require("../event-listener/event-listener-opts");
20
- var _constants3 = require("../../features/logging/constants");
21
20
  /**
22
21
  * Copyright 2020-2026 New Relic, Inc. All rights reserved.
23
22
  * SPDX-License-Identifier: Apache-2.0
24
23
  */
25
24
 
26
- // this is what can be stored in local storage (not enforced but probably should be)
25
+ // this is what can be stored in local storage (enforced during reads)
27
26
  // these values should sync between local storage and the parent class props
28
27
  const model = {
29
28
  value: '',
30
29
  inactiveAt: 0,
31
30
  expiresAt: 0,
32
31
  updatedAt: Date.now(),
33
- sessionReplayMode: _constants.MODE.OFF,
32
+ sessionReplayMode: null,
34
33
  sessionReplaySentFirstChunk: false,
35
- sessionTraceMode: _constants.MODE.OFF,
34
+ sessionTraceMode: null,
36
35
  traceHarvestStarted: false,
37
- loggingMode: _constants3.LOGGING_MODE.OFF,
38
- logApiMode: _constants3.LOGGING_MODE.OFF,
36
+ loggingMode: null,
37
+ logApiMode: null,
39
38
  serverTimeDiff: null,
40
39
  // set by TimeKeeper; "undefined" value will not be stringified and stored but "null" will
41
40
  custom: {},
42
41
  numOfResets: 0,
43
- consent: false // set by consent() API call
42
+ consent: false,
43
+ // set by consent() API call
44
+ cachedRumResponse: null
44
45
  };
45
46
  class SessionEntity {
46
47
  /**
@@ -252,7 +253,6 @@ class SessionEntity {
252
253
  this.expiresTimer?.clear?.();
253
254
  delete this.isNew;
254
255
  this.setup({
255
- agentRef: this.agentRef,
256
256
  key: this.key,
257
257
  storage: this.storage,
258
258
  expiresMs: this.expiresMs,