@oneuptime/react-native-replay 16.0.0 → 17.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -99,7 +99,7 @@ var SESSION_REPLAY_MAX_OFFLINE_DELAY_MS = 3 * 24 * 60 * 60 * 1e3;
99
99
  var MOBILE_CAPTURE_INTERVAL_MS = 500;
100
100
  var MOBILE_RECORDER_KIND = "rn-view-tree";
101
101
  var SYNTHETIC_RRWEB_VERSION = "synthetic-1";
102
- var RECORDER_VERSION = true ? "16.0.0" : "0.0.0-dev";
102
+ var RECORDER_VERSION = true ? "17.1.0" : "0.0.0-dev";
103
103
  var SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES = [
104
104
  "mobile-view-tree",
105
105
  "mobile-touch-events",
@@ -250,10 +250,11 @@ function maskTextValue(value) {
250
250
  const maskedLength = length <= 8 ? 4 : length <= 32 ? 16 : 40;
251
251
  return "\u2022".repeat(maskedLength);
252
252
  }
253
- function maskStringMapValues(values) {
253
+ var READABLE_VALUE_PATTERN = /^[A-Za-z0-9_.:/-]{0,32}$/;
254
+ function maskStringMapValues(values, readableKeys = []) {
254
255
  const masked = /* @__PURE__ */ Object.create(null);
255
256
  for (const [key, value] of Object.entries(values)) {
256
- masked[key] = maskTextValue(value);
257
+ masked[key] = readableKeys.indexOf(key) !== -1 && READABLE_VALUE_PATTERN.test(value) ? value : maskTextValue(value);
257
258
  }
258
259
  return masked;
259
260
  }
@@ -519,22 +520,28 @@ var RollingReplayBuffer = class {
519
520
  // src/CustomSignals.ts
520
521
  var TRIGGERS = [
521
522
  "click",
523
+ "tap",
522
524
  "page",
523
525
  "event",
524
526
  "error"
525
527
  ];
528
+ var MAX_TAP_TARGET_TEST_IDS = 32;
526
529
  function asRecord(value) {
527
530
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
528
531
  }
529
532
  function isTrigger(value) {
530
533
  return typeof value === "string" && TRIGGERS.indexOf(value) !== -1;
531
534
  }
535
+ function isTapPatternUsable(pattern) {
536
+ const star = pattern.indexOf("*");
537
+ return star === -1 || star > 0 && star === pattern.length - 1;
538
+ }
532
539
  function readCustomSignal(value) {
533
540
  const record = asRecord(value);
534
541
  const name = typeof record["name"] === "string" ? record["name"].trim() : "";
535
542
  const trigger = record["trigger"];
536
543
  const match = typeof record["match"] === "string" ? record["match"].trim() : "";
537
- if (name.length === 0 || name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH || !isTrigger(trigger) || match.length === 0 || match.length > (trigger === "event" ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) || trigger === "page" && match.charAt(0) !== "/" && match.charAt(0) !== "*") {
544
+ if (name.length === 0 || name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH || !isTrigger(trigger) || match.length === 0 || match.length > (trigger === "event" ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) || trigger === "page" && match.charAt(0) !== "/" && match.charAt(0) !== "*" || trigger === "tap" && !isTapPatternUsable(match)) {
538
545
  return null;
539
546
  }
540
547
  return {
@@ -655,6 +662,29 @@ function matchesErrorText(match, text) {
655
662
  function matchesEventName(match, name) {
656
663
  return match.trim().toLowerCase() === name.trim().toLowerCase();
657
664
  }
665
+ function matchesTapTarget(match, testId) {
666
+ const pattern = match.trim().toLowerCase();
667
+ const target = testId.toLowerCase();
668
+ if (!pattern || !target || !isTapPatternUsable(pattern)) {
669
+ return false;
670
+ }
671
+ return pattern.charAt(pattern.length - 1) === "*" ? target.indexOf(pattern.slice(0, -1)) === 0 : target === pattern;
672
+ }
673
+ function readTapTargetTestIds(value) {
674
+ if (!Array.isArray(value)) {
675
+ return [];
676
+ }
677
+ const testIds = [];
678
+ for (const entry of value) {
679
+ if (typeof entry === "string" && entry.length > 0 && entry.length <= SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) {
680
+ testIds.push(entry);
681
+ }
682
+ if (testIds.length >= MAX_TAP_TARGET_TEST_IDS) {
683
+ break;
684
+ }
685
+ }
686
+ return testIds;
687
+ }
658
688
  function routeMatchPath(route) {
659
689
  let path = typeof route === "string" ? route.trim() : "";
660
690
  const scheme = path.indexOf("://");
@@ -676,6 +706,26 @@ var CustomSignalMatcher = class {
676
706
  constructor() {
677
707
  __publicField(this, "lastFiredAt", /* @__PURE__ */ new Map());
678
708
  }
709
+ /*
710
+ * A tap on a view whose testID a tap signal names - or on anything inside
711
+ * it: testIds holds the touched view's testID and those of the views
712
+ * around it, out to the replay root, the touched one first.
713
+ */
714
+ matchTap(signals, testIds, atUnixMs) {
715
+ if (testIds.length === 0) {
716
+ return [];
717
+ }
718
+ return this.collect(
719
+ signals,
720
+ "tap",
721
+ atUnixMs,
722
+ (signal) => {
723
+ return testIds.some((testId) => {
724
+ return matchesTapTarget(signal.match, testId);
725
+ });
726
+ }
727
+ );
728
+ }
679
729
  matchPage(signals, route, atUnixMs) {
680
730
  const path = routeMatchPath(route);
681
731
  return this.collect(
@@ -737,6 +787,89 @@ var CustomSignalMatcher = class {
737
787
  }
738
788
  };
739
789
 
790
+ // src/ProductAnalyticsContract.ts
791
+ var PRODUCT_ANALYTICS_EVENTS_PATH = "/telemetry/session-replay/v1/events";
792
+ var PRODUCT_ANALYTICS_WIRE_VERSION = 1;
793
+ var PRODUCT_ANALYTICS_CONTENT_TYPE = "application/json";
794
+ var PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH = 100;
795
+ var PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH = 100;
796
+ var PRODUCT_ANALYTICS_MAX_BATCH_BYTES = 64 * 1024;
797
+ var PRODUCT_ANALYTICS_TARGET_BATCH_BYTES = 24 * 1024;
798
+ var PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS = 5e3;
799
+ var PRODUCT_ANALYTICS_MAX_PENDING_EVENTS = 500;
800
+ var PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH = 64;
801
+ var PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH = 64;
802
+ var PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH = 64;
803
+ var PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS = 3 * 24 * 60 * 60 * 1e3;
804
+ var PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE = 600;
805
+ var METRIC_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]{0,99}$/;
806
+ var PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX = "oneuptime.";
807
+ function isProductAnalyticsMetricName(value) {
808
+ return typeof value === "string" && METRIC_NAME_PATTERN.test(value) && !value.toLowerCase().startsWith(PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX);
809
+ }
810
+ function toProductAnalyticsEventName(value) {
811
+ if (typeof value !== "string") {
812
+ return null;
813
+ }
814
+ let name = "";
815
+ for (const character of value) {
816
+ const code = character.charCodeAt(0);
817
+ if (code < 32 || code === 127) {
818
+ continue;
819
+ }
820
+ name += character;
821
+ }
822
+ name = name.trim().slice(0, PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH).trim();
823
+ return name.length > 0 ? name : null;
824
+ }
825
+ var NOT_PRINTABLE_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
826
+ function toProductAnalyticsAppVersion(value) {
827
+ if (typeof value !== "string") {
828
+ return "";
829
+ }
830
+ const version = value.trim().slice(0, PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH).trim();
831
+ return NOT_PRINTABLE_PATTERN.test(version) ? "" : version;
832
+ }
833
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS = 20;
834
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH = 40;
835
+ function normalizeProductAnalyticsUserPropertyKeys(value) {
836
+ if (!Array.isArray(value)) {
837
+ return [];
838
+ }
839
+ const keys = [];
840
+ const seen = /* @__PURE__ */ new Set();
841
+ for (const entry of value) {
842
+ if (typeof entry !== "string") {
843
+ continue;
844
+ }
845
+ const key = entry.trim().slice(0, PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH);
846
+ if (key.length === 0 || key === "__proto__") {
847
+ continue;
848
+ }
849
+ if (seen.has(key.toLowerCase())) {
850
+ continue;
851
+ }
852
+ seen.add(key.toLowerCase());
853
+ keys.push(key);
854
+ if (keys.length >= PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS) {
855
+ break;
856
+ }
857
+ }
858
+ return keys;
859
+ }
860
+ function readProductAnalyticsRecorderConfig(value) {
861
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
862
+ return { enabled: false, userPropertyKeys: [] };
863
+ }
864
+ const record = value;
865
+ return {
866
+ enabled: record["enabled"] === true,
867
+ userPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
868
+ record["userPropertyKeys"]
869
+ )
870
+ };
871
+ }
872
+
740
873
  // src/Config.ts
741
874
  var CONFIG_FETCH_TIMEOUT_MS = 5e3;
742
875
  var MOBILE_APP_IDENTIFIER_LABEL_PATTERN = /^[a-z0-9_-]+$/u;
@@ -852,6 +985,8 @@ function failClosed(reason) {
852
985
  configEpoch: 0,
853
986
  isTargeted: false,
854
987
  frustrationSignals: { customSignals: [] },
988
+ productAnalytics: { enabled: false, userPropertyKeys: [] },
989
+ readableEventPropertyKeys: [],
855
990
  disabledReason: reason
856
991
  };
857
992
  }
@@ -880,7 +1015,21 @@ function normalizeReplayConfig(value) {
880
1015
  */
881
1016
  frustrationSignals: {
882
1017
  customSignals: readCustomSignals(config.frustrationSignals)
883
- }
1018
+ },
1019
+ /*
1020
+ * Absent - a server from before product analytics, or an application
1021
+ * with it off - reads as off, so no batch is sent nobody asked for.
1022
+ */
1023
+ productAnalytics: readProductAnalyticsRecorderConfig(
1024
+ config.productAnalytics
1025
+ ),
1026
+ /*
1027
+ * Read as product analytics reads the traits it keeps, as Common's
1028
+ * normalizeSessionReplayReadablePropertyKeys does: absent, none.
1029
+ */
1030
+ readableEventPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
1031
+ config.readableEventPropertyKeys
1032
+ )
884
1033
  };
885
1034
  if (typeof config.disabledReason === "string") {
886
1035
  resolved.disabledReason = config.disabledReason.slice(0, 100);
@@ -1463,6 +1612,24 @@ var ReactNativeViewTreeAdapter = class {
1463
1612
  return true;
1464
1613
  }
1465
1614
  }
1615
+ /*
1616
+ * A native module built before tap signals existed (an over-the-air
1617
+ * update of the JavaScript alone) has no such method: no testIDs, so no
1618
+ * tap signal fires, and nothing else changes.
1619
+ */
1620
+ async touchTargetTestIds(targetTag, replayRootTag) {
1621
+ const nativeModule = import_react_native.NativeModules["OneUptimeReplayViewTree"];
1622
+ if (typeof nativeModule?.touchTargetTestIds !== "function") {
1623
+ return [];
1624
+ }
1625
+ try {
1626
+ return readTapTargetTestIds(
1627
+ await nativeModule.touchTargetTestIds(targetTag, replayRootTag)
1628
+ );
1629
+ } catch {
1630
+ return [];
1631
+ }
1632
+ }
1466
1633
  };
1467
1634
  var defaultNativeViewTreeAdapter = new ReactNativeViewTreeAdapter();
1468
1635
  function getViewport() {
@@ -2709,172 +2876,6 @@ var ReplayOutbox = class {
2709
2876
  }
2710
2877
  };
2711
2878
 
2712
- // src/Storage.ts
2713
- var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
2714
- var REPLAY_ID_PATTERN = /^[0-9a-f]{32}$/u;
2715
- var defaultReplayStorage = import_async_storage.default;
2716
- function generateReplayId() {
2717
- const bytes = new Uint8Array(16);
2718
- const cryptoRef = globalThis.crypto;
2719
- if (cryptoRef && typeof cryptoRef.getRandomValues === "function") {
2720
- cryptoRef.getRandomValues(bytes);
2721
- } else {
2722
- for (let index = 0; index < bytes.length; index += 1) {
2723
- bytes[index] = Math.floor(Math.random() * 256);
2724
- }
2725
- }
2726
- return Array.from(bytes).map((byte) => {
2727
- return byte.toString(16).padStart(2, "0");
2728
- }).join("");
2729
- }
2730
- function isReplayId(value) {
2731
- return typeof value === "string" && REPLAY_ID_PATTERN.test(value);
2732
- }
2733
- function parseStoredSession(value) {
2734
- if (!value) {
2735
- return null;
2736
- }
2737
- try {
2738
- const parsed = JSON.parse(value);
2739
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2740
- return null;
2741
- }
2742
- const candidate = parsed;
2743
- if (!isReplayId(candidate.sessionId) || !Number.isSafeInteger(candidate.sessionStartUnixMs) || !Number.isSafeInteger(candidate.lastActivityUnixMs) || !Number.isSafeInteger(candidate.nextChunkIndex) || (candidate.nextChunkIndex ?? -1) < 0) {
2744
- return null;
2745
- }
2746
- return candidate;
2747
- } catch {
2748
- return null;
2749
- }
2750
- }
2751
- var ReplaySessionStore = class {
2752
- constructor(storage, namespace) {
2753
- __publicField(this, "storage");
2754
- __publicField(this, "sessionKey");
2755
- __publicField(this, "visitorKey");
2756
- __publicField(this, "identity", null);
2757
- this.storage = storage;
2758
- this.sessionKey = `@oneuptime/replay/${namespace}/session`;
2759
- this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;
2760
- }
2761
- async resolve(nowUnixMs) {
2762
- const stored = parseStoredSession(
2763
- await this.safeGet(this.sessionKey)
2764
- );
2765
- const shouldRotate = !stored || stored.nextChunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION || nowUnixMs - stored.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - stored.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS;
2766
- let session;
2767
- if (shouldRotate || !stored) {
2768
- session = {
2769
- sessionId: generateReplayId(),
2770
- sessionStartUnixMs: nowUnixMs,
2771
- lastActivityUnixMs: nowUnixMs,
2772
- nextChunkIndex: 0
2773
- };
2774
- } else {
2775
- session = {
2776
- sessionId: stored.sessionId,
2777
- sessionStartUnixMs: stored.sessionStartUnixMs,
2778
- lastActivityUnixMs: nowUnixMs,
2779
- nextChunkIndex: stored.nextChunkIndex
2780
- };
2781
- }
2782
- let visitorId = await this.safeGet(this.visitorKey);
2783
- if (!isReplayId(visitorId)) {
2784
- visitorId = generateReplayId();
2785
- await this.safeSet(this.visitorKey, visitorId);
2786
- }
2787
- await this.safeSet(this.sessionKey, JSON.stringify(session));
2788
- this.identity = {
2789
- sessionId: session.sessionId,
2790
- tabId: generateReplayId(),
2791
- visitorId,
2792
- sessionStartUnixMs: session.sessionStartUnixMs,
2793
- chunkIndex: session.nextChunkIndex
2794
- };
2795
- return { ...this.identity };
2796
- }
2797
- async takeChunkIndex(nowUnixMs) {
2798
- if (!this.identity) {
2799
- await this.resolve(nowUnixMs);
2800
- }
2801
- const identity = this.identity;
2802
- const index = identity.chunkIndex;
2803
- identity.chunkIndex += 1;
2804
- const state = {
2805
- sessionId: identity.sessionId,
2806
- sessionStartUnixMs: identity.sessionStartUnixMs,
2807
- lastActivityUnixMs: nowUnixMs,
2808
- nextChunkIndex: identity.chunkIndex
2809
- };
2810
- await this.safeSet(this.sessionKey, JSON.stringify(state));
2811
- return index;
2812
- }
2813
- getNextChunkIndex() {
2814
- return this.identity?.chunkIndex ?? null;
2815
- }
2816
- async rotate(nowUnixMs) {
2817
- let visitorId = await this.safeGet(this.visitorKey);
2818
- if (!isReplayId(visitorId)) {
2819
- visitorId = generateReplayId();
2820
- await this.safeSet(this.visitorKey, visitorId);
2821
- }
2822
- const session = {
2823
- sessionId: generateReplayId(),
2824
- sessionStartUnixMs: nowUnixMs,
2825
- lastActivityUnixMs: nowUnixMs,
2826
- nextChunkIndex: 0
2827
- };
2828
- await this.safeSet(this.sessionKey, JSON.stringify(session));
2829
- this.identity = {
2830
- sessionId: session.sessionId,
2831
- tabId: generateReplayId(),
2832
- visitorId,
2833
- sessionStartUnixMs: nowUnixMs,
2834
- chunkIndex: 0
2835
- };
2836
- return { ...this.identity };
2837
- }
2838
- /*
2839
- * Forget the stored session without starting the next one. A session
2840
- * that ends while the recorder is paused for idle has no successor until
2841
- * the person comes back, and its record - last written by its own final
2842
- * chunk, so it looks recent - would otherwise let a relaunch in the
2843
- * meantime carry on a session that is already over. The visitor id stays,
2844
- * and so does the in-memory identity: nothing more is sent under it, and
2845
- * the next rotate() writes the new session.
2846
- */
2847
- async end() {
2848
- await this.safeRemove(this.sessionKey);
2849
- }
2850
- async clear() {
2851
- this.identity = null;
2852
- await Promise.all([
2853
- this.safeRemove(this.sessionKey),
2854
- this.safeRemove(this.visitorKey)
2855
- ]);
2856
- }
2857
- async safeGet(key) {
2858
- try {
2859
- return await this.storage.getItem(key);
2860
- } catch {
2861
- return null;
2862
- }
2863
- }
2864
- async safeSet(key, value) {
2865
- try {
2866
- await this.storage.setItem(key, value);
2867
- } catch {
2868
- }
2869
- }
2870
- async safeRemove(key) {
2871
- try {
2872
- await this.storage.removeItem(key);
2873
- } catch {
2874
- }
2875
- }
2876
- };
2877
-
2878
2879
  // src/RetryAfter.ts
2879
2880
  var RETRY_AFTER_HEADER = "retry-after";
2880
2881
  var DEFAULT_RETRY_AFTER_MIN_MS = 1e3;
@@ -3026,46 +3027,1314 @@ var RetryAfter = class _RetryAfter {
3026
3027
  return headers[name];
3027
3028
  }
3028
3029
  }
3029
- return void 0;
3030
+ return void 0;
3031
+ }
3032
+ // parseMs of a response's Retry-After header.
3033
+ static msFromHeaders(headers, options) {
3034
+ return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
3035
+ }
3036
+ // parseSeconds of a response's Retry-After header.
3037
+ static secondsFromHeaders(headers, options) {
3038
+ return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
3039
+ }
3040
+ /*
3041
+ * An HTTP-date in any of its three shapes, exactly as written, as
3042
+ * milliseconds since the epoch; undefined for anything else. nowMs is what
3043
+ * an RFC 850 date's two-digit year is read against.
3044
+ */
3045
+ static parseHttpDate(value, nowMs) {
3046
+ let match = IMF_FIXDATE.exec(value);
3047
+ if (match) {
3048
+ return toUtcMs(
3049
+ Number(match[3]),
3050
+ match[2],
3051
+ match[1],
3052
+ match[4],
3053
+ match[5],
3054
+ match[6]
3055
+ );
3056
+ }
3057
+ match = RFC_850_DATE.exec(value);
3058
+ if (match) {
3059
+ return readRfc850Date(match, readNow(nowMs));
3060
+ }
3061
+ match = ASCTIME_DATE.exec(value);
3062
+ return match ? toUtcMs(
3063
+ Number(match[6]),
3064
+ match[1],
3065
+ match[2],
3066
+ match[3],
3067
+ match[4],
3068
+ match[5]
3069
+ ) : void 0;
3070
+ }
3071
+ };
3072
+
3073
+ // src/Storage.ts
3074
+ var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
3075
+ var REPLAY_ID_PATTERN = /^[0-9a-f]{32}$/u;
3076
+ var defaultReplayStorage = import_async_storage.default;
3077
+ function generateReplayId() {
3078
+ const bytes = new Uint8Array(16);
3079
+ const cryptoRef = globalThis.crypto;
3080
+ if (cryptoRef && typeof cryptoRef.getRandomValues === "function") {
3081
+ cryptoRef.getRandomValues(bytes);
3082
+ } else {
3083
+ for (let index = 0; index < bytes.length; index += 1) {
3084
+ bytes[index] = Math.floor(Math.random() * 256);
3085
+ }
3086
+ }
3087
+ return Array.from(bytes).map((byte) => {
3088
+ return byte.toString(16).padStart(2, "0");
3089
+ }).join("");
3090
+ }
3091
+ function isReplayId(value) {
3092
+ return typeof value === "string" && REPLAY_ID_PATTERN.test(value);
3093
+ }
3094
+ function parseStoredSession(value) {
3095
+ if (!value) {
3096
+ return null;
3097
+ }
3098
+ try {
3099
+ const parsed = JSON.parse(value);
3100
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
3101
+ return null;
3102
+ }
3103
+ const candidate = parsed;
3104
+ if (!isReplayId(candidate.sessionId) || !Number.isSafeInteger(candidate.sessionStartUnixMs) || !Number.isSafeInteger(candidate.lastActivityUnixMs) || !Number.isSafeInteger(candidate.nextChunkIndex) || (candidate.nextChunkIndex ?? -1) < 0) {
3105
+ return null;
3106
+ }
3107
+ return candidate;
3108
+ } catch {
3109
+ return null;
3110
+ }
3111
+ }
3112
+ var ReplaySessionStore = class {
3113
+ constructor(storage, namespace) {
3114
+ __publicField(this, "storage");
3115
+ __publicField(this, "sessionKey");
3116
+ __publicField(this, "visitorKey");
3117
+ __publicField(this, "identity", null);
3118
+ /* When the session's last activity was, as the stored record says. */
3119
+ __publicField(this, "lastActivityUnixMs", 0);
3120
+ this.storage = storage;
3121
+ this.sessionKey = `@oneuptime/replay/${namespace}/session`;
3122
+ this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;
3123
+ }
3124
+ async resolve(nowUnixMs) {
3125
+ const stored = parseStoredSession(
3126
+ await this.safeGet(this.sessionKey)
3127
+ );
3128
+ const shouldRotate = !stored || stored.nextChunkIndex >= MAX_SESSION_REPLAY_CHUNKS_PER_SESSION || nowUnixMs - stored.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - stored.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS;
3129
+ let session;
3130
+ if (shouldRotate || !stored) {
3131
+ session = {
3132
+ sessionId: generateReplayId(),
3133
+ sessionStartUnixMs: nowUnixMs,
3134
+ lastActivityUnixMs: nowUnixMs,
3135
+ nextChunkIndex: 0
3136
+ };
3137
+ } else {
3138
+ session = {
3139
+ sessionId: stored.sessionId,
3140
+ sessionStartUnixMs: stored.sessionStartUnixMs,
3141
+ lastActivityUnixMs: nowUnixMs,
3142
+ nextChunkIndex: stored.nextChunkIndex
3143
+ };
3144
+ }
3145
+ let visitorId = await this.safeGet(this.visitorKey);
3146
+ if (!isReplayId(visitorId)) {
3147
+ visitorId = generateReplayId();
3148
+ await this.safeSet(this.visitorKey, visitorId);
3149
+ }
3150
+ await this.safeSet(this.sessionKey, JSON.stringify(session));
3151
+ this.identity = {
3152
+ sessionId: session.sessionId,
3153
+ tabId: generateReplayId(),
3154
+ visitorId,
3155
+ sessionStartUnixMs: session.sessionStartUnixMs,
3156
+ chunkIndex: session.nextChunkIndex
3157
+ };
3158
+ this.lastActivityUnixMs = nowUnixMs;
3159
+ return { ...this.identity };
3160
+ }
3161
+ /*
3162
+ * The session a product analytics event belongs to while the replay
3163
+ * records nothing of it (an unsampled session, issue #6629): nothing else
3164
+ * moves the session then, so the event is its activity. The session
3165
+ * carries on, or - past the idle window or the longest a session lasts -
3166
+ * the next one starts, as resolve() would decide at the next launch.
3167
+ * Synchronous: decided in memory and written in the background, where a
3168
+ * failed write costs only a relaunch's resume. Null before resolve().
3169
+ */
3170
+ continueSession(nowUnixMs) {
3171
+ const identity = this.identity;
3172
+ if (!identity) {
3173
+ return null;
3174
+ }
3175
+ if (nowUnixMs - this.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - identity.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS) {
3176
+ identity.sessionId = generateReplayId();
3177
+ identity.tabId = generateReplayId();
3178
+ identity.sessionStartUnixMs = nowUnixMs;
3179
+ identity.chunkIndex = 0;
3180
+ }
3181
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
3182
+ const state = {
3183
+ sessionId: identity.sessionId,
3184
+ sessionStartUnixMs: identity.sessionStartUnixMs,
3185
+ lastActivityUnixMs: this.lastActivityUnixMs,
3186
+ nextChunkIndex: identity.chunkIndex
3187
+ };
3188
+ void this.safeSet(this.sessionKey, JSON.stringify(state));
3189
+ return { ...identity };
3190
+ }
3191
+ async takeChunkIndex(nowUnixMs) {
3192
+ if (!this.identity) {
3193
+ await this.resolve(nowUnixMs);
3194
+ }
3195
+ const identity = this.identity;
3196
+ const index = identity.chunkIndex;
3197
+ identity.chunkIndex += 1;
3198
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
3199
+ const state = {
3200
+ sessionId: identity.sessionId,
3201
+ sessionStartUnixMs: identity.sessionStartUnixMs,
3202
+ lastActivityUnixMs: nowUnixMs,
3203
+ nextChunkIndex: identity.chunkIndex
3204
+ };
3205
+ await this.safeSet(this.sessionKey, JSON.stringify(state));
3206
+ return index;
3207
+ }
3208
+ getNextChunkIndex() {
3209
+ return this.identity?.chunkIndex ?? null;
3210
+ }
3211
+ async rotate(nowUnixMs) {
3212
+ let visitorId = await this.safeGet(this.visitorKey);
3213
+ if (!isReplayId(visitorId)) {
3214
+ visitorId = generateReplayId();
3215
+ await this.safeSet(this.visitorKey, visitorId);
3216
+ }
3217
+ const session = {
3218
+ sessionId: generateReplayId(),
3219
+ sessionStartUnixMs: nowUnixMs,
3220
+ lastActivityUnixMs: nowUnixMs,
3221
+ nextChunkIndex: 0
3222
+ };
3223
+ await this.safeSet(this.sessionKey, JSON.stringify(session));
3224
+ this.identity = {
3225
+ sessionId: session.sessionId,
3226
+ tabId: generateReplayId(),
3227
+ visitorId,
3228
+ sessionStartUnixMs: nowUnixMs,
3229
+ chunkIndex: 0
3230
+ };
3231
+ this.lastActivityUnixMs = nowUnixMs;
3232
+ return { ...this.identity };
3233
+ }
3234
+ /*
3235
+ * Forget the stored session without starting the next one. A session
3236
+ * that ends while the recorder is paused for idle has no successor until
3237
+ * the person comes back, and its record - last written by its own final
3238
+ * chunk, so it looks recent - would otherwise let a relaunch in the
3239
+ * meantime carry on a session that is already over. The visitor id stays,
3240
+ * and so does the in-memory identity: nothing more is sent under it, and
3241
+ * the next rotate() writes the new session.
3242
+ */
3243
+ async end() {
3244
+ await this.safeRemove(this.sessionKey);
3245
+ }
3246
+ async clear() {
3247
+ this.identity = null;
3248
+ await Promise.all([
3249
+ this.safeRemove(this.sessionKey),
3250
+ this.safeRemove(this.visitorKey)
3251
+ ]);
3252
+ }
3253
+ async safeGet(key) {
3254
+ try {
3255
+ return await this.storage.getItem(key);
3256
+ } catch {
3257
+ return null;
3258
+ }
3259
+ }
3260
+ async safeSet(key, value) {
3261
+ try {
3262
+ await this.storage.setItem(key, value);
3263
+ } catch {
3264
+ }
3265
+ }
3266
+ async safeRemove(key) {
3267
+ try {
3268
+ await this.storage.removeItem(key);
3269
+ } catch {
3270
+ }
3271
+ }
3272
+ };
3273
+
3274
+ // src/ProductAnalytics.ts
3275
+ var PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS = 1e4;
3276
+ var PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS = 5 * 60 * 1e3;
3277
+ var RETRY_AFTER_LIMIT_SECONDS = 300;
3278
+ var REPLAY_ID_PATTERN2 = /^[0-9a-f]{32}$/u;
3279
+ function productAnalyticsSessionKey(namespace) {
3280
+ return `@oneuptime/replay/${namespace}/analytics-session`;
3281
+ }
3282
+ function productAnalyticsQueueKey(namespace) {
3283
+ return `@oneuptime/replay/${namespace}/analytics-queue`;
3284
+ }
3285
+ var PRODUCT_ANALYTICS_STORED_QUEUE_VERSION = 1;
3286
+ var PRODUCT_ANALYTICS_MAX_STORED_BYTES = 512 * 1024;
3287
+ var PRODUCT_ANALYTICS_STORE_DELAY_MS = 1e3;
3288
+ var storeWrites = /* @__PURE__ */ new WeakMap();
3289
+ function writesOf(storage) {
3290
+ let writes = storeWrites.get(storage);
3291
+ if (!writes) {
3292
+ writes = /* @__PURE__ */ new Map();
3293
+ storeWrites.set(storage, writes);
3294
+ }
3295
+ return writes;
3296
+ }
3297
+ function enqueueStoreWrite(storage, key, write) {
3298
+ const writes = writesOf(storage);
3299
+ const run = async () => {
3300
+ try {
3301
+ await write();
3302
+ } catch {
3303
+ }
3304
+ };
3305
+ const next = (writes.get(key) ?? Promise.resolve()).then(
3306
+ run,
3307
+ run
3308
+ );
3309
+ writes.set(key, next);
3310
+ return next;
3311
+ }
3312
+ async function storeWritesSettled(storage, key) {
3313
+ try {
3314
+ await writesOf(storage).get(key);
3315
+ } catch {
3316
+ }
3317
+ }
3318
+ async function clearStoredProductAnalytics(storage, namespace) {
3319
+ await Promise.all([
3320
+ enqueueStoreWrite(
3321
+ storage,
3322
+ productAnalyticsQueueKey(namespace),
3323
+ async () => {
3324
+ await storage.removeItem(productAnalyticsQueueKey(namespace));
3325
+ }
3326
+ ),
3327
+ enqueueStoreWrite(
3328
+ storage,
3329
+ productAnalyticsSessionKey(namespace),
3330
+ async () => {
3331
+ await storage.removeItem(productAnalyticsSessionKey(namespace));
3332
+ }
3333
+ )
3334
+ ]);
3335
+ }
3336
+ var EVENT_KINDS = [
3337
+ "session" /* Session */,
3338
+ "page" /* Page */,
3339
+ "custom" /* Custom */
3340
+ ];
3341
+ function isPlainRecord(value) {
3342
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3343
+ }
3344
+ function isStringMap(value) {
3345
+ return isPlainRecord(value) && Object.keys(value).every((key) => {
3346
+ return typeof value[key] === "string";
3347
+ });
3348
+ }
3349
+ function isFiniteTime(value) {
3350
+ return typeof value === "number" && Number.isFinite(value);
3351
+ }
3352
+ function readStoredEvent(value) {
3353
+ if (!isPlainRecord(value) || typeof value["kind"] !== "string" || EVENT_KINDS.indexOf(value["kind"]) === -1 || typeof value["name"] !== "string" || !isFiniteTime(value["at"]) || value["page"] !== void 0 && typeof value["page"] !== "string" || value["properties"] !== void 0 && !isStringMap(value["properties"])) {
3354
+ return null;
3355
+ }
3356
+ const event = {
3357
+ kind: value["kind"],
3358
+ name: value["name"],
3359
+ at: value["at"]
3360
+ };
3361
+ if (typeof value["page"] === "string") {
3362
+ event.page = value["page"];
3363
+ }
3364
+ if (isStringMap(value["properties"])) {
3365
+ event.properties = value["properties"];
3366
+ }
3367
+ return event;
3368
+ }
3369
+ function readStoredMetric(value) {
3370
+ if (!isPlainRecord(value) || !isProductAnalyticsMetricName(value["name"]) || !isFiniteTime(value["value"]) || !isFiniteTime(value["at"]) || value["attributes"] !== void 0 && !isStringMap(value["attributes"])) {
3371
+ return null;
3372
+ }
3373
+ const metric = {
3374
+ name: value["name"],
3375
+ value: value["value"],
3376
+ at: value["at"]
3377
+ };
3378
+ if (isStringMap(value["attributes"])) {
3379
+ metric.attributes = value["attributes"];
3380
+ }
3381
+ return metric;
3382
+ }
3383
+ function readStoredScope(value) {
3384
+ if (!isPlainRecord(value) || typeof value["sessionId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["sessionId"]) || typeof value["userRef"] !== "string" || value["userProperties"] !== null && !isStringMap(value["userProperties"])) {
3385
+ return null;
3386
+ }
3387
+ return {
3388
+ sessionId: value["sessionId"],
3389
+ userRef: value["userRef"],
3390
+ userProperties: value["userProperties"]
3391
+ };
3392
+ }
3393
+ function readStoredBatch(value) {
3394
+ if (!isPlainRecord(value) || value["v"] !== PRODUCT_ANALYTICS_WIRE_VERSION || typeof value["batchId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["batchId"]) || typeof value["sessionId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["sessionId"]) || typeof value["visitorId"] !== "string" || typeof value["consentState"] !== "string" || !isFiniteTime(value["sentAt"]) || !isStringMap(value["context"]) || !Array.isArray(value["events"]) || !Array.isArray(value["metrics"]) || value["events"].length > PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH || value["metrics"].length > PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH || value["userRef"] !== void 0 && typeof value["userRef"] !== "string" || value["userProperties"] !== void 0 && !isStringMap(value["userProperties"])) {
3395
+ return null;
3396
+ }
3397
+ const events = [];
3398
+ const metrics = [];
3399
+ for (const entry of value["events"]) {
3400
+ const event = readStoredEvent(entry);
3401
+ if (!event) {
3402
+ return null;
3403
+ }
3404
+ events.push(event);
3405
+ }
3406
+ for (const entry of value["metrics"]) {
3407
+ const metric = readStoredMetric(entry);
3408
+ if (!metric) {
3409
+ return null;
3410
+ }
3411
+ metrics.push(metric);
3412
+ }
3413
+ const context = value["context"];
3414
+ const batch = {
3415
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
3416
+ batchId: value["batchId"],
3417
+ sessionId: value["sessionId"],
3418
+ visitorId: value["visitorId"],
3419
+ consentState: value["consentState"],
3420
+ sentAt: value["sentAt"],
3421
+ context: {
3422
+ deviceType: context["deviceType"] ?? "",
3423
+ browserName: context["browserName"] ?? "",
3424
+ osName: context["osName"] ?? "",
3425
+ appVersion: context["appVersion"] ?? ""
3426
+ },
3427
+ events,
3428
+ metrics
3429
+ };
3430
+ if (typeof value["userRef"] === "string") {
3431
+ batch.userRef = value["userRef"];
3432
+ batch.userProperties = isStringMap(value["userProperties"]) ? value["userProperties"] : {};
3433
+ }
3434
+ return batch;
3435
+ }
3436
+ function readStoredQueue(raw) {
3437
+ if (!raw) {
3438
+ return null;
3439
+ }
3440
+ let parsed;
3441
+ try {
3442
+ parsed = JSON.parse(raw);
3443
+ } catch {
3444
+ return null;
3445
+ }
3446
+ if (!isPlainRecord(parsed) || parsed["v"] !== PRODUCT_ANALYTICS_STORED_QUEUE_VERSION || !Array.isArray(parsed["scopes"]) || !Array.isArray(parsed["items"])) {
3447
+ return null;
3448
+ }
3449
+ const scopes = parsed["scopes"].map(readStoredScope);
3450
+ const items = [];
3451
+ for (const entry of parsed["items"]) {
3452
+ if (!isPlainRecord(entry) || typeof entry["s"] !== "number") {
3453
+ continue;
3454
+ }
3455
+ const scope = scopes[entry["s"]];
3456
+ if (!scope) {
3457
+ continue;
3458
+ }
3459
+ if (entry["e"] !== void 0) {
3460
+ const event = readStoredEvent(
3461
+ entry["e"]
3462
+ );
3463
+ if (event) {
3464
+ items.push({ scope, event });
3465
+ }
3466
+ continue;
3467
+ }
3468
+ const metric = readStoredMetric(
3469
+ entry["m"]
3470
+ );
3471
+ if (metric) {
3472
+ items.push({ scope, metric });
3473
+ }
3474
+ }
3475
+ return {
3476
+ items,
3477
+ pending: parsed["pending"] === null || parsed["pending"] === void 0 ? null : readStoredBatch(parsed["pending"])
3478
+ };
3479
+ }
3480
+ function scopeKey(scope) {
3481
+ return JSON.stringify([scope.sessionId, scope.userRef, scope.userProperties]);
3482
+ }
3483
+ function buildStoredQueue(items, pending) {
3484
+ const named = items.filter((item) => {
3485
+ return item.scope.sessionId !== "";
3486
+ });
3487
+ if (named.length === 0 && !pending) {
3488
+ return null;
3489
+ }
3490
+ const build = (from2) => {
3491
+ const scopes = [];
3492
+ const scopeIndex = /* @__PURE__ */ new Map();
3493
+ const stored = [];
3494
+ for (const item of named.slice(from2)) {
3495
+ const key = scopeKey(item.scope);
3496
+ let index = scopeIndex.get(key);
3497
+ if (index === void 0) {
3498
+ index = scopes.length;
3499
+ scopes.push(item.scope);
3500
+ scopeIndex.set(key, index);
3501
+ }
3502
+ if (item.event) {
3503
+ stored.push({ s: index, e: item.event });
3504
+ } else if (item.metric) {
3505
+ stored.push({ s: index, m: item.metric });
3506
+ }
3507
+ }
3508
+ const queue = {
3509
+ v: PRODUCT_ANALYTICS_STORED_QUEUE_VERSION,
3510
+ scopes,
3511
+ items: stored,
3512
+ pending
3513
+ };
3514
+ return JSON.stringify(queue);
3515
+ };
3516
+ let from = 0;
3517
+ let value = build(from);
3518
+ if (byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {
3519
+ return value;
3520
+ }
3521
+ let low = 1;
3522
+ let high = named.length;
3523
+ while (low < high) {
3524
+ const middle = Math.floor((low + high) / 2);
3525
+ if (byteLength(build(middle)) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {
3526
+ high = middle;
3527
+ } else {
3528
+ low = middle + 1;
3529
+ }
3530
+ }
3531
+ from = low;
3532
+ value = build(from);
3533
+ return byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES ? value : null;
3534
+ }
3535
+ function itemAt(item) {
3536
+ return item.event ? item.event.at : item.metric?.at ?? 0;
3537
+ }
3538
+ function sameScope(left, right) {
3539
+ return left.sessionId === right.sessionId && left.userRef === right.userRef && JSON.stringify(left.userProperties) === JSON.stringify(right.userProperties);
3540
+ }
3541
+ function pickProductAnalyticsUserProperties(traits, allowedKeys) {
3542
+ const picked = {};
3543
+ if (!traits) {
3544
+ return picked;
3545
+ }
3546
+ for (const key of allowedKeys) {
3547
+ if (Object.prototype.hasOwnProperty.call(traits, key) && typeof traits[key] === "string") {
3548
+ picked[key] = traits[key];
3549
+ }
3550
+ }
3551
+ return picked;
3552
+ }
3553
+ var MobileProductAnalytics = class {
3554
+ constructor(host, config) {
3555
+ __publicField(this, "host");
3556
+ __publicField(this, "config");
3557
+ __publicField(this, "items", []);
3558
+ __publicField(this, "eventCount", 0);
3559
+ __publicField(this, "metricCount", 0);
3560
+ /*
3561
+ * The batch on its way, kept until the server says what became of it, so
3562
+ * a retry sends the same batch id and the server files it once.
3563
+ */
3564
+ __publicField(this, "pending", null);
3565
+ __publicField(this, "sending", false);
3566
+ __publicField(this, "sendGeneration", 0);
3567
+ __publicField(this, "retryAtUnixMs", 0);
3568
+ __publicField(this, "failures", 0);
3569
+ /* The session items are filed under now, and the screen shown in it. */
3570
+ __publicField(this, "sessionId", "");
3571
+ __publicField(this, "shownPage", "");
3572
+ /* The last screen the app named, in any session. */
3573
+ __publicField(this, "route", "");
3574
+ /* The session this device last announced; null until read. */
3575
+ __publicField(this, "announcedSessionId", null);
3576
+ __publicField(this, "droppedEvents", 0);
3577
+ __publicField(this, "started", false);
3578
+ __publicField(this, "stopReason", null);
3579
+ __publicField(this, "revoked", false);
3580
+ /* The connectivity source said the device is offline. */
3581
+ __publicField(this, "offline", false);
3582
+ __publicField(this, "flushTimer", null);
3583
+ __publicField(this, "appStateSubscription", null);
3584
+ __publicField(this, "unsubscribeConnectivity", null);
3585
+ /*
3586
+ * The stored queue (issue #9577). Written only once what a previous run
3587
+ * left there has been read back, so a channel that never got that far
3588
+ * can never overwrite it with nothing.
3589
+ */
3590
+ __publicField(this, "restored", false);
3591
+ __publicField(this, "storeTimer", null);
3592
+ this.host = host;
3593
+ this.config = config;
3594
+ }
3595
+ /*
3596
+ * Reads which session this device last announced, then starts: the
3597
+ * session's start (unless announced already), the timer, and the app's
3598
+ * lifecycle and connectivity. Items before this resolves are not taken.
3599
+ */
3600
+ async start() {
3601
+ if (this.started || this.stopReason) {
3602
+ return;
3603
+ }
3604
+ let stored = null;
3605
+ let storedQueue = null;
3606
+ const queueKey = productAnalyticsQueueKey(this.host.namespace);
3607
+ await storeWritesSettled(this.host.storage, queueKey);
3608
+ try {
3609
+ stored = await this.host.storage.getItem(
3610
+ productAnalyticsSessionKey(this.host.namespace)
3611
+ );
3612
+ } catch {
3613
+ stored = null;
3614
+ }
3615
+ try {
3616
+ storedQueue = await this.host.storage.getItem(queueKey);
3617
+ } catch {
3618
+ storedQueue = null;
3619
+ }
3620
+ if (this.started || this.stopReason) {
3621
+ return;
3622
+ }
3623
+ this.announcedSessionId = typeof stored === "string" && REPLAY_ID_PATTERN2.test(stored) ? stored : null;
3624
+ this.started = true;
3625
+ this.restored = true;
3626
+ if (!this.revoked) {
3627
+ this.restoreQueue(storedQueue, this.host.now());
3628
+ }
3629
+ this.enterCurrentSession(this.host.now(), false);
3630
+ this.flushTimer = setInterval(() => {
3631
+ this.flush(false);
3632
+ }, PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS);
3633
+ this.listenToLifecycle();
3634
+ this.host.onDiagnostic("analytics-started", {
3635
+ userPropertyKeys: this.config.userPropertyKeys.length
3636
+ });
3637
+ }
3638
+ /* A refreshed policy's keys; whether it waits for consent is asked live. */
3639
+ setConfig(config) {
3640
+ this.config = config;
3641
+ }
3642
+ isStarted() {
3643
+ return this.started && !this.stopReason;
3644
+ }
3645
+ track(name, properties) {
3646
+ const eventName = toProductAnalyticsEventName(name);
3647
+ if (!eventName || !this.accepts()) {
3648
+ return;
3649
+ }
3650
+ const now = this.host.now();
3651
+ const scope = this.scopeNow(now);
3652
+ if (!scope) {
3653
+ return;
3654
+ }
3655
+ const event = {
3656
+ kind: "custom" /* Custom */,
3657
+ name: eventName,
3658
+ at: now,
3659
+ properties: this.host.toProperties(properties)
3660
+ };
3661
+ if (this.shownPage) {
3662
+ event.page = this.shownPage;
3663
+ } else if (this.route) {
3664
+ event.page = this.route;
3665
+ }
3666
+ this.pushEvent(scope, event);
3667
+ }
3668
+ /*
3669
+ * A screen the app moved to (setRoute(), already scrubbed as the replay
3670
+ * keeps a route): a page view, unless it is the screen already shown in
3671
+ * this session.
3672
+ */
3673
+ page(route) {
3674
+ if (!route || !this.accepts()) {
3675
+ return;
3676
+ }
3677
+ this.route = route;
3678
+ const now = this.host.now();
3679
+ const scope = this.scopeNow(now);
3680
+ if (!scope || route === this.shownPage) {
3681
+ return;
3682
+ }
3683
+ this.shownPage = route;
3684
+ this.pushEvent(scope, {
3685
+ kind: "page" /* Page */,
3686
+ name: route,
3687
+ at: now,
3688
+ page: route
3689
+ });
3690
+ }
3691
+ /*
3692
+ * metric(name, value, attributes): a number the app measured
3693
+ * ("cart.value", 42.5), filed in the metric store under the RUM
3694
+ * application. A name outside the instrument-name shape, or in
3695
+ * OneUptime's own namespace, or a value that is not a finite number, is
3696
+ * refused here and says why in the diagnostics.
3697
+ */
3698
+ metric(name, value, attributes) {
3699
+ if (!this.accepts()) {
3700
+ return;
3701
+ }
3702
+ if (!isProductAnalyticsMetricName(name)) {
3703
+ this.host.onDiagnostic("metric-name-refused", {
3704
+ name: typeof name === "string" ? name.slice(0, 100) : typeof name
3705
+ });
3706
+ return;
3707
+ }
3708
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3709
+ this.host.onDiagnostic("metric-value-refused", { name });
3710
+ return;
3711
+ }
3712
+ const now = this.host.now();
3713
+ const scope = this.scopeNow(now);
3714
+ if (!scope) {
3715
+ return;
3716
+ }
3717
+ this.items.push({
3718
+ scope,
3719
+ metric: {
3720
+ name,
3721
+ value,
3722
+ at: now,
3723
+ attributes: this.host.toProperties(attributes)
3724
+ }
3725
+ });
3726
+ this.metricCount++;
3727
+ if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3728
+ this.dropOldest("metric");
3729
+ }
3730
+ this.scheduleStore();
3731
+ if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3732
+ this.flush(false);
3733
+ }
3734
+ }
3735
+ /*
3736
+ * Send what is held. `final` is the app leaving the foreground: sent at
3737
+ * once, whatever a retry was waiting for, while the system still lets
3738
+ * the app use the network.
3739
+ */
3740
+ flush(final) {
3741
+ if (!this.started || this.stopReason || this.revoked || this.sending) {
3742
+ return;
3743
+ }
3744
+ if (this.isAwaitingConsent() || this.offline) {
3745
+ return;
3746
+ }
3747
+ const now = this.host.now();
3748
+ if (!final && now < this.retryAtUnixMs) {
3749
+ return;
3750
+ }
3751
+ if (!this.pending) {
3752
+ this.enterCurrentSession(now, false);
3753
+ this.pending = this.takeBatch(now);
3754
+ }
3755
+ const batch = this.pending;
3756
+ if (!batch) {
3757
+ return;
3758
+ }
3759
+ this.send(batch);
3760
+ }
3761
+ /*
3762
+ * Consent withdrawn: everything held is dropped, the batch on its way
3763
+ * too, the session this device announced is forgotten, and nothing is
3764
+ * kept or sent until a new grant.
3765
+ */
3766
+ forget() {
3767
+ this.revoked = true;
3768
+ this.clear();
3769
+ this.forgetStoredQueue();
3770
+ this.forgetAnnouncedSession();
3771
+ }
3772
+ /*
3773
+ * The policy now waits for a consent this run has not been given: what
3774
+ * was held, and the device's record, go as on a withdrawal, but what
3775
+ * happens from now on is held for the grant, as before any consent.
3776
+ */
3777
+ reset() {
3778
+ this.clear();
3779
+ this.forgetStoredQueue();
3780
+ this.forgetAnnouncedSession();
3781
+ }
3782
+ /* Granted: what was held is filed under the session the grant opened, and goes now. */
3783
+ onConsentGranted() {
3784
+ this.revoked = false;
3785
+ this.retryAtUnixMs = 0;
3786
+ this.enterCurrentSession(this.host.now(), false);
3787
+ this.scheduleStore();
3788
+ this.flush(false);
3789
+ }
3790
+ /*
3791
+ * The recorder's session may have changed under the channel - a policy
3792
+ * refreshed, a session named after consent: what was held for it is
3793
+ * filed under it, and what can go, goes.
3794
+ */
3795
+ refresh() {
3796
+ if (!this.accepts()) {
3797
+ return;
3798
+ }
3799
+ this.enterCurrentSession(this.host.now(), false);
3800
+ this.scheduleStore();
3801
+ this.flush(false);
3802
+ }
3803
+ stop(reason = "stopped") {
3804
+ const isFirstStop = !this.stopReason;
3805
+ if (!this.stopReason) {
3806
+ this.stopReason = reason;
3807
+ }
3808
+ if (isFirstStop && this.restored) {
3809
+ if (reason === "stopped") {
3810
+ this.storeNow();
3811
+ } else {
3812
+ this.forgetStoredQueue();
3813
+ }
3814
+ }
3815
+ this.clear();
3816
+ this.cancelStoreTimer();
3817
+ if (this.flushTimer) {
3818
+ clearInterval(this.flushTimer);
3819
+ this.flushTimer = null;
3820
+ }
3821
+ this.appStateSubscription?.remove();
3822
+ this.appStateSubscription = null;
3823
+ const unsubscribe = this.unsubscribeConnectivity;
3824
+ this.unsubscribeConnectivity = null;
3825
+ try {
3826
+ unsubscribe?.();
3827
+ } catch {
3828
+ }
3829
+ }
3830
+ getStopReason() {
3831
+ return this.stopReason;
3832
+ }
3833
+ getPendingCount() {
3834
+ return this.items.length + (this.pending ? this.pending.events.length + this.pending.metrics.length : 0);
3835
+ }
3836
+ getDroppedEventCount() {
3837
+ return this.droppedEvents;
3838
+ }
3839
+ getDiagnostics() {
3840
+ return {
3841
+ state: this.stopReason || "on",
3842
+ pending: this.getPendingCount(),
3843
+ dropped: this.droppedEvents
3844
+ };
3845
+ }
3846
+ accepts() {
3847
+ return this.started && !this.stopReason && !this.revoked;
3848
+ }
3849
+ isAwaitingConsent() {
3850
+ return this.host.requiresConsent() && this.host.getConsentState() !== "Granted";
3851
+ }
3852
+ clear() {
3853
+ this.items = [];
3854
+ this.eventCount = 0;
3855
+ this.metricCount = 0;
3856
+ this.pending = null;
3857
+ this.sendGeneration++;
3858
+ this.sending = false;
3859
+ this.sessionId = "";
3860
+ this.shownPage = "";
3861
+ }
3862
+ forgetAnnouncedSession() {
3863
+ this.announcedSessionId = null;
3864
+ void this.host.storage.removeItem(productAnalyticsSessionKey(this.host.namespace)).catch(() => {
3865
+ });
3866
+ }
3867
+ announce(sessionId) {
3868
+ this.announcedSessionId = sessionId;
3869
+ void this.host.storage.setItem(productAnalyticsSessionKey(this.host.namespace), sessionId).catch(() => {
3870
+ });
3871
+ }
3872
+ makeScope(sessionId) {
3873
+ const identity = this.host.getIdentity();
3874
+ return {
3875
+ sessionId,
3876
+ userRef: identity.userRef,
3877
+ userProperties: identity.userRef ? pickProductAnalyticsUserProperties(
3878
+ identity.traits,
3879
+ this.config.userPropertyKeys
3880
+ ) : null
3881
+ };
3882
+ }
3883
+ /*
3884
+ * The scope of an item that happens now, or null when it has none to be
3885
+ * filed under (no session, and no consent being waited for).
3886
+ */
3887
+ scopeNow(now) {
3888
+ const sessionId = this.enterCurrentSession(now, true);
3889
+ if (sessionId) {
3890
+ return this.makeScope(sessionId);
3891
+ }
3892
+ return this.isAwaitingConsent() ? this.makeScope("") : null;
3893
+ }
3894
+ /*
3895
+ * Follows the host's session: a new one starts with its start (once per
3896
+ * session on this device) and the screen the app shows, and items held
3897
+ * before consent are filed under the first session there is to name.
3898
+ * Returns the session, or "" when there is none to name. Only an item
3899
+ * that happens now is activity (isActivity); the timer only looks.
3900
+ */
3901
+ enterCurrentSession(now, isActivity) {
3902
+ const sessionId = isActivity ? this.host.getSessionId(now) : this.host.peekSessionId();
3903
+ if (!sessionId) {
3904
+ return "";
3905
+ }
3906
+ const firstUnnamed = this.items.findIndex(
3907
+ (item) => {
3908
+ return item.scope.sessionId === "";
3909
+ }
3910
+ );
3911
+ if (sessionId === this.sessionId && firstUnnamed < 0) {
3912
+ return sessionId;
3913
+ }
3914
+ const isNewSession = sessionId !== this.sessionId;
3915
+ this.sessionId = sessionId;
3916
+ let startedAt = now;
3917
+ let startPage = this.route;
3918
+ let startScope = this.makeScope(sessionId);
3919
+ if (firstUnnamed >= 0) {
3920
+ const first = this.items[firstUnnamed];
3921
+ startedAt = Math.min(now, itemAt(first));
3922
+ startPage = first.event?.page || this.route;
3923
+ startScope = { ...first.scope, sessionId };
3924
+ for (const item of this.items) {
3925
+ if (item.scope.sessionId === "") {
3926
+ item.scope = { ...item.scope, sessionId };
3927
+ }
3928
+ }
3929
+ } else if (isNewSession) {
3930
+ this.shownPage = "";
3931
+ }
3932
+ if (this.announcedSessionId !== sessionId) {
3933
+ const start = {
3934
+ kind: "session" /* Session */,
3935
+ name: "",
3936
+ at: startedAt
3937
+ };
3938
+ if (startPage) {
3939
+ start.page = startPage;
3940
+ }
3941
+ const item = { scope: startScope, event: start };
3942
+ if (firstUnnamed >= 0) {
3943
+ this.items.splice(firstUnnamed, 0, item);
3944
+ } else {
3945
+ this.items.push(item);
3946
+ }
3947
+ this.eventCount++;
3948
+ this.announce(sessionId);
3949
+ this.trimEvents();
3950
+ this.scheduleStore();
3951
+ }
3952
+ if (firstUnnamed < 0 && isNewSession && this.route) {
3953
+ this.shownPage = this.route;
3954
+ this.items.push({
3955
+ scope: this.makeScope(sessionId),
3956
+ event: {
3957
+ kind: "page" /* Page */,
3958
+ name: this.route,
3959
+ at: now,
3960
+ page: this.route
3961
+ }
3962
+ });
3963
+ this.eventCount++;
3964
+ this.trimEvents();
3965
+ this.scheduleStore();
3966
+ }
3967
+ return sessionId;
3968
+ }
3969
+ pushEvent(scope, event) {
3970
+ this.items.push({ scope, event });
3971
+ this.eventCount++;
3972
+ this.trimEvents();
3973
+ this.scheduleStore();
3974
+ if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3975
+ this.flush(false);
3976
+ }
3977
+ }
3978
+ /* Held too long (no consent, no network): the oldest go first, counted. */
3979
+ trimEvents() {
3980
+ while (this.eventCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3981
+ this.dropOldest("event");
3982
+ this.droppedEvents++;
3983
+ }
3984
+ }
3985
+ dropOldest(kind) {
3986
+ const index = this.items.findIndex((item) => {
3987
+ return kind === "event" ? Boolean(item.event) : Boolean(item.metric);
3988
+ });
3989
+ if (index < 0) {
3990
+ return;
3991
+ }
3992
+ this.items.splice(index, 1);
3993
+ if (kind === "event") {
3994
+ this.eventCount--;
3995
+ } else {
3996
+ this.metricCount--;
3997
+ }
3998
+ }
3999
+ /*
4000
+ * The next batch: the oldest items of one session and one person, up to
4001
+ * the per-batch counts and the target size. Items the server would drop
4002
+ * for their age are dropped here instead.
4003
+ */
4004
+ takeBatch(now) {
4005
+ this.dropTooOld(now);
4006
+ const first = this.items[0];
4007
+ if (!first || first.scope.sessionId === "") {
4008
+ return null;
4009
+ }
4010
+ const scope = first.scope;
4011
+ let count = 0;
4012
+ let events = 0;
4013
+ let metrics = 0;
4014
+ for (const item of this.items) {
4015
+ if (!sameScope(item.scope, scope)) {
4016
+ break;
4017
+ }
4018
+ if (item.event) {
4019
+ if (events >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
4020
+ break;
4021
+ }
4022
+ events++;
4023
+ } else {
4024
+ if (metrics >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
4025
+ break;
4026
+ }
4027
+ metrics++;
4028
+ }
4029
+ count++;
4030
+ }
4031
+ const build = (taken) => {
4032
+ const slice = this.items.slice(0, taken);
4033
+ const batch2 = {
4034
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
4035
+ batchId: generateReplayId(),
4036
+ sessionId: scope.sessionId,
4037
+ visitorId: this.host.getVisitorId(),
4038
+ consentState: this.host.getConsentState(),
4039
+ sentAt: now,
4040
+ context: this.host.getContext(),
4041
+ events: slice.filter((item) => {
4042
+ return Boolean(item.event);
4043
+ }).map((item) => {
4044
+ return item.event;
4045
+ }),
4046
+ metrics: slice.filter((item) => {
4047
+ return Boolean(item.metric);
4048
+ }).map((item) => {
4049
+ return item.metric;
4050
+ })
4051
+ };
4052
+ if (scope.userRef) {
4053
+ batch2.userRef = scope.userRef;
4054
+ batch2.userProperties = scope.userProperties || {};
4055
+ }
4056
+ return batch2;
4057
+ };
4058
+ let batch = build(count);
4059
+ while (JSON.stringify(batch).length > PRODUCT_ANALYTICS_TARGET_BATCH_BYTES && count > 1) {
4060
+ count = Math.floor(count / 2);
4061
+ batch = build(count);
4062
+ }
4063
+ this.items.splice(0, count);
4064
+ this.eventCount -= batch.events.length;
4065
+ this.metricCount -= batch.metrics.length;
4066
+ this.scheduleStore();
4067
+ return batch;
4068
+ }
4069
+ dropTooOld(now) {
4070
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
4071
+ const kept = [];
4072
+ for (const item of this.items) {
4073
+ if (itemAt(item) >= oldest) {
4074
+ kept.push(item);
4075
+ continue;
4076
+ }
4077
+ if (item.event) {
4078
+ this.eventCount--;
4079
+ this.droppedEvents++;
4080
+ } else {
4081
+ this.metricCount--;
4082
+ }
4083
+ }
4084
+ if (kept.length !== this.items.length) {
4085
+ this.scheduleStore();
4086
+ }
4087
+ this.items = kept;
4088
+ }
4089
+ /*
4090
+ * What a previous run left in the device's storage (issue #9577), taken
4091
+ * back before anything new: the items under the sessions and people they
4092
+ * happened under, the batch that was on its way under its own id. What
4093
+ * the server would no longer keep (PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS) is
4094
+ * left out, and the caps apply as to anything held: past them the oldest
4095
+ * events go, counted in the diagnostics' dropped.
4096
+ */
4097
+ restoreQueue(raw, now) {
4098
+ if (!raw) {
4099
+ return;
4100
+ }
4101
+ const queue = readStoredQueue(raw);
4102
+ if (!queue) {
4103
+ this.host.onDiagnostic("analytics-store-unreadable");
4104
+ this.forgetStoredQueue();
4105
+ return;
4106
+ }
4107
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
4108
+ const droppedBefore = this.droppedEvents;
4109
+ let tooOld = 0;
4110
+ const pending = queue.pending;
4111
+ if (pending) {
4112
+ const isLive = [...pending.events, ...pending.metrics].some(
4113
+ (item) => {
4114
+ return item.at >= oldest;
4115
+ }
4116
+ );
4117
+ if (isLive) {
4118
+ this.pending = pending;
4119
+ } else {
4120
+ this.droppedEvents += pending.events.length;
4121
+ tooOld += pending.events.length + pending.metrics.length;
4122
+ }
4123
+ }
4124
+ this.items = queue.items.filter((item) => {
4125
+ if (itemAt(item) >= oldest) {
4126
+ return true;
4127
+ }
4128
+ if (item.event) {
4129
+ this.droppedEvents++;
4130
+ }
4131
+ tooOld++;
4132
+ return false;
4133
+ });
4134
+ this.eventCount = this.items.filter((item) => {
4135
+ return Boolean(item.event);
4136
+ }).length;
4137
+ this.metricCount = this.items.length - this.eventCount;
4138
+ const droppedTooOld = this.droppedEvents - droppedBefore;
4139
+ this.trimEvents();
4140
+ while (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
4141
+ this.dropOldest("metric");
4142
+ }
4143
+ this.host.onDiagnostic("analytics-restored", {
4144
+ events: this.eventCount + (this.pending?.events.length ?? 0),
4145
+ metrics: this.metricCount + (this.pending?.metrics.length ?? 0),
4146
+ droppedTooOld,
4147
+ droppedOverCap: this.droppedEvents - droppedBefore - droppedTooOld
4148
+ });
4149
+ if (tooOld > 0 || this.items.length < queue.items.length) {
4150
+ this.scheduleStore();
4151
+ }
4152
+ }
4153
+ /* A change to what is held: written once the burst it belongs to is over. */
4154
+ scheduleStore() {
4155
+ if (!this.restored || this.stopReason || this.storeTimer) {
4156
+ return;
4157
+ }
4158
+ this.storeTimer = setTimeout(() => {
4159
+ this.storeTimer = null;
4160
+ this.storeNow();
4161
+ }, PRODUCT_ANALYTICS_STORE_DELAY_MS);
4162
+ }
4163
+ /* What is held, written now, in the order the writes were asked for. */
4164
+ storeNow() {
4165
+ this.cancelStoreTimer();
4166
+ if (!this.restored || this.revoked) {
4167
+ return;
4168
+ }
4169
+ const storage = this.host.storage;
4170
+ const key = productAnalyticsQueueKey(this.host.namespace);
4171
+ const value = buildStoredQueue(this.items, this.pending);
4172
+ void enqueueStoreWrite(storage, key, async () => {
4173
+ if (value === null) {
4174
+ await storage.removeItem(key);
4175
+ } else {
4176
+ await storage.setItem(key, value);
4177
+ }
4178
+ });
4179
+ }
4180
+ forgetStoredQueue() {
4181
+ this.cancelStoreTimer();
4182
+ const storage = this.host.storage;
4183
+ const key = productAnalyticsQueueKey(this.host.namespace);
4184
+ void enqueueStoreWrite(storage, key, async () => {
4185
+ await storage.removeItem(key);
4186
+ });
4187
+ }
4188
+ cancelStoreTimer() {
4189
+ if (this.storeTimer) {
4190
+ clearTimeout(this.storeTimer);
4191
+ this.storeTimer = null;
4192
+ }
4193
+ }
4194
+ send(batch) {
4195
+ const generation = this.sendGeneration;
4196
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
4197
+ let timeout = null;
4198
+ const init = {
4199
+ method: "POST",
4200
+ headers: {
4201
+ ...this.host.headers,
4202
+ "Content-Type": PRODUCT_ANALYTICS_CONTENT_TYPE
4203
+ },
4204
+ body: JSON.stringify({ ...batch, sentAt: this.host.now() })
4205
+ };
4206
+ if (controller) {
4207
+ init.signal = controller.signal;
4208
+ }
4209
+ let request;
4210
+ try {
4211
+ request = this.host.fetch(this.host.url, init);
4212
+ } catch {
4213
+ this.retryLater(this.host.now(), 0);
4214
+ return;
4215
+ }
4216
+ const deadline = new Promise(
4217
+ (_resolve, reject) => {
4218
+ timeout = setTimeout(() => {
4219
+ controller?.abort();
4220
+ reject(new Error("analytics-request-timeout"));
4221
+ }, PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS);
4222
+ }
4223
+ );
4224
+ this.sending = true;
4225
+ Promise.race([request, deadline]).then((response) => {
4226
+ if (generation !== this.sendGeneration) {
4227
+ return;
4228
+ }
4229
+ this.sending = false;
4230
+ this.onAnswer(response, this.host.now());
4231
+ }).catch(() => {
4232
+ if (generation !== this.sendGeneration) {
4233
+ return;
4234
+ }
4235
+ this.sending = false;
4236
+ this.retryLater(this.host.now(), 0);
4237
+ }).finally(() => {
4238
+ if (timeout) {
4239
+ clearTimeout(timeout);
4240
+ }
4241
+ });
4242
+ }
4243
+ onAnswer(response, now) {
4244
+ const status = response.status;
4245
+ if (status === 202 || status === 200) {
4246
+ this.pending = null;
4247
+ this.failures = 0;
4248
+ this.scheduleStore();
4249
+ if (this.items.length > 0) {
4250
+ this.flush(false);
4251
+ }
4252
+ return;
4253
+ }
4254
+ if (status === 413) {
4255
+ this.pending = null;
4256
+ this.scheduleStore();
4257
+ return;
4258
+ }
4259
+ if (status === 204 || status === 400 || status === 403) {
4260
+ let reason = "";
4261
+ try {
4262
+ reason = response.headers?.get("x-oneuptime-replay-reason") || "";
4263
+ } catch {
4264
+ reason = "";
4265
+ }
4266
+ this.host.onDiagnostic("analytics-stopped", {
4267
+ status,
4268
+ reason: reason.slice(0, 100)
4269
+ });
4270
+ this.stop(
4271
+ status === 403 ? "origin-not-allowed" : status === 204 ? "not-enabled" : "refused"
4272
+ );
4273
+ return;
4274
+ }
4275
+ const retryAfterMs = status === 429 || status === 503 ? RetryAfter.msFromHeaders(response.headers, {
4276
+ maxMs: RETRY_AFTER_LIMIT_SECONDS * 1e3,
4277
+ nowMs: now
4278
+ }) ?? 0 : 0;
4279
+ this.retryLater(now, retryAfterMs);
3030
4280
  }
