@oneuptime/react-native-replay 16.0.0 → 17.0.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.js CHANGED
@@ -60,7 +60,7 @@ var SESSION_REPLAY_MAX_OFFLINE_DELAY_MS = 3 * 24 * 60 * 60 * 1e3;
60
60
  var MOBILE_CAPTURE_INTERVAL_MS = 500;
61
61
  var MOBILE_RECORDER_KIND = "rn-view-tree";
62
62
  var SYNTHETIC_RRWEB_VERSION = "synthetic-1";
63
- var RECORDER_VERSION = true ? "16.0.0" : "0.0.0-dev";
63
+ var RECORDER_VERSION = true ? "17.0.0" : "0.0.0-dev";
64
64
  var SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES = [
65
65
  "mobile-view-tree",
66
66
  "mobile-touch-events",
@@ -698,6 +698,89 @@ var CustomSignalMatcher = class {
698
698
  }
699
699
  };
700
700
 
701
+ // src/ProductAnalyticsContract.ts
702
+ var PRODUCT_ANALYTICS_EVENTS_PATH = "/telemetry/session-replay/v1/events";
703
+ var PRODUCT_ANALYTICS_WIRE_VERSION = 1;
704
+ var PRODUCT_ANALYTICS_CONTENT_TYPE = "application/json";
705
+ var PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH = 100;
706
+ var PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH = 100;
707
+ var PRODUCT_ANALYTICS_MAX_BATCH_BYTES = 64 * 1024;
708
+ var PRODUCT_ANALYTICS_TARGET_BATCH_BYTES = 24 * 1024;
709
+ var PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS = 5e3;
710
+ var PRODUCT_ANALYTICS_MAX_PENDING_EVENTS = 500;
711
+ var PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH = 64;
712
+ var PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH = 64;
713
+ var PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH = 64;
714
+ var PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS = 3 * 24 * 60 * 60 * 1e3;
715
+ var PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE = 600;
716
+ var METRIC_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]{0,99}$/;
717
+ var PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX = "oneuptime.";
718
+ function isProductAnalyticsMetricName(value) {
719
+ return typeof value === "string" && METRIC_NAME_PATTERN.test(value) && !value.toLowerCase().startsWith(PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX);
720
+ }
721
+ function toProductAnalyticsEventName(value) {
722
+ if (typeof value !== "string") {
723
+ return null;
724
+ }
725
+ let name = "";
726
+ for (const character of value) {
727
+ const code = character.charCodeAt(0);
728
+ if (code < 32 || code === 127) {
729
+ continue;
730
+ }
731
+ name += character;
732
+ }
733
+ name = name.trim().slice(0, PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH).trim();
734
+ return name.length > 0 ? name : null;
735
+ }
736
+ var NOT_PRINTABLE_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
737
+ function toProductAnalyticsAppVersion(value) {
738
+ if (typeof value !== "string") {
739
+ return "";
740
+ }
741
+ const version = value.trim().slice(0, PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH).trim();
742
+ return NOT_PRINTABLE_PATTERN.test(version) ? "" : version;
743
+ }
744
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS = 20;
745
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH = 40;
746
+ function normalizeProductAnalyticsUserPropertyKeys(value) {
747
+ if (!Array.isArray(value)) {
748
+ return [];
749
+ }
750
+ const keys = [];
751
+ const seen = /* @__PURE__ */ new Set();
752
+ for (const entry of value) {
753
+ if (typeof entry !== "string") {
754
+ continue;
755
+ }
756
+ const key = entry.trim().slice(0, PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH);
757
+ if (key.length === 0 || key === "__proto__") {
758
+ continue;
759
+ }
760
+ if (seen.has(key.toLowerCase())) {
761
+ continue;
762
+ }
763
+ seen.add(key.toLowerCase());
764
+ keys.push(key);
765
+ if (keys.length >= PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS) {
766
+ break;
767
+ }
768
+ }
769
+ return keys;
770
+ }
771
+ function readProductAnalyticsRecorderConfig(value) {
772
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
773
+ return { enabled: false, userPropertyKeys: [] };
774
+ }
775
+ const record = value;
776
+ return {
777
+ enabled: record["enabled"] === true,
778
+ userPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
779
+ record["userPropertyKeys"]
780
+ )
781
+ };
782
+ }
783
+
701
784
  // src/Config.ts
702
785
  var CONFIG_FETCH_TIMEOUT_MS = 5e3;
703
786
  var MOBILE_APP_IDENTIFIER_LABEL_PATTERN = /^[a-z0-9_-]+$/u;
@@ -813,6 +896,7 @@ function failClosed(reason) {
813
896
  configEpoch: 0,
814
897
  isTargeted: false,
815
898
  frustrationSignals: { customSignals: [] },
899
+ productAnalytics: { enabled: false, userPropertyKeys: [] },
816
900
  disabledReason: reason
817
901
  };
818
902
  }
@@ -841,7 +925,14 @@ function normalizeReplayConfig(value) {
841
925
  */
842
926
  frustrationSignals: {
843
927
  customSignals: readCustomSignals(config.frustrationSignals)
844
- }
928
+ },
929
+ /*
930
+ * Absent - a server from before product analytics, or an application
931
+ * with it off - reads as off, so no batch is sent nobody asked for.
932
+ */
933
+ productAnalytics: readProductAnalyticsRecorderConfig(
934
+ config.productAnalytics
935
+ )
845
936
  };
846
937
  if (typeof config.disabledReason === "string") {
847
938
  resolved.disabledReason = config.disabledReason.slice(0, 100);
@@ -2670,6 +2761,200 @@ var ReplayOutbox = class {
2670
2761
  }
2671
2762
  };
2672
2763
 
