@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.
@@ -1 +1 @@
1
- {"version":3,"file":"joryio-cards-ui.min.js","sources":["../src/core/placements.ts","../src/cards-ui/card-feed-view.ts","../src/core/cards-ui-contract.ts","../src/cards-ui/index.ts"],"sourcesContent":["/**\n * Placements (docs/PLACEMENTS_PLAN.md, BACKLOG D444): named spots inside the\n * page - `home_hero`, `cart_upsell` - that Joryio fills per visitor from\n * placement campaigns and journey steps.\n *\n * Unlike overlays (inapp.ts) a placement is drawn INSIDE an element the site\n * owns, or handed to the site as data to draw itself. The serve endpoint is\n * `POST /v1/in-app/placements`; interactions are the in-app event family\n * (`/v1/in-app/track`), with the placement key alongside.\n *\n * The rules this file implements, and the names every Joryio SDK shares\n * (pinned by packages/backend/src/modules/tracking/sdk-placements-parity.spec.ts):\n *\n * - `insertPlacement(key, element)`, `<div data-joryio-placement=\"key\">`\n * auto-mount, `getPlacements([...])`, `refreshPlacements(keys?)`,\n * `onPlacementsUpdated(cb)`; `item.markDisplayed()`, `markClicked()`,\n * `markDismissed()`, `placement.markDisplayed()` (holdout exposure).\n * - Batched: every key asked for within PLACEMENT_BATCH_WINDOW_MS goes in one\n * request, at most PLACEMENT_MAX_KEYS_PER_REQUEST keys each.\n * - Cached per key for the placement's `ttlSeconds` (memory + sessionStorage,\n * scoped to the visitor), and a key is fetched from the network at most once\n * per PLACEMENT_MIN_REFRESH_SECONDS; extra refreshes coalesce.\n * - Viewable = at least PLACEMENT_VIEWABLE_FRACTION of the item in view for\n * IN_APP_DISPLAY_DWELL_MS continuously, page visible; reported once per\n * delivery.\n * - Never swaps content under the reader's eyes: an update to a placement that\n * is on screen is applied when it next leaves the viewport or is mounted again.\n * - Consent: without tracking consent the request names nobody (no user id, no\n * anonymous id, no session), the server answers with generic content and no\n * delivery token, and the SDK reports nothing.\n * - HTML items render in the same sandboxed, nonce-CSP frame as overlays, and\n * only when `allowHtmlJsInAppMessages` is on.\n */\n\nimport { JoryioSubscription, joryioSubscription } from './subscription';\nimport { bucketHash } from '../utils/bucket-hash';\nimport { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';\nimport { Logger } from '../utils/logger';\nimport { sdkIdentityHeaders } from './config';\nimport { IdentityManager } from './identity';\nimport { SessionManager } from './session';\nimport type { LinkContext, LinkRouter } from './links';\nimport {\n buildInAppSrcdoc,\n inAppTriggerFilterMatches,\n normalizedElementId,\n IN_APP_DISPLAY_DWELL_MS,\n InAppAuthProvider,\n InAppTrigger,\n} from './inapp';\n\n/** Share of an item that must be in view for it to count as seen. Same name and value on every Joryio SDK. */\nexport const PLACEMENT_VIEWABLE_FRACTION = 0.5;\n/** A placement key is fetched from the network at most once per this many seconds. Same on every Joryio SDK. */\nexport const PLACEMENT_MIN_REFRESH_SECONDS = 30;\n/** Keys asked for within this window go in one request. */\nexport const PLACEMENT_BATCH_WINDOW_MS = 50;\n/** The serve endpoint takes 1-10 keys per request. */\nexport const PLACEMENT_MAX_KEYS_PER_REQUEST = 10;\n/** How long an event-triggered item stays eligible after its event, when the server does not say. */\nexport const PLACEMENT_DEFAULT_TRIGGER_WINDOW_SECONDS = 1800;\n/**\n * A drawn product card's tap is reported as `clicked` with the elementId\n * `product:<product id>` (at most 128 characters), so the click report counts\n * clicks per product. Same name and value on every Joryio SDK.\n */\nexport const PLACEMENT_PRODUCT_ELEMENT_PREFIX = 'product:';\n/** 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. */\nexport const PLACEMENT_PRODUCT_CARD_WIDTH = 160;\n/** The elementId a product card's click is reported with - use it when you draw the cards yourself. */\nexport function placementProductElementId(productId: string): string {\n return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);\n}\n/** Used when an answer carries no ttlSeconds. */\nconst DEFAULT_TTL_SECONDS = 300;\n/** The pre-scoping, origin-wide name - never read, removed on start. */\nconst LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';\n/**\n * Per workspace, like the flags cache (flagsStorageKey): two workspaces on one\n * site that know a visitor by the same ids must never read each other's\n * placements. Carries a hash of the SDK key, never the key itself.\n */\nexport const placementsStorageKey = (sdkKey: string): string => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;\n/** The host-window object the placement HTML frames call into (overlays use their own). */\nconst PLACEMENT_BRIDGE_GLOBAL = '__joryioPlacement';\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\n\nexport type PlacementEmptyBehavior = 'collapse' | 'keep_space';\nexport type PlacementItemKind = 'native' | 'html' | 'data';\n/** The consent the request carries: the existing wire values. */\nexport type PlacementConsent = 'granted' | 'denied' | 'pending';\n\nexport type PlacementContent =\n | { kind: 'html'; html: string; css?: string }\n | {\n kind: 'native';\n title?: string;\n body?: string;\n imageUrl?: string;\n buttons?: Array<{ id: string; text: string; action: string; url?: string }>;\n closeButton?: boolean;\n };\n\n/** One item as the server sends it. */\n/** A product card of a recommendation placement item (D444 Phase 2b). Same names on all five SDKs. */\nexport interface PlacementProduct {\n id: string;\n title: string | null;\n price: string | null;\n compareAtPrice: string | null;\n discountPercent: number | null;\n imageUrl: string | null;\n url: string | null;\n}\n\nexport interface PlacementItemWire {\n id: string;\n variantId?: string | null;\n deliveryToken?: string | null;\n priority?: number;\n kind: PlacementItemKind;\n data?: Record<string, string | number | boolean>;\n content?: PlacementContent | null;\n /** Products picked for the person by a recommendation model (absent = none). */\n products?: PlacementProduct[] | null;\n triggers?: InAppTrigger[] | null;\n /** How long an event trigger keeps the item eligible (seconds). */\n placementTriggerWindowSeconds?: number | null;\n expiresAt?: string | null;\n /** Echoed in `shown` when present; the item id otherwise. */\n deliveryId?: string | null;\n}\n\n/** One placement as the server sends it. */\nexport interface PlacementWire {\n placementKey: string;\n emptyBehavior?: PlacementEmptyBehavior;\n maxItems?: number;\n ttlSeconds?: number;\n isControl?: boolean;\n controlToken?: string | null;\n items?: PlacementItemWire[];\n /**\n * D444 Phase 4: the answer depends on the page (a campaign of this\n * placement has page targeting), so it is cached per page (origin + path)\n * and asked again on a route change.\n */\n pageScoped?: boolean;\n}\n\nexport interface PlacementsResponse {\n success: boolean;\n evaluatedAt?: string;\n placements?: Record<string, PlacementWire>;\n}\n\n/** An item to draw, with the calls that report what the person did with it. */\nexport interface PlacementItem {\n id: string;\n variantId?: string | null;\n kind: PlacementItemKind;\n data: Record<string, string | number | boolean>;\n content?: PlacementContent | null;\n /** Products picked for the person by a recommendation model; [] when the item has none. Draw them as cards. */\n products: PlacementProduct[];\n priority?: number;\n expiresAt?: string | null;\n /** Report a viewable impression (the app drew it itself). Once per delivery. */\n markDisplayed(): void;\n /** Report a tap or click; `elementId` names the button or link. */\n markClicked(elementId?: string): void;\n /** Report that the person closed it. The placement's dismissal rule applies on the server. */\n markDismissed(): void;\n}\n\nexport interface Placement {\n placementKey: string;\n items: PlacementItem[];\n isControl: boolean;\n emptyBehavior: PlacementEmptyBehavior;\n maxItems: number;\n ttlSeconds: number;\n /**\n * For a held-out visitor (`isControl`): report that the (empty) spot was\n * viewable. Drawn placements do this themselves; a data-first app calls it\n * when its spot was on screen. No-op for a placement that is not a control.\n */\n markDisplayed(): void;\n}\n\nexport interface PlacementHandle {\n placementKey: string;\n element: HTMLElement;\n /** Stop filling the element and remove what the SDK drew. */\n remove(): void;\n}\n\nexport interface InsertPlacementOptions {\n /** Called after the SDK (re)drew the element, with what it drew. */\n onRender?: (placement: Placement, element: HTMLElement) => void;\n /**\n * A `deep_link` button with an app link (`myapp://cart`) was tapped: route\n * it in your app (the click is already reported). An http(s) link is opened\n * by the SDK in a new tab instead, and any other scheme (javascript:, data:,\n * intent:, ...) is refused - it reaches neither this handler nor the page.\n * A handler set with `setLinkHandler` sees every link first; this one is\n * called when it returns false.\n */\n onDeepLink?: (url: string, item: PlacementItem) => void;\n /**\n * Draw an item's recommended products as a horizontal row of cards (image,\n * title, price, optional button) below its content - alone for a data item.\n * Default true; false leaves the products to you (`onRender` / getPlacements).\n */\n showProducts?: boolean;\n /** Label of a button on every product card; unset = no button (the whole card opens the product). */\n productButtonText?: string;\n /** Width of one product card in CSS px (default PLACEMENT_PRODUCT_CARD_WIDTH). */\n productCardWidth?: number;\n}\n\nexport type PlacementsUpdatedCallback = (placements: Record<string, Placement>) => void;\n\n/** What the placement manager needs from the SDK. */\nexport interface PlacementRuntime {\n /**\n * The consent to send, or null when nothing may be sent at all (SDK not\n * initialised, disabled, ingestion suspended). `granted` = personal serving\n * and reporting; anything else = an anonymous request and no reporting.\n */\n consent: () => PlacementConsent | null;\n allowHtml: () => boolean;\n requestTimeoutMs?: number;\n noteStatus?: (status: number, data: any) => void;\n /** The SDK calls the HTML bridge reaches (custom events, attributes, push). */\n bridge?: {\n logCustomEvent: (name: string, properties?: Record<string, any>) => void;\n setCustomUserAttribute: (key: string, value: any) => void;\n changeUser: (userId: string) => void;\n requestPushPermission: () => void;\n };\n}\n\ninterface CacheEntry {\n placement: PlacementWire;\n fetchedAt: number;\n /** The page it was answered for (origin + path); matters only when `pageScoped`. */\n url?: string | null;\n}\n\ninterface Waiter {\n keys: string[];\n resolve: () => void;\n}\n\ninterface Mount {\n key: string;\n element: HTMLElement;\n options: InsertPlacementOptions;\n wrapper: HTMLElement | null;\n /** Item ids currently drawn (the `shown` list sent with the next request). */\n shown: string[];\n /** A newer answer that waits until the spot leaves the viewport. */\n pendingUpdate: boolean;\n /** Whether any part of the host element is in the viewport. */\n hostInView: boolean;\n hostObserver: IntersectionObserver | null;\n trackers: ViewTracker[];\n frameIds: string[];\n}\n\nconst nowMs = () => Date.now();\n\nfunction validKey(key: unknown): key is string {\n return typeof key === 'string' && PLACEMENT_KEY_PATTERN.test(key);\n}\n\n/** The page address without query or fragment: context only, and query strings carry PII. */\nfunction pageContext(): { url: string | null; screen: null } {\n return { url: currentPageUrl(), screen: null };\n}\n\n/**\n * Whether the page has a live user gesture. User activation propagates from a\n * frame to its ancestors, so a click inside a placement frame activates the\n * host page too; a call made by anything else (a timer, a synthetic event)\n * finds none. Browsers without the API are trusted - the frame's nonce CSP\n * already stops author script.\n */\nfunction hasUserGesture(): boolean {\n try {\n const activation = (navigator as any)?.userActivation;\n return activation ? activation.isActive === true : true;\n } catch {\n return true;\n }\n}\n\n/** An http(s) URL the SDK may open itself, or null. The one link rule of placements and content cards. */\nexport function safeHttpUrl(url: unknown): string | null {\n return typeof url === 'string' && /^https?:\\/\\//i.test(url) ? url : null;\n}\n\n/** Schemes never opened nor handed to the site, whatever the link says (the backend's card / placement link rule). */\nconst REFUSED_LINK_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'blob', 'about', 'content', 'intent'];\n\n/**\n * An app deep link (`myapp://cart`) that may go to the site's own handler: a\n * `scheme://` link whose scheme is not http(s) and not a refused one. The SDK\n * never navigates to it itself. The same rule on every Joryio SDK.\n */\nexport function isAppDeepLink(url: unknown): boolean {\n if (typeof url !== 'string') return false;\n const m = /^([a-z][a-z0-9+.-]*):\\/\\/./i.exec(url.trim());\n if (!m) return false;\n const scheme = m[1].toLowerCase();\n return scheme !== 'http' && scheme !== 'https' && !REFUSED_LINK_SCHEMES.includes(scheme);\n}\n\n/** One element's viewability measurement (see trackViewable). */\nexport interface ViewTracker {\n observer: IntersectionObserver | null;\n timer: ReturnType<typeof setTimeout> | null;\n inView: boolean;\n /** Restart the dwell when the page becomes visible again. */\n resume(): void;\n /** Stop the dwell while the page is hidden. */\n pause(): void;\n /** Stop measuring for good. */\n cancel(): void;\n}\n\nfunction pageIsVisible(): boolean {\n return typeof document === 'undefined' || document.visibilityState !== 'hidden';\n}\n\n/**\n * Call `onViewable` once `node` has had PLACEMENT_VIEWABLE_FRACTION of its\n * area in view for IN_APP_DISPLAY_DWELL_MS continuously, with the page\n * visible. Without IntersectionObserver (very old browsers) the page being\n * visible for the dwell counts. Shared by placements and the card feed; the\n * caller forwards page visibility changes to `resume` / `pause`.\n */\nexport function trackViewable(node: Element, onViewable: () => void): ViewTracker {\n let cancelled = false;\n const tracker: ViewTracker = {\n observer: null,\n timer: null,\n inView: false,\n resume: () => {\n if (cancelled || tracker.timer || !tracker.inView || !pageIsVisible()) return;\n tracker.timer = setTimeout(() => {\n tracker.timer = null;\n if (!cancelled && tracker.inView && pageIsVisible()) {\n cancelled = true;\n tracker.observer?.disconnect();\n onViewable();\n }\n }, IN_APP_DISPLAY_DWELL_MS);\n },\n pause: () => {\n if (tracker.timer) clearTimeout(tracker.timer);\n tracker.timer = null;\n },\n cancel: () => {\n cancelled = true;\n tracker.observer?.disconnect();\n tracker.pause();\n },\n };\n if (typeof IntersectionObserver === 'undefined') {\n tracker.inView = true;\n tracker.resume();\n return tracker;\n }\n tracker.observer = new IntersectionObserver(\n (entries) => {\n for (const e of entries) {\n // A zero-area target (a collapsed control spot) reports ratio 1 while intersecting.\n tracker.inView = e.isIntersecting && e.intersectionRatio >= PLACEMENT_VIEWABLE_FRACTION;\n if (tracker.inView) tracker.resume();\n else tracker.pause();\n }\n },\n { threshold: [0, PLACEMENT_VIEWABLE_FRACTION, 1] },\n );\n tracker.observer.observe(node);\n return tracker;\n}\n\nexport class PlacementManager {\n /** The SDK's link router (`setLinkHandler`); set by the SDK after construction. */\n links: LinkRouter | null = null;\n\n private cache = new Map<string, CacheEntry>();\n /** When each key last went to the network (the client rate limit). */\n private lastNetworkAt = new Map<string, number>();\n private inflight = new Map<string, Promise<void>>();\n private batchKeys = new Set<string>();\n private batchTimer: ReturnType<typeof setTimeout> | null = null;\n private batchWaiters: Waiter[] = [];\n /** Refreshes asked for inside the rate-limit window, run when it opens. */\n private deferredKeys = new Set<string>();\n private deferredTimer: ReturnType<typeof setTimeout> | null = null;\n private listeners = new Set<PlacementsUpdatedCallback>();\n private mounts = new Set<Mount>();\n /** Delivery handles already reported, per transition (displayed once, control once). */\n private reported = new Set<string>();\n /** Event-triggered items: when their event fired. */\n private triggeredAt = new Map<string, number>();\n /** Items the person dismissed: hidden locally until the server's next answer. */\n private dismissedLocally = new Set<string>();\n /** Bumped when WHO the placements are for changes; older answers are discarded. */\n private generation = 0;\n private mutationObserver: MutationObserver | null = null;\n private frames = new Map<string, { iframe: HTMLIFrameElement; key: string; item: PlacementItemWire }>();\n private frameSeq = 0;\n private pageListener: (() => void) | null = null;\n private destroyed = false;\n private page: PageContextTracker | null = null;\n private pageUnsubscribe: (() => void) | null = null;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private identity: IdentityManager,\n private session: SessionManager,\n private logger: Logger,\n private runtime: PlacementRuntime,\n private auth?: InAppAuthProvider,\n ) {\n this.loadCache();\n this.installBridge();\n this.installPageVisibility();\n }\n\n // ── public API ──────────────────────────────────────────────────────────\n\n /** Draw placement `key` into `element`. Returns a handle whose remove() stops it. */\n insertPlacement(key: string, element: HTMLElement, options: InsertPlacementOptions = {}): PlacementHandle | null {\n if (!validKey(key)) {\n this.logger.warn(`insertPlacement: \"${key}\" is not a placement key (a-z, 0-9 and _, up to 64)`);\n return null;\n }\n if (!element || typeof (element as any).appendChild !== 'function') {\n this.logger.warn('insertPlacement: an element is required');\n return null;\n }\n for (const existing of this.mounts) {\n if (existing.element === element) this.unmount(existing);\n }\n const mount: Mount = {\n key,\n element,\n options,\n wrapper: null,\n shown: [],\n pendingUpdate: false,\n hostInView: false,\n hostObserver: null,\n trackers: [],\n frameIds: [],\n };\n this.mounts.add(mount);\n this.observeHost(mount);\n const cached = this.freshEntry(key);\n if (cached) this.render(mount);\n this.ensure([key]).then(() => {\n // Drawn already when the answer changed the cache (applyChanged); an\n // unchanged or failed answer still draws what there is.\n if (this.mounts.has(mount) && !mount.wrapper) this.render(mount);\n }).catch((error) => this.logger.debug('Placement fetch failed:', error));\n return { placementKey: key, element, remove: () => this.unmount(mount) };\n }\n\n /** The placements for `keys`, from the cache when fresh, from the network otherwise. */\n async getPlacements(keys: string[]): Promise<Record<string, Placement>> {\n const wanted = this.cleanKeys(keys);\n await this.ensure(wanted);\n const out: Record<string, Placement> = {};\n for (const key of wanted) out[key] = this.toPlacement(key);\n return out;\n }\n\n /** Ask the server again for `keys` (default: every placement on the page or in the cache). */\n async refreshPlacements(keys?: string[]): Promise<void> {\n const wanted = keys ? this.cleanKeys(keys) : this.knownKeys();\n if (!wanted.length) return;\n await this.fetchKeys(wanted, true);\n }\n\n /** Called with the placements that changed after each answer. Returns a JoryioSubscription. */\n onPlacementsUpdated(callback: PlacementsUpdatedCallback): JoryioSubscription {\n if (typeof callback !== 'function') return joryioSubscription(() => undefined);\n // One entry per subscription, so the same function subscribed twice is two subscriptions.\n const entry: PlacementsUpdatedCallback = (placements) => callback(placements);\n this.listeners.add(entry);\n return joryioSubscription(() => {\n this.listeners.delete(entry);\n });\n }\n\n /** Mount every `[data-joryio-placement]` element on the page, now and as the page changes. */\n autoMount(): void {\n if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;\n if (document.readyState === 'loading' && typeof document.addEventListener === 'function') {\n // The script ran in <head>: the elements are not parsed yet.\n document.addEventListener('DOMContentLoaded', () => !this.destroyed && this.autoMount(), { once: true });\n return;\n }\n this.scanDocument();\n if (this.mutationObserver || typeof MutationObserver === 'undefined' || !document.body) return;\n this.mutationObserver = new MutationObserver(() => this.scanDocument());\n this.mutationObserver.observe(document.body, { childList: true, subtree: true });\n }\n\n /** An event was tracked: event-triggered items waiting on it become eligible. */\n onEventTracked(eventName: string, properties?: Record<string, any>): void {\n if (!eventName) return;\n const changed = new Set<string>();\n for (const [key, entry] of this.cache) {\n for (const item of entry.placement.items || []) {\n const match = (item.triggers || []).some(\n (t) => t.type === 'event' && t.event === eventName && inAppTriggerFilterMatches(t, properties),\n );\n if (match) {\n this.triggeredAt.set(this.handle(key, item), nowMs());\n changed.add(key);\n }\n }\n }\n if (changed.size) this.applyChanged(Array.from(changed));\n }\n\n /**\n * The visitor changed (identify, reset, consent): forget every answer and\n * ask again for the placements on the page.\n */\n invalidate(): void {\n this.generation++;\n this.cache.clear();\n this.lastNetworkAt.clear();\n this.triggeredAt.clear();\n this.dismissedLocally.clear();\n this.reported.clear();\n this.persistCache();\n const keys = this.mountedKeys();\n // The previous person's content goes NOW, on screen or not: it must not\n // stay in front of the next person, nor report against them.\n for (const mount of this.mounts) this.render(mount);\n if (keys.length) this.fetchKeys(keys, true).catch(() => undefined);\n }\n\n destroy(): void {\n this.destroyed = true;\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n for (const mount of Array.from(this.mounts)) this.unmount(mount);\n this.mutationObserver?.disconnect();\n this.mutationObserver = null;\n if (this.batchTimer) clearTimeout(this.batchTimer);\n if (this.deferredTimer) clearTimeout(this.deferredTimer);\n this.batchTimer = null;\n this.deferredTimer = null;\n this.batchWaiters.forEach((w) => w.resolve());\n this.batchWaiters = [];\n this.listeners.clear();\n if (this.pageListener && typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {\n document.removeEventListener('visibilitychange', this.pageListener);\n }\n try {\n if (typeof window !== 'undefined' && (window as any)[PLACEMENT_BRIDGE_GLOBAL]?.__owner === this) {\n delete (window as any)[PLACEMENT_BRIDGE_GLOBAL];\n }\n } catch {\n /* ignore */\n }\n }\n\n // ── fetching ────────────────────────────────────────────────────────────\n\n private cleanKeys(keys: string[]): string[] {\n const out: string[] = [];\n for (const key of Array.isArray(keys) ? keys : []) {\n if (validKey(key) && !out.includes(key)) out.push(key);\n else if (!validKey(key)) this.logger.warn(`Ignoring \"${key}\": not a placement key`);\n }\n return out;\n }\n\n private knownKeys(): string[] {\n return Array.from(new Set([...this.mountedKeys(), ...this.cache.keys()]));\n }\n\n private mountedKeys(): string[] {\n return Array.from(new Set(Array.from(this.mounts).map((m) => m.key)));\n }\n\n /**\n * Page context (D444 Phase 4): requests carry the page (URL without query,\n * allow-listed variables), and a page-scoped answer is good for its page\n * only - on a route change it goes, and the spot asks again.\n */\n setPageContext(tracker: PageContextTracker | null): void {\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n this.page = tracker;\n if (!tracker) return;\n this.pageUnsubscribe = tracker.onSignal((signal) => {\n if (signal.type !== 'page_change' || this.destroyed) return;\n const stale: string[] = [];\n this.cache.forEach((entry, key) => {\n if (entry.placement.pageScoped && entry.url !== signal.url) stale.push(key);\n });\n if (!stale.length) return;\n stale.forEach((key) => this.cache.delete(key));\n this.persistCache();\n // The old page's item must not stay on the new page while the answer is on its way.\n for (const mount of this.mounts) if (stale.includes(mount.key)) this.render(mount);\n const mounted = stale.filter((key) => this.mountedKeys().includes(key));\n if (mounted.length) {\n this.fetchKeys(mounted, false)\n .then(() => {\n for (const mount of this.mounts) if (mounted.includes(mount.key) && !mount.wrapper) this.render(mount);\n })\n .catch(() => undefined);\n }\n });\n }\n\n private currentUrl(): string | null {\n return this.page ? this.page.current().url : currentPageUrl();\n }\n\n /** The rate-limit key: per page for a page-scoped placement, so a route change can ask again at once. */\n private rateKey(key: string): string {\n return this.cache.get(key)?.placement.pageScoped || this.pageScopedKeys.has(key) ? `${key}\\u0000${this.currentUrl() ?? ''}` : key;\n }\n private pageScopedKeys = new Set<string>();\n\n private freshEntry(key: string): CacheEntry | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n if (entry.placement.pageScoped && entry.url !== this.currentUrl()) return null;\n const ttl = (entry.placement.ttlSeconds || DEFAULT_TTL_SECONDS) * 1000;\n return nowMs() - entry.fetchedAt < ttl ? entry : null;\n }\n\n /** Fresh from the cache, or fetched (never more often than the rate limit allows). */\n private async ensure(keys: string[]): Promise<void> {\n const stale = keys.filter((key) => !this.freshEntry(key));\n if (stale.length) await this.fetchKeys(stale, false);\n }\n\n /**\n * Fetch `keys`, batched with every other key asked for in the next\n * PLACEMENT_BATCH_WINDOW_MS. A key fetched less than\n * PLACEMENT_MIN_REFRESH_SECONDS ago is not fetched again: a forced refresh\n * is deferred to when the window opens, anything else is served the cache.\n */\n private fetchKeys(keys: string[], force: boolean): Promise<void> {\n const now = nowMs();\n const waits: Promise<void>[] = [];\n const due: string[] = [];\n for (const key of keys) {\n const inflight = this.inflight.get(key);\n if (inflight) {\n waits.push(inflight);\n if (force) this.defer(key);\n continue;\n }\n const last = this.lastNetworkAt.get(this.rateKey(key));\n if (last !== undefined && now - last < PLACEMENT_MIN_REFRESH_SECONDS * 1000) {\n if (force) this.defer(key);\n continue;\n }\n due.push(key);\n }\n if (due.length) {\n due.forEach((key) => this.batchKeys.add(key));\n const batched = new Promise<void>((resolve) => this.batchWaiters.push({ keys: due, resolve }));\n due.forEach((key) => this.inflight.set(key, batched));\n if (!this.batchTimer) this.batchTimer = setTimeout(() => void this.flushBatch(), PLACEMENT_BATCH_WINDOW_MS);\n waits.push(batched);\n }\n return Promise.all(waits).then(() => undefined);\n }\n\n private defer(key: string): void {\n this.deferredKeys.add(key);\n if (this.deferredTimer) return;\n const last = Math.min(...Array.from(this.deferredKeys).map((k) => this.lastNetworkAt.get(this.rateKey(k)) ?? 0));\n const wait = Math.max(0, last + PLACEMENT_MIN_REFRESH_SECONDS * 1000 - nowMs());\n this.deferredTimer = setTimeout(() => {\n this.deferredTimer = null;\n const keys = Array.from(this.deferredKeys);\n this.deferredKeys.clear();\n if (keys.length && !this.destroyed) this.fetchKeys(keys, false).catch(() => undefined);\n }, wait + 10);\n }\n\n private async flushBatch(): Promise<void> {\n this.batchTimer = null;\n const keys = Array.from(this.batchKeys);\n this.batchKeys.clear();\n const waiters = this.batchWaiters;\n this.batchWaiters = [];\n const chunks: string[][] = [];\n for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {\n chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));\n }\n try {\n await Promise.all(chunks.map((chunk) => this.request(chunk)));\n } finally {\n keys.forEach((key) => this.inflight.delete(key));\n waiters.forEach((w) => w.resolve());\n }\n }\n\n private async request(keys: string[]): Promise<void> {\n const consent = this.runtime.consent();\n if (consent === null || this.destroyed) return;\n const generation = this.generation;\n const personal = consent === 'granted';\n const sentAt = nowMs();\n keys.forEach((key) => this.lastNetworkAt.set(this.rateKey(key), sentAt));\n const askedFor = this.currentUrl();\n\n const shown: Record<string, string[]> = {};\n for (const mount of this.mounts) {\n if (keys.includes(mount.key) && mount.shown.length) shown[mount.key] = mount.shown.slice();\n }\n const userId = personal ? this.identity.getUserId() : null;\n const anonymousId = personal ? this.identity.getAnonymousId() : null;\n const body: Record<string, any> = {\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n ...(personal ? { sessionId: this.session.getSessionId() } : {}),\n deviceType: 'web',\n locale: typeof navigator !== 'undefined' ? navigator.language : undefined,\n capabilities: this.capabilities(),\n trackingConsent: consent,\n placements: keys,\n shown,\n context: this.page ? { ...this.page.current(), screen: null } : pageContext(),\n };\n\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);\n const url = `${this.apiEndpoint}/v1/in-app/placements`;\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n // Only a consented request carries the visitor's auth: an\n // unconsented one names nobody.\n ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),\n },\n body: JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n });\n if (!response.ok) {\n // 429 (the per-device limit) and every other failure: keep the cache.\n this.runtime.noteStatus?.(response.status, null);\n this.logger.debug(`Placements request answered ${response.status}; keeping the cached placements`);\n return;\n }\n const data: PlacementsResponse = await response.json();\n if (generation !== this.generation) {\n this.logger.debug('Discarding a placements answer that predates an identity or consent change');\n return;\n }\n if (!data || data.success === false || !data.placements || typeof data.placements !== 'object') return;\n const fetchedAt = nowMs();\n const changed: string[] = [];\n for (const key of keys) {\n // A key the server left out is an empty placement (never an error).\n const wire = data.placements[key] || { placementKey: key, items: [] };\n const normalized = this.normalize(key, wire);\n const before = this.cache.get(key);\n this.cache.set(key, { placement: normalized, fetchedAt, url: askedFor });\n if (normalized.pageScoped) this.pageScopedKeys.add(key);\n else this.pageScopedKeys.delete(key);\n // The server's answer already applied the dismissal rule.\n for (const handle of Array.from(this.dismissedLocally)) {\n if (handle.startsWith(`${key}\\u0000`)) this.dismissedLocally.delete(handle);\n }\n if (!before || JSON.stringify(before.placement) !== JSON.stringify(normalized)) changed.push(key);\n }\n this.persistCache();\n if (changed.length) this.applyChanged(changed);\n } catch (error) {\n const timedOut = (error as any)?.name === 'AbortError';\n this.logger.debug(timedOut ? 'Placements request timed out' : 'Placements request failed', error);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private capabilities(): string[] {\n const caps = ['placements', 'content.native', 'content.data'];\n if (this.page) caps.push(PAGE_CONTEXT_CAPABILITY);\n if (this.runtime.allowHtml()) caps.push('content.html');\n return caps;\n }\n\n private normalize(key: string, wire: PlacementWire): PlacementWire {\n const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];\n return {\n placementKey: key,\n emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse',\n maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1,\n ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS,\n isControl: wire.isControl === true,\n controlToken: wire.controlToken || null,\n items,\n ...(wire.pageScoped === true ? { pageScoped: true } : {}),\n };\n }\n\n /** Re-draw mounted placements and tell listeners, for keys whose answer changed. */\n private applyChanged(keys: string[]): void {\n for (const mount of this.mounts) {\n if (!keys.includes(mount.key)) continue;\n // Never under the reader's eyes: applied when the spot leaves the viewport.\n if (mount.hostInView && mount.shown.length) mount.pendingUpdate = true;\n else this.render(mount);\n }\n if (!this.listeners.size) return;\n const update: Record<string, Placement> = {};\n keys.forEach((key) => (update[key] = this.toPlacement(key)));\n for (const listener of Array.from(this.listeners)) {\n try {\n listener(update);\n } catch (error) {\n this.logger.error('The onPlacementsUpdated callback threw; ignored:', error);\n }\n }\n }\n\n // ── what is eligible now ────────────────────────────────────────────────\n\n private handle(key: string, item: PlacementItemWire): string {\n return `${key}\\u0000${item.deliveryToken || item.id}`;\n }\n\n /** The items to show now: not expired, not dismissed here, triggered when they wait on an event. */\n private visibleItems(key: string): PlacementItemWire[] {\n const entry = this.cache.get(key);\n if (!entry) return [];\n const now = nowMs();\n const max = entry.placement.maxItems || 1;\n return (entry.placement.items || [])\n .filter((item) => {\n if (item.expiresAt && Date.parse(item.expiresAt) <= now) return false;\n if (this.dismissedLocally.has(this.handle(key, item))) return false;\n const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');\n if (eventTriggers.length) {\n const at = this.triggeredAt.get(this.handle(key, item));\n const windowS = item.placementTriggerWindowSeconds || PLACEMENT_DEFAULT_TRIGGER_WINDOW_SECONDS;\n if (at === undefined || now - at > windowS * 1000) return false;\n }\n return true;\n })\n .slice(0, max);\n }\n\n private toPlacement(key: string): Placement {\n const entry = this.cache.get(key);\n const wire = entry?.placement || this.normalize(key, { placementKey: key, items: [] });\n const generation = this.generation;\n return {\n placementKey: key,\n items: this.visibleItems(key).map((item) => this.toItem(key, item, generation)),\n isControl: wire.isControl === true,\n emptyBehavior: wire.emptyBehavior || 'collapse',\n maxItems: wire.maxItems || 1,\n ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,\n markDisplayed: () => this.current(generation) && this.reportControl(key),\n };\n }\n\n /** Created for the person still here? A Placement / item outlives an identify or reset: then it reports nothing. */\n private current(generation: number): boolean {\n return generation === this.generation;\n }\n\n private toItem(key: string, item: PlacementItemWire, generation: number): PlacementItem {\n return {\n id: item.id,\n variantId: item.variantId ?? null,\n kind: item.kind,\n data: { ...(item.data || {}) },\n content: item.content ?? null,\n products: toProducts(item.products),\n priority: item.priority,\n expiresAt: item.expiresAt ?? null,\n markDisplayed: () => this.current(generation) && this.report(key, item, 'displayed'),\n markClicked: (elementId?: string) => this.current(generation) && this.report(key, item, 'clicked', elementId),\n markDismissed: () => this.current(generation) && this.dismissItem(key, item),\n };\n }\n\n // ── reporting ───────────────────────────────────────────────────────────\n\n private dismissItem(key: string, item: PlacementItemWire): void {\n this.report(key, item, 'dismissed');\n this.dismissedLocally.add(this.handle(key, item));\n for (const mount of this.mounts) if (mount.key === key) this.render(mount);\n }\n\n /**\n * Report a transition to `/v1/in-app/track`. Only with consent (an\n * unconsented answer carries no delivery token and nothing is reported).\n * `displayed` once per delivery; a click or dismiss first counts the item\n * as displayed - the person saw it.\n */\n private report(key: string, item: PlacementItemWire, type: 'displayed' | 'clicked' | 'dismissed', elementId?: string): void {\n if (this.runtime.consent() !== 'granted') return;\n const once = `${type}:${this.handle(key, item)}`;\n if (type !== 'clicked') {\n if (this.reported.has(once)) return;\n this.reported.add(once);\n }\n if (type !== 'displayed') this.report(key, item, 'displayed');\n const at = new Date().toISOString();\n const normalizedId = normalizedElementId(elementId);\n const body: Record<string, any> = {\n campaignId: item.id,\n ...(item.variantId ? { variantId: item.variantId } : {}),\n ...(item.deliveryToken ? { deliveryToken: item.deliveryToken } : {}),\n placementKey: key,\n ...this.subject(),\n sessionId: this.session.getSessionId(),\n deviceType: 'web',\n ...(type === 'displayed' ? { action: 'displayed', displayedAt: at } : {}),\n ...(type === 'clicked' ? { action: 'clicked', clicked: true, clickedAt: at, ...(normalizedId ? { elementId: normalizedId } : {}) } : {}),\n ...(type === 'dismissed' ? { action: 'dismissed', dismissedAt: at } : {}),\n };\n this.post('/v1/in-app/track', body);\n }\n\n /**\n * A held-out visitor's empty spot was viewable: `in_app.control_viewed`,\n * once per control token. The token (from the answer) names the placement,\n * the campaign when it was a campaign control variant, and the visitor.\n */\n private reportControl(key: string): void {\n const entry = this.cache.get(key);\n if (!entry?.placement.isControl || !entry.placement.controlToken) return;\n if (this.runtime.consent() !== 'granted') return;\n const once = `control:${entry.placement.controlToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post('/v1/in-app/track', {\n action: 'control_viewed',\n controlToken: entry.placement.controlToken,\n placementKey: key,\n ...this.subject(),\n sessionId: this.session.getSessionId(),\n deviceType: 'web',\n viewedAt: new Date().toISOString(),\n });\n }\n\n private subject(): { userId?: string; anonymousId: string } {\n const userId = this.identity.getUserId();\n return { ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId() };\n }\n\n private post(path: string, body: Record<string, any>): void {\n const userId = typeof body.userId === 'string' ? body.userId : null;\n fetch(`${this.apiEndpoint}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : body.anonymousId ?? null) || {}),\n },\n body: JSON.stringify(body),\n keepalive: true,\n })\n .then((response) => {\n if (!response.ok) this.runtime.noteStatus?.(response.status, null);\n })\n .catch((error) => this.logger.debug(`Placement report to ${path} failed`, error));\n }\n\n // ── drawing ─────────────────────────────────────────────────────────────\n\n private scanDocument(): void {\n if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;\n // Elements removed from the page stop being filled.\n for (const mount of Array.from(this.mounts)) {\n if ((mount.element as any).isConnected === false) this.unmount(mount);\n }\n const mountedElements = new Set(Array.from(this.mounts).map((m) => m.element));\n document.querySelectorAll<HTMLElement>('[data-joryio-placement]').forEach((element) => {\n if (mountedElements.has(element)) return;\n const key = element.getAttribute('data-joryio-placement');\n if (key) this.insertPlacement(key, element);\n });\n }\n\n private unmount(mount: Mount): void {\n this.mounts.delete(mount);\n mount.hostObserver?.disconnect();\n this.clearTrackers(mount);\n this.clearDrawn(mount);\n mount.element.removeAttribute?.('data-joryio-placement-state');\n }\n\n private clearTrackers(mount: Mount): void {\n for (const t of mount.trackers) t.cancel();\n mount.trackers = [];\n }\n\n private clearDrawn(mount: Mount): void {\n mount.frameIds.forEach((id) => this.frames.delete(id));\n mount.frameIds = [];\n mount.wrapper?.remove();\n mount.wrapper = null;\n mount.shown = [];\n }\n\n private render(mount: Mount): void {\n if (!this.mounts.has(mount)) return;\n mount.pendingUpdate = false;\n this.clearTrackers(mount);\n this.clearDrawn(mount);\n const placement = this.toPlacement(mount.key);\n const entry = this.cache.get(mount.key);\n const wrapper = document.createElement('div');\n wrapper.className = 'joryio-placement';\n wrapper.setAttribute('data-joryio-placement-key', mount.key);\n const drawn: PlacementItemWire[] = [];\n for (const item of this.visibleItems(mount.key)) {\n const node = this.drawItem(mount, item);\n if (!node) continue;\n wrapper.appendChild(node);\n drawn.push(item);\n this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));\n }\n mount.shown = drawn.map((item) => item.deliveryId || item.id);\n mount.element.appendChild(wrapper);\n mount.wrapper = wrapper;\n const state = drawn.length ? 'filled' : placement.isControl ? 'control' : 'empty';\n mount.element.setAttribute('data-joryio-placement-state', state);\n if (!drawn.length) {\n // collapse: nothing drawn, the wrapper takes no space. keep_space: the\n // element keeps whatever box the site gave it.\n wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';\n if (placement.isControl && entry?.placement.controlToken) {\n // The holdout's exposure: the SPOT (the site's element) was viewable.\n this.trackViewability(mount, mount.element, () => this.reportControl(mount.key));\n }\n }\n if (mount.options.onRender) {\n try {\n mount.options.onRender(placement, mount.element);\n } catch (error) {\n this.logger.error('The insertPlacement onRender callback threw; ignored:', error);\n }\n }\n }\n\n private drawItem(mount: Mount, item: PlacementItemWire): HTMLElement | null {\n const content = item.content;\n let node: HTMLElement | null = null;\n if (content?.kind === 'html') {\n if (!this.runtime.allowHtml()) {\n this.logger.warn(`Placement ${mount.key}: HTML item skipped (allowHtmlJsInAppMessages is off)`);\n return null;\n }\n node = this.drawHtml(mount, item, content);\n } else if (content?.kind === 'native') {\n node = this.drawNative(mount, item, content);\n } else if (content) {\n return null;\n }\n // Recommended products: a row of cards below the content, or alone for a\n // data item (without products a data item is the app's to draw).\n const products = mount.options.showProducts === false ? [] : toProducts(item.products);\n if (!products.length) return node;\n const row = this.drawProducts(mount, item, products);\n if (!node) return row;\n const box = document.createElement('div');\n box.className = 'joryio-placement-item';\n box.setAttribute('data-joryio-item', item.id);\n box.appendChild(node);\n box.appendChild(row);\n return box;\n }\n\n /**\n * The built-in product cards: a horizontally scrolling row, one card per\n * product (image, title, price - the compare-at price struck through - and\n * the optional button). A tap reports `clicked` with\n * placementProductElementId and opens the product's link the way a\n * `deep_link` button does: http(s) in a new tab, an app link to the\n * handlers, anything else refused. Styled with the joryio-placement-product*\n * classes.\n */\n private drawProducts(mount: Mount, item: PlacementItemWire, products: PlacementProduct[]): HTMLElement {\n const row = document.createElement('div');\n row.className = 'joryio-placement-products';\n row.setAttribute('data-joryio-item', item.id);\n row.style.cssText = 'display:flex;gap:8px;overflow-x:auto;box-sizing:border-box;';\n const requested = Number(mount.options.productCardWidth);\n const width = Number.isFinite(requested) && requested > 0 ? requested : PLACEMENT_PRODUCT_CARD_WIDTH;\n for (const p of products) {\n const card = document.createElement('div');\n card.className = 'joryio-placement-product';\n card.setAttribute('data-joryio-product', p.id);\n card.style.cssText = `flex:0 0 ${width}px;width:${width}px;box-sizing:border-box;`;\n const open = p.url ? () => this.buttonAction(mount, item, { id: placementProductElementId(p.id), action: 'deep_link', url: p.url! }) : null;\n const image = safeHttpUrl(p.imageUrl);\n if (image) {\n const img = document.createElement('img');\n img.className = 'joryio-placement-product-image';\n img.src = image;\n img.alt = p.title || '';\n img.style.cssText = 'display:block;width:100%;aspect-ratio:1/1;object-fit:cover;';\n card.appendChild(img);\n }\n if (p.title) {\n const title = document.createElement('div');\n title.className = 'joryio-placement-product-title';\n title.textContent = p.title;\n card.appendChild(title);\n }\n if (p.price) {\n const price = document.createElement('div');\n price.className = 'joryio-placement-product-price';\n price.textContent = p.price;\n if (p.compareAtPrice) {\n const was = document.createElement('s');\n was.className = 'joryio-placement-product-compare';\n was.textContent = p.compareAtPrice;\n was.style.cssText = 'margin-inline-start:6px;opacity:0.6;';\n price.appendChild(was);\n }\n card.appendChild(price);\n }\n if (open && mount.options.productButtonText) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'joryio-placement-product-button';\n btn.textContent = mount.options.productButtonText;\n btn.addEventListener('click', (e?: Event) => {\n e?.stopPropagation?.();\n open();\n });\n card.appendChild(btn);\n }\n if (open) {\n card.setAttribute('role', 'link');\n card.tabIndex = 0;\n card.style.cursor = 'pointer';\n card.addEventListener('click', open);\n card.addEventListener('keydown', (e?: KeyboardEvent) => {\n if (e?.key === 'Enter') open();\n });\n }\n row.appendChild(card);\n }\n return row;\n }\n\n private drawNative(\n mount: Mount,\n item: PlacementItemWire,\n content: Extract<PlacementContent, { kind: 'native' }>,\n ): HTMLElement {\n const card = document.createElement('div');\n card.className = 'joryio-placement-card';\n card.setAttribute('data-joryio-item', item.id);\n card.style.cssText = 'position:relative;box-sizing:border-box;';\n const image = safeHttpUrl(content.imageUrl);\n if (image) {\n const img = document.createElement('img');\n img.src = image;\n img.alt = '';\n img.style.cssText = 'display:block;max-width:100%;height:auto;';\n card.appendChild(img);\n }\n if (content.title) {\n const title = document.createElement('div');\n title.className = 'joryio-placement-title';\n title.textContent = content.title;\n card.appendChild(title);\n }\n if (content.body) {\n const body = document.createElement('div');\n body.className = 'joryio-placement-body';\n body.textContent = content.body;\n card.appendChild(body);\n }\n if (content.buttons?.length) {\n const row = document.createElement('div');\n row.className = 'joryio-placement-buttons';\n content.buttons.forEach((b, index) => {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = index === 0 ? 'primary' : 'secondary';\n btn.textContent = b.text;\n btn.addEventListener('click', () => this.buttonAction(mount, item, b));\n row.appendChild(btn);\n });\n card.appendChild(row);\n }\n // Inline content has no close control unless the author asked for one.\n if (content.closeButton === true) {\n const close = document.createElement('button');\n close.type = 'button';\n close.className = 'joryio-placement-close';\n close.setAttribute('aria-label', 'Close');\n close.textContent = '×';\n close.addEventListener('click', () => this.dismissItem(mount.key, item));\n card.appendChild(close);\n }\n return card;\n }\n\n /**\n * A native button: report the click, then act. Unlike an overlay, an inline\n * item stays after a click - only a `dismiss` button (or the close control)\n * removes it.\n */\n private buttonAction(mount: Mount, item: PlacementItemWire, b: { id: string; action: string; url?: string }): void {\n const key = mount.key;\n // Synchronous first: the push prompt needs the click's user activation.\n if (b.action === 'request_push_permission') this.runtime.bridge?.requestPushPermission();\n this.report(key, item, 'clicked', b.id);\n if (b.action === 'url' || b.action === 'deep_link') {\n // http(s) opens in a new tab; an app deep link goes to the site's own\n // handler (the SDK never navigates to a custom scheme); anything else -\n // javascript:, data:, intent:, ... - is refused silently.\n // The site-wide link handler (setLinkHandler) sees it first.\n const url = safeHttpUrl(b.url);\n const context: LinkContext = { placementKey: key, itemId: item.id };\n if (url) {\n this.openLink(url, context, () => window.open(url, '_blank', 'noopener'));\n } else if (b.action === 'deep_link' && isAppDeepLink(b.url) && (mount.options.onDeepLink || this.links?.hasHandler)) {\n const deepLink = (b.url as string).trim();\n this.openLink(deepLink, context, () => {\n if (!mount.options.onDeepLink) return;\n try {\n mount.options.onDeepLink(deepLink, this.toItem(key, item, this.generation));\n } catch (error) {\n this.logger.error('The insertPlacement onDeepLink callback threw; ignored:', error);\n }\n });\n }\n return;\n }\n if (b.action === 'dismiss' || b.action === 'close') {\n this.dismissItem(key, item);\n }\n }\n\n /** Through the site-wide link handler when there is a router, else straight to the fallback. */\n private openLink(url: string, context: LinkContext, fallback: () => void): void {\n if (this.links) this.links.route(url, 'placement', context, fallback);\n else fallback();\n }\n\n private drawHtml(mount: Mount, item: PlacementItemWire, content: Extract<PlacementContent, { kind: 'html' }>): HTMLElement {\n const id = `p${++this.frameSeq}`;\n const iframe = document.createElement('iframe');\n iframe.className = 'joryio-placement-frame';\n iframe.setAttribute('data-joryio-item', item.id);\n // The overlay's sandbox exactly: same-origin so the bootstrap can reach\n // the host bridge; author script is stopped by the nonce CSP in the srcdoc.\n iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups');\n iframe.setAttribute('title', 'Placement');\n iframe.style.cssText = 'display:block;width:100%;height:0;border:0;';\n iframe.srcdoc = buildInAppSrcdoc(id, content.html || '', content.css || '', 'placement', PLACEMENT_BRIDGE_GLOBAL);\n this.frames.set(id, { iframe, key: mount.key, item });\n mount.frameIds.push(id);\n return iframe;\n }\n\n /**\n * The host object the placement frames call into. Every method is keyed by\n * the frame id and acts only while that frame is drawn.\n */\n private installBridge(): void {\n if (typeof window === 'undefined') return;\n const frame = (id: string) => this.frames.get(id);\n (window as any)[PLACEMENT_BRIDGE_GLOBAL] = {\n __owner: this,\n setSize: (id: string, _w: number, height: number) => {\n const f = frame(id);\n if (f && Number.isFinite(height) && height > 0) f.iframe.style.height = `${Math.ceil(height)}px`;\n },\n // A click counts, and a link opens, only from the person's own gesture.\n logClick: (id: string, action?: string) => {\n const f = frame(id);\n if (f && hasUserGesture()) this.report(f.key, f.item, 'clicked', action);\n },\n // Always a new tab, never the host page itself: inline content does not\n // navigate the page it sits in.\n navigate: (id: string, url: string) => {\n if (!frame(id) || !hasUserGesture()) return;\n const safe = safeHttpUrl(url);\n const f = frame(id);\n if (safe && f) this.openLink(safe, { placementKey: f.key, itemId: f.item.id }, () => window.open(safe, '_blank', 'noopener'));\n },\n closeMessage: (id: string) => {\n const f = frame(id);\n if (f) this.dismissItem(f.key, f.item);\n },\n logConversion: () => undefined,\n logCustomEvent: (id: string, name: string, properties?: Record<string, any>) => {\n if (frame(id) && name) this.runtime.bridge?.logCustomEvent(name, properties);\n },\n setCustomUserAttribute: (id: string, key: string, value: any) => {\n if (frame(id) && key) this.runtime.bridge?.setCustomUserAttribute(key, value);\n },\n changeUser: (id: string, userId: string) => {\n if (frame(id) && userId) this.runtime.bridge?.changeUser(userId);\n },\n requestPushPermission: (id: string) => {\n if (frame(id)) this.runtime.bridge?.requestPushPermission();\n },\n submitForm: () => Promise.resolve({ ok: false, message: 'Forms are not available in this spot.' }),\n };\n }\n\n // ── viewability ─────────────────────────────────────────────────────────\n\n private pageVisible(): boolean {\n return typeof document === 'undefined' || document.visibilityState !== 'hidden';\n }\n\n /** Whether any part of the host element is on screen (for \"never swap under the reader's eyes\"). */\n private observeHost(mount: Mount): void {\n if (typeof IntersectionObserver === 'undefined') return;\n const observer = new IntersectionObserver((entries) => {\n for (const e of entries) {\n mount.hostInView = e.isIntersecting;\n if (!e.isIntersecting && mount.pendingUpdate) this.render(mount);\n }\n });\n observer.observe(mount.element);\n mount.hostObserver = observer;\n }\n\n /** Measure `node` (the shared rule, trackViewable) while it stays drawn in `mount`. */\n private trackViewability(mount: Mount, node: Element, onViewable: () => void): void {\n let tracker: ViewTracker | null = null;\n tracker = trackViewable(node, () => {\n if (tracker && mount.trackers.includes(tracker)) onViewable();\n });\n mount.trackers.push(tracker);\n }\n\n private installPageVisibility(): void {\n if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return;\n this.pageListener = () => {\n for (const mount of this.mounts) {\n for (const t of mount.trackers) {\n if (this.pageVisible()) t.resume();\n else t.pause();\n }\n }\n };\n document.addEventListener('visibilitychange', this.pageListener);\n }\n\n // ── session cache ───────────────────────────────────────────────────────\n\n private subjectKey(): string {\n return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;\n }\n\n private loadCache(): void {\n try {\n if (typeof sessionStorage === 'undefined') return;\n sessionStorage.removeItem?.(LEGACY_CACHE_STORAGE_NAME);\n const raw = sessionStorage.getItem(placementsStorageKey(this.sdkKey));\n if (!raw) return;\n const stored = JSON.parse(raw);\n // Another visitor's answers (a reset or a login since) are not this one's.\n if (!stored || stored.subject !== this.subjectKey() || typeof stored.entries !== 'object') return;\n for (const [key, entry] of Object.entries<any>(stored.entries)) {\n if (validKey(key) && entry && entry.placement && typeof entry.fetchedAt === 'number') {\n this.cache.set(key, {\n placement: this.normalize(key, entry.placement),\n fetchedAt: entry.fetchedAt,\n url: typeof entry.url === 'string' ? entry.url : null,\n });\n }\n }\n } catch {\n /* storage blocked or corrupt: start empty */\n }\n }\n\n private persistCache(): void {\n try {\n if (typeof sessionStorage === 'undefined') return;\n const entries: Record<string, CacheEntry> = {};\n this.cache.forEach((entry, key) => {\n entries[key] = entry;\n });\n sessionStorage.setItem(placementsStorageKey(this.sdkKey), JSON.stringify({ subject: this.subjectKey(), entries }));\n } catch {\n /* storage blocked or full: memory only */\n }\n }\n}\n\n/** The wire's product cards, defensively typed: an entry without an id is dropped. */\nexport function toProducts(raw: unknown): PlacementProduct[] {\n if (!Array.isArray(raw)) return [];\n const str = (v: unknown) => (typeof v === 'string' ? v : null);\n return raw\n .filter((p): p is Record<string, unknown> => !!p && typeof p === 'object' && (typeof (p as any).id === 'string' || typeof (p as any).id === 'number'))\n .map((p) => ({\n id: String(p.id),\n title: str(p.title),\n price: str(p.price),\n compareAtPrice: str(p.compareAtPrice),\n discountPercent: typeof p.discountPercent === 'number' ? p.discountPercent : null,\n imageUrl: str(p.imageUrl),\n url: str(p.url),\n }));\n}\n","/**\n * The default card feed (`mountCardFeed`), drawn from what the core's\n * CardFeedHost gives it (src/core/cards-ui-contract.ts). Lives in\n * `joryio-cards-ui.min.js`, loaded only by a page that mounts a feed.\n *\n * Text is set as text, never as markup; colors and fonts are the page's.\n */\nimport type { Card, MountCardFeedOptions } from '../core/cards';\nimport type { CardFeedHost, CardFeedView } from '../core/cards-ui-contract';\nimport type { ViewTracker } from '../core/placements';\nimport { isAppDeepLink, safeHttpUrl } from '../core/placements';\n\ntype DrawnCard = { node: HTMLElement; sig: string; tracker: ViewTracker | null };\n\nconst DEFAULT_LABELS = { emptyText: 'No messages yet', pinnedLabel: 'Pinned', dismissLabel: 'Dismiss', unreadLabel: 'Unread' };\n\nexport function mountFeedView(element: HTMLElement, options: MountCardFeedOptions, host: CardFeedHost): CardFeedView {\n const opts = options || {};\n let removed = false;\n let loadingMore = false;\n /** Drawn card nodes by card key, reused while the card looks the same. */\n let nodes = new Map<string, DrawnCard>();\n let empty: HTMLElement | null = null;\n\n const root = document.createElement('div');\n root.className = 'joryio-card-feed';\n root.setAttribute('role', 'list');\n const sentinel = document.createElement('div');\n sentinel.className = 'joryio-card-feed-end';\n sentinel.setAttribute('aria-hidden', 'true');\n element.appendChild(root);\n\n /** A tap: report clicked, then open the url by the placement link rule (the site-wide link handler sees it first). */\n const click = (card: Card): void => {\n host.markCardClicked(card);\n const url = card.url?.trim();\n if (!url) return;\n const context = { campaignId: card.campaignId, cardId: card.id };\n const http = safeHttpUrl(url);\n if (http) {\n host.routeLink(http, context, () => {\n try {\n window.open(http, '_blank', 'noopener');\n } catch (error) {\n host.logger.debug('Could not open the card link', error);\n }\n });\n return;\n }\n if (isAppDeepLink(url)) {\n // The site routes its own links; the SDK never navigates to a custom scheme.\n host.routeLink(url, context, () => {\n if (!opts.onDeepLink) return;\n try {\n opts.onDeepLink(url, card);\n } catch (error) {\n host.logger.error('The mountCardFeed onDeepLink callback threw; ignored:', error);\n }\n });\n return;\n }\n host.logger.warn('Card link refused: not http(s) or an app deep link');\n };\n\n const label = (k: keyof typeof DEFAULT_LABELS): string => {\n const v = opts[k];\n return typeof v === 'string' ? v : DEFAULT_LABELS[k];\n };\n\n /** Image on top, a header with the unread dot, the title, the pinned marker and the dismiss control, then the body and the button. */\n const drawCard = (card: Card, generation: number): HTMLElement => {\n const el = document.createElement('div');\n el.className = 'joryio-card';\n el.setAttribute('role', 'listitem');\n el.setAttribute('data-joryio-card', card.id);\n el.setAttribute('data-joryio-card-read', card.read ? 'true' : 'false');\n if (card.pinned) el.setAttribute('data-joryio-card-pinned', 'true');\n el.style.cssText = `position:relative;box-sizing:border-box;padding:12px 16px;${card.url ? 'cursor:pointer;' : ''}`;\n const open = () => !removed && generation === host.generation() && click(card);\n if (card.url) {\n el.setAttribute('tabindex', '0');\n el.addEventListener('click', open);\n el.addEventListener('keydown', (e: any) => {\n if (e?.key === 'Enter' && e?.target === el) open();\n });\n }\n const image = safeHttpUrl(card.imageUrl);\n if (image) {\n const img = document.createElement('img');\n img.className = 'joryio-card-image';\n img.src = image;\n img.alt = '';\n img.style.cssText = 'display:block;max-width:100%;height:auto;margin-bottom:8px;';\n el.appendChild(img);\n }\n const header = document.createElement('div');\n header.className = 'joryio-card-header';\n header.style.cssText = 'display:flex;align-items:center;gap:6px;';\n if (!card.read) {\n const dot = document.createElement('span');\n dot.className = 'joryio-card-unread';\n dot.setAttribute('role', 'img');\n dot.setAttribute('aria-label', label('unreadLabel'));\n dot.textContent = '●';\n dot.style.cssText = 'font-size:10px;line-height:1;';\n header.appendChild(dot);\n }\n const title = document.createElement('div');\n title.className = 'joryio-card-title';\n title.textContent = card.title || '';\n title.style.cssText = 'flex:1;font-weight:bold;';\n header.appendChild(title);\n if (card.pinned) {\n const pinned = document.createElement('span');\n pinned.className = 'joryio-card-pinned';\n pinned.textContent = label('pinnedLabel');\n pinned.style.cssText = 'font-size:0.8em;';\n header.appendChild(pinned);\n }\n const dismiss = document.createElement('button');\n dismiss.type = 'button';\n dismiss.className = 'joryio-card-dismiss';\n dismiss.setAttribute('aria-label', label('dismissLabel'));\n dismiss.textContent = '×';\n dismiss.style.cssText = 'background:none;border:0;padding:4px 8px;color:inherit;font:inherit;font-size:1.25em;line-height:1;cursor:pointer;';\n dismiss.addEventListener('click', (e: any) => {\n e?.stopPropagation?.();\n if (generation === host.generation()) host.dismissCard(card);\n });\n header.appendChild(dismiss);\n el.appendChild(header);\n if (card.body) {\n const body = document.createElement('div');\n body.className = 'joryio-card-body';\n body.textContent = card.body;\n el.appendChild(body);\n }\n if (card.buttonText && card.url) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'joryio-card-button';\n btn.textContent = card.buttonText;\n btn.style.cssText = 'margin-top:8px;font:inherit;';\n btn.addEventListener('click', (e: any) => {\n e?.stopPropagation?.();\n open();\n });\n el.appendChild(btn);\n }\n return el;\n };\n\n const render = (): void => {\n if (removed) return;\n const feed = host.view();\n const generation = host.generation();\n const keep = new Map<string, DrawnCard>();\n for (const card of feed.cards) {\n const key = `${card.id}\\u0000${card.createdAt}`;\n const sig = JSON.stringify(card);\n const existing = nodes.get(key);\n if (existing && existing.sig === sig) {\n keep.set(key, existing);\n nodes.delete(key);\n continue;\n }\n const node = drawCard(card, generation);\n // Viewed, then read, once at least half the card was on screen for a second.\n const tracker = card.read\n ? null\n : host.trackViewable(node, () => {\n if (generation !== host.generation()) return;\n host.markCardViewed(card);\n host.markCardRead(card);\n });\n keep.set(key, { node, sig, tracker });\n }\n // Cards no longer in the feed (dismissed, expired, another person's) go.\n nodes.forEach((n) => {\n n.tracker?.cancel();\n n.node.remove();\n });\n nodes = keep;\n if (empty) {\n empty.remove();\n empty = null;\n }\n sentinel.remove();\n if (!feed.cards.length) {\n empty = document.createElement('div');\n empty.className = 'joryio-card-feed-empty';\n empty.textContent = label('emptyText');\n empty.style.cssText = 'padding:32px 16px;text-align:center;';\n root.appendChild(empty);\n } else {\n // appendChild moves a node that is already drawn: the order follows the feed.\n keep.forEach((n) => root.appendChild(n.node));\n }\n root.appendChild(sentinel);\n element.setAttribute('data-joryio-card-feed-state', feed.cards.length ? 'filled' : 'empty');\n if (opts.onRender) {\n try {\n opts.onRender(feed, element);\n } catch (error) {\n host.logger.error('The mountCardFeed onRender callback threw; ignored:', error);\n }\n }\n };\n\n // Load the next page when the end of the feed comes into view.\n let observer: IntersectionObserver | null = null;\n if (typeof IntersectionObserver !== 'undefined') {\n observer = new IntersectionObserver((entries) => {\n if (removed || loadingMore || !entries.some((e) => e.isIntersecting)) return;\n loadingMore = true;\n host\n .loadMore()\n .catch(() => undefined)\n .finally(() => {\n loadingMore = false;\n });\n });\n observer.observe(sentinel);\n }\n\n // The viewability dwell stops while the page is hidden.\n const onVisibility = () => {\n const visible = document.visibilityState !== 'hidden';\n nodes.forEach((n) => {\n if (!n.tracker) return;\n if (visible) n.tracker.resume();\n else n.tracker.pause();\n });\n };\n if (typeof document.addEventListener === 'function') document.addEventListener('visibilitychange', onVisibility);\n\n return {\n render,\n remove() {\n if (removed) return;\n removed = true;\n observer?.disconnect();\n if (typeof document.removeEventListener === 'function') document.removeEventListener('visibilitychange', onVisibility);\n nodes.forEach((n) => n.tracker?.cancel());\n nodes.clear();\n root.remove();\n },\n };\n}\n","/**\n * The contract between the core (src/core/cards.ts) and the default card feed\n * renderer, `joryio-cards-ui.min.js` (src/cards-ui/), a separate file next to\n * `joryio.min.js` on the SDK host (BACKLOG D444). Only a page that calls\n * `mountCardFeed` downloads it; the data API (getCards, markCard*, ...) stays\n * in the core.\n *\n * The renderer registers one global, `__joryioCardsUi`, and nothing else. The\n * core reads it once, checks `version`, keeps the reference, and hands each\n * mount a `CardFeedHost`: what the renderer may do is exactly what the public\n * API already lets a page do (read the feed, report viewed / read / clicked /\n * dismissed, pass a link to its own link handler, load the next page) - never\n * the delivery tokens, the request code or the storage. A page that replaced the global\n * would get nothing it could not already call on `window.Joryio`.\n *\n * Type-only imports: nothing of the core is bundled into the renderer through here.\n */\nimport type { Card, CardFeed, MountCardFeedOptions } from './cards';\nimport type { ViewTracker } from './placements';\nimport type { Logger } from '../utils/logger';\n\nexport const CARDS_UI_GLOBAL = '__joryioCardsUi';\n/** Bumped on a breaking change to CardFeedHost / CardsUiBundleApi; a renderer of another version is refused. */\nexport const CARDS_UI_API_VERSION = 1;\n/** The file next to joryio.min.js on the SDK host (and in the npm package's dist/). */\nexport const CARDS_UI_BUNDLE_FILE = 'joryio-cards-ui.min.js';\n\n/** What one mounted feed may ask of the core. */\nexport interface CardFeedHost {\n /** The feed now (cached, with this browser's read / dismissed state applied). */\n view(): CardFeed;\n /** Bumped when the person or the consent changes: a node drawn under an older one does nothing. */\n generation(): number;\n markCardViewed(card: Card): void;\n markCardRead(card: Card): void;\n markCardClicked(card: Card): void;\n dismissCard(card: Card): void;\n /** Hand a card link to the site-wide link handler (`setLinkHandler`); `fallback` runs when there is none or it declined. */\n routeLink(url: string, context: { campaignId?: string; cardId?: string }, fallback: () => void): void;\n /** Load the page after the feed's nextCursor, if any (a no-op on the last page). */\n loadMore(): Promise<void>;\n /** The viewability rule (half the card on screen for the dwell), the same as placements'. */\n trackViewable(node: Element, onViewable: () => void): ViewTracker;\n logger: Logger;\n}\n\n/** One drawn feed. */\nexport interface CardFeedView {\n /** Redraw from host.view() (the core calls it on every feed change). */\n render(): void;\n /** Take out everything drawn and stop observing. */\n remove(): void;\n}\n\nexport interface CardsUiBundleApi {\n version: number;\n mount(element: HTMLElement, options: MountCardFeedOptions, host: CardFeedHost): CardFeedView;\n}\n","/**\n * The default card feed bundle - `joryio-cards-ui.min.js` on the SDK host,\n * next to `joryio.min.js` (BACKLOG D444).\n *\n * Loaded by the core (src/core/cards.ts) the first time the page calls\n * `mountCardFeed`, so a visitor of a site without a feed never downloads it.\n * It registers one global and does nothing else on its own: no request, no\n * listener, until the core calls `mount` with a CardFeedHost.\n *\n * A bundler user who does not want the SDK host fetch imports this file once\n * (`import '@joryio/web-sdk/dist/joryio-cards-ui.min.js'`): the core finds the\n * global and draws at once.\n */\nimport { mountFeedView } from './card-feed-view';\nimport { CARDS_UI_API_VERSION, CARDS_UI_GLOBAL, type CardsUiBundleApi } from '../core/cards-ui-contract';\n\nconst api: CardsUiBundleApi = {\n version: CARDS_UI_API_VERSION,\n mount: mountFeedView,\n};\n\nif (typeof window !== 'undefined' && !(window as any)[CARDS_UI_GLOBAL]) {\n (window as any)[CARDS_UI_GLOBAL] = api;\n}\n\nexport { api as cardsUiApi };\n"],"names":["safeHttpUrl","url","test","REFUSED_LINK_SCHEMES","DEFAULT_LABELS","emptyText","pinnedLabel","dismissLabel","unreadLabel","CARDS_UI_GLOBAL","api","version","mount","element","options","host","opts","removed","loadingMore","nodes","Map","empty","root","document","createElement","className","setAttribute","sentinel","appendChild","label","k","v","drawCard","card","generation","el","id","read","pinned","style","cssText","open","markCardClicked","_a","trim","context","campaignId","cardId","http","routeLink","window","error","logger","debug","m","exec","scheme","toLowerCase","includes","isAppDeepLink","onDeepLink","warn","click","addEventListener","e","key","target","image","imageUrl","img","src","alt","header","dot","textContent","title","dismiss","type","stopPropagation","dismissCard","body","buttonText","btn","observer","IntersectionObserver","entries","some","isIntersecting","loadMore","catch","finally","observe","onVisibility","visible","visibilityState","forEach","n","tracker","resume","pause","render","feed","view","keep","cards","createdAt","sig","JSON","stringify","existing","get","set","delete","node","trackViewable","markCardViewed","markCardRead","cancel","remove","length","onRender","disconnect","removeEventListener","clear"],"mappings":"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"}
1
+ {"version":3,"file":"joryio-cards-ui.min.js","sources":["../src/core/placements.ts","../src/cards-ui/card-feed-view.ts","../src/core/cards-ui-contract.ts","../src/cards-ui/index.ts"],"sourcesContent":["/**\n * Placements (docs/PLACEMENTS_PLAN.md, BACKLOG D444): named spots inside the\n * page - `home_hero`, `cart_upsell` - that Joryio fills per visitor from\n * placement campaigns and journey steps.\n *\n * Unlike overlays (inapp.ts) a placement is drawn INSIDE an element the site\n * owns, or handed to the site as data to draw itself. The serve endpoint is\n * `POST /v1/in-app/placements`; interactions are the in-app event family\n * (`/v1/in-app/track`), with the placement key alongside.\n *\n * The rules this file implements, and the names every Joryio SDK shares\n * (pinned by packages/backend/src/modules/tracking/sdk-placements-parity.spec.ts):\n *\n * - `insertPlacement(key, element)`, `<div data-joryio-placement=\"key\">`\n * auto-mount, `getPlacements([...])`, `refreshPlacements(keys?)`,\n * `onPlacementsUpdated(cb)`; `item.markDisplayed()`, `markClicked()`,\n * `markDismissed()`, `placement.markDisplayed()` (holdout exposure).\n * - Batched: every key asked for within PLACEMENT_BATCH_WINDOW_MS goes in one\n * request, at most PLACEMENT_MAX_KEYS_PER_REQUEST keys each.\n * - Cached per key for the placement's `ttlSeconds` (memory + sessionStorage,\n * scoped to the visitor), and a key is fetched from the network at most once\n * per PLACEMENT_MIN_REFRESH_SECONDS; extra refreshes coalesce.\n * - Viewable = at least PLACEMENT_VIEWABLE_FRACTION of the item in view for\n * IN_APP_DISPLAY_DWELL_MS continuously, page visible; reported once per\n * delivery.\n * - Never swaps content under the reader's eyes: an update to a placement that\n * is on screen is applied when it next leaves the viewport or is mounted again.\n * - Consent: without tracking consent the request names nobody (no user id, no\n * anonymous id, no session), the server answers with generic content and no\n * delivery token, and the SDK reports nothing.\n * - HTML items render in the same sandboxed, nonce-CSP frame as overlays, and\n * only when `allowHtmlJsInAppMessages` is on.\n * - Show when (D465, show-when.ts): an item with a `showWhen` other than load\n * is held - neither drawn nor handed to the data API - until its moment in\n * this page view, then the key's spots re-draw and onPlacementsUpdated\n * fires; a route change holds it again until the new page's moment. A\n * control answer's `showWhen` delays its exposure the same way, and\n * `deferredControls` are reported once their own moment has come and the\n * spot was viewable. An event named in `recheckOn` (or one an item waits\n * on) re-fetches the key at once, past the 30 s limit, once per page view.\n * - Server-filled slots (D466): a store plugin may write a slot's\n * content into the HTML when Joryio's answer for it is the same for every\n * visitor (`data-joryio-server-filled` on the slot, the fill inside it, the\n * marker block's `fills`). The SDK keeps that drawing when the visitor's own\n * answer is the same campaign, variant and products - no redraw - and\n * reports its impression with the visitor's own token once it is viewable\n * (nothing without consent, as for every item); otherwise it replaces it\n * with the visitor's answer, or removes it per the empty behaviour.\n */\n\nimport { JoryioSubscription, joryioSubscription } from './subscription';\nimport { bucketHash } from '../utils/bucket-hash';\nimport { currentPageUrl, PAGE_CONTEXT_CAPABILITY, type PageContextTracker } from './page-context';\nimport { Logger } from '../utils/logger';\nimport { eventNames, isDeferred, parseShowWhen, type RecheckEvent, type ShowWhenMoments } from './show-when';\nimport { sdkIdentityHeaders } from './config';\nimport { IdentityManager } from './identity';\nimport { SessionManager } from './session';\nimport type { LinkContext, LinkRouter } from './links';\nimport { serverMarkerElement } from './page-edits';\nimport {\n buildInAppSrcdoc,\n inAppTriggerFilterMatches,\n normalizedElementId,\n IN_APP_DISPLAY_DWELL_MS,\n InAppAuthProvider,\n InAppTrigger,\n} from './inapp';\n\n/** Share of an item that must be in view for it to count as seen. Same name and value on every Joryio SDK. */\nexport const PLACEMENT_VIEWABLE_FRACTION = 0.5;\n/** A placement key is fetched from the network at most once per this many seconds. Same on every Joryio SDK. */\nexport const PLACEMENT_MIN_REFRESH_SECONDS = 30;\n/** Keys asked for within this window go in one request. */\nexport const PLACEMENT_BATCH_WINDOW_MS = 50;\n/** The serve endpoint takes 1-10 keys per request. */\nexport const PLACEMENT_MAX_KEYS_PER_REQUEST = 10;\n/** How long an event-triggered item stays eligible after its event, when the server does not say. */\nexport const PLACEMENT_DEFAULT_TRIGGER_WINDOW_SECONDS = 1800;\n/**\n * A drawn product card's tap is reported as `clicked` with the elementId\n * `product:<product id>` (at most 128 characters), so the click report counts\n * clicks per product. Same name and value on every Joryio SDK.\n */\nexport const PLACEMENT_PRODUCT_ELEMENT_PREFIX = 'product:';\n/** 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. */\nexport const PLACEMENT_PRODUCT_CARD_WIDTH = 160;\n/** The elementId a product card's click is reported with - use it when you draw the cards yourself. */\nexport function placementProductElementId(productId: string): string {\n return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);\n}\n/**\n * Server-filled slots (D466; backend common/placements/server-slot-fills.ts,\n * the plugins' shared core). Same names and values pinned by\n * server-slot-fills-sdk-parity.spec.ts.\n */\nexport const SERVER_FILLED_ATTR = 'data-joryio-server-filled';\nexport const SERVER_FILL_ATTR = 'data-joryio-server-fill';\nexport const SERVER_FILLS_MARKER_KEY = 'fills';\n\n/** One slot the store's server filled: what it drew, from the marker. */\ninterface ServerFill {\n campaignId: string;\n variantId: string;\n products: string[];\n /** The fill's `.joryio-placement` wrapper inside the slot. */\n wrapper: HTMLElement;\n}\n\n/** Used when an answer carries no ttlSeconds. */\nconst DEFAULT_TTL_SECONDS = 300;\n/** The pre-scoping, origin-wide name - never read, removed on start. */\nconst LEGACY_CACHE_STORAGE_NAME = 'joryio_placements_v1';\n/**\n * Per workspace, like the flags cache (flagsStorageKey): two workspaces on one\n * site that know a visitor by the same ids must never read each other's\n * placements. Carries a hash of the SDK key, never the key itself.\n */\nexport const placementsStorageKey = (sdkKey: string): string => `joryio_placements_v1_${bucketHash(sdkKey).toString(36)}`;\n/** The host-window object the placement HTML frames call into (overlays use their own). */\nconst PLACEMENT_BRIDGE_GLOBAL = '__joryioPlacement';\nconst PLACEMENT_KEY_PATTERN = /^[a-z0-9][a-z0-9_]{0,63}$/;\n\nexport type PlacementEmptyBehavior = 'collapse' | 'keep_space';\nexport type PlacementItemKind = 'native' | 'html' | 'data';\n/** The consent the request carries: the existing wire values. */\nexport type PlacementConsent = 'granted' | 'denied' | 'pending';\n\nexport type PlacementContent =\n | { kind: 'html'; html: string; css?: string }\n | {\n kind: 'native';\n title?: string;\n body?: string;\n imageUrl?: string;\n buttons?: Array<{ id: string; text: string; action: string; url?: string }>;\n closeButton?: boolean;\n };\n\n/** One item as the server sends it. */\n/** A product card of a recommendation placement item (D444 Phase 2b). Same names on all five SDKs. */\nexport interface PlacementProduct {\n id: string;\n title: string | null;\n price: string | null;\n compareAtPrice: string | null;\n discountPercent: number | null;\n imageUrl: string | null;\n url: string | null;\n}\n\nexport interface PlacementItemWire {\n id: string;\n variantId?: string | null;\n deliveryToken?: string | null;\n priority?: number;\n kind: PlacementItemKind;\n data?: Record<string, string | number | boolean>;\n content?: PlacementContent | null;\n /** Products picked for the person by a recommendation model (absent = none). */\n products?: PlacementProduct[] | null;\n triggers?: InAppTrigger[] | null;\n /** How long an event trigger keeps the item eligible (seconds). */\n placementTriggerWindowSeconds?: number | null;\n expiresAt?: string | null;\n /** Echoed in `shown` when present; the item id otherwise. */\n deliveryId?: string | null;\n /** Show when (D465): the item's moment; absent = on load. */\n showWhen?: unknown;\n}\n\n/** One placement as the server sends it. */\nexport interface PlacementWire {\n placementKey: string;\n emptyBehavior?: PlacementEmptyBehavior;\n maxItems?: number;\n ttlSeconds?: number;\n isControl?: boolean;\n controlToken?: string | null;\n items?: PlacementItemWire[];\n /**\n * D444 Phase 4: the answer depends on the page (a campaign of this\n * placement has page targeting), so it is cached per page (origin + path)\n * and asked again on a route change.\n */\n pageScoped?: boolean;\n /** Show when (D465), on a control answer only: the moment the held-out treatment would have shown. */\n showWhen?: unknown;\n /** Control exposures to report once their moment came and the spot was viewable. */\n deferredControls?: Array<{ controlToken: string; showWhen: unknown }>;\n /** Event names that re-fetch this key at once when tracked. */\n recheckOn?: string[];\n}\n\nexport interface PlacementsResponse {\n success: boolean;\n evaluatedAt?: string;\n placements?: Record<string, PlacementWire>;\n}\n\n/** An item to draw, with the calls that report what the person did with it. */\nexport interface PlacementItem {\n id: string;\n variantId?: string | null;\n kind: PlacementItemKind;\n data: Record<string, string | number | boolean>;\n content?: PlacementContent | null;\n /** Products picked for the person by a recommendation model; [] when the item has none. Draw them as cards. */\n products: PlacementProduct[];\n priority?: number;\n expiresAt?: string | null;\n /** Report a viewable impression (the app drew it itself). Once per delivery. */\n markDisplayed(): void;\n /** Report a tap or click; `elementId` names the button or link. */\n markClicked(elementId?: string): void;\n /** Report that the person closed it. The placement's dismissal rule applies on the server. */\n markDismissed(): void;\n}\n\nexport interface Placement {\n placementKey: string;\n items: PlacementItem[];\n isControl: boolean;\n emptyBehavior: PlacementEmptyBehavior;\n maxItems: number;\n ttlSeconds: number;\n /**\n * For a held-out visitor (`isControl`): report that the (empty) spot was\n * viewable. Drawn placements do this themselves; a data-first app calls it\n * when its spot was on screen. No-op for a placement that is not a control.\n */\n markDisplayed(): void;\n}\n\nexport interface PlacementHandle {\n placementKey: string;\n element: HTMLElement;\n /** Stop filling the element and remove what the SDK drew. */\n remove(): void;\n}\n\nexport interface InsertPlacementOptions {\n /** Called after the SDK (re)drew the element, with what it drew. */\n onRender?: (placement: Placement, element: HTMLElement) => void;\n /**\n * A `deep_link` button with an app link (`myapp://cart`) was tapped: route\n * it in your app (the click is already reported). An http(s) link is opened\n * by the SDK in a new tab instead, and any other scheme (javascript:, data:,\n * intent:, ...) is refused - it reaches neither this handler nor the page.\n * A handler set with `setLinkHandler` sees every link first; this one is\n * called when it returns false.\n */\n onDeepLink?: (url: string, item: PlacementItem) => void;\n /**\n * Draw an item's recommended products as a horizontal row of cards (image,\n * title, price, optional button) below its content - alone for a data item.\n * Default true; false leaves the products to you (`onRender` / getPlacements).\n */\n showProducts?: boolean;\n /** Label of a button on every product card; unset = no button (the whole card opens the product). */\n productButtonText?: string;\n /** Width of one product card in CSS px (default PLACEMENT_PRODUCT_CARD_WIDTH). */\n productCardWidth?: number;\n}\n\nexport type PlacementsUpdatedCallback = (placements: Record<string, Placement>) => void;\n\n/** What the placement manager needs from the SDK. */\nexport interface PlacementRuntime {\n /**\n * The consent to send, or null when nothing may be sent at all (SDK not\n * initialised, disabled, ingestion suspended). `granted` = personal serving\n * and reporting; anything else = an anonymous request and no reporting.\n */\n consent: () => PlacementConsent | null;\n allowHtml: () => boolean;\n requestTimeoutMs?: number;\n noteStatus?: (status: number, data: any) => void;\n /** The SDK calls the HTML bridge reaches (custom events, attributes, push). */\n bridge?: {\n logCustomEvent: (name: string, properties?: Record<string, any>) => void;\n setCustomUserAttribute: (key: string, value: any) => void;\n changeUser: (userId: string) => void;\n requestPushPermission: () => void;\n };\n}\n\ninterface CacheEntry {\n placement: PlacementWire;\n fetchedAt: number;\n /** The page it was answered for (origin + path); matters only when `pageScoped`. */\n url?: string | null;\n}\n\ninterface Waiter {\n keys: string[];\n resolve: () => void;\n}\n\ninterface Mount {\n key: string;\n element: HTMLElement;\n options: InsertPlacementOptions;\n wrapper: HTMLElement | null;\n /** Item ids currently drawn (the `shown` list sent with the next request). */\n shown: string[];\n /** A newer answer that waits until the spot leaves the viewport. */\n pendingUpdate: boolean;\n /** Whether any part of the host element is in the viewport. */\n hostInView: boolean;\n hostObserver: IntersectionObserver | null;\n trackers: ViewTracker[];\n frameIds: string[];\n /** D466: the store's server drew this slot; kept or replaced once the visitor's answer is known. */\n serverFill: ServerFill | null;\n}\n\nconst nowMs = () => Date.now();\n\nfunction validKey(key: unknown): key is string {\n return typeof key === 'string' && PLACEMENT_KEY_PATTERN.test(key);\n}\n\n/** The page address without query or fragment: context only, and query strings carry PII. */\nfunction pageContext(): { url: string | null; screen: null } {\n return { url: currentPageUrl(), screen: null };\n}\n\n/**\n * Whether the page has a live user gesture. User activation propagates from a\n * frame to its ancestors, so a click inside a placement frame activates the\n * host page too; a call made by anything else (a timer, a synthetic event)\n * finds none. Browsers without the API are trusted - the frame's nonce CSP\n * already stops author script.\n */\nfunction hasUserGesture(): boolean {\n try {\n const activation = (navigator as any)?.userActivation;\n return activation ? activation.isActive === true : true;\n } catch {\n return true;\n }\n}\n\n/** An http(s) URL the SDK may open itself, or null. The one link rule of placements and content cards. */\nexport function safeHttpUrl(url: unknown): string | null {\n return typeof url === 'string' && /^https?:\\/\\//i.test(url) ? url : null;\n}\n\n/** Schemes never opened nor handed to the site, whatever the link says (the backend's card / placement link rule). */\nconst REFUSED_LINK_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'blob', 'about', 'content', 'intent'];\n\n/**\n * An app deep link (`myapp://cart`) that may go to the site's own handler: a\n * `scheme://` link whose scheme is not http(s) and not a refused one. The SDK\n * never navigates to it itself. The same rule on every Joryio SDK.\n */\nexport function isAppDeepLink(url: unknown): boolean {\n if (typeof url !== 'string') return false;\n const m = /^([a-z][a-z0-9+.-]*):\\/\\/./i.exec(url.trim());\n if (!m) return false;\n const scheme = m[1].toLowerCase();\n return scheme !== 'http' && scheme !== 'https' && !REFUSED_LINK_SCHEMES.includes(scheme);\n}\n\n/** One element's viewability measurement (see trackViewable). */\nexport interface ViewTracker {\n observer: IntersectionObserver | null;\n timer: ReturnType<typeof setTimeout> | null;\n inView: boolean;\n /** Restart the dwell when the page becomes visible again. */\n resume(): void;\n /** Stop the dwell while the page is hidden. */\n pause(): void;\n /** Stop measuring for good. */\n cancel(): void;\n}\n\nfunction pageIsVisible(): boolean {\n return typeof document === 'undefined' || document.visibilityState !== 'hidden';\n}\n\n/**\n * Call `onViewable` once `node` has had PLACEMENT_VIEWABLE_FRACTION of its\n * area in view for IN_APP_DISPLAY_DWELL_MS continuously, with the page\n * visible. Without IntersectionObserver (very old browsers) the page being\n * visible for the dwell counts. Shared by placements and the card feed; the\n * caller forwards page visibility changes to `resume` / `pause`.\n */\nexport function trackViewable(node: Element, onViewable: () => void): ViewTracker {\n let cancelled = false;\n const tracker: ViewTracker = {\n observer: null,\n timer: null,\n inView: false,\n resume: () => {\n if (cancelled || tracker.timer || !tracker.inView || !pageIsVisible()) return;\n tracker.timer = setTimeout(() => {\n tracker.timer = null;\n if (!cancelled && tracker.inView && pageIsVisible()) {\n cancelled = true;\n tracker.observer?.disconnect();\n onViewable();\n }\n }, IN_APP_DISPLAY_DWELL_MS);\n },\n pause: () => {\n if (tracker.timer) clearTimeout(tracker.timer);\n tracker.timer = null;\n },\n cancel: () => {\n cancelled = true;\n tracker.observer?.disconnect();\n tracker.pause();\n },\n };\n if (typeof IntersectionObserver === 'undefined') {\n tracker.inView = true;\n tracker.resume();\n return tracker;\n }\n tracker.observer = new IntersectionObserver(\n (entries) => {\n for (const e of entries) {\n // A zero-area target (a collapsed control spot) reports ratio 1 while intersecting.\n tracker.inView = e.isIntersecting && e.intersectionRatio >= PLACEMENT_VIEWABLE_FRACTION;\n if (tracker.inView) tracker.resume();\n else tracker.pause();\n }\n },\n { threshold: [0, PLACEMENT_VIEWABLE_FRACTION, 1] },\n );\n tracker.observer.observe(node);\n return tracker;\n}\n\nexport class PlacementManager {\n /** The SDK's link router (`setLinkHandler`); set by the SDK after construction. */\n links: LinkRouter | null = null;\n\n private cache = new Map<string, CacheEntry>();\n /** When each key last went to the network (the client rate limit). */\n private lastNetworkAt = new Map<string, number>();\n private inflight = new Map<string, Promise<void>>();\n private batchKeys = new Set<string>();\n private batchTimer: ReturnType<typeof setTimeout> | null = null;\n private batchWaiters: Waiter[] = [];\n /** Refreshes asked for inside the rate-limit window, run when it opens. */\n private deferredKeys = new Set<string>();\n private deferredTimer: ReturnType<typeof setTimeout> | null = null;\n private listeners = new Set<PlacementsUpdatedCallback>();\n private mounts = new Set<Mount>();\n /** Delivery handles already reported, per transition (displayed once, control once). */\n private reported = new Set<string>();\n /** Event-triggered items: when their event fired. */\n private triggeredAt = new Map<string, number>();\n /** Items the person dismissed: hidden locally until the server's next answer. */\n private dismissedLocally = new Set<string>();\n /** Bumped when WHO the placements are for changes; older answers are discarded. */\n private generation = 0;\n private mutationObserver: MutationObserver | null = null;\n private frames = new Map<string, { iframe: HTMLIFrameElement; key: string; item: PlacementItemWire }>();\n private frameSeq = 0;\n private pageListener: (() => void) | null = null;\n private destroyed = false;\n private page: PageContextTracker | null = null;\n private pageUnsubscribe: (() => void) | null = null;\n /** Show when (D465): the moments; null = this manager holds every non-load item for good. */\n private moments: ShowWhenMoments | null = null;\n private momentsUnsubscribe: (() => void) | null = null;\n /** Held items / control answers revealed in this page view (handles; `ctl:` + token for a control). */\n private revealed = new Set<string>();\n /** Keys whose spot was viewable in this page view (drawn item, control spot, or markDisplayed). */\n private spotViewable = new Set<string>();\n /** `key + event` re-checked in this page view. */\n private rechecked = new Set<string>();\n /** The event the next batch re-checks for (only a re-check request carries it). */\n private recheckEvent: RecheckEvent | null = null;\n\n constructor(\n private apiEndpoint: string,\n private sdkKey: string,\n private identity: IdentityManager,\n private session: SessionManager,\n private logger: Logger,\n private runtime: PlacementRuntime,\n private auth?: InAppAuthProvider,\n ) {\n this.loadCache();\n this.installBridge();\n this.installPageVisibility();\n }\n\n // ── public API ──────────────────────────────────────────────────────────\n\n /** Draw placement `key` into `element`. Returns a handle whose remove() stops it. */\n insertPlacement(key: string, element: HTMLElement, options: InsertPlacementOptions = {}): PlacementHandle | null {\n if (!validKey(key)) {\n this.logger.warn(`insertPlacement: \"${key}\" is not a placement key (a-z, 0-9 and _, up to 64)`);\n return null;\n }\n if (!element || typeof (element as any).appendChild !== 'function') {\n this.logger.warn('insertPlacement: an element is required');\n return null;\n }\n for (const existing of this.mounts) {\n if (existing.element === element) this.unmount(existing);\n }\n const mount: Mount = {\n key,\n element,\n options,\n wrapper: null,\n shown: [],\n pendingUpdate: false,\n hostInView: false,\n hostObserver: null,\n trackers: [],\n frameIds: [],\n serverFill: this.serverFillOf(key, element),\n };\n this.mounts.add(mount);\n this.observeHost(mount);\n const cached = this.freshEntry(key);\n if (cached) this.render(mount);\n this.ensure([key]).then(() => {\n // Drawn already when the answer changed the cache (applyChanged); an\n // unchanged or failed answer still draws what there is.\n if (this.mounts.has(mount) && !mount.wrapper) this.render(mount);\n }).catch((error) => this.logger.debug('Placement fetch failed:', error));\n return { placementKey: key, element, remove: () => this.unmount(mount) };\n }\n\n /** The placements for `keys`, from the cache when fresh, from the network otherwise. */\n async getPlacements(keys: string[]): Promise<Record<string, Placement>> {\n const wanted = this.cleanKeys(keys);\n await this.ensure(wanted);\n const out: Record<string, Placement> = {};\n for (const key of wanted) out[key] = this.toPlacement(key);\n return out;\n }\n\n /** Ask the server again for `keys` (default: every placement on the page or in the cache). */\n async refreshPlacements(keys?: string[]): Promise<void> {\n const wanted = keys ? this.cleanKeys(keys) : this.knownKeys();\n if (!wanted.length) return;\n await this.fetchKeys(wanted, true);\n }\n\n /** Called with the placements that changed after each answer. Returns a JoryioSubscription. */\n onPlacementsUpdated(callback: PlacementsUpdatedCallback): JoryioSubscription {\n if (typeof callback !== 'function') return joryioSubscription(() => undefined);\n // One entry per subscription, so the same function subscribed twice is two subscriptions.\n const entry: PlacementsUpdatedCallback = (placements) => callback(placements);\n this.listeners.add(entry);\n return joryioSubscription(() => {\n this.listeners.delete(entry);\n });\n }\n\n /** Mount every `[data-joryio-placement]` element on the page, now and as the page changes. */\n autoMount(): void {\n if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;\n if (document.readyState === 'loading' && typeof document.addEventListener === 'function') {\n // The script ran in <head>: the elements are not parsed yet.\n document.addEventListener('DOMContentLoaded', () => !this.destroyed && this.autoMount(), { once: true });\n return;\n }\n this.scanDocument();\n if (this.mutationObserver || typeof MutationObserver === 'undefined' || !document.body) return;\n this.mutationObserver = new MutationObserver(() => this.scanDocument());\n this.mutationObserver.observe(document.body, { childList: true, subtree: true });\n }\n\n /** An event was tracked: event-triggered items waiting on it become eligible. */\n onEventTracked(eventName: string, properties?: Record<string, any>): void {\n if (!eventName) return;\n const changed = new Set<string>();\n for (const [key, entry] of this.cache) {\n for (const item of entry.placement.items || []) {\n const match = (item.triggers || []).some(\n (t) => t.type === 'event' && t.event === eventName && inAppTriggerFilterMatches(t, properties),\n );\n if (match) {\n this.triggeredAt.set(this.handle(key, item), nowMs());\n changed.add(key);\n }\n }\n }\n if (changed.size) this.applyChanged(Array.from(changed));\n }\n\n /**\n * The visitor changed (identify, reset, consent): forget every answer and\n * ask again for the placements on the page.\n */\n invalidate(): void {\n this.generation++;\n this.cache.clear();\n this.lastNetworkAt.clear();\n this.triggeredAt.clear();\n this.dismissedLocally.clear();\n this.reported.clear();\n this.revealed.clear();\n this.spotViewable.clear();\n this.persistCache();\n const keys = this.mountedKeys();\n // The previous person's content goes NOW, on screen or not: it must not\n // stay in front of the next person, nor report against them.\n for (const mount of this.mounts) this.render(mount);\n if (keys.length) this.fetchKeys(keys, true).catch(() => undefined);\n }\n\n destroy(): void {\n this.destroyed = true;\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n this.momentsUnsubscribe?.();\n this.momentsUnsubscribe = null;\n for (const mount of Array.from(this.mounts)) this.unmount(mount);\n this.mutationObserver?.disconnect();\n this.mutationObserver = null;\n if (this.batchTimer) clearTimeout(this.batchTimer);\n if (this.deferredTimer) clearTimeout(this.deferredTimer);\n this.batchTimer = null;\n this.deferredTimer = null;\n this.batchWaiters.forEach((w) => w.resolve());\n this.batchWaiters = [];\n this.listeners.clear();\n if (this.pageListener && typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {\n document.removeEventListener('visibilitychange', this.pageListener);\n }\n try {\n if (typeof window !== 'undefined' && (window as any)[PLACEMENT_BRIDGE_GLOBAL]?.__owner === this) {\n delete (window as any)[PLACEMENT_BRIDGE_GLOBAL];\n }\n } catch {\n /* ignore */\n }\n }\n\n // ── fetching ────────────────────────────────────────────────────────────\n\n private cleanKeys(keys: string[]): string[] {\n const out: string[] = [];\n for (const key of Array.isArray(keys) ? keys : []) {\n if (validKey(key) && !out.includes(key)) out.push(key);\n else if (!validKey(key)) this.logger.warn(`Ignoring \"${key}\": not a placement key`);\n }\n return out;\n }\n\n private knownKeys(): string[] {\n return Array.from(new Set([...this.mountedKeys(), ...this.cache.keys()]));\n }\n\n private mountedKeys(): string[] {\n return Array.from(new Set(Array.from(this.mounts).map((m) => m.key)));\n }\n\n /**\n * Page context (D444 Phase 4): requests carry the page (URL without query,\n * allow-listed variables), and a page-scoped answer is good for its page\n * only - on a route change it goes, and the spot asks again.\n */\n setPageContext(tracker: PageContextTracker | null): void {\n this.pageUnsubscribe?.();\n this.pageUnsubscribe = null;\n this.page = tracker;\n if (!tracker) return;\n this.pageUnsubscribe = tracker.onSignal((signal) => {\n if (signal.type !== 'page_change' || this.destroyed) return;\n // Show when: a new page view - held items wait for this page's moment again.\n const held = this.revealed.size ? this.keysWithMoments() : [];\n this.revealed.clear();\n this.spotViewable.clear();\n this.rechecked.clear();\n const stale: string[] = [];\n this.cache.forEach((entry, key) => {\n if (entry.placement.pageScoped && entry.url !== signal.url) stale.push(key);\n });\n const rehide = held.filter((key) => !stale.includes(key));\n if (rehide.length) {\n for (const mount of this.mounts) if (rehide.includes(mount.key)) this.render(mount);\n this.notify(rehide);\n this.sweep();\n }\n if (!stale.length) return;\n stale.forEach((key) => this.cache.delete(key));\n this.persistCache();\n // The old page's item must not stay on the new page while the answer is on its way.\n for (const mount of this.mounts) if (stale.includes(mount.key)) this.render(mount);\n const mounted = stale.filter((key) => this.mountedKeys().includes(key));\n if (mounted.length) {\n this.fetchKeys(mounted, false)\n .then(() => {\n for (const mount of this.mounts) if (mounted.includes(mount.key) && !mount.wrapper) this.render(mount);\n })\n .catch(() => undefined);\n }\n });\n }\n\n /** Show when (D465): the SDK's moments. Held content is revealed as they come. */\n setShowWhen(moments: ShowWhenMoments | null): void {\n this.momentsUnsubscribe?.();\n this.moments = moments;\n this.momentsUnsubscribe = moments ? moments.onChange(() => !this.destroyed && this.sweep()) : null;\n }\n\n /** Has this held content's moment come in this page view? Once yes, it stays yes until a route change. */\n private due(handle: string, raw: unknown): boolean {\n const sw = parseShowWhen(raw);\n if (!sw) return false;\n return sw.kind === 'load' || this.revealed.has(handle) || (!!this.moments && this.moments.met(sw));\n }\n\n /** Keys whose answer holds anything until a moment. */\n private keysWithMoments(): string[] {\n const out: string[] = [];\n this.cache.forEach((entry, key) => {\n const p = entry.placement;\n if (p.showWhen !== undefined || p.deferredControls?.length || (p.items || []).some((i) => i.showWhen !== undefined)) out.push(key);\n });\n return out;\n }\n\n /**\n * A moment may have come: reveal held items and control answers whose moment\n * did (re-draw + onPlacementsUpdated), and report the deferred control\n * exposures that are now due.\n */\n private sweep(): void {\n const changed: string[] = [];\n this.cache.forEach((entry, key) => {\n const p = entry.placement;\n const handles: Array<[string, unknown]> = (p.items || []).filter((i) => isDeferred(i.showWhen)).map((i) => [this.handle(key, i), i.showWhen]);\n if (p.isControl && isDeferred(p.showWhen)) handles.push([`ctl:${key}:${p.controlToken || ''}`, p.showWhen]);\n for (const [h, raw] of handles) {\n if (this.revealed.has(h) || !this.due(h, raw)) continue;\n this.revealed.add(h);\n if (!changed.includes(key)) changed.push(key);\n }\n this.reportDeferred(key);\n });\n if (changed.length) this.applyChanged(changed);\n }\n\n /**\n * Show when: the keys to ask again now that `eventName` was tracked - their\n * answer lists it in `recheckOn` or holds an item waiting on it - at most\n * once per (key, event) per page view. Marks them as asked.\n */\n recheckKeysFor(eventName: string): string[] {\n if (!this.moments || this.destroyed) return [];\n const out: string[] = [];\n this.cache.forEach((entry, key) => {\n const p = entry.placement;\n if (p.pageScoped && entry.url !== this.currentUrl()) return;\n const waits =\n (p.recheckOn || []).includes(eventName) ||\n (p.items || []).some((i) => (parseShowWhen(i.showWhen) as { event?: string } | null)?.event === eventName);\n const once = `${key}\\u0000${eventName}`;\n if (!waits || this.rechecked.has(once)) return;\n this.rechecked.add(once);\n out.push(key);\n });\n return out;\n }\n\n /**\n * Ask the server again for `keys` now, past the client refresh limit (the\n * show-when re-check), carrying the event that caused it (`recheckEvent`).\n */\n recheck(keys: string[], event?: RecheckEvent): Promise<void> {\n const go = (): Promise<void> => {\n keys.forEach((key) => this.lastNetworkAt.delete(this.rateKey(key)));\n if (event) this.recheckEvent = event;\n return this.fetchKeys(keys, false);\n };\n // A request already on its way may predate the event: ask again once it is back.\n const inflight = keys.map((key) => this.inflight.get(key)).filter(Boolean);\n return (inflight.length ? Promise.all(inflight).then(go) : go()).catch(() => undefined);\n }\n\n private currentUrl(): string | null {\n return this.page ? this.page.current().url : currentPageUrl();\n }\n\n /** The rate-limit key: per page for a page-scoped placement, so a route change can ask again at once. */\n private rateKey(key: string): string {\n return this.cache.get(key)?.placement.pageScoped || this.pageScopedKeys.has(key) ? `${key}\\u0000${this.currentUrl() ?? ''}` : key;\n }\n private pageScopedKeys = new Set<string>();\n\n private freshEntry(key: string): CacheEntry | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n if (entry.placement.pageScoped && entry.url !== this.currentUrl()) return null;\n const ttl = (entry.placement.ttlSeconds || DEFAULT_TTL_SECONDS) * 1000;\n return nowMs() - entry.fetchedAt < ttl ? entry : null;\n }\n\n /** Fresh from the cache, or fetched (never more often than the rate limit allows). */\n private async ensure(keys: string[]): Promise<void> {\n const stale = keys.filter((key) => !this.freshEntry(key));\n if (stale.length) await this.fetchKeys(stale, false);\n }\n\n /**\n * Fetch `keys`, batched with every other key asked for in the next\n * PLACEMENT_BATCH_WINDOW_MS. A key fetched less than\n * PLACEMENT_MIN_REFRESH_SECONDS ago is not fetched again: a forced refresh\n * is deferred to when the window opens, anything else is served the cache.\n */\n private fetchKeys(keys: string[], force: boolean): Promise<void> {\n const now = nowMs();\n const waits: Promise<void>[] = [];\n const due: string[] = [];\n for (const key of keys) {\n const inflight = this.inflight.get(key);\n if (inflight) {\n waits.push(inflight);\n if (force) this.defer(key);\n continue;\n }\n const last = this.lastNetworkAt.get(this.rateKey(key));\n if (last !== undefined && now - last < PLACEMENT_MIN_REFRESH_SECONDS * 1000) {\n if (force) this.defer(key);\n continue;\n }\n due.push(key);\n }\n if (due.length) {\n due.forEach((key) => this.batchKeys.add(key));\n const batched = new Promise<void>((resolve) => this.batchWaiters.push({ keys: due, resolve }));\n due.forEach((key) => this.inflight.set(key, batched));\n if (!this.batchTimer) this.batchTimer = setTimeout(() => void this.flushBatch(), PLACEMENT_BATCH_WINDOW_MS);\n waits.push(batched);\n }\n return Promise.all(waits).then(() => undefined);\n }\n\n private defer(key: string): void {\n this.deferredKeys.add(key);\n if (this.deferredTimer) return;\n const last = Math.min(...Array.from(this.deferredKeys).map((k) => this.lastNetworkAt.get(this.rateKey(k)) ?? 0));\n const wait = Math.max(0, last + PLACEMENT_MIN_REFRESH_SECONDS * 1000 - nowMs());\n this.deferredTimer = setTimeout(() => {\n this.deferredTimer = null;\n const keys = Array.from(this.deferredKeys);\n this.deferredKeys.clear();\n if (keys.length && !this.destroyed) this.fetchKeys(keys, false).catch(() => undefined);\n }, wait + 10);\n }\n\n private async flushBatch(): Promise<void> {\n this.batchTimer = null;\n const keys = Array.from(this.batchKeys);\n this.batchKeys.clear();\n const waiters = this.batchWaiters;\n this.batchWaiters = [];\n const recheckEvent = this.recheckEvent;\n this.recheckEvent = null;\n const chunks: string[][] = [];\n for (let i = 0; i < keys.length; i += PLACEMENT_MAX_KEYS_PER_REQUEST) {\n chunks.push(keys.slice(i, i + PLACEMENT_MAX_KEYS_PER_REQUEST));\n }\n try {\n await Promise.all(chunks.map((chunk) => this.request(chunk, recheckEvent)));\n } finally {\n keys.forEach((key) => this.inflight.delete(key));\n waiters.forEach((w) => w.resolve());\n }\n }\n\n private async request(keys: string[], recheckEvent?: RecheckEvent | null): Promise<void> {\n const consent = this.runtime.consent();\n if (consent === null || this.destroyed) return;\n const generation = this.generation;\n const personal = consent === 'granted';\n const sentAt = nowMs();\n keys.forEach((key) => this.lastNetworkAt.set(this.rateKey(key), sentAt));\n const askedFor = this.currentUrl();\n\n const shown: Record<string, string[]> = {};\n for (const mount of this.mounts) {\n if (keys.includes(mount.key) && mount.shown.length) shown[mount.key] = mount.shown.slice();\n }\n const userId = personal ? this.identity.getUserId() : null;\n const anonymousId = personal ? this.identity.getAnonymousId() : null;\n const body: Record<string, any> = {\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n ...(personal ? { sessionId: this.session.getSessionId() } : {}),\n deviceType: 'web',\n locale: typeof navigator !== 'undefined' ? navigator.language : undefined,\n capabilities: this.capabilities(),\n trackingConsent: consent,\n placements: keys,\n shown,\n context: this.page ? { ...this.page.current(), screen: null } : pageContext(),\n ...(recheckEvent ? { recheckEvent } : {}),\n };\n\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timeout = setTimeout(() => controller?.abort(), this.runtime.requestTimeoutMs ?? 10000);\n const url = `${this.apiEndpoint}/v1/in-app/placements`;\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n // Only a consented request carries the visitor's auth: an\n // unconsented one names nobody.\n ...(personal ? this.auth?.getSdkAuthHeaders(userId, userId ? null : anonymousId) || {} : {}),\n },\n body: JSON.stringify(body),\n ...(controller ? { signal: controller.signal } : {}),\n });\n if (!response.ok) {\n // 429 (the per-device limit) and every other failure: keep the cache.\n this.runtime.noteStatus?.(response.status, null);\n this.logger.debug(`Placements request answered ${response.status}; keeping the cached placements`);\n return;\n }\n const data: PlacementsResponse = await response.json();\n if (generation !== this.generation) {\n this.logger.debug('Discarding a placements answer that predates an identity or consent change');\n return;\n }\n if (!data || data.success === false || !data.placements || typeof data.placements !== 'object') return;\n const fetchedAt = nowMs();\n const changed: string[] = [];\n for (const key of keys) {\n // A key the server left out is an empty placement (never an error).\n const wire = data.placements[key] || { placementKey: key, items: [] };\n const normalized = this.normalize(key, wire);\n const before = this.cache.get(key);\n this.cache.set(key, { placement: normalized, fetchedAt, url: askedFor });\n if (normalized.pageScoped) this.pageScopedKeys.add(key);\n else this.pageScopedKeys.delete(key);\n // The server's answer already applied the dismissal rule.\n for (const handle of Array.from(this.dismissedLocally)) {\n if (handle.startsWith(`${key}\\u0000`)) this.dismissedLocally.delete(handle);\n }\n if (!before || JSON.stringify(before.placement) !== JSON.stringify(normalized)) changed.push(key);\n }\n this.persistCache();\n if (changed.length) this.applyChanged(changed);\n } catch (error) {\n const timedOut = (error as any)?.name === 'AbortError';\n this.logger.debug(timedOut ? 'Placements request timed out' : 'Placements request failed', error);\n } finally {\n clearTimeout(timeout);\n }\n }\n\n private capabilities(): string[] {\n const caps = ['placements', 'content.native', 'content.data'];\n if (this.page) caps.push(PAGE_CONTEXT_CAPABILITY);\n if (this.runtime.allowHtml()) caps.push('content.html');\n return caps;\n }\n\n private normalize(key: string, wire: PlacementWire): PlacementWire {\n const items = Array.isArray(wire.items) ? wire.items.filter((i) => i && typeof i.id === 'string') : [];\n return {\n placementKey: key,\n emptyBehavior: wire.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse',\n maxItems: typeof wire.maxItems === 'number' && wire.maxItems > 0 ? wire.maxItems : 1,\n ttlSeconds: typeof wire.ttlSeconds === 'number' && wire.ttlSeconds > 0 ? wire.ttlSeconds : DEFAULT_TTL_SECONDS,\n isControl: wire.isControl === true,\n controlToken: wire.controlToken || null,\n items,\n ...(wire.pageScoped === true ? { pageScoped: true } : {}),\n ...(wire.isControl === true && wire.showWhen != null ? { showWhen: wire.showWhen } : {}),\n ...(Array.isArray(wire.deferredControls) && wire.deferredControls.length\n ? { deferredControls: wire.deferredControls.filter((d) => d && typeof d.controlToken === 'string' && d.controlToken) }\n : {}),\n ...(eventNames(wire.recheckOn).length ? { recheckOn: eventNames(wire.recheckOn) } : {}),\n };\n }\n\n /** Re-draw mounted placements and tell listeners, for keys whose answer changed. */\n private applyChanged(keys: string[]): void {\n for (const mount of this.mounts) {\n if (!keys.includes(mount.key)) continue;\n // Never under the reader's eyes: applied when the spot leaves the viewport.\n if (mount.hostInView && mount.shown.length) mount.pendingUpdate = true;\n else this.render(mount);\n }\n this.notify(keys);\n }\n\n private notify(keys: string[]): void {\n if (!this.listeners.size) return;\n const update: Record<string, Placement> = {};\n keys.forEach((key) => (update[key] = this.toPlacement(key)));\n for (const listener of Array.from(this.listeners)) {\n try {\n listener(update);\n } catch (error) {\n this.logger.error('The onPlacementsUpdated callback threw; ignored:', error);\n }\n }\n }\n\n // ── what is eligible now ────────────────────────────────────────────────\n\n private handle(key: string, item: PlacementItemWire): string {\n return `${key}\\u0000${item.deliveryToken || item.id}`;\n }\n\n /** The items to show now: not expired, not dismissed here, triggered when they wait on an event. */\n private visibleItems(key: string): PlacementItemWire[] {\n const entry = this.cache.get(key);\n if (!entry) return [];\n const now = nowMs();\n const max = entry.placement.maxItems || 1;\n return (entry.placement.items || [])\n .filter((item) => {\n if (item.expiresAt && Date.parse(item.expiresAt) <= now) return false;\n if (this.dismissedLocally.has(this.handle(key, item))) return false;\n // Show when: held until its moment in this page view; an unknown or invalid moment is never shown.\n if (item.showWhen !== undefined && !this.due(this.handle(key, item), item.showWhen)) return false;\n const eventTriggers = (item.triggers || []).filter((t) => t.type === 'event');\n if (eventTriggers.length) {\n const at = this.triggeredAt.get(this.handle(key, item));\n const windowS = item.placementTriggerWindowSeconds || PLACEMENT_DEFAULT_TRIGGER_WINDOW_SECONDS;\n if (at === undefined || now - at > windowS * 1000) return false;\n }\n return true;\n })\n .slice(0, max);\n }\n\n private toPlacement(key: string): Placement {\n const entry = this.cache.get(key);\n const wire = entry?.placement || this.normalize(key, { placementKey: key, items: [] });\n const generation = this.generation;\n return {\n placementKey: key,\n items: this.visibleItems(key).map((item) => this.toItem(key, item, generation)),\n isControl: wire.isControl === true,\n emptyBehavior: wire.emptyBehavior || 'collapse',\n maxItems: wire.maxItems || 1,\n ttlSeconds: wire.ttlSeconds || DEFAULT_TTL_SECONDS,\n markDisplayed: () => {\n if (!this.current(generation)) return;\n this.reportControl(key);\n this.markSpotViewable(key);\n },\n };\n }\n\n /** Created for the person still here? A Placement / item outlives an identify or reset: then it reports nothing. */\n private current(generation: number): boolean {\n return generation === this.generation;\n }\n\n private toItem(key: string, item: PlacementItemWire, generation: number): PlacementItem {\n return {\n id: item.id,\n variantId: item.variantId ?? null,\n kind: item.kind,\n data: { ...(item.data || {}) },\n content: item.content ?? null,\n products: toProducts(item.products),\n priority: item.priority,\n expiresAt: item.expiresAt ?? null,\n markDisplayed: () => this.current(generation) && this.report(key, item, 'displayed'),\n markClicked: (elementId?: string) => this.current(generation) && this.report(key, item, 'clicked', elementId),\n markDismissed: () => this.current(generation) && this.dismissItem(key, item),\n };\n }\n\n // ── reporting ───────────────────────────────────────────────────────────\n\n private dismissItem(key: string, item: PlacementItemWire): void {\n this.report(key, item, 'dismissed');\n this.dismissedLocally.add(this.handle(key, item));\n for (const mount of this.mounts) if (mount.key === key) this.render(mount);\n }\n\n /**\n * Report a transition to `/v1/in-app/track`. Only with consent (an\n * unconsented answer carries no delivery token and nothing is reported).\n * `displayed` once per delivery; a click or dismiss first counts the item\n * as displayed - the person saw it.\n */\n private report(key: string, item: PlacementItemWire, type: 'displayed' | 'clicked' | 'dismissed', elementId?: string): void {\n if (type === 'displayed') this.markSpotViewable(key);\n if (this.runtime.consent() !== 'granted') return;\n const once = `${type}:${this.handle(key, item)}`;\n if (type !== 'clicked') {\n if (this.reported.has(once)) return;\n this.reported.add(once);\n }\n if (type !== 'displayed') this.report(key, item, 'displayed');\n const at = new Date().toISOString();\n const normalizedId = normalizedElementId(elementId);\n const body: Record<string, any> = {\n campaignId: item.id,\n ...(item.variantId ? { variantId: item.variantId } : {}),\n ...(item.deliveryToken ? { deliveryToken: item.deliveryToken } : {}),\n placementKey: key,\n ...this.subject(),\n sessionId: this.session.getSessionId(),\n deviceType: 'web',\n ...(type === 'displayed' ? { action: 'displayed', displayedAt: at } : {}),\n ...(type === 'clicked' ? { action: 'clicked', clicked: true, clickedAt: at, ...(normalizedId ? { elementId: normalizedId } : {}) } : {}),\n ...(type === 'dismissed' ? { action: 'dismissed', dismissedAt: at } : {}),\n };\n this.post('/v1/in-app/track', body);\n }\n\n /**\n * A held-out visitor's empty spot was viewable: `in_app.control_viewed`,\n * once per control token. The token (from the answer) names the placement,\n * the campaign when it was a campaign control variant, and the visitor.\n */\n private reportControl(key: string): void {\n const entry = this.cache.get(key);\n if (!entry?.placement.isControl || !entry.placement.controlToken) return;\n // Show when: not before the moment the treatment would have shown (the spot re-draws, and\n // onPlacementsUpdated fires, at that moment - a markDisplayed before it is ignored).\n if (!this.due(`ctl:${key}:${entry.placement.controlToken}`, entry.placement.showWhen)) return;\n this.postControl(key, entry.placement.controlToken);\n }\n\n /** The spot of `key` was viewable in this page view: deferred control exposures may now be due. */\n private markSpotViewable(key: string): void {\n if (this.spotViewable.has(key)) return;\n this.spotViewable.add(key);\n this.reportDeferred(key);\n }\n\n /** `deferredControls` of the answer: each once, after its own moment, once the spot was viewable in this page view. */\n private reportDeferred(key: string): void {\n const list = this.cache.get(key)?.placement.deferredControls;\n if (!list?.length || !this.spotViewable.has(key)) return;\n for (const d of list) if (this.due(`ctl:${key}:${d.controlToken}`, d.showWhen)) this.postControl(key, d.controlToken);\n }\n\n /** `in_app.control_viewed`, once per control token, with consent only. */\n private postControl(key: string, controlToken: string): void {\n if (this.runtime.consent() !== 'granted') return;\n const once = `control:${controlToken}`;\n if (this.reported.has(once)) return;\n this.reported.add(once);\n this.post('/v1/in-app/track', {\n action: 'control_viewed',\n controlToken,\n placementKey: key,\n ...this.subject(),\n sessionId: this.session.getSessionId(),\n deviceType: 'web',\n viewedAt: new Date().toISOString(),\n });\n }\n\n private subject(): { userId?: string; anonymousId: string } {\n const userId = this.identity.getUserId();\n return { ...(userId ? { userId } : {}), anonymousId: this.identity.getAnonymousId() };\n }\n\n private post(path: string, body: Record<string, any>): void {\n const userId = typeof body.userId === 'string' ? body.userId : null;\n fetch(`${this.apiEndpoint}${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-SDK-Key': this.sdkKey,\n ...sdkIdentityHeaders(),\n ...(this.auth?.getSdkAuthHeaders(userId, userId ? null : body.anonymousId ?? null) || {}),\n },\n body: JSON.stringify(body),\n keepalive: true,\n })\n .then((response) => {\n if (!response.ok) this.runtime.noteStatus?.(response.status, null);\n })\n .catch((error) => this.logger.debug(`Placement report to ${path} failed`, error));\n }\n\n // ── drawing ─────────────────────────────────────────────────────────────\n\n private scanDocument(): void {\n if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return;\n // Elements removed from the page stop being filled.\n for (const mount of Array.from(this.mounts)) {\n if ((mount.element as any).isConnected === false) this.unmount(mount);\n }\n const mountedElements = new Set(Array.from(this.mounts).map((m) => m.element));\n document.querySelectorAll<HTMLElement>('[data-joryio-placement]').forEach((element) => {\n if (mountedElements.has(element)) return;\n const key = element.getAttribute('data-joryio-placement');\n if (key) this.insertPlacement(key, element);\n });\n }\n\n private unmount(mount: Mount): void {\n this.mounts.delete(mount);\n mount.hostObserver?.disconnect();\n this.clearTrackers(mount);\n this.clearDrawn(mount);\n mount.element.removeAttribute?.('data-joryio-placement-state');\n }\n\n private clearTrackers(mount: Mount): void {\n for (const t of mount.trackers) t.cancel();\n mount.trackers = [];\n }\n\n private clearDrawn(mount: Mount): void {\n if (mount.serverFill) {\n // A server drawing never settled (removed before any answer): it goes with the mount.\n this.dropServerFill(mount.element, mount.serverFill.wrapper);\n mount.serverFill = null;\n }\n mount.frameIds.forEach((id) => this.frames.delete(id));\n mount.frameIds = [];\n mount.wrapper?.remove();\n mount.wrapper = null;\n mount.shown = [];\n }\n\n /** The marker block's fills by key (read once per page load; the plugin writes it before any script). */\n private markerFills: Map<string, { campaignId: string; variantId: string; products: string[] }> | null = null;\n\n private serverFillsOfMarker(): Map<string, { campaignId: string; variantId: string; products: string[] }> {\n if (this.markerFills) return this.markerFills;\n const out = new Map<string, { campaignId: string; variantId: string; products: string[] }>();\n try {\n const el = typeof document !== 'undefined' ? serverMarkerElement() : null;\n const data = el ? JSON.parse(el.textContent || 'null') : null;\n const list = data && data.v === 1 && Array.isArray(data[SERVER_FILLS_MARKER_KEY]) ? data[SERVER_FILLS_MARKER_KEY] : [];\n for (const f of list.slice(0, 20)) {\n if (!f || !validKey(f.placementKey) || typeof f.campaignId !== 'string' || !f.campaignId) continue;\n const products = Array.isArray(f.products) ? f.products.filter((p: unknown) => typeof p === 'string').slice(0, 24) : [];\n out.set(f.placementKey, { campaignId: f.campaignId, variantId: typeof f.variantId === 'string' ? f.variantId : '', products });\n }\n } catch {\n // A broken marker: no slot is treated as server-filled (their content is replaced below).\n }\n this.markerFills = out;\n return out;\n }\n\n /**\n * The server's drawing in a slot element, when the element, its fill and\n * the marker block agree on placement, campaign and variant. A fill they do\n * not agree on (or one this SDK may not show: HTML with\n * allowHtmlJsInAppMessages off) is removed at once and the slot is drawn\n * as any other.\n */\n private serverFillOf(key: string, element: HTMLElement): ServerFill | null {\n const token = element.getAttribute?.(SERVER_FILLED_ATTR);\n if (!token) return null;\n const wrapper = Array.from(element.children || []).find(\n (c) => (c as HTMLElement).classList?.contains('joryio-placement') && c.hasAttribute?.(SERVER_FILL_ATTR),\n ) as HTMLElement | undefined;\n const fill = this.serverFillsOfMarker().get(key);\n const ok =\n !!wrapper &&\n !!fill &&\n wrapper.getAttribute(SERVER_FILL_ATTR) === token &&\n token === `${key}:${fill.campaignId}:${fill.variantId}` &&\n (this.runtime.allowHtml() || !wrapper.querySelector('.joryio-placement-html'));\n if (!ok) {\n this.dropServerFill(element, wrapper ?? null);\n return null;\n }\n attachServerShadowRoots(wrapper!);\n return { ...fill!, wrapper: wrapper! };\n }\n\n private dropServerFill(element: HTMLElement, wrapper: HTMLElement | null): void {\n wrapper?.remove();\n element.removeAttribute?.(SERVER_FILLED_ATTR);\n element.removeAttribute?.('data-joryio-placement-state');\n }\n\n /**\n * The slot was filled by the store's server: keep that drawing when this\n * visitor's answer is the same campaign, variant and products (no redraw),\n * else drop it. True when it was kept. Before any answer it stays as it is.\n */\n private settleServerFill(mount: Mount): 'kept' | 'dropped' | 'waiting' {\n const sf = mount.serverFill;\n if (!sf) return 'dropped';\n const entry = this.cache.get(mount.key);\n if (!entry) return 'waiting';\n mount.serverFill = null;\n const items = this.visibleItems(mount.key);\n const item = items[0];\n const products = toProducts(item?.products).map((p) => p.id);\n const html = !!sf.wrapper.querySelector('.joryio-placement-html');\n const same =\n items.length === 1 &&\n entry.placement.isControl !== true &&\n item.id === sf.campaignId &&\n (item.variantId ?? '') === sf.variantId &&\n products.length === sf.products.length &&\n products.every((id, i) => id === sf.products[i]) &&\n (item.content?.kind === 'html') === html &&\n (!html || this.runtime.allowHtml()) &&\n (mount.options.showProducts !== false || !products.length);\n if (!same) {\n this.dropServerFill(mount.element, sf.wrapper);\n return 'dropped';\n }\n mount.pendingUpdate = false;\n this.clearTrackers(mount);\n mount.wrapper = sf.wrapper;\n mount.shown = [item.deliveryId || item.id];\n mount.element.setAttribute('data-joryio-placement-state', 'filled');\n const node = (sf.wrapper.firstElementChild as HTMLElement | null) || sf.wrapper;\n this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));\n this.bindServerFill(mount, sf.wrapper, item);\n if (mount.options.onRender) {\n try {\n mount.options.onRender(this.toPlacement(mount.key), mount.element);\n } catch (error) {\n this.logger.error('The insertPlacement onRender callback threw; ignored:', error);\n }\n }\n return 'kept';\n }\n\n /**\n * Clicks in a kept server drawing, with the SDK's own rules: a product card\n * reports `clicked` with placementProductElementId and opens through the\n * link router in a new tab; in HTML content an <a> or <button> reports the\n * frame's `link_click` / `cta_click` (or its data-action) and an http(s)\n * link opens in a new tab - inline content never navigates the page it\n * sits in. #anchors, mailto:, tel: and sms: are left to the browser.\n */\n private bindServerFill(mount: Mount, wrapper: HTMLElement, item: PlacementItemWire): void {\n wrapper.addEventListener(\n 'click',\n (event: Event) => {\n if (!this.mounts.has(mount) || mount.wrapper !== wrapper) return;\n const path = (typeof (event as any).composedPath === 'function' ? (event as any).composedPath() : [event.target]) as Element[];\n for (const el of path) {\n if (!el || el === wrapper || typeof (el as Element).getAttribute !== 'function') break;\n const productId = el.getAttribute('data-joryio-product');\n if (productId) {\n const href = el.getAttribute('href');\n if (href) event.preventDefault?.();\n this.buttonAction(mount, item, { id: placementProductElementId(productId), action: 'deep_link', url: href || undefined });\n return;\n }\n const tag = (el.tagName || '').toUpperCase();\n if (tag === 'A' || tag === 'BUTTON') {\n const href = tag === 'A' ? el.getAttribute('href') : null;\n if (hasUserGesture()) this.report(mount.key, item, 'clicked', el.getAttribute('data-action') || (href ? 'link_click' : 'cta_click'));\n if (href && !/^(#|mailto:|tel:|sms:)/i.test(href.trim())) {\n event.preventDefault?.();\n const safe = safeHttpUrl(href.trim());\n if (safe && hasUserGesture()) this.openLink(safe, { placementKey: mount.key, itemId: item.id }, () => window.open(safe, '_blank', 'noopener'));\n }\n return;\n }\n }\n },\n true,\n );\n }\n\n private render(mount: Mount): void {\n if (!this.mounts.has(mount)) return;\n if (mount.serverFill && this.settleServerFill(mount) !== 'dropped') return;\n mount.pendingUpdate = false;\n this.clearTrackers(mount);\n this.clearDrawn(mount);\n const placement = this.toPlacement(mount.key);\n const entry = this.cache.get(mount.key);\n const wrapper = document.createElement('div');\n wrapper.className = 'joryio-placement';\n wrapper.setAttribute('data-joryio-placement-key', mount.key);\n const drawn: PlacementItemWire[] = [];\n for (const item of this.visibleItems(mount.key)) {\n const node = this.drawItem(mount, item);\n if (!node) continue;\n wrapper.appendChild(node);\n drawn.push(item);\n this.trackViewability(mount, node, () => this.report(mount.key, item, 'displayed'));\n }\n mount.shown = drawn.map((item) => item.deliveryId || item.id);\n mount.element.appendChild(wrapper);\n mount.wrapper = wrapper;\n const state = drawn.length ? 'filled' : placement.isControl ? 'control' : 'empty';\n mount.element.setAttribute('data-joryio-placement-state', state);\n if (!drawn.length) {\n // collapse: nothing drawn, the wrapper takes no space. keep_space: the\n // element keeps whatever box the site gave it.\n wrapper.style.display = placement.emptyBehavior === 'keep_space' ? '' : 'none';\n if (placement.isControl && entry?.placement.controlToken) {\n // The holdout's exposure: the SPOT (the site's element) was viewable.\n this.trackViewability(mount, mount.element, () => {\n this.reportControl(mount.key);\n this.markSpotViewable(mount.key);\n });\n }\n }\n if (mount.options.onRender) {\n try {\n mount.options.onRender(placement, mount.element);\n } catch (error) {\n this.logger.error('The insertPlacement onRender callback threw; ignored:', error);\n }\n }\n }\n\n private drawItem(mount: Mount, item: PlacementItemWire): HTMLElement | null {\n const content = item.content;\n let node: HTMLElement | null = null;\n if (content?.kind === 'html') {\n if (!this.runtime.allowHtml()) {\n this.logger.warn(`Placement ${mount.key}: HTML item skipped (allowHtmlJsInAppMessages is off)`);\n return null;\n }\n node = this.drawHtml(mount, item, content);\n } else if (content?.kind === 'native') {\n node = this.drawNative(mount, item, content);\n } else if (content) {\n return null;\n }\n // Recommended products: a row of cards below the content, or alone for a\n // data item (without products a data item is the app's to draw).\n const products = mount.options.showProducts === false ? [] : toProducts(item.products);\n if (!products.length) return node;\n const row = this.drawProducts(mount, item, products);\n if (!node) return row;\n const box = document.createElement('div');\n box.className = 'joryio-placement-item';\n box.setAttribute('data-joryio-item', item.id);\n box.appendChild(node);\n box.appendChild(row);\n return box;\n }\n\n /**\n * The built-in product cards: a horizontally scrolling row, one card per\n * product (image, title, price - the compare-at price struck through - and\n * the optional button). A tap reports `clicked` with\n * placementProductElementId and opens the product's link the way a\n * `deep_link` button does: http(s) in a new tab, an app link to the\n * handlers, anything else refused. Styled with the joryio-placement-product*\n * classes.\n */\n private drawProducts(mount: Mount, item: PlacementItemWire, products: PlacementProduct[]): HTMLElement {\n const row = document.createElement('div');\n row.className = 'joryio-placement-products';\n row.setAttribute('data-joryio-item', item.id);\n row.style.cssText = 'display:flex;gap:8px;overflow-x:auto;box-sizing:border-box;';\n const requested = Number(mount.options.productCardWidth);\n const width = Number.isFinite(requested) && requested > 0 ? requested : PLACEMENT_PRODUCT_CARD_WIDTH;\n for (const p of products) {\n const card = document.createElement('div');\n card.className = 'joryio-placement-product';\n card.setAttribute('data-joryio-product', p.id);\n card.style.cssText = `flex:0 0 ${width}px;width:${width}px;box-sizing:border-box;`;\n const open = p.url ? () => this.buttonAction(mount, item, { id: placementProductElementId(p.id), action: 'deep_link', url: p.url! }) : null;\n const image = safeHttpUrl(p.imageUrl);\n if (image) {\n const img = document.createElement('img');\n img.className = 'joryio-placement-product-image';\n img.src = image;\n img.alt = p.title || '';\n img.style.cssText = 'display:block;width:100%;aspect-ratio:1/1;object-fit:cover;';\n card.appendChild(img);\n }\n if (p.title) {\n const title = document.createElement('div');\n title.className = 'joryio-placement-product-title';\n title.textContent = p.title;\n card.appendChild(title);\n }\n if (p.price) {\n const price = document.createElement('div');\n price.className = 'joryio-placement-product-price';\n price.textContent = p.price;\n if (p.compareAtPrice) {\n const was = document.createElement('s');\n was.className = 'joryio-placement-product-compare';\n was.textContent = p.compareAtPrice;\n was.style.cssText = 'margin-inline-start:6px;opacity:0.6;';\n price.appendChild(was);\n }\n card.appendChild(price);\n }\n if (open && mount.options.productButtonText) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'joryio-placement-product-button';\n btn.textContent = mount.options.productButtonText;\n btn.addEventListener('click', (e?: Event) => {\n e?.stopPropagation?.();\n open();\n });\n card.appendChild(btn);\n }\n if (open) {\n card.setAttribute('role', 'link');\n card.tabIndex = 0;\n card.style.cursor = 'pointer';\n card.addEventListener('click', open);\n card.addEventListener('keydown', (e?: KeyboardEvent) => {\n if (e?.key === 'Enter') open();\n });\n }\n row.appendChild(card);\n }\n return row;\n }\n\n private drawNative(\n mount: Mount,\n item: PlacementItemWire,\n content: Extract<PlacementContent, { kind: 'native' }>,\n ): HTMLElement {\n const card = document.createElement('div');\n card.className = 'joryio-placement-card';\n card.setAttribute('data-joryio-item', item.id);\n card.style.cssText = 'position:relative;box-sizing:border-box;';\n const image = safeHttpUrl(content.imageUrl);\n if (image) {\n const img = document.createElement('img');\n img.src = image;\n img.alt = '';\n img.style.cssText = 'display:block;max-width:100%;height:auto;';\n card.appendChild(img);\n }\n if (content.title) {\n const title = document.createElement('div');\n title.className = 'joryio-placement-title';\n title.textContent = content.title;\n card.appendChild(title);\n }\n if (content.body) {\n const body = document.createElement('div');\n body.className = 'joryio-placement-body';\n body.textContent = content.body;\n card.appendChild(body);\n }\n if (content.buttons?.length) {\n const row = document.createElement('div');\n row.className = 'joryio-placement-buttons';\n content.buttons.forEach((b, index) => {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = index === 0 ? 'primary' : 'secondary';\n btn.textContent = b.text;\n btn.addEventListener('click', () => this.buttonAction(mount, item, b));\n row.appendChild(btn);\n });\n card.appendChild(row);\n }\n // Inline content has no close control unless the author asked for one.\n if (content.closeButton === true) {\n const close = document.createElement('button');\n close.type = 'button';\n close.className = 'joryio-placement-close';\n close.setAttribute('aria-label', 'Close');\n close.textContent = '×';\n close.addEventListener('click', () => this.dismissItem(mount.key, item));\n card.appendChild(close);\n }\n return card;\n }\n\n /**\n * A native button: report the click, then act. Unlike an overlay, an inline\n * item stays after a click - only a `dismiss` button (or the close control)\n * removes it.\n */\n private buttonAction(mount: Mount, item: PlacementItemWire, b: { id: string; action: string; url?: string }): void {\n const key = mount.key;\n // Synchronous first: the push prompt needs the click's user activation.\n if (b.action === 'request_push_permission') this.runtime.bridge?.requestPushPermission();\n this.report(key, item, 'clicked', b.id);\n if (b.action === 'url' || b.action === 'deep_link') {\n // http(s) opens in a new tab; an app deep link goes to the site's own\n // handler (the SDK never navigates to a custom scheme); anything else -\n // javascript:, data:, intent:, ... - is refused silently.\n // The site-wide link handler (setLinkHandler) sees it first.\n const url = safeHttpUrl(b.url);\n const context: LinkContext = { placementKey: key, itemId: item.id };\n if (url) {\n this.openLink(url, context, () => window.open(url, '_blank', 'noopener'));\n } else if (b.action === 'deep_link' && isAppDeepLink(b.url) && (mount.options.onDeepLink || this.links?.hasHandler)) {\n const deepLink = (b.url as string).trim();\n this.openLink(deepLink, context, () => {\n if (!mount.options.onDeepLink) return;\n try {\n mount.options.onDeepLink(deepLink, this.toItem(key, item, this.generation));\n } catch (error) {\n this.logger.error('The insertPlacement onDeepLink callback threw; ignored:', error);\n }\n });\n }\n return;\n }\n if (b.action === 'dismiss' || b.action === 'close') {\n this.dismissItem(key, item);\n }\n }\n\n /** Through the site-wide link handler when there is a router, else straight to the fallback. */\n private openLink(url: string, context: LinkContext, fallback: () => void): void {\n if (this.links) this.links.route(url, 'placement', context, fallback);\n else fallback();\n }\n\n private drawHtml(mount: Mount, item: PlacementItemWire, content: Extract<PlacementContent, { kind: 'html' }>): HTMLElement {\n const id = `p${++this.frameSeq}`;\n const iframe = document.createElement('iframe');\n iframe.className = 'joryio-placement-frame';\n iframe.setAttribute('data-joryio-item', item.id);\n // The overlay's sandbox exactly: same-origin so the bootstrap can reach\n // the host bridge; author script is stopped by the nonce CSP in the srcdoc.\n iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups');\n iframe.setAttribute('title', 'Placement');\n iframe.style.cssText = 'display:block;width:100%;height:0;border:0;';\n iframe.srcdoc = buildInAppSrcdoc(id, content.html || '', content.css || '', 'placement', PLACEMENT_BRIDGE_GLOBAL);\n this.frames.set(id, { iframe, key: mount.key, item });\n mount.frameIds.push(id);\n return iframe;\n }\n\n /**\n * The host object the placement frames call into. Every method is keyed by\n * the frame id and acts only while that frame is drawn.\n */\n private installBridge(): void {\n if (typeof window === 'undefined') return;\n const frame = (id: string) => this.frames.get(id);\n (window as any)[PLACEMENT_BRIDGE_GLOBAL] = {\n __owner: this,\n setSize: (id: string, _w: number, height: number) => {\n const f = frame(id);\n if (f && Number.isFinite(height) && height > 0) f.iframe.style.height = `${Math.ceil(height)}px`;\n },\n // A click counts, and a link opens, only from the person's own gesture.\n logClick: (id: string, action?: string) => {\n const f = frame(id);\n if (f && hasUserGesture()) this.report(f.key, f.item, 'clicked', action);\n },\n // Always a new tab, never the host page itself: inline content does not\n // navigate the page it sits in.\n navigate: (id: string, url: string) => {\n if (!frame(id) || !hasUserGesture()) return;\n const safe = safeHttpUrl(url);\n const f = frame(id);\n if (safe && f) this.openLink(safe, { placementKey: f.key, itemId: f.item.id }, () => window.open(safe, '_blank', 'noopener'));\n },\n closeMessage: (id: string) => {\n const f = frame(id);\n if (f) this.dismissItem(f.key, f.item);\n },\n logConversion: () => undefined,\n logCustomEvent: (id: string, name: string, properties?: Record<string, any>) => {\n if (frame(id) && name) this.runtime.bridge?.logCustomEvent(name, properties);\n },\n setCustomUserAttribute: (id: string, key: string, value: any) => {\n if (frame(id) && key) this.runtime.bridge?.setCustomUserAttribute(key, value);\n },\n changeUser: (id: string, userId: string) => {\n if (frame(id) && userId) this.runtime.bridge?.changeUser(userId);\n },\n requestPushPermission: (id: string) => {\n if (frame(id)) this.runtime.bridge?.requestPushPermission();\n },\n submitForm: () => Promise.resolve({ ok: false, message: 'Forms are not available in this spot.' }),\n };\n }\n\n // ── viewability ─────────────────────────────────────────────────────────\n\n private pageVisible(): boolean {\n return typeof document === 'undefined' || document.visibilityState !== 'hidden';\n }\n\n /** Whether any part of the host element is on screen (for \"never swap under the reader's eyes\"). */\n private observeHost(mount: Mount): void {\n if (typeof IntersectionObserver === 'undefined') return;\n const observer = new IntersectionObserver((entries) => {\n for (const e of entries) {\n mount.hostInView = e.isIntersecting;\n if (!e.isIntersecting && mount.pendingUpdate) this.render(mount);\n }\n });\n observer.observe(mount.element);\n mount.hostObserver = observer;\n }\n\n /** Measure `node` (the shared rule, trackViewable) while it stays drawn in `mount`. */\n private trackViewability(mount: Mount, node: Element, onViewable: () => void): void {\n let tracker: ViewTracker | null = null;\n tracker = trackViewable(node, () => {\n if (tracker && mount.trackers.includes(tracker)) onViewable();\n });\n mount.trackers.push(tracker);\n }\n\n private installPageVisibility(): void {\n if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return;\n this.pageListener = () => {\n for (const mount of this.mounts) {\n for (const t of mount.trackers) {\n if (this.pageVisible()) t.resume();\n else t.pause();\n }\n }\n };\n document.addEventListener('visibilitychange', this.pageListener);\n }\n\n // ── session cache ───────────────────────────────────────────────────────\n\n private subjectKey(): string {\n return `${this.identity.getUserId() || ''}|${this.identity.getAnonymousId()}`;\n }\n\n private loadCache(): void {\n try {\n if (typeof sessionStorage === 'undefined') return;\n sessionStorage.removeItem?.(LEGACY_CACHE_STORAGE_NAME);\n const raw = sessionStorage.getItem(placementsStorageKey(this.sdkKey));\n if (!raw) return;\n const stored = JSON.parse(raw);\n // Another visitor's answers (a reset or a login since) are not this one's.\n if (!stored || stored.subject !== this.subjectKey() || typeof stored.entries !== 'object') return;\n for (const [key, entry] of Object.entries<any>(stored.entries)) {\n if (validKey(key) && entry && entry.placement && typeof entry.fetchedAt === 'number') {\n this.cache.set(key, {\n placement: this.normalize(key, entry.placement),\n fetchedAt: entry.fetchedAt,\n url: typeof entry.url === 'string' ? entry.url : null,\n });\n }\n }\n } catch {\n /* storage blocked or corrupt: start empty */\n }\n }\n\n private persistCache(): void {\n try {\n if (typeof sessionStorage === 'undefined') return;\n const entries: Record<string, CacheEntry> = {};\n this.cache.forEach((entry, key) => {\n entries[key] = entry;\n });\n sessionStorage.setItem(placementsStorageKey(this.sdkKey), JSON.stringify({ subject: this.subjectKey(), entries }));\n } catch {\n /* storage blocked or full: memory only */\n }\n }\n}\n\n/** The wire's product cards, defensively typed: an entry without an id is dropped. */\n/**\n * A browser without declarative shadow DOM leaves the server's\n * `<template shadowrootmode=\"open\">` inert: attach it here, as the parser\n * would have (D466).\n */\nexport function attachServerShadowRoots(wrapper: HTMLElement): void {\n for (const host of Array.from(wrapper.querySelectorAll?.('.joryio-placement-html') || []) as HTMLElement[]) {\n if (host.shadowRoot || typeof host.attachShadow !== 'function') continue;\n const tpl = Array.from(host.children).find((c) => c.tagName === 'TEMPLATE' && c.getAttribute('shadowrootmode') === 'open') as HTMLTemplateElement | undefined;\n if (!tpl) continue;\n try {\n host.attachShadow({ mode: 'open' }).appendChild(tpl.content);\n tpl.remove();\n } catch {\n // Left as it is: the template stays inert.\n }\n }\n}\n\nexport function toProducts(raw: unknown): PlacementProduct[] {\n if (!Array.isArray(raw)) return [];\n const str = (v: unknown) => (typeof v === 'string' ? v : null);\n return raw\n .filter((p): p is Record<string, unknown> => !!p && typeof p === 'object' && (typeof (p as any).id === 'string' || typeof (p as any).id === 'number'))\n .map((p) => ({\n id: String(p.id),\n title: str(p.title),\n price: str(p.price),\n compareAtPrice: str(p.compareAtPrice),\n discountPercent: typeof p.discountPercent === 'number' ? p.discountPercent : null,\n imageUrl: str(p.imageUrl),\n url: str(p.url),\n }));\n}\n","/**\n * The default card feed (`mountCardFeed`), drawn from what the core's\n * CardFeedHost gives it (src/core/cards-ui-contract.ts). Lives in\n * `joryio-cards-ui.min.js`, loaded only by a page that mounts a feed.\n *\n * Text is set as text, never as markup; colors and fonts are the page's.\n */\nimport type { Card, MountCardFeedOptions } from '../core/cards';\nimport type { CardFeedHost, CardFeedView } from '../core/cards-ui-contract';\nimport type { ViewTracker } from '../core/placements';\nimport { isAppDeepLink, safeHttpUrl } from '../core/placements';\n\ntype DrawnCard = { node: HTMLElement; sig: string; tracker: ViewTracker | null };\n\nconst DEFAULT_LABELS = { emptyText: 'No messages yet', pinnedLabel: 'Pinned', dismissLabel: 'Dismiss', unreadLabel: 'Unread' };\n\nexport function mountFeedView(element: HTMLElement, options: MountCardFeedOptions, host: CardFeedHost): CardFeedView {\n const opts = options || {};\n let removed = false;\n let loadingMore = false;\n /** Drawn card nodes by card key, reused while the card looks the same. */\n let nodes = new Map<string, DrawnCard>();\n let empty: HTMLElement | null = null;\n\n const root = document.createElement('div');\n root.className = 'joryio-card-feed';\n root.setAttribute('role', 'list');\n const sentinel = document.createElement('div');\n sentinel.className = 'joryio-card-feed-end';\n sentinel.setAttribute('aria-hidden', 'true');\n element.appendChild(root);\n\n /** A tap: report clicked, then open the url by the placement link rule (the site-wide link handler sees it first). */\n const click = (card: Card): void => {\n host.markCardClicked(card);\n const url = card.url?.trim();\n if (!url) return;\n const context = { campaignId: card.campaignId, cardId: card.id };\n const http = safeHttpUrl(url);\n if (http) {\n host.routeLink(http, context, () => {\n try {\n window.open(http, '_blank', 'noopener');\n } catch (error) {\n host.logger.debug('Could not open the card link', error);\n }\n });\n return;\n }\n if (isAppDeepLink(url)) {\n // The site routes its own links; the SDK never navigates to a custom scheme.\n host.routeLink(url, context, () => {\n if (!opts.onDeepLink) return;\n try {\n opts.onDeepLink(url, card);\n } catch (error) {\n host.logger.error('The mountCardFeed onDeepLink callback threw; ignored:', error);\n }\n });\n return;\n }\n host.logger.warn('Card link refused: not http(s) or an app deep link');\n };\n\n const label = (k: keyof typeof DEFAULT_LABELS): string => {\n const v = opts[k];\n return typeof v === 'string' ? v : DEFAULT_LABELS[k];\n };\n\n /** Image on top, a header with the unread dot, the title, the pinned marker and the dismiss control, then the body and the button. */\n const drawCard = (card: Card, generation: number): HTMLElement => {\n const el = document.createElement('div');\n el.className = 'joryio-card';\n el.setAttribute('role', 'listitem');\n el.setAttribute('data-joryio-card', card.id);\n el.setAttribute('data-joryio-card-read', card.read ? 'true' : 'false');\n if (card.pinned) el.setAttribute('data-joryio-card-pinned', 'true');\n el.style.cssText = `position:relative;box-sizing:border-box;padding:12px 16px;${card.url ? 'cursor:pointer;' : ''}`;\n const open = () => !removed && generation === host.generation() && click(card);\n if (card.url) {\n el.setAttribute('tabindex', '0');\n el.addEventListener('click', open);\n el.addEventListener('keydown', (e: any) => {\n if (e?.key === 'Enter' && e?.target === el) open();\n });\n }\n const image = safeHttpUrl(card.imageUrl);\n if (image) {\n const img = document.createElement('img');\n img.className = 'joryio-card-image';\n img.src = image;\n img.alt = '';\n img.style.cssText = 'display:block;max-width:100%;height:auto;margin-bottom:8px;';\n el.appendChild(img);\n }\n const header = document.createElement('div');\n header.className = 'joryio-card-header';\n header.style.cssText = 'display:flex;align-items:center;gap:6px;';\n if (!card.read) {\n const dot = document.createElement('span');\n dot.className = 'joryio-card-unread';\n dot.setAttribute('role', 'img');\n dot.setAttribute('aria-label', label('unreadLabel'));\n dot.textContent = '●';\n dot.style.cssText = 'font-size:10px;line-height:1;';\n header.appendChild(dot);\n }\n const title = document.createElement('div');\n title.className = 'joryio-card-title';\n title.textContent = card.title || '';\n title.style.cssText = 'flex:1;font-weight:bold;';\n header.appendChild(title);\n if (card.pinned) {\n const pinned = document.createElement('span');\n pinned.className = 'joryio-card-pinned';\n pinned.textContent = label('pinnedLabel');\n pinned.style.cssText = 'font-size:0.8em;';\n header.appendChild(pinned);\n }\n const dismiss = document.createElement('button');\n dismiss.type = 'button';\n dismiss.className = 'joryio-card-dismiss';\n dismiss.setAttribute('aria-label', label('dismissLabel'));\n dismiss.textContent = '×';\n dismiss.style.cssText = 'background:none;border:0;padding:4px 8px;color:inherit;font:inherit;font-size:1.25em;line-height:1;cursor:pointer;';\n dismiss.addEventListener('click', (e: any) => {\n e?.stopPropagation?.();\n if (generation === host.generation()) host.dismissCard(card);\n });\n header.appendChild(dismiss);\n el.appendChild(header);\n if (card.body) {\n const body = document.createElement('div');\n body.className = 'joryio-card-body';\n body.textContent = card.body;\n el.appendChild(body);\n }\n if (card.buttonText && card.url) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'joryio-card-button';\n btn.textContent = card.buttonText;\n btn.style.cssText = 'margin-top:8px;font:inherit;';\n btn.addEventListener('click', (e: any) => {\n e?.stopPropagation?.();\n open();\n });\n el.appendChild(btn);\n }\n return el;\n };\n\n const render = (): void => {\n if (removed) return;\n const feed = host.view();\n const generation = host.generation();\n const keep = new Map<string, DrawnCard>();\n for (const card of feed.cards) {\n const key = `${card.id}\\u0000${card.createdAt}`;\n const sig = JSON.stringify(card);\n const existing = nodes.get(key);\n if (existing && existing.sig === sig) {\n keep.set(key, existing);\n nodes.delete(key);\n continue;\n }\n const node = drawCard(card, generation);\n // Viewed, then read, once at least half the card was on screen for a second.\n const tracker = card.read\n ? null\n : host.trackViewable(node, () => {\n if (generation !== host.generation()) return;\n host.markCardViewed(card);\n host.markCardRead(card);\n });\n keep.set(key, { node, sig, tracker });\n }\n // Cards no longer in the feed (dismissed, expired, another person's) go.\n nodes.forEach((n) => {\n n.tracker?.cancel();\n n.node.remove();\n });\n nodes = keep;\n if (empty) {\n empty.remove();\n empty = null;\n }\n sentinel.remove();\n if (!feed.cards.length) {\n empty = document.createElement('div');\n empty.className = 'joryio-card-feed-empty';\n empty.textContent = label('emptyText');\n empty.style.cssText = 'padding:32px 16px;text-align:center;';\n root.appendChild(empty);\n } else {\n // appendChild moves a node that is already drawn: the order follows the feed.\n keep.forEach((n) => root.appendChild(n.node));\n }\n root.appendChild(sentinel);\n element.setAttribute('data-joryio-card-feed-state', feed.cards.length ? 'filled' : 'empty');\n if (opts.onRender) {\n try {\n opts.onRender(feed, element);\n } catch (error) {\n host.logger.error('The mountCardFeed onRender callback threw; ignored:', error);\n }\n }\n };\n\n // Load the next page when the end of the feed comes into view.\n let observer: IntersectionObserver | null = null;\n if (typeof IntersectionObserver !== 'undefined') {\n observer = new IntersectionObserver((entries) => {\n if (removed || loadingMore || !entries.some((e) => e.isIntersecting)) return;\n loadingMore = true;\n host\n .loadMore()\n .catch(() => undefined)\n .finally(() => {\n loadingMore = false;\n });\n });\n observer.observe(sentinel);\n }\n\n // The viewability dwell stops while the page is hidden.\n const onVisibility = () => {\n const visible = document.visibilityState !== 'hidden';\n nodes.forEach((n) => {\n if (!n.tracker) return;\n if (visible) n.tracker.resume();\n else n.tracker.pause();\n });\n };\n if (typeof document.addEventListener === 'function') document.addEventListener('visibilitychange', onVisibility);\n\n return {\n render,\n remove() {\n if (removed) return;\n removed = true;\n observer?.disconnect();\n if (typeof document.removeEventListener === 'function') document.removeEventListener('visibilitychange', onVisibility);\n nodes.forEach((n) => n.tracker?.cancel());\n nodes.clear();\n root.remove();\n },\n };\n}\n","/**\n * The contract between the core (src/core/cards.ts) and the default card feed\n * renderer, `joryio-cards-ui.min.js` (src/cards-ui/), a separate file next to\n * `joryio.min.js` on the SDK host (BACKLOG D444). Only a page that calls\n * `mountCardFeed` downloads it; the data API (getCards, markCard*, ...) stays\n * in the core.\n *\n * The renderer registers one global, `__joryioCardsUi`, and nothing else. The\n * core reads it once, checks `version`, keeps the reference, and hands each\n * mount a `CardFeedHost`: what the renderer may do is exactly what the public\n * API already lets a page do (read the feed, report viewed / read / clicked /\n * dismissed, pass a link to its own link handler, load the next page) - never\n * the delivery tokens, the request code or the storage. A page that replaced the global\n * would get nothing it could not already call on `window.Joryio`.\n *\n * Type-only imports: nothing of the core is bundled into the renderer through here.\n */\nimport type { Card, CardFeed, MountCardFeedOptions } from './cards';\nimport type { ViewTracker } from './placements';\nimport type { Logger } from '../utils/logger';\n\nexport const CARDS_UI_GLOBAL = '__joryioCardsUi';\n/** Bumped on a breaking change to CardFeedHost / CardsUiBundleApi; a renderer of another version is refused. */\nexport const CARDS_UI_API_VERSION = 1;\n/** The file next to joryio.min.js on the SDK host (and in the npm package's dist/). */\nexport const CARDS_UI_BUNDLE_FILE = 'joryio-cards-ui.min.js';\n\n/** What one mounted feed may ask of the core. */\nexport interface CardFeedHost {\n /** The feed now (cached, with this browser's read / dismissed state applied). */\n view(): CardFeed;\n /** Bumped when the person or the consent changes: a node drawn under an older one does nothing. */\n generation(): number;\n markCardViewed(card: Card): void;\n markCardRead(card: Card): void;\n markCardClicked(card: Card): void;\n dismissCard(card: Card): void;\n /** Hand a card link to the site-wide link handler (`setLinkHandler`); `fallback` runs when there is none or it declined. */\n routeLink(url: string, context: { campaignId?: string; cardId?: string }, fallback: () => void): void;\n /** Load the page after the feed's nextCursor, if any (a no-op on the last page). */\n loadMore(): Promise<void>;\n /** The viewability rule (half the card on screen for the dwell), the same as placements'. */\n trackViewable(node: Element, onViewable: () => void): ViewTracker;\n logger: Logger;\n}\n\n/** One drawn feed. */\nexport interface CardFeedView {\n /** Redraw from host.view() (the core calls it on every feed change). */\n render(): void;\n /** Take out everything drawn and stop observing. */\n remove(): void;\n}\n\nexport interface CardsUiBundleApi {\n version: number;\n mount(element: HTMLElement, options: MountCardFeedOptions, host: CardFeedHost): CardFeedView;\n}\n","/**\n * The default card feed bundle - `joryio-cards-ui.min.js` on the SDK host,\n * next to `joryio.min.js` (BACKLOG D444).\n *\n * Loaded by the core (src/core/cards.ts) the first time the page calls\n * `mountCardFeed`, so a visitor of a site without a feed never downloads it.\n * It registers one global and does nothing else on its own: no request, no\n * listener, until the core calls `mount` with a CardFeedHost.\n *\n * A bundler user who does not want the SDK host fetch imports this file once\n * (`import '@joryio/web-sdk/dist/joryio-cards-ui.min.js'`): the core finds the\n * global and draws at once.\n */\nimport { mountFeedView } from './card-feed-view';\nimport { CARDS_UI_API_VERSION, CARDS_UI_GLOBAL, type CardsUiBundleApi } from '../core/cards-ui-contract';\n\nconst api: CardsUiBundleApi = {\n version: CARDS_UI_API_VERSION,\n mount: mountFeedView,\n};\n\nif (typeof window !== 'undefined' && !(window as any)[CARDS_UI_GLOBAL]) {\n (window as any)[CARDS_UI_GLOBAL] = api;\n}\n\nexport { api as cardsUiApi };\n"],"names":["safeHttpUrl","url","test","REFUSED_LINK_SCHEMES","DEFAULT_LABELS","emptyText","pinnedLabel","dismissLabel","unreadLabel","CARDS_UI_GLOBAL","api","version","mount","element","options","host","opts","removed","loadingMore","nodes","Map","empty","root","document","createElement","className","setAttribute","sentinel","appendChild","label","k","v","drawCard","card","generation","el","id","read","pinned","style","cssText","open","markCardClicked","_a","trim","context","campaignId","cardId","http","routeLink","window","error","logger","debug","m","exec","scheme","toLowerCase","includes","isAppDeepLink","onDeepLink","warn","click","addEventListener","e","key","target","image","imageUrl","img","src","alt","header","dot","textContent","title","dismiss","type","stopPropagation","dismissCard","body","buttonText","btn","observer","IntersectionObserver","entries","some","isIntersecting","loadMore","catch","finally","observe","onVisibility","visible","visibilityState","forEach","n","tracker","resume","pause","render","feed","view","keep","cards","createdAt","sig","JSON","stringify","existing","get","set","delete","node","trackViewable","markCardViewed","markCardRead","cancel","remove","length","onRender","disconnect","removeEventListener","clear"],"mappings":"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"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Joryio Web SDK v1.4.0-beta.8
2
+ * Joryio Web SDK v1.4.0-beta.9
3
3
  * (c) 2026 Joryio. All rights reserved.
4
4
  * @license Commercial - see https://github.com/joryio/joryio-web-sdk/blob/main/LICENSE
5
5
  */