@npaw/forge-web 9.7.5 → 10.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -29,6 +29,225 @@ function isCapturePlanEnabled(bits, bit) {
29
29
  return (bits & bit) !== 0;
30
30
  }
31
31
 
32
+ // src/network-timing.ts
33
+ var DEFAULT_MATCH_TOLERANCE_MS = 250;
34
+ var DEFAULT_MATCH_TIMEOUT_MS = 2e3;
35
+ var DEFAULT_MAX_PENDING = 256;
36
+ function phaseMs(end, start) {
37
+ if (!Number.isFinite(end) || !Number.isFinite(start)) {
38
+ return void 0;
39
+ }
40
+ if (start <= 0) {
41
+ return void 0;
42
+ }
43
+ const delta = end - start;
44
+ if (!Number.isFinite(delta) || delta <= 0) {
45
+ return void 0;
46
+ }
47
+ return Math.round(delta);
48
+ }
49
+ function nonNegativeMs(value) {
50
+ if (!Number.isFinite(value) || value < 0) {
51
+ return void 0;
52
+ }
53
+ return Math.round(value);
54
+ }
55
+ function positiveBytes(value) {
56
+ if (!Number.isFinite(value) || value <= 0) {
57
+ return void 0;
58
+ }
59
+ return Math.round(value);
60
+ }
61
+ function timingFieldsFromResourceEntry(entry) {
62
+ var _a, _b;
63
+ const fields = {};
64
+ const duration = nonNegativeMs(entry.duration);
65
+ if (duration !== void 0) {
66
+ fields.durationMs = duration;
67
+ }
68
+ const timeToFirstByteMs = (_a = phaseMs(entry.responseStart, entry.requestStart)) != null ? _a : phaseMs(entry.responseStart, entry.startTime);
69
+ if (timeToFirstByteMs !== void 0) {
70
+ fields.timeToFirstByteMs = timeToFirstByteMs;
71
+ }
72
+ const dnsDurationMs = phaseMs(entry.domainLookupEnd, entry.domainLookupStart);
73
+ if (dnsDurationMs !== void 0) {
74
+ fields.dnsDurationMs = dnsDurationMs;
75
+ }
76
+ const connectDurationMs = phaseMs(entry.connectEnd, entry.connectStart);
77
+ if (connectDurationMs !== void 0) {
78
+ fields.connectDurationMs = connectDurationMs;
79
+ }
80
+ const sslDurationMs = phaseMs(entry.connectEnd, entry.secureConnectionStart);
81
+ if (sslDurationMs !== void 0) {
82
+ fields.sslDurationMs = sslDurationMs;
83
+ }
84
+ const responseDownloadDurationMs = phaseMs(entry.responseEnd, entry.responseStart);
85
+ if (responseDownloadDurationMs !== void 0) {
86
+ fields.responseDownloadDurationMs = responseDownloadDurationMs;
87
+ }
88
+ const redirectDurationMs = phaseMs(entry.redirectEnd, entry.redirectStart);
89
+ if (redirectDurationMs !== void 0) {
90
+ fields.redirectDurationMs = redirectDurationMs;
91
+ fields.redirectCount = 1;
92
+ }
93
+ if (typeof entry.nextHopProtocol === "string" && entry.nextHopProtocol.length > 0) {
94
+ fields.protocol = entry.nextHopProtocol;
95
+ }
96
+ const responseBytes = (_b = positiveBytes(entry.transferSize)) != null ? _b : positiveBytes(entry.encodedBodySize);
97
+ if (responseBytes !== void 0) {
98
+ fields.responseBytes = responseBytes;
99
+ }
100
+ return fields;
101
+ }
102
+ function timingMatchKey(url) {
103
+ var _a, _b;
104
+ const withoutFragment = (_a = url.split("#")[0]) != null ? _a : url;
105
+ return (_b = withoutFragment.split("?")[0]) != null ? _b : withoutFragment;
106
+ }
107
+ var ResourceTimingCorrelator = class {
108
+ constructor(options) {
109
+ this.options = options;
110
+ this.pending = /* @__PURE__ */ new Map();
111
+ this.pendingCount = 0;
112
+ this.disposed = false;
113
+ var _a, _b, _c;
114
+ this.toleranceMs = (_a = options.toleranceMs) != null ? _a : DEFAULT_MATCH_TOLERANCE_MS;
115
+ this.timeoutMs = (_b = options.timeoutMs) != null ? _b : DEFAULT_MATCH_TIMEOUT_MS;
116
+ this.maxPending = (_c = options.maxPending) != null ? _c : DEFAULT_MAX_PENDING;
117
+ try {
118
+ this.observer = options.observerFactory((entries) => this.onEntries(entries));
119
+ } catch (e) {
120
+ this.observer = void 0;
121
+ }
122
+ }
123
+ /** True when correlation is actually available; false means timeout-only. */
124
+ get active() {
125
+ return this.observer !== void 0;
126
+ }
127
+ track(observation, url, startedAtMs) {
128
+ if (this.disposed || !this.observer) {
129
+ this.options.emit(observation);
130
+ return;
131
+ }
132
+ const key = timingMatchKey(url);
133
+ const record = {
134
+ key,
135
+ startedAtMs,
136
+ observation,
137
+ timer: void 0,
138
+ emitted: false
139
+ };
140
+ record.timer = this.options.setTimer(() => this.flush(record, false), this.timeoutMs);
141
+ const bucket = this.pending.get(key);
142
+ if (bucket) {
143
+ bucket.push(record);
144
+ } else {
145
+ this.pending.set(key, [record]);
146
+ }
147
+ this.pendingCount += 1;
148
+ this.evictOverflow();
149
+ }
150
+ dispose() {
151
+ var _a;
152
+ this.disposed = true;
153
+ try {
154
+ (_a = this.observer) == null ? void 0 : _a.disconnect();
155
+ } catch (e) {
156
+ }
157
+ for (const bucket of [...this.pending.values()]) {
158
+ for (const record of [...bucket]) {
159
+ this.flush(record, false);
160
+ }
161
+ }
162
+ this.pending.clear();
163
+ this.pendingCount = 0;
164
+ }
165
+ onEntries(entries) {
166
+ for (const entry of entries) {
167
+ if (!entry || entry.entryType !== "resource") {
168
+ continue;
169
+ }
170
+ const record = this.take(entry);
171
+ if (!record) {
172
+ continue;
173
+ }
174
+ Object.assign(record.observation, timingFieldsFromResourceEntry(entry));
175
+ this.flush(record, true);
176
+ }
177
+ }
178
+ /**
179
+ * Pairs an entry with the closest pending observation for the same URL whose
180
+ * start time falls inside the tolerance window. Matching on start time as
181
+ * well as URL is what keeps concurrent requests to one endpoint apart.
182
+ */
183
+ take(entry) {
184
+ const bucket = this.pending.get(timingMatchKey(entry.name));
185
+ if (!bucket || bucket.length === 0) {
186
+ return void 0;
187
+ }
188
+ let best;
189
+ let bestDistance = Number.POSITIVE_INFINITY;
190
+ for (const record of bucket) {
191
+ if (record.emitted) {
192
+ continue;
193
+ }
194
+ const distance = Math.abs(record.startedAtMs - entry.startTime);
195
+ if (distance < bestDistance) {
196
+ bestDistance = distance;
197
+ best = record;
198
+ }
199
+ }
200
+ return bestDistance > this.toleranceMs ? void 0 : best;
201
+ }
202
+ flush(record, matched) {
203
+ var _a, _b;
204
+ if (record.emitted) {
205
+ return;
206
+ }
207
+ record.emitted = true;
208
+ this.detach(record);
209
+ this.options.clearTimer(record.timer);
210
+ if (!matched) {
211
+ (_b = (_a = this.options).onUnmatched) == null ? void 0 : _b.call(_a, record.observation);
212
+ }
213
+ this.options.emit(record.observation);
214
+ }
215
+ detach(record) {
216
+ const bucket = this.pending.get(record.key);
217
+ if (!bucket) {
218
+ return;
219
+ }
220
+ const index = bucket.indexOf(record);
221
+ if (index >= 0) {
222
+ bucket.splice(index, 1);
223
+ this.pendingCount -= 1;
224
+ }
225
+ if (bucket.length === 0) {
226
+ this.pending.delete(record.key);
227
+ }
228
+ }
229
+ evictOverflow() {
230
+ while (this.pendingCount > this.maxPending) {
231
+ const oldest = this.oldestRecord();
232
+ if (!oldest) {
233
+ return;
234
+ }
235
+ this.flush(oldest, false);
236
+ }
237
+ }
238
+ oldestRecord() {
239
+ let oldest;
240
+ for (const bucket of this.pending.values()) {
241
+ for (const record of bucket) {
242
+ if (!oldest || record.startedAtMs < oldest.startedAtMs) {
243
+ oldest = record;
244
+ }
245
+ }
246
+ }
247
+ return oldest;
248
+ }
249
+ };
250
+
32
251
  // src/sections-capture.ts