2764
+ // src/RetryAfter.ts
2765
+ var RETRY_AFTER_HEADER = "retry-after";
2766
+ var DEFAULT_RETRY_AFTER_MIN_MS = 1e3;
2767
+ var DEFAULT_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
2768
+ var DELAY_SECONDS = /^\d+$/;
2769
+ var MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ");
2770
+ var DAY_NAME = "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)";
2771
+ var DAY_NAME_LONG = "(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day";
2772
+ var MONTH = `(${MONTHS.join("|")})`;
2773
+ var TIME_OF_DAY = "(\\d\\d):(\\d\\d):(\\d\\d)";
2774
+ var IMF_FIXDATE = new RegExp(
2775
+ `^${DAY_NAME}, (\\d\\d) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`
2776
+ );
2777
+ var RFC_850_DATE = new RegExp(
2778
+ `^${DAY_NAME_LONG}, (\\d\\d)-${MONTH}-(\\d\\d) ${TIME_OF_DAY} GMT$`
2779
+ );
2780
+ var ASCTIME_DATE = new RegExp(
2781
+ `^${DAY_NAME} ${MONTH} (\\d\\d| \\d) ${TIME_OF_DAY} (\\d{4})$`
2782
+ );
2783
+ var TWO_DIGIT_YEAR_LOOKAHEAD_YEARS = 50;
2784
+ function toUtcMs(year, month, day, hour, minute, second) {
2785
+ const monthIndex = MONTHS.indexOf(month || "");
2786
+ const dayOfMonth = Number(day);
2787
+ const date = /* @__PURE__ */ new Date(0);
2788
+ date.setUTCFullYear(year, monthIndex, dayOfMonth);
2789
+ if (monthIndex < 0 || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== dayOfMonth || !(Number(hour) <= 23 && Number(minute) <= 59 && Number(second) <= 60)) {
2790
+ return void 0;
2791
+ }
2792
+ date.setUTCHours(Number(hour), Number(minute), Number(second), 0);
2793
+ return date.getTime();
2794
+ }
2795
+ function readRfc850Date(match, nowMs) {
2796
+ const thisYear = new Date(nowMs).getUTCFullYear();
2797
+ const lookaheadEnd = new Date(nowMs);
2798
+ lookaheadEnd.setUTCFullYear(thisYear + TWO_DIGIT_YEAR_LOOKAHEAD_YEARS);
2799
+ let year = thisYear - thisYear % 100 + Number(match[3]);
2800
+ let atMs = toUtcMs(
2801
+ year,
2802
+ match[2],
2803
+ match[1],
2804
+ match[4],
2805
+ match[5],
2806
+ match[6]
2807
+ );
2808
+ if (atMs !== void 0 && atMs > lookaheadEnd.getTime()) {
2809
+ year -= 100;
2810
+ atMs = toUtcMs(year, match[2], match[1], match[4], match[5], match[6]);
2811
+ }
2812
+ return atMs;
2813
+ }
2814
+ function isSpace(code) {
2815
+ return code === 32 || code === 9;
2816
+ }
2817
+ function toText(value) {
2818
+ if (Array.isArray(value)) {
2819
+ const copies = value.map(
2820
+ (copy) => {
2821
+ return Array.isArray(copy) ? void 0 : toText(copy);
2822
+ }
2823
+ );
2824
+ return copies.every((copy) => {
2825
+ return copy === copies[0];
2826
+ }) ? copies[0] : void 0;
2827
+ }
2828
+ if (typeof value !== "string" && typeof value !== "number") {
2829
+ return void 0;
2830
+ }
2831
+ const text = String(value);
2832
+ let start = 0;
2833
+ let end = text.length;
2834
+ while (start < end && isSpace(text.charCodeAt(start))) {
2835
+ start++;
2836
+ }
2837
+ while (end > start && isSpace(text.charCodeAt(end - 1))) {
2838
+ end--;
2839
+ }
2840
+ return start < end ? text.slice(start, end) : void 0;
2841
+ }
2842
+ function readNow(nowMs) {
2843
+ return typeof nowMs === "number" && Number.isFinite(nowMs) ? nowMs : Date.now();
2844
+ }
2845
+ function readBound(bound, fallback) {
2846
+ return typeof bound === "number" && Number.isFinite(bound) && bound >= 0 ? bound : fallback;
2847
+ }
2848
+ var RetryAfter = class _RetryAfter {
2849
+ /*
2850
+ * The wait a Retry-After value asks for, in milliseconds, held between
2851
+ * minMs and maxMs; undefined when the value is not a Retry-After (absent,
2852
+ * empty, or neither delay-seconds nor an HTTP-date), so the caller waits
2853
+ * its own backoff. The value is a header's: a string, a number, or the
2854
+ * copies of a header sent more than once - which count only when they
2855
+ * all say the same.
2856
+ */
2857
+ static parseMs(value, options) {
2858
+ const text = toText(value);
2859
+ const asked = options || {};
2860
+ let waitMs;
2861
+ if (text === void 0) {
2862
+ return void 0;
2863
+ }
2864
+ if (DELAY_SECONDS.test(text)) {
2865
+ waitMs = Number(text) * 1e3;
2866
+ } else if (asked.acceptHttpDate !== false) {
2867
+ const nowMs = readNow(asked.nowMs);
2868
+ const retryAtMs = _RetryAfter.parseHttpDate(
2869
+ text,
2870
+ nowMs
2871
+ );
2872
+ waitMs = retryAtMs === void 0 ? void 0 : retryAtMs - nowMs;
2873
+ }
2874
+ return waitMs === void 0 ? void 0 : Math.min(
2875
+ Math.max(waitMs, readBound(asked.minMs, DEFAULT_RETRY_AFTER_MIN_MS)),
2876
+ readBound(asked.maxMs, DEFAULT_RETRY_AFTER_MAX_MS)
2877
+ );
2878
+ }
2879
+ /*
2880
+ * The same wait in whole seconds, rounded up - never sooner than asked -
2881
+ * for a caller that counts in seconds.
2882
+ */
2883
+ static parseSeconds(value, options) {
2884
+ const waitMs = _RetryAfter.parseMs(value, options);
2885
+ return waitMs === void 0 ? void 0 : Math.ceil(waitMs / 1e3);
2886
+ }
2887
+ /*
2888
+ * The Retry-After header of a response's headers, whatever its case: an
2889
+ * object with a get() (fetch's Headers, axios's AxiosHeaders), or a plain
2890
+ * object of names to values (Node's, a test's). Undefined when there is
2891
+ * none; a get() that throws reads as none.
2892
+ */
2893
+ static readHeader(headers) {
2894
+ if (!headers || typeof headers !== "object") {
2895
+ return void 0;
2896
+ }
2897
+ const get = headers.get;
2898
+ if (typeof get === "function") {
2899
+ try {
2900
+ const value = get.call(
2901
+ headers,
2902
+ RETRY_AFTER_HEADER
2903
+ );
2904
+ if (value !== void 0 && value !== null) {
2905
+ return value;
2906
+ }
2907
+ } catch {
2908
+ }
2909
+ }
2910
+ for (const name of Object.keys(headers)) {
2911
+ if (name.toLowerCase() === RETRY_AFTER_HEADER) {
2912
+ return headers[name];
2913
+ }
2914
+ }
2915
+ return void 0;
2916
+ }
2917
+ // parseMs of a response's Retry-After header.
2918
+ static msFromHeaders(headers, options) {
2919
+ return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
2920
+ }
2921
+ // parseSeconds of a response's Retry-After header.
2922
+ static secondsFromHeaders(headers, options) {
2923
+ return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
2924
+ }
2925
+ /*
2926
+ * An HTTP-date in any of its three shapes, exactly as written, as
2927
+ * milliseconds since the epoch; undefined for anything else. nowMs is what
2928
+ * an RFC 850 date's two-digit year is read against.
2929
+ */
2930
+ static parseHttpDate(value, nowMs) {
2931
+ let match = IMF_FIXDATE.exec(value);
2932
+ if (match) {
2933
+ return toUtcMs(
2934
+ Number(match[3]),
2935
+ match[2],
2936
+ match[1],
2937
+ match[4],
2938
+ match[5],
2939
+ match[6]
2940
+ );
2941
+ }
2942
+ match = RFC_850_DATE.exec(value);
2943
+ if (match) {
2944
+ return readRfc850Date(match, readNow(nowMs));
2945
+ }
2946
+ match = ASCTIME_DATE.exec(value);
2947
+ return match ? toUtcMs(
2948
+ Number(match[6]),
2949
+ match[1],
2950
+ match[2],
2951
+ match[3],
2952
+ match[4],
2953
+ match[5]
2954
+ ) : void 0;
2955
+ }
2956
+ };
2957
+
2673
2958
  // src/Storage.ts
2674
2959
  import AsyncStorage from "@react-native-async-storage/async-storage";
2675
2960
  var REPLAY_ID_PATTERN = /^[0-9a-f]{32}$/u;
@@ -2715,6 +3000,8 @@ var ReplaySessionStore = class {
2715
3000
  __publicField(this, "sessionKey");
2716
3001
  __publicField(this, "visitorKey");
2717
3002
  __publicField(this, "identity", null);
3003
+ /* When the session's last activity was, as the stored record says. */
3004
+ __publicField(this, "lastActivityUnixMs", 0);
2718
3005
  this.storage = storage;
2719
3006
  this.sessionKey = `@oneuptime/replay/${namespace}/session`;
2720
3007
  this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;
@@ -2753,8 +3040,39 @@ var ReplaySessionStore = class {
2753
3040
  sessionStartUnixMs: session.sessionStartUnixMs,
2754
3041
  chunkIndex: session.nextChunkIndex
2755
3042
  };
3043
+ this.lastActivityUnixMs = nowUnixMs;
2756
3044
  return { ...this.identity };
2757
3045
  }
