@oneuptime/react-native-replay 17.0.0 → 17.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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 ? "17.0.0" : "0.0.0-dev";
63
+ var RECORDER_VERSION = true ? "17.1.0" : "0.0.0-dev";
64
64
  var SESSION_REPLAY_MOBILE_RECORDER_CAPABILITIES = [
65
65
  "mobile-view-tree",
66
66
  "mobile-touch-events",
@@ -211,10 +211,11 @@ function maskTextValue(value) {
211
211
  const maskedLength = length <= 8 ? 4 : length <= 32 ? 16 : 40;
212
212
  return "\u2022".repeat(maskedLength);
213
213
  }
214
- function maskStringMapValues(values) {
214
+ var READABLE_VALUE_PATTERN = /^[A-Za-z0-9_.:/-]{0,32}$/;
215
+ function maskStringMapValues(values, readableKeys = []) {
215
216
  const masked = /* @__PURE__ */ Object.create(null);
216
217
  for (const [key, value] of Object.entries(values)) {
217
- masked[key] = maskTextValue(value);
218
+ masked[key] = readableKeys.indexOf(key) !== -1 && READABLE_VALUE_PATTERN.test(value) ? value : maskTextValue(value);
218
219
  }
219
220
  return masked;
220
221
  }
@@ -480,22 +481,28 @@ var RollingReplayBuffer = class {
480
481
  // src/CustomSignals.ts
481
482
  var TRIGGERS = [
482
483
  "click",
484
+ "tap",
483
485
  "page",
484
486
  "event",
485
487
  "error"
486
488
  ];
489
+ var MAX_TAP_TARGET_TEST_IDS = 32;
487
490
  function asRecord(value) {
488
491
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
489
492
  }
490
493
  function isTrigger(value) {
491
494
  return typeof value === "string" && TRIGGERS.indexOf(value) !== -1;
492
495
  }
496
+ function isTapPatternUsable(pattern) {
497
+ const star = pattern.indexOf("*");
498
+ return star === -1 || star > 0 && star === pattern.length - 1;
499
+ }
493
500
  function readCustomSignal(value) {
494
501
  const record = asRecord(value);
495
502
  const name = typeof record["name"] === "string" ? record["name"].trim() : "";
496
503
  const trigger = record["trigger"];
497
504
  const match = typeof record["match"] === "string" ? record["match"].trim() : "";
498
- if (name.length === 0 || name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH || !isTrigger(trigger) || match.length === 0 || match.length > (trigger === "event" ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) || trigger === "page" && match.charAt(0) !== "/" && match.charAt(0) !== "*") {
505
+ if (name.length === 0 || name.length > SESSION_REPLAY_MAX_CUSTOM_SIGNAL_NAME_LENGTH || !isTrigger(trigger) || match.length === 0 || match.length > (trigger === "event" ? SESSION_REPLAY_MAX_CUSTOM_SIGNAL_EVENT_NAME_LENGTH : SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) || trigger === "page" && match.charAt(0) !== "/" && match.charAt(0) !== "*" || trigger === "tap" && !isTapPatternUsable(match)) {
499
506
  return null;
500
507
  }
501
508
  return {
@@ -616,6 +623,29 @@ function matchesErrorText(match, text) {
616
623
  function matchesEventName(match, name) {
617
624
  return match.trim().toLowerCase() === name.trim().toLowerCase();
618
625
  }
626
+ function matchesTapTarget(match, testId) {
627
+ const pattern = match.trim().toLowerCase();
628
+ const target = testId.toLowerCase();
629
+ if (!pattern || !target || !isTapPatternUsable(pattern)) {
630
+ return false;
631
+ }
632
+ return pattern.charAt(pattern.length - 1) === "*" ? target.indexOf(pattern.slice(0, -1)) === 0 : target === pattern;
633
+ }
634
+ function readTapTargetTestIds(value) {
635
+ if (!Array.isArray(value)) {
636
+ return [];
637
+ }
638
+ const testIds = [];
639
+ for (const entry of value) {
640
+ if (typeof entry === "string" && entry.length > 0 && entry.length <= SESSION_REPLAY_MAX_CUSTOM_SIGNAL_MATCH_LENGTH) {
641
+ testIds.push(entry);
642
+ }
643
+ if (testIds.length >= MAX_TAP_TARGET_TEST_IDS) {
644
+ break;
645
+ }
646
+ }
647
+ return testIds;
648
+ }
619
649
  function routeMatchPath(route) {
620
650
  let path = typeof route === "string" ? route.trim() : "";
621
651
  const scheme = path.indexOf("://");
@@ -637,6 +667,26 @@ var CustomSignalMatcher = class {
637
667
  constructor() {
638
668
  __publicField(this, "lastFiredAt", /* @__PURE__ */ new Map());
639
669
  }
670
+ /*
671
+ * A tap on a view whose testID a tap signal names - or on anything inside
672
+ * it: testIds holds the touched view's testID and those of the views
673
+ * around it, out to the replay root, the touched one first.
674
+ */
675
+ matchTap(signals, testIds, atUnixMs) {
676
+ if (testIds.length === 0) {
677
+ return [];
678
+ }
679
+ return this.collect(
680
+ signals,
681
+ "tap",
682
+ atUnixMs,
683
+ (signal) => {
684
+ return testIds.some((testId) => {
685
+ return matchesTapTarget(signal.match, testId);
686
+ });
687
+ }
688
+ );
689
+ }
640
690
  matchPage(signals, route, atUnixMs) {
641
691
  const path = routeMatchPath(route);
642
692
  return this.collect(
@@ -897,6 +947,7 @@ function failClosed(reason) {
897
947
  isTargeted: false,
898
948
  frustrationSignals: { customSignals: [] },
899
949
  productAnalytics: { enabled: false, userPropertyKeys: [] },
950
+ readableEventPropertyKeys: [],
900
951
  disabledReason: reason
901
952
  };
902
953
  }
@@ -932,6 +983,13 @@ function normalizeReplayConfig(value) {
932
983
  */
933
984
  productAnalytics: readProductAnalyticsRecorderConfig(
934
985
  config.productAnalytics
986
+ ),
987
+ /*
988
+ * Read as product analytics reads the traits it keeps, as Common's
989
+ * normalizeSessionReplayReadablePropertyKeys does: absent, none.
990
+ */
991
+ readableEventPropertyKeys: normalizeProductAnalyticsUserPropertyKeys(
992
+ config.readableEventPropertyKeys
935
993
  )
936
994
  };
937
995
  if (typeof config.disabledReason === "string") {
@@ -1515,6 +1573,24 @@ var ReactNativeViewTreeAdapter = class {
1515
1573
  return true;
1516
1574
  }
1517
1575
  }
1576
+ /*
1577
+ * A native module built before tap signals existed (an over-the-air
1578
+ * update of the JavaScript alone) has no such method: no testIDs, so no
1579
+ * tap signal fires, and nothing else changes.
1580
+ */
1581
+ async touchTargetTestIds(targetTag, replayRootTag) {
1582
+ const nativeModule = NativeModules["OneUptimeReplayViewTree"];
1583
+ if (typeof nativeModule?.touchTargetTestIds !== "function") {
1584
+ return [];
1585
+ }
1586
+ try {
1587
+ return readTapTargetTestIds(
1588
+ await nativeModule.touchTargetTestIds(targetTag, replayRootTag)
1589
+ );
1590
+ } catch {
1591
+ return [];
1592
+ }
1593
+ }
1518
1594
  };
1519
1595
  var defaultNativeViewTreeAdapter = new ReactNativeViewTreeAdapter();
1520
1596
  function getViewport() {
@@ -3164,6 +3240,259 @@ var REPLAY_ID_PATTERN2 = /^[0-9a-f]{32}$/u;
3164
3240
  function productAnalyticsSessionKey(namespace) {
3165
3241
  return `@oneuptime/replay/${namespace}/analytics-session`;
3166
3242
  }
3243
+ function productAnalyticsQueueKey(namespace) {
3244
+ return `@oneuptime/replay/${namespace}/analytics-queue`;
3245
+ }
3246
+ var PRODUCT_ANALYTICS_STORED_QUEUE_VERSION = 1;
3247
+ var PRODUCT_ANALYTICS_MAX_STORED_BYTES = 512 * 1024;
3248
+ var PRODUCT_ANALYTICS_STORE_DELAY_MS = 1e3;
3249
+ var storeWrites = /* @__PURE__ */ new WeakMap();
3250
+ function writesOf(storage) {
3251
+ let writes = storeWrites.get(storage);
3252
+ if (!writes) {
3253
+ writes = /* @__PURE__ */ new Map();
3254
+ storeWrites.set(storage, writes);
3255
+ }
3256
+ return writes;
3257
+ }
3258
+ function enqueueStoreWrite(storage, key, write) {
3259
+ const writes = writesOf(storage);
3260
+ const run = async () => {
3261
+ try {
3262
+ await write();
3263
+ } catch {
3264
+ }
3265
+ };
3266
+ const next = (writes.get(key) ?? Promise.resolve()).then(
3267
+ run,
3268
+ run
3269
+ );
3270
+ writes.set(key, next);
3271
+ return next;
3272
+ }
3273
+ async function storeWritesSettled(storage, key) {
3274
+ try {
3275
+ await writesOf(storage).get(key);
3276
+ } catch {
3277
+ }
3278
+ }
3279
+ async function clearStoredProductAnalytics(storage, namespace) {
3280
+ await Promise.all([
3281
+ enqueueStoreWrite(
3282
+ storage,
3283
+ productAnalyticsQueueKey(namespace),
3284
+ async () => {
3285
+ await storage.removeItem(productAnalyticsQueueKey(namespace));
3286
+ }
3287
+ ),
3288
+ enqueueStoreWrite(
3289
+ storage,
3290
+ productAnalyticsSessionKey(namespace),
3291
+ async () => {
3292
+ await storage.removeItem(productAnalyticsSessionKey(namespace));
3293
+ }
3294
+ )
3295
+ ]);
3296
+ }
3297
+ var EVENT_KINDS = [
3298
+ "session" /* Session */,
3299
+ "page" /* Page */,
3300
+ "custom" /* Custom */
3301
+ ];
3302
+ function isPlainRecord(value) {
3303
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3304
+ }
3305
+ function isStringMap(value) {
3306
+ return isPlainRecord(value) && Object.keys(value).every((key) => {
3307
+ return typeof value[key] === "string";
3308
+ });
3309
+ }
3310
+ function isFiniteTime(value) {
3311
+ return typeof value === "number" && Number.isFinite(value);
3312
+ }
3313
+ function readStoredEvent(value) {
3314
+ if (!isPlainRecord(value) || typeof value["kind"] !== "string" || EVENT_KINDS.indexOf(value["kind"]) === -1 || typeof value["name"] !== "string" || !isFiniteTime(value["at"]) || value["page"] !== void 0 && typeof value["page"] !== "string" || value["properties"] !== void 0 && !isStringMap(value["properties"])) {
3315
+ return null;
3316
+ }
3317
+ const event = {
3318
+ kind: value["kind"],
3319
+ name: value["name"],
3320
+ at: value["at"]
3321
+ };
3322
+ if (typeof value["page"] === "string") {
3323
+ event.page = value["page"];
3324
+ }
3325
+ if (isStringMap(value["properties"])) {
3326
+ event.properties = value["properties"];
3327
+ }
3328
+ return event;
3329
+ }
3330
+ function readStoredMetric(value) {
3331
+ if (!isPlainRecord(value) || !isProductAnalyticsMetricName(value["name"]) || !isFiniteTime(value["value"]) || !isFiniteTime(value["at"]) || value["attributes"] !== void 0 && !isStringMap(value["attributes"])) {
3332
+ return null;
3333
+ }
3334
+ const metric = {
3335
+ name: value["name"],
3336
+ value: value["value"],
3337
+ at: value["at"]
3338
+ };
3339
+ if (isStringMap(value["attributes"])) {
3340
+ metric.attributes = value["attributes"];
3341
+ }
3342
+ return metric;
3343
+ }
3344
+ function readStoredScope(value) {
3345
+ if (!isPlainRecord(value) || typeof value["sessionId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["sessionId"]) || typeof value["userRef"] !== "string" || value["userProperties"] !== null && !isStringMap(value["userProperties"])) {
3346
+ return null;
3347
+ }
3348
+ return {
3349
+ sessionId: value["sessionId"],
3350
+ userRef: value["userRef"],
3351
+ userProperties: value["userProperties"]
3352
+ };
3353
+ }
3354
+ function readStoredBatch(value) {
3355
+ if (!isPlainRecord(value) || value["v"] !== PRODUCT_ANALYTICS_WIRE_VERSION || typeof value["batchId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["batchId"]) || typeof value["sessionId"] !== "string" || !REPLAY_ID_PATTERN2.test(value["sessionId"]) || typeof value["visitorId"] !== "string" || typeof value["consentState"] !== "string" || !isFiniteTime(value["sentAt"]) || !isStringMap(value["context"]) || !Array.isArray(value["events"]) || !Array.isArray(value["metrics"]) || value["events"].length > PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH || value["metrics"].length > PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH || value["userRef"] !== void 0 && typeof value["userRef"] !== "string" || value["userProperties"] !== void 0 && !isStringMap(value["userProperties"])) {
3356
+ return null;
3357
+ }
3358
+ const events = [];
3359
+ const metrics = [];
3360
+ for (const entry of value["events"]) {
3361
+ const event = readStoredEvent(entry);
3362
+ if (!event) {
3363
+ return null;
3364
+ }
3365
+ events.push(event);
3366
+ }
3367
+ for (const entry of value["metrics"]) {
3368
+ const metric = readStoredMetric(entry);
3369
+ if (!metric) {
3370
+ return null;
3371
+ }
3372
+ metrics.push(metric);
3373
+ }
3374
+ const context = value["context"];
3375
+ const batch = {
3376
+ v: PRODUCT_ANALYTICS_WIRE_VERSION,
3377
+ batchId: value["batchId"],
3378
+ sessionId: value["sessionId"],
3379
+ visitorId: value["visitorId"],
3380
+ consentState: value["consentState"],
3381
+ sentAt: value["sentAt"],
3382
+ context: {
3383
+ deviceType: context["deviceType"] ?? "",
3384
+ browserName: context["browserName"] ?? "",
3385
+ osName: context["osName"] ?? "",
3386
+ appVersion: context["appVersion"] ?? ""
3387
+ },
3388
+ events,
3389
+ metrics
3390
+ };
3391
+ if (typeof value["userRef"] === "string") {
3392
+ batch.userRef = value["userRef"];
3393
+ batch.userProperties = isStringMap(value["userProperties"]) ? value["userProperties"] : {};
3394
+ }
3395
+ return batch;
3396
+ }
3397
+ function readStoredQueue(raw) {
3398
+ if (!raw) {
3399
+ return null;
3400
+ }
3401
+ let parsed;
3402
+ try {
3403
+ parsed = JSON.parse(raw);
3404
+ } catch {
3405
+ return null;
3406
+ }
3407
+ if (!isPlainRecord(parsed) || parsed["v"] !== PRODUCT_ANALYTICS_STORED_QUEUE_VERSION || !Array.isArray(parsed["scopes"]) || !Array.isArray(parsed["items"])) {
3408
+ return null;
3409
+ }
3410
+ const scopes = parsed["scopes"].map(readStoredScope);
3411
+ const items = [];
3412
+ for (const entry of parsed["items"]) {
3413
+ if (!isPlainRecord(entry) || typeof entry["s"] !== "number") {
3414
+ continue;
3415
+ }
3416
+ const scope = scopes[entry["s"]];
3417
+ if (!scope) {
3418
+ continue;
3419
+ }
3420
+ if (entry["e"] !== void 0) {
3421
+ const event = readStoredEvent(
3422
+ entry["e"]
3423
+ );
3424
+ if (event) {
3425
+ items.push({ scope, event });
3426
+ }
3427
+ continue;
3428
+ }
3429
+ const metric = readStoredMetric(
3430
+ entry["m"]
3431
+ );
3432
+ if (metric) {
3433
+ items.push({ scope, metric });
3434
+ }
3435
+ }
3436
+ return {
3437
+ items,
3438
+ pending: parsed["pending"] === null || parsed["pending"] === void 0 ? null : readStoredBatch(parsed["pending"])
3439
+ };
3440
+ }
3441
+ function scopeKey(scope) {
3442
+ return JSON.stringify([scope.sessionId, scope.userRef, scope.userProperties]);
3443
+ }
3444
+ function buildStoredQueue(items, pending) {
3445
+ const named = items.filter((item) => {
3446
+ return item.scope.sessionId !== "";
3447
+ });
3448
+ if (named.length === 0 && !pending) {
3449
+ return null;
3450
+ }
3451
+ const build = (from2) => {
3452
+ const scopes = [];
3453
+ const scopeIndex = /* @__PURE__ */ new Map();
3454
+ const stored = [];
3455
+ for (const item of named.slice(from2)) {
3456
+ const key = scopeKey(item.scope);
3457
+ let index = scopeIndex.get(key);
3458
+ if (index === void 0) {
3459
+ index = scopes.length;
3460
+ scopes.push(item.scope);
3461
+ scopeIndex.set(key, index);
3462
+ }
3463
+ if (item.event) {
3464
+ stored.push({ s: index, e: item.event });
3465
+ } else if (item.metric) {
3466
+ stored.push({ s: index, m: item.metric });
3467
+ }
3468
+ }
3469
+ const queue = {
3470
+ v: PRODUCT_ANALYTICS_STORED_QUEUE_VERSION,
3471
+ scopes,
3472
+ items: stored,
3473
+ pending
3474
+ };
3475
+ return JSON.stringify(queue);
3476
+ };
3477
+ let from = 0;
3478
+ let value = build(from);
3479
+ if (byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {
3480
+ return value;
3481
+ }
3482
+ let low = 1;
3483
+ let high = named.length;
3484
+ while (low < high) {
3485
+ const middle = Math.floor((low + high) / 2);
3486
+ if (byteLength(build(middle)) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES) {
3487
+ high = middle;
3488
+ } else {
3489
+ low = middle + 1;
3490
+ }
3491
+ }
3492
+ from = low;
3493
+ value = build(from);
3494
+ return byteLength(value) <= PRODUCT_ANALYTICS_MAX_STORED_BYTES ? value : null;
3495
+ }
3167
3496
  function itemAt(item) {
3168
3497
  return item.event ? item.event.at : item.metric?.at ?? 0;
3169
3498
  }
@@ -3214,6 +3543,13 @@ var MobileProductAnalytics = class {
3214
3543
  __publicField(this, "flushTimer", null);
3215
3544
  __publicField(this, "appStateSubscription", null);
3216
3545
  __publicField(this, "unsubscribeConnectivity", null);
3546
+ /*
3547
+ * The stored queue (issue #9577). Written only once what a previous run
3548
+ * left there has been read back, so a channel that never got that far
3549
+ * can never overwrite it with nothing.
3550
+ */
3551
+ __publicField(this, "restored", false);
3552
+ __publicField(this, "storeTimer", null);
3217
3553
  this.host = host;
3218
3554
  this.config = config;
3219
3555
  }
@@ -3227,6 +3563,9 @@ var MobileProductAnalytics = class {
3227
3563
  return;
3228
3564
  }
3229
3565
  let stored = null;
3566
+ let storedQueue = null;
3567
+ const queueKey = productAnalyticsQueueKey(this.host.namespace);
3568
+ await storeWritesSettled(this.host.storage, queueKey);
3230
3569
  try {
3231
3570
  stored = await this.host.storage.getItem(
3232
3571
  productAnalyticsSessionKey(this.host.namespace)
@@ -3234,11 +3573,20 @@ var MobileProductAnalytics = class {
3234
3573
  } catch {
3235
3574
  stored = null;
3236
3575
  }
3576
+ try {
3577
+ storedQueue = await this.host.storage.getItem(queueKey);
3578
+ } catch {
3579
+ storedQueue = null;
3580
+ }
3237
3581
  if (this.started || this.stopReason) {
3238
3582
  return;
3239
3583
  }
3240
3584
  this.announcedSessionId = typeof stored === "string" && REPLAY_ID_PATTERN2.test(stored) ? stored : null;
3241
3585
  this.started = true;
3586
+ this.restored = true;
3587
+ if (!this.revoked) {
3588
+ this.restoreQueue(storedQueue, this.host.now());
3589
+ }
3242
3590
  this.enterCurrentSession(this.host.now(), false);
3243
3591
  this.flushTimer = setInterval(() => {
3244
3592
  this.flush(false);
@@ -3340,6 +3688,7 @@ var MobileProductAnalytics = class {
3340
3688
  if (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
3341
3689
  this.dropOldest("metric");
3342
3690
  }
3691
+ this.scheduleStore();
3343
3692
  if (this.metricCount >= PRODUCT_ANALYTICS_MAX_METRICS_PER_BATCH) {
3344
3693
  this.flush(false);
3345
3694
  }
@@ -3378,6 +3727,7 @@ var MobileProductAnalytics = class {
3378
3727
  forget() {
3379
3728
  this.revoked = true;
3380
3729
  this.clear();
3730
+ this.forgetStoredQueue();
3381
3731
  this.forgetAnnouncedSession();
3382
3732
  }
3383
3733
  /*
@@ -3387,6 +3737,7 @@ var MobileProductAnalytics = class {
3387
3737
  */
3388
3738
  reset() {
3389
3739
  this.clear();
3740
+ this.forgetStoredQueue();
3390
3741
  this.forgetAnnouncedSession();
3391
3742
  }
3392
3743
  /* Granted: what was held is filed under the session the grant opened, and goes now. */
@@ -3394,6 +3745,7 @@ var MobileProductAnalytics = class {
3394
3745
  this.revoked = false;
3395
3746
  this.retryAtUnixMs = 0;
3396
3747
  this.enterCurrentSession(this.host.now(), false);
3748
+ this.scheduleStore();
3397
3749
  this.flush(false);
3398
3750
  }
3399
3751
  /*
@@ -3406,13 +3758,23 @@ var MobileProductAnalytics = class {
3406
3758
  return;
3407
3759
  }
3408
3760
  this.enterCurrentSession(this.host.now(), false);
3761
+ this.scheduleStore();
3409
3762
  this.flush(false);
3410
3763
  }
3411
3764
  stop(reason = "stopped") {
3765
+ const isFirstStop = !this.stopReason;
3412
3766
  if (!this.stopReason) {
3413
3767
  this.stopReason = reason;
3414
3768
  }
3769
+ if (isFirstStop && this.restored) {
3770
+ if (reason === "stopped") {
3771
+ this.storeNow();
3772
+ } else {
3773
+ this.forgetStoredQueue();
3774
+ }
3775
+ }
3415
3776
  this.clear();
3777
+ this.cancelStoreTimer();
3416
3778
  if (this.flushTimer) {
3417
3779
  clearInterval(this.flushTimer);
3418
3780
  this.flushTimer = null;
@@ -3546,6 +3908,7 @@ var MobileProductAnalytics = class {
3546
3908
  this.eventCount++;
3547
3909
  this.announce(sessionId);
3548
3910
  this.trimEvents();
3911
+ this.scheduleStore();
3549
3912
  }
3550
3913
  if (firstUnnamed < 0 && isNewSession && this.route) {
3551
3914
  this.shownPage = this.route;
@@ -3560,6 +3923,7 @@ var MobileProductAnalytics = class {
3560
3923
  });
3561
3924
  this.eventCount++;
3562
3925
  this.trimEvents();
3926
+ this.scheduleStore();
3563
3927
  }
3564
3928
  return sessionId;
3565
3929
  }
@@ -3567,6 +3931,7 @@ var MobileProductAnalytics = class {
3567
3931
  this.items.push({ scope, event });
3568
3932
  this.eventCount++;
3569
3933
  this.trimEvents();
3934
+ this.scheduleStore();
3570
3935
  if (this.eventCount >= PRODUCT_ANALYTICS_MAX_EVENTS_PER_BATCH) {
3571
3936
  this.flush(false);
3572
3937
  }
@@ -3659,6 +4024,7 @@ var MobileProductAnalytics = class {
3659
4024
  this.items.splice(0, count);
3660
4025
  this.eventCount -= batch.events.length;
3661
4026
  this.metricCount -= batch.metrics.length;
4027
+ this.scheduleStore();
3662
4028
  return batch;
3663
4029
  }
3664
4030
  dropTooOld(now) {
@@ -3676,8 +4042,116 @@ var MobileProductAnalytics = class {
3676
4042
  this.metricCount--;
3677
4043
  }
3678
4044
  }
4045
+ if (kept.length !== this.items.length) {
4046
+ this.scheduleStore();
4047
+ }
3679
4048
  this.items = kept;
3680
4049
  }
4050
+ /*
4051
+ * What a previous run left in the device's storage (issue #9577), taken
4052
+ * back before anything new: the items under the sessions and people they
4053
+ * happened under, the batch that was on its way under its own id. What
4054
+ * the server would no longer keep (PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS) is
4055
+ * left out, and the caps apply as to anything held: past them the oldest
4056
+ * events go, counted in the diagnostics' dropped.
4057
+ */
4058
+ restoreQueue(raw, now) {
4059
+ if (!raw) {
4060
+ return;
4061
+ }
4062
+ const queue = readStoredQueue(raw);
4063
+ if (!queue) {
4064
+ this.host.onDiagnostic("analytics-store-unreadable");
4065
+ this.forgetStoredQueue();
4066
+ return;
4067
+ }
4068
+ const oldest = now - PRODUCT_ANALYTICS_MAX_EVENT_AGE_MS;
4069
+ const droppedBefore = this.droppedEvents;
4070
+ let tooOld = 0;
4071
+ const pending = queue.pending;
4072
+ if (pending) {
4073
+ const isLive = [...pending.events, ...pending.metrics].some(
4074
+ (item) => {
4075
+ return item.at >= oldest;
4076
+ }
4077
+ );
4078
+ if (isLive) {
4079
+ this.pending = pending;
4080
+ } else {
4081
+ this.droppedEvents += pending.events.length;
4082
+ tooOld += pending.events.length + pending.metrics.length;
4083
+ }
4084
+ }
4085
+ this.items = queue.items.filter((item) => {
4086
+ if (itemAt(item) >= oldest) {
4087
+ return true;
4088
+ }
4089
+ if (item.event) {
4090
+ this.droppedEvents++;
4091
+ }
4092
+ tooOld++;
4093
+ return false;
4094
+ });
4095
+ this.eventCount = this.items.filter((item) => {
4096
+ return Boolean(item.event);
4097
+ }).length;
4098
+ this.metricCount = this.items.length - this.eventCount;
4099
+ const droppedTooOld = this.droppedEvents - droppedBefore;
4100
+ this.trimEvents();
4101
+ while (this.metricCount > PRODUCT_ANALYTICS_MAX_PENDING_EVENTS) {
4102
+ this.dropOldest("metric");
4103
+ }
4104
+ this.host.onDiagnostic("analytics-restored", {
4105
+ events: this.eventCount + (this.pending?.events.length ?? 0),
4106
+ metrics: this.metricCount + (this.pending?.metrics.length ?? 0),
4107
+ droppedTooOld,
4108
+ droppedOverCap: this.droppedEvents - droppedBefore - droppedTooOld
4109
+ });
4110
+ if (tooOld > 0 || this.items.length < queue.items.length) {
4111
+ this.scheduleStore();
4112
+ }
4113
+ }
4114
+ /* A change to what is held: written once the burst it belongs to is over. */
4115
+ scheduleStore() {
4116
+ if (!this.restored || this.stopReason || this.storeTimer) {
4117
+ return;
4118
+ }
4119
+ this.storeTimer = setTimeout(() => {
4120
+ this.storeTimer = null;
4121
+ this.storeNow();
4122
+ }, PRODUCT_ANALYTICS_STORE_DELAY_MS);
4123
+ }
4124
+ /* What is held, written now, in the order the writes were asked for. */
4125
+ storeNow() {
4126
+ this.cancelStoreTimer();
4127
+ if (!this.restored || this.revoked) {
4128
+ return;
4129
+ }
4130
+ const storage = this.host.storage;
4131
+ const key = productAnalyticsQueueKey(this.host.namespace);
4132
+ const value = buildStoredQueue(this.items, this.pending);
4133
+ void enqueueStoreWrite(storage, key, async () => {
4134
+ if (value === null) {
4135
+ await storage.removeItem(key);
4136
+ } else {
4137
+ await storage.setItem(key, value);
4138
+ }
4139
+ });
4140
+ }
4141
+ forgetStoredQueue() {
4142
+ this.cancelStoreTimer();
4143
+ const storage = this.host.storage;
4144
+ const key = productAnalyticsQueueKey(this.host.namespace);
4145
+ void enqueueStoreWrite(storage, key, async () => {
4146
+ await storage.removeItem(key);
4147
+ });
4148
+ }
4149
+ cancelStoreTimer() {
4150
+ if (this.storeTimer) {
4151
+ clearTimeout(this.storeTimer);
4152
+ this.storeTimer = null;
4153
+ }
4154
+ }
3681
4155
  send(batch) {
3682
4156
  const generation = this.sendGeneration;
3683
4157
  const controller = typeof AbortController === "undefined" ? null : new AbortController();
@@ -3688,7 +4162,7 @@ var MobileProductAnalytics = class {
3688
4162
  ...this.host.headers,
3689
4163
  "Content-Type": PRODUCT_ANALYTICS_CONTENT_TYPE
3690
4164
  },
3691
- body: JSON.stringify(batch)
4165
+ body: JSON.stringify({ ...batch, sentAt: this.host.now() })
3692
4166
  };
3693
4167
  if (controller) {
3694
4168
  init.signal = controller.signal;
@@ -3732,6 +4206,7 @@ var MobileProductAnalytics = class {
3732
4206
  if (status === 202 || status === 200) {
3733
4207
  this.pending = null;
3734
4208
  this.failures = 0;
4209
+ this.scheduleStore();
3735
4210
  if (this.items.length > 0) {
3736
4211
  this.flush(false);
3737
4212
  }
@@ -3739,6 +4214,7 @@ var MobileProductAnalytics = class {
3739
4214
  }
3740
4215
  if (status === 413) {
3741
4216
  this.pending = null;
4217
+ this.scheduleStore();
3742
4218
  return;
3743
4219
  }
3744
4220
  if (status === 204 || status === 400 || status === 403) {
@@ -3788,6 +4264,7 @@ var MobileProductAnalytics = class {
3788
4264
  return;
3789
4265
  }
3790
4266
  this.flush(true);
4267
+ this.storeNow();
3791
4268
  }
3792
4269
  );
3793
4270
  } catch {
@@ -4247,6 +4724,8 @@ function isTouchPrivate(privacyMap, x2, y) {
4247
4724
  // src/MobileReplayRecorder.ts
4248
4725
  var MAX_DIAGNOSTIC_EVENTS = 100;
4249
4726
  var TOUCH_MOVE_SAMPLE_MS = 50;
4727
+ var TAP_SLOP_POINTS = 10;
4728
+ var MAX_TAP_CANDIDATES = 10;
4250
4729
  var MOBILE_POLICY_REFRESH_INTERVAL_MS = 5 * 6e4;
4251
4730
  var MAX_EVENTS_HELD_FOR_RESUME = 500;
4252
4731
  var SAFE_ERROR_NAMES = /* @__PURE__ */ new Set([
@@ -4336,7 +4815,7 @@ var MobileReplayRecorder = class {
4336
4815
  __publicField(this, "now");
4337
4816
  __publicField(this, "serializer", new ViewTreeSerializer());
4338
4817
  __publicField(this, "chunkBuffer", new ReplayChunkBuffer());
4339
- /* The application's own page, event and error signals (issue #6443). */
4818
+ /* The application's own tap, page, event and error signals (#6443, #6517). */
4340
4819
  __publicField(this, "customSignalMatcher", new CustomSignalMatcher());
4341
4820
  __publicField(this, "rollingBuffer", new RollingReplayBuffer());
4342
4821
  __publicField(this, "diagnosticsStatus", "idle");
@@ -4432,6 +4911,11 @@ var MobileReplayRecorder = class {
4432
4911
  __publicField(this, "suppressedTouchPointers", /* @__PURE__ */ new Set());
4433
4912
  __publicField(this, "unidentifiedTouchCount", 0);
4434
4913
  __publicField(this, "unidentifiedTouchPrivate", false);
4914
+ /*
4915
+ * Each touch still down that may yet be a tap, for the application's tap
4916
+ * signals (issue #6517): where it started and on which view.
4917
+ */
4918
+ __publicField(this, "tapCandidates", /* @__PURE__ */ new Map());
4435
4919
  /*
4436
4920
  * When the person last did something: a touch (any touch - one inside a
4437
4921
  * ReplayMask is still someone using the app, even though it is never
@@ -4820,6 +5304,7 @@ var MobileReplayRecorder = class {
4820
5304
  await this.outbox?.clear();
4821
5305
  await this.sessionStore?.clear();
4822
5306
  await this.forgetCachedConfig();
5307
+ await this.forgetStoredProductAnalytics();
4823
5308
  this.identity = null;
4824
5309
  this.userRef = null;
4825
5310
  this.traits = {};
@@ -4893,7 +5378,8 @@ var MobileReplayRecorder = class {
4893
5378
  this.analytics?.track(name, properties);
4894
5379
  });
4895
5380
  const sanitizedProperties = maskStringMapValues(
4896
- sanitizeEventProperties(properties)
5381
+ sanitizeEventProperties(properties),
5382
+ this.readableEventPropertyKeys()
4897
5383
  );
4898
5384
  this.runExternalActivity(this.now(), () => {
4899
5385
  this.appendCustom(
@@ -5080,8 +5566,16 @@ var MobileReplayRecorder = class {
5080
5566
  if (!this.running || !this.acceptingEvents || !this.foreground || !this.isCurrentGeneration(generation)) {
5081
5567
  return;
5082
5568
  }
5083
- if (this.updateTouchSuppression(touch, pointIsPrivate)) {
5569
+ const suppressed = this.updateTouchSuppression(
5570
+ touch,
5571
+ pointIsPrivate
5572
+ );
5573
+ const tap = this.followTap(touch);
5574
+ if (suppressed) {
5084
5575
  this.diagnostic("touch-suppressed-private-region");
5576
+ if (tap) {
5577
+ await this.recordTapSignals(tap, touch.timestamp, generation, false);
5578
+ }
5085
5579
  return;
5086
5580
  }
5087
5581
  if (touch.phase === "move" && touch.timestamp - this.lastTouchMoveAtUnixMs < TOUCH_MOVE_SAMPLE_MS) {
@@ -5107,6 +5601,90 @@ var MobileReplayRecorder = class {
5107
5601
  y: touch.y
5108
5602
  });
5109
5603
  }
5604
+ if (tap) {
5605
+ await this.recordTapSignals(tap, touch.timestamp, generation, true);
5606
+ }
5607
+ }
5608
+ /* The application's signals that fire on a tap. */
5609
+ tapSignals() {
5610
+ return this.customSignals().filter(
5611
+ (signal) => {
5612
+ return signal.trigger === "tap";
5613
+ }
5614
+ );
5615
+ }
5616
+ /*
5617
+ * Follows each touch for the application's tap signals (issue #6517): a
5618
+ * touch that ends within TAP_SLOP_POINTS of where it started is a tap on
5619
+ * the view it started on, and is returned on its end. A touch that slid
5620
+ * further was a scroll or a drag. Nothing is followed while the
5621
+ * application has no tap signal, so a touch costs what it always did.
5622
+ */
5623
+ followTap(touch) {
5624
+ const key = touch.pointerId === void 0 ? "unidentified" : `${typeof touch.pointerId}:${String(touch.pointerId)}`;
5625
+ if (touch.phase === "start") {
5626
+ if (this.tapSignals().length === 0 || this.tapCandidates.size >= MAX_TAP_CANDIDATES && !this.tapCandidates.has(key)) {
5627
+ return null;
5628
+ }
5629
+ this.tapCandidates.set(key, {
5630
+ x: touch.x,
5631
+ y: touch.y,
5632
+ targetTag: touch.targetTag
5633
+ });
5634
+ return null;
5635
+ }
5636
+ const started = this.tapCandidates.get(key);
5637
+ if (!started) {
5638
+ return null;
5639
+ }
5640
+ const slid = Math.hypot(touch.x - started.x, touch.y - started.y) > TAP_SLOP_POINTS;
5641
+ if (touch.phase === "move") {
5642
+ if (slid) {
5643
+ this.tapCandidates.delete(key);
5644
+ }
5645
+ return null;
5646
+ }
5647
+ this.tapCandidates.delete(key);
5648
+ return slid || started.targetTag === void 0 ? null : { targetTag: started.targetTag, x: touch.x, y: touch.y };
5649
+ }
5650
+ /*
5651
+ * A tap's signals: the touched view's testID, and those of the views
5652
+ * around it out to the replay root, matched here on the device - never
5653
+ * recorded or sent. A hit carries the signal's name, where the tap was
5654
+ * when the touch itself is recorded (withPosition), and like a page or
5655
+ * an event signal it starts an "On error or frustration" upload when it
5656
+ * counts as frustration.
5657
+ */
5658
+ async recordTapSignals(tap, atUnixMs, generation, withPosition) {
5659
+ const signals = this.tapSignals();
5660
+ if (signals.length === 0 || !this.rootTag || typeof this.nativeViewTree.touchTargetTestIds !== "function") {
5661
+ return;
5662
+ }
5663
+ let testIds = [];
5664
+ try {
5665
+ testIds = readTapTargetTestIds(
5666
+ await this.nativeViewTree.touchTargetTestIds(
5667
+ tap.targetTag,
5668
+ this.rootTag
5669
+ )
5670
+ );
5671
+ } catch {
5672
+ this.diagnostic("tap-target-unreadable");
5673
+ return;
5674
+ }
5675
+ if (!this.running || !this.acceptingEvents || !this.isCurrentGeneration(generation)) {
5676
+ return;
5677
+ }
5678
+ const hits = this.customSignalMatcher.matchTap(signals, testIds, atUnixMs);
5679
+ if (withPosition) {
5680
+ for (const hit of hits) {
5681
+ hit.x = tap.x;
5682
+ hit.y = tap.y;
5683
+ }
5684
+ }
5685
+ if (this.recordCustomSignals(hits)) {
5686
+ await this.trigger("frustration" /* Frustration */);
5687
+ }
5110
5688
  }
5111
5689
  setRootTag(rootTag) {
5112
5690
  this.rootTag = typeof rootTag === "number" && Number.isSafeInteger(rootTag) && rootTag > 0 ? rootTag : null;
@@ -5443,10 +6021,17 @@ var MobileReplayRecorder = class {
5443
6021
  }
5444
6022
  }
5445
6023
  }
5446
- /* The page, event and error signals the application's policy defines. */
6024
+ /* The tap, page, event and error signals the application's policy defines. */
5447
6025
  customSignals() {
5448
6026
  return this.config?.frustrationSignals.customSignals ?? [];
5449
6027
  }
6028
+ /*
6029
+ * The application's readable event properties (issue #7501): none until
6030
+ * the policy is read, so a track() before it is masked whole.
6031
+ */
6032
+ readableEventPropertyKeys() {
6033
+ return this.config?.readableEventPropertyKeys ?? [];
6034
+ }
5450
6035
  /*
5451
6036
  * Marks each hit in the stream and counts it on the chunk, as the browser
5452
6037
  * recorder does. Returns whether one of them counts as frustration, which
@@ -5473,6 +6058,10 @@ var MobileReplayRecorder = class {
5473
6058
  isFrustration: hit.isFrustration,
5474
6059
  atUnixMs: hit.atUnixMs
5475
6060
  };
6061
+ if (typeof hit.x === "number" && Number.isFinite(hit.x) && typeof hit.y === "number" && Number.isFinite(hit.y)) {
6062
+ payload.x = hit.x;
6063
+ payload.y = hit.y;
6064
+ }
5476
6065
  this.appendEvent(
5477
6066
  createCustomEvent(
5478
6067
  CUSTOM_SIGNAL_CUSTOM_EVENT_TAG,
@@ -5993,6 +6582,20 @@ var MobileReplayRecorder = class {
5993
6582
  );
5994
6583
  }
5995
6584
  }
6585
+ /*
6586
+ * The product analytics events and metric points the device kept unsent
6587
+ * (issue #9577) go with consent too, as the outbox's chunks do - a
6588
+ * channel running now drops its own (forget(), reset()), and this
6589
+ * removes them whether one runs or not, a previous launch's included.
6590
+ */
6591
+ async forgetStoredProductAnalytics() {
6592
+ if (this.options) {
6593
+ await clearStoredProductAnalytics(
6594
+ this.storage,
6595
+ getReplayStorageNamespace(this.options)
6596
+ );
6597
+ }
6598
+ }
5996
6599
  mayPersistUnder(config) {
5997
6600
  return !config.enabled || config.consentMode === "NotRequired" /* NotRequired */ || this.consentGranted;
5998
6601
  }
@@ -6109,6 +6712,7 @@ var MobileReplayRecorder = class {
6109
6712
  this.suppressedTouchPointers.clear();
6110
6713
  this.unidentifiedTouchCount = 0;
6111
6714
  this.unidentifiedTouchPrivate = false;
6715
+ this.tapCandidates.clear();
6112
6716
  }
6113
6717
  async applyIdentityChange(ref, traits, identityEpoch) {
6114
6718
  if (identityEpoch !== this.identityCancellationEpoch) {
@@ -6369,6 +6973,7 @@ var MobileReplayRecorder = class {
6369
6973
  await this.outbox?.clear();
6370
6974
  await this.sessionStore?.clear();
6371
6975
  await this.forgetCachedConfig();
6976
+ await this.forgetStoredProductAnalytics();
6372
6977
  if (!this.running || !this.isCurrentGeneration(generation)) {
6373
6978
  return false;
6374
6979
  }
@@ -6848,7 +7453,10 @@ var MobileReplayRecorder = class {
6848
7453
  return this.analyticsIdentity();
6849
7454
  },
6850
7455
  toProperties: (value) => {
6851
- return maskStringMapValues(sanitizeEventProperties(value));
7456
+ return maskStringMapValues(
7457
+ sanitizeEventProperties(value),
7458
+ this.readableEventPropertyKeys()
7459
+ );
6852
7460
  },
6853
7461
  getContext: () => {
6854
7462
  return this.analyticsContext();