@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.js CHANGED
@@ -187,11 +187,21 @@ function parseConfig(rawText) {
187
187
  if (!projectId) return null;
188
188
  const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
189
189
  const theme = root.theme && typeof root.theme === "object" && !Array.isArray(root.theme) ? root.theme : null;
190
- return { projectId, fetchedAt: strOrUndef(root.fetchedAt) ?? null, theme, surveys };
190
+ return {
191
+ projectId,
192
+ fetchedAt: strOrUndef(root.fetchedAt) ?? null,
193
+ theme,
194
+ surveys,
195
+ eventSignals: root.eventSignals === true,
196
+ debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h) => typeof h === "string") : [],
197
+ pendingEvents: root.pendingEvents === true,
198
+ serverEvents: Array.isArray(root.serverEvents) ? root.serverEvents.filter((n) => typeof n === "string") : []
199
+ };
191
200
  }
192
201
 
193
202
  // src/core/apiClient.ts
194
203
  var API_VERSION = "2026-06-30";
204
+ var PENDING_PAGE_SIZE = 50;
195
205
  var ApiClient = class {
196
206
  constructor(apiKey, baseURL, storage) {
197
207
  __publicField(this, "apiKey");
@@ -217,6 +227,36 @@ var ApiClient = class {
217
227
  const rawText = await res.text();
218
228
  return { kind: "config", rawText, config: parseConfig(rawText), etag: res.headers.get("ETag") };
219
229
  }
230
+ // ── Server events mailbox ───────────────────────────────────────────────────
231
+ /** `POST /api/sdk/pending`: the server events waiting for this user, oldest
232
+ * first. Each is handed out once, so this is not queued in the outbox. Resolves
233
+ * `[]` without a request when there's no id to ask for. Throws on network/HTTP
234
+ * errors; malformed entries are dropped. */
235
+ async fetchPending(ids) {
236
+ const body = {};
237
+ if (ids.userId) body.userId = ids.userId;
238
+ if (ids.deviceId) body.deviceId = ids.deviceId;
239
+ if (Object.keys(body).length === 0) return [];
240
+ const res = await fetch(this.endpoint("/api/sdk/pending"), {
241
+ method: "POST",
242
+ headers: {
243
+ Authorization: `Bearer ${this.apiKey}`,
244
+ "MS-Api-Version": API_VERSION,
245
+ "Content-Type": "application/json; charset=utf-8"
246
+ },
247
+ body: JSON.stringify(body)
248
+ });
249
+ if (!res.ok) throw new Error(`pending fetch failed: ${res.status}`);
250
+ const root = await res.json();
251
+ const events = Array.isArray(root?.events) ? root.events : [];
252
+ return events.flatMap((raw) => {
253
+ const e = raw;
254
+ if (!e || typeof e.id !== "string" || typeof e.name !== "string" || typeof e.occurredAt !== "string") return [];
255
+ if (Number.isNaN(Date.parse(e.occurredAt))) return [];
256
+ const properties = e.properties && typeof e.properties === "object" && !Array.isArray(e.properties) ? e.properties : {};
257
+ return [{ id: e.id, name: e.name, properties, occurredAt: e.occurredAt }];
258
+ });
259
+ }
220
260
  // ── Impressions / responses ─────────────────────────────────────────────────
221
261
  /** Queues the impression and returns its `clientId`, so the response from the
222
262
  * same showing can point back to it. */
@@ -249,25 +289,47 @@ var ApiClient = class {
249
289
  };
250
290
  this.enqueue("/api/sdk/responses", { responses: [payload] });
251
291
  }
292
+ // ── Event signals ─────────────────────────────────────────────────────────
293
+ /** Queues one upload window of event counts. No clientId: a re-sent batch
294
+ * can count twice, which is fine for "last seen" and trend lines. */
295
+ recordEventCounts(events, context) {
296
+ if (events.length === 0) return;
297
+ this.enqueue("/api/sdk/events", { events, context });
298
+ }
299
+ // ── Live debugger ─────────────────────────────────────────────────────────
300
+ /** Sends one debugger entry from a test device. */
301
+ recordDebug(entry, endUserId, context) {
302
+ this.enqueue("/api/sdk/debug", { entries: [entry], endUserId, context });
303
+ }
252
304
  enqueue(path, value) {
253
305
  this.outbox.enqueue(path, JSON.stringify(value));
254
306
  void this.flush();
255
307
  }
256
308
  // ── Flush ────────────────────────────────────────────────────────────────────
257
309
  /** POSTs queued entries in order. Stops at the first retryable failure (likely
258
- * offline) and leaves the rest for next time. Idempotency keys make re-sends
259
- * safe. Never throws. */
310
+ * offline) and leaves the rest for next time. Entries queued while a flush is
311
+ * running are sent by the same flush, so nothing waits for the next event.
312
+ * Idempotency keys make re-sends safe. Never throws. */
260
313
  async flush() {
261
314
  if (this.isFlushing) return;
262
315
  this.isFlushing = true;
263
316
  try {
264
- for (const entry of this.outbox.snapshot()) {
265
- try {
266
- await this.post(entry.path, entry.body);
267
- this.outbox.remove(entry.id);
268
- } catch {
269
- break;
317
+ const sent = /* @__PURE__ */ new Set();
318
+ for (; ; ) {
319
+ const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
320
+ if (pending.length === 0) break;
321
+ let failed = false;
322
+ for (const entry of pending) {
323
+ try {
324
+ await this.post(entry.path, entry.body);
325
+ this.outbox.remove(entry.id);
326
+ sent.add(entry.id);
327
+ } catch {
328
+ failed = true;
329
+ break;
330
+ }
270
331
  }
332
+ if (failed) break;
271
333
  }
272
334
  } finally {
273
335
  this.isFlushing = false;
@@ -321,6 +383,21 @@ var ConfigStore = class {
321
383
  get theme() {
322
384
  return this.parsed?.theme ?? null;
323
385
  }
386
+ get eventSignals() {
387
+ return this.parsed?.eventSignals ?? false;
388
+ }
389
+ get projectId() {
390
+ return this.parsed?.projectId ?? null;
391
+ }
392
+ get debugUsers() {
393
+ return this.parsed?.debugUsers ?? [];
394
+ }
395
+ get pendingEvents() {
396
+ return this.parsed?.pendingEvents ?? false;
397
+ }
398
+ get serverEvents() {
399
+ return this.parsed?.serverEvents ?? [];
400
+ }
324
401
  get etag() {
325
402
  return this.persisted?.etag ?? null;
326
403
  }
@@ -528,6 +605,9 @@ function advance(trigger, record, eventName, properties, nowT) {
528
605
  satisfied = matchesStep(0);
529
606
  } else {
530
607
  const expected = Math.min(next.stepIndex, steps.length - 1);
608
+ if (expected !== 0 && next.startedAt !== null && nowT < next.startedAt) {
609
+ return { record: next, satisfied: false };
610
+ }
531
611
  if (matchesStep(expected)) {
532
612
  if (expected === 0) {
533
613
  next.startedAt = nowT;
@@ -571,6 +651,7 @@ var TriggerEngine = class {
571
651
  __publicField(this, "onPresent");
572
652
  __publicField(this, "platform");
573
653
  __publicField(this, "now");
654
+ __publicField(this, "onDecision");
574
655
  __publicField(this, "timers", /* @__PURE__ */ new Set());
575
656
  this.store = opts.store;
576
657
  this.surveysProvider = opts.surveysProvider;
@@ -578,26 +659,65 @@ var TriggerEngine = class {
578
659
  this.onPresent = opts.onPresent;
579
660
  this.platform = opts.platform;
580
661
  this.now = opts.now ?? (() => Date.now() / 1e3);
662
+ this.onDecision = opts.onDecision ?? (() => {
663
+ });
581
664
  }
582
- /** Feed an event into the engine. */
583
- process(name, properties = {}) {
665
+ /** Feed an event into the engine. `eventT` (unix seconds) is when it happened,
666
+ * for a replayed server event; it drives sequence progress and
667
+ * `sequenceWindowSeconds`. The survey window, caps and delay always use now. */
668
+ process(name, properties = {}, eventT) {
584
669
  const identity = this.identityProvider();
585
670
  const endUserId = endUserIdOf(identity);
586
671
  const state = this.store.load(endUserId);
587
672
  const nowT = this.now();
673
+ const atT = eventT ?? nowT;
588
674
  for (const survey of this.surveysProvider()) {
589
675
  const triggers = survey.triggers;
590
676
  if (!triggers || triggers.length === 0) continue;
591
- if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
677
+ const names = (t) => t.steps.some((st) => st.event === name);
678
+ if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {
679
+ const t = triggers.find(names);
680
+ if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: "platform" });
681
+ continue;
682
+ }
592
683
  for (const trigger of triggers) {
593
- const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
594
- if (!satisfied) continue;
684
+ const satisfied = this.advanceTrigger(trigger, state, name, properties, atT);
685
+ const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
686
+ if (!satisfied) {
687
+ if (names(trigger)) {
688
+ const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));
689
+ skip(matchedStep ? "sequence_in_progress" : "property_mismatch");
690
+ }
691
+ continue;
692
+ }
595
693
  const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;
596
- if (!this.isWithinWindow(survey, nowT)) continue;
597
- if (!passesFrequency(trigger, occurrence)) continue;
598
- if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;
599
- if (!this.passesSampling(survey, endUserId, state)) continue;
600
- if (!passesCap(survey, state, nowT)) continue;
694
+ const window = this.windowState(survey, nowT);
695
+ if (window !== "open") {
696
+ skip(window);
697
+ continue;
698
+ }
699
+ if (!passesFrequency(trigger, occurrence)) {
700
+ skip("frequency");
701
+ continue;
702
+ }
703
+ if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {
704
+ skip("audience");
705
+ continue;
706
+ }
707
+ if (!this.passesSampling(survey, endUserId, state)) {
708
+ skip("sampled_out");
709
+ continue;
710
+ }
711
+ if (!passesCap(survey, state, nowT)) {
712
+ skip("cap");
713
+ continue;
714
+ }
715
+ this.onDecision({
716
+ surveyId: survey.id,
717
+ triggerId: trigger.id,
718
+ reason: "eligible",
719
+ delaySeconds: Math.max(0, trigger.delaySeconds)
720
+ });
601
721
  this.scheduleShow(survey, trigger, identity);
602
722
  }
603
723
  }
@@ -616,16 +736,16 @@ var TriggerEngine = class {
616
736
  return satisfied;
617
737
  }
618
738
  // ── Eligibility checks ─────────────────────────────────────────────────────
619
- isWithinWindow(survey, nowT) {
739
+ windowState(survey, nowT) {
620
740
  if (survey.startsAt) {
621
741
  const start = Date.parse(survey.startsAt);
622
- if (!Number.isNaN(start) && nowT < start / 1e3) return false;
742
+ if (!Number.isNaN(start) && nowT < start / 1e3) return "not_started";
623
743
  }
624
744
  if (survey.endsAt) {
625
745
  const end = Date.parse(survey.endsAt);
626
- if (!Number.isNaN(end) && nowT > end / 1e3) return false;
746
+ if (!Number.isNaN(end) && nowT > end / 1e3) return "ended";
627
747
  }
628
- return true;
748
+ return "open";
629
749
  }
630
750
  passesSampling(survey, endUserId, state) {
631
751
  const existing = state.surveys[survey.id]?.sampleDecision;
@@ -644,7 +764,10 @@ var TriggerEngine = class {
644
764
  const endUserId = endUserIdOf(identity);
645
765
  const state = this.store.load(endUserId);
646
766
  const nowT = this.now();
647
- if (!passesCap(survey, state, nowT)) return;
767
+ if (!passesCap(survey, state, nowT)) {
768
+ this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "cap" });
769
+ return;
770
+ }
648
771
  const record = state.surveys[survey.id] ?? {};
649
772
  record.lastShownAt = nowT;
650
773
  state.surveys[survey.id] = record;
@@ -667,9 +790,75 @@ function passesCap(survey, state, nowT) {
667
790
  return elapsed >= days * 86400;
668
791
  }
669
792
 
793
+ // src/core/eventCounter.ts
794
+ var MAX_NAMES = 200;
795
+ var MAX_KEYS = 20;
796
+ var MAX_NAME_LENGTH = 200;
797
+ var MAX_KEY_LENGTH = 100;
798
+ var EventCounter = class {
799
+ constructor() {
800
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
801
+ }
802
+ get size() {
803
+ return this.entries.size;
804
+ }
805
+ record(name, properties = {}, now = Date.now()) {
806
+ if (!name || name.length > MAX_NAME_LENGTH) return;
807
+ let e = this.entries.get(name);
808
+ if (!e) {
809
+ if (this.entries.size >= MAX_NAMES) return;
810
+ e = { count: 0, first: now, last: now, keys: /* @__PURE__ */ new Set() };
811
+ this.entries.set(name, e);
812
+ }
813
+ e.count += 1;
814
+ e.last = Math.max(e.last, now);
815
+ for (const key of Object.keys(properties)) {
816
+ if (e.keys.size >= MAX_KEYS) break;
817
+ if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);
818
+ }
819
+ }
820
+ /** Everything counted since the last drain, and a fresh window. */
821
+ drain() {
822
+ const out = [...this.entries].map(([name, e]) => ({
823
+ name,
824
+ count: e.count,
825
+ firstSeenAt: new Date(e.first).toISOString(),
826
+ lastSeenAt: new Date(e.last).toISOString(),
827
+ propertyKeys: [...e.keys]
828
+ }));
829
+ this.entries = /* @__PURE__ */ new Map();
830
+ return out;
831
+ }
832
+ };
833
+
834
+ // src/core/debug.ts
835
+ function debugKey(projectId, endUserId) {
836
+ return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, "0");
837
+ }
838
+ var MAX_PROPS = 30;
839
+ var MAX_STRING = 200;
840
+ function debugProperties(properties) {
841
+ const out = {};
842
+ for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {
843
+ if (typeof v === "string") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}\u2026` : v;
844
+ else if (typeof v === "number" || typeof v === "boolean" || v === null) out[k] = v;
845
+ else if (Array.isArray(v)) out[k] = `[${v.length} items]`;
846
+ else if (typeof v === "object") out[k] = "{\u2026}";
847
+ }
848
+ return out;
849
+ }
850
+
851
+ // src/core/version.ts
852
+ var SDK_VERSION = "0.1.4";
853
+
670
854
  // src/core/client.ts
671
855
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
672
856
  var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
857
+ var EVENT_COUNTS_INTERVAL_MS = 60 * 1e3;
858
+ var PENDING_FOLLOW_UPS_MS = [30 * 1e3, 90 * 1e3];
859
+ var PENDING_INTERVAL_MS = 5 * 60 * 1e3;
860
+ var PENDING_WAITING_INTERVAL_MS = 60 * 1e3;
861
+ var PENDING_WAITING_MAX_SECONDS = 3 * 60 * 60;
673
862
  var MicroSurveysClient = class {
674
863
  constructor(opts) {
675
864
  __publicField(this, "api");
@@ -683,6 +872,16 @@ var MicroSurveysClient = class {
683
872
  __publicField(this, "osVersion");
684
873
  __publicField(this, "appVersion");
685
874
  __publicField(this, "subscribeForeground");
875
+ __publicField(this, "subscribeBackground");
876
+ __publicField(this, "eventCounter", new EventCounter());
877
+ __publicField(this, "eventCountsTimer", null);
878
+ /** Decisions collected while one event is processed, for the live debugger. */
879
+ __publicField(this, "collecting", null);
880
+ __publicField(this, "unsubscribeBackground", null);
881
+ /** Mailbox timers, cleared on background and stop. */
882
+ __publicField(this, "pendingTimers", []);
883
+ __publicField(this, "pendingIntervals", []);
884
+ __publicField(this, "pendingInFlight", false);
686
885
  __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
687
886
  __publicField(this, "configListeners", /* @__PURE__ */ new Set());
688
887
  __publicField(this, "active", null);
@@ -699,32 +898,48 @@ var MicroSurveysClient = class {
699
898
  this.osVersion = opts.osVersion;
700
899
  this.appVersion = opts.appVersion;
701
900
  this.subscribeForeground = opts.subscribeForeground;
901
+ this.subscribeBackground = opts.subscribeBackground;
702
902
  this.engine = new TriggerEngine({
703
903
  store: this.triggerStateStore,
704
904
  surveysProvider: () => this.configStore.surveys,
705
905
  identityProvider: () => this.identityStore.snapshot(),
706
906
  onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
707
- platform: opts.platform
907
+ platform: opts.platform,
908
+ onDecision: (d) => this.handleDecision(d)
708
909
  });
709
910
  }
710
911
  // ── Lifecycle ────────────────────────────────────────────────────────────────
711
- /** Flush any queued ingest, refresh config, and (optionally) wire the
712
- * foreground refresh. Safe to call once early. */
912
+ /** Flush any queued ingest, refresh config, wire the foreground refresh
913
+ * (optional) and the server events mailbox checks. Safe to call once early. */
713
914
  start() {
714
915
  if (this.started) return;
715
916
  this.started = true;
716
917
  void this.api.flush();
717
- void this.refreshConfig();
718
- if (this.refreshOnForeground) {
719
- this.unsubscribeForeground = this.subscribeForeground(() => {
918
+ void this.refreshConfig().then(() => {
919
+ if (this.started) this.startPendingChecks();
920
+ });
921
+ this.unsubscribeForeground = this.subscribeForeground(() => {
922
+ if (this.refreshOnForeground) {
720
923
  void this.api.flush();
721
924
  this.refreshConfigIfStale();
722
- });
723
- }
925
+ }
926
+ this.startPendingChecks();
927
+ });
928
+ this.unsubscribeBackground = this.subscribeBackground?.(() => {
929
+ this.flushEventCounts();
930
+ this.stopPendingChecks();
931
+ }) ?? null;
932
+ this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
724
933
  }
725
934
  /** Tear down listeners + pending timers. */
726
935
  stop() {
727
936
  this.engine.stop();
937
+ this.flushEventCounts();
938
+ if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
939
+ this.eventCountsTimer = null;
940
+ this.stopPendingChecks();
941
+ this.unsubscribeBackground?.();
942
+ this.unsubscribeBackground = null;
728
943
  this.unsubscribeForeground?.();
729
944
  this.unsubscribeForeground = null;
730
945
  this.started = false;
@@ -751,7 +966,126 @@ var MicroSurveysClient = class {
751
966
  this.identityStore.setUser(userId, properties);
752
967
  }
753
968
  track(name, properties = {}) {
754
- this.engine.process(name, properties);
969
+ if (this.configStore.eventSignals) {
970
+ this.eventCounter.record(name, properties);
971
+ if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
972
+ }
973
+ this.processEvent(name, properties);
974
+ }
975
+ /** Runs one event through the engine, reporting to the live debugger on test
976
+ * devices. `occurredAt` (ms epoch) is set for a replayed server event. */
977
+ processEvent(name, properties, occurredAt) {
978
+ const eventT = occurredAt === void 0 ? void 0 : occurredAt / 1e3;
979
+ if (!this.isDebugDevice()) {
980
+ this.engine.process(name, properties, eventT);
981
+ return;
982
+ }
983
+ this.collecting = [];
984
+ try {
985
+ this.engine.process(name, properties, eventT);
986
+ } finally {
987
+ const decisions = this.collecting;
988
+ this.collecting = null;
989
+ this.sendDebug(name, debugProperties(properties), decisions, occurredAt);
990
+ }
991
+ }
992
+ // ── Server events mailbox ────────────────────────────────────────────────────
993
+ /** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while
994
+ * a sequence waits on a server event. Restarts the schedule; no-op unless the
995
+ * config has `pendingEvents`. */
996
+ startPendingChecks() {
997
+ this.stopPendingChecks();
998
+ if (!this.configStore.pendingEvents) return;
999
+ void this.checkPending();
1000
+ for (const ms of PENDING_FOLLOW_UPS_MS) {
1001
+ this.pendingTimers.push(setTimeout(() => void this.checkPending(), ms));
1002
+ }
1003
+ this.pendingIntervals.push(
1004
+ setInterval(() => void this.checkPending(), PENDING_INTERVAL_MS),
1005
+ setInterval(() => {
1006
+ if (this.isWaitingOnServerEvent()) void this.checkPending();
1007
+ }, PENDING_WAITING_INTERVAL_MS)
1008
+ );
1009
+ }
1010
+ stopPendingChecks() {
1011
+ for (const t of this.pendingTimers) clearTimeout(t);
1012
+ for (const t of this.pendingIntervals) clearInterval(t);
1013
+ this.pendingTimers = [];
1014
+ this.pendingIntervals = [];
1015
+ }
1016
+ /** Fetches and replays this user's waiting server events. One request at a
1017
+ * time; a full page is followed by one more call. Failures are silent: the
1018
+ * next scheduled check retries. */
1019
+ async checkPending() {
1020
+ if (this.pendingInFlight || !this.configStore.pendingEvents) return;
1021
+ const identity = this.identityStore.snapshot();
1022
+ const userId = identity.amplitudeUserId ?? identity.hostUserId ?? null;
1023
+ const deviceId = identity.amplitudeDeviceId ?? null;
1024
+ if (!userId && !deviceId) return;
1025
+ this.pendingInFlight = true;
1026
+ try {
1027
+ for (let call = 0; call < 2; call++) {
1028
+ const events = await this.api.fetchPending({ userId, deviceId });
1029
+ this.replayPending(events);
1030
+ if (events.length < PENDING_PAGE_SIZE) break;
1031
+ }
1032
+ } catch {
1033
+ } finally {
1034
+ this.pendingInFlight = false;
1035
+ }
1036
+ }
1037
+ /** Replays server events like `track`, oldest first, at the time each one
1038
+ * happened. Not counted in event signals: the app didn't send them. */
1039
+ replayPending(events) {
1040
+ const timed = events.map((e) => ({ e, at: Date.parse(e.occurredAt) }));
1041
+ timed.sort((a, b) => a.at - b.at);
1042
+ for (const { e, at } of timed) this.processEvent(e.name, e.properties, at);
1043
+ }
1044
+ /** True while a SEQUENCE trigger for the current user has started and its next
1045
+ * step's event arrives by server stream, up to 3 hours after it started. */
1046
+ isWaitingOnServerEvent() {
1047
+ const serverEvents = this.configStore.serverEvents;
1048
+ if (serverEvents.length === 0) return false;
1049
+ const state = this.triggerStateStore.load(endUserIdOf(this.identityStore.snapshot()));
1050
+ const nowT = Date.now() / 1e3;
1051
+ for (const survey of this.configStore.surveys) {
1052
+ for (const trigger of survey.triggers ?? []) {
1053
+ if (trigger.type !== "SEQUENCE") continue;
1054
+ const record = state.triggers[trigger.id];
1055
+ if (!record || record.stepIndex <= 0 || record.startedAt === null) continue;
1056
+ if (nowT - record.startedAt > PENDING_WAITING_MAX_SECONDS) continue;
1057
+ const steps = [...trigger.steps].sort((a, b) => a.order - b.order);
1058
+ const next = steps[Math.min(record.stepIndex, steps.length - 1)];
1059
+ if (next && serverEvents.includes(next.event)) return true;
1060
+ }
1061
+ }
1062
+ return false;
1063
+ }
1064
+ // ── Live debugger ────────────────────────────────────────────────────────────
1065
+ /** True when the dashboard picked the current user as a test device. */
1066
+ isDebugDevice() {
1067
+ const users = this.configStore.debugUsers;
1068
+ const projectId = this.configStore.projectId;
1069
+ if (users.length === 0 || !projectId) return false;
1070
+ return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));
1071
+ }
1072
+ handleDecision(d) {
1073
+ if (this.collecting) this.collecting.push(d);
1074
+ else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
1075
+ }
1076
+ /** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */
1077
+ sendDebug(event, properties, decisions, at) {
1078
+ const endUserId = endUserIdOf(this.identityStore.snapshot());
1079
+ this.api.recordDebug(
1080
+ { at: new Date(at ?? Date.now()).toISOString(), event, properties, decisions },
1081
+ endUserId,
1082
+ { ...this.deviceContext(), sdkVersion: SDK_VERSION }
1083
+ );
1084
+ }
1085
+ /** Uploads the events counted since the last upload (no-op when there are none). */
1086
+ flushEventCounts() {
1087
+ if (this.eventCounter.size === 0) return;
1088
+ this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });
755
1089
  }
756
1090
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
757
1091
  * Its user/device id take precedence over `identify()` for `endUserId`. */
@@ -780,7 +1114,11 @@ var MicroSurveysClient = class {
780
1114
  return () => this.presentListeners.delete(cb);
781
1115
  }
782
1116
  handlePresent(survey, trigger, identity) {
783
- if (this.active && !this.active.closed) return;
1117
+ if (this.active && !this.active.closed) {
1118
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "another_survey_showing" });
1119
+ return;
1120
+ }
1121
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "shown" });
784
1122
  const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
785
1123
  this.active = p;
786
1124
  const active = this.toActiveSurvey(p);
@@ -921,6 +1259,12 @@ function appStateForeground(onForeground) {
921
1259
  });
922
1260
  return () => sub.remove();
923
1261
  }
1262
+ function appStateBackground(onBackground) {
1263
+ const sub = AppState.addEventListener("change", (state) => {
1264
+ if (state === "background") onBackground();
1265
+ });
1266
+ return () => sub.remove();
1267
+ }
924
1268
  var MicroSurveys = class {
925
1269
  constructor(opts) {
926
1270
  __publicField(this, "apiKey");
@@ -941,7 +1285,8 @@ var MicroSurveys = class {
941
1285
  osVersion: String(Platform.Version),
942
1286
  appVersion: opts.appVersion,
943
1287
  storage: kv,
944
- subscribeForeground: appStateForeground
1288
+ subscribeForeground: appStateForeground,
1289
+ subscribeBackground: appStateBackground
945
1290
  });
946
1291
  this.client = client;
947
1292
  const queued = this.pending;