33
252
  var DEFAULT_VISIBILITY_THRESHOLD_PCT = 50;
34
253
  var DEFAULT_IMPRESSION_MIN_VISIBLE_MS = 1e3;
@@ -1606,6 +1825,8 @@ var BrowserCapture = class {
1606
1825
  this.featureDisposers = /* @__PURE__ */ new Map();
1607
1826
  this.lastScrollAtMs = 0;
1608
1827
  this.disposed = false;
1828
+ /** Observations emitted on wrapper timing because no entry ever matched. */
1829
+ this.unmatchedNetworkTimings = 0;
1609
1830
  this.initialNavigationReported = false;
1610
1831
  this.attributionReported = false;
1611
1832
  this.foregroundCount = 0;
@@ -2214,6 +2435,7 @@ var BrowserCapture = class {
2214
2435
  sink.push(() => {
2215
2436
  generation.active = false;
2216
2437
  });
2438
+ this.installResourceTimingCorrelator(sink);
2217
2439
  if (this.options.network.fetch) {
2218
2440
  this.patchFetch(sink, generation);
2219
2441
  }
@@ -2221,6 +2443,60 @@ var BrowserCapture = class {
2221
2443
  this.patchXmlHttpRequest(sink, generation);
2222
2444
  }
2223
2445
  }
2446
+ /**
2447
+ * The wrappers cannot see connection phases, protocol, or a duration free of
2448
+ * JS scheduling — and a `fetch` promise resolves at headers, so timing it
2449
+ * yields time-to-first-byte rather than duration. The correlator holds each
2450
+ * observation until its Resource Timing entry arrives and merges the two.
2451
+ */
2452
+ installResourceTimingCorrelator(sink) {
2453
+ const factory = this.resourceTimingObserverFactory();
2454
+ if (!factory) {
2455
+ return;
2456
+ }
2457
+ const correlator = new ResourceTimingCorrelator({
2458
+ emit: (observation) => safeCaptureCall(() => this.host.trackNetworkEvent(observation)),
2459
+ observerFactory: factory,
2460
+ setTimer: (callback, delayMs) => this.timers().setTimeout(callback, delayMs),
2461
+ clearTimer: (handle) => this.timers().clearTimeout(handle),
2462
+ onUnmatched: () => {
2463
+ this.unmatchedNetworkTimings += 1;
2464
+ }
2465
+ });
2466
+ if (!correlator.active) {
2467
+ return;
2468
+ }
2469
+ this.networkTimingCorrelator = correlator;
2470
+ sink.push(() => {
2471
+ this.networkTimingCorrelator = void 0;
2472
+ correlator.dispose();
2473
+ });
2474
+ }
2475
+ /**
2476
+ * Prefers an injected factory (tests, non-browser hosts) and otherwise builds
2477
+ * one over `PerformanceObserver`. An observer is used rather than
2478
+ * `getEntriesByType` because the resource buffer caps at 250 entries by
2479
+ * default: a long-lived SPA silently drops the rest, whereas an observer is
2480
+ * handed every entry once as it is recorded.
2481
+ */
2482
+ resourceTimingObserverFactory() {
2483
+ const injected = this.options.environment.resourceTimingObserverFactory;
2484
+ if (injected) {
2485
+ return injected;
2486
+ }
2487
+ const windowRef = this.window();
2488
+ const ObserverCtor = windowRef == null ? void 0 : windowRef.PerformanceObserver;
2489
+ if (typeof ObserverCtor !== "function") {
2490
+ return void 0;
2491
+ }
2492
+ return (callback) => {
2493
+ const observer = new ObserverCtor((list) => {
2494
+ callback(list.getEntries());
2495
+ });
2496
+ observer.observe({ type: "resource", buffered: true });
2497
+ return observer;
2498
+ };
2499
+ }
2224
2500
  installWebVitalsCapture(sink) {
2225
2501
  const handle = installWebVitalsCapture(this.host, this.options);
2226
2502
  sink.push(() => handle.dispose());
@@ -2501,6 +2777,11 @@ var BrowserCapture = class {
2501
2777
  if (Object.keys(responseHeaders).length > 0) {
2502
2778
  observation.responseHeaders = responseHeaders;
2503
2779
  }
2780
+ const correlator = this.networkTimingCorrelator;
2781
+ if (correlator) {
2782
+ correlator.track(observation, metadata.targetUrl, startedAt.elapsedMs);
2783
+ return;
2784
+ }
2504
2785
  safeCaptureCall(() => this.host.trackNetworkEvent(observation));
2505
2786
  }
2506
2787
  emitRawEvent(name, params = {}, presanitized) {
@@ -3606,6 +3887,9 @@ function requestBody(request) {
3606
3887
  if (request.bodyBytes !== void 0) {
3607
3888
  return new Uint8Array(request.bodyBytes);
3608
3889
  }
3890
+ if (request.bodyText !== void 0) {
3891
+ return request.bodyText;
3892
+ }
3609
3893
  if (request.body !== void 0) {
3610
3894
  return JSON.stringify(request.body);
3611
3895
  }
@@ -3817,6 +4101,8 @@ var ForgeRuntimeBridge = class _ForgeRuntimeBridge {
3817
4101
  return command.timestamp === void 0 ? { ...command, timestamp: timestamp(this.clock) } : command;
3818
4102
  case "sessionEvent":
3819
4103
  return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
4104
+ case "sessionUpdate":
4105
+ return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
3820
4106
  case "identityEvent":
3821
4107
  return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
3822
4108
  case "applicationForeground":
@@ -3928,7 +4214,11 @@ function deviceSampleCollector(options) {
3928
4214
  function runtimeConfig(options) {
3929
4215
  var _a, _b;
3930
4216
  const config = {
3931
- accountCode: options.accountCode
4217
+ accountCode: options.accountCode,
4218
+ // Browsers preflight any request with custom headers; the kernel's
4219
+ // CORS-simple profile keeps Forge's own NQS traffic to one HTTP call
4220
+ // per event (the browser supplies User-Agent and Host itself).
4221
+ corsSimpleTransport: true
3932
4222
  };
3933
4223
  assignOptional(config, "appName", options.appName);
3934
4224
  assignOptional(config, "buildVariant", options.buildVariant);
@@ -3948,6 +4238,7 @@ function runtimeConfig(options) {
3948
4238
  "preSessionEventQueueMaxAgeMs",
3949
4239
  options.preSessionEventQueueMaxAgeMs
3950
4240
  );
4241
+ assignOptional(config, "logoutSessionGuardMs", options.logoutSessionGuardMs);
3951
4242
  assignOptional(config, "logLevel", options.logLevel);
3952
4243
  const autoDeviceIdentity = (_a = options.autoDeviceIdentity) != null ? _a : true;
3953
4244
  assignOptional(
@@ -4263,6 +4554,9 @@ var VideoAdapter = class {
4263
4554
  var _a, _b;
4264
4555
  (_b = (_a = this.playerAdapter) == null ? void 0 : _a.detach) == null ? void 0 : _b.call(_a);
4265
4556
  this.playerAdapter = adapter;
4557
+ if (this.playerSetupAtMs === void 0 && typeof performance !== "undefined") {
4558
+ this.playerSetupAtMs = Math.round(performance.now());
4559
+ }
4266
4560
  adapter.attach(this);
4267
4561
  }
4268
4562
  setAdAdapter(adapter) {
@@ -4426,6 +4720,7 @@ var VideoAdapter = class {
4426
4720
  this.qos = qos;
4427
4721
  }
4428
4722
  this.metadata = withoutOneShotFields(mergedMetadata, ONE_SHOT_CONTENT_FIELDS);
4723
+ applyPageContextDefaults(mergedMetadata, this.playerSetupAtMs);
4429
4724
  const command = {
4430
4725
  type: "videoEvent",
4431
4726
  event,
@@ -4748,6 +5043,17 @@ function withOptionalString(value, key, optional) {
4748
5043
  [key]: optional
4749
5044
  };
4750
5045
  }
5046
+ function applyPageContextDefaults(metadata, playerSetupAtMs) {
5047
+ if (metadata.referer === void 0 && typeof location !== "undefined" && location.href) {
5048
+ metadata.referer = sanitizeCaptureUrl(location.href);
5049
+ }
5050
+ if (metadata.referral === void 0 && typeof document !== "undefined" && document.referrer) {
5051
+ metadata.referral = sanitizeCaptureUrl(document.referrer);
5052
+ }
5053
+ if (metadata.playerStartupTimeMs === void 0 && playerSetupAtMs !== void 0) {
5054
+ metadata.playerStartupTimeMs = playerSetupAtMs;
5055
+ }
5056
+ }
4751
5057
 
4752
5058
  // src/forge.ts
4753
5059
  var _NPAWForge = class _NPAWForge {
@@ -4823,6 +5129,39 @@ var _NPAWForge = class _NPAWForge {
4823
5129
  const normalizedName = name.trim().startsWith("raw_") ? name.trim() : `raw_${name.trim()}`;
4824
5130
  return this.trackSessionEvent(normalizedName, params);
4825
5131
  }
5132
+ /**
5133
+ * Hot-updates session-level dimensions without restarting the session:
5134
+ * `param1`..`param20` extraparams, `screenName`, or any dimension the NQS
5135
+ * parameter registry marks updatable — new backend dimensions work without
5136
+ * an SDK release. The change reaches NQS on the next session event within
5137
+ * one second, or on an immediate beat after that window; the very next
5138
+ * analytics row shows the new values, and later video views inherit them.
5139
+ *
5140
+ * Identity keys (`username`, `profileId`, `userType`, `anonymousUser`) are
5141
+ * rejected — use the typed identity API (`loginSuccess`,
5142
+ * `profileSelected`, `logout`). Blank values are dropped: NQS never erases
5143
+ * a session value. Requires the account's remote config to enable session
5144
+ * updates; otherwise the update is ignored with a diagnostic.
5145
+ */
5146
+ updateSession(params) {
5147
+ return this.runtime.process({
5148
+ type: "sessionUpdate",
5149
+ params: normalizeParams(params)
5150
+ });
5151
+ }
5152
+ /**
5153
+ * Reports numeric session metrics (account-registered custom metrics).
5154
+ * Values accumulate on the server per the account's registered operation
5155
+ * (sum/min/average/...) and settle on the session close row. Re-sending an
5156
+ * unchanged value is a no-op. Same remote-config gating as
5157
+ * {@link updateSession}.
5158
+ */
5159
+ updateSessionMetrics(metrics) {
5160
+ return this.runtime.process({
5161
+ type: "sessionUpdate",
5162
+ metrics
5163
+ });
5164
+ }
4826
5165
  /**
4827
5166
  * Emits a `raw_search` event. The query text is subject to the kernel-side
4828
5167
  * remote visible-text privacy policy, which can strip it before any payload