@magicfeedback/popup-sdk 1.17.2 → 1.19.0

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.
Files changed (55) hide show
  1. package/MagicfeedbackPopupSdk.podspec +18 -0
  2. package/README.md +33 -1
  3. package/dist/2.2.38-CCK7SF4A.mjs +2343 -0
  4. package/dist/2.2.38-CCK7SF4A.mjs.map +1 -0
  5. package/dist/2.2.38-LGZRM7GX.mjs +2343 -0
  6. package/dist/2.2.38-LGZRM7GX.mjs.map +1 -0
  7. package/dist/2.2.39-BJJ3YRJ4.mjs +2344 -0
  8. package/dist/2.2.39-BJJ3YRJ4.mjs.map +1 -0
  9. package/dist/2.2.39-HPNDYUPP.mjs +2344 -0
  10. package/dist/2.2.39-HPNDYUPP.mjs.map +1 -0
  11. package/dist/assets/assets/style.css +165 -1
  12. package/dist/assets/assets/survey-css/2.2.38.css +2335 -0
  13. package/dist/assets/assets/survey-css/2.2.39.css +2336 -0
  14. package/dist/chunk-3QS3WKRC.mjs +31 -0
  15. package/dist/chunk-3QS3WKRC.mjs.map +1 -0
  16. package/dist/chunk-7ZQOAKXR.mjs +3335 -0
  17. package/dist/chunk-7ZQOAKXR.mjs.map +1 -0
  18. package/dist/chunk-BJTO5JO5.mjs +11 -0
  19. package/dist/chunk-BJTO5JO5.mjs.map +1 -0
  20. package/dist/{chunk-AFRHPS3K.mjs → chunk-EW2ARDEY.mjs} +591 -51
  21. package/dist/chunk-EW2ARDEY.mjs.map +1 -0
  22. package/dist/{chunk-VHTN5UXD.mjs → chunk-XOEEBDBJ.mjs} +630 -10
  23. package/dist/chunk-XOEEBDBJ.mjs.map +1 -0
  24. package/dist/index.d.mts +159 -10
  25. package/dist/index.d.ts +159 -10
  26. package/dist/index.js +7275 -1466
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +318 -41
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/index.native.d.mts +1616 -0
  31. package/dist/index.native.d.ts +1616 -0
  32. package/dist/index.native.js +15853 -0
  33. package/dist/index.native.js.map +1 -0
  34. package/dist/index.native.mjs +3914 -0
  35. package/dist/index.native.mjs.map +1 -0
  36. package/dist/react-native.d.mts +105 -8
  37. package/dist/react-native.d.ts +105 -8
  38. package/dist/react-native.js +5827 -132
  39. package/dist/react-native.js.map +1 -1
  40. package/dist/react-native.mjs +313 -43
  41. package/dist/react-native.mjs.map +1 -1
  42. package/dist/renderPopup-2Y4QMWR7.mjs +3847 -0
  43. package/dist/renderPopup-2Y4QMWR7.mjs.map +1 -0
  44. package/dist/renderPopup-YDJUON42.mjs +3847 -0
  45. package/dist/renderPopup-YDJUON42.mjs.map +1 -0
  46. package/dist/{renderPopup-L2Q3KJAZ.mjs → renderPopup-ZHTRMFO2.mjs} +142 -9
  47. package/dist/renderPopup-ZHTRMFO2.mjs.map +1 -0
  48. package/ios/DeepdotsBackgroundTask.m +71 -0
  49. package/package.json +14 -5
  50. package/react-native.config.js +9 -0
  51. package/dist/chunk-AFRHPS3K.mjs.map +0 -1
  52. package/dist/chunk-VHTN5UXD.mjs.map +0 -1
  53. package/dist/renderPopup-L2Q3KJAZ.mjs.map +0 -1
  54. package/dist/renderPopup-PQWJSBOY.mjs +0 -3622
  55. package/dist/renderPopup-PQWJSBOY.mjs.map +0 -1
