@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.cjs CHANGED
@@ -117,16 +117,29 @@ function numOr(v, fallback) {
117
117
  function strOrUndef(v) {
118
118
  return typeof v === "string" ? v : void 0;
119
119
  }
120
+ var MAX_SCALE_POINTS = 101;
121
+ var MAX_SCALE_ABS = 1e3;
122
+ var MAX_STARS = 100;
123
+ var MAX_OPTIONS = 100;
124
+ function boundedScale(min, max) {
125
+ const lo = Math.min(Math.max(min, -MAX_SCALE_ABS), MAX_SCALE_ABS);
126
+ let hi = Math.min(Math.max(max, -MAX_SCALE_ABS), MAX_SCALE_ABS);
127
+ if (hi - lo > MAX_SCALE_POINTS - 1) hi = lo + MAX_SCALE_POINTS - 1;
128
+ return { min: lo, max: hi };
129
+ }
130
+ function boundedOptions(raw) {
131
+ return Array.isArray(raw) ? raw.slice(0, MAX_OPTIONS) : [];
132
+ }
120
133
  function normalizeConfig(type, raw) {
121
134
  switch (type) {
122
135
  case "NPS":
123
- return { kind: "scale", min: numOr(raw.min, 0), max: numOr(raw.max, 10), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
136
+ return { kind: "scale", ...boundedScale(numOr(raw.min, 0), numOr(raw.max, 10)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
124
137
  case "CES":
125
- return { kind: "scale", min: numOr(raw.min, 1), max: numOr(raw.max, 7), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
138
+ return { kind: "scale", ...boundedScale(numOr(raw.min, 1), numOr(raw.max, 7)), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
126
139
  case "CSAT_STAR":
127
- return { kind: "stars", count: numOr(raw.count, 5) };
140
+ return { kind: "stars", count: Math.min(numOr(raw.count, 5), MAX_STARS) };
128
141
  case "CSAT_EMOJI": {
129
- const opts = Array.isArray(raw.options) ? raw.options : [];
142
+ const opts = boundedOptions(raw.options);
130
143
  const options = opts.map((o) => {
131
144
  const oo = asObject(o);
132
145
  return { value: String(oo.value ?? ""), emoji: typeof oo.emoji === "string" ? oo.emoji : "", label: strOrUndef(oo.label) };
@@ -136,7 +149,7 @@ function normalizeConfig(type, raw) {
136
149
  case "THUMBS":
137
150
  return { kind: "thumbs" };
138
151
  case "SINGLE_CHOICE": {
139
- const opts = Array.isArray(raw.options) ? raw.options : [];
152
+ const opts = boundedOptions(raw.options);
140
153
  const options = opts.map((o) => {
141
154
  const oo = asObject(o);
142
155
  const value = String(oo.value ?? "");
@@ -215,7 +228,14 @@ function parseConfig(rawText) {
215
228
  if (!projectId) return null;
216
229
  const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
217
230
  const theme = root.theme && typeof root.theme === "object" && !Array.isArray(root.theme) ? root.theme : null;
218
- 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
+ };
219
239
  }
220
240
 
221
241
  // src/core/apiClient.ts
@@ -277,25 +297,47 @@ var ApiClient = class {
277
297
  };
278
298
  this.enqueue("/api/sdk/responses", { responses: [payload] });
279
299
  }
300
+ // ── Event signals ─────────────────────────────────────────────────────────
301
+ /** Queues one upload window of event counts. No clientId: a re-sent batch
302
+ * can count twice, which is fine for "last seen" and trend lines. */
303
+ recordEventCounts(events, context) {
304
+ if (events.length === 0) return;
305
+ this.enqueue("/api/sdk/events", { events, context });
306
+ }
307
+ // ── Live debugger ─────────────────────────────────────────────────────────
308
+ /** Sends one debugger entry from a test device. */
309
+ recordDebug(entry, endUserId, context) {
310
+ this.enqueue("/api/sdk/debug", { entries: [entry], endUserId, context });
311
+ }
280
312
  enqueue(path, value) {
281
313
  this.outbox.enqueue(path, JSON.stringify(value));
282
314
  void this.flush();
283
315
  }
284
316
  // ── Flush ────────────────────────────────────────────────────────────────────
285
317
  /** POSTs queued entries in order. Stops at the first retryable failure (likely
286
- * offline) and leaves the rest for next time. Idempotency keys make re-sends
287
- * safe. Never throws. */
318
+ * offline) and leaves the rest for next time. Entries queued while a flush is
319
+ * running are sent by the same flush, so nothing waits for the next event.
320
+ * Idempotency keys make re-sends safe. Never throws. */
288
321
  async flush() {
289
322
  if (this.isFlushing) return;
290
323
  this.isFlushing = true;
291
324
  try {
292
- for (const entry of this.outbox.snapshot()) {
293
- try {
294
- await this.post(entry.path, entry.body);
295
- this.outbox.remove(entry.id);
296
- } catch {
297
- break;
325
+ const sent = /* @__PURE__ */ new Set();
326
+ for (; ; ) {
327
+ const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
328
+ if (pending.length === 0) break;
329
+ let failed = false;
330
+ for (const entry of pending) {
331
+ try {
332
+ await this.post(entry.path, entry.body);
333
+ this.outbox.remove(entry.id);
334
+ sent.add(entry.id);
335
+ } catch {
336
+ failed = true;
337
+ break;
338
+ }
298
339
  }
340
+ if (failed) break;
299
341
  }
300
342
  } finally {
301
343
  this.isFlushing = false;
@@ -349,6 +391,15 @@ var ConfigStore = class {
349
391
  get theme() {
350
392
  return this.parsed?.theme ?? null;
351
393
  }
394
+ get eventSignals() {
395
+ return this.parsed?.eventSignals ?? false;
396
+ }
397
+ get projectId() {
398
+ return this.parsed?.projectId ?? null;
399
+ }
400
+ get debugUsers() {
401
+ return this.parsed?.debugUsers ?? [];
402
+ }
352
403
  get etag() {
353
404
  return this.persisted?.etag ?? null;
354
405
  }
@@ -599,6 +650,7 @@ var TriggerEngine = class {
599
650
  __publicField(this, "onPresent");
600
651
  __publicField(this, "platform");
601
652
  __publicField(this, "now");
653
+ __publicField(this, "onDecision");
602
654
  __publicField(this, "timers", /* @__PURE__ */ new Set());
603
655
  this.store = opts.store;
604
656
  this.surveysProvider = opts.surveysProvider;
@@ -606,6 +658,8 @@ var TriggerEngine = class {
606
658
  this.onPresent = opts.onPresent;
607
659
  this.platform = opts.platform;
608
660
  this.now = opts.now ?? (() => Date.now() / 1e3);
661
+ this.onDecision = opts.onDecision ?? (() => {
662
+ });
609
663
  }
610
664
  /** Feed an event into the engine. */
611
665
  process(name, properties = {}) {
@@ -616,16 +670,50 @@ var TriggerEngine = class {
616
670
  for (const survey of this.surveysProvider()) {
617
671
  const triggers = survey.triggers;
618
672
  if (!triggers || triggers.length === 0) continue;
619
- if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
673
+ const names = (t) => t.steps.some((st) => st.event === name);
674
+ if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) {
675
+ const t = triggers.find(names);
676
+ if (t) this.onDecision({ surveyId: survey.id, triggerId: t.id, reason: "platform" });
677
+ continue;
678
+ }
620
679
  for (const trigger of triggers) {
621
680
  const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
622
- if (!satisfied) continue;
681
+ const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
682
+ if (!satisfied) {
683
+ if (names(trigger)) {
684
+ const matchedStep = trigger.steps.some((st) => eventMatchesStep(name, properties, st));
685
+ skip(matchedStep ? "sequence_in_progress" : "property_mismatch");
686
+ }
687
+ continue;
688
+ }
623
689
  const occurrence = state.triggers[trigger.id]?.satisfiedCount ?? 0;
624
- if (!this.isWithinWindow(survey, nowT)) continue;
625
- if (!passesFrequency(trigger, occurrence)) continue;
626
- if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) continue;
627
- if (!this.passesSampling(survey, endUserId, state)) continue;
628
- if (!passesCap(survey, state, nowT)) continue;
690
+ const window = this.windowState(survey, nowT);
691
+ if (window !== "open") {
692
+ skip(window);
693
+ continue;
694
+ }
695
+ if (!passesFrequency(trigger, occurrence)) {
696
+ skip("frequency");
697
+ continue;
698
+ }
699
+ if (survey.audienceMatch && !audienceMatches(survey.audienceMatch, identity.userProperties)) {
700
+ skip("audience");
701
+ continue;
702
+ }
703
+ if (!this.passesSampling(survey, endUserId, state)) {
704
+ skip("sampled_out");
705
+ continue;
706
+ }
707
+ if (!passesCap(survey, state, nowT)) {
708
+ skip("cap");
709
+ continue;
710
+ }
711
+ this.onDecision({
712
+ surveyId: survey.id,
713
+ triggerId: trigger.id,
714
+ reason: "eligible",
715
+ delaySeconds: Math.max(0, trigger.delaySeconds)
716
+ });
629
717
  this.scheduleShow(survey, trigger, identity);
630
718
  }
631
719
  }
@@ -644,16 +732,16 @@ var TriggerEngine = class {
644
732
  return satisfied;
645
733
  }
646
734
  // ── Eligibility checks ─────────────────────────────────────────────────────
647
- isWithinWindow(survey, nowT) {
735
+ windowState(survey, nowT) {
648
736
  if (survey.startsAt) {
649
737
  const start = Date.parse(survey.startsAt);
650
- if (!Number.isNaN(start) && nowT < start / 1e3) return false;
738
+ if (!Number.isNaN(start) && nowT < start / 1e3) return "not_started";
651
739
  }
652
740
  if (survey.endsAt) {
653
741
  const end = Date.parse(survey.endsAt);
654
- if (!Number.isNaN(end) && nowT > end / 1e3) return false;
742
+ if (!Number.isNaN(end) && nowT > end / 1e3) return "ended";
655
743
  }
656
- return true;
744
+ return "open";
657
745
  }
658
746
  passesSampling(survey, endUserId, state) {
659
747
  const existing = state.surveys[survey.id]?.sampleDecision;
@@ -672,7 +760,10 @@ var TriggerEngine = class {
672
760
  const endUserId = endUserIdOf(identity);
673
761
  const state = this.store.load(endUserId);
674
762
  const nowT = this.now();
675
- if (!passesCap(survey, state, nowT)) return;
763
+ if (!passesCap(survey, state, nowT)) {
764
+ this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "cap" });
765
+ return;
766
+ }
676
767
  const record = state.surveys[survey.id] ?? {};
677
768
  record.lastShownAt = nowT;
678
769
  state.surveys[survey.id] = record;
@@ -695,9 +786,71 @@ function passesCap(survey, state, nowT) {
695
786
  return elapsed >= days * 86400;
696
787
  }
697
788
 
789
+ // src/core/eventCounter.ts
790
+ var MAX_NAMES = 200;
791
+ var MAX_KEYS = 20;
792
+ var MAX_NAME_LENGTH = 200;
793
+ var MAX_KEY_LENGTH = 100;
794
+ var EventCounter = class {
795
+ constructor() {
796
+ __publicField(this, "entries", /* @__PURE__ */ new Map());
797
+ }
798
+ get size() {
799
+ return this.entries.size;
800
+ }
801
+ record(name, properties = {}, now = Date.now()) {
802
+ if (!name || name.length > MAX_NAME_LENGTH) return;
803
+ let e = this.entries.get(name);
804
+ if (!e) {
805
+ if (this.entries.size >= MAX_NAMES) return;
806
+ e = { count: 0, first: now, last: now, keys: /* @__PURE__ */ new Set() };
807
+ this.entries.set(name, e);
808
+ }
809
+ e.count += 1;
810
+ e.last = Math.max(e.last, now);
811
+ for (const key of Object.keys(properties)) {
812
+ if (e.keys.size >= MAX_KEYS) break;
813
+ if (key && key.length <= MAX_KEY_LENGTH) e.keys.add(key);
814
+ }
815
+ }
816
+ /** Everything counted since the last drain, and a fresh window. */
817
+ drain() {
818
+ const out = [...this.entries].map(([name, e]) => ({
819
+ name,
820
+ count: e.count,
821
+ firstSeenAt: new Date(e.first).toISOString(),
822
+ lastSeenAt: new Date(e.last).toISOString(),
823
+ propertyKeys: [...e.keys]
824
+ }));
825
+ this.entries = /* @__PURE__ */ new Map();
826
+ return out;
827
+ }
828
+ };
829
+
830
+ // src/core/debug.ts
831
+ function debugKey(projectId, endUserId) {
832
+ return fnv1a32(`debug:${projectId}:${endUserId}`).toString(16).padStart(8, "0");
833
+ }
834
+ var MAX_PROPS = 30;
835
+ var MAX_STRING = 200;
836
+ function debugProperties(properties) {
837
+ const out = {};
838
+ for (const [k, v] of Object.entries(properties).slice(0, MAX_PROPS)) {
839
+ if (typeof v === "string") out[k] = v.length > MAX_STRING ? `${v.slice(0, MAX_STRING)}\u2026` : v;
840
+ else if (typeof v === "number" || typeof v === "boolean" || v === null) out[k] = v;
841
+ else if (Array.isArray(v)) out[k] = `[${v.length} items]`;
842
+ else if (typeof v === "object") out[k] = "{\u2026}";
843
+ }
844
+ return out;
845
+ }
846
+
847
+ // src/core/version.ts
848
+ var SDK_VERSION = "0.1.3";
849
+
698
850
  // src/core/client.ts
699
851
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
700
852
  var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
853
+ var EVENT_COUNTS_INTERVAL_MS = 60 * 1e3;
701
854
  var MicroSurveysClient = class {
702
855
  constructor(opts) {
703
856
  __publicField(this, "api");
@@ -711,6 +864,12 @@ var MicroSurveysClient = class {
711
864
  __publicField(this, "osVersion");
712
865
  __publicField(this, "appVersion");
713
866
  __publicField(this, "subscribeForeground");
867
+ __publicField(this, "subscribeBackground");
868
+ __publicField(this, "eventCounter", new EventCounter());
869
+ __publicField(this, "eventCountsTimer", null);
870
+ /** Decisions collected while one event is processed, for the live debugger. */
871
+ __publicField(this, "collecting", null);
872
+ __publicField(this, "unsubscribeBackground", null);
714
873
  __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
715
874
  __publicField(this, "configListeners", /* @__PURE__ */ new Set());
716
875
  __publicField(this, "active", null);
@@ -727,12 +886,14 @@ var MicroSurveysClient = class {
727
886
  this.osVersion = opts.osVersion;
728
887
  this.appVersion = opts.appVersion;
729
888
  this.subscribeForeground = opts.subscribeForeground;
889
+ this.subscribeBackground = opts.subscribeBackground;
730
890
  this.engine = new TriggerEngine({
731
891
  store: this.triggerStateStore,
732
892
  surveysProvider: () => this.configStore.surveys,
733
893
  identityProvider: () => this.identityStore.snapshot(),
734
894
  onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
735
- platform: opts.platform
895
+ platform: opts.platform,
896
+ onDecision: (d) => this.handleDecision(d)
736
897
  });
737
898
  }
738
899
  // ── Lifecycle ────────────────────────────────────────────────────────────────
@@ -749,10 +910,17 @@ var MicroSurveysClient = class {
749
910
  this.refreshConfigIfStale();
750
911
  });
751
912
  }
913
+ this.unsubscribeBackground = this.subscribeBackground?.(() => this.flushEventCounts()) ?? null;
914
+ this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
752
915
  }
753
916
  /** Tear down listeners + pending timers. */
754
917
  stop() {
755
918
  this.engine.stop();
919
+ this.flushEventCounts();
920
+ if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
921
+ this.eventCountsTimer = null;
922
+ this.unsubscribeBackground?.();
923
+ this.unsubscribeBackground = null;
756
924
  this.unsubscribeForeground?.();
757
925
  this.unsubscribeForeground = null;
758
926
  this.started = false;
@@ -779,7 +947,47 @@ var MicroSurveysClient = class {
779
947
  this.identityStore.setUser(userId, properties);
780
948
  }
781
949
  track(name, properties = {}) {
782
- this.engine.process(name, properties);
950
+ if (this.configStore.eventSignals) {
951
+ this.eventCounter.record(name, properties);
952
+ if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
953
+ }
954
+ if (!this.isDebugDevice()) {
955
+ this.engine.process(name, properties);
956
+ return;
957
+ }
958
+ this.collecting = [];
959
+ try {
960
+ this.engine.process(name, properties);
961
+ } finally {
962
+ const decisions = this.collecting;
963
+ this.collecting = null;
964
+ this.sendDebug(name, debugProperties(properties), decisions);
965
+ }
966
+ }
967
+ // ── Live debugger ────────────────────────────────────────────────────────────
968
+ /** True when the dashboard picked the current user as a test device. */
969
+ isDebugDevice() {
970
+ const users = this.configStore.debugUsers;
971
+ const projectId = this.configStore.projectId;
972
+ if (users.length === 0 || !projectId) return false;
973
+ return users.includes(debugKey(projectId, endUserIdOf(this.identityStore.snapshot())));
974
+ }
975
+ handleDecision(d) {
976
+ if (this.collecting) this.collecting.push(d);
977
+ else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
978
+ }
979
+ sendDebug(event, properties, decisions) {
980
+ const endUserId = endUserIdOf(this.identityStore.snapshot());
981
+ this.api.recordDebug(
982
+ { at: (/* @__PURE__ */ new Date()).toISOString(), event, properties, decisions },
983
+ endUserId,
984
+ { ...this.deviceContext(), sdkVersion: SDK_VERSION }
985
+ );
986
+ }
987
+ /** Uploads the events counted since the last upload (no-op when there are none). */
988
+ flushEventCounts() {
989
+ if (this.eventCounter.size === 0) return;
990
+ this.api.recordEventCounts(this.eventCounter.drain(), { ...this.deviceContext(), sdkVersion: SDK_VERSION });
783
991
  }
784
992
  /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
785
993
  * Its user/device id take precedence over `identify()` for `endUserId`. */
@@ -808,7 +1016,11 @@ var MicroSurveysClient = class {
808
1016
  return () => this.presentListeners.delete(cb);
809
1017
  }
810
1018
  handlePresent(survey, trigger, identity) {
811
- if (this.active && !this.active.closed) return;
1019
+ if (this.active && !this.active.closed) {
1020
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "another_survey_showing" });
1021
+ return;
1022
+ }
1023
+ this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "shown" });
812
1024
  const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
813
1025
  this.active = p;
814
1026
  const active = this.toActiveSurvey(p);
@@ -949,6 +1161,12 @@ function appStateForeground(onForeground) {
949
1161
  });
950
1162
  return () => sub.remove();
951
1163
  }
1164
+ function appStateBackground(onBackground) {
1165
+ const sub = import_react_native.AppState.addEventListener("change", (state) => {
1166
+ if (state === "background") onBackground();
1167
+ });
1168
+ return () => sub.remove();
1169
+ }
952
1170
  var MicroSurveys = class {
953
1171
  constructor(opts) {
954
1172
  __publicField(this, "apiKey");
@@ -969,7 +1187,8 @@ var MicroSurveys = class {
969
1187
  osVersion: String(import_react_native.Platform.Version),
970
1188
  appVersion: opts.appVersion,
971
1189
  storage: kv,
972
- subscribeForeground: appStateForeground
1190
+ subscribeForeground: appStateForeground,
1191
+ subscribeBackground: appStateBackground
973
1192
  });
974
1193
  this.client = client;
975
1194
  const queued = this.pending;