@joryio/web-sdk 1.4.0-beta.2 → 1.4.0-beta.5

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 (71) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +1 -1
  3. package/dist/cards-ui/card-feed-view.d.ts +4 -0
  4. package/dist/cards-ui/card-feed-view.d.ts.map +1 -0
  5. package/dist/cards-ui/index.d.ts +4 -0
  6. package/dist/cards-ui/index.d.ts.map +1 -0
  7. package/dist/core/cards-ui-contract.d.ts +30 -0
  8. package/dist/core/cards-ui-contract.d.ts.map +1 -0
  9. package/dist/core/cards.d.ts +131 -0
  10. package/dist/core/cards.d.ts.map +1 -0
  11. package/dist/core/config.d.ts +21 -1
  12. package/dist/core/config.d.ts.map +1 -1
  13. package/dist/core/editor-gate.d.ts +47 -0
  14. package/dist/core/editor-gate.d.ts.map +1 -0
  15. package/dist/core/flags.d.ts +74 -0
  16. package/dist/core/flags.d.ts.map +1 -0
  17. package/dist/core/inapp.d.ts +13 -1
  18. package/dist/core/inapp.d.ts.map +1 -1
  19. package/dist/core/links.d.ts +27 -0
  20. package/dist/core/links.d.ts.map +1 -0
  21. package/dist/core/network.d.ts.map +1 -1
  22. package/dist/core/page-context.d.ts +101 -0
  23. package/dist/core/page-context.d.ts.map +1 -0
  24. package/dist/core/page-edits.d.ts +129 -0
  25. package/dist/core/page-edits.d.ts.map +1 -0
  26. package/dist/core/placements.d.ts +219 -0
  27. package/dist/core/placements.d.ts.map +1 -0
  28. package/dist/core/sdk-host-files.d.ts +5 -0
  29. package/dist/core/sdk-host-files.d.ts.map +1 -0
  30. package/dist/core/sdk.d.ts +37 -0
  31. package/dist/core/sdk.d.ts.map +1 -1
  32. package/dist/core/subscription.d.ts +6 -0
  33. package/dist/core/subscription.d.ts.map +1 -0
  34. package/dist/editor/index.d.ts +4 -0
  35. package/dist/editor/index.d.ts.map +1 -0
  36. package/dist/editor/visual-editor.d.ts +39 -0
  37. package/dist/editor/visual-editor.d.ts.map +1 -0
  38. package/dist/index.d.mts +206 -3
  39. package/dist/index.d.ts +9 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/joryio-cards-ui.min.js +7 -0
  42. package/dist/joryio-cards-ui.min.js.map +1 -0
  43. package/dist/joryio-editor.min.js +7 -0
  44. package/dist/joryio-editor.min.js.map +1 -0
  45. package/dist/joryio-sw.js +1 -1
  46. package/dist/joryio.cjs.js +7215 -3508
  47. package/dist/joryio.min.js +2 -2
  48. package/dist/joryio.min.js.map +1 -1
  49. package/dist/joryio.mjs +7207 -3509
  50. package/dist/joryio.umd.js +7214 -3507
  51. package/package.json +4 -1
  52. package/src/cards-ui/card-feed-view.ts +249 -0
  53. package/src/cards-ui/index.ts +26 -0
  54. package/src/core/cards-ui-contract.ts +58 -0
  55. package/src/core/cards.ts +846 -0
  56. package/src/core/config.ts +86 -2
  57. package/src/core/editor-gate.ts +158 -0
  58. package/src/core/flags.ts +378 -0
  59. package/src/core/inapp.ts +283 -152
  60. package/src/core/links.ts +104 -0
  61. package/src/core/network.ts +3 -0
  62. package/src/core/page-context.ts +460 -0
  63. package/src/core/page-edits.ts +1036 -0
  64. package/src/core/placements.ts +1434 -0
  65. package/src/core/sdk-host-files.ts +93 -0
  66. package/src/core/sdk.ts +383 -1
  67. package/src/core/subscription.ts +27 -0
  68. package/src/editor/index.ts +27 -0
  69. package/src/editor/visual-editor.ts +301 -0
  70. package/src/index.ts +35 -0
  71. package/src/snippet/loader.js +25 -1
