@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.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.0.0" : "0.0.0-dev";
103
103
  var SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES = [
104
104
  "mobile-view-tree",
105
105
  "mobile-touch-events",
@@ -737,6 +737,89 @@ var CustomSignalMatcher = class {
737
737
  }
738
738
  };
739
739
 
740
+ // src/ProductAnalyticsContract.ts
741
+ var PRODUCT_ANALYTICS_EVENTS_PATH = "/telemetry/session-replay/v1/events";
742
+ var PRODUCT_ANALYTICS_WIRE_VERSION = 1;
743
+ var PRODUCT_ANALYTICS_CONTENT_TYPE = "application/json";
744
+ var PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH = 100;
745
+ var PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH = 100;
746
+ var PRODUCT_ANALYTICS_MAX_BATCH_BYTES = 64 * 1024;
747
+ var PRODUCT_ANALYTICS_TARGET_BATCH_BYTES = 24 * 1024;
748
+ var PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS = 5e3;
749
+ var PRODUCT_ANALYTICS_MAX_PENDING_EVENTS = 500;
750
+ var PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH = 64;
751
+ var PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH = 64;
752
+ var PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH = 64;
753
+ var PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS = 3 * 24 * 60 * 60 * 1e3;
754
+ var PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE = 600;
755
+ var METRIC_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]{0,99}$/;
756
+ var PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX = "oneuptime.";
757
+ function isProductAnalyticsMetricName(value) {
758
+ return typeof value === "string" && METRIC_NAME_PATTERN.test(value) && !value.toLowerCase().startsWith(PRODUCT_ANALYTICS_RESERVED_METRIC_PREFIX);
759
+ }
760
+ function toProductAnalyticsEventName(value) {
761
+ if (typeof value !== "string") {
762
+ return null;
763
+ }
764
+ let name = "";
765
+ for (const character of value) {
766
+ const code = character.charCodeAt(0);
767
+ if (code < 32 || code === 127) {
768
+ continue;
769
+ }
770
+ name += character;
771
+ }
772
+ name = name.trim().slice(0, PRODUCT_ANALYTICS_MAX_EVENT_NAME_LENGTH).trim();
773
+ return name.length > 0 ? name : null;
774
+ }
775
+ var NOT_PRINTABLE_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
776
+ function toProductAnalyticsAppVersion(value) {
777
+ if (typeof value !== "string") {
778
+ return "";
779
+ }
780
+ const version = value.trim().slice(0, PRODUCT_ANALYTICS_MAX_APP_VERSION_LENGTH).trim();
781
+ return NOT_PRINTABLE_PATTERN.test(version) ? "" : version;
782
+ }
783
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS = 20;
784
+ var PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH = 40;
785
+ function normalizeProductAnalyticsUserPropertyKeys(value) {
786
+ if (!Array.isArray(value)) {
787
+ return [];
788
+ }
789
+ const keys = [];
790
+ const seen = /* @__PURE__ */ new Set();
791
+ for (const entry of value) {
792
+ if (typeof entry !== "string") {
793
+ continue;
794
+ }
795
+ const key = entry.trim().slice(0, PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEY_LENGTH);
796
+ if (key.length === 0 || key === "__proto__") {
797
+ continue;
798
+ }
799
+ if (seen.has(key.toLowerCase())) {
800
+ continue;
801
+ }
802
+ seen.add(key.toLowerCase());
803
+ keys.push(key);
804
+ if (keys.length >= PRODUCT_ANALYTICS_MAX_USER_PROPERTY_KEYS) {
805
+ break;
806
+ }
807
+ }
808
+ return keys;
809
+ }
810
+ function readProductAnalyticsRecorderConfig(value) {
811
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
812
+ return { enabled: false, userPropertyKeys: [] };
813
+ }
814
+ const record = value;
815
+ return {
816
+ enabled: record["enabled"] === true,
817
+ userPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
818
+ record["userPropertyKeys"]
819
+ )
820
+ };
821
+ }
822
+
740
823
  // src/Config.ts
741
824
  var CONFIG_FETCH_TIMEOUT_MS = 5e3;
742
825
  var MOBILE_APP_IDENTIFIER_LABEL_PATTERN = /^[a-z0-9_-]+$/u;
@@ -852,6 +935,7 @@ function failClosed(reason) {
852
935
  configEpoch: 0,
853
936
  isTargeted: false,
854
937
  frustrationSignals: { customSignals: [] },
938
+ productAnalytics: { enabled: false, userPropertyKeys: [] },
855
939
  disabledReason: reason
856
940
  };
857
941
  }
@@ -880,7 +964,14 @@ function normalizeReplayConfig(value) {
880
964
  */
881
965
  frustrationSignals: {
882
966
  customSignals: readCustomSignals(config.frustrationSignals)
883
- }
967
+ },
968
+ /*
969
+ * Absent - a server from before product analytics, or an application
970
+ * with it off - reads as off, so no batch is sent nobody asked for.
971
+ */
972
+ productAnalytics: readProductAnalyticsRecorderConfig(
973
+ config.productAnalytics
974
+ )
884
975
  };
885
976
  if (typeof config.disabledReason === "string") {
886
977
  resolved.disabledReason = config.disabledReason.slice(0, 100);
@@ -2709,6 +2800,200 @@ var ReplayOutbox = class {
2709
2800
  }
2710
2801
  };
2711
2802
 
