@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.
@@ -152,6 +152,225 @@ var NPAWForge = (() => {
152
152
  return (bits & bit) !== 0;
153
153
  }
154
154
 
155
+ // src/network-timing.ts
156
+ var DEFAULT_MATCH_TOLERANCE_MS = 250;
157
+ var DEFAULT_MATCH_TIMEOUT_MS = 2e3;
158
+ var DEFAULT_MAX_PENDING = 256;
159
+ function phaseMs(end, start) {
160
+ if (!Number.isFinite(end) || !Number.isFinite(start)) {
161
+ return void 0;
162
+ }
163
+ if (start <= 0) {
164
+ return void 0;
165
+ }
166
+ const delta = end - start;
167
+ if (!Number.isFinite(delta) || delta <= 0) {
168
+ return void 0;
169
+ }
170
+ return Math.round(delta);
171
+ }
172
+ function nonNegativeMs(value) {
173
+ if (!Number.isFinite(value) || value < 0) {
174
+ return void 0;
175
+ }
176
+ return Math.round(value);
177
+ }
178
+ function positiveBytes(value) {
179
+ if (!Number.isFinite(value) || value <= 0) {
180
+ return void 0;
181
+ }
182
+ return Math.round(value);
183
+ }
184
+ function timingFieldsFromResourceEntry(entry) {
185
+ var _a, _b;
186
+ const fields = {};
187
+ const duration = nonNegativeMs(entry.duration);
188
+ if (duration !== void 0) {
189
+ fields.durationMs = duration;
190
+ }
191
+ const timeToFirstByteMs = (_a = phaseMs(entry.responseStart, entry.requestStart)) != null ? _a : phaseMs(entry.responseStart, entry.startTime);
192
+ if (timeToFirstByteMs !== void 0) {
193
+ fields.timeToFirstByteMs = timeToFirstByteMs;
194
+ }
195
+ const dnsDurationMs = phaseMs(entry.domainLookupEnd, entry.domainLookupStart);
196
+ if (dnsDurationMs !== void 0) {
197
+ fields.dnsDurationMs = dnsDurationMs;
198
+ }
199
+ const connectDurationMs = phaseMs(entry.connectEnd, entry.connectStart);
200
+ if (connectDurationMs !== void 0) {
201
+ fields.connectDurationMs = connectDurationMs;
202
+ }
203
+ const sslDurationMs = phaseMs(entry.connectEnd, entry.secureConnectionStart);
204
+ if (sslDurationMs !== void 0) {
205
+ fields.sslDurationMs = sslDurationMs;
206
+ }
207
+ const responseDownloadDurationMs = phaseMs(entry.responseEnd, entry.responseStart);
208
+ if (responseDownloadDurationMs !== void 0) {
209
+ fields.responseDownloadDurationMs = responseDownloadDurationMs;
210
+ }
211
+ const redirectDurationMs = phaseMs(entry.redirectEnd, entry.redirectStart);
212
+ if (redirectDurationMs !== void 0) {
213
+ fields.redirectDurationMs = redirectDurationMs;
214
+ fields.redirectCount = 1;
215
+ }
216
+ if (typeof entry.nextHopProtocol === "string" && entry.nextHopProtocol.length > 0) {
217
+ fields.protocol = entry.nextHopProtocol;
218
+ }
219
+ const responseBytes = (_b = positiveBytes(entry.transferSize)) != null ? _b : positiveBytes(entry.encodedBodySize);
220
+ if (responseBytes !== void 0) {
221
+ fields.responseBytes = responseBytes;
222
+ }
223
+ return fields;
224
+ }
225
+ function timingMatchKey(url) {
226
+ var _a, _b;
227
+ const withoutFragment = (_a = url.split("#")[0]) != null ? _a : url;
228
+ return (_b = withoutFragment.split("?")[0]) != null ? _b : withoutFragment;
229
+ }
230
+ var ResourceTimingCorrelator = class {
231
+ constructor(options) {
232
+ this.options = options;
233
+ this.pending = /* @__PURE__ */ new Map();
234
+ this.pendingCount = 0;
235
+ this.disposed = false;
236
+ var _a, _b, _c;
237
+ this.toleranceMs = (_a = options.toleranceMs) != null ? _a : DEFAULT_MATCH_TOLERANCE_MS;
238
+ this.timeoutMs = (_b = options.timeoutMs) != null ? _b : DEFAULT_MATCH_TIMEOUT_MS;
239
+ this.maxPending = (_c = options.maxPending) != null ? _c : DEFAULT_MAX_PENDING;
240
+ try {
241
+ this.observer = options.observerFactory((entries) => this.onEntries(entries));
242
+ } catch (e2) {
243
+ this.observer = void 0;
244
+ }
245
+ }
246
+ /** True when correlation is actually available; false means timeout-only. */
247
+ get active() {
248
+ return this.observer !== void 0;
249
+ }
250
+ track(observation, url, startedAtMs) {
251
+ if (this.disposed || !this.observer) {
252
+ this.options.emit(observation);
253
+ return;
254
+ }
255
+ const key = timingMatchKey(url);
256
+ const record = {
257
+ key,
258
+ startedAtMs,
259
+ observation,
260
+ timer: void 0,
261
+ emitted: false
262
+ };
263
+ record.timer = this.options.setTimer(() => this.flush(record, false), this.timeoutMs);
264
+ const bucket = this.pending.get(key);
265
+ if (bucket) {
266
+ bucket.push(record);
267
+ } else {
268
+ this.pending.set(key, [record]);
269
+ }
270
+ this.pendingCount += 1;
271
+ this.evictOverflow();
272
+ }
273
+ dispose() {
274
+ var _a;
275
+ this.disposed = true;
276
+ try {
277
+ (_a = this.observer) == null ? void 0 : _a.disconnect();
278
+ } catch (e2) {
279
+ }
280
+ for (const bucket of [...this.pending.values()]) {
281
+ for (const record of [...bucket]) {
282
+ this.flush(record, false);
283
+ }
284
+ }
285
+ this.pending.clear();
286
+ this.pendingCount = 0;
287
+ }
288
+ onEntries(entries) {
289
+ for (const entry of entries) {
290
+ if (!entry || entry.entryType !== "resource") {
291
+ continue;
292
+ }
293
+ const record = this.take(entry);
294
+ if (!record) {
295
+ continue;
296
+ }
297
+ Object.assign(record.observation, timingFieldsFromResourceEntry(entry));
298
+ this.flush(record, true);
299
+ }
300
+ }
301
+ /**
302
+ * Pairs an entry with the closest pending observation for the same URL whose
303
+ * start time falls inside the tolerance window. Matching on start time as
304
+ * well as URL is what keeps concurrent requests to one endpoint apart.
305
+ */
306
+ take(entry) {
307
+ const bucket = this.pending.get(timingMatchKey(entry.name));
308
+ if (!bucket || bucket.length === 0) {
309
+ return void 0;
310
+ }
311
+ let best;
312
+ let bestDistance = Number.POSITIVE_INFINITY;
313
+ for (const record of bucket) {
314
+ if (record.emitted) {
315
+ continue;
316
+ }
317
+ const distance = Math.abs(record.startedAtMs - entry.startTime);
318
+ if (distance < bestDistance) {
319
+ bestDistance = distance;
320
+ best = record;
321
+ }
322
+ }
323
+ return bestDistance > this.toleranceMs ? void 0 : best;
324
+ }
325
+ flush(record, matched) {
326
+ var _a, _b;
327
+ if (record.emitted) {
328
+ return;
329
+ }
330
+ record.emitted = true;
331
+ this.detach(record);
332
+ this.options.clearTimer(record.timer);
333
+ if (!matched) {
334
+ (_b = (_a = this.options).onUnmatched) == null ? void 0 : _b.call(_a, record.observation);
335
+ }
336
+ this.options.emit(record.observation);
337
+ }
338
+ detach(record) {
339
+ const bucket = this.pending.get(record.key);
340
+ if (!bucket) {
341
+ return;
342
+ }
343
+ const index = bucket.indexOf(record);
344
+ if (index >= 0) {
345
+ bucket.splice(index, 1);
346
+ this.pendingCount -= 1;
347
+ }
348
+ if (bucket.length === 0) {
349
+ this.pending.delete(record.key);
350
+ }
351
+ }
352
+ evictOverflow() {
353
+ while (this.pendingCount > this.maxPending) {
354
+ const oldest = this.oldestRecord();
355
+ if (!oldest) {
356
+ return;
357
+ }
358
+ this.flush(oldest, false);
359
+ }
360
+ }
361
+ oldestRecord() {
362
+ let oldest;
363
+ for (const bucket of this.pending.values()) {
364
+ for (const record of bucket) {
365
+ if (!oldest || record.startedAtMs < oldest.startedAtMs) {
366
+ oldest = record;
367
+ }
368
+ }
369
+ }
370
+ return oldest;
371
+ }
372
+ };
373
+
155
374
  // src/sections-capture.ts
156
375
  var DEFAULT_VISIBILITY_THRESHOLD_PCT = 50;
157
376
  var DEFAULT_IMPRESSION_MIN_VISIBLE_MS = 1e3;
@@ -2125,6 +2344,8 @@ var NPAWForge = (() => {
2125
2344
  this.featureDisposers = /* @__PURE__ */ new Map();
2126
2345
  this.lastScrollAtMs = 0;
2127
2346
  this.disposed = false;
2347
+ /** Observations emitted on wrapper timing because no entry ever matched. */
2348
+ this.unmatchedNetworkTimings = 0;
2128
2349
  this.initialNavigationReported = false;
2129
2350
  this.attributionReported = false;
2130
2351
  this.foregroundCount = 0;
@@ -2733,6 +2954,7 @@ var NPAWForge = (() => {
2733
2954
  sink.push(() => {
2734
2955
  generation.active = false;
2735
2956
  });
2957
+ this.installResourceTimingCorrelator(sink);
2736
2958
  if (this.options.network.fetch) {
2737
2959
  this.patchFetch(sink, generation);
2738
2960
  }
@@ -2740,6 +2962,60 @@ var NPAWForge = (() => {
2740
2962
  this.patchXmlHttpRequest(sink, generation);
2741
2963
  }
2742
2964
  }
2965
+ /**
2966
+ * The wrappers cannot see connection phases, protocol, or a duration free of
2967
+ * JS scheduling — and a `fetch` promise resolves at headers, so timing it
2968
+ * yields time-to-first-byte rather than duration. The correlator holds each
2969
+ * observation until its Resource Timing entry arrives and merges the two.
2970
+ */
2971
+ installResourceTimingCorrelator(sink) {
2972
+ const factory = this.resourceTimingObserverFactory();
2973
+ if (!factory) {
2974
+ return;
2975
+ }
2976
+ const correlator = new ResourceTimingCorrelator({
2977
+ emit: (observation) => safeCaptureCall(() => this.host.trackNetworkEvent(observation)),
2978
+ observerFactory: factory,
2979
+ setTimer: (callback, delayMs) => this.timers().setTimeout(callback, delayMs),
2980
+ clearTimer: (handle) => this.timers().clearTimeout(handle),
2981
+ onUnmatched: () => {
2982
+ this.unmatchedNetworkTimings += 1;
2983
+ }
2984
+ });
2985
+ if (!correlator.active) {
2986
+ return;
2987
+ }
2988
+ this.networkTimingCorrelator = correlator;
2989
+ sink.push(() => {
2990
+ this.networkTimingCorrelator = void 0;
2991
+ correlator.dispose();
2992
+ });
2993
+ }
2994
+ /**
2995
+ * Prefers an injected factory (tests, non-browser hosts) and otherwise builds
2996
+ * one over `PerformanceObserver`. An observer is used rather than
2997
+ * `getEntriesByType` because the resource buffer caps at 250 entries by
2998
+ * default: a long-lived SPA silently drops the rest, whereas an observer is
2999
+ * handed every entry once as it is recorded.
3000
+ */
3001
+ resourceTimingObserverFactory() {
3002
+ const injected = this.options.environment.resourceTimingObserverFactory;
3003
+ if (injected) {
3004
+ return injected;
3005
+ }
3006
+ const windowRef = this.window();
3007
+ const ObserverCtor = windowRef == null ? void 0 : windowRef.PerformanceObserver;
3008
+ if (typeof ObserverCtor !== "function") {
3009
+ return void 0;
3010
+ }
3011
+ return (callback) => {
3012
+ const observer = new ObserverCtor((list) => {
3013
+ callback(list.getEntries());
3014
+ });
3015
+ observer.observe({ type: "resource", buffered: true });
3016
+ return observer;
3017
+ };
3018
+ }
2743
3019
  installWebVitalsCapture(sink) {
2744
3020
  const handle = installWebVitalsCapture(this.host, this.options);
2745
3021
  sink.push(() => handle.dispose());
@@ -3020,6 +3296,11 @@ var NPAWForge = (() => {
3020
3296
  if (Object.keys(responseHeaders).length > 0) {
3021
3297
  observation.responseHeaders = responseHeaders;
3022
3298
  }
3299
+ const correlator = this.networkTimingCorrelator;
3300
+ if (correlator) {
3301
+ correlator.track(observation, metadata.targetUrl, startedAt.elapsedMs);
3302
+ return;
3303
+ }
3023
3304
  safeCaptureCall(() => this.host.trackNetworkEvent(observation));
3024
3305
  }
3025
3306
  emitRawEvent(name, params = {}, presanitized) {
@@ -4125,6 +4406,9 @@ var NPAWForge = (() => {
4125
4406
  if (request.bodyBytes !== void 0) {
4126
4407
  return new Uint8Array(request.bodyBytes);
4127
4408
  }
4409
+ if (request.bodyText !== void 0) {
4410
+ return request.bodyText;
4411
+ }
4128
4412
  if (request.body !== void 0) {
4129
4413
  return JSON.stringify(request.body);
4130
4414
  }
@@ -4336,6 +4620,8 @@ var NPAWForge = (() => {
4336
4620
  return command.timestamp === void 0 ? { ...command, timestamp: timestamp(this.clock) } : command;
4337
4621
  case "sessionEvent":
4338
4622
  return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
4623
+ case "sessionUpdate":
4624
+ return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
4339
4625
  case "identityEvent":
4340
4626
  return command.timemarkMs === void 0 ? { ...command, timemarkMs: this.nowMs() } : command;
4341
4627
  case "applicationForeground":
@@ -4447,7 +4733,11 @@ var NPAWForge = (() => {
4447
4733
  function runtimeConfig(options) {
4448
4734
  var _a, _b;
4449
4735
  const config = {
4450
- accountCode: options.accountCode
4736
+ accountCode: options.accountCode,
4737
+ // Browsers preflight any request with custom headers; the kernel's
4738
+ // CORS-simple profile keeps Forge's own NQS traffic to one HTTP call
4739
+ // per event (the browser supplies User-Agent and Host itself).
4740
+ corsSimpleTransport: true
4451
4741
  };
4452
4742
  assignOptional(config, "appName", options.appName);
4453
4743
  assignOptional(config, "buildVariant", options.buildVariant);
@@ -4467,6 +4757,7 @@ var NPAWForge = (() => {
4467
4757
  "preSessionEventQueueMaxAgeMs",
4468
4758
  options.preSessionEventQueueMaxAgeMs
4469
4759
  );
4760
+ assignOptional(config, "logoutSessionGuardMs", options.logoutSessionGuardMs);
4470
4761
  assignOptional(config, "logLevel", options.logLevel);
4471
4762
  const autoDeviceIdentity = (_a = options.autoDeviceIdentity) != null ? _a : true;
4472
4763
  assignOptional(
@@ -4782,6 +5073,9 @@ var NPAWForge = (() => {
4782
5073
  var _a, _b;
4783
5074
  (_b = (_a = this.playerAdapter) == null ? void 0 : _a.detach) == null ? void 0 : _b.call(_a);
4784
5075
  this.playerAdapter = adapter;
5076
+ if (this.playerSetupAtMs === void 0 && typeof performance !== "undefined") {
5077
+ this.playerSetupAtMs = Math.round(performance.now());
5078
+ }
4785
5079
  adapter.attach(this);
4786
5080
  }
4787
5081
  setAdAdapter(adapter) {
@@ -4945,6 +5239,7 @@ var NPAWForge = (() => {
4945
5239
  this.qos = qos;
4946
5240
  }
4947
5241
  this.metadata = withoutOneShotFields(mergedMetadata, ONE_SHOT_CONTENT_FIELDS);
5242
+ applyPageContextDefaults(mergedMetadata, this.playerSetupAtMs);
4948
5243
  const command = {
4949
5244
  type: "videoEvent",
4950
5245
  event,
@@ -5267,6 +5562,17 @@ var NPAWForge = (() => {
5267
5562
  [key]: optional
5268
5563
  };
5269
5564
  }
5565
+ function applyPageContextDefaults(metadata, playerSetupAtMs) {
5566
+ if (metadata.referer === void 0 && typeof location !== "undefined" && location.href) {
5567
+ metadata.referer = sanitizeCaptureUrl(location.href);
5568
+ }
5569
+ if (metadata.referral === void 0 && typeof document !== "undefined" && document.referrer) {
5570
+ metadata.referral = sanitizeCaptureUrl(document.referrer);
5571
+ }
5572
+ if (metadata.playerStartupTimeMs === void 0 && playerSetupAtMs !== void 0) {
5573
+ metadata.playerStartupTimeMs = playerSetupAtMs;
5574
+ }
5575
+ }
5270
5576
 
5271
5577
  // src/forge.ts
5272
5578
  var _NPAWForge = class _NPAWForge {
@@ -5342,6 +5648,39 @@ var NPAWForge = (() => {
5342
5648
  const normalizedName = name.trim().startsWith("raw_") ? name.trim() : `raw_${name.trim()}`;
5343
5649
  return this.trackSessionEvent(normalizedName, params);
5344
5650
  }
5651
+ /**
5652
+ * Hot-updates session-level dimensions without restarting the session:
5653
+ * `param1`..`param20` extraparams, `screenName`, or any dimension the NQS
5654
+ * parameter registry marks updatable — new backend dimensions work without
5655
+ * an SDK release. The change reaches NQS on the next session event within
5656
+ * one second, or on an immediate beat after that window; the very next
5657
+ * analytics row shows the new values, and later video views inherit them.
5658
+ *
5659
+ * Identity keys (`username`, `profileId`, `userType`, `anonymousUser`) are
5660
+ * rejected — use the typed identity API (`loginSuccess`,
5661
+ * `profileSelected`, `logout`). Blank values are dropped: NQS never erases
5662
+ * a session value. Requires the account's remote config to enable session
5663
+ * updates; otherwise the update is ignored with a diagnostic.
5664
+ */
5665
+ updateSession(params) {
5666
+ return this.runtime.process({
5667
+ type: "sessionUpdate",
5668
+ params: normalizeParams(params)
5669
+ });
5670
+ }
5671
+ /**
5672
+ * Reports numeric session metrics (account-registered custom metrics).
5673
+ * Values accumulate on the server per the account's registered operation
5674
+ * (sum/min/average/...) and settle on the session close row. Re-sending an
5675
+ * unchanged value is a no-op. Same remote-config gating as
5676
+ * {@link updateSession}.
5677
+ */
5678
+ updateSessionMetrics(metrics) {
5679
+ return this.runtime.process({
5680
+ type: "sessionUpdate",
5681
+ metrics
5682
+ });
5683
+ }
5345
5684
  /**
5346
5685
  * Emits a `raw_search` event. The query text is subject to the kernel-side
5347
5686
  * remote visible-text privacy policy, which can strip it before any payload