@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
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ BUNDLED_SURVEY_SDK_VERSION,
2
3
  BUSY_JS,
3
4
  InMemoryStorage,
4
5
  LABELS,
@@ -6,22 +7,30 @@ import {
6
7
  RESOLVE_LOCALE_JS,
7
8
  REVEAL_TIMEOUT_MS,
8
9
  RTL_LOCALES,
10
+ SDK_IDENTIFIER,
9
11
  STORAGE_KEYS,
12
+ SUBMIT_ERROR_JS,
10
13
  SUPPORTED_LANGUAGES,
11
14
  TrackingManager,
12
15
  buildFontFaceCss,
13
16
  buildFontFamilyValue,
14
17
  buildSurveyIdentity,
18
+ chooseSurveySdkVersion,
15
19
  createDefaultStorage,
20
+ describeSurveySdkChoice,
16
21
  directionFor,
17
22
  getLabels,
18
23
  isRtlLanguage,
19
24
  resolveActionLabels,
20
25
  resolveLocale,
26
+ sdkLog,
21
27
  sdkWarn,
22
28
  setLogger,
23
- style_default
24
- } from "./chunk-AFRHPS3K.mjs";
29
+ style_default,
30
+ surveySdkCssUrls,
31
+ surveySdkUrls
32
+ } from "./chunk-XOEEBDBJ.mjs";
33
+ import "./chunk-3QS3WKRC.mjs";
25
34
 
26
35
  // src/types/index.ts