2803
+ // src/RetryAfter.ts
2804
+ var RETRY_AFTER_HEADER = "retry-after";
2805
+ var DEFAULT_RETRY_AFTER_MIN_MS = 1e3;
2806
+ var DEFAULT_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
2807
+ var DELAY_SECONDS = /^\d+$/;
2808
+ var MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ");
2809
+ var DAY_NAME = "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)";
2810
+ var DAY_NAME_LONG = "(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day";
2811
+ var MONTH = `(${MONTHS.join("|")})`;
2812
+ var TIME_OF_DAY = "(\\d\\d):(\\d\\d):(\\d\\d)";
2813
+ var IMF_FIXDATE = new RegExp(
2814
+ `^${DAY_NAME}, (\\d\\d) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`
2815
+ );
2816
+ var RFC_850_DATE = new RegExp(
2817
+ `^${DAY_NAME_LONG}, (\\d\\d)-${MONTH}-(\\d\\d) ${TIME_OF_DAY} GMT$`
2818
+ );
2819
+ var ASCTIME_DATE = new RegExp(
2820
+ `^${DAY_NAME} ${MONTH} (\\d\\d| \\d) ${TIME_OF_DAY} (\\d{4})$`
2821
+ );
2822
+ var TWO_DIGIT_YEAR_LOOKAHEAD_YEARS = 50;
2823
+ function toUtcMs(year, month, day, hour, minute, second) {
2824
+ const monthIndex = MONTHS.indexOf(month || "");
2825
+ const dayOfMonth = Number(day);
2826
+ const date = /* @__PURE__ */ new Date(0);
2827
+ date.setUTCFullYear(year, monthIndex, dayOfMonth);
2828
+ if (monthIndex < 0 || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== dayOfMonth || !(Number(hour) <= 23 && Number(minute) <= 59 && Number(second) <= 60)) {
2829
+ return void 0;
2830
+ }
2831
+ date.setUTCHours(Number(hour), Number(minute), Number(second), 0);
2832
+ return date.getTime();
2833
+ }
2834
+ function readRfc850Date(match, nowMs) {
2835
+ const thisYear = new Date(nowMs).getUTCFullYear();
2836
+ const lookaheadEnd = new Date(nowMs);
2837
+ lookaheadEnd.setUTCFullYear(thisYear + TWO_DIGIT_YEAR_LOOKAHEAD_YEARS);
2838
+ let year = thisYear - thisYear % 100 + Number(match[3]);
2839
+ let atMs = toUtcMs(
2840
+ year,
2841
+ match[2],
2842
+ match[1],
2843
+ match[4],
2844
+ match[5],
2845
+ match[6]
2846
+ );
2847
+ if (atMs !== void 0 && atMs > lookaheadEnd.getTime()) {
2848
+ year -= 100;
2849
+ atMs = toUtcMs(year, match[2], match[1], match[4], match[5], match[6]);
2850
+ }
2851
+ return atMs;
2852
+ }
2853
+ function isSpace(code) {
2854
+ return code === 32 || code === 9;
2855
+ }
2856
+ function toText(value) {
2857
+ if (Array.isArray(value)) {
2858
+ const copies = value.map(
2859
+ (copy) => {
2860
+ return Array.isArray(copy) ? void 0 : toText(copy);
2861
+ }
2862
+ );
2863
+ return copies.every((copy) => {
2864
+ return copy === copies[0];
2865
+ }) ? copies[0] : void 0;
2866
+ }
2867
+ if (typeof value !== "string" && typeof value !== "number") {
2868
+ return void 0;
2869
+ }
2870
+ const text = String(value);
2871
+ let start = 0;
2872
+ let end = text.length;
2873
+ while (start < end && isSpace(text.charCodeAt(start))) {
2874
+ start++;
2875
+ }
2876
+ while (end > start && isSpace(text.charCodeAt(end - 1))) {
2877
+ end--;
2878
+ }
2879
+ return start < end ? text.slice(start, end) : void 0;
2880
+ }
2881
+ function readNow(nowMs) {
2882
+ return typeof nowMs === "number" && Number.isFinite(nowMs) ? nowMs : Date.now();
2883
+ }
2884
+ function readBound(bound, fallback) {
2885
+ return typeof bound === "number" && Number.isFinite(bound) && bound >= 0 ? bound : fallback;
2886
+ }
2887
+ var RetryAfter = class _RetryAfter {
2888
+ /*
2889
+ * The wait a Retry-After value asks for, in milliseconds, held between
2890
+ * minMs and maxMs; undefined when the value is not a Retry-After (absent,
2891
+ * empty, or neither delay-seconds nor an HTTP-date), so the caller waits
2892
+ * its own backoff. The value is a header's: a string, a number, or the
2893
+ * copies of a header sent more than once - which count only when they
2894
+ * all say the same.
2895
+ */
2896
+ static parseMs(value, options) {
2897
+ const text = toText(value);
2898
+ const asked = options || {};
2899
+ let waitMs;
2900
+ if (text === void 0) {
2901
+ return void 0;
2902
+ }
2903
+ if (DELAY_SECONDS.test(text)) {
2904
+ waitMs = Number(text) * 1e3;
2905
+ } else if (asked.acceptHttpDate !== false) {
2906
+ const nowMs = readNow(asked.nowMs);
2907
+ const retryAtMs = _RetryAfter.parseHttpDate(
2908
+ text,
2909
+ nowMs
2910
+ );
2911
+ waitMs = retryAtMs === void 0 ? void 0 : retryAtMs - nowMs;
2912
+ }
2913
+ return waitMs === void 0 ? void 0 : Math.min(
2914
+ Math.max(waitMs, readBound(asked.minMs, DEFAULT_RETRY_AFTER_MIN_MS)),
2915
+ readBound(asked.maxMs, DEFAULT_RETRY_AFTER_MAX_MS)
2916
+ );
2917
+ }
2918
+ /*
2919
+ * The same wait in whole seconds, rounded up - never sooner than asked -
2920
+ * for a caller that counts in seconds.
2921
+ */
2922
+ static parseSeconds(value, options) {
2923
+ const waitMs = _RetryAfter.parseMs(value, options);
2924
+ return waitMs === void 0 ? void 0 : Math.ceil(waitMs / 1e3);
2925
+ }
2926
+ /*
2927
+ * The Retry-After header of a response's headers, whatever its case: an
2928
+ * object with a get() (fetch's Headers, axios's AxiosHeaders), or a plain
2929
+ * object of names to values (Node's, a test's). Undefined when there is
2930
+ * none; a get() that throws reads as none.
2931
+ */
2932
+ static readHeader(headers) {
2933
+ if (!headers || typeof headers !== "object") {
2934
+ return void 0;
2935
+ }
2936
+ const get = headers.get;
2937
+ if (typeof get === "function") {
2938
+ try {
2939
+ const value = get.call(
2940
+ headers,
2941
+ RETRY_AFTER_HEADER
2942
+ );
2943
+ if (value !== void 0 && value !== null) {
2944
+ return value;
2945
+ }
2946
+ } catch {
2947
+ }
2948
+ }
2949
+ for (const name of Object.keys(headers)) {
2950
+ if (name.toLowerCase() === RETRY_AFTER_HEADER) {
2951
+ return headers[name];
2952
+ }
2953
+ }
2954
+ return void 0;
2955
+ }
2956
+ // parseMs of a response's Retry-After header.
2957
+ static msFromHeaders(headers, options) {
2958
+ return _RetryAfter.parseMs(_RetryAfter.readHeader(headers), options);
2959
+ }
2960
+ // parseSeconds of a response's Retry-After header.
2961
+ static secondsFromHeaders(headers, options) {
2962
+ return _RetryAfter.parseSeconds(_RetryAfter.readHeader(headers), options);
2963
+ }
2964
+ /*
2965
+ * An HTTP-date in any of its three shapes, exactly as written, as
2966
+ * milliseconds since the epoch; undefined for anything else. nowMs is what
2967
+ * an RFC 850 date's two-digit year is read against.
2968
+ */
2969
+ static parseHttpDate(value, nowMs) {
2970
+ let match = IMF_FIXDATE.exec(value);
2971
+ if (match) {
2972
+ return toUtcMs(
2973
+ Number(match[3]),
2974
+ match[2],
2975
+ match[1],
2976
+ match[4],
2977
+ match[5],
2978
+ match[6]
2979
+ );
2980
+ }
2981
+ match = RFC_850_DATE.exec(value);
2982
+ if (match) {
2983
+ return readRfc850Date(match, readNow(nowMs));
2984
+ }
2985
+ match = ASCTIME_DATE.exec(value);
2986
+ return match ? toUtcMs(
2987
+ Number(match[6]),
2988
+ match[1],
2989
+ match[2],
2990
+ match[3],
2991
+ match[4],
2992
+ match[5]
2993
+ ) : void 0;
2994
+ }
2995
+ };
2996
+
2712
2997
  // src/Storage.ts
2713
2998
  var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
2714
2999
  var REPLAY_ID_PATTERN = /^[0-9a-f]{32}$/u;
@@ -2754,6 +3039,8 @@ var ReplaySessionStore = class {
2754
3039
  __publicField(this, "sessionKey");
2755
3040
  __publicField(this, "visitorKey");
2756
3041
  __publicField(this, "identity", null);
3042
+ /* When the session's last activity was, as the stored record says. */
3043
+ __publicField(this, "lastActivityUnixMs", 0);
2757
3044
  this.storage = storage;
2758
3045
  this.sessionKey = `@oneuptime/replay/${namespace}/session`;
2759
3046
  this.visitorKey = `@oneuptime/replay/${namespace}/visitor`;
@@ -2792,8 +3079,39 @@ var ReplaySessionStore = class {
2792
3079
  sessionStartUnixMs: session.sessionStartUnixMs,
2793
3080
  chunkIndex: session.nextChunkIndex
2794
3081
  };
3082
+ this.lastActivityUnixMs = nowUnixMs;
2795
3083
  return { ...this.identity };
2796
3084
  }
