@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
package/dist/joryio.mjs CHANGED
@@ -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
  */
@@ -25,7 +25,7 @@ function bucketHash(input) {
25
25
  return fmix32(hash >>> 0);
26
26
  }
27
27
 
28
- const SDK_VERSION = '1.4.0-beta.7';
28
+ const SDK_VERSION = '1.4.0-beta.9';
29
29
  const SDK_PLATFORM_HEADER = 'X-Joryio-SDK';
30
30
  const SDK_VERSION_HEADER = 'X-Joryio-SDK-Version';
31
31
  const SDK_PLATFORM = 'web';
@@ -309,6 +309,15 @@ function readPath(root, path) {
309
309
  }
310
310
  return cur;
311
311
  }
312
+ const TOUCH_EXIT_INTENT = {
313
+ armPercent: 25,
314
+ armPx: 400,
315
+ upPx: 120,
316
+ windowMs: 300,
317
+ minMs: 3000,
318
+ sampleMs: 50,
319
+ };
320
+ const TOUCH_PRIMARY_QUERY = '(hover: none) and (pointer: coarse)';
312
321
  class PageContextTracker {
313
322
  constructor(options = {}) {
314
323
  this.options = options;
@@ -319,6 +328,10 @@ class PageContextTracker {
319
328
  this.visibleMs = 0;
320
329
  this.visibleSince = null;
321
330
  this.exitFired = false;
331
+ this.pageStartedAt = Date.now();
332
+ this.maxScrollY = 0;
333
+ this.scrollSamples = [];
334
+ this.touchQuery = null;
322
335
  this.timer = null;
323
336
  this.undo = [];
324
337
  this.started = false;
@@ -427,7 +440,17 @@ class PageContextTracker {
427
440
  this.undo.push(() => target.removeEventListener(ev, fn, opts));
428
441
  };
429
442
  on(window, 'popstate', () => this.checkRoute());
430
- on(window, 'scroll', () => this.measureScroll(), { passive: true });
443
+ this.pageStartedAt = Date.now();
444
+ try {
445
+ this.touchQuery = typeof window.matchMedia === 'function' ? window.matchMedia(TOUCH_PRIMARY_QUERY) : null;
446
+ }
447
+ catch (_a) {
448
+ this.touchQuery = null;
449
+ }
450
+ on(window, 'scroll', () => {
451
+ this.measureScroll();
452
+ this.touchExitIntent();
453
+ }, { passive: true });
431
454
  on(document, 'mouseout', (e) => {
432
455
  if (this.exitFired || e.relatedTarget || e.toElement)
433
456
  return;
@@ -458,6 +481,8 @@ class PageContextTracker {
458
481
  }
459
482
  }
460
483
  this.listeners.clear();
484
+ this.scrollSamples = [];
485
+ this.touchQuery = null;
461
486
  this.started = false;
462
487
  }
463
488
  checkRoute() {
@@ -469,6 +494,9 @@ class PageContextTracker {
469
494
  this.visibleMs = 0;
470
495
  this.visibleSince = typeof document !== 'undefined' && document.visibilityState === 'hidden' ? null : Date.now();
471
496
  this.exitFired = false;
497
+ this.pageStartedAt = Date.now();
498
+ this.maxScrollY = 0;
499
+ this.scrollSamples = [];
472
500
  this.emit({ type: 'page_change', url });
473
501
  }
474
502
  patchHistory() {
@@ -510,6 +538,38 @@ class PageContextTracker {
510
538
  catch (_b) {
511
539
  }
512
540
  }
541
+ touchExitIntent() {
542
+ var _a;
543
+ if (this.exitFired || !((_a = this.touchQuery) === null || _a === void 0 ? void 0 : _a.matches))
544
+ return;
545
+ try {
546
+ const c = TOUCH_EXIT_INTENT;
547
+ const now = Date.now();
548
+ const last = this.scrollSamples[this.scrollSamples.length - 1];
549
+ if (last && now - last.t < c.sampleMs)
550
+ return;
551
+ const y = Math.max(0, window.scrollY || document.documentElement.scrollTop || 0);
552
+ if (y > this.maxScrollY)
553
+ this.maxScrollY = y;
554
+ this.scrollSamples = this.scrollSamples.filter((s) => now - s.t <= c.windowMs);
555
+ this.scrollSamples.push({ y, t: now });
556
+ if (now - this.pageStartedAt < c.minMs)
557
+ return;
558
+ if (this.maxScrollY < c.armPx && this.maxScrollPercent < c.armPercent)
559
+ return;
560
+ let peak = y;
561
+ for (const s of this.scrollSamples)
562
+ if (s.y > peak)
563
+ peak = s.y;
564
+ if (peak - y >= c.upPx) {
565
+ this.exitFired = true;
566
+ this.scrollSamples = [];
567
+ this.emit({ type: 'exit_intent' });
568
+ }
569
+ }
570
+ catch (_b) {
571
+ }
572
+ }
513
573
  visibilityChanged() {
514
574
  if (document.visibilityState === 'hidden') {
515
575
  if (this.visibleSince !== null)
@@ -546,8 +606,119 @@ function pageTriggerMet(trigger, signal, progress) {
546
606
  }
547
607
  }
548
608
 
609
+ const SHOW_WHEN_KINDS = ['load', 'seconds', 'scroll', 'exit', 'event'];
610
+ const intIn = (v, min, max) => typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max;
611
+ function parseShowWhen(raw) {
612
+ if (raw === undefined || raw === null)
613
+ return { kind: 'load' };
614
+ if (typeof raw !== 'object')
615
+ return null;
616
+ const o = raw;
617
+ switch (o.kind) {
618
+ case 'load':
619
+ case 'exit':
620
+ return { kind: o.kind };
621
+ case 'seconds':
622
+ return intIn(o.seconds, 1, 3600) ? { kind: 'seconds', seconds: o.seconds } : null;
623
+ case 'scroll':
624
+ return intIn(o.percent, 1, 100) ? { kind: 'scroll', percent: o.percent } : null;
625
+ case 'event': {
626
+ const e = typeof o.event === 'string' ? o.event.trim() : '';
627
+ return e && e.length <= 255 ? { kind: 'event', event: e } : null;
628
+ }
629
+ default:
630
+ return null;
631
+ }
632
+ }
633
+ const isDeferred = (raw) => { var _a; return ((_a = parseShowWhen(raw)) === null || _a === void 0 ? void 0 : _a.kind) !== 'load'; };
634
+ function eventNames(raw, max = 50) {
635
+ return Array.isArray(raw) ? raw.filter((e) => typeof e === 'string' && e.length > 0 && e.length <= 255).slice(0, max) : [];
636
+ }
637
+ const MAX_EVENTS = 200;
638
+ class ShowWhenMoments {
639
+ constructor(page, sessionId, sdkKey) {
640
+ this.page = page;
641
+ this.sessionId = sessionId;
642
+ this.events = new Set();
643
+ this.sid = undefined;
644
+ this.listeners = new Set();
645
+ this.store = `jry_show_when_${bucketHash(sdkKey).toString(36)}`;
646
+ this.off = page ? page.onSignal(() => this.emit()) : null;
647
+ }
648
+ met(sw) {
649
+ var _a;
650
+ if (!sw)
651
+ return false;
652
+ if (sw.kind === 'load')
653
+ return true;
654
+ if (sw.kind === 'event')
655
+ return this.visitEvents().has(sw.event);
656
+ const p = (_a = this.page) === null || _a === void 0 ? void 0 : _a.progress();
657
+ if (!p)
658
+ return false;
659
+ return sw.kind === 'seconds' ? p.seconds >= sw.seconds : sw.kind === 'scroll' ? p.scrollPercent >= sw.percent : p.exitIntent;
660
+ }
661
+ noteEvent(name) {
662
+ const events = this.visitEvents();
663
+ if (!events.has(name) && events.size < MAX_EVENTS) {
664
+ events.add(name);
665
+ try {
666
+ sessionStorage.setItem(this.store, JSON.stringify({ sid: this.sid, names: Array.from(events) }));
667
+ }
668
+ catch (_a) {
669
+ }
670
+ }
671
+ this.emit();
672
+ }
673
+ onChange(cb) {
674
+ this.listeners.add(cb);
675
+ return () => this.listeners.delete(cb);
676
+ }
677
+ destroy() {
678
+ var _a;
679
+ (_a = this.off) === null || _a === void 0 ? void 0 : _a.call(this);
680
+ this.listeners.clear();
681
+ }
682
+ visitEvents() {
683
+ const sid = this.sessionId();
684
+ if (sid !== this.sid) {
685
+ this.sid = sid;
686
+ this.events = new Set();
687
+ try {
688
+ const raw = JSON.parse(sessionStorage.getItem(this.store) || 'null');
689
+ if (raw && sid && raw.sid === sid)
690
+ this.events = new Set(eventNames(raw.names, MAX_EVENTS));
691
+ }
692
+ catch (_a) {
693
+ }
694
+ }
695
+ return this.events;
696
+ }
697
+ emit() {
698
+ for (const cb of Array.from(this.listeners)) {
699
+ try {
700
+ cb();
701
+ }
702
+ catch (_a) {
703
+ }
704
+ }
705
+ }
706
+ }
707
+
549
708
  const PAGE_EDIT_POSITIONS = ['before', 'after', 'prepend', 'append', 'replace'];
550
709
  const PAGE_EDITS_CAPABILITY = 'page_edits';
710
+ const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'];
711
+ const PAGE_EDIT_MOBILE_BREAKPOINT = 768;
712
+ const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';
713
+ function isMobileViewport(win = window) {
714
+ try {
715
+ return typeof win.matchMedia === 'function' ? win.matchMedia(PAGE_EDIT_MOBILE_QUERY).matches : win.innerWidth < PAGE_EDIT_MOBILE_BREAKPOINT;
716
+ }
717
+ catch (_a) {
718
+ return false;
719
+ }
720
+ }
721
+ const editShowsOn = (e, mobile) => !e.device || e.device === 'all' || (e.device === 'mobile') === mobile;
551
722
  const PAGE_EDIT_ANTI_FLICKER_MS = 300;
552
723
  const MAX_SELECTOR_LENGTH = 500;
553
724
  const MAX_TEXT_LENGTH = 2000;
@@ -570,13 +741,14 @@ const SERVER_ORIG_ATTR = 'data-joryio-orig';
570
741
  const SERVER_SPOT_ATTR = 'data-joryio-server-spot';
571
742
  const SERVER_MARKER_VERSION = 1;
572
743
  const sameEdit = (a, b) => {
573
- var _a, _b, _c, _d, _e, _f;
744
+ var _a, _b, _c, _d, _e, _f, _g, _h;
574
745
  return a.id === b.id &&
575
746
  a.selector === b.selector &&
576
747
  a.operation === b.operation &&
577
748
  ((_a = a.value) !== null && _a !== void 0 ? _a : null) === ((_b = b.value) !== null && _b !== void 0 ? _b : null) &&
578
749
  ((_c = a.placementKey) !== null && _c !== void 0 ? _c : null) === ((_d = b.placementKey) !== null && _d !== void 0 ? _d : null) &&
579
750
  ((_e = a.position) !== null && _e !== void 0 ? _e : null) === ((_f = b.position) !== null && _f !== void 0 ? _f : null) &&
751
+ ((_g = a.device) !== null && _g !== void 0 ? _g : null) === ((_h = b.device) !== null && _h !== void 0 ? _h : null) &&
580
752
  !b.personalized;
581
753
  };
582
754
  function serverMarkerElement() {
@@ -703,7 +875,10 @@ function isSafeEditUrl(url) {
703
875
  function trustedEdit(e) {
704
876
  if (!e || typeof e !== 'object' || typeof e.id !== 'string' || !isSafeSelector(e.selector))
705
877
  return null;
706
- const base = Object.assign({ id: e.id, selector: e.selector.trim() }, (e.personalized === true ? { personalized: true } : {}));
878
+ const device = e.device;
879
+ if (device != null && !PAGE_EDIT_DEVICES.includes(device))
880
+ return null;
881
+ const base = Object.assign(Object.assign({ id: e.id, selector: e.selector.trim() }, (device === 'mobile' || device === 'desktop' ? { device: device } : {})), (e.personalized === true ? { personalized: true } : {}));
707
882
  switch (e.operation) {
708
883
  case 'hide':
709
884
  return Object.assign(Object.assign({}, base), { operation: 'hide' });
@@ -742,8 +917,15 @@ class PageEditManager {
742
917
  this.server = null;
743
918
  this.serverUrl = null;
744
919
  this.generation = 0;
920
+ this.mobile = false;
921
+ this.offMedia = null;
745
922
  this.started = false;
746
923
  this.destroyed = false;
924
+ this.moments = null;
925
+ this.momentsUnsubscribe = null;
926
+ this.revealed = new Set();
927
+ this.recheckOn = [];
928
+ this.rechecked = new Set();
747
929
  this.stores = pageEditsStorageKeys(sdkKey);
748
930
  try {
749
931
  localStorage.removeItem(LEGACY_SELECTOR_STORE);
@@ -764,7 +946,45 @@ class PageEditManager {
764
946
  });
765
947
  }
766
948
  }
949
+ setShowWhen(moments) {
950
+ var _a;
951
+ (_a = this.momentsUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
952
+ this.moments = moments;
953
+ this.momentsUnsubscribe = moments ? moments.onChange(() => this.sweep()) : null;
954
+ }
955
+ due(x) {
956
+ const sw = parseShowWhen(x.showWhen);
957
+ return !!sw && (sw.kind === 'load' || this.revealed.has(x.id) || (!!this.moments && this.moments.met(sw)));
958
+ }
959
+ sweep() {
960
+ if (!this.started || this.destroyed)
961
+ return;
962
+ let any = false;
963
+ for (const x of this.experiences) {
964
+ if (this.revealed.has(x.wire.id) || !isDeferred(x.wire.showWhen) || !this.due(x.wire))
965
+ continue;
966
+ this.revealed.add(x.wire.id);
967
+ any = true;
968
+ }
969
+ if (any)
970
+ this.applyAll();
971
+ }
972
+ claimRecheck(eventName) {
973
+ if (!this.moments || !this.started || this.destroyed || this.rechecked.has(eventName))
974
+ return false;
975
+ const waits = this.recheckOn.includes(eventName) ||
976
+ this.experiences.some((x) => { var _a; return ((_a = parseShowWhen(x.wire.showWhen)) === null || _a === void 0 ? void 0 : _a.event) === eventName; });
977
+ if (waits)
978
+ this.rechecked.add(eventName);
979
+ return waits;
980
+ }
981
+ recheck(event) {
982
+ const url = this.url();
983
+ if (url && this.started && !this.destroyed)
984
+ void this.fetch(url, this.generation, event);
985
+ }
767
986
  start() {
987
+ var _a;
768
988
  if (this.started || this.destroyed || typeof document === 'undefined')
769
989
  return;
770
990
  this.started = true;
@@ -772,8 +992,28 @@ class PageEditManager {
772
992
  this.observer = new MutationObserver(() => this.schedule());
773
993
  this.observer.observe(document.documentElement, { childList: true, subtree: true });
774
994
  }
995
+ this.mobile = isMobileViewport();
996
+ const mq = typeof window.matchMedia === 'function' ? window.matchMedia(PAGE_EDIT_MOBILE_QUERY) : null;
997
+ if (mq) {
998
+ const onChange = () => this.viewportChanged();
999
+ if (mq.addEventListener)
1000
+ mq.addEventListener('change', onChange);
1001
+ else
1002
+ (_a = mq.addListener) === null || _a === void 0 ? void 0 : _a.call(mq, onChange);
1003
+ this.offMedia = () => { var _a; return (mq.removeEventListener ? mq.removeEventListener('change', onChange) : (_a = mq.removeListener) === null || _a === void 0 ? void 0 : _a.call(mq, onChange)); };
1004
+ }
775
1005
  this.loadPage();
776
1006
  }
1007
+ viewportChanged() {
1008
+ const mobile = isMobileViewport();
1009
+ if (this.destroyed || mobile === this.mobile)
1010
+ return;
1011
+ this.mobile = mobile;
1012
+ if (!this.experiences.some((x) => x.edits.some((e) => e.device)))
1013
+ return;
1014
+ this.revertAll();
1015
+ this.applyAll();
1016
+ }
777
1017
  invalidate(opts = {}) {
778
1018
  this.generation++;
779
1019
  this.reported.clear();
@@ -788,10 +1028,13 @@ class PageEditManager {
788
1028
  this.loadPage();
789
1029
  }
790
1030
  destroy() {
791
- var _a, _b;
1031
+ var _a, _b, _c, _d;
792
1032
  this.destroyed = true;
793
1033
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
794
- (_b = this.observer) === null || _b === void 0 ? void 0 : _b.disconnect();
1034
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
1035
+ (_c = this.offMedia) === null || _c === void 0 ? void 0 : _c.call(this);
1036
+ this.offMedia = null;
1037
+ (_d = this.observer) === null || _d === void 0 ? void 0 : _d.disconnect();
795
1038
  this.observer = null;
796
1039
  this.revertAll();
797
1040
  this.showAll();
@@ -808,6 +1051,9 @@ class PageEditManager {
808
1051
  loadPage() {
809
1052
  const generation = ++this.generation;
810
1053
  this.revertAll();
1054
+ this.revealed.clear();
1055
+ this.rechecked.clear();
1056
+ this.recheckOn = [];
811
1057
  const url = this.url();
812
1058
  if (!url) {
813
1059
  this.experiences = [];
@@ -943,7 +1189,7 @@ class PageEditManager {
943
1189
  this.siteRequest = request;
944
1190
  return request;
945
1191
  }
946
- async fetch(url, generation) {
1192
+ async fetch(url, generation, recheckEvent) {
947
1193
  var _a, _b, _c, _d;
948
1194
  const consent = this.runtime.consent();
949
1195
  if (consent === null || this.destroyed) {
@@ -953,7 +1199,7 @@ class PageEditManager {
953
1199
  const personal = consent === 'granted';
954
1200
  const userId = personal ? this.identity.getUserId() : null;
955
1201
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
956
- 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: {} } });
1202
+ 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 } : {}));
957
1203
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
958
1204
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
959
1205
  try {
@@ -972,6 +1218,7 @@ class PageEditManager {
972
1218
  .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e) => !!e) }));
973
1219
  this.revertAll();
974
1220
  this.experiences = experiences;
1221
+ this.recheckOn = eventNames(data.recheckOn);
975
1222
  this.reconcileServer(experiences);
976
1223
  this.remember(url, experiences, data.ttlSeconds);
977
1224
  this.applyAll();
@@ -1005,6 +1252,8 @@ class PageEditManager {
1005
1252
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1006
1253
  try {
1007
1254
  for (const x of this.experiences) {
1255
+ if (!this.due(x.wire))
1256
+ continue;
1008
1257
  if (x.wire.isControl) {
1009
1258
  const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
1010
1259
  if (seen)
@@ -1013,6 +1262,8 @@ class PageEditManager {
1013
1262
  }
1014
1263
  let landed = false;
1015
1264
  for (const edit of x.edits) {
1265
+ if (!editShowsOn(edit, this.mobile))
1266
+ continue;
1016
1267
  const token = `${x.wire.id}:${edit.id}`;
1017
1268
  const server = this.serverEdits().get(token);
1018
1269
  const byServer = !!server && server.variantId === ((_b = x.wire.variantId) !== null && _b !== void 0 ? _b : null) && sameEdit(server.edit, edit);
@@ -1160,7 +1411,7 @@ class PageEditManager {
1160
1411
  return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
1161
1412
  }
1162
1413
  remember(url, experiences, ttlSeconds) {
1163
- const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.map((e) => e.selector))))];
1414
+ 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))))];
1164
1415
  try {
1165
1416
  const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
1166
1417
  delete all[url];
@@ -1254,7 +1505,7 @@ class PageEditManager {
1254
1505
  return;
1255
1506
  const keep = new Set();
1256
1507
  for (const x of experiences) {
1257
- if (x.wire.isControl)
1508
+ if (x.wire.isControl || isDeferred(x.wire.showWhen))
1258
1509
  continue;
1259
1510
  for (const e of x.edits) {
1260
1511
  const token = `${x.wire.id}:${e.id}`;
@@ -1477,6 +1728,19 @@ function editorRequested() {
1477
1728
  return false;
1478
1729
  }
1479
1730
  }
1731
+ const EDITOR_FRAME_FLAG = 'frame';
1732
+ function editorFrame() {
1733
+ try {
1734
+ if (typeof window === 'undefined' || window.parent === window)
1735
+ return false;
1736
+ if (new URLSearchParams(window.location.search).get(EDITOR_QUERY_FLAG) !== EDITOR_FRAME_FLAG)
1737
+ return false;
1738
+ return !!window.parent[EDITOR_GLOBAL];
1739
+ }
1740
+ catch (_a) {
1741
+ return false;
1742
+ }
1743
+ }
1480
1744
  function loadScript(src) {
1481
1745
  return loadSdkScript(src, 'data-joryio-editor');
1482
1746
  }
@@ -5603,6 +5867,9 @@ const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
5603
5867
  function placementProductElementId(productId) {
5604
5868
  return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
5605
5869
  }
5870
+ const SERVER_FILLED_ATTR = 'data-joryio-server-filled';
5871
+ const SERVER_FILL_ATTR = 'data-joryio-server-fill';
5872
+ const SERVER_FILLS_MARKER_KEY = 'fills';
5606
5873
  const DEFAULT_TTL_SECONDS = 300;
5607
5874
  const LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';
5608
5875
  const placementsStorageKey = (sdkKey) => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;
@@ -5719,7 +5986,14 @@ class PlacementManager {
5719
5986
  this.destroyed = false;
5720
5987
  this.page = null;
5721
5988
  this.pageUnsubscribe = null;
5989
+ this.moments = null;
5990
+ this.momentsUnsubscribe = null;
5991
+ this.revealed = new Set();
5992
+ this.spotViewable = new Set();
5993
+ this.rechecked = new Set();
5994
+ this.recheckEvent = null;
5722
5995
  this.pageScopedKeys = new Set();
5996
+ this.markerFills = null;
5723
5997
  this.loadCache();
5724
5998
  this.installBridge();
5725
5999
  this.installPageVisibility();
@@ -5748,6 +6022,7 @@ class PlacementManager {
5748
6022
  hostObserver: null,
5749
6023
  trackers: [],
5750
6024
  frameIds: [],
6025
+ serverFill: this.serverFillOf(key, element),
5751
6026
  };
5752
6027
  this.mounts.add(mount);
5753
6028
  this.observeHost(mount);
@@ -5819,6 +6094,8 @@ class PlacementManager {
5819
6094
  this.triggeredAt.clear();
5820
6095
  this.dismissedLocally.clear();
5821
6096
  this.reported.clear();
6097
+ this.revealed.clear();
6098
+ this.spotViewable.clear();
5822
6099
  this.persistCache();
5823
6100
  const keys = this.mountedKeys();
5824
6101
  for (const mount of this.mounts)
@@ -5827,13 +6104,15 @@ class PlacementManager {
5827
6104
  this.fetchKeys(keys, true).catch(() => undefined);
5828
6105
  }
5829
6106
  destroy() {
5830
- var _a, _b, _c;
6107
+ var _a, _b, _c, _d;
5831
6108
  this.destroyed = true;
5832
6109
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
5833
6110
  this.pageUnsubscribe = null;
6111
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
6112
+ this.momentsUnsubscribe = null;
5834
6113
  for (const mount of Array.from(this.mounts))
5835
6114
  this.unmount(mount);
5836
- (_b = this.mutationObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
6115
+ (_c = this.mutationObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
5837
6116
  this.mutationObserver = null;
5838
6117
  if (this.batchTimer)
5839
6118
  clearTimeout(this.batchTimer);
@@ -5848,11 +6127,11 @@ class PlacementManager {
5848
6127
  document.removeEventListener('visibilitychange', this.pageListener);
5849
6128
  }
5850
6129
  try {
5851
- if (typeof window !== 'undefined' && ((_c = window[PLACEMENT_BRIDGE_GLOBAL]) === null || _c === void 0 ? void 0 : _c.__owner) === this) {
6130
+ if (typeof window !== 'undefined' && ((_d = window[PLACEMENT_BRIDGE_GLOBAL]) === null || _d === void 0 ? void 0 : _d.__owner) === this) {
5852
6131
  delete window[PLACEMENT_BRIDGE_GLOBAL];
5853
6132
  }
5854
6133
  }
5855
- catch (_d) {
6134
+ catch (_e) {
5856
6135
  }
5857
6136
  }
5858
6137
  cleanKeys(keys) {
@@ -5881,11 +6160,23 @@ class PlacementManager {
5881
6160
  this.pageUnsubscribe = tracker.onSignal((signal) => {
5882
6161
  if (signal.type !== 'page_change' || this.destroyed)
5883
6162
  return;
6163
+ const held = this.revealed.size ? this.keysWithMoments() : [];
6164
+ this.revealed.clear();
6165
+ this.spotViewable.clear();
6166
+ this.rechecked.clear();
5884
6167
  const stale = [];
5885
6168
  this.cache.forEach((entry, key) => {
5886
6169
  if (entry.placement.pageScoped && entry.url !== signal.url)
5887
6170
  stale.push(key);
5888
6171
  });
6172
+ const rehide = held.filter((key) => !stale.includes(key));
6173
+ if (rehide.length) {
6174
+ for (const mount of this.mounts)
6175
+ if (rehide.includes(mount.key))
6176
+ this.render(mount);
6177
+ this.notify(rehide);
6178
+ this.sweep();
6179
+ }
5889
6180
  if (!stale.length)
5890
6181
  return;
5891
6182
  stale.forEach((key) => this.cache.delete(key));
@@ -5905,6 +6196,75 @@ class PlacementManager {
5905
6196
  }
5906
6197
  });
5907
6198
  }
6199
+ setShowWhen(moments) {
6200
+ var _a;
6201
+ (_a = this.momentsUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
6202
+ this.moments = moments;
6203
+ this.momentsUnsubscribe = moments ? moments.onChange(() => !this.destroyed && this.sweep()) : null;
6204
+ }
6205
+ due(handle, raw) {
6206
+ const sw = parseShowWhen(raw);
6207
+ if (!sw)
6208
+ return false;
6209
+ return sw.kind === 'load' || this.revealed.has(handle) || (!!this.moments && this.moments.met(sw));
6210
+ }
6211
+ keysWithMoments() {
6212
+ const out = [];
6213
+ this.cache.forEach((entry, key) => {
6214
+ var _a;
6215
+ const p = entry.placement;
6216
+ if (p.showWhen !== undefined || ((_a = p.deferredControls) === null || _a === void 0 ? void 0 : _a.length) || (p.items || []).some((i) => i.showWhen !== undefined))
6217
+ out.push(key);
6218
+ });
6219
+ return out;
6220
+ }
6221
+ sweep() {
6222
+ const changed = [];
6223
+ this.cache.forEach((entry, key) => {
6224
+ const p = entry.placement;
6225
+ const handles = (p.items || []).filter((i) => isDeferred(i.showWhen)).map((i) => [this.handle(key, i), i.showWhen]);
6226
+ if (p.isControl && isDeferred(p.showWhen))
6227
+ handles.push([`ctl:${key}:${p.controlToken || ''}`, p.showWhen]);
6228
+ for (const [h, raw] of handles) {
6229
+ if (this.revealed.has(h) || !this.due(h, raw))
6230
+ continue;
6231
+ this.revealed.add(h);
6232
+ if (!changed.includes(key))
6233
+ changed.push(key);
6234
+ }
6235
+ this.reportDeferred(key);
6236
+ });
6237
+ if (changed.length)
6238
+ this.applyChanged(changed);
6239
+ }
6240
+ recheckKeysFor(eventName) {
6241
+ if (!this.moments || this.destroyed)
6242
+ return [];
6243
+ const out = [];
6244
+ this.cache.forEach((entry, key) => {
6245
+ const p = entry.placement;
6246
+ if (p.pageScoped && entry.url !== this.currentUrl())
6247
+ return;
6248
+ const waits = (p.recheckOn || []).includes(eventName) ||
6249
+ (p.items || []).some((i) => { var _a; return ((_a = parseShowWhen(i.showWhen)) === null || _a === void 0 ? void 0 : _a.event) === eventName; });
6250
+ const once = `${key}\u0000${eventName}`;
6251
+ if (!waits || this.rechecked.has(once))
6252
+ return;
6253
+ this.rechecked.add(once);
6254
+ out.push(key);
6255
+ });
6256
+ return out;
6257
+ }
6258
+ recheck(keys, event) {
6259
+ const go = () => {
6260
+ keys.forEach((key) => this.lastNetworkAt.delete(this.rateKey(key)));
6261
+ if (event)
6262
+ this.recheckEvent = event;
6263
+ return this.fetchKeys(keys, false);
6264
+ };
6265
+ const inflight = keys.map((key) => this.inflight.get(key)).filter(Boolean);
6266
+ return (inflight.length ? Promise.all(inflight).then(go) : go()).catch(() => undefined);
6267
+ }
5908
6268
  currentUrl() {
5909
6269
  return this.page ? this.page.current().url : currentPageUrl();
5910
6270
  }
@@ -5976,19 +6336,21 @@ class PlacementManager {
5976
6336
  this.batchKeys.clear();
5977
6337
  const waiters = this.batchWaiters;
5978
6338
  this.batchWaiters = [];
6339
+ const recheckEvent = this.recheckEvent;
6340
+ this.recheckEvent = null;
5979
6341
  const chunks = [];
5980
6342
  for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
5981
6343
  chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
5982
6344
  }
5983
6345
  try {
5984
- await Promise.all(chunks.map((chunk) => this.request(chunk)));
6346
+ await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));
5985
6347
  }
5986
6348
  finally {
5987
6349
  keys.forEach((key) => this.inflight.delete(key));
5988
6350
  waiters.forEach((w) => w.resolve());
5989
6351
  }
5990
6352
  }
5991
- async request(keys) {
6353
+ async request(keys, recheckEvent) {
5992
6354
  var _a, _b, _c, _d;
5993
6355
  const consent = this.runtime.consent();
5994
6356
  if (consent === null || this.destroyed)
@@ -6005,7 +6367,7 @@ class PlacementManager {
6005
6367
  }
6006
6368
  const userId = personal ? this.identity.getUserId() : null;
6007
6369
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
6008
- 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() });
6370
+ 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 } : {}));
6009
6371
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
6010
6372
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
6011
6373
  const url = `${this.apiEndpoint}/v1/in-app/placements`;
@@ -6063,7 +6425,9 @@ class PlacementManager {
6063
6425
  }
6064
6426
  normalize(key, wire) {
6065
6427
  const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];
6066
- 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 } : {}));
6428
+ 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
6429
+ ? { deferredControls: wire.deferredControls.filter((d) => d && typeof d.controlToken === 'string' && d.controlToken) }
6430
+ : {})), (eventNames(wire.recheckOn).length ? { recheckOn: eventNames(wire.recheckOn) } : {}));
6067
6431
  }
6068
6432
  applyChanged(keys) {
6069
6433
  for (const mount of this.mounts) {
@@ -6074,6 +6438,9 @@ class PlacementManager {
6074
6438
  else
6075
6439
  this.render(mount);
6076
6440
  }
6441
+ this.notify(keys);
6442
+ }
6443
+ notify(keys) {
6077
6444
  if (!this.listeners.size)
6078
6445
  return;
6079
6446
  const update = {};
@@ -6102,6 +6469,8 @@ class PlacementManager {
6102
6469
  return false;
6103
6470
  if (this.dismissedLocally.has(this.handle(key, item)))
6104
6471
  return false;
6472
+ if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen))
6473
+ return false;
6105
6474
  const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
6106
6475
  if (eventTriggers.length) {
6107
6476
  const at = this.triggeredAt.get(this.handle(key, item));
@@ -6124,7 +6493,12 @@ class PlacementManager {
6124
6493
  emptyBehavior: wire.emptyBehavior || 'collapse',
6125
6494
  maxItems: wire.maxItems || 1,
6126
6495
  ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
6127
- markDisplayed: () => this.current(generation) && this.reportControl(key),
6496
+ markDisplayed: () => {
6497
+ if (!this.current(generation))
6498
+ return;
6499
+ this.reportControl(key);
6500
+ this.markSpotViewable(key);
6501
+ },
6128
6502
  };
6129
6503
  }
6130
6504
  current(generation) {
@@ -6154,6 +6528,8 @@ class PlacementManager {
6154
6528
  this.render(mount);
6155
6529
  }
6156
6530
  report(key, item, type, elementId) {
6531
+ if (type === 'displayed')
6532
+ this.markSpotViewable(key);
6157
6533
  if (this.runtime.consent() !== 'granted')
6158
6534
  return;
6159
6535
  const once = `${type}:${this.handle(key, item)}`;
@@ -6173,13 +6549,33 @@ class PlacementManager {
6173
6549
  const entry = this.cache.get(key);
6174
6550
  if (!(entry === null || entry === void 0 ? void 0 : entry.placement.isControl) || !entry.placement.controlToken)
6175
6551
  return;
6552
+ if (!this.due(`ctl:${key}:${entry.placement.controlToken}`, entry.placement.showWhen))
6553
+ return;
6554
+ this.postControl(key, entry.placement.controlToken);
6555
+ }
6556
+ markSpotViewable(key) {
6557
+ if (this.spotViewable.has(key))
6558
+ return;
6559
+ this.spotViewable.add(key);
6560
+ this.reportDeferred(key);
6561
+ }
6562
+ reportDeferred(key) {
6563
+ var _a;
6564
+ const list = (_a = this.cache.get(key)) === null || _a === void 0 ? void 0 : _a.placement.deferredControls;
6565
+ if (!(list === null || list === void 0 ? void 0 : list.length) || !this.spotViewable.has(key))
6566
+ return;
6567
+ for (const d of list)
6568
+ if (this.due(`ctl:${key}:${d.controlToken}`, d.showWhen))
6569
+ this.postControl(key, d.controlToken);
6570
+ }
6571
+ postControl(key, controlToken) {
6176
6572
  if (this.runtime.consent() !== 'granted')
6177
6573
  return;
6178
- const once = `control:${entry.placement.controlToken}`;
6574
+ const once = `control:${controlToken}`;
6179
6575
  if (this.reported.has(once))
6180
6576
  return;
6181
6577
  this.reported.add(once);
6182
- 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() }));
6578
+ 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() }));
6183
6579
  }
6184
6580
  subject() {
6185
6581
  const userId = this.identity.getUserId();
@@ -6232,15 +6628,143 @@ class PlacementManager {
6232
6628
  }
6233
6629
  clearDrawn(mount) {
6234
6630
  var _a;
6631
+ if (mount.serverFill) {
6632
+ this.dropServerFill(mount.element, mount.serverFill.wrapper);
6633
+ mount.serverFill = null;
6634
+ }
6235
6635
  mount.frameIds.forEach((id) => this.frames.delete(id));
6236
6636
  mount.frameIds = [];
6237
6637
  (_a = mount.wrapper) === null || _a === void 0 ? void 0 : _a.remove();
6238
6638
  mount.wrapper = null;
6239
6639
  mount.shown = [];
6240
6640
  }
6641
+ serverFillsOfMarker() {
6642
+ if (this.markerFills)
6643
+ return this.markerFills;
6644
+ const out = new Map();
6645
+ try {
6646
+ const el = typeof document !== 'undefined' ? serverMarkerElement() : null;
6647
+ const data = el ? JSON.parse(el.textContent || 'null') : null;
6648
+ const list = data && data.v === 1 && Array.isArray(data[SERVER_FILLS_MARKER_KEY]) ? data[SERVER_FILLS_MARKER_KEY] : [];
6649
+ for (const f of list.slice(0, 20)) {
6650
+ if (!f || !validKey(f.placementKey) || typeof f.campaignId !== 'string' || !f.campaignId)
6651
+ continue;
6652
+ const products = Array.isArray(f.products) ? f.products.filter((p) => typeof p === 'string').slice(0, 24) : [];
6653
+ out.set(f.placementKey, { campaignId: f.campaignId, variantId: typeof f.variantId === 'string' ? f.variantId : '', products });
6654
+ }
6655
+ }
6656
+ catch (_a) {
6657
+ }
6658
+ this.markerFills = out;
6659
+ return out;
6660
+ }
6661
+ serverFillOf(key, element) {
6662
+ var _a;
6663
+ const token = (_a = element.getAttribute) === null || _a === void 0 ? void 0 : _a.call(element, SERVER_FILLED_ATTR);
6664
+ if (!token)
6665
+ return null;
6666
+ 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)); });
6667
+ const fill = this.serverFillsOfMarker().get(key);
6668
+ const ok = !!wrapper &&
6669
+ !!fill &&
6670
+ wrapper.getAttribute(SERVER_FILL_ATTR) === token &&
6671
+ token === `${key}:${fill.campaignId}:${fill.variantId}` &&
6672
+ (this.runtime.allowHtml() || !wrapper.querySelector('.joryio-placement-html'));
6673
+ if (!ok) {
6674
+ this.dropServerFill(element, wrapper !== null && wrapper !== void 0 ? wrapper : null);
6675
+ return null;
6676
+ }
6677
+ attachServerShadowRoots(wrapper);
6678
+ return Object.assign(Object.assign({}, fill), { wrapper: wrapper });
6679
+ }
6680
+ dropServerFill(element, wrapper) {
6681
+ var _a, _b;
6682
+ wrapper === null || wrapper === void 0 ? void 0 : wrapper.remove();
6683
+ (_a = element.removeAttribute) === null || _a === void 0 ? void 0 : _a.call(element, SERVER_FILLED_ATTR);
6684
+ (_b = element.removeAttribute) === null || _b === void 0 ? void 0 : _b.call(element, 'data-joryio-placement-state');
6685
+ }
6686
+ settleServerFill(mount) {
6687
+ var _a, _b;
6688
+ const sf = mount.serverFill;
6689
+ if (!sf)
6690
+ return 'dropped';
6691
+ const entry = this.cache.get(mount.key);
6692
+ if (!entry)
6693
+ return 'waiting';
6694
+ mount.serverFill = null;
6695
+ const items = this.visibleItems(mount.key);
6696
+ const item = items[0];
6697
+ const products = toProducts(item === null || item === void 0 ? void 0 : item.products).map((p) => p.id);
6698
+ const html = !!sf.wrapper.querySelector('.joryio-placement-html');
6699
+ const same = items.length === 1 &&
6700
+ entry.placement.isControl !== true &&
6701
+ item.id === sf.campaignId &&
6702
+ ((_a = item.variantId) !== null && _a !== void 0 ? _a : '') === sf.variantId &&
6703
+ products.length === sf.products.length &&
6704
+ products.every((id, i) => id === sf.products[i]) &&
6705
+ (((_b = item.content) === null || _b === void 0 ? void 0 : _b.kind) === 'html') === html &&
6706
+ (!html || this.runtime.allowHtml()) &&
6707
+ (mount.options.showProducts !== false || !products.length);
6708
+ if (!same) {
6709
+ this.dropServerFill(mount.element, sf.wrapper);
6710
+ return 'dropped';
6711
+ }
6712
+ mount.pendingUpdate = false;
6713
+ this.clearTrackers(mount);
6714
+ mount.wrapper = sf.wrapper;
6715
+ mount.shown = [item.deliveryId || item.id];
6716
+ mount.element.setAttribute('data-joryio-placement-state', 'filled');
6717
+ const node = sf.wrapper.firstElementChild || sf.wrapper;
6718
+ this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));
6719
+ this.bindServerFill(mount, sf.wrapper, item);
6720
+ if (mount.options.onRender) {
6721
+ try {
6722
+ mount.options.onRender(this.toPlacement(mount.key), mount.element);
6723
+ }
6724
+ catch (error) {
6725
+ this.logger.error('The insertPlacement onRender callback threw; ignored:', error);
6726
+ }
6727
+ }
6728
+ return 'kept';
6729
+ }
6730
+ bindServerFill(mount, wrapper, item) {
6731
+ wrapper.addEventListener('click', (event) => {
6732
+ var _a, _b;
6733
+ if (!this.mounts.has(mount) || mount.wrapper !== wrapper)
6734
+ return;
6735
+ const path = (typeof event.composedPath === 'function' ? event.composedPath() : [event.target]);
6736
+ for (const el of path) {
6737
+ if (!el || el === wrapper || typeof el.getAttribute !== 'function')
6738
+ break;
6739
+ const productId = el.getAttribute('data-joryio-product');
6740
+ if (productId) {
6741
+ const href = el.getAttribute('href');
6742
+ if (href)
6743
+ (_a = event.preventDefault) === null || _a === void 0 ? void 0 : _a.call(event);
6744
+ this.buttonAction(mount, item, { id: placementProductElementId(productId), action: 'deep_link', url: href || undefined });
6745
+ return;
6746
+ }
6747
+ const tag = (el.tagName || '').toUpperCase();
6748
+ if (tag === 'A' || tag === 'BUTTON') {
6749
+ const href = tag === 'A' ? el.getAttribute('href') : null;
6750
+ if (hasUserGesture())
6751
+ this.report(mount.key, item, 'clicked', el.getAttribute('data-action') || (href ? 'link_click' : 'cta_click'));
6752
+ if (href && !/^(#|mailto:|tel:|sms:)/i.test(href.trim())) {
6753
+ (_b = event.preventDefault) === null || _b === void 0 ? void 0 : _b.call(event);
6754
+ const safe = safeHttpUrl(href.trim());
6755
+ if (safe && hasUserGesture())
6756
+ this.openLink(safe, { placementKey: mount.key, itemId: item.id }, () => window.open(safe, '_blank', 'noopener'));
6757
+ }
6758
+ return;
6759
+ }
6760
+ }
6761
+ }, true);
6762
+ }
6241
6763
  render(mount) {
6242
6764
  if (!this.mounts.has(mount))
6243
6765
  return;
6766
+ if (mount.serverFill && this.settleServerFill(mount) !== 'dropped')
6767
+ return;
6244
6768
  mount.pendingUpdate = false;
6245
6769
  this.clearTrackers(mount);
6246
6770
  this.clearDrawn(mount);
@@ -6266,7 +6790,10 @@ class PlacementManager {
6266
6790
  if (!drawn.length) {
6267
6791
  wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
6268
6792
  if (placement.isControl && (entry === null || entry === void 0 ? void 0 : entry.placement.controlToken)) {
6269
- this.trackViewability(mount, mount.element, () => this.reportControl(mount.key));
6793
+ this.trackViewability(mount, mount.element, () => {
6794
+ this.reportControl(mount.key);
6795
+ this.markSpotViewable(mount.key);
6796
+ });
6270
6797
  }
6271
6798
  }
6272
6799
  if (mount.options.onRender) {
@@ -6608,6 +7135,22 @@ class PlacementManager {
6608
7135
  }
6609
7136
  }
6610
7137
  }
7138
+ function attachServerShadowRoots(wrapper) {
7139
+ var _a;
7140
+ for (const host of Array.from(((_a = wrapper.querySelectorAll) === null || _a === void 0 ? void 0 : _a.call(wrapper, '.joryio-placement-html')) || [])) {
7141
+ if (host.shadowRoot || typeof host.attachShadow !== 'function')
7142
+ continue;
7143
+ const tpl = Array.from(host.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute('shadowrootmode') === 'open');
7144
+ if (!tpl)
7145
+ continue;
7146
+ try {
7147
+ host.attachShadow({ mode: 'open' }).appendChild(tpl.content);
7148
+ tpl.remove();
7149
+ }
7150
+ catch (_b) {
7151
+ }
7152
+ }
7153
+ }
6611
7154
  function toProducts(raw) {
6612
7155
  if (!Array.isArray(raw))
6613
7156
  return [];
@@ -9297,6 +9840,7 @@ class JoryioSDK {
9297
9840
  this.attributeGeneration = 0;
9298
9841
  this.attributeFailures = 0;
9299
9842
  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); });
9843
+ this.pendingRechecks = [];
9300
9844
  this.editor = null;
9301
9845
  this._ecommerce = null;
9302
9846
  this.isInitialized = false;
@@ -9335,6 +9879,9 @@ class JoryioSDK {
9335
9879
  console.error(`[Joryio] SDK not started: ${keyProblem}. Calls on this instance are ignored.`);
9336
9880
  this.disabled = true;
9337
9881
  }
9882
+ else if (editorFrame()) {
9883
+ this.disabled = true;
9884
+ }
9338
9885
  this.config = resolveConfig(keyProblem
9339
9886
  ? Object.assign(Object.assign({}, (config && typeof config === 'object' ? config : {})), { sdkKey: 'jry_sdk_invalid', optOut: false }) : config);
9340
9887
  this.logger = new Logger(this.config.loggingEnabled, this.config.logLevel);
@@ -9435,6 +9982,11 @@ class JoryioSDK {
9435
9982
  this.pageContext = new PageContextTracker(this.config.pageContext);
9436
9983
  this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
9437
9984
  this.inapp.setPageContext(this.pageContext);
9985
+ this.showWhen = new ShowWhenMoments(this.pageContext, () => this.session.getSessionId(), this.config.sdkKey);
9986
+ this.pageContext.onSignal((s) => {
9987
+ if (s.type === 'page_change')
9988
+ this.pendingRechecks = [];
9989
+ });
9438
9990
  this.placements = new PlacementManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9439
9991
  consent: () => this.placementConsent(),
9440
9992
  allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
@@ -9450,12 +10002,14 @@ class JoryioSDK {
9450
10002
  },
9451
10003
  }, this.network);