27
36
  var POPUP_TRIGGER_CONDITION_STATUSES = [
@@ -57,7 +66,7 @@ function setupTrigger(popups, trigger) {
57
66
  function setupTimeTrigger(popups, trigger) {
58
67
  const delay = toNumericValue(trigger.value, 5e3);
59
68
  setTimeout(() => {
60
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
69
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
61
70
  }, delay);
62
71
  popups.debug(`Time trigger set for ${delay}ms`);
63
72
  }
@@ -66,7 +75,7 @@ function setupScrollTrigger(popups, trigger) {
66
75
  const handler = () => {
67
76
  const scrollPercentage = window.scrollY / (document.documentElement.scrollHeight - window.innerHeight) * 100;
68
77
  if (scrollPercentage >= threshold) {
69
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
78
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
70
79
  window.removeEventListener("scroll", handler);
71
80
  }
72
81
  };
@@ -75,7 +84,7 @@ function setupScrollTrigger(popups, trigger) {
75
84
  }
76
85
  function setupExitTrigger(popups, trigger) {
77
86
  if (typeof window === "undefined") return;
78
- const delaySeconds = parseExitDelaySeconds(trigger.value);
87
+ const delaySeconds = typeof trigger.delaySeconds === "number" && trigger.delaySeconds > 0 ? trigger.delaySeconds : parseExitDelaySeconds(trigger.value);
79
88
  const historyRef = window.history;
80
89
  const originalPushState = historyRef.pushState.bind(historyRef);
81
90
  const originalReplaceState = historyRef.replaceState.bind(historyRef);
@@ -186,7 +195,7 @@ function setupClickTrigger(popups, trigger) {
186
195
  }
187
196
  const handler = (e) => {
188
197
  if (e.defaultPrevented) return;
189
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
198
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
190
199
  el.removeEventListener("click", handler);
191
200
  };
192
201
  el.addEventListener("click", handler);
@@ -254,8 +263,9 @@ function trimmedOrNull(value) {
254
263
  }
255
264
  function buildSurveyHtml(opts) {
256
265
  const env = opts.env === "development" ? "dev" : "prod";
257
- const version = opts.version ?? "2.2.33";
258
- const cdn = `https://cdn.jsdelivr.net/npm/@magicfeedback/native@${version}/dist/magicfeedback-sdk.browser.js`;
266
+ const version = opts.version ?? BUNDLED_SURVEY_SDK_VERSION;
267
+ const assigned = version !== BUNDLED_SURVEY_SDK_VERSION ? { version, css: surveySdkCssUrls(version), js: surveySdkUrls(version) } : null;
268
+ const bundledJs = surveySdkUrls(BUNDLED_SURVEY_SDK_VERSION);
259
269
  const sid = jsonForScript(opts.surveyId);
260
270
  const pid = jsonForScript(opts.productId);
261
271
  const profileJson = jsonForScript(opts.profile ?? []);
@@ -307,8 +317,10 @@ function buildSurveyHtml(opts) {
307
317
  return `<!DOCTYPE html><html><head>
308
318
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
309
319
  <meta name="color-scheme" content="${colorScheme}"/>
310
- <style>
320
+ <style id="dd-survey-css">
311
321
  ${style_default}
322
+ </style>
323
+ <style>
312
324
  ${fontFaceCss}
313
325
  html,body{margin:0;padding:0;height:100%;font-family:${fontFamilyValue}}
314
326
  /* Apertura diferida: ni la tarjeta ni el velo se pintan hasta que el survey est\xE1 listo
@@ -426,6 +438,7 @@ ${customCss}
426
438
  (function(){
427
439
  function emit(s){ try{ if(window.ReactNativeWebView){ window.ReactNativeWebView.postMessage(s); } }catch(e){} }
428
440
  function emitJSON(n,p){ try{ emit(JSON.stringify({name:n,payload:p||{}})); }catch(e){} }
441
+ var ddLastReportedError=null;
429
442
  window.DeepdotsClose = function(){ emitJSON('popup_close'); };
430
443
  var chromeOn=${chrome ? "true" : "false"};
431
444
 
@@ -606,6 +619,7 @@ ${customCss}
606
619
 
607
620
  ${PRIMARY_COLOR_JS}
608
621
  ${BUSY_JS}
622
+ ${SUBMIT_ERROR_JS}
609
623
  ${REVEAL_JS}
610
624
  // Foco en la primera pregunta si es de escribir. Al navegar lo pone @magicfeedback/native
611
625
  // (autofocus:'navigation'); la apertura la decide el popup, que es quien sabe cu\xE1ndo se revela.
@@ -757,18 +771,23 @@ ${REVEAL_JS}
757
771
  emitJSON('before_submit');
758
772
  },
759
773
  afterSubmitEvent:function(p){
760
- var error=p && p.error ? (typeof p.error==='string' ? p.error : String(p.error)) : '';
761
- if(error){
774
+ if(p && p.error){
762
775
  setLoading(false);
763
- if(error.toLowerCase().indexOf('no response')!==-1){
776
+ var ddErr=ddClassifySubmitError(p.error);
777
+ if(ddErr.reason==='required' || ddErr.reason==='invalid_email'){
764
778
  // La p\xE1gina no ha cambiado: el estado de navegaci\xF3n se queda como estaba.
765
- errorHint.textContent=DD_LABELS_ACTIVE.errorRequired;
779
+ errorHint.textContent=ddErr.reason==='invalid_email' ? DD_LABELS_ACTIVE.errorInvalidEmail : DD_LABELS_ACTIVE.errorRequired;
766
780
  errorHint.style.display='block';
767
781
  updateNavButtons();
768
782
  return;
769
783
  }
770
784
  errorHint.textContent=DD_LABELS_ACTIVE.errorSubmit;
771
785
  errorHint.style.display='block';
786
+ // Un solo aviso por fallo: native repite el mismo objeto al cerrar el survey.
787
+ if(p.error!==ddLastReportedError){
788
+ ddLastReportedError=p.error;
789
+ emitJSON('survey_error', ddErr);
790
+ }
772
791
  return;
773
792
  }
774
793
  errorHint.style.display='none';
@@ -798,10 +817,46 @@ ${REVEAL_JS}
798
817
  }catch(e){ ddShowLoadError('error:exception', e); }
799
818
  return true;
800
819
  }
801
- var s=document.createElement('script'); s.src=${JSON.stringify(cdn)}; s.async=true;
802
- s.onload=function(){ initMF(); };
803
- s.onerror=function(){ ddShowLoadError('error:load', 'survey script failed to load'); };
804
- document.head.appendChild(s);
820
+ // DD-70: versi\xF3n asignada (hoja + JS) y, si algo falla, la empaquetada (hoja + JS).
821
+ var ddAssigned=${jsonForScript(assigned)}, ddBundledJs=${jsonForScript(bundledJs)};
822
+ var ddCssEl=document.getElementById('dd-survey-css'), ddBundledCss=ddCssEl?ddCssEl.textContent:'';
823
+ function ddMark(v){ try{ document.documentElement.setAttribute('data-survey-sdk', v); }catch(_){} }
824
+ function ddLoadScripts(urls, i, onFail){
825
+ if(i>=urls.length){ onFail(); return; }
826
+ var s=document.createElement('script'); s.src=urls[i]; s.async=true;
827
+ s.onload=function(){ initMF(); };
828
+ s.onerror=function(){
829
+ try{ console.warn('[Deepdots] survey SDK failed from '+urls[i]); }catch(_){}
830
+ ddLoadScripts(urls, i+1, onFail);
831
+ };
832
+ document.head.appendChild(s);
833
+ }
834
+ function ddLoadBundled(){
835
+ if(ddCssEl){ ddCssEl.textContent=ddBundledCss; }
836
+ ddMark(${jsonForScript(BUNDLED_SURVEY_SDK_VERSION + " bundled")});
837
+ ddLoadScripts(ddBundledJs, 0, function(){ ddShowLoadError('error:load', 'survey script failed to load'); });
838
+ }
839
+ function ddFetchCss(urls, i, ok, fail){
840
+ if(i>=urls.length || typeof fetch!=='function'){ fail(); return; }
841
+ fetch(urls[i]).then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.text(); })
842
+ .then(function(css){ if(!css) throw new Error('empty'); ok(css); })
843
+ .catch(function(){ ddFetchCss(urls, i+1, ok, fail); });
844
+ }
845
+ if(ddAssigned){
846
+ ddFetchCss(ddAssigned.css, 0, function(css){
847
+ if(ddCssEl){ ddCssEl.textContent=css; }
848
+ ddMark(ddAssigned.version+' assigned');
849
+ ddLoadScripts(ddAssigned.js, 0, function(){
850
+ try{ console.warn('[Deepdots] survey SDK '+ddAssigned.version+' failed, using bundled'); }catch(_){}
851
+ ddLoadBundled();
852
+ });
853
+ }, function(){
854
+ try{ console.warn('[Deepdots] survey CSS '+ddAssigned.version+' failed, using bundled'); }catch(_){}
855
+ ddLoadBundled();
856
+ });
857
+ } else {
858
+ ddLoadBundled();
859
+ }
805
860
  var tries=0, t=setInterval(function(){ if(initMF()||++tries>40){ clearInterval(t); } },150);
806
861
  })();
807
862
  <\/script>
@@ -830,9 +885,12 @@ var ReactNativePopupRenderer = class {
830
885
  this.readyEmitted = false;
831
886
  this.armReadyFallback(surveyId);
832
887
  const { profile, metadata } = buildSurveyIdentity(userId ?? null, sessionId ?? null, miniService ?? null, analyticsFeedbackSessionId ?? null);
888
+ const surveySdk = chooseSurveySdkVersion(options?.surveySdkVersion);
889
+ logRnSurveySdkChoice(surveySdk, options?.debug);
833
890
  const html = buildSurveyHtml({
834
891
  surveyId,
835
892
  productId,
893
+ version: surveySdk.version,
836
894
  env,
837
895
  profile,
838
896
  metadata,
@@ -891,8 +949,9 @@ var ReactNativePopupRenderer = class {
891
949
  const surveyId = this.currentSurveyId;
892
950
  if (!surveyId || !this.emitFn) return;
893
951
  let name;
952
+ let payload;
894
953
  try {
895
- name = JSON.parse(raw).name;
954
+ ({ name, payload } = JSON.parse(raw));
896
955
  } catch {
897
956
  name = raw;
898
957
  }
@@ -913,6 +972,9 @@ var ReactNativePopupRenderer = class {
913
972
  case "survey_completed":
914
973
  this.emitFn("survey_completed", surveyId);
915
974
  break;
975
+ case "survey_error":
976
+ this.emitFn("survey_error", surveyId, { reason: payload?.reason, message: payload?.message });
977
+ break;
916
978
  case "popup_close":
917
979
  this.onCloseFn?.();
918
980
  break;
@@ -928,9 +990,14 @@ function isReactNativeEnv() {
928
990
  function createReactNativeRenderer() {
929
991
  return new ReactNativePopupRenderer();
930
992
  }
993
+ function logRnSurveySdkChoice(choice, debug) {
994
+ const problem = choice.source === "bundled" && choice.reason === "invalid";
995
+ if (problem) sdkWarn(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
996
+ else if (debug) sdkLog(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
997
+ }
931
998
 
932
999
  // src/ui/preload.ts
933
- var defaultLoader = () => import("./renderPopup-PQWJSBOY.mjs");
1000
+ var defaultLoader = () => import("./renderPopup-2Y4QMWR7.mjs");
934
1001
  var pending = null;
935
1002
  function preloadRenderPopup(loader = defaultLoader) {
936
1003
  if (pending) return pending;
@@ -1003,7 +1070,7 @@ var BrowserPopupRenderer = class {
1003
1070
  if (!this.container) return;
1004
1071
  this.visible = true;
1005
1072
  const container = this.container;
1006
- void import("./renderPopup-PQWJSBOY.mjs").then(
1073
+ void import("./renderPopup-2Y4QMWR7.mjs").then(
1007
1074
  ({ renderPopup }) => {
1008
1075
  renderPopup(container, surveyId, productId, actions, emit, onClose, env, userId, style, sessionId, miniService, analyticsFeedbackSessionId, options);
1009
1076
  },
@@ -1167,6 +1234,7 @@ var AnalyticsManager = class {
1167
1234
  sessionId: identity.sessionId,
1168
1235
  context: {
1169
1236
  platform: this.platform,
1237
+ sdk: SDK_IDENTIFIER,
1170
1238
  language: this.language,
1171
1239
  device: this.device,
1172
1240
  attributes: { ...this.attributes },
@@ -1214,6 +1282,48 @@ var AnalyticsManager = class {
1214
1282
  }
1215
1283
  };
1216
1284
 
1285
+ // src/analytics/background-task.ts
1286
+ var BACKGROUND_TASK_MAX_MS = 25e3;
1287
+ async function runInBackgroundTask(begin, name, work, maxMs = BACKGROUND_TASK_MAX_MS) {
1288
+ let end;
1289
+ try {
1290
+ end = begin?.(name);
1291
+ } catch {
1292
+ end = void 0;
1293
+ }
1294
+ if (typeof end !== "function") return work();
1295
+ let ended = false;
1296
+ const finish = () => {
1297
+ if (ended) return;
1298
+ ended = true;
1299
+ clearTimeout(timer);
1300
+ try {
1301
+ end();
1302
+ } catch {
1303
+ }
1304
+ };
1305
+ const timer = setTimeout(finish, maxMs);
1306
+ try {
1307
+ return await work();
1308
+ } finally {
1309
+ finish();
1310
+ }
1311
+ }
1312
+ function backgroundTimerTask(timer) {
1313
+ let open = 0;
1314
+ return () => {
1315
+ if (open === 0) timer.start(0);
1316
+ open++;
1317
+ let closed = false;
1318
+ return () => {
1319
+ if (closed) return;
1320
+ closed = true;
1321
+ open--;
1322
+ if (open === 0) timer.stop();
1323
+ };
1324
+ };
1325
+ }
1326
+
1217
1327
  // src/analytics/feedback-payload.ts
1218
1328
  function pushKV(list, key, value) {
1219
1329
  if (value === void 0 || value === null || value === "") return;
@@ -1227,6 +1337,7 @@ function buildAnalyticsFeedbackBody(envelope, keys, feedbackSessionId, options)
1227
1337
  pushKV(metadata, "deepdots_user_id", envelope.userId);
1228
1338
  pushKV(metadata, "deepdots_session_id", envelope.sessionId);
1229
1339
  pushKV(metadata, "deepdots_platform", context.platform);
1340
+ pushKV(metadata, "deepdots_sdk", context.sdk);
1230
1341
  pushKV(metadata, "deepdots_language", context.language);
1231
1342
  if (context.device) {
1232
1343
  const d = context.device;
@@ -1425,7 +1536,9 @@ function createFeedbackSink(options) {
1425
1536
  savePending();
1426
1537
  setTimeout(() => void drain(), 0);
1427
1538
  }
1428
- return async (envelope, meta) => {
1539
+ const sink = (envelope, meta) => runInBackgroundTask(options.backgroundTask, "deepdots-analytics", () => deliver(envelope, meta));
1540
+ return sink;
1541
+ async function deliver(envelope, meta) {
1429
1542
  if (meta?.resetSession) {
1430
1543
  feedbackSessionId = void 0;
1431
1544
  options.onSessionReset?.();
@@ -1446,7 +1559,7 @@ function createFeedbackSink(options) {
1446
1559
  }
1447
1560
  const retries = pending2.length ? drain() : null;
1448
1561
  await Promise.all([retries, send(batch, final, false)]);
1449
- };
1562
+ }
1450
1563
  }
1451
1564
 
1452
1565
  // src/analytics/suspended-session.ts
@@ -2042,6 +2155,33 @@ function clearPopupState(storage) {
2042
2155
  }
2043
2156
  }
2044
2157
 
2158
+ // src/platform/react-native-platform.ts
2159
+ var registered = null;
2160
+ function getReactNativePlatform() {
2161
+ return registered;
2162
+ }
2163
+ function nativeModuleTask(mod) {
2164
+ let seq = 0;
2165
+ return (name) => {
2166
+ const token = `dd-${Date.now().toString(36)}-${(seq++).toString(36)}`;
2167
+ mod.begin(token, name);
2168
+ let ended = false;
2169
+ return () => {
2170
+ if (ended) return;
2171
+ ended = true;
2172
+ mod.end(token);
2173
+ };
2174
+ };
2175
+ }
2176
+ function resolveBackgroundTask(explicit, platform) {
2177
+ if (explicit) return explicit;
2178
+ const mod = platform?.backgroundTaskModule;
2179
+ if (platform?.os === "ios" && mod && typeof mod.begin === "function" && typeof mod.end === "function") {
2180
+ return nativeModuleTask(mod);
2181
+ }
2182
+ return void 0;
2183
+ }
2184
+
2045
2185
  // src/analytics/messaging.ts
2046
2186
  var MESSAGE_CHANNELS = ["push", "in_app"];
2047
2187
  function buildMessageParams(stage, o) {
@@ -2121,6 +2261,10 @@ var ANALYTICS_RESUME_WINDOW_MS = 6e4;
2121
2261
  var RESERVED_EVENT_PREFIX = "deepdots_";
2122
2262
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
2123
2263
  var MAX_PENDING_TRIGGERS = 20;
2264
+ function triggerDelayMs(delaySeconds) {
2265
+ const n = typeof delaySeconds === "number" ? delaySeconds : Number(delaySeconds);
2266
+ return Number.isFinite(n) && n > 0 ? Math.round(n * 1e3) : 0;
2267
+ }
2124
2268
  var DeepdotsPopups = class {
2125
2269
  constructor() {
2126
2270
  this.config = null;
@@ -2152,6 +2296,10 @@ var DeepdotsPopups = class {
2152
2296
  this.surveyToPopupId = /* @__PURE__ */ new Map();
2153
2297
  // surveyId -> popupId
2154
2298
  this.deferredExitTimers = [];
2299
+ /** Popups esperando su `delaySeconds` (uno por popup). */
2300
+ this.delayedPopups = /* @__PURE__ */ new Map();
2301
+ /** Última pantalla de `setScreen` (React Native). */
2302
+ this.currentScreen = null;
2155
2303
  this.baseUrl = "";
2156
2304
  this.env = "production";
2157
2305
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -2197,6 +2345,8 @@ var DeepdotsPopups = class {
2197
2345
  this.lastEngagementAt = 0;
2198
2346
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
2199
2347
  this.hiddenAt = null;
2348
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
2349
+ this.appStateSubscription = void 0;
2200
2350
  /**
2201
2351
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
2202
2352
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -2229,6 +2379,10 @@ var DeepdotsPopups = class {
2229
2379
  this.log("SDK already initialized");
2230
2380
  return;
2231
2381
  }
2382
+ const rn = getReactNativePlatform();
2383
+ if (!config.platform && (rn?.os === "ios" || rn?.os === "android")) {
2384
+ config = { ...config, platform: rn.os };
2385
+ }
2232
2386
  const env = resolveEnvironment(config.nodeEnv);
2233
2387
  this.baseUrl = env.apiBaseUrl;
2234
2388
  this.env = config.nodeEnv || "production";
@@ -2279,6 +2433,10 @@ var DeepdotsPopups = class {
2279
2433
  // persiste y se reenvía en el arranque siguiente. En web el cierre sale con
2280
2434
  // `keepalive` y varias pestañas compartirían el mismo storage.
2281
2435
  storage: (config.platform ?? "web") !== "web" ? storage : void 0,
2436
+ // iOS suspende la app con el POST de cierre en vuelo: el host puede darle
2437
+ // tiempo de background (DD-55). El reenvío del arranque siguiente sigue igual.
2438
+ // La del host o, en iOS, la del módulo nativo del paquete (autolinking).
2439
+ backgroundTask: resolveBackgroundTask(config.backgroundTask, rn),
2282
2440
  onSessionId: (id) => {
2283
2441
  this.analyticsFeedbackSessionId = id;
2284
2442
  this.notifyFeedbackSession(id, "open");
@@ -2336,6 +2494,7 @@ var DeepdotsPopups = class {
2336
2494
  }
2337
2495
  }
2338
2496
  this.initialized = true;
2497
+ this.installAutoLifecycle(rn, config);
2339
2498
  this.log("SDK initialized", this.config);
2340
2499
  if (this.renderer.init) this.renderer.init();
2341
2500
  this.awaitingPopups = Boolean(this.config.apiKey && this.baseUrl);
@@ -2506,6 +2665,11 @@ var DeepdotsPopups = class {
2506
2665
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
2507
2666
  */
2508
2667
  setScreen(name) {
2668
+ const screen2 = typeof name === "string" ? name.trim() : "";
2669
+ if (screen2) {
2670
+ this.cancelDelayedPopups("screen change", (entry) => entry.screen !== screen2);
2671
+ this.currentScreen = screen2;
2672
+ }
2509
2673
  if (!this.navObserver) return;
2510
2674
  if (!this.navStarted) {
2511
2675
  this.navObserver.begin(name);
@@ -2527,9 +2691,42 @@ var DeepdotsPopups = class {
2527
2691
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
2528
2692
  */
2529
2693
  onBackground() {
2694
+ this.cancelDelayedPopups("app to background");
2530
2695
  this.closeSession("background");
2531
2696
  this.engagement?.pause();
2532
2697
  }
2698
+ /**
2699
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
2700
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
2701
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
2702
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
2703
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
2704
+ */
2705
+ onInactive() {
2706
+ if (this.sessionOpen) this.flushEngagement();
2707
+ this.flushAnalytics();
2708
+ }
2709
+ /**
2710
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
2711
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
2712
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
2713
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
2714
+ * `autoTrack.lifecycle: false` lo apaga.
2715
+ */
2716
+ installAutoLifecycle(rn, config) {
2717
+ if (config.autoTrack?.lifecycle === false) return;
2718
+ const appState = rn?.appState;
2719
+ if (!appState || typeof appState.addEventListener !== "function" || this.appStateSubscription) return;
2720
+ try {
2721
+ this.appStateSubscription = appState.addEventListener("change", (state) => {
2722
+ if (state === "active") this.onForeground();
2723
+ else if (state === "background") this.onBackground();
2724
+ else this.onInactive();
2725
+ });
2726
+ this.log("lifecycle \xB7 AppState wired automatically");
2727
+ } catch {
2728
+ }
2729
+ }
2533
2730
  /**
2534
2731
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
2535
2732
  * `session_end` y envía el último lote con `completed:true`.
@@ -2870,16 +3067,21 @@ var DeepdotsPopups = class {
2870
3067
  return;
2871
3068
  }
2872
3069
  const value = type === "time" && typeof trigger.value === "number" ? trigger.value * 1e3 : trigger.value;
2873
- derived.push({ type, value, surveyId: def.surveyId, popupId: def.id });
3070
+ derived.push({ type, value, surveyId: def.surveyId, popupId: def.id, delaySeconds: trigger.delaySeconds });
2874
3071
  });
2875
3072
  });
2876
3073
  if (derived.length) {
2877
3074
  this.configureTriggers(derived);
2878
3075
  }
2879
3076
  }
2880
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
2881
- triggerSurvey(surveyId, popupId) {
2882
- if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId })) return;
3077
+ /**
3078
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
3079
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
3080
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
3081
+ */
3082
+ triggerSurvey(surveyId, popupId, options) {
3083
+ const delaySeconds = options?.delaySeconds;
3084
+ if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId, delaySeconds })) return;
2883
3085
  const def = this.findPopupDefinition(surveyId, popupId);
2884
3086
  if (!def) {
2885
3087
  this.debug("No popup definition for trigger", { surveyId, popupId });
@@ -2889,7 +3091,7 @@ var DeepdotsPopups = class {
2889
3091
  this.debug("Conditions prevented showing popup", def.id);
2890
3092
  return;
2891
3093
  }
2892
- this.showDefinition(def);
3094
+ this.showAfterDelay(def, delaySeconds);
2893
3095
  }
2894
3096
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
2895
3097
  triggerEvent(eventName) {
@@ -2906,9 +3108,9 @@ var DeepdotsPopups = class {
2906
3108
  }
2907
3109
  evaluateEvent(normalized) {
2908
3110
  const candidates = this.popupDefinitions.filter((def) => {
2909
- return def.triggers.some((trigger) => {
2910
- const triggerValue = String(trigger.value ?? "").trim();
2911
- return trigger.type === "event" && triggerValue === normalized;
3111
+ return def.triggers.some((trigger2) => {
3112
+ const triggerValue = String(trigger2.value ?? "").trim();
3113
+ return trigger2.type === "event" && triggerValue === normalized;
2912
3114
  });
2913
3115
  });
2914
3116
  if (!candidates.length) {
@@ -2920,7 +3122,69 @@ var DeepdotsPopups = class {
2920
3122
  this.debug("Event popup blocked by conditions/segments", { eventName: normalized });
2921
3123
  return;
2922
3124
  }
2923
- this.showDefinition(matched);
3125
+ const trigger = matched.triggers.find(
3126
+ (t) => t.type === "event" && String(t.value ?? "").trim() === normalized
3127
+ );
3128
+ this.showAfterDelay(matched, trigger?.delaySeconds);
3129
+ }
3130
+ /**
3131
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
3132
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
3133
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
3134
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
3135
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
3136
+ */
3137
+ showAfterDelay(def, delaySeconds) {
3138
+ const delayMs = triggerDelayMs(delaySeconds);
3139
+ if (delayMs <= 0) {
3140
+ this.showDefinition(def);
3141
+ return;
3142
+ }
3143
+ if (this.delayedPopups.has(def.id)) {
3144
+ this.debug("Popup already waiting for its delay", def.id);
3145
+ return;
3146
+ }
3147
+ const entry = {
3148
+ popupId: def.id,
3149
+ timer: setTimeout(() => this.showDelayedPopup(def.id), delayMs),
3150
+ firedAt: Date.now(),
3151
+ href: this.currentHref(),
3152
+ screen: this.currentScreen
3153
+ };
3154
+ this.delayedPopups.set(def.id, entry);
3155
+ this.debug(`Popup delayed ${delayMs}ms`, def.id);
3156
+ }
3157
+ showDelayedPopup(popupId) {
3158
+ const entry = this.delayedPopups.get(popupId);
3159
+ if (!entry) return;
3160
+ this.delayedPopups.delete(popupId);
3161
+ const def = this.popupDefinitions.find((popup) => popup.id === popupId);
3162
+ if (!def) return;
3163
+ if (this.currentHref() !== entry.href || this.currentScreen !== entry.screen) {
3164
+ this.debug("Delayed popup dropped: route changed", popupId);
3165
+ return;
3166
+ }
3167
+ if (!this.shouldShow(def)) {
3168
+ this.debug("Delayed popup dropped by conditions at due time", popupId);
3169
+ return;
3170
+ }
3171
+ if ((this.lastShown.get(popupId) ?? 0) >= entry.firedAt) {
3172
+ this.debug("Delayed popup dropped: already shown while waiting", popupId);
3173
+ return;
3174
+ }
3175
+ this.showDefinition(def);
3176
+ }
3177
+ cancelDelayedPopups(reason, predicate = () => true) {
3178
+ this.delayedPopups.forEach((entry, popupId) => {
3179
+ if (!predicate(entry)) return;
3180
+ clearTimeout(entry.timer);
3181
+ this.delayedPopups.delete(popupId);
3182
+ this.debug(`Delayed popup cancelled (${reason})`, popupId);
3183
+ });
3184
+ }
3185
+ currentHref() {
3186
+ if (typeof window === "undefined" || !window.location) return "";
3187
+ return this.normalizeUrl(window.location.href || "");
2924
3188
  }
2925
3189
  /**
2926
3190
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
@@ -2953,7 +3217,7 @@ var DeepdotsPopups = class {
2953
3217
  this.debug("Replaying triggers received before popups loaded", replay.length);
2954
3218
  replay.forEach((trigger) => {
2955
3219
  if (trigger.kind === "event") this.evaluateEvent(trigger.name);
2956
- else this.triggerSurvey(trigger.surveyId, trigger.popupId);
3220
+ else this.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
2957
3221
  });
2958
3222
  }
2959
3223
  showDefinition(def) {
@@ -2965,7 +3229,7 @@ var DeepdotsPopups = class {
2965
3229
  this.surveyToPopupId.set(def.surveyId, def.id);
2966
3230
  this.lastShown.set(def.id, Date.now());
2967
3231
  this.persistPopupState();
2968
- this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title);
3232
+ this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title, def.surveyFrontend?.sdkVersion);
2969
3233
  this.emitEvent("popup_shown", def.surveyId, { popupId: def.id });
2970
3234
  }
2971
3235
  shouldShow(def, pathUrl, skipPathCheck = false) {
@@ -3337,7 +3601,7 @@ var DeepdotsPopups = class {
3337
3601
  }
3338
3602
  }
3339
3603
  /** Render the popup UI */
3340
- renderPopup(surveyId, productId, actions, style, title) {
3604
+ renderPopup(surveyId, productId, actions, style, title, surveySdkVersion) {
3341
3605
  const userId = this.tracking?.getUserId() ?? this.config?.userId;
3342
3606
  const sessionId = this.tracking?.getSessionId() ?? void 0;
3343
3607
  const miniService = this.analytics?.getMiniService() ?? void 0;
@@ -3356,7 +3620,7 @@ var DeepdotsPopups = class {
3356
3620
  miniService,
3357
3621
  analyticsFeedbackSessionId,
3358
3622
  this.renderChrome,
3359
- { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce }
3623
+ { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce, surveySdkVersion, debug: this.config?.debug }
3360
3624
  );
3361
3625
  }
3362
3626
  /** Hide the popup */
@@ -3367,6 +3631,15 @@ var DeepdotsPopups = class {
3367
3631
  emitEvent(type, surveyId, data) {
3368
3632
  const event = { type, surveyId, timestamp: Date.now(), data };
3369
3633
  this.log("Event emitted", event);
3634
+ if (type === "survey_error") {
3635
+ const popupId = data?.popupId || this.surveyToPopupId.get(surveyId);
3636
+ this.track("deepdots_survey_error", {
3637
+ survey_id: surveyId,
3638
+ ...popupId ? { popup_id: popupId } : {},
3639
+ reason: data?.reason,
3640
+ message: data?.message
3641
+ });
3642
+ }
3370
3643
  const isPartialClick = type === "popup_clicked" && data?.action === "partial";
3371
3644
  if (isPartialClick) {
3372
3645
  this.markSurveyProgress(surveyId, "PARTIAL");
@@ -3514,10 +3787,10 @@ var DeepdotsPopups = class {
3514
3787
  }
3515
3788
  normalizeTriggers(value) {
3516
3789
  const items = Array.isArray(value) ? value : value ? [value] : [];
3517
- return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => ({
3518
- type: trigger.type,
3519
- value: trigger.value
3520
- }));
3790
+ return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => {
3791
+ const delayMs = triggerDelayMs(trigger.delaySeconds);
3792
+ return delayMs > 0 ? { type: trigger.type, value: trigger.value, delaySeconds: delayMs / 1e3 } : { type: trigger.type, value: trigger.value };
3793
+ });
3521
3794
  }
3522
3795
  normalizeCooldown(value) {
3523
3796
  if (!Array.isArray(value)) return [];
@@ -3572,7 +3845,9 @@ function setupReactNative(sdk, config, deps = {}) {
3572
3845
  const storage = deps.mmkv ? mmkvStorage(deps.mmkv) : config.storage;
3573
3846
  const device = deps.deviceInfo ? collectRnDevice(deps.deviceInfo) : config.device;
3574
3847
  const platform = deps.platform ?? config.platform;
3575
- sdk.init({ ...config, storage, device, platform });
3848
+ const backgroundTask = config.backgroundTask ?? deps.backgroundTask ?? void 0;
3849
+ const autoTrack = deps.appState?.addEventListener ? { ...config.autoTrack, lifecycle: false } : config.autoTrack;
3850
+ sdk.init({ ...config, storage, device, platform, backgroundTask, autoTrack });
3576
3851
  const errorUtils = deps.errorUtils ?? globalThis.ErrorUtils;
3577
3852
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
3578
3853
  sdk.installReactNativeCrashHandler(errorUtils);
@@ -3582,7 +3857,7 @@ function setupReactNative(sdk, config, deps = {}) {
3582
3857
  subscription = deps.appState.addEventListener("change", (state) => {
3583
3858
  if (state === "active") sdk.onForeground();
3584
3859
  else if (state === "background") sdk.onBackground();
3585
- else sdk.flushAnalytics();
3860
+ else sdk.onInactive();
3586
3861
  });
3587
3862
  }
3588
3863
  return () => {
@@ -3590,6 +3865,7 @@ function setupReactNative(sdk, config, deps = {}) {
3590
3865
  };
3591
3866
  }
3592
3867
  export {
3868
+ BACKGROUND_TASK_MAX_MS,
3593
3869
  BrowserPopupRenderer,
3594
3870
  ContactManager,
3595
3871
  CrashReporter,
@@ -3606,6 +3882,7 @@ export {
3606
3882
  RTL_LOCALES,
3607
3883
  ReactNativePopupRenderer,
3608
3884
  SUPPORTED_LANGUAGES,
3885
+ backgroundTimerTask,
3609
3886
  buildAnalyticsFeedbackBody,
3610
3887
  buildMessageParams,
3611
3888
  buildSurveyHtml,