3085
+ /*
3086
+ * The session a product analytics event belongs to while the replay
3087
+ * records nothing of it (an unsampled session, issue #6629): nothing else
3088
+ * moves the session then, so the event is its activity. The session
3089
+ * carries on, or - past the idle window or the longest a session lasts -
3090
+ * the next one starts, as resolve() would decide at the next launch.
3091
+ * Synchronous: decided in memory and written in the background, where a
3092
+ * failed write costs only a relaunch's resume. Null before resolve().
3093
+ */
3094
+ continueSession(nowUnixMs) {
3095
+ const identity = this.identity;
3096
+ if (!identity) {
3097
+ return null;
3098
+ }
3099
+ if (nowUnixMs - this.lastActivityUnixMs >= SESSION_REPLAY_IDLE_ROLLOVER_MS || nowUnixMs - identity.sessionStartUnixMs >= SESSION_REPLAY_MAX_SESSION_MS) {
3100
+ identity.sessionId = generateReplayId();
3101
+ identity.tabId = generateReplayId();
3102
+ identity.sessionStartUnixMs = nowUnixMs;
3103
+ identity.chunkIndex = 0;
3104
+ }
3105
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
3106
+ const state = {
3107
+ sessionId: identity.sessionId,
3108
+ sessionStartUnixMs: identity.sessionStartUnixMs,
3109
+ lastActivityUnixMs: this.lastActivityUnixMs,
3110
+ nextChunkIndex: identity.chunkIndex
3111
+ };
3112
+ void this.safeSet(this.sessionKey, JSON.stringify(state));
3113
+ return { ...identity };
3114
+ }
2797
3115
  async takeChunkIndex(nowUnixMs) {
2798
3116
  if (!this.identity) {
2799
3117
  await this.resolve(nowUnixMs);
@@ -2801,6 +3119,7 @@ var ReplaySessionStore = class {
2801
3119
  const identity = this.identity;
2802
3120
  const index = identity.chunkIndex;
2803
3121
  identity.chunkIndex += 1;
3122
+ this.lastActivityUnixMs = Math.max(this.lastActivityUnixMs, nowUnixMs);
2804
3123
  const state = {
2805
3124
  sessionId: identity.sessionId,
2806
3125
  sessionStartUnixMs: identity.sessionStartUnixMs,
@@ -2833,6 +3152,7 @@ var ReplaySessionStore = class {
2833
3152
  sessionStartUnixMs: nowUnixMs,
2834
3153
  chunkIndex: 0
2835
3154
  };
3155
+ this.lastActivityUnixMs = nowUnixMs;
2836
3156
  return { ...this.identity };
2837
3157
  }
2838
3158
  /*
@@ -2875,197 +3195,669 @@ var ReplaySessionStore = class {
2875
3195
  }
2876
3196
  };
2877
3197
 
2878
- // src/RetryAfter.ts
2879
- var RETRY_AFTER_HEADER = "retry-after";
2880
- var DEFAULT_RETRY_AFTER_MIN_MS = 1e3;
2881
- var DEFAULT_RETRY_AFTER_MAX_MS = 60 * 60 * 1e3;
2882
- var DELAY_SECONDS = /^\d+$/;
2883
- var MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ");
2884
- var DAY_NAME = "(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)";
2885
- var DAY_NAME_LONG = "(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day";
2886
- var MONTH = `(${MONTHS.join("|")})`;
2887
- var TIME_OF_DAY = "(\\d\\d):(\\d\\d):(\\d\\d)";
2888
- var IMF_FIXDATE = new RegExp(
2889
- `^${DAY_NAME}, (\\d\\d) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`
2890
- );
2891
- var RFC_850_DATE = new RegExp(
2892
- `^${DAY_NAME_LONG}, (\\d\\d)-${MONTH}-(\\d\\d) ${TIME_OF_DAY} GMT$`
2893
- );
2894
- var ASCTIME_DATE = new RegExp(
2895
- `^${DAY_NAME} ${MONTH} (\\d\\d| \\d) ${TIME_OF_DAY} (\\d{4})$`
2896
- );
2897
- var TWO_DIGIT_YEAR_LOOKAHEAD_YEARS = 50;
2898
- function toUtcMs(year, month, day, hour, minute, second) {
2899
- const monthIndex = MONTHS.indexOf(month || "");
2900
- const dayOfMonth = Number(day);
2901
- const date = /* @__PURE__ */ new Date(0);
2902
- date.setUTCFullYear(year, monthIndex, dayOfMonth);
2903
- if (monthIndex < 0 || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== dayOfMonth || !(Number(hour) <= 23 && Number(minute) <= 59 && Number(second) <= 60)) {
2904
- return void 0;
2905
- }
2906
- date.setUTCHours(Number(hour), Number(minute), Number(second), 0);
2907
- return date.getTime();
3198
+ // src/ProductAnalytics.ts
3199
+ var PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS = 1e4;
3200
+ var PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS = 5 * 60 * 1e3;
3201
+ var RETRY_AFTER_LIMIT_SECONDS = 300;
3202
+ var REPLAY_ID_PATTERN2 = /^[0-9a-f]{32}$/u;
3203
+ function productAnalyticsSessionKey(namespace) {
3204
+ return `@oneuptime/replay/${namespace}/analytics-session`;
2908
3205
  }
2909
- function readRfc850Date(match, nowMs) {
2910
- const thisYear = new Date(nowMs).getUTCFullYear();
2911
- const lookaheadEnd = new Date(nowMs);
2912
- lookaheadEnd.setUTCFullYear(thisYear + TWO_DIGIT_YEAR_LOOKAHEAD_YEARS);
2913
- let year = thisYear - thisYear % 100 + Number(match[3]);
2914
- let atMs = toUtcMs(
2915
- year,
2916
- match[2],
2917
- match[1],
2918
- match[4],
2919
- match[5],
2920
- match[6]
2921
- );
2922
- if (atMs !== void 0 && atMs > lookaheadEnd.getTime()) {
2923
- year -= 100;
2924
- atMs = toUtcMs(year, match[2], match[1], match[4], match[5], match[6]);
2925
- }
2926
- return atMs;
3206
+ function itemAt(item) {
3207
+ return item.event ? item.event.at : item.metric?.at ?? 0;
2927
3208
  }
2928
- function isSpace(code) {
2929
- return code === 32 || code === 9;
3209
+ function sameScope(left, right) {
3210
+ return left.sessionId === right.sessionId && left.userRef === right.userRef && JSON.stringify(left.userProperties) === JSON.stringify(right.userProperties);
2930
3211
  }
2931
- function toText(value) {
2932
- if (Array.isArray(value)) {
2933
- const copies = value.map(
2934
- (copy) => {
2935
- return Array.isArray(copy) ? void 0 : toText(copy);
3212
+ function pickProductAnalyticsUserProperties(traits, allowedKeys) {
3213
+ const picked = {};
3214
+ if (!traits) {
3215
+ return picked;
3216
+ }
3217
+ for (const key of allowedKeys) {
3218
+ if (Object.prototype.hasOwnProperty.call(traits, key) && typeof traits[key] === "string") {
3219
+ picked[key] = traits[key];
3220
+ }
3221
+ }
3222
+ return picked;
3223
+ }
3224
+ var MobileProductAnalytics = class {
3225
+ constructor(host, config) {
3226
+ __publicField(this, "host");
3227
+ __publicField(this, "config");
3228
+ __publicField(this, "items", []);
3229
+ __publicField(this, "eventCount", 0);
3230
+ __publicField(this, "metricCount", 0);
3231
+ /*
3232
+ * The batch on its way, kept until the server says what became of it, so
3233
+ * a retry sends the same batch id and the server files it once.
3234
+ */
3235
+ __publicField(this, "pending", null);
3236
+ __publicField(this, "sending", false);
3237
+ __publicField(this, "sendGeneration", 0);
3238
+ __publicField(this, "retryAtUnixMs", 0);
3239
+ __publicField(this, "failures", 0);
3240
+ /* The session items are filed under now, and the screen shown in it. */
3241
+ __publicField(this, "sessionId", "");
3242
+ __publicField(this, "shownPage", "");
3243
+ /* The last screen the app named, in any session. */
3244
+ __publicField(this, "route", "");
3245
+ /* The session this device last announced; null until read. */
3246
+ __publicField(this, "announcedSessionId", null);
3247
+ __publicField(this, "droppedEvents", 0);
3248
+ __publicField(this, "started", false);
3249
+ __publicField(this, "stopReason", null);
3250
+ __publicField(this, "revoked", false);
3251
+ /* The connectivity source said the device is offline. */
3252
+ __publicField(this, "offline", false);
3253
+ __publicField(this, "flushTimer", null);
3254
+ __publicField(this, "appStateSubscription", null);
3255
+ __publicField(this, "unsubscribeConnectivity", null);
3256
+ this.host = host;
3257
+ this.config = config;
3258
+ }
3259
+ /*
3260
+ * Reads which session this device last announced, then starts: the
3261
+ * session's start (unless announced already), the timer, and the app's
3262
+ * lifecycle and connectivity. Items before this resolves are not taken.
3263
+ */
3264
+ async start() {
3265
+ if (this.started || this.stopReason) {
3266
+ return;
3267
+ }
3268
+ let stored = null;
3269
+ try {
3270
+ stored = await this.host.storage.getItem(
3271
+ productAnalyticsSessionKey(this.host.namespace)
3272
+ );
3273
+ } catch {
3274
+ stored = null;
3275
+ }
3276
+ if (this.started || this.stopReason) {
3277
+ return;
3278
+ }
3279
+ this.announcedSessionId = typeof stored === "string" && REPLAY_ID_PATTERN2.test(stored) ? stored : null;
3280
+ this.started = true;
3281
+ this.enterCurrentSession(this.host.now(), false);
3282
+ this.flushTimer = setInterval(() => {
3283
+ this.flush(false);
3284
+ }, PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS);
3285
+ this.listenToLifecycle();
3286
+ this.host.onDiagnostic("analytics-started", {
3287
+ userPropertyKeys: this.config.userPropertyKeys.length
3288
+ });
3289
+ }
3290
+ /* A refreshed policy's keys; whether it waits for consent is asked live. */
3291
+ setConfig(config) {
3292
+ this.config = config;
3293
+ }
3294
+ isStarted() {
3295
+ return this.started && !this.stopReason;
3296
+ }
3297
+ track(name, properties) {
3298
+ const eventName = toProductAnalyticsEventName(name);
3299
+ if (!eventName || !this.accepts()) {
3300
+ return;
3301
+ }
3302
+ const now = this.host.now();
3303
+ const scope = this.scopeNow(now);
3304
+ if (!scope) {
3305
+ return;
3306
+ }
3307
+ const event = {
3308
+ kind: "custom" /* Custom */,
3309
+ name: eventName,
3310
+ at: now,
3311
+ properties: this.host.toProperties(properties)
3312
+ };
3313
+ if (this.shownPage) {
3314
+ event.page = this.shownPage;
3315
+ } else if (this.route) {
3316
+ event.page = this.route;
3317
+ }
3318
+ this.pushEvent(scope, event);
3319
+ }
3320
+ /*
3321
+ * A screen the app moved to (setRoute(), already scrubbed as the replay
3322
+ * keeps a route): a page view, unless it is the screen already shown in
3323
+ * this session.
3324
+ */
3325
+ page(route) {
3326
+ if (!route || !this.accepts()) {
3327
+ return;
3328
+ }
3329
+ this.route = route;
3330
+ const now = this.host.now();
3331
+ const scope = this.scopeNow(now);
3332
+ if (!scope || route === this.shownPage) {
3333
+ return;
3334
+ }
3335
+ this.shownPage = route;
3336
+ this.pushEvent(scope, {
3337
+ kind: "page" /* Page */,
3338
+ name: route,
3339
+ at: now,
3340
+ page: route
3341
+ });
3342
+ }
3343
+ /*
3344
+ * metric(name, value, attributes): a number the app measured
3345
+ * ("cart.value", 42.5), filed in the metric store under the RUM
3346
+ * application. A name outside the instrument-name shape, or in
3347
+ * OneUptime's own namespace, or a value that is not a finite number, is
3348
+ * refused here and says why in the diagnostics.
3349
+ */
3350
+ metric(name, value, attributes) {
3351
+ if (!this.accepts()) {
3352
+ return;
3353
+ }
3354
+ if (!isProductAnalyticsMetricName(name)) {
3355
+ this.host.onDiagnostic("metric-name-refused", {
3356
+ name: typeof name === "string" ? name.slice(0, 100) : typeof name
3357
+ });
3358
+ return;
3359
+ }
3360
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3361
+ this.host.onDiagnostic("metric-value-refused", { name });
3362
+ return;
3363
+ }
3364
+ const now = this.host.now();
3365
+ const scope = this.scopeNow(now);
3366
+ if (!scope) {
3367
+ return;
3368
+ }
3369
+ this.items.push({
3370
+ scope,
3371
+ metric: {
3372
+ name,
3373
+ value,
3374
+ at: now,
3375
+ attributes: this.host.toProperties(attributes)
3376
+ }
3377
+ });
3378
+ this.metricCount++;
3379
+ if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3380
+ this.dropOldest("metric");
3381
+ }
3382
+ if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3383
+ this.flush(false);
3384
+ }
3385
+ }
3386
+ /*
3387
+ * Send what is held. `final` is the app leaving the foreground: sent at
3388
+ * once, whatever a retry was waiting for, while the system still lets
3389
+ * the app use the network.
3390
+ */
3391
+ flush(final) {
3392
+ if (!this.started || this.stopReason || this.revoked || this.sending) {
3393
+ return;
3394
+ }
3395
+ if (this.isAwaitingConsent() || this.offline) {
3396
+ return;
3397
+ }
3398
+ const now = this.host.now();
3399
+ if (!final && now < this.retryAtUnixMs) {
3400
+ return;
3401
+ }
3402
+ if (!this.pending) {
3403
+ this.enterCurrentSession(now, false);
3404
+ this.pending = this.takeBatch(now);
3405
+ }
3406
+ const batch = this.pending;
3407
+ if (!batch) {
3408
+ return;
3409
+ }
3410
+ this.send(batch);
3411
+ }
3412
+ /*
3413
+ * Consent withdrawn: everything held is dropped, the batch on its way
3414
+ * too, the session this device announced is forgotten, and nothing is
3415
+ * kept or sent until a new grant.
3416
+ */
3417
+ forget() {
3418
+ this.revoked = true;
3419
+ this.clear();
3420
+ this.forgetAnnouncedSession();
3421
+ }
3422
+ /*
3423
+ * The policy now waits for a consent this run has not been given: what
3424
+ * was held, and the device's record, go as on a withdrawal, but what
3425
+ * happens from now on is held for the grant, as before any consent.
3426
+ */
3427
+ reset() {
3428
+ this.clear();
3429
+ this.forgetAnnouncedSession();
3430
+ }
3431
+ /* Granted: what was held is filed under the session the grant opened, and goes now. */
3432
+ onConsentGranted() {
3433
+ this.revoked = false;
3434
+ this.retryAtUnixMs = 0;
3435
+ this.enterCurrentSession(this.host.now(), false);
3436
+ this.flush(false);
3437
+ }
3438
+ /*
3439
+ * The recorder's session may have changed under the channel - a policy
3440
+ * refreshed, a session named after consent: what was held for it is
3441
+ * filed under it, and what can go, goes.
3442
+ */
3443
+ refresh() {
3444
+ if (!this.accepts()) {
3445
+ return;
3446
+ }
3447
+ this.enterCurrentSession(this.host.now(), false);
3448
+ this.flush(false);
3449
+ }
3450
+ stop(reason = "stopped") {
3451
+ if (!this.stopReason) {
3452
+ this.stopReason = reason;
3453
+ }
3454
+ this.clear();
3455
+ if (this.flushTimer) {
3456
+ clearInterval(this.flushTimer);
3457
+ this.flushTimer = null;
3458
+ }
3459
+ this.appStateSubscription?.remove();
3460
+ this.appStateSubscription = null;
3461
+ const unsubscribe = this.unsubscribeConnectivity;
3462
+ this.unsubscribeConnectivity = null;
3463
+ try {
3464
+ unsubscribe?.();
3465
+ } catch {
3466
+ }
3467
+ }
3468
+ getStopReason() {
3469
+ return this.stopReason;
3470
+ }
3471
+ getPendingCount() {
3472
+ return this.items.length + (this.pending ? this.pending.events.length + this.pending.metrics.length : 0);
3473
+ }
3474
+ getDroppedEventCount() {
3475
+ return this.droppedEvents;
3476
+ }
3477
+ getDiagnostics() {
3478
+ return {
3479
+ state: this.stopReason || "on",
3480
+ pending: this.getPendingCount(),
3481
+ dropped: this.droppedEvents
3482
+ };
3483
+ }
3484
+ accepts() {
3485
+ return this.started && !this.stopReason && !this.revoked;
3486
+ }
3487
+ isAwaitingConsent() {
3488
+ return this.host.requiresConsent() && this.host.getConsentState() !== "Granted";
3489
+ }
3490
+ clear() {
3491
+ this.items = [];
3492
+ this.eventCount = 0;
3493
+ this.metricCount = 0;
3494
+ this.pending = null;
3495
+ this.sendGeneration++;
3496
+ this.sending = false;
3497
+ this.sessionId = "";
3498
+ this.shownPage = "";
3499
+ }
3500
+ forgetAnnouncedSession() {
3501
+ this.announcedSessionId = null;
3502
+ void this.host.storage.removeItem(productAnalyticsSessionKey(this.host.namespace)).catch(() => {
3503
+ });
3504
+ }
3505
+ announce(sessionId) {
3506
+ this.announcedSessionId = sessionId;
3507
+ void this.host.storage.setItem(productAnalyticsSessionKey(this.host.namespace), sessionId).catch(() => {
3508
+ });
3509
+ }
3510
+ makeScope(sessionId) {
3511
+ const identity = this.host.getIdentity();
3512
+ return {
3513
+ sessionId,
3514
+ userRef: identity.userRef,
3515
+ userProperties: identity.userRef ? pickProductAnalyticsUserProperties(
3516
+ identity.traits,
3517
+ this.config.userPropertyKeys
3518
+ ) : null
3519
+ };
3520
+ }
3521
+ /*
3522
+ * The scope of an item that happens now, or null when it has none to be
3523
+ * filed under (no session, and no consent being waited for).
3524
+ */
3525
+ scopeNow(now) {
3526
+ const sessionId = this.enterCurrentSession(now, true);
3527
+ if (sessionId) {
3528
+ return this.makeScope(sessionId);
3529
+ }
3530
+ return this.isAwaitingConsent() ? this.makeScope("") : null;
3531
+ }
3532
+ /*
3533
+ * Follows the host's session: a new one starts with its start (once per
3534
+ * session on this device) and the screen the app shows, and items held
3535
+ * before consent are filed under the first session there is to name.
3536
+ * Returns the session, or "" when there is none to name. Only an item
3537
+ * that happens now is activity (isActivity); the timer only looks.
3538
+ */
3539
+ enterCurrentSession(now, isActivity) {
3540
+ const sessionId = isActivity ? this.host.getSessionId(now) : this.host.peekSessionId();
3541
+ if (!sessionId) {
3542
+ return "";
3543
+ }
3544
+ const firstUnnamed = this.items.findIndex(
3545
+ (item) => {
3546
+ return item.scope.sessionId === "";
2936
3547
  }
2937
3548
  );
2938
- return copies.every((copy) => {
2939
- return copy === copies[0];
2940
- }) ? copies[0] : void 0;
3549
+ if (sessionId === this.sessionId && firstUnnamed < 0) {
3550
+ return sessionId;
3551
+ }
3552
+ const isNewSession = sessionId !== this.sessionId;
3553
+ this.sessionId = sessionId;
3554
+ let startedAt = now;
3555
+ let startPage = this.route;
3556
+ let startScope = this.makeScope(sessionId);
3557
+ if (firstUnnamed >= 0) {
3558
+ const first = this.items[firstUnnamed];
3559
+ startedAt = Math.min(now, itemAt(first));
3560
+ startPage = first.event?.page || this.route;
3561
+ startScope = { ...first.scope, sessionId };
3562
+ for (const item of this.items) {
3563
+ if (item.scope.sessionId === "") {
3564
+ item.scope = { ...item.scope, sessionId };
3565
+ }
3566
+ }
3567
+ } else if (isNewSession) {
3568
+ this.shownPage = "";
3569
+ }
3570
+ if (this.announcedSessionId !== sessionId) {
3571
+ const start = {
3572
+ kind: "session" /* Session */,
3573
+ name: "",
3574
+ at: startedAt
3575
+ };
3576
+ if (startPage) {
3577
+ start.page = startPage;
3578
+ }
3579
+ const item = { scope: startScope, event: start };
3580
+ if (firstUnnamed >= 0) {
3581
+ this.items.splice(firstUnnamed, 0, item);
3582
+ } else {
3583
+ this.items.push(item);
3584
+ }
3585
+ this.eventCount++;
3586
+ this.announce(sessionId);
3587
+ this.trimEvents();
3588
+ }
3589
+ if (firstUnnamed < 0 && isNewSession && this.route) {
3590
+ this.shownPage = this.route;
3591
+ this.items.push({
3592
+ scope: this.makeScope(sessionId),
3593
+ event: {
3594
+ kind: "page" /* Page */,
3595
+ name: this.route,
3596
+ at: now,
3597
+ page: this.route
3598
+ }
3599
+ });
3600
+ this.eventCount++;
3601
+ this.trimEvents();
3602
+ }
3603
+ return sessionId;
2941
3604
  }
2942
- if (typeof value !== "string" && typeof value !== "number") {
2943
- return void 0;
3605
+ pushEvent(scope, event) {
3606
+ this.items.push({ scope, event });
3607
+ this.eventCount++;
3608
+ this.trimEvents();
3609
+ if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3610
+ this.flush(false);
3611
+ }
2944
3612
  }
2945
- const text = String(value);
2946
- let start = 0;
2947
- let end = text.length;
2948
- while (start < end && isSpace(text.charCodeAt(start))) {
2949
- start++;
3613
+ /* Held too long (no consent, no network): the oldest go first, counted. */
3614
+ trimEvents() {
3615
+ while (this.eventCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3616
+ this.dropOldest("event");
3617
+ this.droppedEvents++;
3618
+ }
2950
3619
  }
2951
- while (end > start && isSpace(text.charCodeAt(end - 1))) {
2952
- end--;
3620
+ dropOldest(kind) {
3621
+ const index = this.items.findIndex((item) => {
3622
+ return kind === "event" ? Boolean(item.event) : Boolean(item.metric);
3623
+ });
3624
+ if (index < 0) {
3625
+ return;
3626
+ }
3627
+ this.items.splice(index, 1);
3628
+ if (kind === "event") {
3629
+ this.eventCount--;
3630
+ } else {
3631
+ this.metricCount--;
3632
+ }
2953
3633
  }
2954
- return start < end ? text.slice(start, end) : void 0;
2955
- }
2956
- function readNow(nowMs) {
2957
- return typeof nowMs === "number" && Number.isFinite(nowMs) ? nowMs : Date.now();
2958
- }
2959
- function readBound(bound, fallback) {
2960
- return typeof bound === "number" && Number.isFinite(bound) && bound >= 0 ? bound : fallback;
2961
- }
2962
- var RetryAfter = class _RetryAfter {
2963
3634
  /*
2964
- * The wait a Retry-After value asks for, in milliseconds, held between
2965
- * minMs and maxMs; undefined when the value is not a Retry-After (absent,
2966
- * empty, or neither delay-seconds nor an HTTP-date), so the caller waits
2967
- * its own backoff. The value is a header's: a string, a number, or the
2968
- * copies of a header sent more than once - which count only when they
2969
- * all say the same.
3635
+ * The next batch: the oldest items of one session and one person, up to
3636
+ * the per-batch counts and the target size. Items the server would drop
3637
+ * for their age are dropped here instead.
2970
3638
  */
2971
- static parseMs(value, options) {
2972
- const text = toText(value);
2973
- const asked = options || {};
2974
- let waitMs;
2975
- if (text === void 0) {
2976
- return void 0;
3639
+ takeBatch(now) {
3640
+ this.dropTooOld(now);
3641
+ const first = this.items[0];
3642
+ if (!first || first.scope.sessionId === "") {
3643
+ return null;
3644
+ }
3645
+ const scope = first.scope;
3646
+ let count = 0;
3647
+ let events = 0;
3648
+ let metrics = 0;
3649
+ for (const item of this.items) {
3650
+ if (!sameScope(item.scope, scope)) {
3651
+ break;
3652
+ }
3653
+ if (item.event) {
3654
+ if (events >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3655
+ break;
3656
+ }
3657
+ events++;
3658
+ } else {
3659
+ if (metrics >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3660
+ break;
3661
+ }
3662
+ metrics++;
3663
+ }
3664
+ count++;
3665
+ }
3666
+ const build = (taken) => {
3667
+ const slice = this.items.slice(0, taken);
3668
+ const batch2 = {
3669
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
3670
+ batchId: generateReplayId(),
3671
+ sessionId: scope.sessionId,
3672
+ visitorId: this.host.getVisitorId(),
3673
+ consentState: this.host.getConsentState(),
3674
+ sentAt: now,
3675
+ context: this.host.getContext(),
3676
+ events: slice.filter((item) => {
3677
+ return Boolean(item.event);
3678
+ }).map((item) => {
3679
+ return item.event;
3680
+ }),
3681
+ metrics: slice.filter((item) => {
3682
+ return Boolean(item.metric);
3683
+ }).map((item) => {
3684
+ return item.metric;
3685
+ })
3686
+ };
3687
+ if (scope.userRef) {
3688
+ batch2.userRef = scope.userRef;
3689
+ batch2.userProperties = scope.userProperties || {};
3690
+ }
3691
+ return batch2;
3692
+ };
3693
+ let batch = build(count);
3694
+ while (JSON.stringify(batch).length > PRODUCT_ANALYTICS_TARGET_BATCH_BYTES && count > 1) {
3695
+ count = Math.floor(count / 2);
3696
+ batch = build(count);
3697
+ }
3698
+ this.items.splice(0, count);
3699
+ this.eventCount -= batch.events.length;
3700
+ this.metricCount -= batch.metrics.length;
3701
+ return batch;
3702
+ }
3703
+ dropTooOld(now) {
3704
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
3705
+ const kept = [];
3706
+ for (const item of this.items) {
3707
+ if (itemAt(item) >= oldest) {
3708
+ kept.push(item);
3709
+ continue;
3710
+ }
3711
+ if (item.event) {
3712
+ this.eventCount--;
3713
+ this.droppedEvents++;
3714
+ } else {
3715
+ this.metricCount--;
3716
+ }
3717
+ }
3718
+ this.items = kept;
3719
+ }
3720
+ send(batch) {
3721
+ const generation = this.sendGeneration;
3722
+ const controller = typeof AbortController === "undefined" ? null : new AbortController();
3723
+ let timeout = null;
3724
+ const init = {
3725
+ method: "POST",
3726
+ headers: {
3727
+ ...this.host.headers,
3728
+ "Content-Type": PRODUCT_ANALYTICS_CONTENT_TYPE
3729
+ },
3730
+ body: JSON.stringify(batch)
3731
+ };
3732
+ if (controller) {
3733
+ init.signal = controller.signal;
3734
+ }
3735
+ let request;
3736
+ try {
3737
+ request = this.host.fetch(this.host.url, init);
3738
+ } catch {
3739
+ this.retryLater(this.host.now(), 0);
3740
+ return;
2977
3741
  }
2978
- if (DELAY_SECONDS.test(text)) {
2979
- waitMs = Number(text) * 1e3;
2980
- } else if (asked.acceptHttpDate !== false) {
2981
- const nowMs = readNow(asked.nowMs);
2982
- const retryAtMs = _RetryAfter.parseHttpDate(
2983
- text,
2984
- nowMs
3742
+ const deadline = new Promise(
3743
+ (_resolve, reject) => {
3744
+ timeout = setTimeout(() => {
3745
+ controller?.abort();
3746
+ reject(new Error("analytics-request-timeout"));
3747
+ }, PRODUCT_ANALYTICS_REQUEST_TIMEOUT_MS);
3748
+ }
3749
+ );
3750
+ this.sending = true;
3751
+ Promise.race([request, deadline]).then((response) => {
3752
+ if (generation !== this.sendGeneration) {
3753
+ return;
3754
+ }
3755
+ this.sending = false;
3756
+ this.onAnswer(response, this.host.now());
3757
+ }).catch(() => {
3758
+ if (generation !== this.sendGeneration) {
3759
+ return;
3760
+ }
3761
+ this.sending = false;
3762
+ this.retryLater(this.host.now(), 0);
3763
+ }).finally(() => {
3764
+ if (timeout) {
3765
+ clearTimeout(timeout);
3766
+ }
3767
+ });
3768
+ }
3769
+ onAnswer(response, now) {
3770
+ const status = response.status;
3771
+ if (status === 202 || status === 200) {
3772
+ this.pending = null;
3773
+ this.failures = 0;
3774
+ if (this.items.length > 0) {
3775
+ this.flush(false);
3776
+ }
3777
+ return;
3778
+ }
3779
+ if (status === 413) {
3780
+ this.pending = null;
3781
+ return;
3782
+ }
3783
+ if (status === 204 || status === 400 || status === 403) {
3784
+ let reason = "";
3785
+ try {
3786
+ reason = response.headers?.get("x-oneuptime-replay-reason") || "";
3787
+ } catch {
3788
+ reason = "";
3789
+ }
3790
+ this.host.onDiagnostic("analytics-stopped", {
3791
+ status,
3792
+ reason: reason.slice(0, 100)
3793
+ });
3794
+ this.stop(
3795
+ status === 403 ? "origin-not-allowed" : status === 204 ? "not-enabled" : "refused"
2985
3796
  );
2986
- waitMs = retryAtMs === void 0 ? void 0 : retryAtMs - nowMs;
3797
+ return;
2987
3798
  }
2988
- return waitMs === void 0 ? void 0 : Math.min(
2989
- Math.max(waitMs, readBound(asked.minMs, DEFAULT_RETRY_AFTER_MIN_MS)),
2990
- readBound(asked.maxMs, DEFAULT_RETRY_AFTER_MAX_MS)
2991
- );
3799
+ const retryAfterMs = status === 429 || status === 503 ? RetryAfter.msFromHeaders(response.headers, {
3800
+ maxMs: RETRY_AFTER_LIMIT_SECONDS * 1e3,
3801
+ nowMs: now
3802
+ }) ?? 0 : 0;
3803
+ this.retryLater(now, retryAfterMs);
2992
3804
  }
2993
- /*
2994
- * The same wait in whole seconds, rounded up - never sooner than asked -
2995
- * for a caller that counts in seconds.
2996
- */
2997
- static parseSeconds(value, options) {
2998
- const waitMs = _RetryAfter.parseMs(value, options);
2999
- return waitMs === void 0 ? void 0 : Math.ceil(waitMs / 1e3);
3805
+ retryLater(now, delayMs) {
3806
+ this.failures++;
3807
+ this.retryAtUnixMs = now + (delayMs > 0 ? delayMs : Math.min(
3808
+ PRODUCT_ANALYTICS_MAX_RETRY_DELAY_MS,
3809
+ PRODUCT_ANALYTICS_FLUSH_INTERVAL_MS * Math.pow(2, this.failures)
3810
+ ));
3000
3811
  }
3001
3812
  /*
3002
- * The Retry-After header of a response's headers, whatever its case: an
3003
- * object with a get() (fetch's Headers, axios's AxiosHeaders), or a plain
3004
- * object of names to values (Node's, a test's). Undefined when there is
3005
- * none; a get() that throws reads as none.
3813
+ * The app leaving the foreground sends what is held while it still can;
3814
+ * coming back, or the device saying it is online again, sends a batch
3815
+ * that waited at once, rather than when its retry was due.
3006
3816
  */
3007
- static readHeader(headers) {
3008
- if (!headers || typeof headers !== "object") {
3009
- return void 0;
3010
- }
3011
- const get = headers.get;
3012
- if (typeof get === "function") {
3817
+ listenToLifecycle() {
3818
+ const appState = this.host.appState;
3819
+ if (appState && typeof appState.addEventListener === "function") {
3013
3820
  try {
3014
- const value = get.call(
3015
- headers,
3016
- RETRY_AFTER_HEADER
3821
+ this.appStateSubscription = appState.addEventListener(
3822
+ "change",
3823
+ (state) => {
3824
+ if (state === "active") {
3825
+ this.retryAtUnixMs = 0;
3826
+ this.flush(false);
3827
+ return;
3828
+ }
3829
+ this.flush(true);
3830
+ }
3017
3831
  );
3018
- if (value !== void 0 && value !== null) {
3019
- return value;
3020
- }
3021
3832
  } catch {
3833
+ this.appStateSubscription = null;
3022
3834
  }
3023
3835
  }
3024
- for (const name of Object.keys(headers)) {
3025
- if (name.toLowerCase() === RETRY_AFTER_HEADER) {
3026
- return headers[name];
3027
- }
3836
+ const connectivity = this.host.connectivity;
3837
+ if (!connectivity) {
3838
+ return;
3028
3839
  }
3029
- return void 0;
3030
- }
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);
3038
- }
3039
- /*
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.
3043
- */
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]
3840
+ try {
3841
+ const unsubscribe = connectivity.subscribe(
3842
+ (isConnected) => {
3843
+ if (isConnected === false) {
3844
+ this.offline = true;
3845
+ return;
3846
+ }
3847
+ if (isConnected === true) {
3848
+ const wasOffline = this.offline;
3849
+ this.offline = false;
3850
+ if (wasOffline) {
3851
+ this.retryAtUnixMs = 0;
3852
+ this.flush(false);
3853
+ }
3854
+ }
3855
+ }
3054
3856
  );
3857
+ this.unsubscribeConnectivity = typeof unsubscribe === "function" ? unsubscribe : null;
3858
+ } catch {
3859
+ this.unsubscribeConnectivity = null;
3055
3860
  }
3056
- match = RFC_850_DATE.exec(value);
3057
- if (match) {
3058
- return readRfc850Date(match, readNow(nowMs));
3059
- }
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
3861
  }
3070
3862
  };
3071
3863
 
@@ -3727,6 +4519,19 @@ var MobileReplayRecorder = class {
3727
4519
  */
3728
4520
  __publicField(this, "softKeyboardVisible", false);
3729
4521
  __publicField(this, "keyboardSubscriptions", []);
4522
+ /*
4523
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts): beside
4524
+ * the recording, from every session the policy lets the recorder run in,
4525
+ * recorded or not. Null while the application has them off.
4526
+ */
4527
+ __publicField(this, "analytics", null);
4528
+ /*
4529
+ * The replay sample left the session out under "Always": nothing of it
4530
+ * is recorded, but its product analytics events are still sent - and,
4531
+ * nothing else moving the session, they are what keeps it alive
4532
+ * (ReplaySessionStore.continueSession), as the browser recorder does.
4533
+ */
4534
+ __publicField(this, "analyticsOnly", false);
3730
4535
  this.storage = dependencies.storage ?? defaultReplayStorage;
3731
4536
  this.nativeViewTree = dependencies.nativeViewTree ?? defaultNativeViewTreeAdapter;
3732
4537
  this.appState = dependencies.appState ?? import_react_native2.AppState;
@@ -3810,6 +4615,7 @@ var MobileReplayRecorder = class {
3810
4615
  this.idlePause = null;
3811
4616
  this.idleResumeBacklog = null;
3812
4617
  this.customSignalMatcher.reset();
4618
+ this.stopProductAnalytics();
3813
4619
  const validated = validateStartOptions(options);
3814
4620
  if (!validated) {
3815
4621
  this.disable("invalid-start-options");
@@ -3890,35 +4696,27 @@ var MobileReplayRecorder = class {
3890
4696
  }
3891
4697
  this.sessionLastActivityUnixMs = nowUnixMs;
3892
4698
  this.lastInputUnixMs = nowUnixMs;
4699
+ let metadataRead = false;
4700
+ if (config.productAnalytics.enabled) {
4701
+ if (!await this.readAppMetadata(validated, generation)) {
4702
+ return false;
4703
+ }
4704
+ metadataRead = true;
4705
+ await this.startProductAnalytics(validated, config, namespace);
4706
+ if (!this.isCurrentGeneration(generation)) {
4707
+ return false;
4708
+ }
4709
+ }
3893
4710
  if (!awaitingConsent && config.captureTrigger === "Always" /* Always */ && !this.sampled && !config.isTargeted) {
4711
+ this.analyticsOnly = this.analytics !== null;
3894
4712
  this.disable("not-sampled");
3895
4713
  return false;
3896
4714
  }
3897
4715
  this.outbox = new ReplayOutbox(this.storage, namespace, this.now);
3898
4716
  this.transport = this.createTransport(validated, this.outbox);
3899
4717
  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");
4718
+ if (!metadataRead && !await this.readAppMetadata(validated, generation)) {
4719
+ return false;
3922
4720
  }
3923
4721
  this.route = "/";
3924
4722
  this.entryUrl = toAppUrl(validated.mobileAppIdentifier, this.route);
@@ -3958,6 +4756,7 @@ var MobileReplayRecorder = class {
3958
4756
  this.lifecycleCancellationEpoch += 1;
3959
4757
  this.pendingStartCancellation?.cancel();
3960
4758
  this.acceptingEvents = false;
4759
+ this.stopProductAnalytics(true);
3961
4760
  this.quiesceCapture();
3962
4761
  return this.enqueueLifecycleOperation(async () => {
3963
4762
  await identityBarrier;
@@ -4032,6 +4831,7 @@ var MobileReplayRecorder = class {
4032
4831
  }
4033
4832
  this.diagnosticsStatus = this.foreground ? "recording" : "background";
4034
4833
  this.diagnostic("consent-granted");
4834
+ this.analytics?.onConsentGranted();
4035
4835
  }
4036
4836
  revokeConsent() {
4037
4837
  this.lifecycleGeneration += 1;
@@ -4040,6 +4840,7 @@ var MobileReplayRecorder = class {
4040
4840
  this.pendingStartCancellation?.cancel();
4041
4841
  this.consentGranted = false;
4042
4842
  this.acceptingEvents = false;
4843
+ this.analytics?.forget();
4043
4844
  this.haltCapture();
4044
4845
  this.transport?.destroy();
4045
4846
  return this.enqueueLifecycleOperation(async () => {
@@ -4127,6 +4928,9 @@ var MobileReplayRecorder = class {
4127
4928
  if (!eventName) {
4128
4929
  return;
4129
4930
  }
4931
+ this.afterIdentity(() => {
4932
+ this.analytics?.track(name, properties);
4933
+ });
4130
4934
  const sanitizedProperties = maskStringMapValues(
4131
4935
  sanitizeEventProperties(properties)
4132
4936
  );
@@ -4147,8 +4951,42 @@ var MobileReplayRecorder = class {
4147
4951
  }
4148
4952
  });
4149
4953
  }
4954
+ /*
4955
+ * A number the app measured ("cart.value", 42.5), with optional
4956
+ * attributes: a point in the metric store under the RUM application, for
4957
+ * charts, dashboards and Metrics monitors (issue #6629). It needs product
4958
+ * analytics on for the application; its attribute values are masked, as
4959
+ * track()'s property values are.
4960
+ */
4961
+ metric(name, value, attributes) {
4962
+ if (!this.analytics || !this.analytics.isStarted()) {
4963
+ this.diagnostic("metric-analytics-off");
4964
+ return;
4965
+ }
4966
+ this.afterIdentity(() => {
4967
+ this.analytics?.metric(name, value, attributes);
4968
+ });
4969
+ }
4970
+ /*
4971
+ * Runs a product analytics call once every identify() made before it has
4972
+ * been applied - a change of user starts the next session first - or
4973
+ * now, when none is pending. Dropped when consent is withdrawn meanwhile.
4974
+ */
4975
+ afterIdentity(action) {
4976
+ if (this.pendingIdentityOperations === 0) {
4977
+ action();
4978
+ return;
4979
+ }
4980
+ const identityEpoch = this.identityCancellationEpoch;
4981
+ void this.identityQueue.then(() => {
4982
+ if (identityEpoch === this.identityCancellationEpoch) {
4983
+ action();
4984
+ }
4985
+ });
4986
+ }
4150
4987
  async setRoute(route) {
4151
4988
  await this.identityQueue;
4989
+ this.analytics?.page(sanitizeRoute(route));
4152
4990
  if (this.running && (!this.acceptingEvents || this.isIdlePaused())) {
4153
4991
  this.route = sanitizeRoute(route);
4154
4992
  return;
@@ -4329,6 +5167,7 @@ var MobileReplayRecorder = class {
4329
5167
  triggered: this.triggered,
4330
5168
  consentState: this.consentState(),
4331
5169
  pendingEvents: this.rollingBuffer.length + (this.chunkBuffer.isEmpty() ? 0 : 1),
5170
+ productAnalytics: this.analytics ? this.analytics.getDiagnostics() : { state: "off", pending: 0, dropped: 0 },
4332
5171
  events: this.diagnosticsEvents.map(
4333
5172
  (event) => {
4334
5173
  const copied = {
@@ -5315,6 +6154,15 @@ var MobileReplayRecorder = class {
5315
6154
  return;
5316
6155
  }
5317
6156
  if (!this.running) {
6157
+ if (this.analyticsOnly && ref !== this.userRef && this.identityPersisted && this.sessionStore) {
6158
+ const identity = await this.sessionStore.rotate(
6159
+ this.now()
6160
+ );
6161
+ if (identityEpoch !== this.identityCancellationEpoch) {
6162
+ return;
6163
+ }
6164
+ this.identity = identity;
6165
+ }
5318
6166
  this.applyIdentityValues(ref, traits, true);
5319
6167
  return;
5320
6168
  }
@@ -5538,10 +6386,18 @@ var MobileReplayRecorder = class {
5538
6386
  async applyRuntimePolicy(_previousConfig, freshConfig, previousConsentState, wasAcceptingEvents, generation) {
5539
6387
  this.config = freshConfig;
5540
6388
  this.metaDirty = true;
6389
+ const analyticsStart = this.syncProductAnalytics(freshConfig);
6390
+ if (analyticsStart) {
6391
+ await analyticsStart;
6392
+ if (!this.running || !this.isCurrentGeneration(generation)) {
6393
+ return false;
6394
+ }
6395
+ }
5541
6396
  const hasConsent = freshConfig.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5542
6397
  if (!hasConsent) {
5543
6398
  const mustWithdrawPersistedState = this.identityPersisted || this.uploadActive || previousConsentState !== "Unknown";
5544
6399
  if (mustWithdrawPersistedState) {
6400
+ this.analytics?.reset();
5545
6401
  this.transport?.destroy();
5546
6402
  this.chunkBuffer.clear();
5547
6403
  this.rollingBuffer.clear();
@@ -5633,6 +6489,7 @@ var MobileReplayRecorder = class {
5633
6489
  this.diagnostic("policy-refreshed", {
5634
6490
  configEpoch: freshConfig.configEpoch
5635
6491
  });
6492
+ this.analytics?.refresh();
5636
6493
  return true;
5637
6494
  }
5638
6495
  currentStartOptions() {
@@ -5652,6 +6509,11 @@ var MobileReplayRecorder = class {
5652
6509
  }
5653
6510
  }
5654
6511
  async discardForPolicyStop(code, reason) {
6512
+ if (reason === "not-sampled") {
6513
+ this.analyticsOnly = this.analytics !== null;
6514
+ } else {
6515
+ this.stopProductAnalytics();
6516
+ }
5655
6517
  this.disable(code, { reason });
5656
6518
  this.haltCapture();
5657
6519
  this.transport?.destroy();
@@ -5946,6 +6808,7 @@ var MobileReplayRecorder = class {
5946
6808
  this.entryUrl = toAppUrl(this.options.mobileAppIdentifier, this.route);
5947
6809
  this.diagnostic("session-rotated", { reason });
5948
6810
  if (this.config.captureTrigger === "Always" /* Always */ && this.identityPersisted && !this.sampled && !this.config.isTargeted) {
6811
+ this.analyticsOnly = this.analytics !== null;
5949
6812
  this.disable("not-sampled");
5950
6813
  this.haltCapture();
5951
6814
  return;
@@ -5954,6 +6817,184 @@ var MobileReplayRecorder = class {
5954
6817
  this.startTimers();
5955
6818
  }
5956
6819
  }
6820
+ /*
6821
+ * The app's name, version and system, as the start options and then the
6822
+ * native module say them. False when a newer start or a stop took over
6823
+ * meanwhile.
6824
+ */
6825
+ async readAppMetadata(validated, generation) {
6826
+ try {
6827
+ const nativeMetadata = await this.nativeViewTree.getAppMetadata();
6828
+ if (!this.isCurrentGeneration(generation)) {
6829
+ return false;
6830
+ }
6831
+ this.metadata = {
6832
+ appName: safeMetadataValue(
6833
+ validated.appName,
6834
+ safeMetadataValue(nativeMetadata?.appName, "React Native")
6835
+ ),
6836
+ appVersion: safeMetadataValue(
6837
+ validated.appVersion,
6838
+ safeMetadataValue(nativeMetadata?.appVersion, "unknown")
6839
+ ),
6840
+ osName: safeMetadataValue(nativeMetadata?.osName, "unknown"),
6841
+ osVersion: safeMetadataValue(nativeMetadata?.osVersion, "unknown")
6842
+ };
6843
+ } catch {
6844
+ if (!this.isCurrentGeneration(generation)) {
6845
+ return false;
6846
+ }
6847
+ this.diagnostic("native-metadata-unavailable");
6848
+ }
6849
+ return true;
6850
+ }
6851
+ /*
6852
+ * Product analytics events (issue #6629, src/ProductAnalytics.ts), when
6853
+ * the application has them on: the channel asks this recorder for the
6854
+ * session, the visitor, consent and who is signed in, so an event and a
6855
+ * recording of the same visit carry the same ids.
6856
+ */
6857
+ async startProductAnalytics(options, config, namespace) {
6858
+ if (this.analytics || !config.productAnalytics.enabled) {
6859
+ return;
6860
+ }
6861
+ const analytics = new MobileProductAnalytics(
6862
+ {
6863
+ url: `${options.host}${PRODUCT_ANALYTICS_EVENTS_PATH}`,
6864
+ headers: mobileRequestHeaders(options),
6865
+ fetch: options.fetch,
6866
+ now: this.now,
6867
+ storage: this.storage,
6868
+ namespace,
6869
+ appState: this.appState,
6870
+ connectivity: options.connectivity,
6871
+ getSessionId: (nowUnixMs) => {
6872
+ return this.analyticsSessionId(nowUnixMs, true);
6873
+ },
6874
+ peekSessionId: () => {
6875
+ return this.analyticsSessionId(this.now(), false);
6876
+ },
6877
+ getVisitorId: () => {
6878
+ return this.identityPersisted ? this.identity?.visitorId ?? "" : "";
6879
+ },
6880
+ getConsentState: () => {
6881
+ return this.consentState();
6882
+ },
6883
+ requiresConsent: () => {
6884
+ return this.config?.consentMode === "RequireExplicit" /* RequireExplicit */;
6885
+ },
6886
+ getIdentity: () => {
6887
+ return this.analyticsIdentity();
6888
+ },
6889
+ toProperties: (value) => {
6890
+ return maskStringMapValues(sanitizeEventProperties(value));
6891
+ },
6892
+ getContext: () => {
6893
+ return this.analyticsContext();
6894
+ },
6895
+ onDiagnostic: (code, details) => {
6896
+ this.diagnostic(code, details);
6897
+ }
6898
+ },
6899
+ config.productAnalytics
6900
+ );
6901
+ this.analytics = analytics;
6902
+ await analytics.start();
6903
+ }
6904
+ /*
6905
+ * Ends the product analytics channel this recorder started; `flushFirst`
6906
+ * sends what it holds first (stop()).
6907
+ */
6908
+ stopProductAnalytics(flushFirst = false) {
6909
+ const analytics = this.analytics;
6910
+ this.analytics = null;
6911
+ this.analyticsOnly = false;
6912
+ if (!analytics) {
6913
+ return;
6914
+ }
6915
+ if (flushFirst) {
6916
+ analytics.flush(true);
6917
+ }
6918
+ analytics.stop();
6919
+ }
6920
+ /*
6921
+ * A refreshed policy's product analytics: switched off, the channel
6922
+ * stops; switched on, it starts - again, too, after the server said they
6923
+ * were off - and its trait keys follow the policy. A promise only when a
6924
+ * channel has to start.
6925
+ */
6926
+ syncProductAnalytics(config) {
6927
+ if (!config.productAnalytics.enabled) {
6928
+ this.stopProductAnalytics();
6929
+ return null;
6930
+ }
6931
+ if (this.analytics && this.analytics.getStopReason() !== "not-enabled") {
6932
+ this.analytics.setConfig(config.productAnalytics);
6933
+ return null;
6934
+ }
6935
+ if (!this.options) {
6936
+ return null;
6937
+ }
6938
+ const options = this.currentStartOptions();
6939
+ this.stopProductAnalytics();
6940
+ return this.startProductAnalytics(
6941
+ options,
6942
+ config,
6943
+ getReplayStorageNamespace(options)
6944
+ );
6945
+ }
6946
+ /*
6947
+ * The session a product analytics event belongs to (issue #6629). The
6948
+ * recording's own while the recorder runs: it rotates its session
6949
+ * itself, and a session that ended idle keeps its id until the next one
6950
+ * starts. "" before consent, when the session the recorder holds is a
6951
+ * throwaway: the events wait for the one the grant opens. A session the
6952
+ * replay sample left out records nothing, so an event is its activity
6953
+ * (isActivity), and keeps it alive or rolls it over.
6954
+ */
6955
+ analyticsSessionId(nowUnixMs, isActivity) {
6956
+ if (!this.identity || !this.identityPersisted) {
6957
+ return "";
6958
+ }
6959
+ if (this.running) {
6960
+ return this.identity.sessionId;
6961
+ }
6962
+ if (this.analyticsOnly && this.sessionStore) {
6963
+ if (isActivity) {
6964
+ const continued = this.sessionStore.continueSession(nowUnixMs);
6965
+ if (continued) {
6966
+ this.identity = continued;
6967
+ }
6968
+ }
6969
+ return this.identity.sessionId;
6970
+ }
6971
+ return "";
6972
+ }
6973
+ /* Who is signed in, only while the application captures identity. */
6974
+ analyticsIdentity() {
6975
+ if (this.config?.captureUserIdentity !== true || !this.userRef) {
6976
+ return { userRef: "", traits: null };
6977
+ }
6978
+ return { userRef: this.userRef, traits: { ...this.traits } };
6979
+ }
6980
+ /*
6981
+ * What the app runs on, as its recorded sessions are filed (Common's
6982
+ * RumProductAnalyticsSession): a phone, or a tablet from a shorter side
6983
+ * of 600 points; no browser; the system the native module names; and the
6984
+ * app's version, from the start options or the native module.
6985
+ */
6986
+ analyticsContext() {
6987
+ const size = getViewport();
6988
+ const known = (value) => {
6989
+ return value === "unknown" ? "" : value;
6990
+ };
6991
+ return {
6992
+ deviceType: Math.min(size.width, size.height) >= PRODUCT_ANALYTICS_TABLET_MIN_SHORT_SIDE ? "tablet" : "mobile",
6993
+ browserName: "",
6994
+ osName: known(this.metadata.osName).trim().slice(0, PRODUCT_ANALYTICS_MAX_CONTEXT_VALUE_LENGTH),
6995
+ appVersion: toProductAnalyticsAppVersion(known(this.metadata.appVersion))
6996
+ };
6997
+ }
5957
6998
  disable(code, details) {
5958
6999
  this.diagnosticsStatus = "disabled";
5959
7000
  this.diagnostic(code, details);