@@ -0,0 +1,1434 @@
1
+ /**
2
+ * Placements (docs/PLACEMENTS_PLAN.md, BACKLOG D444): named spots inside the
3
+ * page - `home_hero`, `cart_upsell` - that Joryio fills per visitor from
4
+ * placement campaigns and journey steps.
5
+ *
6
+ * Unlike overlays (inapp.ts) a placement is drawn INSIDE an element the site
7
+ * owns, or handed to the site as data to draw itself. The serve endpoint is
8
+ * `POST /v1/in-app/placements`; interactions are the in-app event family
9
+ * (`/v1/in-app/track`), with the placement key alongside.
10
+ *
11
+ * The rules this file implements, and the names every Joryio SDK shares
12
+ * (pinned by packages/backend/src/modules/tracking/sdk-placements-parity.spec.ts):
13
+ *
14
+ * - `insertPlacement(key, element)`, `<div data-joryio-placement="key">`
15
+ * auto-mount, `getPlacements([...])`, `refreshPlacements(keys?)`,
16
+ * `onPlacementsUpdated(cb)`; `item.markDisplayed()`, `markClicked()`,
17
+ * `markDismissed()`, `placement.markDisplayed()` (holdout exposure).
18
+ * - Batched: every key asked for within PLACEMENT_BATCH_WINDOW_MS goes in one
19
+ * request, at most PLACEMENT_MAX_KEYS_PER_REQUEST keys each.
20
+ * - Cached per key for the placement's `ttlSeconds` (memory + sessionStorage,
21
+ * scoped to the visitor), and a key is fetched from the network at most once
22
+ * per PLACEMENT_MIN_REFRESH_SECONDS; extra refreshes coalesce.
23
+ * - Viewable = at least PLACEMENT_VIEWABLE_FRACTION of the item in view for
24
+ * IN_APP_DISPLAY_DWELL_MS continuously, page visible; reported once per
25
+ * delivery.
26
+ * - Never swaps content under the reader's eyes: an update to a placement that
27
+ * is on screen is applied when it next leaves the viewport or is mounted again.
28
+ * - Consent: without tracking consent the request names nobody (no user id, no
29
+ * anonymous id, no session), the server answers with generic content and no
30
+ * delivery token, and the SDK reports nothing.
31
+ * - HTML items render in the same sandboxed, nonce-CSP frame as overlays, and
32
+ * only when `allowHtmlJsInAppMessages` is on.
33
+ */
34
+
35
+ import { JoryioSubscription, joryioSubscription } from './subscription';
36
+ import { bucketHash } from '../utils/bucket-hash';
37
+ import { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';
38
+ import { Logger } from '../utils/logger';
39
+ import { sdkIdentityHeaders } from './config';
40
+ import { IdentityManager } from './identity';
41
+ import { SessionManager } from './session';
42
+ import type { LinkContext, LinkRouter } from './links';
43
+ import {
44
+ buildInAppSrcdoc,
45
+ inAppTriggerFilterMatches,
46
+ normalizedElementId,
47
+ IN_APP_DISPLAY_DWELL_MS,
48
+ InAppAuthProvider,
49
+ InAppTrigger,
50
+ } from './inapp';
51
+
52
+ /** Share of an item that must be in view for it to count as seen. Same name and value on every Joryio SDK. */
53
+ export const PLACEMENT_VIEWABLE_FRACTION = 0.5;
54
+ /** A placement key is fetched from the network at most once per this many seconds. Same on every Joryio SDK. */
55
+ export const PLACEMENT_MIN_REFRESH_SECONDS = 30;
56
+ /** Keys asked for within this window go in one request. */
57
+ export const PLACEMENT_BATCH_WINDOW_MS = 50;
58
+ /** The serve endpoint takes 1-10 keys per request. */
59
+ export const PLACEMENT_MAX_KEYS_PER_REQUEST = 10;
60
+ /** How long an event-triggered item stays eligible after its event, when the server does not say. */
61
+ export const PLACEMENT_DEFAULT_TRIGGER_WINDOW_SECONDS = 1800;
62
+ /**
63
+ * A drawn product card's tap is reported as `clicked` with the elementId
64
+ * `product:<product id>` (at most 128 characters), so the click report counts
65
+ * clicks per product. Same name and value on every Joryio SDK.
66
+ */
67
+ export const PLACEMENT_PRODUCT_ELEMENT_PREFIX = 'product:';
68
+ /** Width of a drawn product card when the app does not set one (CSS px; points on iOS, dp on Android). Same on every Joryio SDK. */
69
+ export const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
70
+ /** The elementId a product card's click is reported with - use it when you draw the cards yourself. */
71
+ export function placementProductElementId(productId: string): string {
72
+ return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
73
+ }
74
+ /** Used when an answer carries no ttlSeconds. */
75
+ const DEFAULT_TTL_SECONDS = 300;
76
+ /** The pre-scoping, origin-wide name - never read, removed on start. */
77
+ const LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';
78
+ /**
79
+ * Per workspace, like the flags cache (flagsStorageKey): two workspaces on one
80
+ * site that know a visitor by the same ids must never read each other's
81
+ * placements. Carries a hash of the SDK key, never the key itself.
82
+ */
83
+ export const placementsStorageKey = (sdkKey: string): string => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;
84
+ /** The host-window object the placement HTML frames call into (overlays use their own). */
85
+ const PLACEMENT_BRIDGE_GLOBAL = '__joryioPlacement';
86
+ const PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;
87
+
88
+ export type PlacementEmptyBehavior = 'collapse' | 'keep_space';
89
+ export type PlacementItemKind = 'native' | 'html' | 'data';
90
+ /** The consent the request carries: the existing wire values. */
91
+ export type PlacementConsent = 'granted' | 'denied' | 'pending';
92
+
93
+ export type PlacementContent =
94
+ | { kind: 'html'; html: string; css?: string }
95
+ | {
96
+ kind: 'native';
97
+ title?: string;
98
+ body?: string;
99
+ imageUrl?: string;
100
+ buttons?: Array<{ id: string; text: string; action: string; url?: string }>;
101
+ closeButton?: boolean;
102
+ };
103
+
104
+ /** One item as the server sends it. */
105
+ /** A product card of a recommendation placement item (D444 Phase 2b). Same names on all five SDKs. */
106
+ export interface PlacementProduct {
107
+ id: string;
108
+ title: string | null;
109
+ price: string | null;
110
+ compareAtPrice: string | null;
111
+ discountPercent: number | null;
112
+ imageUrl: string | null;
113
+ url: string | null;
114
+ }
115
+
116
+ export interface PlacementItemWire {
117
+ id: string;
118
+ variantId?: string | null;
119
+ deliveryToken?: string | null;
120
+ priority?: number;
121
+ kind: PlacementItemKind;
122
+ data?: Record<string, string | number | boolean>;
123
+ content?: PlacementContent | null;
124
+ /** Products picked for the person by a recommendation model (absent = none). */
125
+ products?: PlacementProduct[] | null;
126
+ triggers?: InAppTrigger[] | null;
127
+ /** How long an event trigger keeps the item eligible (seconds). */
128
+ placementTriggerWindowSeconds?: number | null;
129
+ expiresAt?: string | null;
130
+ /** Echoed in `shown` when present; the item id otherwise. */
131
+ deliveryId?: string | null;
132
+ }
133
+
134
+ /** One placement as the server sends it. */
135
+ export interface PlacementWire {
136
+ placementKey: string;
137
+ emptyBehavior?: PlacementEmptyBehavior;
138
+ maxItems?: number;
139
+ ttlSeconds?: number;
140
+ isControl?: boolean;
141
+ controlToken?: string | null;
142
+ items?: PlacementItemWire[];
143
+ /**
144
+ * D444 Phase 4: the answer depends on the page (a campaign of this
145
+ * placement has page targeting), so it is cached per page (origin + path)
146
+ * and asked again on a route change.
147
+ */
148
+ pageScoped?: boolean;
149
+ }
150
+
151
+ export interface PlacementsResponse {
152
+ success: boolean;
153
+ evaluatedAt?: string;
154
+ placements?: Record<string, PlacementWire>;
155
+ }
156
+
157
+ /** An item to draw, with the calls that report what the person did with it. */
158
+ export interface PlacementItem {
159
+ id: string;
160
+ variantId?: string | null;
161
+ kind: PlacementItemKind;
162
+ data: Record<string, string | number | boolean>;
163
+ content?: PlacementContent | null;
164
+ /** Products picked for the person by a recommendation model; [] when the item has none. Draw them as cards. */
165
+ products: PlacementProduct[];
166
+ priority?: number;
167
+ expiresAt?: string | null;
168
+ /** Report a viewable impression (the app drew it itself). Once per delivery. */
169
+ markDisplayed(): void;
170
+ /** Report a tap or click; `elementId` names the button or link. */
171
+ markClicked(elementId?: string): void;
172
+ /** Report that the person closed it. The placement's dismissal rule applies on the server. */
173
+ markDismissed(): void;
174
+ }
175
+
176
+ export interface Placement {
177
+ placementKey: string;
178
+ items: PlacementItem[];
179
+ isControl: boolean;
180
+ emptyBehavior: PlacementEmptyBehavior;
181
+ maxItems: number;
182
+ ttlSeconds: number;
183
+ /**
184
+ * For a held-out visitor (`isControl`): report that the (empty) spot was
185
+ * viewable. Drawn placements do this themselves; a data-first app calls it
186
+ * when its spot was on screen. No-op for a placement that is not a control.
187
+ */
188
+ markDisplayed(): void;
189
+ }
190
+
191
+ export interface PlacementHandle {
192
+ placementKey: string;
193
+ element: HTMLElement;
194
+ /** Stop filling the element and remove what the SDK drew. */
195
+ remove(): void;
196
+ }
197
+
198
+ export interface InsertPlacementOptions {
199
+ /** Called after the SDK (re)drew the element, with what it drew. */
200
+ onRender?: (placement: Placement, element: HTMLElement) => void;
201
+ /**
202
+ * A `deep_link` button with an app link (`myapp://cart`) was tapped: route
203
+ * it in your app (the click is already reported). An http(s) link is opened
204
+ * by the SDK in a new tab instead, and any other scheme (javascript:, data:,
205
+ * intent:, ...) is refused - it reaches neither this handler nor the page.
206
+ * A handler set with `setLinkHandler` sees every link first; this one is
207
+ * called when it returns false.
208
+ */
209
+ onDeepLink?: (url: string, item: PlacementItem) => void;
210
+ /**
211
+ * Draw an item's recommended products as a horizontal row of cards (image,
212
+ * title, price, optional button) below its content - alone for a data item.
213
+ * Default true; false leaves the products to you (`onRender` / getPlacements).
214
+ */
215
+ showProducts?: boolean;
216
+ /** Label of a button on every product card; unset = no button (the whole card opens the product). */
217
+ productButtonText?: string;
218
+ /** Width of one product card in CSS px (default PLACEMENT_PRODUCT_CARD_WIDTH). */
219
+ productCardWidth?: number;
220
+ }
221
+
222
+ export type PlacementsUpdatedCallback = (placements: Record<string, Placement>) => void;
223
+
224
+ /** What the placement manager needs from the SDK. */
225
+ export interface PlacementRuntime {
226
+ /**
227
+ * The consent to send, or null when nothing may be sent at all (SDK not
228
+ * initialised, disabled, ingestion suspended). `granted` = personal serving
229
+ * and reporting; anything else = an anonymous request and no reporting.
230
+ */
231
+ consent: () => PlacementConsent | null;
232
+ allowHtml: () => boolean;
233
+ requestTimeoutMs?: number;
234
+ noteStatus?: (status: number, data: any) => void;
235
+ /** The SDK calls the HTML bridge reaches (custom events, attributes, push). */
236
+ bridge?: {
237
+ logCustomEvent: (name: string, properties?: Record<string, any>) => void;
238
+ setCustomUserAttribute: (key: string, value: any) => void;
239
+ changeUser: (userId: string) => void;
240
+ requestPushPermission: () => void;
241
+ };
242
+ }
243
+
244
+ interface CacheEntry {
245
+ placement: PlacementWire;
246
+ fetchedAt: number;
247
+ /** The page it was answered for (origin + path); matters only when `pageScoped`. */
248
+ url?: string | null;
249
+ }
250
+
251
+ interface Waiter {
252
+ keys: string[];
253
+ resolve: () => void;
254
+ }
255
+
256
+ interface Mount {
257
+ key: string;
258
+ element: HTMLElement;
259
+ options: InsertPlacementOptions;
260
+ wrapper: HTMLElement | null;
261
+ /** Item ids currently drawn (the `shown` list sent with the next request). */
262
+ shown: string[];
263
+ /** A newer answer that waits until the spot leaves the viewport. */
264
+ pendingUpdate: boolean;
265
+ /** Whether any part of the host element is in the viewport. */
266
+ hostInView: boolean;
267
+ hostObserver: IntersectionObserver | null;
268
+ trackers: ViewTracker[];
269
+ frameIds: string[];
270
+ }
271
+
272
+ const nowMs = () => Date.now();
273
+
274
+ function validKey(key: unknown): key is string {
275
+ return typeof key === 'string' && PLACEMENT_KEY_PATTERN.test(key);
276
+ }
277
+
278
+ /** The page address without query or fragment: context only, and query strings carry PII. */
279
+ function pageContext(): { url: string | null; screen: null } {
280
+ return { url: currentPageUrl(), screen: null };
281
+ }
282
+
283
+ /**
284
+ * Whether the page has a live user gesture. User activation propagates from a
285
+ * frame to its ancestors, so a click inside a placement frame activates the
286
+ * host page too; a call made by anything else (a timer, a synthetic event)
287
+ * finds none. Browsers without the API are trusted - the frame's nonce CSP
288
+ * already stops author script.
289
+ */
290
+ function hasUserGesture(): boolean {
291
+ try {
292
+ const activation = (navigator as any)?.userActivation;
293
+ return activation ? activation.isActive === true : true;
294
+ } catch {
295
+ return true;
296
+ }
297
+ }
298
+
299
+ /** An http(s) URL the SDK may open itself, or null. The one link rule of placements and content cards. */
300
+ export function safeHttpUrl(url: unknown): string | null {
301
+ return typeof url === 'string' && /^https?:\/\//i.test(url) ? url : null;
302
+ }
303
+
304
+ /** Schemes never opened nor handed to the site, whatever the link says (the backend's card / placement link rule). */
305
+ const REFUSED_LINK_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'blob', 'about', 'content', 'intent'];
306
+
307
+ /**
308
+ * An app deep link (`myapp://cart`) that may go to the site's own handler: a
309
+ * `scheme://` link whose scheme is not http(s) and not a refused one. The SDK
310
+ * never navigates to it itself. The same rule on every Joryio SDK.
311
+ */
312
+ export function isAppDeepLink(url: unknown): boolean {
313
+ if (typeof url !== 'string') return false;
314
+ const m = /^([a-z][a-z0-9+.-]*):\/\/./i.exec(url.trim());
315
+ if (!m) return false;
316
+ const scheme = m[1].toLowerCase();
317
+ return scheme !== 'http' && scheme !== 'https' && !REFUSED_LINK_SCHEMES.includes(scheme);
318
+ }
319
+
320
+ /** One element's viewability measurement (see trackViewable). */
321
+ export interface ViewTracker {
322
+ observer: IntersectionObserver | null;
323
+ timer: ReturnType<typeof setTimeout> | null;
324
+ inView: boolean;
325
+ /** Restart the dwell when the page becomes visible again. */
326
+ resume(): void;
327
+ /** Stop the dwell while the page is hidden. */
328
+ pause(): void;
329
+ /** Stop measuring for good. */
330
+ cancel(): void;
331
+ }
332
+
333
+ function pageIsVisible(): boolean {
334
+ return typeof document === 'undefined' || document.visibilityState !== 'hidden';
335
+ }
336
+
337
+ /**
338
+ * Call `onViewable` once `node` has had PLACEMENT_VIEWABLE_FRACTION of its
339
+ * area in view for IN_APP_DISPLAY_DWELL_MS continuously, with the page
340
+ * visible. Without IntersectionObserver (very old browsers) the page being
341
+ * visible for the dwell counts. Shared by placements and the card feed; the
342
+ * caller forwards page visibility changes to `resume` / `pause`.
343
+ */
344
+ export function trackViewable(node: Element, onViewable: () => void): ViewTracker {
345
+ let cancelled = false;
346
+ const tracker: ViewTracker = {
347
+ observer: null,
348
+ timer: null,
349
+ inView: false,
350
+ resume: () => {
351
+ if (cancelled || tracker.timer || !tracker.inView || !pageIsVisible()) return;
352
+ tracker.timer = setTimeout(() => {
353
+ tracker.timer = null;
354
+ if (!cancelled && tracker.inView && pageIsVisible()) {
355
+ cancelled = true;
356
+ tracker.observer?.disconnect();
357
+ onViewable();
358
+ }
359
+ }, IN_APP_DISPLAY_DWELL_MS);
360
+ },
361
+ pause: () => {
362
+ if (tracker.timer) clearTimeout(tracker.timer);
363
+ tracker.timer = null;
364
+ },
365
+ cancel: () => {
366
+ cancelled = true;
367
+ tracker.observer?.disconnect();
368
+ tracker.pause();
369
+ },
370
+ };
371
+ if (typeof IntersectionObserver === 'undefined') {
372
+ tracker.inView = true;
373
+ tracker.resume();
374
+ return tracker;
375
+ }
376
+ tracker.observer = new IntersectionObserver(
377
+ (entries) => {
378
+ for (const e of entries) {
379
+ // A zero-area target (a collapsed control spot) reports ratio 1 while intersecting.
380
+ tracker.inView = e.isIntersecting && e.intersectionRatio >= PLACEMENT_VIEWABLE_FRACTION;
381
+ if (tracker.inView) tracker.resume();
382
+ else tracker.pause();
383
+ }
384
+ },
385
+ { threshold: [0, PLACEMENT_VIEWABLE_FRACTION, 1] },
386
+ );
387
+ tracker.observer.observe(node);
388
+ return tracker;
389
+ }
390
+
391
+ export class PlacementManager {
392
+ /** The SDK's link router (`setLinkHandler`); set by the SDK after construction. */
393
+ links: LinkRouter | null = null;
394
+
395
+ private cache = new Map<string, CacheEntry>();
396
+ /** When each key last went to the network (the client rate limit). */
397
+ private lastNetworkAt = new Map<string, number>();
398
+ private inflight = new Map<string, Promise<void>>();
399
+ private batchKeys = new Set<string>();
400
+ private batchTimer: ReturnType<typeof setTimeout> | null = null;
401
+ private batchWaiters: Waiter[] = [];
402
+ /** Refreshes asked for inside the rate-limit window, run when it opens. */
403
+ private deferredKeys = new Set<string>();
404
+ private deferredTimer: ReturnType<typeof setTimeout> | null = null;
405
+ private listeners = new Set<PlacementsUpdatedCallback>();
406
+ private mounts = new Set<Mount>();
407
+ /** Delivery handles already reported, per transition (displayed once, control once). */
408
+ private reported = new Set<string>();
409
+ /** Event-triggered items: when their event fired. */
410
+ private triggeredAt = new Map<string, number>();
411
+ /** Items the person dismissed: hidden locally until the server's next answer. */
412
+ private dismissedLocally = new Set<string>();
413
+ /** Bumped when WHO the placements are for changes; older answers are discarded. */
414
+ private generation = 0;
415
+ private mutationObserver: MutationObserver | null = null;
416
+ private frames = new Map<string, { iframe: HTMLIFrameElement; key: string; item: PlacementItemWire }>();
417
+ private frameSeq = 0;
418
+ private pageListener: (() => void) | null = null;
419
+ private destroyed = false;
420
+ private page: PageContextTracker | null = null;
421
+ private pageUnsubscribe: (() => void) | null = null;
422
+
423
+ constructor(
424
+ private apiEndpoint: string,
425
+ private sdkKey: string,
426
+ private identity: IdentityManager,
427
+ private session: SessionManager,
428
+ private logger: Logger,
429
+ private runtime: PlacementRuntime,
430
+ private auth?: InAppAuthProvider,
431
+ ) {
432
+ this.loadCache();
433
+ this.installBridge();
434
+ this.installPageVisibility();
435
+ }
436
+
437
+ // ── public API ──────────────────────────────────────────────────────────
438
+
439
+ /** Draw placement `key` into `element`. Returns a handle whose remove() stops it. */
440
+ insertPlacement(key: string, element: HTMLElement, options: InsertPlacementOptions = {}): PlacementHandle | null {
441
+ if (!validKey(key)) {
442
+ this.logger.warn(`insertPlacement: "${key}" is not a placement key (a-z, 0-9 and _, up to 64)`);
443
+ return null;
444
+ }
445
+ if (!element || typeof (element as any).appendChild !== 'function') {
446
+ this.logger.warn('insertPlacement: an element is required');
447
+ return null;
448
+ }
449
+ for (const existing of this.mounts) {
450
+ if (existing.element === element) this.unmount(existing);
451
+ }
452
+ const mount: Mount = {
453
+ key,
454
+ element,
455
+ options,
456
+ wrapper: null,
457
+ shown: [],
458
+ pendingUpdate: false,
459
+ hostInView: false,
460
+ hostObserver: null,
461
+ trackers: [],
462
+ frameIds: [],
463
+ };
464
+ this.mounts.add(mount);
465
+ this.observeHost(mount);
466
+ const cached = this.freshEntry(key);
467
+ if (cached) this.render(mount);
468
+ this.ensure([key]).then(() => {
469
+ // Drawn already when the answer changed the cache (applyChanged); an
470
+ // unchanged or failed answer still draws what there is.
471
+ if (this.mounts.has(mount) && !mount.wrapper) this.render(mount);
472
+ }).catch((error) => this.logger.debug('Placement fetch failed:', error));
473
+ return { placementKey: key, element, remove: () => this.unmount(mount) };
474
+ }
475
+
476
+ /** The placements for `keys`, from the cache when fresh, from the network otherwise. */
477
+ async getPlacements(keys: string[]): Promise<Record<string, Placement>> {
478
+ const wanted = this.cleanKeys(keys);
479
+ await this.ensure(wanted);
480
+ const out: Record<string, Placement> = {};
481
+ for (const key of wanted) out[key] = this.toPlacement(key);
482
+ return out;
483
+ }
484
+
485
+ /** Ask the server again for `keys` (default: every placement on the page or in the cache). */
486
+ async refreshPlacements(keys?: string[]): Promise<void> {
487
+ const wanted = keys ? this.cleanKeys(keys) : this.knownKeys();
488
+ if (!wanted.length) return;
489
+ await this.fetchKeys(wanted, true);
490
+ }
491
+
492
+ /** Called with the placements that changed after each answer. Returns a JoryioSubscription. */
493
+ onPlacementsUpdated(callback: PlacementsUpdatedCallback): JoryioSubscription {
494
+ if (typeof callback !== 'function') return joryioSubscription(() => undefined);
495
+ // One entry per subscription, so the same function subscribed twice is two subscriptions.
496
+ const entry: PlacementsUpdatedCallback = (placements) => callback(placements);
497
+ this.listeners.add(entry);
498
+ return joryioSubscription(() => {
499
+ this.listeners.delete(entry);
500
+ });
501
+ }
502
+
503
+ /** Mount every `[data-joryio-placement]` element on the page, now and as the page changes. */
504
+ autoMount(): void {
505
+ if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
506
+ if (document.readyState === 'loading' && typeof document.addEventListener === 'function') {
507
+ // The script ran in <head>: the elements are not parsed yet.
508
+ document.addEventListener('DOMContentLoaded', () => !this.destroyed && this.autoMount(), { once: true });
509
+ return;
510
+ }
511
+ this.scanDocument();
512
+ if (this.mutationObserver || typeof MutationObserver === 'undefined' || !document.body) return;
513
+ this.mutationObserver = new MutationObserver(() => this.scanDocument());
514
+ this.mutationObserver.observe(document.body, { childList: true, subtree: true });
515
+ }
516
+
517
+ /** An event was tracked: event-triggered items waiting on it become eligible. */
518
+ onEventTracked(eventName: string, properties?: Record<string, any>): void {
519
+ if (!eventName) return;
520
+ const changed = new Set<string>();
521
+ for (const [key, entry] of this.cache) {
522
+ for (const item of entry.placement.items || []) {
523
+ const match = (item.triggers || []).some(
524
+ (t) => t.type === 'event' && t.event === eventName && inAppTriggerFilterMatches(t, properties),
525
+ );
526
+ if (match) {
527
+ this.triggeredAt.set(this.handle(key, item), nowMs());
528
+ changed.add(key);
529
+ }
530
+ }
531
+ }
532
+ if (changed.size) this.applyChanged(Array.from(changed));
533
+ }
534
+
535
+ /**
536
+ * The visitor changed (identify, reset, consent): forget every answer and
537
+ * ask again for the placements on the page.
538
+ */
539
+ invalidate(): void {
540
+ this.generation++;
541
+ this.cache.clear();
542
+ this.lastNetworkAt.clear();
543
+ this.triggeredAt.clear();
544
+ this.dismissedLocally.clear();
545
+ this.reported.clear();
546
+ this.persistCache();
547
+ const keys = this.mountedKeys();
548
+ // The previous person's content goes NOW, on screen or not: it must not
549
+ // stay in front of the next person, nor report against them.
550
+ for (const mount of this.mounts) this.render(mount);
551
+ if (keys.length) this.fetchKeys(keys, true).catch(() => undefined);
552
+ }
553
+
554
+ destroy(): void {
555
+ this.destroyed = true;
556
+ this.pageUnsubscribe?.();
557
+ this.pageUnsubscribe = null;
558
+ for (const mount of Array.from(this.mounts)) this.unmount(mount);
559
+ this.mutationObserver?.disconnect();
560
+ this.mutationObserver = null;
561
+ if (this.batchTimer) clearTimeout(this.batchTimer);
562
+ if (this.deferredTimer) clearTimeout(this.deferredTimer);
563
+ this.batchTimer = null;
564
+ this.deferredTimer = null;
565
+ this.batchWaiters.forEach((w) => w.resolve());
566
+ this.batchWaiters = [];
567
+ this.listeners.clear();
568
+ if (this.pageListener && typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
569
+ document.removeEventListener('visibilitychange', this.pageListener);
570
+ }
571
+ try {
572
+ if (typeof window !== 'undefined' && (window as any)[PLACEMENT_BRIDGE_GLOBAL]?.__owner === this) {
573
+ delete (window as any)[PLACEMENT_BRIDGE_GLOBAL];
574
+ }
575
+ } catch {
576
+ /* ignore */
577
+ }
578
+ }
579
+
580
+ // ── fetching ────────────────────────────────────────────────────────────
581
+
582
+ private cleanKeys(keys: string[]): string[] {
583
+ const out: string[] = [];
584
+ for (const key of Array.isArray(keys) ? keys : []) {
585
+ if (validKey(key) && !out.includes(key)) out.push(key);
586
+ else if (!validKey(key)) this.logger.warn(`Ignoring "${key}": not a placement key`);
587
+ }
588
+ return out;
589
+ }
590
+
591
+ private knownKeys(): string[] {
592
+ return Array.from(new Set([...this.mountedKeys(), ...this.cache.keys()]));
593
+ }
594
+
595
+ private mountedKeys(): string[] {
596
+ return Array.from(new Set(Array.from(this.mounts).map((m) => m.key)));
597
+ }
598
+
599
+ /**
600
+ * Page context (D444 Phase 4): requests carry the page (URL without query,
601
+ * allow-listed variables), and a page-scoped answer is good for its page
602
+ * only - on a route change it goes, and the spot asks again.
603
+ */
604
+ setPageContext(tracker: PageContextTracker | null): void {
605
+ this.pageUnsubscribe?.();
606
+ this.pageUnsubscribe = null;
607
+ this.page = tracker;
608
+ if (!tracker) return;
609
+ this.pageUnsubscribe = tracker.onSignal((signal) => {
610
+ if (signal.type !== 'page_change' || this.destroyed) return;
611
+ const stale: string[] = [];
612
+ this.cache.forEach((entry, key) => {
613
+ if (entry.placement.pageScoped && entry.url !== signal.url) stale.push(key);
614
+ });
615
+ if (!stale.length) return;
616
+ stale.forEach((key) => this.cache.delete(key));
617
+ this.persistCache();
618
+ // The old page's item must not stay on the new page while the answer is on its way.
619
+ for (const mount of this.mounts) if (stale.includes(mount.key)) this.render(mount);
620
+ const mounted = stale.filter((key) => this.mountedKeys().includes(key));
621
+ if (mounted.length) {
622
+ this.fetchKeys(mounted, false)
623
+ .then(() => {
624
+ for (const mount of this.mounts) if (mounted.includes(mount.key) && !mount.wrapper) this.render(mount);
625
+ })
626
+ .catch(() => undefined);
627
+ }
628
+ });
629
+ }
630
+
631
+ private currentUrl(): string | null {
632
+ return this.page ? this.page.current().url : currentPageUrl();
633
+ }
634
+
635
+ /** The rate-limit key: per page for a page-scoped placement, so a route change can ask again at once. */
636
+ private rateKey(key: string): string {
637
+ return this.cache.get(key)?.placement.pageScoped || this.pageScopedKeys.has(key) ? `${key}\u0000${this.currentUrl() ?? ''}` : key;
638
+ }
639
+ private pageScopedKeys = new Set<string>();
640
+
641
+ private freshEntry(key: string): CacheEntry | null {
642
+ const entry = this.cache.get(key);
643
+ if (!entry) return null;
644
+ if (entry.placement.pageScoped && entry.url !== this.currentUrl()) return null;
645
+ const ttl = (entry.placement.ttlSeconds || DEFAULT_TTL_SECONDS) * 1000;
646
+ return nowMs() - entry.fetchedAt < ttl ? entry : null;
647
+ }
648
+
649
+ /** Fresh from the cache, or fetched (never more often than the rate limit allows). */
650
+ private async ensure(keys: string[]): Promise<void> {
651
+ const stale = keys.filter((key) => !this.freshEntry(key));
652
+ if (stale.length) await this.fetchKeys(stale, false);
653
+ }
654
+
655
+ /**
656
+ * Fetch `keys`, batched with every other key asked for in the next
657
+ * PLACEMENT_BATCH_WINDOW_MS. A key fetched less than
658
+ * PLACEMENT_MIN_REFRESH_SECONDS ago is not fetched again: a forced refresh
659
+ * is deferred to when the window opens, anything else is served the cache.
660
+ */
661
+ private fetchKeys(keys: string[], force: boolean): Promise<void> {
662
+ const now = nowMs();
663
+ const waits: Promise<void>[] = [];
664
+ const due: string[] = [];
665
+ for (const key of keys) {
666
+ const inflight = this.inflight.get(key);
667
+ if (inflight) {
668
+ waits.push(inflight);
669
+ if (force) this.defer(key);
670
+ continue;
671
+ }
672
+ const last = this.lastNetworkAt.get(this.rateKey(key));
673
+ if (last !== undefined && now - last < PLACEMENT_MIN_REFRESH_SECONDS * 1000) {
674
+ if (force) this.defer(key);
675
+ continue;
676
+ }
677
+ due.push(key);
678
+ }
679
+ if (due.length) {
680
+ due.forEach((key) => this.batchKeys.add(key));
681
+ const batched = new Promise<void>((resolve) => this.batchWaiters.push({ keys: due, resolve }));
682
+ due.forEach((key) => this.inflight.set(key, batched));
683
+ if (!this.batchTimer) this.batchTimer = setTimeout(() => void this.flushBatch(), PLACEMENT_BATCH_WINDOW_MS);
684
+ waits.push(batched);
685
+ }
686
+ return Promise.all(waits).then(() => undefined);
687
+ }
688
+
689
+ private defer(key: string): void {
690
+ this.deferredKeys.add(key);
691
+ if (this.deferredTimer) return;
692
+ const last = Math.min(...Array.from(this.deferredKeys).map((k) => this.lastNetworkAt.get(this.rateKey(k)) ?? 0));
693
+ const wait = Math.max(0, last + PLACEMENT_MIN_REFRESH_SECONDS * 1000 - nowMs());
694
+ this.deferredTimer = setTimeout(() => {
695
+ this.deferredTimer = null;
696
+ const keys = Array.from(this.deferredKeys);
697
+ this.deferredKeys.clear();
698
+ if (keys.length && !this.destroyed) this.fetchKeys(keys, false).catch(() => undefined);
699
+ }, wait + 10);
700
+ }
701
+
702
+ private async flushBatch(): Promise<void> {
703
+ this.batchTimer = null;
704
+ const keys = Array.from(this.batchKeys);
705
+ this.batchKeys.clear();
706
+ const waiters = this.batchWaiters;
707
+ this.batchWaiters = [];
708
+ const chunks: string[][] = [];
709
+ for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {
710
+ chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));
711
+ }
712
+ try {
713
+ await Promise.all(chunks.map((chunk) => this.request(chunk)));
714
+ } finally {
715
+ keys.forEach((key) => this.inflight.delete(key));
716
+ waiters.forEach((w) => w.resolve());
717
+ }
718
+ }
719
+
720
+ private async request(keys: string[]): Promise<void> {
721
+ const consent = this.runtime.consent();
722
+ if (consent === null || this.destroyed) return;
723
+ const generation = this.generation;
724
+ const personal = consent === 'granted';
725
+ const sentAt = nowMs();
726
+ keys.forEach((key) => this.lastNetworkAt.set(this.rateKey(key), sentAt));
727
+ const askedFor = this.currentUrl();
728
+
729
+ const shown: Record<string, string[]> = {};
730
+ for (const mount of this.mounts) {
731
+ if (keys.includes(mount.key) && mount.shown.length) shown[mount.key] = mount.shown.slice();
732
+ }
733
+ const userId = personal ? this.identity.getUserId() : null;
734
+ const anonymousId = personal ? this.identity.getAnonymousId() : null;
735
+ const body: Record<string, any> = {
736
+ ...(userId ? { userId } : {}),
737
+ ...(anonymousId ? { anonymousId } : {}),
738
+ ...(personal ? { sessionId: this.session.getSessionId() } : {}),
739
+ deviceType: 'web',
740
+ locale: typeof navigator !== 'undefined' ? navigator.language : undefined,
741
+ capabilities: this.capabilities(),
742
+ trackingConsent: consent,
743
+ placements: keys,
744
+ shown,
745
+ context: this.page ? { ...this.page.current(), screen: null } : pageContext(),
746
+ };
747
+
748
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
749
+ const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);
750
+ const url = `${this.apiEndpoint}/v1/in-app/placements`;
751
+ try {
752
+ const response = await fetch(url, {
753
+ method: 'POST',
754
+ headers: {
755
+ 'Content-Type': 'application/json',
756
+ 'X-SDK-Key': this.sdkKey,
757
+ ...sdkIdentityHeaders(),
758
+ // Only a consented request carries the visitor's auth: an
759
+ // unconsented one names nobody.
760
+ ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),
761
+ },
762
+ body: JSON.stringify(body),
763
+ ...(controller ? { signal: controller.signal } : {}),
764
+ });
765
+ if (!response.ok) {
766
+ // 429 (the per-device limit) and every other failure: keep the cache.
767
+ this.runtime.noteStatus?.(response.status, null);
768
+ this.logger.debug(`Placements request answered ${response.status}; keeping the cached placements`);
769
+ return;
770
+ }
771
+ const data: PlacementsResponse = await response.json();
772
+ if (generation !== this.generation) {
773
+ this.logger.debug('Discarding a placements answer that predates an identity or consent change');
774
+ return;
775
+ }
776
+ if (!data || data.success === false || !data.placements || typeof data.placements !== 'object') return;
777
+ const fetchedAt = nowMs();
778
+ const changed: string[] = [];
779
+ for (const key of keys) {
780
+ // A key the server left out is an empty placement (never an error).
781
+ const wire = data.placements[key] || { placementKey: key, items: [] };
782
+ const normalized = this.normalize(key, wire);
783
+ const before = this.cache.get(key);
784
+ this.cache.set(key, { placement: normalized, fetchedAt, url: askedFor });
785
+ if (normalized.pageScoped) this.pageScopedKeys.add(key);
786
+ else this.pageScopedKeys.delete(key);
787
+ // The server's answer already applied the dismissal rule.
788
+ for (const handle of Array.from(this.dismissedLocally)) {
789
+ if (handle.startsWith(`${key}\u0000`)) this.dismissedLocally.delete(handle);
790
+ }
791
+ if (!before || JSON.stringify(before.placement) !== JSON.stringify(normalized)) changed.push(key);
792
+ }
793
+ this.persistCache();
794
+ if (changed.length) this.applyChanged(changed);
795
+ } catch (error) {
796
+ const timedOut = (error as any)?.name === 'AbortError';
797
+ this.logger.debug(timedOut ? 'Placements request timed out' : 'Placements request failed', error);
798
+ } finally {
799
+ clearTimeout(timeout);
800
+ }
801
+ }
802
+
803
+ private capabilities(): string[] {
804
+ const caps = ['placements', 'content.native', 'content.data'];
805
+ if (this.page) caps.push(PAGE_CONTEXT_CAPABILITY);
806
+ if (this.runtime.allowHtml()) caps.push('content.html');
807
+ return caps;
808
+ }
809
+
810
+ private normalize(key: string, wire: PlacementWire): PlacementWire {
811
+ const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];
812
+ return {
813
+ placementKey: key,
814
+ emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse',
815
+ maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1,
816
+ ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS,
817
+ isControl: wire.isControl === true,
818
+ controlToken: wire.controlToken || null,
819
+ items,
820
+ ...(wire.pageScoped === true ? { pageScoped: true } : {}),
821
+ };
822
+ }
823
+
824
+ /** Re-draw mounted placements and tell listeners, for keys whose answer changed. */
825
+ private applyChanged(keys: string[]): void {
826
+ for (const mount of this.mounts) {
827
+ if (!keys.includes(mount.key)) continue;
828
+ // Never under the reader's eyes: applied when the spot leaves the viewport.
829
+ if (mount.hostInView && mount.shown.length) mount.pendingUpdate = true;
830
+ else this.render(mount);
831
+ }
832
+ if (!this.listeners.size) return;
833
+ const update: Record<string, Placement> = {};
834
+ keys.forEach((key) => (update[key] = this.toPlacement(key)));
835
+ for (const listener of Array.from(this.listeners)) {
836
+ try {
837
+ listener(update);
838
+ } catch (error) {
839
+ this.logger.error('The onPlacementsUpdated callback threw; ignored:', error);
840
+ }
841
+ }
842
+ }
843
+
844
+ // ── what is eligible now ────────────────────────────────────────────────
845
+
846
+ private handle(key: string, item: PlacementItemWire): string {
847
+ return `${key}\u0000${item.deliveryToken || item.id}`;
848
+ }
849
+
850
+ /** The items to show now: not expired, not dismissed here, triggered when they wait on an event. */
851
+ private visibleItems(key: string): PlacementItemWire[] {
852
+ const entry = this.cache.get(key);
853
+ if (!entry) return [];
854
+ const now = nowMs();
855
+ const max = entry.placement.maxItems || 1;
856
+ return (entry.placement.items || [])
857
+ .filter((item) => {
858
+ if (item.expiresAt && Date.parse(item.expiresAt) <= now) return false;
859
+ if (this.dismissedLocally.has(this.handle(key, item))) return false;
860
+ const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');
861
+ if (eventTriggers.length) {
862
+ const at = this.triggeredAt.get(this.handle(key, item));
863
+ const windowS = item.placementTriggerWindowSeconds || PLACEMENT_DEFAULT_TRIGGER_WINDOW_SECONDS;
864
+ if (at === undefined || now - at > windowS * 1000) return false;
865
+ }
866
+ return true;
867
+ })
868
+ .slice(0, max);
869
+ }
870
+
871
+ private toPlacement(key: string): Placement {
872
+ const entry = this.cache.get(key);
873
+ const wire = entry?.placement || this.normalize(key, { placementKey: key, items: [] });
874
+ const generation = this.generation;
875
+ return {
876
+ placementKey: key,
877
+ items: this.visibleItems(key).map((item) => this.toItem(key, item, generation)),
878
+ isControl: wire.isControl === true,
879
+ emptyBehavior: wire.emptyBehavior || 'collapse',
880
+ maxItems: wire.maxItems || 1,
881
+ ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,
882
+ markDisplayed: () => this.current(generation) && this.reportControl(key),
883
+ };
884
+ }
885
+
886
+ /** Created for the person still here? A Placement / item outlives an identify or reset: then it reports nothing. */
887
+ private current(generation: number): boolean {
888
+ return generation === this.generation;
889
+ }
890
+
891
+ private toItem(key: string, item: PlacementItemWire, generation: number): PlacementItem {
892
+ return {
893
+ id: item.id,
894
+ variantId: item.variantId ?? null,
895
+ kind: item.kind,
896
+ data: { ...(item.data || {}) },
897
+ content: item.content ?? null,
898
+ products: toProducts(item.products),
899
+ priority: item.priority,
900
+ expiresAt: item.expiresAt ?? null,
901
+ markDisplayed: () => this.current(generation) && this.report(key, item, 'displayed'),
902
+ markClicked: (elementId?: string) => this.current(generation) && this.report(key, item, 'clicked', elementId),
903
+ markDismissed: () => this.current(generation) && this.dismissItem(key, item),
904
+ };
905
+ }
906
+
907
+ // ── reporting ───────────────────────────────────────────────────────────
908
+
909
+ private dismissItem(key: string, item: PlacementItemWire): void {
910
+ this.report(key, item, 'dismissed');
911
+ this.dismissedLocally.add(this.handle(key, item));
912
+ for (const mount of this.mounts) if (mount.key === key) this.render(mount);
913
+ }
914
+
915
+ /**
916
+ * Report a transition to `/v1/in-app/track`. Only with consent (an
917
+ * unconsented answer carries no delivery token and nothing is reported).
918
+ * `displayed` once per delivery; a click or dismiss first counts the item
919
+ * as displayed - the person saw it.
920
+ */
921
+ private report(key: string, item: PlacementItemWire, type: 'displayed' | 'clicked' | 'dismissed', elementId?: string): void {
922
+ if (this.runtime.consent() !== 'granted') return;
923
+ const once = `${type}:${this.handle(key, item)}`;
924
+ if (type !== 'clicked') {
925
+ if (this.reported.has(once)) return;
926
+ this.reported.add(once);
927
+ }
928
+ if (type !== 'displayed') this.report(key, item, 'displayed');
929
+ const at = new Date().toISOString();
930
+ const normalizedId = normalizedElementId(elementId);
931
+ const body: Record<string, any> = {
932
+ campaignId: item.id,
933
+ ...(item.variantId ? { variantId: item.variantId } : {}),
934
+ ...(item.deliveryToken ? { deliveryToken: item.deliveryToken } : {}),
935
+ placementKey: key,
936
+ ...this.subject(),
937
+ sessionId: this.session.getSessionId(),
938
+ deviceType: 'web',
939
+ ...(type === 'displayed' ? { action: 'displayed', displayedAt: at } : {}),
940
+ ...(type === 'clicked' ? { action: 'clicked', clicked: true, clickedAt: at, ...(normalizedId ? { elementId: normalizedId } : {}) } : {}),
941
+ ...(type === 'dismissed' ? { action: 'dismissed', dismissedAt: at } : {}),
942
+ };
943
+ this.post('/v1/in-app/track', body);
944
+ }
945
+
946
+ /**
947
+ * A held-out visitor's empty spot was viewable: `in_app.control_viewed`,
948
+ * once per control token. The token (from the answer) names the placement,
949
+ * the campaign when it was a campaign control variant, and the visitor.
950
+ */
951
+ private reportControl(key: string): void {
952
+ const entry = this.cache.get(key);
953
+ if (!entry?.placement.isControl || !entry.placement.controlToken) return;
954
+ if (this.runtime.consent() !== 'granted') return;
955
+ const once = `control:${entry.placement.controlToken}`;
956
+ if (this.reported.has(once)) return;
957
+ this.reported.add(once);
958
+ this.post('/v1/in-app/track', {
959
+ action: 'control_viewed',
960
+ controlToken: entry.placement.controlToken,
961
+ placementKey: key,
962
+ ...this.subject(),
963
+ sessionId: this.session.getSessionId(),
964
+ deviceType: 'web',
965
+ viewedAt: new Date().toISOString(),
966
+ });
967
+ }
968
+
969
+ private subject(): { userId?: string; anonymousId: string } {
970
+ const userId = this.identity.getUserId();
971
+ return { ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId() };
972
+ }
973
+
974
+ private post(path: string, body: Record<string, any>): void {
975
+ const userId = typeof body.userId === 'string' ? body.userId : null;
976
+ fetch(`${this.apiEndpoint}${path}`, {
977
+ method: 'POST',
978
+ headers: {
979
+ 'Content-Type': 'application/json',
980
+ 'X-SDK-Key': this.sdkKey,
981
+ ...sdkIdentityHeaders(),
982
+ ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : body.anonymousId ?? null) || {}),
983
+ },
984
+ body: JSON.stringify(body),
985
+ keepalive: true,
986
+ })
987
+ .then((response) => {
988
+ if (!response.ok) this.runtime.noteStatus?.(response.status, null);
989
+ })
990
+ .catch((error) => this.logger.debug(`Placement report to ${path} failed`, error));
991
+ }
992
+
993
+ // ── drawing ─────────────────────────────────────────────────────────────
994
+
995
+ private scanDocument(): void {
996
+ if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;
997
+ // Elements removed from the page stop being filled.
998
+ for (const mount of Array.from(this.mounts)) {
999
+ if ((mount.element as any).isConnected === false) this.unmount(mount);
1000
+ }
1001
+ const mountedElements = new Set(Array.from(this.mounts).map((m) => m.element));
1002
+ document.querySelectorAll<HTMLElement>('[data-joryio-placement]').forEach((element) => {
1003
+ if (mountedElements.has(element)) return;
1004
+ const key = element.getAttribute('data-joryio-placement');
1005
+ if (key) this.insertPlacement(key, element);
1006
+ });
1007
+ }
1008
+
1009
+ private unmount(mount: Mount): void {
1010
+ this.mounts.delete(mount);
1011
+ mount.hostObserver?.disconnect();
1012
+ this.clearTrackers(mount);
1013
+ this.clearDrawn(mount);
1014
+ mount.element.removeAttribute?.('data-joryio-placement-state');
1015
+ }
1016
+
1017
+ private clearTrackers(mount: Mount): void {
1018
+ for (const t of mount.trackers) t.cancel();
1019
+ mount.trackers = [];
1020
+ }
1021
+
1022
+ private clearDrawn(mount: Mount): void {
1023
+ mount.frameIds.forEach((id) => this.frames.delete(id));
1024
+ mount.frameIds = [];
1025
+ mount.wrapper?.remove();
1026
+ mount.wrapper = null;
1027
+ mount.shown = [];
1028
+ }
1029
+
1030
+ private render(mount: Mount): void {
1031
+ if (!this.mounts.has(mount)) return;
1032
+ mount.pendingUpdate = false;
1033
+ this.clearTrackers(mount);
1034
+ this.clearDrawn(mount);
1035
+ const placement = this.toPlacement(mount.key);
1036
+ const entry = this.cache.get(mount.key);
1037
+ const wrapper = document.createElement('div');
1038
+ wrapper.className = 'joryio-placement';
1039
+ wrapper.setAttribute('data-joryio-placement-key', mount.key);
1040
+ const drawn: PlacementItemWire[] = [];
1041
+ for (const item of this.visibleItems(mount.key)) {
1042
+ const node = this.drawItem(mount, item);
1043
+ if (!node) continue;
1044
+ wrapper.appendChild(node);
1045
+ drawn.push(item);
1046
+ this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));
1047
+ }
1048
+ mount.shown = drawn.map((item) => item.deliveryId || item.id);
1049
+ mount.element.appendChild(wrapper);
1050
+ mount.wrapper = wrapper;
1051
+ const state = drawn.length ? 'filled' : placement.isControl ? 'control' : 'empty';
1052
+ mount.element.setAttribute('data-joryio-placement-state', state);
1053
+ if (!drawn.length) {
1054
+ // collapse: nothing drawn, the wrapper takes no space. keep_space: the
1055
+ // element keeps whatever box the site gave it.
1056
+ wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';
1057
+ if (placement.isControl && entry?.placement.controlToken) {
1058
+ // The holdout's exposure: the SPOT (the site's element) was viewable.
1059
+ this.trackViewability(mount, mount.element, () => this.reportControl(mount.key));
1060
+ }
1061
+ }
1062
+ if (mount.options.onRender) {
1063
+ try {
1064
+ mount.options.onRender(placement, mount.element);
1065
+ } catch (error) {
1066
+ this.logger.error('The insertPlacement onRender callback threw; ignored:', error);
1067
+ }
1068
+ }
1069
+ }
1070
+
1071
+ private drawItem(mount: Mount, item: PlacementItemWire): HTMLElement | null {
1072
+ const content = item.content;
1073
+ let node: HTMLElement | null = null;
1074
+ if (content?.kind === 'html') {
1075
+ if (!this.runtime.allowHtml()) {
1076
+ this.logger.warn(`Placement ${mount.key}: HTML item skipped (allowHtmlJsInAppMessages is off)`);
1077
+ return null;
1078
+ }
1079
+ node = this.drawHtml(mount, item, content);
1080
+ } else if (content?.kind === 'native') {
1081
+ node = this.drawNative(mount, item, content);
1082
+ } else if (content) {
1083
+ return null;
1084
+ }
1085
+ // Recommended products: a row of cards below the content, or alone for a
1086
+ // data item (without products a data item is the app's to draw).
1087
+ const products = mount.options.showProducts === false ? [] : toProducts(item.products);
1088
+ if (!products.length) return node;
1089
+ const row = this.drawProducts(mount, item, products);
1090
+ if (!node) return row;
1091
+ const box = document.createElement('div');
1092
+ box.className = 'joryio-placement-item';
1093
+ box.setAttribute('data-joryio-item', item.id);
1094
+ box.appendChild(node);
1095
+ box.appendChild(row);
1096
+ return box;
1097
+ }
1098
+
1099
+ /**
1100
+ * The built-in product cards: a horizontally scrolling row, one card per
1101
+ * product (image, title, price - the compare-at price struck through - and
1102
+ * the optional button). A tap reports `clicked` with
1103
+ * placementProductElementId and opens the product's link the way a
1104
+ * `deep_link` button does: http(s) in a new tab, an app link to the
1105
+ * handlers, anything else refused. Styled with the joryio-placement-product*
1106
+ * classes.
1107
+ */
1108
+ private drawProducts(mount: Mount, item: PlacementItemWire, products: PlacementProduct[]): HTMLElement {
1109
+ const row = document.createElement('div');
1110
+ row.className = 'joryio-placement-products';
1111
+ row.setAttribute('data-joryio-item', item.id);
1112
+ row.style.cssText = 'display:flex;gap:8px;overflow-x:auto;box-sizing:border-box;';
1113
+ const requested = Number(mount.options.productCardWidth);
1114
+ const width = Number.isFinite(requested) && requested > 0 ? requested : PLACEMENT_PRODUCT_CARD_WIDTH;
1115
+ for (const p of products) {
1116
+ const card = document.createElement('div');
1117
+ card.className = 'joryio-placement-product';
1118
+ card.setAttribute('data-joryio-product', p.id);
1119
+ card.style.cssText = `flex:0 0 ${width}px;width:${width}px;box-sizing:border-box;`;
1120
+ const open = p.url ? () => this.buttonAction(mount, item, { id: placementProductElementId(p.id), action: 'deep_link', url: p.url! }) : null;
1121
+ const image = safeHttpUrl(p.imageUrl);
1122
+ if (image) {
1123
+ const img = document.createElement('img');
1124
+ img.className = 'joryio-placement-product-image';
1125
+ img.src = image;
1126
+ img.alt = p.title || '';
1127
+ img.style.cssText = 'display:block;width:100%;aspect-ratio:1/1;object-fit:cover;';
1128
+ card.appendChild(img);
1129
+ }
1130
+ if (p.title) {
1131
+ const title = document.createElement('div');
1132
+ title.className = 'joryio-placement-product-title';
1133
+ title.textContent = p.title;
1134
+ card.appendChild(title);
1135
+ }
1136
+ if (p.price) {
1137
+ const price = document.createElement('div');
1138
+ price.className = 'joryio-placement-product-price';
1139
+ price.textContent = p.price;
1140
+ if (p.compareAtPrice) {
1141
+ const was = document.createElement('s');
1142
+ was.className = 'joryio-placement-product-compare';
1143
+ was.textContent = p.compareAtPrice;
1144
+ was.style.cssText = 'margin-inline-start:6px;opacity:0.6;';
1145
+ price.appendChild(was);
1146
+ }
1147
+ card.appendChild(price);
1148
+ }
1149
+ if (open && mount.options.productButtonText) {
1150
+ const btn = document.createElement('button');
1151
+ btn.type = 'button';
1152
+ btn.className = 'joryio-placement-product-button';
1153
+ btn.textContent = mount.options.productButtonText;
1154
+ btn.addEventListener('click', (e?: Event) => {
1155
+ e?.stopPropagation?.();
1156
+ open();
1157
+ });
1158
+ card.appendChild(btn);
1159
+ }
1160
+ if (open) {
1161
+ card.setAttribute('role', 'link');
1162
+ card.tabIndex = 0;
1163
+ card.style.cursor = 'pointer';
1164
+ card.addEventListener('click', open);
1165
+ card.addEventListener('keydown', (e?: KeyboardEvent) => {
1166
+ if (e?.key === 'Enter') open();
1167
+ });
1168
+ }
1169
+ row.appendChild(card);
1170
+ }
1171
+ return row;
1172
+ }
1173
+
1174
+ private drawNative(
1175
+ mount: Mount,
1176
+ item: PlacementItemWire,
1177
+ content: Extract<PlacementContent, { kind: 'native' }>,
1178
+ ): HTMLElement {
1179
+ const card = document.createElement('div');
1180
+ card.className = 'joryio-placement-card';
1181
+ card.setAttribute('data-joryio-item', item.id);
1182
+ card.style.cssText = 'position:relative;box-sizing:border-box;';
1183
+ const image = safeHttpUrl(content.imageUrl);
1184
+ if (image) {
1185
+ const img = document.createElement('img');
1186
+ img.src = image;
1187
+ img.alt = '';
1188
+ img.style.cssText = 'display:block;max-width:100%;height:auto;';
1189
+ card.appendChild(img);
1190
+ }
1191
+ if (content.title) {
1192
+ const title = document.createElement('div');
1193
+ title.className = 'joryio-placement-title';
1194
+ title.textContent = content.title;
1195
+ card.appendChild(title);
1196
+ }
1197
+ if (content.body) {
1198
+ const body = document.createElement('div');
1199
+ body.className = 'joryio-placement-body';
1200
+ body.textContent = content.body;
1201
+ card.appendChild(body);
1202
+ }
1203
+ if (content.buttons?.length) {
1204
+ const row = document.createElement('div');
1205
+ row.className = 'joryio-placement-buttons';
1206
+ content.buttons.forEach((b, index) => {
1207
+ const btn = document.createElement('button');
1208
+ btn.type = 'button';
1209
+ btn.className = index === 0 ? 'primary' : 'secondary';
1210
+ btn.textContent = b.text;
1211
+ btn.addEventListener('click', () => this.buttonAction(mount, item, b));
1212
+ row.appendChild(btn);
1213
+ });
1214
+ card.appendChild(row);
1215
+ }
1216
+ // Inline content has no close control unless the author asked for one.
1217
+ if (content.closeButton === true) {
1218
+ const close = document.createElement('button');
1219
+ close.type = 'button';
1220
+ close.className = 'joryio-placement-close';
1221
+ close.setAttribute('aria-label', 'Close');
1222
+ close.textContent = '×';
1223
+ close.addEventListener('click', () => this.dismissItem(mount.key, item));
1224
+ card.appendChild(close);
1225
+ }
1226
+ return card;
1227
+ }
1228
+
1229
+ /**
1230
+ * A native button: report the click, then act. Unlike an overlay, an inline
1231
+ * item stays after a click - only a `dismiss` button (or the close control)
1232
+ * removes it.
1233
+ */
1234
+ private buttonAction(mount: Mount, item: PlacementItemWire, b: { id: string; action: string; url?: string }): void {
1235
+ const key = mount.key;
1236
+ // Synchronous first: the push prompt needs the click's user activation.
1237
+ if (b.action === 'request_push_permission') this.runtime.bridge?.requestPushPermission();
1238
+ this.report(key, item, 'clicked', b.id);
1239
+ if (b.action === 'url' || b.action === 'deep_link') {
1240
+ // http(s) opens in a new tab; an app deep link goes to the site's own
1241
+ // handler (the SDK never navigates to a custom scheme); anything else -
1242
+ // javascript:, data:, intent:, ... - is refused silently.
1243
+ // The site-wide link handler (setLinkHandler) sees it first.
1244
+ const url = safeHttpUrl(b.url);
1245
+ const context: LinkContext = { placementKey: key, itemId: item.id };
1246
+ if (url) {
1247
+ this.openLink(url, context, () => window.open(url, '_blank', 'noopener'));
1248
+ } else if (b.action === 'deep_link' && isAppDeepLink(b.url) && (mount.options.onDeepLink || this.links?.hasHandler)) {
1249
+ const deepLink = (b.url as string).trim();
1250
+ this.openLink(deepLink, context, () => {
1251
+ if (!mount.options.onDeepLink) return;
1252
+ try {
1253
+ mount.options.onDeepLink(deepLink, this.toItem(key, item, this.generation));
1254
+ } catch (error) {
1255
+ this.logger.error('The insertPlacement onDeepLink callback threw; ignored:', error);
1256
+ }
1257
+ });
1258
+ }
1259
+ return;
1260
+ }
1261
+ if (b.action === 'dismiss' || b.action === 'close') {
1262
+ this.dismissItem(key, item);
1263
+ }
1264
+ }
1265
+
1266
+ /** Through the site-wide link handler when there is a router, else straight to the fallback. */
1267
+ private openLink(url: string, context: LinkContext, fallback: () => void): void {
1268
+ if (this.links) this.links.route(url, 'placement', context, fallback);
1269
+ else fallback();
1270
+ }
1271
+
1272
+ private drawHtml(mount: Mount, item: PlacementItemWire, content: Extract<PlacementContent, { kind: 'html' }>): HTMLElement {
1273
+ const id = `p${++this.frameSeq}`;
1274
+ const iframe = document.createElement('iframe');
1275
+ iframe.className = 'joryio-placement-frame';
1276
+ iframe.setAttribute('data-joryio-item', item.id);
1277
+ // The overlay's sandbox exactly: same-origin so the bootstrap can reach
1278
+ // the host bridge; author script is stopped by the nonce CSP in the srcdoc.
1279
+ iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups');
1280
+ iframe.setAttribute('title', 'Placement');
1281
+ iframe.style.cssText = 'display:block;width:100%;height:0;border:0;';
1282
+ iframe.srcdoc = buildInAppSrcdoc(id, content.html || '', content.css || '', 'placement', PLACEMENT_BRIDGE_GLOBAL);
1283
+ this.frames.set(id, { iframe, key: mount.key, item });
1284
+ mount.frameIds.push(id);
1285
+ return iframe;
1286
+ }
1287
+
1288
+ /**
1289
+ * The host object the placement frames call into. Every method is keyed by
1290
+ * the frame id and acts only while that frame is drawn.
1291
+ */
1292
+ private installBridge(): void {
1293
+ if (typeof window === 'undefined') return;
1294
+ const frame = (id: string) => this.frames.get(id);
1295
+ (window as any)[PLACEMENT_BRIDGE_GLOBAL] = {
1296
+ __owner: this,
1297
+ setSize: (id: string, _w: number, height: number) => {
1298
+ const f = frame(id);
1299
+ if (f && Number.isFinite(height) && height > 0) f.iframe.style.height = `${Math.ceil(height)}px`;
1300
+ },
1301
+ // A click counts, and a link opens, only from the person's own gesture.
1302
+ logClick: (id: string, action?: string) => {
1303
+ const f = frame(id);
1304
+ if (f && hasUserGesture()) this.report(f.key, f.item, 'clicked', action);
1305
+ },
1306
+ // Always a new tab, never the host page itself: inline content does not
1307
+ // navigate the page it sits in.
1308
+ navigate: (id: string, url: string) => {
1309
+ if (!frame(id) || !hasUserGesture()) return;
1310
+ const safe = safeHttpUrl(url);
1311
+ const f = frame(id);
1312
+ if (safe && f) this.openLink(safe, { placementKey: f.key, itemId: f.item.id }, () => window.open(safe, '_blank', 'noopener'));
1313
+ },
1314
+ closeMessage: (id: string) => {
1315
+ const f = frame(id);
1316
+ if (f) this.dismissItem(f.key, f.item);
1317
+ },
1318
+ logConversion: () => undefined,
1319
+ logCustomEvent: (id: string, name: string, properties?: Record<string, any>) => {
1320
+ if (frame(id) && name) this.runtime.bridge?.logCustomEvent(name, properties);
1321
+ },
1322
+ setCustomUserAttribute: (id: string, key: string, value: any) => {
1323
+ if (frame(id) && key) this.runtime.bridge?.setCustomUserAttribute(key, value);
1324
+ },
1325
+ changeUser: (id: string, userId: string) => {
1326
+ if (frame(id) && userId) this.runtime.bridge?.changeUser(userId);
1327
+ },
1328
+ requestPushPermission: (id: string) => {
1329
+ if (frame(id)) this.runtime.bridge?.requestPushPermission();
1330
+ },
1331
+ submitForm: () => Promise.resolve({ ok: false, message: 'Forms are not available in this spot.' }),
1332
+ };
1333
+ }
1334
+
1335
+ // ── viewability ─────────────────────────────────────────────────────────
1336
+
1337
+ private pageVisible(): boolean {
1338
+ return typeof document === 'undefined' || document.visibilityState !== 'hidden';
1339
+ }
1340
+
1341
+ /** Whether any part of the host element is on screen (for "never swap under the reader's eyes"). */
1342
+ private observeHost(mount: Mount): void {
1343
+ if (typeof IntersectionObserver === 'undefined') return;
1344
+ const observer = new IntersectionObserver((entries) => {
1345
+ for (const e of entries) {
1346
+ mount.hostInView = e.isIntersecting;
1347
+ if (!e.isIntersecting && mount.pendingUpdate) this.render(mount);
1348
+ }
1349
+ });
1350
+ observer.observe(mount.element);
1351
+ mount.hostObserver = observer;
1352
+ }
1353
+
1354
+ /** Measure `node` (the shared rule, trackViewable) while it stays drawn in `mount`. */
1355
+ private trackViewability(mount: Mount, node: Element, onViewable: () => void): void {
1356
+ let tracker: ViewTracker | null = null;
1357
+ tracker = trackViewable(node, () => {
1358
+ if (tracker && mount.trackers.includes(tracker)) onViewable();
1359
+ });
1360
+ mount.trackers.push(tracker);
1361
+ }
1362
+
1363
+ private installPageVisibility(): void {
1364
+ if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return;
1365
+ this.pageListener = () => {
1366
+ for (const mount of this.mounts) {
1367
+ for (const t of mount.trackers) {
1368
+ if (this.pageVisible()) t.resume();
1369
+ else t.pause();
1370
+ }
1371
+ }
1372
+ };
1373
+ document.addEventListener('visibilitychange', this.pageListener);
1374
+ }
1375
+
1376
+ // ── session cache ───────────────────────────────────────────────────────
1377
+
1378
+ private subjectKey(): string {
1379
+ return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;
1380
+ }
1381
+
1382
+ private loadCache(): void {
1383
+ try {
1384
+ if (typeof sessionStorage === 'undefined') return;
1385
+ sessionStorage.removeItem?.(LEGACY_CACHE_STORAGE_NAME);
1386
+ const raw = sessionStorage.getItem(placementsStorageKey(this.sdkKey));
1387
+ if (!raw) return;
1388
+ const stored = JSON.parse(raw);
1389
+ // Another visitor's answers (a reset or a login since) are not this one's.
1390
+ if (!stored || stored.subject !== this.subjectKey() || typeof stored.entries !== 'object') return;
1391
+ for (const [key, entry] of Object.entries<any>(stored.entries)) {
1392
+ if (validKey(key) && entry && entry.placement && typeof entry.fetchedAt === 'number') {
1393
+ this.cache.set(key, {
1394
+ placement: this.normalize(key, entry.placement),
1395
+ fetchedAt: entry.fetchedAt,
1396
+ url: typeof entry.url === 'string' ? entry.url : null,
1397
+ });
1398
+ }
1399
+ }
1400
+ } catch {
1401
+ /* storage blocked or corrupt: start empty */
1402
+ }
1403
+ }
1404
+
1405
+ private persistCache(): void {
1406
+ try {
1407
+ if (typeof sessionStorage === 'undefined') return;
1408
+ const entries: Record<string, CacheEntry> = {};
1409
+ this.cache.forEach((entry, key) => {
1410
+ entries[key] = entry;
1411
+ });
1412
+ sessionStorage.setItem(placementsStorageKey(this.sdkKey), JSON.stringify({ subject: this.subjectKey(), entries }));
1413
+ } catch {
1414
+ /* storage blocked or full: memory only */
1415
+ }
1416
+ }
1417
+ }
1418
+
1419
+ /** The wire's product cards, defensively typed: an entry without an id is dropped. */
1420
+ export function toProducts(raw: unknown): PlacementProduct[] {
1421
+ if (!Array.isArray(raw)) return [];
1422
+ const str = (v: unknown) => (typeof v === 'string' ? v : null);
1423
+ return raw
1424
+ .filter((p): p is Record<string, unknown> => !!p && typeof p === 'object' && (typeof (p as any).id === 'string' || typeof (p as any).id === 'number'))
1425
+ .map((p) => ({
1426
+ id: String(p.id),
1427
+ title: str(p.title),
1428
+ price: str(p.price),
1429
+ compareAtPrice: str(p.compareAtPrice),
1430
+ discountPercent: typeof p.discountPercent === 'number' ? p.discountPercent : null,
1431
+ imageUrl: str(p.imageUrl),
1432
+ url: str(p.url),
1433
+ }));
1434
+ }