@joryio/web-sdk 1.4.0-beta.7 → 1.4.0-beta.9

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 (48) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/config.d.ts +1 -1
  3. package/dist/core/editor-gate.d.ts +2 -0
  4. package/dist/core/editor-gate.d.ts.map +1 -1
  5. package/dist/core/page-context.d.ts +13 -0
  6. package/dist/core/page-context.d.ts.map +1 -1
  7. package/dist/core/page-edits.d.ts +26 -0
  8. package/dist/core/page-edits.d.ts.map +1 -1
  9. package/dist/core/placements.d.ts +34 -0
  10. package/dist/core/placements.d.ts.map +1 -1
  11. package/dist/core/sdk.d.ts +5 -0
  12. package/dist/core/sdk.d.ts.map +1 -1
  13. package/dist/core/show-when.d.ts +42 -0
  14. package/dist/core/show-when.d.ts.map +1 -0
  15. package/dist/editor/editor-strings.d.ts +11 -0
  16. package/dist/editor/editor-strings.d.ts.map +1 -1
  17. package/dist/editor/editor-ui.d.ts +4 -1
  18. package/dist/editor/editor-ui.d.ts.map +1 -1
  19. package/dist/editor/liquid-field.d.ts +1 -0
  20. package/dist/editor/liquid-field.d.ts.map +1 -1
  21. package/dist/editor/visual-editor.d.ts +25 -2
  22. package/dist/editor/visual-editor.d.ts.map +1 -1
  23. package/dist/index.d.mts +25 -3
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/joryio-cards-ui.min.js +1 -1
  27. package/dist/joryio-cards-ui.min.js.map +1 -1
  28. package/dist/joryio-editor.min.js +2 -2
  29. package/dist/joryio-editor.min.js.map +1 -1
  30. package/dist/joryio-sw.js +1 -1
  31. package/dist/joryio.cjs.js +631 -26
  32. package/dist/joryio.min.js +2 -2
  33. package/dist/joryio.min.js.map +1 -1
  34. package/dist/joryio.mjs +631 -27
  35. package/dist/joryio.umd.js +631 -26
  36. package/package.json +1 -1
  37. package/src/core/config.ts +1 -1
  38. package/src/core/editor-gate.ts +21 -0
  39. package/src/core/page-context.ts +84 -1
  40. package/src/core/page-edits.ts +149 -5
  41. package/src/core/placements.ts +373 -6
  42. package/src/core/sdk.ts +79 -1
  43. package/src/core/show-when.ts +159 -0
  44. package/src/editor/editor-strings.ts +11 -0
  45. package/src/editor/editor-ui.ts +15 -1
  46. package/src/editor/liquid-field.ts +17 -2
  47. package/src/editor/visual-editor.ts +350 -75
  48. package/src/index.ts +4 -0
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.7
2
+ * Joryio Web SDK v1.4.0-beta.9
3
3
  * (c) 2026 Joryio. All rights reserved.
4
4
  * @license Commercial - see https://github.com/joryio/joryio-web-sdk/blob/main/LICENSE
5
5
  */
