@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.
@@ -30,16 +30,34 @@
30
30
  * delivery token, and the SDK reports nothing.
31
31
  * - HTML items render in the same sandboxed, nonce-CSP frame as overlays, and
32
32
  * only when `allowHtmlJsInAppMessages` is on.
33
+ * - Show when (D465, show-when.ts): an item with a `showWhen` other than load
34
+ * is held - neither drawn nor handed to the data API - until its moment in
35
+ * this page view, then the key's spots re-draw and onPlacementsUpdated
36
+ * fires; a route change holds it again until the new page's moment. A
37
+ * control answer's `showWhen` delays its exposure the same way, and
38
+ * `deferredControls` are reported once their own moment has come and the
39
+ * spot was viewable. An event named in `recheckOn` (or one an item waits
40
+ * on) re-fetches the key at once, past the 30 s limit, once per page view.
41
+ * - Server-filled slots (D466): a store plugin may write a slot's
42
+ * content into the HTML when Joryio's answer for it is the same for every
43
+ * visitor (`data-joryio-server-filled` on the slot, the fill inside it, the
44
+ * marker block's `fills`). The SDK keeps that drawing when the visitor's own
45
+ * answer is the same campaign, variant and products - no redraw - and
46
+ * reports its impression with the visitor's own token once it is viewable
47
+ * (nothing without consent, as for every item); otherwise it replaces it
48
+ * with the visitor's answer, or removes it per the empty behaviour.
33
49
  */
34
50
 
35
51
  import { JoryioSubscription, joryioSubscription } from './subscription';
36
52
  import { bucketHash } from '../utils/bucket-hash';
37
53
  import { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';
38
54
  import { Logger } from '../utils/logger';
55
+ import { eventNames, isDeferred, parseShowWhen, type RecheckEvent, type ShowWhenMoments } from './show-when';
39
56
  import { sdkIdentityHeaders } from './config';
40
57
  import { IdentityManager } from './identity';
41
58
  import { SessionManager } from './session';
42
59
  import type { LinkContext, LinkRouter } from './links';
60
+ import { serverMarkerElement } from './page-edits';
43
61
  import {
44
62
  buildInAppSrcdoc,
45
63
  inAppTriggerFilterMatches,
@@ -71,6 +89,24 @@ export const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
71
89
  export function placementProductElementId(productId: string): string {
72
90
  return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
73
91
  }
92
+ /**
93
+ * Server-filled slots (D466; backend common/placements/server-slot-fills.ts,
94
+ * the plugins' shared core). Same names and values pinned by
95
+ * server-slot-fills-sdk-parity.spec.ts.
96
+ */
97
+ export const SERVER_FILLED_ATTR = 'data-joryio-server-filled';
98
+ export const SERVER_FILL_ATTR = 'data-joryio-server-fill';
99
+ export const SERVER_FILLS_MARKER_KEY = 'fills';
100
+
101
+ /** One slot the store's server filled: what it drew, from the marker. */
102
+ interface ServerFill {
103
+ campaignId: string;
104
+ variantId: string;
105
+ products: string[];
106
+ /** The fill's `.joryio-placement` wrapper inside the slot. */
107
+ wrapper: HTMLElement;
108
+ }
109
+
74
110
  /** Used when an answer carries no ttlSeconds. */
75
111
  const DEFAULT_TTL_SECONDS = 300;
76
112
  /** The pre-scoping, origin-wide name - never read, removed on start. */
@@ -129,6 +165,8 @@ export interface PlacementItemWire {
129
165
  expiresAt?: string | null;
130
166
  /** Echoed in `shown` when present; the item id otherwise. */
131
167
  deliveryId?: string | null;
168
+ /** Show when (D465): the item's moment; absent = on load. */
169
+ showWhen?: unknown;
132
170
  }
133
171
 
134
172
  /** One placement as the server sends it. */
@@ -146,6 +184,12 @@ export interface PlacementWire {
146
184
  * and asked again on a route change.
147
185
  */
148
186
  pageScoped?: boolean;
187
+ /** Show when (D465), on a control answer only: the moment the held-out treatment would have shown. */
188
+ showWhen?: unknown;
189
+ /** Control exposures to report once their moment came and the spot was viewable. */
190
+ deferredControls?: Array<{ controlToken: string; showWhen: unknown }>;
191
+ /** Event names that re-fetch this key at once when tracked. */
192
+ recheckOn?: string[];
149
193
  }
150
194
 
151
195
  export interface PlacementsResponse {
@@ -267,6 +311,8 @@ interface Mount {
267
311
  hostObserver: IntersectionObserver | null;
268
312
  trackers: ViewTracker[];
269
313
  frameIds: string[];
314
+ /** D466: the store's server drew this slot; kept or replaced once the visitor's answer is known. */
315
+ serverFill: ServerFill | null;
270
316
  }
271
317
 
272
318
  const nowMs = () => Date.now();
@@ -419,6 +465,17 @@ export class PlacementManager {
419
465
  private destroyed = false;
420
466
  private page: PageContextTracker | null = null;
421
467
  private pageUnsubscribe: (() => void) | null = null;
468
+ /** Show when (D465): the moments; null = this manager holds every non-load item for good. */
469
+ private moments: ShowWhenMoments | null = null;
470
+ private momentsUnsubscribe: (() => void) | null = null;
471
+ /** Held items / control answers revealed in this page view (handles; `ctl:` + token for a control). */
472
+ private revealed = new Set<string>();
473
+ /** Keys whose spot was viewable in this page view (drawn item, control spot, or markDisplayed). */
474
+ private spotViewable = new Set<string>();
475
+ /** `key + event` re-checked in this page view. */
476
+ private rechecked = new Set<string>();
477
+ /** The event the next batch re-checks for (only a re-check request carries it). */
478
+ private recheckEvent: RecheckEvent | null = null;
422
479
 
423
480
  constructor(
424
481
  private apiEndpoint: string,
@@ -460,6 +517,7 @@ export class PlacementManager {
460
517
  hostObserver: null,
461
518
  trackers: [],
462
519
  frameIds: [],
520
+ serverFill: this.serverFillOf(key, element),
463
521
  };
464
522
  this.mounts.add(mount);
465
523
  this.observeHost(mount);
@@ -543,6 +601,8 @@ export class PlacementManager {
543
601
  this.triggeredAt.clear();
544
602
  this.dismissedLocally.clear();
545
603
  this.reported.clear();
604
+ this.revealed.clear();
605
+ this.spotViewable.clear();
546
606
  this.persistCache();
547
607
  const keys = this.mountedKeys();
548
608
  // The previous person's content goes NOW, on screen or not: it must not
@@ -555,6 +615,8 @@ export class PlacementManager {
555
615
  this.destroyed = true;
556
616
  this.pageUnsubscribe?.();
557
617
  this.pageUnsubscribe = null;
618
+ this.momentsUnsubscribe?.();
619
+ this.momentsUnsubscribe = null;
558
620
  for (const mount of Array.from(this.mounts)) this.unmount(mount);
559
621
  this.mutationObserver?.disconnect();
560
622
  this.mutationObserver = null;
@@ -608,10 +670,21 @@ export class PlacementManager {
608
670
  if (!tracker) return;
609
671
  this.pageUnsubscribe = tracker.onSignal((signal) => {
610
672
  if (signal.type !== 'page_change' || this.destroyed) return;
673
+ // Show when: a new page view - held items wait for this page's moment again.
674
+ const held = this.revealed.size ? this.keysWithMoments() : [];
675
+ this.revealed.clear();
676
+ this.spotViewable.clear();
677
+ this.rechecked.clear();
611
678
  const stale: string[] = [];
612
679
  this.cache.forEach((entry, key) => {
613
680
  if (entry.placement.pageScoped && entry.url !== signal.url) stale.push(key);
614
681
  });
682
+ const rehide = held.filter((key) => !stale.includes(key));
683
+ if (rehide.length) {
684
+ for (const mount of this.mounts) if (rehide.includes(mount.key)) this.render(mount);
685
+ this.notify(rehide);
686
+ this.sweep();
687
+ }
615
688
  if (!stale.length) return;
616
689
  stale.forEach((key) => this.cache.delete(key));
617
690
  this.persistCache();
@@ -628,6 +701,88 @@ export class PlacementManager {
628
701
  });
629
702
  }
630
703
 
704
+ /** Show when (D465): the SDK's moments. Held content is revealed as they come. */
705
+ setShowWhen(moments: ShowWhenMoments | null): void {
706
+ this.momentsUnsubscribe?.();
707
+ this.moments = moments;
708
+ this.momentsUnsubscribe = moments ? moments.onChange(() => !this.destroyed && this.sweep()) : null;
709
+ }
710
+
711
+ /** Has this held content's moment come in this page view? Once yes, it stays yes until a route change. */
712
+ private due(handle: string, raw: unknown): boolean {
713
+ const sw = parseShowWhen(raw);
714
+ if (!sw) return false;
715
+ return sw.kind === 'load' || this.revealed.has(handle) || (!!this.moments && this.moments.met(sw));
716
+ }
717
+
718
+ /** Keys whose answer holds anything until a moment. */
719
+ private keysWithMoments(): string[] {
720
+ const out: string[] = [];
721
+ this.cache.forEach((entry, key) => {
722
+ const p = entry.placement;
723
+ if (p.showWhen !== undefined || p.deferredControls?.length || (p.items || []).some((i) => i.showWhen !== undefined)) out.push(key);
724
+ });
725
+ return out;
726
+ }
727
+
728
+ /**
729
+ * A moment may have come: reveal held items and control answers whose moment
730
+ * did (re-draw + onPlacementsUpdated), and report the deferred control
731
+ * exposures that are now due.
732
+ */
733
+ private sweep(): void {
734
+ const changed: string[] = [];
735
+ this.cache.forEach((entry, key) => {
736
+ const p = entry.placement;
737
+ const handles: Array<[string, unknown]> = (p.items || []).filter((i) => isDeferred(i.showWhen)).map((i) => [this.handle(key, i), i.showWhen]);
738
+ if (p.isControl && isDeferred(p.showWhen)) handles.push([`ctl:${key}:${p.controlToken || ''}`, p.showWhen]);
739
+ for (const [h, raw] of handles) {
740
+ if (this.revealed.has(h) || !this.due(h, raw)) continue;
741
+ this.revealed.add(h);
742
+ if (!changed.includes(key)) changed.push(key);
743
+ }
744
+ this.reportDeferred(key);
745
+ });
746
+ if (changed.length) this.applyChanged(changed);
747
+ }
748
+
749
+ /**
750
+ * Show when: the keys to ask again now that `eventName` was tracked - their
751
+ * answer lists it in `recheckOn` or holds an item waiting on it - at most
752
+ * once per (key, event) per page view. Marks them as asked.
753
+ */
754
+ recheckKeysFor(eventName: string): string[] {
755
+ if (!this.moments || this.destroyed) return [];
756
+ const out: string[] = [];
757
+ this.cache.forEach((entry, key) => {
758
+ const p = entry.placement;
759
+ if (p.pageScoped && entry.url !== this.currentUrl()) return;
760
+ const waits =
761
+ (p.recheckOn || []).includes(eventName) ||
762
+ (p.items || []).some((i) => (parseShowWhen(i.showWhen) as { event?: string } | null)?.event === eventName);
763
+ const once = `${key}\u0000${eventName}`;
764
+ if (!waits || this.rechecked.has(once)) return;
765
+ this.rechecked.add(once);
766
+ out.push(key);
767
+ });
768
+ return out;
769
+ }
770
+
771
+ /**
772
+ * Ask the server again for `keys` now, past the client refresh limit (the
773
+ * show-when re-check), carrying the event that caused it (`recheckEvent`).
774
+ */
775
+ recheck(keys: string[], event?: RecheckEvent): Promise<void> {
776
+ const go = (): Promise<void> => {
777
+ keys.forEach((key) => this.lastNetworkAt.delete(this.rateKey(key)));
778
+ if (event) this.recheckEvent = event;
779
+ return this.fetchKeys(keys, false);
780
+ };
781
+ // A request already on its way may predate the event: ask again once it is back.
782
+ const inflight = keys.map((key) => this.inflight.get(key)).filter(Boolean);
783
+ return (inflight.length ? Promise.all(inflight).then(go) : go()).catch(() => undefined);
784
+ }
785
+
631
786
  private currentUrl(): string | null {
632
787
  return this.page ? this.page.current().url : currentPageUrl();
633
788
  }
@@ -705,19 +860,21 @@ export class PlacementManager {
705
860
  this.batchKeys.clear();
706
861
  const waiters = this.batchWaiters;
707
862
  this.batchWaiters = [];
863
+ const recheckEvent = this.recheckEvent;
864
+ this.recheckEvent = null;
708
865
  const chunks: string[][] = [];
709
866
  for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
710
867
  chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
711
868
  }
712
869
  try {
713
- await Promise.all(chunks.map((chunk) => this.request(chunk)));
870
+ await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));
714
871
  } finally {
715
872
  keys.forEach((key) => this.inflight.delete(key));
716
873
  waiters.forEach((w) => w.resolve());
717
874
  }
718
875
  }
719
876
 
720
- private async request(keys: string[]): Promise<void> {
877
+ private async request(keys: string[], recheckEvent?: RecheckEvent | null): Promise<void> {
721
878
  const consent = this.runtime.consent();
722
879
  if (consent === null || this.destroyed) return;
723
880
  const generation = this.generation;
@@ -743,6 +900,7 @@ export class PlacementManager {
743
900
  placements: keys,
744
901
  shown,
745
902
  context: this.page ? { ...this.page.current(), screen: null } : pageContext(),
903
+ ...(recheckEvent ? { recheckEvent } : {}),
746
904
  };
747
905
 
748
906
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
@@ -818,6 +976,11 @@ export class PlacementManager {
818
976
  controlToken: wire.controlToken || null,
819
977
  items,
820
978
  ...(wire.pageScoped === true ? { pageScoped: true } : {}),
979
+ ...(wire.isControl === true && wire.showWhen != null ? { showWhen: wire.showWhen } : {}),
980
+ ...(Array.isArray(wire.deferredControls) && wire.deferredControls.length
981
+ ? { deferredControls: wire.deferredControls.filter((d) => d && typeof d.controlToken === 'string' && d.controlToken) }
982
+ : {}),
983
+ ...(eventNames(wire.recheckOn).length ? { recheckOn: eventNames(wire.recheckOn) } : {}),
821
984
  };
822
985
  }
823
986
 
@@ -829,6 +992,10 @@ export class PlacementManager {
829
992
  if (mount.hostInView && mount.shown.length) mount.pendingUpdate = true;
830
993
  else this.render(mount);
831
994
  }
995
+ this.notify(keys);
996
+ }
997
+
998
+ private notify(keys: string[]): void {
832
999
  if (!this.listeners.size) return;
833
1000
  const update: Record<string, Placement> = {};
834
1001
  keys.forEach((key) => (update[key] = this.toPlacement(key)));
@@ -857,6 +1024,8 @@ export class PlacementManager {
857
1024
  .filter((item) => {
858
1025
  if (item.expiresAt && Date.parse(item.expiresAt) <= now) return false;
859
1026
  if (this.dismissedLocally.has(this.handle(key, item))) return false;
1027
+ // Show when: held until its moment in this page view; an unknown or invalid moment is never shown.
1028
+ if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen)) return false;
860
1029
  const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
861
1030
  if (eventTriggers.length) {
862
1031
  const at = this.triggeredAt.get(this.handle(key, item));
@@ -879,7 +1048,11 @@ export class PlacementManager {
879
1048
  emptyBehavior: wire.emptyBehavior || 'collapse',
880
1049
  maxItems: wire.maxItems || 1,
881
1050
  ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
882
- markDisplayed: () => this.current(generation) && this.reportControl(key),
1051
+ markDisplayed: () => {
1052
+ if (!this.current(generation)) return;
1053
+ this.reportControl(key);
1054
+ this.markSpotViewable(key);
1055
+ },
883
1056
  };
884
1057
  }
885
1058
 
@@ -919,6 +1092,7 @@ export class PlacementManager {
919
1092
  * as displayed - the person saw it.
920
1093
  */
921
1094
  private report(key: string, item: PlacementItemWire, type: 'displayed' | 'clicked' | 'dismissed', elementId?: string): void {
1095
+ if (type === 'displayed') this.markSpotViewable(key);
922
1096
  if (this.runtime.consent() !== 'granted') return;
923
1097
  const once = `${type}:${this.handle(key, item)}`;
924
1098
  if (type !== 'clicked') {
@@ -951,13 +1125,35 @@ export class PlacementManager {
951
1125
  private reportControl(key: string): void {
952
1126
  const entry = this.cache.get(key);
953
1127
  if (!entry?.placement.isControl || !entry.placement.controlToken) return;
1128
+ // Show when: not before the moment the treatment would have shown (the spot re-draws, and
1129
+ // onPlacementsUpdated fires, at that moment - a markDisplayed before it is ignored).
1130
+ if (!this.due(`ctl:${key}:${entry.placement.controlToken}`, entry.placement.showWhen)) return;
1131
+ this.postControl(key, entry.placement.controlToken);
1132
+ }
1133
+
1134
+ /** The spot of `key` was viewable in this page view: deferred control exposures may now be due. */
1135
+ private markSpotViewable(key: string): void {
1136
+ if (this.spotViewable.has(key)) return;
1137
+ this.spotViewable.add(key);
1138
+ this.reportDeferred(key);
1139
+ }
1140
+
1141
+ /** `deferredControls` of the answer: each once, after its own moment, once the spot was viewable in this page view. */
1142
+ private reportDeferred(key: string): void {
1143
+ const list = this.cache.get(key)?.placement.deferredControls;
1144
+ if (!list?.length || !this.spotViewable.has(key)) return;
1145
+ for (const d of list) if (this.due(`ctl:${key}:${d.controlToken}`, d.showWhen)) this.postControl(key, d.controlToken);
1146
+ }
1147
+
1148
+ /** `in_app.control_viewed`, once per control token, with consent only. */
1149
+ private postControl(key: string, controlToken: string): void {
954
1150
  if (this.runtime.consent() !== 'granted') return;
955
- const once = `control:${entry.placement.controlToken}`;
1151
+ const once = `control:${controlToken}`;
956
1152
  if (this.reported.has(once)) return;
957
1153
  this.reported.add(once);
958
1154
  this.post('/v1/in-app/track', {
959
1155
  action: 'control_viewed',
960
- controlToken: entry.placement.controlToken,
1156
+ controlToken,
961
1157
  placementKey: key,
962
1158
  ...this.subject(),
963
1159
  sessionId: this.session.getSessionId(),
@@ -1020,6 +1216,11 @@ export class PlacementManager {
1020
1216
  }
1021
1217
 
1022
1218
  private clearDrawn(mount: Mount): void {
1219
+ if (mount.serverFill) {
1220
+ // A server drawing never settled (removed before any answer): it goes with the mount.
1221
+ this.dropServerFill(mount.element, mount.serverFill.wrapper);
1222
+ mount.serverFill = null;
1223
+ }
1023
1224
  mount.frameIds.forEach((id) => this.frames.delete(id));
1024
1225
  mount.frameIds = [];
1025
1226
  mount.wrapper?.remove();
@@ -1027,8 +1228,152 @@ export class PlacementManager {
1027
1228
  mount.shown = [];
1028
1229
  }
1029
1230
 
1231
+ /** The marker block's fills by key (read once per page load; the plugin writes it before any script). */
1232
+ private markerFills: Map<string, { campaignId: string; variantId: string; products: string[] }> | null = null;
1233
+
1234
+ private serverFillsOfMarker(): Map<string, { campaignId: string; variantId: string; products: string[] }> {
1235
+ if (this.markerFills) return this.markerFills;
1236
+ const out = new Map<string, { campaignId: string; variantId: string; products: string[] }>();
1237
+ try {
1238
+ const el = typeof document !== 'undefined' ? serverMarkerElement() : null;
1239
+ const data = el ? JSON.parse(el.textContent || 'null') : null;
1240
+ const list = data && data.v === 1 && Array.isArray(data[SERVER_FILLS_MARKER_KEY]) ? data[SERVER_FILLS_MARKER_KEY] : [];
1241
+ for (const f of list.slice(0, 20)) {
1242
+ if (!f || !validKey(f.placementKey) || typeof f.campaignId !== 'string' || !f.campaignId) continue;
1243
+ const products = Array.isArray(f.products) ? f.products.filter((p: unknown) => typeof p === 'string').slice(0, 24) : [];
1244
+ out.set(f.placementKey, { campaignId: f.campaignId, variantId: typeof f.variantId === 'string' ? f.variantId : '', products });
1245
+ }
1246
+ } catch {
1247
+ // A broken marker: no slot is treated as server-filled (their content is replaced below).
1248
+ }
1249
+ this.markerFills = out;
1250
+ return out;
1251
+ }
1252
+
1253
+ /**
1254
+ * The server's drawing in a slot element, when the element, its fill and
1255
+ * the marker block agree on placement, campaign and variant. A fill they do
1256
+ * not agree on (or one this SDK may not show: HTML with
1257
+ * allowHtmlJsInAppMessages off) is removed at once and the slot is drawn
1258
+ * as any other.
1259
+ */
1260
+ private serverFillOf(key: string, element: HTMLElement): ServerFill | null {
1261
+ const token = element.getAttribute?.(SERVER_FILLED_ATTR);
1262
+ if (!token) return null;
1263
+ const wrapper = Array.from(element.children || []).find(
1264
+ (c) => (c as HTMLElement).classList?.contains('joryio-placement') && c.hasAttribute?.(SERVER_FILL_ATTR),
1265
+ ) as HTMLElement | undefined;
1266
+ const fill = this.serverFillsOfMarker().get(key);
1267
+ const ok =
1268
+ !!wrapper &&
1269
+ !!fill &&
1270
+ wrapper.getAttribute(SERVER_FILL_ATTR) === token &&
1271
+ token === `${key}:${fill.campaignId}:${fill.variantId}` &&
1272
+ (this.runtime.allowHtml() || !wrapper.querySelector('.joryio-placement-html'));
1273
+ if (!ok) {
1274
+ this.dropServerFill(element, wrapper ?? null);
1275
+ return null;
1276
+ }
1277
+ attachServerShadowRoots(wrapper!);
1278
+ return { ...fill!, wrapper: wrapper! };
1279
+ }
1280
+
1281
+ private dropServerFill(element: HTMLElement, wrapper: HTMLElement | null): void {
1282
+ wrapper?.remove();
1283
+ element.removeAttribute?.(SERVER_FILLED_ATTR);
1284
+ element.removeAttribute?.('data-joryio-placement-state');
1285
+ }
1286
+
1287
+ /**
1288
+ * The slot was filled by the store's server: keep that drawing when this
1289
+ * visitor's answer is the same campaign, variant and products (no redraw),
1290
+ * else drop it. True when it was kept. Before any answer it stays as it is.
1291
+ */
1292
+ private settleServerFill(mount: Mount): 'kept' | 'dropped' | 'waiting' {
1293
+ const sf = mount.serverFill;
1294
+ if (!sf) return 'dropped';
1295
+ const entry = this.cache.get(mount.key);
1296
+ if (!entry) return 'waiting';
1297
+ mount.serverFill = null;
1298
+ const items = this.visibleItems(mount.key);
1299
+ const item = items[0];
1300
+ const products = toProducts(item?.products).map((p) => p.id);
1301
+ const html = !!sf.wrapper.querySelector('.joryio-placement-html');
1302
+ const same =
1303
+ items.length === 1 &&
1304
+ entry.placement.isControl !== true &&
1305
+ item.id === sf.campaignId &&
1306
+ (item.variantId ?? '') === sf.variantId &&
1307
+ products.length === sf.products.length &&
1308
+ products.every((id, i) => id === sf.products[i]) &&
1309
+ (item.content?.kind === 'html') === html &&
1310
+ (!html || this.runtime.allowHtml()) &&
1311
+ (mount.options.showProducts !== false || !products.length);
1312
+ if (!same) {
1313
+ this.dropServerFill(mount.element, sf.wrapper);
1314
+ return 'dropped';
1315
+ }
1316
+ mount.pendingUpdate = false;
1317
+ this.clearTrackers(mount);
1318
+ mount.wrapper = sf.wrapper;
1319
+ mount.shown = [item.deliveryId || item.id];
1320
+ mount.element.setAttribute('data-joryio-placement-state', 'filled');
1321
+ const node = (sf.wrapper.firstElementChild as HTMLElement | null) || sf.wrapper;
1322
+ this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));
1323
+ this.bindServerFill(mount, sf.wrapper, item);
1324
+ if (mount.options.onRender) {
1325
+ try {
1326
+ mount.options.onRender(this.toPlacement(mount.key), mount.element);
1327
+ } catch (error) {
1328
+ this.logger.error('The insertPlacement onRender callback threw; ignored:', error);
1329
+ }
1330
+ }
1331
+ return 'kept';
1332
+ }
1333
+
1334
+ /**
1335
+ * Clicks in a kept server drawing, with the SDK's own rules: a product card
1336
+ * reports `clicked` with placementProductElementId and opens through the
1337
+ * link router in a new tab; in HTML content an <a> or <button> reports the
1338
+ * frame's `link_click` / `cta_click` (or its data-action) and an http(s)
1339
+ * link opens in a new tab - inline content never navigates the page it
1340
+ * sits in. #anchors, mailto:, tel: and sms: are left to the browser.
1341
+ */
1342
+ private bindServerFill(mount: Mount, wrapper: HTMLElement, item: PlacementItemWire): void {
1343
+ wrapper.addEventListener(
1344
+ 'click',
1345
+ (event: Event) => {
1346
+ if (!this.mounts.has(mount) || mount.wrapper !== wrapper) return;
1347
+ const path = (typeof (event as any).composedPath === 'function' ? (event as any).composedPath() : [event.target]) as Element[];
1348
+ for (const el of path) {
1349
+ if (!el || el === wrapper || typeof (el as Element).getAttribute !== 'function') break;
1350
+ const productId = el.getAttribute('data-joryio-product');
1351
+ if (productId) {
1352
+ const href = el.getAttribute('href');
1353
+ if (href) event.preventDefault?.();
1354
+ this.buttonAction(mount, item, { id: placementProductElementId(productId), action: 'deep_link', url: href || undefined });
1355
+ return;
1356
+ }
1357
+ const tag = (el.tagName || '').toUpperCase();
1358
+ if (tag === 'A' || tag === 'BUTTON') {
1359
+ const href = tag === 'A' ? el.getAttribute('href') : null;
1360
+ if (hasUserGesture()) this.report(mount.key, item, 'clicked', el.getAttribute('data-action') || (href ? 'link_click' : 'cta_click'));
1361
+ if (href && !/^(#|mailto:|tel:|sms:)/i.test(href.trim())) {
1362
+ event.preventDefault?.();
1363
+ const safe = safeHttpUrl(href.trim());
1364
+ if (safe && hasUserGesture()) this.openLink(safe, { placementKey: mount.key, itemId: item.id }, () => window.open(safe, '_blank', 'noopener'));
1365
+ }
1366
+ return;
1367
+ }
1368
+ }
1369
+ },
1370
+ true,
1371
+ );
1372
+ }
1373
+
1030
1374
  private render(mount: Mount): void {
1031
1375
  if (!this.mounts.has(mount)) return;
1376
+ if (mount.serverFill && this.settleServerFill(mount) !== 'dropped') return;
1032
1377
  mount.pendingUpdate = false;
1033
1378
  this.clearTrackers(mount);
1034
1379
  this.clearDrawn(mount);
@@ -1056,7 +1401,10 @@ export class PlacementManager {
1056
1401
  wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
1057
1402
  if (placement.isControl && entry?.placement.controlToken) {
1058
1403
  // The holdout's exposure: the SPOT (the site's element) was viewable.
1059
- this.trackViewability(mount, mount.element, () => this.reportControl(mount.key));
1404
+ this.trackViewability(mount, mount.element, () => {
1405
+ this.reportControl(mount.key);
1406
+ this.markSpotViewable(mount.key);
1407
+ });
1060
1408
  }
1061
1409
  }
1062
1410
  if (mount.options.onRender) {
@@ -1417,6 +1765,25 @@ export class PlacementManager {
1417
1765
  }
1418
1766
 
1419
1767
  /** The wire's product cards, defensively typed: an entry without an id is dropped. */
1768
+ /**
1769
+ * A browser without declarative shadow DOM leaves the server's
1770
+ * `<template shadowrootmode="open">` inert: attach it here, as the parser
1771
+ * would have (D466).
1772
+ */
1773
+ export function attachServerShadowRoots(wrapper: HTMLElement): void {
1774
+ for (const host of Array.from(wrapper.querySelectorAll?.('.joryio-placement-html') || []) as HTMLElement[]) {
1775
+ if (host.shadowRoot || typeof host.attachShadow !== 'function') continue;
1776
+ const tpl = Array.from(host.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute('shadowrootmode') === 'open') as HTMLTemplateElement | undefined;
1777
+ if (!tpl) continue;
1778
+ try {
1779
+ host.attachShadow({ mode: 'open' }).appendChild(tpl.content);
1780
+ tpl.remove();
1781
+ } catch {
1782
+ // Left as it is: the template stays inert.
1783
+ }
1784
+ }
1785
+ }
1786
+
1420
1787
  export function toProducts(raw: unknown): PlacementProduct[] {
1421
1788
  if (!Array.isArray(raw)) return [];
1422
1789
  const str = (v: unknown) => (typeof v === 'string' ? v : null);