@microsurveysai/react-native 0.1.1 → 0.1.3

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.d.cts CHANGED
@@ -99,6 +99,12 @@ interface SDKConfig {
99
99
  fetchedAt?: string | null;
100
100
  theme: ProjectTheme | null;
101
101
  surveys: Survey[];
102
+ /** The project turned event signals on: count tracked events and upload the
103
+ * counts (see eventCounter.ts). Absent on older servers, which means off. */
104
+ eventSignals: boolean;
105
+ /** Hashes of the project's test devices for the live debugger (see debug.ts).
106
+ * Empty when none are set, or on older servers. */
107
+ debugUsers: string[];
102
108
  }
103
109
  /** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */
104
110
  interface ProjectTheme {
@@ -186,6 +192,9 @@ interface CreateClientOptions {
186
192
  storage: KeyValueStorage;
187
193
  /** Subscribes to "app came to the foreground"; returns an unsubscribe. */
188
194
  subscribeForeground: (onForeground: () => void) => () => void;
195
+ /** Subscribes to "app went to the background"; returns an unsubscribe. Used
196
+ * to upload event counts before the app may be suspended. */
197
+ subscribeBackground?: (onBackground: () => void) => () => void;
189
198
  }
190
199
  /** An auto-triggered survey the host should present. Call `close` exactly once
191
200
  * when the UI dismisses (completed, partial, or dismissed). */
@@ -208,6 +217,12 @@ declare class MicroSurveysClient {
208
217
  private readonly osVersion;
209
218
  private readonly appVersion;
210
219
  private readonly subscribeForeground;
220
+ private readonly subscribeBackground;
221
+ private readonly eventCounter;
222
+ private eventCountsTimer;
223
+ /** Decisions collected while one event is processed, for the live debugger. */
224
+ private collecting;
225
+ private unsubscribeBackground;
211
226
  private readonly presentListeners;
212
227
  private readonly configListeners;
213
228
  private active;
@@ -225,6 +240,12 @@ declare class MicroSurveysClient {
225
240
  refreshConfigIfStale(): void;
226
241
  identify(userId: string | null | undefined, properties?: Record<string, unknown>): void;
227
242
  track(name: string, properties?: Record<string, unknown>): void;
243
+ /** True when the dashboard picked the current user as a test device. */
244
+ private isDebugDevice;
245
+ private handleDecision;
246
+ private sendDebug;
247
+ /** Uploads the events counted since the last upload (no-op when there are none). */
248
+ flushEventCounts(): void;
228
249
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
229
250
  * Its user/device id take precedence over `identify()` for `endUserId`. */
230
251
  updateAnalyticsIdentity(update: AnalyticsIdentity): void;
package/dist/index.d.ts CHANGED
@@ -99,6 +99,12 @@ interface SDKConfig {
99
99
  fetchedAt?: string | null;
100
100
  theme: ProjectTheme | null;
101
101
  surveys: Survey[];
102
+ /** The project turned event signals on: count tracked events and upload the
103
+ * counts (see eventCounter.ts). Absent on older servers, which means off. */
104
+ eventSignals: boolean;
105
+ /** Hashes of the project's test devices for the live debugger (see debug.ts).
106
+ * Empty when none are set, or on older servers. */
107
+ debugUsers: string[];
102
108
  }
103
109
  /** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */
104
110
  interface ProjectTheme {
@@ -186,6 +192,9 @@ interface CreateClientOptions {
186
192
  storage: KeyValueStorage;
187
193
  /** Subscribes to "app came to the foreground"; returns an unsubscribe. */
188
194
  subscribeForeground: (onForeground: () => void) => () => void;
195
+ /** Subscribes to "app went to the background"; returns an unsubscribe. Used
196
+ * to upload event counts before the app may be suspended. */
197
+ subscribeBackground?: (onBackground: () => void) => () => void;
189
198
  }
190
199
  /** An auto-triggered survey the host should present. Call `close` exactly once
191
200
  * when the UI dismisses (completed, partial, or dismissed). */
@@ -208,6 +217,12 @@ declare class MicroSurveysClient {
208
217
  private readonly osVersion;
209
218
  private readonly appVersion;
210
219
  private readonly subscribeForeground;
220
+ private readonly subscribeBackground;
221
+ private readonly eventCounter;
222
+ private eventCountsTimer;
223
+ /** Decisions collected while one event is processed, for the live debugger. */
224
+ private collecting;
225
+ private unsubscribeBackground;
211
226
  private readonly presentListeners;
212
227
  private readonly configListeners;
213
228
  private active;
@@ -225,6 +240,12 @@ declare class MicroSurveysClient {
225
240
  refreshConfigIfStale(): void;
226
241
  identify(userId: string | null | undefined, properties?: Record<string, unknown>): void;
227
242
  track(name: string, properties?: Record<string, unknown>): void;
243
+ /** True when the dashboard picked the current user as a test device. */
244
+ private isDebugDevice;
245
+ private handleDecision;
246
+ private sendDebug;
247
+ /** Uploads the events counted since the last upload (no-op when there are none). */
248
+ flushEventCounts(): void;
228
249
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
229
250
  * Its user/device id take precedence over `identify()` for `endUserId`. */
230
251
  updateAnalyticsIdentity(update: AnalyticsIdentity): void;
package/dist/index.js CHANGED
@@ -76,16 +76,29 @@ function numOr(v, fallback) {
76
76
  function strOrUndef(v) {
77
77
  return typeof v === "string" ? v : void 0;
78
78
  }
79
+ var MAX_SCALE_POINTS = 101;
80
+ var MAX_SCALE_ABS = 1e3;
81
+ var MAX_STARS = 100;
82
+ var MAX_OPTIONS = 100;
83
+ function boundedScale(min, max) {
84
+ const lo = Math.min(Math.max(min, -MAX_SCALE_ABS), MAX_SCALE_ABS);
85
+ let hi = Math.min(Math.max(max, -MAX_SCALE_ABS), MAX_SCALE_ABS);
86
+ if (hi - lo > MAX_SCALE_POINTS - 1) hi = lo + MAX_SCALE_POINTS - 1;
87
+ return { min: lo, max: hi };
88
+ }
89
+ function boundedOptions(raw) {
90
+ return Array.isArray(raw) ? raw.slice(0, MAX_OPTIONS) : [];
91
+ }
79
92
  function normalizeConfig(type, raw) {
80
93
  switch (type) {
81
94
  case "NPS":
82
- return { kind: "scale", min: numOr(raw.min, 0), max: numOr(raw.max, 10), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
95
+ return { kind: "scale", ...boundedScale(numOr(raw.min, 0), numOr(raw.max, 10)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
83
96
  case "CES":
84
- return { kind: "scale", min: numOr(raw.min, 1), max: numOr(raw.max, 7), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
97
+ return { kind: "scale", ...boundedScale(numOr(raw.min, 1), numOr(raw.max, 7)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
85
98
  case "CSAT_STAR":
86
- return { kind: "stars", count: numOr(raw.count, 5) };
99
+ return { kind: "stars", count: Math.min(numOr(raw.count, 5), MAX_STARS) };
87
100
  case "CSAT_EMOJI": {
88
- const opts = Array.isArray(raw.options) ? raw.options : [];
101
+ const opts = boundedOptions(raw.options);
89
102
  const options = opts.map((o) => {
90
103
  const oo = asObject(o);
91
104
  return { value: String(oo.value ?? ""), emoji: typeof oo.emoji === "string" ? oo.emoji : "", label: strOrUndef(oo.label) };
@@ -95,7 +108,7 @@ function normalizeConfig(type, raw) {
95
108
  case "THUMBS":
96
109
  return { kind: "thumbs" };
97
110
  case "SINGLE_CHOICE": {
98
- const opts = Array.isArray(raw.options) ? raw.options : [];
111
+ const opts = boundedOptions(raw.options);
99
112
  const options = opts.map((o) => {
100
113
  const oo = asObject(o);
101
114
  const value = String(oo.value ?? "");
@@ -174,7 +187,14 @@ function parseConfig(rawText) {
174
187
  if (!projectId) return null;
175
188
  const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
176
189
  const theme = root.theme && typeof root.theme === "object" && !Array.isArray(root.theme) ? root.theme : null;
177
- 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
+ };
178
198
  }
179
199
 
180
200
  // src/core/apiClient.ts
@@ -236,25 +256,47 @@ var ApiClient = class {
236
256
  };
237
257
  this.enqueue("/api/sdk/responses", { responses: [payload] });
238
258
  }
259
+ // ── Event signals ─────────────────────────────────────────────────────────
260
+ /** Queues one upload window of event counts. No clientId: a re-sent batch
261
+ * can count twice, which is fine for "last seen" and trend lines. */
262
+ recordEventCounts(events, context) {
263
+ if (events.length === 0) return;
264
+ this.enqueue("/api/sdk/events", { events, context });
265
+ }
266
+ // ── Live debugger ─────────────────────────────────────────────────────────
267
+ /** Sends one debugger entry from a test device. */
268
+ recordDebug(entry, endUserId, context) {
269
+ this.enqueue("/api/sdk/debug", { entries: [entry], endUserId, context });
270
+ }
239
271
  enqueue(path, value) {
240
272
  this.outbox.enqueue(path, JSON.stringify(value));
241
273
  void this.flush();
242
274
  }
243
275
  // ── Flush ────────────────────────────────────────────────────────────────────
244
276
  /** POSTs queued entries in order. Stops at the first retryable failure (likely
245
- * offline) and leaves the rest for next time. Idempotency keys make re-sends
246
- * safe. Never throws. */
277
+ * offline) and leaves the rest for next time. Entries queued while a flush is
278
+ * running are sent by the same flush, so nothing waits for the next event.
279
+ * Idempotency keys make re-sends safe. Never throws. */
247
280
  async flush() {
248
281
  if (this.isFlushing) return;
249
282
  this.isFlushing = true;
250
283
  try {
251
- for (const entry of this.outbox.snapshot()) {
252
- try {
253
- await this.post(entry.path, entry.body);
254
- this.outbox.remove(entry.id);
255
- } catch {
256
- break;
284
+ const sent = /* @__PURE__ */ new Set();
285
+ for (; ; ) {
286
+ const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
287
+ if (pending.length === 0) break;
288
+ let failed = false;
289
+ for (const entry of pending) {
290
+ try {
291
+ await this.post(entry.path, entry.body);
292
+ this.outbox.remove(entry.id);
293
+ sent.add(entry.id);
294
+ } catch {
295
+ failed = true;
296
+ break;
297
+ }
257
298
  }
299
+ if (failed) break;
258
300
  }
259
301
  } finally {
260
302
  this.isFlushing = false;
@@ -308,6 +350,15 @@ var ConfigStore = class {
308
350
  get theme() {
309
351
  return this.parsed?.theme ?? null;
310
352
  }
353
+ get eventSignals() {
354
+ return this.parsed?.eventSignals ?? false;
355
+ }
356
+ get projectId() {
357
+ return this.parsed?.projectId ?? null;
358
+ }
359
+ get debugUsers() {
360
+ return this.parsed?.debugUsers ?? [];
361
+ }
311
362
  get etag() {
312
363
  return this.persisted?.etag ?? null;
313
364
  }
@@ -558,6 +609,7 @@ var TriggerEngine = class {
558
609
  __publicField(this, "onPresent");
559
610
  __publicField(this, "platform");
560
611
  __publicField(this, "now");
612
+ __publicField(this, "onDecision");
561
613
  __publicField(this, "timers", /* @__PURE__ */ new Set());
562
614
  this.store = opts.store;
563
615
  this.surveysProvider = opts.surveysProvider;
@@ -565,6 +617,8 @@ var TriggerEngine = class {
565
617
  this.onPresent = opts.onPresent;
566
618
  this.platform = opts.platform;
567
619
  this.now = opts.now ?? (() => Date.now() / 1e3);
620
+ this.onDecision = opts.onDecision ?? (() => {
621
+ });
568
622
  }
569
623
  /** Feed an event into the engine. */
570
624
  process(name, properties = {}) {
@@ -575,16 +629,50 @@ var TriggerEngine = class {
575
629
  for (const survey of this.surveysProvider()) {
576
630
  const triggers = survey.triggers;
577
631
  if (!triggers || triggers.length === 0) continue;
578
- if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
632
+ const names = (t) => t.steps.some((st) => st.event === name);
633
+ if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {
634
+ const t = triggers.find(names);
635
+ if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: "platform" });
636
+ continue;
637
+ }
579
638
  for (const trigger of triggers) {
580
639
  const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
581
- if (!satisfied) continue;
640
+ const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
641
+ if (!satisfied) {
642
+ if (names(trigger)) {
643
+ const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));
644
+ skip(matchedStep ? "sequence_in_progress" : "property_mismatch");
645
+ }
646
+ continue;
647
+ }
582
648
  const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;
583
- if (!this.isWithinWindow(survey, nowT)) continue;
584
- if (!passesFrequency(trigger, occurrence)) continue;
585
- if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;
586
- if (!this.passesSampling(survey, endUserId, state)) continue;
587
- if (!passesCap(survey, state, nowT)) continue;
649
+ const window = this.windowState(survey, nowT);
650
+ if (window !== "open") {
651
+ skip(window);
652
+ continue;
653
+ }
654
+ if (!passesFrequency(trigger, occurrence)) {
655
+ skip("frequency");
656
+ continue;
657
+ }
658
+ if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {
659
+ skip("audience");
660
+ continue;
661
+ }
662
+ if (!this.passesSampling(survey, endUserId, state)) {
663
+ skip("sampled_out");
664
+ continue;
665
+ }
666
+ if (!passesCap(survey, state, nowT)) {
667
+ skip("cap");
668
+ continue;
669
+ }
670
+ this.onDecision({
671
+ surveyId: survey.id,
672
+ triggerId: trigger.id,
673
+ reason: "eligible",
674
+ delaySeconds: Math.max(0, trigger.delaySeconds)
675
+ });
588
676
  this.scheduleShow(survey, trigger, identity);
589
677
  }
590
678
  }
@@ -603,16 +691,16 @@ var TriggerEngine = class {
603
691
  return satisfied;
604
692
  }
605
693
  // ── Eligibility checks ─────────────────────────────────────────────────────
606
- isWithinWindow(survey, nowT) {
694
+ windowState(survey, nowT) {
607
695
  if (survey.startsAt) {
608
696
  const start = Date.parse(survey.startsAt);
609
- if (!Number.isNaN(start) && nowT < start / 1e3) return false;
697
+ if (!Number.isNaN(start) && nowT < start / 1e3) return "not_started";
610
698
  }
611
699
  if (survey.endsAt) {
612
700
  const end = Date.parse(survey.endsAt);
613
- if (!Number.isNaN(end) && nowT > end / 1e3) return false;
701
+ if (!Number.isNaN(end) && nowT > end / 1e3) return "ended";
614
702
  }
615
- return true;
703
+ return "open";
616
704
  }
617
705
  passesSampling(survey, endUserId, state) {
618
706
  const existing = state.surveys[survey.id]?.sampleDecision;
@@ -631,7 +719,10 @@ var TriggerEngine = class {
631
719
  const endUserId = endUserIdOf(identity);
632
720
  const state = this.store.load(endUserId);
633
721
  const nowT = this.now();
634
- if (!passesCap(survey, state, nowT)) return;
722
+ if (!passesCap(survey, state, nowT)) {
723
+ this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "cap" });
724
+ return;
725
+ }
635
726
  const record = state.surveys[survey.id] ?? {};
636
727
  record.lastShownAt = nowT;
637
728
  state.surveys[survey.id] = record;
@@ -654,9 +745,71 @@ function passesCap(survey, state, nowT) {
654
745
  return elapsed >= days * 86400;
655
746
  }
656
747
 
748
+ // src/core/eventCounter.ts
749
+ var MAX_NAMES = 200;
750
+ var MAX_KEYS = 20;
751
+ var MAX_NAME_LENGTH = 200;
752
+ var MAX_KEY_LENGTH = 100;
753
+ var EventCounter = class {
754
+ constructor() {
755
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
756
+ }
757
+ get size() {
758
+ return this.entries.size;
759
+ }
760
+ record(name, properties = {}, now = Date.now()) {
761
+ if (!name || name.length > MAX_NAME_LENGTH) return;
762
+ let e = this.entries.get(name);
763
+ if (!e) {
764
+ if (this.entries.size >= MAX_NAMES) return;
765
+ e = { count: 0, first: now, last: now, keys: /* @__PURE__ */ new Set() };
766
+ this.entries.set(name, e);
767
+ }
768
+ e.count += 1;
769
+ e.last = Math.max(e.last, now);
770
+ for (const key of Object.keys(properties)) {
771
+ if (e.keys.size >= MAX_KEYS) break;
772
+ if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);
773
+ }
774
+ }
775
+ /** Everything counted since the last drain, and a fresh window. */
776
+ drain() {
777
+ const out = [...this.entries].map(([name, e]) => ({
778
+ name,
779
+ count: e.count,
780
+ firstSeenAt: new Date(e.first).toISOString(),
781
+ lastSeenAt: new Date(e.last).toISOString(),
782
+ propertyKeys: [...e.keys]
783
+ }));
784
+ this.entries = /* @__PURE__ */ new Map();
785
+ return out;
786
+ }
787
+ };
788
+
789
+ // src/core/debug.ts
790
+ function debugKey(projectId, endUserId) {
791
+ return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, "0");
792
+ }
793
+ var MAX_PROPS = 30;
794
+ var MAX_STRING = 200;
795
+ function debugProperties(properties) {
796
+ const out = {};
797
+ for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {
798
+ if (typeof v === "string") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}\u2026` : v;
799
+ else if (typeof v === "number" || typeof v === "boolean" || v === null) out[k] = v;
800
+ else if (Array.isArray(v)) out[k] = `[${v.length} items]`;
801
+ else if (typeof v === "object") out[k] = "{\u2026}";
802
+ }
803
+ return out;
804
+ }
805
+
806
+ // src/core/version.ts
807
+ var SDK_VERSION = "0.1.3";
808
+
657
809
  // src/core/client.ts
658
810
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
659
811
  var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
812
+ var EVENT_COUNTS_INTERVAL_MS = 60 * 1e3;
660
813
  var MicroSurveysClient = class {
661
814
  constructor(opts) {
662
815
  __publicField(this, "api");
@@ -670,6 +823,12 @@ var MicroSurveysClient = class {
670
823
  __publicField(this, "osVersion");
671
824
  __publicField(this, "appVersion");
672
825
  __publicField(this, "subscribeForeground");
826
+ __publicField(this, "subscribeBackground");
827
+ __publicField(this, "eventCounter", new EventCounter());
828
+ __publicField(this, "eventCountsTimer", null);
829
+ /** Decisions collected while one event is processed, for the live debugger. */
830
+ __publicField(this, "collecting", null);
831
+ __publicField(this, "unsubscribeBackground", null);
673
832
  __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
674
833
  __publicField(this, "configListeners", /* @__PURE__ */ new Set());
675
834
  __publicField(this, "active", null);
@@ -686,12 +845,14 @@ var MicroSurveysClient = class {
686
845
  this.osVersion = opts.osVersion;
687
846
  this.appVersion = opts.appVersion;
688
847
  this.subscribeForeground = opts.subscribeForeground;
848
+ this.subscribeBackground = opts.subscribeBackground;
689
849
  this.engine = new TriggerEngine({
690
850
  store: this.triggerStateStore,
691
851
  surveysProvider: () => this.configStore.surveys,
692
852
  identityProvider: () => this.identityStore.snapshot(),
693
853
  onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
694
- platform: opts.platform
854
+ platform: opts.platform,
855
+ onDecision: (d) => this.handleDecision(d)
695
856
  });
696
857
  }
697
858
  // ── Lifecycle ────────────────────────────────────────────────────────────────
@@ -708,10 +869,17 @@ var MicroSurveysClient = class {
708
869
  this.refreshConfigIfStale();
709
870
  });
710
871
  }
872
+ this.unsubscribeBackground = this.subscribeBackground?.(() => this.flushEventCounts()) ?? null;
873
+ this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
711
874
  }
712
875
  /** Tear down listeners + pending timers. */
713
876
  stop() {
714
877
  this.engine.stop();
878
+ this.flushEventCounts();
879
+ if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
880
+ this.eventCountsTimer = null;
881
+ this.unsubscribeBackground?.();
882
+ this.unsubscribeBackground = null;
715
883
  this.unsubscribeForeground?.();
716
884
  this.unsubscribeForeground = null;
717
885
  this.started = false;
@@ -738,7 +906,47 @@ var MicroSurveysClient = class {
738
906
  this.identityStore.setUser(userId, properties);
739
907
  }
740
908
  track(name, properties = {}) {
741
- this.engine.process(name, properties);
909
+ if (this.configStore.eventSignals) {
910
+ this.eventCounter.record(name, properties);
911
+ if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
912
+ }
913
+ if (!this.isDebugDevice()) {
914
+ this.engine.process(name, properties);
915
+ return;
916
+ }
917
+ this.collecting = [];
918
+ try {
919
+ this.engine.process(name, properties);
920
+ } finally {
921
+ const decisions = this.collecting;
922
+ this.collecting = null;
923
+ this.sendDebug(name, debugProperties(properties), decisions);
924
+ }
925
+ }
926
+ // ── Live debugger ────────────────────────────────────────────────────────────
927
+ /** True when the dashboard picked the current user as a test device. */
928
+ isDebugDevice() {
929
+ const users = this.configStore.debugUsers;
930
+ const projectId = this.configStore.projectId;
931
+ if (users.length === 0 || !projectId) return false;
932
+ return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));
933
+ }
934
+ handleDecision(d) {
935
+ if (this.collecting) this.collecting.push(d);
936
+ else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
937
+ }
938
+ sendDebug(event, properties, decisions) {
939
+ const endUserId = endUserIdOf(this.identityStore.snapshot());
940
+ this.api.recordDebug(
941
+ { at: (/* @__PURE__ */ new Date()).toISOString(), event, properties, decisions },
942
+ endUserId,
943
+ { ...this.deviceContext(), sdkVersion: SDK_VERSION }
944
+ );
945
+ }
946
+ /** Uploads the events counted since the last upload (no-op when there are none). */
947
+ flushEventCounts() {
948
+ if (this.eventCounter.size === 0) return;
949
+ this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });
742
950
  }
743
951
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
744
952
  * Its user/device id take precedence over `identify()` for `endUserId`. */
@@ -767,7 +975,11 @@ var MicroSurveysClient = class {
767
975
  return () => this.presentListeners.delete(cb);
768
976
  }
769
977
  handlePresent(survey, trigger, identity) {
770
- if (this.active && !this.active.closed) return;
978
+ if (this.active && !this.active.closed) {
979
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "another_survey_showing" });
980
+ return;
981
+ }
982
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "shown" });
771
983
  const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
772
984
  this.active = p;
773
985
  const active = this.toActiveSurvey(p);
@@ -908,6 +1120,12 @@ function appStateForeground(onForeground) {
908
1120
  });
909
1121
  return () => sub.remove();
910
1122
  }
1123
+ function appStateBackground(onBackground) {
1124
+ const sub = AppState.addEventListener("change", (state) => {
1125
+ if (state === "background") onBackground();
1126
+ });
1127
+ return () => sub.remove();
1128
+ }
911
1129
  var MicroSurveys = class {
912
1130
  constructor(opts) {
913
1131
  __publicField(this, "apiKey");
@@ -928,7 +1146,8 @@ var MicroSurveys = class {
928
1146
  osVersion: String(Platform.Version),
929
1147
  appVersion: opts.appVersion,
930
1148
  storage: kv,
931
- subscribeForeground: appStateForeground
1149
+ subscribeForeground: appStateForeground,
1150
+ subscribeBackground: appStateBackground
932
1151
  });
933
1152
  this.client = client;
934
1153
  const queued = this.pending;