@@ -28,7 +28,7 @@ var JoryioSDK = (function (exports) {
28
28
  return fmix32(hash >>> 0);
29
29
  }
30
30
 
31
- const SDK_VERSION = '1.4.0-beta.7';
31
+ const SDK_VERSION = '1.4.0-beta.9';
32
32
  const SDK_PLATFORM_HEADER = 'X-Joryio-SDK';
33
33
  const SDK_VERSION_HEADER = 'X-Joryio-SDK-Version';
34
34
  const SDK_PLATFORM = 'web';
@@ -312,6 +312,15 @@ var JoryioSDK = (function (exports) {
312
312
  }
313
313
  return cur;
314
314
  }
315
+ const TOUCH_EXIT_INTENT = {
316
+ armPercent: 25,
317
+ armPx: 400,
318
+ upPx: 120,
319
+ windowMs: 300,
320
+ minMs: 3000,
321
+ sampleMs: 50,
322
+ };
323
+ const TOUCH_PRIMARY_QUERY = '(hover: none) and (pointer: coarse)';
315
324
  class PageContextTracker {
316
325
  constructor(options = {}) {
317
326
  this.options = options;
@@ -322,6 +331,10 @@ var JoryioSDK = (function (exports) {
322
331
  this.visibleMs = 0;
323
332
  this.visibleSince = null;
324
333
  this.exitFired = false;
334
+ this.pageStartedAt = Date.now();
335
+ this.maxScrollY = 0;
336
+ this.scrollSamples = [];
337
+ this.touchQuery = null;
325
338
  this.timer = null;
326
339
  this.undo = [];
327
340
  this.started = false;
@@ -430,7 +443,17 @@ var JoryioSDK = (function (exports) {
430
443
  this.undo.push(() => target.removeEventListener(ev, fn, opts));
431
444
  };
432
445
  on(window, 'popstate', () => this.checkRoute());
433
- on(window, 'scroll', () => this.measureScroll(), { passive: true });
446
+ this.pageStartedAt = Date.now();
447
+ try {
448
+ this.touchQuery = typeof window.matchMedia === 'function' ? window.matchMedia(TOUCH_PRIMARY_QUERY) : null;
449
+ }
450
+ catch (_a) {
451
+ this.touchQuery = null;
452
+ }
453
+ on(window, 'scroll', () => {
454
+ this.measureScroll();
455
+ this.touchExitIntent();
456
+ }, { passive: true });
434
457
  on(document, 'mouseout', (e) => {
435
458
  if (this.exitFired || e.relatedTarget || e.toElement)
436
459
  return;
@@ -461,6 +484,8 @@ var JoryioSDK = (function (exports) {
461
484
  }
462
485
  }
463
486
  this.listeners.clear();
487
+ this.scrollSamples = [];
488
+ this.touchQuery = null;
464
489
  this.started = false;
465
490
  }
466
491
  checkRoute() {
@@ -472,6 +497,9 @@ var JoryioSDK = (function (exports) {
472
497
  this.visibleMs = 0;
473
498
  this.visibleSince = typeof document !== 'undefined' && document.visibilityState === 'hidden' ? null : Date.now();
474
499
  this.exitFired = false;
500
+ this.pageStartedAt = Date.now();
501
+ this.maxScrollY = 0;
502
+ this.scrollSamples = [];
475
503
  this.emit({ type: 'page_change', url });
476
504
  }
477
505
  patchHistory() {
@@ -513,6 +541,38 @@ var JoryioSDK = (function (exports) {
513
541
  catch (_b) {
514
542
  }
515
543
  }
544
+ touchExitIntent() {
545
+ var _a;
546
+ if (this.exitFired || !((_a = this.touchQuery) === null || _a === void 0 ? void 0 : _a.matches))
547
+ return;
548
+ try {
549
+ const c = TOUCH_EXIT_INTENT;
550
+ const now = Date.now();
551
+ const last = this.scrollSamples[this.scrollSamples.length - 1];
552
+ if (last && now - last.t < c.sampleMs)
553
+ return;
554
+ const y = Math.max(0, window.scrollY || document.documentElement.scrollTop || 0);
555
+ if (y > this.maxScrollY)
556
+ this.maxScrollY = y;
557
+ this.scrollSamples = this.scrollSamples.filter((s) => now - s.t <= c.windowMs);
558
+ this.scrollSamples.push({ y, t: now });
559
+ if (now - this.pageStartedAt < c.minMs)
560
+ return;
561
+ if (this.maxScrollY < c.armPx && this.maxScrollPercent < c.armPercent)
562
+ return;
563
+ let peak = y;
564
+ for (const s of this.scrollSamples)
565
+ if (s.y > peak)
566
+ peak = s.y;
567
+ if (peak - y >= c.upPx) {
568
+ this.exitFired = true;
569
+ this.scrollSamples = [];
570
+ this.emit({ type: 'exit_intent' });
571
+ }
572
+ }
573
+ catch (_b) {
574
+ }
575
+ }
516
576
  visibilityChanged() {
517
577
  if (document.visibilityState === 'hidden') {
518
578
  if (this.visibleSince !== null)
@@ -549,8 +609,119 @@ var JoryioSDK = (function (exports) {
549
609
  }
550
610
  }
551
611
 
612
+ const SHOW_WHEN_KINDS = ['load', 'seconds', 'scroll', 'exit', 'event'];
613
+ const intIn = (v, min, max) => typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max;
614
+ function parseShowWhen(raw) {
615
+ if (raw === undefined || raw === null)
616
+ return { kind: 'load' };
617
+ if (typeof raw !== 'object')
618
+ return null;
619
+ const o = raw;
620
+ switch (o.kind) {
621
+ case 'load':
622
+ case 'exit':
623
+ return { kind: o.kind };
624
+ case 'seconds':
625
+ return intIn(o.seconds, 1, 3600) ? { kind: 'seconds', seconds: o.seconds } : null;
626
+ case 'scroll':
627
+ return intIn(o.percent, 1, 100) ? { kind: 'scroll', percent: o.percent } : null;
628
+ case 'event': {
629
+ const e = typeof o.event === 'string' ? o.event.trim() : '';
630
+ return e && e.length <= 255 ? { kind: 'event', event: e } : null;
631
+ }
632
+ default:
633
+ return null;
634
+ }
635
+ }
636
+ const isDeferred = (raw) => { var _a; return ((_a = parseShowWhen(raw)) === null || _a === void 0 ? void 0 : _a.kind) !== 'load'; };
637
+ function eventNames(raw, max = 50) {
638
+ return Array.isArray(raw) ? raw.filter((e) => typeof e === 'string' && e.length > 0 && e.length <= 255).slice(0, max) : [];
639
+ }
640
+ const MAX_EVENTS = 200;
641
+ class ShowWhenMoments {
642
+ constructor(page, sessionId, sdkKey) {
643
+ this.page = page;
644
+ this.sessionId = sessionId;
645
+ this.events = new Set();
646
+ this.sid = undefined;
647
+ this.listeners = new Set();
648
+ this.store = `jry_show_when_${bucketHash(sdkKey).toString(36)}`;
649
+ this.off = page ? page.onSignal(() => this.emit()) : null;
650
+ }
651
+ met(sw) {
652
+ var _a;
653
+ if (!sw)
654
+ return false;
655
+ if (sw.kind === 'load')
656
+ return true;
657
+ if (sw.kind === 'event')
658
+ return this.visitEvents().has(sw.event);
659
+ const p = (_a = this.page) === null || _a === void 0 ? void 0 : _a.progress();
660
+ if (!p)
661
+ return false;
662
+ return sw.kind === 'seconds' ? p.seconds >= sw.seconds : sw.kind === 'scroll' ? p.scrollPercent >= sw.percent : p.exitIntent;
663
+ }
664
+ noteEvent(name) {
665
+ const events = this.visitEvents();
666
+ if (!events.has(name) && events.size < MAX_EVENTS) {
667
+ events.add(name);
668
+ try {
669
+ sessionStorage.setItem(this.store, JSON.stringify({ sid: this.sid, names: Array.from(events) }));
670
+ }
671
+ catch (_a) {
672
+ }
673
+ }
674
+ this.emit();
675
+ }
676
+ onChange(cb) {
677
+ this.listeners.add(cb);
678
+ return () => this.listeners.delete(cb);
679
+ }
680
+ destroy() {
681
+ var _a;
682
+ (_a = this.off) === null || _a === void 0 ? void 0 : _a.call(this);
683
+ this.listeners.clear();
684
+ }
685
+ visitEvents() {
686
+ const sid = this.sessionId();
687
+ if (sid !== this.sid) {
688
+ this.sid = sid;
689
+ this.events = new Set();
690
+ try {
691
+ const raw = JSON.parse(sessionStorage.getItem(this.store) || 'null');
692
+ if (raw && sid && raw.sid === sid)
693
+ this.events = new Set(eventNames(raw.names, MAX_EVENTS));
694
+ }
695
+ catch (_a) {
696
+ }
697
+ }
698
+ return this.events;
699
+ }
700
+ emit() {
701
+ for (const cb of Array.from(this.listeners)) {
702
+ try {
703
+ cb();
704
+ }
705
+ catch (_a) {
706
+ }
707
+ }
708
+ }
709
+ }
710
+
552
711
  const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append', 'replace'];
553
712
  const PAGE_EDITS_CAPABILITY = 'page_edits';
713
+ const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'];
714
+ const PAGE_EDIT_MOBILE_BREAKPOINT = 768;
715
+ const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';
716
+ function isMobileViewport(win = window) {
717
+ try {
718
+ return typeof win.matchMedia === 'function' ? win.matchMedia(PAGE_EDIT_MOBILE_QUERY).matches : win.innerWidth < PAGE_EDIT_MOBILE_BREAKPOINT;
719
+ }
720
+ catch (_a) {
721
+ return false;
722
+ }
723
+ }
724
+ const editShowsOn = (e, mobile) => !e.device || e.device === 'all' || (e.device === 'mobile') === mobile;
554
725
  const PAGE_EDIT_ANTI_FLICKER_MS = 300;
555
726
  const MAX_SELECTOR_LENGTH = 500;
556
727
  const MAX_TEXT_LENGTH = 2000;
@@ -573,13 +744,14 @@ var JoryioSDK = (function (exports) {
573
744
  const SERVER_SPOT_ATTR = 'data-joryio-server-spot';
574
745
  const SERVER_MARKER_VERSION = 1;
575
746
  const sameEdit = (a, b) => {
576
- var _a, _b, _c, _d, _e, _f;
747
+ var _a, _b, _c, _d, _e, _f, _g, _h;
577
748
  return a.id === b.id &&
578
749
  a.selector === b.selector &&
579
750
  a.operation === b.operation &&
580
751
  ((_a = a.value) !== null && _a !== void 0 ? _a : null) === ((_b = b.value) !== null && _b !== void 0 ? _b : null) &&
581
752
  ((_c = a.placementKey) !== null && _c !== void 0 ? _c : null) === ((_d = b.placementKey) !== null && _d !== void 0 ? _d : null) &&
582
753
  ((_e = a.position) !== null && _e !== void 0 ? _e : null) === ((_f = b.position) !== null && _f !== void 0 ? _f : null) &&
754
+ ((_g = a.device) !== null && _g !== void 0 ? _g : null) === ((_h = b.device) !== null && _h !== void 0 ? _h : null) &&
583
755
  !b.personalized;
584
756
  };
585
757
  function serverMarkerElement() {
@@ -706,7 +878,10 @@ var JoryioSDK = (function (exports) {
706
878
  function trustedEdit(e) {
707
879
  if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector))
708
880
  return null;
709
- const base = Object.assign({ id: e.id, selector: e.selector.trim() }, (e.personalized === true ? { personalized: true } : {}));
881
+ const device = e.device;
882
+ if (device != null && !PAGE_EDIT_DEVICES.includes(device))
883
+ return null;
884
+ const base = Object.assign(Object.assign({ id: e.id, selector: e.selector.trim() }, (device === 'mobile' || device === 'desktop' ? { device: device } : {})), (e.personalized === true ? { personalized: true } : {}));
710
885
  switch (e.operation) {
711
886
  case 'hide':
712
887
  return Object.assign(Object.assign({}, base), { operation: 'hide' });
@@ -745,8 +920,15 @@ var JoryioSDK = (function (exports) {
745
920
  this.server = null;
746
921
  this.serverUrl = null;
747
922
  this.generation = 0;
923
+ this.mobile = false;
924
+ this.offMedia = null;
748
925
  this.started = false;
749
926
  this.destroyed = false;
927
+ this.moments = null;
928
+ this.momentsUnsubscribe = null;
929
+ this.revealed = new Set();
930
+ this.recheckOn = [];
931
+ this.rechecked = new Set();
750
932
  this.stores = pageEditsStorageKeys(sdkKey);
751
933
  try {
752
934
  localStorage.removeItem(LEGACY_SELECTOR_STORE);
@@ -767,7 +949,45 @@ var JoryioSDK = (function (exports) {
767
949
  });
768
950
  }
769
951
  }
952
+ setShowWhen(moments) {
953
+ var _a;
954
+ (_a = this.momentsUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
955
+ this.moments = moments;
956
+ this.momentsUnsubscribe = moments ? moments.onChange(() => this.sweep()) : null;
957
+ }
958
+ due(x) {
959
+ const sw = parseShowWhen(x.showWhen);
960
+ return !!sw && (sw.kind === 'load' || this.revealed.has(x.id) || (!!this.moments && this.moments.met(sw)));
961
+ }
962
+ sweep() {
963
+ if (!this.started || this.destroyed)
964
+ return;
965
+ let any = false;
966
+ for (const x of this.experiences) {
967
+ if (this.revealed.has(x.wire.id) || !isDeferred(x.wire.showWhen) || !this.due(x.wire))
968
+ continue;
969
+ this.revealed.add(x.wire.id);
970
+ any = true;
971
+ }
972
+ if (any)
973
+ this.applyAll();
974
+ }
975
+ claimRecheck(eventName) {
976
+ if (!this.moments || !this.started || this.destroyed || this.rechecked.has(eventName))
977
+ return false;
978
+ const waits = this.recheckOn.includes(eventName) ||
979
+ this.experiences.some((x) => { var _a; return ((_a = parseShowWhen(x.wire.showWhen)) === null || _a === void 0 ? void 0 : _a.event) === eventName; });
980
+ if (waits)
981
+ this.rechecked.add(eventName);
982
+ return waits;
983
+ }
984
+ recheck(event) {
985
+ const url = this.url();
986
+ if (url && this.started && !this.destroyed)
987
+ void this.fetch(url, this.generation, event);
988
+ }
770
989
  start() {
990
+ var _a;
771
991
  if (this.started || this.destroyed || typeof document === 'undefined')
772
992
  return;
773
993
  this.started = true;
@@ -775,8 +995,28 @@ var JoryioSDK = (function (exports) {
775
995
  this.observer = new MutationObserver(() => this.schedule());
776
996
  this.observer.observe(document.documentElement, { childList: true, subtree: true });
777
997
  }
998
+ this.mobile = isMobileViewport();
999
+ const mq = typeof window.matchMedia === 'function' ? window.matchMedia(PAGE_EDIT_MOBILE_QUERY) : null;
1000
+ if (mq) {
1001
+ const onChange = () => this.viewportChanged();
1002
+ if (mq.addEventListener)
1003
+ mq.addEventListener('change', onChange);
1004
+ else
1005
+ (_a = mq.addListener) === null || _a === void 0 ? void 0 : _a.call(mq, onChange);
1006
+ this.offMedia = () => { var _a; return (mq.removeEventListener ? mq.removeEventListener('change', onChange) : (_a = mq.removeListener) === null || _a === void 0 ? void 0 : _a.call(mq, onChange)); };
1007
+ }
778
1008
  this.loadPage();
779
1009
  }
1010
+ viewportChanged() {
1011
+ const mobile = isMobileViewport();
1012
+ if (this.destroyed || mobile === this.mobile)
1013
+ return;
1014
+ this.mobile = mobile;
1015
+ if (!this.experiences.some((x) => x.edits.some((e) => e.device)))
1016
+ return;
1017
+ this.revertAll();
1018
+ this.applyAll();
1019
+ }
780
1020
  invalidate(opts = {}) {
781
1021
  this.generation++;
782
1022
  this.reported.clear();
@@ -791,10 +1031,13 @@ var JoryioSDK = (function (exports) {
791
1031
  this.loadPage();
792
1032
  }
793
1033
  destroy() {
794
- var _a, _b;
1034
+ var _a, _b, _c, _d;
795
1035
  this.destroyed = true;
796
1036
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
797
- (_b = this.observer) === null || _b === void 0 ? void 0 : _b.disconnect();
1037
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
1038
+ (_c = this.offMedia) === null || _c === void 0 ? void 0 : _c.call(this);
1039
+ this.offMedia = null;
1040
+ (_d = this.observer) === null || _d === void 0 ? void 0 : _d.disconnect();
798
1041
  this.observer = null;
799
1042
  this.revertAll();
800
1043
  this.showAll();
@@ -811,6 +1054,9 @@ var JoryioSDK = (function (exports) {
811
1054
  loadPage() {
812
1055
  const generation = ++this.generation;
813
1056
  this.revertAll();
1057
+ this.revealed.clear();
1058
+ this.rechecked.clear();
1059
+ this.recheckOn = [];
814
1060
  const url = this.url();
815
1061
  if (!url) {
816
1062
  this.experiences = [];
@@ -946,7 +1192,7 @@ var JoryioSDK = (function (exports) {
946
1192
  this.siteRequest = request;
947
1193
  return request;
948
1194
  }
949
- async fetch(url, generation) {
1195
+ async fetch(url, generation, recheckEvent) {
950
1196
  var _a, _b, _c, _d;
951
1197
  const consent = this.runtime.consent();
952
1198
  if (consent === null || this.destroyed) {
@@ -956,7 +1202,7 @@ var JoryioSDK = (function (exports) {
956
1202
  const personal = consent === 'granted';
957
1203
  const userId = personal ? this.identity.getUserId() : null;
958
1204
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
959
- const body = Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY], trackingConsent: consent, context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} } });
1205
+ const body = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: [PAGE_CONTEXT_CAPABILITY, PAGE_EDITS_CAPABILITY], trackingConsent: consent, context: this.page ? this.page.current() : { url, pageVariables: {}, dataLayer: {} } }), (recheckEvent ? { recheckEvent } : {}));
960
1206
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
961
1207
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
962
1208
  try {
@@ -975,6 +1221,7 @@ var JoryioSDK = (function (exports) {
975
1221
  .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e) => !!e) }));
976
1222
  this.revertAll();
977
1223
  this.experiences = experiences;
1224
+ this.recheckOn = eventNames(data.recheckOn);
978
1225
  this.reconcileServer(experiences);
979
1226
  this.remember(url, experiences, data.ttlSeconds);
980
1227
  this.applyAll();
@@ -1008,6 +1255,8 @@ var JoryioSDK = (function (exports) {
1008
1255
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1009
1256
  try {
1010
1257
  for (const x of this.experiences) {
1258
+ if (!this.due(x.wire))
1259
+ continue;
1011
1260
  if (x.wire.isControl) {
1012
1261
  const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
1013
1262
  if (seen)
@@ -1016,6 +1265,8 @@ var JoryioSDK = (function (exports) {
1016
1265
  }
1017
1266
  let landed = false;
1018
1267
  for (const edit of x.edits) {
1268
+ if (!editShowsOn(edit, this.mobile))
1269
+ continue;
1019
1270
  const token = `${x.wire.id}:${edit.id}`;
1020
1271
  const server = this.serverEdits().get(token);
1021
1272
  const byServer = !!server && server.variantId === ((_b = x.wire.variantId) !== null && _b !== void 0 ? _b : null) && sameEdit(server.edit, edit);
@@ -1163,7 +1414,7 @@ var JoryioSDK = (function (exports) {
1163
1414
  return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
1164
1415
  }
1165
1416
  remember(url, experiences, ttlSeconds) {
1166
- const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.map((e) => e.selector))))];
1417
+ const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl || isDeferred(x.wire.showWhen) ? [] : x.edits.filter((e) => editShowsOn(e, this.mobile)).map((e) => e.selector))))];
1167
1418
  try {
1168
1419
  const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
1169
1420
  delete all[url];
@@ -1257,7 +1508,7 @@ var JoryioSDK = (function (exports) {
1257
1508
  return;
1258
1509
  const keep = new Set();
1259
1510
  for (const x of experiences) {
1260
- if (x.wire.isControl)
1511
+ if (x.wire.isControl || isDeferred(x.wire.showWhen))
1261
1512
  continue;
1262
1513
  for (const e of x.edits) {
1263
1514
  const token = `${x.wire.id}:${e.id}`;
@@ -1480,6 +1731,19 @@ var JoryioSDK = (function (exports) {
1480
1731
  return false;
1481
1732
  }
1482
1733
  }
1734
+ const EDITOR_FRAME_FLAG = 'frame';
1735
+ function editorFrame() {
1736
+ try {
1737
+ if (typeof window === 'undefined' || window.parent === window)
1738
+ return false;
1739
+ if (new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) !== EDITOR_FRAME_FLAG)
1740
+ return false;
1741
+ return !!window.parent[EDITOR_GLOBAL];
1742
+ }
1743
+ catch (_a) {
1744
+ return false;
1745
+ }
1746
+ }
1483
1747
  function loadScript(src) {
1484
1748
  return loadSdkScript(src, 'data-joryio-editor');
1485
1749
  }
@@ -5606,6 +5870,9 @@ var JoryioSDK = (function (exports) {
5606
5870
  function placementProductElementId(productId) {
5607
5871
  return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
5608
5872
  }
5873
+ const SERVER_FILLED_ATTR = 'data-joryio-server-filled';
5874
+ const SERVER_FILL_ATTR = 'data-joryio-server-fill';
5875
+ const SERVER_FILLS_MARKER_KEY = 'fills';
5609
5876
  const DEFAULT_TTL_SECONDS = 300;
5610
5877
  const LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';
5611
5878
  const placementsStorageKey = (sdkKey) => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;
@@ -5722,7 +5989,14 @@ var JoryioSDK = (function (exports) {
5722
5989
  this.destroyed = false;
5723
5990
  this.page = null;
5724
5991
  this.pageUnsubscribe = null;
5992
+ this.moments = null;
5993
+ this.momentsUnsubscribe = null;
5994
+ this.revealed = new Set();
5995
+ this.spotViewable = new Set();
5996
+ this.rechecked = new Set();
5997
+ this.recheckEvent = null;
5725
5998
  this.pageScopedKeys = new Set();
5999
+ this.markerFills = null;
5726
6000
  this.loadCache();
5727
6001
  this.installBridge();
5728
6002
  this.installPageVisibility();
@@ -5751,6 +6025,7 @@ var JoryioSDK = (function (exports) {
5751
6025
  hostObserver: null,
5752
6026
  trackers: [],
5753
6027
  frameIds: [],
6028
+ serverFill: this.serverFillOf(key, element),
5754
6029
  };
5755
6030
  this.mounts.add(mount);
5756
6031
  this.observeHost(mount);
@@ -5822,6 +6097,8 @@ var JoryioSDK = (function (exports) {
5822
6097
  this.triggeredAt.clear();
5823
6098
  this.dismissedLocally.clear();
5824
6099
  this.reported.clear();
6100
+ this.revealed.clear();
6101
+ this.spotViewable.clear();
5825
6102
  this.persistCache();
5826
6103
  const keys = this.mountedKeys();
5827
6104
  for (const mount of this.mounts)
@@ -5830,13 +6107,15 @@ var JoryioSDK = (function (exports) {
5830
6107
  this.fetchKeys(keys, true).catch(() => undefined);
5831
6108
  }
5832
6109
  destroy() {
5833
- var _a, _b, _c;
6110
+ var _a, _b, _c, _d;
5834
6111
  this.destroyed = true;
5835
6112
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
5836
6113
  this.pageUnsubscribe = null;
6114
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
6115
+ this.momentsUnsubscribe = null;
5837
6116
  for (const mount of Array.from(this.mounts))
5838
6117
  this.unmount(mount);
5839
- (_b = this.mutationObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
6118
+ (_c = this.mutationObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
5840
6119
  this.mutationObserver = null;
5841
6120
  if (this.batchTimer)
5842
6121
  clearTimeout(this.batchTimer);
@@ -5851,11 +6130,11 @@ var JoryioSDK = (function (exports) {
5851
6130
  document.removeEventListener('visibilitychange', this.pageListener);
5852
6131
  }
5853
6132
  try {
5854
- if (typeof window !== 'undefined' && ((_c = window[PLACEMENT_BRIDGE_GLOBAL]) === null || _c === void 0 ? void 0 : _c.__owner) === this) {
6133
+ if (typeof window !== 'undefined' && ((_d = window[PLACEMENT_BRIDGE_GLOBAL]) === null || _d === void 0 ? void 0 : _d.__owner) === this) {
5855
6134
  delete window[PLACEMENT_BRIDGE_GLOBAL];
5856
6135
  }
5857
6136
  }
5858
- catch (_d) {
6137
+ catch (_e) {
5859
6138
  }
5860
6139
  }
5861
6140
  cleanKeys(keys) {
@@ -5884,11 +6163,23 @@ var JoryioSDK = (function (exports) {
5884
6163
  this.pageUnsubscribe = tracker.onSignal((signal) => {
5885
6164
  if (signal.type !== 'page_change' || this.destroyed)
5886
6165
  return;
6166
+ const held = this.revealed.size ? this.keysWithMoments() : [];
6167
+ this.revealed.clear();
6168
+ this.spotViewable.clear();
6169
+ this.rechecked.clear();
5887
6170
  const stale = [];
5888
6171
  this.cache.forEach((entry, key) => {
5889
6172
  if (entry.placement.pageScoped && entry.url !== signal.url)
5890
6173
  stale.push(key);
5891
6174
  });
6175
+ const rehide = held.filter((key) => !stale.includes(key));
6176
+ if (rehide.length) {
6177
+ for (const mount of this.mounts)
6178
+ if (rehide.includes(mount.key))
6179
+ this.render(mount);
6180
+ this.notify(rehide);
6181
+ this.sweep();
6182
+ }
5892
6183
  if (!stale.length)
5893
6184
  return;
5894
6185
  stale.forEach((key) => this.cache.delete(key));
@@ -5908,6 +6199,75 @@ var JoryioSDK = (function (exports) {
5908
6199
  }
5909
6200
  });
5910
6201
  }
6202
+ setShowWhen(moments) {
6203
+ var _a;
6204
+ (_a = this.momentsUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
6205
+ this.moments = moments;
6206
+ this.momentsUnsubscribe = moments ? moments.onChange(() => !this.destroyed && this.sweep()) : null;
6207
+ }
6208
+ due(handle, raw) {
6209
+ const sw = parseShowWhen(raw);
6210
+ if (!sw)
6211
+ return false;
6212
+ return sw.kind === 'load' || this.revealed.has(handle) || (!!this.moments && this.moments.met(sw));
6213
+ }
6214
+ keysWithMoments() {
6215
+ const out = [];
6216
+ this.cache.forEach((entry, key) => {
6217
+ var _a;
6218
+ const p = entry.placement;
6219
+ if (p.showWhen !== undefined || ((_a = p.deferredControls) === null || _a === void 0 ? void 0 : _a.length) || (p.items || []).some((i) => i.showWhen !== undefined))
6220
+ out.push(key);
6221
+ });
6222
+ return out;
6223
+ }
6224
+ sweep() {
6225
+ const changed = [];
6226
+ this.cache.forEach((entry, key) => {
6227
+ const p = entry.placement;
6228
+ const handles = (p.items || []).filter((i) => isDeferred(i.showWhen)).map((i) => [this.handle(key, i), i.showWhen]);
6229
+ if (p.isControl && isDeferred(p.showWhen))
6230
+ handles.push([`ctl:${key}:${p.controlToken || ''}`, p.showWhen]);
6231
+ for (const [h, raw] of handles) {
6232
+ if (this.revealed.has(h) || !this.due(h, raw))
6233
+ continue;
6234
+ this.revealed.add(h);
6235
+ if (!changed.includes(key))
6236
+ changed.push(key);
6237
+ }
6238
+ this.reportDeferred(key);
6239
+ });
6240
+ if (changed.length)
6241
+ this.applyChanged(changed);
6242
+ }
6243
+ recheckKeysFor(eventName) {
6244
+ if (!this.moments || this.destroyed)
6245
+ return [];
6246
+ const out = [];
6247
+ this.cache.forEach((entry, key) => {
6248
+ const p = entry.placement;
6249
+ if (p.pageScoped && entry.url !== this.currentUrl())
6250
+ return;
6251
+ const waits = (p.recheckOn || []).includes(eventName) ||
6252
+ (p.items || []).some((i) => { var _a; return ((_a = parseShowWhen(i.showWhen)) === null || _a === void 0 ? void 0 : _a.event) === eventName; });
6253
+ const once = `${key}\u0000${eventName}`;
6254
+ if (!waits || this.rechecked.has(once))
6255
+ return;
6256
+ this.rechecked.add(once);
6257
+ out.push(key);
6258
+ });
6259
+ return out;
6260
+ }
6261
+ recheck(keys, event) {
6262
+ const go = () => {
6263
+ keys.forEach((key) => this.lastNetworkAt.delete(this.rateKey(key)));
6264
+ if (event)
6265
+ this.recheckEvent = event;
6266
+ return this.fetchKeys(keys, false);
6267
+ };
6268
+ const inflight = keys.map((key) => this.inflight.get(key)).filter(Boolean);
6269
+ return (inflight.length ? Promise.all(inflight).then(go) : go()).catch(() => undefined);
6270
+ }
5911
6271
  currentUrl() {
5912
6272
  return this.page ? this.page.current().url : currentPageUrl();
5913
6273
  }
@@ -5979,19 +6339,21 @@ var JoryioSDK = (function (exports) {
5979
6339
  this.batchKeys.clear();
5980
6340
  const waiters = this.batchWaiters;
5981
6341
  this.batchWaiters = [];
6342
+ const recheckEvent = this.recheckEvent;
6343
+ this.recheckEvent = null;
5982
6344
  const chunks = [];
5983
6345
  for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
5984
6346
  chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
5985
6347
  }
5986
6348
  try {
5987
- await Promise.all(chunks.map((chunk) => this.request(chunk)));
6349
+ await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));
5988
6350
  }
5989
6351
  finally {
5990
6352
  keys.forEach((key) => this.inflight.delete(key));
5991
6353
  waiters.forEach((w) => w.resolve());
5992
6354
  }
5993
6355
  }
5994
- async request(keys) {
6356
+ async request(keys, recheckEvent) {
5995
6357
  var _a, _b, _c, _d;
5996
6358
  const consent = this.runtime.consent();
5997
6359
  if (consent === null || this.destroyed)
@@ -6008,7 +6370,7 @@ var JoryioSDK = (function (exports) {
6008
6370
  }
6009
6371
  const userId = personal ? this.identity.getUserId() : null;
6010
6372
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
6011
- const body = Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: this.capabilities(), trackingConsent: consent, placements: keys, shown, context: this.page ? Object.assign(Object.assign({}, this.page.current()), { screen: null }) : pageContext() });
6373
+ const body = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (userId ? { userId } : {})), (anonymousId ? { anonymousId } : {})), (personal ? { sessionId: this.session.getSessionId() } : {})), { deviceType: 'web', locale: typeof navigator !== 'undefined' ? navigator.language : undefined, capabilities: this.capabilities(), trackingConsent: consent, placements: keys, shown, context: this.page ? Object.assign(Object.assign({}, this.page.current()), { screen: null }) : pageContext() }), (recheckEvent ? { recheckEvent } : {}));
6012
6374
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
6013
6375
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
6014
6376
  const url = `${this.apiEndpoint}/v1/in-app/placements`;
@@ -6066,7 +6428,9 @@ var JoryioSDK = (function (exports) {
6066
6428
  }
6067
6429
  normalize(key, wire) {
6068
6430
  const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];
6069
- return Object.assign({ placementKey: key, emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse', maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1, ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS, isControl: wire.isControl === true, controlToken: wire.controlToken || null, items }, (wire.pageScoped === true ? { pageScoped: true } : {}));
6431
+ return Object.assign(Object.assign(Object.assign(Object.assign({ placementKey: key, emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse', maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1, ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS, isControl: wire.isControl === true, controlToken: wire.controlToken || null, items }, (wire.pageScoped === true ? { pageScoped: true } : {})), (wire.isControl === true && wire.showWhen != null ? { showWhen: wire.showWhen } : {})), (Array.isArray(wire.deferredControls) && wire.deferredControls.length
6432
+ ? { deferredControls: wire.deferredControls.filter((d) => d && typeof d.controlToken === 'string' && d.controlToken) }
6433
+ : {})), (eventNames(wire.recheckOn).length ? { recheckOn: eventNames(wire.recheckOn) } : {}));
6070
6434
  }
6071
6435
  applyChanged(keys) {
6072
6436
  for (const mount of this.mounts) {
@@ -6077,6 +6441,9 @@ var JoryioSDK = (function (exports) {
6077
6441
  else
6078
6442
  this.render(mount);
6079
6443
  }
6444
+ this.notify(keys);
6445
+ }
6446
+ notify(keys) {
6080
6447
  if (!this.listeners.size)
6081
6448
  return;
6082
6449
  const update = {};
@@ -6105,6 +6472,8 @@ var JoryioSDK = (function (exports) {
6105
6472
  return false;
6106
6473
  if (this.dismissedLocally.has(this.handle(key, item)))
6107
6474
  return false;
6475
+ if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen))
6476
+ return false;
6108
6477
  const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
6109
6478
  if (eventTriggers.length) {
6110
6479
  const at = this.triggeredAt.get(this.handle(key, item));
@@ -6127,7 +6496,12 @@ var JoryioSDK = (function (exports) {
6127
6496
  emptyBehavior: wire.emptyBehavior || 'collapse',
6128
6497
  maxItems: wire.maxItems || 1,
6129
6498
  ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
6130
- markDisplayed: () => this.current(generation) && this.reportControl(key),
6499
+ markDisplayed: () => {
6500
+ if (!this.current(generation))
6501
+ return;
6502
+ this.reportControl(key);
6503
+ this.markSpotViewable(key);
6504
+ },
6131
6505
  };
6132
6506
  }
6133
6507
  current(generation) {
@@ -6157,6 +6531,8 @@ var JoryioSDK = (function (exports) {
6157
6531
  this.render(mount);
6158
6532
  }
6159
6533
  report(key, item, type, elementId) {
6534
+ if (type === 'displayed')
6535
+ this.markSpotViewable(key);
6160
6536
  if (this.runtime.consent() !== 'granted')
6161
6537
  return;
6162
6538
  const once = `${type}:${this.handle(key, item)}`;
@@ -6176,13 +6552,33 @@ var JoryioSDK = (function (exports) {
6176
6552
  const entry = this.cache.get(key);
6177
6553
  if (!(entry === null || entry === void 0 ? void 0 : entry.placement.isControl) || !entry.placement.controlToken)
6178
6554
  return;
6555
+ if (!this.due(`ctl:${key}:${entry.placement.controlToken}`, entry.placement.showWhen))
6556
+ return;
6557
+ this.postControl(key, entry.placement.controlToken);
6558
+ }
6559
+ markSpotViewable(key) {
6560
+ if (this.spotViewable.has(key))
6561
+ return;
6562
+ this.spotViewable.add(key);
6563
+ this.reportDeferred(key);
6564
+ }
6565
+ reportDeferred(key) {
6566
+ var _a;
6567
+ const list = (_a = this.cache.get(key)) === null || _a === void 0 ? void 0 : _a.placement.deferredControls;
6568
+ if (!(list === null || list === void 0 ? void 0 : list.length) || !this.spotViewable.has(key))
6569
+ return;
6570
+ for (const d of list)
6571
+ if (this.due(`ctl:${key}:${d.controlToken}`, d.showWhen))
6572
+ this.postControl(key, d.controlToken);
6573
+ }
6574
+ postControl(key, controlToken) {
6179
6575
  if (this.runtime.consent() !== 'granted')
6180
6576
  return;
6181
- const once = `control:${entry.placement.controlToken}`;
6577
+ const once = `control:${controlToken}`;
6182
6578
  if (this.reported.has(once))
6183
6579
  return;
6184
6580
  this.reported.add(once);
6185
- this.post('/v1/in-app/track', Object.assign(Object.assign({ action: 'control_viewed', controlToken: entry.placement.controlToken, placementKey: key }, this.subject()), { sessionId: this.session.getSessionId(), deviceType: 'web', viewedAt: new Date().toISOString() }));
6581
+ this.post('/v1/in-app/track', Object.assign(Object.assign({ action: 'control_viewed', controlToken, placementKey: key }, this.subject()), { sessionId: this.session.getSessionId(), deviceType: 'web', viewedAt: new Date().toISOString() }));
6186
6582
  }
6187
6583
  subject() {
6188
6584
  const userId = this.identity.getUserId();
@@ -6235,15 +6631,143 @@ var JoryioSDK = (function (exports) {
6235
6631
  }
6236
6632
  clearDrawn(mount) {
6237
6633
  var _a;
6634
+ if (mount.serverFill) {
6635
+ this.dropServerFill(mount.element, mount.serverFill.wrapper);
6636
+ mount.serverFill = null;
6637
+ }
6238
6638
  mount.frameIds.forEach((id) => this.frames.delete(id));
6239
6639
  mount.frameIds = [];
6240
6640
  (_a = mount.wrapper) === null || _a === void 0 ? void 0 : _a.remove();
6241
6641
  mount.wrapper = null;
6242
6642
  mount.shown = [];
6243
6643
  }
6644
+ serverFillsOfMarker() {
6645
+ if (this.markerFills)
6646
+ return this.markerFills;
6647
+ const out = new Map();
6648
+ try {
6649
+ const el = typeof document !== 'undefined' ? serverMarkerElement() : null;
6650
+ const data = el ? JSON.parse(el.textContent || 'null') : null;
6651
+ const list = data && data.v === 1 && Array.isArray(data[SERVER_FILLS_MARKER_KEY]) ? data[SERVER_FILLS_MARKER_KEY] : [];
6652
+ for (const f of list.slice(0, 20)) {
6653
+ if (!f || !validKey(f.placementKey) || typeof f.campaignId !== 'string' || !f.campaignId)
6654
+ continue;
6655
+ const products = Array.isArray(f.products) ? f.products.filter((p) => typeof p === 'string').slice(0, 24) : [];
6656
+ out.set(f.placementKey, { campaignId: f.campaignId, variantId: typeof f.variantId === 'string' ? f.variantId : '', products });
6657
+ }
6658
+ }
6659
+ catch (_a) {
6660
+ }
6661
+ this.markerFills = out;
6662
+ return out;
6663
+ }
6664
+ serverFillOf(key, element) {
6665
+ var _a;
6666
+ const token = (_a = element.getAttribute) === null || _a === void 0 ? void 0 : _a.call(element, SERVER_FILLED_ATTR);
6667
+ if (!token)
6668
+ return null;
6669
+ const wrapper = Array.from(element.children || []).find((c) => { var _a, _b; return ((_a = c.classList) === null || _a === void 0 ? void 0 : _a.contains('joryio-placement')) && ((_b = c.hasAttribute) === null || _b === void 0 ? void 0 : _b.call(c, SERVER_FILL_ATTR)); });
6670
+ const fill = this.serverFillsOfMarker().get(key);
6671
+ const ok = !!wrapper &&
6672
+ !!fill &&
6673
+ wrapper.getAttribute(SERVER_FILL_ATTR) === token &&
6674
+ token === `${key}:${fill.campaignId}:${fill.variantId}` &&
6675
+ (this.runtime.allowHtml() || !wrapper.querySelector('.joryio-placement-html'));
6676
+ if (!ok) {
6677
+ this.dropServerFill(element, wrapper !== null && wrapper !== void 0 ? wrapper : null);
6678
+ return null;
6679
+ }
6680
+ attachServerShadowRoots(wrapper);
6681
+ return Object.assign(Object.assign({}, fill), { wrapper: wrapper });
6682
+ }
6683
+ dropServerFill(element, wrapper) {
6684
+ var _a, _b;
6685
+ wrapper === null || wrapper === void 0 ? void 0 : wrapper.remove();
6686
+ (_a = element.removeAttribute) === null || _a === void 0 ? void 0 : _a.call(element, SERVER_FILLED_ATTR);
6687
+ (_b = element.removeAttribute) === null || _b === void 0 ? void 0 : _b.call(element, 'data-joryio-placement-state');
6688
+ }
6689
+ settleServerFill(mount) {
6690
+ var _a, _b;
6691
+ const sf = mount.serverFill;
6692
+ if (!sf)
6693
+ return 'dropped';
6694
+ const entry = this.cache.get(mount.key);
6695
+ if (!entry)
6696
+ return 'waiting';
6697
+ mount.serverFill = null;
6698
+ const items = this.visibleItems(mount.key);
6699
+ const item = items[0];
6700
+ const products = toProducts(item === null || item === void 0 ? void 0 : item.products).map((p) => p.id);
6701
+ const html = !!sf.wrapper.querySelector('.joryio-placement-html');
6702
+ const same = items.length === 1 &&
6703
+ entry.placement.isControl !== true &&
6704
+ item.id === sf.campaignId &&
6705
+ ((_a = item.variantId) !== null && _a !== void 0 ? _a : '') === sf.variantId &&
6706
+ products.length === sf.products.length &&
6707
+ products.every((id, i) => id === sf.products[i]) &&
6708
+ (((_b = item.content) === null || _b === void 0 ? void 0 : _b.kind) === 'html') === html &&
6709
+ (!html || this.runtime.allowHtml()) &&
6710
+ (mount.options.showProducts !== false || !products.length);
6711
+ if (!same) {
6712
+ this.dropServerFill(mount.element, sf.wrapper);
6713
+ return 'dropped';
6714
+ }
6715
+ mount.pendingUpdate = false;
6716
+ this.clearTrackers(mount);
6717
+ mount.wrapper = sf.wrapper;
6718
+ mount.shown = [item.deliveryId || item.id];
6719
+ mount.element.setAttribute('data-joryio-placement-state', 'filled');
6720
+ const node = sf.wrapper.firstElementChild || sf.wrapper;
6721
+ this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));
6722
+ this.bindServerFill(mount, sf.wrapper, item);
6723
+ if (mount.options.onRender) {
6724
+ try {
6725
+ mount.options.onRender(this.toPlacement(mount.key), mount.element);
6726
+ }
6727
+ catch (error) {
6728
+ this.logger.error('The insertPlacement onRender callback threw; ignored:', error);
6729
+ }
6730
+ }
6731
+ return 'kept';
6732
+ }
6733
+ bindServerFill(mount, wrapper, item) {
6734
+ wrapper.addEventListener('click', (event) => {
6735
+ var _a, _b;
6736
+ if (!this.mounts.has(mount) || mount.wrapper !== wrapper)
6737
+ return;
6738
+ const path = (typeof event.composedPath === 'function' ? event.composedPath() : [event.target]);
6739
+ for (const el of path) {
6740
+ if (!el || el === wrapper || typeof el.getAttribute !== 'function')
6741
+ break;
6742
+ const productId = el.getAttribute('data-joryio-product');
6743
+ if (productId) {
6744
+ const href = el.getAttribute('href');
6745
+ if (href)
6746
+ (_a = event.preventDefault) === null || _a === void 0 ? void 0 : _a.call(event);
6747
+ this.buttonAction(mount, item, { id: placementProductElementId(productId), action: 'deep_link', url: href || undefined });
6748
+ return;
6749
+ }
6750
+ const tag = (el.tagName || '').toUpperCase();
6751
+ if (tag === 'A' || tag === 'BUTTON') {
6752
+ const href = tag === 'A' ? el.getAttribute('href') : null;
6753
+ if (hasUserGesture())
6754
+ this.report(mount.key, item, 'clicked', el.getAttribute('data-action') || (href ? 'link_click' : 'cta_click'));
6755
+ if (href && !/^(#|mailto:|tel:|sms:)/i.test(href.trim())) {
6756
+ (_b = event.preventDefault) === null || _b === void 0 ? void 0 : _b.call(event);
6757
+ const safe = safeHttpUrl(href.trim());
6758
+ if (safe && hasUserGesture())
6759
+ this.openLink(safe, { placementKey: mount.key, itemId: item.id }, () => window.open(safe, '_blank', 'noopener'));
6760
+ }
6761
+ return;
6762
+ }
6763
+ }
6764
+ }, true);
6765
+ }
6244
6766
  render(mount) {
6245
6767
  if (!this.mounts.has(mount))
6246
6768
  return;
6769
+ if (mount.serverFill && this.settleServerFill(mount) !== 'dropped')
6770
+ return;
6247
6771
  mount.pendingUpdate = false;
6248
6772
  this.clearTrackers(mount);
6249
6773
  this.clearDrawn(mount);
@@ -6269,7 +6793,10 @@ var JoryioSDK = (function (exports) {
6269
6793
  if (!drawn.length) {
6270
6794
  wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
6271
6795
  if (placement.isControl && (entry === null || entry === void 0 ? void 0 : entry.placement.controlToken)) {
6272
- this.trackViewability(mount, mount.element, () => this.reportControl(mount.key));
6796
+ this.trackViewability(mount, mount.element, () => {
6797
+ this.reportControl(mount.key);
6798
+ this.markSpotViewable(mount.key);
6799
+ });
6273
6800
  }
6274
6801
  }
6275
6802
  if (mount.options.onRender) {
@@ -6611,6 +7138,22 @@ var JoryioSDK = (function (exports) {
6611
7138
  }
6612
7139
  }
6613
7140
  }
7141
+ function attachServerShadowRoots(wrapper) {
7142
+ var _a;
7143
+ for (const host of Array.from(((_a = wrapper.querySelectorAll) === null || _a === void 0 ? void 0 : _a.call(wrapper, '.joryio-placement-html')) || [])) {
7144
+ if (host.shadowRoot || typeof host.attachShadow !== 'function')
7145
+ continue;
7146
+ const tpl = Array.from(host.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute('shadowrootmode') === 'open');
7147
+ if (!tpl)
7148
+ continue;
7149
+ try {
7150
+ host.attachShadow({ mode: 'open' }).appendChild(tpl.content);
7151
+ tpl.remove();
7152
+ }
7153
+ catch (_b) {
7154
+ }
7155
+ }
7156
+ }
6614
7157
  function toProducts(raw) {
6615
7158
  if (!Array.isArray(raw))
6616
7159
  return [];
@@ -9300,6 +9843,7 @@ var JoryioSDK = (function (exports) {
9300
9843
  this.attributeGeneration = 0;
9301
9844
  this.attributeFailures = 0;
9302
9845
  this.links = new LinkRouter((error) => { var _a; return (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error('Your link handler threw; the link opens as without one:', error); });
9846
+ this.pendingRechecks = [];
9303
9847
  this.editor = null;
9304
9848
  this._ecommerce = null;
9305
9849
  this.isInitialized = false;
@@ -9338,6 +9882,9 @@ var JoryioSDK = (function (exports) {
9338
9882
  console.error(`[Joryio] SDK not started: ${keyProblem}. Calls on this instance are ignored.`);
9339
9883
  this.disabled = true;
9340
9884
  }
9885
+ else if (editorFrame()) {
9886
+ this.disabled = true;
9887
+ }
9341
9888
  this.config = resolveConfig(keyProblem
9342
9889
  ? Object.assign(Object.assign({}, (config && typeof config === 'object' ? config : {})), { sdkKey: 'jry_sdk_invalid', optOut: false }) : config);
9343
9890
  this.logger = new Logger(this.config.loggingEnabled, this.config.logLevel);
@@ -9438,6 +9985,11 @@ var JoryioSDK = (function (exports) {
9438
9985
  this.pageContext = new PageContextTracker(this.config.pageContext);
9439
9986
  this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
9440
9987
  this.inapp.setPageContext(this.pageContext);
9988
+ this.showWhen = new ShowWhenMoments(this.pageContext, () => this.session.getSessionId(), this.config.sdkKey);
9989
+ this.pageContext.onSignal((s) => {
9990
+ if (s.type === 'page_change')
9991
+ this.pendingRechecks = [];
9992
+ });
9441
9993
  this.placements = new PlacementManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9442
9994
  consent: () => this.placementConsent(),
9443
9995
  allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
@@ -9453,12 +10005,14 @@ var JoryioSDK = (function (exports) {
9453
10005
  },
9454
10006
  }, this.network);
9455
10007
  this.placements.setPageContext(this.pageContext);
10008
+ this.placements.setShowWhen(this.showWhen);
9456
10009
  this.pageEdits = new PageEditManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9457
10010
  consent: () => this.placementConsent(),
9458
10011
  requestTimeoutMs: this.config.requestTimeout,
9459
10012
  noteStatus: (status, data) => this.network.noteSuspended(status, data),
9460
10013
  }, this.network);
9461
10014
  this.pageEdits.setPageContext(this.pageContext);
10015
+ this.pageEdits.setShowWhen(this.showWhen);
9462
10016
  this.cards = new CardManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9463
10017
  consent: () => this.placementConsent(),
9464
10018
  requestTimeoutMs: this.config.requestTimeout,
@@ -9498,6 +10052,8 @@ var JoryioSDK = (function (exports) {
9498
10052
  return await this.flushEvents(events, identify);
9499
10053
  }
9500
10054
  finally {
10055
+ if (this.pendingRechecks.length)
10056
+ setTimeout(() => this.runRechecks(), 0);
9501
10057
  this.scheduleRetiredTokenPrune();
9502
10058
  }
9503
10059
  });
@@ -9794,6 +10350,7 @@ var JoryioSDK = (function (exports) {
9794
10350
  this.network.switchUser(userId);
9795
10351
  this.identity.adopt(anonymousId, userId);
9796
10352
  this.placements.invalidate();
10353
+ this.pendingRechecks = [];
9797
10354
  this.cards.invalidate(true);
9798
10355
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate();
9799
10356
  this.flags.onIdentityChanged();
@@ -10059,6 +10616,7 @@ var JoryioSDK = (function (exports) {
10059
10616
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
10060
10617
  this.inapp.invalidate();
10061
10618
  (_a = this.placements) === null || _a === void 0 ? void 0 : _a.invalidate();
10619
+ this.pendingRechecks = [];
10062
10620
  (_b = this.cards) === null || _b === void 0 ? void 0 : _b.invalidate(false);
10063
10621
  (_c = this.pageEdits) === null || _c === void 0 ? void 0 : _c.invalidate({ siteSettings: true });
10064
10622
  (_d = this.flags) === null || _d === void 0 ? void 0 : _d.onIdentityChanged();
@@ -10262,7 +10820,7 @@ var JoryioSDK = (function (exports) {
10262
10820
  this.track('Page Viewed', properties);
10263
10821
  }
10264
10822
  track(eventName, properties) {
10265
- var _a, _b;
10823
+ var _a, _b, _c;
10266
10824
  if (!this.isInitialized) {
10267
10825
  this.logger.error('SDK not initialized');
10268
10826
  return;
@@ -10328,6 +10886,8 @@ var JoryioSDK = (function (exports) {
10328
10886
  try {
10329
10887
  (_a = this.inapp) === null || _a === void 0 ? void 0 : _a.onEventTracked(eventName, eventProperties);
10330
10888
  (_b = this.placements) === null || _b === void 0 ? void 0 : _b.onEventTracked(eventName, eventProperties);
10889
+ (_c = this.showWhen) === null || _c === void 0 ? void 0 : _c.noteEvent(eventName);
10890
+ this.recheckShowWhen(eventName, processedEvent);
10331
10891
  }
10332
10892
  catch (error) {
10333
10893
  this.logger.error('In-app trigger evaluation failed:', error);
@@ -10351,6 +10911,45 @@ var JoryioSDK = (function (exports) {
10351
10911
  this.logger.error('track() failed:', error);
10352
10912
  }
10353
10913
  }
10914
+ recheckShowWhen(eventName, queued) {
10915
+ var _a, _b;
10916
+ const keys = ((_a = this.placements) === null || _a === void 0 ? void 0 : _a.recheckKeysFor(eventName)) || [];
10917
+ const edits = !!((_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.claimRecheck(eventName));
10918
+ if (!keys.length && !edits)
10919
+ return;
10920
+ const event = { name: eventName, eventId: queued.eventId, properties: Object.assign({}, (queued.properties || {})) };
10921
+ this.pendingRechecks.push({ event, keys, edits, who: this.recheckOwner(), at: Date.now() });
10922
+ if (this.pendingRechecks.length > 20)
10923
+ this.pendingRechecks.shift();
10924
+ void this.queue
10925
+ .flush(false, true)
10926
+ .catch(() => undefined)
10927
+ .then(() => this.runRechecks());
10928
+ }
10929
+ recheckOwner() {
10930
+ var _a;
10931
+ return [this.identity.getUserId() || '', this.identity.getAnonymousId(), this.placementConsent() || '', ((_a = this.pageContext) === null || _a === void 0 ? void 0 : _a.current().url) || ''].join('\u0000');
10932
+ }
10933
+ runRechecks() {
10934
+ if (!this.pendingRechecks.length || !this.isInitialized)
10935
+ return;
10936
+ const owner = this.recheckOwner();
10937
+ const now = Date.now();
10938
+ this.pendingRechecks = this.pendingRechecks.filter((r) => r.who === owner && now - r.at <= 60000);
10939
+ const waiting = new Set([...this.queue.getQueuedEvents(), ...this.queue.getInflightEvents()].map((e) => e.eventId));
10940
+ const due = this.pendingRechecks.filter((r) => !waiting.has(r.event.eventId));
10941
+ if (!due.length)
10942
+ return;
10943
+ this.pendingRechecks = this.pendingRechecks.filter((r) => waiting.has(r.event.eventId));
10944
+ if (!this.canSend())
10945
+ return;
10946
+ for (const r of due) {
10947
+ if (r.keys.length)
10948
+ void this.placements.recheck(r.keys, r.event);
10949
+ if (r.edits)
10950
+ this.pageEdits.recheck(r.event);
10951
+ }
10952
+ }
10354
10953
  identify(userId) {
10355
10954
  var _a;
10356
10955
  if (!this.isInitialized) {
@@ -10386,6 +10985,7 @@ var JoryioSDK = (function (exports) {
10386
10985
  if (previousUserId !== userId) {
10387
10986
  this.inapp.invalidate();
10388
10987
  this.placements.invalidate();
10988
+ this.pendingRechecks = [];
10389
10989
  this.cards.invalidate(true);
10390
10990
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate();
10391
10991
  this.flags.onIdentityChanged();
@@ -10722,6 +11322,7 @@ var JoryioSDK = (function (exports) {
10722
11322
  this.flags.onIdentityChanged();
10723
11323
  this.network.setCurrentUserId(this.identity.getUserId());
10724
11324
  this.placements.invalidate();
11325
+ this.pendingRechecks = [];
10725
11326
  this.cards.invalidate(true);
10726
11327
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate({ siteSettings: true });
10727
11328
  this.utm.reset();
@@ -10788,6 +11389,7 @@ var JoryioSDK = (function (exports) {
10788
11389
  this.flags.onIdentityChanged();
10789
11390
  this.network.setCurrentUserId(null);
10790
11391
  this.placements.invalidate();
11392
+ this.pendingRechecks = [];
10791
11393
  (_a = this.cards) === null || _a === void 0 ? void 0 : _a.invalidate(true);
10792
11394
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate({ siteSettings: true });
10793
11395
  this.utm.reset();
@@ -11384,7 +11986,7 @@ var JoryioSDK = (function (exports) {
11384
11986
  return this.flags.onFlagsUpdated(callback);
11385
11987
  }
11386
11988
  async destroy() {
11387
- var _a, _b, _c;
11989
+ var _a, _b, _c, _d;
11388
11990
  if (!this.isInitialized) {
11389
11991
  return;
11390
11992
  }
@@ -11426,7 +12028,9 @@ var JoryioSDK = (function (exports) {
11426
12028
  this.cards.destroy();
11427
12029
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.destroy();
11428
12030
  (_b = this.editor) === null || _b === void 0 ? void 0 : _b.stop();
11429
- (_c = this.pageContext) === null || _c === void 0 ? void 0 : _c.destroy();
12031
+ (_c = this.showWhen) === null || _c === void 0 ? void 0 : _c.destroy();
12032
+ this.pendingRechecks = [];
12033
+ (_d = this.pageContext) === null || _d === void 0 ? void 0 : _d.destroy();
11430
12034
  this.flags.destroy();
11431
12035
  this.isInitialized = false;
11432
12036
  if (JoryioSDK.instance === this)
@@ -11626,6 +12230,7 @@ var JoryioSDK = (function (exports) {
11626
12230
  exports.PLACEMENT_VIEWABLE_FRACTION = PLACEMENT_VIEWABLE_FRACTION;
11627
12231
  exports.PushManager = PushManager;
11628
12232
  exports.SDK_VERSION = SDK_VERSION;
12233
+ exports.SHOW_WHEN_KINDS = SHOW_WHEN_KINDS;
11629
12234
  exports.User = User;
11630
12235
  exports.createEcommerceTracker = createEcommerceTracker;
11631
12236
  exports.default = JoryioSDK;