@microsurveysai/react-native 0.1.2 → 0.1.4

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
@@ -228,11 +228,21 @@ function parseConfig(rawText) {
228
228
  if (!projectId) return null;
229
229
  const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
230
230
  const theme = root.theme && typeof root.theme === "object" && !Array.isArray(root.theme) ? root.theme : null;
231
- return { projectId, fetchedAt: strOrUndef(root.fetchedAt) ?? null, theme, surveys };
231
+ return {
232
+ projectId,
233
+ fetchedAt: strOrUndef(root.fetchedAt) ?? null,
234
+ theme,
235
+ surveys,
236
+ eventSignals: root.eventSignals === true,
237
+ debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h) => typeof h === "string") : [],
238
+ pendingEvents: root.pendingEvents === true,
239
+ serverEvents: Array.isArray(root.serverEvents) ? root.serverEvents.filter((n) => typeof n === "string") : []
240
+ };
232
241
  }
233
242
 
234
243
  // src/core/apiClient.ts
235
244
  var API_VERSION = "2026-06-30";
245
+ var PENDING_PAGE_SIZE = 50;
236
246
  var ApiClient = class {
237
247
  constructor(apiKey, baseURL, storage) {
238
248
  __publicField(this, "apiKey");
@@ -258,6 +268,36 @@ var ApiClient = class {
258
268
  const rawText = await res.text();
259
269
  return { kind: "config", rawText, config: parseConfig(rawText), etag: res.headers.get("ETag") };
260
270
  }
271
+ // ── Server events mailbox ───────────────────────────────────────────────────
272
+ /** `POST /api/sdk/pending`: the server events waiting for this user, oldest
273
+ * first. Each is handed out once, so this is not queued in the outbox. Resolves
274
+ * `[]` without a request when there's no id to ask for. Throws on network/HTTP
275
+ * errors; malformed entries are dropped. */
276
+ async fetchPending(ids) {
277
+ const body = {};
278
+ if (ids.userId) body.userId = ids.userId;
279
+ if (ids.deviceId) body.deviceId = ids.deviceId;
280
+ if (Object.keys(body).length === 0) return [];
281
+ const res = await fetch(this.endpoint("/api/sdk/pending"), {
282
+ method: "POST",
283
+ headers: {
284
+ Authorization: `Bearer ${this.apiKey}`,
285
+ "MS-Api-Version": API_VERSION,
286
+ "Content-Type": "application/json; charset=utf-8"
287
+ },
288
+ body: JSON.stringify(body)
289
+ });
290
+ if (!res.ok) throw new Error(`pending fetch failed: ${res.status}`);
291
+ const root = await res.json();
292
+ const events = Array.isArray(root?.events) ? root.events : [];
293
+ return events.flatMap((raw) => {
294
+ const e = raw;
295
+ if (!e || typeof e.id !== "string" || typeof e.name !== "string" || typeof e.occurredAt !== "string") return [];
296
+ if (Number.isNaN(Date.parse(e.occurredAt))) return [];
297
+ const properties = e.properties && typeof e.properties === "object" && !Array.isArray(e.properties) ? e.properties : {};
298
+ return [{ id: e.id, name: e.name, properties, occurredAt: e.occurredAt }];
299
+ });
300
+ }
261
301
  // ── Impressions / responses ─────────────────────────────────────────────────
262
302
  /** Queues the impression and returns its `clientId`, so the response from the
263
303
  * same showing can point back to it. */
@@ -290,25 +330,47 @@ var ApiClient = class {
290
330
  };
291
331
  this.enqueue("/api/sdk/responses", { responses: [payload] });
292
332
  }
333
+ // ── Event signals ─────────────────────────────────────────────────────────
334
+ /** Queues one upload window of event counts. No clientId: a re-sent batch
335
+ * can count twice, which is fine for "last seen" and trend lines. */
336
+ recordEventCounts(events, context) {
337
+ if (events.length === 0) return;
338
+ this.enqueue("/api/sdk/events", { events, context });
339
+ }
340
+ // ── Live debugger ─────────────────────────────────────────────────────────
341
+ /** Sends one debugger entry from a test device. */
342
+ recordDebug(entry, endUserId, context) {
343
+ this.enqueue("/api/sdk/debug", { entries: [entry], endUserId, context });
344
+ }
293
345
  enqueue(path, value) {
294
346
  this.outbox.enqueue(path, JSON.stringify(value));
295
347
  void this.flush();
296
348
  }
297
349
  // ── Flush ────────────────────────────────────────────────────────────────────
298
350
  /** POSTs queued entries in order. Stops at the first retryable failure (likely
299
- * offline) and leaves the rest for next time. Idempotency keys make re-sends
300
- * safe. Never throws. */
351
+ * offline) and leaves the rest for next time. Entries queued while a flush is
352
+ * running are sent by the same flush, so nothing waits for the next event.
353
+ * Idempotency keys make re-sends safe. Never throws. */
301
354
  async flush() {
302
355
  if (this.isFlushing) return;
303
356
  this.isFlushing = true;
304
357
  try {
305
- for (const entry of this.outbox.snapshot()) {
306
- try {
307
- await this.post(entry.path, entry.body);
308
- this.outbox.remove(entry.id);
309
- } catch {
310
- break;
358
+ const sent = /* @__PURE__ */ new Set();
359
+ for (; ; ) {
360
+ const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
361
+ if (pending.length === 0) break;
362
+ let failed = false;
363
+ for (const entry of pending) {
364
+ try {
365
+ await this.post(entry.path, entry.body);
366
+ this.outbox.remove(entry.id);
367
+ sent.add(entry.id);
368
+ } catch {
369
+ failed = true;
370
+ break;
371
+ }
311
372
  }
373
+ if (failed) break;
312
374
  }
313
375
  } finally {
314
376
  this.isFlushing = false;
@@ -362,6 +424,21 @@ var ConfigStore = class {
362
424
  get theme() {
363
425
  return this.parsed?.theme ?? null;
364
426
  }
427
+ get eventSignals() {
428
+ return this.parsed?.eventSignals ?? false;
429
+ }
430
+ get projectId() {
431
+ return this.parsed?.projectId ?? null;
432
+ }
433
+ get debugUsers() {
434
+ return this.parsed?.debugUsers ?? [];
435
+ }
436
+ get pendingEvents() {
437
+ return this.parsed?.pendingEvents ?? false;
438
+ }
439
+ get serverEvents() {
440
+ return this.parsed?.serverEvents ?? [];
441
+ }
365
442
  get etag() {
366
443
  return this.persisted?.etag ?? null;
367
444
  }
@@ -569,6 +646,9 @@ function advance(trigger, record, eventName, properties, nowT) {
569
646
  satisfied = matchesStep(0);
570
647
  } else {
571
648
  const expected = Math.min(next.stepIndex, steps.length - 1);
649
+ if (expected !== 0 && next.startedAt !== null && nowT < next.startedAt) {
650
+ return { record: next, satisfied: false };
651
+ }
572
652
  if (matchesStep(expected)) {
573
653
  if (expected === 0) {
574
654
  next.startedAt = nowT;
@@ -612,6 +692,7 @@ var TriggerEngine = class {
612
692
  __publicField(this, "onPresent");
613
693
  __publicField(this, "platform");
614
694
  __publicField(this, "now");
695
+ __publicField(this, "onDecision");
615
696
  __publicField(this, "timers", /* @__PURE__ */ new Set());
616
697
  this.store = opts.store;
617
698
  this.surveysProvider = opts.surveysProvider;
@@ -619,26 +700,65 @@ var TriggerEngine = class {
619
700
  this.onPresent = opts.onPresent;
620
701
  this.platform = opts.platform;
621
702
  this.now = opts.now ?? (() => Date.now() / 1e3);
703
+ this.onDecision = opts.onDecision ?? (() => {
704
+ });
622
705
  }
623
- /** Feed an event into the engine. */
624
- process(name, properties = {}) {
706
+ /** Feed an event into the engine. `eventT` (unix seconds) is when it happened,
707
+ * for a replayed server event; it drives sequence progress and
708
+ * `sequenceWindowSeconds`. The survey window, caps and delay always use now. */
709
+ process(name, properties = {}, eventT) {
625
710
  const identity = this.identityProvider();
626
711
  const endUserId = endUserIdOf(identity);
627
712
  const state = this.store.load(endUserId);
628
713
  const nowT = this.now();
714
+ const atT = eventT ?? nowT;
629
715
  for (const survey of this.surveysProvider()) {
630
716
  const triggers = survey.triggers;
631
717
  if (!triggers || triggers.length === 0) continue;
632
- if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
718
+ const names = (t) => t.steps.some((st) => st.event === name);
719
+ if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {
720
+ const t = triggers.find(names);
721
+ if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: "platform" });
722
+ continue;
723
+ }
633
724
  for (const trigger of triggers) {
634
- const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
635
- if (!satisfied) continue;
725
+ const satisfied = this.advanceTrigger(trigger, state, name, properties, atT);
726
+ const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
727
+ if (!satisfied) {
728
+ if (names(trigger)) {
729
+ const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));
730
+ skip(matchedStep ? "sequence_in_progress" : "property_mismatch");
731
+ }
732
+ continue;
733
+ }
636
734
  const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;
637
- if (!this.isWithinWindow(survey, nowT)) continue;
638
- if (!passesFrequency(trigger, occurrence)) continue;
639
- if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;
640
- if (!this.passesSampling(survey, endUserId, state)) continue;
641
- if (!passesCap(survey, state, nowT)) continue;
735
+ const window = this.windowState(survey, nowT);
736
+ if (window !== "open") {
737
+ skip(window);
738
+ continue;
739
+ }
740
+ if (!passesFrequency(trigger, occurrence)) {
741
+ skip("frequency");
742
+ continue;
743
+ }
744
+ if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {
745
+ skip("audience");
746
+ continue;
747
+ }
748
+ if (!this.passesSampling(survey, endUserId, state)) {
749
+ skip("sampled_out");
750
+ continue;
751
+ }
752
+ if (!passesCap(survey, state, nowT)) {
753
+ skip("cap");
754
+ continue;
755
+ }
756
+ this.onDecision({
757
+ surveyId: survey.id,
758
+ triggerId: trigger.id,
759
+ reason: "eligible",
760
+ delaySeconds: Math.max(0, trigger.delaySeconds)
761
+ });
642
762
  this.scheduleShow(survey, trigger, identity);
643
763
  }
644
764
  }
@@ -657,16 +777,16 @@ var TriggerEngine = class {
657
777
  return satisfied;
658
778
  }
659
779
  // ── Eligibility checks ─────────────────────────────────────────────────────
660
- isWithinWindow(survey, nowT) {
780
+ windowState(survey, nowT) {
661
781
  if (survey.startsAt) {
662
782
  const start = Date.parse(survey.startsAt);
663
- if (!Number.isNaN(start) && nowT < start / 1e3) return false;
783
+ if (!Number.isNaN(start) && nowT < start / 1e3) return "not_started";
664
784
  }
665
785
  if (survey.endsAt) {
666
786
  const end = Date.parse(survey.endsAt);
667
- if (!Number.isNaN(end) && nowT > end / 1e3) return false;
787
+ if (!Number.isNaN(end) && nowT > end / 1e3) return "ended";
668
788
  }
669
- return true;
789
+ return "open";
670
790
  }
671
791
  passesSampling(survey, endUserId, state) {
672
792
  const existing = state.surveys[survey.id]?.sampleDecision;
@@ -685,7 +805,10 @@ var TriggerEngine = class {
685
805
  const endUserId = endUserIdOf(identity);
686
806
  const state = this.store.load(endUserId);
687
807
  const nowT = this.now();
688
- if (!passesCap(survey, state, nowT)) return;
808
+ if (!passesCap(survey, state, nowT)) {
809
+ this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "cap" });
810
+ return;
811
+ }
689
812
  const record = state.surveys[survey.id] ?? {};
690
813
  record.lastShownAt = nowT;
691
814
  state.surveys[survey.id] = record;
@@ -708,9 +831,75 @@ function passesCap(survey, state, nowT) {
708
831
  return elapsed >= days * 86400;
709
832
  }
710
833
 
834
+ // src/core/eventCounter.ts
835
+ var MAX_NAMES = 200;
836
+ var MAX_KEYS = 20;
837
+ var MAX_NAME_LENGTH = 200;
838
+ var MAX_KEY_LENGTH = 100;
839
+ var EventCounter = class {
840
+ constructor() {
841
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
842
+ }
843
+ get size() {
844
+ return this.entries.size;
845
+ }
846
+ record(name, properties = {}, now = Date.now()) {
847
+ if (!name || name.length > MAX_NAME_LENGTH) return;
848
+ let e = this.entries.get(name);
849
+ if (!e) {
850
+ if (this.entries.size >= MAX_NAMES) return;
851
+ e = { count: 0, first: now, last: now, keys: /* @__PURE__ */ new Set() };
852
+ this.entries.set(name, e);
853
+ }
854
+ e.count += 1;
855
+ e.last = Math.max(e.last, now);
856
+ for (const key of Object.keys(properties)) {
857
+ if (e.keys.size >= MAX_KEYS) break;
858
+ if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);
859
+ }
860
+ }
861
+ /** Everything counted since the last drain, and a fresh window. */
862
+ drain() {
863
+ const out = [...this.entries].map(([name, e]) => ({
864
+ name,
865
+ count: e.count,
866
+ firstSeenAt: new Date(e.first).toISOString(),
867
+ lastSeenAt: new Date(e.last).toISOString(),
868
+ propertyKeys: [...e.keys]
869
+ }));
870
+ this.entries = /* @__PURE__ */ new Map();
871
+ return out;
872
+ }
873
+ };
874
+
875
+ // src/core/debug.ts
876
+ function debugKey(projectId, endUserId) {
877
+ return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, "0");
878
+ }
879
+ var MAX_PROPS = 30;
880
+ var MAX_STRING = 200;
881
+ function debugProperties(properties) {
882
+ const out = {};
883
+ for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {
884
+ if (typeof v === "string") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}\u2026` : v;
885
+ else if (typeof v === "number" || typeof v === "boolean" || v === null) out[k] = v;
886
+ else if (Array.isArray(v)) out[k] = `[${v.length} items]`;
887
+ else if (typeof v === "object") out[k] = "{\u2026}";
888
+ }
889
+ return out;
890
+ }
891
+
892
+ // src/core/version.ts
893
+ var SDK_VERSION = "0.1.4";
894
+
711
895
  // src/core/client.ts
712
896
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
713
897
  var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
898
+ var EVENT_COUNTS_INTERVAL_MS = 60 * 1e3;
899
+ var PENDING_FOLLOW_UPS_MS = [30 * 1e3, 90 * 1e3];
900
+ var PENDING_INTERVAL_MS = 5 * 60 * 1e3;
901
+ var PENDING_WAITING_INTERVAL_MS = 60 * 1e3;
902
+ var PENDING_WAITING_MAX_SECONDS = 3 * 60 * 60;
714
903
  var MicroSurveysClient = class {
715
904
  constructor(opts) {
716
905
  __publicField(this, "api");
@@ -724,6 +913,16 @@ var MicroSurveysClient = class {
724
913
  __publicField(this, "osVersion");
725
914
  __publicField(this, "appVersion");
726
915
  __publicField(this, "subscribeForeground");
916
+ __publicField(this, "subscribeBackground");
917
+ __publicField(this, "eventCounter", new EventCounter());
918
+ __publicField(this, "eventCountsTimer", null);
919
+ /** Decisions collected while one event is processed, for the live debugger. */
920
+ __publicField(this, "collecting", null);
921
+ __publicField(this, "unsubscribeBackground", null);
922
+ /** Mailbox timers, cleared on background and stop. */
923
+ __publicField(this, "pendingTimers", []);
924
+ __publicField(this, "pendingIntervals", []);
925
+ __publicField(this, "pendingInFlight", false);
727
926
  __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
728
927
  __publicField(this, "configListeners", /* @__PURE__ */ new Set());
729
928
  __publicField(this, "active", null);
@@ -740,32 +939,48 @@ var MicroSurveysClient = class {
740
939
  this.osVersion = opts.osVersion;
741
940
  this.appVersion = opts.appVersion;
742
941
  this.subscribeForeground = opts.subscribeForeground;
942
+ this.subscribeBackground = opts.subscribeBackground;
743
943
  this.engine = new TriggerEngine({
744
944
  store: this.triggerStateStore,
745
945
  surveysProvider: () => this.configStore.surveys,
746
946
  identityProvider: () => this.identityStore.snapshot(),
747
947
  onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
748
- platform: opts.platform
948
+ platform: opts.platform,
949
+ onDecision: (d) => this.handleDecision(d)
749
950
  });
750
951
  }
751
952
  // ── Lifecycle ────────────────────────────────────────────────────────────────
752
- /** Flush any queued ingest, refresh config, and (optionally) wire the
753
- * foreground refresh. Safe to call once early. */
953
+ /** Flush any queued ingest, refresh config, wire the foreground refresh
954
+ * (optional) and the server events mailbox checks. Safe to call once early. */
754
955
  start() {
755
956
  if (this.started) return;
756
957
  this.started = true;
757
958
  void this.api.flush();
758
- void this.refreshConfig();
759
- if (this.refreshOnForeground) {
760
- this.unsubscribeForeground = this.subscribeForeground(() => {
959
+ void this.refreshConfig().then(() => {
960
+ if (this.started) this.startPendingChecks();
961
+ });
962
+ this.unsubscribeForeground = this.subscribeForeground(() => {
963
+ if (this.refreshOnForeground) {
761
964
  void this.api.flush();
762
965
  this.refreshConfigIfStale();
763
- });
764
- }
966
+ }
967
+ this.startPendingChecks();
968
+ });
969
+ this.unsubscribeBackground = this.subscribeBackground?.(() => {
970
+ this.flushEventCounts();
971
+ this.stopPendingChecks();
972
+ }) ?? null;
973
+ this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
765
974
  }
766
975
  /** Tear down listeners + pending timers. */
767
976
  stop() {
768
977
  this.engine.stop();
978
+ this.flushEventCounts();
979
+ if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
980
+ this.eventCountsTimer = null;
981
+ this.stopPendingChecks();
982
+ this.unsubscribeBackground?.();
983
+ this.unsubscribeBackground = null;
769
984
  this.unsubscribeForeground?.();
770
985
  this.unsubscribeForeground = null;
771
986
  this.started = false;
@@ -792,7 +1007,126 @@ var MicroSurveysClient = class {
792
1007
  this.identityStore.setUser(userId, properties);
793
1008
  }
794
1009
  track(name, properties = {}) {
795
- this.engine.process(name, properties);
1010
+ if (this.configStore.eventSignals) {
1011
+ this.eventCounter.record(name, properties);
1012
+ if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
1013
+ }
1014
+ this.processEvent(name, properties);
1015
+ }
1016
+ /** Runs one event through the engine, reporting to the live debugger on test
1017
+ * devices. `occurredAt` (ms epoch) is set for a replayed server event. */
1018
+ processEvent(name, properties, occurredAt) {
1019
+ const eventT = occurredAt === void 0 ? void 0 : occurredAt / 1e3;
1020
+ if (!this.isDebugDevice()) {
1021
+ this.engine.process(name, properties, eventT);
1022
+ return;
1023
+ }
1024
+ this.collecting = [];
1025
+ try {
1026
+ this.engine.process(name, properties, eventT);
1027
+ } finally {
1028
+ const decisions = this.collecting;
1029
+ this.collecting = null;
1030
+ this.sendDebug(name, debugProperties(properties), decisions, occurredAt);
1031
+ }
1032
+ }
1033
+ // ── Server events mailbox ────────────────────────────────────────────────────
1034
+ /** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while
1035
+ * a sequence waits on a server event. Restarts the schedule; no-op unless the
1036
+ * config has `pendingEvents`. */
1037
+ startPendingChecks() {
1038
+ this.stopPendingChecks();
1039
+ if (!this.configStore.pendingEvents) return;
1040
+ void this.checkPending();
1041
+ for (const ms of PENDING_FOLLOW_UPS_MS) {
1042
+ this.pendingTimers.push(setTimeout(() => void this.checkPending(), ms));
1043
+ }
1044
+ this.pendingIntervals.push(
1045
+ setInterval(() => void this.checkPending(), PENDING_INTERVAL_MS),
1046
+ setInterval(() => {
1047
+ if (this.isWaitingOnServerEvent()) void this.checkPending();
1048
+ }, PENDING_WAITING_INTERVAL_MS)
1049
+ );
1050
+ }
1051
+ stopPendingChecks() {
1052
+ for (const t of this.pendingTimers) clearTimeout(t);
1053
+ for (const t of this.pendingIntervals) clearInterval(t);
1054
+ this.pendingTimers = [];
1055
+ this.pendingIntervals = [];
1056
+ }
1057
+ /** Fetches and replays this user's waiting server events. One request at a
1058
+ * time; a full page is followed by one more call. Failures are silent: the
1059
+ * next scheduled check retries. */
1060
+ async checkPending() {
1061
+ if (this.pendingInFlight || !this.configStore.pendingEvents) return;
1062
+ const identity = this.identityStore.snapshot();
1063
+ const userId = identity.amplitudeUserId ?? identity.hostUserId ?? null;
1064
+ const deviceId = identity.amplitudeDeviceId ?? null;
1065
+ if (!userId && !deviceId) return;
1066
+ this.pendingInFlight = true;
1067
+ try {
1068
+ for (let call = 0; call < 2; call++) {
1069
+ const events = await this.api.fetchPending({ userId, deviceId });
1070
+ this.replayPending(events);
1071
+ if (events.length < PENDING_PAGE_SIZE) break;
1072
+ }
1073
+ } catch {
1074
+ } finally {
1075
+ this.pendingInFlight = false;
1076
+ }
1077
+ }
1078
+ /** Replays server events like `track`, oldest first, at the time each one
1079
+ * happened. Not counted in event signals: the app didn't send them. */
1080
+ replayPending(events) {
1081
+ const timed = events.map((e) => ({ e, at: Date.parse(e.occurredAt) }));
1082
+ timed.sort((a, b) => a.at - b.at);
1083
+ for (const { e, at } of timed) this.processEvent(e.name, e.properties, at);
1084
+ }
1085
+ /** True while a SEQUENCE trigger for the current user has started and its next
1086
+ * step's event arrives by server stream, up to 3 hours after it started. */
1087
+ isWaitingOnServerEvent() {
1088
+ const serverEvents = this.configStore.serverEvents;
1089
+ if (serverEvents.length === 0) return false;
1090
+ const state = this.triggerStateStore.load(endUserIdOf(this.identityStore.snapshot()));
1091
+ const nowT = Date.now() / 1e3;
1092
+ for (const survey of this.configStore.surveys) {
1093
+ for (const trigger of survey.triggers ?? []) {
1094
+ if (trigger.type !== "SEQUENCE") continue;
1095
+ const record = state.triggers[trigger.id];
1096
+ if (!record || record.stepIndex <= 0 || record.startedAt === null) continue;
1097
+ if (nowT - record.startedAt > PENDING_WAITING_MAX_SECONDS) continue;
1098
+ const steps = [...trigger.steps].sort((a, b) => a.order - b.order);
1099
+ const next = steps[Math.min(record.stepIndex, steps.length - 1)];
1100
+ if (next && serverEvents.includes(next.event)) return true;
1101
+ }
1102
+ }
1103
+ return false;
1104
+ }
1105
+ // ── Live debugger ────────────────────────────────────────────────────────────
1106
+ /** True when the dashboard picked the current user as a test device. */
1107
+ isDebugDevice() {
1108
+ const users = this.configStore.debugUsers;
1109
+ const projectId = this.configStore.projectId;
1110
+ if (users.length === 0 || !projectId) return false;
1111
+ return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));
1112
+ }
1113
+ handleDecision(d) {
1114
+ if (this.collecting) this.collecting.push(d);
1115
+ else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
1116
+ }
1117
+ /** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */
1118
+ sendDebug(event, properties, decisions, at) {
1119
+ const endUserId = endUserIdOf(this.identityStore.snapshot());
1120
+ this.api.recordDebug(
1121
+ { at: new Date(at ?? Date.now()).toISOString(), event, properties, decisions },
1122
+ endUserId,
1123
+ { ...this.deviceContext(), sdkVersion: SDK_VERSION }
1124
+ );
1125
+ }
1126
+ /** Uploads the events counted since the last upload (no-op when there are none). */
1127
+ flushEventCounts() {
1128
+ if (this.eventCounter.size === 0) return;
1129
+ this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });
796
1130
  }
797
1131
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
798
1132
  * Its user/device id take precedence over `identify()` for `endUserId`. */
@@ -821,7 +1155,11 @@ var MicroSurveysClient = class {
821
1155
  return () => this.presentListeners.delete(cb);
822
1156
  }
823
1157
  handlePresent(survey, trigger, identity) {
824
- if (this.active && !this.active.closed) return;
1158
+ if (this.active && !this.active.closed) {
1159
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "another_survey_showing" });
1160
+ return;
1161
+ }
1162
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "shown" });
825
1163
  const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
826
1164
  this.active = p;
827
1165
  const active = this.toActiveSurvey(p);
@@ -962,6 +1300,12 @@ function appStateForeground(onForeground) {
962
1300
  });
963
1301
  return () => sub.remove();
964
1302
  }
1303
+ function appStateBackground(onBackground) {
1304
+ const sub = import_react_native.AppState.addEventListener("change", (state) => {
1305
+ if (state === "background") onBackground();
1306
+ });
1307
+ return () => sub.remove();
1308
+ }
965
1309
  var MicroSurveys = class {
966
1310
  constructor(opts) {
967
1311
  __publicField(this, "apiKey");
@@ -982,7 +1326,8 @@ var MicroSurveys = class {
982
1326
  osVersion: String(import_react_native.Platform.Version),
983
1327
  appVersion: opts.appVersion,
984
1328
  storage: kv,
985
- subscribeForeground: appStateForeground
1329
+ subscribeForeground: appStateForeground,
1330
+ subscribeBackground: appStateBackground
986
1331
  });
987
1332
  this.client = client;
988
1333
  const queued = this.pending;