@microsurveysai/react-native 0.1.6 → 0.1.7

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/README.md CHANGED
@@ -59,7 +59,7 @@ import { MicroSurvey } from "@microsurveysai/react-native";
59
59
  | --- | --- | --- |
60
60
  | `apiKey` | — | Your project API key. |
61
61
  | `apiBaseURL` | `https://console.microsurveys.ai` | For self-hosted deployments. |
62
- | `refreshOnForeground` | `true` | On app foreground, retry queued ingest and refresh a stale config. |
62
+ | `refreshOnForeground` | `true` | On app foreground, refresh a stale config. (Queued impressions and responses are retried on every foreground, and every few seconds while offline, either way.) |
63
63
  | `configTTLms` | 12h | How long the cached config counts as fresh. |
64
64
  | `storage` | AsyncStorage | A synchronous store (e.g. MMKV) to persist into instead. |
65
65
  | `appVersion` | — | Your app's version (e.g. `"3.2.0"`), sent with responses so results can be compared across releases. With Expo, pass `Application.nativeApplicationVersion` from `expo-application`. |
package/dist/index.cjs CHANGED
@@ -250,12 +250,24 @@ function parseConfig(rawText) {
250
250
  // src/core/apiClient.ts
251
251
  var API_VERSION = "2026-06-30";
252
252
  var PENDING_PAGE_SIZE = 50;
253
+ var RETRY_BASE_MS = 2e3;
254
+ var RETRY_MAX_MS = 3e4;
255
+ var INGEST_TIMEOUT_MS = 15e3;
253
256
  var ApiClient = class {
254
257
  constructor(apiKey, baseURL, storage) {
255
258
  __publicField(this, "apiKey");
256
259
  __publicField(this, "baseURL");
257
260
  __publicField(this, "outbox");
258
261
  __publicField(this, "isFlushing", false);
262
+ /** The flush in progress, returned to callers that ask for another meanwhile. */
263
+ __publicField(this, "flushPromise", Promise.resolve());
264
+ /** Set when flush() is called during a flush: run another pass before finishing. */
265
+ __publicField(this, "flushAgain", false);
266
+ __publicField(this, "retryTimer", null);
267
+ /** Failed flushes in a row, for the retry backoff. */
268
+ __publicField(this, "failures", 0);
269
+ /** After `cancelRetry()`: no new retry timers until the next `resumeRetry()`. */
270
+ __publicField(this, "retryStopped", false);
259
271
  this.apiKey = apiKey;
260
272
  this.outbox = new Outbox(storage);
261
273
  this.baseURL = baseURL.replace(/\/+$/, "");
@@ -307,9 +319,11 @@ var ApiClient = class {
307
319
  }
308
320
  // ── Impressions / responses ─────────────────────────────────────────────────
309
321
  /** Queues the impression and returns its `clientId`, so the response from the
310
- * same showing can point back to it. */
322
+ * same showing can point back to it. Pass the `clientId` to send the same
323
+ * impression again (e.g. with `dismissed: true` once the user dismissed it):
324
+ * the server updates the one it has. */
311
325
  recordImpression(input) {
312
- const clientId = uuid();
326
+ const clientId = input.clientId ?? uuid();
313
327
  const payload = {
314
328
  clientId,
315
329
  surveyId: input.surveyId,
@@ -355,46 +369,94 @@ var ApiClient = class {
355
369
  }
356
370
  // ── Flush ────────────────────────────────────────────────────────────────────
357
371
  /** POSTs queued entries in order. Stops at the first retryable failure (likely
358
- * offline) and leaves the rest for next time. Entries queued while a flush is
359
- * running are sent by the same flush, so nothing waits for the next event.
360
- * Idempotency keys make re-sends safe. Never throws. */
361
- async flush() {
362
- if (this.isFlushing) return;
372
+ * offline) and schedules a retry (2 s, doubling, capped at 30 s). Entries
373
+ * queued while a flush is running are sent by the same flush, so nothing waits
374
+ * for the next event. Idempotency keys make re-sends safe. Resolves when the
375
+ * flush in progress is done; never throws. */
376
+ flush() {
377
+ if (this.isFlushing) {
378
+ this.flushAgain = true;
379
+ return this.flushPromise;
380
+ }
363
381
  this.isFlushing = true;
382
+ this.clearRetryTimer();
383
+ this.flushPromise = this.runFlush();
384
+ return this.flushPromise;
385
+ }
386
+ /** Stops retrying (the client is stopping). Queued entries stay for later. */
387
+ cancelRetry() {
388
+ this.retryStopped = true;
389
+ this.clearRetryTimer();
390
+ }
391
+ /** Allows retries again after `cancelRetry()`. */
392
+ resumeRetry() {
393
+ this.retryStopped = false;
394
+ }
395
+ async runFlush() {
396
+ let failed = false;
397
+ const sent = /* @__PURE__ */ new Set();
364
398
  try {
365
- const sent = /* @__PURE__ */ new Set();
366
- for (; ; ) {
367
- const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
368
- if (pending.length === 0) break;
369
- let failed = false;
370
- for (const entry of pending) {
371
- try {
372
- await this.post(entry.path, entry.body);
373
- this.outbox.remove(entry.id);
374
- sent.add(entry.id);
375
- } catch {
376
- failed = true;
377
- break;
399
+ do {
400
+ this.flushAgain = false;
401
+ for (; ; ) {
402
+ const pending = this.outbox.snapshot().filter((e) => !sent.has(e.id));
403
+ if (pending.length === 0) break;
404
+ for (const entry of pending) {
405
+ try {
406
+ await this.post(entry.path, entry.body);
407
+ this.outbox.remove(entry.id);
408
+ sent.add(entry.id);
409
+ } catch {
410
+ failed = true;
411
+ break;
412
+ }
378
413
  }
414
+ if (failed) break;
379
415
  }
380
- if (failed) break;
381
- }
416
+ } while (!failed && this.flushAgain);
382
417
  } finally {
418
+ this.flushAgain = false;
383
419
  this.isFlushing = false;
384
420
  }
421
+ if (failed) {
422
+ this.failures += 1;
423
+ this.scheduleRetry();
424
+ } else {
425
+ this.failures = 0;
426
+ }
427
+ }
428
+ /** One pending retry at most. */
429
+ scheduleRetry() {
430
+ if (this.retryStopped || this.retryTimer) return;
431
+ const delay = Math.min(RETRY_BASE_MS * 2 ** Math.max(0, this.failures - 1), RETRY_MAX_MS);
432
+ this.retryTimer = setTimeout(() => {
433
+ this.retryTimer = null;
434
+ void this.flush();
435
+ }, delay);
436
+ }
437
+ clearRetryTimer() {
438
+ if (this.retryTimer) clearTimeout(this.retryTimer);
439
+ this.retryTimer = null;
385
440
  }
386
441
  async post(path, body) {
387
- const res = await fetch(this.endpoint(path), {
388
- method: "POST",
389
- headers: {
390
- Authorization: `Bearer ${this.apiKey}`,
391
- "MS-Api-Version": API_VERSION,
392
- "Content-Type": "application/json; charset=utf-8"
393
- },
394
- body
395
- });
396
- if (res.status === 429 || res.status >= 500 && res.status < 600) {
397
- throw new Error(`retryable ${res.status}`);
442
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
443
+ const timeout = controller ? setTimeout(() => controller.abort(), INGEST_TIMEOUT_MS) : null;
444
+ try {
445
+ const res = await fetch(this.endpoint(path), {
446
+ method: "POST",
447
+ headers: {
448
+ Authorization: `Bearer ${this.apiKey}`,
449
+ "MS-Api-Version": API_VERSION,
450
+ "Content-Type": "application/json; charset=utf-8"
451
+ },
452
+ body,
453
+ signal: controller?.signal
454
+ });
455
+ if (res.status === 429 || res.status >= 500 && res.status < 600) {
456
+ throw new Error(`retryable ${res.status}`);
457
+ }
458
+ } finally {
459
+ if (timeout) clearTimeout(timeout);
398
460
  }
399
461
  }
400
462
  endpoint(path) {
@@ -897,7 +959,7 @@ function debugProperties(properties) {
897
959
  }
898
960
 
899
961
  // src/core/version.ts
900
- var SDK_VERSION = "0.1.6";
962
+ var SDK_VERSION = "0.1.7";
901
963
 
902
964
  // src/core/client.ts
903
965
  var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
@@ -962,15 +1024,14 @@ var MicroSurveysClient = class {
962
1024
  start() {
963
1025
  if (this.started) return;
964
1026
  this.started = true;
1027
+ this.api.resumeRetry();
965
1028
  void this.api.flush();
966
1029
  void this.refreshConfig().then(() => {
967
1030
  if (this.started) this.startPendingChecks();
968
1031
  });
969
1032
  this.unsubscribeForeground = this.subscribeForeground(() => {
970
- if (this.refreshOnForeground) {
971
- void this.api.flush();
972
- this.refreshConfigIfStale();
973
- }
1033
+ void this.api.flush();
1034
+ if (this.refreshOnForeground) this.refreshConfigIfStale();
974
1035
  this.startPendingChecks();
975
1036
  });
976
1037
  this.unsubscribeBackground = this.subscribeBackground?.(() => {
@@ -990,6 +1051,7 @@ var MicroSurveysClient = class {
990
1051
  this.unsubscribeBackground = null;
991
1052
  this.unsubscribeForeground?.();
992
1053
  this.unsubscribeForeground = null;
1054
+ this.api.cancelRetry();
993
1055
  this.started = false;
994
1056
  }
995
1057
  /** Force an ETag-aware config refresh; keeps the cache on failure. */
@@ -1167,49 +1229,81 @@ var MicroSurveysClient = class {
1167
1229
  return;
1168
1230
  }
1169
1231
  this.handleDecision({ surveyId: survey.id, triggerId: trigger.id, reason: "shown" });
1170
- const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
1232
+ const p = this.newPresentation(survey, trigger, identity);
1171
1233
  this.active = p;
1172
1234
  const active = this.toActiveSurvey(p);
1173
1235
  this.presentListeners.forEach((l) => l(active));
1174
1236
  }
1237
+ newPresentation(survey, trigger, identity) {
1238
+ return { survey, trigger, identity, impressionId: uuid(), presentedAt: /* @__PURE__ */ new Date(), impression: null, closed: false };
1239
+ }
1175
1240
  toActiveSurvey(p) {
1176
1241
  return {
1177
1242
  survey: p.survey,
1178
1243
  trigger: p.trigger,
1244
+ shown: () => this.markShown(p),
1179
1245
  close: (result) => {
1180
1246
  if (p.closed) return;
1181
1247
  p.closed = true;
1182
- this.recordOutcome(p.survey.id, p.trigger?.id ?? null, p.identity, p.shownAt, result);
1183
1248
  if (this.active === p) this.active = null;
1249
+ if (result) this.recordOutcome(p, result);
1184
1250
  }
1185
1251
  };
1186
1252
  }
1187
- /** Records the outcome of an **inline** `<MicroSurvey>` (no trigger/gate). */
1188
- recordInline(survey, result, shownAt) {
1189
- const identity = this.identityStore.snapshot();
1190
- this.recordOutcome(survey.id, null, identity, shownAt, result);
1253
+ /** Queues the impression the moment the survey is on screen, so it counts even
1254
+ * if the app is killed before the survey closes. */
1255
+ markShown(p) {
1256
+ if (p.impression || p.closed) return;
1257
+ p.impression = {
1258
+ clientId: p.impressionId,
1259
+ surveyId: p.survey.id,
1260
+ triggerId: p.trigger?.id ?? null,
1261
+ endUserId: endUserIdOf(p.identity),
1262
+ shownAt: /* @__PURE__ */ new Date(),
1263
+ dismissed: false,
1264
+ context: this.deviceContext()
1265
+ };
1266
+ this.api.recordImpression(p.impression);
1191
1267
  }
1192
- recordOutcome(surveyId, triggerId, identity, shownAt, result) {
1193
- const endUserId = endUserIdOf(identity);
1194
- const context = this.deviceContext();
1195
- const impressionId = this.api.recordImpression({
1196
- surveyId,
1197
- triggerId,
1198
- endUserId,
1199
- shownAt,
1200
- dismissed: result.dismissed,
1201
- context
1202
- });
1268
+ /** An **inline** `<MicroSurvey>` (no trigger, no gate, not "the" active survey).
1269
+ * Call `shown` when it renders and `close` with its outcome. */
1270
+ presentInline(survey) {
1271
+ return this.toActiveSurvey(this.newPresentation(survey, null, this.identityStore.snapshot()));
1272
+ }
1273
+ /** Records the outcome of an inline survey in one go, at close. Prefer
1274
+ * `presentInline`, which sends the impression when the survey appears. */
1275
+ recordInline(survey, result, shownAt) {
1276
+ const p = this.newPresentation(survey, null, this.identityStore.snapshot());
1277
+ p.presentedAt = shownAt;
1278
+ p.closed = true;
1279
+ this.recordOutcome(p, result);
1280
+ }
1281
+ recordOutcome(p, result) {
1282
+ let impression = p.impression;
1283
+ if (!impression) {
1284
+ impression = {
1285
+ clientId: p.impressionId,
1286
+ surveyId: p.survey.id,
1287
+ triggerId: p.trigger?.id ?? null,
1288
+ endUserId: endUserIdOf(p.identity),
1289
+ shownAt: p.presentedAt,
1290
+ dismissed: result.dismissed,
1291
+ context: this.deviceContext()
1292
+ };
1293
+ this.api.recordImpression(impression);
1294
+ } else if (result.dismissed) {
1295
+ this.api.recordImpression({ ...impression, dismissed: true });
1296
+ }
1203
1297
  if (result.completed || result.answers.length > 0) {
1204
1298
  this.api.recordResponse({
1205
- surveyId,
1206
- endUserId,
1299
+ surveyId: p.survey.id,
1300
+ endUserId: impression.endUserId,
1207
1301
  completed: result.completed,
1208
1302
  submittedAt: /* @__PURE__ */ new Date(),
1209
- userProps: identity.userProperties,
1210
- impressionId,
1211
- triggerId,
1212
- context,
1303
+ userProps: p.identity.userProperties,
1304
+ impressionId: p.impressionId,
1305
+ triggerId: p.trigger?.id ?? null,
1306
+ context: impression.context,
1213
1307
  answers: result.answers
1214
1308
  });
1215
1309
  }
@@ -1419,7 +1513,23 @@ var MicroSurveys = class {
1419
1513
  unsubscribe?.();
1420
1514
  };
1421
1515
  }
1422
- /** Records the outcome of an inline `<MicroSurvey>`. */
1516
+ /** Starts one showing of an inline `<MicroSurvey>`: call `shown` once it
1517
+ * renders (sends the impression) and `close` with its outcome. */
1518
+ presentInline(survey) {
1519
+ let inner = null;
1520
+ const withShowing = (fn) => this.withClient((c) => {
1521
+ inner ?? (inner = c.presentInline(survey));
1522
+ fn(inner);
1523
+ });
1524
+ return {
1525
+ survey,
1526
+ trigger: null,
1527
+ shown: () => withShowing((s) => s.shown()),
1528
+ close: (result) => withShowing((s) => s.close(result))
1529
+ };
1530
+ }
1531
+ /** Records the outcome of an inline survey in one go, at close. Prefer
1532
+ * `presentInline`, which sends the impression when the survey appears. */
1423
1533
  recordInline(survey, result, shownAt) {
1424
1534
  this.withClient((c) => c.recordInline(survey, result, shownAt));
1425
1535
  }
@@ -2255,7 +2365,11 @@ function OverlayHost({ instance, fontFamily }) {
2255
2365
  }),
2256
2366
  [instance]
2257
2367
  );
2368
+ (0, import_react4.useEffect)(() => {
2369
+ current?.active.shown();
2370
+ }, [current]);
2258
2371
  function showNext() {
2372
+ current?.active.close();
2259
2373
  const next = queue.current.shift();
2260
2374
  if (next) {
2261
2375
  setCurrent({ active: next, id: nextId.current++ });
@@ -2301,7 +2415,7 @@ function MicroSurvey({ surveyId, onComplete, style }) {
2301
2415
  const scheme = (0, import_react_native7.useColorScheme)() === "dark" ? "dark" : "light";
2302
2416
  const [survey, setSurvey] = (0, import_react5.useState)(null);
2303
2417
  const [closed, setClosed] = (0, import_react5.useState)(false);
2304
- const shownAt = (0, import_react5.useRef)(null);
2418
+ const showing = (0, import_react5.useRef)(null);
2305
2419
  const result = (0, import_react5.useRef)(null);
2306
2420
  (0, import_react5.useEffect)(() => {
2307
2421
  if (!instance) return;
@@ -2309,8 +2423,14 @@ function MicroSurvey({ surveyId, onComplete, style }) {
2309
2423
  }, [instance, surveyId]);
2310
2424
  const projectTheme = instance?.getTheme();
2311
2425
  const theme = (0, import_react5.useMemo)(() => resolveTheme(projectTheme, { scheme, fontFamily }), [projectTheme, scheme, fontFamily]);
2426
+ const visible = !!instance && !!survey && !closed;
2427
+ if (visible && (!showing.current || showing.current.survey.id !== survey.id)) {
2428
+ showing.current = instance.presentInline(survey);
2429
+ }
2430
+ (0, import_react5.useEffect)(() => {
2431
+ if (visible) showing.current?.shown();
2432
+ }, [visible, survey]);
2312
2433
  if (!instance || !survey || closed) return null;
2313
- if (!shownAt.current) shownAt.current = /* @__PURE__ */ new Date();
2314
2434
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2315
2435
  import_react_native7.View,
2316
2436
  {
@@ -2326,7 +2446,7 @@ function MicroSurvey({ surveyId, onComplete, style }) {
2326
2446
  variant: "inline",
2327
2447
  onResult: (r) => {
2328
2448
  result.current = r;
2329
- instance.recordInline(survey, r, shownAt.current ?? /* @__PURE__ */ new Date());
2449
+ showing.current?.close(r);
2330
2450
  },
2331
2451
  onClose: () => {
2332
2452
  setClosed(true);