9452
10004
  this.placements.setPageContext(this.pageContext);
10005
+ this.placements.setShowWhen(this.showWhen);
9453
10006
  this.pageEdits = new PageEditManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9454
10007
  consent: () => this.placementConsent(),
9455
10008
  requestTimeoutMs: this.config.requestTimeout,
9456
10009
  noteStatus: (status, data) => this.network.noteSuspended(status, data),
9457
10010
  }, this.network);
9458
10011
  this.pageEdits.setPageContext(this.pageContext);
10012
+ this.pageEdits.setShowWhen(this.showWhen);
9459
10013
  this.cards = new CardManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9460
10014
  consent: () => this.placementConsent(),
9461
10015
  requestTimeoutMs: this.config.requestTimeout,
@@ -9495,6 +10049,8 @@ class JoryioSDK {
9495
10049
  return await this.flushEvents(events, identify);
9496
10050
  }
9497
10051
  finally {
10052
+ if (this.pendingRechecks.length)
10053
+ setTimeout(() => this.runRechecks(), 0);
9498
10054
  this.scheduleRetiredTokenPrune();
9499
10055
  }
9500
10056
  });
@@ -9791,6 +10347,7 @@ class JoryioSDK {
9791
10347
  this.network.switchUser(userId);
9792
10348
  this.identity.adopt(anonymousId, userId);
9793
10349
  this.placements.invalidate();
10350
+ this.pendingRechecks = [];
9794
10351
  this.cards.invalidate(true);
9795
10352
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate();
9796
10353
  this.flags.onIdentityChanged();
@@ -10056,6 +10613,7 @@ class JoryioSDK {
10056
10613
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
10057
10614
  this.inapp.invalidate();
10058
10615
  (_a = this.placements) === null || _a === void 0 ? void 0 : _a.invalidate();
10616
+ this.pendingRechecks = [];
10059
10617
  (_b = this.cards) === null || _b === void 0 ? void 0 : _b.invalidate(false);
10060
10618
  (_c = this.pageEdits) === null || _c === void 0 ? void 0 : _c.invalidate({ siteSettings: true });
10061
10619
  (_d = this.flags) === null || _d === void 0 ? void 0 : _d.onIdentityChanged();
@@ -10259,7 +10817,7 @@ class JoryioSDK {
10259
10817
  this.track('Page Viewed', properties);
10260
10818
  }
10261
10819
  track(eventName, properties) {
10262
- var _a, _b;
10820
+ var _a, _b, _c;
10263
10821
  if (!this.isInitialized) {
10264
10822
  this.logger.error('SDK not initialized');
10265
10823
  return;
@@ -10325,6 +10883,8 @@ class JoryioSDK {
10325
10883
  try {
10326
10884
  (_a = this.inapp) === null || _a === void 0 ? void 0 : _a.onEventTracked(eventName, eventProperties);
10327
10885
  (_b = this.placements) === null || _b === void 0 ? void 0 : _b.onEventTracked(eventName, eventProperties);
10886
+ (_c = this.showWhen) === null || _c === void 0 ? void 0 : _c.noteEvent(eventName);
10887
+ this.recheckShowWhen(eventName, processedEvent);
10328
10888
  }
10329
10889
  catch (error) {
10330
10890
  this.logger.error('In-app trigger evaluation failed:', error);
@@ -10348,6 +10908,45 @@ class JoryioSDK {
10348
10908
  this.logger.error('track() failed:', error);
10349
10909
  }
10350
10910
  }
10911
+ recheckShowWhen(eventName, queued) {
10912
+ var _a, _b;
10913
+ const keys = ((_a = this.placements) === null || _a === void 0 ? void 0 : _a.recheckKeysFor(eventName)) || [];
10914
+ const edits = !!((_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.claimRecheck(eventName));
10915
+ if (!keys.length && !edits)
10916
+ return;
10917
+ const event = { name: eventName, eventId: queued.eventId, properties: Object.assign({}, (queued.properties || {})) };
10918
+ this.pendingRechecks.push({ event, keys, edits, who: this.recheckOwner(), at: Date.now() });
10919
+ if (this.pendingRechecks.length > 20)
10920
+ this.pendingRechecks.shift();
10921
+ void this.queue
10922
+ .flush(false, true)
10923
+ .catch(() => undefined)
10924
+ .then(() => this.runRechecks());
10925
+ }
10926
+ recheckOwner() {
10927
+ var _a;
10928
+ return [this.identity.getUserId() || '', this.identity.getAnonymousId(), this.placementConsent() || '', ((_a = this.pageContext) === null || _a === void 0 ? void 0 : _a.current().url) || ''].join('\u0000');
10929
+ }
10930
+ runRechecks() {
10931
+ if (!this.pendingRechecks.length || !this.isInitialized)
10932
+ return;
10933
+ const owner = this.recheckOwner();
10934
+ const now = Date.now();
10935
+ this.pendingRechecks = this.pendingRechecks.filter((r) => r.who === owner && now - r.at <= 60000);
10936
+ const waiting = new Set([...this.queue.getQueuedEvents(), ...this.queue.getInflightEvents()].map((e) => e.eventId));
10937
+ const due = this.pendingRechecks.filter((r) => !waiting.has(r.event.eventId));
10938
+ if (!due.length)
10939
+ return;
10940
+ this.pendingRechecks = this.pendingRechecks.filter((r) => waiting.has(r.event.eventId));
10941
+ if (!this.canSend())
10942
+ return;
10943
+ for (const r of due) {
10944
+ if (r.keys.length)
10945
+ void this.placements.recheck(r.keys, r.event);
10946
+ if (r.edits)
10947
+ this.pageEdits.recheck(r.event);
10948
+ }
10949
+ }
10351
10950
  identify(userId) {
10352
10951
  var _a;
10353
10952
  if (!this.isInitialized) {
@@ -10383,6 +10982,7 @@ class JoryioSDK {
10383
10982
  if (previousUserId !== userId) {
10384
10983
  this.inapp.invalidate();
10385
10984
  this.placements.invalidate();
10985
+ this.pendingRechecks = [];
10386
10986
  this.cards.invalidate(true);
10387
10987
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate();
10388
10988
  this.flags.onIdentityChanged();
@@ -10719,6 +11319,7 @@ class JoryioSDK {
10719
11319
  this.flags.onIdentityChanged();
10720
11320
  this.network.setCurrentUserId(this.identity.getUserId());
10721
11321
  this.placements.invalidate();
11322
+ this.pendingRechecks = [];
10722
11323
  this.cards.invalidate(true);
10723
11324
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate({ siteSettings: true });
10724
11325
  this.utm.reset();
@@ -10785,6 +11386,7 @@ class JoryioSDK {
10785
11386
  this.flags.onIdentityChanged();
10786
11387
  this.network.setCurrentUserId(null);
10787
11388
  this.placements.invalidate();
11389
+ this.pendingRechecks = [];
10788
11390
  (_a = this.cards) === null || _a === void 0 ? void 0 : _a.invalidate(true);
10789
11391
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate({ siteSettings: true });
10790
11392
  this.utm.reset();
@@ -11381,7 +11983,7 @@ class JoryioSDK {
11381
11983
  return this.flags.onFlagsUpdated(callback);
11382
11984
  }
11383
11985
  async destroy() {
11384
- var _a, _b, _c;
11986
+ var _a, _b, _c, _d;
11385
11987
  if (!this.isInitialized) {
11386
11988
  return;
11387
11989
  }
@@ -11423,7 +12025,9 @@ class JoryioSDK {
11423
12025
  this.cards.destroy();
11424
12026
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.destroy();
11425
12027
  (_b = this.editor) === null || _b === void 0 ? void 0 : _b.stop();
11426
- (_c = this.pageContext) === null || _c === void 0 ? void 0 : _c.destroy();
12028
+ (_c = this.showWhen) === null || _c === void 0 ? void 0 : _c.destroy();
12029
+ this.pendingRechecks = [];
12030
+ (_d = this.pageContext) === null || _d === void 0 ? void 0 : _d.destroy();
11427
12031
  this.flags.destroy();
11428
12032
  this.isInitialized = false;
11429
12033
  if (JoryioSDK.instance === this)
@@ -11610,4 +12214,4 @@ if (typeof window !== 'undefined') {
11610
12214
  installSnippetQueue(window);
11611
12215
  }
11612
12216
 
11613
- export { CARD_FEED_TTL_SECONDS, CARD_MIN_REFRESH_SECONDS, EcommerceTracker, FLAGS_MIN_REFRESH_SECONDS, FLAG_SYNC_PUSH_VALUE, IN_APP_DISPLAY_DWELL_MS, JoryioSDK, PLACEMENT_MIN_REFRESH_SECONDS, PLACEMENT_PRODUCT_CARD_WIDTH, PLACEMENT_PRODUCT_ELEMENT_PREFIX, PLACEMENT_VIEWABLE_FRACTION, PushManager, SDK_VERSION, SubscriptionStatus, User, createEcommerceTracker, JoryioSDK as default, installSnippetQueue, placementProductElementId };
12217
+ export { CARD_FEED_TTL_SECONDS, CARD_MIN_REFRESH_SECONDS, EcommerceTracker, FLAGS_MIN_REFRESH_SECONDS, FLAG_SYNC_PUSH_VALUE, IN_APP_DISPLAY_DWELL_MS, JoryioSDK, PLACEMENT_MIN_REFRESH_SECONDS, PLACEMENT_PRODUCT_CARD_WIDTH, PLACEMENT_PRODUCT_ELEMENT_PREFIX, PLACEMENT_VIEWABLE_FRACTION, PushManager, SDK_VERSION, SHOW_WHEN_KINDS, SubscriptionStatus, User, createEcommerceTracker, JoryioSDK as default, installSnippetQueue, placementProductElementId };