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