3046
+ /*
3047
+ * The session a product analytics event belongs to while the replay
3048
+ * records nothing of it (an unsampled session, issue #6629): nothing else
3049
+ * moves the session then, so the event is its activity. The session
3050
+ * carries on, or - past the idle window or the longest a session lasts -
3051
+ * the next one starts, as resolve() would decide at the next launch.
3052
+ * Synchronous: decided in memory and written in the background, where a
3053
+ * failed write costs only a relaunch's resume. Null before resolve().
3054
+ */
3055
+ continueSession(nowUnixMs) {
3056
+ const identity = this.identity;
3057
+ if (!identity) {
3058
+ return null;
3059
+ }
3060
+ if (nowUnixMs - this.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - identity.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS) {
3061
+ identity.sessionId = generateReplayId();
3062
+ identity.tabId = generateReplayId();
3063
+ identity.sessionStartUnixMs = nowUnixMs;
3064
+ identity.chunkIndex = 0;
3065
+ }
3066
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
3067
+ const state = {
3068
+ sessionId: identity.sessionId,
3069
+ sessionStartUnixMs: identity.sessionStartUnixMs,
3070
+ lastActivityUnixMs: this.lastActivityUnixMs,
3071
+ nextChunkIndex: identity.chunkIndex
3072
+ };
3073
+ void this.safeSet(this.sessionKey, JSON.stringify(state));
3074
+ return { ...identity };
3075
+ }
2758
3076
  async takeChunkIndex(nowUnixMs) {
2759
3077
  if (!this.identity) {
2760
3078
  await this.resolve(nowUnixMs);
@@ -2762,6 +3080,7 @@ var ReplaySessionStore = class {
2762
3080
  const identity = this.identity;
2763
3081
  const index = identity.chunkIndex;
2764
3082
  identity.chunkIndex += 1;
3083
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
2765
3084
  const state = {
2766
3085
  sessionId: identity.sessionId,
2767
3086
  sessionStartUnixMs: identity.sessionStartUnixMs,
@@ -2794,6 +3113,7 @@ var ReplaySessionStore = class {
2794
3113
  sessionStartUnixMs: nowUnixMs,
2795
3114
  chunkIndex: 0
2796
3115
  };
3116
+ this.lastActivityUnixMs = nowUnixMs;
2797
3117
  return { ...this.identity };
2798
3118
  }
2799
3119
  /*
@@ -2836,197 +3156,669 @@ var ReplaySessionStore = class {
2836
3156
  }
2837
3157
  };
2838
3158
 
2839
- // src/RetryAfter.ts
2840
- var RETRY_AFTER_HEADER = "retry-after";
2841
- var DEFAULT_RETRY_AFTER_MIN_MS = 1e3;
2842
- var DEFAULT_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
2843
- var DELAY_SECONDS = /^\d+$/;
2844
- var MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ");
2845
- var DAY_NAME = "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)";
2846
- var DAY_NAME_LONG = "(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day";
2847
- var MONTH = `(${MONTHS.join("|")})`;
2848
- var TIME_OF_DAY = "(\\d\\d):(\\d\\d):(\\d\\d)";
2849
- var IMF_FIXDATE = new RegExp(
2850
- `^${DAY_NAME}, (\\d\\d) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`
2851
- );
2852
- var RFC_850_DATE = new RegExp(
2853
- `^${DAY_NAME_LONG}, (\\d\\d)-${MONTH}-(\\d\\d) ${TIME_OF_DAY} GMT$`
2854
- );
2855
- var ASCTIME_DATE = new RegExp(
2856
- `^${DAY_NAME} ${MONTH} (\\d\\d| \\d) ${TIME_OF_DAY} (\\d{4})$`
2857
- );
2858
- var TWO_DIGIT_YEAR_LOOKAHEAD_YEARS = 50;
2859
- function toUtcMs(year, month, day, hour, minute, second) {
2860
- const monthIndex = MONTHS.indexOf(month || "");
2861
- const dayOfMonth = Number(day);
2862
- const date = /* @__PURE__ */ new Date(0);
2863
- date.setUTCFullYear(year, monthIndex, dayOfMonth);
2864
- if (monthIndex < 0 || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== dayOfMonth || !(Number(hour) <= 23 && Number(minute) <= 59 && Number(second) <= 60)) {
2865
- return void 0;
2866
- }
2867
- date.setUTCHours(Number(hour), Number(minute), Number(second), 0);
2868
- return date.getTime();
3159
+ // src/ProductAnalytics.ts
3160
+ var PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS = 1e4;
3161
+ var PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS = 5 * 60 * 1e3;
3162
+ var RETRY_AFTER_LIMIT_SECONDS = 300;
3163
+ var REPLAY_ID_PATTERN2 = /^[0-9a-f]{32}$/u;
3164
+ function productAnalyticsSessionKey(namespace) {
3165
+ return `@oneuptime/replay/${namespace}/analytics-session`;
2869
3166
  }
2870
- function readRfc850Date(match, nowMs) {
2871
- const thisYear = new Date(nowMs).getUTCFullYear();
2872
- const lookaheadEnd = new Date(nowMs);
2873
- lookaheadEnd.setUTCFullYear(thisYear + TWO_DIGIT_YEAR_LOOKAHEAD_YEARS);
2874
- let year = thisYear - thisYear % 100 + Number(match[3]);
2875
- let atMs = toUtcMs(
2876
- year,
2877
- match[2],
2878
- match[1],
2879
- match[4],
2880
- match[5],
2881
- match[6]
2882
- );
2883
- if (atMs !== void 0 && atMs > lookaheadEnd.getTime()) {
2884
- year -= 100;
2885
- atMs = toUtcMs(year, match[2], match[1], match[4], match[5], match[6]);
2886
- }
2887
- return atMs;
3167
+ function itemAt(item) {
3168
+ return item.event ? item.event.at : item.metric?.at ?? 0;
2888
3169
  }
2889
- function isSpace(code) {
2890
- return code === 32 || code === 9;
3170
+ function sameScope(left, right) {
3171
+ return left.sessionId === right.sessionId && left.userRef === right.userRef && JSON.stringify(left.userProperties) === JSON.stringify(right.userProperties);
2891
3172
  }
2892
- function toText(value) {
2893
- if (Array.isArray(value)) {
2894
- const copies = value.map(
2895
- (copy) => {
2896
- return Array.isArray(copy) ? void 0 : toText(copy);
3173
+ function pickProductAnalyticsUserProperties(traits, allowedKeys) {
3174
+ const picked = {};
3175
+ if (!traits) {
3176
+ return picked;
3177
+ }
3178
+ for (const key of allowedKeys) {
3179
+ if (Object.prototype.hasOwnProperty.call(traits, key) && typeof traits[key] === "string") {
3180
+ picked[key] = traits[key];
3181
+ }
3182
+ }
3183
+ return picked;
3184
+ }
3185
+ var MobileProductAnalytics = class {
3186
+ constructor(host, config) {
3187
+ __publicField(this, "host");
3188
+ __publicField(this, "config");
3189
+ __publicField(this, "items", []);
3190
+ __publicField(this, "eventCount", 0);
3191
+ __publicField(this, "metricCount", 0);
3192
+ /*
3193
+ * The batch on its way, kept until the server says what became of it, so
3194
+ * a retry sends the same batch id and the server files it once.
3195
+ */
3196
+ __publicField(this, "pending", null);
3197
+ __publicField(this, "sending", false);
3198
+ __publicField(this, "sendGeneration", 0);
3199
+ __publicField(this, "retryAtUnixMs", 0);
3200
+ __publicField(this, "failures", 0);
3201
+ /* The session items are filed under now, and the screen shown in it. */
3202
+ __publicField(this, "sessionId", "");
3203
+ __publicField(this, "shownPage", "");
3204
+ /* The last screen the app named, in any session. */
3205
+ __publicField(this, "route", "");
3206
+ /* The session this device last announced; null until read. */
3207
+ __publicField(this, "announcedSessionId", null);
3208
+ __publicField(this, "droppedEvents", 0);
3209
+ __publicField(this, "started", false);
3210
+ __publicField(this, "stopReason", null);
3211
+ __publicField(this, "revoked", false);
3212
+ /* The connectivity source said the device is offline. */
3213
+ __publicField(this, "offline", false);
3214
+ __publicField(this, "flushTimer", null);
3215
+ __publicField(this, "appStateSubscription", null);
3216
+ __publicField(this, "unsubscribeConnectivity", null);
3217
+ this.host = host;
3218
+ this.config = config;
3219
+ }
3220
+ /*
3221
+ * Reads which session this device last announced, then starts: the
3222
+ * session's start (unless announced already), the timer, and the app's
3223
+ * lifecycle and connectivity. Items before this resolves are not taken.
3224
+ */
3225
+ async start() {
3226
+ if (this.started || this.stopReason) {
3227
+ return;
3228
+ }
3229
+ let stored = null;
3230
+ try {
3231
+ stored = await this.host.storage.getItem(
3232
+ productAnalyticsSessionKey(this.host.namespace)
3233
+ );
3234
+ } catch {
3235
+ stored = null;
3236
+ }
3237
+ if (this.started || this.stopReason) {
3238
+ return;
3239
+ }
3240
+ this.announcedSessionId = typeof stored === "string" && REPLAY_ID_PATTERN2.test(stored) ? stored : null;
3241
+ this.started = true;
3242
+ this.enterCurrentSession(this.host.now(), false);
3243
+ this.flushTimer = setInterval(() => {
3244
+ this.flush(false);
3245
+ }, PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS);
3246
+ this.listenToLifecycle();
3247
+ this.host.onDiagnostic("analytics-started", {
3248
+ userPropertyKeys: this.config.userPropertyKeys.length
3249
+ });
3250
+ }
3251
+ /* A refreshed policy's keys; whether it waits for consent is asked live. */
3252
+ setConfig(config) {
3253
+ this.config = config;
3254
+ }
3255
+ isStarted() {
3256
+ return this.started && !this.stopReason;
3257
+ }
3258
+ track(name, properties) {
3259
+ const eventName = toProductAnalyticsEventName(name);
3260
+ if (!eventName || !this.accepts()) {
3261
+ return;
3262
+ }
3263
+ const now = this.host.now();
3264
+ const scope = this.scopeNow(now);
3265
+ if (!scope) {
3266
+ return;
3267
+ }
3268
+ const event = {
3269
+ kind: "custom" /* Custom */,
3270
+ name: eventName,
3271
+ at: now,
3272
+ properties: this.host.toProperties(properties)
3273
+ };
3274
+ if (this.shownPage) {
3275
+ event.page = this.shownPage;
3276
+ } else if (this.route) {
3277
+ event.page = this.route;
3278
+ }
3279
+ this.pushEvent(scope, event);
3280
+ }
3281
+ /*
3282
+ * A screen the app moved to (setRoute(), already scrubbed as the replay
3283
+ * keeps a route): a page view, unless it is the screen already shown in
3284
+ * this session.
3285
+ */
3286
+ page(route) {
3287
+ if (!route || !this.accepts()) {
3288
+ return;
3289
+ }
3290
+ this.route = route;
3291
+ const now = this.host.now();
3292
+ const scope = this.scopeNow(now);
3293
+ if (!scope || route === this.shownPage) {
3294
+ return;
3295
+ }
3296
+ this.shownPage = route;
3297
+ this.pushEvent(scope, {
3298
+ kind: "page" /* Page */,
3299
+ name: route,
3300
+ at: now,
3301
+ page: route
3302
+ });
3303
+ }
3304
+ /*
3305
+ * metric(name, value, attributes): a number the app measured
3306
+ * ("cart.value", 42.5), filed in the metric store under the RUM
3307
+ * application. A name outside the instrument-name shape, or in
3308
+ * OneUptime's own namespace, or a value that is not a finite number, is
3309
+ * refused here and says why in the diagnostics.
3310
+ */
3311
+ metric(name, value, attributes) {
3312
+ if (!this.accepts()) {
3313
+ return;
3314
+ }
3315
+ if (!isProductAnalyticsMetricName(name)) {
3316
+ this.host.onDiagnostic("metric-name-refused", {
3317
+ name: typeof name === "string" ? name.slice(0, 100) : typeof name
3318
+ });
3319
+ return;
3320
+ }
3321
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3322
+ this.host.onDiagnostic("metric-value-refused", { name });
3323
+ return;
3324
+ }
3325
+ const now = this.host.now();
3326
+ const scope = this.scopeNow(now);
3327
+ if (!scope) {
3328
+ return;
3329
+ }
3330
+ this.items.push({
3331
+ scope,
3332
+ metric: {
3333
+ name,
3334
+ value,
3335
+ at: now,
3336
+ attributes: this.host.toProperties(attributes)
3337
+ }
3338
+ });
3339
+ this.metricCount++;
3340
+ if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3341
+ this.dropOldest("metric");
3342
+ }
3343
+ if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3344
+ this.flush(false);
3345
+ }
3346
+ }
3347
+ /*
3348
+ * Send what is held. `final` is the app leaving the foreground: sent at
3349
+ * once, whatever a retry was waiting for, while the system still lets
3350
+ * the app use the network.
3351
+ */
3352
+ flush(final) {
3353
+ if (!this.started || this.stopReason || this.revoked || this.sending) {
3354
+ return;
3355
+ }
3356
+ if (this.isAwaitingConsent() || this.offline) {
3357
+ return;
3358
+ }
3359
+ const now = this.host.now();
3360
+ if (!final && now < this.retryAtUnixMs) {
3361
+ return;
3362
+ }
3363
+ if (!this.pending) {
3364
+ this.enterCurrentSession(now, false);
3365
+ this.pending = this.takeBatch(now);
3366
+ }
3367
+ const batch = this.pending;
3368
+ if (!batch) {
3369
+ return;
3370
+ }
3371
+ this.send(batch);
3372
+ }
3373
+ /*
3374
+ * Consent withdrawn: everything held is dropped, the batch on its way
3375
+ * too, the session this device announced is forgotten, and nothing is
3376
+ * kept or sent until a new grant.
3377
+ */
3378
+ forget() {
3379
+ this.revoked = true;
3380
+ this.clear();
3381
+ this.forgetAnnouncedSession();
3382
+ }
3383
+ /*
3384
+ * The policy now waits for a consent this run has not been given: what
3385
+ * was held, and the device's record, go as on a withdrawal, but what
3386
+ * happens from now on is held for the grant, as before any consent.
3387
+ */
3388
+ reset() {
3389
+ this.clear();
3390
+ this.forgetAnnouncedSession();
3391
+ }
3392
+ /* Granted: what was held is filed under the session the grant opened, and goes now. */
3393
+ onConsentGranted() {
3394
+ this.revoked = false;
3395
+ this.retryAtUnixMs = 0;
3396
+ this.enterCurrentSession(this.host.now(), false);
3397
+ this.flush(false);
3398
+ }
3399
+ /*
3400
+ * The recorder's session may have changed under the channel - a policy
3401
+ * refreshed, a session named after consent: what was held for it is
3402
+ * filed under it, and what can go, goes.
3403
+ */
3404
+ refresh() {
3405
+ if (!this.accepts()) {
3406
+ return;
3407
+ }
3408
+ this.enterCurrentSession(this.host.now(), false);
3409
+ this.flush(false);
3410
+ }
3411
+ stop(reason = "stopped") {
3412
+ if (!this.stopReason) {
3413
+ this.stopReason = reason;
3414
+ }
3415
+ this.clear();
3416
+ if (this.flushTimer) {
3417
+ clearInterval(this.flushTimer);
3418
+ this.flushTimer = null;
3419
+ }
3420
+ this.appStateSubscription?.remove();
3421
+ this.appStateSubscription = null;
3422
+ const unsubscribe = this.unsubscribeConnectivity;
3423
+ this.unsubscribeConnectivity = null;
3424
+ try {
3425
+ unsubscribe?.();
3426
+ } catch {
3427
+ }
3428
+ }
3429
+ getStopReason() {
3430
+ return this.stopReason;
3431
+ }
3432
+ getPendingCount() {
3433
+ return this.items.length + (this.pending ? this.pending.events.length + this.pending.metrics.length : 0);
3434
+ }
3435
+ getDroppedEventCount() {
3436
+ return this.droppedEvents;
3437
+ }
3438
+ getDiagnostics() {
3439
+ return {
3440
+ state: this.stopReason || "on",
3441
+ pending: this.getPendingCount(),
3442
+ dropped: this.droppedEvents
3443
+ };
3444
+ }
3445
+ accepts() {
3446
+ return this.started && !this.stopReason && !this.revoked;
3447
+ }
3448
+ isAwaitingConsent() {
3449
+ return this.host.requiresConsent() && this.host.getConsentState() !== "Granted";
3450
+ }
3451
+ clear() {
3452
+ this.items = [];
3453
+ this.eventCount = 0;
3454
+ this.metricCount = 0;
3455
+ this.pending = null;
3456
+ this.sendGeneration++;
3457
+ this.sending = false;
3458
+ this.sessionId = "";
3459
+ this.shownPage = "";
3460
+ }
3461
+ forgetAnnouncedSession() {
3462
+ this.announcedSessionId = null;
3463
+ void this.host.storage.removeItem(productAnalyticsSessionKey(this.host.namespace)).catch(() => {
3464
+ });
3465
+ }
3466
+ announce(sessionId) {
3467
+ this.announcedSessionId = sessionId;
3468
+ void this.host.storage.setItem(productAnalyticsSessionKey(this.host.namespace), sessionId).catch(() => {
3469
+ });
3470
+ }
3471
+ makeScope(sessionId) {
3472
+ const identity = this.host.getIdentity();
3473
+ return {
3474
+ sessionId,
3475
+ userRef: identity.userRef,
3476
+ userProperties: identity.userRef ? pickProductAnalyticsUserProperties(
3477
+ identity.traits,
3478
+ this.config.userPropertyKeys
3479
+ ) : null
3480
+ };
3481
+ }
3482
+ /*
3483
+ * The scope of an item that happens now, or null when it has none to be
3484
+ * filed under (no session, and no consent being waited for).
3485
+ */
3486
+ scopeNow(now) {
3487
+ const sessionId = this.enterCurrentSession(now, true);
3488
+ if (sessionId) {
3489
+ return this.makeScope(sessionId);
3490
+ }
3491
+ return this.isAwaitingConsent() ? this.makeScope("") : null;
3492
+ }
3493
+ /*
3494
+ * Follows the host's session: a new one starts with its start (once per
3495
+ * session on this device) and the screen the app shows, and items held
3496
+ * before consent are filed under the first session there is to name.
3497
+ * Returns the session, or "" when there is none to name. Only an item
3498
+ * that happens now is activity (isActivity); the timer only looks.
3499
+ */
3500
+ enterCurrentSession(now, isActivity) {
3501
+ const sessionId = isActivity ? this.host.getSessionId(now) : this.host.peekSessionId();
3502
+ if (!sessionId) {
3503
+ return "";
3504
+ }
3505
+ const firstUnnamed = this.items.findIndex(
3506
+ (item) => {
3507
+ return item.scope.sessionId === "";
2897
3508
  }
2898
3509
  );
2899
- return copies.every((copy) => {
2900
- return copy === copies[0];
2901
- }) ? copies[0] : void 0;
3510
+ if (sessionId === this.sessionId && firstUnnamed < 0) {
3511
+ return sessionId;
3512
+ }
3513
+ const isNewSession = sessionId !== this.sessionId;
3514
+ this.sessionId = sessionId;
3515
+ let startedAt = now;
3516
+ let startPage = this.route;
3517
+ let startScope = this.makeScope(sessionId);
3518
+ if (firstUnnamed >= 0) {
3519
+ const first = this.items[firstUnnamed];
3520
+ startedAt = Math.min(now, itemAt(first));
3521
+ startPage = first.event?.page || this.route;
3522
+ startScope = { ...first.scope, sessionId };
3523
+ for (const item of this.items) {
3524
+ if (item.scope.sessionId === "") {
3525
+ item.scope = { ...item.scope, sessionId };
3526
+ }
3527
+ }
3528
+ } else if (isNewSession) {
3529
+ this.shownPage = "";
3530
+ }
3531
+ if (this.announcedSessionId !== sessionId) {
3532
+ const start = {
3533
+ kind: "session" /* Session */,
3534
+ name: "",
3535
+ at: startedAt
3536
+ };
3537
+ if (startPage) {
3538
+ start.page = startPage;
3539
+ }
3540
+ const item = { scope: startScope, event: start };
3541
+ if (firstUnnamed >= 0) {
3542
+ this.items.splice(firstUnnamed, 0, item);
3543
+ } else {
3544
+ this.items.push(item);
3545
+ }
3546
+ this.eventCount++;
3547
+ this.announce(sessionId);
3548
+ this.trimEvents();
3549
+ }
3550
+ if (firstUnnamed < 0 && isNewSession && this.route) {
3551
+ this.shownPage = this.route;
3552
+ this.items.push({
3553
+ scope: this.makeScope(sessionId),
3554
+ event: {
3555
+ kind: "page" /* Page */,
3556
+ name: this.route,
3557
+ at: now,
3558
+ page: this.route
3559
+ }
3560
+ });
3561
+ this.eventCount++;
3562
+ this.trimEvents();
3563
+ }
3564
+ return sessionId;
2902
3565
  }
2903
- if (typeof value !== "string" && typeof value !== "number") {
2904
- return void 0;
3566
+ pushEvent(scope, event) {
3567
+ this.items.push({ scope, event });
3568
+ this.eventCount++;
3569
+ this.trimEvents();
3570
+ if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3571
+ this.flush(false);
3572
+ }
2905
3573
  }
2906
- const text = String(value);
2907
- let start = 0;
2908
- let end = text.length;
2909
- while (start < end && isSpace(text.charCodeAt(start))) {
2910
- start++;
3574
+ /* Held too long (no consent, no network): the oldest go first, counted. */
3575
+ trimEvents() {
3576
+ while (this.eventCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3577
+ this.dropOldest("event");
3578
+ this.droppedEvents++;
3579
+ }
2911
3580
  }
2912
- while (end > start && isSpace(text.charCodeAt(end - 1))) {
2913
- end--;
3581
+ dropOldest(kind) {
3582
+ const index = this.items.findIndex((item) => {
3583
+ return kind === "event" ? Boolean(item.event) : Boolean(item.metric);
3584
+ });
3585
+ if (index < 0) {
3586
+ return;
3587
+ }
3588
+ this.items.splice(index, 1);
3589
+ if (kind === "event") {
3590
+ this.eventCount--;
3591
+ } else {
3592
+ this.metricCount--;
3593
+ }
2914
3594
  }
2915
- return start < end ? text.slice(start, end) : void 0;
2916
- }
2917
- function readNow(nowMs) {
2918
- return typeof nowMs === "number" && Number.isFinite(nowMs) ? nowMs : Date.now();
2919
- }
2920
- function readBound(bound, fallback) {
2921
- return typeof bound === "number" && Number.isFinite(bound) && bound >= 0 ? bound : fallback;
2922
- }
2923
- var RetryAfter = class _RetryAfter {
2924
3595
  /*
2925
- * The wait a Retry-After value asks for, in milliseconds, held between
2926
- * minMs and maxMs; undefined when the value is not a Retry-After (absent,
2927
- * empty, or neither delay-seconds nor an HTTP-date), so the caller waits
2928
- * its own backoff. The value is a header's: a string, a number, or the
2929
- * copies of a header sent more than once - which count only when they
2930
- * all say the same.
3596
+ * The next batch: the oldest items of one session and one person, up to
3597
+ * the per-batch counts and the target size. Items the server would drop
3598
+ * for their age are dropped here instead.
2931
3599
  */
2932
- static parseMs(value, options) {
2933
- const text = toText(value);
2934
- const asked = options || {};
2935
- let waitMs;
2936
- if (text === void 0) {
2937
- return void 0;
3600
+ takeBatch(now) {
3601
+ this.dropTooOld(now);
3602
+ const first = this.items[0];
3603
+ if (!first || first.scope.sessionId === "") {
3604
+ return null;
3605
+ }
3606
+ const scope = first.scope;
3607
+ let count = 0;
3608
+ let events = 0;
3609
+ let metrics = 0;
3610
+ for (const item of this.items) {
3611
+ if (!sameScope(item.scope, scope)) {
3612
+ break;
3613
+ }
3614
+ if (item.event) {
3615
+ if (events >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3616
+ break;
3617
+ }
3618
+ events++;
3619
+ } else {
3620
+ if (metrics >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3621
+ break;
3622
+ }
3623
+ metrics++;
3624
+ }
3625
+ count++;
3626
+ }
3627
+ const build = (taken) => {
3628
+ const slice = this.items.slice(0, taken);
3629
+ const batch2 = {
3630
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
3631
+ batchId: generateReplayId(),
3632
+ sessionId: scope.sessionId,
3633
+ visitorId: this.host.getVisitorId(),
3634
+ consentState: this.host.getConsentState(),
3635
+ sentAt: now,
3636
+ context: this.host.getContext(),
3637
+ events: slice.filter((item) => {
3638
+ return Boolean(item.event);
3639
+ }).map((item) => {
3640
+ return item.event;
3641
+ }),
3642
+ metrics: slice.filter((item) => {
3643
+ return Boolean(item.metric);
3644
+ }).map((item) => {
3645
+ return item.metric;
3646
+ })
3647
+ };
3648
+ if (scope.userRef) {
3649
+ batch2.userRef = scope.userRef;
3650
+ batch2.userProperties = scope.userProperties || {};
3651
+ }
3652
+ return batch2;
3653
+ };
3654
+ let batch = build(count);
3655
+ while (JSON.stringify(batch).length > PRODUCT_ANALYTICS_TARGET_BATCH_BYTES && count > 1) {
3656
+ count = Math.floor(count / 2);
3657
+ batch = build(count);
3658
+ }
3659
+ this.items.splice(0, count);
3660
+ this.eventCount -= batch.events.length;
3661
+ this.metricCount -= batch.metrics.length;
3662
+ return batch;
3663
+ }
3664
+ dropTooOld(now) {
3665
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
3666
+ const kept = [];
3667
+ for (const item of this.items) {
3668
+ if (itemAt(item) >= oldest) {
3669
+ kept.push(item);
3670
+ continue;
3671
+ }
3672
+ if (item.event) {
3673
+ this.eventCount--;
3674
+ this.droppedEvents++;
3675
+ } else {
3676
+ this.metricCount--;
3677
+ }
3678
+ }
3679
+ this.items = kept;
3680
+ }
3681
+ send(batch) {
3682
+ const generation = this.sendGeneration;
3683
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
3684
+ let timeout = null;
3685
+ const init = {
3686
+ method: "POST",
3687
+ headers: {
3688
+ ...this.host.headers,
3689
+ "Content-Type": PRODUCT_ANALYTICS_CONTENT_TYPE
3690
+ },
3691
+ body: JSON.stringify(batch)
3692
+ };
3693
+ if (controller) {
3694
+ init.signal = controller.signal;
3695
+ }
3696
+ let request;
3697
+ try {
3698
+ request = this.host.fetch(this.host.url, init);
3699
+ } catch {
3700
+ this.retryLater(this.host.now(), 0);
3701
+ return;
2938
3702
  }
2939
- if (DELAY_SECONDS.test(text)) {
2940
- waitMs = Number(text) * 1e3;
2941
- } else if (asked.acceptHttpDate !== false) {
2942
- const nowMs = readNow(asked.nowMs);
2943
- const retryAtMs = _RetryAfter.parseHttpDate(
2944
- text,
2945
- nowMs
3703
+ const deadline = new Promise(
3704
+ (_resolve, reject) => {
3705
+ timeout = setTimeout(() => {
3706
+ controller?.abort();
3707
+ reject(new Error("analytics-request-timeout"));
3708
+ }, PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS);
3709
+ }
3710
+ );
3711
+ this.sending = true;
3712
+ Promise.race([request, deadline]).then((response) => {
3713
+ if (generation !== this.sendGeneration) {
3714
+ return;
3715
+ }
3716
+ this.sending = false;
3717
+ this.onAnswer(response, this.host.now());
3718
+ }).catch(() => {
3719
+ if (generation !== this.sendGeneration) {
3720
+ return;
3721
+ }
3722
+ this.sending = false;
3723
+ this.retryLater(this.host.now(), 0);
3724
+ }).finally(() => {
3725
+ if (timeout) {
3726
+ clearTimeout(timeout);
3727
+ }
3728
+ });
3729
+ }
3730
+ onAnswer(response, now) {
3731
+ const status = response.status;
3732
+ if (status === 202 || status === 200) {
3733
+ this.pending = null;
3734
+ this.failures = 0;
3735
+ if (this.items.length > 0) {
3736
+ this.flush(false);
3737
+ }
3738
+ return;
3739
+ }
3740
+ if (status === 413) {
3741
+ this.pending = null;
3742
+ return;
3743
+ }
3744
+ if (status === 204 || status === 400 || status === 403) {
3745
+ let reason = "";
3746
+ try {
3747
+ reason = response.headers?.get("x-oneuptime-replay-reason") || "";
3748
+ } catch {
3749
+ reason = "";
3750
+ }
3751
+ this.host.onDiagnostic("analytics-stopped", {
3752
+ status,
3753
+ reason: reason.slice(0, 100)
3754
+ });
3755
+ this.stop(
3756
+ status === 403 ? "origin-not-allowed" : status === 204 ? "not-enabled" : "refused"
2946
3757
  );
2947
- waitMs = retryAtMs === void 0 ? void 0 : retryAtMs - nowMs;
3758
+ return;
2948
3759
  }
2949
- return waitMs === void 0 ? void 0 : Math.min(
2950
- Math.max(waitMs, readBound(asked.minMs, DEFAULT_RETRY_AFTER_MIN_MS)),
2951
- readBound(asked.maxMs, DEFAULT_RETRY_AFTER_MAX_MS)
2952
- );
3760
+ const retryAfterMs = status === 429 || status === 503 ? RetryAfter.msFromHeaders(response.headers, {
3761
+ maxMs: RETRY_AFTER_LIMIT_SECONDS * 1e3,
3762
+ nowMs: now
3763
+ }) ?? 0 : 0;
3764
+ this.retryLater(now, retryAfterMs);
2953
3765
  }
2954
- /*
2955
- * The same wait in whole seconds, rounded up - never sooner than asked -
2956
- * for a caller that counts in seconds.
2957
- */
2958
- static parseSeconds(value, options) {
2959
- const waitMs = _RetryAfter.parseMs(value, options);
2960
- return waitMs === void 0 ? void 0 : Math.ceil(waitMs / 1e3);
3766
+ retryLater(now, delayMs) {
3767
+ this.failures++;
3768
+ this.retryAtUnixMs = now + (delayMs > 0 ? delayMs : Math.min(
3769
+ PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS,
3770
+ PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS * Math.pow(2, this.failures)
3771
+ ));
2961
3772
  }
2962
3773
  /*
2963
- * The Retry-After header of a response's headers, whatever its case: an
2964
- * object with a get() (fetch's Headers, axios's AxiosHeaders), or a plain
2965
- * object of names to values (Node's, a test's). Undefined when there is
2966
- * none; a get() that throws reads as none.
3774
+ * The app leaving the foreground sends what is held while it still can;
3775
+ * coming back, or the device saying it is online again, sends a batch
3776
+ * that waited at once, rather than when its retry was due.
2967
3777
  */
2968
- static readHeader(headers) {
2969
- if (!headers || typeof headers !== "object") {
2970
- return void 0;
2971
- }
2972
- const get = headers.get;
2973
- if (typeof get === "function") {
3778
+ listenToLifecycle() {
3779
+ const appState = this.host.appState;
3780
+ if (appState && typeof appState.addEventListener === "function") {
2974
3781
  try {
2975
- const value = get.call(
2976
- headers,
2977
- RETRY_AFTER_HEADER
3782
+ this.appStateSubscription = appState.addEventListener(
3783
+ "change",
3784
+ (state) => {
3785
+ if (state === "active") {
3786
+ this.retryAtUnixMs = 0;
3787
+ this.flush(false);
3788
+ return;
3789
+ }
3790
+ this.flush(true);
3791
+ }
2978
3792
  );
2979
- if (value !== void 0 && value !== null) {
2980
- return value;
2981
- }
2982
3793
  } catch {
3794
+ this.appStateSubscription = null;
2983
3795
  }
2984
3796
  }
2985
- for (const name of Object.keys(headers)) {
2986
- if (name.toLowerCase() === RETRY_AFTER_HEADER) {
2987
- return headers[name];
2988
- }
3797
+ const connectivity = this.host.connectivity;
3798
+ if (!connectivity) {
3799
+ return;
2989
3800
  }
2990
- return void 0;
2991
- }
2992
- // parseMs of a response's Retry-After header.
2993
- static msFromHeaders(headers, options) {
2994
- return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
2995
- }
2996
- // parseSeconds of a response's Retry-After header.
2997
- static secondsFromHeaders(headers, options) {
2998
- return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
2999
- }
3000
- /*
3001
- * An HTTP-date in any of its three shapes, exactly as written, as
3002
- * milliseconds since the epoch; undefined for anything else. nowMs is what
3003
- * an RFC 850 date's two-digit year is read against.
3004
- */
3005
- static parseHttpDate(value, nowMs) {
3006
- let match = IMF_FIXDATE.exec(value);
3007
- if (match) {
3008
- return toUtcMs(
3009
- Number(match[3]),
3010
- match[2],
3011
- match[1],
3012
- match[4],
3013
- match[5],
3014
- match[6]
3801
+ try {
3802
+ const unsubscribe = connectivity.subscribe(
3803
+ (isConnected) => {
3804
+ if (isConnected === false) {
3805
+ this.offline = true;
3806
+ return;
3807
+ }
3808
+ if (isConnected === true) {
3809
+ const wasOffline = this.offline;
3810
+ this.offline = false;
3811
+ if (wasOffline) {
3812
+ this.retryAtUnixMs = 0;
3813
+ this.flush(false);
3814
+ }
3815
+ }
3816
+ }
3015
3817
  );
3818
+ this.unsubscribeConnectivity = typeof unsubscribe === "function" ? unsubscribe : null;
3819
+ } catch {
3820
+ this.unsubscribeConnectivity = null;
3016
3821
  }
3017
- match = RFC_850_DATE.exec(value);
3018
- if (match) {
3019
- return readRfc850Date(match, readNow(nowMs));
3020
- }
3021
- match = ASCTIME_DATE.exec(value);
3022
- return match ? toUtcMs(
3023
- Number(match[6]),
3024
- match[1],
3025
- match[2],
3026
- match[3],
3027
- match[4],
3028
- match[5]
3029
- ) : void 0;
3030
3822
  }
3031
3823
  };
3032
3824
 
@@ -3688,6 +4480,19 @@ var MobileReplayRecorder = class {
3688
4480
  */
3689
4481
  __publicField(this, "softKeyboardVisible", false);
3690
4482
  __publicField(this, "keyboardSubscriptions", []);
4483
+ /*
4484
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts): beside
4485
+ * the recording, from every session the policy lets the recorder run in,
4486
+ * recorded or not. Null while the application has them off.
4487
+ */
4488
+ __publicField(this, "analytics", null);
4489
+ /*
4490
+ * The replay sample left the session out under "Always": nothing of it
4491
+ * is recorded, but its product analytics events are still sent - and,
4492
+ * nothing else moving the session, they are what keeps it alive
4493
+ * (ReplaySessionStore.continueSession), as the browser recorder does.
4494
+ */
4495
+ __publicField(this, "analyticsOnly", false);
3691
4496
  this.storage = dependencies.storage ?? defaultReplayStorage;
3692
4497
  this.nativeViewTree = dependencies.nativeViewTree ?? defaultNativeViewTreeAdapter;
3693
4498
  this.appState = dependencies.appState ?? AppState;
@@ -3771,6 +4576,7 @@ var MobileReplayRecorder = class {
3771
4576
  this.idlePause = null;
3772
4577
  this.idleResumeBacklog = null;
3773
4578
  this.customSignalMatcher.reset();
4579
+ this.stopProductAnalytics();
3774
4580
  const validated = validateStartOptions(options);
3775
4581
  if (!validated) {
3776
4582
  this.disable("invalid-start-options");
@@ -3851,35 +4657,27 @@ var MobileReplayRecorder = class {
3851
4657
  }
3852
4658
  this.sessionLastActivityUnixMs = nowUnixMs;
3853
4659
  this.lastInputUnixMs = nowUnixMs;
4660
+ let metadataRead = false;
4661
+ if (config.productAnalytics.enabled) {
4662
+ if (!await this.readAppMetadata(validated, generation)) {
4663
+ return false;
4664
+ }
4665
+ metadataRead = true;
4666
+ await this.startProductAnalytics(validated, config, namespace);
4667
+ if (!this.isCurrentGeneration(generation)) {
4668
+ return false;
4669
+ }
4670
+ }
3854
4671
  if (!awaitingConsent && config.captureTrigger === "Always" /* Always */ && !this.sampled && !config.isTargeted) {
4672
+ this.analyticsOnly = this.analytics !== null;
3855
4673
  this.disable("not-sampled");
3856
4674
  return false;
3857
4675
  }
3858
4676
  this.outbox = new ReplayOutbox(this.storage, namespace, this.now);
3859
4677
  this.transport = this.createTransport(validated, this.outbox);
3860
4678
  this.subscribeConnectivity(validated);
3861
- try {
3862
- const nativeMetadata = await this.nativeViewTree.getAppMetadata();
3863
- if (!this.isCurrentGeneration(generation)) {
3864
- return false;
3865
- }
3866
- this.metadata = {
3867
- appName: safeMetadataValue(
3868
- validated.appName,
3869
- safeMetadataValue(nativeMetadata?.appName, "React Native")
3870
- ),
3871
- appVersion: safeMetadataValue(
3872
- validated.appVersion,
3873
- safeMetadataValue(nativeMetadata?.appVersion, "unknown")
3874
- ),
3875
- osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
3876
- osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
3877
- };
3878
- } catch {
3879
- if (!this.isCurrentGeneration(generation)) {
3880
- return false;
3881
- }
3882
- this.diagnostic("native-metadata-unavailable");
4679
+ if (!metadataRead && !await this.readAppMetadata(validated, generation)) {
4680
+ return false;
3883
4681
  }
3884
4682
  this.route = "/";
3885
4683
  this.entryUrl = toAppUrl(validated.mobileAppIdentifier, this.route);
@@ -3919,6 +4717,7 @@ var MobileReplayRecorder = class {
3919
4717
  this.lifecycleCancellationEpoch += 1;
3920
4718
  this.pendingStartCancellation?.cancel();
3921
4719
  this.acceptingEvents = false;
4720
+ this.stopProductAnalytics(true);
3922
4721
  this.quiesceCapture();
3923
4722
  return this.enqueueLifecycleOperation(async () => {
3924
4723
  await identityBarrier;
@@ -3993,6 +4792,7 @@ var MobileReplayRecorder = class {
3993
4792
  }
3994
4793
  this.diagnosticsStatus = this.foreground ? "recording" : "background";
3995
4794
  this.diagnostic("consent-granted");
4795
+ this.analytics?.onConsentGranted();
3996
4796
  }
3997
4797
  revokeConsent() {
3998
4798
  this.lifecycleGeneration += 1;
@@ -4001,6 +4801,7 @@ var MobileReplayRecorder = class {
4001
4801
  this.pendingStartCancellation?.cancel();
4002
4802
  this.consentGranted = false;
4003
4803
  this.acceptingEvents = false;
4804
+ this.analytics?.forget();
4004
4805
  this.haltCapture();
4005
4806
  this.transport?.destroy();
4006
4807
  return this.enqueueLifecycleOperation(async () => {
@@ -4088,6 +4889,9 @@ var MobileReplayRecorder = class {
4088
4889
  if (!eventName) {
4089
4890
  return;
4090
4891
  }
4892
+ this.afterIdentity(() => {
4893
+ this.analytics?.track(name, properties);
4894
+ });
4091
4895
  const sanitizedProperties = maskStringMapValues(
4092
4896
  sanitizeEventProperties(properties)
4093
4897
  );
@@ -4108,8 +4912,42 @@ var MobileReplayRecorder = class {
4108
4912
  }
4109
4913
  });
4110
4914
  }
4915
+ /*
4916
+ * A number the app measured ("cart.value", 42.5), with optional
4917
+ * attributes: a point in the metric store under the RUM application, for
4918
+ * charts, dashboards and Metrics monitors (issue #6629). It needs product
4919
+ * analytics on for the application; its attribute values are masked, as
4920
+ * track()'s property values are.
4921
+ */
4922
+ metric(name, value, attributes) {
4923
+ if (!this.analytics || !this.analytics.isStarted()) {
4924
+ this.diagnostic("metric-analytics-off");
4925
+ return;
4926
+ }
4927
+ this.afterIdentity(() => {
4928
+ this.analytics?.metric(name, value, attributes);
4929
+ });
4930
+ }
4931
+ /*
4932
+ * Runs a product analytics call once every identify() made before it has
4933
+ * been applied - a change of user starts the next session first - or
4934
+ * now, when none is pending. Dropped when consent is withdrawn meanwhile.
4935
+ */
4936
+ afterIdentity(action) {
4937
+ if (this.pendingIdentityOperations === 0) {
4938
+ action();
4939
+ return;
4940
+ }
4941
+ const identityEpoch = this.identityCancellationEpoch;
4942
+ void this.identityQueue.then(() => {
4943
+ if (identityEpoch === this.identityCancellationEpoch) {
4944
+ action();
4945
+ }
4946
+ });
4947
+ }
4111
4948
  async setRoute(route) {
4112
4949
  await this.identityQueue;
4950
+ this.analytics?.page(sanitizeRoute(route));
4113
4951
  if (this.running && (!this.acceptingEvents || this.isIdlePaused())) {
4114
4952
  this.route = sanitizeRoute(route);
4115
4953
  return;
@@ -4290,6 +5128,7 @@ var MobileReplayRecorder = class {
4290
5128
  triggered: this.triggered,
4291
5129
  consentState: this.consentState(),
4292
5130
  pendingEvents: this.rollingBuffer.length + (this.chunkBuffer.isEmpty() ? 0 : 1),
5131
+ productAnalytics: this.analytics ? this.analytics.getDiagnostics() : { state: "off", pending: 0, dropped: 0 },
4293
5132
  events: this.diagnosticsEvents.map(
4294
5133
  (event) => {
4295
5134
  const copied = {
@@ -5276,6 +6115,15 @@ var MobileReplayRecorder = class {
5276
6115
  return;
5277
6116
  }
5278
6117
  if (!this.running) {
6118
+ if (this.analyticsOnly && ref !== this.userRef && this.identityPersisted && this.sessionStore) {
6119
+ const identity = await this.sessionStore.rotate(
6120
+ this.now()
6121
+ );
6122
+ if (identityEpoch !== this.identityCancellationEpoch) {
6123
+ return;
6124
+ }
6125
+ this.identity = identity;
6126
+ }
5279
6127
  this.applyIdentityValues(ref, traits, true);
5280
6128
  return;
5281
6129
  }
@@ -5499,10 +6347,18 @@ var MobileReplayRecorder = class {
5499
6347
  async applyRuntimePolicy(_previousConfig, freshConfig, previousConsentState, wasAcceptingEvents, generation) {
5500
6348
  this.config = freshConfig;
5501
6349
  this.metaDirty = true;
6350
+ const analyticsStart = this.syncProductAnalytics(freshConfig);
6351
+ if (analyticsStart) {
6352
+ await analyticsStart;
6353
+ if (!this.running || !this.isCurrentGeneration(generation)) {
6354
+ return false;
6355
+ }
6356
+ }
5502
6357
  const hasConsent = freshConfig.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5503
6358
  if (!hasConsent) {
5504
6359
  const mustWithdrawPersistedState = this.identityPersisted || this.uploadActive || previousConsentState !== "Unknown";
5505
6360
  if (mustWithdrawPersistedState) {
6361
+ this.analytics?.reset();
5506
6362
  this.transport?.destroy();
5507
6363
  this.chunkBuffer.clear();
5508
6364
  this.rollingBuffer.clear();
@@ -5594,6 +6450,7 @@ var MobileReplayRecorder = class {
5594
6450
  this.diagnostic("policy-refreshed", {
5595
6451
  configEpoch: freshConfig.configEpoch
5596
6452
  });
6453
+ this.analytics?.refresh();
5597
6454
  return true;
5598
6455
  }
5599
6456
  currentStartOptions() {
@@ -5613,6 +6470,11 @@ var MobileReplayRecorder = class {
5613
6470
  }
5614
6471
  }
5615
6472
  async discardForPolicyStop(code, reason) {
6473
+ if (reason === "not-sampled") {
6474
+ this.analyticsOnly = this.analytics !== null;
6475
+ } else {
6476
+ this.stopProductAnalytics();
6477
+ }
5616
6478
  this.disable(code, { reason });
5617
6479
  this.haltCapture();
5618
6480
  this.transport?.destroy();
@@ -5907,6 +6769,7 @@ var MobileReplayRecorder = class {
5907
6769
  this.entryUrl = toAppUrl(this.options.mobileAppIdentifier, this.route);
5908
6770
  this.diagnostic("session-rotated", { reason });
5909
6771
  if (this.config.captureTrigger === "Always" /* Always */ && this.identityPersisted && !this.sampled && !this.config.isTargeted) {
6772
+ this.analyticsOnly = this.analytics !== null;
5910
6773
  this.disable("not-sampled");
5911
6774
  this.haltCapture();
5912
6775
  return;
@@ -5915,6 +6778,184 @@ var MobileReplayRecorder = class {
5915
6778
  this.startTimers();
5916
6779
  }
5917
6780
  }
6781
+ /*
6782
+ * The app's name, version and system, as the start options and then the
6783
+ * native module say them. False when a newer start or a stop took over
6784
+ * meanwhile.
6785
+ */
6786
+ async readAppMetadata(validated, generation) {
6787
+ try {
6788
+ const nativeMetadata = await this.nativeViewTree.getAppMetadata();
6789
+ if (!this.isCurrentGeneration(generation)) {
6790
+ return false;
6791
+ }
6792
+ this.metadata = {
6793
+ appName: safeMetadataValue(
6794
+ validated.appName,
6795
+ safeMetadataValue(nativeMetadata?.appName, "React Native")
6796
+ ),
6797
+ appVersion: safeMetadataValue(
6798
+ validated.appVersion,
6799
+ safeMetadataValue(nativeMetadata?.appVersion, "unknown")
6800
+ ),
6801
+ osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
6802
+ osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
6803
+ };
6804
+ } catch {
6805
+ if (!this.isCurrentGeneration(generation)) {
6806
+ return false;
6807
+ }
6808
+ this.diagnostic("native-metadata-unavailable");
6809
+ }
6810
+ return true;
6811
+ }
6812
+ /*
6813
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts), when
6814
+ * the application has them on: the channel asks this recorder for the
6815
+ * session, the visitor, consent and who is signed in, so an event and a
6816
+ * recording of the same visit carry the same ids.
6817
+ */
6818
+ async startProductAnalytics(options, config, namespace) {
6819
+ if (this.analytics || !config.productAnalytics.enabled) {
6820
+ return;
6821
+ }
6822
+ const analytics = new MobileProductAnalytics(
6823
+ {
6824
+ url: `${options.host}${PRODUCT_ANALYTICS_EVENTS_PATH}`,
6825
+ headers: mobileRequestHeaders(options),
6826
+ fetch: options.fetch,
6827
+ now: this.now,
6828
+ storage: this.storage,
6829
+ namespace,
6830
+ appState: this.appState,
6831
+ connectivity: options.connectivity,
6832
+ getSessionId: (nowUnixMs) => {
6833
+ return this.analyticsSessionId(nowUnixMs, true);
6834
+ },
6835
+ peekSessionId: () => {
6836
+ return this.analyticsSessionId(this.now(), false);
6837
+ },
6838
+ getVisitorId: () => {
6839
+ return this.identityPersisted ? this.identity?.visitorId ?? "" : "";
6840
+ },
6841
+ getConsentState: () => {
6842
+ return this.consentState();
6843
+ },
6844
+ requiresConsent: () => {
6845
+ return this.config?.consentMode === "RequireExplicit" /* RequireExplicit */;
6846
+ },
6847
+ getIdentity: () => {
6848
+ return this.analyticsIdentity();
6849
+ },
6850
+ toProperties: (value) => {
6851
+ return maskStringMapValues(sanitizeEventProperties(value));
6852
+ },
6853
+ getContext: () => {
6854
+ return this.analyticsContext();
6855
+ },
6856
+ onDiagnostic: (code, details) => {
6857
+ this.diagnostic(code, details);
6858
+ }
6859
+ },
6860
+ config.productAnalytics
6861
+ );
6862
+ this.analytics = analytics;
6863
+ await analytics.start();
6864
+ }
6865
+ /*
6866
+ * Ends the product analytics channel this recorder started; `flushFirst`
6867
+ * sends what it holds first (stop()).
6868
+ */
6869
+ stopProductAnalytics(flushFirst = false) {
6870
+ const analytics = this.analytics;
6871
+ this.analytics = null;
6872
+ this.analyticsOnly = false;
6873
+ if (!analytics) {
6874
+ return;
6875
+ }
6876
+ if (flushFirst) {
6877
+ analytics.flush(true);
6878
+ }
6879
+ analytics.stop();
6880
+ }
6881
+ /*
6882
+ * A refreshed policy's product analytics: switched off, the channel
6883
+ * stops; switched on, it starts - again, too, after the server said they
6884
+ * were off - and its trait keys follow the policy. A promise only when a
6885
+ * channel has to start.
6886
+ */
6887
+ syncProductAnalytics(config) {
6888
+ if (!config.productAnalytics.enabled) {
6889
+ this.stopProductAnalytics();
6890
+ return null;
6891
+ }
6892
+ if (this.analytics && this.analytics.getStopReason() !== "not-enabled") {
6893
+ this.analytics.setConfig(config.productAnalytics);
6894
+ return null;
6895
+ }
6896
+ if (!this.options) {
6897
+ return null;
6898
+ }
6899
+ const options = this.currentStartOptions();
6900
+ this.stopProductAnalytics();
6901
+ return this.startProductAnalytics(
6902
+ options,
6903
+ config,
6904
+ getReplayStorageNamespace(options)
6905
+ );
6906
+ }
6907
+ /*
6908
+ * The session a product analytics event belongs to (issue #6629). The
6909
+ * recording's own while the recorder runs: it rotates its session
6910
+ * itself, and a session that ended idle keeps its id until the next one
6911
+ * starts. "" before consent, when the session the recorder holds is a
6912
+ * throwaway: the events wait for the one the grant opens. A session the
6913
+ * replay sample left out records nothing, so an event is its activity
6914
+ * (isActivity), and keeps it alive or rolls it over.
6915
+ */
6916
+ analyticsSessionId(nowUnixMs, isActivity) {
6917
+ if (!this.identity || !this.identityPersisted) {
6918
+ return "";
6919
+ }
6920
+ if (this.running) {
6921
+ return this.identity.sessionId;
6922
+ }
6923
+ if (this.analyticsOnly && this.sessionStore) {
6924
+ if (isActivity) {
6925
+ const continued = this.sessionStore.continueSession(nowUnixMs);
6926
+ if (continued) {
6927
+ this.identity = continued;
6928
+ }
6929
+ }
6930
+ return this.identity.sessionId;
6931
+ }
6932
+ return "";
6933
+ }
6934
+ /* Who is signed in, only while the application captures identity. */
6935
+ analyticsIdentity() {
6936
+ if (this.config?.captureUserIdentity !== true || !this.userRef) {
6937
+ return { userRef: "", traits: null };
6938
+ }
6939
+ return { userRef: this.userRef, traits: { ...this.traits } };
6940
+ }
6941
+ /*
6942
+ * What the app runs on, as its recorded sessions are filed (Common's
6943
+ * RumProductAnalyticsSession): a phone, or a tablet from a shorter side
6944
+ * of 600 points; no browser; the system the native module names; and the
6945
+ * app's version, from the start options or the native module.
6946
+ */
6947
+ analyticsContext() {
6948
+ const size = getViewport();
6949
+ const known = (value) => {
6950
+ return value === "unknown" ? "" : value;
6951
+ };
6952
+ return {
6953
+ deviceType: Math.min(size.width, size.height) >= PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE ? "tablet" : "mobile",
6954
+ browserName: "",
6955
+ osName: known(this.metadata.osName).trim().slice(0, PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH),
6956
+ appVersion: toProductAnalyticsAppVersion(known(this.metadata.appVersion))
6957
+ };
6958
+ }
5918
6959
  disable(code, details) {
5919
6960
  this.diagnosticsStatus = "disabled";
5920
6961
  this.diagnostic(code, details);