3031
- // parseMs of a response's Retry-After header.
3032
- static msFromHeaders(headers, options) {
3033
- return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
3034
- }
3035
- // parseSeconds of a response's Retry-After header.
3036
- static secondsFromHeaders(headers, options) {
3037
- return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
4281
+ retryLater(now, delayMs) {
4282
+ this.failures++;
4283
+ this.retryAtUnixMs = now + (delayMs > 0 ? delayMs : Math.min(
4284
+ PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS,
4285
+ PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS * Math.pow(2, this.failures)
4286
+ ));
3038
4287
  }
3039
4288
  /*
3040
- * An HTTP-date in any of its three shapes, exactly as written, as
3041
- * milliseconds since the epoch; undefined for anything else. nowMs is what
3042
- * an RFC 850 date's two-digit year is read against.
4289
+ * The app leaving the foreground sends what is held while it still can;
4290
+ * coming back, or the device saying it is online again, sends a batch
4291
+ * that waited at once, rather than when its retry was due.
3043
4292
  */
3044
- static parseHttpDate(value, nowMs) {
3045
- let match = IMF_FIXDATE.exec(value);
3046
- if (match) {
3047
- return toUtcMs(
3048
- Number(match[3]),
3049
- match[2],
3050
- match[1],
3051
- match[4],
3052
- match[5],
3053
- match[6]
3054
- );
4293
+ listenToLifecycle() {
4294
+ const appState = this.host.appState;
4295
+ if (appState && typeof appState.addEventListener === "function") {
4296
+ try {
4297
+ this.appStateSubscription = appState.addEventListener(
4298
+ "change",
4299
+ (state) => {
4300
+ if (state === "active") {
4301
+ this.retryAtUnixMs = 0;
4302
+ this.flush(false);
4303
+ return;
4304
+ }
4305
+ this.flush(true);
4306
+ this.storeNow();
4307
+ }
4308
+ );
4309
+ } catch {
4310
+ this.appStateSubscription = null;
4311
+ }
3055
4312
  }
3056
- match = RFC_850_DATE.exec(value);
3057
- if (match) {
3058
- return readRfc850Date(match, readNow(nowMs));
4313
+ const connectivity = this.host.connectivity;
4314
+ if (!connectivity) {
4315
+ return;
4316
+ }
4317
+ try {
4318
+ const unsubscribe = connectivity.subscribe(
4319
+ (isConnected) => {
4320
+ if (isConnected === false) {
4321
+ this.offline = true;
4322
+ return;
4323
+ }
4324
+ if (isConnected === true) {
4325
+ const wasOffline = this.offline;
4326
+ this.offline = false;
4327
+ if (wasOffline) {
4328
+ this.retryAtUnixMs = 0;
4329
+ this.flush(false);
4330
+ }
4331
+ }
4332
+ }
4333
+ );
4334
+ this.unsubscribeConnectivity = typeof unsubscribe === "function" ? unsubscribe : null;
4335
+ } catch {
4336
+ this.unsubscribeConnectivity = null;
3059
4337
  }
3060
- match = ASCTIME_DATE.exec(value);
3061
- return match ? toUtcMs(
3062
- Number(match[6]),
3063
- match[1],
3064
- match[2],
3065
- match[3],
3066
- match[4],
3067
- match[5]
3068
- ) : void 0;
3069
4338
  }
3070
4339
  };
3071
4340
 
@@ -3494,6 +4763,8 @@ function isTouchPrivate(privacyMap, x2, y) {
3494
4763
  // src/MobileReplayRecorder.ts
3495
4764
  var MAX_DIAGNOSTIC_EVENTS = 100;
3496
4765
  var TOUCH_MOVE_SAMPLE_MS = 50;
4766
+ var TAP_SLOP_POINTS = 10;
4767
+ var MAX_TAP_CANDIDATES = 10;
3497
4768
  var MOBILE_POLICY_REFRESH_INTERVAL_MS = 5 * 6e4;
3498
4769
  var MAX_EVENTS_HELD_FOR_RESUME = 500;
3499
4770
  var SAFE_ERROR_NAMES = /* @__PURE__ */ new Set([
@@ -3583,7 +4854,7 @@ var MobileReplayRecorder = class {
3583
4854
  __publicField(this, "now");
3584
4855
  __publicField(this, "serializer", new ViewTreeSerializer());
3585
4856
  __publicField(this, "chunkBuffer", new ReplayChunkBuffer());
3586
- /* The application's own page, event and error signals (issue #6443). */
4857
+ /* The application's own tap, page, event and error signals (#6443, #6517). */
3587
4858
  __publicField(this, "customSignalMatcher", new CustomSignalMatcher());
3588
4859
  __publicField(this, "rollingBuffer", new RollingReplayBuffer());
3589
4860
  __publicField(this, "diagnosticsStatus", "idle");
@@ -3679,6 +4950,11 @@ var MobileReplayRecorder = class {
3679
4950
  __publicField(this, "suppressedTouchPointers", /* @__PURE__ */ new Set());
3680
4951
  __publicField(this, "unidentifiedTouchCount", 0);
3681
4952
  __publicField(this, "unidentifiedTouchPrivate", false);
4953
+ /*
4954
+ * Each touch still down that may yet be a tap, for the application's tap
4955
+ * signals (issue #6517): where it started and on which view.
4956
+ */
4957
+ __publicField(this, "tapCandidates", /* @__PURE__ */ new Map());
3682
4958
  /*
3683
4959
  * When the person last did something: a touch (any touch - one inside a
3684
4960
  * ReplayMask is still someone using the app, even though it is never
@@ -3727,6 +5003,19 @@ var MobileReplayRecorder = class {
3727
5003
  */
3728
5004
  __publicField(this, "softKeyboardVisible", false);
3729
5005
  __publicField(this, "keyboardSubscriptions", []);
5006
+ /*
5007
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts): beside
5008
+ * the recording, from every session the policy lets the recorder run in,
5009
+ * recorded or not. Null while the application has them off.
5010
+ */
5011
+ __publicField(this, "analytics", null);
5012
+ /*
5013
+ * The replay sample left the session out under "Always": nothing of it
5014
+ * is recorded, but its product analytics events are still sent - and,
5015
+ * nothing else moving the session, they are what keeps it alive
5016
+ * (ReplaySessionStore.continueSession), as the browser recorder does.
5017
+ */
5018
+ __publicField(this, "analyticsOnly", false);
3730
5019
  this.storage = dependencies.storage ?? defaultReplayStorage;
3731
5020
  this.nativeViewTree = dependencies.nativeViewTree ?? defaultNativeViewTreeAdapter;
3732
5021
  this.appState = dependencies.appState ?? import_react_native2.AppState;
@@ -3810,6 +5099,7 @@ var MobileReplayRecorder = class {
3810
5099
  this.idlePause = null;
3811
5100
  this.idleResumeBacklog = null;
3812
5101
  this.customSignalMatcher.reset();
5102
+ this.stopProductAnalytics();
3813
5103
  const validated = validateStartOptions(options);
3814
5104
  if (!validated) {
3815
5105
  this.disable("invalid-start-options");
@@ -3890,35 +5180,27 @@ var MobileReplayRecorder = class {
3890
5180
  }
3891
5181
  this.sessionLastActivityUnixMs = nowUnixMs;
3892
5182
  this.lastInputUnixMs = nowUnixMs;
5183
+ let metadataRead = false;
5184
+ if (config.productAnalytics.enabled) {
5185
+ if (!await this.readAppMetadata(validated, generation)) {
5186
+ return false;
5187
+ }
5188
+ metadataRead = true;
5189
+ await this.startProductAnalytics(validated, config, namespace);
5190
+ if (!this.isCurrentGeneration(generation)) {
5191
+ return false;
5192
+ }
5193
+ }
3893
5194
  if (!awaitingConsent && config.captureTrigger === "Always" /* Always */ && !this.sampled && !config.isTargeted) {
5195
+ this.analyticsOnly = this.analytics !== null;
3894
5196
  this.disable("not-sampled");
3895
5197
  return false;
3896
5198
  }
3897
5199
  this.outbox = new ReplayOutbox(this.storage, namespace, this.now);
3898
5200
  this.transport = this.createTransport(validated, this.outbox);
3899
5201
  this.subscribeConnectivity(validated);
3900
- try {
3901
- const nativeMetadata = await this.nativeViewTree.getAppMetadata();
3902
- if (!this.isCurrentGeneration(generation)) {
3903
- return false;
3904
- }
3905
- this.metadata = {
3906
- appName: safeMetadataValue(
3907
- validated.appName,
3908
- safeMetadataValue(nativeMetadata?.appName, "React Native")
3909
- ),
3910
- appVersion: safeMetadataValue(
3911
- validated.appVersion,
3912
- safeMetadataValue(nativeMetadata?.appVersion, "unknown")
3913
- ),
3914
- osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
3915
- osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
3916
- };
3917
- } catch {
3918
- if (!this.isCurrentGeneration(generation)) {
3919
- return false;
3920
- }
3921
- this.diagnostic("native-metadata-unavailable");
5202
+ if (!metadataRead && !await this.readAppMetadata(validated, generation)) {
5203
+ return false;
3922
5204
  }
3923
5205
  this.route = "/";
3924
5206
  this.entryUrl = toAppUrl(validated.mobileAppIdentifier, this.route);
@@ -3958,6 +5240,7 @@ var MobileReplayRecorder = class {
3958
5240
  this.lifecycleCancellationEpoch += 1;
3959
5241
  this.pendingStartCancellation?.cancel();
3960
5242
  this.acceptingEvents = false;
5243
+ this.stopProductAnalytics(true);
3961
5244
  this.quiesceCapture();
3962
5245
  return this.enqueueLifecycleOperation(async () => {
3963
5246
  await identityBarrier;
@@ -4032,6 +5315,7 @@ var MobileReplayRecorder = class {
4032
5315
  }
4033
5316
  this.diagnosticsStatus = this.foreground ? "recording" : "background";
4034
5317
  this.diagnostic("consent-granted");
5318
+ this.analytics?.onConsentGranted();
4035
5319
  }
4036
5320
  revokeConsent() {
4037
5321
  this.lifecycleGeneration += 1;
@@ -4040,6 +5324,7 @@ var MobileReplayRecorder = class {
4040
5324
  this.pendingStartCancellation?.cancel();
4041
5325
  this.consentGranted = false;
4042
5326
  this.acceptingEvents = false;
5327
+ this.analytics?.forget();
4043
5328
  this.haltCapture();
4044
5329
  this.transport?.destroy();
4045
5330
  return this.enqueueLifecycleOperation(async () => {
@@ -4058,6 +5343,7 @@ var MobileReplayRecorder = class {
4058
5343
  await this.outbox?.clear();
4059
5344
  await this.sessionStore?.clear();
4060
5345
  await this.forgetCachedConfig();
5346
+ await this.forgetStoredProductAnalytics();
4061
5347
  this.identity = null;
4062
5348
  this.userRef = null;
4063
5349
  this.traits = {};
@@ -4127,8 +5413,12 @@ var MobileReplayRecorder = class {
4127
5413
  if (!eventName) {
4128
5414
  return;
4129
5415
  }
5416
+ this.afterIdentity(() => {
5417
+ this.analytics?.track(name, properties);
5418
+ });
4130
5419
  const sanitizedProperties = maskStringMapValues(
4131
- sanitizeEventProperties(properties)
5420
+ sanitizeEventProperties(properties),
5421
+ this.readableEventPropertyKeys()
4132
5422
  );
4133
5423
  this.runExternalActivity(this.now(), () => {
4134
5424
  this.appendCustom(
@@ -4147,8 +5437,42 @@ var MobileReplayRecorder = class {
4147
5437
  }
4148
5438
  });
4149
5439
  }
5440
+ /*
5441
+ * A number the app measured ("cart.value", 42.5), with optional
5442
+ * attributes: a point in the metric store under the RUM application, for
5443
+ * charts, dashboards and Metrics monitors (issue #6629). It needs product
5444
+ * analytics on for the application; its attribute values are masked, as
5445
+ * track()'s property values are.
5446
+ */
5447
+ metric(name, value, attributes) {
5448
+ if (!this.analytics || !this.analytics.isStarted()) {
5449
+ this.diagnostic("metric-analytics-off");
5450
+ return;
5451
+ }
5452
+ this.afterIdentity(() => {
5453
+ this.analytics?.metric(name, value, attributes);
5454
+ });
5455
+ }
5456
+ /*
5457
+ * Runs a product analytics call once every identify() made before it has
5458
+ * been applied - a change of user starts the next session first - or
5459
+ * now, when none is pending. Dropped when consent is withdrawn meanwhile.
5460
+ */
5461
+ afterIdentity(action) {
5462
+ if (this.pendingIdentityOperations === 0) {
5463
+ action();
5464
+ return;
5465
+ }
5466
+ const identityEpoch = this.identityCancellationEpoch;
5467
+ void this.identityQueue.then(() => {
5468
+ if (identityEpoch === this.identityCancellationEpoch) {
5469
+ action();
5470
+ }
5471
+ });
5472
+ }
4150
5473
  async setRoute(route) {
4151
5474
  await this.identityQueue;
5475
+ this.analytics?.page(sanitizeRoute(route));
4152
5476
  if (this.running && (!this.acceptingEvents || this.isIdlePaused())) {
4153
5477
  this.route = sanitizeRoute(route);
4154
5478
  return;
@@ -4281,8 +5605,16 @@ var MobileReplayRecorder = class {
4281
5605
  if (!this.running || !this.acceptingEvents || !this.foreground || !this.isCurrentGeneration(generation)) {
4282
5606
  return;
4283
5607
  }
4284
- if (this.updateTouchSuppression(touch, pointIsPrivate)) {
5608
+ const suppressed = this.updateTouchSuppression(
5609
+ touch,
5610
+ pointIsPrivate
5611
+ );
5612
+ const tap = this.followTap(touch);
5613
+ if (suppressed) {
4285
5614
  this.diagnostic("touch-suppressed-private-region");
5615
+ if (tap) {
5616
+ await this.recordTapSignals(tap, touch.timestamp, generation, false);
5617
+ }
4286
5618
  return;
4287
5619
  }
4288
5620
  if (touch.phase === "move" && touch.timestamp - this.lastTouchMoveAtUnixMs < TOUCH_MOVE_SAMPLE_MS) {
@@ -4308,6 +5640,90 @@ var MobileReplayRecorder = class {
4308
5640
  y: touch.y
4309
5641
  });
4310
5642
  }
5643
+ if (tap) {
5644
+ await this.recordTapSignals(tap, touch.timestamp, generation, true);
5645
+ }
5646
+ }
5647
+ /* The application's signals that fire on a tap. */
5648
+ tapSignals() {
5649
+ return this.customSignals().filter(
5650
+ (signal) => {
5651
+ return signal.trigger === "tap";
5652
+ }
5653
+ );
5654
+ }
5655
+ /*
5656
+ * Follows each touch for the application's tap signals (issue #6517): a
5657
+ * touch that ends within TAP_SLOP_POINTS of where it started is a tap on
5658
+ * the view it started on, and is returned on its end. A touch that slid
5659
+ * further was a scroll or a drag. Nothing is followed while the
5660
+ * application has no tap signal, so a touch costs what it always did.
5661
+ */
5662
+ followTap(touch) {
5663
+ const key = touch.pointerId === void 0 ? "unidentified" : `${typeof touch.pointerId}:${String(touch.pointerId)}`;
5664
+ if (touch.phase === "start") {
5665
+ if (this.tapSignals().length === 0 || this.tapCandidates.size >= MAX_TAP_CANDIDATES && !this.tapCandidates.has(key)) {
5666
+ return null;
5667
+ }
5668
+ this.tapCandidates.set(key, {
5669
+ x: touch.x,
5670
+ y: touch.y,
5671
+ targetTag: touch.targetTag
5672
+ });
5673
+ return null;
5674
+ }
5675
+ const started = this.tapCandidates.get(key);
5676
+ if (!started) {
5677
+ return null;
5678
+ }
5679
+ const slid = Math.hypot(touch.x - started.x, touch.y - started.y) > TAP_SLOP_POINTS;
5680
+ if (touch.phase === "move") {
5681
+ if (slid) {
5682
+ this.tapCandidates.delete(key);
5683
+ }
5684
+ return null;
5685
+ }
5686
+ this.tapCandidates.delete(key);
5687
+ return slid || started.targetTag === void 0 ? null : { targetTag: started.targetTag, x: touch.x, y: touch.y };
5688
+ }
5689
+ /*
5690
+ * A tap's signals: the touched view's testID, and those of the views
5691
+ * around it out to the replay root, matched here on the device - never
5692
+ * recorded or sent. A hit carries the signal's name, where the tap was
5693
+ * when the touch itself is recorded (withPosition), and like a page or
5694
+ * an event signal it starts an "On error or frustration" upload when it
5695
+ * counts as frustration.
5696
+ */
5697
+ async recordTapSignals(tap, atUnixMs, generation, withPosition) {
5698
+ const signals = this.tapSignals();
5699
+ if (signals.length === 0 || !this.rootTag || typeof this.nativeViewTree.touchTargetTestIds !== "function") {
5700
+ return;
5701
+ }
5702
+ let testIds = [];
5703
+ try {
5704
+ testIds = readTapTargetTestIds(
5705
+ await this.nativeViewTree.touchTargetTestIds(
5706
+ tap.targetTag,
5707
+ this.rootTag
5708
+ )
5709
+ );
5710
+ } catch {
5711
+ this.diagnostic("tap-target-unreadable");
5712
+ return;
5713
+ }
5714
+ if (!this.running || !this.acceptingEvents || !this.isCurrentGeneration(generation)) {
5715
+ return;
5716
+ }
5717
+ const hits = this.customSignalMatcher.matchTap(signals, testIds, atUnixMs);
5718
+ if (withPosition) {
5719
+ for (const hit of hits) {
5720
+ hit.x = tap.x;
5721
+ hit.y = tap.y;
5722
+ }
5723
+ }
5724
+ if (this.recordCustomSignals(hits)) {
5725
+ await this.trigger("frustration" /* Frustration */);
5726
+ }
4311
5727
  }
4312
5728
  setRootTag(rootTag) {
4313
5729
  this.rootTag = typeof rootTag === "number" && Number.isSafeInteger(rootTag) && rootTag > 0 ? rootTag : null;
@@ -4329,6 +5745,7 @@ var MobileReplayRecorder = class {
4329
5745
  triggered: this.triggered,
4330
5746
  consentState: this.consentState(),
4331
5747
  pendingEvents: this.rollingBuffer.length + (this.chunkBuffer.isEmpty() ? 0 : 1),
5748
+ productAnalytics: this.analytics ? this.analytics.getDiagnostics() : { state: "off", pending: 0, dropped: 0 },
4332
5749
  events: this.diagnosticsEvents.map(
4333
5750
  (event) => {
4334
5751
  const copied = {
@@ -4643,10 +6060,17 @@ var MobileReplayRecorder = class {
4643
6060
  }
4644
6061
  }
4645
6062
  }
4646
- /* The page, event and error signals the application's policy defines. */
6063
+ /* The tap, page, event and error signals the application's policy defines. */
4647
6064
  customSignals() {
4648
6065
  return this.config?.frustrationSignals.customSignals ?? [];
4649
6066
  }
6067
+ /*
6068
+ * The application's readable event properties (issue #7501): none until
6069
+ * the policy is read, so a track() before it is masked whole.
6070
+ */
6071
+ readableEventPropertyKeys() {
6072
+ return this.config?.readableEventPropertyKeys ?? [];
6073
+ }
4650
6074
  /*
4651
6075
  * Marks each hit in the stream and counts it on the chunk, as the browser
4652
6076
  * recorder does. Returns whether one of them counts as frustration, which
@@ -4673,6 +6097,10 @@ var MobileReplayRecorder = class {
4673
6097
  isFrustration: hit.isFrustration,
4674
6098
  atUnixMs: hit.atUnixMs
4675
6099
  };
6100
+ if (typeof hit.x === "number" && Number.isFinite(hit.x) && typeof hit.y === "number" && Number.isFinite(hit.y)) {
6101
+ payload.x = hit.x;
6102
+ payload.y = hit.y;
6103
+ }
4676
6104
  this.appendEvent(
4677
6105
  createCustomEvent(
4678
6106
  CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,
@@ -5193,6 +6621,20 @@ var MobileReplayRecorder = class {
5193
6621
  );
5194
6622
  }
5195
6623
  }
6624
+ /*
6625
+ * The product analytics events and metric points the device kept unsent
6626
+ * (issue #9577) go with consent too, as the outbox's chunks do - a
6627
+ * channel running now drops its own (forget(), reset()), and this
6628
+ * removes them whether one runs or not, a previous launch's included.
6629
+ */
6630
+ async forgetStoredProductAnalytics() {
6631
+ if (this.options) {
6632
+ await clearStoredProductAnalytics(
6633
+ this.storage,
6634
+ getReplayStorageNamespace(this.options)
6635
+ );
6636
+ }
6637
+ }
5196
6638
  mayPersistUnder(config) {
5197
6639
  return !config.enabled || config.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5198
6640
  }
@@ -5309,12 +6751,22 @@ var MobileReplayRecorder = class {
5309
6751
  this.suppressedTouchPointers.clear();
5310
6752
  this.unidentifiedTouchCount = 0;
5311
6753
  this.unidentifiedTouchPrivate = false;
6754
+ this.tapCandidates.clear();
5312
6755
  }
5313
6756
  async applyIdentityChange(ref, traits, identityEpoch) {
5314
6757
  if (identityEpoch !== this.identityCancellationEpoch) {
5315
6758
  return;
5316
6759
  }
5317
6760
  if (!this.running) {
6761
+ if (this.analyticsOnly && ref !== this.userRef && this.identityPersisted && this.sessionStore) {
6762
+ const identity = await this.sessionStore.rotate(
6763
+ this.now()
6764
+ );
6765
+ if (identityEpoch !== this.identityCancellationEpoch) {
6766
+ return;
6767
+ }
6768
+ this.identity = identity;
6769
+ }
5318
6770
  this.applyIdentityValues(ref, traits, true);
5319
6771
  return;
5320
6772
  }
@@ -5538,10 +6990,18 @@ var MobileReplayRecorder = class {
5538
6990
  async applyRuntimePolicy(_previousConfig, freshConfig, previousConsentState, wasAcceptingEvents, generation) {
5539
6991
  this.config = freshConfig;
5540
6992
  this.metaDirty = true;
6993
+ const analyticsStart = this.syncProductAnalytics(freshConfig);
6994
+ if (analyticsStart) {
6995
+ await analyticsStart;
6996
+ if (!this.running || !this.isCurrentGeneration(generation)) {
6997
+ return false;
6998
+ }
6999
+ }
5541
7000
  const hasConsent = freshConfig.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5542
7001
  if (!hasConsent) {
5543
7002
  const mustWithdrawPersistedState = this.identityPersisted || this.uploadActive || previousConsentState !== "Unknown";
5544
7003
  if (mustWithdrawPersistedState) {
7004
+ this.analytics?.reset();
5545
7005
  this.transport?.destroy();
5546
7006
  this.chunkBuffer.clear();
5547
7007
  this.rollingBuffer.clear();
@@ -5552,6 +7012,7 @@ var MobileReplayRecorder = class {
5552
7012
  await this.outbox?.clear();
5553
7013
  await this.sessionStore?.clear();
5554
7014
  await this.forgetCachedConfig();
7015
+ await this.forgetStoredProductAnalytics();
5555
7016
  if (!this.running || !this.isCurrentGeneration(generation)) {
5556
7017
  return false;
5557
7018
  }
@@ -5633,6 +7094,7 @@ var MobileReplayRecorder = class {
5633
7094
  this.diagnostic("policy-refreshed", {
5634
7095
  configEpoch: freshConfig.configEpoch
5635
7096
  });
7097
+ this.analytics?.refresh();
5636
7098
  return true;
5637
7099
  }
5638
7100
  currentStartOptions() {
@@ -5652,6 +7114,11 @@ var MobileReplayRecorder = class {
5652
7114
  }
5653
7115
  }
5654
7116
  async discardForPolicyStop(code, reason) {
7117
+ if (reason === "not-sampled") {
7118
+ this.analyticsOnly = this.analytics !== null;
7119
+ } else {
7120
+ this.stopProductAnalytics();
7121
+ }
5655
7122
  this.disable(code, { reason });
5656
7123
  this.haltCapture();
5657
7124
  this.transport?.destroy();
@@ -5946,6 +7413,7 @@ var MobileReplayRecorder = class {
5946
7413
  this.entryUrl = toAppUrl(this.options.mobileAppIdentifier, this.route);
5947
7414
  this.diagnostic("session-rotated", { reason });
5948
7415
  if (this.config.captureTrigger === "Always" /* Always */ && this.identityPersisted && !this.sampled && !this.config.isTargeted) {
7416
+ this.analyticsOnly = this.analytics !== null;
5949
7417
  this.disable("not-sampled");
5950
7418
  this.haltCapture();
5951
7419
  return;
@@ -5954,6 +7422,187 @@ var MobileReplayRecorder = class {
5954
7422
  this.startTimers();
5955
7423
  }
5956
7424
  }
7425
+ /*
7426
+ * The app's name, version and system, as the start options and then the
7427
+ * native module say them. False when a newer start or a stop took over
7428
+ * meanwhile.
7429
+ */
7430
+ async readAppMetadata(validated, generation) {
7431
+ try {
7432
+ const nativeMetadata = await this.nativeViewTree.getAppMetadata();
7433
+ if (!this.isCurrentGeneration(generation)) {
7434
+ return false;
7435
+ }
7436
+ this.metadata = {
7437
+ appName: safeMetadataValue(
7438
+ validated.appName,
7439
+ safeMetadataValue(nativeMetadata?.appName, "React Native")
7440
+ ),
7441
+ appVersion: safeMetadataValue(
7442
+ validated.appVersion,
7443
+ safeMetadataValue(nativeMetadata?.appVersion, "unknown")
7444
+ ),
7445
+ osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
7446
+ osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
7447
+ };
7448
+ } catch {
7449
+ if (!this.isCurrentGeneration(generation)) {
7450
+ return false;
7451
+ }
7452
+ this.diagnostic("native-metadata-unavailable");
7453
+ }
7454
+ return true;
7455
+ }
7456
+ /*
7457
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts), when
7458
+ * the application has them on: the channel asks this recorder for the
7459
+ * session, the visitor, consent and who is signed in, so an event and a
7460
+ * recording of the same visit carry the same ids.
7461
+ */
7462
+ async startProductAnalytics(options, config, namespace) {
7463
+ if (this.analytics || !config.productAnalytics.enabled) {
7464
+ return;
7465
+ }
7466
+ const analytics = new MobileProductAnalytics(
7467
+ {
7468
+ url: `${options.host}${PRODUCT_ANALYTICS_EVENTS_PATH}`,
7469
+ headers: mobileRequestHeaders(options),
7470
+ fetch: options.fetch,
7471
+ now: this.now,
7472
+ storage: this.storage,
7473
+ namespace,
7474
+ appState: this.appState,
7475
+ connectivity: options.connectivity,
7476
+ getSessionId: (nowUnixMs) => {
7477
+ return this.analyticsSessionId(nowUnixMs, true);
7478
+ },
7479
+ peekSessionId: () => {
7480
+ return this.analyticsSessionId(this.now(), false);
7481
+ },
7482
+ getVisitorId: () => {
7483
+ return this.identityPersisted ? this.identity?.visitorId ?? "" : "";
7484
+ },
7485
+ getConsentState: () => {
7486
+ return this.consentState();
7487
+ },
7488
+ requiresConsent: () => {
7489
+ return this.config?.consentMode === "RequireExplicit" /* RequireExplicit */;
7490
+ },
7491
+ getIdentity: () => {
7492
+ return this.analyticsIdentity();
7493
+ },
7494
+ toProperties: (value) => {
7495
+ return maskStringMapValues(
7496
+ sanitizeEventProperties(value),
7497
+ this.readableEventPropertyKeys()
7498
+ );
7499
+ },
7500
+ getContext: () => {
7501
+ return this.analyticsContext();
7502
+ },
7503
+ onDiagnostic: (code, details) => {
7504
+ this.diagnostic(code, details);
7505
+ }
7506
+ },
7507
+ config.productAnalytics
7508
+ );
7509
+ this.analytics = analytics;
7510
+ await analytics.start();
7511
+ }
7512
+ /*
7513
+ * Ends the product analytics channel this recorder started; `flushFirst`
7514
+ * sends what it holds first (stop()).
7515
+ */
7516
+ stopProductAnalytics(flushFirst = false) {
7517
+ const analytics = this.analytics;
7518
+ this.analytics = null;
7519
+ this.analyticsOnly = false;
7520
+ if (!analytics) {
7521
+ return;
7522
+ }
7523
+ if (flushFirst) {
7524
+ analytics.flush(true);
7525
+ }
7526
+ analytics.stop();
7527
+ }
7528
+ /*
7529
+ * A refreshed policy's product analytics: switched off, the channel
7530
+ * stops; switched on, it starts - again, too, after the server said they
7531
+ * were off - and its trait keys follow the policy. A promise only when a
7532
+ * channel has to start.
7533
+ */
7534
+ syncProductAnalytics(config) {
7535
+ if (!config.productAnalytics.enabled) {
7536
+ this.stopProductAnalytics();
7537
+ return null;
7538
+ }
7539
+ if (this.analytics && this.analytics.getStopReason() !== "not-enabled") {
7540
+ this.analytics.setConfig(config.productAnalytics);
7541
+ return null;
7542
+ }
7543
+ if (!this.options) {
7544
+ return null;
7545
+ }
7546
+ const options = this.currentStartOptions();
7547
+ this.stopProductAnalytics();
7548
+ return this.startProductAnalytics(
7549
+ options,
7550
+ config,
7551
+ getReplayStorageNamespace(options)
7552
+ );
7553
+ }
7554
+ /*
7555
+ * The session a product analytics event belongs to (issue #6629). The
7556
+ * recording's own while the recorder runs: it rotates its session
7557
+ * itself, and a session that ended idle keeps its id until the next one
7558
+ * starts. "" before consent, when the session the recorder holds is a
7559
+ * throwaway: the events wait for the one the grant opens. A session the
7560
+ * replay sample left out records nothing, so an event is its activity
7561
+ * (isActivity), and keeps it alive or rolls it over.
7562
+ */
7563
+ analyticsSessionId(nowUnixMs, isActivity) {
7564
+ if (!this.identity || !this.identityPersisted) {
7565
+ return "";
7566
+ }
7567
+ if (this.running) {
7568
+ return this.identity.sessionId;
7569
+ }
7570
+ if (this.analyticsOnly && this.sessionStore) {
7571
+ if (isActivity) {
7572
+ const continued = this.sessionStore.continueSession(nowUnixMs);
7573
+ if (continued) {
7574
+ this.identity = continued;
7575
+ }
7576
+ }
7577
+ return this.identity.sessionId;
7578
+ }
7579
+ return "";
7580
+ }
7581
+ /* Who is signed in, only while the application captures identity. */
7582
+ analyticsIdentity() {
7583
+ if (this.config?.captureUserIdentity !== true || !this.userRef) {
7584
+ return { userRef: "", traits: null };
7585
+ }
7586
+ return { userRef: this.userRef, traits: { ...this.traits } };
7587
+ }
7588
+ /*
7589
+ * What the app runs on, as its recorded sessions are filed (Common's
7590
+ * RumProductAnalyticsSession): a phone, or a tablet from a shorter side
7591
+ * of 600 points; no browser; the system the native module names; and the
7592
+ * app's version, from the start options or the native module.
7593
+ */
7594
+ analyticsContext() {
7595
+ const size = getViewport();
7596
+ const known = (value) => {
7597
+ return value === "unknown" ? "" : value;
7598
+ };
7599
+ return {
7600
+ deviceType: Math.min(size.width, size.height) >= PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE ? "tablet" : "mobile",
7601
+ browserName: "",
7602
+ osName: known(this.metadata.osName).trim().slice(0, PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH),
7603
+ appVersion: toProductAnalyticsAppVersion(known(this.metadata.appVersion))
7604
+ };
7605
+ }
5957
7606
  disable(code, details) {
5958
7607
  this.diagnosticsStatus = "disabled";
5959
7608
  this.diagnostic(code, details);