@newrelic/browser-agent 1.316.0 → 1.317.0-rc.1

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 (170) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/cjs/common/config/configurable.js +1 -1
  3. package/dist/cjs/common/config/init-types.js +1 -0
  4. package/dist/cjs/common/config/init.js +6 -4
  5. package/dist/cjs/common/constants/env.cdn.js +2 -2
  6. package/dist/cjs/common/constants/env.npm.js +2 -2
  7. package/dist/cjs/common/constants/events.js +26 -0
  8. package/dist/cjs/common/harvest/harvester.js +9 -217
  9. package/dist/cjs/common/harvest/send.js +232 -0
  10. package/dist/cjs/common/harvest/types.js +9 -5
  11. package/dist/cjs/common/payloads/payloads.js +127 -0
  12. package/dist/cjs/common/serialize/bel-serializer.js +4 -3
  13. package/dist/cjs/common/session/session-entity.js +8 -8
  14. package/dist/cjs/common/util/data-size.js +2 -2
  15. package/dist/cjs/common/util/obfuscate.js +147 -3
  16. package/dist/cjs/common/v2/mfe-vitals.js +286 -0
  17. package/dist/cjs/common/wrap/wrap-websocket.js +2 -1
  18. package/dist/cjs/common/wrap/wrap-xhr.js +1 -1
  19. package/dist/cjs/features/ajax/aggregate/gql.js +40 -1
  20. package/dist/cjs/features/ajax/aggregate/index.js +51 -13
  21. package/dist/cjs/features/ajax/constants.js +6 -1
  22. package/dist/cjs/features/ajax/instrument/index.js +105 -17
  23. package/dist/cjs/features/generic_events/aggregate/index.js +15 -10
  24. package/dist/cjs/features/generic_events/constants.js +3 -2
  25. package/dist/cjs/features/jserrors/aggregate/format-stack-trace.js +2 -2
  26. package/dist/cjs/features/jserrors/aggregate/index.js +12 -3
  27. package/dist/cjs/features/logging/aggregate/index.js +12 -8
  28. package/dist/cjs/features/metrics/aggregate/index.js +5 -1
  29. package/dist/cjs/features/page_view_event/aggregate/index.js +72 -33
  30. package/dist/cjs/features/page_view_timing/aggregate/index.js +6 -1
  31. package/dist/cjs/features/session_replay/aggregate/index.js +39 -29
  32. package/dist/cjs/features/session_trace/aggregate/index.js +35 -29
  33. package/dist/cjs/features/session_trace/constants.js +17 -3
  34. package/dist/cjs/features/soft_navigations/aggregate/ajax-node.js +36 -5
  35. package/dist/cjs/features/soft_navigations/aggregate/index.js +7 -1
  36. package/dist/cjs/features/soft_navigations/aggregate/initial-page-load-interaction.js +1 -1
  37. package/dist/cjs/features/soft_navigations/aggregate/interaction.js +6 -4
  38. package/dist/cjs/features/utils/aggregate-base.js +4 -3
  39. package/dist/cjs/loaders/api/register.js +26 -4
  40. package/dist/esm/common/config/configurable.js +1 -1
  41. package/dist/esm/common/config/init-types.js +1 -0
  42. package/dist/esm/common/config/init.js +3 -1
  43. package/dist/esm/common/constants/env.cdn.js +2 -2
  44. package/dist/esm/common/constants/env.npm.js +2 -2
  45. package/dist/esm/common/constants/events.js +20 -0
  46. package/dist/esm/common/harvest/harvester.js +9 -217
  47. package/dist/esm/common/harvest/send.js +226 -0
  48. package/dist/esm/common/harvest/types.js +9 -5
  49. package/dist/esm/common/payloads/payloads.js +118 -0
  50. package/dist/esm/common/serialize/bel-serializer.js +4 -3
  51. package/dist/esm/common/session/session-entity.js +9 -9
  52. package/dist/esm/common/util/data-size.js +2 -2
  53. package/dist/esm/common/util/obfuscate.js +147 -3
  54. package/dist/esm/common/v2/mfe-vitals.js +281 -0
  55. package/dist/esm/common/wrap/wrap-websocket.js +2 -1
  56. package/dist/esm/common/wrap/wrap-xhr.js +1 -1
  57. package/dist/esm/features/ajax/aggregate/gql.js +39 -1
  58. package/dist/esm/features/ajax/aggregate/index.js +52 -14
  59. package/dist/esm/features/ajax/constants.js +5 -0
  60. package/dist/esm/features/ajax/instrument/index.js +106 -18
  61. package/dist/esm/features/generic_events/aggregate/index.js +15 -10
  62. package/dist/esm/features/generic_events/constants.js +3 -2
  63. package/dist/esm/features/jserrors/aggregate/format-stack-trace.js +2 -2
  64. package/dist/esm/features/jserrors/aggregate/index.js +12 -3
  65. package/dist/esm/features/logging/aggregate/index.js +12 -8
  66. package/dist/esm/features/metrics/aggregate/index.js +5 -1
  67. package/dist/esm/features/page_view_event/aggregate/index.js +71 -32
  68. package/dist/esm/features/page_view_timing/aggregate/index.js +6 -1
  69. package/dist/esm/features/session_replay/aggregate/index.js +39 -29
  70. package/dist/esm/features/session_trace/aggregate/index.js +36 -30
  71. package/dist/esm/features/session_trace/constants.js +16 -2
  72. package/dist/esm/features/soft_navigations/aggregate/ajax-node.js +36 -5
  73. package/dist/esm/features/soft_navigations/aggregate/index.js +7 -1
  74. package/dist/esm/features/soft_navigations/aggregate/initial-page-load-interaction.js +1 -1
  75. package/dist/esm/features/soft_navigations/aggregate/interaction.js +6 -4
  76. package/dist/esm/features/utils/aggregate-base.js +4 -3
  77. package/dist/esm/loaders/api/register.js +26 -4
  78. package/dist/tsconfig.tsbuildinfo +1 -1
  79. package/dist/types/common/config/init-types.d.ts +4 -0
  80. package/dist/types/common/config/init-types.d.ts.map +1 -1
  81. package/dist/types/common/config/init.d.ts.map +1 -1
  82. package/dist/types/common/constants/events.d.ts +16 -0
  83. package/dist/types/common/constants/events.d.ts.map +1 -0
  84. package/dist/types/common/harvest/harvester.d.ts +2 -16
  85. package/dist/types/common/harvest/harvester.d.ts.map +1 -1
  86. package/dist/types/common/harvest/send.d.ts +9 -0
  87. package/dist/types/common/harvest/send.d.ts.map +1 -0
  88. package/dist/types/common/harvest/types.d.ts +39 -10
  89. package/dist/types/common/harvest/types.d.ts.map +1 -1
  90. package/dist/types/common/payloads/payloads.d.ts +42 -0
  91. package/dist/types/common/payloads/payloads.d.ts.map +1 -0
  92. package/dist/types/common/serialize/bel-serializer.d.ts +1 -1
  93. package/dist/types/common/serialize/bel-serializer.d.ts.map +1 -1
  94. package/dist/types/common/session/session-entity.d.ts.map +1 -1
  95. package/dist/types/common/util/obfuscate.d.ts +23 -2
  96. package/dist/types/common/util/obfuscate.d.ts.map +1 -1
  97. package/dist/types/common/v2/mfe-vitals.d.ts +14 -0
  98. package/dist/types/common/v2/mfe-vitals.d.ts.map +1 -0
  99. package/dist/types/common/wrap/wrap-websocket.d.ts.map +1 -1
  100. package/dist/types/features/ajax/aggregate/gql.d.ts +8 -0
  101. package/dist/types/features/ajax/aggregate/gql.d.ts.map +1 -1
  102. package/dist/types/features/ajax/aggregate/index.d.ts +2 -0
  103. package/dist/types/features/ajax/aggregate/index.d.ts.map +1 -1
  104. package/dist/types/features/ajax/constants.d.ts +5 -0
  105. package/dist/types/features/ajax/constants.d.ts.map +1 -1
  106. package/dist/types/features/ajax/instrument/index.d.ts.map +1 -1
  107. package/dist/types/features/generic_events/aggregate/index.d.ts +3 -1
  108. package/dist/types/features/generic_events/aggregate/index.d.ts.map +1 -1
  109. package/dist/types/features/generic_events/constants.d.ts.map +1 -1
  110. package/dist/types/features/jserrors/aggregate/index.d.ts +8 -1
  111. package/dist/types/features/jserrors/aggregate/index.d.ts.map +1 -1
  112. package/dist/types/features/logging/aggregate/index.d.ts +3 -1
  113. package/dist/types/features/logging/aggregate/index.d.ts.map +1 -1
  114. package/dist/types/features/metrics/aggregate/index.d.ts +2 -0
  115. package/dist/types/features/metrics/aggregate/index.d.ts.map +1 -1
  116. package/dist/types/features/page_view_event/aggregate/index.d.ts +3 -0
  117. package/dist/types/features/page_view_event/aggregate/index.d.ts.map +1 -1
  118. package/dist/types/features/page_view_timing/aggregate/index.d.ts +2 -0
  119. package/dist/types/features/page_view_timing/aggregate/index.d.ts.map +1 -1
  120. package/dist/types/features/session_replay/aggregate/index.d.ts +4 -2
  121. package/dist/types/features/session_replay/aggregate/index.d.ts.map +1 -1
  122. package/dist/types/features/session_trace/aggregate/index.d.ts +3 -1
  123. package/dist/types/features/session_trace/aggregate/index.d.ts.map +1 -1
  124. package/dist/types/features/session_trace/constants.d.ts +17 -0
  125. package/dist/types/features/soft_navigations/aggregate/ajax-node.d.ts +6 -1
  126. package/dist/types/features/soft_navigations/aggregate/ajax-node.d.ts.map +1 -1
  127. package/dist/types/features/soft_navigations/aggregate/index.d.ts +3 -0
  128. package/dist/types/features/soft_navigations/aggregate/index.d.ts.map +1 -1
  129. package/dist/types/features/soft_navigations/aggregate/interaction.d.ts +3 -1
  130. package/dist/types/features/soft_navigations/aggregate/interaction.d.ts.map +1 -1
  131. package/dist/types/features/utils/aggregate-base.d.ts +0 -1
  132. package/dist/types/features/utils/aggregate-base.d.ts.map +1 -1
  133. package/dist/types/loaders/api/register.d.ts.map +1 -1
  134. package/package.json +3 -3
  135. package/src/common/config/configurable.js +1 -1
  136. package/src/common/config/init-types.js +1 -0
  137. package/src/common/config/init.js +2 -1
  138. package/src/common/constants/events.js +20 -0
  139. package/src/common/harvest/harvester.js +9 -201
  140. package/src/common/harvest/send.js +209 -0
  141. package/src/common/harvest/types.js +9 -5
  142. package/src/common/payloads/payloads.js +135 -0
  143. package/src/common/serialize/bel-serializer.js +4 -3
  144. package/src/common/session/session-entity.js +8 -9
  145. package/src/common/util/data-size.js +2 -2
  146. package/src/common/util/obfuscate.js +154 -3
  147. package/src/common/v2/mfe-vitals.js +260 -0
  148. package/src/common/wrap/wrap-websocket.js +2 -1
  149. package/src/common/wrap/wrap-xhr.js +1 -1
  150. package/src/features/ajax/aggregate/gql.js +42 -1
  151. package/src/features/ajax/aggregate/index.js +43 -13
  152. package/src/features/ajax/constants.js +5 -1
  153. package/src/features/ajax/instrument/index.js +114 -18
  154. package/src/features/generic_events/aggregate/index.js +14 -9
  155. package/src/features/generic_events/constants.js +3 -2
  156. package/src/features/jserrors/aggregate/format-stack-trace.js +3 -3
  157. package/src/features/jserrors/aggregate/index.js +12 -3
  158. package/src/features/logging/aggregate/index.js +12 -11
  159. package/src/features/metrics/aggregate/index.js +5 -1
  160. package/src/features/page_view_event/aggregate/index.js +58 -29
  161. package/src/features/page_view_timing/aggregate/index.js +6 -1
  162. package/src/features/session_replay/aggregate/index.js +37 -28
  163. package/src/features/session_trace/aggregate/index.js +37 -30
  164. package/src/features/session_trace/constants.js +7 -1
  165. package/src/features/soft_navigations/aggregate/ajax-node.js +26 -5
  166. package/src/features/soft_navigations/aggregate/index.js +7 -1
  167. package/src/features/soft_navigations/aggregate/initial-page-load-interaction.js +1 -1
  168. package/src/features/soft_navigations/aggregate/interaction.js +6 -4
  169. package/src/features/utils/aggregate-base.js +3 -3
  170. package/src/loaders/api/register.js +24 -4
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ import { JSERRORS, RUM, EVENTS, FEATURE_NAMES, BLOBS, LOGS } from '../../loaders/features/features'
6
+ import { VERSION } from '../constants/env'
7
+ import { globalScope, isWorkerScope } from '../constants/runtime'
8
+ import { handle } from '../event-emitter/handle'
9
+ import { eventListenerOpts } from '../event-listener/event-listener-opts'
10
+ import { now } from '../timing/now'
11
+ import { cleanURL } from '../url/clean-url'
12
+ import { obj, param } from '../url/encode'
13
+ import { warn } from '../util/console'
14
+ import { stringify } from '../util/stringify'
15
+ import { xhr as xhrMethod, xhrFetch as fetchMethod } from '../util/submit-data'
16
+ import { dispatchGlobalEvent } from '../dispatch/global-event'
17
+
18
+ /**
19
+ * @typedef {import('./types.js').NetworkSendSpec} NetworkSendSpec
20
+ */
21
+
22
+ const warnings = {}
23
+
24
+ /**
25
+ * Initiate a harvest call.
26
+ * @param {object} agentRef The initialized agent reference
27
+ * @param {NetworkSendSpec} spec Specification for sending data
28
+ * @returns {boolean} True if a network call was made. Note that this does not mean or guarantee that it was successful.
29
+ */
30
+ export function send (agentRef, { endpoint, payload, localOpts = {}, submitMethod, cbFinished, raw, featureName, endpointVersion = 1, harvesterObfuscator }) {
31
+ if (!agentRef.info.errorBeacon) return false
32
+
33
+ let { body, qs } = cleanPayload(payload)
34
+
35
+ if (Object.keys(body).length === 0 && !localOpts.sendEmptyBody) { // if there's no body to send, just run onfinish stuff and return
36
+ if (cbFinished) cbFinished({ sent: false })
37
+ return false
38
+ }
39
+
40
+ const protocol = agentRef.init.ssl === false ? 'http' : 'https'
41
+ const perceivedBeacon = agentRef.init.proxy.beacon || agentRef.info.errorBeacon
42
+ const url = raw
43
+ ? `${protocol}://${perceivedBeacon}/${endpoint}`
44
+ : `${protocol}://${perceivedBeacon}${endpoint !== RUM ? '/' + endpoint : ''}/${endpointVersion}/${agentRef.info.licenseKey}`
45
+ const baseParams = !raw ? baseQueryString(agentRef, qs, endpoint, harvesterObfuscator) : ''
46
+ let payloadParams = obj(qs, agentRef.runtime.maxBytes)
47
+ if (baseParams === '' && payloadParams.startsWith('&')) {
48
+ payloadParams = payloadParams.substring(1)
49
+ }
50
+
51
+ const fullUrl = `${url}?${baseParams}${payloadParams}`
52
+ const gzip = !!qs?.attributes?.includes('gzip')
53
+
54
+ // all gzipped data is already in the correct format and needs no transformation
55
+ // all features going to 'events' endpoint should already be serialized & stringified
56
+ let stringBody = gzip || endpoint === EVENTS ? body : stringify(body)
57
+
58
+ // If body is null, undefined, or an empty object or array after stringifying, send an empty string instead.
59
+ if (!stringBody || stringBody.length === 0 || stringBody === '{}' || stringBody === '[]') stringBody = ''
60
+
61
+ // Warn--once per endpoint--if the agent tries to send large payloads
62
+ if (endpoint !== BLOBS && stringBody.length > 750000 && (warnings[endpoint] = (warnings[endpoint] || 0) + 1) === 1) warn(28, endpoint)
63
+
64
+ const headers = [{ key: 'content-type', value: 'text/plain' }]
65
+
66
+ /* Since workers don't support sendBeacon right now, they can only use XHR method.
67
+ Because they still do permit synch XHR, the idea is that at final harvest time (worker is closing),
68
+ we just make a BLOCKING request--trivial impact--with the remaining data as a temp fill-in for sendBeacon.
69
+ Following the removal of img-element method. */
70
+ let result = submitMethod({ url: fullUrl, body: stringBody, sync: localOpts.isFinalHarvest && isWorkerScope, headers })
71
+
72
+ if (!localOpts.isFinalHarvest && cbFinished) { // final harvests don't hold onto buffer data (shouldRetryOnFail is false), so cleanup isn't needed
73
+ if (submitMethod === xhrMethod) {
74
+ result.addEventListener('loadend', function () {
75
+ // `this` here in block refers to the XHR object in this scope, do not change the anon function to an arrow function
76
+ // status 0 refers to a local error, such as CORS or network failure, or a blocked request by the browser (e.g. adblocker)
77
+ const cbResult = { sent: this.status !== 0, status: this.status, retry: shouldRetry(this.status), fullUrl, xhr: this, responseText: this.responseText }
78
+ cbFinished(cbResult)
79
+
80
+ /** temporary audit of consistency of harvest metadata flags */
81
+ if (!shouldRetry(this.status)) trackHarvestMetadata()
82
+ }, eventListenerOpts(false))
83
+ } else if (submitMethod === fetchMethod) {
84
+ result.then(async function (response) {
85
+ const status = response.status
86
+ const cbResult = { sent: true, status, retry: shouldRetry(status), fullUrl, fetchResponse: response, responseText: await response.text() }
87
+ cbFinished(cbResult)
88
+ /** temporary audit of consistency of harvest metadata flags */
89
+ if (!shouldRetry(status)) trackHarvestMetadata()
90
+ })
91
+ }
92
+
93
+ function trackHarvestMetadata () {
94
+ try {
95
+ if (featureName === FEATURE_NAMES.jserrors && !body?.err) return
96
+
97
+ const hasReplay = baseParams.includes('hr=1')
98
+ const hasTrace = baseParams.includes('ht=1')
99
+ const hasError = qs?.attributes?.includes('hasError=true')
100
+
101
+ handle('harvest-metadata', [{
102
+ [featureName]: {
103
+ ...(hasReplay && { hasReplay }),
104
+ ...(hasTrace && { hasTrace }),
105
+ ...(hasError && { hasError })
106
+ }
107
+ }], undefined, FEATURE_NAMES.metrics, agentRef.ee)
108
+ } catch (err) {
109
+ // do nothing
110
+ }
111
+ }
112
+ }
113
+
114
+ dispatchGlobalEvent({
115
+ drained: !!agentRef.runtime?.activatedFeatures,
116
+ type: 'data',
117
+ name: 'harvest',
118
+ feature: featureName,
119
+ data: {
120
+ endpoint,
121
+ headers,
122
+ payload,
123
+ submitMethod: getSubmitMethodName(),
124
+ raw,
125
+ synchronousXhr: !!(localOpts.isFinalHarvest && isWorkerScope)
126
+ }
127
+ })
128
+
129
+ return true
130
+
131
+ function shouldRetry (status) {
132
+ switch (status) {
133
+ case 408:
134
+ case 429:
135
+ case 500:
136
+ return true
137
+ }
138
+ return (status >= 502 && status <= 504) || (status >= 512 && status <= 530)
139
+ }
140
+
141
+ function getSubmitMethodName () {
142
+ if (submitMethod === xhrMethod) return 'xhr'
143
+ if (submitMethod === fetchMethod) return 'fetch'
144
+ return 'beacon'
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Cleans and returns a payload object containing a body and qs
150
+ * object with key/value pairs. KV pairs where the value is null,
151
+ * undefined, or an empty string are removed to save on transmission
152
+ * size.
153
+ * @param {HarvestPayload} payload Payload to be sent to the endpoint.
154
+ * @returns {HarvestPayload} Cleaned payload payload to be sent to the endpoint.
155
+ */
156
+ function cleanPayload (payload = {}) {
157
+ const clean = (input) => {
158
+ if ((typeof Uint8Array !== 'undefined' && input instanceof Uint8Array) || Array.isArray(input)) return input
159
+ if (typeof input === 'string') return input
160
+ return Object.entries(input || {}).reduce((accumulator, [key, value]) => {
161
+ if ((typeof value === 'number') ||
162
+ (typeof value === 'string' && value.length > 0) ||
163
+ (typeof value === 'object' && Object.keys(value || {}).length > 0)
164
+ ) {
165
+ accumulator[key] = value
166
+ }
167
+ return accumulator
168
+ }, {})
169
+ }
170
+
171
+ return {
172
+ body: clean(payload.body),
173
+ qs: clean(payload.qs)
174
+ }
175
+ }
176
+
177
+ // The stuff that gets sent every time.
178
+ function baseQueryString (agentRef, qs, endpoint, harvesterObfuscator) {
179
+ const cleanedURL = cleanURL('' + globalScope.location)
180
+ const ref = harvesterObfuscator?.obfuscateString(cleanedURL) ?? cleanedURL
181
+ const session = agentRef.runtime.session
182
+ const hr = !!session?.state.sessionReplaySentFirstChunk && session?.state.sessionReplayMode === 1 && endpoint !== JSERRORS
183
+ const ht = !!session?.state.traceHarvestStarted && session?.state.sessionTraceMode === 1 && ![LOGS, BLOBS].includes(endpoint)
184
+
185
+ const qps = [
186
+ 'a=' + agentRef.info.applicationID,
187
+ param('sa', (agentRef.info.sa ? '' + agentRef.info.sa : '')),
188
+ param('v', VERSION),
189
+ transactionNameParam(),
190
+ param('ct', agentRef.runtime.customTransaction),
191
+ '&rst=' + now(),
192
+ '&ck=0', // ck param DEPRECATED - still expected by backend
193
+ '&s=' + (session?.state.value || '0'), // the 0 id encaps all untrackable and default traffic
194
+ param('ref', ref),
195
+ param('ptid', (agentRef.runtime.ptid ? '' + agentRef.runtime.ptid : ''))
196
+ ]
197
+ if (hr) qps.push(param('hr', '1', qs))
198
+ if (ht) qps.push(param('ht', '1', qs))
199
+
200
+ return qps.join('')
201
+
202
+ // Constructs the transaction name param for the beacon URL.
203
+ // Prefers the obfuscated transaction name over the plain text.
204
+ // Falls back to making up a name.
205
+ function transactionNameParam () {
206
+ if (agentRef.info.transactionName) return param('to', agentRef.info.transactionName)
207
+ return param('t', agentRef.info.tNamePlain || 'Unnamed Transaction')
208
+ }
209
+ }
@@ -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
 
@@ -23,11 +23,15 @@
23
23
  * @typedef {object} NetworkSendSpec
24
24
  * @property {HarvestEndpointIdentifier} endpoint The endpoint to use (jserrors, events, resources etc.)
25
25
  * @property {HarvestPayload} payload Object representing payload.
26
- * @property {object} localOpts Additional options for sending data
27
- * @property {boolean} localOpts.isFinalHarvest Specify whether the call is a final harvest during page unload.
28
- * @property {boolean} localOpts.sendEmptyBody Specify whether the call should be made even if the body is empty. Useful for rum calls.
29
- * @property {boolean} localOpts.forceNoRetry Don't save the buffered data in the case of a need to retry the transmission.
26
+ * @property {object} [localOpts] Additional options for sending data
27
+ * @property {boolean} [localOpts.isFinalHarvest] Specify whether the call is a final harvest during page unload.
28
+ * @property {boolean} [localOpts.sendEmptyBody] Specify whether the call should be made even if the body is empty. Useful for rum calls.
29
+ * @property {boolean} [localOpts.forceNoRetry] Don't save the buffered data in the case of a need to retry the transmission.
30
30
  * @property {import('../util/submit-data.js').NetworkMethods} submitMethod The network method to use {@link ../util/submit-data.js}
31
+ * @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.
32
+ * @property {boolean} [raw] If true, skips standard versioned URL path construction and uses a bare endpoint URL.
33
+ * @property {string} [featureName] The feature name associated with this harvest, used for metadata tracking and the global harvest event.
34
+ * @property {number} [endpointVersion] The endpoint version included in the URL path. Defaults to 1.
31
35
  */
32
36
 
33
37
  export const unused = {}
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Copyright 2020-2026 New Relic, Inc. All rights reserved.
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ import { stringify } from '../util/stringify'
7
+ import { CAPTURE_PAYLOAD_SETTINGS } from '../../features/ajax/constants'
8
+
9
+ /**
10
+ * Determines whether payload data should be captured based on the capture mode setting,
11
+ * HTTP status code, and GraphQL error status.
12
+ * @param {string} captureMode - The capture mode setting ('none', 'all', or 'failures')
13
+ * @param {number} statusCode - The HTTP status code
14
+ * @param {boolean} hasGQLErrors - Whether the response contains GraphQL errors
15
+ * @returns {boolean} True if payload should be captured
16
+ */
17
+ export function canCapturePayload (captureMode, statusCode, hasGQLErrors) {
18
+ if (captureMode === CAPTURE_PAYLOAD_SETTINGS.ALL) return true
19
+ if (!captureMode || captureMode === CAPTURE_PAYLOAD_SETTINGS.NONE) return false
20
+
21
+ // Default "failures" mode
22
+ return statusCode === 0 || statusCode >= 400 || hasGQLErrors === true
23
+ }
24
+
25
+ /**
26
+ * Parses a query string into an object of key-value pairs.
27
+ * @param {string} search a query string starting with "?" or without (ex. new URL(...).search)
28
+ * @returns {Object|undefined} Parsed query parameters as key-value pairs. Returns undefined if no valid parameters are found.
29
+ */
30
+ export function parseQueryString (search) {
31
+ if (!search || search.length === 0) return
32
+
33
+ const queryParams = {}
34
+ try {
35
+ const searchParams = new URLSearchParams(search)
36
+ searchParams.forEach(function (value, key) {
37
+ queryParams[key] = value
38
+ })
39
+ } catch (e) {
40
+ // Fallback for environments without URLSearchParams
41
+ }
42
+
43
+ return queryParams
44
+ }
45
+
46
+ /**
47
+ * Determines if the given content type is likely to be human-readable (text-based).
48
+ * @param {Object} headers - The headers object containing content-type
49
+ * @param {*} data - The data to check
50
+ * @returns {boolean} True if the content type is human-readable (text-based)
51
+ */
52
+ export function isLikelyHumanReadable (headers, data) {
53
+ if (!headers) return typeof data === 'string'
54
+ var contentType = headers['content-type']
55
+ if (!contentType) return typeof data === 'string'
56
+ // Normalize to lowercase and extract the mime type (ignore charset, etc.)
57
+ var mimeType = contentType.toLowerCase().split(';')[0].trim()
58
+
59
+ // Check for text/* types
60
+ if (mimeType.indexOf('text/') === 0) return true
61
+
62
+ // Check for specific application/* types
63
+ var readableAppTypes = [
64
+ '/json',
65
+ '/xml',
66
+ '/xhtml+xml',
67
+ '/ld+json',
68
+ '/yaml',
69
+ '/x-www-form-urlencoded'
70
+ ]
71
+
72
+ for (var i = 0; i < readableAppTypes.length; i++) {
73
+ if (mimeType === 'application' + readableAppTypes[i]) return true
74
+ }
75
+
76
+ return false
77
+ }
78
+
79
+ /**
80
+ * Truncates a string to ensure its UTF-8 byte length does not exceed 4092 bytes. If truncation is necessary,
81
+ * the string is cut off at a character boundary to avoid breaking multi-byte characters and " ..." is appended to indicate truncation.
82
+ * If not a string, it is first converted to a string using JSON.stringify.
83
+ * @param {*} data The data to truncate.
84
+ * @returns {string}
85
+ */
86
+ export function truncateAsString (data) {
87
+ if (!data) return data
88
+ try {
89
+ if (typeof data !== 'string') data = stringify(data)
90
+ let bytes = 0
91
+ let i = 0
92
+ let needsEllipsis = false
93
+
94
+ while (i < data.length) {
95
+ const c = data.charCodeAt(i)
96
+ const charBytes = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0xD800 || c >= 0xE000 ? 3 : 4
97
+
98
+ if (bytes + charBytes > 4092) {
99
+ needsEllipsis = true
100
+ break
101
+ }
102
+
103
+ bytes += charBytes
104
+ i += charBytes === 4 ? 2 : 1
105
+ }
106
+
107
+ return data.slice(0, i) + (needsEllipsis ? ' ...' : '')
108
+ } catch (e) {
109
+ return data
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Creates string adder functions for BEL serialization with obfuscation and optional truncation.
115
+ * This ensures a single string table is used while providing separate handling for regular vs payload attributes.
116
+ * @param {Function} getAddStringContext - Function that creates a new string table context
117
+ * @param {Object} obfuscator - Optional obfuscator instance for string obfuscation
118
+ * @returns {{addString: Function, addStringWithTruncation: Function}} Object containing both string adder functions
119
+ */
120
+ export function createStringAdders (getAddStringContext, obfuscator) {
121
+ const addStringRaw = getAddStringContext()
122
+
123
+ const processString = (str, shouldTruncate) => {
124
+ if (typeof str === 'undefined' || str === '') return addStringRaw(str)
125
+ if (typeof str !== 'string') str = stringify(str)
126
+ const obfuscated = obfuscator?.obfuscateString(str) ?? str
127
+ const processed = shouldTruncate ? truncateAsString(obfuscated) : obfuscated
128
+ return addStringRaw(processed)
129
+ }
130
+
131
+ return {
132
+ addString: (str) => processString(str, false),
133
+ addStringWithTruncation: (str) => processString(str, true)
134
+ }
135
+ }
@@ -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
 
@@ -21,7 +21,7 @@ export function numeric (n, noDefault) {
21
21
  return (n === undefined || n === 0) ? '' : Math.floor(n).toString(36)
22
22
  }
23
23
 
24
- export function getAddStringContext (obfuscator) {
24
+ export function getAddStringContext (obfuscator, truncator) {
25
25
  let stringTableIdx = 0
26
26
  const stringTable = Object.prototype.hasOwnProperty.call(Object, 'create') ? Object.create(null) : {}
27
27
 
@@ -29,7 +29,8 @@ export function getAddStringContext (obfuscator) {
29
29
 
30
30
  function addString (str) {
31
31
  if (typeof str === 'undefined' || str === '') return ''
32
- str = obfuscator.obfuscateString(String(str))
32
+ str = obfuscator?.obfuscateString(String(str)) ?? String(str)
33
+ str = truncator?.(str) ?? str
33
34
  if (hasOwnProp.call(stringTable, str)) {
34
35
  return numeric(stringTable[str], true)
35
36
  } else {
@@ -7,7 +7,7 @@ import { warn } from '../util/console'
7
7
  import { stringify } from '../util/stringify'
8
8
  import { Timer } from '../timer/timer'
9
9
  import { isBrowserScope } from '../constants/runtime'
10
- import { DEFAULT_EXPIRES_MS, DEFAULT_INACTIVE_MS, MODE, SESSION_EVENTS, SESSION_EVENT_TYPES, SESSION_STORAGE_KEY_PREFIX } from './constants'
10
+ import { DEFAULT_EXPIRES_MS, DEFAULT_INACTIVE_MS, SESSION_EVENTS, SESSION_EVENT_TYPES, SESSION_STORAGE_KEY_PREFIX } from './constants'
11
11
  import { InteractionTimer } from '../timer/interaction-timer'
12
12
  import { wrapEvents } from '../wrap/wrap-events'
13
13
  import { getModeledObject } from '../config/configurable'
@@ -15,25 +15,25 @@ import { handle } from '../event-emitter/handle'
15
15
  import { SUPPORTABILITY_METRIC_CHANNEL } from '../../features/metrics/constants'
16
16
  import { FEATURE_NAMES } from '../../loaders/features/features'
17
17
  import { windowAddEventListener } from '../event-listener/event-listener-opts'
18
- import { LOGGING_MODE } from '../../features/logging/constants'
19
18
 
20
- // this is what can be stored in local storage (not enforced but probably should be)
19
+ // this is what can be stored in local storage (enforced during reads)
21
20
  // these values should sync between local storage and the parent class props
22
21
  const model = {
23
22
  value: '',
24
23
  inactiveAt: 0,
25
24
  expiresAt: 0,
26
25
  updatedAt: Date.now(),
27
- sessionReplayMode: MODE.OFF,
26
+ sessionReplayMode: null,
28
27
  sessionReplaySentFirstChunk: false,
29
- sessionTraceMode: MODE.OFF,
28
+ sessionTraceMode: null,
30
29
  traceHarvestStarted: false,
31
- loggingMode: LOGGING_MODE.OFF,
32
- logApiMode: LOGGING_MODE.OFF,
30
+ loggingMode: null,
31
+ logApiMode: null,
33
32
  serverTimeDiff: null, // set by TimeKeeper; "undefined" value will not be stringified and stored but "null" will
34
33
  custom: {},
35
34
  numOfResets: 0,
36
- consent: false // set by consent() API call
35
+ consent: false, // set by consent() API call
36
+ cachedRumResponse: null
37
37
  }
38
38
 
39
39
  export class SessionEntity {
@@ -242,7 +242,6 @@ export class SessionEntity {
242
242
  delete this.isNew
243
243
 
244
244
  this.setup({
245
- agentRef: this.agentRef,
246
245
  key: this.key,
247
246
  storage: this.storage,
248
247
  expiresMs: this.expiresMs,
@@ -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
 
@@ -12,7 +12,7 @@ import { stringify } from './stringify'
12
12
  * @returns {(number|undefined)} - The size of the data or undefined if size cannot be determined.
13
13
  */
14
14
  export function dataSize (data) {
15
- if (typeof data === 'string' && data.length) return data.length
15
+ if (typeof data === 'string') return data.length
16
16
  if (typeof data !== 'object') return undefined
17
17
  // eslint-disable-next-line
18
18
  if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer && data.byteLength) return data.byteLength
@@ -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 { isFileProtocol } from '../url/protocol'
@@ -10,6 +10,7 @@ import { warn } from './console'
10
10
  * @typedef {object} ObfuscationRule
11
11
  * @property {string|RegExp} regex The regular expression to match against in the payload
12
12
  * @property {string} [replacement] The string to replace the matched regex with
13
+ * @property {string[]} [eventFilter] An optional list of event types to which this rule should be applied. If not provided, or an empty array, the rule will be applied to all events.
13
14
  */
14
15
 
15
16
  /**
@@ -24,15 +25,34 @@ import { warn } from './console'
24
25
  */
25
26
 
26
27
  export class Obfuscator {
27
- constructor (agentRef) {
28
+ /**
29
+ * @param {Object} agentRef - Reference to the agent instance
30
+ * @param {string} [eventType] - Optional event type this obfuscator instance handles.
31
+ * If provided, only rules matching this event type (or rules with no eventFilter) will be applied.
32
+ */
33
+ constructor (agentRef, eventType) {
28
34
  this.agentRef = agentRef
35
+ this.eventType = eventType
29
36
  this.warnedRegexMissing = false
30
37
  this.warnedInvalidRegex = false
31
38
  this.warnedInvalidReplacement = false
32
39
  }
33
40
 
34
41
  get obfuscateConfigRules () {
35
- return this.agentRef.init.obfuscate || []
42
+ const allRules = this.agentRef.init.obfuscate || []
43
+
44
+ // If this instance has no specific event type, return all rules
45
+ if (!this.eventType) return allRules
46
+
47
+ // Filter rules to only those that apply to this instance's event type
48
+ return allRules.filter(rule => {
49
+ // If rule has no eventFilter, it applies to all events
50
+ if (!this.#hasValidEventFilter(rule)) {
51
+ return true
52
+ }
53
+ // Otherwise, check if this instance's event type matches the rule's filter
54
+ return rule.eventFilter.includes(this.eventType)
55
+ })
36
56
  }
37
57
 
38
58
  /**
@@ -60,6 +80,137 @@ export class Obfuscator {
60
80
  }, input)
61
81
  }
62
82
 
83
+ /**
84
+ * Traverses an object and obfuscates all string properties.
85
+ * This instance will only apply rules that match its configured event type (if any).
86
+ * For features with mixed event types in their payloads (like generic_events), this will
87
+ * traverse the object and check each object's eventType property against the rules.
88
+ * @param {Object|Array} obj - The object or array to traverse
89
+ * @returns {Object|Array} The modified object
90
+ */
91
+ traverseAndObfuscateEvents (obj) {
92
+ if (!obj || typeof obj !== 'object') return obj
93
+
94
+ // If this instance was configured with a specific event type, obfuscate everything
95
+ // (rules are already filtered in obfuscateConfigRules getter)
96
+ if (this.eventType) {
97
+ this.#applyFnToAllStrings(obj, this.obfuscateString.bind(this))
98
+ return obj
99
+ }
100
+
101
+ // For generic obfuscators (no specific event types), check individual eventType properties
102
+ // This path is for features like generic_events that handle multiple event types
103
+ const eventTypesToObfuscate = new Set()
104
+ const globalRules = []
105
+ const eventSpecificRules = []
106
+
107
+ this.obfuscateConfigRules.forEach(rule => {
108
+ if (this.#hasValidEventFilter(rule)) {
109
+ eventSpecificRules.push(rule)
110
+ rule.eventFilter.forEach(eventType => eventTypesToObfuscate.add(eventType))
111
+ } else {
112
+ globalRules.push(rule)
113
+ }
114
+ })
115
+
116
+ // Optimization: if ALL rules are global (no event-specific rules exist),
117
+ // we can just apply all rules to everything without checking eventType properties
118
+ if (eventSpecificRules.length === 0) {
119
+ this.#applyFnToAllStrings(obj, this.obfuscateString.bind(this))
120
+ return obj
121
+ }
122
+
123
+ // We have a mix of global and event-specific rules:
124
+ // - Apply event-specific rules only to matching eventTypes
125
+ // - Apply global rules to ALL event types
126
+ this.#applyFnWithEventTypeFilter(obj, this.obfuscateString.bind(this), Array.from(eventTypesToObfuscate), globalRules, null)
127
+ return obj
128
+ }
129
+
130
+ /**
131
+ * Recursively applies a function to all string properties in an object.
132
+ * @param {Object|Array} obj - The object or array to traverse
133
+ * @param {Function} fn - The function to apply to string properties
134
+ * @private
135
+ */
136
+ #applyFnToAllStrings (obj, fn) {
137
+ if (!obj || typeof obj !== 'object') return
138
+
139
+ Object.keys(obj).forEach(property => {
140
+ const value = obj[property]
141
+
142
+ if (typeof value === 'object' && value !== null) {
143
+ this.#applyFnToAllStrings(value, fn)
144
+ } else if (typeof value === 'string') {
145
+ obj[property] = fn(value)
146
+ }
147
+ })
148
+ }
149
+
150
+ /**
151
+ * Recursively applies a function to string properties based on eventType filtering.
152
+ * @param {Object|Array} obj - The object or array to traverse
153
+ * @param {Function} fn - The function to apply to string properties (applies all rules)
154
+ * @param {string[]} eventTypes - Array of event types to apply event-specific obfuscation
155
+ * @param {Array} globalRules - Rules without eventFilter that apply to all events
156
+ * @param {boolean|null} shouldObfuscate - Track obfuscation state: null = not determined yet, true = obfuscate with all rules, false = obfuscate with global rules only
157
+ * @private
158
+ */
159
+ #applyFnWithEventTypeFilter (obj, fn, eventTypes, globalRules, shouldObfuscate) {
160
+ if (!obj || typeof obj !== 'object') return
161
+
162
+ // Determine the obfuscation state for this object
163
+ let currentShouldObfuscate = shouldObfuscate
164
+
165
+ // Check if this object has an eventType property
166
+ if ('eventType' in obj && typeof obj.eventType === 'string') {
167
+ currentShouldObfuscate = eventTypes.includes(obj.eventType)
168
+ }
169
+
170
+ // Process all properties
171
+ Object.keys(obj).forEach(property => {
172
+ const value = obj[property]
173
+
174
+ if (typeof value === 'object' && value !== null) {
175
+ // Recursively traverse objects/arrays, passing the current obfuscation state
176
+ this.#applyFnWithEventTypeFilter(value, fn, eventTypes, globalRules, currentShouldObfuscate)
177
+ } else if (typeof value === 'string') {
178
+ if (currentShouldObfuscate === true) {
179
+ // Apply all rules (both global and event-specific)
180
+ obj[property] = fn(value)
181
+ } else if (currentShouldObfuscate === false && globalRules.length > 0) {
182
+ // Apply only global rules
183
+ obj[property] = this.#applyRulesToString(value, globalRules)
184
+ }
185
+ // If currentShouldObfuscate is null, we haven't found an eventType yet, so don't obfuscate
186
+ }
187
+ })
188
+ }
189
+
190
+ /**
191
+ * Applies specific obfuscation rules to a string.
192
+ * @param {string} input - The string to obfuscate
193
+ * @param {Array} rules - The rules to apply
194
+ * @returns {string} The obfuscated string
195
+ * @private
196
+ */
197
+ #applyRulesToString (input, rules) {
198
+ if (typeof input !== 'string' || input.trim().length === 0) return input
199
+
200
+ const validatedRules = rules.map(rule => this.validateObfuscationRule(rule))
201
+
202
+ return validatedRules
203
+ .filter(ruleValidation => ruleValidation.isValid)
204
+ .reduce((input, ruleValidation) => {
205
+ const { rule } = ruleValidation
206
+ return input.replace(rule.regex, rule.replacement || '*')
207
+ }, input)
208
+ }
209
+
210
+ #hasValidEventFilter (rule) {
211
+ return Array.isArray(rule?.eventFilter) && rule.eventFilter.length > 0
212
+ }
213
+
63
214
  /**
64
215
  * Validates an obfuscation rule and provides errors if any are found.
65
216
  * @param {ObfuscationRule} rule The rule to validate