@microsurveysai/react-native 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,1957 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/MicroSurveys.ts
6
+ import AsyncStorage from "@react-native-async-storage/async-storage";
7
+ import { AppState, Platform } from "react-native";
8
+
9
+ // src/core/storage.ts
10
+ var STORAGE_KEY_PREFIX = "com.microsurveys.";
11
+ function uuid() {
12
+ try {
13
+ const crypto = globalThis.crypto;
14
+ if (crypto && typeof crypto.randomUUID === "function") {
15
+ return crypto.randomUUID();
16
+ }
17
+ } catch {
18
+ }
19
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
20
+ const r = Math.random() * 16 | 0;
21
+ const v = c === "x" ? r : r & 3 | 8;
22
+ return v.toString(16);
23
+ });
24
+ }
25
+
26
+ // src/core/outbox.ts
27
+ var KEY = "com.microsurveys.outbox";
28
+ var MAX_ENTRIES = 200;
29
+ var Outbox = class {
30
+ constructor(kv) {
31
+ __publicField(this, "kv", kv);
32
+ }
33
+ read() {
34
+ const data = this.kv.getItem(KEY);
35
+ if (!data) return [];
36
+ try {
37
+ const parsed = JSON.parse(data);
38
+ return Array.isArray(parsed) ? parsed : [];
39
+ } catch {
40
+ return [];
41
+ }
42
+ }
43
+ write(entries) {
44
+ this.kv.setItem(KEY, JSON.stringify(entries));
45
+ }
46
+ enqueue(path, body) {
47
+ const entries = this.read();
48
+ entries.push({ id: uuid(), path, body });
49
+ if (entries.length > MAX_ENTRIES) entries.splice(0, entries.length - MAX_ENTRIES);
50
+ this.write(entries);
51
+ }
52
+ snapshot() {
53
+ return this.read();
54
+ }
55
+ remove(id) {
56
+ this.write(this.read().filter((e) => e.id !== id));
57
+ }
58
+ };
59
+
60
+ // src/core/types.ts
61
+ function endUserIdOf(identity) {
62
+ return identity.amplitudeUserId ?? identity.amplitudeDeviceId ?? identity.hostUserId ?? identity.anonymousId;
63
+ }
64
+ function newTriggerRecord() {
65
+ return { stepIndex: 0, startedAt: null, satisfiedCount: 0 };
66
+ }
67
+ function newUserTriggerState() {
68
+ return { triggers: {}, surveys: {} };
69
+ }
70
+ function asObject(v) {
71
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
72
+ }
73
+ function numOr(v, fallback) {
74
+ return typeof v === "number" && Number.isFinite(v) ? v : fallback;
75
+ }
76
+ function strOrUndef(v) {
77
+ return typeof v === "string" ? v : void 0;
78
+ }
79
+ function normalizeConfig(type, raw) {
80
+ switch (type) {
81
+ case "NPS":
82
+ return { kind: "scale", min: numOr(raw.min, 0), max: numOr(raw.max, 10), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
83
+ case "CES":
84
+ return { kind: "scale", min: numOr(raw.min, 1), max: numOr(raw.max, 7), minLabel: strOrUndef(raw.minLabel), maxLabel: strOrUndef(raw.maxLabel) };
85
+ case "CSAT_STAR":
86
+ return { kind: "stars", count: numOr(raw.count, 5) };
87
+ case "CSAT_EMOJI": {
88
+ const opts = Array.isArray(raw.options) ? raw.options : [];
89
+ const options = opts.map((o) => {
90
+ const oo = asObject(o);
91
+ return { value: String(oo.value ?? ""), emoji: typeof oo.emoji === "string" ? oo.emoji : "", label: strOrUndef(oo.label) };
92
+ });
93
+ return { kind: "emoji", options };
94
+ }
95
+ case "THUMBS":
96
+ return { kind: "thumbs" };
97
+ case "SINGLE_CHOICE": {
98
+ const opts = Array.isArray(raw.options) ? raw.options : [];
99
+ const options = opts.map((o) => {
100
+ const oo = asObject(o);
101
+ const value = String(oo.value ?? "");
102
+ return { value, label: typeof oo.label === "string" ? oo.label : value };
103
+ });
104
+ return { kind: "singleChoice", options };
105
+ }
106
+ case "OPEN_TEXT":
107
+ return { kind: "openText", placeholder: strOrUndef(raw.placeholder), maxLength: typeof raw.maxLength === "number" ? raw.maxLength : void 0 };
108
+ }
109
+ }
110
+ function normalizeQuestion(raw) {
111
+ const id = strOrUndef(raw.id);
112
+ const type = strOrUndef(raw.type);
113
+ const prompt = strOrUndef(raw.prompt);
114
+ if (!id || !type || prompt === void 0) return null;
115
+ return {
116
+ id,
117
+ order: numOr(raw.order, 0),
118
+ type,
119
+ prompt,
120
+ required: raw.required === true,
121
+ config: normalizeConfig(type, asObject(raw.config))
122
+ };
123
+ }
124
+ function normalizeTrigger(raw) {
125
+ const id = strOrUndef(raw.id);
126
+ if (!id) return null;
127
+ const type = raw.type === "SEQUENCE" ? "SEQUENCE" : "SINGLE";
128
+ const steps = (Array.isArray(raw.steps) ? raw.steps : []).map((s) => {
129
+ const so = asObject(s);
130
+ const event = strOrUndef(so.event);
131
+ if (!event) return null;
132
+ return { order: numOr(so.order, 0), event, match: asObject(so.match) };
133
+ }).filter((s) => s !== null);
134
+ return {
135
+ id,
136
+ type,
137
+ delaySeconds: numOr(raw.delaySeconds, 0),
138
+ sequenceWindowSeconds: typeof raw.sequenceWindowSeconds === "number" ? raw.sequenceWindowSeconds : null,
139
+ fireEvery: numOr(raw.fireEvery, 1),
140
+ warmupCount: numOr(raw.warmupCount, 0),
141
+ steps
142
+ };
143
+ }
144
+ function normalizeSurvey(raw) {
145
+ const id = strOrUndef(raw.id);
146
+ const name = strOrUndef(raw.name);
147
+ if (!id || name === void 0) return null;
148
+ const questions = (Array.isArray(raw.questions) ? raw.questions : []).map((q) => normalizeQuestion(asObject(q))).filter((q) => q !== null);
149
+ const triggers = (Array.isArray(raw.triggers) ? raw.triggers : []).map((t) => normalizeTrigger(asObject(t))).filter((t) => t !== null);
150
+ return {
151
+ id,
152
+ name,
153
+ questions,
154
+ audienceMatch: raw.audienceMatch ?? null,
155
+ samplePercent: typeof raw.samplePercent === "number" ? raw.samplePercent : null,
156
+ maxPerUserDays: typeof raw.maxPerUserDays === "number" ? raw.maxPerUserDays : null,
157
+ startsAt: strOrUndef(raw.startsAt) ?? null,
158
+ endsAt: strOrUndef(raw.endsAt) ?? null,
159
+ triggers,
160
+ dismissible: typeof raw.dismissible === "boolean" ? raw.dismissible : null,
161
+ presentation: strOrUndef(raw.presentation) ?? null,
162
+ successMessage: strOrUndef(raw.successMessage) ?? null,
163
+ platforms: Array.isArray(raw.platforms) ? raw.platforms.filter((p) => typeof p === "string") : null
164
+ };
165
+ }
166
+ function parseConfig(rawText) {
167
+ let root;
168
+ try {
169
+ root = asObject(JSON.parse(rawText));
170
+ } catch {
171
+ return null;
172
+ }
173
+ const projectId = strOrUndef(root.projectId);
174
+ if (!projectId) return null;
175
+ const surveys = (Array.isArray(root.surveys) ? root.surveys : []).map((s) => normalizeSurvey(asObject(s))).filter((s) => s !== null);
176
+ 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 };
178
+ }
179
+
180
+ // src/core/apiClient.ts
181
+ var API_VERSION = "2026-06-30";
182
+ var ApiClient = class {
183
+ constructor(apiKey, baseURL, storage) {
184
+ __publicField(this, "apiKey");
185
+ __publicField(this, "baseURL");
186
+ __publicField(this, "outbox");
187
+ __publicField(this, "isFlushing", false);
188
+ this.apiKey = apiKey;
189
+ this.outbox = new Outbox(storage);
190
+ this.baseURL = baseURL.replace(/\/+$/, "");
191
+ }
192
+ // ── Config ─────────────────────────────────────────────────────────────────
193
+ /** `GET /api/sdk/config` with optional `If-None-Match`. Resolves `notModified`
194
+ * on 304 so the caller keeps its cache. Throws on network/5xx errors. */
195
+ async fetchConfig(etag) {
196
+ const headers = {
197
+ Authorization: `Bearer ${this.apiKey}`,
198
+ "MS-Api-Version": API_VERSION
199
+ };
200
+ if (etag) headers["If-None-Match"] = etag;
201
+ const res = await fetch(this.endpoint("/api/sdk/config"), { method: "GET", headers });
202
+ if (res.status === 304) return { kind: "notModified" };
203
+ if (!res.ok) throw new Error(`config fetch failed: ${res.status}`);
204
+ const rawText = await res.text();
205
+ return { kind: "config", rawText, config: parseConfig(rawText), etag: res.headers.get("ETag") };
206
+ }
207
+ // ── Impressions / responses ─────────────────────────────────────────────────
208
+ /** Queues the impression and returns its `clientId`, so the response from the
209
+ * same showing can point back to it. */
210
+ recordImpression(input) {
211
+ const clientId = uuid();
212
+ const payload = {
213
+ clientId,
214
+ surveyId: input.surveyId,
215
+ triggerId: input.triggerId ?? void 0,
216
+ endUserId: input.endUserId,
217
+ shownAt: input.shownAt.toISOString(),
218
+ dismissed: input.dismissed,
219
+ context: input.context
220
+ };
221
+ this.enqueue("/api/sdk/impressions", { impressions: [payload] });
222
+ return clientId;
223
+ }
224
+ recordResponse(input) {
225
+ const payload = {
226
+ clientId: uuid(),
227
+ surveyId: input.surveyId,
228
+ endUserId: input.endUserId,
229
+ completed: input.completed,
230
+ submittedAt: input.submittedAt.toISOString(),
231
+ userProps: input.userProps,
232
+ impressionId: input.impressionId,
233
+ triggerId: input.triggerId ?? void 0,
234
+ context: input.context,
235
+ answers: input.answers
236
+ };
237
+ this.enqueue("/api/sdk/responses", { responses: [payload] });
238
+ }
239
+ enqueue(path, value) {
240
+ this.outbox.enqueue(path, JSON.stringify(value));
241
+ void this.flush();
242
+ }
243
+ // ── Flush ────────────────────────────────────────────────────────────────────
244
+ /** 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. */
247
+ async flush() {
248
+ if (this.isFlushing) return;
249
+ this.isFlushing = true;
250
+ 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;
257
+ }
258
+ }
259
+ } finally {
260
+ this.isFlushing = false;
261
+ }
262
+ }
263
+ async post(path, body) {
264
+ const res = await fetch(this.endpoint(path), {
265
+ method: "POST",
266
+ headers: {
267
+ Authorization: `Bearer ${this.apiKey}`,
268
+ "MS-Api-Version": API_VERSION,
269
+ "Content-Type": "application/json; charset=utf-8"
270
+ },
271
+ body
272
+ });
273
+ if (res.status === 429 || res.status >= 500 && res.status < 600) {
274
+ throw new Error(`retryable ${res.status}`);
275
+ }
276
+ }
277
+ endpoint(path) {
278
+ return this.baseURL + path;
279
+ }
280
+ };
281
+
282
+ // src/core/persistence.ts
283
+ var CONFIG_KEY = "com.microsurveys.config.cache";
284
+ var STATE_PREFIX = "com.microsurveys.triggerstate.";
285
+ var ConfigStore = class {
286
+ constructor(kv) {
287
+ __publicField(this, "kv", kv);
288
+ __publicField(this, "persisted", null);
289
+ __publicField(this, "parsed", null);
290
+ const data = kv.getItem(CONFIG_KEY);
291
+ if (data) {
292
+ try {
293
+ const entry = JSON.parse(data);
294
+ if (entry && typeof entry.rawConfig === "string") {
295
+ this.persisted = entry;
296
+ this.parsed = parseConfig(entry.rawConfig);
297
+ }
298
+ } catch {
299
+ }
300
+ }
301
+ }
302
+ get config() {
303
+ return this.parsed;
304
+ }
305
+ get surveys() {
306
+ return this.parsed?.surveys ?? [];
307
+ }
308
+ get theme() {
309
+ return this.parsed?.theme ?? null;
310
+ }
311
+ get etag() {
312
+ return this.persisted?.etag ?? null;
313
+ }
314
+ /** When the cached config was last written (ms epoch), for TTL checks. */
315
+ get storedAt() {
316
+ return this.persisted?.storedAt ?? null;
317
+ }
318
+ /** Persists the raw config response and refreshes the in-memory parse. */
319
+ save(rawConfig, etag) {
320
+ const entry = { rawConfig, etag, storedAt: Date.now() };
321
+ this.persisted = entry;
322
+ this.parsed = parseConfig(rawConfig);
323
+ this.kv.setItem(CONFIG_KEY, JSON.stringify(entry));
324
+ }
325
+ };
326
+ var TriggerStateStore = class {
327
+ constructor(kv) {
328
+ __publicField(this, "kv", kv);
329
+ }
330
+ load(endUserId) {
331
+ const data = this.kv.getItem(STATE_PREFIX + endUserId);
332
+ if (!data) return newUserTriggerState();
333
+ try {
334
+ const parsed = JSON.parse(data);
335
+ return { triggers: parsed.triggers ?? {}, surveys: parsed.surveys ?? {} };
336
+ } catch {
337
+ return newUserTriggerState();
338
+ }
339
+ }
340
+ save(endUserId, state) {
341
+ this.kv.setItem(STATE_PREFIX + endUserId, JSON.stringify(state));
342
+ }
343
+ reset(endUserId) {
344
+ this.kv.removeItem(STATE_PREFIX + endUserId);
345
+ }
346
+ };
347
+
348
+ // src/core/identity.ts
349
+ var ANON_KEY = "com.microsurveys.anonymousId";
350
+ var PROPS_KEY = "com.microsurveys.userProperties";
351
+ var IdentityStore = class {
352
+ constructor(kv) {
353
+ __publicField(this, "kv", kv);
354
+ __publicField(this, "identity");
355
+ let anon = kv.getItem(ANON_KEY);
356
+ if (!anon) {
357
+ anon = "anon_" + uuid();
358
+ kv.setItem(ANON_KEY, anon);
359
+ }
360
+ let userProperties = {};
361
+ const props = kv.getItem(PROPS_KEY);
362
+ if (props) {
363
+ try {
364
+ const parsed = JSON.parse(props);
365
+ if (parsed && typeof parsed === "object") userProperties = parsed;
366
+ } catch {
367
+ }
368
+ }
369
+ this.identity = { anonymousId: anon, userProperties };
370
+ }
371
+ /** Thread-safe not required (single-threaded JS); returns a shallow snapshot. */
372
+ snapshot() {
373
+ return { ...this.identity, userProperties: { ...this.identity.userProperties } };
374
+ }
375
+ /** Apply a host `identify(id, properties)` call. Merges properties. */
376
+ setUser(id, properties) {
377
+ if (id) this.identity.hostUserId = id;
378
+ if (properties) {
379
+ for (const key of Object.keys(properties)) {
380
+ this.identity.userProperties[key] = toJson(properties[key]);
381
+ }
382
+ this.persistProperties();
383
+ }
384
+ }
385
+ /** Merge an analytics identity update. Called per event, so it only persists
386
+ * when the properties actually changed. */
387
+ updateFromAnalytics(update) {
388
+ if (update.userId) this.identity.amplitudeUserId = update.userId;
389
+ if (update.deviceId) this.identity.amplitudeDeviceId = update.deviceId;
390
+ let changed = false;
391
+ if (update.userProperties) {
392
+ for (const key of Object.keys(update.userProperties)) {
393
+ const value = toJson(update.userProperties[key]);
394
+ if (JSON.stringify(this.identity.userProperties[key]) !== JSON.stringify(value)) {
395
+ this.identity.userProperties[key] = value;
396
+ changed = true;
397
+ }
398
+ }
399
+ }
400
+ if (update.setOnceProperties) {
401
+ for (const key of Object.keys(update.setOnceProperties)) {
402
+ if (key in this.identity.userProperties) continue;
403
+ this.identity.userProperties[key] = toJson(update.setOnceProperties[key]);
404
+ changed = true;
405
+ }
406
+ }
407
+ for (const key of update.unsetProperties ?? []) {
408
+ if (key in this.identity.userProperties) {
409
+ delete this.identity.userProperties[key];
410
+ changed = true;
411
+ }
412
+ }
413
+ if (changed) this.persistProperties();
414
+ }
415
+ persistProperties() {
416
+ this.kv.setItem(PROPS_KEY, JSON.stringify(this.identity.userProperties));
417
+ }
418
+ };
419
+ function toJson(value) {
420
+ if (value === null || value === void 0) return null;
421
+ switch (typeof value) {
422
+ case "string":
423
+ case "number":
424
+ case "boolean":
425
+ return value;
426
+ case "object":
427
+ if (Array.isArray(value)) return value.map(toJson);
428
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toJson(v)]));
429
+ default:
430
+ return String(value);
431
+ }
432
+ }
433
+
434
+ // src/core/sampling.ts
435
+ var encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
436
+ function utf8Bytes(s, useEncoder = true) {
437
+ if (encoder && useEncoder) return encoder.encode(s);
438
+ const out = [];
439
+ for (const ch of s) {
440
+ const c = ch.codePointAt(0);
441
+ if (c < 128) out.push(c);
442
+ else if (c < 2048) {
443
+ out.push(192 | c >> 6, 128 | c & 63);
444
+ } else if (c < 65536) {
445
+ out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
446
+ } else {
447
+ out.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);
448
+ }
449
+ }
450
+ return Uint8Array.from(out);
451
+ }
452
+ function fnv1a32(s) {
453
+ let hash = 2166136261;
454
+ const bytes = utf8Bytes(s);
455
+ for (let i = 0; i < bytes.length; i++) {
456
+ hash ^= bytes[i];
457
+ hash = Math.imul(hash, 16777619);
458
+ }
459
+ return hash >>> 0;
460
+ }
461
+ function inSample(endUserId, surveyId, samplePercent) {
462
+ if (samplePercent >= 100) return true;
463
+ if (samplePercent <= 0) return false;
464
+ const bucket = fnv1a32(`${endUserId}:${surveyId}`) % 100;
465
+ return bucket < samplePercent;
466
+ }
467
+ function numberString(n) {
468
+ if (Number.isFinite(n) && Math.trunc(n) === n && Math.abs(n) < 1e15) {
469
+ return String(Math.trunc(n));
470
+ }
471
+ return String(n);
472
+ }
473
+ function stringify(value) {
474
+ switch (typeof value) {
475
+ case "string":
476
+ return value;
477
+ case "boolean":
478
+ return value ? "true" : "false";
479
+ case "number":
480
+ return numberString(value);
481
+ default:
482
+ return null;
483
+ }
484
+ }
485
+ function matches(filter, properties) {
486
+ for (const key of Object.keys(filter)) {
487
+ const expectedStr = stringify(filter[key]);
488
+ if (expectedStr === null) return false;
489
+ const actualStr = stringify(properties[key]);
490
+ if (actualStr === null) return false;
491
+ if (expectedStr !== actualStr) return false;
492
+ }
493
+ return true;
494
+ }
495
+ function eventMatchesStep(eventName, properties, step) {
496
+ if (eventName !== step.event) return false;
497
+ return matches(step.match, properties);
498
+ }
499
+ function audienceMatches(audience, userProperties) {
500
+ return matches(audience, userProperties);
501
+ }
502
+
503
+ // src/core/triggerSequencer.ts
504
+ function windowExpired(window, startedAt, nowT) {
505
+ if (window === null || window <= 0 || startedAt === null) return false;
506
+ return nowT - startedAt > window;
507
+ }
508
+ function advance(trigger, record, eventName, properties, nowT) {
509
+ const next = { ...record };
510
+ const steps = [...trigger.steps].sort((a, b) => a.order - b.order);
511
+ if (steps.length === 0) return { record: next, satisfied: false };
512
+ const matchesStep = (index) => eventMatchesStep(eventName, properties, steps[index]);
513
+ let satisfied = false;
514
+ if (trigger.type === "SINGLE") {
515
+ satisfied = matchesStep(0);
516
+ } else {
517
+ const expected = Math.min(next.stepIndex, steps.length - 1);
518
+ if (matchesStep(expected)) {
519
+ if (expected === 0) {
520
+ next.startedAt = nowT;
521
+ next.stepIndex = 1;
522
+ } else if (windowExpired(trigger.sequenceWindowSeconds, next.startedAt, nowT)) {
523
+ if (matchesStep(0)) {
524
+ next.startedAt = nowT;
525
+ next.stepIndex = 1;
526
+ } else {
527
+ next.stepIndex = 0;
528
+ next.startedAt = null;
529
+ }
530
+ } else {
531
+ next.stepIndex = expected + 1;
532
+ }
533
+ if (next.stepIndex >= steps.length) {
534
+ satisfied = true;
535
+ next.stepIndex = 0;
536
+ next.startedAt = null;
537
+ }
538
+ } else if (expected !== 0 && matchesStep(0)) {
539
+ next.startedAt = nowT;
540
+ next.stepIndex = 1;
541
+ if (steps.length === 1) {
542
+ satisfied = true;
543
+ next.stepIndex = 0;
544
+ next.startedAt = null;
545
+ }
546
+ }
547
+ }
548
+ if (satisfied) next.satisfiedCount += 1;
549
+ return { record: next, satisfied };
550
+ }
551
+
552
+ // src/core/triggerEngine.ts
553
+ var TriggerEngine = class {
554
+ constructor(opts) {
555
+ __publicField(this, "store");
556
+ __publicField(this, "surveysProvider");
557
+ __publicField(this, "identityProvider");
558
+ __publicField(this, "onPresent");
559
+ __publicField(this, "platform");
560
+ __publicField(this, "now");
561
+ __publicField(this, "timers", /* @__PURE__ */ new Set());
562
+ this.store = opts.store;
563
+ this.surveysProvider = opts.surveysProvider;
564
+ this.identityProvider = opts.identityProvider;
565
+ this.onPresent = opts.onPresent;
566
+ this.platform = opts.platform;
567
+ this.now = opts.now ?? (() => Date.now() / 1e3);
568
+ }
569
+ /** Feed an event into the engine. */
570
+ process(name, properties = {}) {
571
+ const identity = this.identityProvider();
572
+ const endUserId = endUserIdOf(identity);
573
+ const state = this.store.load(endUserId);
574
+ const nowT = this.now();
575
+ for (const survey of this.surveysProvider()) {
576
+ const triggers = survey.triggers;
577
+ if (!triggers || triggers.length === 0) continue;
578
+ if (survey.platforms && survey.platforms.length > 0 && !survey.platforms.includes(this.platform)) continue;
579
+ for (const trigger of triggers) {
580
+ const satisfied = this.advanceTrigger(trigger, state, name, properties, nowT);
581
+ if (!satisfied) continue;
582
+ 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;
588
+ this.scheduleShow(survey, trigger, identity);
589
+ }
590
+ }
591
+ this.store.save(endUserId, state);
592
+ }
593
+ /** Cancels any pending scheduled presentations. */
594
+ stop() {
595
+ for (const t of this.timers) clearTimeout(t);
596
+ this.timers.clear();
597
+ }
598
+ // ── Trigger advancement ────────────────────────────────────────────────────
599
+ advanceTrigger(trigger, state, eventName, properties, nowT) {
600
+ const record = state.triggers[trigger.id] ?? newTriggerRecord();
601
+ const { record: updated, satisfied } = advance(trigger, record, eventName, properties, nowT);
602
+ state.triggers[trigger.id] = updated;
603
+ return satisfied;
604
+ }
605
+ // ── Eligibility checks ─────────────────────────────────────────────────────
606
+ isWithinWindow(survey, nowT) {
607
+ if (survey.startsAt) {
608
+ const start = Date.parse(survey.startsAt);
609
+ if (!Number.isNaN(start) && nowT < start / 1e3) return false;
610
+ }
611
+ if (survey.endsAt) {
612
+ const end = Date.parse(survey.endsAt);
613
+ if (!Number.isNaN(end) && nowT > end / 1e3) return false;
614
+ }
615
+ return true;
616
+ }
617
+ passesSampling(survey, endUserId, state) {
618
+ const existing = state.surveys[survey.id]?.sampleDecision;
619
+ if (existing !== void 0 && existing !== null) return existing;
620
+ const decision = inSample(endUserId, survey.id, survey.samplePercent ?? 100);
621
+ const record = state.surveys[survey.id] ?? {};
622
+ record.sampleDecision = decision;
623
+ state.surveys[survey.id] = record;
624
+ return decision;
625
+ }
626
+ // ── Scheduling ─────────────────────────────────────────────────────────────
627
+ scheduleShow(survey, trigger, identity) {
628
+ const delayMs = Math.max(0, trigger.delaySeconds) * 1e3;
629
+ const timer = setTimeout(() => {
630
+ this.timers.delete(timer);
631
+ const endUserId = endUserIdOf(identity);
632
+ const state = this.store.load(endUserId);
633
+ const nowT = this.now();
634
+ if (!passesCap(survey, state, nowT)) return;
635
+ const record = state.surveys[survey.id] ?? {};
636
+ record.lastShownAt = nowT;
637
+ state.surveys[survey.id] = record;
638
+ this.store.save(endUserId, state);
639
+ this.onPresent(survey, trigger, identity);
640
+ }, delayMs);
641
+ this.timers.add(timer);
642
+ }
643
+ };
644
+ function passesFrequency(trigger, occurrence) {
645
+ const fireEvery = Math.max(1, trigger.fireEvery);
646
+ const effective = occurrence - trigger.warmupCount;
647
+ return effective >= 1 && effective % fireEvery === 0;
648
+ }
649
+ function passesCap(survey, state, nowT) {
650
+ const days = survey.maxPerUserDays ?? 0;
651
+ const lastShown = state.surveys[survey.id]?.lastShownAt;
652
+ if (days <= 0 || lastShown === void 0 || lastShown === null) return true;
653
+ const elapsed = nowT - lastShown;
654
+ return elapsed >= days * 86400;
655
+ }
656
+
657
+ // src/core/client.ts
658
+ var DEFAULT_BASE_URL = "https://console.microsurveys.ai";
659
+ var DEFAULT_CONFIG_TTL_MS = 30 * 60 * 1e3;
660
+ var MicroSurveysClient = class {
661
+ constructor(opts) {
662
+ __publicField(this, "api");
663
+ __publicField(this, "configStore");
664
+ __publicField(this, "identityStore");
665
+ __publicField(this, "triggerStateStore");
666
+ __publicField(this, "engine");
667
+ __publicField(this, "configTTLms");
668
+ __publicField(this, "refreshOnForeground");
669
+ __publicField(this, "platform");
670
+ __publicField(this, "osVersion");
671
+ __publicField(this, "appVersion");
672
+ __publicField(this, "subscribeForeground");
673
+ __publicField(this, "presentListeners", /* @__PURE__ */ new Set());
674
+ __publicField(this, "configListeners", /* @__PURE__ */ new Set());
675
+ __publicField(this, "active", null);
676
+ __publicField(this, "started", false);
677
+ __publicField(this, "unsubscribeForeground", null);
678
+ const kv = opts.storage;
679
+ this.configStore = new ConfigStore(kv);
680
+ this.identityStore = new IdentityStore(kv);
681
+ this.triggerStateStore = new TriggerStateStore(kv);
682
+ this.api = new ApiClient(opts.apiKey, opts.apiBaseURL ?? DEFAULT_BASE_URL, kv);
683
+ this.configTTLms = opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS;
684
+ this.refreshOnForeground = opts.refreshOnForeground ?? true;
685
+ this.platform = opts.platform;
686
+ this.osVersion = opts.osVersion;
687
+ this.appVersion = opts.appVersion;
688
+ this.subscribeForeground = opts.subscribeForeground;
689
+ this.engine = new TriggerEngine({
690
+ store: this.triggerStateStore,
691
+ surveysProvider: () => this.configStore.surveys,
692
+ identityProvider: () => this.identityStore.snapshot(),
693
+ onPresent: (survey, trigger, identity) => this.handlePresent(survey, trigger, identity),
694
+ platform: opts.platform
695
+ });
696
+ }
697
+ // ── Lifecycle ────────────────────────────────────────────────────────────────
698
+ /** Flush any queued ingest, refresh config, and (optionally) wire the
699
+ * foreground refresh. Safe to call once early. */
700
+ start() {
701
+ if (this.started) return;
702
+ this.started = true;
703
+ void this.api.flush();
704
+ void this.refreshConfig();
705
+ if (this.refreshOnForeground) {
706
+ this.unsubscribeForeground = this.subscribeForeground(() => {
707
+ void this.api.flush();
708
+ this.refreshConfigIfStale();
709
+ });
710
+ }
711
+ }
712
+ /** Tear down listeners + pending timers. */
713
+ stop() {
714
+ this.engine.stop();
715
+ this.unsubscribeForeground?.();
716
+ this.unsubscribeForeground = null;
717
+ this.started = false;
718
+ }
719
+ /** Force an ETag-aware config refresh; keeps the cache on failure. */
720
+ async refreshConfig() {
721
+ try {
722
+ const result = await this.api.fetchConfig(this.configStore.etag);
723
+ if (result.kind === "config") {
724
+ this.configStore.save(result.rawText, result.etag);
725
+ this.configListeners.forEach((l) => l());
726
+ }
727
+ } catch {
728
+ }
729
+ }
730
+ /** Refresh only when the cache is missing or older than the TTL. */
731
+ refreshConfigIfStale() {
732
+ const storedAt = this.configStore.storedAt;
733
+ if (storedAt !== null && Date.now() - storedAt < this.configTTLms) return;
734
+ void this.refreshConfig();
735
+ }
736
+ // ── Identity + events ────────────────────────────────────────────────────────
737
+ identify(userId, properties) {
738
+ this.identityStore.setUser(userId, properties);
739
+ }
740
+ track(name, properties = {}) {
741
+ this.engine.process(name, properties);
742
+ }
743
+ /** Merge identity forwarded by an analytics SDK (e.g. the Amplitude plugin).
744
+ * Its user/device id take precedence over `identify()` for `endUserId`. */
745
+ updateAnalyticsIdentity(update) {
746
+ this.identityStore.updateFromAnalytics(update);
747
+ }
748
+ // ── Config accessors (for inline rendering) ──────────────────────────────────
749
+ getTheme() {
750
+ return this.configStore.theme;
751
+ }
752
+ getSurvey(surveyId) {
753
+ return this.configStore.surveys.find((s) => s.id === surveyId);
754
+ }
755
+ /** Subscribe to config refreshes (e.g. to render an inline survey that wasn't
756
+ * cached yet). Returns an unsubscribe function. */
757
+ onConfigChange(cb) {
758
+ this.configListeners.add(cb);
759
+ return () => this.configListeners.delete(cb);
760
+ }
761
+ // ── Presentation ─────────────────────────────────────────────────────────────
762
+ /** Subscribe to auto-triggered surveys. Returns an unsubscribe function. If a
763
+ * survey is already active, the new subscriber is notified immediately. */
764
+ onPresent(cb) {
765
+ this.presentListeners.add(cb);
766
+ if (this.active && !this.active.closed) cb(this.toActiveSurvey(this.active));
767
+ return () => this.presentListeners.delete(cb);
768
+ }
769
+ handlePresent(survey, trigger, identity) {
770
+ if (this.active && !this.active.closed) return;
771
+ const p = { survey, trigger, identity, shownAt: /* @__PURE__ */ new Date(), closed: false };
772
+ this.active = p;
773
+ const active = this.toActiveSurvey(p);
774
+ this.presentListeners.forEach((l) => l(active));
775
+ }
776
+ toActiveSurvey(p) {
777
+ return {
778
+ survey: p.survey,
779
+ trigger: p.trigger,
780
+ close: (result) => {
781
+ if (p.closed) return;
782
+ p.closed = true;
783
+ this.recordOutcome(p.survey.id, p.trigger?.id ?? null, p.identity, p.shownAt, result);
784
+ if (this.active === p) this.active = null;
785
+ }
786
+ };
787
+ }
788
+ /** Records the outcome of an **inline** `<MicroSurvey>` (no trigger/gate). */
789
+ recordInline(survey, result, shownAt) {
790
+ const identity = this.identityStore.snapshot();
791
+ this.recordOutcome(survey.id, null, identity, shownAt, result);
792
+ }
793
+ recordOutcome(surveyId, triggerId, identity, shownAt, result) {
794
+ const endUserId = endUserIdOf(identity);
795
+ const context = this.deviceContext();
796
+ const impressionId = this.api.recordImpression({
797
+ surveyId,
798
+ triggerId,
799
+ endUserId,
800
+ shownAt,
801
+ dismissed: result.dismissed,
802
+ context
803
+ });
804
+ if (result.completed || result.answers.length > 0) {
805
+ this.api.recordResponse({
806
+ surveyId,
807
+ endUserId,
808
+ completed: result.completed,
809
+ submittedAt: /* @__PURE__ */ new Date(),
810
+ userProps: identity.userProperties,
811
+ impressionId,
812
+ triggerId,
813
+ context,
814
+ answers: result.answers
815
+ });
816
+ }
817
+ }
818
+ /** Where this showing happened. The language is read at record time: the user
819
+ * can change it while the app runs. */
820
+ deviceContext() {
821
+ let locale;
822
+ try {
823
+ locale = Intl.DateTimeFormat().resolvedOptions().locale || void 0;
824
+ } catch {
825
+ }
826
+ return { platform: this.platform, appVersion: this.appVersion, osVersion: this.osVersion, locale };
827
+ }
828
+ };
829
+ function createClient(opts) {
830
+ return new MicroSurveysClient(opts);
831
+ }
832
+
833
+ // src/amplitude.ts
834
+ function createAmplitudePlugin(forwarder) {
835
+ return {
836
+ name: "microsurveys",
837
+ type: "enrichment",
838
+ async setup() {
839
+ },
840
+ async execute(event) {
841
+ try {
842
+ forwarder.updateAnalyticsIdentity(identityOf(event));
843
+ if (!event.event_type.startsWith("$")) {
844
+ forwarder.track(event.event_type, event.event_properties ?? {});
845
+ }
846
+ } catch {
847
+ }
848
+ return event;
849
+ }
850
+ };
851
+ }
852
+ function identityOf(event) {
853
+ const update = { userId: event.user_id, deviceId: event.device_id };
854
+ if (event.event_type !== "$identify" || !event.user_properties) return update;
855
+ const ops = event.user_properties;
856
+ const set = asRecord(ops.$set);
857
+ const setOnce = asRecord(ops.$setOnce);
858
+ if (set) update.userProperties = set;
859
+ if (setOnce) update.setOnceProperties = setOnce;
860
+ const unset = asRecord(ops.$unset);
861
+ if (unset) update.unsetProperties = Object.keys(unset);
862
+ return update;
863
+ }
864
+ function asRecord(v) {
865
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
866
+ }
867
+
868
+ // src/asyncStorage.ts
869
+ async function hydrateAsyncStorage(store) {
870
+ const cache = /* @__PURE__ */ new Map();
871
+ try {
872
+ const keys = (await store.getAllKeys()).filter((k) => k.startsWith(STORAGE_KEY_PREFIX));
873
+ for (const [key, value] of await readMany(store, keys)) {
874
+ if (value !== null) cache.set(key, value);
875
+ }
876
+ } catch {
877
+ }
878
+ let chain = Promise.resolve();
879
+ const enqueue = (write) => {
880
+ chain = chain.then(write).catch(() => {
881
+ });
882
+ };
883
+ return {
884
+ getItem: (key) => cache.get(key) ?? null,
885
+ setItem(key, value) {
886
+ cache.set(key, value);
887
+ enqueue(() => store.setItem(key, value));
888
+ },
889
+ removeItem(key) {
890
+ cache.delete(key);
891
+ enqueue(() => store.removeItem(key));
892
+ }
893
+ };
894
+ }
895
+ async function readMany(store, keys) {
896
+ if (keys.length === 0) return [];
897
+ if (store.getMany) return Object.entries(await store.getMany(keys));
898
+ if (store.multiGet) return (await store.multiGet(keys)).map(([k, v]) => [k, v]);
899
+ return Promise.all(keys.map(async (k) => [k, await store.getItem(k)]));
900
+ }
901
+
902
+ // src/MicroSurveys.ts
903
+ var DEFAULT_BASE_URL2 = "https://console.microsurveys.ai";
904
+ var DEFAULT_CONFIG_TTL_MS2 = 12 * 60 * 60 * 1e3;
905
+ function appStateForeground(onForeground) {
906
+ const sub = AppState.addEventListener("change", (state) => {
907
+ if (state === "active") onForeground();
908
+ });
909
+ return () => sub.remove();
910
+ }
911
+ var MicroSurveys = class {
912
+ constructor(opts) {
913
+ __publicField(this, "apiKey");
914
+ /** Resolves with the underlying runtime once storage has loaded. */
915
+ __publicField(this, "ready");
916
+ __publicField(this, "client", null);
917
+ __publicField(this, "pending", []);
918
+ this.apiKey = opts.apiKey;
919
+ const storage = opts.storage ? Promise.resolve(opts.storage) : hydrateAsyncStorage(opts.asyncStorage ?? AsyncStorage);
920
+ this.ready = storage.then((kv) => {
921
+ const client = createClient({
922
+ apiKey: opts.apiKey,
923
+ apiBaseURL: opts.apiBaseURL ?? DEFAULT_BASE_URL2,
924
+ configTTLms: opts.configTTLms ?? DEFAULT_CONFIG_TTL_MS2,
925
+ refreshOnForeground: opts.refreshOnForeground ?? true,
926
+ // Survey platform targeting: "ios" | "android".
927
+ platform: Platform.OS,
928
+ osVersion: String(Platform.Version),
929
+ appVersion: opts.appVersion,
930
+ storage: kv,
931
+ subscribeForeground: appStateForeground
932
+ });
933
+ this.client = client;
934
+ const queued = this.pending;
935
+ this.pending = [];
936
+ for (const run of queued) run(client);
937
+ return client;
938
+ });
939
+ }
940
+ /** Runs `fn` now if the runtime is ready, otherwise as soon as it is. */
941
+ withClient(fn) {
942
+ if (this.client) fn(this.client);
943
+ else this.pending.push(fn);
944
+ }
945
+ // ── Lifecycle ────────────────────────────────────────────────────────────────
946
+ /** Flushes queued impressions/responses, refreshes the config, and starts the
947
+ * foreground refresh. Safe to call once early in app launch (the provider
948
+ * calls it for you unless `autoStart={false}`). */
949
+ start() {
950
+ this.withClient((c) => c.start());
951
+ }
952
+ /** Stops foreground refresh and cancels pending (delayed) presentations. */
953
+ stop() {
954
+ this.withClient((c) => c.stop());
955
+ }
956
+ /** Forces an ETag-aware config refresh. Keeps the cache on failure. */
957
+ async refreshConfig() {
958
+ const client = await this.ready;
959
+ await client.refreshConfig();
960
+ }
961
+ // ── Identity + events ────────────────────────────────────────────────────────
962
+ /** Identify the current user and/or attach properties used by audience
963
+ * targeting. Optional with Amplitude (identity flows in via the plugin). */
964
+ identify(userId, properties) {
965
+ this.withClient((c) => c.identify(userId, properties));
966
+ }
967
+ /** Record an event. An eligible survey presents itself after its configured
968
+ * delay. Not needed for events that already flow through Amplitude. */
969
+ track(name, properties) {
970
+ this.withClient((c) => c.track(name, properties));
971
+ }
972
+ /** Identity forwarded by an analytics SDK. Used by the Amplitude plugin. */
973
+ updateAnalyticsIdentity(update) {
974
+ this.withClient((c) => c.updateAnalyticsIdentity(update));
975
+ }
976
+ /** The enrichment plugin to register on your Amplitude instance:
977
+ * `amplitude.add(ms.amplitudePlugin())`. Forwards events + identity into the
978
+ * SDK and returns every event unmodified. */
979
+ amplitudePlugin() {
980
+ return createAmplitudePlugin(this);
981
+ }
982
+ // ── Config + presentation (used by the provider and inline surveys) ──────────
983
+ getTheme() {
984
+ return this.client?.getTheme() ?? null;
985
+ }
986
+ getSurvey(surveyId) {
987
+ return this.client?.getSurvey(surveyId);
988
+ }
989
+ /** Subscribe to config loads/refreshes. Fires once when the cached config
990
+ * becomes available. Returns an unsubscribe function. */
991
+ onConfigChange(cb) {
992
+ let unsubscribe = null;
993
+ let cancelled = false;
994
+ this.withClient((c) => {
995
+ if (cancelled) return;
996
+ unsubscribe = c.onConfigChange(cb);
997
+ cb();
998
+ });
999
+ return () => {
1000
+ cancelled = true;
1001
+ unsubscribe?.();
1002
+ };
1003
+ }
1004
+ /** Subscribe to auto-triggered surveys. Returns an unsubscribe function. */
1005
+ onPresent(cb) {
1006
+ let unsubscribe = null;
1007
+ let cancelled = false;
1008
+ this.withClient((c) => {
1009
+ if (!cancelled) unsubscribe = c.onPresent(cb);
1010
+ });
1011
+ return () => {
1012
+ cancelled = true;
1013
+ unsubscribe?.();
1014
+ };
1015
+ }
1016
+ /** Records the outcome of an inline `<MicroSurvey>`. */
1017
+ recordInline(survey, result, shownAt) {
1018
+ this.withClient((c) => c.recordInline(survey, result, shownAt));
1019
+ }
1020
+ };
1021
+
1022
+ // src/provider.tsx
1023
+ import { createContext, useContext, useEffect as useEffect3, useMemo as useMemo3, useRef as useRef3, useState as useState4 } from "react";
1024
+
1025
+ // src/ui/SurveyModal.tsx
1026
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState3 } from "react";
1027
+ import {
1028
+ Animated as Animated2,
1029
+ Easing,
1030
+ Keyboard,
1031
+ KeyboardAvoidingView,
1032
+ Modal,
1033
+ PanResponder,
1034
+ Platform as Platform5,
1035
+ Pressable as Pressable4,
1036
+ StyleSheet as StyleSheet4,
1037
+ View as View4,
1038
+ useColorScheme,
1039
+ useWindowDimensions
1040
+ } from "react-native";
1041
+ import { SafeAreaProvider, initialWindowMetrics, useSafeAreaInsets } from "react-native-safe-area-context";
1042
+
1043
+ // src/ui/SurveyCard.tsx
1044
+ import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState as useState2 } from "react";
1045
+ import { Animated, Platform as Platform4, Pressable as Pressable3, ScrollView, StyleSheet as StyleSheet3, Text as Text2, View as View3 } from "react-native";
1046
+
1047
+ // src/ui/CloseButton.tsx
1048
+ import { Platform as Platform3, Pressable, StyleSheet, View } from "react-native";
1049
+
1050
+ // src/ui/platform.ts
1051
+ import { Platform as Platform2 } from "react-native";
1052
+ var usesGlassChrome = Platform2.OS === "ios" && parseInt(String(Platform2.Version), 10) >= 26;
1053
+ var FLOATING_SHEET_INSET = 8;
1054
+ var FLOATING_SHEET_RADIUS = 52;
1055
+
1056
+ // src/ui/CloseButton.tsx
1057
+ import { jsx } from "react/jsx-runtime";
1058
+ function CloseButton({ theme, onPress, style }) {
1059
+ let circle;
1060
+ let cross;
1061
+ if (usesGlassChrome) {
1062
+ circle = {
1063
+ width: 44,
1064
+ height: 44,
1065
+ borderRadius: 22,
1066
+ backgroundColor: theme.dark ? "rgba(72, 72, 74, 0.92)" : "rgba(255, 255, 255, 0.94)",
1067
+ borderWidth: StyleSheet.hairlineWidth,
1068
+ borderColor: theme.dark ? "rgba(255, 255, 255, 0.16)" : "rgba(0, 0, 0, 0.14)",
1069
+ shadowColor: "#000",
1070
+ shadowOpacity: theme.dark ? 0.3 : 0.08,
1071
+ shadowRadius: 8,
1072
+ shadowOffset: { width: 0, height: 2 }
1073
+ };
1074
+ cross = { color: theme.dark ? "rgba(255, 255, 255, 0.92)" : "rgba(0, 0, 0, 0.88)", length: 19, thickness: 2.6 };
1075
+ } else if (Platform3.OS === "ios") {
1076
+ circle = { width: 31, height: 31, borderRadius: 15.5, backgroundColor: theme.dark ? "rgba(235, 235, 245, 0.6)" : "rgba(60, 60, 67, 0.6)" };
1077
+ cross = { color: theme.surface, length: 12, thickness: 2.4 };
1078
+ } else {
1079
+ circle = { width: 32, height: 32, borderRadius: 16, backgroundColor: theme.track };
1080
+ cross = { color: theme.secondaryText, length: 13, thickness: 2 };
1081
+ }
1082
+ return /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Close survey", onPress, hitSlop: 6, style: [styles.hit, style], children: ({ pressed }) => /* @__PURE__ */ jsx(View, { style: [circle, styles.center, pressed && { opacity: 0.7 }], children: [45, -45].map((deg) => /* @__PURE__ */ jsx(
1083
+ View,
1084
+ {
1085
+ style: {
1086
+ position: "absolute",
1087
+ width: cross.length,
1088
+ height: cross.thickness,
1089
+ borderRadius: cross.thickness / 2,
1090
+ backgroundColor: cross.color,
1091
+ transform: [{ rotate: `${deg}deg` }]
1092
+ }
1093
+ },
1094
+ deg
1095
+ )) }) });
1096
+ }
1097
+ var styles = StyleSheet.create({
1098
+ hit: { position: "absolute", width: 44, height: 44, alignItems: "center", justifyContent: "center" },
1099
+ center: { alignItems: "center", justifyContent: "center" }
1100
+ });
1101
+
1102
+ // src/ui/questions.tsx
1103
+ import { useState } from "react";
1104
+ import { Pressable as Pressable2, StyleSheet as StyleSheet2, Text, TextInput, View as View2 } from "react-native";
1105
+
1106
+ // src/ui/theme.ts
1107
+ var PALETTES = {
1108
+ light: {
1109
+ background: "#09090B",
1110
+ surface: "#FFFFFF",
1111
+ text: "#18181B",
1112
+ secondaryText: "#71717A",
1113
+ accent: "#2E7272",
1114
+ // Slate Teal (brand primary)
1115
+ accentText: "#FFFFFF",
1116
+ border: "#E4E4E7",
1117
+ track: "#F4F4F5"
1118
+ },
1119
+ dark: {
1120
+ background: "#000000",
1121
+ surface: "#1A1A1E",
1122
+ text: "#FAFAFA",
1123
+ secondaryText: "#A1A1AA",
1124
+ accent: "#41B2B2",
1125
+ accentText: "#FFFFFF",
1126
+ border: "#333338",
1127
+ track: "#27272A"
1128
+ }
1129
+ };
1130
+ var WEIGHTS = { regular: "400", medium: "500", semibold: "600", bold: "700" };
1131
+ function resolveTheme(project, opts = {}) {
1132
+ const p = project ?? {};
1133
+ const base = PALETTES[opts.scheme ?? "light"];
1134
+ const accent = color(p.accent) ?? base.accent;
1135
+ const controlHeight = num(p.controlHeight) ?? 48;
1136
+ let cornerRadius = 16;
1137
+ let sheetCornerRadius = 28;
1138
+ let controlRadius = 12;
1139
+ const cr = num(p.cornerRadius);
1140
+ if (cr !== void 0) {
1141
+ cornerRadius = cr;
1142
+ sheetCornerRadius = cr;
1143
+ controlRadius = Math.max(0, cr - 2);
1144
+ }
1145
+ controlRadius = num(p.controlRadius) ?? controlRadius;
1146
+ if (p.controlPill === true) controlRadius = controlHeight / 2;
1147
+ let position = p.position === "center" ? "center" : "bottom";
1148
+ switch (opts.presentation) {
1149
+ case "dialog":
1150
+ case "center":
1151
+ position = "center";
1152
+ break;
1153
+ case "sheet":
1154
+ case "bottom":
1155
+ position = "bottom";
1156
+ break;
1157
+ }
1158
+ return {
1159
+ // A fixed ~40% dim of the (opaque) configured background, like iOS.
1160
+ scrim: withAlpha(color(p.background) ?? base.background, 0.4),
1161
+ surface: color(p.surface) ?? base.surface,
1162
+ text: color(p.text) ?? base.text,
1163
+ secondaryText: color(p.secondaryText) ?? base.secondaryText,
1164
+ accent,
1165
+ accentText: color(p.accentText) ?? base.accentText,
1166
+ border: color(p.border) ?? base.border,
1167
+ track: base.track,
1168
+ accentTint: withAlpha(accent, 0.1),
1169
+ accentTintStrong: withAlpha(accent, 0.12),
1170
+ cornerRadius,
1171
+ sheetCornerRadius,
1172
+ nativeSheetCorners: cr === void 0,
1173
+ dark: opts.scheme === "dark",
1174
+ controlRadius,
1175
+ controlHeight,
1176
+ spacing: num(p.spacing) ?? 16,
1177
+ textScale: Math.max(0.5, num(p.textScale) ?? 1),
1178
+ titleSize: num(p.titleSize) ?? 20,
1179
+ titleWeight: WEIGHTS[(p.titleWeight ?? "").toLowerCase()] ?? "600",
1180
+ titleLineHeight: num(p.titleLineHeight) ?? 1.1,
1181
+ titleLetterSpacing: num(p.titleLetterSpacing) ?? 0,
1182
+ position,
1183
+ align: p.alignment === "center" ? "center" : "left",
1184
+ fontFamily: opts.fontFamily
1185
+ };
1186
+ }
1187
+ function clampRadius(radius, width, height) {
1188
+ return Math.min(radius, Math.min(width, height) / 2);
1189
+ }
1190
+ function num(v) {
1191
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
1192
+ }
1193
+ function color(hex) {
1194
+ if (typeof hex !== "string") return void 0;
1195
+ let h = hex.trim().replace(/^#/, "");
1196
+ if (h.length === 3) h = h.replace(/./g, (c) => c + c);
1197
+ if (!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(h)) return void 0;
1198
+ return "#" + h.toUpperCase();
1199
+ }
1200
+ function withAlpha(hex, alpha) {
1201
+ const h = (color(hex) ?? "#000000").slice(1);
1202
+ const r = parseInt(h.slice(0, 2), 16);
1203
+ const g = parseInt(h.slice(2, 4), 16);
1204
+ const b = parseInt(h.slice(4, 6), 16);
1205
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
1206
+ }
1207
+
1208
+ // src/ui/questions.tsx
1209
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1210
+ function QuestionInput({ question, theme, value, onChange, autoFocus }) {
1211
+ const cfg = question.config;
1212
+ switch (cfg.kind) {
1213
+ case "scale":
1214
+ return /* @__PURE__ */ jsx2(ScaleInput, { min: cfg.min, max: cfg.max, minLabel: cfg.minLabel, maxLabel: cfg.maxLabel, theme, value: numValue(value), onPick: (n) => onChange({ value: n }) });
1215
+ case "stars":
1216
+ return /* @__PURE__ */ jsx2(StarsInput, { count: cfg.count, theme, value: numValue(value), onPick: (n) => onChange({ value: n }) });
1217
+ case "emoji":
1218
+ return /* @__PURE__ */ jsx2(EmojiInput, { options: cfg.options, theme, value: strValue(value), onPick: (v) => onChange({ value: v }) });
1219
+ case "thumbs":
1220
+ return /* @__PURE__ */ jsx2(ThumbsInput, { theme, value: strValue(value), onPick: (v) => onChange({ value: v }) });
1221
+ case "singleChoice":
1222
+ return /* @__PURE__ */ jsx2(ChoiceInput, { options: cfg.options, theme, value: value && "choice" in value ? value.choice : void 0, onPick: (v) => onChange({ choice: v }) });
1223
+ case "openText":
1224
+ return /* @__PURE__ */ jsx2(
1225
+ OpenTextInput,
1226
+ {
1227
+ placeholder: cfg.placeholder,
1228
+ maxLength: cfg.maxLength,
1229
+ theme,
1230
+ autoFocus,
1231
+ onText: (t) => onChange(t.trim().length > 0 ? { text: t.trim() } : void 0)
1232
+ }
1233
+ );
1234
+ }
1235
+ }
1236
+ function isAnswerValid(question, value) {
1237
+ return question.required ? value !== void 0 : true;
1238
+ }
1239
+ function numValue(v) {
1240
+ return v && "value" in v && typeof v.value === "number" ? v.value : void 0;
1241
+ }
1242
+ function strValue(v) {
1243
+ return v && "value" in v && typeof v.value === "string" ? v.value : void 0;
1244
+ }
1245
+ function font(theme, size, weight = "400") {
1246
+ return { fontSize: size * theme.textScale, fontWeight: weight, fontFamily: theme.fontFamily };
1247
+ }
1248
+ var MAX_FONT_SCALE = 1.6;
1249
+ var CHIP_GAP = 8;
1250
+ var CHIP_MIN_SIDE = 44;
1251
+ function ScaleInput({ min, max, minLabel, maxLabel, theme, value, onPick }) {
1252
+ const [width, setWidth] = useState(0);
1253
+ const lo = Math.min(min, max);
1254
+ const hi = Math.max(min, max);
1255
+ const points = [];
1256
+ for (let i = lo; i <= hi; i++) points.push(i);
1257
+ const compact = points.length <= 7;
1258
+ const chipWidth = compact && width > 0 ? (width - CHIP_GAP * (points.length - 1)) / points.length : CHIP_MIN_SIDE;
1259
+ const chipHeight = compact ? Math.min(theme.controlHeight, chipWidth) : CHIP_MIN_SIDE;
1260
+ const hasLabels = !!minLabel || !!maxLabel;
1261
+ return /* @__PURE__ */ jsxs(View2, { onLayout: (e) => setWidth(e.nativeEvent.layout.width), children: [
1262
+ /* @__PURE__ */ jsx2(View2, { style: [styles2.scaleRow, !compact && styles2.wrap], children: width > 0 && points.map((n) => {
1263
+ const on = value === n;
1264
+ return /* @__PURE__ */ jsx2(
1265
+ Pressable2,
1266
+ {
1267
+ accessibilityRole: "button",
1268
+ accessibilityLabel: String(n),
1269
+ accessibilityState: { selected: on },
1270
+ onPress: () => onPick(n),
1271
+ style: ({ pressed }) => [
1272
+ styles2.chip,
1273
+ {
1274
+ width: compact ? chipWidth : void 0,
1275
+ minWidth: compact ? void 0 : CHIP_MIN_SIDE,
1276
+ height: chipHeight,
1277
+ borderRadius: clampRadius(theme.controlRadius, compact ? chipWidth : CHIP_MIN_SIDE, chipHeight),
1278
+ backgroundColor: on ? theme.accent : theme.surface,
1279
+ borderColor: on ? theme.accent : theme.border,
1280
+ opacity: pressed ? 0.85 : 1
1281
+ }
1282
+ ],
1283
+ children: /* @__PURE__ */ jsx2(Text, { maxFontSizeMultiplier: MAX_FONT_SCALE, style: [font(theme, 16, "500"), { color: on ? theme.accentText : theme.text }], children: n })
1284
+ },
1285
+ n
1286
+ );
1287
+ }) }),
1288
+ hasLabels && /* @__PURE__ */ jsxs(View2, { style: styles2.endLabels, children: [
1289
+ /* @__PURE__ */ jsx2(Text, { style: [font(theme, 13), styles2.endLabel, { color: theme.secondaryText }], numberOfLines: 2, children: minLabel }),
1290
+ /* @__PURE__ */ jsx2(Text, { style: [font(theme, 13), styles2.endLabel, { color: theme.secondaryText, textAlign: "right" }], numberOfLines: 2, children: maxLabel })
1291
+ ] })
1292
+ ] });
1293
+ }
1294
+ function StarsInput({ count, theme, value, onPick }) {
1295
+ const stars = [];
1296
+ for (let i = 1; i <= Math.max(1, count); i++) stars.push(i);
1297
+ return /* @__PURE__ */ jsx2(View2, { style: styles2.starsRow, children: stars.map((n) => {
1298
+ const on = value !== void 0 && n <= value;
1299
+ return /* @__PURE__ */ jsx2(
1300
+ Pressable2,
1301
+ {
1302
+ accessibilityRole: "button",
1303
+ accessibilityLabel: `${n} star${n === 1 ? "" : "s"}`,
1304
+ accessibilityState: { selected: value === n },
1305
+ onPress: () => onPick(n),
1306
+ hitSlop: 4,
1307
+ style: styles2.star,
1308
+ children: /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: { fontSize: 38, lineHeight: 46, color: theme.accent }, children: on ? "\u2605" : "\u2606" })
1309
+ },
1310
+ n
1311
+ );
1312
+ }) });
1313
+ }
1314
+ function EmojiInput({ options, theme, value, onPick }) {
1315
+ return /* @__PURE__ */ jsx2(View2, { style: styles2.emojiRow, children: options.map((o) => {
1316
+ const on = value === o.value;
1317
+ return /* @__PURE__ */ jsxs(
1318
+ Pressable2,
1319
+ {
1320
+ accessibilityRole: "button",
1321
+ accessibilityLabel: o.label || o.value,
1322
+ accessibilityState: { selected: on },
1323
+ onPress: () => onPick(o.value),
1324
+ style: ({ pressed }) => [
1325
+ styles2.emojiCell,
1326
+ {
1327
+ borderRadius: theme.controlRadius,
1328
+ backgroundColor: on ? theme.accentTintStrong : theme.surface,
1329
+ borderColor: on ? theme.accent : theme.border,
1330
+ opacity: pressed ? 0.85 : 1
1331
+ }
1332
+ ],
1333
+ children: [
1334
+ /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: styles2.emojiGlyph, children: o.emoji }),
1335
+ !!o.label && /* @__PURE__ */ jsx2(Text, { maxFontSizeMultiplier: MAX_FONT_SCALE, style: [font(theme, 13), { color: theme.secondaryText, textAlign: "center" }], children: o.label })
1336
+ ]
1337
+ },
1338
+ o.value
1339
+ );
1340
+ }) });
1341
+ }
1342
+ function ThumbsInput({ theme, value, onPick }) {
1343
+ const sides = [
1344
+ { value: "up", emoji: "\u{1F44D}", label: "Thumbs up" },
1345
+ { value: "down", emoji: "\u{1F44E}", label: "Thumbs down" }
1346
+ ];
1347
+ return /* @__PURE__ */ jsx2(View2, { style: styles2.thumbsRow, children: sides.map((s) => {
1348
+ const on = value === s.value;
1349
+ return /* @__PURE__ */ jsx2(
1350
+ Pressable2,
1351
+ {
1352
+ accessibilityRole: "button",
1353
+ accessibilityLabel: s.label,
1354
+ accessibilityState: { selected: on },
1355
+ onPress: () => onPick(s.value),
1356
+ style: ({ pressed }) => [
1357
+ styles2.thumb,
1358
+ {
1359
+ height: theme.controlHeight,
1360
+ borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),
1361
+ backgroundColor: on ? theme.accent : theme.surface,
1362
+ borderColor: on ? theme.accent : theme.border,
1363
+ opacity: pressed ? 0.85 : 1
1364
+ }
1365
+ ],
1366
+ children: /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: styles2.thumbGlyph, children: s.emoji })
1367
+ },
1368
+ s.value
1369
+ );
1370
+ }) });
1371
+ }
1372
+ function ChoiceInput({ options, theme, value, onPick }) {
1373
+ return /* @__PURE__ */ jsx2(View2, { style: styles2.choices, children: options.map((o) => {
1374
+ const on = value === o.value;
1375
+ return /* @__PURE__ */ jsxs(
1376
+ Pressable2,
1377
+ {
1378
+ accessibilityRole: "radio",
1379
+ accessibilityLabel: o.label,
1380
+ accessibilityState: { checked: on },
1381
+ onPress: () => onPick(o.value),
1382
+ style: ({ pressed }) => [
1383
+ styles2.choice,
1384
+ {
1385
+ minHeight: theme.controlHeight,
1386
+ borderRadius: clampRadius(theme.controlRadius, Infinity, theme.controlHeight),
1387
+ backgroundColor: on ? theme.accentTint : theme.surface,
1388
+ borderColor: on ? theme.accent : theme.border,
1389
+ opacity: pressed ? 0.85 : 1
1390
+ }
1391
+ ],
1392
+ children: [
1393
+ /* @__PURE__ */ jsx2(Text, { style: [font(theme, 16), styles2.choiceLabel, { color: theme.text }], children: o.label }),
1394
+ /* @__PURE__ */ jsx2(
1395
+ View2,
1396
+ {
1397
+ style: [
1398
+ styles2.radio,
1399
+ on ? { backgroundColor: theme.accent, borderColor: theme.accent } : { borderColor: theme.border }
1400
+ ],
1401
+ children: on && /* @__PURE__ */ jsx2(Text, { allowFontScaling: false, style: [styles2.radioCheck, { color: theme.accentText }], children: "\u2713" })
1402
+ }
1403
+ )
1404
+ ]
1405
+ },
1406
+ o.value
1407
+ );
1408
+ }) });
1409
+ }
1410
+ function OpenTextInput({ placeholder, maxLength, theme, autoFocus, onText }) {
1411
+ const [text, setText] = useState("");
1412
+ const [focused, setFocused] = useState(false);
1413
+ return /* @__PURE__ */ jsxs(View2, { children: [
1414
+ /* @__PURE__ */ jsx2(
1415
+ TextInput,
1416
+ {
1417
+ multiline: true,
1418
+ autoFocus,
1419
+ value: text,
1420
+ onChangeText: (t) => {
1421
+ setText(t);
1422
+ onText(t);
1423
+ },
1424
+ onFocus: () => setFocused(true),
1425
+ onBlur: () => setFocused(false),
1426
+ placeholder,
1427
+ placeholderTextColor: theme.secondaryText,
1428
+ maxLength,
1429
+ textAlignVertical: "top",
1430
+ style: [
1431
+ font(theme, 16),
1432
+ styles2.textArea,
1433
+ {
1434
+ minHeight: theme.controlHeight * 2,
1435
+ borderRadius: theme.controlRadius,
1436
+ borderColor: focused ? theme.accent : theme.border,
1437
+ backgroundColor: theme.surface,
1438
+ color: theme.text
1439
+ }
1440
+ ]
1441
+ }
1442
+ ),
1443
+ maxLength !== void 0 && /* @__PURE__ */ jsxs(Text, { style: [font(theme, 13), styles2.counter, { color: theme.secondaryText }], children: [
1444
+ text.length,
1445
+ "/",
1446
+ maxLength
1447
+ ] })
1448
+ ] });
1449
+ }
1450
+ var styles2 = StyleSheet2.create({
1451
+ scaleRow: { flexDirection: "row", gap: CHIP_GAP },
1452
+ wrap: { flexWrap: "wrap", justifyContent: "center" },
1453
+ chip: { borderWidth: 1, alignItems: "center", justifyContent: "center", paddingHorizontal: 10 },
1454
+ endLabels: { flexDirection: "row", gap: 12, marginTop: 10, paddingHorizontal: 2 },
1455
+ endLabel: { flex: 1 },
1456
+ starsRow: { flexDirection: "row", justifyContent: "center", gap: 6, height: 48, alignItems: "center" },
1457
+ star: { paddingHorizontal: 2 },
1458
+ emojiRow: { flexDirection: "row", flexWrap: "wrap", justifyContent: "center", columnGap: 10, rowGap: 12 },
1459
+ emojiCell: { minWidth: 64, paddingVertical: 8, paddingHorizontal: 10, borderWidth: 1, alignItems: "center", gap: 2 },
1460
+ emojiGlyph: { fontSize: 32, lineHeight: 40 },
1461
+ thumbsRow: { flexDirection: "row", gap: 16 },
1462
+ thumb: { flex: 1, borderWidth: 1, alignItems: "center", justifyContent: "center" },
1463
+ thumbGlyph: { fontSize: 32, lineHeight: 40 },
1464
+ choices: { gap: 10 },
1465
+ choice: { flexDirection: "row", alignItems: "center", borderWidth: 1, paddingVertical: 14, paddingHorizontal: 16, gap: 12 },
1466
+ choiceLabel: { flex: 1 },
1467
+ radio: { width: 22, height: 22, borderRadius: 11, borderWidth: 1.5, alignItems: "center", justifyContent: "center" },
1468
+ radioCheck: { fontSize: 13, lineHeight: 16, fontWeight: "700" },
1469
+ textArea: { borderWidth: 1, paddingHorizontal: 16, paddingTop: 12, paddingBottom: 12 },
1470
+ counter: { marginTop: 6, textAlign: "right" }
1471
+ });
1472
+
1473
+ // src/ui/SurveyCard.tsx
1474
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
1475
+ var CLIP_ROOM = 4;
1476
+ var THANKS_MS = 1300;
1477
+ var SurveyCard = forwardRef(function SurveyCard2({ survey, theme, variant, bottomInset, onResult, onClose }, ref) {
1478
+ const questions = useMemo(() => [...survey.questions].sort((a, b) => a.order - b.order), [survey]);
1479
+ const dismissible = survey.dismissible !== false;
1480
+ const [index, setIndex] = useState2(0);
1481
+ const committed = useRef({});
1482
+ const [current, setCurrent] = useState2(void 0);
1483
+ const [done, setDone] = useState2(false);
1484
+ const [height, setHeight] = useState2(0);
1485
+ const reported = useRef(false);
1486
+ const closeTimer = useRef(null);
1487
+ useEffect(() => () => {
1488
+ if (closeTimer.current) clearTimeout(closeTimer.current);
1489
+ }, []);
1490
+ const question = questions[index];
1491
+ const isLast = index >= questions.length - 1;
1492
+ const valid = question ? isAnswerValid(question, current) : false;
1493
+ function collected() {
1494
+ return questions.filter((q) => committed.current[q.id] !== void 0).map((q) => ({ questionId: q.id, value: committed.current[q.id] }));
1495
+ }
1496
+ function report(completed) {
1497
+ if (reported.current) return false;
1498
+ reported.current = true;
1499
+ onResult({ answers: collected(), completed, dismissed: !completed });
1500
+ return true;
1501
+ }
1502
+ function dismiss() {
1503
+ if (report(false)) onClose();
1504
+ }
1505
+ useImperativeHandle(ref, () => ({ dismiss }));
1506
+ useEffect(() => {
1507
+ if (questions.length === 0) dismiss();
1508
+ }, []);
1509
+ function advance2() {
1510
+ if (!question || !valid) return;
1511
+ if (current !== void 0) committed.current[question.id] = current;
1512
+ if (!isLast) {
1513
+ setIndex(index + 1);
1514
+ setCurrent(void 0);
1515
+ return;
1516
+ }
1517
+ if (report(true)) {
1518
+ setDone(true);
1519
+ closeTimer.current = setTimeout(onClose, THANKS_MS);
1520
+ }
1521
+ }
1522
+ const pad = theme.spacing + 4;
1523
+ const topInset = variant === "sheet" ? pad + 12 : pad;
1524
+ const hasProgress = questions.length > 1;
1525
+ if (!question) return null;
1526
+ if (done) {
1527
+ const custom = survey.successMessage?.trim();
1528
+ return (
1529
+ // Keep the card's height so the sheet doesn't jump when the content swaps.
1530
+ /* @__PURE__ */ jsx3(View3, { style: [styles3.thanks, { minHeight: height, padding: pad }], accessibilityLiveRegion: "polite", children: /* @__PURE__ */ jsx3(FadeIn, { children: /* @__PURE__ */ jsxs2(View3, { style: styles3.thanksStack, children: [
1531
+ /* @__PURE__ */ jsx3(View3, { style: [styles3.check, { backgroundColor: theme.accent }], children: /* @__PURE__ */ jsx3(Text2, { allowFontScaling: false, style: [styles3.checkGlyph, { color: theme.accentText }], children: "\u2713" }) }),
1532
+ /* @__PURE__ */ jsx3(Text2, { style: [promptStyle(theme), { color: theme.text, textAlign: "center", marginTop: theme.spacing }], children: custom || "Thanks!" })
1533
+ ] }) }) })
1534
+ );
1535
+ }
1536
+ return /* @__PURE__ */ jsxs2(View3, { onLayout: (e) => setHeight(e.nativeEvent.layout.height), style: styles3.card, children: [
1537
+ hasProgress && /* @__PURE__ */ jsxs2(Text2, { style: [font(theme, 13), { color: theme.secondaryText, marginTop: topInset, marginHorizontal: pad }], children: [
1538
+ index + 1,
1539
+ " of ",
1540
+ questions.length
1541
+ ] }),
1542
+ /* @__PURE__ */ jsx3(
1543
+ ScrollView,
1544
+ {
1545
+ style: styles3.scroll,
1546
+ contentContainerStyle: { paddingHorizontal: pad, paddingTop: hasProgress ? theme.spacing : topInset, paddingBottom: CLIP_ROOM, gap: theme.spacing + 8 },
1547
+ keyboardShouldPersistTaps: "handled",
1548
+ showsVerticalScrollIndicator: false,
1549
+ bounces: false,
1550
+ children: /* @__PURE__ */ jsx3(FadeIn, { children: /* @__PURE__ */ jsxs2(View3, { style: { gap: theme.spacing + 8 }, children: [
1551
+ /* @__PURE__ */ jsx3(Text2, { accessibilityRole: "header", style: [promptStyle(theme), { color: theme.text, paddingRight: dismissible ? 48 : 0 }], children: question.prompt }),
1552
+ /* @__PURE__ */ jsx3(QuestionInput, { question, theme, value: current, onChange: setCurrent, autoFocus: variant !== "inline" })
1553
+ ] }) }, question.id)
1554
+ }
1555
+ ),
1556
+ /* @__PURE__ */ jsx3(
1557
+ Pressable3,
1558
+ {
1559
+ accessibilityRole: "button",
1560
+ accessibilityState: { disabled: !valid },
1561
+ disabled: !valid,
1562
+ onPress: advance2,
1563
+ style: ({ pressed }) => [
1564
+ styles3.button,
1565
+ {
1566
+ height: theme.controlHeight,
1567
+ marginTop: theme.spacing - CLIP_ROOM,
1568
+ marginHorizontal: pad,
1569
+ marginBottom: Math.max(pad, bottomInset ?? 0),
1570
+ borderRadius: Math.min(theme.controlRadius, theme.controlHeight / 2),
1571
+ backgroundColor: theme.accent,
1572
+ opacity: !valid ? 0.45 : pressed ? 0.9 : 1
1573
+ }
1574
+ ],
1575
+ children: /* @__PURE__ */ jsx3(Text2, { maxFontSizeMultiplier: 1.6, style: [font(theme, 16, "600"), { color: theme.accentText }], children: isLast ? "Submit" : "Next" })
1576
+ }
1577
+ ),
1578
+ dismissible && /* @__PURE__ */ jsx3(
1579
+ CloseButton,
1580
+ {
1581
+ theme,
1582
+ onPress: dismiss,
1583
+ style: Platform4.OS === "ios" ? { top: pad, right: pad } : { top: variant === "sheet" ? pad + 4 : pad - 6, right: pad - 6 }
1584
+ }
1585
+ )
1586
+ ] });
1587
+ });
1588
+ function promptStyle(theme) {
1589
+ return {
1590
+ fontSize: theme.titleSize,
1591
+ fontWeight: theme.titleWeight,
1592
+ fontFamily: theme.fontFamily,
1593
+ // iOS applies `lineHeightMultiple` to the font's natural line height (~1.2em).
1594
+ lineHeight: Math.round(theme.titleSize * 1.2 * theme.titleLineHeight),
1595
+ letterSpacing: theme.titleLetterSpacing,
1596
+ textAlign: theme.align
1597
+ };
1598
+ }
1599
+ function FadeIn({ children }) {
1600
+ const opacity = useRef(new Animated.Value(0)).current;
1601
+ useEffect(() => {
1602
+ Animated.timing(opacity, { toValue: 1, duration: 220, useNativeDriver: false }).start();
1603
+ }, [opacity]);
1604
+ return /* @__PURE__ */ jsx3(Animated.View, { style: { opacity }, children });
1605
+ }
1606
+ var styles3 = StyleSheet3.create({
1607
+ card: { flexShrink: 1 },
1608
+ scroll: { flexGrow: 0, flexShrink: 1 },
1609
+ button: { alignItems: "center", justifyContent: "center" },
1610
+ thanks: { alignItems: "center", justifyContent: "center" },
1611
+ thanksStack: { alignItems: "center" },
1612
+ check: { width: 48, height: 48, borderRadius: 24, alignItems: "center", justifyContent: "center" },
1613
+ checkGlyph: { fontSize: 26, fontWeight: "700", lineHeight: 30 }
1614
+ });
1615
+
1616
+ // src/ui/SurveyModal.tsx
1617
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
1618
+ function SurveyModal({ survey, theme: projectTheme, fontFamily, onResult, onClose }) {
1619
+ const scheme = useColorScheme() === "dark" ? "dark" : "light";
1620
+ const theme = useMemo2(
1621
+ () => resolveTheme(projectTheme, { scheme, presentation: survey?.presentation, fontFamily }),
1622
+ [projectTheme, scheme, survey?.presentation, fontFamily]
1623
+ );
1624
+ const card = useRef2(null);
1625
+ if (!survey) return null;
1626
+ return /* @__PURE__ */ jsx4(
1627
+ Modal,
1628
+ {
1629
+ visible: true,
1630
+ transparent: true,
1631
+ animationType: "none",
1632
+ statusBarTranslucent: true,
1633
+ navigationBarTranslucent: true,
1634
+ onRequestClose: () => {
1635
+ if (survey.dismissible !== false) card.current?.dismiss();
1636
+ },
1637
+ children: /* @__PURE__ */ jsx4(SafeAreaProvider, { initialMetrics: initialWindowMetrics, children: /* @__PURE__ */ jsx4(Presentation, { card, survey, theme, onResult, onClose }, survey.id) })
1638
+ }
1639
+ );
1640
+ }
1641
+ function Presentation({ card, survey, theme, onResult, onClose }) {
1642
+ const insets = useSafeAreaInsets();
1643
+ const window = useWindowDimensions();
1644
+ const isSheet = theme.position === "bottom";
1645
+ const dismissible = survey.dismissible !== false;
1646
+ const floating = isSheet && usesGlassChrome && insets.bottom > 0;
1647
+ const floatScale = floating ? (window.width - 2 * FLOATING_SHEET_INSET) / window.width : 1;
1648
+ const sheetRadius = floating && theme.nativeSheetCorners ? FLOATING_SHEET_RADIUS / floatScale : theme.sheetCornerRadius;
1649
+ const scrim = isSheet ? Platform5.OS === "ios" ? "rgba(0, 0, 0, 0.2)" : "rgba(0, 0, 0, 0.32)" : theme.scrim;
1650
+ const progress = useRef2(new Animated2.Value(0)).current;
1651
+ const drag = useRef2(new Animated2.Value(0)).current;
1652
+ const [sheetHeight, setSheetHeight] = useState3(window.height);
1653
+ const sheetTop = useRef2(window.height);
1654
+ const [keyboard, setKeyboard] = useState3(0);
1655
+ const keyboardUp = keyboard > 0;
1656
+ const insetForKeyboard = isSheet && Platform5.OS === "ios";
1657
+ const keyboardSpacer = useRef2(new Animated2.Value(0)).current;
1658
+ const keyboardDuration = useRef2(250);
1659
+ useEffect2(() => {
1660
+ Animated2.timing(progress, {
1661
+ toValue: 1,
1662
+ duration: isSheet ? 320 : 280,
1663
+ easing: Easing.out(Easing.cubic),
1664
+ useNativeDriver: false
1665
+ }).start();
1666
+ }, [progress, isSheet]);
1667
+ useEffect2(() => {
1668
+ const update = (height, duration) => {
1669
+ if (duration) keyboardDuration.current = duration;
1670
+ setKeyboard(height);
1671
+ };
1672
+ const show = Keyboard.addListener(
1673
+ Platform5.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow",
1674
+ (e) => update(e.endCoordinates.height, e.duration)
1675
+ );
1676
+ const hide = Keyboard.addListener(Platform5.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide", (e) => update(0, e.duration));
1677
+ return () => {
1678
+ show.remove();
1679
+ hide.remove();
1680
+ };
1681
+ }, []);
1682
+ const spacerTarget = insetForKeyboard && keyboard > 0 ? (keyboard - (floating ? FLOATING_SHEET_INSET : 0)) / floatScale : 0;
1683
+ useEffect2(() => {
1684
+ Animated2.timing(keyboardSpacer, {
1685
+ toValue: spacerTarget,
1686
+ duration: keyboardDuration.current,
1687
+ easing: Easing.bezier(0.17, 0.59, 0.4, 0.77),
1688
+ // close to the iOS keyboard curve
1689
+ useNativeDriver: false
1690
+ }).start();
1691
+ }, [keyboardSpacer, spacerTarget]);
1692
+ function animateOut() {
1693
+ Keyboard.dismiss();
1694
+ Animated2.timing(progress, { toValue: 0, duration: 240, easing: Easing.in(Easing.cubic), useNativeDriver: false }).start(() => onClose?.());
1695
+ }
1696
+ function requestDismiss() {
1697
+ if (dismissible) card.current?.dismiss();
1698
+ }
1699
+ const pan = useMemo2(
1700
+ () => PanResponder.create({
1701
+ // Own touches that start in the sheet's header band (grabber, progress) from
1702
+ // the start: otherwise a responder higher up the tree (e.g. a draggable
1703
+ // dev overlay at the app root) claims them and the sheet never sees the
1704
+ // drag. Buttons in the band (close) are deeper and still win taps.
1705
+ onStartShouldSetPanResponder: (e) => isSheet && dismissible && e.nativeEvent.pageY - sheetTop.current < DRAG_HEADER_HEIGHT,
1706
+ // Elsewhere, take over a downward drag nothing inside wanted.
1707
+ onMoveShouldSetPanResponder: (_, g) => isSheet && dismissible && isDownwardDrag(g),
1708
+ onPanResponderTerminationRequest: () => false,
1709
+ onPanResponderMove: (_, g) => drag.setValue(Math.max(0, g.dy)),
1710
+ onPanResponderRelease: (_, g) => {
1711
+ if (isDownwardDrag(g) && (g.dy > 120 || g.vy > 1)) requestDismiss();
1712
+ else Animated2.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start();
1713
+ },
1714
+ onPanResponderTerminate: () => Animated2.spring(drag, { toValue: 0, useNativeDriver: false, bounciness: 0 }).start()
1715
+ }),
1716
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1717
+ [isSheet, dismissible]
1718
+ );
1719
+ const cardContent = /* @__PURE__ */ jsx4(
1720
+ SurveyCard,
1721
+ {
1722
+ ref: card,
1723
+ survey,
1724
+ theme,
1725
+ variant: isSheet ? "sheet" : "dialog",
1726
+ bottomInset: isSheet && !keyboardUp ? insets.bottom : 0,
1727
+ onResult: (r) => onResult?.(r),
1728
+ onClose: animateOut
1729
+ }
1730
+ );
1731
+ return /* @__PURE__ */ jsxs3(View4, { style: StyleSheet4.absoluteFill, accessibilityViewIsModal: true, children: [
1732
+ /* @__PURE__ */ jsx4(Animated2.View, { style: [StyleSheet4.absoluteFill, { backgroundColor: scrim, opacity: progress }], children: /* @__PURE__ */ jsx4(
1733
+ Pressable4,
1734
+ {
1735
+ style: StyleSheet4.absoluteFill,
1736
+ onPress: requestDismiss,
1737
+ accessible: false,
1738
+ importantForAccessibility: "no"
1739
+ }
1740
+ ) }),
1741
+ /* @__PURE__ */ jsx4(
1742
+ KeyboardAvoidingView,
1743
+ {
1744
+ behavior: insetForKeyboard ? void 0 : Platform5.OS === "ios" ? "padding" : "height",
1745
+ style: [styles4.fill, isSheet ? styles4.bottom : [styles4.center, { paddingTop: insets.top }]],
1746
+ pointerEvents: "box-none",
1747
+ children: isSheet ? /* @__PURE__ */ jsxs3(
1748
+ Animated2.View,
1749
+ {
1750
+ ...pan.panHandlers,
1751
+ onLayout: (e) => {
1752
+ setSheetHeight(e.nativeEvent.layout.height);
1753
+ sheetTop.current = e.nativeEvent.layout.y;
1754
+ },
1755
+ style: [
1756
+ styles4.sheet,
1757
+ shadow,
1758
+ floating ? {
1759
+ borderRadius: sheetRadius,
1760
+ borderCurve: "continuous",
1761
+ borderWidth: StyleSheet4.hairlineWidth / floatScale,
1762
+ borderColor: theme.dark ? "rgba(255, 255, 255, 0.14)" : "rgba(0, 0, 0, 0.18)"
1763
+ } : { borderTopLeftRadius: sheetRadius, borderTopRightRadius: sheetRadius, borderCurve: "continuous" },
1764
+ {
1765
+ maxHeight: window.height - insets.top - 24,
1766
+ backgroundColor: theme.surface,
1767
+ transform: [
1768
+ {
1769
+ translateY: Animated2.add(
1770
+ progress.interpolate({
1771
+ inputRange: [0, 1],
1772
+ // Shown: scaling about the center lifts the bottom edge by
1773
+ // h(1-s)/2; shift so it rests FLOATING_SHEET_INSET above the screen edge.
1774
+ outputRange: [sheetHeight, floating ? sheetHeight * (1 - floatScale) / 2 - FLOATING_SHEET_INSET : 0]
1775
+ }),
1776
+ drag
1777
+ )
1778
+ },
1779
+ { scale: floatScale }
1780
+ ]
1781
+ }
1782
+ ],
1783
+ children: [
1784
+ /* @__PURE__ */ jsx4(View4, { style: [styles4.grabber, { backgroundColor: theme.secondaryText }] }),
1785
+ cardContent,
1786
+ insetForKeyboard && /* @__PURE__ */ jsx4(Animated2.View, { style: { height: keyboardSpacer } })
1787
+ ]
1788
+ }
1789
+ ) : /* @__PURE__ */ jsx4(
1790
+ Animated2.View,
1791
+ {
1792
+ style: [
1793
+ styles4.dialog,
1794
+ shadow,
1795
+ {
1796
+ maxHeight: window.height - insets.top - insets.bottom - 48,
1797
+ marginBottom: insets.bottom,
1798
+ backgroundColor: theme.surface,
1799
+ borderRadius: theme.cornerRadius,
1800
+ borderCurve: "continuous",
1801
+ opacity: progress,
1802
+ transform: [{ scale: progress.interpolate({ inputRange: [0, 1], outputRange: [0.94, 1] }) }]
1803
+ }
1804
+ ],
1805
+ children: cardContent
1806
+ }
1807
+ )
1808
+ }
1809
+ )
1810
+ ] });
1811
+ }
1812
+ var DRAG_HEADER_HEIGHT = 72;
1813
+ function isDownwardDrag(g) {
1814
+ return g.dy > 6 && Math.abs(g.dy) > Math.abs(g.dx);
1815
+ }
1816
+ var shadow = {
1817
+ shadowColor: "#000",
1818
+ shadowOpacity: 0.18,
1819
+ shadowRadius: 24,
1820
+ shadowOffset: { width: 0, height: -4 },
1821
+ elevation: 16
1822
+ };
1823
+ var styles4 = StyleSheet4.create({
1824
+ fill: { flex: 1 },
1825
+ bottom: { justifyContent: "flex-end" },
1826
+ center: { justifyContent: "center", paddingHorizontal: 20 },
1827
+ sheet: { width: "100%", maxWidth: 640, alignSelf: "center" },
1828
+ dialog: { width: "100%", maxWidth: 480, alignSelf: "center", overflow: "hidden" },
1829
+ grabber: { position: "absolute", top: 6, alignSelf: "center", width: 36, height: 5, borderRadius: 3, opacity: 0.35, zIndex: 1 }
1830
+ });
1831
+
1832
+ // src/provider.tsx
1833
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
1834
+ var MicroSurveysContext = createContext({ instance: null });
1835
+ function MicroSurveysProvider({ apiKey, apiBaseURL, appVersion, instance, autoStart = true, fontFamily, children }) {
1836
+ const [owned] = useState4(() => !instance && apiKey ? new MicroSurveys({ apiKey, apiBaseURL, appVersion }) : null);
1837
+ const ms = instance ?? owned;
1838
+ useEffect3(() => {
1839
+ if (!ms || !autoStart) return;
1840
+ ms.start();
1841
+ return () => owned?.stop();
1842
+ }, [ms, owned, autoStart]);
1843
+ const value = useMemo3(() => ({ instance: ms, fontFamily }), [ms, fontFamily]);
1844
+ return /* @__PURE__ */ jsxs4(MicroSurveysContext.Provider, { value, children: [
1845
+ children,
1846
+ ms && /* @__PURE__ */ jsx5(OverlayHost, { instance: ms, fontFamily })
1847
+ ] });
1848
+ }
1849
+ function OverlayHost({ instance, fontFamily }) {
1850
+ const [current, setCurrent] = useState4(null);
1851
+ const queue = useRef3([]);
1852
+ const showing = useRef3(false);
1853
+ const nextId = useRef3(0);
1854
+ useEffect3(
1855
+ () => instance.onPresent((active) => {
1856
+ if (showing.current) {
1857
+ queue.current.push(active);
1858
+ return;
1859
+ }
1860
+ showing.current = true;
1861
+ setCurrent({ active, id: nextId.current++ });
1862
+ }),
1863
+ [instance]
1864
+ );
1865
+ function showNext() {
1866
+ const next = queue.current.shift();
1867
+ if (next) {
1868
+ setCurrent({ active: next, id: nextId.current++ });
1869
+ } else {
1870
+ showing.current = false;
1871
+ setCurrent(null);
1872
+ }
1873
+ }
1874
+ return /* @__PURE__ */ jsx5(
1875
+ SurveyModal,
1876
+ {
1877
+ survey: current?.active.survey ?? null,
1878
+ theme: instance.getTheme(),
1879
+ fontFamily,
1880
+ onResult: (result) => current?.active.close(result),
1881
+ onClose: showNext
1882
+ },
1883
+ current?.id ?? "none"
1884
+ );
1885
+ }
1886
+ function useMicroSurveysInstance() {
1887
+ return useContext(MicroSurveysContext).instance;
1888
+ }
1889
+ function useMicroSurveys() {
1890
+ const instance = useMicroSurveysInstance();
1891
+ return useMemo3(
1892
+ () => ({
1893
+ instance,
1894
+ track: (name, properties) => instance?.track(name, properties),
1895
+ identify: (userId, properties) => instance?.identify(userId, properties),
1896
+ refresh: () => instance?.refreshConfig()
1897
+ }),
1898
+ [instance]
1899
+ );
1900
+ }
1901
+
1902
+ // src/MicroSurvey.tsx
1903
+ import { useContext as useContext2, useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4, useState as useState5 } from "react";
1904
+ import { View as View5, useColorScheme as useColorScheme2 } from "react-native";
1905
+ import { jsx as jsx6 } from "react/jsx-runtime";
1906
+ function MicroSurvey({ surveyId, onComplete, style }) {
1907
+ const { instance, fontFamily } = useContext2(MicroSurveysContext);
1908
+ const scheme = useColorScheme2() === "dark" ? "dark" : "light";
1909
+ const [survey, setSurvey] = useState5(null);
1910
+ const [closed, setClosed] = useState5(false);
1911
+ const shownAt = useRef4(null);
1912
+ const result = useRef4(null);
1913
+ useEffect4(() => {
1914
+ if (!instance) return;
1915
+ return instance.onConfigChange(() => setSurvey(instance.getSurvey(surveyId) ?? null));
1916
+ }, [instance, surveyId]);
1917
+ const projectTheme = instance?.getTheme();
1918
+ const theme = useMemo4(() => resolveTheme(projectTheme, { scheme, fontFamily }), [projectTheme, scheme, fontFamily]);
1919
+ if (!instance || !survey || closed) return null;
1920
+ if (!shownAt.current) shownAt.current = /* @__PURE__ */ new Date();
1921
+ return /* @__PURE__ */ jsx6(
1922
+ View5,
1923
+ {
1924
+ style: [
1925
+ { backgroundColor: theme.surface, borderRadius: theme.cornerRadius, borderWidth: 1, borderColor: theme.border, overflow: "hidden" },
1926
+ style
1927
+ ],
1928
+ children: /* @__PURE__ */ jsx6(
1929
+ SurveyCard,
1930
+ {
1931
+ survey,
1932
+ theme,
1933
+ variant: "inline",
1934
+ onResult: (r) => {
1935
+ result.current = r;
1936
+ instance.recordInline(survey, r, shownAt.current ?? /* @__PURE__ */ new Date());
1937
+ },
1938
+ onClose: () => {
1939
+ setClosed(true);
1940
+ if (result.current) onComplete?.(result.current);
1941
+ }
1942
+ }
1943
+ )
1944
+ }
1945
+ );
1946
+ }
1947
+ export {
1948
+ MicroSurvey,
1949
+ MicroSurveys,
1950
+ MicroSurveysProvider,
1951
+ SurveyModal,
1952
+ hydrateAsyncStorage,
1953
+ parseConfig,
1954
+ useMicroSurveys,
1955
+ useMicroSurveysInstance
1956
+ };
1957
+ //# sourceMappingURL=index.js.map