@microsurveysai/react-native 0.1.3 → 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 +157 -18
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +33 -3
- package/dist/index.d.ts +33 -3
- package/dist/index.js +157 -18
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -105,6 +105,12 @@ interface SDKConfig {
|
|
|
105
105
|
/** Hashes of the project's test devices for the live debugger (see debug.ts).
|
|
106
106
|
* Empty when none are set, or on older servers. */
|
|
107
107
|
debugUsers: string[];
|
|
108
|
+
/** The project has server events waiting to be picked up: check the mailbox
|
|
109
|
+
* (`POST /api/sdk/pending`). Absent on older servers, which means off. */
|
|
110
|
+
pendingEvents: boolean;
|
|
111
|
+
/** Trigger event names that arrive by server stream rather than from the app.
|
|
112
|
+
* A sequence waiting on one of them as its next step checks more often. */
|
|
113
|
+
serverEvents: string[];
|
|
108
114
|
}
|
|
109
115
|
/** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */
|
|
110
116
|
interface ProjectTheme {
|
|
@@ -193,7 +199,8 @@ interface CreateClientOptions {
|
|
|
193
199
|
/** Subscribes to "app came to the foreground"; returns an unsubscribe. */
|
|
194
200
|
subscribeForeground: (onForeground: () => void) => () => void;
|
|
195
201
|
/** Subscribes to "app went to the background"; returns an unsubscribe. Used
|
|
196
|
-
* to upload event counts before the app may be suspended
|
|
202
|
+
* to upload event counts before the app may be suspended, and to stop the
|
|
203
|
+
* server events mailbox timers. */
|
|
197
204
|
subscribeBackground?: (onBackground: () => void) => () => void;
|
|
198
205
|
}
|
|
199
206
|
/** An auto-triggered survey the host should present. Call `close` exactly once
|
|
@@ -223,14 +230,18 @@ declare class MicroSurveysClient {
|
|
|
223
230
|
/** Decisions collected while one event is processed, for the live debugger. */
|
|
224
231
|
private collecting;
|
|
225
232
|
private unsubscribeBackground;
|
|
233
|
+
/** Mailbox timers, cleared on background and stop. */
|
|
234
|
+
private pendingTimers;
|
|
235
|
+
private pendingIntervals;
|
|
236
|
+
private pendingInFlight;
|
|
226
237
|
private readonly presentListeners;
|
|
227
238
|
private readonly configListeners;
|
|
228
239
|
private active;
|
|
229
240
|
private started;
|
|
230
241
|
private unsubscribeForeground;
|
|
231
242
|
constructor(opts: CreateClientOptions);
|
|
232
|
-
/** Flush any queued ingest, refresh config,
|
|
233
|
-
*
|
|
243
|
+
/** Flush any queued ingest, refresh config, wire the foreground refresh
|
|
244
|
+
* (optional) and the server events mailbox checks. Safe to call once early. */
|
|
234
245
|
start(): void;
|
|
235
246
|
/** Tear down listeners + pending timers. */
|
|
236
247
|
stop(): void;
|
|
@@ -240,9 +251,28 @@ declare class MicroSurveysClient {
|
|
|
240
251
|
refreshConfigIfStale(): void;
|
|
241
252
|
identify(userId: string | null | undefined, properties?: Record<string, unknown>): void;
|
|
242
253
|
track(name: string, properties?: Record<string, unknown>): void;
|
|
254
|
+
/** Runs one event through the engine, reporting to the live debugger on test
|
|
255
|
+
* devices. `occurredAt` (ms epoch) is set for a replayed server event. */
|
|
256
|
+
private processEvent;
|
|
257
|
+
/** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while
|
|
258
|
+
* a sequence waits on a server event. Restarts the schedule; no-op unless the
|
|
259
|
+
* config has `pendingEvents`. */
|
|
260
|
+
private startPendingChecks;
|
|
261
|
+
private stopPendingChecks;
|
|
262
|
+
/** Fetches and replays this user's waiting server events. One request at a
|
|
263
|
+
* time; a full page is followed by one more call. Failures are silent: the
|
|
264
|
+
* next scheduled check retries. */
|
|
265
|
+
private checkPending;
|
|
266
|
+
/** Replays server events like `track`, oldest first, at the time each one
|
|
267
|
+
* happened. Not counted in event signals: the app didn't send them. */
|
|
268
|
+
private replayPending;
|
|
269
|
+
/** True while a SEQUENCE trigger for the current user has started and its next
|
|
270
|
+
* step's event arrives by server stream, up to 3 hours after it started. */
|
|
271
|
+
private isWaitingOnServerEvent;
|
|
243
272
|
/** True when the dashboard picked the current user as a test device. */
|
|
244
273
|
private isDebugDevice;
|
|
245
274
|
private handleDecision;
|
|
275
|
+
/** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */
|
|
246
276
|
private sendDebug;
|
|
247
277
|
/** Uploads the events counted since the last upload (no-op when there are none). */
|
|
248
278
|
flushEventCounts(): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -105,6 +105,12 @@ interface SDKConfig {
|
|
|
105
105
|
/** Hashes of the project's test devices for the live debugger (see debug.ts).
|
|
106
106
|
* Empty when none are set, or on older servers. */
|
|
107
107
|
debugUsers: string[];
|
|
108
|
+
/** The project has server events waiting to be picked up: check the mailbox
|
|
109
|
+
* (`POST /api/sdk/pending`). Absent on older servers, which means off. */
|
|
110
|
+
pendingEvents: boolean;
|
|
111
|
+
/** Trigger event names that arrive by server stream rather than from the app.
|
|
112
|
+
* A sequence waiting on one of them as its next step checks more often. */
|
|
113
|
+
serverEvents: string[];
|
|
108
114
|
}
|
|
109
115
|
/** Brand-level survey appearance (API-CONTRACT §Theme). All keys optional. */
|
|
110
116
|
interface ProjectTheme {
|
|
@@ -193,7 +199,8 @@ interface CreateClientOptions {
|
|
|
193
199
|
/** Subscribes to "app came to the foreground"; returns an unsubscribe. */
|
|
194
200
|
subscribeForeground: (onForeground: () => void) => () => void;
|
|
195
201
|
/** Subscribes to "app went to the background"; returns an unsubscribe. Used
|
|
196
|
-
* to upload event counts before the app may be suspended
|
|
202
|
+
* to upload event counts before the app may be suspended, and to stop the
|
|
203
|
+
* server events mailbox timers. */
|
|
197
204
|
subscribeBackground?: (onBackground: () => void) => () => void;
|
|
198
205
|
}
|
|
199
206
|
/** An auto-triggered survey the host should present. Call `close` exactly once
|
|
@@ -223,14 +230,18 @@ declare class MicroSurveysClient {
|
|
|
223
230
|
/** Decisions collected while one event is processed, for the live debugger. */
|
|
224
231
|
private collecting;
|
|
225
232
|
private unsubscribeBackground;
|
|
233
|
+
/** Mailbox timers, cleared on background and stop. */
|
|
234
|
+
private pendingTimers;
|
|
235
|
+
private pendingIntervals;
|
|
236
|
+
private pendingInFlight;
|
|
226
237
|
private readonly presentListeners;
|
|
227
238
|
private readonly configListeners;
|
|
228
239
|
private active;
|
|
229
240
|
private started;
|
|
230
241
|
private unsubscribeForeground;
|
|
231
242
|
constructor(opts: CreateClientOptions);
|
|
232
|
-
/** Flush any queued ingest, refresh config,
|
|
233
|
-
*
|
|
243
|
+
/** Flush any queued ingest, refresh config, wire the foreground refresh
|
|
244
|
+
* (optional) and the server events mailbox checks. Safe to call once early. */
|
|
234
245
|
start(): void;
|
|
235
246
|
/** Tear down listeners + pending timers. */
|
|
236
247
|
stop(): void;
|
|
@@ -240,9 +251,28 @@ declare class MicroSurveysClient {
|
|
|
240
251
|
refreshConfigIfStale(): void;
|
|
241
252
|
identify(userId: string | null | undefined, properties?: Record<string, unknown>): void;
|
|
242
253
|
track(name: string, properties?: Record<string, unknown>): void;
|
|
254
|
+
/** Runs one event through the engine, reporting to the live debugger on test
|
|
255
|
+
* devices. `occurredAt` (ms epoch) is set for a replayed server event. */
|
|
256
|
+
private processEvent;
|
|
257
|
+
/** Checks now, then 30 s and 90 s later, every 5 minutes, and every 60 s while
|
|
258
|
+
* a sequence waits on a server event. Restarts the schedule; no-op unless the
|
|
259
|
+
* config has `pendingEvents`. */
|
|
260
|
+
private startPendingChecks;
|
|
261
|
+
private stopPendingChecks;
|
|
262
|
+
/** Fetches and replays this user's waiting server events. One request at a
|
|
263
|
+
* time; a full page is followed by one more call. Failures are silent: the
|
|
264
|
+
* next scheduled check retries. */
|
|
265
|
+
private checkPending;
|
|
266
|
+
/** Replays server events like `track`, oldest first, at the time each one
|
|
267
|
+
* happened. Not counted in event signals: the app didn't send them. */
|
|
268
|
+
private replayPending;
|
|
269
|
+
/** True while a SEQUENCE trigger for the current user has started and its next
|
|
270
|
+
* step's event arrives by server stream, up to 3 hours after it started. */
|
|
271
|
+
private isWaitingOnServerEvent;
|
|
243
272
|
/** True when the dashboard picked the current user as a test device. */
|
|
244
273
|
private isDebugDevice;
|
|
245
274
|
private handleDecision;
|
|
275
|
+
/** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */
|
|
246
276
|
private sendDebug;
|
|
247
277
|
/** Uploads the events counted since the last upload (no-op when there are none). */
|
|
248
278
|
flushEventCounts(): void;
|
package/dist/index.js
CHANGED
|
@@ -193,12 +193,15 @@ function parseConfig(rawText) {
|
|
|
193
193
|
theme,
|
|
194
194
|
surveys,
|
|
195
195
|
eventSignals: root.eventSignals === true,
|
|
196
|
-
debugUsers: Array.isArray(root.debugUsers) ? root.debugUsers.filter((h) => typeof h === "string") : []
|
|
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") : []
|
|
197
199
|
};
|
|
198
200
|
}
|
|
199
201
|
|
|
200
202
|
// src/core/apiClient.ts
|
|
201
203
|
var API_VERSION = "2026-06-30";
|
|
204
|
+
var PENDING_PAGE_SIZE = 50;
|
|
202
205
|
var ApiClient = class {
|
|
203
206
|
constructor(apiKey, baseURL, storage) {
|
|
204
207
|
__publicField(this, "apiKey");
|
|
@@ -224,6 +227,36 @@ var ApiClient = class {
|
|
|
224
227
|
const rawText = await res.text();
|
|
225
228
|
return { kind: "config", rawText, config: parseConfig(rawText), etag: res.headers.get("ETag") };
|
|
226
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
|
+
}
|
|
227
260
|
// ── Impressions / responses ─────────────────────────────────────────────────
|
|
228
261
|
/** Queues the impression and returns its `clientId`, so the response from the
|
|
229
262
|
* same showing can point back to it. */
|
|
@@ -359,6 +392,12 @@ var ConfigStore = class {
|
|
|
359
392
|
get debugUsers() {
|
|
360
393
|
return this.parsed?.debugUsers ?? [];
|
|
361
394
|
}
|
|
395
|
+
get pendingEvents() {
|
|
396
|
+
return this.parsed?.pendingEvents ?? false;
|
|
397
|
+
}
|
|
398
|
+
get serverEvents() {
|
|
399
|
+
return this.parsed?.serverEvents ?? [];
|
|
400
|
+
}
|
|
362
401
|
get etag() {
|
|
363
402
|
return this.persisted?.etag ?? null;
|
|
364
403
|
}
|
|
@@ -566,6 +605,9 @@ function advance(trigger, record, eventName, properties, nowT) {
|
|
|
566
605
|
satisfied = matchesStep(0);
|
|
567
606
|
} else {
|
|
568
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
|
+
}
|
|
569
611
|
if (matchesStep(expected)) {
|
|
570
612
|
if (expected === 0) {
|
|
571
613
|
next.startedAt = nowT;
|
|
@@ -620,12 +662,15 @@ var TriggerEngine = class {
|
|
|
620
662
|
this.onDecision = opts.onDecision ?? (() => {
|
|
621
663
|
});
|
|
622
664
|
}
|
|
623
|
-
/** Feed an event into the engine.
|
|
624
|
-
|
|
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) {
|
|
625
669
|
const identity = this.identityProvider();
|
|
626
670
|
const endUserId = endUserIdOf(identity);
|
|
627
671
|
const state = this.store.load(endUserId);
|
|
628
672
|
const nowT = this.now();
|
|
673
|
+
const atT = eventT ?? nowT;
|
|
629
674
|
for (const survey of this.surveysProvider()) {
|
|
630
675
|
const triggers = survey.triggers;
|
|
631
676
|
if (!triggers || triggers.length === 0) continue;
|
|
@@ -636,7 +681,7 @@ var TriggerEngine = class {
|
|
|
636
681
|
continue;
|
|
637
682
|
}
|
|
638
683
|
for (const trigger of triggers) {
|
|
639
|
-
const satisfied = this.advanceTrigger(trigger, state, name, properties,
|
|
684
|
+
const satisfied = this.advanceTrigger(trigger, state, name, properties, atT);
|
|
640
685
|
const skip = (reason) => this.onDecision({ surveyId: survey.id, triggerId: trigger.id, reason });
|
|
641
686
|
if (!satisfied) {
|
|
642
687
|
if (names(trigger)) {
|
|
@@ -804,12 +849,16 @@ function debugProperties(properties) {
|
|
|
804
849
|
}
|
|
805
850
|
|
|
806
851
|
// src/core/version.ts
|
|
807
|
-
var SDK_VERSION = "0.1.
|
|
852
|
+
var SDK_VERSION = "0.1.4";
|
|
808
853
|
|
|
809
854
|
// src/core/client.ts
|
|
810
855
|
var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
|
|
811
856
|
var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
|
|
812
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;
|
|
813
862
|
var MicroSurveysClient = class {
|
|
814
863
|
constructor(opts) {
|
|
815
864
|
__publicField(this, "api");
|
|
@@ -829,6 +878,10 @@ var MicroSurveysClient = class {
|
|
|
829
878
|
/** Decisions collected while one event is processed, for the live debugger. */
|
|
830
879
|
__publicField(this, "collecting", null);
|
|
831
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);
|
|
832
885
|
__publicField(this, "presentListeners", /* @__PURE__ */ new Set());
|
|
833
886
|
__publicField(this, "configListeners", /* @__PURE__ */ new Set());
|
|
834
887
|
__publicField(this, "active", null);
|
|
@@ -856,20 +909,26 @@ var MicroSurveysClient = class {
|
|
|
856
909
|
});
|
|
857
910
|
}
|
|
858
911
|
// ── Lifecycle ────────────────────────────────────────────────────────────────
|
|
859
|
-
/** Flush any queued ingest, refresh config,
|
|
860
|
-
*
|
|
912
|
+
/** Flush any queued ingest, refresh config, wire the foreground refresh
|
|
913
|
+
* (optional) and the server events mailbox checks. Safe to call once early. */
|
|
861
914
|
start() {
|
|
862
915
|
if (this.started) return;
|
|
863
916
|
this.started = true;
|
|
864
917
|
void this.api.flush();
|
|
865
|
-
void this.refreshConfig()
|
|
866
|
-
|
|
867
|
-
|
|
918
|
+
void this.refreshConfig().then(() => {
|
|
919
|
+
if (this.started) this.startPendingChecks();
|
|
920
|
+
});
|
|
921
|
+
this.unsubscribeForeground = this.subscribeForeground(() => {
|
|
922
|
+
if (this.refreshOnForeground) {
|
|
868
923
|
void this.api.flush();
|
|
869
924
|
this.refreshConfigIfStale();
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
|
|
925
|
+
}
|
|
926
|
+
this.startPendingChecks();
|
|
927
|
+
});
|
|
928
|
+
this.unsubscribeBackground = this.subscribeBackground?.(() => {
|
|
929
|
+
this.flushEventCounts();
|
|
930
|
+
this.stopPendingChecks();
|
|
931
|
+
}) ?? null;
|
|
873
932
|
this.eventCountsTimer = setInterval(() => this.flushEventCounts(), EVENT_COUNTS_INTERVAL_MS);
|
|
874
933
|
}
|
|
875
934
|
/** Tear down listeners + pending timers. */
|
|
@@ -878,6 +937,7 @@ var MicroSurveysClient = class {
|
|
|
878
937
|
this.flushEventCounts();
|
|
879
938
|
if (this.eventCountsTimer) clearInterval(this.eventCountsTimer);
|
|
880
939
|
this.eventCountsTimer = null;
|
|
940
|
+
this.stopPendingChecks();
|
|
881
941
|
this.unsubscribeBackground?.();
|
|
882
942
|
this.unsubscribeBackground = null;
|
|
883
943
|
this.unsubscribeForeground?.();
|
|
@@ -910,18 +970,96 @@ var MicroSurveysClient = class {
|
|
|
910
970
|
this.eventCounter.record(name, properties);
|
|
911
971
|
if (this.eventCounter.size >= MAX_NAMES) this.flushEventCounts();
|
|
912
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;
|
|
913
979
|
if (!this.isDebugDevice()) {
|
|
914
|
-
this.engine.process(name, properties);
|
|
980
|
+
this.engine.process(name, properties, eventT);
|
|
915
981
|
return;
|
|
916
982
|
}
|
|
917
983
|
this.collecting = [];
|
|
918
984
|
try {
|
|
919
|
-
this.engine.process(name, properties);
|
|
985
|
+
this.engine.process(name, properties, eventT);
|
|
920
986
|
} finally {
|
|
921
987
|
const decisions = this.collecting;
|
|
922
988
|
this.collecting = null;
|
|
923
|
-
this.sendDebug(name, debugProperties(properties), decisions);
|
|
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
|
+
}
|
|
924
1061
|
}
|
|
1062
|
+
return false;
|
|
925
1063
|
}
|
|
926
1064
|
// ── Live debugger ────────────────────────────────────────────────────────────
|
|
927
1065
|
/** True when the dashboard picked the current user as a test device. */
|
|
@@ -935,10 +1073,11 @@ var MicroSurveysClient = class {
|
|
|
935
1073
|
if (this.collecting) this.collecting.push(d);
|
|
936
1074
|
else if (this.isDebugDevice()) this.sendDebug(null, {}, [d]);
|
|
937
1075
|
}
|
|
938
|
-
|
|
1076
|
+
/** `at` (ms epoch) defaults to now; a replayed server event passes its `occurredAt`. */
|
|
1077
|
+
sendDebug(event, properties, decisions, at) {
|
|
939
1078
|
const endUserId = endUserIdOf(this.identityStore.snapshot());
|
|
940
1079
|
this.api.recordDebug(
|
|
941
|
-
{ at: (
|
|
1080
|
+
{ at: new Date(at ?? Date.now()).toISOString(), event, properties, decisions },
|
|
942
1081
|
endUserId,
|
|
943
1082
|
{ ...this.deviceContext(), sdkVersion: SDK_VERSION }
|
|
944
1083
|
);
|