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,SAAU,EACzB,CAACs4D,EAAcnwD,UAAW,EAC1B,CAACmwD,EAAcluD,KAAM,EACrB,CAACkuD,EAAclxD,MAAO,EACtB,CAACkxD,EAAclpC,cAAe,EAC9B,CAACkpC,EAAcnoC,SAAU,EACzB,CAACmoC,EAAcz/B,eAAgB,EAC/B,CAACy/B,EAAclwD,SAAU,GACzB,CAACkwD,EAAcxjC,eAAgB,IAEpB2jC,EAAsB,CACjC,CAACH,EAActxB,gBAAiB,SAChC,CAACsxB,EAAclxD,MAAO,SACtB,CAACkxD,EAAcluD,KAAM,SACrB,CAACkuD,EAAcnoC,SAAU,SACzB,CAACmoC,EAAct4D,SAAU,WACzB,CAACs4D,EAAcnwD,UAAW,WAC1B,CAACmwD,EAAclpC,cAAe,gBAC9B,CAACkpC,EAAcz/B,eAAgB,gBAC/B,CAACy/B,EAAclwD,SAAU,eACzB,CAACkwD,EAAcxjC,eAAgB,M","sources":["webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/aggregate/aggregator.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/aggregate/event-aggregator.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/config/configurable.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/config/info.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/dom/query-selector.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/config/init.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/config/loader-config.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/config/runtime.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/constants/agent-constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/constants/env.npm.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/constants/runtime.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/context/shared-context.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/deny-list/deny-list.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/dom/iframe.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/drain/drain.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/event-emitter/contextual-ee.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/event-emitter/event-context.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/event-emitter/handle.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/event-emitter/register-handler.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/event-listener/event-listener-opts.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/unload/eol.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/harvest/harvest-scheduler.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/harvest/harvest.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/url/location.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/ids/bundle-id.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/ids/unique-id.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/serialize/bel-serializer.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/session/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/timing/nav-timing.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/timing/now.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/url/clean-url.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/url/encode.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/url/parse-url.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/url/protocol.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/console.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/dispatch/global-event.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/feature-flags.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/get-or-set.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/invoke.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/stringify.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/submit-data.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/traverse.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/first-contentful-paint.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/first-paint.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/time-to-first-byte.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/vital-metric.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/window/load.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/window/nreum.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/window/page-visibility.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-events.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-function.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/ajax/aggregate/gql.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/type-check.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/ajax/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/ajax/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/generic_events/aggregate/user-actions/aggregated-user-action.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/generic_events/aggregate/user-actions/user-actions-aggregator.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/dom/selector-path.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/generic_events/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/generic_events/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/aggregate/canonical-function-name.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/aggregate/format-stack-trace.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/url/canonicalize-url.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/aggregate/compute-stack-trace.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/aggregate/string-hash-code.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/aggregate/internal-errors.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/logging/shared/log.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/logging/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/logging/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/logging/shared/utils.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/metrics/aggregate/framework-detection.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/metrics/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/metrics/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_event/aggregate/initialized-features.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/timing/time-keeper.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_event/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_event/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/cumulative-layout-shift.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/first-input-delay.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/interaction-to-next-paint.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/vitals/largest-contentful-paint.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_timing/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_timing/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/constants/shared-channel.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/shared/recorder-events.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/shared/recorder.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/shared/stylesheet-evaluator.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/shared/utils.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_trace/aggregate/trace/node.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_trace/aggregate/trace/storage.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_trace/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_trace/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/aggregate/bel-node.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/aggregate/ajax-node.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/aggregate/interaction.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/aggregate/initial-page-load-interaction.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/spa/aggregate/interaction-node.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/spa/aggregate/interaction.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/spa/aggregate/serializer.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/spa/aggregate/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/spa/constants.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/timer/timer.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/timer/interaction-timer.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/session/session-entity.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/storage/local-storage.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/agent-session.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/obfuscate.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/aggregate-base.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/event-buffer.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/feature-base.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/feature-gates.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/lazy-feature-loader.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/api/apiAsync.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/micro-agent-base.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/agent-base.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/features/enabled-features.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/utils/instrument-base.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_event/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/agent.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/features/featureDependencies.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/page_view_timing/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/metrics/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/shared/uncaught-error.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/shared/cast-error.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/jserrors/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/ids/id.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/util/data-size.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-xhr.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-fetch.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/ajax/instrument/distributed-tracing.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/ajax/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/ajax/instrument/response-size.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-history.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_trace/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-jsonp.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-promise.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-timer.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-mutation.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/spa/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/session_replay/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/generic_events/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/logging/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/features/soft_navigations/instrument/index.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/browser-agent.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/api/api-methods.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/common/wrap/wrap-logger.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/api/api.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/configure/public-path.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/configure/configure.js","webpack:///../node_modules/@newrelic/browser-agent/dist/esm/loaders/features/features.js"],"sourcesContent":["/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nexport class Aggregator {\n constructor() {\n this.aggregatedData = {};\n }\n\n // Items with the same type and name get aggregated together\n // params are example data from the aggregated items\n // metrics are the numeric values to be aggregated\n\n store(type, name, params, newMetrics, customParams) {\n var bucket = this.#getBucket(type, name, params, customParams);\n bucket.metrics = aggregateMetrics(newMetrics, bucket.metrics);\n return bucket;\n }\n merge(type, name, metrics, params, customParams, overwriteParams = false) {\n var bucket = this.#getBucket(type, name, params, customParams);\n if (overwriteParams) bucket.params = params; // replace current params with incoming params obj\n\n if (!bucket.metrics) {\n bucket.metrics = metrics;\n return;\n }\n var oldMetrics = bucket.metrics;\n oldMetrics.count += metrics.count;\n\n // iterate through each new metric and merge\n Object.keys(metrics || {}).forEach(key => {\n // count is a special case handled above\n if (key === 'count') return;\n var oldMetric = oldMetrics[key];\n var newMetric = metrics[key];\n\n // handling the case where newMetric is a single-value first\n if (newMetric && !newMetric.c) {\n oldMetrics[key] = updateMetric(newMetric.t, oldMetric);\n } else {\n // newMetric is a metric object\n oldMetrics[key] = mergeMetric(newMetric, oldMetrics[key]);\n }\n });\n }\n storeMetric(type, name, params, value) {\n var bucket = this.#getBucket(type, name, params);\n bucket.stats = updateMetric(value, bucket.stats);\n return bucket;\n }\n\n // Get all listed types buckets and it deletes the retrieved content from the aggregatedData\n take(types, deleteWhenRetrieved = true) {\n var results = {};\n var type = '';\n var hasData = false;\n for (var i = 0; i < types.length; i++) {\n type = types[i];\n results[type] = Object.values(this.aggregatedData[type] || {});\n if (results[type].length) hasData = true;\n if (deleteWhenRetrieved) delete this.aggregatedData[type];\n }\n return hasData ? results : null;\n }\n #getBucket(type, name, params, customParams) {\n if (!this.aggregatedData[type]) this.aggregatedData[type] = {};\n var bucket = this.aggregatedData[type][name];\n if (!bucket) {\n bucket = this.aggregatedData[type][name] = {\n params: params || {}\n };\n if (customParams) {\n bucket.custom = customParams;\n }\n }\n return bucket;\n }\n}\nfunction aggregateMetrics(newMetrics, oldMetrics) {\n if (!oldMetrics) oldMetrics = {\n count: 0\n };\n oldMetrics.count += 1;\n Object.entries(newMetrics || {}).forEach(([key, value]) => {\n oldMetrics[key] = updateMetric(value, oldMetrics[key]);\n });\n return oldMetrics;\n}\nfunction updateMetric(value, metric) {\n // when there is no value, then send only count\n if (value == null) {\n return updateCounterMetric(metric);\n }\n\n // When there is only one data point, the c (count), min, max, and sos (sum of squares) params are superfluous.\n if (!metric) return {\n t: value\n };\n\n // but on the second data point, we need to calculate the other values before aggregating in new values\n if (!metric.c) {\n metric = createMetricObject(metric.t);\n }\n\n // at this point, metric is always uncondensed\n metric.c += 1;\n metric.t += value;\n metric.sos += value * value;\n if (value > metric.max) metric.max = value;\n if (value < metric.min) metric.min = value;\n return metric;\n}\nfunction updateCounterMetric(metric) {\n if (!metric) {\n metric = {\n c: 1\n };\n } else {\n metric.c++;\n }\n return metric;\n}\nfunction mergeMetric(newMetric, oldMetric) {\n if (!oldMetric) return newMetric;\n if (!oldMetric.c) {\n // oldMetric is a single-value\n oldMetric = createMetricObject(oldMetric.t);\n }\n oldMetric.min = Math.min(newMetric.min, oldMetric.min);\n oldMetric.max = Math.max(newMetric.max, oldMetric.max);\n oldMetric.t += newMetric.t;\n oldMetric.sos += newMetric.sos;\n oldMetric.c += newMetric.c;\n return oldMetric;\n}\n\n// take a value and create a metric object\nfunction createMetricObject(value) {\n return {\n t: value,\n min: value,\n max: value,\n sos: value * value,\n c: 1\n };\n}","import { Aggregator } from './aggregator';\n\n/**\n * An extension of the Aggregator class that provides an interface similar to that of EventBuffer class.\n * This typecasting allow features that uses Aggregator as their event handler to share the same AggregateBase.events utilization by those features.\n */\nexport class EventAggregator {\n #aggregator = new Aggregator();\n #savedNamesToBuckets = {};\n isEmpty({\n aggregatorTypes\n }) {\n if (!aggregatorTypes) return Object.keys(this.#aggregator.aggregatedData).length === 0;\n return aggregatorTypes.every(type => !this.#aggregator.aggregatedData[type]); // no bucket exist for any of the types we're looking for\n }\n add(type, name, params, newMetrics, customParams) {\n // Do we need to track byte size here like EventBuffer?\n this.#aggregator.store(type, name, params, newMetrics, customParams);\n return true;\n }\n addMetric(type, name, params, value) {\n this.#aggregator.storeMetric(type, name, params, value);\n return true;\n }\n save({\n aggregatorTypes\n }) {\n const key = aggregatorTypes.toString(); // the stringified types serve as the key to each save call, e.g. ['err', 'ierr', 'xhr'] => 'err,ierr,xhr'\n const backupAggregatedDataSubset = {};\n aggregatorTypes.forEach(type => backupAggregatedDataSubset[type] = this.#aggregator.aggregatedData[type]); // make a subset of the aggregatedData for each of the types we want to save\n this.#savedNamesToBuckets[key] = backupAggregatedDataSubset;\n /*\n { 'err,ierr,xhr': {\n 'err': {\n : { metrics: { count: 1, time, ... }, params: {}, custom: {} },\n : { metrics: { count: 1, ... }, ... }\n },\n 'ierr': { ... },\n 'xhr': { ... }\n }\n }\n */\n }\n get(opts) {\n const aggregatorTypes = Array.isArray(opts) ? opts : opts.aggregatorTypes;\n return this.#aggregator.take(aggregatorTypes, false);\n }\n clear({\n aggregatorTypes\n } = {}) {\n if (!aggregatorTypes) {\n this.#aggregator.aggregatedData = {};\n return;\n }\n aggregatorTypes.forEach(type => delete this.#aggregator.aggregatedData[type]);\n }\n reloadSave({\n aggregatorTypes\n }) {\n const key = aggregatorTypes.toString();\n const backupAggregatedDataSubset = this.#savedNamesToBuckets[key];\n // Grabs the previously stored subset and merge it back into aggregatedData.\n aggregatorTypes.forEach(type => {\n Object.keys(backupAggregatedDataSubset[type] || {}).forEach(name => {\n const bucket = backupAggregatedDataSubset[type][name];\n // The older aka saved params take effect over the newer one. This is especially important when merging back for a failed harvest retry if, for example,\n // the first-ever occurrence of an error is in the retry: it contains the params.stack_trace whereas the newer or current bucket.params would not.\n this.#aggregator.merge(type, name, bucket.metrics, bucket.params, bucket.custom, true);\n });\n });\n }\n clearSave({\n aggregatorTypes\n }) {\n const key = aggregatorTypes.toString();\n delete this.#savedNamesToBuckets[key];\n }\n}","import { warn } from '../util/console';\nexport function getModeledObject(obj, model) {\n try {\n if (!obj || typeof obj !== 'object') return warn(3);\n if (!model || typeof model !== 'object') return warn(4);\n // allow getters and setters to pass from model to target\n const output = Object.create(Object.getPrototypeOf(model), Object.getOwnPropertyDescriptors(model));\n const target = Object.keys(output).length === 0 ? obj : output;\n for (let key in target) {\n if (obj[key] === undefined) continue;\n try {\n if (obj[key] === null) {\n output[key] = null;\n continue;\n }\n if (Array.isArray(obj[key]) && Array.isArray(model[key])) output[key] = Array.from(new Set([...obj[key], ...model[key]]));else if (typeof obj[key] === 'object' && typeof model[key] === 'object') output[key] = getModeledObject(obj[key], model[key]);else output[key] = obj[key];\n } catch (e) {\n warn(1, e);\n }\n }\n return output;\n } catch (err) {\n warn(2, err);\n }\n}","import { defaults as nrDefaults, getNREUMInitializedAgent } from '../window/nreum';\nimport { getModeledObject } from './configurable';\nconst model = {\n // preset defaults\n beacon: nrDefaults.beacon,\n errorBeacon: nrDefaults.errorBeacon,\n // others must be populated by user\n licenseKey: undefined,\n applicationID: undefined,\n sa: undefined,\n queueTime: undefined,\n applicationTime: undefined,\n ttGuid: undefined,\n user: undefined,\n account: undefined,\n product: undefined,\n extra: undefined,\n jsAttributes: {},\n userAttributes: undefined,\n atts: undefined,\n transactionName: undefined,\n tNamePlain: undefined\n};\nconst _cache = {};\nexport function isValid(id) {\n try {\n const info = getInfo(id);\n return !!info.licenseKey && !!info.errorBeacon && !!info.applicationID;\n } catch (err) {\n return false;\n }\n}\nexport function getInfo(id) {\n if (!id) throw new Error('All info objects require an agent identifier!');\n if (!_cache[id]) throw new Error(\"Info for \".concat(id, \" was never set\"));\n return _cache[id];\n}\nexport function setInfo(id, obj) {\n if (!id) throw new Error('All info objects require an agent identifier!');\n _cache[id] = getModeledObject(obj, model);\n const agentInst = getNREUMInitializedAgent(id);\n if (agentInst) agentInst.info = _cache[id];\n}","export const isValidSelector = selector => {\n if (!selector || typeof selector !== 'string') return false;\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch {\n return false;\n }\n return true;\n};","import { LOG_LEVELS } from '../../features/logging/constants';\nimport { isValidSelector } from '../dom/query-selector';\nimport { DEFAULT_EXPIRES_MS, DEFAULT_INACTIVE_MS } from '../session/constants';\nimport { warn } from '../util/console';\nimport { getNREUMInitializedAgent } from '../window/nreum';\nimport { getModeledObject } from './configurable';\nconst nrMask = '[data-nr-mask]';\nconst model = () => {\n const hiddenState = {\n mask_selector: '*',\n block_selector: '[data-nr-block]',\n mask_input_options: {\n color: false,\n date: false,\n 'datetime-local': false,\n email: false,\n month: false,\n number: false,\n range: false,\n search: false,\n tel: false,\n text: false,\n time: false,\n url: false,\n week: false,\n // unify textarea and select element with text input\n textarea: false,\n select: false,\n password: true // This will be enforced to always be true in the setter\n }\n };\n return {\n ajax: {\n deny_list: undefined,\n block_internal: true,\n enabled: true,\n harvestTimeSeconds: 10,\n autoStart: true\n },\n distributed_tracing: {\n enabled: undefined,\n exclude_newrelic_header: undefined,\n cors_use_newrelic_header: undefined,\n cors_use_tracecontext_headers: undefined,\n allowed_origins: undefined\n },\n feature_flags: [],\n generic_events: {\n enabled: true,\n harvestTimeSeconds: 30,\n autoStart: true\n },\n harvest: {\n tooManyRequestsDelay: 60\n },\n jserrors: {\n enabled: true,\n harvestTimeSeconds: 10,\n autoStart: true\n },\n logging: {\n enabled: true,\n harvestTimeSeconds: 10,\n autoStart: true,\n level: LOG_LEVELS.INFO\n },\n metrics: {\n enabled: true,\n autoStart: true\n },\n obfuscate: undefined,\n page_action: {\n enabled: true\n },\n page_view_event: {\n enabled: true,\n autoStart: true\n },\n page_view_timing: {\n enabled: true,\n harvestTimeSeconds: 30,\n autoStart: true\n },\n performance: {\n capture_marks: false,\n capture_measures: false // false by default through experimental phase, but flipped to true once GA'd\n },\n privacy: {\n cookies_enabled: true\n },\n // *cli - per discussion, default should be true\n proxy: {\n assets: undefined,\n // if this value is set, it will be used to overwrite the webpack asset path used to fetch assets\n beacon: undefined // likewise for the url to which we send analytics\n },\n session: {\n expiresMs: DEFAULT_EXPIRES_MS,\n inactiveMs: DEFAULT_INACTIVE_MS\n },\n session_replay: {\n // feature settings\n autoStart: true,\n enabled: false,\n harvestTimeSeconds: 60,\n preload: false,\n // if true, enables the agent to load rrweb immediately instead of waiting to do so after the window.load event\n sampling_rate: 10,\n // float from 0 - 100\n error_sampling_rate: 100,\n // float from 0 - 100\n collect_fonts: false,\n // serialize fonts for collection without public asset url, this is currently broken in RRWeb -- https://github.com/rrweb-io/rrweb/issues/1304. When fixed, revisit with test cases\n inline_images: false,\n // serialize images for collection without public asset url -- right now this is only useful for testing as it easily generates payloads too large to be harvested\n fix_stylesheets: true,\n // fetch missing stylesheet resources for inlining\n // recording config settings\n mask_all_inputs: true,\n // this has a getter/setter to facilitate validation of the selectors\n get mask_text_selector() {\n return hiddenState.mask_selector;\n },\n set mask_text_selector(val) {\n if (isValidSelector(val)) hiddenState.mask_selector = \"\".concat(val, \",\").concat(nrMask);else if (val === '' || val === null) hiddenState.mask_selector = nrMask;else warn(5, val);\n },\n // these properties only have getters because they are enforcable constants and should error if someone tries to override them\n get block_class() {\n return 'nr-block';\n },\n get ignore_class() {\n return 'nr-ignore';\n },\n get mask_text_class() {\n return 'nr-mask';\n },\n // props with a getter and setter are used to extend enforcable constants with customer input\n // we must preserve data-nr-block no matter what else the customer sets\n get block_selector() {\n return hiddenState.block_selector;\n },\n set block_selector(val) {\n if (isValidSelector(val)) hiddenState.block_selector += \",\".concat(val);else if (val !== '') warn(6, val);\n },\n // password: must always be present and true no matter what customer sets\n get mask_input_options() {\n return hiddenState.mask_input_options;\n },\n set mask_input_options(val) {\n if (val && typeof val === 'object') hiddenState.mask_input_options = {\n ...val,\n password: true\n };else warn(7, val);\n }\n },\n session_trace: {\n enabled: true,\n harvestTimeSeconds: 10,\n autoStart: true\n },\n soft_navigations: {\n enabled: true,\n harvestTimeSeconds: 10,\n autoStart: true\n },\n spa: {\n enabled: true,\n harvestTimeSeconds: 10,\n autoStart: true\n },\n ssl: undefined,\n user_actions: {\n enabled: true\n }\n };\n};\nconst _cache = {};\nconst missingAgentIdError = 'All configuration objects require an agent identifier!';\nexport function getConfiguration(id) {\n if (!id) throw new Error(missingAgentIdError);\n if (!_cache[id]) throw new Error(\"Configuration for \".concat(id, \" was never set\"));\n return _cache[id];\n}\nexport function setConfiguration(id, obj) {\n if (!id) throw new Error(missingAgentIdError);\n _cache[id] = getModeledObject(obj, model());\n const agentInst = getNREUMInitializedAgent(id);\n if (agentInst) agentInst.init = _cache[id];\n}\nexport function getConfigurationValue(id, path) {\n if (!id) throw new Error(missingAgentIdError);\n var val = getConfiguration(id);\n if (val) {\n var parts = path.split('.');\n for (var i = 0; i < parts.length - 1; i++) {\n val = val[parts[i]];\n if (typeof val !== 'object') return;\n }\n val = val[parts[parts.length - 1]];\n }\n return val;\n}\n\n// TO DO: a setConfigurationValue equivalent may be nice so individual\n// properties can be tuned instead of reseting the whole model per call to `setConfiguration(agentIdentifier, {})`","import { getNREUMInitializedAgent } from '../window/nreum';\nimport { getModeledObject } from './configurable';\nconst model = {\n accountID: undefined,\n trustKey: undefined,\n agentID: undefined,\n licenseKey: undefined,\n applicationID: undefined,\n xpid: undefined\n};\nconst _cache = {};\nexport function getLoaderConfig(id) {\n if (!id) throw new Error('All loader-config objects require an agent identifier!');\n if (!_cache[id]) throw new Error(\"LoaderConfig for \".concat(id, \" was never set\"));\n return _cache[id];\n}\nexport function setLoaderConfig(id, obj) {\n if (!id) throw new Error('All loader-config objects require an agent identifier!');\n _cache[id] = getModeledObject(obj, model);\n const agentInst = getNREUMInitializedAgent(id);\n if (agentInst) agentInst.loader_config = _cache[id];\n}","import { getModeledObject } from './configurable';\nimport { getNREUMInitializedAgent } from '../window/nreum';\nimport { originTime } from '../constants/runtime';\nimport { BUILD_ENV, DIST_METHOD, VERSION } from \"../constants/env.npm\";\n\n/**\n * Module level count of harvests. This property will auto-increment each time it is accessed.\n * @type {number}\n */\nlet harvestCount = 0;\nconst readonly = {\n buildEnv: BUILD_ENV,\n distMethod: DIST_METHOD,\n version: VERSION,\n originTime\n};\nconst model = {\n customTransaction: undefined,\n disabled: false,\n isolatedBacklog: false,\n loaderType: undefined,\n maxBytes: 30000,\n onerror: undefined,\n ptid: undefined,\n releaseIds: {},\n /** Agent-specific metadata found in the RUM call response. ex. entityGuid */\n appMetadata: {},\n session: undefined,\n denyList: undefined,\n timeKeeper: undefined,\n obfuscator: undefined\n};\nconst _cache = {};\nexport function getRuntime(id) {\n if (!id) throw new Error('All runtime objects require an agent identifier!');\n if (!_cache[id]) throw new Error(\"Runtime for \".concat(id, \" was never set\"));\n return _cache[id];\n}\nexport function setRuntime(id, obj) {\n if (!id) throw new Error('All runtime objects require an agent identifier!');\n _cache[id] = {\n ...getModeledObject(obj, model),\n ...readonly\n };\n if (!Object.hasOwnProperty.call(_cache[id], 'harvestCount')) {\n // Harvest count needs to be added as a getter so the variable is updated each time it is accessed\n Object.defineProperty(_cache[id], 'harvestCount', {\n get: () => ++harvestCount\n });\n }\n const agentInst = getNREUMInitializedAgent(id);\n if (agentInst) agentInst.runtime = _cache[id];\n}","export const IDEAL_PAYLOAD_SIZE = 64000;\nexport const MAX_PAYLOAD_SIZE = 1000000;","/**\n * @file This file exposes NPM build environment variables. These variables will\n * be overridden with babel.\n */\n\n/**\n * Exposes the version of the agent\n */\nexport const VERSION = \"1.274.0\";\n\n/**\n * Exposes the build type of the agent\n * Valid values are LOCAL, PROD, DEV\n */\nexport const BUILD_ENV = 'NPM';\n\n/**\n * Exposes the distribution method of the agent\n * Valid valuse are CDN, NPM\n */\nexport const DIST_METHOD = 'NPM';\n\n/**\n * Exposes the lib version of rrweb\n */\nexport const RRWEB_VERSION = \"^2.0.0-alpha.17\";","/**\n * @file Contains constants about the environment the agent is running\n * within. These values are derived at the time the agent is first loaded.\n * @copyright 2023 New Relic Corporation. All rights reserved.\n * @license Apache-2.0\n */\n\nimport { now } from '../timing/now';\n\n/**\n * Indicates if the agent is running within a normal browser window context.\n */\nexport const isBrowserScope = typeof window !== 'undefined' && !!window.document;\n\n/**\n * Indicates if the agent is running within a worker context.\n */\nexport const isWorkerScope = typeof WorkerGlobalScope !== 'undefined' && (typeof self !== 'undefined' && self instanceof WorkerGlobalScope && self.navigator instanceof WorkerNavigator || typeof globalThis !== 'undefined' && globalThis instanceof WorkerGlobalScope && globalThis.navigator instanceof WorkerNavigator);\nexport const globalScope = isBrowserScope ? window : typeof WorkerGlobalScope !== 'undefined' && (typeof self !== 'undefined' && self instanceof WorkerGlobalScope && self || typeof globalThis !== 'undefined' && globalThis instanceof WorkerGlobalScope && globalThis);\nexport const loadedAsDeferredBrowserScript = globalScope?.document?.readyState === 'complete';\nexport const initiallyHidden = Boolean(globalScope?.document?.visibilityState === 'hidden');\nexport const initialLocation = '' + globalScope?.location;\nexport const isiOS = /iPad|iPhone|iPod/.test(globalScope.navigator?.userAgent);\n\n/**\n * Shared Web Workers introduced in iOS 16.0+ and n/a in 15.6-\n *\n * It was discovered in Safari 14 (https://bugs.webkit.org/show_bug.cgi?id=225305) that the buffered flag in PerformanceObserver\n * did not work. This affects our onFCP metric in particular since web-vitals uses that flag to retrieve paint timing entries.\n * This was fixed in v16+.\n */\nexport const iOSBelow16 = isiOS && typeof SharedWorker === 'undefined';\nexport const ffVersion = (() => {\n const match = globalScope.navigator?.userAgent?.match(/Firefox[/\\s](\\d+\\.\\d+)/);\n if (Array.isArray(match) && match.length >= 2) {\n return +match[1];\n }\n return 0;\n})();\n\n/**\n * Represents the absolute timestamp in milliseconds that the page was loaded\n * according to the browser's local clock.\n * @type {number}\n */\nexport const originTime = Date.now() - now();","import { warn } from '../util/console';\nconst model = {\n agentIdentifier: '',\n ee: undefined\n};\nexport class SharedContext {\n constructor(context) {\n try {\n if (typeof context !== 'object') return warn(8);\n this.sharedContext = {};\n Object.assign(this.sharedContext, model);\n Object.entries(context).forEach(([key, value]) => {\n if (Object.keys(model).includes(key)) this.sharedContext[key] = value;\n });\n } catch (err) {\n warn(9, err);\n }\n }\n}","/** An array of filter objects {hostname, pathname} for identifying XHR events to be excluded from collection.\n * @see {@link https://docs.newrelic.com/docs/browser/new-relic-browser/configuration/filter-ajax-request-events/ Filter AjaxRequest events}\n * @type {Array.<{hostname: string, pathname: string}>}\n */\nvar denyList = [];\n\n/**\n * Evaluates whether an XHR event should be included for collection based on the {@link denyList|AjaxRequest deny list}.\n * @param {Object} params - object with properties of the XHR event\n * @returns {boolean} `true` if request does not match any entries of {@link denyList|deny list}; else `false`\n */\nexport function shouldCollectEvent(params) {\n if (!params || hasUndefinedHostname(params)) return false;\n if (denyList.length === 0) return true;\n for (var i = 0; i < denyList.length; i++) {\n var parsed = denyList[i];\n if (parsed.hostname === '*') {\n return false;\n }\n if (domainMatchesPattern(parsed.hostname, params.hostname) && comparePath(parsed.pathname, params.pathname)) {\n return false;\n }\n }\n return true;\n}\nexport function hasUndefinedHostname(params) {\n return params.hostname === undefined; // requests with an undefined hostname (e.g., data URLs) should not be collected.\n}\n\n/**\n * Initializes the {@link denyList|XHR deny list} by extracting hostname and pathname from an array of filter strings.\n * @param {string[]} denyListConfig - array of URL filters to identify XHR requests to be excluded from collection\n */\nexport function setDenyList(denyListConfig) {\n denyList = [];\n if (!denyListConfig || !denyListConfig.length) {\n return;\n }\n for (var i = 0; i < denyListConfig.length; i++) {\n let url = denyListConfig[i];\n if (!url) continue; // ignore bad values like undefined or empty strings\n\n if (url.indexOf('http://') === 0) {\n url = url.substring(7);\n } else if (url.indexOf('https://') === 0) {\n url = url.substring(8);\n }\n const firstSlash = url.indexOf('/');\n let host, pathname;\n if (firstSlash > 0) {\n host = url.substring(0, firstSlash);\n pathname = url.substring(firstSlash);\n } else {\n host = url;\n pathname = '';\n }\n let [hostname] = host.split(':');\n denyList.push({\n hostname,\n pathname\n });\n }\n}\n/**\n * Returns true if the right side of `domain` (end of string) matches `pattern`.\n * @param {string} pattern - a string to be matched against the end of `domain` string\n * @param {string} domain - a domain string with no protocol or path (e.g., app1.example.com)\n * @returns {boolean} `true` if domain matches pattern; else `false`\n */\nfunction domainMatchesPattern(pattern, domain) {\n if (pattern.length > domain.length) {\n return false;\n }\n return domain.indexOf(pattern) === domain.length - pattern.length;\n}\n\n/**\n * Returns true if a URL path matches a pattern string, disregarding leading slashes.\n * @param {string} pattern - a string to compare with path (e.g., api/v1)\n * @param {string} path - a string representing a URL path (e.g., /api/v1)\n * @returns {boolean} `true` if path and pattern are an exact string match (except for leading slashes); else `false`\n */\nfunction comparePath(pattern, path) {\n if (pattern.indexOf('/') === 0) {\n pattern = pattern.substring(1);\n }\n if (path.indexOf('/') === 0) {\n path = path.substring(1);\n }\n\n // No path in pattern means match all paths.\n if (pattern === '') {\n return true;\n }\n return pattern === path;\n}","export function isIFrameWindow(windowObject) {\n if (!windowObject) return false;\n return windowObject.self !== windowObject.top;\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ee } from '../event-emitter/contextual-ee';\nimport { registerHandler as defaultRegister } from '../event-emitter/register-handler';\nimport { featurePriority } from '../../loaders/features/features';\nimport { EventContext } from '../event-emitter/event-context';\nconst registry = {};\n\n/**\n * Adds an entry to the centralized drain registry specifying that a particular agent has events of a particular named\n * event-group \"bucket\" that should be drained at the time the agent drains all its buffered events. Buffered events\n * accumulate because instrumentation begins as soon as possible, before the agent has finished lazy-loading the code\n * responsible for aggregating and reporting captured data.\n * @param {string} agentIdentifier - A 16 character string uniquely identifying the agent.\n * @param {string} group - The named \"bucket\" for the events this feature will be bucketing for later collection.\n */\nexport function registerDrain(agentIdentifier, group) {\n // Here `item` captures the registered properties of a feature-group: whether it is ready for its buffered events\n // to be drained (`staged`) and the `priority` order in which it should be drained relative to other feature groups.\n const item = {\n staged: false,\n priority: featurePriority[group] || 0\n };\n curateRegistry(agentIdentifier);\n if (!registry[agentIdentifier].get(group)) registry[agentIdentifier].set(group, item);\n}\n\n/**\n * Removes an item from the registry and immediately re-checks if the registry is ready to \"drain all\"\n * @param {*} agentIdentifier - A 16 character string uniquely identifying the agent.\n * @param {*} group - The named \"bucket\" to be removed from the registry\n */\nexport function deregisterDrain(agentIdentifier, group) {\n if (!agentIdentifier || !registry[agentIdentifier]) return;\n if (registry[agentIdentifier].get(group)) registry[agentIdentifier].delete(group);\n drainGroup(agentIdentifier, group, false);\n if (registry[agentIdentifier].size) checkCanDrainAll(agentIdentifier);\n}\n\n/**\n * Registers the specified agent with the centralized event buffer registry if it is not already registered.\n * Agents without an identifier (as in the case of some tests) will be excluded from the registry.\n * @param {string} agentIdentifier - A 16 character string uniquely identifying an agent.\n */\nfunction curateRegistry(agentIdentifier) {\n if (!agentIdentifier) throw new Error('agentIdentifier required');\n if (!registry[agentIdentifier]) registry[agentIdentifier] = new Map();\n}\n\n/**\n * Drain buffered events out of the event emitter. Each feature should have its events bucketed by \"group\" and drain\n * its own named group explicitly, when ready.\n * @param {string} agentIdentifier - A unique 16 character ID corresponding to an instantiated agent.\n * @param {string} featureName - A named group into which the feature's buffered events are bucketed.\n * @param {boolean} force - Whether to force the drain to occur immediately, bypassing the registry and staging logic.\n */\nexport function drain(agentIdentifier = '', featureName = 'feature', force = false) {\n curateRegistry(agentIdentifier);\n // If the feature for the specified agent is not in the registry, that means the instrument file was bypassed.\n // This could happen in tests, or loaders that directly import the aggregator. In these cases it is safe to\n // drain the feature group immediately rather than waiting to drain all at once.\n if (!agentIdentifier || !registry[agentIdentifier].get(featureName) || force) return drainGroup(agentIdentifier, featureName);\n\n // When `drain` is called, this feature is ready to drain (staged).\n registry[agentIdentifier].get(featureName).staged = true;\n checkCanDrainAll(agentIdentifier);\n}\n\n/** Checks all items in the registry to see if they have been \"staged\". If ALL items are staged, it will drain all registry items (drainGroup). It not, nothing will happen */\nfunction checkCanDrainAll(agentIdentifier) {\n // Only when the event-groups for all features are ready to drain (staged) do we execute the drain. This has the effect\n // that the last feature to call drain triggers drain for all features.\n const items = Array.from(registry[agentIdentifier]);\n if (items.every(([key, values]) => values.staged)) {\n items.sort((a, b) => a[1].priority - b[1].priority);\n items.forEach(([group]) => {\n registry[agentIdentifier].delete(group);\n drainGroup(agentIdentifier, group);\n });\n }\n}\n\n/**\n * Drains all the buffered (backlog) events for a particular feature's event-group by emitting each event to each of\n * the subscribed handlers for the group.\n * @param {*} group - The name of a particular feature's event \"bucket\".\n */\nfunction drainGroup(agentIdentifier, group, activateGroup = true) {\n const baseEE = agentIdentifier ? ee.get(agentIdentifier) : ee;\n const handlers = defaultRegister.handlers; // other storage in registerHandler\n if (baseEE.aborted || !baseEE.backlog || !handlers) return;\n\n // Only activated features being drained should run queued listeners on buffered events. Deactivated features only need to release memory.\n if (activateGroup) {\n const bufferedEventsInGroup = baseEE.backlog[group];\n const groupHandlers = handlers[group]; // each group in the registerHandler storage\n if (groupHandlers) {\n // We don't cache the length of the buffer while looping because events might still be added while processing.\n for (let i = 0; bufferedEventsInGroup && i < bufferedEventsInGroup.length; ++i) {\n // eslint-disable-line no-unmodified-loop-condition\n emitEvent(bufferedEventsInGroup[i], groupHandlers);\n }\n Object.entries(groupHandlers).forEach(([eventType, handlerRegistrationList]) => {\n Object.values(handlerRegistrationList || {}).forEach(registration => {\n // registration *should* be an array of: [targetEE, eventHandler]\n // certain browser polyfills of .values and .entries pass the prototype methods into the callback,\n // which breaks this assumption and throws errors. So we make sure here that we only call .on() if its an actual NR EE\n if (registration[0]?.on && registration[0]?.context() instanceof EventContext) registration[0].on(eventType, registration[1]);\n });\n });\n }\n }\n if (!baseEE.isolatedBacklog) delete handlers[group];\n baseEE.backlog[group] = null;\n baseEE.emit('drain-' + group, []); // TODO: Code exists purely for a unit test and needs to be refined\n}\n\n/**\n * Processes the specified event using all relevant handler functions associated with a particular feature, based on\n * whether the the handler is meant to apply to events of this type. (Event type is a descriptive string set at the\n * time an event is originally created by instrumentation, as with calls to the `handle` method.)\n * @param {*} evt - A single event to be emitted to (processed by) eligible handler functions.\n * @param {*} groupHandlers - A set of handler functions associated with a particular feature's event-group.\n */\nfunction emitEvent(evt, groupHandlers) {\n var type = evt[1];\n Object.values(groupHandlers[type] || {}).forEach(registration => {\n var sourceEE = evt[0];\n var ee = registration[0];\n if (ee === sourceEE) {\n var handler = registration[1];\n var ctx = evt[3];\n var args = evt[2];\n handler.apply(ctx, args);\n }\n });\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { gosNREUM } from '../window/nreum';\nimport { getOrSet } from '../util/get-or-set';\nimport { getRuntime } from '../config/runtime';\nimport { EventContext } from './event-context';\nimport { bundleId } from '../ids/bundle-id';\n\n// create a unique id to store event context data for the current agent bundle\nconst contextId = \"nr@context:\".concat(bundleId);\n// create global emitter instance that can be shared among bundles\nconst globalInstance = ee(undefined, 'globalEE');\n\n// Only override the exposed event emitter if one has not already been exposed\nconst nr = gosNREUM();\nif (!nr.ee) {\n nr.ee = globalInstance;\n}\nexport { globalInstance as ee, contextId };\nfunction ee(old, debugId) {\n var handlers = {};\n var bufferGroupMap = {};\n var emitters = {};\n // In cases where multiple agents can run on a page, the event backlogs of feature event emitters must be isolated\n // to prevent event emitter context and buffers from \"bubbling up\" to other agents operating in the scope.\n // An example of this is our MicroAgent loader package, which sets this property to true to prevent overlap.\n var isolatedBacklog = false;\n try {\n // We only want to check the runtime configuration for `isolatedBacklog` if the event emitter belongs to a feature.\n // For feature event emitters, the debugId will be an agentIdentifier with a length of 16. In contrast, some of our\n // tests do not namespace the event emitter with an agentID and just use the parent (which has no ID).\n isolatedBacklog = debugId.length !== 16 ? false : getRuntime(debugId).isolatedBacklog;\n } catch (err) {\n // Do nothing for now.\n }\n var emitter = {\n on: addEventListener,\n addEventListener,\n removeEventListener,\n emit,\n get: getOrCreate,\n listeners,\n context,\n buffer: bufferEventsByGroup,\n abort,\n isBuffering,\n debugId,\n backlog: isolatedBacklog ? {} : old && typeof old.backlog === 'object' ? old.backlog : {},\n isolatedBacklog\n };\n function abort() {\n emitter._aborted = true;\n Object.keys(emitter.backlog).forEach(key => {\n delete emitter.backlog[key];\n });\n }\n Object.defineProperty(emitter, 'aborted', {\n get: () => {\n let aborted = emitter._aborted || false;\n if (aborted) return aborted;else if (old) {\n aborted = old.aborted;\n }\n return aborted;\n }\n });\n return emitter;\n function context(contextOrStore) {\n if (contextOrStore && contextOrStore instanceof EventContext) {\n return contextOrStore;\n } else if (contextOrStore) {\n return getOrSet(contextOrStore, contextId, () => new EventContext(contextId));\n } else {\n return new EventContext(contextId);\n }\n }\n function emit(type, args, contextOrStore, force, bubble) {\n if (bubble !== false) bubble = true;\n if (globalInstance.aborted && !force) {\n return;\n }\n if (old && bubble) old.emit(type, args, contextOrStore);\n var ctx = context(contextOrStore);\n var handlersArray = listeners(type);\n var len = handlersArray.length;\n\n // Apply each handler function in the order they were added\n // to the context with the arguments\n\n for (var i = 0; i < len; i++) handlersArray[i].apply(ctx, args);\n\n // Buffer after emitting for consistent ordering\n var bufferGroup = getBuffer()[bufferGroupMap[type]];\n if (bufferGroup) {\n bufferGroup.push([emitter, type, args, ctx]);\n }\n\n // Return the context so that the module that emitted can see what was done.\n return ctx;\n }\n function addEventListener(type, fn) {\n // Retrieve type from handlers, if it doesn't exist assign the default and retrieve it.\n handlers[type] = listeners(type).concat(fn);\n }\n function removeEventListener(type, fn) {\n var listeners = handlers[type];\n if (!listeners) return;\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i] === fn) {\n listeners.splice(i, 1);\n }\n }\n }\n function listeners(type) {\n return handlers[type] || [];\n }\n function getOrCreate(name) {\n return emitters[name] = emitters[name] || ee(emitter, name);\n }\n function bufferEventsByGroup(types, group) {\n const eventBuffer = getBuffer();\n group = group || 'feature';\n\n // do not buffer events if agent has been aborted\n if (emitter.aborted) return;\n Object.entries(types || {}).forEach(([_, type]) => {\n bufferGroupMap[type] = group;\n if (!(group in eventBuffer)) {\n eventBuffer[group] = [];\n }\n });\n }\n function isBuffering(type) {\n var bufferGroup = getBuffer()[bufferGroupMap[type]];\n return !!bufferGroup;\n }\n\n // buffer is associated with a base emitter, since there are two\n // (global and scoped to the current bundle), it is now part of the emitter\n function getBuffer() {\n return emitter.backlog;\n }\n}","export class EventContext {\n constructor(contextId) {\n this.contextId = contextId;\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ee as globalInstance } from './contextual-ee';\nexport var handleEE = globalInstance.get('handle');\nexport function handle(type, args, ctx, group, ee) {\n if (ee) {\n ee.buffer([type], group);\n ee.emit(type, args, ctx);\n } else {\n handleEE.buffer([type], group);\n handleEE.emit(type, args, ctx);\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { handleEE } from './handle';\nexport { defaultRegister as registerHandler };\ndefaultRegister.on = registerWithSpecificEmitter;\nvar handlers = defaultRegister.handlers = {};\nexport function defaultRegister(type, handler, group, ee) {\n registerWithSpecificEmitter(ee || handleEE, handlers, type, handler, group);\n}\nfunction registerWithSpecificEmitter(ee, handlers, type, handler, group) {\n if (!group) group = 'feature';\n if (!ee) ee = handleEE;\n var groupHandlers = handlers[group] = handlers[group] || {};\n var list = groupHandlers[type] = groupHandlers[type] || [];\n list.push([ee, handler]);\n}","export function eventListenerOpts(useCapture, abortSignal) {\n return {\n capture: useCapture,\n passive: false,\n signal: abortSignal\n };\n}\n\n/** Do not use this within the worker context. */\nexport function windowAddEventListener(event, listener, capture = false, abortSignal) {\n window.addEventListener(event, listener, eventListenerOpts(capture, abortSignal));\n}\n/** Do not use this within the worker context. */\nexport function documentAddEventListener(event, listener, capture = false, abortSignal) {\n document.addEventListener(event, listener, eventListenerOpts(capture, abortSignal));\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { globalScope, isWorkerScope, isBrowserScope } from '../constants/runtime';\nimport { subscribeToVisibilityChange } from '../window/page-visibility';\nif (isWorkerScope) {\n globalScope.cleanupTasks = []; // create new list on WorkerGlobalScope to track funcs to run before exiting thread\n\n const origClose = globalScope.close;\n globalScope.close = () => {\n // on worker's EoL signal, execute all \"listeners\", e.g. final harvests\n for (let task of globalScope.cleanupTasks) {\n task();\n }\n origClose();\n };\n}\n\n/**\n * Subscribes a provided callback to the time/event when the agent should treat it as end-of-life.\n * This is used, for example, to submit a final harvest and send all remaining data on best-effort.\n * @param {function} cb - func to run before or during the last reliable event or time of an env's life span\n */\nexport function subscribeToEOL(cb, capturePhase) {\n if (isBrowserScope) {\n subscribeToVisibilityChange(cb, true, capturePhase); // when user switches tab or hides window, esp. mobile scenario\n } else if (isWorkerScope) {\n globalScope.cleanupTasks.push(cb); // close() should run these tasks before quitting thread\n }\n // By default (for other env), this fn has no effect.\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as submitData from '../util/submit-data';\nimport { SharedContext } from '../context/shared-context';\nimport { Harvest } from './harvest';\nimport { subscribeToEOL } from '../unload/eol';\nimport { SESSION_EVENTS } from '../session/constants';\n\n/**\n * Periodically invokes harvest calls and handles retries\n */\nexport class HarvestScheduler extends SharedContext {\n /**\n * Create a HarvestScheduler\n * @param {string} endpoint - The base BAM endpoint name -- ex. 'events'\n * @param {object} opts - The options used to configure the HarvestScheduler\n * @param {Function} opts.onFinished - The callback to be fired when a harvest has finished\n * @param {Function} opts.getPayload - A callback which can be triggered to return a payload for harvesting\n * @param {number} opts.retryDelay - The number of seconds to wait before retrying after a network failure\n * @param {boolean} opts.raw - Use a prefabricated payload shape as the harvest payload without the need for formatting\n * @param {string} opts.customUrl - A custom url that falls outside of the shape of the standard BAM harvester url pattern. Will use directly instead of concatenating various pieces\n * @param {*} parent - The parent object, whose state can be passed into SharedContext\n */\n constructor(endpoint, opts, parent) {\n super(parent); // gets any allowed properties from the parent and stores them in `sharedContext`\n this.endpoint = endpoint;\n this.opts = opts || {};\n this.started = false;\n this.timeoutHandle = null;\n this.aborted = false; // this controls the per-interval and final harvests for the scheduler (currently per feature specific!)\n this.harvesting = false;\n this.harvest = new Harvest(this.sharedContext);\n\n // If a feature specifies stuff to be done on page unload, those are frontrunned (via capture phase) before ANY feature final harvests.\n if (typeof this.opts.onUnload === 'function') subscribeToEOL(this.opts.onUnload, true);\n subscribeToEOL(this.unload.bind(this)); // this should consist only of sending final harvest\n\n /* Flush all buffered data if session resets and give up retries. This should be synchronous to ensure that the correct `session` value is sent.\n Since session-reset generates a new session ID and the ID is grabbed at send-time, any delays or retries would cause the payload to be sent under\n the wrong session ID. */\n this.sharedContext?.ee.on(SESSION_EVENTS.RESET, () => this.runHarvest({\n forceNoRetry: true\n }));\n }\n\n /**\n * This function is only meant for the last outgoing harvest cycle of a page. It trickles down to using sendBeacon, which should not be used\n * to send payloads while the page is still active, due to limitations on how much data can be buffered in the API at any one time.\n */\n unload() {\n if (this.aborted) return;\n this.runHarvest({\n unload: true\n });\n }\n startTimer(interval, initialDelay) {\n this.interval = interval;\n this.started = true;\n this.scheduleHarvest(initialDelay != null ? initialDelay : this.interval);\n }\n stopTimer(permanently = false) {\n this.aborted = permanently; // stopping permanently is same as aborting, but this function also cleans up the setTimeout loop\n this.started = false;\n if (this.timeoutHandle) {\n clearTimeout(this.timeoutHandle);\n }\n }\n scheduleHarvest(delay, opts) {\n if (this.timeoutHandle) return;\n if (delay == null) {\n delay = this.interval;\n }\n this.timeoutHandle = setTimeout(() => {\n this.timeoutHandle = null;\n this.runHarvest(opts);\n }, delay * 1000);\n }\n runHarvest(opts) {\n if (this.aborted) return;\n this.harvesting = true;\n\n /**\n * This is executed immediately after harvest sends the data via XHR, or if there's nothing to send. Note that this excludes on unloading / sendBeacon.\n * @param {Object} result\n */\n const cbRanAfterSend = result => {\n this.harvesting = false;\n if (opts?.forceNoRetry) result.retry = false; // discard unsent data rather than re-queuing for next harvest attempt\n this.onHarvestFinished(opts, result);\n };\n let harvests = [];\n let submitMethod;\n let payload;\n if (this.opts.getPayload) {\n // Ajax, PVT, Softnav, Logging, SR & ST features provide a single callback function to get data for harvesting\n submitMethod = submitData.getSubmitMethod({\n isFinalHarvest: opts?.unload\n });\n if (!submitMethod) return false;\n const retry = !opts?.unload && submitMethod === submitData.xhr;\n payload = this.opts.getPayload({\n retry,\n ...opts\n });\n if (!payload) {\n if (this.started) {\n this.scheduleHarvest();\n }\n return;\n }\n payload = Object.prototype.toString.call(payload) === '[object Array]' ? payload : [payload];\n harvests.push(...payload);\n }\n\n /** sendX is used for features that do not supply a preformatted payload via \"getPayload\" */\n let send = args => this.harvest.sendX(args);\n if (harvests.length) {\n /** _send is the underlying method for sending in the harvest, if sending raw we can bypass the other helpers completely which format the payloads */\n if (this.opts.raw) send = args => this.harvest._send(args);\n /** send is used to formated the payloads from \"getPayload\" and obfuscate before sending */else send = args => this.harvest.send(args);\n } else {\n // force it to run at least once in sendX mode\n harvests.push(undefined);\n }\n harvests.forEach(payload => {\n send({\n endpoint: this.endpoint,\n payload,\n opts,\n submitMethod,\n cbFinished: cbRanAfterSend,\n customUrl: this.opts.customUrl,\n raw: this.opts.raw\n });\n });\n if (this.started) {\n this.scheduleHarvest();\n }\n }\n onHarvestFinished(opts, result) {\n if (this.opts.onFinished) {\n this.opts.onFinished(result);\n }\n if (result.sent && result.retry) {\n const delay = result.delay || this.opts.retryDelay;\n // reschedule next harvest if should be delayed longer\n if (this.started && delay) {\n clearTimeout(this.timeoutHandle);\n this.timeoutHandle = null;\n this.scheduleHarvest(delay, opts);\n } else if (!this.started && delay) {\n // if not running on a timer, schedule a single retry\n this.scheduleHarvest(delay, opts);\n }\n }\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { obj as encodeObj, param as encodeParam } from '../url/encode';\nimport { stringify } from '../util/stringify';\nimport * as submitData from '../util/submit-data';\nimport { getLocation } from '../url/location';\nimport { getInfo } from '../config/info';\nimport { getConfigurationValue, getConfiguration } from '../config/init';\nimport { getRuntime } from '../config/runtime';\nimport { cleanURL } from '../url/clean-url';\nimport { eventListenerOpts } from '../event-listener/event-listener-opts';\nimport { SharedContext } from '../context/shared-context';\nimport { VERSION } from \"../constants/env.npm\";\nimport { isWorkerScope } from '../constants/runtime';\nimport { warn } from '../util/console';\nimport { now } from '../timing/now';\nconst warnings = {};\n\n/**\n * @typedef {import('./types.js').NetworkSendSpec} NetworkSendSpec\n * @typedef {import('./types.js').HarvestEndpointIdentifier} HarvestEndpointIdentifier\n * @typedef {import('./types.js').HarvestPayload} HarvestPayload\n * @typedef {import('./types.js').FeatureHarvestCallback} FeatureHarvestCallback\n * @typedef {import('./types.js').FeatureHarvestCallbackOptions} FeatureHarvestCallbackOptions\n */\nexport class Harvest extends SharedContext {\n constructor(parent) {\n super(parent); // gets any allowed properties from the parent and stores them in `sharedContext`\n\n this.tooManyRequestsDelay = getConfigurationValue(this.sharedContext.agentIdentifier, 'harvest.tooManyRequestsDelay') || 60;\n this.obfuscator = getRuntime(this.sharedContext.agentIdentifier).obfuscator;\n this._events = {};\n }\n\n /**\n * Initiate a harvest from multiple sources. An event that corresponds to the endpoint\n * name is emitted, which gives any listeners the opportunity to provide payload data.\n * Note: Used by page_action\n * @param {NetworkSendSpec} spec Specification for sending data\n */\n sendX(spec = {}) {\n const submitMethod = submitData.getSubmitMethod({\n isFinalHarvest: spec.opts?.unload\n });\n const options = {\n retry: !spec.opts?.unload && submitMethod === submitData.xhr,\n isFinalHarvest: spec.opts?.unload === true\n };\n const payload = this.createPayload(spec.endpoint, options);\n const caller = this._send.bind(this);\n return caller({\n ...spec,\n payload,\n submitMethod\n });\n }\n\n /**\n * Initiate a harvest call.\n * @param {NetworkSendSpec} spec Specification for sending data\n */\n send(spec = {}) {\n const caller = this._send.bind(this);\n return caller(spec);\n }\n\n /**\n * Initiate a harvest call. Typically used by `sendX` and `send` methods or called directly\n * for raw network calls.\n * @param {NetworkSendSpec} param0 Specification for sending data\n * @returns {boolean} True if the network call succeeded. For final harvest calls, the return\n * value should not be relied upon because network calls will be made asynchronously.\n */\n _send({\n endpoint,\n payload = {},\n opts = {},\n submitMethod,\n cbFinished,\n customUrl,\n raw,\n includeBaseParams = true\n }) {\n const info = getInfo(this.sharedContext.agentIdentifier);\n if (!info.errorBeacon) return false;\n const agentRuntime = getRuntime(this.sharedContext.agentIdentifier);\n let {\n body,\n qs\n } = this.cleanPayload(payload);\n if (Object.keys(body).length === 0 && !opts?.sendEmptyBody) {\n // no payload body? nothing to send, just run onfinish stuff and return\n if (cbFinished) {\n cbFinished({\n sent: false\n });\n }\n return false;\n }\n const init = getConfiguration(this.sharedContext.agentIdentifier);\n const protocol = init.ssl === false ? 'http' : 'https';\n const perceviedBeacon = init.proxy.beacon || info.errorBeacon;\n const endpointURLPart = endpoint !== 'rum' ? \"/\".concat(endpoint) : '';\n let url = \"\".concat(protocol, \"://\").concat(perceviedBeacon).concat(endpointURLPart, \"/1/\").concat(info.licenseKey);\n if (customUrl) url = customUrl;\n if (raw) url = \"\".concat(protocol, \"://\").concat(perceviedBeacon, \"/\").concat(endpoint);\n const baseParams = !raw && includeBaseParams ? this.baseQueryString(qs, endpoint) : '';\n let payloadParams = encodeObj(qs, agentRuntime.maxBytes);\n if (!submitMethod) {\n submitMethod = submitData.getSubmitMethod({\n isFinalHarvest: opts.unload\n });\n }\n if (baseParams === '' && payloadParams.startsWith('&')) {\n payloadParams = payloadParams.substring(1);\n }\n const fullUrl = \"\".concat(url, \"?\").concat(baseParams).concat(payloadParams);\n const gzip = !!qs?.attributes?.includes('gzip');\n if (!gzip) {\n if (endpoint !== 'events') body = stringify(body); // all features going to /events/ endpoint should already be serialized & stringified\n /** Warn --once per endpoint-- if the agent tries to send large payloads */\n if (body.length > 750000 && (warnings[endpoint] = (warnings?.[endpoint] || 0) + 1) === 1) warn(28, endpoint);\n }\n if (!body || body.length === 0 || body === '{}' || body === '[]') {\n // If body is null, undefined, or an empty object or array, send an empty string instead\n body = '';\n }\n const headers = [];\n headers.push({\n key: 'content-type',\n value: 'text/plain'\n });\n\n /* Since workers don't support sendBeacon right now, they can only use XHR method.\n Because they still do permit synch XHR, the idea is that at final harvest time (worker is closing),\n we just make a BLOCKING request--trivial impact--with the remaining data as a temp fill-in for sendBeacon.\n Following the removal of img-element method. */\n let result = submitMethod({\n url: fullUrl,\n body,\n sync: opts.unload && isWorkerScope,\n headers\n });\n if (!opts.unload && cbFinished && submitMethod === submitData.xhr) {\n const harvestScope = this;\n result.addEventListener('loadend', function () {\n // `this` refers to the XHR object in this scope, do not change this to a fat arrow\n // status 0 refers to a local error, such as CORS or network failure, or a blocked request by the browser (e.g. adblocker)\n const cbResult = {\n sent: this.status !== 0,\n status: this.status,\n xhr: this,\n fullUrl\n };\n if (this.status === 429) {\n cbResult.retry = true;\n cbResult.delay = harvestScope.tooManyRequestsDelay;\n } else if (this.status === 408 || this.status === 500 || this.status === 503) {\n cbResult.retry = true;\n }\n if (opts.needResponse) {\n cbResult.responseText = this.responseText;\n }\n cbFinished(cbResult);\n }, eventListenerOpts(false));\n }\n return result;\n }\n\n // The stuff that gets sent every time.\n baseQueryString(qs, endpoint) {\n const runtime = getRuntime(this.sharedContext.agentIdentifier);\n const info = getInfo(this.sharedContext.agentIdentifier);\n const ref = this.obfuscator.obfuscateString(cleanURL(getLocation()));\n const hr = runtime?.session?.state.sessionReplayMode === 1 && endpoint !== 'jserrors';\n const qps = ['a=' + info.applicationID, encodeParam('sa', info.sa ? '' + info.sa : ''), encodeParam('v', VERSION), transactionNameParam(info), encodeParam('ct', runtime.customTransaction), '&rst=' + now(), '&ck=0',\n // ck param DEPRECATED - still expected by backend\n '&s=' + (runtime.session?.state.value || '0'),\n // the 0 id encaps all untrackable and default traffic\n encodeParam('ref', ref), encodeParam('ptid', runtime.ptid ? '' + runtime.ptid : '')];\n if (hr) qps.push(encodeParam('hr', '1', qs));\n return qps.join('');\n }\n\n /**\n * Calls and accumulates data from registered harvesting functions based on\n * the endpoint being harvested.\n * @param {HarvestEndpointIdentifier} endpoint BAM endpoint identifier.\n * @param {FeatureHarvestCallbackOptions} options Options to be passed to the\n * feature harvest listener callback.\n * @returns {HarvestPayload} Payload object to transmit to the bam endpoint.\n */\n createPayload(endpoint, options) {\n const listeners = this._events[endpoint];\n const payload = {\n body: {},\n qs: {}\n };\n if (Array.isArray(listeners) && listeners.length > 0) {\n for (let i = 0; i < listeners.length; i++) {\n const singlePayload = listeners[i](options);\n if (singlePayload) {\n payload.body = {\n ...payload.body,\n ...(singlePayload.body || {})\n };\n payload.qs = {\n ...payload.qs,\n ...(singlePayload.qs || {})\n };\n }\n }\n }\n return payload;\n }\n\n /**\n * Cleans and returns a payload object containing a body and qs\n * object with key/value pairs. KV pairs where the value is null,\n * undefined, or an empty string are removed to save on transmission\n * size.\n * @param {HarvestPayload} payload Payload to be sent to the endpoint.\n * @returns {HarvestPayload} Cleaned payload payload to be sent to the endpoint.\n */\n cleanPayload(payload = {}) {\n const clean = input => {\n if (typeof Uint8Array !== 'undefined' && input instanceof Uint8Array || Array.isArray(input)) return input;\n if (typeof input === 'string') return input.length > 0 ? input : null;\n return Object.entries(input || {}).reduce((accumulator, [key, value]) => {\n if (typeof value === 'number' || typeof value === 'string' && value.length > 0 || typeof value === 'object' && Object.keys(value || {}).length > 0) {\n accumulator[key] = value;\n }\n return accumulator;\n }, {});\n };\n return {\n body: clean(payload.body),\n qs: clean(payload.qs)\n };\n }\n\n /**\n * Registers a function to be called when harvesting is triggered for a specific\n * endpoint.\n * @param {HarvestEndpointIdentifier} endpoint\n * @param {FeatureHarvestCallback} listener\n */\n on(endpoint, listener) {\n if (!Array.isArray(this._events[endpoint])) {\n this._events[endpoint] = [];\n }\n this._events[endpoint].push(listener);\n }\n}\n\n// Constructs the transaction name param for the beacon URL.\n// Prefers the obfuscated transaction name over the plain text.\n// Falls back to making up a name.\nfunction transactionNameParam(info) {\n if (info.transactionName) return encodeParam('to', info.transactionName);\n return encodeParam('t', info.tNamePlain || 'Unnamed Transaction');\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This method only exists to support testing in JIL and can be removed once tests are migrated to WDIO.\n * @returns global scope location\n */\nexport function getLocation() {\n return '' + location;\n}","/**\n * @file Contains a unique identifier for the running agent bundle\n * when loaded.\n * @copyright 2023 New Relic Corporation. All rights reserved.\n * @license Apache-2.0\n */\n\nimport { generateUuid } from './unique-id';\n\n/**\n * Provides a unique id for the current agent bundle\n */\nexport const bundleId = generateUuid();","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { globalScope } from '../constants/runtime';\nconst uuidv4Template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';\n\n/**\n * Creates a random single hexadecimal value from a provided random value\n * table and corresponding index. If a random value table is not provided,\n * Math.random will be used to generate the value.\n *\n * @param {Uint8Array} valueTable Random value table typically generated using\n * the built-in crypto engine.\n * @param {int} tableIndex The index of the value table to use for generating\n * the hexadecimal value.\n * @returns {int} single hexadecimal value in decimal format\n */\nfunction getRandomValue(valueTable, tableIndex) {\n if (valueTable) {\n /**\n * The value table could have any number value in the given index. Use\n * bitwise AND to ensure the value we generate is a valid hex value.\n * x & 15 will ensure the value converted to hex using `toString(16)`\n * falls within the range of 0 and 15 inclusively.\n */\n return valueTable[tableIndex] & 15;\n } else {\n return Math.random() * 16 | 0;\n }\n}\n\n/**\n * Generates a RFC compliant UUIDv4 using native browser crypto engine. If the browser\n * does not support the crypto engine, the function will fallback to insecure Math.random()\n * @returns {string} uuid version 4 string\n */\nexport function generateUuid() {\n const crypto = globalScope?.crypto || globalScope?.msCrypto;\n let randomValueTable;\n let randomValueIndex = 0;\n if (crypto && crypto.getRandomValues) {\n // For a UUID, we only need 30 characters since two characters are pre-defined\n // eslint-disable-next-line\n randomValueTable = crypto.getRandomValues(new Uint8Array(30));\n }\n return uuidv4Template.split('').map(templateInput => {\n if (templateInput === 'x') {\n return getRandomValue(randomValueTable, randomValueIndex++).toString(16);\n } else if (templateInput === 'y') {\n // this is the uuid variant per spec (8, 9, a, b)\n // % 4, then shift to get values 8-11\n return (getRandomValue() & 0x3 | 0x8).toString(16);\n } else {\n return templateInput;\n }\n }).join('');\n}\n\n/**\n * Generates a string of the given length containing only hexadecimal\n * value 0-9 and a-f.\n * @param {int} length length of the string to generate\n * @returns {string} generated hex string\n */\nexport function generateRandomHexString(length) {\n const crypto = globalScope?.crypto || globalScope?.msCrypto;\n let randomValueTable;\n let randomValueIndex = 0;\n if (crypto && crypto.getRandomValues) {\n // eslint-disable-next-line\n randomValueTable = crypto.getRandomValues(new Uint8Array(length));\n }\n const chars = [];\n for (var i = 0; i < length; i++) {\n chars.push(getRandomValue(randomValueTable, randomValueIndex++).toString(16));\n }\n return chars.join('');\n}\n\n/**\n * Generates a 16 character length hexadecimal string.\n * per DT-spec.\n * @see generateRandomHexString\n * @returns {string} generated hex string\n */\nexport function generateSpanId() {\n return generateRandomHexString(16);\n}\n\n/**\n * Generates a 32 character length hexadecimal string.\n * per DT-spec.\n * @see generateRandomHexString\n * @returns {string} generated hex string\n */\nexport function generateTraceId() {\n return generateRandomHexString(32);\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { stringify } from '../util/stringify';\nimport { getRuntime } from '../config/runtime';\nvar hasOwnProp = Object.prototype.hasOwnProperty;\nvar MAX_ATTRIBUTES = 64;\nexport function nullable(val, fn, comma) {\n return val || val === 0 || val === '' ? fn(val) + (comma ? ',' : '') : '!';\n}\nexport function numeric(n, noDefault) {\n if (noDefault) {\n return Math.floor(n).toString(36);\n }\n return n === undefined || n === 0 ? '' : Math.floor(n).toString(36);\n}\nexport function getAddStringContext(agentIdentifier) {\n let stringTableIdx = 0;\n const stringTable = Object.prototype.hasOwnProperty.call(Object, 'create') ? Object.create(null) : {};\n const obfuscator = getRuntime(agentIdentifier).obfuscator;\n return addString;\n function addString(str) {\n if (typeof str === 'undefined' || str === '') return '';\n str = obfuscator.obfuscateString(String(str));\n if (hasOwnProp.call(stringTable, str)) {\n return numeric(stringTable[str], true);\n } else {\n stringTable[str] = stringTableIdx++;\n return quoteString(str);\n }\n }\n}\nexport function addCustomAttributes(attrs, addString) {\n var attrParts = [];\n Object.entries(attrs || {}).forEach(([key, val]) => {\n if (attrParts.length >= MAX_ATTRIBUTES) return;\n var type = 5;\n var serializedValue;\n // add key to string table first\n key = addString(key);\n switch (typeof val) {\n case 'object':\n if (val) {\n // serialize objects to strings\n serializedValue = addString(stringify(val));\n } else {\n // null attribute type\n type = 9;\n }\n break;\n case 'number':\n type = 6;\n // make sure numbers contain a `.` so they are parsed as doubles\n serializedValue = val % 1 ? val : val + '.';\n break;\n case 'boolean':\n type = val ? 7 : 8;\n break;\n case 'undefined':\n // we treat undefined as a null attribute (since dirac does not have a concept of undefined)\n type = 9;\n break;\n default:\n serializedValue = addString(val);\n }\n attrParts.push([type, key + (serializedValue ? ',' + serializedValue : '')]);\n });\n return attrParts;\n}\nvar escapable = /([,\\\\;])/g;\nfunction quoteString(str) {\n return \"'\" + str.replace(escapable, '\\\\$1');\n}","export const PREFIX = 'NRBA';\nexport const DEFAULT_KEY = 'SESSION';\nexport const DEFAULT_EXPIRES_MS = 14400000;\nexport const DEFAULT_INACTIVE_MS = 1800000;\nexport const SESSION_EVENTS = {\n STARTED: 'session-started',\n PAUSE: 'session-pause',\n RESET: 'session-reset',\n RESUME: 'session-resume',\n UPDATE: 'session-update'\n};\nexport const SESSION_EVENT_TYPES = {\n SAME_TAB: 'same-tab',\n CROSS_TAB: 'cross-tab'\n};\nexport const MODE = {\n OFF: 0,\n FULL: 1,\n ERROR: 2\n};","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// We don't use JSON.stringify directly on the performance timing data for these reasons:\n// * Chrome has extra data in the performance object that we don't want to send all the time (wasteful)\n// * Firefox fails to stringify the native object due to - http://code.google.com/p/v8/issues/detail?id=1223\n// * The variable names are long and wasteful to transmit\n\n// Add Performance Timing values to the given object.\n// * Values are written relative to an offset to reduce their length (i.e. number of characters).\n// * The offset is sent with the data\n// * 0's are not included unless the value is a 'relative zero'\n//\n\nvar START = 'Start';\nvar END = 'End';\nvar UNLOAD_EVENT = 'unloadEvent';\nvar REDIRECT = 'redirect';\nvar DOMAIN_LOOKUP = 'domainLookup';\nvar ONNECT = 'onnect';\nvar REQUEST = 'request';\nvar RESPONSE = 'response';\nvar LOAD_EVENT = 'loadEvent';\nvar DOM_CONTENT_LOAD_EVENT = 'domContentLoadedEvent';\nexport const navTimingValues = [];\nfunction getPntType(type) {\n if (typeof type === 'number') return type;\n const types = {\n navigate: undefined,\n reload: 1,\n back_forward: 2,\n prerender: 3\n };\n return types[type];\n}\nexport function addPT(offset, pt, v = {}, isL1Api = false) {\n if (!pt) return;\n v.of = offset;\n handleValue(v.of, v, 'n', true);\n handleValue(pt[UNLOAD_EVENT + START], v, 'u', isL1Api);\n handleValue(pt[REDIRECT + START], v, 'r', isL1Api);\n handleValue(pt[UNLOAD_EVENT + END], v, 'ue', isL1Api);\n handleValue(pt[REDIRECT + END], v, 're', isL1Api);\n handleValue(pt['fetch' + START], v, 'f', isL1Api);\n handleValue(pt[DOMAIN_LOOKUP + START], v, 'dn', isL1Api);\n handleValue(pt[DOMAIN_LOOKUP + END], v, 'dne', isL1Api);\n handleValue(pt['c' + ONNECT + START], v, 'c', isL1Api);\n handleValue(pt['secureC' + ONNECT + 'ion' + START], v, 's', isL1Api);\n handleValue(pt['c' + ONNECT + END], v, 'ce', isL1Api);\n handleValue(pt[REQUEST + START], v, 'rq', isL1Api);\n handleValue(pt[RESPONSE + START], v, 'rp', isL1Api);\n handleValue(pt[RESPONSE + END], v, 'rpe', isL1Api);\n handleValue(pt.domLoading, v, 'dl', isL1Api);\n handleValue(pt.domInteractive, v, 'di', isL1Api);\n handleValue(pt[DOM_CONTENT_LOAD_EVENT + START], v, 'ds', isL1Api);\n handleValue(pt[DOM_CONTENT_LOAD_EVENT + END], v, 'de', isL1Api);\n handleValue(pt.domComplete, v, 'dc', isL1Api);\n handleValue(pt[LOAD_EVENT + START], v, 'l', isL1Api);\n handleValue(pt[LOAD_EVENT + END], v, 'le', isL1Api);\n return v;\n}\n\n// Add Performance Navigation values to the given object\nexport function addPN(pn, v) {\n handleValue(getPntType(pn.type), v, 'ty');\n handleValue(pn.redirectCount, v, 'rc');\n return v;\n}\n\n/**\n * By side effect, this modifies 'obj' with a mapping of the 'prop' provided to a 'value', and invalid values are not added.\n * On the other hand, the local navTimingValues array gets the value appended if valid and 'undefined' appended if invalid, regardless.\n */\nfunction handleValue(value, obj, prop, isOldApi) {\n /*\n For L2 Timing API, the value will already be a relative-to-previous-document DOMHighResTimeStamp.\n For L1 (deprecated) Timing, the value is an UNIX epoch timestamp, which we will convert to a relative time using our offset.\n PNT.type is reported as undefined, 1, 2, etc -- note that zero-value properties will be recorded as 'undefined', however DEM interprets undefined \"types\" as \"navigate\"\n */\n if (typeof value === 'number' && value > 0) {\n // note that zero-value properties will be recorded as 'undefined'\n if (isOldApi) {\n const offset = obj?.of > 0 ? obj.of : 0; // expect an epoch timestamp, if called by addPT\n value = Math.max(value - offset, 0);\n }\n value = Math.round(value);\n obj[prop] = value;\n navTimingValues.push(value);\n } else navTimingValues.push(undefined);\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// This is our own layer around performance.now. It's not strictly necessary, but we keep it in case of future mod-ing of the value for refactor purpose.\nexport function now() {\n return Math.floor(performance.now());\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nvar patternWithHash = /([^?#]*)[^#]*(#[^?]*|$).*/;\nvar patternWithoutHash = /([^?#]*)().*/;\n\n/**\n * Cleans a URL by removing the query string and fragment (hash portion).\n * @param {string} url - The original URL to be cleaned.\n * @param {boolean} [keepHash=false] - Whether to preserve the hash portion of the URL.\n * @returns {string} The cleaned URL.\n */\nexport function cleanURL(url, keepHash) {\n return url.replace(keepHash ? patternWithHash : patternWithoutHash, '$1$2');\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { stringify } from '../util/stringify';\n\n// Characters that are safe in a qs, but get encoded.\nvar charMap = {\n '%2C': ',',\n '%3A': ':',\n '%2F': '/',\n '%40': '@',\n '%24': '$',\n '%3B': ';'\n};\nvar charList = Object.keys(charMap);\nvar safeEncoded = new RegExp(charList.join('|'), 'g');\nfunction real(c) {\n return charMap[c];\n}\n\n// Encode as URI Component, then unescape anything that is ok in the\n// query string position.\nexport function qs(value) {\n if (value === null || value === undefined) return 'null';\n return encodeURIComponent(value).replace(safeEncoded, real);\n}\nexport function fromArray(qs, maxBytes) {\n var bytes = 0;\n for (var i = 0; i < qs.length; i++) {\n bytes += qs[i].length;\n if (bytes > maxBytes) return qs.slice(0, i).join('');\n }\n return qs.join('');\n}\nexport function obj(payload, maxBytes) {\n var total = 0;\n var result = '';\n Object.entries(payload || {}).forEach(([feature, dataArray]) => {\n var intermediate = [];\n var next;\n var i;\n if (typeof dataArray === 'string' || !Array.isArray(dataArray) && dataArray !== null && dataArray !== undefined && dataArray.toString().length) {\n next = '&' + feature + '=' + qs(dataArray);\n total += next.length;\n result += next;\n } else if (Array.isArray(dataArray) && dataArray.length) {\n total += 9;\n for (i = 0; i < dataArray.length; i++) {\n next = qs(stringify(dataArray[i]));\n total += next.length;\n if (typeof maxBytes !== 'undefined' && total >= maxBytes) break;\n intermediate.push(next);\n }\n result += '&' + feature + '=%5B' + intermediate.join(',') + '%5D';\n }\n });\n return result;\n}\n\n// Constructs an HTTP parameter to add to the BAM router URL\nexport function param(name, value, base = {}) {\n if (Object.keys(base).includes(name)) return ''; // we assume if feature supplied a matching qp to the base, we should honor what the feature sent over the default\n if (value && typeof value === 'string') {\n return '&' + name + '=' + qs(value);\n }\n return '';\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { globalScope } from '../constants/runtime';\nexport function parseUrl(url) {\n // Return if URL is a data URL, parseUrl assumes urls are http/https\n if ((url || '').indexOf('data:') === 0) {\n return {\n protocol: 'data'\n };\n }\n try {\n const parsedUrl = new URL(url, location.href);\n const returnVal = {\n port: parsedUrl.port,\n hostname: parsedUrl.hostname,\n pathname: parsedUrl.pathname,\n search: parsedUrl.search,\n protocol: parsedUrl.protocol.slice(0, parsedUrl.protocol.indexOf(':')),\n sameOrigin: parsedUrl.protocol === globalScope?.location?.protocol && parsedUrl.host === globalScope?.location?.host\n };\n if (!returnVal.port || returnVal.port === '') {\n if (parsedUrl.protocol === 'http:') returnVal.port = '80';\n if (parsedUrl.protocol === 'https:') returnVal.port = '443';\n }\n if (!returnVal.pathname || returnVal.pathname === '') {\n returnVal.pathname = '/';\n } else if (!returnVal.pathname.startsWith('/')) {\n returnVal.pathname = \"/\".concat(returnVal.pathname);\n }\n return returnVal;\n } catch (err) {\n return {};\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { globalScope } from '../constants/runtime';\nexport function isFileProtocol() {\n return Boolean(globalScope?.location?.protocol === 'file:');\n}","/* eslint no-console: [\"error\", { allow: [\"debug\"] }] */\n\n/**\n * A helper method to warn to the console with New Relic: decoration\n * @param {string} message The primary message to warn\n * @param {*} [secondary] Secondary data to include, usually an error or object\n * @returns\n */\nexport function warn(code, secondary) {\n if (typeof console.debug !== 'function') return;\n console.debug(\"New Relic Warning: https://github.com/newrelic/newrelic-browser-agent/blob/main/docs/warning-codes.md#\".concat(code), secondary);\n}","import { globalScope } from '../constants/runtime';\nconst GLOBAL_EVENT_NAMESPACE = 'newrelic';\nexport function dispatchGlobalEvent(detail = {}) {\n try {\n globalScope.dispatchEvent(new CustomEvent(GLOBAL_EVENT_NAMESPACE, {\n detail\n }));\n } catch (err) {\n // something happened... dispatchEvent or CustomEvent might not be supported\n // decide what to do about it here\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { ee } from '../event-emitter/contextual-ee';\nimport { dispatchGlobalEvent } from '../dispatch/global-event';\nconst sentIds = new Set();\n\n/** A map of feature flags and their values as provided by the rum call -- scoped by agent ID */\nexport const activatedFeatures = {};\n\n/**\n * Sets the activatedFeatures object, dispatches the global loaded event,\n * and emits the rumresp flag to features\n * @param {{[key:string]:number}} flags key-val pair of flag names and numeric\n * @param {string} agentIdentifier agent instance identifier\n * @returns {void}\n */\nexport function activateFeatures(flags, agentIdentifier) {\n const sharedEE = ee.get(agentIdentifier);\n activatedFeatures[agentIdentifier] ??= {};\n if (!(flags && typeof flags === 'object')) return;\n if (sentIds.has(agentIdentifier)) return;\n sharedEE.emit('rumresp', [flags]);\n activatedFeatures[agentIdentifier] = flags;\n sentIds.add(agentIdentifier);\n\n // let any window level subscribers know that the agent is running\n dispatchGlobalEvent({\n loaded: true\n });\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nvar has = Object.prototype.hasOwnProperty;\n\n/**\n * Always returns the current value of obj[prop], even if it has to set it first. Sets properties as non-enumerable if possible.\n *\n * @param {Object} obj - The object to get or set the property on.\n * @param {string} prop - The name of the property.\n * @param {Function} getVal - A function that returns the value to be set if the property does not exist.\n * @returns {*} The value of the property in the object.\n */\nexport function getOrSet(obj, prop, getVal) {\n // If the value exists return it.\n if (has.call(obj, prop)) return obj[prop];\n var val = getVal();\n\n // Attempt to set the property so it's not enumerable\n if (Object.defineProperty && Object.keys) {\n try {\n Object.defineProperty(obj, prop, {\n value: val,\n // old IE inherits non-write-ability\n writable: true,\n enumerable: false\n });\n return val;\n } catch (e) {\n // Can't report internal errors,\n // because GOS is a dependency of the reporting mechanisms\n }\n }\n\n // fall back to setting normally\n obj[prop] = val;\n return val;\n}","/**\n * Reduce the invocation of the supplied function so that it is only invoked\n * once within a given timeout.\n *\n * If `wait` is `0`, the function will be invoked during the next tick.\n * If `options.leading` is false or not provided, the function will be invoked\n * N milliseconds after the last invocation of the returned function where\n * N is the `timeout` value.\n * If `options.leading` is true, the function will be invoked immediately upon\n * the first invocation of the returned function and not again for N milliseconds\n * where N is the `timeout` value.\n * @param {function} func Function whose invocation should be limited so it is only invoked\n * once within a given timeout period.\n * @param {number} timeout Time in milliseconds that the function should only be invoked\n * once within.\n * @param {object} options Debounce options\n * @param {boolean} options.leading Forces the function to be invoked on the first\n * invocation of the returned function instead of N milliseconds after the last\n * invocation.\n * @returns {function} A wrapping function that will ensure the provided function\n * is invoked only once within the given timeout.\n */\nexport function debounce(func, timeout = 500, options = {}) {\n const leading = options?.leading || false;\n let timer;\n return (...args) => {\n if (leading && timer === undefined) {\n func.apply(this, args);\n timer = setTimeout(() => {\n timer = clearTimeout(timer);\n }, timeout);\n }\n if (!leading) {\n clearTimeout(timer);\n timer = setTimeout(() => {\n func.apply(this, args);\n }, timeout);\n }\n };\n}\n\n/**\n * Reduce the invocation of the supplied function so that it is only invoked\n * once.\n * @param {function} func Function whose invocation should be limited so it is only invoked\n * once.\n * @returns {function} A wrapping function that will ensure the provided function\n * is invoked only once.\n */\nexport function single(func) {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n func.apply(this, args);\n }\n };\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ee } from '../event-emitter/contextual-ee';\n\n/**\n * Returns a function for use as a replacer parameter in JSON.stringify() to handle circular references.\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value MDN - Cyclical object value}\n * @returns {Function} A function that filters out values it has seen before.\n */\nconst getCircularReplacer = () => {\n const seen = new WeakSet();\n return (key, value) => {\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n }\n return value;\n };\n};\n\n/**\n * The native JSON.stringify method augmented with a replacer function to handle circular references.\n * Circular references will be excluded from the JSON output rather than triggering errors.\n * @param {*} val - A value to be converted to a JSON string.\n * @returns {string} A JSON string representation of the value, with circular references handled.\n */\nexport function stringify(val) {\n try {\n return JSON.stringify(val, getCircularReplacer()) ?? '';\n } catch (e) {\n try {\n ee.emit('internal-error', [e]);\n } catch (err) {\n // do nothing\n }\n // return a string so that downstream users of the method do not throw errors\n return '';\n }\n}","/**\n * @file Contains common methods used to transmit harvested data.\n * @copyright 2023 New Relic Corporation. All rights reserved.\n * @license Apache-2.0\n */\n\nimport { isBrowserScope } from '../constants/runtime';\n\n/**\n * @typedef {xhr|beacon} NetworkMethods\n */\n\n/**\n * Determines the submit method to use based on options.\n * @param {object} opts Options used to determine submit method.\n * @param {boolean} opts.isFinalHarvest Indicates if the data submission is due to\n * a final harvest within the agent.\n */\nexport function getSubmitMethod({\n isFinalHarvest = false\n} = {}) {\n return isFinalHarvest && isBrowserScope\n // Use sendBeacon for final harvest\n ? beacon\n // If not final harvest, or not browserScope, always use xhr post\n : xhr;\n}\n\n/**\n * Send via XHR\n * @param {Object} args - The args.\n * @param {string} args.url - The URL to send to.\n * @param {string=} args.body - The Stringified body. Default null to prevent IE11 from breaking.\n * @param {boolean=} args.sync - Run XHR synchronously.\n * @param {string=} [args.method=POST] - The XHR method to use.\n * @param {{key: string, value: string}[]} [args.headers] - The headers to attach.\n * @returns {XMLHttpRequest}\n */\nexport function xhr({\n url,\n body = null,\n sync,\n method = 'POST',\n headers = [{\n key: 'content-type',\n value: 'text/plain'\n }]\n}) {\n const request = new XMLHttpRequest();\n request.open(method, url, !sync);\n try {\n // Set cookie\n if ('withCredentials' in request) request.withCredentials = true;\n } catch (e) {\n // do nothing\n }\n headers.forEach(header => {\n request.setRequestHeader(header.key, header.value);\n });\n request.send(body);\n return request;\n}\n\n/**\n * Send via sendBeacon. Do NOT call this function outside of a guaranteed web window environment.\n * @param {Object} args - The args\n * @param {string} args.url - The URL to send to\n * @param {string=} args.body - The Stringified body\n * @returns {boolean}\n */\nexport function beacon({\n url,\n body\n}) {\n try {\n // Navigator has to be bound to ensure it does not error in some browsers\n // https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch\n const send = window.navigator.sendBeacon.bind(window.navigator);\n return send(url, body);\n } catch (err) {\n // if sendBeacon still trys to throw an illegal invocation error,\n // we can catch here and return\n return false;\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Applies a function to properties of a specified type in an object, recursively.\n *\n * @param {Object} obj - The object to apply the function to.\n * @param {Function} fn - The function to apply to matching properties.\n * @param {string} [type='string'] - The type of properties to apply the function to.\n * @param {Array} [ignoreKeys=[]] - The keys of properties to ignore and not modify.\n * @returns {Object} - The object with function recursively applied.\n */\nexport function applyFnToProps(obj, fn, type = 'string', ignoreKeys = []) {\n if (!obj || typeof obj !== 'object') return obj;\n Object.keys(obj).forEach(property => {\n if (typeof obj[property] === 'object') {\n applyFnToProps(obj[property], fn, type, ignoreKeys);\n } else {\n // eslint-disable-next-line valid-typeof\n if (typeof obj[property] === type && !ignoreKeys.includes(property)) obj[property] = fn(obj[property]);\n }\n });\n return obj;\n}","export const VITAL_NAMES = {\n FIRST_PAINT: 'fp',\n FIRST_CONTENTFUL_PAINT: 'fcp',\n FIRST_INPUT_DELAY: 'fi',\n LARGEST_CONTENTFUL_PAINT: 'lcp',\n CUMULATIVE_LAYOUT_SHIFT: 'cls',\n INTERACTION_TO_NEXT_PAINT: 'inp',\n TIME_TO_FIRST_BYTE: 'ttfb'\n};","import { onFCP } from 'web-vitals/attribution';\n// eslint-disable-next-line camelcase\nimport { iOSBelow16, initiallyHidden, isBrowserScope } from '../constants/runtime';\nimport { VITAL_NAMES } from './constants';\nimport { VitalMetric } from './vital-metric';\nexport const firstContentfulPaint = new VitalMetric(VITAL_NAMES.FIRST_CONTENTFUL_PAINT);\n\n/* First Contentful Paint - As of WV v3, it still imperfectly tries to detect document vis state asap and isn't supposed to report if page starts hidden. */\nif (isBrowserScope) {\n // eslint-disable-next-line camelcase\n if (iOSBelow16) {\n try {\n if (!initiallyHidden) {\n // see ios-version.js for detail on this following bug case; tldr: buffered flag doesn't work but getEntriesByType does\n const paintEntries = performance.getEntriesByType('paint');\n paintEntries.forEach(entry => {\n if (entry.name === 'first-contentful-paint') {\n firstContentfulPaint.update({\n value: Math.floor(entry.startTime)\n });\n }\n });\n }\n } catch (e) {\n // ignore\n }\n } else {\n onFCP(({\n value,\n attribution\n }) => {\n if (initiallyHidden || firstContentfulPaint.isValid) return;\n const attrs = {\n timeToFirstByte: attribution.timeToFirstByte,\n firstByteToFCP: attribution.firstByteToFCP,\n loadState: attribution.loadState\n };\n firstContentfulPaint.update({\n value,\n attrs\n });\n });\n }\n}","import { initiallyHidden, isBrowserScope } from '../constants/runtime';\nimport { VITAL_NAMES } from './constants';\nimport { VitalMetric } from './vital-metric';\nexport const firstPaint = new VitalMetric(VITAL_NAMES.FIRST_PAINT);\nif (isBrowserScope) {\n const handleEntries = entries => {\n entries.forEach(entry => {\n if (entry.name === 'first-paint' && !firstPaint.isValid) {\n observer.disconnect();\n\n /* Initial hidden state and pre-rendering not yet considered for first paint. See web-vitals onFCP for example. */\n firstPaint.update({\n value: entry.startTime\n });\n }\n });\n };\n let observer;\n try {\n if (PerformanceObserver.supportedEntryTypes.includes('paint') && !initiallyHidden) {\n observer = new PerformanceObserver(list => {\n // Delay by a microtask to workaround a bug in Safari where the\n // callback is invoked immediately, rather than in a separate task.\n // See: https://github.com/GoogleChrome/web-vitals/issues/277\n Promise.resolve().then(() => {\n handleEntries(list.getEntries());\n });\n });\n observer.observe({\n type: 'paint',\n buffered: true\n });\n }\n } catch (e) {\n // Do nothing.\n }\n}","import { globalScope, isBrowserScope, isiOS, originTime } from '../constants/runtime';\nimport { VITAL_NAMES } from './constants';\nimport { VitalMetric } from './vital-metric';\nimport { onTTFB } from 'web-vitals/attribution';\nexport const timeToFirstByte = new VitalMetric(VITAL_NAMES.TIME_TO_FIRST_BYTE);\n\n/**\n * onTTFB is not supported in the following scenarios:\n * - in a non-browser scope\n * - in browsers that do not support PerformanceNavigationTiming API\n * - in an iOS browser\n * - cross-origin iframes specifically in firefox and safari\n */\nif (isBrowserScope && typeof PerformanceNavigationTiming !== 'undefined' && !isiOS && window === window.parent) {\n onTTFB(({\n value,\n attribution\n }) => {\n if (timeToFirstByte.isValid) return;\n timeToFirstByte.update({\n value,\n attrs: {\n navigationEntry: attribution.navigationEntry\n }\n });\n });\n} else {\n if (!timeToFirstByte.isValid) {\n const entry = {};\n // convert real timestamps to relative timestamps to match web-vitals behavior\n for (let key in globalScope?.performance?.timing || {}) entry[key] = Math.max(globalScope?.performance?.timing[key] - originTime, 0);\n\n // ttfb is equiv to document's responseStart property in timing API --> https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming/responseStart\n timeToFirstByte.update({\n value: entry.responseStart,\n attrs: {\n navigationEntry: entry\n }\n });\n }\n}","export class VitalMetric {\n #subscribers = new Set();\n history = [];\n constructor(name, roundingMethod) {\n this.name = name;\n this.attrs = {};\n this.roundingMethod = typeof roundingMethod === 'function' ? roundingMethod : Math.floor;\n }\n update({\n value,\n attrs = {}\n }) {\n if (value === undefined || value === null || value < 0) return;\n const state = {\n value: this.roundingMethod(value),\n name: this.name,\n attrs\n };\n this.history.push(state);\n this.#subscribers.forEach(cb => {\n try {\n cb(state);\n } catch (e) {\n // ignore errors\n }\n });\n }\n get current() {\n return this.history[this.history.length - 1] || {\n value: undefined,\n name: this.name,\n attrs: {}\n };\n }\n get isValid() {\n return this.current.value >= 0;\n }\n subscribe(callback, buffered = true) {\n if (typeof callback !== 'function') return;\n this.#subscribers.add(callback);\n // emit full history on subscription (\"buffered\" behavior)\n if (this.isValid && !!buffered) this.history.forEach(state => {\n callback(state);\n });\n return () => {\n this.#subscribers.delete(callback);\n };\n }\n}","import { windowAddEventListener, documentAddEventListener } from '../event-listener/event-listener-opts';\nexport function checkState() {\n return typeof document === 'undefined' || document.readyState === 'complete';\n}\nexport function onWindowLoad(cb, useCapture) {\n if (checkState()) return cb();\n windowAddEventListener('load', cb, useCapture);\n}\nexport function onDOMContentLoaded(cb) {\n if (checkState()) return cb();\n documentAddEventListener('DOMContentLoaded', cb);\n}","import { globalScope } from '../constants/runtime';\nimport { now } from '../timing/now';\nexport const defaults = {\n beacon: 'bam.nr-data.net',\n errorBeacon: 'bam.nr-data.net'\n};\nexport function gosNREUM() {\n if (!globalScope.NREUM) {\n globalScope.NREUM = {};\n }\n if (typeof globalScope.newrelic === 'undefined') globalScope.newrelic = globalScope.NREUM;\n return globalScope.NREUM;\n}\nexport function gosNREUMInfo() {\n let nr = gosNREUM();\n const externallySupplied = nr.info || {};\n nr.info = {\n beacon: defaults.beacon,\n errorBeacon: defaults.errorBeacon,\n ...externallySupplied\n };\n return nr;\n}\nexport function gosNREUMLoaderConfig() {\n let nr = gosNREUM();\n const externallySupplied = nr.loader_config || {};\n nr.loader_config = {\n ...externallySupplied\n };\n return nr;\n}\nexport function gosNREUMInit() {\n let nr = gosNREUM();\n const externallySupplied = nr.init || {};\n nr.init = {\n ...externallySupplied\n };\n return nr;\n}\nexport function gosNREUMOriginals() {\n let nr = gosNREUM();\n if (!nr.o) {\n nr.o = {\n ST: globalScope.setTimeout,\n SI: globalScope.setImmediate,\n CT: globalScope.clearTimeout,\n XHR: globalScope.XMLHttpRequest,\n REQ: globalScope.Request,\n EV: globalScope.Event,\n PR: globalScope.Promise,\n MO: globalScope.MutationObserver,\n // this'll be undefined if not in a web window\n FETCH: globalScope.fetch,\n WS: globalScope.WebSocket\n };\n }\n return nr;\n}\nexport function setNREUMInitializedAgent(id, newAgentInstance) {\n let nr = gosNREUM();\n nr.initializedAgents ??= {};\n newAgentInstance.initializedAt = {\n ms: now(),\n date: new Date()\n };\n nr.initializedAgents[id] = newAgentInstance;\n}\n\n/**\n * Get the agent instance under the associated identifier on the global newrelic object.\n * @see setNREUMInitializedAgents\n * @returns Existing agent instance under newrelic.initializedAgent[id], or undefined if it does not exist.\n */\nexport function getNREUMInitializedAgent(id) {\n let nr = gosNREUM();\n return nr.initializedAgents?.[id];\n}\nexport function addToNREUM(fnName, fn) {\n let nr = gosNREUM();\n nr[fnName] = fn;\n}\nexport function NREUMinitialized() {\n const nr = gosNREUM();\n nr.initialized = true;\n}\nexport function gosCDN() {\n gosNREUMInfo();\n gosNREUMInit();\n gosNREUMOriginals();\n gosNREUMLoaderConfig();\n return gosNREUM();\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { documentAddEventListener } from '../event-listener/event-listener-opts';\n\n/**\n * @param {function} cb - called when a visibility change occurs with the vis state at that time\n * @param {boolean} [toHiddenOnly=false] - only execute the 'cb' when the vis is changing to the hidden state; no arg is passed to 'cb' if used\n * @returns void\n */\nexport function subscribeToVisibilityChange(cb, toHiddenOnly = false, capture, abortSignal) {\n documentAddEventListener('visibilitychange', handleVisibilityChange, capture, abortSignal);\n function handleVisibilityChange() {\n if (toHiddenOnly) {\n // trigger cb on change to hidden state only\n if (document.visibilityState === 'hidden') cb();\n return;\n }\n cb(document.visibilityState);\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Wraps `addEventListener` and `removeEventListener` for instrumentation.\n * This module is used directly by: session_trace.\n * It is also called by -> wrapXhr <-, so see \"wrap-xhr.js\" for features that use this indirectly.\n */\nimport { ee as baseEE, contextId } from '../event-emitter/contextual-ee';\nimport { createWrapperWithEmitter as wfn } from './wrap-function';\nimport { getOrSet } from '../util/get-or-set';\nimport { globalScope, isBrowserScope } from '../constants/runtime';\nconst wrapped = {};\nconst XHR = globalScope.XMLHttpRequest;\nconst ADD_EVENT_LISTENER = 'addEventListener';\nconst REMOVE_EVENT_LISTENER = 'removeEventListener';\nconst flag = \"nr@wrapped:\".concat(contextId);\n\n/**\n * Wraps `addEventListener` and `removeEventListener` on: global scope; the prototype of `XMLHttpRequest`, and\n * `document` (if in a browser scope). Adds custom events in context of a new emitter scoped only to these methods.\n * @param {Object} sharedEE - The shared event emitter on which a new scoped\n * event emitter will be based.\n * @returns {Object} Scoped event emitter with a debug ID of `events`.\n */\nexport function wrapEvents(sharedEE) {\n var ee = scopedEE(sharedEE);\n\n // Notice if our wrapping never ran yet, the falsy NaN will not early return; but if it has,\n // then we increment the count to track # of feats using this at runtime.\n if (wrapped[ee.debugId]++) return ee;\n wrapped[ee.debugId] = 1; // otherwise, first feature to wrap events\n var wrapFn = wfn(ee, true);\n\n // Guard against instrumenting environments w/o necessary features\n if ('getPrototypeOf' in Object) {\n if (isBrowserScope) findEventListenerProtoAndCb(document, wrapNode);\n findEventListenerProtoAndCb(globalScope, wrapNode);\n findEventListenerProtoAndCb(XHR.prototype, wrapNode);\n }\n ee.on(ADD_EVENT_LISTENER + '-start', function (args, target) {\n var originalListener = args[1];\n if (originalListener === null || typeof originalListener !== 'function' && typeof originalListener !== 'object') {\n return;\n }\n var wrapped = getOrSet(originalListener, flag, function () {\n var listener = {\n object: wrapHandleEvent,\n function: originalListener\n }[typeof originalListener];\n return listener ? wrapFn(listener, 'fn-', null, listener.name || 'anonymous') : originalListener;\n function wrapHandleEvent() {\n if (typeof originalListener.handleEvent !== 'function') return;\n return originalListener.handleEvent.apply(originalListener, arguments);\n }\n });\n this.wrapped = args[1] = wrapped;\n });\n ee.on(REMOVE_EVENT_LISTENER + '-start', function (args) {\n args[1] = this.wrapped || args[1];\n });\n function wrapNode(node) {\n wrapFn.inPlace(node, [ADD_EVENT_LISTENER, REMOVE_EVENT_LISTENER], '-', uniqueListener);\n }\n function uniqueListener(args, obj) {\n // Context for the listener is stored on itself.\n return args[1];\n }\n return ee;\n}\n/**\n * Find the base prototype of 'object' that has its own \"addEventListener\" property, and run some function on it.\n * @param {Object} object - the initial object to traverse prototype chain on\n * @param {Function} cb - the function to run on the ancestral object once found, accepts an object as a arg\n * @param {Array} rest - [optional] any additional arguments to pass to the cb\n */\nfunction findEventListenerProtoAndCb(object, cb, ...rest) {\n let step = object;\n while (typeof step === 'object' && !Object.prototype.hasOwnProperty.call(step, ADD_EVENT_LISTENER)) {\n step = Object.getPrototypeOf(step);\n }\n if (step) cb(step, ...rest);\n}\n\n/**\n * Returns an event emitter scoped specifically for the `events` context. This scoping is a remnant from when all the\n * features shared the same group in the event, to isolate events between features. It will likely be revisited.\n * @param {Object} sharedEE - Optional event emitter on which to base the scoped emitter.\n * Uses `ee` on the global scope if undefined).\n * @returns {Object} Scoped event emitter with a debug ID of 'events'.\n */\nexport function scopedEE(sharedEE) {\n return (sharedEE || baseEE).get('events');\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Provides helper functions for wrapping functions in various scenarios.\n */\n\nimport { ee } from '../event-emitter/contextual-ee';\nimport { bundleId } from '../ids/bundle-id';\nexport const flag = \"nr@original:\".concat(bundleId);\n\n/**\n * A convenience alias of `hasOwnProperty`.\n * @type {function}\n */\nvar has = Object.prototype.hasOwnProperty;\n\n/**\n * For tracking whether an event is already being emitted inside the wrapper.\n * @type {boolean}\n */\nvar inWrapper = false;\n\n// eslint-disable-next-line\nexport default createWrapperWithEmitter;\n\n/**\n * Wraps a function in order to emit events on start, end, and error.\n * @param {Object} [emitter] - The desired emitter for events emitted by the wrapper. Defaults to the global emitter.\n * @param {boolean} always - If `true`, emit events even if already emitting an event.\n * @returns {function} The wrapped function.\n */\nexport function createWrapperWithEmitter(emitter, always) {\n emitter || (emitter = ee);\n wrapFn.inPlace = inPlace;\n\n /**\n * A flag used to determine if a native function has already been wrapped.\n * As a property on a wrapped function, contains the original function.\n * @type {string}\n */\n wrapFn.flag = flag;\n return wrapFn;\n\n /**\n * Wraps a function with event emitting functionality.\n * @param {function} fn - The function to wrap.\n * @param {string} prefix - A prefix for the names of emitted events.\n * @param {function|object} getContext - The function or object that will serve as the 'this' context for handlers of events emitted by this wrapper.\n * @param {string} methodName - The name of the method being wrapped.\n * @param {boolean} bubble - If true, emitted events should also bubble up to the old emitter upon which the `emitter` in the current scope was based (if it defines one).\n * @returns {function} The wrapped function.\n */\n function wrapFn(fn, prefix, getContext, methodName, bubble) {\n // Unless fn is both wrappable and unwrapped, return it unchanged.\n if (notWrappable(fn)) return fn;\n if (!prefix) prefix = '';\n nrWrapper[flag] = fn;\n copy(fn, nrWrapper, emitter);\n return nrWrapper;\n\n /**\n * A wrapper function that emits events before and after calling the wrapped function.\n * Any arguments will be passed along to the original function.\n * @returns {any} The return value of the wrapped function.\n */\n function nrWrapper() {\n var args;\n var originalThis;\n var ctx;\n var result;\n try {\n originalThis = this;\n args = [...arguments];\n if (typeof getContext === 'function') {\n ctx = getContext(args, originalThis);\n } else {\n ctx = getContext || {};\n }\n } catch (e) {\n report([e, '', [args, originalThis, methodName], ctx], emitter);\n }\n\n // Warning: start events may mutate args!\n safeEmit(prefix + 'start', [args, originalThis, methodName], ctx, bubble);\n try {\n result = fn.apply(originalThis, args);\n return result;\n } catch (err) {\n safeEmit(prefix + 'err', [args, originalThis, err], ctx, bubble);\n\n // rethrow error so we don't effect execution by observing.\n throw err;\n } finally {\n // happens no matter what.\n safeEmit(prefix + 'end', [args, originalThis, result], ctx, bubble);\n }\n }\n }\n\n /**\n * Creates wrapper functions around each of an array of methods on a specified object.\n * @param {Object} obj The object to which the specified methods belong.\n * @param {string[]} methods An array of method names to be wrapped.\n * @param {string} [prefix=''] A prefix to add to the names of emitted events. If `-` is the first character, also\n * adds the method name before the prefix.\n * @param {function|object} [getContext] The function or object that will serve as the 'this' context for handlers\n * of events emitted by this wrapper.\n * @param {boolean} [bubble=false] If `true`, emitted events should also bubble up to the old emitter upon which\n * the `emitter` in the current scope was based (if it defines one).\n */\n function inPlace(obj, methods, prefix, getContext, bubble) {\n if (!prefix) prefix = '';\n\n // If prefix starts with '-' set this boolean to add the method name to the prefix before passing each one to wrap.\n const prependMethodPrefix = prefix.charAt(0) === '-';\n for (let i = 0; i < methods.length; i++) {\n const method = methods[i];\n const fn = obj[method];\n\n // Unless fn is both wrappable and unwrapped, bail so we don't add extra properties with undefined values.\n if (notWrappable(fn)) continue;\n obj[method] = wrapFn(fn, prependMethodPrefix ? method + prefix : prefix, getContext, method, bubble);\n }\n }\n\n /**\n * Emits an event using the `emit` method of the `emitter` object in the executing scope, but only if an event is not\n * already being emitted (except when the executing scope defines `always` as `true`).\n * @param {string} evt - The name of the event to be emitted.\n * @param {array} arr - An array of arguments to pass with the event.\n * @param {Object} store - The function or object that will serve as the 'this'\n * context when applying handler functions for this event.\n * @param {boolean} bubble - If `true`, emitted events should also\n * bubble up to the old emitter upon which the `emitter` in the\n * executing scope was based (if it defines one).\n */\n function safeEmit(evt, arr, store, bubble) {\n if (inWrapper && !always) return;\n var prev = inWrapper;\n inWrapper = true;\n try {\n emitter.emit(evt, arr, store, always, bubble);\n } catch (e) {\n report([e, evt, arr, store], emitter);\n }\n inWrapper = prev;\n }\n}\n\n/**\n * Emits an \"internal-error\" event. Used to report errors encountered when emitting events using `safeEmit`.\n * @param {array} args - Arguments to be passed to the \"internal-error\" event.\n * @param {Object} [emitter] - The (optional) desired event emitter. Defaults to the global event emitter.\n */\nfunction report(args, emitter) {\n emitter || (emitter = ee);\n try {\n emitter.emit('internal-error', args);\n } catch (err) {\n // do nothing\n }\n}\n\n/**\n * Copies properties from one object to another. Used for creating a wrapper function from an original function and for\n * copying an original function to a property of a wrapper function named by `flag` in the executing context.\n * @param {Object} from - The source function or object.\n * @param {Object} to - The destination function or object.\n * @param {Object} [emitter] - The (optional) desired event emitter if errors are encountered while copying.\n * Defaults to the global event emitter.\n * @returns {object} - The destination founction or object with copied properties.\n */\nfunction copy(from, to, emitter) {\n if (Object.defineProperty && Object.keys) {\n // Create accessors that proxy to actual function\n try {\n var keys = Object.keys(from);\n // eslint-disable-next-line\n keys.forEach(function (key) {\n Object.defineProperty(to, key, {\n get: function () {\n return from[key];\n },\n // eslint-disable-next-line\n set: function (val) {\n from[key] = val;\n return val;\n }\n });\n });\n return to;\n } catch (e) {\n report([e], emitter);\n }\n }\n // fall back to copying properties\n for (var i in from) {\n if (has.call(from, i)) {\n to[i] = from[i];\n }\n }\n return to;\n}\n\n/**\n * Determines whether a function is eligible to be wrapped in part based on whether it has already been wrapped.\n * @param {function} fn - The function in question.\n * @returns {boolean} Whether the passed function is ineligible to be wrapped.\n */\nfunction notWrappable(fn) {\n return !(fn && typeof fn === 'function' && fn.apply && !fn[flag]);\n}","import { isPureObject } from '../../../common/util/type-check';\n\n/**\n * @typedef {object} GQLMetadata\n * @property {string} operationName Name of the operation\n * @property {string} operationType Type of the operation\n * @property {string} operationFramework Framework responsible for the operation\n */\n\n/**\n * Parses and returns the graphql metadata from a network request. If the network\n * request is not a graphql call, undefined will be returned.\n * @param {object|string} body Ajax request body\n * @param {string} query Ajax request query param string\n * @returns {GQLMetadata | undefined}\n */\nexport function parseGQL({\n body,\n query\n} = {}) {\n if (!body && !query) return;\n try {\n const gqlBody = parseBatchGQL(parseGQLContents(body));\n if (gqlBody) return gqlBody;\n const gqlQuery = parseSingleGQL(parseGQLQueryString(query));\n if (gqlQuery) return gqlQuery;\n } catch (err) {\n // parsing failed, return undefined\n }\n}\n\n/**\n * @param {string|Object} gql The GraphQL object body sent to a GQL server\n * @returns {GQLMetadata}\n */\nfunction parseSingleGQL(contents) {\n if (typeof contents !== 'object' || !contents.query || typeof contents.query !== 'string') return;\n\n /** parses gql query string and returns [fullmatch, type match, name match] */\n const matches = contents.query.trim().match(/^(query|mutation|subscription)\\s?(\\w*)/);\n const operationType = matches?.[1];\n if (!operationType) return;\n const operationName = contents.operationName || matches?.[2] || 'Anonymous';\n return {\n operationName,\n // the operation name of the indiv query\n operationType,\n // query, mutation, or subscription,\n operationFramework: 'GraphQL'\n };\n}\nfunction parseBatchGQL(contents) {\n if (!contents) return;\n if (!Array.isArray(contents)) contents = [contents];\n const opNames = [];\n const opTypes = [];\n for (let content of contents) {\n const operation = parseSingleGQL(content);\n if (!operation) continue;\n opNames.push(operation.operationName);\n opTypes.push(operation.operationType);\n }\n if (!opTypes.length) return;\n return {\n operationName: opNames.join(','),\n // the operation name of the indiv query -- joined by ',' for batched results\n operationType: opTypes.join(','),\n // query, mutation, or subscription -- joined by ',' for batched results\n operationFramework: 'GraphQL'\n };\n}\nfunction parseGQLContents(gqlContents) {\n let contents;\n if (!gqlContents || typeof gqlContents !== 'string' && typeof gqlContents !== 'object') return;else if (typeof gqlContents === 'string') contents = JSON.parse(gqlContents);else contents = gqlContents;\n if (!isPureObject(contents) && !Array.isArray(contents)) return;\n let isValid = false;\n if (Array.isArray(contents)) isValid = contents.some(x => validateGQLObject(x));else isValid = validateGQLObject(contents);\n if (!isValid) return;\n return contents;\n}\nfunction parseGQLQueryString(gqlQueryString) {\n if (!gqlQueryString || typeof gqlQueryString !== 'string') return;\n const params = new URLSearchParams(gqlQueryString);\n return parseGQLContents(Object.fromEntries(params));\n}\nfunction validateGQLObject(obj) {\n return !(typeof obj !== 'object' || !obj.query || typeof obj.query !== 'string');\n}","/**\n * Tests a passed object to see if it is a pure object or not. All non-primatives in JS\n * are technically objects and would pass a `typeof` check.\n * @param {*} obj Input object to be tested\n**/\nexport function isPureObject(obj) {\n return obj?.constructor === {}.constructor;\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { stringify } from '../../../common/util/stringify';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { setDenyList, shouldCollectEvent } from '../../../common/deny-list/deny-list';\nimport { FEATURE_NAME } from '../constants';\nimport { FEATURE_NAMES, FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { parseGQL } from './gql';\nimport { nullable, numeric, getAddStringContext, addCustomAttributes } from '../../../common/serialize/bel-serializer';\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n const harvestTimeSeconds = agentRef.init.ajax.harvestTimeSeconds || 10;\n setDenyList(agentRef.runtime.denyList);\n this.underSpaEvents = {};\n const classThis = this;\n\n // --- v Used by old spa feature\n this.ee.on('interactionDone', (interaction, wasSaved) => {\n if (!this.underSpaEvents[interaction.id]) return;\n if (!wasSaved) {\n // if the ixn was saved, then its ajax reqs are part of the payload whereas if it was discarded, it should still be harvested in the ajax feature itself\n this.underSpaEvents[interaction.id].forEach(item => this.events.add(item));\n }\n delete this.underSpaEvents[interaction.id];\n });\n // --- ^\n // --- v Used by new soft nav\n registerHandler('returnAjax', event => this.events.add(event), this.featureName, this.ee);\n // --- ^\n registerHandler('xhr', function () {\n // the EE-drain system not only switches \"this\" but also passes a new EventContext with info. Should consider platform refactor to another system which passes a mutable context around separately and predictably to avoid problems like this.\n classThis.storeXhr(...arguments, this); // this switches the context back to the class instance while passing the NR context as an argument -- see \"ctx\" in storeXhr\n }, this.featureName, this.ee);\n this.waitForFlags([]).then(() => {\n const scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n getPayload: options => this.makeHarvestPayload(options.retry)\n }, this);\n scheduler.startTimer(harvestTimeSeconds);\n this.drain();\n });\n }\n storeXhr(params, metrics, startTime, endTime, type, ctx) {\n metrics.time = startTime;\n\n // send to session traces\n let hash;\n if (params.cat) {\n hash = stringify([params.status, params.cat]);\n } else {\n hash = stringify([params.status, params.host, params.pathname]);\n }\n const shouldCollect = shouldCollectEvent(params);\n const shouldOmitAjaxMetrics = this.agentRef.init.feature_flags?.includes('ajax_metrics_deny_list');\n const jserrorsInUse = Boolean(this.agentRef.features?.[FEATURE_NAMES.jserrors]);\n\n // Report ajax timeslice metric (to be harvested by jserrors feature, but only if it's running).\n if (jserrorsInUse && (shouldCollect || !shouldOmitAjaxMetrics)) {\n this.agentRef.sharedAggregator.add('xhr', hash, params, metrics);\n }\n if (!shouldCollect) {\n if (params.hostname === this.agentRef.info.errorBeacon || this.agentRef.init.proxy?.beacon && params.hostname === this.agentRef.init.proxy.beacon) {\n // This doesn't make a distinction if the same-domain request is going to a different port or path...\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Ajax/Events/Excluded/Agent'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (shouldOmitAjaxMetrics) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Ajax/Metrics/Excluded/Agent'], undefined, FEATURE_NAMES.metrics, this.ee);\n } else {\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Ajax/Events/Excluded/App'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (shouldOmitAjaxMetrics) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Ajax/Metrics/Excluded/App'], undefined, FEATURE_NAMES.metrics, this.ee);\n }\n return; // do not send this ajax as an event\n }\n handle('bstXhrAgg', ['xhr', hash, params, metrics], undefined, FEATURE_NAMES.sessionTrace, this.ee); // have trace feature harvest AjaxNode\n\n const event = {\n method: params.method,\n status: params.status,\n domain: params.host,\n path: params.pathname,\n requestSize: metrics.txSize,\n responseSize: metrics.rxSize,\n type,\n startTime,\n endTime,\n callbackDuration: metrics.cbTime\n };\n if (ctx.dt) {\n event.spanId = ctx.dt.spanId;\n event.traceId = ctx.dt.traceId;\n event.spanTimestamp = Math.floor(this.agentRef.runtime.timeKeeper.correctAbsoluteTimestamp(ctx.dt.timestamp));\n }\n\n // parsed from the AJAX body, looking for operationName param & parsing query for operationType\n event.gql = params.gql = parseGQL({\n body: ctx.body,\n query: ctx.parsedOrigin?.search\n });\n if (event.gql) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Ajax/Events/GraphQL/Bytes-Added', stringify(event.gql).length], undefined, FEATURE_NAMES.metrics, this.ee);\n const softNavInUse = Boolean(this.agentRef.features?.[FEATURE_NAMES.softNav]);\n if (softNavInUse) {\n // For newer soft nav (when running), pass the event to it for evaluation -- either part of an interaction or is given back\n handle('ajax', [event], undefined, FEATURE_NAMES.softNav, this.ee);\n } else if (ctx.spaNode) {\n // For old spa (when running), if the ajax happened inside an interaction, hold it until the interaction finishes\n const interactionId = ctx.spaNode.interaction.id;\n this.underSpaEvents[interactionId] ??= [];\n this.underSpaEvents[interactionId].push(event);\n } else {\n this.events.add(event);\n }\n }\n serializer(eventBuffer) {\n const addString = getAddStringContext(this.agentIdentifier);\n let payload = 'bel.7;';\n for (let i = 0; i < eventBuffer.length; i++) {\n const event = eventBuffer[i];\n const fields = [numeric(event.startTime), numeric(event.endTime - event.startTime), numeric(0),\n // callbackEnd\n numeric(0),\n // no callbackDuration for non-SPA events\n addString(event.method), numeric(event.status), addString(event.domain), addString(event.path), numeric(event.requestSize), numeric(event.responseSize), event.type === 'fetch' ? 1 : '', addString(0),\n // nodeId\n nullable(event.spanId, addString, true) +\n // guid\n nullable(event.traceId, addString, true) +\n // traceId\n nullable(event.spanTimestamp, numeric, false) // timestamp\n ];\n let insert = '2,';\n\n // Since configuration objects (like info) are created new each time they are set, we have to grab the current pointer to the attr object here.\n const jsAttributes = this.agentRef.info.jsAttributes;\n\n // add custom attributes\n // gql decorators are added as custom attributes to alleviate need for new BEL schema\n const attrParts = addCustomAttributes({\n ...(jsAttributes || {}),\n ...(event.gql || {})\n }, addString);\n fields.unshift(numeric(attrParts.length));\n insert += fields.join(',');\n if (attrParts && attrParts.length > 0) {\n insert += ';' + attrParts.join(';');\n }\n if (i + 1 < eventBuffer.length) insert += ';';\n payload += insert;\n }\n return payload;\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.ajax;","import { RAGE_CLICK_THRESHOLD_EVENTS, RAGE_CLICK_THRESHOLD_MS } from '../../constants';\nexport class AggregatedUserAction {\n constructor(evt, selectorPath) {\n this.event = evt;\n this.count = 1;\n this.originMs = Math.floor(evt.timeStamp);\n this.relativeMs = [0];\n this.selectorPath = selectorPath;\n this.rageClick = undefined;\n }\n\n /**\n * Aggregates the count and maintains the relative MS array for matching events\n * Will determine if a rage click was observed as part of the aggregation\n * @param {Event} evt\n * @returns {void}\n */\n aggregate(evt) {\n this.count++;\n this.relativeMs.push(Math.floor(evt.timeStamp - this.originMs));\n if (this.isRageClick()) this.rageClick = true;\n }\n\n /**\n * Determines if the current set of relative ms values constitutes a rage click\n * @returns {boolean}\n */\n isRageClick() {\n const len = this.relativeMs.length;\n return this.event.type === 'click' && len >= RAGE_CLICK_THRESHOLD_EVENTS && this.relativeMs[len - 1] - this.relativeMs[len - RAGE_CLICK_THRESHOLD_EVENTS] < RAGE_CLICK_THRESHOLD_MS;\n }\n}","import { generateSelectorPath } from '../../../../common/dom/selector-path';\nimport { OBSERVED_WINDOW_EVENTS } from '../../constants';\nimport { AggregatedUserAction } from './aggregated-user-action';\nexport class UserActionsAggregator {\n /** @type {AggregatedUserAction=} */\n #aggregationEvent = undefined;\n #aggregationKey = '';\n get aggregationEvent() {\n // if this is accessed externally, we need to be done aggregating on it\n // to prevent potential mutability and duplication issues, so the state is cleared upon returning.\n // This value may need to be accessed during an unload harvest.\n const finishedEvent = this.#aggregationEvent;\n this.#aggregationKey = '';\n this.#aggregationEvent = undefined;\n return finishedEvent;\n }\n\n /**\n * Process the event and determine if a new aggregation set should be made or if it should increment the current aggregation\n * @param {Event} evt The event supplied by the addEventListener callback\n * @returns {AggregatedUserAction|undefined} The previous aggregation set if it has been completed by processing the current event\n */\n process(evt) {\n if (!evt) return;\n const selectorPath = getSelectorPath(evt);\n const aggregationKey = getAggregationKey(evt, selectorPath);\n if (!!aggregationKey && aggregationKey === this.#aggregationKey) {\n // an aggregation exists already, so lets just continue to increment\n this.#aggregationEvent.aggregate(evt);\n } else {\n // return the prev existing one (if there is one)\n const finishedEvent = this.#aggregationEvent;\n // then set as this new event aggregation\n this.#aggregationKey = aggregationKey;\n this.#aggregationEvent = new AggregatedUserAction(evt, selectorPath);\n return finishedEvent;\n }\n }\n}\n\n/**\n * Generates a selector path for the event, starting with simple cases like window or document and getting more complex for dom-tree traversals as needed.\n * Will return a random selector path value if no other path can be determined, to force the aggregator to skip aggregation for this event.\n * @param {Event} evt\n * @returns {string}\n */\nfunction getSelectorPath(evt) {\n let selectorPath;\n if (OBSERVED_WINDOW_EVENTS.includes(evt.type) || evt.target === window) selectorPath = 'window';else if (evt.target === document) selectorPath = 'document';\n // if still no selectorPath, generate one from target tree that includes elem ids\n else selectorPath = generateSelectorPath(evt.target);\n // if STILL no selectorPath, it will return undefined which will skip aggregation for this event\n return selectorPath;\n}\n\n/**\n * Returns an aggregation key based on the event type and the selector path of the event's target.\n * Scrollend events are aggregated into one set, no matter what.\n * @param {Event} evt\n * @param {string} selectorPath\n * @returns {string}\n */\nfunction getAggregationKey(evt, selectorPath) {\n let aggregationKey = evt.type;\n /** aggregate all scrollends into one set (if sequential), no matter what their target is\n * the aggregation group's selector path with be reflected as the first one observed\n * due to the way the aggregation logic works (by storing the initial value and aggregating it) */\n if (evt.type !== 'scrollend') aggregationKey += '-' + selectorPath;\n return aggregationKey;\n}","/**\n * Generates a CSS selector path for the given element, if possible\n * @param {HTMLElement} elem\n * @param {boolean} includeId\n * @param {boolean} includeClass\n * @returns {string|undefined}\n */\nexport const generateSelectorPath = elem => {\n if (!elem) return;\n const getNthOfTypeIndex = node => {\n try {\n let i = 1;\n const {\n tagName\n } = node;\n while (node.previousElementSibling) {\n if (node.previousElementSibling.tagName === tagName) i++;\n node = node.previousElementSibling;\n }\n return i;\n } catch (err) {\n // do nothing for now. An invalid child count will make the path selector not return a nth-of-type selector statement\n }\n };\n let pathSelector = '';\n let index = getNthOfTypeIndex(elem);\n try {\n while (elem?.tagName) {\n const {\n id,\n localName\n } = elem;\n const selector = [localName, id ? \"#\".concat(id) : '', pathSelector ? \">\".concat(pathSelector) : ''].join('');\n pathSelector = selector;\n elem = elem.parentNode;\n }\n } catch (err) {\n // do nothing for now\n }\n return pathSelector ? index ? \"\".concat(pathSelector, \":nth-of-type(\").concat(index, \")\") : pathSelector : undefined;\n};","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { stringify } from '../../../common/util/stringify';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { cleanURL } from '../../../common/url/clean-url';\nimport { FEATURE_NAME } from '../constants';\nimport { initialLocation, isBrowserScope } from '../../../common/constants/runtime';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { warn } from '../../../common/util/console';\nimport { now } from '../../../common/timing/now';\nimport { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { applyFnToProps } from '../../../common/util/traverse';\nimport { IDEAL_PAYLOAD_SIZE } from '../../../common/constants/agent-constants';\nimport { FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { UserActionsAggregator } from './user-actions/user-actions-aggregator';\nimport { isIFrameWindow } from '../../../common/dom/iframe';\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n this.eventsPerHarvest = 1000;\n this.harvestTimeSeconds = agentRef.init.generic_events.harvestTimeSeconds;\n this.referrerUrl = isBrowserScope && document.referrer ? cleanURL(document.referrer) : undefined;\n this.waitForFlags(['ins']).then(([ins]) => {\n if (!ins) {\n this.blocked = true;\n this.deregisterDrain();\n return;\n }\n if (agentRef.init.page_action.enabled) {\n registerHandler('api-addPageAction', (timestamp, name, attributes) => {\n this.addEvent({\n ...attributes,\n eventType: 'PageAction',\n timestamp: Math.floor(this.agentRef.runtime.timeKeeper.correctRelativeTimestamp(timestamp)),\n timeSinceLoad: timestamp / 1000,\n actionName: name,\n referrerUrl: this.referrerUrl,\n ...(isBrowserScope && {\n browserWidth: window.document.documentElement?.clientWidth,\n browserHeight: window.document.documentElement?.clientHeight\n })\n });\n }, this.featureName, this.ee);\n }\n let addUserAction;\n if (isBrowserScope && agentRef.init.user_actions.enabled) {\n this.userActionAggregator = new UserActionsAggregator();\n addUserAction = aggregatedUserAction => {\n try {\n /** The aggregator process only returns an event when it is \"done\" aggregating -\n * so we still need to validate that an event was given to this method before we try to add */\n if (aggregatedUserAction?.event) {\n const {\n target,\n timeStamp,\n type\n } = aggregatedUserAction.event;\n this.addEvent({\n eventType: 'UserAction',\n timestamp: Math.floor(this.agentRef.runtime.timeKeeper.correctRelativeTimestamp(timeStamp)),\n action: type,\n actionCount: aggregatedUserAction.count,\n actionDuration: aggregatedUserAction.relativeMs[aggregatedUserAction.relativeMs.length - 1],\n actionMs: aggregatedUserAction.relativeMs,\n rageClick: aggregatedUserAction.rageClick,\n target: aggregatedUserAction.selectorPath,\n ...(isIFrameWindow(window) && {\n iframe: true\n }),\n ...(target?.id && {\n targetId: target.id\n }),\n ...(target?.tagName && {\n targetTag: target.tagName\n }),\n ...(target?.type && {\n targetType: target.type\n }),\n ...(target?.className && {\n targetClass: target.className\n })\n });\n }\n } catch (e) {\n // do nothing for now\n }\n };\n registerHandler('ua', evt => {\n /** the processor will return the previously aggregated event if it has been completed by processing the current event */\n addUserAction(this.userActionAggregator.process(evt));\n }, this.featureName, this.ee);\n }\n\n /**\n * is it worth complicating the agent and skipping the POs for single repeating queries? maybe,\n * but right now it was less desirable simply because it is a nice benefit of populating the event buffer\n * immediately as events happen for payload evaluation purposes and that becomes a little more chaotic\n * with an arbitrary query method. note: eventTypes: [...types] does not support the 'buffered' flag so we have\n * to create up to two PO's here.\n */\n const performanceTypesToCapture = [...(agentRef.init.performance.capture_marks ? ['mark'] : []), ...(agentRef.init.performance.capture_measures ? ['measure'] : [])];\n if (performanceTypesToCapture.length) {\n try {\n performanceTypesToCapture.forEach(type => {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const observer = new PerformanceObserver(list => {\n list.getEntries().forEach(entry => {\n try {\n this.addEvent({\n eventType: 'BrowserPerformance',\n timestamp: Math.floor(agentRef.runtime.timeKeeper.correctRelativeTimestamp(entry.startTime)),\n entryName: entry.name,\n entryDuration: entry.duration,\n entryType: type,\n ...(entry.detail && {\n entryDetail: entry.detail\n })\n });\n } catch (err) {}\n });\n });\n observer.observe({\n buffered: true,\n type\n });\n }\n });\n } catch (err) {\n // Something failed in our set up, likely the browser does not support PO's... do nothing\n }\n }\n this.harvestScheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n onUnload: () => addUserAction?.(this.userActionAggregator.aggregationEvent)\n }, this);\n this.harvestScheduler.harvest.on(FEATURE_TO_ENDPOINT[this.featureName], options => this.makeHarvestPayload(options.retry));\n this.harvestScheduler.startTimer(this.harvestTimeSeconds, 0);\n this.drain();\n });\n }\n\n // WARNING: Insights times are in seconds. EXCEPT timestamp, which is in ms.\n /** Some keys are set by the query params or request headers sent with the harvest and override the body values, so check those before adding new standard body values...\n * see harvest.js#baseQueryString for more info on the query params\n * Notably:\n * * name: set by the `t=` query param\n * * appId: set by the `a=` query param\n * * standalone: set by the `sa=` query param\n * * session: set by the `s=` query param\n * * sessionTraceId: set by the `ptid=` query param\n * * userAgent*: set by the userAgent header\n * @param {object=} obj the event object for storing in the event buffer\n * @returns void\n */\n addEvent(obj = {}) {\n if (!obj || !Object.keys(obj).length) return;\n if (!obj.eventType) {\n warn(44);\n return;\n }\n for (let key in obj) {\n let val = obj[key];\n obj[key] = val && typeof val === 'object' ? stringify(val) : val;\n }\n const defaultEventAttributes = {\n /** should be overridden by the event-specific attributes, but just in case -- set it to now() */\n timestamp: Math.floor(this.agentRef.runtime.timeKeeper.correctRelativeTimestamp(now())),\n /** all generic events require pageUrl(s) */\n pageUrl: cleanURL('' + initialLocation),\n currentUrl: cleanURL('' + location)\n };\n const eventAttributes = {\n /** Agent-level custom attributes */\n ...(this.agentRef.info.jsAttributes || {}),\n /** Fallbacks for required properties in-case the event did not supply them, should take precedence over agent-level custom attrs */\n ...defaultEventAttributes,\n /** Event-specific attributes take precedence over agent-level custom attributes and fallbacks */\n ...obj\n };\n this.events.add(eventAttributes);\n this.checkEventLimits();\n }\n serializer(eventBuffer) {\n return applyFnToProps({\n ins: eventBuffer\n }, this.obfuscator.obfuscateString.bind(this.obfuscator), 'string');\n }\n queryStringsBuilder() {\n return {\n ua: this.agentRef.info.userAttributes,\n at: this.agentRef.info.atts\n };\n }\n checkEventLimits() {\n // check if we've reached any harvest limits...\n if (this.events.byteSize() > IDEAL_PAYLOAD_SIZE) {\n this.ee.emit(SUPPORTABILITY_METRIC_CHANNEL, ['GenericEvents/Harvest/Max/Seen']);\n this.harvestScheduler.runHarvest();\n }\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.genericEvents;\nexport const IDEAL_PAYLOAD_SIZE = 64000;\nexport const MAX_PAYLOAD_SIZE = 1000000;\nexport const OBSERVED_EVENTS = ['auxclick', 'click', 'copy', 'keydown', 'paste', 'scrollend'];\nexport const OBSERVED_WINDOW_EVENTS = ['focus', 'blur'];\nexport const RAGE_CLICK_THRESHOLD_EVENTS = 4;\nexport const RAGE_CLICK_THRESHOLD_MS = 1000;","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nconst canonicalFunctionNameRe = /([a-z0-9]+)$/i;\n\n/**\n * Given a function name string, extracts only an alphanumeric segment at the end of the string (if one exists).\n * This is useful for stack traces, where functions might not be named (e.g., anonymous, computed).\n *\n * @param {string} functionNameString - The original function name string.\n * @returns {string|undefined} The canonical function name, or undefined if the input is falsy or no alphanumeric segments are found.\n */\nexport function canonicalFunctionName(functionNameString) {\n if (!functionNameString) return;\n const match = functionNameString.match(canonicalFunctionNameRe);\n if (match) return match[1];\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nvar stripNewlinesRegex = /^\\n+|\\n+$/g;\nvar MAX_STACK_TRACE_LENGTH = 65530;\nexport function formatStackTrace(stackLines) {\n return truncateStackLines(stackLines).replace(stripNewlinesRegex, '');\n}\n\n// takes array of stack lines and returns string with top 50 and buttom 50 lines\nfunction truncateStackLines(stackLines) {\n var stackString;\n if (stackLines.length > 100) {\n var truncatedLines = stackLines.length - 100;\n stackString = stackLines.slice(0, 50).join('\\n');\n stackString += '\\n< ...truncated ' + truncatedLines + ' lines... >\\n';\n stackString += stackLines.slice(-50).join('\\n');\n } else {\n stackString = stackLines.join('\\n');\n }\n return stackString;\n}\n\n// truncates stack string to limit what is sent to backend\nexport function truncateSize(stackString) {\n return stackString.length > MAX_STACK_TRACE_LENGTH ? stackString.substr(0, MAX_STACK_TRACE_LENGTH) : stackString;\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { initialLocation } from '../constants/runtime';\nimport { cleanURL } from './clean-url';\n\n/**\n * Converts a URL to its basic form without a query string or fragment. If the resulting URL is the same as the\n * loader's origin URL, returns ''.\n * @param {string} url - The URL to be canonicalized.\n * @param {string} loaderOriginUrl - The origin URL of the agent loader, used for inline detection.\n * @returns {string} The canonicalized URL, or '' if the URL matches the loader origin URL.\n */\nexport function canonicalizeUrl(url) {\n if (typeof url !== 'string') return '';\n const cleanedUrl = cleanURL(url);\n const cleanedGlobalScopeUrl = cleanURL(initialLocation);\n\n // If the URL matches the origin URL of the loader, we assume it originated within an inline script.\n if (cleanedUrl === cleanedGlobalScopeUrl) {\n return '';\n } else {\n return cleanedUrl;\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/* eslint-disable no-useless-escape */\n\n// computeStackTrace: cross-browser stack traces in JavaScript\n//\n// Syntax:\n// s = computeStackTrace(exception) // consider using TraceKit.report instead\n// Returns:\n// s.name - exception name\n// s.message - exception message\n// s.stack[i].url - JavaScript or HTML file URL\n// s.stack[i].func - function name, or empty for anonymous functions\n// s.stack[i].line - line number, if known\n// s.stack[i].column - column number, if known\n// s.stack[i].context - an array of source code lines; the middle element corresponds to the correct line#\n// s.mode - 'stack', 'stacktrace', 'multiline', 'callers', 'onerror', or 'failed' -- method used to collect the stack trace\n//\n// Supports:\n// - Firefox: full stack trace with line numbers and unreliable column\n// number on top frame\n// - Chrome: full stack trace with line and column numbers\n// - Safari: line and column number for the topmost stacktrace element\n// only\n// - IE: no line numbers whatsoever\n\n// Contents of Exception in various browsers.\n//\n// SAFARI:\n// ex.message = Can't find variable: qq\n// ex.line = 59\n// ex.sourceId = 580238192\n// ex.sourceURL = http://...\n// ex.expressionBeginOffset = 96\n// ex.expressionCaretOffset = 98\n// ex.expressionEndOffset = 98\n// ex.name = ReferenceError\n//\n// FIREFOX:\n// ex.message = qq is not defined\n// ex.fileName = http://...\n// ex.lineNumber = 59\n// ex.stack = ...stack trace... (see the example below)\n// ex.name = ReferenceError\n//\n// CHROME:\n// ex.message = qq is not defined\n// ex.name = ReferenceError\n// ex.type = not_defined\n// ex.arguments = ['aa']\n// ex.stack = ...stack trace...\n//\n// INTERNET EXPLORER:\n// ex.message = ...\n// ex.name = ReferenceError\nimport { formatStackTrace } from './format-stack-trace';\nimport { canonicalizeUrl } from '../../../common/url/canonicalize-url';\nvar debug = false;\nvar classNameRegex = /function (.+?)\\s*\\(/;\nvar chrome = /^\\s*at (?:((?:\\[object object\\])?(?:[^(]*\\([^)]*\\))*[^()]*(?: \\[as \\S+\\])?) )?\\(?((?:file|http|https|chrome-extension):.*?)?:(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nvar gecko = /^\\s*(?:(\\S*|global code)(?:\\(.*?\\))?@)?((?:file|http|https|chrome|safari-extension).*?):(\\d+)(?::(\\d+))?\\s*$/i;\nvar chromeEval = /^\\s*at .+ \\(eval at \\S+ \\((?:(?:file|http|https):[^)]+)?\\)(?:, [^:]*:\\d+:\\d+)?\\)$/i;\nvar ieEval = /^\\s*at Function code \\(Function code:\\d+:\\d+\\)\\s*/i;\n\n/**\n * Represents an error with a stack trace.\n * @typedef {Object} StackInfo\n * @property {string} name - The name of the error (e.g. 'TypeError').\n * @property {string} message - The error message.\n * @property {string} stackString - The stack trace as a string.\n * @property {Array} frames - An array of frames in the stack trace.\n * @property {string} frames.url - The URL of the file containing the code for the frame.\n * @property {string} frames.func - The name of the function associated with the frame.\n * @property {number} frames.line - The line number of the code in the frame.\n */\n\n/**\n * Attempts to compute a stack trace for the given exception.\n * @param {Error} ex - The exception for which to compute the stack trace.\n * @returns {StackInfo} A stack trace object containing information about the frames on the stack.\n */\nexport function computeStackTrace(ex) {\n var stack = null;\n try {\n stack = computeStackTraceFromStackProp(ex);\n if (stack) {\n return stack;\n }\n } catch (e) {\n if (debug) {\n throw e;\n }\n }\n try {\n stack = computeStackTraceBySourceAndLine(ex);\n if (stack) {\n return stack;\n }\n } catch (e) {\n if (debug) {\n throw e;\n }\n }\n try {\n stack = computeStackTraceWithMessageOnly(ex);\n if (stack) {\n return stack;\n }\n } catch (e) {\n if (debug) {\n throw e;\n }\n }\n return {\n mode: 'failed',\n stackString: '',\n frames: []\n };\n}\n\n/**\n * Computes stack trace information from the stack property. Chrome and Gecko use this property.\n *\n * @param {Error} ex - The error object to compute the stack trace for.\n * @return {?Object.} Stack trace information.\n */\nfunction computeStackTraceFromStackProp(ex) {\n if (!ex.stack) {\n return null;\n }\n var errorInfo = ex.stack.split('\\n').reduce(parseStackProp, {\n frames: [],\n stackLines: [],\n wrapperSeen: false\n });\n if (!errorInfo.frames.length) return null;\n return {\n mode: 'stack',\n name: ex.name || getClassName(ex),\n message: ex.message,\n stackString: formatStackTrace(errorInfo.stackLines),\n frames: errorInfo.frames\n };\n}\n\n/**\n * Parses a line from a JavaScript error stack trace and adds it to the given `info` object.\n * Ignores all stack entries thrown from one of our wrapper functions.\n *\n * @param {object} info - The `info` object to add the parsed line to.\n * @param {string} line - The line to parse.\n * @returns {object} The `info` object with the parsed line added.\n */\nfunction parseStackProp(info, line) {\n let element = getStackElement(line);\n\n // This catches lines that aren't frames (like the first line stating the error).\n if (!element) {\n info.stackLines.push(line);\n return info;\n }\n\n // Once we've seen a wrapper, ignore all subsequent stack entries.\n if (isNrWrapper(element.func)) info.wrapperSeen = true;\n if (!info.wrapperSeen) {\n // Query strings and fragments should be removed, and URLs matching the loader's origin should be \"\".\n let canonicalUrl = canonicalizeUrl(element.url);\n if (canonicalUrl !== element.url) {\n line = line.replace(element.url, canonicalUrl);\n element.url = canonicalUrl;\n }\n info.stackLines.push(line);\n info.frames.push(element);\n }\n return info;\n}\n\n/**\n * Parses a line from a JavaScript error stack trace to extract information about a stack trace element, such as the\n * URL, function name, line number, and column number.\n *\n * @param {string} line - A single line from a JavaScript error stack trace.\n * @returns {object} An object containing information about the stack trace element, including the URL, function\n * name, line number, and column number (if available).\n */\nfunction getStackElement(line) {\n var parts = line.match(gecko);\n if (!parts) parts = line.match(chrome);\n if (parts) {\n return {\n url: parts[2],\n func: parts[1] !== 'Anonymous function' && parts[1] !== 'global code' && parts[1] || null,\n line: +parts[3],\n column: parts[4] ? +parts[4] : null\n };\n }\n if (line.match(chromeEval) || line.match(ieEval) || line === 'anonymous') {\n return {\n func: 'evaluated code'\n };\n }\n}\n\n/**\n * Computes a stack trace object from an error object, by extracting the source and line number from the error object,\n * and using them to create a single stack frame.\n *\n * @param {Error} ex - The error object to compute the stack trace for.\n * @returns {Object|null} - An object representing the computed stack trace, or null if the\n * input error object does not contain a line number.\n */\nfunction computeStackTraceBySourceAndLine(ex) {\n if (!('line' in ex)) return null;\n var className = ex.name || getClassName(ex);\n\n // Safari does not provide a URL for errors in eval'd code\n if (!ex.sourceURL) {\n return {\n mode: 'sourceline',\n name: className,\n message: ex.message,\n stackString: className + ': ' + ex.message + '\\n in evaluated code',\n frames: [{\n func: 'evaluated code'\n }]\n };\n }\n\n // Remove any query string and fragment\n var canonicalUrl = canonicalizeUrl(ex.sourceURL);\n var stackString = className + ': ' + ex.message + '\\n at ' + canonicalUrl;\n if (ex.line) {\n stackString += ':' + ex.line;\n if (ex.column) {\n stackString += ':' + ex.column;\n }\n }\n return {\n mode: 'sourceline',\n name: className,\n message: ex.message,\n stackString,\n frames: [{\n url: canonicalUrl,\n line: ex.line,\n column: ex.column\n }]\n };\n}\n\n/**\n * For exceptions with no stack and only a message, derives a stack trace by extracting the class name and message.\n *\n * @param {Error} ex - The exception for which to compute the stack trace.\n * @returns {StackTrace} A stack trace object containing the name and message of the exception.\n */\nfunction computeStackTraceWithMessageOnly(ex) {\n var className = ex.name || getClassName(ex);\n if (!className) return null;\n return {\n mode: 'nameonly',\n name: className,\n message: ex.message,\n stackString: className + ': ' + ex.message,\n frames: []\n };\n}\n\n/**\n * Attempts to extract the name of the constructor function (the class) of the given object.\n *\n * @param {Object} obj - The object for which to extract the constructor function name.\n * @returns {string} The name of the constructor function, or 'unknown' if the name cannot be determined.\n */\nfunction getClassName(obj) {\n var results = classNameRegex.exec(String(obj.constructor));\n return results && results.length > 1 ? results[1] : 'unknown';\n}\n\n/**\n * Checks whether the given function name is a New Relic wrapper function.\n *\n * @param {string} functionName - The name of the function to check.\n * @returns {boolean} True if the function name includes the string 'nrWrapper', false otherwise.\n */\nfunction isNrWrapper(functionName) {\n return functionName && functionName.indexOf('nrWrapper') >= 0;\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function stringHashCode(string) {\n var hash = 0;\n var charVal;\n if (!string || !string.length) return hash;\n for (var i = 0; i < string.length; i++) {\n charVal = string.charCodeAt(i);\n hash = (hash << 5) - hash + charVal;\n hash = hash | 0; // Convert to 32bit integer\n }\n return hash;\n}","const REASON_RRWEB = 'Rrweb';\nconst REASON_SECURITY_POLICY = 'Security-Policy';\n/**\n * This function is responsible for determining if an error should be swallowed or not.\n * @param {Object} stackInfo - The error stack information.\n * @returns {boolean} - Whether the error should be swallowed or not.\n */\nexport function evaluateInternalError(stackInfo, internal) {\n const output = {\n shouldSwallow: internal || false,\n reason: 'Other'\n };\n const leadingFrame = stackInfo.frames?.[0];\n /** If we cant otherwise determine from the frames and message, the default of internal + reason will be the fallback */\n if (!leadingFrame || typeof stackInfo?.message !== 'string') return output;\n\n // check if the error happened in expected modules or if messages match known patterns\n const isNrRecorder = leadingFrame?.url?.match(/nr-(.*)-recorder.min.js/);\n const isRrweb = leadingFrame?.url?.match(/rrweb/);\n const isMaybeNrRecorder = leadingFrame?.url?.match(/recorder/);\n const isSecurityPolicyAPIError = stackInfo.message.toLowerCase().match(/an attempt was made to break through the security policy of the user agent/);\n\n // check if modules and patterns above fit known swallow cases\n if (!!isNrRecorder || !!isRrweb) {\n /** We know -for sure- that the error came from our recorder module or rrweb directly if these are true, so swallow it */\n output.shouldSwallow = true;\n output.reason = REASON_RRWEB;\n if (isSecurityPolicyAPIError) output.reason += '-' + REASON_SECURITY_POLICY;\n } else if (!!isMaybeNrRecorder && isSecurityPolicyAPIError) {\n /** We -suspect- that the error came from NR, so if it matches the exact case we know about, swallow it */\n output.shouldSwallow = true;\n output.reason = REASON_RRWEB + '-' + REASON_SECURITY_POLICY;\n }\n // other swallow conditions could also be added here\n return output;\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { canonicalFunctionName } from './canonical-function-name';\nimport { computeStackTrace } from './compute-stack-trace';\nimport { stringHashCode } from './string-hash-code';\nimport { truncateSize } from './format-stack-trace';\nimport { registerHandler as register } from '../../../common/event-emitter/register-handler';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { stringify } from '../../../common/util/stringify';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { globalScope } from '../../../common/constants/runtime';\nimport { FEATURE_NAME } from '../constants';\nimport { FEATURE_NAMES, FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { now } from '../../../common/timing/now';\nimport { applyFnToProps } from '../../../common/util/traverse';\nimport { evaluateInternalError } from './internal-errors';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\n\n/**\n * @typedef {import('./compute-stack-trace.js').StackInfo} StackInfo\n */\n\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n this.stackReported = {};\n this.observedAt = {};\n this.pageviewReported = {};\n this.bufferedErrorsUnderSpa = {};\n this.errorOnPage = false;\n\n // this will need to change to match whatever ee we use in the instrument\n this.ee.on('interactionDone', (interaction, wasSaved) => this.onInteractionDone(interaction, wasSaved));\n register('err', (...args) => this.storeError(...args), this.featureName, this.ee);\n register('ierr', (...args) => this.storeError(...args), this.featureName, this.ee);\n register('softNavFlush', (interactionId, wasFinished, softNavAttrs) => this.onSoftNavNotification(interactionId, wasFinished, softNavAttrs), this.featureName, this.ee); // when an ixn is done or cancelled\n\n const harvestTimeSeconds = agentRef.init.jserrors.harvestTimeSeconds || 10;\n const aggregatorTypes = ['err', 'ierr', 'xhr']; // the types in EventAggregator this feature cares about\n\n // 0 == off, 1 == on\n this.waitForFlags(['err']).then(([errFlag]) => {\n if (errFlag) {\n const scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry, {\n aggregatorTypes\n })\n }, this);\n scheduler.harvest.on(FEATURE_TO_ENDPOINT[this.featureName], options => this.makeHarvestPayload(options.retry, {\n aggregatorTypes\n }));\n scheduler.startTimer(harvestTimeSeconds);\n this.drain();\n } else {\n this.blocked = true; // if rum response determines that customer lacks entitlements for spa endpoint, this feature shouldn't harvest\n this.deregisterDrain();\n }\n });\n }\n serializer(aggregatorTypeToBucketsMap) {\n return applyFnToProps(aggregatorTypeToBucketsMap, this.obfuscator.obfuscateString.bind(this.obfuscator), 'string');\n }\n queryStringsBuilder(aggregatorTakeReturnedData) {\n const qs = {};\n const releaseIds = stringify(this.agentRef.runtime.releaseIds);\n if (releaseIds !== '{}') qs.ri = releaseIds;\n if (aggregatorTakeReturnedData?.err?.length) {\n if (!this.errorOnPage) {\n qs.pve = '1';\n this.errorOnPage = true;\n }\n // For assurance, erase any `hasReplay` flag from all errors if replay is not recording, not-yet imported, or not running at all.\n if (!this.agentRef.features?.[FEATURE_NAMES.sessionReplay]?.featAggregate?.replayIsActive()) aggregatorTakeReturnedData.err.forEach(error => delete error.params.hasReplay);\n }\n return qs;\n }\n\n /**\n * Builds a standardized stack trace string from the frames in the given `stackInfo` object, with each frame separated\n * by a newline character. Lines take the form `@:`.\n *\n * @param {StackInfo} stackInfo - An object specifying a stack string and individual frames.\n * @returns {string} A canonical stack string built from the URLs and function names in the given `stackInfo` object.\n */\n buildCanonicalStackString(stackInfo) {\n var canonicalStackString = '';\n for (var i = 0; i < stackInfo.frames.length; i++) {\n var frame = stackInfo.frames[i];\n var func = canonicalFunctionName(frame.func);\n if (canonicalStackString) canonicalStackString += '\\n';\n if (func) canonicalStackString += func + '@';\n if (typeof frame.url === 'string') canonicalStackString += frame.url;\n if (frame.line) canonicalStackString += ':' + frame.line;\n }\n return canonicalStackString;\n }\n\n /**\n *\n * @param {Error|UncaughtError} err The error instance to be processed\n * @param {number} time the relative ms (to origin) timestamp of occurence\n * @param {boolean=} internal if the error was \"caught\" and deemed \"internal\" before reporting to the jserrors feature\n * @param {object=} customAttributes any custom attributes to be included in the error payload\n * @param {boolean=} hasReplay a flag indicating if the error occurred during a replay session\n * @returns\n */\n storeError(err, time, internal, customAttributes, hasReplay) {\n if (!err) return;\n // are we in an interaction\n time = time || now();\n let filterOutput;\n if (!internal && this.agentRef.runtime.onerror) {\n filterOutput = this.agentRef.runtime.onerror(err);\n if (filterOutput && !(typeof filterOutput.group === 'string' && filterOutput.group.length)) {\n // All truthy values mean don't report (store) the error, per backwards-compatible usage,\n // - EXCEPT if a fingerprinting label is returned, via an object with key of 'group' and value of non-empty string\n return;\n }\n // Again as with previous usage, all falsey values would include the error.\n }\n var stackInfo = computeStackTrace(err);\n const {\n shouldSwallow,\n reason\n } = evaluateInternalError(stackInfo, internal);\n if (shouldSwallow) {\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Internal/Error/' + reason], undefined, FEATURE_NAMES.metrics, this.ee);\n return;\n }\n var canonicalStackString = this.buildCanonicalStackString(stackInfo);\n const params = {\n stackHash: stringHashCode(canonicalStackString),\n exceptionClass: stackInfo.name,\n request_uri: globalScope?.location.pathname\n };\n if (stackInfo.message) params.message = '' + stackInfo.message;\n // Notice if filterOutput isn't false|undefined OR our specified object, this func would've returned already (so it's unnecessary to req-check group).\n // Do not modify the name ('errorGroup') of params without DEM approval!\n if (filterOutput?.group) params.errorGroup = filterOutput.group;\n if (hasReplay) params.hasReplay = hasReplay;\n /**\n * The bucketHash is different from the params.stackHash because the params.stackHash is based on the canonicalized\n * stack trace and is used downstream in NR1 to attempt to group the same errors across different browsers. However,\n * the canonical stack trace excludes items like the column number increasing the hit-rate of different errors potentially\n * bucketing and ultimately resulting in the loss of data in NR1.\n */\n var bucketHash = stringHashCode(\"\".concat(stackInfo.name, \"_\").concat(stackInfo.message, \"_\").concat(stackInfo.stackString, \"_\").concat(params.hasReplay ? 1 : 0));\n if (!this.stackReported[bucketHash]) {\n this.stackReported[bucketHash] = true;\n params.stack_trace = truncateSize(stackInfo.stackString);\n this.observedAt[bucketHash] = Math.floor(this.agentRef.runtime.timeKeeper.correctRelativeTimestamp(time));\n } else {\n params.browser_stack_hash = stringHashCode(stackInfo.stackString);\n }\n params.releaseIds = stringify(this.agentRef.runtime.releaseIds);\n\n // When debugging stack canonicalization/hashing, uncomment these lines for\n // more output in the test logs\n // params.origStack = err.stack\n // params.canonicalStack = canonicalStack\n\n if (!this.pageviewReported[bucketHash]) {\n params.pageview = 1;\n this.pageviewReported[bucketHash] = true;\n }\n params.firstOccurrenceTimestamp = this.observedAt[bucketHash];\n params.timestamp = Math.floor(this.agentRef.runtime.timeKeeper.correctRelativeTimestamp(time));\n var type = 'err';\n var newMetrics = {\n time\n };\n\n // Trace sends the error in its payload, and both trace & replay simply listens for any error to occur.\n const jsErrorEvent = [type, bucketHash, params, newMetrics, customAttributes];\n handle('trace-jserror', jsErrorEvent, undefined, FEATURE_NAMES.sessionTrace, this.ee);\n // still send EE events for other features such as above, but stop this one from aggregating internal data\n if (this.blocked) return;\n if (err?.__newrelic?.[this.agentIdentifier]) {\n params._interactionId = err.__newrelic[this.agentIdentifier].interactionId;\n params._interactionNodeId = err.__newrelic[this.agentIdentifier].interactionNodeId;\n }\n const softNavInUse = Boolean(this.agentRef.features?.[FEATURE_NAMES.softNav]);\n // Note: the following are subject to potential race cond wherein if the other feature aren't fully initialized, it'll be treated as there being no associated interaction.\n // They each will also tack on their respective properties to the params object as part of the decision flow.\n if (softNavInUse) handle('jserror', [params, time], undefined, FEATURE_NAMES.softNav, this.ee);else handle('spa-jserror', jsErrorEvent, undefined, FEATURE_NAMES.spa, this.ee);\n if (params.browserInteractionId && !params._softNavFinished) {\n // hold onto the error until the in-progress interaction is done, eithered saved or discarded\n this.bufferedErrorsUnderSpa[params.browserInteractionId] ??= [];\n this.bufferedErrorsUnderSpa[params.browserInteractionId].push(jsErrorEvent);\n } else if (params._interactionId != null) {\n // same as above, except tailored for the way old spa does it\n this.bufferedErrorsUnderSpa[params._interactionId] = this.bufferedErrorsUnderSpa[params._interactionId] || [];\n this.bufferedErrorsUnderSpa[params._interactionId].push(jsErrorEvent);\n } else {\n // Either there is no interaction (then all these params properties will be undefined) OR there's a related soft navigation that's already completed.\n // The old spa does not look up completed interactions at all, so there's no need to consider it.\n this.#storeJserrorForHarvest(jsErrorEvent, params.browserInteractionId !== undefined, params._softNavAttributes);\n }\n }\n #storeJserrorForHarvest(errorInfoArr, softNavOccurredFinished, softNavCustomAttrs = {}) {\n let [type, bucketHash, params, newMetrics, localAttrs] = errorInfoArr;\n const allCustomAttrs = {};\n if (softNavOccurredFinished) {\n Object.entries(softNavCustomAttrs).forEach(([k, v]) => setCustom(k, v)); // when an ixn finishes, it'll include stuff in jsAttributes + attrs specific to the ixn\n bucketHash += params.browserInteractionId;\n delete params._softNavAttributes; // cleanup temp properties from synchronous evaluation; this is harmless when async from soft nav (properties DNE)\n delete params._softNavFinished;\n } else {\n // interaction was cancelled -> error should not be associated OR there was no interaction\n Object.entries(this.agentRef.info.jsAttributes).forEach(([k, v]) => setCustom(k, v));\n delete params.browserInteractionId;\n }\n if (localAttrs) Object.entries(localAttrs).forEach(([k, v]) => setCustom(k, v)); // local custom attrs are applied in either case with the highest precedence\n\n const jsAttributesHash = stringHashCode(stringify(allCustomAttrs));\n const aggregateHash = bucketHash + ':' + jsAttributesHash;\n this.events.add(type, aggregateHash, params, newMetrics, allCustomAttrs);\n function setCustom(key, val) {\n allCustomAttrs[key] = val && typeof val === 'object' ? stringify(val) : val;\n }\n }\n\n // TO-DO: Remove this function when old spa is taken out. #storeJserrorForHarvest handles the work with the softnav feature.\n onInteractionDone(interaction, wasSaved) {\n if (!this.bufferedErrorsUnderSpa[interaction.id] || this.blocked) return;\n this.bufferedErrorsUnderSpa[interaction.id].forEach(item => {\n var allCustomAttrs = {};\n const localCustomAttrs = item[4];\n Object.entries(interaction.root.attrs.custom || {}).forEach(setCustom); // tack on custom attrs from the interaction\n Object.entries(localCustomAttrs || {}).forEach(setCustom);\n var params = item[2];\n if (wasSaved) {\n params.browserInteractionId = interaction.root.attrs.id;\n if (params._interactionNodeId) params.parentNodeId = params._interactionNodeId.toString();\n }\n delete params._interactionId;\n delete params._interactionNodeId;\n var hash = wasSaved ? item[1] + interaction.root.attrs.id : item[1];\n var jsAttributesHash = stringHashCode(stringify(allCustomAttrs));\n var aggregateHash = hash + ':' + jsAttributesHash;\n this.events.add(item[0], aggregateHash, params, item[3], allCustomAttrs);\n function setCustom([key, val]) {\n allCustomAttrs[key] = val && typeof val === 'object' ? stringify(val) : val;\n }\n });\n delete this.bufferedErrorsUnderSpa[interaction.id];\n }\n onSoftNavNotification(interactionId, wasFinished, softNavAttrs) {\n if (this.blocked) return;\n this.bufferedErrorsUnderSpa[interactionId]?.forEach(jsErrorEvent => this.#storeJserrorForHarvest(jsErrorEvent, wasFinished, softNavAttrs) // this should not modify the re-used softNavAttrs contents\n );\n delete this.bufferedErrorsUnderSpa[interactionId]; // wipe the list of jserrors so they aren't duplicated by another call to the same id\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.jserrors;","import { initialLocation } from '../../../common/constants/runtime';\nimport { cleanURL } from '../../../common/url/clean-url';\nimport { LOG_LEVELS } from '../constants';\nexport class Log {\n /** @type {long} the unix timestamp of the log event */\n timestamp;\n /** @type {string} the log message */\n message;\n /** @type {object} the object of attributes to be parsed by logging ingest into top-level properties */\n attributes;\n /** @type {'ERROR'|'TRACE'|'DEBUG'|'INFO'|'WARN'} the log type of the log */\n level;\n\n /**\n * @param {number} timestamp - Unix timestamp\n * @param {string} message - message string\n * @param {object} attributes - other log event attributes\n * @param {enum} level - Log level\n */\n constructor(timestamp, message, attributes = {}, level = LOG_LEVELS.INFO) {\n /** @type {long} */\n this.timestamp = timestamp;\n this.message = message;\n this.attributes = {\n ...attributes,\n pageUrl: cleanURL('' + initialLocation)\n };\n this.level = level.toUpperCase();\n }\n}","import { handle } from '../../../common/event-emitter/handle';\nimport { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { warn } from '../../../common/util/console';\nimport { stringify } from '../../../common/util/stringify';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { FEATURE_NAME, LOGGING_EVENT_EMITTER_CHANNEL, LOG_LEVELS } from '../constants';\nimport { Log } from '../shared/log';\nimport { isValidLogLevel } from '../shared/utils';\nimport { applyFnToProps } from '../../../common/util/traverse';\nimport { MAX_PAYLOAD_SIZE } from '../../../common/constants/agent-constants';\nimport { FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n this.harvestTimeSeconds = agentRef.init.logging.harvestTimeSeconds;\n this.waitForFlags([]).then(() => {\n this.scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n retryDelay: this.harvestTimeSeconds,\n getPayload: options => this.makeHarvestPayload(options.retry),\n raw: true\n }, this);\n /** emitted by instrument class (wrapped loggers) or the api methods directly */\n registerHandler(LOGGING_EVENT_EMITTER_CHANNEL, this.handleLog.bind(this), this.featureName, this.ee);\n this.drain();\n /** harvest immediately once started to purge pre-load logs collected */\n this.scheduler.startTimer(this.harvestTimeSeconds, 0);\n });\n }\n handleLog(timestamp, message, attributes = {}, level = LOG_LEVELS.INFO) {\n if (this.blocked) return;\n if (!attributes || typeof attributes !== 'object') attributes = {};\n if (typeof level === 'string') level = level.toUpperCase();\n if (!isValidLogLevel(level)) return warn(30, level);\n try {\n if (typeof message !== 'string') {\n const stringified = stringify(message);\n /**\n * Error instances convert to `{}` when stringified\n * Symbol converts to '' when stringified\n * other cases tbd\n * */\n if (!!stringified && stringified !== '{}') message = stringified;else message = String(message);\n }\n } catch (err) {\n warn(16, message);\n return;\n }\n if (typeof message !== 'string' || !message) return warn(32);\n const log = new Log(Math.floor(this.agentRef.runtime.timeKeeper.correctRelativeTimestamp(timestamp)), message, attributes, level);\n const logBytes = log.message.length + stringify(log.attributes).length + log.level.length + 10; // timestamp == 10 chars\n\n const failToHarvestMessage = 'Logging/Harvest/Failed/Seen';\n if (logBytes > MAX_PAYLOAD_SIZE) {\n // cannot possibly send this, even with an empty buffer\n handle(SUPPORTABILITY_METRIC_CHANNEL, [failToHarvestMessage, logBytes]);\n warn(31, log.message.slice(0, 25) + '...');\n return;\n }\n if (this.events.wouldExceedMaxSize(logBytes)) {\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Logging/Harvest/Early/Seen', this.events.bytes + logBytes]);\n this.scheduler.runHarvest(); // force a harvest to try adding again\n }\n if (!this.events.add(log)) {\n // still failed after a harvest attempt despite not being too large would mean harvest failed with options.retry\n handle(SUPPORTABILITY_METRIC_CHANNEL, [failToHarvestMessage, logBytes]);\n warn(31, log.message.slice(0, 25) + '...');\n }\n }\n serializer(eventBuffer) {\n const sessionEntity = this.agentRef.runtime.session;\n return [{\n common: {\n /** Attributes in the `common` section are added to `all` logs generated in the payload */\n attributes: {\n 'entity.guid': this.agentRef.runtime.appMetadata?.agents?.[0]?.entityGuid,\n // browser entity guid as provided from RUM response\n ...(sessionEntity && {\n session: sessionEntity.state.value || '0',\n // The session ID that we generate and keep across page loads\n hasReplay: sessionEntity.state.sessionReplayMode === 1,\n // True if a session replay recording is running\n hasTrace: sessionEntity.state.sessionTraceMode === 1 // True if a session trace recording is running\n }),\n ptid: this.agentRef.runtime.ptid,\n // page trace id\n appId: this.agentRef.info.applicationID,\n // Application ID from info object,\n standalone: Boolean(this.agentRef.info.sa),\n // copy paste (true) vs APM (false)\n agentVersion: this.agentRef.runtime.version,\n // browser agent version\n // The following 3 attributes are evaluated and dropped at ingest processing time and do not get stored on NRDB:\n 'instrumentation.provider': 'browser',\n 'instrumentation.version': this.agentRef.runtime.version,\n 'instrumentation.name': this.agentRef.runtime.loaderType\n }\n },\n /** logs section contains individual unique log entries */\n logs: applyFnToProps(eventBuffer, this.obfuscator.obfuscateString.bind(this.obfuscator), 'string')\n }];\n }\n queryStringsBuilder() {\n return {\n browser_monitoring_key: this.agentRef.info.licenseKey\n };\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const LOG_LEVELS = {\n ERROR: 'ERROR',\n WARN: 'WARN',\n INFO: 'INFO',\n DEBUG: 'DEBUG',\n TRACE: 'TRACE'\n};\nexport const LOGGING_EVENT_EMITTER_CHANNEL = 'log';\nexport const FEATURE_NAME = FEATURE_NAMES.logging;","import { handle } from '../../../common/event-emitter/handle';\nimport { now } from '../../../common/timing/now';\nimport { FEATURE_NAMES } from '../../../loaders/features/features';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { LOGGING_EVENT_EMITTER_CHANNEL, LOG_LEVELS } from '../constants';\n\n/**\n * @param {ContextualEE} ee - The contextual ee tied to the instance\n * @param {string} message - the log message string\n * @param {{[key: string]: *}} customAttributes - The log's custom attributes if any\n * @param {enum} level - the log level enum\n */\nexport function bufferLog(ee, message, customAttributes = {}, level = LOG_LEVELS.INFO) {\n handle(SUPPORTABILITY_METRIC_CHANNEL, [\"API/logging/\".concat(level.toLowerCase(), \"/called\")], undefined, FEATURE_NAMES.metrics, ee);\n handle(LOGGING_EVENT_EMITTER_CHANNEL, [now(), message, customAttributes, level], undefined, FEATURE_NAMES.logging, ee);\n}\n\n/**\n * Checks if a supplied log level is acceptable for use in generating a log event\n * @param {string} level -- must be cast to uppercase before running this test\n * @returns {boolean}\n */\nexport function isValidLogLevel(level) {\n if (typeof level !== 'string') return false;\n return Object.values(LOG_LEVELS).some(logLevel => logLevel === level.toUpperCase().trim());\n}","import { isBrowserScope } from '../../../common/constants/runtime';\nconst FRAMEWORKS = {\n REACT: 'React',\n NEXTJS: 'NextJS',\n VUE: 'Vue',\n NUXTJS: 'NuxtJS',\n ANGULAR: 'Angular',\n ANGULARUNIVERSAL: 'AngularUniversal',\n SVELTE: 'Svelte',\n SVELTEKIT: 'SvelteKit',\n PREACT: 'Preact',\n PREACTSSR: 'PreactSSR',\n ANGULARJS: 'AngularJS',\n BACKBONE: 'Backbone',\n EMBER: 'Ember',\n METEOR: 'Meteor',\n ZEPTO: 'Zepto',\n JQUERY: 'Jquery',\n MOOTOOLS: 'MooTools',\n QWIK: 'Qwik',\n ELECTRON: 'Electron'\n};\nexport function getFrameworks() {\n if (!isBrowserScope) return []; // don't bother detecting frameworks if not in the main window context\n\n const frameworks = [];\n try {\n if (detectReact()) {\n frameworks.push(FRAMEWORKS.REACT);\n if (detectNextJS()) frameworks.push(FRAMEWORKS.NEXTJS);\n }\n if (detectVue()) {\n frameworks.push(FRAMEWORKS.VUE);\n if (detectNuxtJS()) frameworks.push(FRAMEWORKS.NUXTJS);\n }\n if (detectAngular()) {\n frameworks.push(FRAMEWORKS.ANGULAR);\n if (detectAngularUniversal()) frameworks.push(FRAMEWORKS.ANGULARUNIVERSAL);\n }\n if (detectSvelte()) {\n frameworks.push(FRAMEWORKS.SVELTE);\n if (detectSvelteKit()) frameworks.push(FRAMEWORKS.SVELTEKIT);\n }\n if (detectPreact()) {\n frameworks.push(FRAMEWORKS.PREACT);\n if (detectPreactSSR()) frameworks.push(FRAMEWORKS.PREACTSSR);\n }\n if (detectAngularJs()) frameworks.push(FRAMEWORKS.ANGULARJS);\n if (Object.prototype.hasOwnProperty.call(window, 'Backbone')) frameworks.push(FRAMEWORKS.BACKBONE);\n if (Object.prototype.hasOwnProperty.call(window, 'Ember')) frameworks.push(FRAMEWORKS.EMBER);\n if (Object.prototype.hasOwnProperty.call(window, 'Meteor')) frameworks.push(FRAMEWORKS.METEOR);\n if (Object.prototype.hasOwnProperty.call(window, 'Zepto')) frameworks.push(FRAMEWORKS.ZEPTO);\n if (Object.prototype.hasOwnProperty.call(window, 'jQuery')) frameworks.push(FRAMEWORKS.JQUERY);\n if (Object.prototype.hasOwnProperty.call(window, 'MooTools')) frameworks.push(FRAMEWORKS.MOOTOOLS);\n if (Object.prototype.hasOwnProperty.call(window, 'qwikevents')) frameworks.push(FRAMEWORKS.QWIK);\n if (detectElectron()) frameworks.push(FRAMEWORKS.ELECTRON);\n } catch (err) {\n // Possibly not supported\n }\n return frameworks;\n}\nfunction detectReact() {\n try {\n return Object.prototype.hasOwnProperty.call(window, 'React') || Object.prototype.hasOwnProperty.call(window, 'ReactDOM') || Object.prototype.hasOwnProperty.call(window, 'ReactRedux') || document.querySelector('[data-reactroot], [data-reactid]') || (() => {\n const divs = document.querySelectorAll('body > div');\n for (let i = 0; i < divs.length; i++) {\n if (Object.prototype.hasOwnProperty.call(divs[i], '_reactRootContainer')) {\n return true;\n }\n }\n })();\n } catch (err) {\n return false;\n }\n}\nfunction detectNextJS() {\n // React SSR\n try {\n return Object.prototype.hasOwnProperty.call(window, 'next') && Object.prototype.hasOwnProperty.call(window.next, 'version');\n } catch (err) {\n return false;\n }\n}\nfunction detectVue() {\n try {\n return Object.prototype.hasOwnProperty.call(window, 'Vue');\n } catch (err) {\n return false;\n }\n}\nfunction detectNuxtJS() {\n // Vue SSR\n try {\n return Object.prototype.hasOwnProperty.call(window, '$nuxt') && Object.prototype.hasOwnProperty.call(window.$nuxt, 'nuxt');\n } catch (err) {\n return false;\n }\n}\nfunction detectAngular() {\n try {\n return Object.prototype.hasOwnProperty.call(window, 'ng') || document.querySelector('[ng-version]');\n } catch (err) {\n return false;\n }\n}\nfunction detectAngularUniversal() {\n // Anguler SSR\n try {\n return document.querySelector('[ng-server-context]');\n } catch (err) {\n return false;\n }\n}\nfunction detectSvelte() {\n try {\n return Object.prototype.hasOwnProperty.call(window, '__svelte');\n } catch (err) {\n return false;\n }\n}\nfunction detectSvelteKit() {\n // Svelte SSR\n try {\n return !!Object.keys(window).find(prop => prop.startsWith('__sveltekit'));\n } catch (err) {\n return false;\n }\n}\nfunction detectPreact() {\n try {\n return Object.prototype.hasOwnProperty.call(window, 'preact');\n } catch (err) {\n return false;\n }\n}\nfunction detectPreactSSR() {\n // Svelte SSR\n try {\n return document.querySelector('script[type=\"__PREACT_CLI_DATA__\"]');\n } catch (err) {\n return false;\n }\n}\nfunction detectAngularJs() {\n try {\n return Object.prototype.hasOwnProperty.call(window, 'angular') || document.querySelector('.ng-binding, [ng-app], [data-ng-app], [ng-controller], [data-ng-controller], [ng-repeat], [data-ng-repeat]') || document.querySelector('script[src*=\"angular.js\"], script[src*=\"angular.min.js\"]');\n } catch (err) {\n return false;\n }\n}\nfunction detectElectron() {\n try {\n return typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0;\n } catch (err) {\n return false;\n }\n}","import { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { FEATURE_NAME, SUPPORTABILITY_METRIC, CUSTOM_METRIC, SUPPORTABILITY_METRIC_CHANNEL, CUSTOM_METRIC_CHANNEL /*, WATCHABLE_WEB_SOCKET_EVENTS */ } from '../constants';\nimport { getFrameworks } from './framework-detection';\nimport { isFileProtocol } from '../../../common/url/protocol';\nimport { onDOMContentLoaded } from '../../../common/window/load';\nimport { windowAddEventListener } from '../../../common/event-listener/event-listener-opts';\nimport { isBrowserScope, isWorkerScope } from '../../../common/constants/runtime';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { isIFrameWindow } from '../../../common/dom/iframe';\n// import { WEBSOCKET_TAG } from '../../../common/wrap/wrap-websocket'\n// import { handleWebsocketEvents } from './websocket-detection'\n\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n const aggregatorTypes = ['cm', 'sm']; // the types in EventAggregator this feature cares about\n\n this.waitForFlags(['err']).then(([errFlag]) => {\n if (errFlag) {\n // *cli, Mar 23 - Per NR-94597, this feature should only harvest ONCE at the (potential) EoL time of the page.\n const scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onUnload: () => this.unload()\n }, this);\n // this is needed to ensure EoL is \"on\" and sent\n scheduler.harvest.on(FEATURE_TO_ENDPOINT[this.featureName], () => this.makeHarvestPayload(undefined, {\n aggregatorTypes\n }));\n this.drain();\n } else {\n this.blocked = true; // if rum response determines that customer lacks entitlements for spa endpoint, this feature shouldn't harvest\n this.deregisterDrain();\n }\n });\n\n // Allow features external to the metrics feature to capture SMs and CMs through the event emitter\n registerHandler(SUPPORTABILITY_METRIC_CHANNEL, this.storeSupportabilityMetrics.bind(this), this.featureName, this.ee);\n registerHandler(CUSTOM_METRIC_CHANNEL, this.storeEventMetrics.bind(this), this.featureName, this.ee);\n this.singleChecks(); // checks that are run only one time, at script load\n this.eachSessionChecks(); // the start of every time user engages with page\n }\n storeSupportabilityMetrics(name, value) {\n if (this.blocked) return;\n const type = SUPPORTABILITY_METRIC;\n const params = {\n name\n };\n this.events.addMetric(type, name, params, value);\n }\n storeEventMetrics(name, metrics) {\n if (this.blocked) return;\n const type = CUSTOM_METRIC;\n const params = {\n name\n };\n this.events.add(type, name, params, metrics);\n }\n singleChecks() {\n // report loaderType\n const {\n distMethod,\n loaderType\n } = this.agentRef.runtime;\n const {\n proxy,\n privacy\n } = this.agentRef.init;\n if (loaderType) this.storeSupportabilityMetrics(\"Generic/LoaderType/\".concat(loaderType, \"/Detected\"));\n if (distMethod) this.storeSupportabilityMetrics(\"Generic/DistMethod/\".concat(distMethod, \"/Detected\"));\n if (isBrowserScope) {\n this.storeSupportabilityMetrics('Generic/Runtime/Browser/Detected');\n const nonce = document?.currentScript?.nonce;\n if (nonce && nonce !== '') {\n this.storeSupportabilityMetrics('Generic/Runtime/Nonce/Detected');\n }\n\n // These SMs are used by the AppExp team\n onDOMContentLoaded(() => {\n getFrameworks().forEach(framework => {\n this.storeSupportabilityMetrics('Framework/' + framework + '/Detected');\n });\n });\n if (!privacy.cookies_enabled) this.storeSupportabilityMetrics('Config/SessionTracking/Disabled');\n } else if (isWorkerScope) {\n this.storeSupportabilityMetrics('Generic/Runtime/Worker/Detected');\n } else {\n this.storeSupportabilityMetrics('Generic/Runtime/Unknown/Detected');\n }\n\n // Track if the agent is being loaded using a file protocol such as is the case in some\n // set-top box applications or Electron applications\n if (isFileProtocol()) {\n this.storeSupportabilityMetrics('Generic/FileProtocol/Detected');\n }\n\n // Capture SMs to assess customer engagement with the obfuscation config\n const ruleValidations = this.obfuscator.ruleValidationCache;\n if (ruleValidations.length > 0) {\n this.storeSupportabilityMetrics('Generic/Obfuscate/Detected');\n if (ruleValidations.filter(ruleValidation => !ruleValidation.isValid).length > 0) this.storeSupportabilityMetrics('Generic/Obfuscate/Invalid');\n }\n\n // Check if proxy for either chunks or beacon is being used\n if (proxy.assets) this.storeSupportabilityMetrics('Config/AssetsUrl/Changed');\n if (proxy.beacon) this.storeSupportabilityMetrics('Config/BeaconUrl/Changed');\n if (isBrowserScope && window.MutationObserver) {\n if (isIFrameWindow(window)) {\n this.storeSupportabilityMetrics('Generic/Runtime/IFrame/Detected');\n }\n const preExistingVideos = window.document.querySelectorAll('video').length;\n if (preExistingVideos) this.storeSupportabilityMetrics('Generic/VideoElement/Added', preExistingVideos);\n const preExistingIframes = window.document.querySelectorAll('iframe').length;\n if (preExistingIframes) this.storeSupportabilityMetrics('Generic/IFrame/Added', preExistingIframes);\n const mo = new MutationObserver(records => {\n records.forEach(record => {\n record.addedNodes.forEach(addedNode => {\n if (addedNode instanceof HTMLVideoElement) {\n this.storeSupportabilityMetrics('Generic/VideoElement/Added', 1);\n }\n if (addedNode instanceof HTMLIFrameElement) {\n this.storeSupportabilityMetrics('Generic/IFrame/Added', 1);\n }\n });\n });\n });\n mo.observe(window.document.body, {\n childList: true,\n subtree: true\n });\n }\n\n // WATCHABLE_WEB_SOCKET_EVENTS.forEach(tag => {\n // registerHandler('buffered-' + WEBSOCKET_TAG + tag, (...args) => {\n // handleWebsocketEvents(this.storeSupportabilityMetrics.bind(this), tag, ...args)\n // }, this.featureName, this.ee)\n // })\n }\n eachSessionChecks() {\n if (!isBrowserScope) return;\n\n // [Temporary] Report restores from BFCache to NR1 while feature flag is in place in lieu of sending pageshow events.\n windowAddEventListener('pageshow', evt => {\n if (evt?.persisted) {\n this.storeSupportabilityMetrics('Generic/BFCache/PageRestored');\n }\n });\n }\n unload() {\n try {\n if (this.resourcesSent) return;\n this.resourcesSent = true; // make sure this only gets sent once\n\n // Capture SMs around network resources using the performance API to assess\n // work to split this out from the ST nodes\n // differentiate between internal+external and ajax+non-ajax\n const ajaxResources = ['beacon', 'fetch', 'xmlhttprequest'];\n const internalUrls = ['nr-data.net', 'newrelic.com', 'nr-local.net', 'localhost'];\n function isInternal(x) {\n return internalUrls.some(y => x.name.indexOf(y) >= 0);\n }\n function isAjax(x) {\n return ajaxResources.includes(x.initiatorType);\n }\n const allResources = performance?.getEntriesByType('resource') || [];\n allResources.forEach(entry => {\n if (isInternal(entry)) {\n if (isAjax(entry)) this.storeSupportabilityMetrics('Generic/Resources/Ajax/Internal');else this.storeSupportabilityMetrics('Generic/Resources/Non-Ajax/Internal');\n } else {\n if (isAjax(entry)) this.storeSupportabilityMetrics('Generic/Resources/Ajax/External');else this.storeSupportabilityMetrics('Generic/Resources/Non-Ajax/External');\n }\n });\n\n // Capture SMs for performance markers and measures to assess the usage and possible inclusion of this\n // data in the agent for use in NR\n if (typeof performance !== 'undefined') {\n const markers = performance.getEntriesByType('mark');\n const measures = performance.getEntriesByType('measure');\n if (markers.length) this.storeSupportabilityMetrics('Generic/Performance/Mark/Seen', markers.length);\n if (measures.length) this.storeSupportabilityMetrics('Generic/Performance/Measure/Seen', measures.length);\n }\n } catch (e) {\n // do nothing\n }\n }\n}","// import { ADD_EVENT_LISTENER_TAG } from '../../common/wrap/wrap-websocket'\nimport { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.metrics;\nexport const SUPPORTABILITY_METRIC = 'sm';\nexport const CUSTOM_METRIC = 'cm';\nexport const SUPPORTABILITY_METRIC_CHANNEL = 'storeSupportabilityMetrics';\nexport const CUSTOM_METRIC_CHANNEL = 'storeEventMetrics';\n\n// export const WATCHABLE_WEB_SOCKET_EVENTS = ['new', 'send', 'close', ADD_EVENT_LISTENER_TAG]","import { FEATURE_NAMES } from '../../../loaders/features/features';\nimport { gosNREUM } from '../../../common/window/nreum';\n\n/**\n * Get an array of flags required by downstream (NR UI) based on the features initialized in this agent\n * (aka what is running on the page).\n * @param {String} agentId - the ID of the initialized agent on the page, mapping to the one under the global 'newrelic' object\n * @returns {String[]} Up to 5 short strings corresponding to ingest mapping of features.\n */\nexport function getActivatedFeaturesFlags(agentId) {\n const flagArr = [];\n const newrelic = gosNREUM();\n try {\n Object.keys(newrelic.initializedAgents[agentId].features).forEach(featName => {\n switch (featName) {\n case FEATURE_NAMES.ajax:\n flagArr.push('xhr');\n break;\n case FEATURE_NAMES.jserrors:\n flagArr.push('err');\n break;\n case FEATURE_NAMES.genericEvents:\n flagArr.push('ins');\n break;\n case FEATURE_NAMES.sessionTrace:\n flagArr.push('stn');\n break;\n case FEATURE_NAMES.softNav:\n case FEATURE_NAMES.spa:\n flagArr.push('spa');\n break;\n }\n });\n } catch (e) {}\n return flagArr;\n}\n\n// Note: this module and the \"af\" param in src/features/page_view_event/aggregate/index.js can be removed in the future at such time\n// that it's no longer being used. For the browser agent, this is an unused flag system.","import { originTime } from '../constants/runtime';\nimport { getRuntime } from '../config/runtime';\n\n/**\n * Class used to adjust the timestamp of harvested data to New Relic server time. This\n * is done by tracking the performance timings of the RUM call and applying a calculation\n * to the harvested data event offset time.\n */\nexport class TimeKeeper {\n /**\n * Pointer to the current agent session if it exists.\n * @type {import('../session/session-entity').SessionEntity}\n */\n #session;\n\n /**\n * Represents the browser origin time corrected to NR server time.\n * @type {number}\n */\n #correctedOriginTime;\n\n /**\n * Represents the difference in milliseconds between the calculated NR server time and\n * the local time.\n * @type {number}\n */\n #localTimeDiff;\n\n /**\n * Represents whether the timekeeper is in a state that it can accurately convert\n * timestamps.\n * @type {boolean}\n */\n #ready = false;\n constructor(agentIdentifier) {\n this.#session = getRuntime(agentIdentifier)?.session;\n this.processStoredDiff();\n }\n get ready() {\n return this.#ready;\n }\n get correctedOriginTime() {\n return this.#correctedOriginTime;\n }\n get localTimeDiff() {\n return this.#localTimeDiff;\n }\n\n /**\n * Process a rum request to calculate NR server time.\n * @param rumRequest {XMLHttpRequest} The xhr for the rum request\n * @param startTime {number} The start time of the RUM request\n * @param endTime {number} The end time of the RUM request\n * @param nrServerTime {number} the unix number value of the NR server time in MS, returned in the RUM request body\n */\n processRumRequest(rumRequest, startTime, endTime, nrServerTime) {\n this.processStoredDiff(); // Check session entity for stored time diff\n if (this.#ready) return; // Server time calculated from session entity\n\n if (!nrServerTime) throw new Error('nrServerTime not found');\n const medianRumOffset = (endTime - startTime) / 2;\n const serverOffset = startTime + medianRumOffset;\n\n // Corrected page origin time\n this.#correctedOriginTime = Math.floor(nrServerTime - serverOffset);\n this.#localTimeDiff = originTime - this.#correctedOriginTime;\n if (isNaN(this.#correctedOriginTime)) {\n throw new Error('Failed to correct browser time to server time');\n }\n this.#session?.write({\n serverTimeDiff: this.#localTimeDiff\n });\n this.#ready = true;\n }\n\n /**\n * Converts a page origin relative time to an absolute timestamp\n * using the user's local clock.\n * @param relativeTime {number} The relative time of the event in milliseconds\n * @returns {number} Corrected unix/epoch timestamp\n */\n convertRelativeTimestamp(relativeTime) {\n return originTime + relativeTime;\n }\n\n /**\n * Converts an absolute timestamp to a relative timestamp using the\n * user's local clock.\n * @param timestamp\n * @returns {number}\n */\n convertAbsoluteTimestamp(timestamp) {\n return timestamp - originTime;\n }\n\n /**\n * Corrects an absolute timestamp to NR server time.\n * @param timestamp {number} The unix/epoch timestamp of the event with milliseconds\n * @return {number} Corrected unix/epoch timestamp\n */\n correctAbsoluteTimestamp(timestamp) {\n return timestamp - this.#localTimeDiff;\n }\n\n /**\n * Corrects relative timestamp to NR server time (epoch).\n * @param {DOMHighResTimeStamp} relativeTime\n * @returns {number}\n */\n correctRelativeTimestamp(relativeTime) {\n return this.correctAbsoluteTimestamp(this.convertRelativeTimestamp(relativeTime));\n }\n\n /** Process the session entity and use the info to set the main time calculations if present */\n processStoredDiff() {\n if (this.#ready) return; // Time diff has already been calculated\n\n const storedServerTimeDiff = this.#session?.read()?.serverTimeDiff;\n if (typeof storedServerTimeDiff === 'number' && !isNaN(storedServerTimeDiff)) {\n this.#localTimeDiff = storedServerTimeDiff;\n this.#correctedOriginTime = originTime - this.#localTimeDiff;\n this.#ready = true;\n }\n }\n}","import { globalScope, isBrowserScope, originTime } from '../../../common/constants/runtime';\nimport { addPT, addPN } from '../../../common/timing/nav-timing';\nimport { stringify } from '../../../common/util/stringify';\nimport { isValid } from '../../../common/config/info';\nimport { Harvest } from '../../../common/harvest/harvest';\nimport * as CONSTANTS from '../constants';\nimport { getActivatedFeaturesFlags } from './initialized-features';\nimport { activateFeatures } from '../../../common/util/feature-flags';\nimport { warn } from '../../../common/util/console';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { firstContentfulPaint } from '../../../common/vitals/first-contentful-paint';\nimport { firstPaint } from '../../../common/vitals/first-paint';\nimport { timeToFirstByte } from '../../../common/vitals/time-to-first-byte';\nimport { now } from '../../../common/timing/now';\nimport { TimeKeeper } from '../../../common/timing/time-keeper';\nimport { applyFnToProps } from '../../../common/util/traverse';\nexport class Aggregate extends AggregateBase {\n static featureName = CONSTANTS.FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, CONSTANTS.FEATURE_NAME);\n this.timeToFirstByte = 0;\n this.firstByteToWindowLoad = 0; // our \"frontend\" duration\n this.firstByteToDomContent = 0; // our \"dom processing\" duration\n this.timeKeeper = new TimeKeeper(agentRef.agentIdentifier);\n if (!isValid(agentRef.agentIdentifier)) {\n this.ee.abort();\n return warn(43);\n }\n if (isBrowserScope) {\n timeToFirstByte.subscribe(({\n value,\n attrs\n }) => {\n const navEntry = attrs.navigationEntry;\n this.timeToFirstByte = Math.max(value, this.timeToFirstByte);\n this.firstByteToWindowLoad = Math.max(Math.round(navEntry.loadEventEnd - this.timeToFirstByte), this.firstByteToWindowLoad); // our \"frontend\" duration\n this.firstByteToDomContent = Math.max(Math.round(navEntry.domContentLoadedEventEnd - this.timeToFirstByte), this.firstByteToDomContent); // our \"dom processing\" duration\n\n this.sendRum();\n });\n } else {\n // worker agent build does not get TTFB values, use default 0 values\n this.sendRum();\n }\n }\n sendRum() {\n const info = this.agentRef.info;\n const harvester = new Harvest(this);\n const measures = {};\n if (info.queueTime) measures.qt = info.queueTime;\n if (info.applicationTime) measures.ap = info.applicationTime;\n\n // These 3 values should've been recorded after load and before this func runs. They are part of the minimum required for PageView events to be created.\n // Following PR #428, which demands that all agents send RUM call, these need to be sent even outside of the main window context where PerformanceTiming\n // or PerformanceNavigationTiming do not exists. Hence, they'll be filled in by 0s instead in, for example, worker threads that still init the PVE module.\n measures.be = this.timeToFirstByte;\n measures.fe = this.firstByteToWindowLoad;\n measures.dc = this.firstByteToDomContent;\n const queryParameters = {\n tt: info.ttGuid,\n us: info.user,\n ac: info.account,\n pr: info.product,\n af: getActivatedFeaturesFlags(this.agentIdentifier).join(','),\n ...measures,\n xx: info.extra,\n ua: info.userAttributes,\n at: info.atts\n };\n if (this.agentRef.runtime.session) queryParameters.fsh = Number(this.agentRef.runtime.session.isNew); // \"first session harvest\" aka RUM request or PageView event of a session\n\n let body;\n if (typeof info.jsAttributes === 'object' && Object.keys(info.jsAttributes).length > 0) {\n body = applyFnToProps({\n ja: info.jsAttributes\n }, this.obfuscator.obfuscateString.bind(this.obfuscator), 'string');\n }\n if (globalScope.performance) {\n if (typeof PerformanceNavigationTiming !== 'undefined') {\n // Navigation Timing level 2 API that replaced PerformanceTiming & PerformanceNavigation\n const navTimingEntry = globalScope?.performance?.getEntriesByType('navigation')?.[0];\n const perf = {\n timing: addPT(originTime, navTimingEntry, {}),\n navigation: addPN(navTimingEntry, {})\n };\n queryParameters.perf = stringify(perf);\n } else if (typeof PerformanceTiming !== 'undefined') {\n // Safari pre-15 did not support level 2 timing\n const perf = {\n timing: addPT(originTime, globalScope.performance.timing, {}, true),\n navigation: addPN(globalScope.performance.navigation, {})\n };\n queryParameters.perf = stringify(perf);\n }\n }\n queryParameters.fp = firstPaint.current.value;\n queryParameters.fcp = firstContentfulPaint.current.value;\n if (this.timeKeeper?.ready) {\n queryParameters.timestamp = Math.floor(this.timeKeeper.correctRelativeTimestamp(now()));\n }\n const rumStartTime = now();\n harvester.send({\n endpoint: 'rum',\n payload: {\n qs: queryParameters,\n body\n },\n opts: {\n needResponse: true,\n sendEmptyBody: true\n },\n cbFinished: ({\n status,\n responseText,\n xhr\n }) => {\n const rumEndTime = now();\n if (status >= 400 || status === 0) {\n // Adding retry logic for the rum call will be a separate change\n this.ee.abort();\n return;\n }\n try {\n const {\n app,\n ...flags\n } = JSON.parse(responseText);\n try {\n this.timeKeeper.processRumRequest(xhr, rumStartTime, rumEndTime, app.nrServerTime);\n if (!this.timeKeeper.ready) throw new Error('TimeKeeper not ready');\n this.agentRef.runtime.timeKeeper = this.timeKeeper;\n } catch (error) {\n this.ee.abort();\n warn(17, error);\n return;\n }\n this.agentRef.runtime.appMetadata = app;\n activateFeatures(flags, this.agentIdentifier);\n this.drain();\n } catch (err) {\n this.ee.abort();\n warn(18, err);\n }\n }\n });\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.pageViewEvent;","import { onCLS } from 'web-vitals/attribution';\nimport { VITAL_NAMES } from './constants';\nimport { VitalMetric } from './vital-metric';\nimport { isBrowserScope } from '../constants/runtime';\nexport const cumulativeLayoutShift = new VitalMetric(VITAL_NAMES.CUMULATIVE_LAYOUT_SHIFT, x => x);\nif (isBrowserScope) {\n onCLS(({\n value,\n attribution,\n id\n }) => {\n const attrs = {\n metricId: id,\n largestShiftTarget: attribution.largestShiftTarget,\n largestShiftTime: attribution.largestShiftTime,\n largestShiftValue: attribution.largestShiftValue,\n loadState: attribution.loadState\n };\n cumulativeLayoutShift.update({\n value,\n attrs\n });\n }, {\n reportAllChanges: true\n });\n}","import { onFID } from 'web-vitals/attribution';\nimport { VitalMetric } from './vital-metric';\nimport { VITAL_NAMES } from './constants';\nimport { initiallyHidden, isBrowserScope } from '../constants/runtime';\nexport const firstInputDelay = new VitalMetric(VITAL_NAMES.FIRST_INPUT_DELAY);\nif (isBrowserScope) {\n onFID(({\n value,\n attribution\n }) => {\n if (initiallyHidden || firstInputDelay.isValid) return;\n const attrs = {\n type: attribution.eventType,\n fid: Math.round(value),\n eventTarget: attribution.eventTarget,\n loadState: attribution.loadState\n };\n\n // CWV will only report one (THE) first-input entry to us; fid isn't reported if there are no user interactions occurs before the *first* page hiding.\n firstInputDelay.update({\n value: attribution.eventTime,\n attrs\n });\n });\n}","import { onINP } from 'web-vitals/attribution';\nimport { VitalMetric } from './vital-metric';\nimport { VITAL_NAMES } from './constants';\nimport { isBrowserScope } from '../constants/runtime';\nexport const interactionToNextPaint = new VitalMetric(VITAL_NAMES.INTERACTION_TO_NEXT_PAINT);\nif (isBrowserScope) {\n /* Interaction-to-Next-Paint */\n onINP(({\n value,\n attribution,\n id\n }) => {\n const attrs = {\n metricId: id,\n eventTarget: attribution.interactionTarget,\n // event* attrs deprecated in v4, kept for NR backwards compatibility\n eventTime: attribution.interactionTime,\n // event* attrs deprecated in v4, kept for NR backwards compatibility\n interactionTarget: attribution.interactionTarget,\n interactionTime: attribution.interactionTime,\n interactionType: attribution.interactionType,\n inputDelay: attribution.inputDelay,\n nextPaintTime: attribution.nextPaintTime,\n processingDuration: attribution.processingDuration,\n presentationDelay: attribution.presentationDelay,\n loadState: attribution.loadState\n };\n interactionToNextPaint.update({\n value,\n attrs\n });\n });\n}","import { onLCP } from 'web-vitals/attribution';\nimport { VitalMetric } from './vital-metric';\nimport { VITAL_NAMES } from './constants';\nimport { initiallyHidden, isBrowserScope } from '../constants/runtime';\nimport { cleanURL } from '../url/clean-url';\nexport const largestContentfulPaint = new VitalMetric(VITAL_NAMES.LARGEST_CONTENTFUL_PAINT);\nif (isBrowserScope) {\n onLCP(({\n value,\n attribution\n }) => {\n /* Largest Contentful Paint - As of WV v3, it still imperfectly tries to detect document vis state asap and isn't supposed to report if page starts hidden. */\n if (initiallyHidden || largestContentfulPaint.isValid) return;\n let attrs;\n const lcpEntry = attribution.lcpEntry;\n if (lcpEntry) {\n attrs = {\n size: lcpEntry.size,\n eid: lcpEntry.id,\n element: attribution.element,\n timeToFirstByte: attribution.timeToFirstByte,\n resourceLoadDelay: attribution.resourceLoadDelay,\n resourceLoadDuration: attribution.resourceLoadDuration,\n resourceLoadTime: attribution.resourceLoadDuration,\n // kept for NR backwards compatibility, deprecated in v3->v4\n elementRenderDelay: attribution.elementRenderDelay\n };\n if (attribution.url) attrs.elUrl = cleanURL(attribution.url);\n if (lcpEntry.element?.tagName) attrs.elTag = lcpEntry.element.tagName;\n }\n largestContentfulPaint.update({\n value,\n attrs\n });\n });\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { nullable, numeric, getAddStringContext, addCustomAttributes } from '../../../common/serialize/bel-serializer';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { FEATURE_NAME } from '../constants';\nimport { FEATURE_NAMES, FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { cumulativeLayoutShift } from '../../../common/vitals/cumulative-layout-shift';\nimport { firstContentfulPaint } from '../../../common/vitals/first-contentful-paint';\nimport { firstInputDelay } from '../../../common/vitals/first-input-delay';\nimport { firstPaint } from '../../../common/vitals/first-paint';\nimport { interactionToNextPaint } from '../../../common/vitals/interaction-to-next-paint';\nimport { largestContentfulPaint } from '../../../common/vitals/largest-contentful-paint';\nimport { timeToFirstByte } from '../../../common/vitals/time-to-first-byte';\nimport { subscribeToVisibilityChange } from '../../../common/window/page-visibility';\nimport { VITAL_NAMES } from '../../../common/vitals/constants';\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n #handleVitalMetric = ({\n name,\n value,\n attrs\n }) => {\n this.addTiming(name, value, attrs);\n };\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n this.curSessEndRecorded = false;\n registerHandler('docHidden', msTimestamp => this.endCurrentSession(msTimestamp), this.featureName, this.ee);\n // Add the time of _window pagehide event_ firing to the next PVT harvest == NRDB windowUnload attr:\n registerHandler('winPagehide', msTimestamp => this.addTiming('unload', msTimestamp, null), this.featureName, this.ee);\n const harvestTimeSeconds = agentRef.init.page_view_timing.harvestTimeSeconds || 30;\n this.waitForFlags([]).then(() => {\n /* It's important that CWV api, like \"onLCP\", is called before the **scheduler** is initialized. The reason is because they listen to the same\n on vis change or pagehide events, and we'd want ex. onLCP to record the timing (win the race) before we try to send \"final harvest\". */\n firstPaint.subscribe(this.#handleVitalMetric);\n firstContentfulPaint.subscribe(this.#handleVitalMetric);\n firstInputDelay.subscribe(this.#handleVitalMetric);\n largestContentfulPaint.subscribe(this.#handleVitalMetric);\n interactionToNextPaint.subscribe(this.#handleVitalMetric);\n timeToFirstByte.subscribe(({\n attrs\n }) => {\n this.addTiming('load', Math.round(attrs.navigationEntry.loadEventEnd));\n });\n subscribeToVisibilityChange(() => {\n /* Downstream, the event consumer interprets all timing node value as ms-unit and converts it to seconds via division by 1000. CLS is unitless so this normally is a problem.\n bel.6 schema also doesn't support decimal values, of which cls within [0,1). However, the two nicely cancels out, and we can multiply cls by 1000 to both negate the division\n and send an integer > 1. We effectively lose some precision down to 3 decimal places for this workaround. E.g. (real) 0.749132... -> 749.132...-> 749 -> 0.749 (final) */\n const {\n name,\n value,\n attrs\n } = cumulativeLayoutShift.current;\n if (value === undefined) return;\n this.addTiming(name, value * 1000, attrs);\n }, true); // CLS node should only reports on vis change rather than on every change\n\n const scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n getPayload: options => this.makeHarvestPayload(options.retry)\n }, this);\n scheduler.startTimer(harvestTimeSeconds);\n this.drain();\n });\n }\n\n /**\n * Add the time of _document visibilitychange to hidden_ to the next PVT harvest == NRDB pageHide attr.\n * @param {number} timestamp\n */\n endCurrentSession(timestamp) {\n if (!this.curSessEndRecorded) {\n // TO DO: stage 2 - we don't want to capture this timing twice on page navigating away, but it should run again if we return to page and away *again*\n this.addTiming('pageHide', timestamp, null);\n this.curSessEndRecorded = true;\n }\n }\n addTiming(name, value, attrs) {\n attrs = attrs || {};\n addConnectionAttributes(attrs); // network conditions may differ from the actual for VitalMetrics when they were captured\n\n // If cls was set to another value by `onCLS`, then it's supported and is attached onto any timing but is omitted until such time.\n /*\n *cli Apr'23 - Convert attach-to-all -> attach-if-not-null. See NEWRELIC-6143.\n Issue: Because NR 'pageHide' was only sent once with what is considered the \"final\" CLS value, in the case that 'pageHide' fires before 'load' happens, we incorrectly a final CLS of 0 for that page.\n Mitigation: We've set initial CLS to null so that it's omitted from timings like 'pageHide' in that edge case. It should only be included if onCLS callback was executed at least once.\n Future: onCLS value changes should be reported directly & CLS separated into its own timing node so it's not beholden to 'pageHide' firing. It'd also be possible to report the real final CLS.\n *cli Mar'24 update: CLS now emitted as its own timing node in addition to as-property under other nodes. The 'cls' property is unnecessary for cls nodes.\n */\n if (name !== VITAL_NAMES.CUMULATIVE_LAYOUT_SHIFT && cumulativeLayoutShift.current.value >= 0) {\n attrs.cls = cumulativeLayoutShift.current.value;\n }\n this.events.add({\n name,\n value,\n attrs\n });\n handle('pvtAdded', [name, value, attrs], undefined, FEATURE_NAMES.sessionTrace, this.ee);\n }\n appendGlobalCustomAttributes(timing) {\n var timingAttributes = timing.attrs || {};\n var reservedAttributes = ['size', 'eid', 'cls', 'type', 'fid', 'elTag', 'elUrl', 'net-type', 'net-etype', 'net-rtt', 'net-dlink'];\n Object.entries(this.agentRef.info.jsAttributes || {}).forEach(([key, val]) => {\n if (reservedAttributes.indexOf(key) < 0) {\n timingAttributes[key] = val;\n }\n });\n }\n\n // serialize array of timing data\n serializer(eventBuffer) {\n var addString = getAddStringContext(this.agentIdentifier);\n var payload = 'bel.6;';\n for (var i = 0; i < eventBuffer.length; i++) {\n var timing = eventBuffer[i];\n payload += 'e,';\n payload += addString(timing.name) + ',';\n payload += nullable(timing.value, numeric, false) + ',';\n this.appendGlobalCustomAttributes(timing);\n var attrParts = addCustomAttributes(timing.attrs, addString);\n if (attrParts && attrParts.length > 0) {\n payload += numeric(attrParts.length) + ';' + attrParts.join(';');\n }\n if (i + 1 < eventBuffer.length) payload += ';';\n }\n return payload;\n }\n}\nfunction addConnectionAttributes(obj) {\n var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; // to date, both window & worker shares the same support for connection\n if (!connection) return;\n if (connection.type) obj['net-type'] = connection.type;\n if (connection.effectiveType) obj['net-etype'] = connection.effectiveType;\n if (connection.rtt) obj['net-rtt'] = connection.rtt;\n if (connection.downlink) obj['net-dlink'] = connection.downlink;\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.pageViewTiming;","/**\n * @file Keeps an object alive that is passed to all feature aggregate modules.\n * The purpose is to have a way for communication and signals to relay across features at runtime.\n * This object can hold any arbitrary values and should be treated as on-the-fly dynamic.\n */\n\nlet onReplayReady;\nconst sessionReplayInitialized = new Promise(resolve => {\n onReplayReady = resolve;\n});\nexport const sharedChannel = Object.freeze({\n onReplayReady,\n sessionReplayInitialized\n});","/*\n * Copyright 2023 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Records, aggregates, and harvests session replay data.\n */\n\nimport { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { ABORT_REASONS, FEATURE_NAME, QUERY_PARAM_PADDING, RRWEB_EVENT_TYPES, SR_EVENT_EMITTER_TYPES, TRIGGERS } from '../constants';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { sharedChannel } from '../../../common/constants/shared-channel';\nimport { obj as encodeObj } from '../../../common/url/encode';\nimport { warn } from '../../../common/util/console';\nimport { globalScope } from '../../../common/constants/runtime';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { FEATURE_NAMES, FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { RRWEB_VERSION } from \"../../../common/constants/env.npm\";\nimport { MODE, SESSION_EVENTS, SESSION_EVENT_TYPES } from '../../../common/session/constants';\nimport { stringify } from '../../../common/util/stringify';\nimport { stylesheetEvaluator } from '../shared/stylesheet-evaluator';\nimport { now } from '../../../common/timing/now';\nimport { buildNRMetaNode } from '../shared/utils';\nimport { MAX_PAYLOAD_SIZE } from '../../../common/constants/agent-constants';\nimport { cleanURL } from '../../../common/url/clean-url';\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n mode = MODE.OFF;\n\n // pass the recorder into the aggregator\n constructor(agentRef, args) {\n super(agentRef, FEATURE_NAME);\n /** The interval to harvest at. This gets overridden if the size of the payload exceeds certain thresholds */\n this.harvestTimeSeconds = agentRef.init.session_replay.harvestTimeSeconds || 60;\n /** Set once the recorder has fully initialized after flag checks and sampling */\n this.initialized = false;\n /** Set once the feature has been \"aborted\" to prevent other side-effects from continuing */\n this.blocked = false;\n /** populated with the gzipper lib async */\n this.gzipper = undefined;\n /** populated with the u8 string lib async */\n this.u8 = undefined;\n\n /** set by BCS response */\n this.entitled = false;\n /** set at BCS response, stored in runtime */\n this.timeKeeper = undefined;\n this.recorder = args?.recorder;\n this.errorNoticed = args?.errorNoticed || false;\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/Enabled'], undefined, FEATURE_NAMES.metrics, this.ee);\n\n // The SessionEntity class can emit a message indicating the session was cleared and reset (expiry, inactivity). This feature must abort and never resume if that occurs.\n this.ee.on(SESSION_EVENTS.RESET, () => {\n this.abort(ABORT_REASONS.RESET);\n });\n\n // The SessionEntity class can emit a message indicating the session was paused (visibility change). This feature must stop recording if that occurs.\n this.ee.on(SESSION_EVENTS.PAUSE, () => {\n this.recorder?.stopRecording();\n });\n // The SessionEntity class can emit a message indicating the session was resumed (visibility change). This feature must start running again (if already running) if that occurs.\n this.ee.on(SESSION_EVENTS.RESUME, () => {\n if (!this.recorder) return;\n // if the mode changed on a different tab, it needs to update this instance to match\n this.mode = agentRef.runtime.session.state.sessionReplayMode;\n if (!this.initialized || this.mode === MODE.OFF) return;\n this.recorder?.startRecording();\n });\n this.ee.on(SESSION_EVENTS.UPDATE, (type, data) => {\n if (!this.recorder || !this.initialized || this.blocked || type !== SESSION_EVENT_TYPES.CROSS_TAB) return;\n if (this.mode !== MODE.OFF && data.sessionReplayMode === MODE.OFF) this.abort(ABORT_REASONS.CROSS_TAB);\n this.mode = data.sessionReplay;\n });\n\n // Bespoke logic for blobs endpoint.\n this.scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result),\n retryDelay: this.harvestTimeSeconds,\n getPayload: ({\n retry,\n ...opts\n }) => this.makeHarvestPayload(retry, opts),\n raw: true\n }, this);\n registerHandler(SR_EVENT_EMITTER_TYPES.PAUSE, () => {\n this.forceStop(this.mode !== MODE.ERROR);\n }, this.featureName, this.ee);\n registerHandler(SR_EVENT_EMITTER_TYPES.ERROR_DURING_REPLAY, e => {\n this.handleError(e);\n }, this.featureName, this.ee);\n const {\n error_sampling_rate,\n sampling_rate,\n autoStart,\n block_selector,\n mask_text_selector,\n mask_all_inputs,\n inline_images,\n collect_fonts\n } = agentRef.init.session_replay;\n this.waitForFlags(['srs', 'sr']).then(([srMode, entitled]) => {\n this.entitled = !!entitled;\n if (!this.entitled) {\n this.deregisterDrain();\n if (this.recorder?.recording) {\n this.abort(ABORT_REASONS.ENTITLEMENTS);\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['SessionReplay/EnabledNotEntitled/Detected'], undefined, FEATURE_NAMES.metrics, this.ee);\n }\n return;\n }\n this.drain();\n this.initializeRecording(srMode);\n }).then(() => {\n if (this.mode === MODE.OFF) {\n this.recorder?.stopRecording(); // stop any conservative preload recording launched by instrument\n while (this.recorder?.getEvents().events.length) this.recorder?.clearBuffer?.();\n }\n sharedChannel.onReplayReady(this.mode);\n }); // notify watchers that replay started with the mode\n\n /** Detect if the default configs have been altered and report a SM. This is useful to evaluate what the reasonable defaults are across a customer base over time */\n if (!autoStart) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/AutoStart/Modified'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (collect_fonts === true) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/CollectFonts/Modified'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (inline_images === true) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/InlineImages/Modifed'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (mask_all_inputs !== true) handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/MaskAllInputs/Modified'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (block_selector !== '[data-nr-block]') handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/BlockSelector/Modified'], undefined, FEATURE_NAMES.metrics, this.ee);\n if (mask_text_selector !== '*') handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/MaskTextSelector/Modified'], undefined, FEATURE_NAMES.metrics, this.ee);\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/SamplingRate/Value', sampling_rate], undefined, FEATURE_NAMES.metrics, this.ee);\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['Config/SessionReplay/ErrorSamplingRate/Value', error_sampling_rate], undefined, FEATURE_NAMES.metrics, this.ee);\n }\n replayIsActive() {\n return Boolean(this.scheduler?.started && this.recorder && this.mode === MODE.FULL && !this.blocked && this.entitled);\n }\n handleError(e) {\n if (this.recorder) this.recorder.currentBufferTarget.hasError = true;\n // run once\n if (this.mode === MODE.ERROR && globalScope?.document.visibilityState === 'visible') {\n this.switchToFull();\n }\n }\n switchToFull() {\n if (!this.entitled || this.blocked) return;\n this.mode = MODE.FULL;\n // if the error was noticed AFTER the recorder was already imported....\n if (this.recorder && this.initialized) {\n if (!this.recorder.recording) this.recorder.startRecording();\n this.scheduler.startTimer(this.harvestTimeSeconds);\n this.syncWithSessionManager({\n sessionReplayMode: this.mode\n });\n } else {\n this.initializeRecording(false, true, true);\n }\n }\n\n /**\n * Evaluate entitlements and sampling before starting feature mechanics, importing and configuring recording library, and setting storage state\n * @param {boolean} entitlements - the true/false state of the \"sr\" flag from RUM response\n * @param {boolean} errorSample - the true/false state of the error sampling decision\n * @param {boolean} fullSample - the true/false state of the full sampling decision\n * @param {boolean} ignoreSession - whether to force the method to ignore the session state and use just the sample flags\n * @returns {void}\n */\n async initializeRecording(srMode, ignoreSession) {\n this.initialized = true;\n if (!this.entitled) return;\n\n // if theres an existing session replay in progress, there's no need to sample, just check the entitlements response\n // if not, these sample flags need to be checked\n // if this isnt the FIRST load of a session AND\n // we are not actively recording SR... DO NOT import or run the recording library\n // session replay samples can only be decided on the first load of a session\n // session replays can continue if already in progress\n const {\n session,\n timeKeeper\n } = this.agentRef.runtime;\n this.timeKeeper = timeKeeper;\n if (this.recorder?.parent.trigger === TRIGGERS.API && this.recorder?.recording) {\n this.mode = MODE.FULL;\n } else if (!session.isNew && !ignoreSession) {\n // inherit the mode of the existing session\n this.mode = session.state.sessionReplayMode;\n } else {\n // The session is new... determine the mode the new session should start in\n this.mode = srMode;\n }\n // If off, then don't record (early return)\n if (this.mode === MODE.OFF) return;\n if (!this.recorder) {\n try {\n // Do not change the webpackChunkName or it will break the webpack nrba-chunking plugin\n const {\n Recorder\n } = await import(/* webpackChunkName: \"recorder\" */'../shared/recorder');\n this.recorder = new Recorder(this);\n this.recorder.currentBufferTarget.hasError = this.errorNoticed;\n } catch (err) {\n return this.abort(ABORT_REASONS.IMPORT);\n }\n } else {\n this.recorder.parent = this;\n }\n\n // If an error was noticed before the mode could be set (like in the early lifecycle of the page), immediately set to FULL mode\n if (this.mode === MODE.ERROR && this.errorNoticed) this.mode = MODE.FULL;\n if (this.mode === MODE.FULL) {\n // If theres preloaded events and we are in full mode, just harvest immediately to clear up space and for consistency\n if (this.recorder?.getEvents().type === 'preloaded') {\n this.prepUtils().then(() => {\n this.scheduler.runHarvest();\n });\n }\n // FULL mode records AND reports from the beginning, while ERROR mode only records (but does not report).\n // ERROR mode will do this until an error is thrown, and then switch into FULL mode.\n // If an error happened in ERROR mode before we've gotten to this stage, it will have already set the mode to FULL\n if (!this.scheduler.started) {\n // We only report (harvest) in FULL mode\n this.scheduler.startTimer(this.harvestTimeSeconds);\n }\n }\n await this.prepUtils();\n if (!this.recorder.recording) this.recorder.startRecording();\n this.syncWithSessionManager({\n sessionReplayMode: this.mode\n });\n }\n async prepUtils() {\n try {\n // Do not change the webpackChunkName or it will break the webpack nrba-chunking plugin\n const {\n gzipSync,\n strToU8\n } = await import(/* webpackChunkName: \"compressor\" */'fflate');\n this.gzipper = gzipSync;\n this.u8 = strToU8;\n } catch (err) {\n // compressor failed to load, but we can still record without compression as a last ditch effort\n }\n }\n makeHarvestPayload(shouldRetryOnFail, opts) {\n if (!this.recorder || !this.timeKeeper?.ready || !this.recorder.hasSeenSnapshot) return;\n const recorderEvents = this.recorder.getEvents();\n // get the event type and use that to trigger another harvest if needed\n if (!recorderEvents.events.length || this.mode !== MODE.FULL || this.blocked) return;\n const payload = this.getHarvestContents(recorderEvents);\n if (!payload.body.length) {\n this.recorder.clearBuffer();\n return;\n }\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['SessionReplay/Harvest/Attempts'], undefined, FEATURE_NAMES.metrics, this.ee);\n let len = 0;\n if (!!this.gzipper && !!this.u8) {\n payload.body = this.gzipper(this.u8(\"[\".concat(payload.body.map(({\n __serialized,\n ...e\n }) => {\n if (e.__newrelic && __serialized) return __serialized;\n const output = {\n ...e\n };\n if (!output.__newrelic) {\n output.__newrelic = buildNRMetaNode(e.timestamp, this.timeKeeper);\n output.timestamp = this.timeKeeper.correctAbsoluteTimestamp(e.timestamp);\n }\n return stringify(output);\n }).join(','), \"]\")));\n len = payload.body.length;\n this.scheduler.opts.gzip = true;\n } else {\n payload.body = payload.body.map(({\n __serialized,\n ...node\n }) => {\n if (node.__newrelic) return node;\n const output = {\n ...node\n };\n output.__newrelic = buildNRMetaNode(node.timestamp, this.timeKeeper);\n output.timestamp = this.timeKeeper.correctAbsoluteTimestamp(node.timestamp);\n return output;\n });\n len = stringify(payload.body).length;\n this.scheduler.opts.gzip = false;\n }\n if (len > MAX_PAYLOAD_SIZE) {\n this.abort(ABORT_REASONS.TOO_BIG, len);\n return;\n }\n // TODO -- Gracefully handle the buffer for retries.\n if (!this.agentRef.runtime.session.state.sessionReplaySentFirstChunk) this.syncWithSessionManager({\n sessionReplaySentFirstChunk: true\n });\n this.recorder.clearBuffer();\n if (recorderEvents.type === 'preloaded') this.scheduler.runHarvest(opts);\n return [payload];\n }\n getCorrectedTimestamp(node) {\n if (!node?.timestamp) return;\n if (node.__newrelic) return node.timestamp;\n return this.timeKeeper.correctAbsoluteTimestamp(node.timestamp);\n }\n getHarvestContents(recorderEvents) {\n recorderEvents ??= this.recorder.getEvents();\n let events = recorderEvents.events;\n const agentRuntime = this.agentRef.runtime;\n const endUserId = this.agentRef.info.jsAttributes?.['enduser.id'];\n\n // do not let the first node be a full snapshot node, since this NEEDS to be preceded by a meta node\n // we will manually inject it if this happens\n const payloadStartsWithFullSnapshot = events?.[0]?.type === RRWEB_EVENT_TYPES.FullSnapshot;\n if (payloadStartsWithFullSnapshot && !!this.recorder.lastMeta) {\n recorderEvents.hasMeta = true;\n events.unshift(this.recorder.lastMeta); // --> pushed the meta from a previous payload into newer payload... but it still has old timestamps\n this.recorder.lastMeta = undefined;\n }\n\n // do not let the last node be a meta node, since this NEEDS to precede a snapshot\n // we will manually inject it later if we find a payload that is missing a meta node\n const payloadEndsWithMeta = events[events.length - 1]?.type === RRWEB_EVENT_TYPES.Meta;\n if (payloadEndsWithMeta) {\n this.recorder.lastMeta = events[events.length - 1];\n events = events.slice(0, events.length - 1);\n recorderEvents.hasMeta = !!events.find(x => x.type === RRWEB_EVENT_TYPES.Meta);\n }\n const relativeNow = now();\n const firstEventTimestamp = this.getCorrectedTimestamp(events[0]); // from rrweb node\n const lastEventTimestamp = this.getCorrectedTimestamp(events[events.length - 1]); // from rrweb node\n // from rrweb node || from when the harvest cycle started\n const firstTimestamp = firstEventTimestamp || Math.floor(this.timeKeeper.correctAbsoluteTimestamp(recorderEvents.cycleTimestamp));\n const lastTimestamp = lastEventTimestamp || Math.floor(this.timeKeeper.correctRelativeTimestamp(relativeNow));\n const agentMetadata = agentRuntime.appMetadata?.agents?.[0] || {};\n return {\n qs: {\n browser_monitoring_key: this.agentRef.info.licenseKey,\n type: 'SessionReplay',\n app_id: this.agentRef.info.applicationID,\n protocol_version: '0',\n timestamp: firstTimestamp,\n attributes: encodeObj({\n // this section of attributes must be controllable and stay below the query param padding limit -- see QUERY_PARAM_PADDING\n // if not, data could be lost to truncation at time of sending, potentially breaking parsing / API behavior in NR1\n ...(!!this.gzipper && !!this.u8 && {\n content_encoding: 'gzip'\n }),\n ...(agentMetadata.entityGuid && {\n entityGuid: agentMetadata.entityGuid\n }),\n harvestId: [agentRuntime.session?.state.value, agentRuntime.ptid, agentRuntime.harvestCount].filter(x => x).join('_'),\n 'replay.firstTimestamp': firstTimestamp,\n 'replay.lastTimestamp': lastTimestamp,\n 'replay.nodes': events.length,\n 'session.durationMs': agentRuntime.session.getDuration(),\n agentVersion: agentRuntime.version,\n session: agentRuntime.session.state.value,\n rst: relativeNow,\n hasMeta: recorderEvents.hasMeta || false,\n hasSnapshot: recorderEvents.hasSnapshot || false,\n hasError: recorderEvents.hasError || false,\n isFirstChunk: agentRuntime.session.state.sessionReplaySentFirstChunk === false,\n decompressedBytes: recorderEvents.payloadBytesEstimation,\n invalidStylesheetsDetected: stylesheetEvaluator.invalidStylesheetsDetected,\n inlinedAllStylesheets: recorderEvents.inlinedAllStylesheets,\n 'rrweb.version': RRWEB_VERSION,\n 'payload.type': recorderEvents.type,\n // customer-defined data should go last so that if it exceeds the query param padding limit it will be truncated instead of important attrs\n ...(endUserId && {\n 'enduser.id': this.obfuscator.obfuscateString(endUserId)\n }),\n currentUrl: this.obfuscator.obfuscateString(cleanURL('' + location))\n // The Query Param is being arbitrarily limited in length here. It is also applied when estimating the size of the payload in getPayloadSize()\n }, QUERY_PARAM_PADDING).substring(1) // remove the leading '&'\n },\n body: events\n };\n }\n postHarvestCleanup(result) {\n // The mutual decision for now is to stop recording and clear buffers if ingest is experiencing 429 rate limiting\n if (result.status === 429) {\n this.abort(ABORT_REASONS.TOO_MANY);\n }\n if (this.blocked) this.scheduler.stopTimer(true);\n }\n\n /**\n * Forces the agent into OFF mode so that changing tabs or navigating\n * does not restart the recording. This is used when the customer calls\n * the stopRecording API.\n */\n forceStop(forceHarvest) {\n if (forceHarvest) this.scheduler.runHarvest();\n this.mode = MODE.OFF;\n this.recorder?.stopRecording?.();\n this.syncWithSessionManager({\n sessionReplayMode: this.mode\n });\n }\n\n /** Abort the feature, once aborted it will not resume */\n abort(reason = {}, data) {\n warn(33, reason.message);\n handle(SUPPORTABILITY_METRIC_CHANNEL, [\"SessionReplay/Abort/\".concat(reason.sm), data], undefined, FEATURE_NAMES.metrics, this.ee);\n this.blocked = true;\n this.mode = MODE.OFF;\n this.recorder?.stopRecording?.();\n this.syncWithSessionManager({\n sessionReplayMode: this.mode\n });\n this.recorder?.clearTimestamps?.();\n this.ee.emit('REPLAY_ABORTED');\n while (this.recorder?.getEvents().events.length) this.recorder?.clearBuffer?.();\n }\n syncWithSessionManager(state = {}) {\n this.agentRef.runtime.session.write(state);\n }\n}","import { MODE } from '../../common/session/constants';\nimport { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.sessionReplay;\nexport const SR_EVENT_EMITTER_TYPES = {\n RECORD: 'recordReplay',\n PAUSE: 'pauseReplay',\n REPLAY_RUNNING: 'replayRunning',\n ERROR_DURING_REPLAY: 'errorDuringReplay'\n};\nexport const AVG_COMPRESSION = 0.12;\nexport const RRWEB_EVENT_TYPES = {\n DomContentLoaded: 0,\n Load: 1,\n FullSnapshot: 2,\n IncrementalSnapshot: 3,\n Meta: 4,\n Custom: 5\n};\n/** Interval between forcing new full snapshots -- 15 seconds in error mode (x2), 5 minutes in full mode */\nexport const CHECKOUT_MS = {\n [MODE.ERROR]: 15000,\n [MODE.FULL]: 300000,\n [MODE.OFF]: 0\n};\nexport const ABORT_REASONS = {\n RESET: {\n message: 'Session was reset',\n sm: 'Reset'\n },\n IMPORT: {\n message: 'Recorder failed to import',\n sm: 'Import'\n },\n TOO_MANY: {\n message: '429: Too Many Requests',\n sm: 'Too-Many'\n },\n TOO_BIG: {\n message: 'Payload was too large',\n sm: 'Too-Big'\n },\n CROSS_TAB: {\n message: 'Session Entity was set to OFF on another tab',\n sm: 'Cross-Tab'\n },\n ENTITLEMENTS: {\n message: 'Session Replay is not allowed and will not be started',\n sm: 'Entitlement'\n }\n};\n/** Reserved room for query param attrs */\nexport const QUERY_PARAM_PADDING = 5000;\nexport const TRIGGERS = {\n API: 'api'\n};","import { EventBuffer } from '../../utils/event-buffer';\nexport class RecorderEvents {\n /** The buffer to hold recorder event nodes */\n #events = new EventBuffer(Infinity);\n /** Payload metadata -- Should indicate when a replay blob started recording. Resets each time a harvest occurs.\n * cycle timestamps are used as fallbacks if event timestamps cannot be used\n */\n cycleTimestamp = Date.now();\n /** Payload metadata -- Should indicate that the payload being sent has a full DOM snapshot. This can happen\n * -- When the recording library begins recording, it starts by taking a DOM snapshot\n * -- When visibility changes from \"hidden\" -> \"visible\", it must capture a full snapshot for the replay to work correctly across tabs\n */\n hasSnapshot = false;\n /** Payload metadata -- Should indicate that the payload being sent has a meta node. The meta node should always precede a snapshot node. */\n hasMeta = false;\n /** Payload metadata -- Should indicate that the payload being sent contains an error. Used for query/filter purposes in UI */\n hasError = false;\n /** Payload metadata -- Denotes whether all stylesheet elements were able to be inlined */\n inlinedAllStylesheets = true;\n add(event) {\n this.#events.add(event);\n }\n get events() {\n return this.#events.get();\n }\n\n /** A value which increments with every new mutation node reported. Resets after a harvest is sent */\n get payloadBytesEstimation() {\n return this.#events.byteSize();\n }\n}","import { record as recorder } from 'rrweb';\nimport { stringify } from '../../../common/util/stringify';\nimport { AVG_COMPRESSION, CHECKOUT_MS, QUERY_PARAM_PADDING, RRWEB_EVENT_TYPES, SR_EVENT_EMITTER_TYPES } from '../constants';\nimport { getConfigurationValue } from '../../../common/config/init';\nimport { RecorderEvents } from './recorder-events';\nimport { MODE } from '../../../common/session/constants';\nimport { stylesheetEvaluator } from './stylesheet-evaluator';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { FEATURE_NAMES } from '../../../loaders/features/features';\nimport { buildNRMetaNode } from './utils';\nimport { IDEAL_PAYLOAD_SIZE } from '../../../common/constants/agent-constants';\nexport class Recorder {\n /** Each page mutation or event will be stored (raw) in this array. This array will be cleared on each harvest */\n #events;\n /** Backlog used for a 2-part sliding window to guarantee a 15-30s buffer window */\n #backloggedEvents;\n /** array of recorder events -- Will be filled only if forced harvest was triggered and harvester does not exist */\n #preloaded;\n /** flag that if true, blocks events from being \"stored\". Only set to true when a full snapshot has incomplete nodes (only stylesheets ATM) */\n #fixing = false;\n constructor(parent) {\n this.#events = new RecorderEvents();\n this.#backloggedEvents = new RecorderEvents();\n this.#preloaded = [new RecorderEvents()];\n /** True when actively recording, false when paused or stopped */\n this.recording = false;\n /** The pointer to the current bucket holding rrweb events */\n this.currentBufferTarget = this.#events;\n /** Only set to true once a snapshot node has been processed. Used to block preload harvests from sending before we know we have a snapshot */\n this.hasSeenSnapshot = false;\n /** Hold on to the last meta node, so that it can be re-inserted if the meta and snapshot nodes are broken up due to harvesting */\n this.lastMeta = false;\n /** The parent class that instantiated the recorder */\n this.parent = parent;\n /** A flag that can be set to false by failing conversions to stop the fetching process */\n this.shouldFix = getConfigurationValue(this.parent.agentIdentifier, 'session_replay.fix_stylesheets');\n /** The method to stop recording. This defaults to a noop, but is overwritten once the recording library is imported and initialized */\n this.stopRecording = () => {/* no-op until set by rrweb initializer */};\n }\n getEvents() {\n if (this.#preloaded[0]?.events.length) {\n return {\n ...this.#preloaded[0],\n events: this.#preloaded[0].events,\n payloadBytesEstimation: this.#preloaded[0].payloadBytesEstimation,\n type: 'preloaded'\n };\n }\n return {\n events: [...this.#backloggedEvents.events, ...this.#events.events].filter(x => x),\n type: 'standard',\n cycleTimestamp: Math.min(this.#backloggedEvents.cycleTimestamp, this.#events.cycleTimestamp),\n payloadBytesEstimation: this.#backloggedEvents.payloadBytesEstimation + this.#events.payloadBytesEstimation,\n hasError: this.#backloggedEvents.hasError || this.#events.hasError,\n hasMeta: this.#backloggedEvents.hasMeta || this.#events.hasMeta,\n hasSnapshot: this.#backloggedEvents.hasSnapshot || this.#events.hasSnapshot,\n inlinedAllStylesheets: !!this.#backloggedEvents.events.length && this.#backloggedEvents.inlinedAllStylesheets || this.#events.inlinedAllStylesheets\n };\n }\n\n /** Clears the buffer (this.#events), and resets all payload metadata properties */\n clearBuffer() {\n if (this.#preloaded[0]?.events.length) this.#preloaded.shift();else if (this.parent.mode === MODE.ERROR) this.#backloggedEvents = this.#events;else this.#backloggedEvents = new RecorderEvents();\n this.#events = new RecorderEvents();\n }\n\n /** Begin recording using configured recording lib */\n startRecording() {\n this.recording = true;\n const {\n block_class,\n ignore_class,\n mask_text_class,\n block_selector,\n mask_input_options,\n mask_text_selector,\n mask_all_inputs,\n inline_images,\n collect_fonts\n } = getConfigurationValue(this.parent.agentIdentifier, 'session_replay');\n const customMasker = (text, element) => {\n try {\n if (typeof element?.type === 'string' && element.type.toLowerCase() !== 'password' && (element?.dataset?.nrUnmask !== undefined || element?.classList?.contains('nr-unmask'))) return text;\n } catch (err) {\n // likely an element was passed to this handler that was invalid and was missing attributes or methods\n }\n return '*'.repeat(text?.length || 0);\n };\n // set up rrweb configurations for maximum privacy --\n // https://newrelic.atlassian.net/wiki/spaces/O11Y/pages/2792293280/2023+02+28+Browser+-+Session+Replay#Configuration-options\n const stop = recorder({\n emit: this.audit.bind(this),\n blockClass: block_class,\n ignoreClass: ignore_class,\n maskTextClass: mask_text_class,\n blockSelector: block_selector,\n maskInputOptions: mask_input_options,\n maskTextSelector: mask_text_selector,\n maskTextFn: customMasker,\n maskAllInputs: mask_all_inputs,\n maskInputFn: customMasker,\n inlineStylesheet: true,\n inlineImages: inline_images,\n collectFonts: collect_fonts,\n checkoutEveryNms: CHECKOUT_MS[this.parent.mode],\n recordAfter: 'DOMContentLoaded'\n });\n this.stopRecording = () => {\n this.recording = false;\n this.parent.ee.emit(SR_EVENT_EMITTER_TYPES.REPLAY_RUNNING, [false, this.parent.mode]);\n stop?.();\n };\n }\n\n /**\n * audit - Checks if the event node payload is missing certain attributes\n * will forward on to the \"store\" method if nothing needs async fixing\n * @param {*} event - An RRWEB event node\n * @param {*} isCheckout - Flag indicating if the payload was triggered as a checkout\n */\n audit(event, isCheckout) {\n /** An count of stylesheet objects that were blocked from accessing contents via JS */\n const incompletes = stylesheetEvaluator.evaluate();\n const missingInlineSMTag = 'SessionReplay/Payload/Missing-Inline-Css/';\n /** only run the full fixing behavior (more costly) if fix_stylesheets is configured as on (default behavior) */\n if (!this.shouldFix) {\n if (incompletes > 0) {\n this.currentBufferTarget.inlinedAllStylesheets = false;\n handle(SUPPORTABILITY_METRIC_CHANNEL, [missingInlineSMTag + 'Skipped', incompletes], undefined, FEATURE_NAMES.metrics, this.parent.ee);\n }\n return this.store(event, isCheckout);\n }\n /** Only stop ignoring data if already ignoring and a new valid snapshap is taking place (0 incompletes and we get a meta node for the snap) */\n if (!incompletes && this.#fixing && event.type === RRWEB_EVENT_TYPES.Meta) this.#fixing = false;\n if (incompletes > 0) {\n /** wait for the evaluator to download/replace the incompletes' src code and then take a new snap */\n stylesheetEvaluator.fix().then(failedToFix => {\n if (failedToFix > 0) {\n this.currentBufferTarget.inlinedAllStylesheets = false;\n this.shouldFix = false;\n }\n handle(SUPPORTABILITY_METRIC_CHANNEL, [missingInlineSMTag + 'Failed', failedToFix], undefined, FEATURE_NAMES.metrics, this.parent.ee);\n handle(SUPPORTABILITY_METRIC_CHANNEL, [missingInlineSMTag + 'Fixed', incompletes - failedToFix], undefined, FEATURE_NAMES.metrics, this.parent.ee);\n this.takeFullSnapshot();\n });\n /** Only start ignoring data if got a faulty snapshot */\n if (event.type === RRWEB_EVENT_TYPES.FullSnapshot || event.type === RRWEB_EVENT_TYPES.Meta) this.#fixing = true;\n }\n /** Only store the data if not being \"fixed\" (full snapshots that have broken css) */\n if (!this.#fixing) this.store(event, isCheckout);\n }\n\n /** Store a payload in the buffer (this.#events). This should be the callback to the recording lib noticing a mutation */\n store(event, isCheckout) {\n if (!event) return;\n if (!this.parent.scheduler && this.#preloaded.length) this.currentBufferTarget = this.#preloaded[this.#preloaded.length - 1];else this.currentBufferTarget = this.#events;\n if (this.parent.blocked) return;\n if (!this.notified) {\n this.parent.ee.emit(SR_EVENT_EMITTER_TYPES.REPLAY_RUNNING, [true, this.parent.mode]);\n this.notified = true;\n }\n if (this.parent.timeKeeper?.ready && !event.__newrelic) {\n event.__newrelic = buildNRMetaNode(event.timestamp, this.parent.timeKeeper);\n event.timestamp = this.parent.timeKeeper.correctAbsoluteTimestamp(event.timestamp);\n }\n event.__serialized = stringify(event);\n const eventBytes = event.__serialized.length;\n /** The estimated size of the payload after compression */\n const payloadSize = this.getPayloadSize(eventBytes);\n // Checkout events are flags by the recording lib that indicate a fullsnapshot was taken every n ms. These are important\n // to help reconstruct the replay later and must be included. While waiting and buffering for errors to come through,\n // each time we see a new checkout, we can drop the old data.\n // we need to check for meta because rrweb will flag it as checkout twice, once for meta, then once for snapshot\n if (this.parent.mode === MODE.ERROR && isCheckout && event.type === RRWEB_EVENT_TYPES.Meta) {\n // we are still waiting for an error to throw, so keep wiping the buffer over time\n this.clearBuffer();\n }\n\n // meta event\n if (event.type === RRWEB_EVENT_TYPES.Meta) {\n this.currentBufferTarget.hasMeta = true;\n }\n // snapshot event\n if (event.type === RRWEB_EVENT_TYPES.FullSnapshot) {\n this.currentBufferTarget.hasSnapshot = true;\n this.hasSeenSnapshot = true;\n }\n this.currentBufferTarget.add(event);\n\n // We are making an effort to try to keep payloads manageable for unloading. If they reach the unload limit before their interval,\n // it will send immediately. This often happens on the first snapshot, which can be significantly larger than the other payloads.\n if ((event.type === RRWEB_EVENT_TYPES.FullSnapshot && this.currentBufferTarget.hasMeta || payloadSize > IDEAL_PAYLOAD_SIZE) && this.parent.mode === MODE.FULL) {\n // if we've made it to the ideal size of ~64kb before the interval timer, we should send early.\n if (this.parent.scheduler) {\n this.parent.scheduler.runHarvest();\n } else {\n // we are still in \"preload\" and it triggered a \"stop point\". Make a new set, which will get pointed at on next cycle\n this.#preloaded.push(new RecorderEvents());\n }\n }\n }\n\n /** force the recording lib to take a full DOM snapshot. This needs to occur in certain cases, like visibility changes */\n takeFullSnapshot() {\n try {\n if (!this.recording) return;\n recorder.takeFullSnapshot();\n } catch (err) {\n // in the off chance we think we are recording, but rrweb does not, rrweb's lib will throw an error. This catch is just a precaution\n }\n }\n clearTimestamps() {\n this.currentBufferTarget.cycleTimestamp = undefined;\n }\n\n /** Estimate the payload size */\n getPayloadSize(newBytes = 0) {\n // the query param padding constant gives us some padding for the other metadata to be safely injected\n return this.estimateCompression(this.currentBufferTarget.payloadBytesEstimation + newBytes) + QUERY_PARAM_PADDING;\n }\n\n /** Extensive research has yielded about an 88% compression factor on these payloads.\n * This is an estimation using that factor as to not cause performance issues while evaluating\n * https://staging.onenr.io/037jbJWxbjy\n * */\n estimateCompression(data) {\n if (!!this.parent.gzipper && !!this.parent.u8) return data * AVG_COMPRESSION;\n return data;\n }\n}","import { gosNREUMOriginals } from '../../../common/window/nreum';\nimport { isBrowserScope } from '../../../common/constants/runtime';\nclass StylesheetEvaluator {\n #evaluated = new WeakSet();\n #brokenSheets = [];\n /**\n * Flipped to true if stylesheets that cannot be natively inlined are detected by the stylesheetEvaluator class\n * Used at harvest time to denote that all subsequent payloads are subject to this and customers should be advised to handle crossorigin decoration\n * */\n invalidStylesheetsDetected = false;\n failedToFix = 0;\n\n /**\n * this works by checking (only ever once) each cssRules obj in the style sheets array. The try/catch will catch an error if the cssRules obj blocks access, triggering the module to try to \"fix\" the asset`. Returns the count of incomplete assets discovered.\n * @returns {Number}\n */\n evaluate() {\n let incompletes = 0;\n this.#brokenSheets = [];\n if (isBrowserScope) {\n for (let i = 0; i < Object.keys(document.styleSheets).length; i++) {\n if (!this.#evaluated.has(document.styleSheets[i])) {\n this.#evaluated.add(document.styleSheets[i]);\n try {\n // eslint-disable-next-line\n const temp = document.styleSheets[i].cssRules;\n } catch (err) {\n if (!document.styleSheets[i].href) return;\n incompletes++;\n this.#brokenSheets.push(document.styleSheets[i]);\n }\n }\n }\n }\n if (incompletes) this.invalidStylesheetsDetected = true;\n return incompletes;\n }\n\n /**\n * Resolves promise once all stylesheets have been fetched and overridden\n * @returns {Promise}\n */\n async fix() {\n await Promise.all(this.#brokenSheets.map(sheet => this.#fetchAndOverride(sheet)));\n this.#brokenSheets = [];\n const failedToFix = this.failedToFix;\n this.failedToFix = 0;\n return failedToFix;\n }\n\n /**\n * Fetches stylesheet contents and overrides the target getters\n * @param {*} target - The stylesheet object target - ex. document.styleSheets[0]\n * @param {*} href - The asset href to fetch\n * @returns {Promise}\n */\n async #fetchAndOverride(target) {\n if (!target?.href) return;\n try {\n const stylesheetContents = await gosNREUMOriginals().o.FETCH.bind(window)(target.href);\n if (!stylesheetContents.ok) {\n this.failedToFix++;\n return;\n }\n const stylesheetText = await stylesheetContents.text();\n try {\n const cssSheet = new CSSStyleSheet();\n await cssSheet.replace(stylesheetText);\n Object.defineProperty(target, 'cssRules', {\n get() {\n return cssSheet.cssRules;\n }\n });\n Object.defineProperty(target, 'rules', {\n get() {\n return cssSheet.rules;\n }\n });\n } catch (err) {\n // cant make new dynamic stylesheets, browser likely doesn't support `.replace()`...\n // this is appended in prep of forking rrweb\n Object.defineProperty(target, 'cssText', {\n get() {\n return stylesheetText;\n }\n });\n this.failedToFix++;\n }\n } catch (err) {\n // failed to fetch\n this.failedToFix++;\n }\n }\n}\nexport const stylesheetEvaluator = new StylesheetEvaluator();","import { gosNREUMOriginals } from '../../../common/window/nreum';\nimport { getConfigurationValue } from '../../../common/config/init';\nimport { canEnableSessionTracking } from '../../utils/feature-gates';\nimport { originTime } from '../../../common/constants/runtime';\nexport function hasReplayPrerequisite(agentId) {\n return !!gosNREUMOriginals().o.MO &&\n // Session Replay cannot work without Mutation Observer\n canEnableSessionTracking(agentId) &&\n // requires session tracking to be running (hence \"session\" replay...)\n getConfigurationValue(agentId, 'session_trace.enabled') === true; // Session Replay as of now is tightly coupled with Session Trace in the UI\n}\nexport function isPreloadAllowed(agentId) {\n return getConfigurationValue(agentId, 'session_replay.preload') === true && hasReplayPrerequisite(agentId);\n}\nexport function buildNRMetaNode(timestamp, timeKeeper) {\n const correctedTimestamp = timeKeeper.correctAbsoluteTimestamp(timestamp);\n return {\n originalTimestamp: timestamp,\n correctedTimestamp,\n timestampDiff: timestamp - correctedTimestamp,\n originTime,\n correctedOriginTime: timeKeeper.correctedOriginTime,\n originTimeDiff: Math.floor(originTime - timeKeeper.correctedOriginTime)\n };\n}","/**\n * All nodes reported to the consumer must take this shape\n */\nexport class TraceNode {\n constructor(name, start, end, origin, type) {\n this.n = name;\n this.s = start;\n this.e = end;\n this.o = origin;\n this.t = type;\n }\n}","import { globalScope } from '../../../../common/constants/runtime';\nimport { MODE } from '../../../../common/session/constants';\nimport { now } from '../../../../common/timing/now';\nimport { parseUrl } from '../../../../common/url/parse-url';\nimport { MAX_NODES_PER_HARVEST } from '../../constants';\nimport { TraceNode } from './node';\nconst ERROR_MODE_SECONDS_WINDOW = 30 * 1000; // sliding window of nodes to track when simply monitoring (but not harvesting) in error mode\nconst SUPPORTS_PERFORMANCE_OBSERVER = typeof globalScope.PerformanceObserver === 'function';\nconst ignoredEvents = {\n // we find that certain events make the data too noisy to be useful\n global: {\n mouseup: true,\n mousedown: true\n },\n // certain events are present both in the window and in PVT metrics. PVT metrics are prefered so the window events should be ignored\n window: {\n load: true,\n pagehide: true\n },\n // when ajax instrumentation is disabled, all XMLHttpRequest events will return with origin = xhrOriginMissing and should be ignored\n xhrOriginMissing: {\n ignoreAll: true\n }\n};\nconst toAggregate = {\n typing: [1000, 2000],\n scrolling: [100, 1000],\n mousing: [1000, 2000],\n touching: [1000, 2000]\n};\n\n/** The purpose of this class is to manage, normalize, and retrieve ST nodes as needed without polluting the main ST modules */\nexport class TraceStorage {\n nodeCount = 0;\n trace = {};\n earliestTimeStamp = Infinity;\n latestTimeStamp = 0;\n prevStoredEvents = new Set();\n #backupTrace;\n constructor(parent) {\n this.parent = parent;\n }\n\n /** Central function called by all the other store__ & addToTrace API to append a trace node. */\n storeSTN(stn) {\n if (this.parent.blocked) return;\n if (this.nodeCount >= MAX_NODES_PER_HARVEST) {\n // limit the amount of pending data awaiting next harvest\n if (this.parent.mode !== MODE.ERROR) return;\n const openedSpace = this.trimSTNs(ERROR_MODE_SECONDS_WINDOW); // but maybe we could make some space by discarding irrelevant nodes if we're in sessioned Error mode\n if (openedSpace === 0) return;\n }\n if (this.trace[stn.n]) this.trace[stn.n].push(stn);else this.trace[stn.n] = [stn];\n if (stn.s < this.earliestTimeStamp) this.earliestTimeStamp = stn.s;\n if (stn.s > this.latestTimeStamp) this.latestTimeStamp = stn.s;\n this.nodeCount++;\n }\n\n /**\n * Trim the collection of nodes awaiting harvest such that those seen outside a certain span of time are discarded.\n * @param {number} lookbackDuration Past length of time until now for which we care about nodes, in milliseconds\n * @returns {number} However many nodes were discarded after trimming.\n */\n trimSTNs(lookbackDuration) {\n let prunedNodes = 0;\n const cutoffHighResTime = Math.max(now() - lookbackDuration, 0);\n Object.keys(this.trace).forEach(nameCategory => {\n const nodeList = this.trace[nameCategory];\n /* Notice nodes are appending under their name's list as they end and are stored. This means each list is already (roughly) sorted in chronological order by end time.\n * This isn't exact since nodes go through some processing & EE handlers chain, but it's close enough as we still capture nodes whose duration overlaps the lookback window.\n * ASSUMPTION: all 'end' timings stored are relative to timeOrigin (DOMHighResTimeStamp) and not Unix epoch based. */\n let cutoffIdx = nodeList.findIndex(node => cutoffHighResTime <= node.e);\n if (cutoffIdx === 0) return;else if (cutoffIdx < 0) {\n // whole list falls outside lookback window and is irrelevant\n cutoffIdx = nodeList.length;\n delete this.trace[nameCategory];\n } else nodeList.splice(0, cutoffIdx); // chop off everything outside our window i.e. before the last timeframe\n\n this.nodeCount -= cutoffIdx;\n prunedNodes += cutoffIdx;\n });\n return prunedNodes;\n }\n\n /** Used by session trace's harvester to create the payload body. */\n takeSTNs() {\n if (!SUPPORTS_PERFORMANCE_OBSERVER) {\n // if PO isn't supported, this checks resourcetiming buffer every harvest.\n this.storeResources(globalScope.performance?.getEntriesByType?.('resource'));\n }\n const stns = Object.entries(this.trace).flatMap(([name, listOfSTNodes]) => {\n // basically take the \"this.trace\" map-obj and concat all the list-type values\n if (!(name in toAggregate)) return listOfSTNodes;\n // Special processing for event nodes dealing with user inputs:\n const reindexByOriginFn = this.smearEvtsByOrigin(name);\n const partitionListByOriginMap = listOfSTNodes.sort((a, b) => a.s - b.s).reduce(reindexByOriginFn, {});\n return Object.values(partitionListByOriginMap).flat(); // join the partitions back into 1-D, now ordered by origin then start time\n }, this);\n const earliestTimeStamp = this.earliestTimeStamp;\n const latestTimeStamp = this.latestTimeStamp;\n return {\n stns,\n earliestTimeStamp,\n latestTimeStamp\n };\n }\n smearEvtsByOrigin(name) {\n const maxGap = toAggregate[name][0];\n const maxLen = toAggregate[name][1];\n const lastO = {};\n return (byOrigin, evtNode) => {\n let lastArr = byOrigin[evtNode.o];\n if (!lastArr) lastArr = byOrigin[evtNode.o] = [];\n const last = lastO[evtNode.o];\n if (name === 'scrolling' && !trivial(evtNode)) {\n lastO[evtNode.o] = null;\n evtNode.n = 'scroll';\n lastArr.push(evtNode);\n } else if (last && evtNode.s - last.s < maxLen && last.e > evtNode.s - maxGap) {\n last.e = evtNode.e;\n } else {\n lastO[evtNode.o] = evtNode;\n lastArr.push(evtNode);\n }\n return byOrigin;\n };\n function trivial(node) {\n const limit = 4;\n return !!(node && typeof node.e === 'number' && typeof node.s === 'number' && node.e - node.s < limit);\n }\n }\n processPVT(name, value, attrs) {\n this.storeTiming({\n [name]: value\n });\n if (hasFID(name, attrs)) this.storeEvent({\n type: 'fid',\n target: 'document'\n }, 'document', value, value + attrs.fid);\n function hasFID(name, attrs) {\n return name === 'fi' && !!attrs && typeof attrs.fid === 'number';\n }\n }\n storeTiming(timingEntry, isAbsoluteTimestamp = false) {\n if (!timingEntry) return;\n\n // loop iterates through prototype also (for FF)\n for (let key in timingEntry) {\n let val = timingEntry[key];\n\n // ignore size and status type nodes that do not map to timestamp metrics\n const lck = key.toLowerCase();\n if (lck.indexOf('size') >= 0 || lck.indexOf('status') >= 0) continue;\n\n // ignore inherited methods, meaningless 0 values, and bogus timestamps\n // that are in the future (Microsoft Edge seems to sometimes produce these)\n if (!(typeof val === 'number' && val >= 0)) continue;\n val = Math.round(val);\n if (this.parent.timeKeeper && this.parent.timeKeeper.ready && isAbsoluteTimestamp) {\n val = this.parent.timeKeeper.convertAbsoluteTimestamp(Math.floor(this.parent.timeKeeper.correctAbsoluteTimestamp(val)));\n }\n this.storeSTN(new TraceNode(key, val, val, 'document', 'timing'));\n }\n }\n\n // Tracks the events and their listener's duration on objects wrapped by wrap-events.\n storeEvent(currentEvent, target, start, end) {\n if (this.shouldIgnoreEvent(currentEvent, target)) return;\n if (this.prevStoredEvents.has(currentEvent)) return; // prevent multiple listeners of an event from creating duplicate trace nodes per occurrence. Cleared every harvest. near-zero chance for re-duplication after clearing per harvest since the timestamps of the event are considered for uniqueness.\n this.prevStoredEvents.add(currentEvent);\n const evt = new TraceNode(this.evtName(currentEvent.type), start, end, undefined, 'event');\n try {\n // webcomponents-lite.js can trigger an exception on currentEvent.target getter because\n // it does not check currentEvent.currentTarget before calling getRootNode() on it\n evt.o = this.evtOrigin(currentEvent.target, target);\n } catch (e) {\n evt.o = this.evtOrigin(null, target);\n }\n this.storeSTN(evt);\n }\n shouldIgnoreEvent(event, target) {\n const origin = this.evtOrigin(event.target, target);\n if (event.type in ignoredEvents.global) return true;\n if (!!ignoredEvents[origin] && ignoredEvents[origin].ignoreAll) return true;\n return !!(!!ignoredEvents[origin] && event.type in ignoredEvents[origin]);\n }\n evtName(type) {\n switch (type) {\n case 'keydown':\n case 'keyup':\n case 'keypress':\n return 'typing';\n case 'mousemove':\n case 'mouseenter':\n case 'mouseleave':\n case 'mouseover':\n case 'mouseout':\n return 'mousing';\n case 'scroll':\n return 'scrolling';\n case 'touchstart':\n case 'touchmove':\n case 'touchend':\n case 'touchcancel':\n case 'touchenter':\n case 'touchleave':\n return 'touching';\n default:\n return type;\n }\n }\n evtOrigin(t, target) {\n let origin = 'unknown';\n if (t && t instanceof XMLHttpRequest) {\n const params = this.parent.ee.context(t).params;\n if (!params || !params.status || !params.method || !params.host || !params.pathname) return 'xhrOriginMissing';\n origin = params.status + ' ' + params.method + ': ' + params.host + params.pathname;\n } else if (t && typeof t.tagName === 'string') {\n origin = t.tagName.toLowerCase();\n if (t.id) origin += '#' + t.id;\n if (t.className) {\n for (let i = 0; i < t.classList.length; i++) origin += '.' + t.classList[i];\n }\n }\n if (origin === 'unknown') {\n if (typeof target === 'string') origin = target;else if (target === document) origin = 'document';else if (target === window) origin = 'window';else if (target instanceof FileReader) origin = 'FileReader';\n }\n return origin;\n }\n\n // Tracks when the window history API specified by wrap-history is used.\n storeHist(path, old, time) {\n this.storeSTN(new TraceNode('history.pushState', time, time, path, old));\n }\n #laststart = 0;\n // Processes all the PerformanceResourceTiming entries captured (by observer).\n storeResources(resources) {\n if (!resources || resources.length === 0) return;\n resources.forEach(currentResource => {\n if ((currentResource.fetchStart | 0) <= this.#laststart) return; // don't recollect already-seen resources\n\n const {\n initiatorType,\n fetchStart,\n responseEnd,\n entryType\n } = currentResource;\n const {\n protocol,\n hostname,\n port,\n pathname\n } = parseUrl(currentResource.name);\n const res = new TraceNode(initiatorType, fetchStart | 0, responseEnd | 0, \"\".concat(protocol, \"://\").concat(hostname, \":\").concat(port).concat(pathname), entryType);\n this.storeSTN(res);\n });\n this.#laststart = resources[resources.length - 1].fetchStart | 0;\n }\n\n // JavascriptError (FEATURE) events pipes into ST here.\n storeErrorAgg(type, name, params, metrics) {\n if (type !== 'err') return; // internal errors are purposefully ignored\n this.storeSTN(new TraceNode('error', metrics.time, metrics.time, params.message, params.stackHash));\n }\n\n // Ajax (FEATURE) events--XML & fetches--pipes into ST here.\n storeXhrAgg(type, name, params, metrics) {\n if (type !== 'xhr') return;\n this.storeSTN(new TraceNode('Ajax', metrics.time, metrics.time + metrics.duration, \"\".concat(params.status, \" \").concat(params.method, \": \").concat(params.host).concat(params.pathname), 'ajax'));\n }\n\n /* Below are the interface expected & required of whatever storage is used across all features on an individual basis. This allows a common `.events` property on Trace. */\n isEmpty() {\n return this.nodeCount === 0;\n }\n save() {\n this.#backupTrace = this.trace;\n }\n get = this.takeSTNs;\n clear() {\n this.trace = {};\n this.nodeCount = 0;\n this.prevStoredEvents.clear(); // release references to past events for GC\n this.earliestTimeStamp = Infinity;\n this.latestTimeStamp = 0;\n }\n reloadSave() {\n Object.values(this.#backupTrace).forEach(stnsArray => stnsArray.forEach(stn => this.storeSTN(stn)));\n }\n clearSave() {\n this.#backupTrace = undefined;\n }\n}","import { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { FEATURE_NAME } from '../constants';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { TraceStorage } from './trace/storage';\nimport { obj as encodeObj } from '../../../common/url/encode';\nimport { globalScope } from '../../../common/constants/runtime';\nimport { MODE, SESSION_EVENTS } from '../../../common/session/constants';\nimport { applyFnToProps } from '../../../common/util/traverse';\nimport { FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { cleanURL } from '../../../common/url/clean-url';\nconst ERROR_MODE_SECONDS_WINDOW = 30 * 1000; // sliding window of nodes to track when simply monitoring (but not harvesting) in error mode\n/** Reserved room for query param attrs */\nconst QUERY_PARAM_PADDING = 5000;\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n this.harvestTimeSeconds = agentRef.init.session_trace.harvestTimeSeconds || 30;\n /** Tied to the entitlement flag response from BCS. Will short circuit operations of the agg if false */\n this.entitled = undefined;\n /** A flag used to decide if the 30 node threshold should be ignored on the first harvest to ensure sending on the first payload */\n this.everHarvested = false;\n /** If the harvest module is harvesting */\n this.harvesting = false;\n /** TraceStorage is the mechanism that holds, normalizes and aggregates ST nodes. It will be accessed and purged when harvests occur */\n this.events = new TraceStorage(this);\n /** This agg needs information about sampling (sts) and entitlements (st) to make the appropriate decisions on running */\n this.waitForFlags(['sts', 'st']).then(([stMode, stEntitled]) => this.initialize(stMode, stEntitled));\n }\n\n /** Sets up event listeners, and initializes this module to run in the correct \"mode\". Can be triggered from a few places, but makes an effort to only set up listeners once */\n initialize(stMode, stEntitled, ignoreSession) {\n this.entitled ??= stEntitled;\n if (this.blocked || !this.entitled) return this.deregisterDrain();\n if (!this.initialized) {\n this.initialized = true;\n /** Store session identifiers at initialization time to be cross-checked later at harvest time for session changes that are subject to race conditions */\n this.ptid = this.agentRef.runtime.ptid;\n this.sessionId = this.agentRef.runtime.session?.state.value;\n // The SessionEntity class can emit a message indicating the session was cleared and reset (expiry, inactivity). This feature must abort and never resume if that occurs.\n this.ee.on(SESSION_EVENTS.RESET, () => {\n if (this.blocked) return;\n this.abort(1);\n });\n // The SessionEntity can have updates (locally or across tabs for SR mode changes), (across tabs for ST mode changes).\n // Those updates should be sync'd here to ensure this page also honors the mode after initialization\n this.ee.on(SESSION_EVENTS.UPDATE, (eventType, sessionState) => {\n if (this.blocked) return;\n // this will only have an effect if ST is NOT already in full mode\n if (this.mode !== MODE.FULL && (sessionState.sessionReplayMode === MODE.FULL || sessionState.sessionTraceMode === MODE.FULL)) this.switchToFull();\n // 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\n if (this.sessionId !== sessionState.value || eventType === 'cross-tab' && this.scheduler?.started && sessionState.sessionTraceMode === MODE.OFF) this.abort(2);\n });\n if (typeof PerformanceNavigationTiming !== 'undefined') {\n this.events.storeTiming(globalScope.performance?.getEntriesByType?.('navigation')[0]);\n } else {\n this.events.storeTiming(globalScope.performance?.timing, true);\n }\n }\n\n /** ST/SR sampling flow in BCS - https://drive.google.com/file/d/19hwt2oft-8Hh4RrjpLqEXfpP_9wYBLcq/view?usp=sharing */\n /** ST will run in the mode provided by BCS if the session IS NEW. If not... it will use the state of the session entity to determine what mode to run in */\n if (!this.agentRef.runtime.session.isNew && !ignoreSession) this.mode = this.agentRef.runtime.session.state.sessionTraceMode;else this.mode = stMode;\n\n /** If the mode is off, we do not want to hold up draining for other features, so we deregister the feature for now.\n * If it drains later (due to a mode change), data and handlers will instantly drain instead of waiting for the registry. */\n if (this.mode === MODE.OFF) return this.deregisterDrain();\n this.timeKeeper ??= this.agentRef.runtime.timeKeeper;\n this.scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n retryDelay: this.harvestTimeSeconds,\n getPayload: options => this.makeHarvestPayload(options.retry),\n raw: true\n }, this);\n\n /** The handlers set up by the Inst file */\n registerHandler('bst', (...args) => this.events.storeEvent(...args), this.featureName, this.ee);\n registerHandler('bstResource', (...args) => this.events.storeResources(...args), this.featureName, this.ee);\n registerHandler('bstHist', (...args) => this.events.storeHist(...args), this.featureName, this.ee);\n registerHandler('bstXhrAgg', (...args) => this.events.storeXhrAgg(...args), this.featureName, this.ee);\n registerHandler('bstApi', (...args) => this.events.storeSTN(...args), this.featureName, this.ee);\n registerHandler('trace-jserror', (...args) => this.events.storeErrorAgg(...args), this.featureName, this.ee);\n registerHandler('pvtAdded', (...args) => this.events.processPVT(...args), this.featureName, this.ee);\n\n /** Only start actually harvesting if running in full mode at init time */\n if (this.mode === MODE.FULL) this.startHarvesting();else {\n /** A separate handler for noticing errors, and switching to \"full\" mode if running in \"error\" mode */\n registerHandler('trace-jserror', () => {\n if (this.mode === MODE.ERROR) this.switchToFull();\n }, this.featureName, this.ee);\n }\n this.agentRef.runtime.session.write({\n sessionTraceMode: this.mode\n });\n this.drain();\n }\n\n /** This module does not auto harvest by default -- it needs to be kicked off. Once this method is called, it will then harvest on an interval */\n startHarvesting() {\n if (this.scheduler.started || this.blocked) return;\n this.scheduler.runHarvest();\n this.scheduler.startTimer(this.harvestTimeSeconds);\n }\n preHarvestChecks() {\n if (this.mode !== MODE.FULL) return; // only allow harvest if running in full mode\n if (!this.timeKeeper?.ready) return; // this should likely never happen, but just to be safe, we should never harvest if we cant correct time\n if (!this.agentRef.runtime.session) return; // session entity is required for trace to run and continue running\n if (this.sessionId !== this.agentRef.runtime.session.state.value || this.ptid !== this.agentRef.runtime.ptid) {\n // If something unexpected happened and we somehow still got to harvesting after a session identifier changed, we should force-exit instead of harvesting:\n this.abort(3);\n return;\n }\n return true;\n }\n serializer({\n stns\n }) {\n if (!stns.length) return; // there are no processed nodes\n this.everHarvested = true;\n return applyFnToProps(stns, this.obfuscator.obfuscateString.bind(this.obfuscator), 'string');\n }\n queryStringsBuilder({\n stns,\n earliestTimeStamp,\n latestTimeStamp\n }) {\n const firstSessionHarvest = !this.agentRef.runtime.session.state.traceHarvestStarted;\n if (firstSessionHarvest) this.agentRef.runtime.session.write({\n traceHarvestStarted: true\n });\n const hasReplay = this.agentRef.runtime.session.state.sessionReplayMode === 1;\n const endUserId = this.agentRef.info.jsAttributes['enduser.id'];\n const entityGuid = this.agentRef.runtime.appMetadata.agents?.[0]?.entityGuid;\n\n /* The blob consumer expects the following and will reject if not supplied:\n * browser_monitoring_key\n * type\n * app_id\n * protocol_version\n * attributes\n *\n * For data that does not fit the schema of the above, it should be url-encoded and placed into `attributes`\n */\n\n return {\n browser_monitoring_key: this.agentRef.info.licenseKey,\n type: 'BrowserSessionChunk',\n app_id: this.agentRef.info.applicationID,\n protocol_version: '0',\n timestamp: Math.floor(this.timeKeeper.correctRelativeTimestamp(earliestTimeStamp)),\n attributes: encodeObj({\n ...(entityGuid && {\n entityGuid\n }),\n harvestId: \"\".concat(this.agentRef.runtime.session.state.value, \"_\").concat(this.agentRef.runtime.ptid, \"_\").concat(this.agentRef.runtime.harvestCount),\n // this section of attributes must be controllable and stay below the query param padding limit -- see QUERY_PARAM_PADDING\n // if not, data could be lost to truncation at time of sending, potentially breaking parsing / API behavior in NR1\n // trace payload metadata\n 'trace.firstTimestamp': Math.floor(this.timeKeeper.correctRelativeTimestamp(earliestTimeStamp)),\n 'trace.lastTimestamp': Math.floor(this.timeKeeper.correctRelativeTimestamp(latestTimeStamp)),\n 'trace.nodes': stns.length,\n 'trace.originTimestamp': this.timeKeeper.correctedOriginTime,\n // other payload metadata\n agentVersion: this.agentRef.runtime.version,\n ...(firstSessionHarvest && {\n firstSessionHarvest\n }),\n ...(hasReplay && {\n hasReplay\n }),\n ptid: \"\".concat(this.ptid),\n session: \"\".concat(this.sessionId),\n // customer-defined data should go last so that if it exceeds the query param padding limit it will be truncated instead of important attrs\n ...(endUserId && {\n 'enduser.id': this.obfuscator.obfuscateString(endUserId)\n }),\n currentUrl: this.obfuscator.obfuscateString(cleanURL('' + location))\n // The Query Param is being arbitrarily limited in length here. It is also applied when estimating the size of the payload in getPayloadSize()\n }, QUERY_PARAM_PADDING).substring(1) // remove the leading '&'\n };\n }\n\n /** Switch from \"off\" or \"error\" to full mode (if entitled) */\n switchToFull() {\n if (this.mode === MODE.FULL || !this.entitled || this.blocked) return;\n const prevMode = this.mode;\n this.mode = MODE.FULL;\n this.agentRef.runtime.session.write({\n sessionTraceMode: this.mode\n });\n if (prevMode === MODE.OFF || !this.initialized) return this.initialize(this.mode, this.entitled);\n if (this.initialized) {\n this.events.trimSTNs(ERROR_MODE_SECONDS_WINDOW); // up until now, Trace would've been just buffering nodes up to max, which needs to be trimmed to last X seconds\n }\n this.startHarvesting();\n }\n\n /** Stop running for the remainder of the page lifecycle */\n abort() {\n this.blocked = true;\n this.mode = MODE.OFF;\n this.agentRef.runtime.session.write({\n sessionTraceMode: this.mode\n });\n this.scheduler?.stopTimer();\n this.events.clear();\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.sessionTrace;\nexport const BST_RESOURCE = 'bstResource';\nexport const RESOURCE = 'resource';\nexport const START = '-start';\nexport const END = '-end';\nexport const FN_START = 'fn' + START;\nexport const FN_END = 'fn' + END;\nexport const PUSH_STATE = 'pushState';\nexport const MAX_NODES_PER_HARVEST = 1000;","let nodesSeen = 0;\nexport class BelNode {\n belType;\n /** List of other BelNode derivatives. Each children should be of a subclass that implements its own 'serialize' function. */\n children = [];\n start;\n end;\n callbackEnd = 0;\n callbackDuration = 0;\n nodeId = ++nodesSeen;\n constructor(agentIdentifier) {\n if (!agentIdentifier) throw new Error('Interaction is missing core attributes');\n this.agentIdentifier = agentIdentifier;\n }\n addChild(child) {\n this.children.push(child);\n }\n\n /** Virtual fn for stringifying an instance. */\n serialize() {}\n}","import { addCustomAttributes, getAddStringContext, nullable, numeric } from '../../../common/serialize/bel-serializer';\nimport { NODE_TYPE } from '../constants';\nimport { BelNode } from './bel-node';\nexport class AjaxNode extends BelNode {\n constructor(agentIdentifier, ajaxEvent) {\n super(agentIdentifier);\n this.belType = NODE_TYPE.AJAX;\n this.method = ajaxEvent.method;\n this.status = ajaxEvent.status;\n this.domain = ajaxEvent.domain;\n this.path = ajaxEvent.path;\n this.txSize = ajaxEvent.requestSize;\n this.rxSize = ajaxEvent.responseSize;\n this.requestedWith = ajaxEvent.type === 'fetch' ? 1 : ''; // 'xhr' and 'beacon' types get the empty string\n this.spanId = ajaxEvent.spanId;\n this.traceId = ajaxEvent.traceId;\n this.spanTimestamp = ajaxEvent.spanTimestamp;\n this.gql = ajaxEvent.gql;\n this.start = ajaxEvent.startTime; // 5000 --- 5500 --> 10500\n this.end = ajaxEvent.endTime;\n }\n serialize(parentStartTimestamp) {\n const addString = getAddStringContext(this.agentIdentifier);\n const nodeList = [];\n\n // IMPORTANT: The order in which addString is called matters and correlates to the order in which string shows up in the harvest payload. Do not re-order the following code.\n const fields = [numeric(this.belType), 0,\n // this will be overwritten below with number of attached nodes\n numeric(this.start - parentStartTimestamp),\n // start relative to parent start (if part of first node in payload) or first parent start\n numeric(this.end - this.start),\n // end is relative to start\n numeric(this.callbackEnd), numeric(this.callbackDuration), addString(this.method), numeric(this.status), addString(this.domain), addString(this.path), numeric(this.txSize), numeric(this.rxSize), this.requestedWith, addString(this.nodeId), nullable(this.spanId, addString, true) + nullable(this.traceId, addString, true) + nullable(this.spanTimestamp, numeric)];\n let allAttachedNodes = [];\n if (typeof this.gql === 'object') allAttachedNodes = addCustomAttributes(this.gql, addString);\n this.children.forEach(node => allAttachedNodes.push(node.serialize())); // no children is expected under ajax nodes at this time\n\n fields[1] = numeric(allAttachedNodes.length);\n nodeList.push(fields);\n if (allAttachedNodes.length) nodeList.push(allAttachedNodes.join(';'));\n return nodeList.join(';');\n }\n}","import { getInfo } from '../../../common/config/info';\nimport { globalScope, initialLocation } from '../../../common/constants/runtime';\nimport { generateUuid } from '../../../common/ids/unique-id';\nimport { addCustomAttributes, getAddStringContext, nullable, numeric } from '../../../common/serialize/bel-serializer';\nimport { now } from '../../../common/timing/now';\nimport { cleanURL } from '../../../common/url/clean-url';\nimport { NODE_TYPE, INTERACTION_STATUS, INTERACTION_TYPE, API_TRIGGER_NAME } from '../constants';\nimport { BelNode } from './bel-node';\n\n/**\n * link https://github.com/newrelic/nr-querypack/blob/main/schemas/bel/7.qpschema\n **/\nexport class Interaction extends BelNode {\n id = generateUuid(); // unique id that is serialized and used to link interactions with errors\n initialPageURL = initialLocation;\n oldURL = '' + globalScope?.location;\n newURL = '' + globalScope?.location;\n customName;\n customAttributes = {};\n customDataByApi = {};\n queueTime; // only used by initialPageLoad interactions\n appTime; // only used by initialPageLoad interactions\n newRoute;\n /** Internal state of this interaction: in-progress, finished, or cancelled. */\n status = INTERACTION_STATUS.IP;\n domTimestamp = 0;\n historyTimestamp = 0;\n createdByApi = false;\n keepOpenUntilEndApi = false;\n onDone = [];\n cancellationTimer;\n constructor(agentIdentifier, uiEvent, uiEventTimestamp, currentRouteKnown) {\n super(agentIdentifier);\n this.belType = NODE_TYPE.INTERACTION;\n this.trigger = uiEvent;\n this.start = uiEventTimestamp;\n this.oldRoute = currentRouteKnown;\n this.eventSubscription = new Map([['finished', []], ['cancelled', []]]);\n this.forceSave = this.forceIgnore = false;\n if (this.trigger === API_TRIGGER_NAME) this.createdByApi = true;\n }\n updateDom(timestamp) {\n this.domTimestamp = timestamp || now(); // default timestamp should be precise for accurate isActiveDuring calculations\n }\n updateHistory(timestamp, newUrl) {\n this.newURL = newUrl || '' + globalScope?.location;\n this.historyTimestamp = timestamp || now();\n }\n seenHistoryAndDomChange() {\n return this.historyTimestamp > 0 && this.domTimestamp > this.historyTimestamp; // URL must change before DOM does\n }\n on(event, cb) {\n if (!this.eventSubscription.has(event)) throw new Error('Cannot subscribe to non pre-defined events.');\n if (typeof cb !== 'function') throw new Error('Must supply function as callback.');\n this.eventSubscription.get(event).push(cb);\n }\n done(customEndTime) {\n // User could've mark this interaction--regardless UI or api started--as \"don't close until .end() is called on it\". Only .end provides a timestamp; the default flows do not.\n if (this.keepOpenUntilEndApi && customEndTime === undefined) return false;\n this.onDone.forEach(apiProvidedCb => apiProvidedCb(this.customDataByApi)); // this interaction's .save or .ignore can still be set by these user provided callbacks for example\n\n if (this.forceIgnore) this.#cancel(); // .ignore() always has precedence over save actions\n else if (this.seenHistoryAndDomChange()) this.#finish(customEndTime); // then this should've already finished while it was the interactionInProgress, with a natural end time\n else if (this.forceSave) this.#finish(customEndTime || performance.now()); // a manually saved ixn (did not fulfill conditions) must have a specified end time, if one wasn't provided\n else this.#cancel();\n return true;\n }\n #finish(customEndTime = 0) {\n if (this.status !== INTERACTION_STATUS.IP) return; // disallow this call if the ixn is already done aka not in-progress\n clearTimeout(this.cancellationTimer);\n this.end = Math.max(this.domTimestamp, this.historyTimestamp, customEndTime);\n this.customAttributes = {\n ...getInfo(this.agentIdentifier).jsAttributes,\n ...this.customAttributes\n }; // attrs specific to this interaction should have precedence over the general custom attrs\n this.status = INTERACTION_STATUS.FIN;\n\n // Run all the callbacks awaiting this interaction to finish.\n const callbacks = this.eventSubscription.get('finished');\n callbacks.forEach(fn => fn());\n }\n #cancel() {\n if (this.status !== INTERACTION_STATUS.IP) return; // disallow this call if the ixn is already done aka not in-progress\n clearTimeout(this.cancellationTimer);\n this.status = INTERACTION_STATUS.CAN;\n\n // Run all the callbacks listening to this interaction's potential cancellation.\n const callbacks = this.eventSubscription.get('cancelled');\n callbacks.forEach(fn => fn());\n }\n\n /**\n * Given a timestamp, determine if it falls within this interaction's span, i.e. if this was the active interaction during that time.\n * For in-progress interactions, this only compares the time with the start of span. Cancelled interactions are not considered active at all.\n * @param {DOMHighResTimeStamp} timestamp\n * @returns True or false boolean.\n */\n isActiveDuring(timestamp) {\n if (this.status === INTERACTION_STATUS.IP) return this.start <= timestamp;\n return this.status === INTERACTION_STATUS.FIN && this.start <= timestamp && this.end >= timestamp;\n }\n\n // Following are virtual properties overridden by a subclass:\n get firstPaint() {}\n get firstContentfulPaint() {}\n get navTiming() {}\n serialize(firstStartTimeOfPayload) {\n const addString = getAddStringContext(this.agentIdentifier);\n const nodeList = [];\n let ixnType;\n if (this.trigger === 'initialPageLoad') ixnType = INTERACTION_TYPE.INITIAL_PAGE_LOAD;else if (this.newURL !== this.oldURL) ixnType = INTERACTION_TYPE.ROUTE_CHANGE;else ixnType = INTERACTION_TYPE.UNSPECIFIED;\n\n // IMPORTANT: The order in which addString is called matters and correlates to the order in which string shows up in the harvest payload. Do not re-order the following code.\n const fields = [numeric(this.belType), 0,\n // this will be overwritten below with number of attached nodes\n numeric(this.start - firstStartTimeOfPayload),\n // relative to first node\n numeric(this.end - this.start),\n // end -- relative to start\n numeric(this.callbackEnd),\n // cbEnd -- relative to start; not used by BrowserInteraction events\n numeric(this.callbackDuration),\n // not relative\n addString(this.trigger), addString(cleanURL(this.initialPageURL, true)), addString(cleanURL(this.oldURL, true)), addString(cleanURL(this.newURL, true)), addString(this.customName), ixnType, nullable(this.queueTime, numeric, true) + nullable(this.appTime, numeric, true) + nullable(this.oldRoute, addString, true) + nullable(this.newRoute, addString, true) + addString(this.id), addString(this.nodeId), nullable(this.firstPaint, numeric, true) + nullable(this.firstContentfulPaint, numeric)];\n const allAttachedNodes = addCustomAttributes(this.customAttributes || {}, addString); // start with all custom attributes\n if (getInfo(this.agentIdentifier).atts) allAttachedNodes.push('a,' + addString(getInfo(this.agentIdentifier).atts)); // add apm provided attributes\n /* Querypack encoder+decoder quirkiness:\n - If first ixn node of payload is being processed, we use this node's start to offset. (firstStartTime should be 0--or undefined.)\n - Else for subsequent ixn nodes, we use the first ixn node's start to offset. */\n this.children.forEach(node => allAttachedNodes.push(node.serialize(firstStartTimeOfPayload || this.start))); // recursively add the serialized string of every child of this (ixn) bel node\n\n fields[1] = numeric(allAttachedNodes.length);\n nodeList.push(fields);\n if (allAttachedNodes.length) nodeList.push(allAttachedNodes.join(';'));\n if (this.navTiming) nodeList.push(this.navTiming);else nodeList.push('');\n // nodeList = [, , || '']\n\n return nodeList.join(';');\n }\n}","import { navTimingValues } from '../../../common/timing/nav-timing';\nimport { Interaction } from './interaction';\nimport { numeric } from '../../../common/serialize/bel-serializer';\nimport { firstPaint } from '../../../common/vitals/first-paint';\nimport { firstContentfulPaint } from '../../../common/vitals/first-contentful-paint';\nimport { getInfo } from '../../../common/config/info';\nexport class InitialPageLoadInteraction extends Interaction {\n constructor(agentIdentifier) {\n super(agentIdentifier, 'initialPageLoad', 0, null);\n const agentInfo = getInfo(agentIdentifier);\n this.queueTime = agentInfo.queueTime;\n this.appTime = agentInfo.applicationTime;\n }\n get firstPaint() {\n return firstPaint.current.value;\n }\n get firstContentfulPaint() {\n return firstContentfulPaint.current.value;\n }\n\n /**\n * Build the navTiming node. This assumes the navTimingValues array in nav-timing.js has already been filled with values via the PageViewEvent feature having\n * executed the addPT function first and foremost.\n */\n get navTiming() {\n if (!navTimingValues.length) return;\n /*\n 1. we initialize the seperator to ',' (seperates the nodeType id from the first value)\n 2. we initialize the navTiming node to 'b' (the nodeType id)\n 3. if the value is present, we add the seperator followed by the value;\n otherwise:\n - we add null seperator ('!') to the navTimingNode\n - we set the seperator to an empty string since we already wrote it above\n the reason for writing the null seperator instead of setting the seperator\n is to ensure we still write it if the null is the last navTiming value.\n */\n let seperator = ',';\n let navTimingNode = 'b';\n let prev = 0;\n\n // Get all navTiming values except offset aka timeOrigin since we just consider that (this.start) 0.\n // These are the latter 20 of the 21 timings appended by addPT:\n navTimingValues.slice(1, 21).forEach(v => {\n if (v !== undefined) {\n navTimingNode += seperator + numeric(v - prev);\n seperator = ',';\n prev = v;\n } else {\n navTimingNode += seperator + '!';\n seperator = '';\n }\n });\n return navTimingNode;\n }\n}","import { handle } from '../../../common/event-emitter/handle';\nimport { registerHandler } from '../../../common/event-emitter/register-handler';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { single } from '../../../common/util/invoke';\nimport { timeToFirstByte } from '../../../common/vitals/time-to-first-byte';\nimport { FEATURE_NAMES, FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { API_TRIGGER_NAME, FEATURE_NAME, INTERACTION_STATUS } from '../constants';\nimport { AjaxNode } from './ajax-node';\nimport { InitialPageLoadInteraction } from './initial-page-load-interaction';\nimport { Interaction } from './interaction';\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef, {\n domObserver\n }) {\n super(agentRef, FEATURE_NAME);\n const harvestTimeSeconds = agentRef.init.soft_navigations.harvestTimeSeconds || 10;\n this.interactionsToHarvest = this.events;\n this.domObserver = domObserver;\n this.initialPageLoadInteraction = new InitialPageLoadInteraction(agentRef.agentIdentifier);\n timeToFirstByte.subscribe(({\n attrs\n }) => {\n const loadEventTime = attrs.navigationEntry.loadEventEnd;\n this.initialPageLoadInteraction.forceSave = true;\n this.initialPageLoadInteraction.done(loadEventTime);\n this.interactionsToHarvest.add(this.initialPageLoadInteraction);\n this.initialPageLoadInteraction = null;\n // Report metric on the initial page load time\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['SoftNav/Interaction/InitialPageLoad/Duration/Ms', Math.round(loadEventTime)], undefined, FEATURE_NAMES.metrics, this.ee);\n });\n this.latestRouteSetByApi = null;\n this.interactionInProgress = null; // aside from the \"page load\" interaction, there can only ever be 1 ongoing at a time\n\n this.blocked = false;\n this.waitForFlags(['spa']).then(([spaOn]) => {\n if (spaOn) {\n this.drain();\n const scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n getPayload: options => this.makeHarvestPayload(options.retry),\n retryDelay: harvestTimeSeconds,\n onUnload: () => this.interactionInProgress?.done() // return any held ajax or jserr events so they can be sent with EoL harvest\n }, this);\n scheduler.startTimer(harvestTimeSeconds, 0);\n } else {\n this.blocked = true; // if rum response determines that customer lacks entitlements for spa endpoint, this feature shouldn't harvest\n this.deregisterDrain();\n }\n });\n\n // By default, a complete UI driven interaction requires event -> URL change -> DOM mod in that exact order.\n registerHandler('newUIEvent', event => this.startUIInteraction(event.type, Math.floor(event.timeStamp), event.target), this.featureName, this.ee);\n registerHandler('newURL', (timestamp, url) => this.interactionInProgress?.updateHistory(timestamp, url), this.featureName, this.ee);\n registerHandler('newDom', timestamp => {\n this.interactionInProgress?.updateDom(timestamp);\n if (this.interactionInProgress?.seenHistoryAndDomChange()) this.interactionInProgress.done();\n }, this.featureName, this.ee);\n this.#registerApiHandlers();\n registerHandler('ajax', this.#handleAjaxEvent.bind(this), this.featureName, this.ee);\n registerHandler('jserror', this.#handleJserror.bind(this), this.featureName, this.ee);\n }\n serializer(eventBuffer) {\n // The payload depacker takes the first ixn of a payload (if there are multiple ixns) and positively offset the subsequent ixns timestamps by that amount.\n // In order to accurately portray the real start & end times of the 2nd & onward ixns, we hence need to negatively offset their start timestamps with that of the 1st ixn.\n let firstIxnStartTime = 0; // the very 1st ixn does not require any offsetting\n const serializedIxnList = [];\n for (const interaction of eventBuffer) {\n serializedIxnList.push(interaction.serialize(firstIxnStartTime));\n if (!firstIxnStartTime) firstIxnStartTime = Math.floor(interaction.start);\n }\n return \"bel.7;\".concat(serializedIxnList.join(';'));\n }\n startUIInteraction(eventName, startedAt, sourceElem) {\n // this is throttled by instrumentation so that it isn't excessively called\n if (this.interactionInProgress?.createdByApi) return; // api-started interactions cannot be disrupted aka cancelled by UI events (and the vice versa applies as well)\n if (this.interactionInProgress?.done() === false) return;\n this.interactionInProgress = new Interaction(this.agentIdentifier, eventName, startedAt, this.latestRouteSetByApi);\n if (eventName === 'click') {\n const sourceElemText = getActionText(sourceElem);\n if (sourceElemText) this.interactionInProgress.customAttributes.actionText = sourceElemText;\n }\n this.interactionInProgress.cancellationTimer = setTimeout(() => {\n this.interactionInProgress.done();\n // Report metric on frequency of cancellation due to timeout for UI ixn\n handle(SUPPORTABILITY_METRIC_CHANNEL, ['SoftNav/Interaction/TimeOut'], undefined, FEATURE_NAMES.metrics, this.ee);\n }, 30000); // UI ixn are disregarded after 30 seconds if it's not completed by then\n this.setClosureHandlers();\n }\n setClosureHandlers() {\n this.interactionInProgress.on('finished', () => {\n const ref = this.interactionInProgress;\n this.interactionsToHarvest.add(this.interactionInProgress);\n this.interactionInProgress = null;\n this.domObserver.disconnect(); // can stop observing whenever our interaction logic completes a cycle\n\n // Report metric on the ixn duration\n handle(SUPPORTABILITY_METRIC_CHANNEL, [\"SoftNav/Interaction/\".concat(ref.newURL !== ref.oldURL ? 'RouteChange' : 'Custom', \"/Duration/Ms\"), Math.round(ref.end - ref.start)], undefined, FEATURE_NAMES.metrics, this.ee);\n });\n this.interactionInProgress.on('cancelled', () => {\n this.interactionInProgress = null;\n this.domObserver.disconnect();\n });\n }\n\n /**\n * Find the active interaction (current or past) for a given timestamp. Note that historic lookups mostly only go as far back as the last harvest for this feature.\n * Also, the caller should check the status of the interaction returned if found via {@link Interaction.status}, if that's pertinent.\n * TIP: Cancelled (status) interactions are NOT returned!\n * IMPORTANT: Finished interactions are in queue for next harvest! It's highly recommended that consumer logic be synchronous for safe reference.\n * @param {DOMHighResTimeStamp} timestamp\n * @returns An {@link Interaction} or undefined, if no active interaction was found.\n */\n getInteractionFor(timestamp) {\n /* In the sole case wherein there can be two \"interactions\" overlapping (initialPageLoad + regular route-change),\n the regular interaction should get precedence in being assigned the \"active\" interaction in regards to our one-at-a-time model.\n */\n if (this.interactionInProgress?.isActiveDuring(timestamp)) return this.interactionInProgress;\n let saveIxn;\n const interactionsBuffer = this.interactionsToHarvest.get();\n for (let idx = interactionsBuffer.length - 1; idx >= 0; idx--) {\n // reverse search for the latest completed interaction for efficiency\n const finishedInteraction = interactionsBuffer[idx];\n if (finishedInteraction.isActiveDuring(timestamp)) {\n if (finishedInteraction.trigger !== 'initialPageLoad') return finishedInteraction;\n // It's possible that a complete interaction occurs before page is fully loaded, so we need to consider if a route-change ixn may have overlapped this iPL\n else saveIxn = finishedInteraction;\n }\n }\n if (saveIxn) return saveIxn; // if an iPL was determined to be active and no route-change was found active for the same time, then iPL is deemed the one\n if (this.initialPageLoadInteraction?.isActiveDuring(timestamp)) return this.initialPageLoadInteraction; // lowest precedence and also only if it's still in-progress\n // Time must be when no interaction is happening, so return undefined.\n }\n\n /**\n * Handles or redirect ajax event based on the interaction, if any, that it's tied to.\n * @param {Object} event see Ajax feature's storeXhr function for object definition\n */\n #handleAjaxEvent(event) {\n const associatedInteraction = this.getInteractionFor(event.startTime);\n if (!associatedInteraction) {\n // no interaction was happening when this ajax started, so give it back to Ajax feature for processing\n handle('returnAjax', [event], undefined, FEATURE_NAMES.ajax, this.ee);\n } else {\n if (associatedInteraction.status === INTERACTION_STATUS.FIN) processAjax(this.agentIdentifier, event, associatedInteraction); // tack ajax onto the ixn object awaiting harvest\n else {\n // same thing as above, just at a later time -- if the interaction in progress is cancelled, just send the event back to ajax feat unmodified\n associatedInteraction.on('finished', () => processAjax(this.agentIdentifier, event, associatedInteraction));\n associatedInteraction.on('cancelled', () => handle('returnAjax', [event], undefined, FEATURE_NAMES.ajax, this.ee));\n }\n }\n function processAjax(agentId, event, parentInteraction) {\n const newNode = new AjaxNode(agentId, event);\n parentInteraction.addChild(newNode);\n }\n }\n\n /**\n * Decorate the passed-in params obj with properties relating to any associated interaction at the time of the timestamp.\n * @param {Object} params reference to the local var instance in Jserrors feature's storeError\n * @param {DOMHighResTimeStamp} timestamp time the jserror occurred\n */\n #handleJserror(params, timestamp) {\n const associatedInteraction = this.getInteractionFor(timestamp);\n if (!associatedInteraction) return; // do not need to decorate this jserror params\n\n // Whether the interaction is in-progress or already finished, the id will let jserror buffer it under its index, until it gets the next step instruction.\n params.browserInteractionId = associatedInteraction.id;\n if (associatedInteraction.status === INTERACTION_STATUS.FIN) {\n // This information cannot be relayed back via handle() that flushes buffered errs because this is being called by a jserror's handle() per se and before the err is buffered.\n params._softNavFinished = true; // instead, signal that this err can be processed right away without needing to be buffered aka wait for an in-progress ixn\n params._softNavAttributes = associatedInteraction.customAttributes;\n } else {\n // These callbacks may be added multiple times for an ixn, but just a single run will deal with all jserrors associated with the interaction.\n // As such, be cautious not to use the params object since that's tied to one specific jserror and won't affect the rest of them.\n associatedInteraction.on('finished', single(() => handle('softNavFlush', [associatedInteraction.id, true, associatedInteraction.customAttributes], undefined, FEATURE_NAMES.jserrors, this.ee)));\n associatedInteraction.on('cancelled', single(() => handle('softNavFlush', [associatedInteraction.id, false, undefined], undefined, FEATURE_NAMES.jserrors, this.ee))); // don't take custom attrs from cancelled ixns\n }\n }\n #registerApiHandlers() {\n const INTERACTION_API = 'api-ixn-';\n const thisClass = this;\n registerHandler(INTERACTION_API + 'get', function (time, {\n waitForEnd\n } = {}) {\n // In here, 'this' refers to the EventContext specific to per InteractionHandle instance spawned by each .interaction() api call.\n // Each api call aka IH instance would therefore retain a reference to either the in-progress interaction *at the time of the call* OR a new api-started interaction.\n this.associatedInteraction = thisClass.getInteractionFor(time);\n if (!this.associatedInteraction) {\n // This new api-driven interaction will be the target of any subsequent .interaction() call, until it is closed by EITHER .end() OR the regular seenHistoryAndDomChange process.\n this.associatedInteraction = thisClass.interactionInProgress = new Interaction(thisClass.agentIdentifier, API_TRIGGER_NAME, time, thisClass.latestRouteSetByApi);\n thisClass.setClosureHandlers();\n }\n if (waitForEnd === true) this.associatedInteraction.keepOpenUntilEndApi = true;\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'end', function (timeNow) {\n this.associatedInteraction.done(timeNow);\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'save', function () {\n this.associatedInteraction.forceSave = true;\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'ignore', function () {\n this.associatedInteraction.forceIgnore = true;\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'getContext', function (time, callback) {\n if (typeof callback !== 'function') return;\n setTimeout(() => callback(this.associatedInteraction.customDataByApi), 0);\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'onEnd', function (time, callback) {\n if (typeof callback !== 'function') return;\n this.associatedInteraction.onDone.push(callback);\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'actionText', function (time, newActionText) {\n if (newActionText) this.associatedInteraction.customAttributes.actionText = newActionText;\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'setName', function (time, name, trigger) {\n if (name) this.associatedInteraction.customName = name;\n if (trigger) this.associatedInteraction.trigger = trigger;\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'setAttribute', function (time, key, value) {\n this.associatedInteraction.customAttributes[key] = value;\n }, thisClass.featureName, thisClass.ee);\n registerHandler(INTERACTION_API + 'routeName', function (time, newRouteName) {\n // notice that this fn tampers with the ixn IP, not with the linked ixn\n thisClass.latestRouteSetByApi = newRouteName;\n if (thisClass.interactionInProgress) thisClass.interactionInProgress.newRoute = newRouteName;\n }, thisClass.featureName, thisClass.ee);\n }\n}\nfunction getActionText(elem) {\n const tagName = elem.tagName.toLowerCase();\n const elementsOfInterest = ['a', 'button', 'input'];\n if (elementsOfInterest.includes(tagName)) {\n return elem.title || elem.value || elem.innerText;\n }\n}","import { FEATURE_NAMES } from '../../loaders/features/features';\nexport const INTERACTION_TRIGGERS = ['click',\n// e.g. user clicks link or the page back/forward buttons\n'keydown',\n// e.g. user presses left and right arrow key to switch between displayed photo gallery\n'submit' // e.g. user clicks submit butotn or presses enter while editing a form field\n];\nexport const API_TRIGGER_NAME = 'api';\nexport const FEATURE_NAME = FEATURE_NAMES.softNav;\nexport const INTERACTION_TYPE = {\n INITIAL_PAGE_LOAD: '',\n ROUTE_CHANGE: 1,\n UNSPECIFIED: 2\n};\nexport const NODE_TYPE = {\n INTERACTION: 1,\n AJAX: 2,\n CUSTOM_END: 3,\n CUSTOM_TRACER: 4\n};\nexport const INTERACTION_STATUS = {\n IP: 'in progress',\n FIN: 'finished',\n CAN: 'cancelled'\n};","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nvar MAX_NODES = 128;\nvar lastId = 0;\nexport function InteractionNode(interaction, parent, type, timestamp) {\n Object.defineProperty(this, 'interaction', {\n value: interaction,\n writable: true // enumerable: false -- by default, which hides this prop from obj (iterations)\n });\n this.parent = parent;\n this.id = ++lastId;\n this.type = type;\n this.children = [];\n this.end = null;\n this.jsEnd = this.start = timestamp;\n this.jsTime = 0;\n this.attrs = {};\n this.cancelled = false;\n}\nvar InteractionNodePrototype = InteractionNode.prototype;\n\n/**\n * @param {string} type\n * @param {number} timestamp\n * @param {string} name\n * @param {bool} dontWait - When true, the interaction will not immediately start waiting\n * for this node to complete. This is used when the creation of\n * the node and its start happen at different times (e.g. XHR).\n */\nInteractionNodePrototype.child = function child(type, timestamp, name, dontWait) {\n var interaction = this.interaction;\n if (interaction.end || interaction.nodes >= MAX_NODES) return null;\n interaction.onNodeAdded(this);\n var node = new InteractionNode(interaction, this, type, timestamp);\n node.attrs.name = name;\n interaction.nodes++;\n if (!dontWait) {\n interaction.remaining++;\n }\n return node;\n};\nInteractionNodePrototype.callback = function addCallbackTime(exclusiveTime, end) {\n var node = this;\n node.jsTime += exclusiveTime;\n if (end > node.jsEnd) {\n node.jsEnd = end;\n node.interaction.lastCb = end;\n }\n};\nInteractionNodePrototype.cancel = function cancel() {\n this.cancelled = true;\n var interaction = this.interaction;\n interaction.remaining--;\n};\nInteractionNodePrototype.finish = function finish(timestamp) {\n var node = this;\n if (node.end) return;\n node.end = timestamp;\n\n // Find the next parent node that is not cancelled\n let parent = node.parent;\n while (parent?.cancelled) parent = parent.parent;\n\n // Assign the node to the non-cancelled parent node\n if (parent) parent.children.push(node);\n node.parent = null;\n\n // Update the interaction remaining counter\n var interaction = this.interaction;\n interaction.remaining--;\n interaction.lastFinish = timestamp;\n // check if interaction has finished, (this is needed for older browsers for unknown reasons)\n interaction.checkFinish();\n};","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getInfo } from '../../../common/config/info';\nimport { initialLocation } from '../../../common/constants/runtime';\nimport { gosNREUMOriginals } from '../../../common/window/nreum';\nimport { ee } from '../../../common/event-emitter/contextual-ee';\nimport { InteractionNode } from './interaction-node';\nvar originalSetTimeout = gosNREUMOriginals().o.ST;\nvar originalClearTimeout = gosNREUMOriginals().o.CT;\nvar lastId = {};\nexport function Interaction(eventName, timestamp, url, routeName, onFinished, agentIdentifier) {\n this.agentIdentifier = agentIdentifier;\n this.ee = ee.get(agentIdentifier);\n lastId[agentIdentifier] = 0;\n this.id = ++lastId[agentIdentifier];\n this.eventName = eventName;\n this.nodes = 0;\n this.remaining = 0;\n this.finishTimer = null;\n this.checkingFinish = false;\n this.lastCb = this.lastFinish = timestamp;\n this.handlers = [];\n this.onFinished = onFinished;\n this.done = false;\n var root = this.root = new InteractionNode(this, null, 'interaction', timestamp);\n var attrs = root.attrs;\n attrs.trigger = eventName;\n attrs.initialPageURL = initialLocation;\n attrs.oldRoute = routeName;\n attrs.newURL = attrs.oldURL = url;\n attrs.custom = {};\n attrs.store = {};\n}\nvar InteractionPrototype = Interaction.prototype;\nInteractionPrototype.checkFinish = function checkFinish() {\n var interaction = this;\n if (interaction.remaining > 0) {\n interaction._resetFinishCheck();\n return;\n }\n if (interaction.checkingFinish) {\n return;\n }\n if (interaction.root.end !== null) return;\n interaction._resetFinishCheck();\n interaction.checkingFinish = true;\n interaction.finishTimer = originalSetTimeout(() => {\n interaction.checkingFinish = false;\n interaction.finishTimer = originalSetTimeout(() => {\n interaction.finishTimer = null;\n if (interaction.remaining <= 0) interaction.finish();\n }, 1);\n }, 0);\n};\nInteractionPrototype.setNewURL = function setNewURL(url) {\n this.root.attrs.newURL = url;\n};\nInteractionPrototype.setNewRoute = function setNewRoute(route) {\n this.root.attrs.newRoute = route;\n};\nInteractionPrototype.onNodeAdded = function onNodeAdded() {\n this._resetFinishCheck();\n};\nInteractionPrototype._resetFinishCheck = function _resetFinishCheck() {\n if (this.finishTimer) {\n originalClearTimeout(this.finishTimer);\n this.finishTimer = null;\n this.checkingFinish = false;\n }\n};\n\n// serialize report and remove nodes from map\nInteractionPrototype.finish = function finishInteraction() {\n var interaction = this;\n var root = interaction.root;\n if (root.end !== null) return;\n var endTimestamp = Math.max(interaction.lastCb, interaction.lastFinish);\n var attrs = root.attrs;\n var customAttrs = attrs.custom;\n if (this.onFinished) {\n this.onFinished(this);\n }\n Object.entries(getInfo(interaction.agentIdentifier).jsAttributes || {}).forEach(([attr, value]) => {\n if (!(attr in customAttrs)) customAttrs[attr] = value;\n });\n root.end = endTimestamp;\n interaction.ee.emit('interaction', [this]);\n};","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { cleanURL } from '../../../common/url/clean-url';\nimport { nullable, numeric, getAddStringContext, addCustomAttributes } from '../../../common/serialize/bel-serializer';\nimport { SharedContext } from '../../../common/context/shared-context';\nimport { getInfo } from '../../../common/config/info';\nexport class Serializer extends SharedContext {\n constructor(parent) {\n super(parent);\n\n /**\n * This variable is used to calculate an interactions ending offset when the\n * harvest includes multiple interactions. This variable is set by the first\n * interaction processed and used by subsequent interactions in the same harvest.\n * See https://issues.newrelic.com/browse/NEWRELIC-5498\n * @type {number|undefined}\n */\n this.firstTimestamp = undefined;\n }\n serializeMultiple(interactions, offset, navTiming) {\n const info = getInfo(this.sharedContext.agentIdentifier);\n var addString = getAddStringContext(this.sharedContext.agentIdentifier);\n var serialized = 'bel.7';\n interactions.forEach(interaction => {\n serialized += ';' + this.serializeInteraction(interaction.root, offset, navTiming, interaction.routeChange, addString, info);\n });\n this.firstTimestamp = undefined;\n return serialized;\n }\n serializeSingle(root, offset, navTiming, isRouteChange) {\n const info = getInfo(this.sharedContext.agentIdentifier);\n var addString = getAddStringContext(this.sharedContext.agentIdentifier);\n var serialized = 'bel.7;' + this.serializeInteraction(root, offset, navTiming, isRouteChange, addString, info);\n this.firstTimestamp = undefined;\n return serialized;\n }\n serializeInteraction(root, offset, navTiming, isRouteChange, addString, info) {\n offset = offset || 0;\n var isInitialPage = root.attrs.trigger === 'initialPageLoad';\n var typeIdsByName = {\n interaction: 1,\n ajax: 2,\n customTracer: 4\n };\n\n // Include the hash fragment with all SPA data\n var includeHashFragment = true;\n const addNode = (node, nodeList) => {\n if (node.type === 'customEnd') return nodeList.push([3, numeric(node.end - this.firstTimestamp)]);\n var typeName = node.type;\n var typeId = typeIdsByName[typeName];\n var startTimestamp = node.start;\n var childCount = node.children.length;\n var attrCount = 0;\n var apmAttributes = info.atts;\n var hasNavTiming = isInitialPage && navTiming.length && typeId === 1;\n var children = [];\n var attrs = node.attrs;\n var metrics = attrs.metrics;\n var params = attrs.params;\n var queueTime = info.queueTime;\n var appTime = info.applicationTime;\n if (typeof this.firstTimestamp === 'undefined') {\n startTimestamp += offset;\n this.firstTimestamp = startTimestamp;\n } else {\n startTimestamp -= this.firstTimestamp;\n }\n var fields = [numeric(startTimestamp), numeric(node.end - node.start), numeric(node.jsEnd - node.end), numeric(node.jsTime)];\n switch (typeId) {\n case 1:\n fields[2] = numeric(node.jsEnd - this.firstTimestamp);\n fields.push(addString(attrs.trigger), addString(cleanURL(attrs.initialPageURL, includeHashFragment)), addString(cleanURL(attrs.oldURL, includeHashFragment)), addString(cleanURL(attrs.newURL, includeHashFragment)), addString(attrs.customName), isInitialPage ? '' : isRouteChange ? 1 : 2, nullable(isInitialPage && queueTime, numeric, true) + nullable(isInitialPage && appTime, numeric, true) + nullable(attrs.oldRoute, addString, true) + nullable(attrs.newRoute, addString, true) + addString(attrs.id), addString(node.id), nullable(attrs.firstPaint, numeric, true) + nullable(attrs.firstContentfulPaint, numeric, false));\n var attrParts = addCustomAttributes(attrs.custom, addString);\n children = children.concat(attrParts);\n attrCount = attrParts.length;\n if (apmAttributes) {\n childCount++;\n children.push('a,' + addString(apmAttributes));\n }\n break;\n case 2:\n fields.push(addString(params.method), numeric(params.status), addString(params.host), addString(params.pathname), numeric(metrics.txSize), numeric(metrics.rxSize), attrs.isFetch ? 1 : attrs.isJSONP ? 2 : '', addString(node.id), nullable(node.dt && node.dt.spanId, addString, true) + nullable(node.dt && node.dt.traceId, addString, true) + nullable(node.dt && node.dt.timestamp, numeric, false));\n\n // add params.gql here\n if (Object.keys(params?.gql || {}).length) {\n var ajaxAttrParts = addCustomAttributes(params.gql, addString);\n children = children.concat(ajaxAttrParts);\n attrCount = ajaxAttrParts.length;\n }\n break;\n case 4:\n var tracedTime = attrs.tracedTime;\n fields.push(addString(attrs.name), nullable(tracedTime, numeric, true) + addString(node.id));\n break;\n }\n for (var i = 0; i < node.children.length; i++) {\n addNode(node.children[i], children);\n }\n fields.unshift(numeric(typeId), numeric(childCount += attrCount));\n nodeList.push(fields);\n if (childCount) {\n nodeList.push(children.join(';'));\n }\n if (hasNavTiming) {\n // this build up the navTiming node\n // it for each navTiming value (pre aggregated in nav-timing.js):\n // we initialize the seperator to ',' (seperates the nodeType id from the first value)\n // we initialize the navTiming node to 'b' (the nodeType id)\n // if the value is present:\n // we add the seperator followed by the value\n // otherwise\n // we add null seperator ('!') to the navTimingNode\n // we set the seperator to an empty string since we already wrote it above\n // the reason for writing the null seperator instead of setting the seperator\n // is to ensure we still write it if the null is the last navTiming value.\n\n var seperator = ',';\n var navTimingNode = 'b';\n var prev = 0;\n\n // get all navTiming values except navigationStart\n // (since its the same as interaction.start)\n // and limit to just the first 20 values we know about\n Object.values(navTiming.slice(1, 21) || {}).forEach(v => {\n if (v !== undefined) {\n navTimingNode += seperator + numeric(v - prev);\n seperator = ',';\n prev = v;\n } else {\n navTimingNode += seperator + '!';\n seperator = '';\n }\n });\n nodeList.push(navTimingNode);\n } else if (typeId === 1) {\n nodeList.push('');\n }\n return nodeList;\n };\n return addNode(root, []).join(';');\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/* eslint no-undef: \"error\" */\nimport { registerHandler as register } from '../../../common/event-emitter/register-handler';\nimport { parseUrl } from '../../../common/url/parse-url';\nimport { shouldCollectEvent } from '../../../common/deny-list/deny-list';\nimport { navTimingValues as navTiming } from '../../../common/timing/nav-timing';\nimport { generateUuid } from '../../../common/ids/unique-id';\nimport { Interaction } from './interaction';\nimport { eventListenerOpts } from '../../../common/event-listener/event-listener-opts';\nimport { HarvestScheduler } from '../../../common/harvest/harvest-scheduler';\nimport { Serializer } from './serializer';\nimport { ee } from '../../../common/event-emitter/contextual-ee';\nimport * as CONSTANTS from '../constants';\nimport { FEATURE_NAMES, FEATURE_TO_ENDPOINT } from '../../../loaders/features/features';\nimport { AggregateBase } from '../../utils/aggregate-base';\nimport { firstContentfulPaint } from '../../../common/vitals/first-contentful-paint';\nimport { firstPaint } from '../../../common/vitals/first-paint';\nimport { bundleId } from '../../../common/ids/bundle-id';\nimport { initialLocation, loadedAsDeferredBrowserScript } from '../../../common/constants/runtime';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../metrics/constants';\nimport { warn } from '../../../common/util/console';\nconst {\n FEATURE_NAME,\n INTERACTION_EVENTS,\n MAX_TIMER_BUDGET,\n FN_START,\n FN_END,\n CB_START,\n INTERACTION_API,\n REMAINING,\n INTERACTION,\n SPA_NODE,\n JSONP_NODE,\n FETCH_START,\n FETCH_DONE,\n FETCH_BODY,\n JSONP_END,\n originalSetTimeout\n} = CONSTANTS;\nexport class Aggregate extends AggregateBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef) {\n super(agentRef, FEATURE_NAME);\n const state = this.state = {\n initialPageURL: initialLocation,\n lastSeenUrl: initialLocation,\n lastSeenRouteName: null,\n timerMap: {},\n timerBudget: MAX_TIMER_BUDGET,\n currentNode: null,\n prevNode: null,\n nodeOnLastHashUpdate: null,\n initialPageLoad: null,\n pageLoaded: false,\n childTime: 0,\n depth: 0,\n harvestTimeSeconds: agentRef.init.spa.harvestTimeSeconds || 10,\n // The below feature flag is used to disable the SPA ajax fix for specific customers, see https://new-relic.atlassian.net/browse/NR-172169\n disableSpaFix: (agentRef.init.feature_flags || []).indexOf('disable-spa-fix') > -1\n };\n this.spaSerializerClass = new Serializer(this);\n const classThis = this;\n let scheduler;\n const baseEE = ee.get(agentRef.agentIdentifier); // <-- parent baseEE\n const mutationEE = baseEE.get('mutation');\n const promiseEE = baseEE.get('promise');\n const historyEE = baseEE.get('history');\n const eventsEE = baseEE.get('events'); // ajax --> ee(123).emit() ee()\n const timerEE = baseEE.get('timer');\n const fetchEE = baseEE.get('fetch');\n const jsonpEE = baseEE.get('jsonp');\n const xhrEE = baseEE.get('xhr');\n const tracerEE = baseEE.get('tracer');\n\n // childTime is used when calculating exclusive time for a cb duration.\n //\n // Exclusive time will be different than the total time for either callbacks\n // which synchronously invoke a customTracer callback or, trigger a synchronous\n // event (eg. onreadystate=1 or popstate).\n //\n // At fn-end, childTime will contain the total time of all timed callbacks and\n // event handlers which executed as a child of the current callback. At the\n // begining of every callback, childTime is saved to the event context (which at\n // that time contains the sum of its preceeding siblings) and is reset to 0. The\n // callback is then executed, and its children may increase childTime. At the\n // end of the callback, it reports its exclusive time as its\n // execution time - exlcuded. childTime is then reset to its previous\n // value, and the totalTime of the callback that just finished executing is\n // added to the childTime time.\n // | clock | childTime | ctx.ct | totalTime | exclusive |\n // click fn-start | 0 | 0 | 0 | | |\n // | click begining: | 5 | 0 | 0 | | |\n // | | custom-1 fn-start | 10 | 0 | 0 | | |\n // | | | custom-1 begining | 15 | 0 | 0 | | |\n // | | | | custom-2 fn-start | 20 | 0 | 0 | | |\n // | | | | | custom-2 | 25 | 0 | 0 | | |\n // | | | | custom-2 fn-end | 30 | 10 | 0 | 10 | 10 |\n // | | | custom-1 middle | 35 | 10 | 0 | | |\n // | | | | custom-3 fn-start | 40 | 0 | 10 | | |\n // | | | | | custom-3 | 45 | 0 | 10 | | |\n // | | | | custom-3 fn-end | 50 | 20 | 0 | 10 | 10 |\n // | | | custom-1 ending | 55 | 20 | 0 | | |\n // | custom-1 fn-end | 60 | 50 | 0 | 50 | 30 |\n // | click ending: | 65 | 50 | | | |\n // click fn-end | 70 | 0 | 0 | 70 | 20 |\n\n this.waitForFlags(['spa']).then(([spaFlag]) => {\n if (spaFlag) {\n scheduler = new HarvestScheduler(FEATURE_TO_ENDPOINT[this.featureName], {\n onFinished: result => this.postHarvestCleanup(result.sent && result.retry),\n getPayload: options => this.makeHarvestPayload(options.retry),\n retryDelay: state.harvestTimeSeconds\n }, this);\n this.drain();\n } else {\n this.blocked = true;\n this.deregisterDrain();\n }\n });\n if (agentRef.init.spa.enabled !== true) return;\n state.initialPageLoad = new Interaction('initialPageLoad', 0, state.lastSeenUrl, state.lastSeenRouteName, onInteractionFinished, agentRef.agentIdentifier);\n state.initialPageLoad.save = true;\n state.prevInteraction = state.initialPageLoad;\n state.currentNode = state.initialPageLoad.root; // hint\n // ensure that checkFinish calls are safe during initialPageLoad\n state.initialPageLoad[REMAINING]++;\n register(FN_START, callbackStart, this.featureName, baseEE);\n register(CB_START, callbackStart, this.featureName, promiseEE);\n\n // register plugins\n var pluginApi = {\n getCurrentNode,\n setCurrentNode\n };\n register('spa-register', function (init) {\n if (typeof init === 'function') {\n init(pluginApi);\n }\n }, FEATURE_NAMES.spa, baseEE);\n function callbackStart() {\n state.depth++;\n this.prevNode = state.currentNode;\n this.ct = state.childTime;\n state.childTime = 0;\n state.timerBudget = MAX_TIMER_BUDGET;\n }\n register(FN_END, callbackEnd, this.featureName, baseEE);\n register('cb-end', callbackEnd, this.featureName, promiseEE);\n function callbackEnd() {\n state.depth--;\n var totalTime = this.jsTime || 0;\n var exclusiveTime = totalTime - state.childTime;\n state.childTime = this.ct + totalTime;\n if (state.currentNode) {\n // transfer accumulated callback time to the active interaction node\n // run even if jsTime is 0 to update jsEnd\n state.currentNode.callback(exclusiveTime, this[FN_END]);\n if (this.isTraced) {\n state.currentNode.attrs.tracedTime = exclusiveTime;\n }\n }\n this.jsTime = state.currentNode ? 0 : exclusiveTime;\n setCurrentNode(this.prevNode);\n this.prevNode = null;\n state.timerBudget = MAX_TIMER_BUDGET;\n }\n register(FN_START, function (args, eventSource) {\n var ev = args[0];\n var evName = ev.type;\n var eventNode = ev[\"__nrNode:\".concat(bundleId)];\n if (!state.pageLoaded && (evName === 'load' && eventSource === window || loadedAsDeferredBrowserScript)) {\n state.pageLoaded = true;\n // set to null so prevNode is set correctly\n this.prevNode = state.currentNode = null;\n if (state.initialPageLoad) {\n eventNode = state.initialPageLoad.root;\n\n // Even if initialPageLoad has remaining callbacks, force the initialPageLoad\n // interaction to complete when the page load event occurs.\n state.initialPageLoad[REMAINING] = 0;\n originalSetTimeout(function () {\n INTERACTION_EVENTS.push('popstate');\n });\n }\n }\n if (eventNode) {\n // If we've already seen a previous handler for this specific event object,\n // just restore that. We want multiple handlers for the same event to share\n // a node.\n setCurrentNode(eventNode);\n } else if (evName === 'hashchange') {\n setCurrentNode(state.nodeOnLastHashUpdate);\n state.nodeOnLastHashUpdate = null;\n } else if (eventSource instanceof XMLHttpRequest) {\n // If this event was emitted by an XHR, restore the node ID associated with\n // that XHR.\n setCurrentNode(baseEE.context(eventSource).spaNode);\n } else if (!state.currentNode && INTERACTION_EVENTS.indexOf(evName) !== -1) {\n // Otherwise, if no interaction is currently active, create a new node ID,\n // and let the aggregator know that we entered a new event handler callback\n // so that it has a chance to possibly start an interaction.\n var ixn = new Interaction(evName, this[FN_START], state.lastSeenUrl, state.lastSeenRouteName, onInteractionFinished, agentRef.agentIdentifier);\n\n // Store the interaction as prevInteraction in case it is prematurely discarded\n state.prevInteraction = ixn;\n setCurrentNode(ixn.root);\n if (evName === 'click') {\n var value = getActionText(ev.target);\n if (value) {\n state.currentNode.attrs.custom.actionText = value;\n }\n }\n }\n ev[\"__nrNode:\".concat(bundleId)] = state.currentNode;\n }, this.featureName, eventsEE);\n\n /**\n * *** TIMERS ***\n * setTimeout call needs to keep the interaction active in case a node is started\n * in its callback.\n */\n\n // The context supplied to this callback will be shared with the fn-start/fn-end\n // callbacks that fire around the callback passed to setTimeout originally.\n register('setTimeout-end', function saveId(args, obj, timerId) {\n if (!state.currentNode || state.timerBudget - this.timerDuration < 0) return;\n if (args && !(args[0] instanceof Function)) return;\n state.currentNode[INTERACTION][REMAINING]++;\n this.timerId = timerId;\n state.timerMap[timerId] = state.currentNode;\n this.timerBudget = state.timerBudget - 50;\n }, this.featureName, timerEE);\n register('clearTimeout-start', function clear(args) {\n var timerId = args[0];\n var node = state.timerMap[timerId];\n if (node) {\n var interaction = node[INTERACTION];\n interaction[REMAINING]--;\n interaction.checkFinish();\n delete state.timerMap[timerId];\n }\n }, this.featureName, timerEE);\n register(FN_START, function () {\n state.timerBudget = this.timerBudget || MAX_TIMER_BUDGET;\n var id = this.timerId;\n var node = state.timerMap[id];\n setCurrentNode(node);\n delete state.timerMap[id];\n if (node) node[INTERACTION][REMAINING]--;\n }, this.featureName, timerEE);\n\n /**\n * *** XHR ***\n * - `new-xhr` event is fired when new instance of XHR is created. Here we create\n * a new node and store it on the XHR object.\n * - When the send method is called (`send-xhr-start` event), we tell the interaction\n * to wait for this XHR to complete.\n * - When any direct event handlers are invoked (`fn-start` on the `xhr` emitter),\n * we restore the node in case other child nodes are started here.\n * - Callbacks attached using `addEventListener` are handled using `fn-start` on the\n * `events` emitter.\n * - When `xhr-resolved` is emitted, we end the node. The node.finish() call also\n * instructs the interaction to stop waiting for this node.\n */\n\n // context is shared with new-xhr event, and is stored on the xhr iteself.\n register(FN_START, function () {\n setCurrentNode(this[SPA_NODE]);\n }, this.featureName, xhrEE);\n\n // context is stored on the xhr and is shared with all callbacks associated\n // with the new xhr\n register('new-xhr', function () {\n if (!state.disableSpaFix && !state.currentNode && state.prevInteraction && !state.prevInteraction.ignored) {\n /*\n * The previous interaction was discarded before a route change. Restore the interaction\n * in case this XHR is associated with a route change.\n */\n const interaction = state.prevInteraction;\n state.currentNode = interaction.root;\n interaction.root.end = null;\n }\n if (state.currentNode) {\n this[SPA_NODE] = state.currentNode.child('ajax', null, null, true);\n }\n }, this.featureName, xhrEE);\n register('send-xhr-start', function () {\n var node = this[SPA_NODE];\n if (node && !this.sent) {\n this.sent = true;\n node.dt = this.dt;\n if (node.dt?.timestamp) {\n node.dt.timestamp = agentRef.runtime.timeKeeper.correctAbsoluteTimestamp(node.dt.timestamp);\n }\n node.jsEnd = node.start = this.startTime;\n node[INTERACTION][REMAINING]++;\n }\n }, this.featureName, xhrEE);\n register('xhr-resolved', function () {\n var node = this[SPA_NODE];\n if (node) {\n if (!shouldCollectEvent(this.params)) {\n node.cancel();\n return;\n }\n var attrs = node.attrs;\n attrs.params = this.params;\n attrs.metrics = this.metrics;\n node.finish(this.endTime);\n if (!!this.currentNode && !!this.currentNode.interaction) this.currentNode.interaction.checkFinish();\n }\n }, this.featureName, baseEE);\n\n /**\n * *** JSONP ***\n *\n */\n\n register('new-jsonp', function (url) {\n if (state.currentNode) {\n var node = this[JSONP_NODE] = state.currentNode.child('ajax', this[FETCH_START]);\n node.start = this['new-jsonp'];\n this.url = url;\n this.status = null;\n }\n }, this.featureName, jsonpEE);\n register('cb-start', function (args) {\n var node = this[JSONP_NODE];\n if (node) {\n setCurrentNode(node);\n this.status = 200;\n }\n }, this.featureName, jsonpEE);\n register('jsonp-error', function () {\n var node = this[JSONP_NODE];\n if (node) {\n setCurrentNode(node);\n this.status = 0;\n }\n }, this.featureName, jsonpEE);\n register(JSONP_END, function () {\n var node = this[JSONP_NODE];\n if (node) {\n // if no status is set then cb never fired - so it's not a valid JSONP\n if (this.status === null) {\n node.cancel();\n return;\n }\n var attrs = node.attrs;\n var params = attrs.params = {};\n var parsed = parseUrl(this.url);\n params.method = 'GET';\n params.pathname = parsed.pathname;\n params.host = parsed.hostname + ':' + parsed.port;\n params.status = this.status;\n attrs.metrics = {\n txSize: 0,\n rxSize: 0\n };\n attrs.isJSONP = true;\n node.jsEnd = this[JSONP_END];\n node.jsTime = this[CB_START] ? this[JSONP_END] - this[CB_START] : 0;\n node.finish(node.jsEnd);\n }\n }, this.featureName, jsonpEE);\n register(FETCH_START, function (fetchArguments, dtPayload) {\n if (fetchArguments) {\n if (!state.disableSpaFix && !state.currentNode && state.prevInteraction && !state.prevInteraction.ignored) {\n /*\n * The previous interaction was discarded before a route change. Restore the interaction\n * in case this XHR is associated with a route change.\n */\n const interaction = state.prevInteraction;\n state.currentNode = interaction.root;\n interaction.root.end = null;\n }\n if (state.currentNode) {\n this[SPA_NODE] = state.currentNode.child('ajax', this[FETCH_START]);\n if (dtPayload && this[SPA_NODE]) {\n this[SPA_NODE].dt = dtPayload;\n if (this[SPA_NODE].dt?.timestamp) {\n this[SPA_NODE].dt.timestamp = agentRef.runtime.timeKeeper.correctAbsoluteTimestamp(this[SPA_NODE].dt.timestamp);\n }\n }\n }\n }\n }, this.featureName, fetchEE);\n register(FETCH_BODY + 'start', function (args) {\n if (state.currentNode) {\n this[SPA_NODE] = state.currentNode;\n state.currentNode[INTERACTION][REMAINING]++;\n }\n }, this.featureName, fetchEE);\n register(FETCH_BODY + 'end', function (args, ctx, bodyPromise) {\n var node = this[SPA_NODE];\n if (node) node[INTERACTION][REMAINING]--;\n }, this.featureName, fetchEE);\n register(FETCH_DONE, function (err, res) {\n var node = this[SPA_NODE];\n if (node) {\n if (err || !shouldCollectEvent(this.params)) {\n node.cancel();\n return;\n }\n var attrs = node.attrs;\n attrs.params = this.params;\n attrs.metrics = {\n txSize: this.txSize,\n rxSize: this.rxSize\n };\n attrs.isFetch = true;\n node.finish(this[FETCH_DONE]);\n }\n }, this.featureName, fetchEE);\n register('newURL', function (url, hashChangedDuringCb) {\n if (state.currentNode) {\n state.currentNode[INTERACTION].setNewURL(url);\n } else if (state.prevInteraction && !state.prevInteraction.ignored) {\n /*\n * The previous interaction was discarded before the route was changed. This can happen in SPA\n * frameworks when using lazy loading. We have also seen this in version 11+ of Nextjs where\n * some route changes re-use cached resolved promises.\n */\n const interaction = state.prevInteraction;\n interaction.setNewURL(url);\n interaction.root.end = null;\n setCurrentNode(interaction.root);\n }\n if (state.currentNode) {\n if (state.lastSeenUrl !== url) {\n state.currentNode[INTERACTION].routeChange = true;\n }\n if (hashChangedDuringCb) {\n state.nodeOnLastHashUpdate = state.currentNode;\n }\n }\n state.lastSeenUrl = url;\n }, this.featureName, historyEE);\n\n /**\n * SCRIPTS\n * This is only needed to keep the interaction open while external scripts are being loaded.\n * The script that is loaded could continue the interaction by making additional AJAX\n * calls or changing the URL. The interaction context (currentNode) needs to be\n * restored somehow, but this differs based on the specific customer code. In some cases, we\n * could wrap a JSONP callback, in other cases we could wrap a higher-level API, and in\n * some cases we may not be able to restore context automatically (customer would need\n * to instrument their code manually).\n *\n * - We do not restore the original context in the load/error callbacks. This would not\n * work for the scripts themselves because by the time the load event fires, the\n * script content has already been executed.\n */\n\n // dom-start is emitted when appendChild or replaceChild are called. If the element being\n // inserted is script and we are inside an interaction, we will keep the interaction open\n // until the script is loaded.\n jsonpEE.on('dom-start', function (args) {\n if (!state.currentNode) return;\n var el = args[0];\n var isScript = el && el.nodeName === 'SCRIPT' && el.src !== '';\n var interaction = state.currentNode.interaction;\n if (isScript) {\n // increase remaining count to keep the interaction open\n interaction[REMAINING]++;\n el.addEventListener('load', onload, eventListenerOpts(false));\n el.addEventListener('error', onerror, eventListenerOpts(false));\n }\n function onload() {\n // decrease remaining to allow interaction to finish\n interaction[REMAINING]--;\n\n // checkFinish is what initiates closing interaction, but is only called\n // when setCurrentNode is called. Since we are not restoring a node here,\n // we need to initiate the check manually.\n // The reason we are not restoring the node here is because 1) this is not\n // where the code of the external script runs (by the time the load event\n // fires, it has already executed), and 2) it would require storing the context\n // probably on the DOM node and restoring in all callbacks, which is a different\n // use case than lazy loading.\n interaction.checkFinish();\n }\n function onerror() {\n interaction[REMAINING]--;\n interaction.checkFinish();\n }\n });\n register(FN_START, function () {\n setCurrentNode(state.prevNode);\n }, this.featureName, mutationEE);\n register('resolve-start', resolvePromise, this.featureName, promiseEE);\n register('executor-err', resolvePromise, this.featureName, promiseEE);\n register('propagate', saveNode, this.featureName, promiseEE);\n register(CB_START, function () {\n var ctx = this.getCtx ? this.getCtx() : this;\n setCurrentNode(ctx[SPA_NODE]);\n }, this.featureName, promiseEE);\n register(INTERACTION_API + 'get', function (t) {\n var interaction;\n if (state?.currentNode?.[INTERACTION]) interaction = this.ixn = state.currentNode[INTERACTION];else if (state?.prevNode?.end === null && state?.prevNode?.[INTERACTION]?.root?.[INTERACTION]?.eventName !== 'initialPageLoad') interaction = this.ixn = state.prevNode[INTERACTION];else interaction = this.ixn = new Interaction('api', t, state.lastSeenUrl, state.lastSeenRouteName, onInteractionFinished, agentRef.agentIdentifier);\n if (!state.currentNode) {\n interaction.checkFinish();\n if (state.depth) setCurrentNode(interaction.root);\n }\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'actionText', function (t, actionText) {\n var customAttrs = this.ixn.root.attrs.custom;\n if (actionText) customAttrs.actionText = actionText;\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'setName', function (t, name, trigger) {\n var attrs = this.ixn.root.attrs;\n if (name) attrs.customName = name;\n if (trigger) attrs.trigger = trigger;\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'setAttribute', function (t, name, value) {\n this.ixn.root.attrs.custom[name] = value;\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'end', function (timestamp) {\n var interaction = this.ixn;\n var node = activeNodeFor(interaction);\n setCurrentNode(null);\n node.child('customEnd', timestamp)?.finish(timestamp);\n interaction.finish();\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'ignore', function (t) {\n this.ixn.ignored = true;\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'save', function (t) {\n this.ixn.save = true;\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'tracer', function (timestamp, name, store) {\n var interaction = this.ixn;\n var parent = activeNodeFor(interaction);\n var ctx = baseEE.context(store);\n if (!name) {\n ctx.inc = ++interaction[REMAINING];\n return ctx[SPA_NODE] = parent;\n }\n ctx[SPA_NODE] = parent.child('customTracer', timestamp, name);\n }, this.featureName, baseEE);\n register(FN_START, tracerDone, this.featureName, tracerEE);\n register('no-' + FN_START, tracerDone, this.featureName, tracerEE);\n function tracerDone(timestamp, interactionContext, hasCb) {\n var node = this[SPA_NODE];\n if (!node) return;\n var interaction = node[INTERACTION];\n var inc = this.inc;\n this.isTraced = true;\n if (inc) {\n interaction[REMAINING]--;\n } else if (node) {\n node.finish(timestamp);\n }\n hasCb ? setCurrentNode(node) : interaction.checkFinish();\n }\n register(INTERACTION_API + 'getContext', function (t, cb) {\n var store = this.ixn.root.attrs.store;\n setTimeout(function () {\n cb(store);\n }, 0);\n }, this.featureName, baseEE);\n register(INTERACTION_API + 'onEnd', function (t, cb) {\n this.ixn.handlers.push(cb);\n }, this.featureName, baseEE);\n register('api-routeName', function (t, currentRouteName) {\n state.lastSeenRouteName = currentRouteName;\n if (state.currentNode) state.currentNode[INTERACTION].setNewRoute(currentRouteName);\n }, this.featureName, baseEE);\n function activeNodeFor(interaction) {\n return state.currentNode && state.currentNode[INTERACTION] === interaction ? state.currentNode : interaction.root;\n }\n function saveNode(val, overwrite) {\n if (overwrite || !this[SPA_NODE]) this[SPA_NODE] = state.currentNode;\n }\n function resolvePromise() {\n if (!this.resolved) {\n this.resolved = true;\n this[SPA_NODE] = state.currentNode;\n }\n }\n function getCurrentNode() {\n return state.currentNode;\n }\n function setCurrentNode(newNode) {\n if (!state.pageLoaded && !newNode && state.initialPageLoad) newNode = state.initialPageLoad.root;\n if (state.currentNode) {\n state.currentNode[INTERACTION].checkFinish();\n }\n state.prevNode = state.currentNode;\n state.currentNode = newNode && !newNode[INTERACTION].root.end ? newNode : null;\n }\n function onInteractionFinished(interaction) {\n if (interaction === state.initialPageLoad) state.initialPageLoad = null;\n var root = interaction.root;\n var attrs = root.attrs;\n\n // make sure that newrelic[INTERACTION]() works in end handler\n state.currentNode = root;\n Object.values(interaction.handlers || {}).forEach(function (cb) {\n cb(attrs.store);\n });\n setCurrentNode(null);\n }\n baseEE.on('spa-jserror', function (type, name, params, metrics) {\n if (!state.currentNode) return;\n params._interactionId = state.currentNode.interaction.id;\n // do not capture parentNodeId when in root node\n if (state.currentNode.type && state.currentNode.type !== 'interaction') {\n params._interactionNodeId = state.currentNode.id;\n }\n });\n register('function-err', function (args, obj, error) {\n if (!state.currentNode) return;\n error.__newrelic ??= {};\n error.__newrelic[agentRef.agentIdentifier] = {\n interactionId: state.currentNode.interaction.id\n };\n if (state.currentNode.type && state.currentNode.type !== 'interaction') {\n error.__newrelic[agentRef.agentIdentifier].interactionNodeId = state.currentNode.id;\n }\n }, this.featureName, baseEE);\n baseEE.on('interaction', saveInteraction);\n function getActionText(node) {\n var nodeType = node.tagName.toLowerCase();\n var goodNodeTypes = ['a', 'button', 'input'];\n var isGoodNode = goodNodeTypes.indexOf(nodeType) !== -1;\n if (isGoodNode) {\n return node.title || node.value || node.innerText;\n }\n }\n function saveInteraction(interaction) {\n if (interaction.ignored || !interaction.save && !interaction.routeChange) {\n baseEE.emit('interactionDone', [interaction, false]);\n return;\n }\n if (state.prevInteraction === interaction) {\n // If the interaction is being saved, remove it from prevInteraction variable\n // to prevent the interaction from possibly being sent twice or causing an internal\n // recursive loop issue.\n state.prevInteraction = null;\n }\n\n // assign unique id, this is serialized and used to link interactions with errors\n interaction.root.attrs.id = generateUuid();\n if (interaction.root.attrs.trigger === 'initialPageLoad') {\n interaction.root.attrs.firstPaint = firstPaint.current.value;\n interaction.root.attrs.firstContentfulPaint = firstContentfulPaint.current.value;\n }\n baseEE.emit('interactionDone', [interaction, true]);\n classThis.events.add(interaction);\n let smCategory;\n if (interaction.root?.attrs?.trigger === 'initialPageLoad') smCategory = 'InitialPageLoad';else if (interaction.routeChange) smCategory = 'RouteChange';else smCategory = 'Custom';\n handle(SUPPORTABILITY_METRIC_CHANNEL, [\"Spa/Interaction/\".concat(smCategory, \"/Duration/Ms\"), Math.max((interaction.root?.end || 0) - (interaction.root?.start || 0), 0)], undefined, FEATURE_NAMES.metrics, baseEE);\n scheduler?.scheduleHarvest(0);\n if (!scheduler) warn(19);\n }\n }\n serializer(eventBuffer) {\n return this.spaSerializerClass.serializeMultiple(eventBuffer, 0, navTiming);\n }\n}","import { gosNREUMOriginals } from '../../common/window/nreum';\nimport { FEATURE_NAMES } from '../../loaders/features/features';\nexport const FEATURE_NAME = FEATURE_NAMES.spa;\nexport const INTERACTION_EVENTS = ['click', 'submit', 'keypress', 'keydown', 'keyup', 'change'];\nexport const MAX_TIMER_BUDGET = 999;\nexport const FN_START = 'fn-start';\nexport const FN_END = 'fn-end';\nexport const CB_START = 'cb-start';\nexport const INTERACTION_API = 'api-ixn-';\nexport const REMAINING = 'remaining';\nexport const INTERACTION = 'interaction';\nexport const SPA_NODE = 'spaNode';\nexport const JSONP_NODE = 'jsonpNode';\nexport const FETCH_START = 'fetch-start';\nexport const FETCH_DONE = 'fetch-done';\nexport const FETCH_BODY = 'fetch-body-';\nexport const JSONP_END = 'jsonp-end';\nexport const originalSetTimeout = gosNREUMOriginals().o.ST;\nexport const START = '-start';\nexport const END = '-end';\nexport const BODY = '-body';\nexport const CB_END = 'cb' + END;\nexport const JS_TIME = 'jsTime';\nexport const FETCH = 'fetch';","export class Timer {\n constructor(opts, ms) {\n if (!opts.onEnd) throw new Error('onEnd handler is required');\n if (!ms) throw new Error('ms duration is required');\n this.onEnd = opts.onEnd;\n this.initialMs = ms;\n this.startTimestamp = Date.now();\n this.timer = this.create(this.onEnd, ms);\n }\n create(cb, ms) {\n if (this.timer) this.clear();\n return setTimeout(() => cb ? cb() : this.onEnd(), ms || this.initialMs);\n }\n clear() {\n clearTimeout(this.timer);\n this.timer = null;\n }\n end() {\n this.clear();\n this.onEnd();\n }\n isValid() {\n return this.initialMs - (Date.now() - this.startTimestamp) > 0;\n }\n}","import { Timer } from './timer';\nimport { subscribeToVisibilityChange } from '../window/page-visibility';\nimport { debounce } from '../util/invoke';\nimport { isBrowserScope } from '../constants/runtime';\nexport class InteractionTimer extends Timer {\n constructor(opts, ms) {\n super(opts, ms);\n this.onPause = typeof opts.onPause === 'function' ? opts.onPause : () => {/* noop */};\n this.onRefresh = typeof opts.onRefresh === 'function' ? opts.onRefresh : () => {/* noop */};\n this.onResume = typeof opts.onResume === 'function' ? opts.onResume : () => {/* noop */};\n\n /** used to double-check LS state at resume time */\n this.readStorage = opts.readStorage;\n\n // used by pause/resume\n this.remainingMs = undefined;\n if (!opts.refreshEvents) opts.refreshEvents = ['click', 'keydown', 'scroll'];\n\n // the abort controller is used to \"reset\" the event listeners and prevent them from duplicating when new sessions are created\n try {\n this.abortController = new AbortController();\n } catch (e) {\n // this try-catch can be removed when IE11 is completely unsupported & gone\n }\n if (isBrowserScope && opts.ee) {\n if (opts.ee) {\n this.ee = opts.ee;\n const debouncedRefresh = debounce(this.refresh.bind(this), 500, {\n leading: true\n });\n this.refreshHandler = evts => {\n if (opts.refreshEvents.includes(evts?.[0]?.type)) {\n debouncedRefresh();\n }\n };\n opts.ee.on('fn-end', this.refreshHandler);\n }\n\n // watch for the vis state changing. If the page is hidden, the local inactivity timer should be paused\n // if the page is brought BACK to visibility and the timer hasnt \"naturally\" expired, refresh the timer...\n // this is to support the concept that other tabs could be experiencing activity. The thought would be that\n // \"backgrounded\" tabs would pause, while \"closed\" tabs that \"reopen\" will just instantiate a new SessionEntity class if restored\n // which will do a \"hard\" check of the timestamps.\n\n // NOTE -- this does not account for 2 browser windows open side by side, blurring/focusing between them\n // IF DEEMED necessary, more event handling would be needed to account for this.\n subscribeToVisibilityChange(state => {\n if (state === 'hidden') this.pause();\n // vis change --> visible is treated like a new interaction with the page\n else this.resume();\n }, false, false, this.abortController?.signal);\n }\n }\n abort() {\n this.clear();\n this.abortController?.abort();\n if (this.refreshHandler) {\n this.ee.removeEventListener('fn-end', this.refreshHandler);\n this.refreshHandler = this.ee = null;\n }\n }\n pause() {\n this.onPause();\n clearTimeout(this.timer);\n this.remainingMs = this.initialMs - (Date.now() - this.startTimestamp);\n }\n resume() {\n try {\n const lsData = this.readStorage();\n const obj = typeof lsData === 'string' ? JSON.parse(lsData) : lsData;\n if (isExpired(obj.expiresAt) || isExpired(obj.inactiveAt)) this.end();else {\n this.refresh();\n this.onResume(); // emit resume event after state updated\n }\n } catch (err) {\n this.end();\n }\n function isExpired(timestamp) {\n return Date.now() > timestamp;\n }\n }\n refresh(cb, ms) {\n this.clear();\n this.timer = this.create(cb, ms);\n this.startTimestamp = Date.now();\n this.remainingMs = undefined;\n this.onRefresh();\n }\n}","import { generateRandomHexString } from '../ids/unique-id';\nimport { warn } from '../util/console';\nimport { stringify } from '../util/stringify';\nimport { ee } from '../event-emitter/contextual-ee';\nimport { Timer } from '../timer/timer';\nimport { isBrowserScope } from '../constants/runtime';\nimport { DEFAULT_EXPIRES_MS, DEFAULT_INACTIVE_MS, MODE, PREFIX, SESSION_EVENTS, SESSION_EVENT_TYPES } from './constants';\nimport { InteractionTimer } from '../timer/interaction-timer';\nimport { wrapEvents } from '../wrap/wrap-events';\nimport { getModeledObject } from '../config/configurable';\nimport { handle } from '../event-emitter/handle';\nimport { SUPPORTABILITY_METRIC_CHANNEL } from '../../features/metrics/constants';\nimport { FEATURE_NAMES } from '../../loaders/features/features';\nimport { windowAddEventListener } from '../event-listener/event-listener-opts';\n\n// this is what can be stored in local storage (not enforced but probably should be)\n// these values should sync between local storage and the parent class props\nconst model = {\n value: '',\n inactiveAt: 0,\n expiresAt: 0,\n updatedAt: Date.now(),\n sessionReplayMode: MODE.OFF,\n sessionReplaySentFirstChunk: false,\n sessionTraceMode: MODE.OFF,\n traceHarvestStarted: false,\n serverTimeDiff: null,\n // set by TimeKeeper; \"undefined\" value will not be stringified and stored but \"null\" will\n custom: {}\n};\nexport class SessionEntity {\n /**\n * Create a self-managing Session Entity. This entity is scoped to the agent identifier which triggered it, allowing for multiple simultaneous session objects to exist.\n * There is one \"namespace\" an agent can store data in LS -- NRBA_{key}. If there are two agents on one page, and they both use the same key, they could overwrite each other since they would both use the same namespace in LS by default.\n * The value can be overridden in the constructor, but will default to a unique 16 character hex string\n * expiresMs and inactiveMs are used to \"expire\" the session, but can be overridden in the constructor. Pass 0 to disable expiration timers.\n */\n constructor(opts) {\n const {\n agentIdentifier,\n key,\n storage\n } = opts;\n if (!agentIdentifier || !key || !storage) {\n throw new Error(\"Missing required field(s):\".concat(!agentIdentifier ? ' agentID' : '').concat(!key ? ' key' : '').concat(!storage ? ' storage' : ''));\n }\n this.agentIdentifier = agentIdentifier;\n this.storage = storage;\n this.state = {};\n\n // key is intended to act as the k=v pair\n this.key = key;\n this.ee = ee.get(agentIdentifier);\n wrapEvents(this.ee);\n this.setup(opts);\n\n /**\n * Do not emit session storage events for IE11, because IE11 is unable to determine\n * if the event was spawned on the current page or an adjacent page, and the behavior tied\n * to storage events is critical to apply only to cross-tab behavior\n * */\n if (isBrowserScope) {\n windowAddEventListener('storage', event => {\n if (event.key === this.lookupKey) {\n const obj = typeof event.newValue === 'string' ? JSON.parse(event.newValue) : event.newValue;\n this.sync(obj);\n this.ee.emit(SESSION_EVENTS.UPDATE, [SESSION_EVENT_TYPES.CROSS_TAB, this.state]);\n }\n });\n }\n }\n setup({\n value = generateRandomHexString(16),\n expiresMs = DEFAULT_EXPIRES_MS,\n inactiveMs = DEFAULT_INACTIVE_MS\n }) {\n /** Ensure that certain properties are preserved across a reset if already set */\n const persistentAttributes = {\n serverTimeDiff: this.state.serverTimeDiff || model.serverTimeDiff\n };\n this.state = {};\n this.sync({\n ...model,\n ...persistentAttributes\n });\n\n // value is intended to act as the primary value of the k=v pair\n this.state.value = value;\n this.expiresMs = expiresMs;\n this.inactiveMs = inactiveMs;\n\n // the first time the session entity class is instantiated, we check the storage API for an existing\n // object. If it exists, the values inside the object are used to inform the timers that run locally.\n // if the initial read is empty, it allows us to set a \"fresh\" \"new\" session immediately.\n // the local timers are used after the session is running to \"expire\" the session, allowing for pausing timers etc.\n // the timestamps stored in the storage API can be checked at initial run, and when the page is restored, otherwise we lean\n // on the local timers to expire the session\n const initialRead = this.read();\n\n // the set-up of the timer used to expire the session \"naturally\" at a certain time\n // this gets ignored if the value is falsy, allowing for session entities that do not expire\n if (expiresMs) {\n this.state.expiresAt = initialRead?.expiresAt || this.getFutureTimestamp(expiresMs);\n this.expiresTimer = new Timer({\n // When the inactive timer ends, collect a SM and reset the session\n onEnd: () => {\n this.collectSM('expired');\n this.collectSM('duration');\n this.reset();\n }\n }, this.state.expiresAt - Date.now());\n } else {\n this.state.expiresAt = Infinity;\n }\n\n // the set-up of the timer used to expire the session due to \"inactivity\" at a certain time\n // this gets ignored if the value is falsy, allowing for session entities that do not expire\n // this gets \"refreshed\" when \"activity\" is observed\n if (inactiveMs) {\n this.state.inactiveAt = initialRead?.inactiveAt || this.getFutureTimestamp(inactiveMs);\n this.inactiveTimer = new InteractionTimer({\n // When the inactive timer ends, collect a SM and reset the session\n onEnd: () => {\n this.collectSM('inactive');\n this.collectSM('duration');\n this.reset();\n },\n // When the inactive timer refreshes, it will update the storage values with an update timestamp\n onRefresh: this.refresh.bind(this),\n onResume: () => {\n this.ee.emit(SESSION_EVENTS.RESUME);\n },\n // When the inactive timer pauses, update the storage values with an update timestamp\n onPause: () => {\n if (this.initialized) this.ee.emit(SESSION_EVENTS.PAUSE);\n this.write(getModeledObject(this.state, model));\n },\n ee: this.ee,\n refreshEvents: ['click', 'keydown', 'scroll'],\n readStorage: () => this.storage.get(this.lookupKey)\n }, this.state.inactiveAt - Date.now());\n } else {\n this.state.inactiveAt = Infinity;\n }\n\n // The fact that the session is \"new\" or pre-existing is used in some places in the agent. Session Replay and Trace\n // can use this info to inform whether to trust a new sampling decision vs continue a previous tracking effort.\n /* [NR-230914] 02/2024 - the logical OR assignment is used so that isNew remains 'true' if it was already set as such. This fixes the expires and inactive timestamps timing out in localStorage\n while no page for a given domain is in-use and the session resetting upon user returning to the page as part of a fresh session. */\n this.isNew ||= !Object.keys(initialRead).length;\n // if its a \"new\" session, we write to storage API with the default values. These values may change over the lifespan of the agent run.\n // we can use a modeled object here to help us know and manage what values are being used. -- see \"model\" above\n if (this.isNew) this.write(getModeledObject(this.state, model), true);else this.sync(initialRead);\n this.initialized = true;\n this.ee.emit(SESSION_EVENTS.STARTED, [this.isNew]);\n }\n\n // This is the actual key appended to the storage API\n get lookupKey() {\n return \"\".concat(PREFIX, \"_\").concat(this.key);\n }\n sync(data) {\n Object.assign(this.state, data);\n }\n\n /**\n * Fetch the stored values from the storage API tied to this entity\n * @returns {Object}\n */\n read() {\n try {\n const val = this.storage.get(this.lookupKey);\n if (!val) return {};\n // TODO - decompression would need to happen here if we decide to do it\n const obj = typeof val === 'string' ? JSON.parse(val) : val;\n if (this.isInvalid(obj)) return {};\n // if the session expires, collect a SM count before resetting\n if (this.isExpired(obj.expiresAt)) {\n this.collectSM('expired');\n this.collectSM('duration', obj, true);\n return this.reset();\n }\n // if \"inactive\" timer is expired at \"read\" time -- esp. initial read -- reset\n // collect a SM count before resetting\n if (this.isExpired(obj.inactiveAt)) {\n this.collectSM('inactive');\n this.collectSM('duration', obj, true);\n return this.reset();\n }\n return obj;\n } catch (e) {\n warn(10, e);\n // storage is inaccessible\n return {};\n }\n }\n\n /**\n * Store data to the storage API tied to this entity\n * To preseve existing attributes, the output of ...session.read()\n * should be appended to the data argument\n * @param {Object} data\n * @returns {Object}\n */\n write(data) {\n try {\n if (!data || typeof data !== 'object') return;\n // everytime we update, we can update a timestamp for sanity\n data.updatedAt = Date.now();\n this.sync(data); // update the parent class \"state\" properties with the local storage values\n //\n // TODO - compression would need happen here if we decide to do it\n this.storage.set(this.lookupKey, stringify(this.state));\n this.ee.emit(SESSION_EVENTS.UPDATE, [SESSION_EVENT_TYPES.SAME_TAB, this.state]);\n return data;\n } catch (e) {\n // storage is inaccessible\n warn(11, e);\n return null;\n }\n }\n reset() {\n // this method should set off a chain of actions across the features by emitting 'new-session'\n // * send off pending payloads\n // * stop recording (stn and sr)...\n // * delete the session and start over\n try {\n if (this.initialized) this.ee.emit(SESSION_EVENTS.RESET);\n this.storage.remove(this.lookupKey);\n this.inactiveTimer?.abort?.();\n this.expiresTimer?.clear?.();\n delete this.isNew;\n this.setup({\n agentIdentifier: this.agentIdentifier,\n key: this.key,\n storage: this.storage,\n expiresMs: this.expiresMs,\n inactiveMs: this.inactiveMs\n });\n return this.read();\n } catch (e) {\n return {};\n }\n }\n\n /**\n * Refresh the inactivity timer data\n */\n refresh() {\n // read here & invalidate\n const existingData = this.read();\n this.write({\n ...existingData,\n inactiveAt: this.getFutureTimestamp(this.inactiveMs)\n });\n }\n\n /**\n * @param {number} timestamp\n * @returns {boolean}\n */\n isExpired(timestamp) {\n return Date.now() > timestamp;\n }\n\n /**\n * @param {Object} data\n * @returns {boolean}\n */\n isInvalid(data) {\n const requiredKeys = Object.keys(model);\n return !requiredKeys.every(x => Object.keys(data).includes(x));\n }\n collectSM(type, data, useUpdatedAt) {\n let value, tag;\n if (type === 'duration') {\n value = this.getDuration(data, useUpdatedAt);\n tag = 'Session/Duration/Ms';\n }\n if (type === 'expired') tag = 'Session/Expired/Seen';\n if (type === 'inactive') tag = 'Session/Inactive/Seen';\n if (tag) handle(SUPPORTABILITY_METRIC_CHANNEL, [tag, value], undefined, FEATURE_NAMES.metrics, this.ee);\n }\n getDuration(data = this.state, useUpdatedAt) {\n const startingTimestamp = data.expiresAt - this.expiresMs;\n const endingTimestamp = !useUpdatedAt ? data.updatedAt : Date.now();\n return endingTimestamp - startingTimestamp;\n }\n\n /**\n * @param {number} futureMs - The number of ms to use to generate a future timestamp\n * @returns {number}\n */\n getFutureTimestamp(futureMs) {\n return Date.now() + futureMs;\n }\n syncCustomAttribute(key, value) {\n if (!isBrowserScope) return;\n if (value === null) {\n const curr = this.read();\n if (curr.custom) {\n delete curr.custom[key];\n this.write({\n ...curr\n });\n }\n } else {\n const curr = this.read();\n this.custom = {\n ...(curr?.custom || {}),\n [key]: value\n };\n this.write({\n ...curr,\n custom: this.custom\n });\n }\n }\n}","export class LocalStorage {\n get(key) {\n try {\n // localStorage strangely type-casts non-existing data to \"null\"...\n // Cast it back to undefined if it doesnt exist\n return localStorage.getItem(key) || undefined;\n } catch (err) {\n // Error is ignored\n return '';\n }\n }\n set(key, value) {\n try {\n if (value === undefined || value === null) return this.remove(key);\n return localStorage.setItem(key, value);\n } catch (err) {\n // Error is ignored\n }\n }\n remove(key) {\n try {\n localStorage.removeItem(key);\n } catch (err) {\n // Error is ignored\n }\n }\n}","import { drain } from '../../common/drain/drain';\nimport { ee } from '../../common/event-emitter/contextual-ee';\nimport { registerHandler } from '../../common/event-emitter/register-handler';\nimport { SessionEntity } from '../../common/session/session-entity';\nimport { LocalStorage } from '../../common/storage/local-storage.js';\nimport { DEFAULT_KEY } from '../../common/session/constants';\nexport function setupAgentSession(agentRef) {\n if (agentRef.runtime.session) return agentRef.runtime.session; // already setup\n\n const sessionInit = agentRef.init.session;\n agentRef.runtime.session = new SessionEntity({\n agentIdentifier: agentRef.agentIdentifier,\n key: DEFAULT_KEY,\n storage: new LocalStorage(),\n expiresMs: sessionInit?.expiresMs,\n inactiveMs: sessionInit?.inactiveMs\n });\n\n // Retrieve & re-add all of the persisted setCustomAttribute|setUserId k-v from previous page load(s), if any was stored.\n const customSessionData = agentRef.runtime.session.state.custom;\n if (customSessionData) {\n agentRef.info.jsAttributes = {\n ...agentRef.info.jsAttributes,\n ...customSessionData\n };\n }\n const sharedEE = ee.get(agentRef.agentIdentifier);\n\n // any calls to newrelic.setCustomAttribute() will need to be added to:\n // local info.jsAttributes {}\n // the session's storage API\n registerHandler('api-setCustomAttribute', (time, key, value) => {\n agentRef.runtime.session.syncCustomAttribute(key, value);\n }, 'session', sharedEE);\n\n // any calls to newrelic.setUserId(...) will need to be added to:\n // local info.jsAttributes {}\n // the session's storage API\n registerHandler('api-setUserId', (time, key, value) => {\n agentRef.runtime.session.syncCustomAttribute(key, value);\n }, 'session', sharedEE);\n drain(agentRef.agentIdentifier, 'session');\n return agentRef.runtime.session;\n}","import { getConfigurationValue } from '../config/init';\nimport { isFileProtocol } from '../url/protocol';\nimport { warn } from './console';\n\n/**\n * Represents an obfuscation rule that can be applied to harvested payloads\n * @typedef {object} ObfuscationRule\n * @property {string|RegExp} regex The regular expression to match against in the payload\n * @property {string} [replacement] The string to replace the matched regex with\n */\n\n/**\n * Represents an obfuscation rule validation state\n * @typedef {object} ObfuscationRuleValidation\n * @property {ObfuscationRule} rule The original rule validated\n * @property {boolean} isValid Whether the rule is valid\n * @property {object} errors Validation errors\n * @property {boolean} errors.regexMissingDetected Whether the regex is missing\n * @property {boolean} errors.invalidRegexDetected Whether the regex is invalid\n * @property {boolean} errors.invalidReplacementDetected Whether the replacement is invalid\n */\n\nexport class Obfuscator {\n /**\n * @type {ObfuscationRuleValidation[]}\n */\n #ruleValidationCache;\n constructor(agentIdentifier) {\n this.#ruleValidationCache = Obfuscator.getRuleValidationCache(agentIdentifier);\n Obfuscator.logObfuscationRuleErrors(this.#ruleValidationCache);\n }\n get ruleValidationCache() {\n return this.#ruleValidationCache;\n }\n\n /**\n * Applies all valid obfuscation rules to the provided input string\n * @param {string} input String to obfuscate\n * @returns {string}\n */\n obfuscateString(input) {\n // if input is not of type string or is an empty string, short-circuit\n if (typeof input !== 'string' || input.trim().length === 0) return input;\n return this.#ruleValidationCache.filter(ruleValidation => ruleValidation.isValid).reduce((input, ruleValidation) => {\n const {\n rule\n } = ruleValidation;\n return input.replace(rule.regex, rule.replacement || '*');\n }, input);\n }\n\n /**\n * Returns an array of obfuscation rules to be applied to harvested payloads\n * @param {string} agentIdentifier The agent identifier to get rules for\n * @returns {ObfuscationRuleValidation[]} The array of rules or validation states\n */\n static getRuleValidationCache(agentIdentifier) {\n /**\n * @type {ObfuscationRule[]}\n */\n let rules = getConfigurationValue(agentIdentifier, 'obfuscate') || [];\n if (isFileProtocol()) {\n rules.push({\n regex: /^file:\\/\\/(.*)/,\n replacement: atob('ZmlsZTovL09CRlVTQ0FURUQ=')\n });\n }\n return rules.map(rule => Obfuscator.validateObfuscationRule(rule));\n }\n\n /**\n * Validates an obfuscation rule and provides errors if any are found.\n * @param {ObfuscationRule} rule The rule to validate\n * @returns {ObfuscationRuleValidation} The validation state of the rule\n */\n static validateObfuscationRule(rule) {\n const regexMissingDetected = Boolean(rule.regex === undefined);\n const invalidRegexDetected = Boolean(rule.regex !== undefined && typeof rule.regex !== 'string' && !(rule.regex instanceof RegExp));\n const invalidReplacementDetected = Boolean(rule.replacement && typeof rule.replacement !== 'string');\n return {\n rule,\n isValid: !regexMissingDetected && !invalidRegexDetected && !invalidReplacementDetected,\n errors: {\n regexMissingDetected,\n invalidRegexDetected,\n invalidReplacementDetected\n }\n };\n }\n\n /**\n * Logs any obfuscation rule errors to the console. This is called when an obfuscator\n * instance is created.\n * @param {ObfuscationRuleValidation[]} ruleValidationCache The cache of rule validation states\n */\n static logObfuscationRuleErrors(ruleValidationCache) {\n for (const ruleValidation of ruleValidationCache) {\n const {\n rule,\n isValid,\n errors\n } = ruleValidation;\n if (isValid) continue;\n if (errors.regexMissingDetected) warn(12, rule);else if (errors.invalidRegexDetected) warn(13, rule);\n if (errors.invalidReplacementDetected) warn(14, rule);\n }\n }\n}","import { FeatureBase } from './feature-base';\nimport { isValid } from '../../common/config/info';\nimport { configure } from '../../loaders/configure/configure';\nimport { gosCDN } from '../../common/window/nreum';\nimport { drain } from '../../common/drain/drain';\nimport { activatedFeatures } from '../../common/util/feature-flags';\nimport { Obfuscator } from '../../common/util/obfuscate';\nimport { EventBuffer } from './event-buffer';\nimport { FEATURE_NAMES } from '../../loaders/features/features';\nexport class AggregateBase extends FeatureBase {\n constructor(agentRef, featureName) {\n super(agentRef.agentIdentifier, featureName);\n this.agentRef = agentRef;\n // Jserror and Metric features uses a singleton EventAggregator instead of a regular EventBuffer.\n if ([FEATURE_NAMES.jserrors, FEATURE_NAMES.metrics].includes(this.featureName)) this.events = agentRef.sharedAggregator;\n // PVE has no need for eventBuffer, and SessionTrace has its own storage mechanism.\n else if (![FEATURE_NAMES.pageViewEvent, FEATURE_NAMES.sessionTrace].includes(this.featureName)) this.events = new EventBuffer();\n this.checkConfiguration(agentRef);\n this.obfuscator = agentRef.runtime.obfuscator;\n }\n\n /**\n * New handler for waiting for multiple flags. Useful when expecting multiple flags simultaneously (ex. stn vs sr)\n * @param {string[]} flagNames\n * @returns {Promise}\n */\n waitForFlags(flagNames = []) {\n const flagsPromise = new Promise((resolve, reject) => {\n if (activatedFeatures[this.agentIdentifier]) {\n resolve(buildOutput(activatedFeatures[this.agentIdentifier]));\n } else {\n this.ee.on('rumresp', (resp = {}) => {\n resolve(buildOutput(resp));\n });\n }\n function buildOutput(ref) {\n return flagNames.map(flag => {\n if (!ref[flag]) return 0;\n return ref[flag];\n });\n }\n });\n return flagsPromise.catch(err => {\n this.ee.emit('internal-error', [err]);\n this.blocked = true;\n this.deregisterDrain();\n });\n }\n drain() {\n drain(this.agentIdentifier, this.featureName);\n this.drained = true;\n }\n\n /**\n * Return harvest payload. A \"serializer\" function can be defined on a derived class to format the payload.\n * @param {Boolean} shouldRetryOnFail - harvester flag to backup payload for retry later if harvest request fails; this should be moved to harvester logic\n * @returns final payload, or undefined if there are no pending events\n */\n makeHarvestPayload(shouldRetryOnFail = false, opts = {}) {\n if (this.events.isEmpty(opts)) return;\n // Other conditions and things to do when preparing harvest that is required.\n if (this.preHarvestChecks && !this.preHarvestChecks()) return;\n if (shouldRetryOnFail) this.events.save(opts);\n const returnedData = this.events.get(opts);\n // A serializer or formatter assists in creating the payload `body` from stored events on harvest when defined by derived feature class.\n const body = this.serializer ? this.serializer(returnedData) : returnedData;\n this.events.clear(opts);\n const payload = {\n body\n };\n // Constructs the payload `qs` for relevant features on harvest.\n if (this.queryStringsBuilder) payload.qs = this.queryStringsBuilder(returnedData);\n return payload;\n }\n\n /**\n * Cleanup task after a harvest.\n * @param {Boolean} harvestFailed - harvester flag to restore events in main buffer for retry later if request failed\n */\n postHarvestCleanup(harvestFailed = false, opts = {}) {\n if (harvestFailed) this.events.reloadSave(opts);\n this.events.clearSave(opts);\n }\n\n /**\n * Checks for additional `jsAttributes` items to support backward compatibility with implementations of the agent where\n * loader configurations may appear after the loader code is executed.\n */\n checkConfiguration(existingAgent) {\n // NOTE: This check has to happen at aggregator load time\n if (!isValid(this.agentIdentifier)) {\n const cdn = gosCDN();\n let jsAttributes = {\n ...cdn.info?.jsAttributes\n };\n try {\n jsAttributes = {\n ...jsAttributes,\n ...existingAgent.info?.jsAttributes\n };\n } catch (err) {\n // do nothing\n }\n configure({\n agentIdentifier: this.agentIdentifier\n }, {\n ...cdn,\n info: {\n ...cdn.info,\n jsAttributes\n },\n runtime: existingAgent.runtime\n });\n }\n if (!existingAgent.runtime.obfuscator) {\n existingAgent.runtime.obfuscator = new Obfuscator(this.agentIdentifier);\n }\n }\n}","import { stringify } from '../../common/util/stringify';\nimport { MAX_PAYLOAD_SIZE } from '../../common/constants/agent-constants';\nexport class EventBuffer {\n #buffer = [];\n #rawBytes = 0;\n #bufferBackup;\n #rawBytesBackup;\n\n /**\n * @param {number} maxPayloadSize\n */\n constructor(maxPayloadSize = MAX_PAYLOAD_SIZE) {\n this.maxPayloadSize = maxPayloadSize;\n }\n isEmpty() {\n return this.#buffer.length === 0;\n }\n get() {\n return this.#buffer;\n }\n byteSize() {\n return this.#rawBytes;\n }\n wouldExceedMaxSize(incomingSize) {\n return this.#rawBytes + incomingSize > this.maxPayloadSize;\n }\n\n /**\n * Add feature-processed event to our buffer. If this event would cause our total raw size to exceed the set max payload size, it is dropped.\n * @param {any} event - any primitive type or object\n * @returns {Boolean} true if successfully added; false otherwise\n */\n add(event) {\n const addSize = stringify(event)?.length || 0; // (estimate) # of bytes a directly stringified event it would take to send\n if (this.#rawBytes + addSize > this.maxPayloadSize) return false;\n this.#buffer.push(event);\n this.#rawBytes += addSize;\n return true;\n }\n\n /**\n * Wipes the main buffer\n */\n clear() {\n this.#buffer = [];\n this.#rawBytes = 0;\n }\n\n /**\n * Backup the buffered data and clear the main buffer\n * @returns {Array} the events being backed up\n */\n save() {\n this.#bufferBackup = this.#buffer;\n this.#rawBytesBackup = this.#rawBytes;\n }\n\n /**\n * Wipes the backup buffer\n */\n clearSave() {\n this.#bufferBackup = undefined;\n this.#rawBytesBackup = undefined;\n }\n\n /**\n * Prepend the backup buffer back into the main buffer\n */\n reloadSave() {\n if (!this.#bufferBackup) return;\n if (this.#rawBytesBackup + this.#rawBytes > this.maxPayloadSize) return;\n this.#buffer = [...this.#bufferBackup, ...this.#buffer];\n this.#rawBytes = this.#rawBytesBackup + this.#rawBytes;\n }\n}","import { ee } from '../../common/event-emitter/contextual-ee';\nimport { deregisterDrain } from '../../common/drain/drain';\nexport class FeatureBase {\n constructor(agentIdentifier, featureName) {\n /** @type {string} */\n this.agentIdentifier = agentIdentifier;\n /** @type {import('../../common/event-emitter/contextual-ee').ee} */\n this.ee = ee.get(agentIdentifier);\n /** @type {string} */\n this.featureName = featureName;\n /**\n * Blocked can be used to prevent aggregation and harvest after inititalization time of the feature.\n * This can currently happen if RUM response setToken flag is 0, which is tied to ingest account entitlement info.\n * @type {boolean}\n */\n this.blocked = false;\n }\n deregisterDrain() {\n deregisterDrain(this.agentIdentifier, this.featureName);\n }\n}","import { getConfigurationValue } from '../../common/config/init';\nimport { isBrowserScope } from '../../common/constants/runtime';\n\n/**\n * Checks if session can be tracked, affects session entity and dependent features\n * @param {string} agentId\n * @returns {boolean}\n */\nexport const canEnableSessionTracking = agentId => {\n return isBrowserScope && getConfigurationValue(agentId, 'privacy.cookies_enabled') === true;\n};","import { FEATURE_NAMES } from '../../loaders/features/features';\n\n/**\n * Centralizes the lazy loading of agent feature aggregate and instrument sources.\n *\n * This function uses two defined switch cases to allow us to easily name our chunks and re-use these\n * chunks for different agent types. We do not use template strings or string concatenation here because\n * doing so makes it much more difficult to name the chunks and forces Webpack to \"guess\" what the chunks\n * should be.\n * @param featureName Name of the feature to import such as ajax or session_trace\n * @param featurePart Name of the feature part to load; should be either instrument or aggregate\n * @returns {Promise}\n */\nexport function lazyFeatureLoader(featureName, featurePart) {\n if (featurePart === 'aggregate') {\n switch (featureName) {\n case FEATURE_NAMES.ajax:\n return import(/* webpackChunkName: \"ajax-aggregate\" */'../ajax/aggregate');\n case FEATURE_NAMES.jserrors:\n return import(/* webpackChunkName: \"jserrors-aggregate\" */'../jserrors/aggregate');\n case FEATURE_NAMES.genericEvents:\n return import(/* webpackChunkName: \"generic_events-aggregate\" */'../generic_events/aggregate');\n case FEATURE_NAMES.logging:\n return import(/* webpackChunkName: \"logging-aggregate\" */'../logging/aggregate');\n case FEATURE_NAMES.metrics:\n return import(/* webpackChunkName: \"metrics-aggregate\" */'../metrics/aggregate');\n case FEATURE_NAMES.pageViewEvent:\n return import(/* webpackChunkName: \"page_view_event-aggregate\" */'../page_view_event/aggregate');\n case FEATURE_NAMES.pageViewTiming:\n return import(/* webpackChunkName: \"page_view_timing-aggregate\" */'../page_view_timing/aggregate');\n case FEATURE_NAMES.sessionReplay:\n return import(/* webpackChunkName: \"session_replay-aggregate\" */'../session_replay/aggregate');\n case FEATURE_NAMES.sessionTrace:\n return import(/* webpackChunkName: \"session_trace-aggregate\" */'../session_trace/aggregate');\n case FEATURE_NAMES.spa:\n return import(/* webpackChunkName: \"spa-aggregate\" */'../spa/aggregate');\n case FEATURE_NAMES.softNav:\n return import(/* webpackChunkName: \"basic-spa-aggregate\" */'../soft_navigations/aggregate');\n default:\n throw new Error(\"Attempted to load unsupported agent feature: \".concat(featureName, \" \").concat(featurePart));\n }\n }\n}","import { FEATURE_NAMES } from '../features/features';\nimport { getRuntime } from '../../common/config/runtime';\nimport { ee } from '../../common/event-emitter/contextual-ee';\nimport { handle } from '../../common/event-emitter/handle';\nimport { registerHandler } from '../../common/event-emitter/register-handler';\nimport { single } from '../../common/util/invoke';\nimport { CUSTOM_METRIC_CHANNEL } from '../../features/metrics/constants';\nimport { originTime } from '../../common/constants/runtime';\nexport function setAPI(agentIdentifier) {\n var instanceEE = ee.get(agentIdentifier);\n var api = {\n finished: single(finished),\n setErrorHandler,\n addToTrace,\n addRelease\n };\n\n // Hook all of the api functions up to the queues/stubs created in loader/api.js\n Object.entries(api).forEach(([fnName, fnCall]) => registerHandler('api-' + fnName, fnCall, 'api', instanceEE));\n\n // All API functions get passed the time they were called as their\n // first parameter. These functions can be called asynchronously.\n\n function finished(t, providedTime) {\n var time = providedTime ? providedTime - originTime : t;\n handle(CUSTOM_METRIC_CHANNEL, ['finished', {\n time\n }], undefined, FEATURE_NAMES.metrics, instanceEE);\n addToTrace(t, {\n name: 'finished',\n start: time + originTime,\n origin: 'nr'\n });\n handle('api-addPageAction', [time, 'finished'], undefined, FEATURE_NAMES.genericEvents, instanceEE);\n }\n function addToTrace(t, evt) {\n if (!(evt && typeof evt === 'object' && evt.name && evt.start)) return;\n var report = {\n n: evt.name,\n s: evt.start - originTime,\n e: (evt.end || evt.start) - originTime,\n o: evt.origin || '',\n t: 'api'\n };\n handle('bstApi', [report], undefined, FEATURE_NAMES.sessionTrace, instanceEE);\n }\n function setErrorHandler(t, handler) {\n getRuntime(agentIdentifier).onerror = handler;\n }\n var releaseCount = 0;\n function addRelease(t, name, id) {\n if (++releaseCount > 10) return;\n getRuntime(agentIdentifier).releaseIds[name.slice(-200)] = ('' + id).slice(-200);\n }\n}","import { warn } from '../common/util/console';\nimport { generateRandomHexString } from '../common/ids/unique-id';\nexport class MicroAgentBase {\n agentIdentifier;\n constructor(agentIdentifier = generateRandomHexString(16)) {\n this.agentIdentifier = agentIdentifier;\n }\n\n /**\n * Tries to execute the api and generates a generic warning message with the api name injected if unsuccessful\n * @param {string} methodName\n * @param {...any} args\n */\n #callMethod(methodName, ...args) {\n if (typeof this.api?.[methodName] !== 'function') warn(35, methodName);else return this.api[methodName](...args);\n }\n\n // MicroAgent class custom defines its own start\n\n /**\n * Reports a browser PageAction event along with a name and optional attributes.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/addpageaction/}\n * @param {string} name Name or category of the action. Reported as the actionName attribute.\n * @param {object} [attributes] JSON object with one or more key/value pairs. For example: {key:\"value\"}. The key is reported as its own PageAction attribute with the specified values.\n */\n addPageAction(name, attributes) {\n return this.#callMethod('addPageAction', name, attributes);\n }\n\n /**\n * Groups page views to help URL structure or to capture the URL's routing information.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/setpageviewname/}\n * @param {string} name The page name you want to use. Use alphanumeric characters.\n * @param {string} [host] Default is http://custom.transaction. Typically set host to your site's domain URI.\n */\n setPageViewName(name, host) {\n return this.#callMethod('setPageViewName', name, host);\n }\n\n /**\n * Adds a user-defined attribute name and value to subsequent events on the page.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/setcustomattribute/}\n * @param {string} name Name of the attribute. Appears as column in the PageView event. It will also appear as a column in the PageAction event if you are using it.\n * @param {string|number|boolean|null} value Value of the attribute. Appears as the value in the named attribute column in the PageView event. It will appear as a column in the PageAction event if you are using it. Custom attribute values cannot be complex objects, only simple types such as Strings, Integers and Booleans. Passing a null value unsets any existing attribute of the same name.\n * @param {boolean} [persist] Default false. If set to true, the name-value pair will also be set into the browser's storage API. Then on the following instrumented pages that load within the same session, the pair will be re-applied as a custom attribute.\n */\n setCustomAttribute(name, value, persist) {\n return this.#callMethod('setCustomAttribute', name, value, persist);\n }\n\n /**\n * Identifies a browser error without disrupting your app's operations.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/noticeerror/}\n * @param {Error|string} error Provide a meaningful error message that you can use when analyzing data on browser's JavaScript errors page.\n * @param {object} [customAttributes] An object containing name/value pairs representing custom attributes.\n */\n noticeError(error, customAttributes) {\n return this.#callMethod('noticeError', error, customAttributes);\n }\n\n /**\n * Adds a user-defined identifier string to subsequent events on the page.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/setuserid/}\n * @param {string|null} value A string identifier for the end-user, useful for tying all browser events to specific users. The value parameter does not have to be unique. If IDs should be unique, the caller is responsible for that validation. Passing a null value unsets any existing user ID.\n */\n setUserId(value) {\n return this.#callMethod('setUserId', value);\n }\n\n /**\n * Adds a user-defined application version string to subsequent events on the page.\n * This decorates all payloads with an attribute of `application.version` which is queryable in NR1.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/setapplicationversion/}\n * @param {string|null} value A string identifier for the application version, useful for\n * tying all browser events to a specific release tag. The value parameter does not\n * have to be unique. Passing a null value unsets any existing value.\n */\n setApplicationVersion(value) {\n return this.#callMethod('setApplicationVersion', value);\n }\n\n /**\n * Allows selective ignoring and grouping of known errors that the browser agent captures.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/seterrorhandler/}\n * @param {(error: Error|string) => boolean | { group: string }} callback When an error occurs, the callback is called with the error object as a parameter. The callback will be called with each error, so it is not specific to one error.\n */\n setErrorHandler(callback) {\n return this.#callMethod('setErrorHandler', callback);\n }\n\n /**\n * Adds a unique name and ID to identify releases with multiple JavaScript bundles on the same page.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/addrelease/}\n * @param {string} name A short description of the component; for example, the name of a project, application, file, or library.\n * @param {string} id The ID or version of this release; for example, a version number, build number from your CI environment, GitHub SHA, GUID, or a hash of the contents.\n */\n addRelease(name, id) {\n return this.#callMethod('addRelease', name, id);\n }\n\n /**\n * Capture a single log.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/log/}\n * @param {string} message String to be captured as log message\n * @param {{customAttributes?: object, level?: 'ERROR'|'TRACE'|'DEBUG'|'INFO'|'WARN'}} [options] customAttributes defaults to `{}` if not assigned, level defaults to `info` if not assigned.\n */\n log(message, options) {\n return this.#callMethod('log', message, options);\n }\n}","/* eslint-disable n/handle-callback-err */\n\nimport { warn } from '../common/util/console';\nimport { SR_EVENT_EMITTER_TYPES } from '../features/session_replay/constants';\nimport { MicroAgentBase } from './micro-agent-base';\n\n/**\n * @typedef {import('./api/interaction-types').InteractionInstance} InteractionInstance\n */\n\nexport class AgentBase extends MicroAgentBase {\n /**\n * Tries to execute the api and generates a generic warning message with the api name injected if unsuccessful\n * @param {string} methodName\n * @param {...any} args\n */\n #callMethod(methodName, ...args) {\n if (typeof this.api?.[methodName] !== 'function') warn(35, methodName);else return this.api[methodName](...args);\n }\n\n /**\n * Starts any and all features that are not running yet in \"autoStart\" mode\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/start/}\n */\n start() {\n return this.#callMethod('start');\n }\n\n /**\n * Records an additional time point as \"finished\" in a session trace and adds a page action.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/finished/}\n * @param {number} [timeStamp] Defaults to the current time of the call. If used, this marks the time that the page is \"finished\" according to your own criteria.\n */\n finished(timeStamp) {\n return this.#callMethod('finished', timeStamp);\n }\n\n /**\n * Forces a replay to record. If a replay is already actively recording, this call will be ignored.\n * If a recording has not been started, a new one will be created. If a recording has been started, but is currently not recording, it will resume recording.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/recordReplay/}\n */\n recordReplay() {\n return this.#callMethod(SR_EVENT_EMITTER_TYPES.RECORD);\n }\n\n /**\n * Forces an active replay to pause recording. If a replay is already actively recording, this call will cause the recording to pause.\n * If a recording is not currently recording, this call will be ignored. This API will pause both manual and automatic replays that are in progress.\n * The only way to resume recording after manually pausing a replay is to manually record again using the recordReplay() API.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/pauseReplay/}\n */\n pauseReplay() {\n return this.#callMethod(SR_EVENT_EMITTER_TYPES.PAUSE);\n }\n\n /**\n * Adds a JavaScript object with a custom name, start time, etc. to an in-progress session trace.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/addtotrace/}\n * @param {{name: string, start: number, end?: number, origin?: string, type?: string}} customAttributes Supply a JavaScript object with these required and optional name/value pairs:\n *\n * - Required name/value pairs: name, start\n * - Optional name/value pairs: end, origin, type\n * - Note: Does not apply to MicroAgent\n *\n * If you are sending the same event object to New Relic as a PageAction, omit the TYPE attribute. (type is a string to describe what type of event you are marking inside of a session trace.) If included, it will override the event type and cause the PageAction event to be sent incorrectly. Instead, use the name attribute for event information.\n */\n addToTrace(customAttributes) {\n return this.#callMethod('addToTrace', customAttributes);\n }\n\n /**\n * Gives SPA routes more accurate names than default names. Monitors specific routes rather than by default grouping.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/setcurrentroutename/}\n * @param {string} name Current route name for the page.\n * - Note: Does not apply to MicroAgent\n */\n setCurrentRouteName(name) {\n return this.#callMethod('setCurrentRouteName', name);\n }\n\n /**\n * Returns a new API object that is bound to the current SPA interaction.\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/interaction/}\n * @returns {InteractionInstance} An API object that is bound to a specific BrowserInteraction event. Each time this method is called for the same BrowserInteraction, a new object is created, but it still references the same interaction.\n * - Note: Does not apply to MicroAgent\n * - Deprecation Notice: interaction.createTracer is deprecated. See https://docs.newrelic.com/eol/2024/04/eol-04-24-24-createtracer/ for more information.\n */\n interaction() {\n return this.#callMethod('interaction');\n }\n\n /**\n * Wrap a logger function to capture a log each time the function is invoked with the message and arguments passed\n * {@link https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/wraplogger/}\n * @param {object} parent The parent object containing the logger method\n * @param {string} functionName The property name of the function in the parent object to be wrapped\n * @param {{customAttributes?: object, level?: 'ERROR'|'TRACE'|'DEBUG'|'INFO'|'WARN'}} [options] customAttributes defaults to `{}` if not assigned, level defaults to `info` if not assigned.\n */\n wrapLogger(parent, functionName, options) {\n return this.#callMethod('wrapLogger', parent, functionName, options);\n }\n}","import { FEATURE_NAMES } from './features';\nimport { getConfigurationValue } from '../../common/config/init';\nconst featureNames = Object.values(FEATURE_NAMES);\nfunction isEnabled(name, agentIdentifier) {\n return getConfigurationValue(agentIdentifier, \"\".concat(name, \".enabled\")) === true;\n}\nexport function getEnabledFeatures(agentIdentifier) {\n const enabledFeatures = {};\n featureNames.forEach(featureName => {\n enabledFeatures[featureName] = isEnabled(featureName, agentIdentifier);\n });\n return enabledFeatures;\n}","/**\n * @file Defines `InstrumentBase` to be used as the super of the Instrument classes implemented by each feature.\n * Inherits and executes the `checkConfiguration` method from [FeatureBase]{@link ./feature-base}, which also\n * exposes the `blocked` property.\n */\n\nimport { drain, registerDrain } from '../../common/drain/drain';\nimport { FeatureBase } from './feature-base';\nimport { onWindowLoad } from '../../common/window/load';\nimport { isBrowserScope } from '../../common/constants/runtime';\nimport { warn } from '../../common/util/console';\nimport { FEATURE_NAMES } from '../../loaders/features/features';\nimport { hasReplayPrerequisite } from '../session_replay/shared/utils';\nimport { canEnableSessionTracking } from './feature-gates';\nimport { single } from '../../common/util/invoke';\n\n/**\n * Base class for instrumenting a feature.\n * @extends FeatureBase\n */\nexport class InstrumentBase extends FeatureBase {\n /**\n * Instantiate InstrumentBase.\n * @param {string} agentIdentifier - The unique ID of the instantiated agent (relative to global scope).\n * @param {string} featureName - The name of the feature module (used to construct file path).\n * @param {boolean} [auto=true] - Determines whether the feature should automatically register to have the draining\n * of its pooled instrumentation data handled by the agent's centralized drain functionality, rather than draining\n * immediately. Primarily useful for fine-grained control in tests.\n */\n constructor(agentRef, featureName, auto = true) {\n super(agentRef.agentIdentifier, featureName);\n this.auto = auto;\n\n /** @type {Function | undefined} This should be set by any derived Instrument class if it has things to do when feature fails or is killed. */\n this.abortHandler = undefined;\n\n /**\n * @type {import('./aggregate-base').AggregateBase} Holds the reference to the feature's aggregate module counterpart, if and after it has been initialized. This may not be assigned until after page loads!\n * The only purpose of this for now is to expose it to the NREUM interface, as the feature's instrument instance is already exposed.\n */\n this.featAggregate = undefined;\n\n /**\n * @type {Promise} Assigned immediately after @see importAggregator runs. Serves as a signal for when the inner async fn finishes execution. Useful for features to await\n * one another if there are inter-features dependencies.\n * TODO: This is only used for the SPA feature component tests and should be refactored out.\n */\n this.onAggregateImported = undefined;\n\n /** used in conjunction with newrelic.start() to defer harvesting in features */\n if (agentRef.init[this.featureName].autoStart === false) this.auto = false;\n /** if the feature requires opt-in (!auto-start), it will get registered once the api has been called */\n if (this.auto) registerDrain(agentRef.agentIdentifier, featureName);else {\n this.ee.on('manual-start-all', single(() => {\n // register the feature to drain only once the API has been called, it will drain when importAggregator finishes for all the features\n // called by the api in that cycle\n registerDrain(agentRef.agentIdentifier, this.featureName);\n this.auto = true;\n this.importAggregator(agentRef);\n }));\n }\n }\n\n /**\n * Lazy-load the latter part of the feature: its aggregator. This method is called by the first part of the feature\n * (the instrumentation) when instrumentation is complete.\n * @param agentRef - reference to the base agent ancestor that this feature belongs to\n * @param {Object} [argsObjFromInstrument] - any values or references to pass down to aggregate\n * @returns void\n */\n importAggregator(agentRef, argsObjFromInstrument = {}) {\n if (this.featAggregate || !this.auto) return;\n let loadedSuccessfully;\n this.onAggregateImported = new Promise(resolve => {\n loadedSuccessfully = resolve;\n });\n const importLater = async () => {\n let session;\n try {\n if (canEnableSessionTracking(this.agentIdentifier)) {\n // would require some setup before certain features start\n const {\n setupAgentSession\n } = await import(/* webpackChunkName: \"session-manager\" */'./agent-session');\n session = setupAgentSession(agentRef);\n }\n } catch (e) {\n warn(20, e);\n this.ee.emit('internal-error', [e]);\n if (this.featureName === FEATURE_NAMES.sessionReplay) this.abortHandler?.(); // SR should stop recording if session DNE\n }\n\n /**\n * Note this try-catch differs from the one in Agent.run() in that it's placed later in a page's lifecycle and\n * it's only responsible for aborting its one specific feature, rather than all.\n */\n try {\n // Create a single Aggregator for this agent if DNE yet; to be used by jserror endpoint features.\n if (!agentRef.sharedAggregator) {\n agentRef.sharedAggregator = import(/* webpackChunkName: \"shared-aggregator\" */'../../common/aggregate/event-aggregator');\n const {\n EventAggregator\n } = await agentRef.sharedAggregator;\n agentRef.sharedAggregator = new EventAggregator();\n } else await agentRef.sharedAggregator; // if another feature is already importing the aggregator, wait for it to finish\n\n if (!this.#shouldImportAgg(this.featureName, session)) {\n drain(this.agentIdentifier, this.featureName);\n loadedSuccessfully(false); // aggregate module isn't loaded at all\n return;\n }\n const {\n lazyFeatureLoader\n } = await import(/* webpackChunkName: \"lazy-feature-loader\" */'./lazy-feature-loader');\n const {\n Aggregate\n } = await lazyFeatureLoader(this.featureName, 'aggregate');\n this.featAggregate = new Aggregate(agentRef, argsObjFromInstrument);\n loadedSuccessfully(true);\n } catch (e) {\n warn(34, e);\n this.abortHandler?.(); // undo any important alterations made to the page\n // not supported yet but nice to do: \"abort\" this agent's EE for this feature specifically\n drain(this.agentIdentifier, this.featureName, true);\n loadedSuccessfully(false);\n if (this.ee) this.ee.abort();\n }\n };\n\n // For regular web pages, we want to wait and lazy-load the aggregator only after all page resources are loaded.\n // Non-browser scopes (i.e. workers) have no `window.load` event, so the aggregator can be lazy-loaded immediately.\n if (!isBrowserScope) importLater();else onWindowLoad(() => importLater(), true);\n }\n\n /**\n * Make a determination if an aggregate class should even be imported\n * @param {string} featureName\n * @param {import('../../common/session/session-entity').SessionEntity} session\n * @returns\n */\n #shouldImportAgg(featureName, session) {\n switch (featureName) {\n case FEATURE_NAMES.sessionReplay:\n // the session manager must be initialized successfully for Replay & Trace features\n return hasReplayPrerequisite(this.agentIdentifier) && !!session;\n case FEATURE_NAMES.sessionTrace:\n return !!session;\n default:\n return true;\n }\n }\n}","import { InstrumentBase } from '../../utils/instrument-base';\nimport * as CONSTANTS from '../constants';\nexport class Instrument extends InstrumentBase {\n static featureName = CONSTANTS.FEATURE_NAME;\n constructor(agentRef, auto = true) {\n super(agentRef, CONSTANTS.FEATURE_NAME, auto);\n this.importAggregator(agentRef);\n }\n}\nexport const PageViewEvent = Instrument;","// important side effects\nimport './configure/public-path';\nimport './configure/nonce';\n// loader files\nimport { AgentBase } from './agent-base';\nimport { getEnabledFeatures } from './features/enabled-features';\nimport { configure } from './configure/configure';\nimport { getFeatureDependencyNames } from './features/featureDependencies';\nimport { featurePriority, FEATURE_NAMES } from './features/features';\n// required features\nimport { Instrument as PageViewEvent } from '../features/page_view_event/instrument';\n// common files\nimport { gosNREUM, setNREUMInitializedAgent } from '../common/window/nreum';\nimport { warn } from '../common/util/console';\nimport { globalScope } from '../common/constants/runtime';\n\n/**\n * A flexible class that may be used to compose an agent from a select subset of feature modules. In applications\n * sensitive to network load, this may result in smaller builds with slightly lower performance impact.\n */\nexport class Agent extends AgentBase {\n /**\n * @param {Object} options Options to initialize agent with\n * @param {string} [agentIdentifier] Optional identifier of agent\n */\n constructor(options, agentIdentifier) {\n super(agentIdentifier);\n if (!globalScope) {\n // We could not determine the runtime environment. Short-circuite the agent here\n // to avoid possible exceptions later that may cause issues with customer's application.\n warn(21);\n return;\n }\n this.features = {};\n setNREUMInitializedAgent(this.agentIdentifier, this); // append this agent onto the global NREUM.initializedAgents\n\n this.desiredFeatures = new Set(options.features || []); // expected to be a list of static Instrument/InstrumentBase classes, see \"spa.js\" for example\n // For Now... ALL agents must make the rum call whether the page_view_event feature was enabled or not.\n // NR1 creates an index on the rum call, and if not seen for a few days, will remove the browser app!\n // Future work is being planned to evaluate removing this behavior from the backend, but for now we must ensure this call is made\n this.desiredFeatures.add(PageViewEvent);\n this.runSoftNavOverSpa = [...this.desiredFeatures].some(instr => instr.featureName === FEATURE_NAMES.softNav);\n configure(this, options, options.loaderType || 'agent'); // add api, exposed, and other config properties\n\n this.run();\n }\n get config() {\n return {\n info: this.info,\n init: this.init,\n loader_config: this.loader_config,\n runtime: this.runtime\n };\n }\n run() {\n // Attempt to initialize all the requested features (sequentially in prio order & synchronously), with any failure aborting the whole process.\n try {\n const enabledFeatures = getEnabledFeatures(this.agentIdentifier);\n const featuresToStart = [...this.desiredFeatures];\n featuresToStart.sort((a, b) => featurePriority[a.featureName] - featurePriority[b.featureName]);\n featuresToStart.forEach(InstrumentCtor => {\n if (!enabledFeatures[InstrumentCtor.featureName] && InstrumentCtor.featureName !== FEATURE_NAMES.pageViewEvent) return; // PVE is required to run even if it's marked disabled\n if (this.runSoftNavOverSpa && InstrumentCtor.featureName === FEATURE_NAMES.spa) return;\n if (!this.runSoftNavOverSpa && InstrumentCtor.featureName === FEATURE_NAMES.softNav) return;\n const dependencies = getFeatureDependencyNames(InstrumentCtor.featureName);\n const missingDependencies = dependencies.filter(featName => !(featName in this.features)); // any other feature(s) this depends on should've been initialized on prior iterations by priority order\n if (missingDependencies.length > 0) {\n warn(36, {\n targetFeature: InstrumentCtor.featureName,\n missingDependencies\n });\n }\n this.features[InstrumentCtor.featureName] = new InstrumentCtor(this);\n });\n } catch (err) {\n warn(22, err);\n for (const featName in this.features) {\n // this.features hold only features that have been instantiated\n this.features[featName].abortHandler?.();\n }\n const newrelic = gosNREUM();\n delete newrelic.initializedAgents[this.agentIdentifier]?.api; // prevent further calls to agent-specific APIs (see \"configure.js\")\n delete newrelic.initializedAgents[this.agentIdentifier]?.features; // GC mem used internally by features\n delete this.sharedAggregator;\n // Keep the initialized agent object with its configs for troubleshooting purposes.\n const thisEE = newrelic.ee.get(this.agentIdentifier);\n thisEE.abort(); // set flag and clear backlog\n return false;\n }\n }\n}","import { FEATURE_NAMES } from './features';\nexport function getFeatureDependencyNames(feature) {\n switch (feature) {\n case FEATURE_NAMES.ajax:\n return [FEATURE_NAMES.jserrors];\n case FEATURE_NAMES.sessionTrace:\n return [FEATURE_NAMES.ajax, FEATURE_NAMES.pageViewEvent];\n case FEATURE_NAMES.sessionReplay:\n return [FEATURE_NAMES.sessionTrace];\n case FEATURE_NAMES.pageViewTiming:\n return [FEATURE_NAMES.pageViewEvent];\n // this could change if we disconnect window load timings\n default:\n return [];\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { handle } from '../../../common/event-emitter/handle';\nimport { subscribeToVisibilityChange } from '../../../common/window/page-visibility';\nimport { windowAddEventListener } from '../../../common/event-listener/event-listener-opts';\nimport { InstrumentBase } from '../../utils/instrument-base';\nimport { FEATURE_NAME } from '../constants';\nimport { isBrowserScope } from '../../../common/constants/runtime';\nimport { now } from '../../../common/timing/now';\nexport class Instrument extends InstrumentBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef, auto = true) {\n super(agentRef, FEATURE_NAME, auto);\n if (!isBrowserScope) return; // CWV is irrelevant outside web context\n\n // While we try to replicate web-vital's visibilitywatcher logic in an effort to defer that library to post-pageload, this isn't perfect and doesn't consider prerendering.\n subscribeToVisibilityChange(() => handle('docHidden', [now()], undefined, FEATURE_NAME, this.ee), true);\n\n // Window fires its pagehide event (typically on navigation--this occurrence is a *subset* of vis change); don't defer this unless it's guarantee it cannot happen before load(?)\n windowAddEventListener('pagehide', () => handle('winPagehide', [now()], undefined, FEATURE_NAME, this.ee));\n this.importAggregator(agentRef);\n }\n}\nexport const PageViewTiming = Instrument;","// import { handle } from '../../../common/event-emitter/handle'\n// import { WEBSOCKET_TAG, wrapWebSocket } from '../../../common/wrap/wrap-websocket'\nimport { InstrumentBase } from '../../utils/instrument-base';\nimport { FEATURE_NAME /*, WATCHABLE_WEB_SOCKET_EVENTS */ } from '../constants';\nexport class Instrument extends InstrumentBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef, auto = true) {\n super(agentRef, FEATURE_NAME, auto);\n // wrapWebSocket(this.ee)\n\n // WATCHABLE_WEB_SOCKET_EVENTS.forEach((suffix) => {\n // this.ee.on(WEBSOCKET_TAG + suffix, (...args) => {\n // handle('buffered-' + WEBSOCKET_TAG + suffix, [...args], undefined, this.featureName, this.ee)\n // })\n // })\n\n this.importAggregator(agentRef);\n }\n}\nexport const Metrics = Instrument;","import { stringify } from '../../../common/util/stringify';\n\n/**\n * Represents an uncaught non Error type error. This class does\n * not extend the Error class to prevent an invalid stack trace\n * from being created. Use this class to cast thrown errors that\n * do not use the Error class (strings, etc) to an object.\n */\nexport class UncaughtError {\n constructor(message, filename, lineno, colno, newrelic) {\n this.name = 'UncaughtError';\n this.message = typeof message === 'string' ? message : stringify(message);\n this.sourceURL = filename;\n this.line = lineno;\n this.column = colno;\n this.__newrelic = newrelic;\n }\n}","import { UncaughtError } from './uncaught-error';\n\n/**\n * Any value can be used with the `throw` keyword. This function ensures that the value is\n * either a proper Error instance or attempts to convert it to an UncaughtError instance.\n * @param {any} error The value thrown\n * @returns {Error|UncaughtError} The converted error instance\n */\nexport function castError(error) {\n /** Sometimes a browser can emit an error object with no stack */\n if (canTrustError(error)) {\n return error;\n }\n\n /**\n * The thrown value may contain a message property. If it does, try to treat the thrown\n * value as an Error-like object.\n */\n return new UncaughtError(error?.message !== undefined ? error.message : error, error?.filename || error?.sourceURL, error?.lineno || error?.line, error?.colno || error?.col, error?.__newrelic);\n}\n\n/**\n * Attempts to convert a PromiseRejectionEvent object to an Error object\n * @param {PromiseRejectionEvent} unhandledRejectionEvent The unhandled promise rejection event\n * @returns {Error} An Error object with the message as the casted reason\n */\nexport function castPromiseRejectionEvent(promiseRejectionEvent) {\n const prefix = 'Unhandled Promise Rejection';\n\n /**\n * If the casted return value is falsy like this, it will get dropped and not produce an error event for harvest.\n * We drop promise rejections that could not form a valid error stack or message deriving from the .reason attribute\n * -- such as a manually invoked rejection without an argument -- since they lack reproduction value and create confusion.\n * */\n if (!promiseRejectionEvent?.reason) return;\n if (canTrustError(promiseRejectionEvent.reason)) {\n try {\n promiseRejectionEvent.reason.message = prefix + ': ' + promiseRejectionEvent.reason.message;\n return castError(promiseRejectionEvent.reason);\n } catch (e) {\n return castError(promiseRejectionEvent.reason);\n }\n }\n const error = castError(promiseRejectionEvent.reason);\n error.message = prefix + ': ' + error?.message;\n return error;\n}\n\n/**\n * Attempts to convert an ErrorEvent object to an Error object\n * @param {ErrorEvent} errorEvent The error event\n * @returns {Error|UncaughtError} The error event converted to an Error object\n */\nexport function castErrorEvent(errorEvent) {\n if (errorEvent.error instanceof SyntaxError && !/:\\d+$/.test(errorEvent.error.stack?.trim())) {\n const error = new UncaughtError(errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error.__newrelic);\n error.name = SyntaxError.name;\n return error;\n }\n if (canTrustError(errorEvent.error)) return errorEvent.error;\n return castError(errorEvent);\n}\nfunction canTrustError(error) {\n return error instanceof Error && !!error.stack;\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { handle } from '../../../common/event-emitter/handle';\nimport { InstrumentBase } from '../../utils/instrument-base';\nimport { FEATURE_NAME } from '../constants';\nimport { globalScope } from '../../../common/constants/runtime';\nimport { eventListenerOpts } from '../../../common/event-listener/event-listener-opts';\nimport { now } from '../../../common/timing/now';\nimport { SR_EVENT_EMITTER_TYPES } from '../../session_replay/constants';\nimport { castError, castErrorEvent, castPromiseRejectionEvent } from '../shared/cast-error';\nexport class Instrument extends InstrumentBase {\n static featureName = FEATURE_NAME;\n #replayRunning = false;\n constructor(agentRef, auto = true) {\n super(agentRef, FEATURE_NAME, auto);\n try {\n // this try-catch can be removed when IE11 is completely unsupported & gone\n this.removeOnAbort = new AbortController();\n } catch (e) {}\n this.ee.on('internal-error', error => {\n if (!this.abortHandler) return;\n handle('ierr', [castError(error), now(), true, {}, this.#replayRunning], undefined, this.featureName, this.ee);\n });\n this.ee.on(SR_EVENT_EMITTER_TYPES.REPLAY_RUNNING, isRunning => {\n this.#replayRunning = isRunning;\n });\n globalScope.addEventListener('unhandledrejection', promiseRejectionEvent => {\n if (!this.abortHandler) return;\n handle('err', [castPromiseRejectionEvent(promiseRejectionEvent), now(), false, {\n unhandledPromiseRejection: 1\n }, this.#replayRunning], undefined, this.featureName, this.ee);\n }, eventListenerOpts(false, this.removeOnAbort?.signal));\n globalScope.addEventListener('error', errorEvent => {\n if (!this.abortHandler) return;\n handle('err', [castErrorEvent(errorEvent), now(), false, {}, this.#replayRunning], undefined, this.featureName, this.ee);\n }, eventListenerOpts(false, this.removeOnAbort?.signal));\n this.abortHandler = this.#abort; // we also use this as a flag to denote that the feature is active or on and handling errors\n this.importAggregator(agentRef);\n }\n\n /** Restoration and resource release tasks to be done if JS error loader is being aborted. Unwind changes to globals. */\n #abort() {\n this.removeOnAbort?.abort();\n this.abortHandler = undefined; // weakly allow this abort op to run only once\n }\n}\nexport const JSErrors = Instrument;","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getOrSet } from '../util/get-or-set';\nimport { globalScope } from '../constants/runtime';\n\n// Start assigning ids at 1 so 0 can always be used for Window or WorkerGlobalScope, without\n// actually setting it (which would create a global variable).\nlet index = 1;\nconst prop = 'nr@id';\n\n/**\n * Tags a specified object with an identifier if it does not already\n * have one. If the object is the global scope, zero will be returned\n * and the object will not be modified. If the object already contains\n * an identifier, it will be returned without modification. If the passed\n * value is not an object, function, or array, -1 will be returned without\n * modifying the passed value.\n * @param {object|function|array} obj Object to be tagged with an identifier\n * @returns {number} Identifier of the given object\n */\nexport function id(obj) {\n const type = typeof obj;\n // We can only tag objects, functions, and arrays with ids.\n // For all primitive values we instead return -1.\n if (!obj || !(type === 'object' || type === 'function')) return -1;\n if (obj === globalScope) return 0;\n return getOrSet(obj, prop, function () {\n return index++;\n });\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { stringify } from './stringify';\n\n/**\n * Returns the size of the provided data. Designed for measuring XHR responses.\n *\n * @param {*} data - The data to be measured.\n * @returns {(number|undefined)} - The size of the data or undefined if size cannot be determined.\n */\nexport function dataSize(data) {\n if (typeof data === 'string' && data.length) return data.length;\n if (typeof data !== 'object') return undefined;\n // eslint-disable-next-line\n if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer && data.byteLength) return data.byteLength;\n if (typeof Blob !== 'undefined' && data instanceof Blob && data.size) return data.size;\n if (typeof FormData !== 'undefined' && data instanceof FormData) return undefined;\n try {\n return stringify(data).length;\n } catch (e) {\n return undefined;\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Wraps AJAX (XHR) related methods for instrumentation.\n * This module is used by: ajax, jserrors, spa.\n */\n\nimport { wrapEvents } from './wrap-events';\nimport { ee as contextualEE } from '../event-emitter/contextual-ee';\nimport { eventListenerOpts } from '../event-listener/event-listener-opts';\nimport { createWrapperWithEmitter as wfn } from './wrap-function';\nimport { globalScope } from '../constants/runtime';\nimport { warn } from '../util/console';\nconst wrapped = {};\nconst XHR_PROPS = ['open', 'send']; // these are the specific funcs being wrapped on all XMLHttpRequests(.prototype)\n\n/**\n * Wraps the native XMLHttpRequest (XHR) object to emit custom events to its readystatechange event and an assortment\n * of handlers. Adds instrumentation in context of a new event emitter scoped only to XHR.\n * @param {Object} sharedEE - The shared event emitter on which a new scoped event emitter will be based.\n * @returns {Object} Scoped event emitter with a debug ID of `xhr`.\n */\n// eslint-disable-next-line\nexport function wrapXhr(sharedEE) {\n var baseEE = sharedEE || contextualEE;\n const ee = scopedEE(baseEE);\n\n // Notice if our wrapping never ran yet, the falsy NaN will not early return; but if it has,\n // then we increment the count to track # of feats using this at runtime.\n if (wrapped[ee.debugId]++) return ee;\n wrapped[ee.debugId] = 1; // otherwise, first feature to wrap XHR\n\n wrapEvents(baseEE); // wrap-events patches XMLHttpRequest.prototype.addEventListener for us\n var wrapFn = wfn(ee);\n var OrigXHR = globalScope.XMLHttpRequest;\n var MutationObserver = globalScope.MutationObserver;\n var Promise = globalScope.Promise;\n var setImmediate = globalScope.setInterval;\n var READY_STATE_CHANGE = 'readystatechange';\n var handlers = ['onload', 'onerror', 'onabort', 'onloadstart', 'onloadend', 'onprogress', 'ontimeout'];\n var pendingXhrs = [];\n var XHR = globalScope.XMLHttpRequest = newXHR;\n function newXHR(opts) {\n const xhr = new OrigXHR(opts);\n const context = ee.context(xhr);\n try {\n ee.emit('new-xhr', [xhr], context);\n xhr.addEventListener(READY_STATE_CHANGE, wrapXHR(context), eventListenerOpts(false));\n } catch (e) {\n warn(15, e);\n try {\n ee.emit('internal-error', [e]);\n } catch (err) {\n // do nothing\n }\n }\n return xhr;\n }\n copy(OrigXHR, XHR);\n XHR.prototype = OrigXHR.prototype;\n wrapFn.inPlace(XHR.prototype, XHR_PROPS, '-xhr-', getObject);\n ee.on('send-xhr-start', function (args, xhr) {\n wrapOnreadystatechange(args, xhr);\n enqueuePendingXhr(xhr);\n });\n ee.on('open-xhr-start', wrapOnreadystatechange);\n function wrapOnreadystatechange(args, xhr) {\n wrapFn.inPlace(xhr, ['onreadystatechange'], 'fn-', getObject);\n }\n function wrapXHR(ctx) {\n return function () {\n var xhr = this;\n if (xhr.readyState > 3 && !ctx.resolved) {\n ctx.resolved = true;\n ee.emit('xhr-resolved', [], xhr);\n }\n wrapFn.inPlace(xhr, handlers, 'fn-', getObject);\n };\n }\n\n // Wrapping the onreadystatechange property of XHRs takes some special tricks.\n //\n // The issue is that the onreadystatechange property may be assigned *after*\n // send() is called against an XHR. This is of particular importance because\n // jQuery uses a single onreadystatechange handler to implement all of the XHR\n // callbacks thtat it provides, and it assigns that property after calling send.\n //\n // There are several 'obvious' approaches to wrapping the onreadystatechange\n // when it's assigned after send:\n //\n // 1. Try to wrap the onreadystatechange handler from a readystatechange\n // addEventListener callback (the addEventListener callback will fire before\n // the onreadystatechange callback).\n //\n // Caveat: this doesn't work in Chrome or Safari, and in fact will cause\n // the onreadystatechange handler to not be invoked at all during the\n // firing cycle in which it is wrapped, which may break applications :(\n //\n // 2. Use Object.defineProperty to create a setter for the onreadystatechange\n // property, and wrap from that setter.\n //\n // Caveat: onreadystatechange is not a configurable property in Safari or\n // older versions of the Android browser.\n //\n // 3. Schedule wrapping of the onreadystatechange property using a setTimeout\n // call issued just before the call to send.\n //\n // Caveat: sometimes, the onreadystatechange handler fires before the\n // setTimeout, meaning the wrapping happens too late.\n //\n // The setTimeout approach is closest to what we use here: we want to schedule\n // the wrapping of the onreadystatechange property when send is called, but\n // ensure that our wrapping happens before onreadystatechange has a chance to\n // fire.\n //\n // We achieve this using a hybrid approach:\n //\n // * In browsers that support MutationObserver, we use that to schedule wrapping\n // of onreadystatechange.\n //\n // * We have discovered that MutationObserver in IE causes a memory leak, so we\n // now will prefer setImmediate for IE, and use a resolved promise to schedule\n // the wrapping in Edge (and other browsers that support promises)\n //\n // * In older browsers that don't support MutationObserver, we rely on the fact\n // that the call to send is probably happening within a callback that we've\n // already wrapped, and use our existing fn-end event callback to wrap the\n // onreadystatechange at the end of the current callback.\n //\n\n if (MutationObserver) {\n var resolved = Promise && Promise.resolve();\n if (!setImmediate && !Promise) {\n var toggle = 1;\n var dummyNode = document.createTextNode(toggle);\n new MutationObserver(drainPendingXhrs).observe(dummyNode, {\n characterData: true\n });\n }\n } else {\n // this below case applies to web workers too\n baseEE.on('fn-end', function (args) {\n // We don't want to try to wrap onreadystatechange from within a\n // readystatechange callback.\n if (args[0] && args[0].type === READY_STATE_CHANGE) return;\n drainPendingXhrs();\n });\n }\n function enqueuePendingXhr(xhr) {\n pendingXhrs.push(xhr);\n if (MutationObserver) {\n if (resolved) {\n resolved.then(drainPendingXhrs);\n } else if (setImmediate) {\n setImmediate(drainPendingXhrs);\n } else {\n toggle = -toggle;\n dummyNode.data = toggle;\n }\n }\n }\n function drainPendingXhrs() {\n for (var i = 0; i < pendingXhrs.length; i++) {\n wrapOnreadystatechange([], pendingXhrs[i]);\n }\n if (pendingXhrs.length) pendingXhrs = [];\n }\n\n // Use the object these methods are on as their\n // context store for the event emitter\n function getObject(args, obj) {\n return obj;\n }\n function copy(from, to) {\n for (var i in from) {\n to[i] = from[i];\n }\n return to;\n }\n return ee;\n}\n\n/**\n * Returns an event emitter scoped specifically for the `xhr` context. This scoping is a remnant from when all the\n * features shared the same group in the event, to isolate events between features. It will likely be revisited.\n * @param {Object} sharedEE - Optional event emitter on which to base the scoped emitter.\n * Uses `ee` on the global scope if undefined).\n * @returns {Object} Scoped event emitter with a debug ID of 'xhr'.\n */\nexport function scopedEE(sharedEE) {\n return (sharedEE || contextualEE).get('xhr');\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Wraps `fetch` and related methods for instrumentation.\n * This module is used by: ajax, spa.\n */\nimport { ee as baseEE, contextId } from '../event-emitter/contextual-ee';\nimport { globalScope } from '../constants/runtime';\nvar prefix = 'fetch-';\nvar bodyPrefix = prefix + 'body-';\nvar bodyMethods = ['arrayBuffer', 'blob', 'json', 'text', 'formData'];\nvar Req = globalScope.Request;\nvar Res = globalScope.Response;\nvar proto = 'prototype';\nconst wrapped = {};\n\n/**\n * Wraps the `fetch` method of the global scope for instrumentation. Also wraps the prototypes of the async methods\n * that parse Request and Response bodies to generate start and end events for each, in context of a new event\n * emitter scoped only to fetch and related methods.\n * @param {Object} sharedEE - The shared event emitter on which a new scoped\n * event emitter will be based.\n * @returns {Object} Scoped event emitter with a debug ID of `fetch`.\n */\nexport function wrapFetch(sharedEE) {\n const ee = scopedEE(sharedEE);\n if (!(Req && Res && globalScope.fetch)) {\n return ee;\n }\n\n // Notice if our wrapping never ran yet, the falsy NaN will not early return; but if it has,\n // then we increment the count to track # of feats using this at runtime.\n if (wrapped[ee.debugId]++) return ee;\n wrapped[ee.debugId] = 1; // otherwise, first feature to wrap fetch\n\n bodyMethods.forEach(method => {\n wrapPromiseMethod(Req[proto], method, bodyPrefix);\n wrapPromiseMethod(Res[proto], method, bodyPrefix);\n });\n wrapPromiseMethod(globalScope, 'fetch', prefix);\n ee.on(prefix + 'end', function (err, res) {\n var ctx = this;\n if (res) {\n var size = res.headers.get('content-length');\n if (size !== null) {\n ctx.rxSize = size;\n }\n ee.emit(prefix + 'done', [null, res], ctx);\n } else {\n ee.emit(prefix + 'done', [err], ctx);\n }\n });\n\n /**\n * Wraps a Promise-returning function (referenced by `target[name]`) to emit custom events before and after\n * execution, each decorated with metadata (arguments, payloads, errors). Used to wrap the async body\n * parsing methods of Request and Response (e.g. `json`, `text`, `formData`).\n * @param {Object} target - The object having the method to be wrapped.\n * @param {string} name - The name of the method to wrap.\n * @param {string} prefix - Used to decorate event names with context.\n */\n function wrapPromiseMethod(target, name, prefix) {\n var fn = target[name];\n if (typeof fn === 'function') {\n target[name] = function () {\n var args = [...arguments];\n var ctx = {};\n // we are wrapping args in an array so we can preserve the reference\n ee.emit(prefix + 'before-start', [args], ctx);\n var dtPayload;\n if (ctx[contextId] && ctx[contextId].dt) dtPayload = ctx[contextId].dt;\n var origPromiseFromFetch = fn.apply(this, args);\n ee.emit(prefix + 'start', [args, dtPayload], origPromiseFromFetch);\n\n // Note we need to cast the returned (orig) Promise from native APIs into the current global Promise, which may or may not be our WrappedPromise.\n return origPromiseFromFetch.then(function (val) {\n ee.emit(prefix + 'end', [null, val], origPromiseFromFetch);\n return val;\n }, function (err) {\n ee.emit(prefix + 'end', [err], origPromiseFromFetch);\n throw err;\n });\n };\n }\n }\n return ee;\n}\n\n/**\n * Returns an event emitter scoped specifically for the `fetch` context. This scoping is a remnant from when all the\n * features shared the same group in the event, to isolate events between features. It will likely be revisited.\n * @param {Object} sharedEE - Optional event emitter on which to base the scoped emitter.\n * Uses `ee` on the global scope if undefined).\n * @returns {Object} Scoped event emitter with a debug ID of 'fetch'.\n */\nexport function scopedEE(sharedEE) {\n return (sharedEE || baseEE).get('fetch');\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { getConfiguration, getConfigurationValue } from '../../../common/config/init';\nimport { getLoaderConfig } from '../../../common/config/loader-config';\nimport { generateSpanId, generateTraceId } from '../../../common/ids/unique-id';\nimport { parseUrl } from '../../../common/url/parse-url';\nimport { globalScope } from '../../../common/constants/runtime';\nimport { stringify } from '../../../common/util/stringify';\nexport class DT {\n constructor(agentIdentifier) {\n this.agentIdentifier = agentIdentifier;\n }\n generateTracePayload(parsedOrigin) {\n if (!this.shouldGenerateTrace(parsedOrigin)) {\n return null;\n }\n var loaderConfig = getLoaderConfig(this.agentIdentifier);\n if (!loaderConfig) {\n return null;\n }\n var accountId = (loaderConfig.accountID || '').toString() || null;\n var agentId = (loaderConfig.agentID || '').toString() || null;\n var trustKey = (loaderConfig.trustKey || '').toString() || null;\n if (!accountId || !agentId) {\n return null;\n }\n var spanId = generateSpanId();\n var traceId = generateTraceId();\n var timestamp = Date.now();\n var payload = {\n spanId,\n traceId,\n timestamp\n };\n if (parsedOrigin.sameOrigin || this.isAllowedOrigin(parsedOrigin) && this.useTraceContextHeadersForCors()) {\n payload.traceContextParentHeader = this.generateTraceContextParentHeader(spanId, traceId);\n payload.traceContextStateHeader = this.generateTraceContextStateHeader(spanId, timestamp, accountId, agentId, trustKey);\n }\n if (parsedOrigin.sameOrigin && !this.excludeNewrelicHeader() || !parsedOrigin.sameOrigin && this.isAllowedOrigin(parsedOrigin) && this.useNewrelicHeaderForCors()) {\n payload.newrelicHeader = this.generateTraceHeader(spanId, traceId, timestamp, accountId, agentId, trustKey);\n }\n return payload;\n }\n generateTraceContextParentHeader(spanId, traceId) {\n return '00-' + traceId + '-' + spanId + '-01';\n }\n generateTraceContextStateHeader(spanId, timestamp, accountId, appId, trustKey) {\n var version = 0;\n var transactionId = '';\n var parentType = 1;\n var sampled = '';\n var priority = '';\n return trustKey + '@nr=' + version + '-' + parentType + '-' + accountId + '-' + appId + '-' + spanId + '-' + transactionId + '-' + sampled + '-' + priority + '-' + timestamp;\n }\n generateTraceHeader(spanId, traceId, timestamp, accountId, appId, trustKey) {\n var hasBtoa = typeof globalScope?.btoa === 'function';\n if (!hasBtoa) {\n return null;\n }\n var payload = {\n v: [0, 1],\n d: {\n ty: 'Browser',\n ac: accountId,\n ap: appId,\n id: spanId,\n tr: traceId,\n ti: timestamp\n }\n };\n if (trustKey && accountId !== trustKey) {\n payload.d.tk = trustKey;\n }\n return btoa(stringify(payload));\n }\n\n // return true if DT is enabled and the origin is allowed, either by being\n // same-origin, or included in the allowed list\n shouldGenerateTrace(parsedOrigin) {\n return this.isDtEnabled() && this.isAllowedOrigin(parsedOrigin);\n }\n isAllowedOrigin(parsedOrigin) {\n var allowed = false;\n var dtConfig = {};\n var dt = getConfigurationValue(this.agentIdentifier, 'distributed_tracing');\n if (dt) {\n dtConfig = getConfiguration(this.agentIdentifier).distributed_tracing;\n }\n if (parsedOrigin.sameOrigin) {\n allowed = true;\n } else if (dtConfig.allowed_origins instanceof Array) {\n for (var i = 0; i < dtConfig.allowed_origins.length; i++) {\n var allowedOrigin = parseUrl(dtConfig.allowed_origins[i]);\n if (parsedOrigin.hostname === allowedOrigin.hostname && parsedOrigin.protocol === allowedOrigin.protocol && parsedOrigin.port === allowedOrigin.port) {\n allowed = true;\n break;\n }\n }\n }\n return allowed;\n }\n isDtEnabled() {\n var dt = getConfigurationValue(this.agentIdentifier, 'distributed_tracing');\n if (dt) {\n return !!dt.enabled;\n }\n return false;\n }\n\n // exclude the newrelic header for same-origin calls\n excludeNewrelicHeader() {\n var dt = getConfigurationValue(this.agentIdentifier, 'distributed_tracing');\n if (dt) {\n return !!dt.exclude_newrelic_header;\n }\n return false;\n }\n useNewrelicHeaderForCors() {\n var dt = getConfigurationValue(this.agentIdentifier, 'distributed_tracing');\n if (dt) {\n return dt.cors_use_newrelic_header !== false;\n }\n return false;\n }\n useTraceContextHeadersForCors() {\n var dt = getConfigurationValue(this.agentIdentifier, 'distributed_tracing');\n if (dt) {\n return !!dt.cors_use_tracecontext_headers;\n }\n return false;\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { gosNREUMOriginals } from '../../../common/window/nreum';\nimport { handle } from '../../../common/event-emitter/handle';\nimport { id } from '../../../common/ids/id';\nimport { ffVersion, globalScope, isBrowserScope } from '../../../common/constants/runtime';\nimport { dataSize } from '../../../common/util/data-size';\nimport { eventListenerOpts } from '../../../common/event-listener/event-listener-opts';\nimport { wrapXhr } from '../../../common/wrap/wrap-xhr';\nimport { wrapFetch } from '../../../common/wrap/wrap-fetch';\nimport { parseUrl } from '../../../common/url/parse-url';\nimport { DT } from './distributed-tracing';\nimport { responseSizeFromXhr } from './response-size';\nimport { InstrumentBase } from '../../utils/instrument-base';\nimport { FEATURE_NAME } from '../constants';\nimport { FEATURE_NAMES } from '../../../loaders/features/features';\nimport { SUPPORTABILITY_METRIC } from '../../metrics/constants';\nimport { now } from '../../../common/timing/now';\nimport { hasUndefinedHostname } from '../../../common/deny-list/deny-list';\nvar handlers = ['load', 'error', 'abort', 'timeout'];\nvar handlersLen = handlers.length;\nvar origRequest = gosNREUMOriginals().o.REQ;\nvar origXHR = gosNREUMOriginals().o.XHR;\nexport class Instrument extends InstrumentBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef, auto = true) {\n super(agentRef, FEATURE_NAME, auto);\n this.dt = new DT(agentRef.agentIdentifier);\n this.handler = (type, args, ctx, group) => handle(type, args, ctx, group, this.ee);\n\n // this is a best (but imperfect) effort at capturing AJAX calls that may have fired before the agent was instantiated\n // this could happen because the agent was \"improperly\" set up (ie, not at the top of the head) or\n // because it was deferred from loading in some way -- e.g. 'deferred' script loading tags or other lazy-loading techniques\n //\n // it is \"imperfect\" because we cannot capture the following with the API vs wrapping the events directly:\n // * requestBodySize - (txSize -- request body size)\n // * method - request type (GET, POST, etc)\n // * callbackDuration - (cbTime -- sum of resulting callback time)\n try {\n const initiators = {\n xmlhttprequest: 'xhr',\n fetch: 'fetch',\n beacon: 'beacon'\n };\n globalScope?.performance?.getEntriesByType('resource').forEach(resource => {\n if (resource.initiatorType in initiators && resource.responseStatus !== 0) {\n const params = {\n status: resource.responseStatus\n };\n const metrics = {\n rxSize: resource.transferSize,\n duration: Math.floor(resource.duration),\n cbTime: 0\n };\n addUrl(params, resource.name);\n this.handler('xhr', [params, metrics, resource.startTime, resource.responseEnd, initiators[resource.initiatorType]], undefined, FEATURE_NAMES.ajax);\n }\n });\n } catch (err) {\n // do nothing\n }\n wrapFetch(this.ee);\n wrapXhr(this.ee);\n subscribeToEvents(agentRef, this.ee, this.handler, this.dt);\n this.importAggregator(agentRef);\n }\n}\nfunction subscribeToEvents(agentRef, ee, handler, dt) {\n ee.on('new-xhr', onNewXhr);\n ee.on('open-xhr-start', onOpenXhrStart);\n ee.on('open-xhr-end', onOpenXhrEnd);\n ee.on('send-xhr-start', onSendXhrStart);\n ee.on('xhr-cb-time', onXhrCbTime);\n ee.on('xhr-load-added', onXhrLoadAdded);\n ee.on('xhr-load-removed', onXhrLoadRemoved);\n ee.on('xhr-resolved', onXhrResolved);\n ee.on('addEventListener-end', onAddEventListenerEnd);\n ee.on('removeEventListener-end', onRemoveEventListenerEnd);\n ee.on('fn-end', onFnEnd);\n ee.on('fetch-before-start', onFetchBeforeStart);\n ee.on('fetch-start', onFetchStart);\n ee.on('fn-start', onFnStart);\n ee.on('fetch-done', onFetchDone);\n\n // Setup the context for each new xhr object\n function onNewXhr(xhr) {\n var ctx = this;\n ctx.totalCbs = 0;\n ctx.called = 0;\n ctx.cbTime = 0;\n ctx.end = end;\n ctx.ended = false;\n ctx.xhrGuids = {};\n ctx.lastSize = null;\n ctx.loadCaptureCalled = false;\n ctx.params = this.params || {};\n ctx.metrics = this.metrics || {};\n xhr.addEventListener('load', function (event) {\n captureXhrData(ctx, xhr);\n }, eventListenerOpts(false));\n\n // In Firefox (v34+), XHR ProgressEvents report pre-content-decoding sizes via\n // their 'loaded' property, rather than post-decoding sizes. We want\n // post-decoding sizes for consistency with browsers where that's all we have.\n // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1227674\n //\n // So we don't use ProgressEvents to measure XHR sizes for FF.\n if (ffVersion) return;\n xhr.addEventListener('progress', function (event) {\n ctx.lastSize = event.loaded;\n }, eventListenerOpts(false));\n }\n function onOpenXhrStart(args) {\n this.params = {\n method: args[0]\n };\n addUrl(this, args[1]);\n this.metrics = {};\n }\n function onOpenXhrEnd(args, xhr) {\n if (agentRef.loader_config.xpid && this.sameOrigin) {\n xhr.setRequestHeader('X-NewRelic-ID', agentRef.loader_config.xpid);\n }\n var payload = dt.generateTracePayload(this.parsedOrigin);\n if (payload) {\n var added = false;\n if (payload.newrelicHeader) {\n xhr.setRequestHeader('newrelic', payload.newrelicHeader);\n added = true;\n }\n if (payload.traceContextParentHeader) {\n xhr.setRequestHeader('traceparent', payload.traceContextParentHeader);\n if (payload.traceContextStateHeader) {\n xhr.setRequestHeader('tracestate', payload.traceContextStateHeader);\n }\n added = true;\n }\n if (added) {\n this.dt = payload;\n }\n }\n }\n function onSendXhrStart(args, xhr) {\n var metrics = this.metrics;\n var data = args[0];\n var context = this;\n if (metrics && data) {\n var size = dataSize(data);\n if (size) metrics.txSize = size;\n }\n this.startTime = now();\n this.body = data;\n this.listener = function (evt) {\n try {\n if (evt.type === 'abort' && !context.loadCaptureCalled) {\n context.params.aborted = true;\n }\n if (evt.type !== 'load' || context.called === context.totalCbs && (context.onloadCalled || typeof xhr.onload !== 'function') && typeof context.end === 'function') context.end(xhr);\n } catch (e) {\n try {\n ee.emit('internal-error', [e]);\n } catch (err) {\n // do nothing\n }\n }\n };\n for (var i = 0; i < handlersLen; i++) {\n xhr.addEventListener(handlers[i], this.listener, eventListenerOpts(false));\n }\n }\n function onXhrCbTime(time, onload, xhr) {\n this.cbTime += time;\n if (onload) this.onloadCalled = true;else this.called += 1;\n if (this.called === this.totalCbs && (this.onloadCalled || typeof xhr.onload !== 'function') && typeof this.end === 'function') this.end(xhr);\n }\n function onXhrLoadAdded(cb, useCapture) {\n // Ignore if the same arguments are passed to addEventListener twice\n var idString = '' + id(cb) + !!useCapture;\n if (!this.xhrGuids || this.xhrGuids[idString]) return;\n this.xhrGuids[idString] = true;\n this.totalCbs += 1;\n }\n function onXhrLoadRemoved(cb, useCapture) {\n // Ignore if event listener didn't exist for this xhr object\n var idString = '' + id(cb) + !!useCapture;\n if (!this.xhrGuids || !this.xhrGuids[idString]) return;\n delete this.xhrGuids[idString];\n this.totalCbs -= 1;\n }\n function onXhrResolved() {\n this.endTime = now();\n }\n\n // Listen for load listeners to be added to xhr objects\n function onAddEventListenerEnd(args, xhr) {\n if (xhr instanceof origXHR && args[0] === 'load') ee.emit('xhr-load-added', [args[1], args[2]], xhr);\n }\n function onRemoveEventListenerEnd(args, xhr) {\n if (xhr instanceof origXHR && args[0] === 'load') ee.emit('xhr-load-removed', [args[1], args[2]], xhr);\n }\n\n // Listen for those load listeners to be called.\n function onFnStart(args, xhr, methodName) {\n if (xhr instanceof origXHR) {\n if (methodName === 'onload') this.onload = true;\n if ((args[0] && args[0].type) === 'load' || this.onload) this.xhrCbStart = now();\n }\n }\n function onFnEnd(args, xhr) {\n if (this.xhrCbStart) ee.emit('xhr-cb-time', [now() - this.xhrCbStart, this.onload, xhr], xhr);\n }\n\n // this event only handles DT\n function onFetchBeforeStart(args) {\n var opts = args[1] || {};\n var url;\n if (typeof args[0] === 'string') {\n // argument is USVString\n url = args[0];\n if (url.length === 0 && isBrowserScope) {\n url = '' + globalScope.location.href;\n }\n } else if (args[0] && args[0].url) {\n // argument is Request object\n url = args[0].url;\n } else if (globalScope?.URL && args[0] && args[0] instanceof URL) {\n // argument is URL object\n url = args[0].href;\n } else if (typeof args[0].toString === 'function') {\n url = args[0].toString();\n }\n if (typeof url !== 'string' || url.length === 0) {\n // Short-circuit DT since we could not determine the URL of the fetch call\n // this is very unlikely to happen\n return;\n }\n if (url) {\n this.parsedOrigin = parseUrl(url);\n this.sameOrigin = this.parsedOrigin.sameOrigin;\n }\n var payload = dt.generateTracePayload(this.parsedOrigin);\n if (!payload || !payload.newrelicHeader && !payload.traceContextParentHeader) {\n return;\n }\n if (args[0] && args[0].headers) {\n if (addHeaders(args[0].headers, payload)) {\n this.dt = payload;\n }\n } else {\n var clone = {};\n for (var key in opts) {\n clone[key] = opts[key];\n }\n clone.headers = new Headers(opts.headers || {});\n if (addHeaders(clone.headers, payload)) {\n this.dt = payload;\n }\n if (args.length > 1) {\n args[1] = clone;\n } else {\n args.push(clone);\n }\n }\n function addHeaders(headersObj, payload) {\n var added = false;\n if (payload.newrelicHeader) {\n headersObj.set('newrelic', payload.newrelicHeader);\n added = true;\n }\n if (payload.traceContextParentHeader) {\n headersObj.set('traceparent', payload.traceContextParentHeader);\n if (payload.traceContextStateHeader) {\n headersObj.set('tracestate', payload.traceContextStateHeader);\n }\n added = true;\n }\n return added;\n }\n }\n function onFetchStart(fetchArguments, dtPayload) {\n this.params = {};\n this.metrics = {};\n this.startTime = now();\n this.dt = dtPayload;\n if (fetchArguments.length >= 1) this.target = fetchArguments[0];\n if (fetchArguments.length >= 2) this.opts = fetchArguments[1];\n var opts = this.opts || {};\n var target = this.target;\n var url;\n if (typeof target === 'string') {\n url = target;\n } else if (typeof target === 'object' && target instanceof origRequest) {\n url = target.url;\n } else if (globalScope?.URL && typeof target === 'object' && target instanceof URL) {\n url = target.href;\n }\n addUrl(this, url);\n var method = ('' + (target && target instanceof origRequest && target.method || opts.method || 'GET')).toUpperCase();\n this.params.method = method;\n this.body = opts.body;\n this.txSize = dataSize(opts.body) || 0;\n }\n\n // we capture failed call as status 0, the actual error is ignored\n // eslint-disable-next-line handle-callback-err\n function onFetchDone(_, res) {\n this.endTime = now();\n if (!this.params) this.params = {};\n if (hasUndefinedHostname(this.params)) return; // don't bother with fetch to url with no hostname\n\n this.params.status = res ? res.status : 0;\n\n // convert rxSize to a number\n let responseSize;\n if (typeof this.rxSize === 'string' && this.rxSize.length > 0) {\n responseSize = +this.rxSize;\n }\n const metrics = {\n txSize: this.txSize,\n rxSize: responseSize,\n duration: now() - this.startTime\n };\n handler('xhr', [this.params, metrics, this.startTime, this.endTime, 'fetch'], this, FEATURE_NAMES.ajax);\n }\n\n // Create report for XHR request that has finished\n function end(xhr) {\n const params = this.params;\n const metrics = this.metrics;\n if (this.ended) return;\n this.ended = true;\n for (let i = 0; i < handlersLen; i++) {\n xhr.removeEventListener(handlers[i], this.listener, false);\n }\n if (params.aborted) return;\n if (hasUndefinedHostname(params)) return; // don't bother with XHR of url with no hostname\n\n metrics.duration = now() - this.startTime;\n if (!this.loadCazptureCalled && xhr.readyState === 4) {\n captureXhrData(this, xhr);\n } else if (params.status == null) {\n params.status = 0;\n }\n\n // Always send cbTime, even if no noticeable time was taken.\n metrics.cbTime = this.cbTime;\n handler('xhr', [params, metrics, this.startTime, this.endTime, 'xhr'], this, FEATURE_NAMES.ajax);\n }\n function captureXhrData(ctx, xhr) {\n ctx.params.status = xhr.status;\n var size = responseSizeFromXhr(xhr, ctx.lastSize);\n if (size) ctx.metrics.rxSize = size;\n if (ctx.sameOrigin) {\n var header = xhr.getResponseHeader('X-NewRelic-App-Data');\n if (header) {\n handle(SUPPORTABILITY_METRIC, ['Ajax/CrossApplicationTracing/Header/Seen'], undefined, FEATURE_NAMES.metrics, ee);\n ctx.params.cat = header.split(', ').pop();\n }\n }\n ctx.loadCaptureCalled = true;\n }\n}\nfunction addUrl(ctx, url) {\n var parsed = parseUrl(url);\n var params = ctx.params || ctx;\n params.hostname = parsed.hostname;\n params.port = parsed.port;\n params.protocol = parsed.protocol;\n params.host = parsed.hostname + ':' + parsed.port;\n params.pathname = parsed.pathname;\n ctx.parsedOrigin = parsed;\n ctx.sameOrigin = parsed.sameOrigin;\n}\nexport const Ajax = Instrument;","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { dataSize } from '../../../common/util/data-size';\nexport function responseSizeFromXhr(xhr, lastSize) {\n var type = xhr.responseType;\n if (type === 'json' && lastSize !== null) return lastSize;\n // Caution! Chrome throws an error if you try to access xhr.responseText for binary data\n if (type === 'arraybuffer' || type === 'blob' || type === 'json') {\n return dataSize(xhr.response);\n } else if (type === 'text' || type === '' || type === undefined) {\n // empty string type defaults to 'text'\n return dataSize(xhr.responseText);\n } else {\n // e.g. ms-stream and document (we do not currently determine the size of Document objects)\n return undefined;\n }\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Wraps `pushState` and `replaceState` methods of `window.history` object for instrumentation.\n * This module is used by: session_trace, spa.\n */\nimport { ee as globalEE } from '../event-emitter/contextual-ee';\nimport { createWrapperWithEmitter as wfn } from './wrap-function';\nimport { isBrowserScope } from '../constants/runtime';\nconst wrapped = {};\nconst HISTORY_FNS = ['pushState', 'replaceState'];\n\n/**\n * Wraps the `pushState` and `replaceState` methods of `window.history` and returns a corresponding event emitter\n * scoped to the history object.\n * @param {Object} sharedEE - The shared event emitter on which a new scoped event emitter will be based.\n * @returns {Object} Scoped event emitter with a debug ID of `history`.\n */\nexport function wrapHistory(sharedEE) {\n const ee = scopedEE(sharedEE);\n\n // Notice if our wrapping never ran yet, the falsy NaN will not early return; but if it has,\n // then we increment the count to track # of feats using this at runtime. History API is only\n // available in browser DOM context.\n if (!isBrowserScope || wrapped[ee.debugId]++) return ee;\n wrapped[ee.debugId] = 1; // otherwise, first feature to wrap history\n\n var wrapFn = wfn(ee);\n /*\n * For objects that will be instantiated more than once, we wrap the object's prototype methods. The history object\n * is instantiated only once, so we can wrap its methods directly--and we must wrap the history methods directly as\n * long as [Chromium issue 783382](https://bugs.chromium.org/p/chromium/issues/detail?id=783382) remains unresolved.\n */\n wrapFn.inPlace(window.history, HISTORY_FNS, '-');\n return ee;\n}\n\n/**\n * Returns an event emitter scoped specifically for the `history` context. This scoping is a remnant from when all the\n * features shared the same group in the event, to isolate events between features. It will likely be revisited.\n * @param {Object} sharedEE - Optional event emitter on which to base the scoped emitter.\n * Uses `ee` on the global scope if undefined).\n * @returns {Object} Scoped event emitter with a debug ID of 'history'.\n */\nexport function scopedEE(sharedEE) {\n return (sharedEE || globalEE).get('history');\n}","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { handle } from '../../../common/event-emitter/handle';\nimport { wrapHistory } from '../../../common/wrap/wrap-history';\nimport { wrapEvents } from '../../../common/wrap/wrap-events';\nimport { InstrumentBase } from '../../utils/instrument-base';\nimport * as CONSTANTS from '../constants';\nimport { FEATURE_NAMES } from '../../../loaders/features/features';\nimport { canEnableSessionTracking } from '../../utils/feature-gates';\nimport { now } from '../../../common/timing/now';\nconst {\n BST_RESOURCE,\n RESOURCE,\n START,\n END,\n FEATURE_NAME,\n FN_END,\n FN_START,\n PUSH_STATE\n} = CONSTANTS;\nexport class Instrument extends InstrumentBase {\n static featureName = FEATURE_NAME;\n constructor(agentRef, auto = true) {\n super(agentRef, FEATURE_NAME, auto);\n const canTrackSession = canEnableSessionTracking(this.agentIdentifier);\n if (!canTrackSession) {\n this.deregisterDrain();\n return;\n }\n const thisInstrumentEE = this.ee;\n wrapHistory(thisInstrumentEE);\n this.eventsEE = wrapEvents(thisInstrumentEE);\n this.eventsEE.on(FN_START, function (args, target) {\n this.bstStart = now();\n });\n this.eventsEE.on(FN_END, function (args, target) {\n // ISSUE: when target is XMLHttpRequest, nr@context should have params so we can calculate event origin\n // When ajax is disabled, this may fail without making ajax a dependency of session_trace\n handle('bst', [args[0], target, this.bstStart, now()], undefined, FEATURE_NAMES.sessionTrace, thisInstrumentEE);\n });\n thisInstrumentEE.on(PUSH_STATE + START, function (args) {\n this.time = now();\n this.startPath = location.pathname + location.hash;\n });\n thisInstrumentEE.on(PUSH_STATE + END, function (args) {\n handle('bstHist', [location.pathname + location.hash, this.startPath, this.time], undefined, FEATURE_NAMES.sessionTrace, thisInstrumentEE);\n });\n let observer;\n try {\n // Capture initial resources and watch for future ones. Don't defer this given there's a default cap on the number of buffered entries.\n observer = new PerformanceObserver(list => {\n // eslint-disable-line no-undef\n const entries = list.getEntries();\n handle(BST_RESOURCE, [entries], undefined, FEATURE_NAMES.sessionTrace, thisInstrumentEE);\n });\n observer.observe({\n type: RESOURCE,\n buffered: true\n });\n } catch (e) {\n // Per NEWRELIC-8525, we don't have a fallback for capturing resources for older versions that don't support PO at this time.\n }\n this.importAggregator(agentRef, {\n resourceObserver: observer\n });\n }\n}\nexport const SessionTrace = Instrument;","/*\n * Copyright 2020 New Relic Corporation. All rights reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n/**\n * @file Wraps DOM insertion methods which in turn wrap JSONP functions that show up in the DOM.\n * This module is used by: spa.\n */\n\nimport { eventListenerOpts } from '../event-listener/event-listener-opts';\nimport { ee as baseEE } from '../event-emitter/contextual-ee';\nimport { createWrapperWithEmitter as wfn } from './wrap-function';\nimport { isBrowserScope } from '../constants/runtime';\nconst wrapped = {};\nconst domInsertMethods = ['appendChild', 'insertBefore', 'replaceChild'];\n\n/**\n * Wraps DOM insertion methods to identify script elements containing JSONP callback functions and instruments those\n * functions with custom events in the context of a new event emitter scoped only to JSONP.\n * @param {Object} sharedEE - The shared event emitter on which a new scoped event emitter will be based.\n * @returns {Object} Scoped event emitter with a debug ID of `jsonp`.\n */\nexport function wrapJsonP(sharedEE) {\n const ee = scopedEE(sharedEE);\n\n // Notice if our wrapping never ran yet, the falsy NaN will not early return; but if it has,\n // then we increment the count to track # of feats using this at runtime. JSONP deals with DOM\n // tags so browser window env is required.\n if (!isBrowserScope || wrapped[ee.debugId]) return ee;\n wrapped[ee.debugId] = true; // otherwise, first feature to wrap JSONP\n\n var wrapFn = wfn(ee);\n var CALLBACK_REGEX = /[?&](?:callback|cb)=([^&#]+)/;\n var PARENT_REGEX = /(.*)\\.([^.]+)/;\n var VALUE_REGEX = /^(\\w+)(\\.|$)(.*)$/;\n\n // JSONP works by dynamically inserting