@@ -0,0 +1,1616 @@
1
+ /**
2
+ * Tiempo de ejecución en segundo plano para los envíos de analytics (DD-55).
3
+ *
4
+ * En iOS la app se suspende pocos segundos después de pasar a background. Si el POST con el
5
+ * cierre de la sesión sigue en vuelo, no termina hasta que el usuario vuelve a abrir la app
6
+ * (medido en producción con React Native, nov 2026: una de cada tres sesiones iOS se cerraba tarde o nunca, frente
7
+ * a ~2 % en Android). iOS concede más tiempo si la app lo pide (`beginBackgroundTask`), pero
8
+ * eso es una API nativa: el SDK es JS puro, así que el host le pasa una función que la abre.
9
+ *
10
+ * Contrato (igual que `beginBackgroundTask` del SDK nativo): `begin(name)` abre una tarea y
11
+ * devuelve la función que la cierra. Puede llamarse varias veces a la vez.
12
+ */
13
+ type BackgroundTaskRunner = (name: string) => () => void;
14
+ /**
15
+ * Techo de una tarea abierta por el SDK. iOS da ~30 s; el POST ya se da por fallido a los
16
+ * 20 s (`POST_TIMEOUT_MS`), así que esto solo cubre un `end` que no llegue nunca.
17
+ */
18
+ declare const BACKGROUND_TASK_MAX_MS = 25000;
19
+ /** Forma mínima de `react-native-background-timer` (`BackgroundTimer` por defecto). */
20
+ interface BackgroundTimerLike {
21
+ start(delay?: number): unknown;
22
+ stop(): unknown;
23
+ }
24
+ /**
25
+ * Adaptador sobre `react-native-background-timer`. En iOS su `start()` abre UNA background
26
+ * task (`beginBackgroundTaskWithName`, y cierra la anterior) y `stop()` la cierra, así que aquí
27
+ * se cuentan las tareas abiertas: `start` con la primera y `stop` cuando se cierra la última.
28
+ *
29
+ * Úsalo solo en iOS: en Android `start()` toma un wakelock (permiso `WAKE_LOCK`) que no hace
30
+ * falta, porque Android no suspende la app al pasar a background.
31
+ */
32
+ declare function backgroundTimerTask(timer: BackgroundTimerLike): BackgroundTaskRunner;
33
+
34
+ /**
35
+ * Identidad + sesión para el tracking de navegación (Fase 1).
36
+ * Implementa el "Contrato común Web+KMP".
37
+ *
38
+ * Modelo: el SDK gestiona el `user_id` (persistente). El `session_id` es propiedad
39
+ * del BACKEND: llega en la respuesta de `POST /sdk/popups` y se cachea; el backend
40
+ * cose sesiones por `user_id` + ventana. El SDK NO genera ni expira sesiones.
41
+ *
42
+ * Sin dependencias de DOM: recibe el storage y (opcionalmente) el reloj y el
43
+ * generador de uuid por inyección. El binding a `localStorage` vive en `createDefaultStorage`.
44
+ */
45
+ /** Store clave/valor mínimo (espejo conceptual del `KeyValueStorage` de KMP). */
46
+ interface KeyValueStorage {
47
+ getItem(key: string): string | null;
48
+ setItem(key: string, value: string): void;
49
+ removeItem(key: string): void;
50
+ }
51
+ /** Impl en memoria — usada en tests y como fallback sin `localStorage`. */
52
+ declare class InMemoryStorage implements KeyValueStorage {
53
+ private map;
54
+ getItem(key: string): string | null;
55
+ setItem(key: string, value: string): void;
56
+ removeItem(key: string): void;
57
+ }
58
+ /** Par clave/valor con el formato `NativeAnswer` que espera `@magicfeedback/native`. */
59
+ interface IdentityAnswer {
60
+ key: string;
61
+ value: string[];
62
+ }
63
+
64
+ /**
65
+ * Device info para el context de analytics (Technology #11–13).
66
+ *
67
+ * En Web enviamos `device_type` + `user_agent` crudo y dejamos que el backend
68
+ * derive OS/navegador del UA (como hace GA). Los campos adicionales (timezone,
69
+ * referrer, viewport, etc.) se recogen de las APIs del navegador sin permisos.
70
+ * `country`/`city` se rellenan de forma asíncrona (ver geo-info.ts).
71
+ * En KMP las APIs nativas dan os_version/device_model reales.
72
+ */
73
+ interface DeviceInfo {
74
+ device_type: 'mobile' | 'tablet' | 'desktop';
75
+ os_version?: string;
76
+ device_model?: string;
77
+ app_version?: string;
78
+ user_agent?: string;
79
+ timezone?: string;
80
+ referrer?: string;
81
+ viewport_size?: string;
82
+ screen_resolution?: string;
83
+ pixel_ratio?: number;
84
+ entry_type?: string;
85
+ page_load_ms?: number;
86
+ connection_type?: string;
87
+ country?: string;
88
+ city?: string;
89
+ }
90
+
91
+ /**
92
+ * Capa de Analytics (eventos GA-style) — canal SEPARADO del feedback de survey.
93
+ *
94
+ * El feedback de survey se envía con `magicfeedback.send()`. La analítica de
95
+ * navegación/comportamiento (page views, mini-services, tasks/funnels, meaningful
96
+ * interactions, findability…) va por un ENDPOINT PROPIO, vinculada por `user_id`.
97
+ *
98
+ * De momento NO se hace la llamada: el `sink` por defecto hace `console.log` del
99
+ * payload exacto que se enviaría (dry-run), para poder verificarlo. Cuando el
100
+ * endpoint exista, se sustituye el sink por un POST.
101
+ */
102
+
103
+ interface AnalyticsEvent {
104
+ name: string;
105
+ timestamp: number;
106
+ params?: Record<string, unknown>;
107
+ }
108
+ interface AnalyticsEnvelope {
109
+ /** Clave pública del cliente (auth). */
110
+ publicKey?: string;
111
+ /** Id que vincula la analítica al usuario (el backend cose por aquí). */
112
+ userId: string | null;
113
+ /** Session id del backend si ya se conoce (puede ir null). */
114
+ sessionId: string | null;
115
+ context: {
116
+ platform: string;
117
+ /** SDK que produce la analítica, `<plataforma>@<versión>` (`deepdots_sdk`). */
118
+ sdk?: string;
119
+ language?: string;
120
+ /** Info de dispositivo (Technology #11–13). */
121
+ device?: DeviceInfo;
122
+ /** User attributes del cliente, usados para breakdowns (registration_status, pass_type, …). */
123
+ attributes: Record<string, string>;
124
+ /** Métricas del host: valores medibles persistentes → van en `feedback.metrics` del body. */
125
+ metrics?: Record<string, string>;
126
+ };
127
+ events: AnalyticsEvent[];
128
+ }
129
+ /** Contexto del flush, para que el sink pueda adaptar el transporte. */
130
+ interface AnalyticsFlushMeta {
131
+ /**
132
+ * `true` cuando el flush ocurre porque la página/app se está cerrando. El sink debe usar
133
+ * un transporte que sobreviva al unload (`fetch` con `keepalive`) y no puede esperar
134
+ * respuestas.
135
+ */
136
+ final?: boolean;
137
+ /**
138
+ * `true` cuando este es el ÚLTIMO lote de la sesión (cierre de página, app a background,
139
+ * cambio de usuario, tracking desactivado). El sink lo envía con `completed:true` y olvida
140
+ * el `sessionId`, para que el lote siguiente abra un registro nuevo.
141
+ */
142
+ sessionEnd?: boolean;
143
+ /**
144
+ * `true` para olvidar la sesión SIN enviar nada (el payload llega vacío): el backend ya la
145
+ * cerró por inactividad. El sink descarta su `sessionId` para que el lote siguiente abra un
146
+ * registro nuevo, igual que tras `sessionEnd`, pero sin POST.
147
+ */
148
+ resetSession?: boolean;
149
+ }
150
+ /**
151
+ * Envío del lote. Si devuelve una promesa que **rechaza**, el manager re-encola los
152
+ * eventos para reintentarlos en el siguiente flush (fallo transitorio: red o 5xx).
153
+ * Resolver = lote entregado o descartado definitivamente (no se reintenta).
154
+ */
155
+ type AnalyticsSink = (payload: AnalyticsEnvelope, meta?: AnalyticsFlushMeta) => void | Promise<void>;
156
+
157
+ /**
158
+ * Mapeo del envelope de analytics → body de `POST /sdk/feedback`.
159
+ *
160
+ * La analítica se envía como un Feedback del modelo del Surveys SDK, agrupado por una
161
+ * INTEGRACIÓN creada en la plataforma. Se manda en streaming con `completed:false`; el
162
+ * backend agrupa los lotes por `sessionId`, que genera el SDK al abrir cada sesión. El
163
+ * ÚLTIMO lote de una sesión (cierre de página, app a background, cambio de usuario) va con
164
+ * `completed:true`: cierra el registro y el lote siguiente abre otro con un sessionId nuevo.
165
+ * `feedback.finished` se queda siempre en `false` (no es la señal de cierre acordada).
166
+ *
167
+ * Encoding:
168
+ * - todo va en `feedback.metadata`: contexto (user_id, session_id, platform, sdk…) + eventos
169
+ * - cada entrada usa `value: string[]` (array de un elemento)
170
+ * - eventos: {key: nombre_evento, value: [JSON(timestamp + params)]}
171
+ * - identidad (user_id) → `profile` como `external-user-id`
172
+ * - métricas del host (setMetric) → `feedback.metrics` (mismo shape que metadata, sin prefijo)
173
+ * - `answers` vacío
174
+ * - `text` vacío
175
+ */
176
+
177
+ interface AnalyticsKeys {
178
+ publicKey: string;
179
+ integration: string;
180
+ }
181
+ interface FeedbackKV {
182
+ key: string;
183
+ value: string[];
184
+ }
185
+ interface AnalyticsFeedbackBody {
186
+ feedback: {
187
+ text: string;
188
+ answers: FeedbackKV[];
189
+ metrics: FeedbackKV[];
190
+ metadata: FeedbackKV[];
191
+ profile: FeedbackKV[];
192
+ finished: boolean;
193
+ };
194
+ publicKey: string;
195
+ integration: string;
196
+ completed: boolean;
197
+ finished?: boolean;
198
+ /** sessionId de la sesión (lo genera el SDK): el backend agrupa todos sus lotes en un solo registro. */
199
+ sessionId?: string;
200
+ }
201
+ interface BuildBodyOptions {
202
+ /**
203
+ * `true` en el último lote de la sesión → `completed:true` (cierra el registro en backend).
204
+ * El body lleva el `sessionId` de la sesión que se cierra; el lote siguiente abre otro
205
+ * registro con un sessionId nuevo.
206
+ */
207
+ sessionEnd?: boolean;
208
+ }
209
+ declare function buildAnalyticsFeedbackBody(envelope: AnalyticsEnvelope, keys: AnalyticsKeys, feedbackSessionId?: string, options?: BuildBodyOptions): AnalyticsFeedbackBody;
210
+ interface FeedbackSinkOptions {
211
+ /** Base URL del backend (api(.|-dev.)deepdots.com) ya resuelta por el entorno. */
212
+ baseUrl: string;
213
+ keys: AnalyticsKeys;
214
+ /** Logger opcional (gated por debug). */
215
+ log?: (...args: unknown[]) => void;
216
+ /** fetch inyectable (tests / RN). */
217
+ fetchImpl?: typeof fetch;
218
+ /**
219
+ * @deprecated Se ignora. El flush final salía por `sendBeacon`, que va SIEMPRE con
220
+ * credenciales; contra la API (`Access-Control-Allow-Origin: *` + `Allow-Credentials:
221
+ * true`) el preflight fallaba y el lote de cierre, el único con `completed:true`, no
222
+ * llegaba nunca. Ahora sale por `fetch` con `keepalive`. Se mantiene en el tipo para no
223
+ * romper a quien lo pase.
224
+ */
225
+ sendBeaconImpl?: (url: string, body: Blob | string) => boolean;
226
+ /**
227
+ * Registro en el que seguir desde el primer lote: el de una sesión suspendida por un
228
+ * `pagehide` y reanudada tras recargar la página (ver `suspended-session.ts`).
229
+ */
230
+ initialSessionId?: string;
231
+ /**
232
+ * Genera el sessionId de cada sesión (default: UUID v4). Inyectable para tests.
233
+ */
234
+ newSessionId?: () => string;
235
+ /**
236
+ * Persistencia de los lotes pendientes (React Native: MMKV). Con él, el lote de cierre se
237
+ * guarda antes de enviarse y cualquier lote que falle sobrevive a que la app muera: el sink
238
+ * del arranque siguiente lo reenvía a su registro. Sin él, los pendientes viven en memoria.
239
+ */
240
+ storage?: KeyValueStorage;
241
+ /** Reloj inyectable (tests). */
242
+ now?: () => number;
243
+ /**
244
+ * Abre una background task nativa mientras dura cada envío (iOS: `beginBackgroundTask`), para
245
+ * que el POST de cierre termine aunque la app pase a background. Sin él, iOS suele suspender
246
+ * la app con el POST en vuelo y el cierre llega al volver a abrirla (ver `background-task.ts`).
247
+ */
248
+ backgroundTask?: BackgroundTaskRunner;
249
+ /** Callback invocado cuando la API acepta el primer lote de una sesión (registro abierto). */
250
+ onSessionId?: (id: string) => void;
251
+ /** Callback invocado al cerrar la sesión (`completed:true`): el sessionId cacheado se olvida. */
252
+ onSessionReset?: () => void;
253
+ /**
254
+ * Callback invocado cuando el backend acepta el lote de cierre, con el sessionId del
255
+ * registro cerrado. Ese registro se convierte en Feedback en segundos.
256
+ */
257
+ onSessionClosed?: (id: string) => void;
258
+ }
259
+ /**
260
+ * Sink real: transforma el envelope y hace `POST {baseUrl}/sdk/feedback`.
261
+ *
262
+ * El `sessionId` de cada sesión lo genera el SDK (UUID) y va en TODOS sus lotes, desde el
263
+ * primero. La API guarda cada lote bajo el sessionId que recibe, así que una sesión es un
264
+ * registro aunque no llegue ninguna respuesta. Antes lo asignaba la API en la respuesta del
265
+ * primer POST: si esa respuesta se perdía (la app pasaba a background con el POST en vuelo),
266
+ * el resto de la sesión acababa en otro registro.
267
+ *
268
+ * Garantías de entrega:
269
+ * - un lote que falla de forma transitoria (red, 5xx, 408, 429, sin respuesta en
270
+ * POST_TIMEOUT_MS) se guarda TAL CUAL —con su sessionId y su `completed`— y se reenvía
271
+ * antes del lote siguiente. Nunca vuelve al buffer del manager: allí se mezclaba con la
272
+ * sesión siguiente y viajaba con su registro. La promesa del sink no rechaza;
273
+ * - con `storage` (React Native) los pendientes sobreviven a que la app muera: el lote de
274
+ * cierre se guarda ANTES de enviarse y el sink del arranque siguiente lo reenvía. La API
275
+ * descarta los eventos repetidos de una misma sesión al ensamblarla;
276
+ * - `keepalive` para que el navegador no cancele el POST al navegar fuera ni al cerrar la
277
+ * página (sin `sendBeacon`: ver `sendBeaconImpl`);
278
+ * - sin credenciales, que es lo único que pasa el CORS de la API (`Allow-Origin: *`);
279
+ * - un 4xx se loguea y se descarta.
280
+ */
281
+ declare function createFeedbackSink(options: FeedbackSinkOptions): AnalyticsSink;
282
+
283
+ /**
284
+ * Custom logger to receive the SDK's debug output instead of the console.
285
+ * Only `log` is required; `warn`/`error`/`info` fall back to `log` when omitted.
286
+ * Lets the host pipe debug output to a file, Firebase, etc. `console` satisfies this shape.
287
+ */
288
+ interface DeepdotsLogger {
289
+ log: (...args: unknown[]) => void;
290
+ warn?: (...args: unknown[]) => void;
291
+ error?: (...args: unknown[]) => void;
292
+ info?: (...args: unknown[]) => void;
293
+ }
294
+ /**
295
+ * A session of the analytics channel as the Deepdots API sees it. Every session becomes ONE
296
+ * feedback, and `sessionId` is what the API stores as `sdkSessionId` on it: the value to look
297
+ * that feedback up with (`GET /feedbacks?filter={"where":{"sdkSessionId":"<sessionId>"}}`).
298
+ * A session that closes again keeps that one feedback: the API updates it.
299
+ * - `open`: the API acknowledged the session's first batch; its events keep accumulating.
300
+ * - `closed`: the API acknowledged the session's closing batch (`completed: true`); the
301
+ * feedback is created from it within seconds.
302
+ */
303
+ interface FeedbackSession {
304
+ sessionId: string;
305
+ status: 'open' | 'closed';
306
+ }
307
+ /** Signals the SDK detects on its own (see `DeepdotsInitParams.autoTrack`). */
308
+ interface AutoTrackOptions {
309
+ /** React Native: listen to `AppState` for session start/end. Default `true`. */
310
+ lifecycle?: boolean;
311
+ }
312
+ interface DeepdotsInitParams {
313
+ /** API key for authentication */
314
+ apiKey?: string;
315
+ /** Node environment: 'development' or 'production' */
316
+ nodeEnv?: 'development' | 'production';
317
+ /** Enable debug logging */
318
+ debug?: boolean;
319
+ /** Custom logger for debug output. When set (and `debug` is true), the SDK routes its logs here instead of `console`. Default: `console`. */
320
+ logger?: DeepdotsLogger;
321
+ /** Optional user id to send with popup events */
322
+ userId?: string;
323
+ /** Starts tracking enabled (default) or disabled (e.g. until consent is granted). Equivalent to calling `setTrackingEnabled` after init. */
324
+ trackingEnabled?: boolean;
325
+ /** Host app version (for analytics device info / Technology #11). */
326
+ appVersion?: string;
327
+ /** Injectable persistent storage (RN: adapter over AsyncStorage). If missing, uses localStorage/in-memory. */
328
+ storage?: KeyValueStorage;
329
+ /** Platform used in the analytics envelope. Default is 'web'; in RN pass 'android'/'ios'. */
330
+ platform?: 'web' | 'android' | 'ios';
331
+ /**
332
+ * BCP-47 language tag (e.g. 'es-ES') used for the analytics context AND for popup
333
+ * language segmentation (`segments.lang`). If omitted, the SDK auto-detects:
334
+ * `navigator.language` on web, or the `Intl` locale as a fallback (works in
335
+ * React Native with Hermes, where `navigator.language` is absent). If no source
336
+ * resolves a language, popups with `segments.lang` cannot be filtered and are shown.
337
+ */
338
+ language?: string;
339
+ /** Injectable device info (RN: from react-native-device-info). If missing, it is derived from the browser. */
340
+ device?: DeviceInfo;
341
+ /**
342
+ * React Native (iOS): opens a native background task while each analytics request is in
343
+ * flight, so the session's closing request finishes after the app goes to background
344
+ * instead of when the user opens the app again. `begin(name)` starts the task and returns
345
+ * the function that ends it (iOS `beginBackgroundTask` / `endBackgroundTask`). The SDK ends
346
+ * it when the request settles, or after 25 s. Use `backgroundTimerTask(BackgroundTimer)`
347
+ * for `react-native-background-timer`, iOS only. Without it, nothing changes: a closing
348
+ * request that does not finish is stored and sent on the next launch.
349
+ */
350
+ backgroundTask?: BackgroundTaskRunner;
351
+ /**
352
+ * What the SDK detects on its own. Everything is on by default; set a signal to `false` to
353
+ * turn it off. `lifecycle` (React Native): the SDK listens to `AppState` itself
354
+ * (`active` → session start, `inactive` → send pending data, `background` → session end), so
355
+ * the host does not need to call `onForeground` / `onInactive` / `onBackground`. Calling them
356
+ * as well is harmless: nothing is sent twice.
357
+ */
358
+ autoTrack?: AutoTrackOptions;
359
+ /**
360
+ * Analytics channel keys (`POST /sdk/feedback`). If provided, analytics is SENT
361
+ * to the configured integration; if missing, it stays in dry-run mode: nothing is sent, and the payload is only
362
+ * logged when `debug` is true.
363
+ */
364
+ analytics?: AnalyticsKeys;
365
+ /**
366
+ * Called when the analytics channel opens or closes a session (needs `analytics`), with the
367
+ * id the Deepdots API stores as `sdkSessionId` on the feedback the session becomes: send it
368
+ * to your backend to attach data to that feedback later. A session whose only batch is the
369
+ * closing one reports just `closed`. `closed` does not come when the page unloads before the
370
+ * closing request returns, for a session dropped after 30 min hidden, nor when the closing
371
+ * request fails (the API closes those itself, later): their id already came with `open`. Key
372
+ * by `sessionId`, not by order: the next session's `open` can arrive before the previous
373
+ * one's `closed`. Same value as `getFeedbackSessionId()` while the session is open.
374
+ */
375
+ onFeedbackSession?: (session: FeedbackSession) => void;
376
+ /**
377
+ * IP geolocation (country/city) added to analytics. Default `true`. The lookup calls
378
+ * third-party services (ipapi.co, then ipwho.is, then ipinfo.io as fallbacks, 3 s timeout
379
+ * each) and only runs when `analytics` is configured, tracking is enabled and the 30-day
380
+ * cache is missing or expired. Set `false` to never call them nor attach country/city.
381
+ */
382
+ geolocation?: boolean;
383
+ /**
384
+ * Internal user attributes known only by the host (language, age, plan, ...), sent
385
+ * to the backend Contact for segmentation/targeting. Requires `userId`. Equivalent to calling
386
+ * `setContactAttributes` after init (sends only when values changed from the last sync).
387
+ */
388
+ contactAttributes?: Record<string, string | number | boolean>;
389
+ /**
390
+ * Whether the SDK renders the popup "modal" (card + backdrop + positioning) around the survey.
391
+ * Default `true`. Only affects React Native (the survey WebView HTML); the web DOM popup is
392
+ * unaffected. With `false` the survey is delivered transparent and edge-to-edge so the host
393
+ * mounts its own Modal/container and controls the styling — avoids the "double modal" when the
394
+ * host already wraps the WebView. The survey stays fully functional (bridge, form, nav buttons,
395
+ * close). Ver `ReactNativePopupRenderer`.
396
+ */
397
+ renderChrome?: boolean;
398
+ /**
399
+ * Barra de progreso ("Question X of Y" + barra) en la cabecera del popup. Si se omite,
400
+ * manda el `showProgressBar` que la plataforma configura en el estilo del survey; `true` o
401
+ * `false` lo fuerzan desde el host. Solo se pinta con más de una página, fuera de la
402
+ * pantalla de inicio y antes de completar, igual que en la web de surveys.
403
+ */
404
+ showProgressBar?: boolean;
405
+ /**
406
+ * CSS propio del host, inyectado como último bloque de estilos del popup: gana en cascada
407
+ * sobre el del SDK y sobre el de `@magicfeedback/native` sin tener que tocar ninguno. Es la
408
+ * vía para reestilar el área de preguntas (enunciados, opciones, escalas) por integración,
409
+ * en vez de cambiar los defaults que comparten todos los clientes.
410
+ */
411
+ surveyCss?: string;
412
+ /**
413
+ * Nonce de la Content-Security-Policy de la página, para hosts con una CSP estricta
414
+ * (`style-src 'nonce-…'` sin `'unsafe-inline'`). El popup lo pone en cada `<style>` que
415
+ * inyecta en el `<head>` (hoja del survey, spinner, responsive, `surveyCss`, `@font-face`);
416
+ * sin él el navegador las bloquea y el survey sale sin estilos. Debe ser el MISMO nonce de
417
+ * la cabecera CSP de esa respuesta (en Angular, el token `CSP_NONCE`). Solo web: en React
418
+ * Native el survey vive en su propio WebView y no le afecta la CSP del host.
419
+ */
420
+ cspNonce?: string;
421
+ }
422
+ interface DeepdotsConfig {
423
+ /** API key for authentication */
424
+ apiKey?: string;
425
+ /** Enable debug logging */
426
+ debug?: boolean;
427
+ /** Optional user id to send with popup events */
428
+ userId?: string;
429
+ }
430
+ /**
431
+ * Options for configuring survey triggers
432
+ */
433
+ interface TriggerConfig {
434
+ /** Trigger type: 'time' (delay), 'scroll' (scroll percentage), 'exit' (route exit), 'click' (element id), 'event' (host event) */
435
+ type: 'time' | 'scroll' | 'exit' | 'click' | 'event';
436
+ /** Value for the trigger (milliseconds for time, percentage for scroll, seconds for exit, element id for click, event name for event) */
437
+ value?: number | string;
438
+ /** Survey ID to show when triggered */
439
+ surveyId: string;
440
+ /** Optional popup definition id (used to disambiguate repeated survey ids) */
441
+ popupId?: string;
442
+ /**
443
+ * Seconds to wait once the trigger fires before showing the popup ("Delay" in the Admin).
444
+ * For `exit` it is the wait on the next route. 0 or missing = at once.
445
+ */
446
+ delaySeconds?: number;
447
+ }
448
+ /**
449
+ * Event types emitted by the SDK
450
+ */
451
+ type DeepdotsEventType = 'popup_shown' | 'popup_clicked' | 'survey_completed'
452
+ /**
453
+ * Fallo al enviar una página del survey (el popup enseña `errorSubmit`). `data`:
454
+ * `{reason: 'send_failed' | 'no_page' | 'unknown', message}`. No es interacción del
455
+ * usuario: no marca el popup como PARTIAL. También va a analítica como `deepdots_survey_error`.
456
+ */
457
+ | 'survey_error';
458
+ /**
459
+ * Event payload structure
460
+ */
461
+ interface DeepdotsEvent {
462
+ type: DeepdotsEventType;
463
+ surveyId: string;
464
+ timestamp: number;
465
+ data?: Record<string, unknown>;
466
+ }
467
+ /**
468
+ * Event listener callback
469
+ */
470
+ type EventListener = (event: DeepdotsEvent) => void;
471
+ /**
472
+ * Motivo del `deepdots_session_end` (último lote de la sesión, enviado con `completed:true`):
473
+ * - `page_hide`: la página web se cierra o se navega fuera (`pagehide`).
474
+ * - `background`: la app pasa a background (RN/nativo). Única señal disponible en móvil:
475
+ * el kill de la app por el usuario o el SO NO produce ningún callback.
476
+ * - `user_change`: `setUserId()` o un `init()` con otro `userId` (login/logout del host).
477
+ * - `tracking_disabled`: `setTrackingEnabled(false)` (consentimiento revocado).
478
+ * - `manual`: `endSession()` llamado por el host.
479
+ * - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta (web). La sesión
480
+ * anterior se cierra y se abre otra, como hace GA con su timeout de sesión.
481
+ */
482
+ type SessionEndReason = 'page_hide' | 'background' | 'user_change' | 'tracking_disabled' | 'manual' | 'idle_timeout';
483
+ /**
484
+ * Motivo del `deepdots_session_start` (param `reason`): por qué EMPIEZA la sesión. Permite a
485
+ * analytics separar una carga/arranque real de una vuelta desde background ("Started here").
486
+ * Mismos valores que el SDK nativo donde el significado coincide:
487
+ * - `cold_start`: `init()` (carga de la página / arranque de la app RN) sin sesión suspendida
488
+ * que reanudar. Una recarga en menos de 1 min no emite `session_start` sino
489
+ * `deepdots_session_resume`.
490
+ * - `foreground`: `onForeground()` (RN, AppState 'active') tras un cierre (`onBackground()`
491
+ * o `endSession()`). Con la sesión abierta no emite nada.
492
+ * - `tracking_enabled`: `setTrackingEnabled(true)` (consentimiento concedido).
493
+ * - `user_change`: `setUserId()` o un `init()` con otro `userId`, tras cerrar la del anterior.
494
+ * - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta (web): la sesión
495
+ * anterior se cerró (o se descartó) y empieza otra.
496
+ * - `bfcache_restore`: la página vuelve de la bfcache (botón atrás, `pageshow` con
497
+ * `persisted`) fuera de la ventana de reanudación (web).
498
+ */
499
+ type SessionStartReason = 'cold_start' | 'foreground' | 'tracking_enabled' | 'user_change' | 'idle_timeout' | 'bfcache_restore';
500
+ /** Trigger type used by remote popup definitions */
501
+ type PopupTriggerType = 'time_on_page' | 'scroll' | 'exit' | 'click' | 'event';
502
+ type PopupTriggerConditionStatus = 'SHOWED' | 'PARTIAL' | 'COMPLETED';
503
+ declare const POPUP_TRIGGER_CONDITION_STATUSES: PopupTriggerConditionStatus[];
504
+ /** Extra condition used to activate the popup */
505
+ interface PopupTriggerCondition {
506
+ answered: PopupTriggerConditionStatus;
507
+ cooldownDays: number;
508
+ }
509
+ /** Trigger attached to the popup definition */
510
+ interface PopupTrigger {
511
+ type: PopupTriggerType;
512
+ value: number | string;
513
+ /**
514
+ * "Delay (seconds)" in the Admin: wait this long after the trigger fires before showing the
515
+ * popup. 0 or missing = at once. For `exit` the Admin stores the delay here and `value` is 0.
516
+ */
517
+ delaySeconds?: number;
518
+ }
519
+ /** Accept action (open survey) */
520
+ interface PopupActionAccept {
521
+ label: string;
522
+ surveyId: string;
523
+ }
524
+ /** Decline action */
525
+ interface PopupActionDecline {
526
+ label: string;
527
+ cooldownDays?: number;
528
+ }
529
+ /** Start Surveys Action */
530
+ interface PopupActionStart {
531
+ label: string;
532
+ }
533
+ /** Complete action (accept and auto-complete survey) */
534
+ interface PopupActionComplete {
535
+ label: string;
536
+ surveyId: string;
537
+ autoCompleteParams: Record<string, unknown>;
538
+ cooldownDays?: number;
539
+ }
540
+ /** Set of actions available in the popup */
541
+ interface PopupActions {
542
+ accept?: PopupActionAccept;
543
+ decline?: PopupActionDecline;
544
+ complete?: PopupActionComplete;
545
+ start?: PopupActionStart;
546
+ back?: PopupActionDecline;
547
+ }
548
+ /** Fuente personalizable del popup + survey (viene de la API por popup) */
549
+ interface PopupFont {
550
+ /** Nombre de la familia. Ej: "Inter" (nombre limpio, NO un stack). */
551
+ family: string;
552
+ /** Opcional: URL a un archivo de fuente (woff2/ttf/otf) para armar un @font-face. */
553
+ url?: string;
554
+ }
555
+ /** Configurable popup styles */
556
+ interface PopupStyle {
557
+ theme: 'light' | 'dark';
558
+ position: 'bottom' | 'bottom-right' | 'bottom-left' | 'top' | 'top-right' | 'top-left' | 'center';
559
+ /** @deprecated Not used by the SDK; kept only for API compatibility */
560
+ imageUrl?: string | null;
561
+ /** Fuente personalizada. Si falta, se mantiene el comportamiento actual. */
562
+ font?: PopupFont;
563
+ }
564
+ /** Segments/targeting rules for showing the popup */
565
+ interface PopupSegments {
566
+ lang?: string[];
567
+ path?: string[];
568
+ /**
569
+ * App routes where it must NOT be shown. Wins over `path`: a route listed here
570
+ * blocks the popup even if `path` matches it (so `path: ['/']` +
571
+ * `excludedPaths: ['/cart']` = everywhere but the cart).
572
+ * Same matching rules as `path`: an absolute URL matches the full href, an entry
573
+ * starting with `/` matches any href containing it (this is what covers hash
574
+ * routes like `/#/cart`), anything else matches the pathname exactly.
575
+ */
576
+ excludedPaths?: string[];
577
+ [key: string]: unknown;
578
+ }
579
+ /** Full popup definition */
580
+ interface PopupDefinition {
581
+ id: string;
582
+ title: string;
583
+ message: string;
584
+ triggers: PopupTrigger[];
585
+ cooldown?: PopupTriggerCondition[];
586
+ actions?: PopupActions;
587
+ surveyId: string;
588
+ productId: string;
589
+ style?: PopupStyle;
590
+ segments?: PopupSegments;
591
+ /**
592
+ * Versión del survey asignada en el Admin (latest o fijada) y su survey SDK (DD-70). La manda
593
+ * la API desde DD-70; con APIs anteriores falta y se usa el survey SDK empaquetado.
594
+ */
595
+ surveyFrontend?: PopupSurveyFrontend | null;
596
+ }
597
+ /** `surveyFrontend` de `GET /sdk/{publicKey}/popups` (DD-70). */
598
+ interface PopupSurveyFrontend {
599
+ /** Versión de MagicSurvey resuelta (X.Y.Z). */
600
+ version?: string;
601
+ /** "latest" o la X.Y.Z fijada. */
602
+ preference?: string;
603
+ status?: string;
604
+ /** `@magicfeedback/native` con el que se construyó esa versión; null si no se conoce. */
605
+ sdkVersion?: string | null;
606
+ }
607
+
608
+ /**
609
+ * Ajustes de presentación que no vienen del estilo del popup. Van agrupados para no seguir
610
+ * alargando la lista posicional de `show`, que ya arrastra doce parámetros.
611
+ */
612
+ interface PopupRenderOptions {
613
+ /**
614
+ * Título de la cabecera: el `title` de la definición del popup, tal cual llega de la API.
615
+ * Varía por popup y vacío es un valor válido (la cabecera se queda solo con la X).
616
+ */
617
+ title?: string;
618
+ /** Barra de progreso: `undefined` deja decidir a la plataforma, `true`/`false` la fuerzan. */
619
+ showProgressBar?: boolean;
620
+ /** CSS del host, inyectado el último: gana sobre el del SDK y el de `@magicfeedback/native`. */
621
+ surveyCss?: string;
622
+ /**
623
+ * Idioma con el que arranca el chrome del popup (botones, progreso, aria-labels, errores).
624
+ * Es el idioma resuelto en `init()` (host > navigator > Intl). Lo pisa el idioma del survey
625
+ * (`formData.lang[0]`) en cuanto este carga, y ambos los pisa `actions.*.label` de la API.
626
+ */
627
+ language?: string;
628
+ /**
629
+ * Nonce de la Content-Security-Policy del host (`DeepdotsInitParams.cspNonce`). Se pone en
630
+ * cada `<style>` que inyecta el popup DOM; sin él, una CSP con `style-src 'nonce-…'` bloquea
631
+ * la hoja del survey. No aplica a React Native (el survey vive en su propio WebView).
632
+ */
633
+ cspNonce?: string;
634
+ /**
635
+ * `surveyFrontend.sdkVersion` del popup (DD-70): versión de `@magicfeedback/native` asignada
636
+ * al survey en el Admin. Se usa si está en el rango soportado y carga; si no, la empaquetada.
637
+ */
638
+ surveySdkVersion?: string | null;
639
+ /** `init({debug})`, para el log de la versión de survey SDK elegida. */
640
+ debug?: boolean;
641
+ }
642
+ interface PopupRenderer {
643
+ /** Preparar recursos si aplica */
644
+ init?(): void;
645
+ /**
646
+ * Traer por adelantado lo que la apertura necesitará, en idle. Opcional: solo lo implementan
647
+ * los renderers cuyo coste de apertura se paga delante del usuario.
648
+ */
649
+ preload?(): void;
650
+ /** Mostrar popup */
651
+ show(surveyId: string, productId: string, actions: PopupActions | undefined, emit: (type: DeepdotsEventType, surveyId: string, data?: Record<string, unknown>) => void, onClose: () => void, env?: string, userId?: string, style?: PopupStyle, sessionId?: string, miniService?: string, analyticsFeedbackSessionId?: string, renderChrome?: boolean, options?: PopupRenderOptions): void;
652
+ /** Ocultar popup */
653
+ hide(): void;
654
+ /**
655
+ * ¿Hay un popup a la vista ahora mismo? Opcional. Con él, el core no da por mostrado un popup
656
+ * que el renderer no va a pintar (porque ya hay otro abierto): ni `popup_shown`, ni SHOWED, ni
657
+ * cooldown gastado. Sin él (renderers del host, RN), el core se comporta como siempre.
658
+ */
659
+ isShowing?(): boolean;
660
+ }
661
+ /** Renderer que no hace nada (SSR / entornos sin DOM) */
662
+ declare class NoopPopupRenderer implements PopupRenderer {
663
+ show(): void;
664
+ hide(): void;
665
+ }
666
+ /** Renderer para navegadores usando la implementación actual basada en renderPopup */
667
+ declare class BrowserPopupRenderer implements PopupRenderer {
668
+ private container;
669
+ private visible;
670
+ init(): void;
671
+ /**
672
+ * Descarga el chunk de `renderPopup` antes de que ningún trigger dispare, para que abrir el
673
+ * popup no empiece por esperar ~238 KB de JS.
674
+ */
675
+ preload(): void;
676
+ show(surveyId: string, productId: string, actions: PopupActions | undefined, emit: (type: DeepdotsEventType, surveyId: string, data?: Record<string, unknown>) => void, onClose: () => void, env?: string, userId?: string, style?: PopupStyle, sessionId?: string, miniService?: string, analyticsFeedbackSessionId?: string, _renderChrome?: boolean, // solo aplica a RN (WebView); el popup DOM web siempre lleva su chrome
677
+ options?: PopupRenderOptions): void;
678
+ isShowing(): boolean;
679
+ hide(): void;
680
+ }
681
+ /** Factoría para obtener renderer por defecto */
682
+ declare function createDefaultRenderer(): PopupRenderer;
683
+
684
+ /** Valor de un atributo de contact (info interna del usuario que solo conoce el host). */
685
+ type ContactAttributeValue = string | number | boolean;
686
+ type ContactAttributes = Record<string, ContactAttributeValue>;
687
+ /** Body de `POST /sdk/popups/contact`. */
688
+ interface ContactBody {
689
+ publicKey: string;
690
+ userId: string;
691
+ userAttributes: ContactAttributes;
692
+ }
693
+ interface ContactManagerOptions {
694
+ storage: KeyValueStorage;
695
+ publicKey: string;
696
+ userId: string;
697
+ /**
698
+ * Envío real (inyectable para tests): hace el `POST /sdk/popups/contact`. Tiene que
699
+ * RECHAZAR si la API no acepta el envío (sin red o respuesta no-2xx): solo así se sabe
700
+ * que no hay que guardar la caché y que la llamada siguiente debe reintentar.
701
+ */
702
+ post: (body: ContactBody) => Promise<void>;
703
+ }
704
+ /**
705
+ * Gestiona los atributos de contact del usuario identificado (`userId` del init).
706
+ * Solo envía cuando cambian respecto a lo último persistido en storage, para ahorrar
707
+ * peticiones (el host puede llamar `setAttributes` en cada identificación sin miedo).
708
+ */
709
+ declare class ContactManager {
710
+ private readonly storage;
711
+ private readonly publicKey;
712
+ private readonly userId;
713
+ private readonly post;
714
+ constructor(options: ContactManagerOptions);
715
+ /**
716
+ * Envía los atributos si cambiaron respecto a lo último enviado. La caché solo se guarda
717
+ * cuando la API acepta el envío; si falla, la llamada siguiente reintenta. Nunca rechaza.
718
+ * @returns `true` si se envió, `false` si no hubo cambios o el envío falló.
719
+ */
720
+ setAttributes(attributes: ContactAttributes): Promise<boolean>;
721
+ }
722
+
723
+ /**
724
+ * Crash & error reporting (Stability #14–17) — captura de errores GESTIONADOS.
725
+ *
726
+ * - `reportError()`: API pública para el host (app viva) → emite `deepdots_app_crash` ya.
727
+ * - handlers de `window` (errores no capturados): persisten a disco y se reenvían
728
+ * en el siguiente arranque (el proceso puede morir antes del flush normal).
729
+ *
730
+ * El contexto de device/sesión se captura EN EL MOMENTO del crash y se guarda en el
731
+ * record — no se lee del envelope en el replay (el replay puede ocurrir en otra
732
+ * app_version/OS). Las dims OS/device en Web suelen ir vacías (se derivan del UA en backend).
733
+ */
734
+
735
+ type CrashSeverity = 'fatal' | 'error' | 'warning';
736
+ interface CrashRecord {
737
+ crashedAt: number;
738
+ crashType: string;
739
+ message: string;
740
+ stack: string;
741
+ fatal: boolean;
742
+ handled: boolean;
743
+ severity: CrashSeverity;
744
+ sessionId: string | null;
745
+ appVersion?: string;
746
+ osVersion?: string;
747
+ deviceModel?: string;
748
+ context?: Record<string, string>;
749
+ }
750
+ interface ReportErrorOptions {
751
+ severity?: CrashSeverity;
752
+ handled?: boolean;
753
+ context?: Record<string, unknown>;
754
+ }
755
+ interface DeviceSnapshot {
756
+ appVersion?: string;
757
+ osVersion?: string;
758
+ deviceModel?: string;
759
+ }
760
+ /** Forma mínima de `global.ErrorUtils` de React Native. */
761
+ interface ReactNativeErrorUtils {
762
+ getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;
763
+ setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;
764
+ }
765
+ interface CrashReporterOptions {
766
+ storage: KeyValueStorage;
767
+ /** Emite un evento deepdots_app_crash AHORA (app viva). */
768
+ emit: (params: Record<string, unknown>) => void;
769
+ /** Snapshot de device en el momento del crash. */
770
+ device: () => DeviceSnapshot;
771
+ /** session_id en el momento del crash. */
772
+ sessionId: () => string | null;
773
+ now?: () => number;
774
+ /** Kill-switch de consentimiento. */
775
+ enabled?: () => boolean;
776
+ }
777
+ /** Convierte un CrashRecord en los params del evento `deepdots_app_crash` (omite undefined). */
778
+ declare function crashRecordToParams(r: CrashRecord): Record<string, unknown>;
779
+ declare class CrashReporter {
780
+ private options;
781
+ private now;
782
+ /** Los handlers de `window` ya están puestos: `install()` es idempotente. */
783
+ private windowInstalled;
784
+ /** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
785
+ private hookedErrorUtils;
786
+ constructor(options: CrashReporterOptions);
787
+ private isEnabled;
788
+ /** Construye un CrashRecord capturando contexto en el momento del crash. */
789
+ private buildRecord;
790
+ /** API pública del host: reporta un error (app viva) → emite el evento ya. */
791
+ reportError(error: unknown, options?: ReportErrorOptions): void;
792
+ /** Captura un error no manejado (fatal) → persiste a disco para replay en el siguiente arranque. */
793
+ captureUnhandled(error: unknown): void;
794
+ /** Persiste un crash no capturado a disco para reenviarlo en el siguiente arranque. */
795
+ private persist;
796
+ /** Lee y vacía la cola de crashes pendientes (llamado en init para el replay). */
797
+ drainPendingCrashes(): CrashRecord[];
798
+ /** Instala los handlers globales de errores no capturados (no-op sin `window`). Idempotente. */
799
+ install(): void;
800
+ /** Engancha `global.ErrorUtils` de RN (no hay `window`): persiste y encadena al handler previo. Idempotente por instancia de ErrorUtils. */
801
+ installReactNative(errorUtils: ReactNativeErrorUtils): void;
802
+ /** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
803
+ _persistForTest(error: unknown): void;
804
+ }
805
+
806
+ /**
807
+ * Messaging (#18–22): tracking de notificaciones del host (push / in-app).
808
+ * Un único evento reservado `deepdots_message` con un campo `stage` discriminador;
809
+ * el funnel se correlaciona por `message_id` y se agrupa por `message_title`.
810
+ */
811
+ type MessageStage = 'delivered' | 'clicked' | 'converted';
812
+ /** Canales válidos. Un mensaje tiene UN canal: se valida en runtime porque el host puede no ser TS. */
813
+ declare const MESSAGE_CHANNELS: readonly ["push", "in_app"];
814
+ type MessageChannel = (typeof MESSAGE_CHANNELS)[number];
815
+ interface TrackMessageOptions {
816
+ /** Identificador del mensaje/notificación — correlaciona el funnel delivered→clicked→converted. */
817
+ id: string;
818
+ /** Título del mensaje — dimensión de agrupación de #18–22. */
819
+ title: string;
820
+ /** Canal de entrega. */
821
+ channel: MessageChannel;
822
+ /** Nombre de la campaña (opcional). */
823
+ campaign?: string;
824
+ /** Valor de conversión (opcional, típico en `stage: 'converted'`). */
825
+ value?: number;
826
+ currency?: string;
827
+ /** Parámetros libres adicionales. */
828
+ params?: Record<string, unknown>;
829
+ }
830
+ /** Construye los params del evento `deepdots_message` (omite opcionales ausentes). */
831
+ declare function buildMessageParams(stage: MessageStage, o: TrackMessageOptions): Record<string, unknown>;
832
+ /** Techo de `message_id` vigilados por sesión; los más antiguos se evictan (memoria acotada). */
833
+ declare const MAX_TRACKED_MESSAGES = 500;
834
+ type MessageRejectionReason = 'invalid_channel' | 'duplicate_stage' | 'channel_conflict';
835
+ type MessageGuardVerdict = {
836
+ emit: true;
837
+ } | {
838
+ emit: false;
839
+ reason: MessageRejectionReason;
840
+ detail: string;
841
+ };
842
+ /**
843
+ * Protege el funnel de Messaging de las formas imposibles que el host puede producir por error
844
+ * (visto en producción: CTR > 100% por falta de `delivered` + el mismo `message_id` reportado en
845
+ * dos canales). Tres reglas, todas dentro de la sesión (se reinicia en cada `init()`):
846
+ *
847
+ * 1. `channel` fuera de `MESSAGE_CHANNELS` → se descarta el evento.
848
+ * 2. Un `(message_id, stage)` ya emitido → se emite una sola vez.
849
+ * 3. Un `message_id` ya visto en un canal → se descartan los eventos de otro canal.
850
+ *
851
+ * Los eventos rechazados NO mutan el estado: un rechazo nunca "consume" el stage bueno.
852
+ * Lo que el SDK no puede arreglar es la ausencia de `delivered`: eso lo instrumenta el host.
853
+ */
854
+ declare class MessageGuard {
855
+ private maxTrackedMessages;
856
+ /** message_id → canal fijado + stages ya emitidos. El orden de inserción marca la eviction. */
857
+ private seen;
858
+ constructor(maxTrackedMessages?: number);
859
+ evaluate(stage: MessageStage, options: TrackMessageOptions): MessageGuardVerdict;
860
+ /** Olvida todo lo vigilado (nueva sesión). */
861
+ reset(): void;
862
+ private remember;
863
+ }
864
+
865
+ /**
866
+ * Main class for managing survey popups
867
+ */
868
+ declare class DeepdotsPopups {
869
+ private config;
870
+ private listeners;
871
+ private triggers;
872
+ private initialized;
873
+ private renderer;
874
+ /** Logger para el output de debug. Default `console`; el host puede inyectar el suyo en init(). */
875
+ private logger;
876
+ private popupDefinitions;
877
+ private popupsLoaded;
878
+ /**
879
+ * `true` mientras el `GET /sdk/{apiKey}/popups` de `init()` está en vuelo. En esa ventana los
880
+ * disparos del host (`triggerEvent`, `triggerSurvey`) no tienen contra qué evaluarse, así que
881
+ * se guardan en `pendingTriggers` y se reproducen al cargar. Click, scroll, time y exit no
882
+ * hacen falta: son listeners que `autoLaunch` instala ya con las definiciones cargadas.
883
+ */
884
+ private awaitingPopups;
885
+ private pendingTriggers;
886
+ private pendingAutoLaunch;
887
+ private answeredSurveys;
888
+ private surveyProgress;
889
+ private lastShown;
890
+ private surveyToPopupId;
891
+ private deferredExitTimers;
892
+ /** Popups esperando su `delaySeconds` (uno por popup). */
893
+ private delayedPopups;
894
+ /** Última pantalla de `setScreen` (React Native). */
895
+ private currentScreen;
896
+ private baseUrl;
897
+ private env;
898
+ /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
899
+ private renderChrome;
900
+ /** Barra de progreso. undefined = la decide la plataforma (style.showProgressBar). */
901
+ private showProgressBar;
902
+ /** CSS del host inyectado al final de los estilos del popup. */
903
+ private surveyCss;
904
+ private cspNonce;
905
+ /** Identidad + sesión (Fase 1 tracking). Null hasta init(). */
906
+ private tracking;
907
+ /** Capa de analytics (canal separado del feedback). Null hasta init(). */
908
+ private analytics;
909
+ /** feedbackSessionId cacheado del canal de analytics (devuelto por POST /sdk/feedback). */
910
+ private analyticsFeedbackSessionId;
911
+ /** `init({ onFeedbackSession })`: avisa al host al abrir y cerrar cada registro. */
912
+ private onFeedbackSession;
913
+ /** Timer del flush periódico de analytics (cada ANALYTICS_FLUSH_INTERVAL_MS). */
914
+ private analyticsFlushTimer;
915
+ /** Crash & error reporting (#14–17). Null hasta init(). */
916
+ private crashReporter;
917
+ /** ErrorUtils de RN recibido del host (o del Provider); se engancha en cuanto haya consentimiento. */
918
+ private rnErrorUtils;
919
+ /** Protecciones del funnel de Messaging (#18–22). Vigencia de sesión: se reinicia en init(). */
920
+ private messageGuard;
921
+ /** Observador de navegación (Fase 2): emite page_view por el canal de analytics. */
922
+ private navObserver;
923
+ /** Tiempo activo (engagement time, #8). */
924
+ private engagement;
925
+ /** Atributos internos del usuario identificado → POST /sdk/popups/contact. Null si no hay userId. */
926
+ private contact;
927
+ /** Storage resuelto en init() (inyectado por el host o localStorage). Reusado al cambiar de usuario. */
928
+ private storage;
929
+ /** Marca si ya se inició la navegación manual (setScreen) — para RN sin History API. */
930
+ private navStarted;
931
+ /**
932
+ * `true` entre `session_start` y `session_end`. Hace idempotente tanto la apertura como
933
+ * el cierre (p. ej. `visibilitychange` + `pagehide` seguidos) y permite abrir una sesión
934
+ * nueva al volver a foreground o al conceder el consentimiento más tarde.
935
+ */
936
+ private sessionOpen;
937
+ /** Último `user_engagement` emitido (ms epoch): marca el latido. */
938
+ private lastEngagementAt;
939
+ /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
940
+ private hiddenAt;
941
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
942
+ private appStateSubscription;
943
+ /**
944
+ * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
945
+ * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
946
+ */
947
+ private suspended;
948
+ /** Integración de analytics del init: la sesión suspendida solo la hereda la misma. */
949
+ private analyticsIntegration;
950
+ /**
951
+ * Idioma resuelto en init() (explícito > navigator.language > Intl). Única fuente de
952
+ * verdad para el context de analytics Y para la segmentación por idioma de los popups.
953
+ */
954
+ private language;
955
+ /** `geolocation` del init: si es false no se usa ni la caché ni el lookup. */
956
+ private geoEnabled;
957
+ /** Solo se consulta a terceros si el país/ciudad se va a enviar (analytics configurado). */
958
+ private geoWanted;
959
+ /** Evita más de un lookup por instancia (el consentimiento puede ir y venir). */
960
+ private geoLookupStarted;
961
+ /** Initialize the SDK with configuration */
962
+ init(config: DeepdotsInitParams): void;
963
+ /** User id actual (generado por el SDK o provisto por el cliente). Null si tracking off. */
964
+ getUserId(): string | null;
965
+ /** Session id de navegación actual. Null si tracking off. */
966
+ getSessionId(): string | null;
967
+ /**
968
+ * Id del registro de analytics abierto: el `sessionId` que devolvió `POST /sdk/feedback`,
969
+ * que la API guarda como `sdkSessionId` en el Feedback en que se convierte la sesión. No es
970
+ * `getSessionId()`. Null hasta que el backend acepta el primer lote y de nuevo al cerrar la
971
+ * sesión: para saber también qué registro se cerró, usa `init({ onFeedbackSession })`.
972
+ */
973
+ getFeedbackSessionId(): string | null;
974
+ /** Avisa al host del registro abierto o cerrado; un fallo del host no corta el envío. */
975
+ private notifyFeedbackSession;
976
+ /** Activa/desactiva el tracking (identidad + sesión + analytics). Kill-switch del contrato §7bis. */
977
+ setTrackingEnabled(enabled: boolean): void;
978
+ /** Registra un evento de analítica (modelo GA: nombre + params). No-op si tracking off. */
979
+ track(name: string, params?: Record<string, unknown>): void;
980
+ /** User attributes para breakdowns (registration_status, pass_type, sector, pass_status…). */
981
+ setUserAttributes(attributes: Record<string, string | number | boolean>): void;
982
+ /**
983
+ * Registra/actualiza una métrica (valor medible) → `feedback.metrics` del body.
984
+ * Persistente y sobrescribe por key. No-op si tracking off.
985
+ */
986
+ setMetric(key: string, value: string | number | boolean): void;
987
+ /** Reporta un error del host (manejado o no) → evento `deepdots_app_crash`. No-op si tracking off. */
988
+ reportError(error: unknown, options?: ReportErrorOptions): void;
989
+ /**
990
+ * Engancha `global.ErrorUtils` de RN para capturar errores JS no manejados. Con tracking off
991
+ * se recuerda y se engancha cuando se conceda el consentimiento (`setTrackingEnabled(true)`).
992
+ */
993
+ installReactNativeCrashHandler(errorUtils: ReactNativeErrorUtils): void;
994
+ /**
995
+ * Pone los handlers de errores no capturados: `window` en web y `ErrorUtils` en RN (el que
996
+ * pasó el host o, si no pasó ninguno, `globalThis.ErrorUtils`, para que un `init()` sin
997
+ * `setupReactNative` también capture). Solo con consentimiento; idempotente, así que se
998
+ * llama en `init()` y cada vez que se activa el tracking.
999
+ */
1000
+ private installCrashHandlers;
1001
+ /**
1002
+ * Info interna del usuario que solo conoce el host (idioma, edad, plan…), persistida en el
1003
+ * Contact del backend para segmentación/targeting de popups. Identificada por el `userId` del
1004
+ * init. Solo envía si los atributos cambiaron (diff en storage). No-op si tracking off o sin userId.
1005
+ * @returns `true` si se envió al backend, `false` si no hubo cambios o está deshabilitado.
1006
+ */
1007
+ setContactAttributes(attributes: ContactAttributes): Promise<boolean>;
1008
+ /** Marca el inicio de un mini-service; etiqueta los eventos siguientes. No-op si tracking off. */
1009
+ enterMiniService(name: string, entryPointType?: string): void;
1010
+ /** Cierra el mini-service `name` (emite `mini_service_exit` con duración, #27). No-op si tracking off o si ese no está activo. */
1011
+ exitMiniService(name: string): void;
1012
+ /** Findability (#31/#35): registra una búsqueda. `has_results` se deriva de `resultsCount`. */
1013
+ trackSearch(query: string, resultsCount: number, params?: Record<string, unknown>): void;
1014
+ /** Findability friction (#34/#35): señal de fricción con su `friction_topic`. */
1015
+ trackFindabilityFriction(frictionTopic: string, params?: Record<string, unknown>): void;
1016
+ /** Funnel: un paso del embudo, correlacionado por `taskId`. El backend reconstruye conversión/drop-off/tiempo. */
1017
+ trackFunnelStep(funnel: string, step: string, taskId: string, params?: Record<string, unknown>): void;
1018
+ /**
1019
+ * Product Effectiveness: una interacción significativa del usuario (`interaction_type` es la
1020
+ * dimensión de agrupación, p. ej. `get_help`, `homepage`, `contact_support`).
1021
+ *
1022
+ * Existe como evento RESERVADO para que la convención no la invente cada host: un `track()`
1023
+ * custom acaba como `deepdots_event_…` y no lo cuenta la analítica de effectiveness.
1024
+ * Un `interactionType` vacío se descarta con warning (no aporta dato agrupable).
1025
+ */
1026
+ trackMeaningfulInteraction(interactionType: string, params?: Record<string, unknown>): void;
1027
+ /**
1028
+ * Messaging (#18–22): registra una etapa del funnel de una notificación (push/in-app).
1029
+ * No-op si tracking off. El evento se descarta (con warning) si el `channel` no es válido,
1030
+ * si ese `(message_id, stage)` ya se emitió en la sesión, o si el `message_id` ya se reportó
1031
+ * en otro canal — ver `MessageGuard`.
1032
+ */
1033
+ trackMessage(stage: MessageStage, options: TrackMessageOptions): void;
1034
+ /**
1035
+ * Navegación MANUAL (entornos sin History API, p. ej. React Native con React Navigation).
1036
+ * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
1037
+ */
1038
+ setScreen(name: string): void;
1039
+ /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
1040
+ onForeground(): void;
1041
+ /**
1042
+ * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
1043
+ * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
1044
+ * envía el último lote con `completed:true`.
1045
+ *
1046
+ * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
1047
+ */
1048
+ onBackground(): void;
1049
+ /**
1050
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
1051
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
1052
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
1053
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
1054
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
1055
+ */
1056
+ onInactive(): void;
1057
+ /**
1058
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
1059
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
1060
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
1061
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
1062
+ * `autoTrack.lifecycle: false` lo apaga.
1063
+ */
1064
+ private installAutoLifecycle;
1065
+ /**
1066
+ * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
1067
+ * `session_end` y envía el último lote con `completed:true`.
1068
+ */
1069
+ endSession(): void;
1070
+ /**
1071
+ * Cambio de usuario (login / logout / cambio de cuenta). Cierra la sesión del usuario
1072
+ * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
1073
+ * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
1074
+ *
1075
+ * Equivale a llamar a `init()` otra vez con otro `userId`.
1076
+ */
1077
+ setUserId(userId?: string): void;
1078
+ /**
1079
+ * Cierra la sesión actual: vuelca todo lo que quedaba abierto y envía el último lote
1080
+ * marcado con `completed:true`, para que el backend cierre el registro. El `sessionId`
1081
+ * cacheado se olvida → el lote siguiente abre un registro nuevo.
1082
+ *
1083
+ * Idempotente: dos cierres seguidos (p. ej. `visibilitychange` + `pagehide`) no duplican
1084
+ * el `session_end`.
1085
+ */
1086
+ private closeSession;
1087
+ /**
1088
+ * Abre sesión (`session_start`) si no hay una abierta y el tracking está activo. Idempotente.
1089
+ * El `reason` dice por qué empieza (ver `SessionStartReason`):
1090
+ * - `cold_start`: init() (carga de la página / arranque de la app RN).
1091
+ * - `foreground`: onForeground() tras un cierre (RN).
1092
+ * - `tracking_enabled`: setTrackingEnabled(true).
1093
+ * - `user_change`: setUserId() o init() con otro userId.
1094
+ * - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta.
1095
+ * - `bfcache_restore`: vuelta desde la bfcache fuera de la ventana de reanudación.
1096
+ * Si hay una sesión suspendida a tiempo emite `deepdots_session_resume` en su lugar, sin reason.
1097
+ */
1098
+ private openSession;
1099
+ /** Web: si la pestaña se ve. Sin `document` (RN) manda AppState vía onForeground/onBackground. */
1100
+ private isDocumentVisible;
1101
+ /** Payload que se ENVIARÍA al endpoint de analytics (no envía ni vacía el buffer). */
1102
+ previewAnalytics(): AnalyticsEnvelope;
1103
+ /**
1104
+ * Envía el lote acumulado de analytics y vacía el buffer.
1105
+ * `final: true` (cierre de página/app): el lote no espera al primer POST en vuelo, porque
1106
+ * el documento se muere; un lote que falle por red o 5xx se re-encola para el siguiente flush.
1107
+ */
1108
+ flushAnalytics(options?: {
1109
+ final?: boolean;
1110
+ sessionEnd?: boolean;
1111
+ }): void;
1112
+ /**
1113
+ * Emite un evento `user_engagement` con el tiempo activo acumulado (#8) y la pantalla en
1114
+ * curso: `screen` y `path` (los mismos que llevará su `page_view`) y `screen_seconds` (lo
1115
+ * que lleva en ella, medido como el `duration_seconds` del `page_view`).
1116
+ *
1117
+ * El `page_view` sale al SALIR de la pantalla; si el cierre no llega nunca (pestaña dormida
1118
+ * y descartada al volver, pestaña o app matada en segundo plano), la última pantalla de la
1119
+ * sesión se perdía y una visita de una sola pantalla se quedaba sin ninguna. Con la pantalla
1120
+ * en el latido y en el engagement de ocultar la pestaña, el backend la reconstruye.
1121
+ *
1122
+ * En los cierres (`closeSession`, `suspendSession`) el observador ya emitió el `page_view`
1123
+ * y no tiene pantalla, así que ese engagement va sin `screen`: nunca se cuenta dos veces.
1124
+ * Tampoco se emite un `page_view` aquí, por lo mismo.
1125
+ */
1126
+ private flushEngagement;
1127
+ /** Tick del flush periódico: latido de engagement si toca, y envío de lo acumulado. */
1128
+ private onAnalyticsFlushTick;
1129
+ /**
1130
+ * La pestaña vuelve a verse. Tras más de ANALYTICS_SESSION_TIMEOUT_MS oculta, la sesión
1131
+ * anterior termina y empieza otra: seguir con el mismo sessionId mezclaba dos visitas y,
1132
+ * si el backend ya la había cerrado por inactividad, la partía en dos feedbacks.
1133
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: el backend aún la tiene abierta → se
1134
+ * cierra con normalidad (page_view de la pantalla, session_end `idle_timeout`, completed).
1135
+ * - Más: ya la cerró el backend → se descarta sin enviar nada.
1136
+ */
1137
+ private onDocumentVisible;
1138
+ /**
1139
+ * `pagehide` en web: SUSPENDE la sesión en vez de cerrarla, porque el navegador lo lanza
1140
+ * igual al recargar que al cerrar la pestaña. Vuelca lo pendiente (page_view de la
1141
+ * pantalla, mini-services, engagement) con un `deepdots_session_suspend` y SIN
1142
+ * `completed`, y deja el registro en `sessionStorage` (ver `suspended-session.ts`):
1143
+ * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
1144
+ * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
1145
+ *
1146
+ * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
1147
+ * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
1148
+ */
1149
+ private suspendSession;
1150
+ /**
1151
+ * Recoge la sesión que dejó suspendida la carga anterior de esta pestaña (ver
1152
+ * `suspendSession`). Solo con analytics configurado y el tracking activo: sin ellos no hay
1153
+ * registro en el que seguir.
1154
+ */
1155
+ private readResumableSession;
1156
+ /**
1157
+ * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
1158
+ * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
1159
+ * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
1160
+ * se abre ahora va a uno nuevo.
1161
+ */
1162
+ private takeSuspendedSession;
1163
+ /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
1164
+ private discardSession;
1165
+ /**
1166
+ * Geolocalización por IP (país/ciudad para analytics). La caché persistente es local y se
1167
+ * aplica siempre que `geolocation` no esté desactivado. El lookup a terceros (ipapi.co →
1168
+ * ipwho.is → ipinfo.io, fallback con timeout) solo se hace si el dato se va a ENVIAR:
1169
+ * analytics configurado + tracking activo + caché ausente o caducada. Una vez por instancia.
1170
+ */
1171
+ private resolveGeo;
1172
+ private analyticsIdentity;
1173
+ /** Flush automático al ocultar/cerrar la página (no perder el lote pendiente). */
1174
+ private setupAnalyticsFlush;
1175
+ private startAnalyticsFlushTimer;
1176
+ /** Enable auto-launch functionality with configured triggers */
1177
+ autoLaunch(): void;
1178
+ /** Inicia los triggers configurados */
1179
+ private startTriggers;
1180
+ /** Configure triggers for auto-launching popups (manual) */
1181
+ configureTriggers(triggers: TriggerConfig[]): void;
1182
+ /** Deriva triggers desde las definiciones de popup */
1183
+ private configureTriggersFromDefinitions;
1184
+ /**
1185
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
1186
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
1187
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
1188
+ */
1189
+ triggerSurvey(surveyId: string, popupId?: string, options?: {
1190
+ delaySeconds?: number;
1191
+ }): void;
1192
+ /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
1193
+ triggerEvent(eventName: string): void;
1194
+ private evaluateEvent;
1195
+ /**
1196
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
1197
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
1198
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
1199
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
1200
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
1201
+ */
1202
+ private showAfterDelay;
1203
+ private showDelayedPopup;
1204
+ private cancelDelayedPopups;
1205
+ private currentHref;
1206
+ /**
1207
+ * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
1208
+ * llamador no debe evaluarlo ahora) y `false` si no hay carga en vuelo (se evalúa ya, como
1209
+ * siempre: tras cargar, tras un fallo o sin apiKey).
1210
+ */
1211
+ private bufferIfAwaitingPopups;
1212
+ /** La carga falló: sin definiciones no hay nada que reproducir, se descarta todo. */
1213
+ private dropPendingTriggers;
1214
+ /** Reproduce en orden por la evaluación normal (segmentos, cooldowns y condiciones de AHORA). */
1215
+ private replayPendingTriggers;
1216
+ private showDefinition;
1217
+ private shouldShow;
1218
+ private matchesSegmentsLang;
1219
+ /** `segments.path`: rutas donde el popup PUEDE mostrarse. Sin lista, en todas. */
1220
+ private matchesSegmentsPath;
1221
+ /**
1222
+ * `segments.excludedPaths`: rutas donde el popup NO debe mostrarse. Gana sobre
1223
+ * `segments.path` (`path: ['/']` + `excludedPaths: ['/cart']` = en todas menos el
1224
+ * carrito) y se aplica también cuando no hay `path` (= en todas menos las excluidas).
1225
+ */
1226
+ private isPathExcluded;
1227
+ /**
1228
+ * Compara UN candidato de `segments.path`/`segments.excludedPaths` con la ruta
1229
+ * actual. Mismas reglas para incluir y para excluir:
1230
+ * - URL absoluta → href completo exacto
1231
+ * - empieza por / → subcadena del href (así entran las rutas con hash: `/#/home`)
1232
+ * - resto → pathname exacto
1233
+ * Ignora entradas que no sean string: el backend puede colar un `null` en la lista
1234
+ * y no puede tumbar la evaluación del trigger entero (mismo fallo que hubo con
1235
+ * `segments.lang`).
1236
+ */
1237
+ private matchesPathCandidate;
1238
+ /** href + pathname normalizados de la ruta a evaluar, o null si no hay `window.location`. */
1239
+ private resolveCurrentLocation;
1240
+ private evaluateCooldown;
1241
+ private evaluateLegacyCondition;
1242
+ private hasCooldownElapsed;
1243
+ /** Marcar encuesta como contestada externamente */
1244
+ markSurveyAnswered(surveyId: string): void;
1245
+ /** Queue an exit popup so it can render after navigation */
1246
+ queueExitPopup(surveyId: string, delaySeconds: number, sourceUrl?: string, popupId?: string): void;
1247
+ private processDeferredExitQueue;
1248
+ private scheduleDeferredExitPopup;
1249
+ private tryShowDeferredExitPopup;
1250
+ private findPopupDefinition;
1251
+ private removeDeferredExitPopup;
1252
+ private getDeferredExitQueue;
1253
+ private setDeferredExitQueue;
1254
+ /** Fetch al servidor para obtener popups. `null` si la carga falló (red, no-2xx, payload inválido). */
1255
+ private fetchPopupsFromServer;
1256
+ /**
1257
+ * Envía los atributos de contact a la API (`POST /sdk/popups/contact`). Rechaza si no se
1258
+ * pudo enviar (sin red o respuesta no-2xx), para que `ContactManager` no guarde la caché
1259
+ * y la llamada siguiente reintente.
1260
+ */
1261
+ private postContact;
1262
+ /** Notifica eventos de popup a la API */
1263
+ private postPopupEvent;
1264
+ /** Add an event listener */
1265
+ on(eventType: DeepdotsEventType, listener: EventListener): void;
1266
+ /** Remove an event listener */
1267
+ off(eventType: DeepdotsEventType, listener: EventListener): void;
1268
+ /** Render the popup UI */
1269
+ private renderPopup;
1270
+ /** Hide the popup */
1271
+ private hidePopup;
1272
+ /** Emit an event */
1273
+ private emitEvent;
1274
+ /** Log debug messages */
1275
+ private log;
1276
+ /** External debug method for triggers */
1277
+ debug(...args: unknown[]): void;
1278
+ /** Set a custom renderer */
1279
+ setRenderer(renderer: PopupRenderer): void;
1280
+ private normalizeUrl;
1281
+ private safeParseUrl;
1282
+ private mapPopupTriggerType;
1283
+ private markSurveyProgress;
1284
+ /**
1285
+ * Fusiona el estado de redisplay del storage con el de memoria: por cada popup/survey gana
1286
+ * la entrada MÁS RECIENTE. Fusionar y no sustituir es lo que hace convivir a varias
1287
+ * pestañas sobre el mismo `localStorage`: se llama en el `init()`, antes de cada decisión
1288
+ * de mostrar y antes de cada escritura. `answeredSurveys` se reconstruye desde las
1289
+ * entradas COMPLETED: es exactamente lo que persiste `markSurveyAnswered`.
1290
+ */
1291
+ private loadPopupState;
1292
+ /**
1293
+ * Vuelca el estado de redisplay al storage. Sin storage (o bloqueado) degrada a memoria.
1294
+ * Fusiona antes de escribir: escribir solo la foto en memoria borraba lo que otra pestaña
1295
+ * hubiese guardado desde nuestro `init()`.
1296
+ */
1297
+ private persistPopupState;
1298
+ private isPopupDefinition;
1299
+ private isPopupTrigger;
1300
+ private isPopupTriggerType;
1301
+ private isPopupTriggerCondition;
1302
+ private isLegacyPopupTriggerCondition;
1303
+ private normalizeTriggers;
1304
+ private normalizeCooldown;
1305
+ private normalizeLegacyConditions;
1306
+ private normalizePopupDefinition;
1307
+ private validatePopupDefinitions;
1308
+ }
1309
+
1310
+ /**
1311
+ * Margen que el aviso nativo de "listo" deja por detrás del techo que ya lleva el HTML. El
1312
+ * WebView se revela solo a `REVEAL_TIMEOUT_MS`; este respaldo solo debe entrar cuando el WebView
1313
+ * no llega ni a ejecutar el HTML (motor que no arranca, documento que no carga), que es el único
1314
+ * caso en el que el host se quedaría esperando para siempre.
1315
+ */
1316
+ declare const NATIVE_READY_GRACE_MS = 500;
1317
+ type EmitFn = (type: DeepdotsEventType, surveyId: string, data?: Record<string, unknown>) => void;
1318
+ /** Payload que recibe el host para montar el WebView del survey. */
1319
+ interface ReactNativeSurveyPayload {
1320
+ surveyId: string;
1321
+ productId: string;
1322
+ /** HTML autocontenido para `<WebView source={{ html }}>`. */
1323
+ html: string;
1324
+ }
1325
+ interface ReactNativeRendererOptions {
1326
+ /** Se llama al mostrar un popup: monta el WebView con `payload.html`. */
1327
+ onShow?: (payload: ReactNativeSurveyPayload) => void;
1328
+ /** Se llama al cerrar el popup: desmonta el WebView. */
1329
+ onHide?: () => void;
1330
+ /**
1331
+ * Se llama cuando el survey ya está pintado dentro del WebView, o pasado el techo de espera.
1332
+ *
1333
+ * Sirve para no enseñar un WebView en blanco: monta el WebView en cuanto llegue `onShow` (fuera
1334
+ * de pantalla o transparente) y ábrelo al recibir `onReady`. El HTML se revela solo de todas
1335
+ * formas, así que el host que no lo use sigue funcionando igual.
1336
+ */
1337
+ onReady?: (payload: {
1338
+ surveyId: string;
1339
+ }) => void;
1340
+ }
1341
+ /**
1342
+ * Renderer de React Native: el SDK no puede pintar componentes RN, así que entrega el
1343
+ * HTML del survey al host (que lo monta en `react-native-webview`) y traduce los
1344
+ * mensajes del WebView a eventos de popup del SDK (→ `POST /sdk/popups`, Messaging #18–22).
1345
+ *
1346
+ * Uso: monta el WebView con `onShow` y enséñalo con `onReady`, para que el usuario no vea el
1347
+ * WebView arrancando en blanco (motor + bundle del CDN + fetch del survey).
1348
+ * ```tsx
1349
+ * const renderer = new ReactNativePopupRenderer({
1350
+ * onShow: (p) => setSurvey({ ...p, ready: false }),
1351
+ * onReady: () => setSurvey((s) => (s ? { ...s, ready: true } : s)),
1352
+ * onHide: () => setSurvey(null),
1353
+ * });
1354
+ * sdk.setRenderer(renderer);
1355
+ * // …
1356
+ * // ⚠️ Con `<Modal visible={survey.ready}>` esto NO funciona: React Native no monta los hijos
1357
+ * // de un Modal cerrado, así que el WebView no empezaría a cargar y `ready` no llegaría nunca.
1358
+ * // El WebView tiene que estar montado y solo invisible.
1359
+ * {survey ? (
1360
+ * <View style={[StyleSheet.absoluteFill, { opacity: survey.ready ? 1 : 0 }]}
1361
+ * pointerEvents={survey.ready ? 'auto' : 'none'}>
1362
+ * <WebView source={{ html: survey.html }}
1363
+ * onMessage={(e) => renderer.handleMessage(e.nativeEvent.data)} />
1364
+ * </View>
1365
+ * ) : null}
1366
+ * ```
1367
+ *
1368
+ * Quien prefiera no complicarse puede ignorar `onReady` y abrir su Modal en `onShow`: el HTML se
1369
+ * revela solo igualmente, así que el usuario verá el contenedor del host unos cientos de ms antes
1370
+ * que la tarjeta, pero nunca el spinner.
1371
+ */
1372
+ declare class ReactNativePopupRenderer implements PopupRenderer {
1373
+ private options;
1374
+ private emitFn;
1375
+ private onCloseFn;
1376
+ private currentSurveyId;
1377
+ private partialEmitted;
1378
+ private readyEmitted;
1379
+ private readyTimer;
1380
+ constructor(options?: ReactNativeRendererOptions);
1381
+ init(): void;
1382
+ show(surveyId: string, productId: string, actions: PopupActions | undefined, emit: EmitFn, onClose: () => void, env?: string, userId?: string, style?: PopupStyle, sessionId?: string, miniService?: string, analyticsFeedbackSessionId?: string, renderChrome?: boolean, options?: PopupRenderOptions): void;
1383
+ hide(): void;
1384
+ /** Respaldo del aviso de listo por si el WebView no llega a ejecutar el HTML. */
1385
+ private armReadyFallback;
1386
+ private clearReadyFallback;
1387
+ /** Idempotente: el WebView puede avisar a la vez que vence el respaldo. */
1388
+ private emitReady;
1389
+ /**
1390
+ * El host la conecta al `onMessage` del WebView. Traduce los mensajes del survey a
1391
+ * eventos del SDK: primera interacción → `popup_clicked` (PARTIAL), completado →
1392
+ * `survey_completed` (COMPLETED) y cierra el popup.
1393
+ */
1394
+ handleMessage(raw: string): void;
1395
+ }
1396
+
1397
+ /**
1398
+ * Construye un HTML autocontenido que renderiza el popup (chrome + survey de
1399
+ * `@magicfeedback/native`) dentro de un WebView (React Native). Es el equivalente RN de
1400
+ * `renderPopup.ts` (DOM real, solo navegador): mismo header con botón cerrar, spinner,
1401
+ * footer con back/start/send, gate "Start survey" y colores/logo desde `formData.style`.
1402
+ * Carga el bundle del survey desde CDN, crea el form con la identidad inyectada
1403
+ * (`profile`/`metadata`) y reenvía los eventos al host vía el puente de
1404
+ * react-native-webview: `window.ReactNativeWebView.postMessage`.
1405
+ *
1406
+ * Mensajes emitidos (JSON `{name, payload}`): `loaded`, `ready`, `before_submit`,
1407
+ * `after_submit`, `survey_completed`, `back`, `popup_close`, y `error:load` / `error:init` /
1408
+ * `error:exception` (con `{message}`) cuando el survey no ha podido cargar.
1409
+ */
1410
+ interface BuildSurveyHtmlOptions {
1411
+ surveyId: string;
1412
+ productId: string;
1413
+ env?: string;
1414
+ profile?: IdentityAnswer[];
1415
+ metadata?: IdentityAnswer[];
1416
+ /**
1417
+ * Versión de `@magicfeedback/native` a cargar (DD-70: la asignada al survey ya elegida con
1418
+ * `chooseSurveySdkVersion`). Por defecto la empaquetada. Con otra, el HTML trae su hoja
1419
+ * vendorizada y su JS; si cualquiera falla, la hoja y la JS empaquetadas.
1420
+ */
1421
+ version?: string;
1422
+ font?: PopupFont;
1423
+ theme?: 'light' | 'dark';
1424
+ position?: 'bottom' | 'bottom-right' | 'bottom-left' | 'top' | 'top-right' | 'top-left' | 'center';
1425
+ actions?: PopupActions;
1426
+ /**
1427
+ * Renderiza el "modal" del popup (tarjeta con fondo/sombra/bordes + overlay + posicionamiento).
1428
+ * Default `true`. Con `false` el HTML es transparente y llena el contenedor: el host monta su
1429
+ * propio Modal/tarjeta y controla el estilo. El survey sigue siendo funcional (bridge, form,
1430
+ * botones y botón de cerrar). Pensado para React Native cuando el host gestiona el contenedor.
1431
+ */
1432
+ chrome?: boolean;
1433
+ /**
1434
+ * Título de la cabecera, a la izquierda del botón de cerrar. Es el `title` de la definición
1435
+ * del popup (`GET /sdk/{publicKey}/popups`), así que cambia de un popup a otro. Vacío es un
1436
+ * valor legítimo: la cabecera se queda solo con la X. NO cae al título del survey.
1437
+ */
1438
+ title?: string;
1439
+ /**
1440
+ * Barra de progreso ("Question X of Y" + barra) bajo la cabecera. `undefined` respeta el
1441
+ * `showProgressBar` que configure la plataforma en el estilo del survey; `true`/`false` lo
1442
+ * fuerzan desde el host. Solo se pinta con más de una página y fuera de la pantalla de inicio.
1443
+ */
1444
+ showProgressBar?: boolean;
1445
+ /**
1446
+ * CSS del host, inyectado como último bloque de estilos: gana en cascada sobre el del SDK
1447
+ * y sobre el de `@magicfeedback/native` sin tener que tocar ninguno de los dos. Es la vía
1448
+ * para reestilar el área de preguntas (enunciados, opciones, escalas) por integración.
1449
+ */
1450
+ surveyCss?: string;
1451
+ /**
1452
+ * Idioma con el que arranca el chrome (botones, progreso, aria-labels, errores). Es el
1453
+ * idioma resuelto en `init()`. Dentro del WebView lo pisa el idioma del survey
1454
+ * (`formData.lang[0]`), y ambos los pisa `actions.*.label` de la API.
1455
+ */
1456
+ language?: string;
1457
+ }
1458
+ declare function buildSurveyHtml(opts: BuildSurveyHtmlOptions): string;
1459
+
1460
+ /**
1461
+ * Apertura diferida del popup: el chrome se monta invisible y se enseña cuando el survey ya
1462
+ * está pintado, en vez de enseñar un spinner girando mientras se espera.
1463
+ *
1464
+ * Vive en su propio módulo porque lo comparten las dos rutas de render y `renderPopup` arrastra
1465
+ * `@magicfeedback/native`: importar la constante desde allí metería el survey entero en el bundle
1466
+ * de React Native. La ruta del WebView (`surveyHtml`) hornea el valor en el HTML y lleva su
1467
+ * propio espejo del algoritmo en ES5, porque ese código corre dentro del WebView.
1468
+ */
1469
+ /**
1470
+ * Techo de la espera. Pasado este tiempo el popup se abre igualmente (con spinner, el
1471
+ * comportamiento de siempre), para que una red mala retrase la apertura pero nunca la impida.
1472
+ *
1473
+ * 1200 ms sale de medir contra producción: el `GET .../info` del survey tarda unos 250 ms de
1474
+ * mediana desde Europa, pero con el servicio frío se han visto 775 ms. El techo tiene que quedar
1475
+ * por encima de esa cola: si cayera justo encima, el popup se abriría con el spinner para
1476
+ * quitarlo 30 ms después, que es peor que cualquiera de las dos opciones.
1477
+ */
1478
+ declare const REVEAL_TIMEOUT_MS = 1200;
1479
+
1480
+ /**
1481
+ * Textos que pinta el SDK alrededor del survey (botones del footer, barra de progreso,
1482
+ * aria-labels y avisos de error). NO son textos del survey: las preguntas, placeholders y
1483
+ * opciones las localiza `@magicfeedback/native` con `formData.lang[0]`, el idioma configurado
1484
+ * en la integración. Este módulo existe para que el chrome del popup hable ese mismo idioma
1485
+ * en lugar de quedarse siempre en inglés.
1486
+ *
1487
+ * Espejo del `i18n/DefaultLabels.kt` del SDK nativo (KMP): mismos locales y mismas reglas de
1488
+ * resolución, para que las tres rutas (popup DOM web, WebView de RN y Compose) digan lo mismo.
1489
+ */
1490
+ /** Locales con traducción propia. Cualquier otro idioma cae a `en`. */
1491
+ type PopupLocale = 'en' | 'es' | 'da' | 'no' | 'sv' | 'fi' | 'de' | 'fr' | 'pt' | 'ar' | 'bn' | 'zh-CN' | 'bg' | 'cs' | 'el' | 'et' | 'ga' | 'hr' | 'hu' | 'it' | 'lt' | 'lv' | 'mt' | 'nl' | 'pl' | 'ro' | 'sk' | 'sl';
1492
+ interface PopupLabels {
1493
+ /** Acción principal: enviar la respuesta. */
1494
+ accept: string;
1495
+ /** Acción de descarte. */
1496
+ decline: string;
1497
+ /** Botón de la pantalla de bienvenida. */
1498
+ start: string;
1499
+ /** Botón de la pantalla final. */
1500
+ complete: string;
1501
+ /** Volver a la pregunta anterior. */
1502
+ back: string;
1503
+ /** Sustantivo del contador de progreso ("Question" en `Question 2 of 5`). */
1504
+ question: string;
1505
+ /** Separador del contador de progreso ("of" en `Question 2 of 5`). */
1506
+ of: string;
1507
+ /** Distintivo de las preguntas de seguimiento dinámicas. */
1508
+ followUp: string;
1509
+ /** aria-label del botón de cerrar. */
1510
+ closeAria: string;
1511
+ /** aria-label del spinner mientras carga el survey. */
1512
+ loadingAria: string;
1513
+ /** Aviso al intentar avanzar con una pregunta obligatoria sin responder. */
1514
+ errorRequired: string;
1515
+ /** Aviso al intentar avanzar con un email que no es una dirección válida (`INVALID_EMAIL`). */
1516
+ errorInvalidEmail: string;
1517
+ /** Aviso cuando el envío falla. */
1518
+ errorSubmit: string;
1519
+ /** Aviso cuando el survey no ha podido cargar (el popup solo ofrece cerrarlo). */
1520
+ errorLoad: string;
1521
+ }
1522
+ /** Tabla completa de traducciones, indexada por locale. */
1523
+ declare const LABELS: Record<PopupLocale, PopupLabels>;
1524
+ /** Locales con traducción propia del SDK. */
1525
+ declare const SUPPORTED_LANGUAGES: PopupLocale[];
1526
+ /**
1527
+ * Normaliza un tag BCP-47 al locale con traducción. Reglas (idénticas a KMP):
1528
+ * - el prefijo de idioma manda, sin importar región ni caja (`da`, `da-DK`, `da_DK` → `da`);
1529
+ * - las variantes noruegas (`nb`, `nn`) colapsan en `no`;
1530
+ * - las variantes chinas (`zh`, `zh-Hans`, `zh-CN`, `zh-TW`) colapsan en `zh-CN`;
1531
+ * - `pt-BR` y `pt-PT` comparten juego, igual que `de-AT`/`de-CH` o `fr-CA`;
1532
+ * - cualquier otra cosa, incluido un valor no-string del backend, cae a `en`.
1533
+ */
1534
+ declare function resolveLocale(lang?: string | null): PopupLocale;
1535
+ /**
1536
+ * Locales que se escriben de derecha a izquierda. Espejo de `RTL_LANGUAGES` de
1537
+ * `@magicfeedback/native` (2.2.22), que estampa `dir="rtl"` en el contenedor del survey para
1538
+ * esos idiomas: el chrome del popup tiene que voltear con él o media tarjeta queda mirando a
1539
+ * un lado y media al otro.
1540
+ */
1541
+ declare const RTL_LOCALES: PopupLocale[];
1542
+ /** Si el chrome debe pintarse de derecha a izquierda para `lang`. */
1543
+ declare function isRtlLanguage(lang?: string | null): boolean;
1544
+ /** Valor del atributo `dir` del chrome para `lang`. Siempre explícito: nunca se hereda del host. */
1545
+ declare function directionFor(lang?: string | null): 'rtl' | 'ltr';
1546
+ /** Textos del chrome del popup para `lang`. Cae a inglés si el idioma no está soportado. */
1547
+ declare function getLabels(lang?: string | null): PopupLabels;
1548
+ /** Etiquetas de los cuatro botones del footer, ya resueltas. */
1549
+ interface ResolvedActionLabels {
1550
+ accept: string;
1551
+ decline: string;
1552
+ start: string;
1553
+ complete: string;
1554
+ back: string;
1555
+ }
1556
+ /**
1557
+ * Resuelve las etiquetas de los botones con la prioridad acordada: lo que configure la
1558
+ * plataforma por popup (`actions.*.label`) gana siempre; si falta o viene en blanco, se usa
1559
+ * la traducción del SDK para `lang`.
1560
+ */
1561
+ declare function resolveActionLabels(actions: PopupActions | undefined, lang?: string | null): ResolvedActionLabels;
1562
+
1563
+ /**
1564
+ * Auto-wiring de React Native: concentra TODA la configuración en el SDK para que el
1565
+ * host solo tenga que envolver su app en un `<DeepdotsProvider config={...}>`.
1566
+ *
1567
+ * No importa React ni librerías nativas: el host (o el Provider) le pasa los módulos
1568
+ * nativos que tenga instalados (MMKV, device-info, AppState). Todo es opcional y degrada
1569
+ * con elegancia (sin MMKV → in-memory; sin device-info → sin device info).
1570
+ */
1571
+
1572
+ /** Forma mínima de `react-native-mmkv` (instancia MMKV). */
1573
+ interface MmkvLike {
1574
+ getString(key: string): string | undefined | null;
1575
+ set(key: string, value: string): void;
1576
+ delete(key: string): void;
1577
+ }
1578
+ /** Forma mínima de `react-native-device-info`. */
1579
+ interface DeviceInfoLike {
1580
+ isTablet?: () => boolean;
1581
+ getSystemVersion?: () => string;
1582
+ getDeviceId?: () => string;
1583
+ getVersion?: () => string;
1584
+ }
1585
+ /** Forma mínima de `AppState` de react-native. */
1586
+ interface AppStateLike {
1587
+ addEventListener(type: 'change', listener: (state: string) => void): {
1588
+ remove: () => void;
1589
+ } | void;
1590
+ }
1591
+ interface ReactNativeSetupDeps {
1592
+ mmkv?: MmkvLike | null;
1593
+ deviceInfo?: DeviceInfoLike | null;
1594
+ appState?: AppStateLike | null;
1595
+ platform?: 'web' | 'android' | 'ios';
1596
+ renderer?: PopupRenderer;
1597
+ /** `global.ErrorUtils` de RN (para capturar errores JS no manejados). Default: `globalThis.ErrorUtils`. */
1598
+ errorUtils?: ReactNativeErrorUtils | null;
1599
+ /**
1600
+ * Background task nativa para los envíos (iOS, DD-55). Si `config.backgroundTask` viene, gana
1601
+ * ese. Para `react-native-background-timer`: `backgroundTimerTask(BackgroundTimer)`.
1602
+ */
1603
+ backgroundTask?: BackgroundTaskRunner | null;
1604
+ }
1605
+ /** Adaptador KeyValueStorage (síncrono) sobre una instancia de MMKV. */
1606
+ declare function mmkvStorage(mmkv: MmkvLike): KeyValueStorage;
1607
+ /** Recoge device info desde react-native-device-info (Technology #11–13). */
1608
+ declare function collectRnDevice(d: DeviceInfoLike): DeviceInfo;
1609
+ /**
1610
+ * Configura el SDK para React Native en una sola llamada: storage persistente (MMKV),
1611
+ * device info, platform, init y lifecycle (AppState → onForeground/onBackground).
1612
+ * Devuelve una función de limpieza (quita el listener de AppState).
1613
+ */
1614
+ declare function setupReactNative(sdk: DeepdotsPopups, config: DeepdotsInitParams, deps?: ReactNativeSetupDeps): () => void;
1615
+
1616
+ export { type AnalyticsFeedbackBody, type AnalyticsKeys, type AppStateLike, type AutoTrackOptions, BACKGROUND_TASK_MAX_MS, type BackgroundTaskRunner, type BackgroundTimerLike, BrowserPopupRenderer, type BuildBodyOptions, type ContactAttributeValue, type ContactAttributes, type ContactBody, ContactManager, type CrashRecord, CrashReporter, type CrashSeverity, type DeepdotsConfig, type DeepdotsEvent, type DeepdotsEventType, type DeepdotsInitParams, type DeepdotsLogger, DeepdotsPopups, type DeviceInfo, type DeviceInfoLike, type DeviceSnapshot, type EventListener, type FeedbackKV, type FeedbackSession, InMemoryStorage, type KeyValueStorage, LABELS, MAX_TRACKED_MESSAGES, MESSAGE_CHANNELS, type MessageChannel, MessageGuard, type MessageGuardVerdict, type MessageRejectionReason, type MessageStage, type MmkvLike, NATIVE_READY_GRACE_MS, NoopPopupRenderer, POPUP_TRIGGER_CONDITION_STATUSES, type PopupDefinition, type PopupLabels, type PopupLocale, type PopupRenderer, type PopupTrigger, type PopupTriggerCondition, type PopupTriggerConditionStatus, REVEAL_TIMEOUT_MS, RTL_LOCALES, type ReactNativeErrorUtils, ReactNativePopupRenderer, type ReactNativeRendererOptions, type ReactNativeSetupDeps, type ReactNativeSurveyPayload, type ReportErrorOptions, type ResolvedActionLabels, SUPPORTED_LANGUAGES, type SessionEndReason, type SessionStartReason, type TrackMessageOptions, type TriggerConfig, backgroundTimerTask, buildAnalyticsFeedbackBody, buildMessageParams, buildSurveyHtml, collectRnDevice, crashRecordToParams, createDefaultRenderer, createFeedbackSink, directionFor, getLabels, isRtlLanguage, mmkvStorage, resolveActionLabels, resolveLocale, setupReactNative };