@joryio/web-sdk 1.4.0-beta.8 → 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.
package/dist/joryio.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.8
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.8';
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,10 +606,108 @@ 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';
551
710
  const PAGE_EDIT_DEVICES = ['all', 'mobile', 'desktop'];
552
- const PAGE_EDIT_DEVICE_CAPABILITY = 'page_edit_device';
553
711
  const PAGE_EDIT_MOBILE_BREAKPOINT = 768;
554
712
  const PAGE_EDIT_MOBILE_QUERY = '(max-width: 767.98px)';
555
713
  function isMobileViewport(win = window) {
@@ -763,6 +921,11 @@ class PageEditManager {
763
921
  this.offMedia = null;
764
922
  this.started = false;
765
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();
766
929
  this.stores = pageEditsStorageKeys(sdkKey);
767
930
  try {
768
931
  localStorage.removeItem(LEGACY_SELECTOR_STORE);
@@ -783,6 +946,43 @@ class PageEditManager {
783
946
  });
784
947
  }
785
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
+ }
786
986
  start() {
787
987
  var _a;
788
988
  if (this.started || this.destroyed || typeof document === 'undefined')
@@ -828,12 +1028,13 @@ class PageEditManager {
828
1028
  this.loadPage();
829
1029
  }
830
1030
  destroy() {
831
- var _a, _b, _c;
1031
+ var _a, _b, _c, _d;
832
1032
  this.destroyed = true;
833
1033
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
834
- (_b = this.offMedia) === null || _b === void 0 ? void 0 : _b.call(this);
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);
835
1036
  this.offMedia = null;
836
- (_c = this.observer) === null || _c === void 0 ? void 0 : _c.disconnect();
1037
+ (_d = this.observer) === null || _d === void 0 ? void 0 : _d.disconnect();
837
1038
  this.observer = null;
838
1039
  this.revertAll();
839
1040
  this.showAll();
@@ -850,6 +1051,9 @@ class PageEditManager {
850
1051
  loadPage() {
851
1052
  const generation = ++this.generation;
852
1053
  this.revertAll();
1054
+ this.revealed.clear();
1055
+ this.rechecked.clear();
1056
+ this.recheckOn = [];
853
1057
  const url = this.url();
854
1058
  if (!url) {
855
1059
  this.experiences = [];
@@ -985,7 +1189,7 @@ class PageEditManager {
985
1189
  this.siteRequest = request;
986
1190
  return request;
987
1191
  }
988
- async fetch(url, generation) {
1192
+ async fetch(url, generation, recheckEvent) {
989
1193
  var _a, _b, _c, _d;
990
1194
  const consent = this.runtime.consent();
991
1195
  if (consent === null || this.destroyed) {
@@ -995,7 +1199,7 @@ class PageEditManager {
995
1199
  const personal = consent === 'granted';
996
1200
  const userId = personal ? this.identity.getUserId() : null;
997
1201
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
998
- 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, PAGE_EDIT_DEVICE_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 } : {}));
999
1203
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
1000
1204
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
1001
1205
  try {
@@ -1014,6 +1218,7 @@ class PageEditManager {
1014
1218
  .map((wire) => ({ wire, edits: (Array.isArray(wire.edits) ? wire.edits : []).map(trustedEdit).filter((e) => !!e) }));
1015
1219
  this.revertAll();
1016
1220
  this.experiences = experiences;
1221
+ this.recheckOn = eventNames(data.recheckOn);
1017
1222
  this.reconcileServer(experiences);
1018
1223
  this.remember(url, experiences, data.ttlSeconds);
1019
1224
  this.applyAll();
@@ -1047,6 +1252,8 @@ class PageEditManager {
1047
1252
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
1048
1253
  try {
1049
1254
  for (const x of this.experiences) {
1255
+ if (!this.due(x.wire))
1256
+ continue;
1050
1257
  if (x.wire.isControl) {
1051
1258
  const seen = (x.wire.selectors || []).some((s) => isSafeSelector(s) && this.query(s).length > 0);
1052
1259
  if (seen)
@@ -1204,7 +1411,7 @@ class PageEditManager {
1204
1411
  return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
1205
1412
  }
1206
1413
  remember(url, experiences, ttlSeconds) {
1207
- const selectors = [...new Set(experiences.flatMap((x) => (x.wire.isControl ? [] : x.edits.filter((e) => editShowsOn(e, this.mobile)).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))))];
1208
1415
  try {
1209
1416
  const all = JSON.parse(localStorage.getItem(this.stores.selectors) || '{}') || {};
1210
1417
  delete all[url];
@@ -1298,7 +1505,7 @@ class PageEditManager {
1298
1505
  return;
1299
1506
  const keep = new Set();
1300
1507
  for (const x of experiences) {
1301
- if (x.wire.isControl)
1508
+ if (x.wire.isControl || isDeferred(x.wire.showWhen))
1302
1509
  continue;
1303
1510
  for (const e of x.edits) {
1304
1511
  const token = `${x.wire.id}:${e.id}`;
@@ -5660,6 +5867,9 @@ const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
5660
5867
  function placementProductElementId(productId) {
5661
5868
  return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
5662
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';
5663
5873
  const DEFAULT_TTL_SECONDS = 300;
5664
5874
  const LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';
5665
5875
  const placementsStorageKey = (sdkKey) => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;
@@ -5776,7 +5986,14 @@ class PlacementManager {
5776
5986
  this.destroyed = false;
5777
5987
  this.page = null;
5778
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;
5779
5995
  this.pageScopedKeys = new Set();
5996
+ this.markerFills = null;
5780
5997
  this.loadCache();
5781
5998
  this.installBridge();
5782
5999
  this.installPageVisibility();
@@ -5805,6 +6022,7 @@ class PlacementManager {
5805
6022
  hostObserver: null,
5806
6023
  trackers: [],
5807
6024
  frameIds: [],
6025
+ serverFill: this.serverFillOf(key, element),
5808
6026
  };
5809
6027
  this.mounts.add(mount);
5810
6028
  this.observeHost(mount);
@@ -5876,6 +6094,8 @@ class PlacementManager {
5876
6094
  this.triggeredAt.clear();
5877
6095
  this.dismissedLocally.clear();
5878
6096
  this.reported.clear();
6097
+ this.revealed.clear();
6098
+ this.spotViewable.clear();
5879
6099
  this.persistCache();
5880
6100
  const keys = this.mountedKeys();
5881
6101
  for (const mount of this.mounts)
@@ -5884,13 +6104,15 @@ class PlacementManager {
5884
6104
  this.fetchKeys(keys, true).catch(() => undefined);
5885
6105
  }
5886
6106
  destroy() {
5887
- var _a, _b, _c;
6107
+ var _a, _b, _c, _d;
5888
6108
  this.destroyed = true;
5889
6109
  (_a = this.pageUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
5890
6110
  this.pageUnsubscribe = null;
6111
+ (_b = this.momentsUnsubscribe) === null || _b === void 0 ? void 0 : _b.call(this);
6112
+ this.momentsUnsubscribe = null;
5891
6113
  for (const mount of Array.from(this.mounts))
5892
6114
  this.unmount(mount);
5893
- (_b = this.mutationObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
6115
+ (_c = this.mutationObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
5894
6116
  this.mutationObserver = null;
5895
6117
  if (this.batchTimer)
5896
6118
  clearTimeout(this.batchTimer);
@@ -5905,11 +6127,11 @@ class PlacementManager {
5905
6127
  document.removeEventListener('visibilitychange', this.pageListener);
5906
6128
  }
5907
6129
  try {
5908
- 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) {
5909
6131
  delete window[PLACEMENT_BRIDGE_GLOBAL];
5910
6132
  }
5911
6133
  }
5912
- catch (_d) {
6134
+ catch (_e) {
5913
6135
  }
5914
6136
  }
5915
6137
  cleanKeys(keys) {
@@ -5938,11 +6160,23 @@ class PlacementManager {
5938
6160
  this.pageUnsubscribe = tracker.onSignal((signal) => {
5939
6161
  if (signal.type !== 'page_change' || this.destroyed)
5940
6162
  return;
6163
+ const held = this.revealed.size ? this.keysWithMoments() : [];
6164
+ this.revealed.clear();
6165
+ this.spotViewable.clear();
6166
+ this.rechecked.clear();
5941
6167
  const stale = [];
5942
6168
  this.cache.forEach((entry, key) => {
5943
6169
  if (entry.placement.pageScoped && entry.url !== signal.url)
5944
6170
  stale.push(key);
5945
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
+ }
5946
6180
  if (!stale.length)
5947
6181
  return;
5948
6182
  stale.forEach((key) => this.cache.delete(key));
@@ -5962,6 +6196,75 @@ class PlacementManager {
5962
6196
  }
5963
6197
  });
5964
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
+ }
5965
6268
  currentUrl() {
5966
6269
  return this.page ? this.page.current().url : currentPageUrl();
5967
6270
  }
@@ -6033,19 +6336,21 @@ class PlacementManager {
6033
6336
  this.batchKeys.clear();
6034
6337
  const waiters = this.batchWaiters;
6035
6338
  this.batchWaiters = [];
6339
+ const recheckEvent = this.recheckEvent;
6340
+ this.recheckEvent = null;
6036
6341
  const chunks = [];
6037
6342
  for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
6038
6343
  chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
6039
6344
  }
6040
6345
  try {
6041
- await Promise.all(chunks.map((chunk) => this.request(chunk)));
6346
+ await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));
6042
6347
  }
6043
6348
  finally {
6044
6349
  keys.forEach((key) => this.inflight.delete(key));
6045
6350
  waiters.forEach((w) => w.resolve());
6046
6351
  }
6047
6352
  }
6048
- async request(keys) {
6353
+ async request(keys, recheckEvent) {
6049
6354
  var _a, _b, _c, _d;
6050
6355
  const consent = this.runtime.consent();
6051
6356
  if (consent === null || this.destroyed)
@@ -6062,7 +6367,7 @@ class PlacementManager {
6062
6367
  }
6063
6368
  const userId = personal ? this.identity.getUserId() : null;
6064
6369
  const anonymousId = personal ? this.identity.getAnonymousId() : null;
6065
- 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 } : {}));
6066
6371
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
6067
6372
  const timeout = setTimeout(() => controller === null || controller === void 0 ? void 0 : controller.abort(), (_a = this.runtime.requestTimeoutMs) !== null && _a !== void 0 ? _a : 10000);
6068
6373
  const url = `${this.apiEndpoint}/v1/in-app/placements`;
@@ -6120,7 +6425,9 @@ class PlacementManager {
6120
6425
  }
6121
6426
  normalize(key, wire) {
6122
6427
  const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];
6123
- 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) } : {}));
6124
6431
  }
6125
6432
  applyChanged(keys) {
6126
6433
  for (const mount of this.mounts) {
@@ -6131,6 +6438,9 @@ class PlacementManager {
6131
6438
  else
6132
6439
  this.render(mount);
6133
6440
  }
6441
+ this.notify(keys);
6442
+ }
6443
+ notify(keys) {
6134
6444
  if (!this.listeners.size)
6135
6445
  return;
6136
6446
  const update = {};
@@ -6159,6 +6469,8 @@ class PlacementManager {
6159
6469
  return false;
6160
6470
  if (this.dismissedLocally.has(this.handle(key, item)))
6161
6471
  return false;
6472
+ if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen))
6473
+ return false;
6162
6474
  const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
6163
6475
  if (eventTriggers.length) {
6164
6476
  const at = this.triggeredAt.get(this.handle(key, item));
@@ -6181,7 +6493,12 @@ class PlacementManager {
6181
6493
  emptyBehavior: wire.emptyBehavior || 'collapse',
6182
6494
  maxItems: wire.maxItems || 1,
6183
6495
  ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
6184
- 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
+ },
6185
6502
  };
6186
6503
  }
6187
6504
  current(generation) {
@@ -6211,6 +6528,8 @@ class PlacementManager {
6211
6528
  this.render(mount);
6212
6529
  }
6213
6530
  report(key, item, type, elementId) {
6531
+ if (type === 'displayed')
6532
+ this.markSpotViewable(key);
6214
6533
  if (this.runtime.consent() !== 'granted')
6215
6534
  return;
6216
6535
  const once = `${type}:${this.handle(key, item)}`;
@@ -6230,13 +6549,33 @@ class PlacementManager {
6230
6549
  const entry = this.cache.get(key);
6231
6550
  if (!(entry === null || entry === void 0 ? void 0 : entry.placement.isControl) || !entry.placement.controlToken)
6232
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) {
6233
6572
  if (this.runtime.consent() !== 'granted')
6234
6573
  return;
6235
- const once = `control:${entry.placement.controlToken}`;
6574
+ const once = `control:${controlToken}`;
6236
6575
  if (this.reported.has(once))
6237
6576
  return;
6238
6577
  this.reported.add(once);
6239
- 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() }));
6240
6579
  }
6241
6580
  subject() {
6242
6581
  const userId = this.identity.getUserId();
@@ -6289,15 +6628,143 @@ class PlacementManager {
6289
6628
  }
6290
6629
  clearDrawn(mount) {
6291
6630
  var _a;
6631
+ if (mount.serverFill) {
6632
+ this.dropServerFill(mount.element, mount.serverFill.wrapper);
6633
+ mount.serverFill = null;
6634
+ }
6292
6635
  mount.frameIds.forEach((id) => this.frames.delete(id));
6293
6636
  mount.frameIds = [];
6294
6637
  (_a = mount.wrapper) === null || _a === void 0 ? void 0 : _a.remove();
6295
6638
  mount.wrapper = null;
6296
6639
  mount.shown = [];
6297
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
+ }
6298
6763
  render(mount) {
6299
6764
  if (!this.mounts.has(mount))
6300
6765
  return;
6766
+ if (mount.serverFill && this.settleServerFill(mount) !== 'dropped')
6767
+ return;
6301
6768
  mount.pendingUpdate = false;
6302
6769
  this.clearTrackers(mount);
6303
6770
  this.clearDrawn(mount);
@@ -6323,7 +6790,10 @@ class PlacementManager {
6323
6790
  if (!drawn.length) {
6324
6791
  wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
6325
6792
  if (placement.isControl && (entry === null || entry === void 0 ? void 0 : entry.placement.controlToken)) {
6326
- 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
+ });
6327
6797
  }
6328
6798
  }
6329
6799
  if (mount.options.onRender) {
@@ -6665,6 +7135,22 @@ class PlacementManager {
6665
7135
  }
6666
7136
  }
6667
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
+ }
6668
7154
  function toProducts(raw) {
6669
7155
  if (!Array.isArray(raw))
6670
7156
  return [];
@@ -9354,6 +9840,7 @@ class JoryioSDK {
9354
9840
  this.attributeGeneration = 0;
9355
9841
  this.attributeFailures = 0;
9356
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 = [];
9357
9844
  this.editor = null;
9358
9845
  this._ecommerce = null;
9359
9846
  this.isInitialized = false;
@@ -9495,6 +9982,11 @@ class JoryioSDK {
9495
9982
  this.pageContext = new PageContextTracker(this.config.pageContext);
9496
9983
  this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
9497
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
+ });
9498
9990
  this.placements = new PlacementManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9499
9991
  consent: () => this.placementConsent(),
9500
9992
  allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
@@ -9510,12 +10002,14 @@ class JoryioSDK {
9510
10002
  },
9511
10003
  }, this.network);
9512
10004
  this.placements.setPageContext(this.pageContext);
10005
+ this.placements.setShowWhen(this.showWhen);
9513
10006
  this.pageEdits = new PageEditManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9514
10007
  consent: () => this.placementConsent(),
9515
10008
  requestTimeoutMs: this.config.requestTimeout,
9516
10009
  noteStatus: (status, data) => this.network.noteSuspended(status, data),
9517
10010
  }, this.network);
9518
10011
  this.pageEdits.setPageContext(this.pageContext);
10012
+ this.pageEdits.setShowWhen(this.showWhen);
9519
10013
  this.cards = new CardManager(this.config.apiEndpoint, this.config.sdkKey, this.identity, this.session, this.logger, {
9520
10014
  consent: () => this.placementConsent(),
9521
10015
  requestTimeoutMs: this.config.requestTimeout,
@@ -9555,6 +10049,8 @@ class JoryioSDK {
9555
10049
  return await this.flushEvents(events, identify);
9556
10050
  }
9557
10051
  finally {
10052
+ if (this.pendingRechecks.length)
10053
+ setTimeout(() => this.runRechecks(), 0);
9558
10054
  this.scheduleRetiredTokenPrune();
9559
10055
  }
9560
10056
  });
@@ -9851,6 +10347,7 @@ class JoryioSDK {
9851
10347
  this.network.switchUser(userId);
9852
10348
  this.identity.adopt(anonymousId, userId);
9853
10349
  this.placements.invalidate();
10350
+ this.pendingRechecks = [];
9854
10351
  this.cards.invalidate(true);
9855
10352
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate();
9856
10353
  this.flags.onIdentityChanged();
@@ -10116,6 +10613,7 @@ class JoryioSDK {
10116
10613
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
10117
10614
  this.inapp.invalidate();
10118
10615
  (_a = this.placements) === null || _a === void 0 ? void 0 : _a.invalidate();
10616
+ this.pendingRechecks = [];
10119
10617
  (_b = this.cards) === null || _b === void 0 ? void 0 : _b.invalidate(false);
10120
10618
  (_c = this.pageEdits) === null || _c === void 0 ? void 0 : _c.invalidate({ siteSettings: true });
10121
10619
  (_d = this.flags) === null || _d === void 0 ? void 0 : _d.onIdentityChanged();
@@ -10319,7 +10817,7 @@ class JoryioSDK {
10319
10817
  this.track('Page Viewed', properties);
10320
10818
  }
10321
10819
  track(eventName, properties) {
10322
- var _a, _b;
10820
+ var _a, _b, _c;
10323
10821
  if (!this.isInitialized) {
10324
10822
  this.logger.error('SDK not initialized');
10325
10823
  return;
@@ -10385,6 +10883,8 @@ class JoryioSDK {
10385
10883
  try {
10386
10884
  (_a = this.inapp) === null || _a === void 0 ? void 0 : _a.onEventTracked(eventName, eventProperties);
10387
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);
10388
10888
  }
10389
10889
  catch (error) {
10390
10890
  this.logger.error('In-app trigger evaluation failed:', error);
@@ -10408,6 +10908,45 @@ class JoryioSDK {
10408
10908
  this.logger.error('track() failed:', error);
10409
10909
  }
10410
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
+ }
10411
10950
  identify(userId) {
10412
10951
  var _a;
10413
10952
  if (!this.isInitialized) {
@@ -10443,6 +10982,7 @@ class JoryioSDK {
10443
10982
  if (previousUserId !== userId) {
10444
10983
  this.inapp.invalidate();
10445
10984
  this.placements.invalidate();
10985
+ this.pendingRechecks = [];
10446
10986
  this.cards.invalidate(true);
10447
10987
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate();
10448
10988
  this.flags.onIdentityChanged();
@@ -10779,6 +11319,7 @@ class JoryioSDK {
10779
11319
  this.flags.onIdentityChanged();
10780
11320
  this.network.setCurrentUserId(this.identity.getUserId());
10781
11321
  this.placements.invalidate();
11322
+ this.pendingRechecks = [];
10782
11323
  this.cards.invalidate(true);
10783
11324
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.invalidate({ siteSettings: true });
10784
11325
  this.utm.reset();
@@ -10845,6 +11386,7 @@ class JoryioSDK {
10845
11386
  this.flags.onIdentityChanged();
10846
11387
  this.network.setCurrentUserId(null);
10847
11388
  this.placements.invalidate();
11389
+ this.pendingRechecks = [];
10848
11390
  (_a = this.cards) === null || _a === void 0 ? void 0 : _a.invalidate(true);
10849
11391
  (_b = this.pageEdits) === null || _b === void 0 ? void 0 : _b.invalidate({ siteSettings: true });
10850
11392
  this.utm.reset();
@@ -11441,7 +11983,7 @@ class JoryioSDK {
11441
11983
  return this.flags.onFlagsUpdated(callback);
11442
11984
  }
11443
11985
  async destroy() {
11444
- var _a, _b, _c;
11986
+ var _a, _b, _c, _d;
11445
11987
  if (!this.isInitialized) {
11446
11988
  return;
11447
11989
  }
@@ -11483,7 +12025,9 @@ class JoryioSDK {
11483
12025
  this.cards.destroy();
11484
12026
  (_a = this.pageEdits) === null || _a === void 0 ? void 0 : _a.destroy();
11485
12027
  (_b = this.editor) === null || _b === void 0 ? void 0 : _b.stop();
11486
- (_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();
11487
12031
  this.flags.destroy();
11488
12032
  this.isInitialized = false;
11489
12033
  if (JoryioSDK.instance === this)
@@ -11670,4 +12214,4 @@ if (typeof window !== 'undefined') {
11670
12214
  installSnippetQueue(window);
11671
12215
  }
11672
12216
 
11673
- 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 };