@joryio/web-sdk 1.4.0-beta.1 → 1.4.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +1 -1
  3. package/dist/cards-ui/card-feed-view.d.ts +4 -0
  4. package/dist/cards-ui/card-feed-view.d.ts.map +1 -0
  5. package/dist/cards-ui/index.d.ts +4 -0
  6. package/dist/cards-ui/index.d.ts.map +1 -0
  7. package/dist/core/cards-ui-contract.d.ts +30 -0
  8. package/dist/core/cards-ui-contract.d.ts.map +1 -0
  9. package/dist/core/cards.d.ts +130 -0
  10. package/dist/core/cards.d.ts.map +1 -0
  11. package/dist/core/config.d.ts +21 -1
  12. package/dist/core/config.d.ts.map +1 -1
  13. package/dist/core/editor-gate.d.ts +47 -0
  14. package/dist/core/editor-gate.d.ts.map +1 -0
  15. package/dist/core/flags.d.ts +73 -0
  16. package/dist/core/flags.d.ts.map +1 -0
  17. package/dist/core/inapp.d.ts +13 -1
  18. package/dist/core/inapp.d.ts.map +1 -1
  19. package/dist/core/links.d.ts +27 -0
  20. package/dist/core/links.d.ts.map +1 -0
  21. package/dist/core/network.d.ts.map +1 -1
  22. package/dist/core/page-context.d.ts +101 -0
  23. package/dist/core/page-context.d.ts.map +1 -0
  24. package/dist/core/page-edits.d.ts +129 -0
  25. package/dist/core/page-edits.d.ts.map +1 -0
  26. package/dist/core/placements.d.ts +218 -0
  27. package/dist/core/placements.d.ts.map +1 -0
  28. package/dist/core/sdk-host-files.d.ts +5 -0
  29. package/dist/core/sdk-host-files.d.ts.map +1 -0
  30. package/dist/core/sdk.d.ts +36 -0
  31. package/dist/core/sdk.d.ts.map +1 -1
  32. package/dist/editor/index.d.ts +4 -0
  33. package/dist/editor/index.d.ts.map +1 -0
  34. package/dist/editor/visual-editor.d.ts +39 -0
  35. package/dist/editor/visual-editor.d.ts.map +1 -0
  36. package/dist/index.d.mts +201 -3
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/joryio-cards-ui.min.js +7 -0
  40. package/dist/joryio-cards-ui.min.js.map +1 -0
  41. package/dist/joryio-editor.min.js +7 -0
  42. package/dist/joryio-editor.min.js.map +1 -0
  43. package/dist/joryio-sw.js +1 -1
  44. package/dist/joryio.cjs.js +7200 -3513
  45. package/dist/joryio.min.js +2 -2
  46. package/dist/joryio.min.js.map +1 -1
  47. package/dist/joryio.mjs +7192 -3514
  48. package/dist/joryio.umd.js +7200 -3513
  49. package/package.json +4 -1
  50. package/src/cards-ui/card-feed-view.ts +249 -0
  51. package/src/cards-ui/index.ts +26 -0
  52. package/src/core/cards-ui-contract.ts +58 -0
  53. package/src/core/cards.ts +843 -0
  54. package/src/core/config.ts +86 -2
  55. package/src/core/editor-gate.ts +158 -0
  56. package/src/core/flags.ts +372 -0
  57. package/src/core/inapp.ts +283 -152
  58. package/src/core/links.ts +104 -0
  59. package/src/core/network.ts +5 -2
  60. package/src/core/page-context.ts +460 -0
  61. package/src/core/page-edits.ts +1036 -0
  62. package/src/core/placements.ts +1431 -0
  63. package/src/core/sdk-host-files.ts +93 -0
  64. package/src/core/sdk.ts +378 -1
  65. package/src/editor/index.ts +27 -0
  66. package/src/editor/visual-editor.ts +301 -0
  67. package/src/index.ts +33 -0
  68. package/src/snippet/loader.js +25 -1
@@ -0,0 +1,39 @@
1
+ import type { Logger } from '../utils/logger';
2
+ import { type PageEditOperation } from '../core/page-edits';
3
+ import { EDITOR_MESSAGES } from '../core/editor-gate';
4
+ export { EDITOR_MESSAGES };
5
+ export declare function cssEscape(value: string): string;
6
+ export declare function robustSelector(el: Element): string | null;
7
+ export declare function operationsFor(el: Element): PageEditOperation[];
8
+ export interface EditorPick {
9
+ type: typeof EDITOR_MESSAGES.PICK;
10
+ selector: string;
11
+ operation: PageEditOperation;
12
+ value?: string;
13
+ placementKey?: string;
14
+ position?: 'before' | 'after' | 'prepend' | 'append';
15
+ tag: string;
16
+ text: string;
17
+ }
18
+ export declare class VisualEditor {
19
+ private dashboardOrigin;
20
+ private opener;
21
+ private logger;
22
+ private onStop;
23
+ private listeners;
24
+ private highlight;
25
+ private panel;
26
+ private selected;
27
+ private active;
28
+ constructor(dashboardOrigin: string, opener: Window, logger: Logger, onStop?: () => void);
29
+ start(): void;
30
+ isActive(): boolean;
31
+ stop(): void;
32
+ private send;
33
+ private activate;
34
+ private outline;
35
+ private unselect;
36
+ select(el: Element): void;
37
+ pick(el: Element, selector: string, operation: PageEditOperation, value: string): boolean;
38
+ }
39
+ //# sourceMappingURL=visual-editor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visual-editor.d.ts","sourceRoot":"","sources":["../../src/editor/visual-editor.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAiC,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC3F,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,CAAC;AAO3B,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAa/C;AAmBD,wBAAgB,cAAc,CAAC,EAAE,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAmCzD;AAGD,wBAAgB,aAAa,CAAC,EAAE,EAAE,OAAO,GAAG,iBAAiB,EAAE,CAO9D;AAED,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,OAAO,eAAe,CAAC,IAAI,CAAC;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,iBAAiB,CAAC;IAC7B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,SAAS,GAAG,QAAQ,CAAC;IACrD,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CACd;AAED,qBAAa,YAAY;IAQrB,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,MAAM;IAVhB,OAAO,CAAC,SAAS,CAAyB;IAC1C,OAAO,CAAC,SAAS,CAA4B;IAC7C,OAAO,CAAC,KAAK,CAA4B;IACzC,OAAO,CAAC,QAAQ,CAAwB;IACxC,OAAO,CAAC,MAAM,CAAS;gBAGb,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,GAAE,MAAM,IAAsB;IAI9C,KAAK,IAAI,IAAI;IAcb,QAAQ,IAAI,OAAO;IAInB,IAAI,IAAI,IAAI;IAgBZ,OAAO,CAAC,IAAI;IASZ,OAAO,CAAC,QAAQ;IAsChB,OAAO,CAAC,OAAO;IAUf,OAAO,CAAC,QAAQ;IAMhB,MAAM,CAAC,EAAE,EAAE,OAAO,GAAG,IAAI;IAkDzB,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO;CAqB1F"}
package/dist/index.d.mts CHANGED
@@ -357,12 +357,21 @@ interface InAppOptions {
357
357
  syncInterval?: number;
358
358
  displayOptions?: InAppDisplayOptions;
359
359
  allowHtmlJsInAppMessages?: boolean;
360
+ autoMountPlacements?: boolean;
360
361
  onMessageDisplay?: (message: any) => void;
361
362
  onMessageClick?: (message: any, action: string) => void;
362
363
  onMessageDismiss?: (message: any, action: string) => void;
363
364
  }
364
365
  interface InitConfig {
365
366
  sdkKey: string;
367
+ pageContext?: {
368
+ pageVariables?: string[];
369
+ dataLayerVariables?: string[];
370
+ dataLayerName?: string;
371
+ };
372
+ pageEdits?: boolean;
373
+ editorScriptUrl?: string;
374
+ cardsUiScriptUrl?: string;
366
375
  apiEndpoint?: string;
367
376
  userId?: string;
368
377
  anonymousId?: string;
@@ -403,6 +412,38 @@ interface Plugin {
403
412
  afterTrack?(event: any): void;
404
413
  }
405
414
 
415
+ type PageVariableValue = string | number | boolean;
416
+ interface PageUrlRule {
417
+ op: string;
418
+ value: string;
419
+ }
420
+ interface PageVariableRule {
421
+ source: string;
422
+ key: string;
423
+ op: string;
424
+ value?: PageVariableValue;
425
+ }
426
+ interface PageTargeting {
427
+ urls?: {
428
+ include?: PageUrlRule[];
429
+ exclude?: PageUrlRule[];
430
+ };
431
+ variables?: PageVariableRule[];
432
+ }
433
+
434
+ type JoryioLinkSource = 'in_app' | 'placement' | 'card' | 'push';
435
+ interface JoryioLink {
436
+ url: string;
437
+ source: JoryioLinkSource;
438
+ campaignId?: string;
439
+ placementKey?: string;
440
+ itemId?: string;
441
+ cardId?: string;
442
+ isAppDeepLink: boolean;
443
+ openDefault: () => void;
444
+ }
445
+ type JoryioLinkHandler = (link: JoryioLink) => boolean;
446
+
406
447
  interface InAppCampaign {
407
448
  id: string;
408
449
  name: string;
@@ -446,9 +487,10 @@ interface InAppCampaign {
446
487
  triggers: InAppTrigger[];
447
488
  reevaluateBeforeDisplay?: boolean;
448
489
  watchedAttributes?: string[];
490
+ pageTargeting?: PageTargeting;
449
491
  }
450
492
  interface InAppTrigger {
451
- type: 'immediate' | 'event' | 'attribute_change' | 'attribute_threshold' | 'push_notification_tap';
493
+ type: 'immediate' | 'event' | 'attribute_change' | 'attribute_threshold' | 'push_notification_tap' | 'page_view' | 'exit_intent' | 'scroll_depth' | 'time_on_page';
452
494
  event?: string;
453
495
  attribute?: string;
454
496
  operator?: string;
@@ -462,6 +504,130 @@ interface InAppMessage {
462
504
  }
463
505
  declare const IN_APP_DISPLAY_DWELL_MS = 1000;
464
506
 
507
+ declare const PLACEMENT_VIEWABLE_FRACTION = 0.5;
508
+ declare const PLACEMENT_MIN_REFRESH_SECONDS = 30;
509
+ declare const PLACEMENT_PRODUCT_ELEMENT_PREFIX = "product:";
510
+ declare const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
511
+ declare function placementProductElementId(productId: string): string;
512
+ type PlacementEmptyBehavior = 'collapse' | 'keep_space';
513
+ type PlacementItemKind = 'native' | 'html' | 'data';
514
+ type PlacementContent = {
515
+ kind: 'html';
516
+ html: string;
517
+ css?: string;
518
+ } | {
519
+ kind: 'native';
520
+ title?: string;
521
+ body?: string;
522
+ imageUrl?: string;
523
+ buttons?: Array<{
524
+ id: string;
525
+ text: string;
526
+ action: string;
527
+ url?: string;
528
+ }>;
529
+ closeButton?: boolean;
530
+ };
531
+ interface PlacementProduct {
532
+ id: string;
533
+ title: string | null;
534
+ price: string | null;
535
+ compareAtPrice: string | null;
536
+ discountPercent: number | null;
537
+ imageUrl: string | null;
538
+ url: string | null;
539
+ }
540
+ interface PlacementItem {
541
+ id: string;
542
+ variantId?: string | null;
543
+ kind: PlacementItemKind;
544
+ data: Record<string, string | number | boolean>;
545
+ content?: PlacementContent | null;
546
+ products: PlacementProduct[];
547
+ priority?: number;
548
+ expiresAt?: string | null;
549
+ markDisplayed(): void;
550
+ markClicked(elementId?: string): void;
551
+ markDismissed(): void;
552
+ }
553
+ interface Placement {
554
+ placementKey: string;
555
+ items: PlacementItem[];
556
+ isControl: boolean;
557
+ emptyBehavior: PlacementEmptyBehavior;
558
+ maxItems: number;
559
+ ttlSeconds: number;
560
+ markDisplayed(): void;
561
+ }
562
+ interface PlacementHandle {
563
+ placementKey: string;
564
+ element: HTMLElement;
565
+ remove(): void;
566
+ }
567
+ interface InsertPlacementOptions {
568
+ onRender?: (placement: Placement, element: HTMLElement) => void;
569
+ onDeepLink?: (url: string, item: PlacementItem) => void;
570
+ showProducts?: boolean;
571
+ productButtonText?: string;
572
+ productCardWidth?: number;
573
+ }
574
+ type PlacementsUpdatedCallback = (placements: Record<string, Placement>) => void;
575
+
576
+ declare const CARD_MIN_REFRESH_SECONDS = 30;
577
+ declare const CARD_FEED_TTL_SECONDS = 300;
578
+ type CardStateScope = 'server' | 'device';
579
+ interface Card {
580
+ id: string;
581
+ campaignId: string;
582
+ variantId: string | null;
583
+ title: string | null;
584
+ body: string | null;
585
+ imageUrl: string | null;
586
+ buttonText: string | null;
587
+ url: string | null;
588
+ pinned: boolean;
589
+ createdAt: string;
590
+ expiresAt: string | null;
591
+ read: boolean;
592
+ clicked: boolean;
593
+ }
594
+ interface CardFeed {
595
+ cards: Card[];
596
+ unreadCount: number;
597
+ nextCursor: string | null;
598
+ stateScope: CardStateScope;
599
+ }
600
+ interface GetCardsOptions {
601
+ cursor?: string | null;
602
+ }
603
+ type CardsUpdatedCallback = (feed: CardFeed) => void;
604
+ interface MountCardFeedOptions {
605
+ emptyText?: string;
606
+ pinnedLabel?: string;
607
+ dismissLabel?: string;
608
+ unreadLabel?: string;
609
+ onDeepLink?: (url: string, card: Card) => void;
610
+ onRender?: (feed: CardFeed, element: HTMLElement) => void;
611
+ }
612
+ interface CardFeedHandle {
613
+ element: HTMLElement;
614
+ remove(): void;
615
+ }
616
+
617
+ declare const FLAGS_MIN_REFRESH_SECONDS = 60;
618
+ declare const FLAG_SYNC_PUSH_VALUE = "flags";
619
+ type FlagValueType = 'boolean' | 'string' | 'number' | 'json';
620
+ type FlagReason = 'off' | 'rule' | 'default' | 'holdout' | 'archived' | 'override' | 'experiment';
621
+ interface FlagResult {
622
+ value: unknown;
623
+ variant: string;
624
+ valueType: FlagValueType;
625
+ reason: FlagReason;
626
+ version: number;
627
+ logExposure: boolean;
628
+ }
629
+ type FlagsUpdatedCallback = (changedKeys: string[]) => void;
630
+
465
631
  interface EcommerceProduct {
466
632
  productId: string;
467
633
  name: string;
@@ -613,6 +779,13 @@ declare class JoryioSDK {
613
779
  private network;
614
780
  private utm;
615
781
  private inapp;
782
+ private placements;
783
+ private cards;
784
+ private links;
785
+ private pageContext;
786
+ private pageEdits;
787
+ private editor;
788
+ private flags;
616
789
  private _user;
617
790
  private _push;
618
791
  private _ecommerce;
@@ -741,11 +914,36 @@ declare class JoryioSDK {
741
914
  displayInAppCampaign(campaignId: string): Promise<void>;
742
915
  dismissInAppMessage(campaignId: string): void;
743
916
  trackInAppConversion(campaignId: string, eventName: string): Promise<void>;
917
+ private placementConsent;
918
+ setLinkHandler(handler: JoryioLinkHandler): void;
919
+ clearLinkHandler(): void;
920
+ setPageVariables(variables: Record<string, string | number | boolean> | null): void;
921
+ insertPlacement(placementKey: string, element: HTMLElement, options?: InsertPlacementOptions): PlacementHandle | null;
922
+ getPlacements(placementKeys: string[]): Promise<Record<string, Placement>>;
923
+ refreshPlacements(placementKeys?: string[]): Promise<void>;
924
+ onPlacementsUpdated(callback: PlacementsUpdatedCallback): () => void;
925
+ getCards(options?: GetCardsOptions): Promise<CardFeed>;
926
+ getUnreadCardCount(): number;
927
+ markCardViewed(card: Card | string): void;
928
+ markCardRead(card: Card | string): void;
929
+ markCardClicked(card: Card | string): void;
930
+ dismissCard(card: Card | string): void;
931
+ refreshCards(): Promise<void>;
932
+ onCardsUpdated(callback: CardsUpdatedCallback): () => void;
933
+ mountCardFeed(element: HTMLElement, options?: MountCardFeedOptions): CardFeedHandle | null;
934
+ getFlag<T = unknown>(key: string, defaultValue: T): T;
935
+ getBoolFlag(key: string, defaultValue: boolean): boolean;
936
+ getStringFlag(key: string, defaultValue: string): string;
937
+ getNumberFlag(key: string, defaultValue: number): number;
938
+ getJsonFlag<T = unknown>(key: string, defaultValue: T): T;
939
+ getAllFlags(): Record<string, unknown>;
940
+ refreshFlags(): Promise<void>;
941
+ onFlagsUpdated(callback: FlagsUpdatedCallback): () => void;
744
942
  destroy(): Promise<void>;
745
943
  static getInstance(): JoryioSDK | null;
746
944
  }
747
945
 
748
946
  declare function installSnippetQueue(win: any): void;
749
947
 
750
- export { EcommerceTracker, IN_APP_DISPLAY_DWELL_MS, JoryioSDK, PushManager, SDK_VERSION, SubscriptionStatus, User, createEcommerceTracker, JoryioSDK as default, installSnippetQueue };
751
- export type { EcommerceCartItem, EcommerceConfig, EcommerceOrder, EcommerceProduct, InAppCampaign, InAppDisplayOptions, InAppMessage, InAppOptions, InAppTrigger, InitConfig, Plugin, PushPermissionState, PushSubscribeOptions, SdkAuthFailureCallback, SdkAuthFailureInfo, SdkAuthFailureReason, StorefrontIdentityTokenProvider, SubscriptionChannel, SubscriptionPreferences, TrackingConsent, UTMData, UTMParameters };
948
+ export { CARD_FEED_TTL_SECONDS, CARD_MIN_REFRESH_SECONDS, EcommerceTracker, FLAGS_MIN_REFRESH_SECONDS, FLAG_SYNC_PUSH_VALUE, IN_APP_DISPLAY_DWELL_MS, JoryioSDK, PLACEMENT_MIN_REFRESH_SECONDS, PLACEMENT_PRODUCT_CARD_WIDTH, PLACEMENT_PRODUCT_ELEMENT_PREFIX, PLACEMENT_VIEWABLE_FRACTION, PushManager, SDK_VERSION, SubscriptionStatus, User, createEcommerceTracker, JoryioSDK as default, installSnippetQueue, placementProductElementId };
949
+ export type { Card, CardFeed, CardFeedHandle, CardStateScope, CardsUpdatedCallback, EcommerceCartItem, EcommerceConfig, EcommerceOrder, EcommerceProduct, FlagReason, FlagResult, FlagValueType, FlagsUpdatedCallback, GetCardsOptions, InAppCampaign, InAppDisplayOptions, InAppMessage, InAppOptions, InAppTrigger, InitConfig, InsertPlacementOptions, JoryioLink, JoryioLinkHandler, JoryioLinkSource, MountCardFeedOptions, Placement, PlacementContent, PlacementEmptyBehavior, PlacementHandle, PlacementItem, PlacementItemKind, PlacementsUpdatedCallback, Plugin, PushPermissionState, PushSubscribeOptions, SdkAuthFailureCallback, SdkAuthFailureInfo, SdkAuthFailureReason, StorefrontIdentityTokenProvider, SubscriptionChannel, SubscriptionPreferences, TrackingConsent, UTMData, UTMParameters };
package/dist/index.d.ts CHANGED
@@ -17,6 +17,14 @@ export { EcommerceTracker, createEcommerceTracker };
17
17
  export type { InitConfig, Plugin, InAppOptions, InAppDisplayOptions, InAppCampaign, InAppMessage, InAppTrigger, UTMParameters, UTMData, SubscriptionChannel, SubscriptionPreferences, PushSubscribeOptions, PushPermissionState, TrackingConsent, EcommerceProduct, EcommerceCartItem, EcommerceOrder, EcommerceConfig, SdkAuthFailureInfo, SdkAuthFailureReason, SdkAuthFailureCallback, StorefrontIdentityTokenProvider, };
18
18
  export { SDK_VERSION } from './core/config';
19
19
  export { IN_APP_DISPLAY_DWELL_MS } from './core/inapp';
20
+ export { PLACEMENT_VIEWABLE_FRACTION, PLACEMENT_MIN_REFRESH_SECONDS } from './core/placements';
21
+ export { PLACEMENT_PRODUCT_ELEMENT_PREFIX, PLACEMENT_PRODUCT_CARD_WIDTH, placementProductElementId } from './core/placements';
22
+ export type { Placement, PlacementItem, PlacementHandle, PlacementContent, PlacementEmptyBehavior, PlacementItemKind, InsertPlacementOptions, PlacementsUpdatedCallback, } from './core/placements';
23
+ export type { JoryioLink, JoryioLinkSource, JoryioLinkHandler } from './core/links';
24
+ export { CARD_MIN_REFRESH_SECONDS, CARD_FEED_TTL_SECONDS } from './core/cards';
25
+ export type { Card, CardFeed, CardStateScope, CardFeedHandle, GetCardsOptions, MountCardFeedOptions, CardsUpdatedCallback, } from './core/cards';
26
+ export { FLAGS_MIN_REFRESH_SECONDS, FLAG_SYNC_PUSH_VALUE } from './core/flags';
27
+ export type { FlagResult, FlagValueType, FlagReason, FlagsUpdatedCallback } from './core/flags';
20
28
  export default JoryioSDK;
21
29
  export declare function installSnippetQueue(win: any): void;
22
30
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,SAAS,EAA8D,MAAM,YAAY,CAAC;AACnG,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,YAAY,CAAC;AACnE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC3F,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,E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blob/main/LICENSE
5
+ */
6
+ !function(){"use strict";function n(n){return"string"==typeof n&&/^https?:\/\//i.test(n)?n:null}const t=["javascript","data","file","vbscript","blob","about","content","intent"],e={emptyText:"No messages yet",pinnedLabel:"Pinned",dismissLabel:"Dismiss",unreadLabel:"Unread"},o="__joryioCardsUi",i={version:1,mount:function(o,i,r){const d=i||{};let c=!1,a=!1,l=new Map,s=null;const u=document.createElement("div");u.className="joryio-card-feed",u.setAttribute("role","list");const p=document.createElement("div");p.className="joryio-card-feed-end",p.setAttribute("aria-hidden","true"),o.appendChild(u);const f=n=>{const t=d[n];return"string"==typeof t?t:e[n]},m=(e,o)=>{const i=document.createElement("div");i.className="joryio-card",i.setAttribute("role","listitem"),i.setAttribute("data-joryio-card",e.id),i.setAttribute("data-joryio-card-read",e.read?"true":"false"),e.pinned&&i.setAttribute("data-joryio-card-pinned","true"),i.style.cssText="position:relative;box-sizing:border-box;padding:12px 16px;"+(e.url?"cursor:pointer;":"");const a=()=>!c&&o===r.generation()&&(e=>{var o;r.markCardClicked(e);const i=null===(o=e.url)||void 0===o?void 0:o.trim();if(!i)return;const c={campaignId:e.campaignId,cardId:e.id},a=n(i);a?r.routeLink(a,c,()=>{try{window.open(a,"_blank","noopener")}catch(n){r.logger.debug("Could not open the card link",n)}}):function(n){if("string"!=typeof n)return!1;const e=/^([a-z][a-z0-9+.-]*):\/\/./i.exec(n.trim());if(!e)return!1;const o=e[1].toLowerCase();return"http"!==o&&"https"!==o&&!t.includes(o)}(i)?r.routeLink(i,c,()=>{if(d.onDeepLink)try{d.onDeepLink(i,e)}catch(n){r.logger.error("The mountCardFeed onDeepLink callback threw; ignored:",n)}}):r.logger.warn("Card link refused: not http(s) or an app deep link")})(e);e.url&&(i.setAttribute("tabindex","0"),i.addEventListener("click",a),i.addEventListener("keydown",n=>{"Enter"===(null==n?void 0:n.key)&&(null==n?void 0:n.target)===i&&a()}));const l=n(e.imageUrl);if(l){const n=document.createElement("img");n.className="joryio-card-image",n.src=l,n.alt="",n.style.cssText="display:block;max-width:100%;height:auto;margin-bottom:8px;",i.appendChild(n)}const s=document.createElement("div");if(s.className="joryio-card-header",s.style.cssText="display:flex;align-items:center;gap:6px;",!e.read){const n=document.createElement("span");n.className="joryio-card-unread",n.setAttribute("role","img"),n.setAttribute("aria-label",f("unreadLabel")),n.textContent="●",n.style.cssText="font-size:10px;line-height:1;",s.appendChild(n)}const u=document.createElement("div");if(u.className="joryio-card-title",u.textContent=e.title||"",u.style.cssText="flex:1;font-weight:bold;",s.appendChild(u),e.pinned){const n=document.createElement("span");n.className="joryio-card-pinned",n.textContent=f("pinnedLabel"),n.style.cssText="font-size:0.8em;",s.appendChild(n)}const p=document.createElement("button");if(p.type="button",p.className="joryio-card-dismiss",p.setAttribute("aria-label",f("dismissLabel")),p.textContent="×",p.style.cssText="background:none;border:0;padding:4px 8px;color:inherit;font:inherit;font-size:1.25em;line-height:1;cursor:pointer;",p.addEventListener("click",n=>{var t;null===(t=null==n?void 0:n.stopPropagation)||void 0===t||t.call(n),o===r.generation()&&r.dismissCard(e)}),s.appendChild(p),i.appendChild(s),e.body){const n=document.createElement("div");n.className="joryio-card-body",n.textContent=e.body,i.appendChild(n)}if(e.buttonText&&e.url){const n=document.createElement("button");n.type="button",n.className="joryio-card-button",n.textContent=e.buttonText,n.style.cssText="margin-top:8px;font:inherit;",n.addEventListener("click",n=>{var t;null===(t=null==n?void 0:n.stopPropagation)||void 0===t||t.call(n),a()}),i.appendChild(n)}return i};let y=null;"undefined"!=typeof IntersectionObserver&&(y=new IntersectionObserver(n=>{c||a||!n.some(n=>n.isIntersecting)||(a=!0,r.loadMore().catch(()=>{}).finally(()=>{a=!1}))}),y.observe(p));const b=()=>{const n="hidden"!==document.visibilityState;l.forEach(t=>{t.tracker&&(n?t.tracker.resume():t.tracker.pause())})};return"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",b),{render:()=>{if(c)return;const n=r.view(),t=r.generation(),e=new Map;for(const o of n.cards){const n=`${o.id}\0${o.createdAt}`,i=JSON.stringify(o),d=l.get(n);if(d&&d.sig===i){e.set(n,d),l.delete(n);continue}const c=m(o,t),a=o.read?null:r.trackViewable(c,()=>{t===r.generation()&&(r.markCardViewed(o),r.markCardRead(o))});e.set(n,{node:c,sig:i,tracker:a})}if(l.forEach(n=>{var t;null===(t=n.tracker)||void 0===t||t.cancel(),n.node.remove()}),l=e,s&&(s.remove(),s=null),p.remove(),n.cards.length?e.forEach(n=>u.appendChild(n.node)):(s=document.createElement("div"),s.className="joryio-card-feed-empty",s.textContent=f("emptyText"),s.style.cssText="padding:32px 16px;text-align:center;",u.appendChild(s)),u.appendChild(p),o.setAttribute("data-joryio-card-feed-state",n.cards.length?"filled":"empty"),d.onRender)try{d.onRender(n,o)}catch(n){r.logger.error("The mountCardFeed onRender callback threw; ignored:",n)}},remove(){c||(c=!0,null==y||y.disconnect(),"function"==typeof document.removeEventListener&&document.removeEventListener("visibilitychange",b),l.forEach(n=>{var t;return null===(t=n.tracker)||void 0===t?void 0:t.cancel()}),l.clear(),u.remove())}}}};"undefined"==typeof window||window[o]||(window[o]=i)}();
7
+ //# sourceMappingURL=joryio-cards-ui.min.js.map
@@ -0,0 +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 { 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 an unsubscribe. */\n onPlacementsUpdated(callback: PlacementsUpdatedCallback): () => void {\n if (typeof callback !== 'function') return () => undefined;\n this.listeners.add(callback);\n return () => {\n this.listeners.delete(callback);\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":";;;;;yBA0SM,SAAUA,EAAYC,GAC1B,MAAsB,iBAARA,GAAoB,gBAAgBC,KAAKD,GAAOA,EAAM,IACtE,CAGA,MAAME,EAAuB,CAAC,aAAc,OAAQ,OAAQ,WAAY,OAAQ,QAAS,UAAW,UCjS9FC,EAAiB,CAAEC,UAAW,kBAAmBC,YAAa,SAAUC,aAAc,UAAWC,YAAa,UCOvGC,EAAkB,kBCLzBC,EAAwB,CAC5BC,QDMkC,ECLlCC,eFF4BC,EAAsBC,EAA+BC,GACjF,MAAMC,EAAOF,GAAW,CAAA,EACxB,IAAIG,GAAU,EACVC,GAAc,EAEdC,EAAQ,IAAIC,IACZC,EAA4B,KAEhC,MAAMC,EAAOC,SAASC,cAAc,OACpCF,EAAKG,UAAY,mBACjBH,EAAKI,aAAa,OAAQ,QAC1B,MAAMC,EAAWJ,SAASC,cAAc,OACxCG,EAASF,UAAY,uBACrBE,EAASD,aAAa,cAAe,QACrCb,EAAQe,YAAYN,GA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,EAAMwG,QACNrG,EAAKgG,SACP,EAEJ,GEnOsB,oBAAXpE,QAA4BA,OAAezC,KACnDyC,OAAezC,GAAmBC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Joryio Web SDK v1.4.0-beta.4
3
+ * (c) 2026 Joryio. All rights reserved.
4
+ * @license Commercial - see https://github.com/joryio/joryio-web-sdk/blob/main/LICENSE
5
+ */
6
+ !function(){"use strict";function t(t){if("string"!=typeof t)return!1;const e=t.trim();if(!e||e.length>500)return!1;if(/[{};<@]/.test(e)||e.includes("/*")||e.includes("*/"))return!1;if(/[\u0000-\u001f\u007f]/.test(e))return!1;try{"undefined"!=typeof document&&document.createDocumentFragment().querySelector(e)}catch(t){return!1}return!0}const e=/\/joryio(?:\.umd)?(?:\.min)?\.js$/;function i(t){if(!t||"string"!=typeof t)return null;let i;try{i=new URL(t)}catch(t){return null}return"https:"===i.protocol&&e.test(i.pathname)?`${i.origin}${i.pathname.replace(/[^/]*$/,"")}`:null}!function(){if("undefined"==typeof document)return null;try{const t=document.currentScript,e=i(t&&t.src);if(e||t&&t.src)return e;const n=document.querySelectorAll("script[src]");for(let t=n.length-1;t>=0;t--){const e=i(n[t].src);if(e)return e}}catch(t){}}();const n="__joryioEditor",o=["data-joryio-id","data-testid","data-test","data-qa","data-cy","data-id","name"],r=/^[a-z0-9][a-z0-9_]{0,63}$/,s=(t,e,i)=>{try{const n=t.querySelectorAll(e);return 1===n.length&&n[0]===i}catch(t){return!1}};class c{constructor(t,e,i,n=()=>{}){this.dashboardOrigin=t,this.opener=e,this.logger=i,this.onStop=n,this.listeners=[],this.highlight=null,this.panel=null,this.selected=null,this.active=!1}start(){if(this.active)return;this.active=!0;const t=t=>{const e=t.data;e&&"string"==typeof e.type&&t.origin===this.dashboardOrigin&&t.source===this.opener&&"joryio:editor-close"===e.type&&this.stop()};window.addEventListener("message",t),this.listeners.push(()=>window.removeEventListener("message",t)),this.activate()}isActive(){return this.active}stop(){var t,e;if(this.active){this.send({type:"joryio:editor-closed"}),this.active=!1;for(const t of this.listeners.splice(0))t();null===(t=this.highlight)||void 0===t||t.remove(),null===(e=this.panel)||void 0===e||e.remove(),this.highlight=this.panel=null,this.selected=null;try{this.onStop()}catch(t){this.logger.debug("Joryio editor stop callback failed",t)}}}send(t){if(this.active)try{this.opener.postMessage(t,this.dashboardOrigin)}catch(t){}}activate(){const t=document,e=t.createElement("div");e.setAttribute("data-joryio-editor","highlight"),e.style.cssText="position:fixed;pointer-events:none;z-index:2147483646;border:2px solid #14b8a6;background:rgba(20,184,166,.12);border-radius:3px;display:none";const i=t.createElement("div");i.setAttribute("data-joryio-editor","panel"),i.style.cssText="position:fixed;left:16px;right:16px;bottom:16px;z-index:2147483647;max-width:560px;margin:0 auto;background:#0f172a;color:#fff;font:14px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:10px;box-shadow:0 8px 30px rgba(0,0,0,.3)",i.textContent="Joryio editor - click an element on the page. Esc to finish.",t.body.appendChild(e),t.body.appendChild(i),this.highlight=e,this.panel=i;const n=t=>t instanceof Element&&!!t.closest("[data-joryio-editor]"),o=t=>{this.selected||n(t.target)||this.outline(t.target instanceof Element?t.target:null)},r=t=>{n(t.target)||(t.preventDefault(),t.stopPropagation(),t.target instanceof Element&&this.select(t.target))},s=t=>{"Escape"===t.key&&(this.selected?this.unselect():this.stop())};t.addEventListener("mousemove",o,!0),t.addEventListener("click",r,!0),t.addEventListener("keydown",s,!0),this.listeners.push(()=>t.removeEventListener("mousemove",o,!0),()=>t.removeEventListener("click",r,!0),()=>t.removeEventListener("keydown",s,!0)),this.send({type:"joryio:editor-active",url:`${location.origin}${location.pathname}`})}outline(t){if(!this.highlight)return;if(!t||t===document.body||t===document.documentElement)return void(this.highlight.style.display="none");const e=t.getBoundingClientRect();Object.assign(this.highlight.style,{display:"block",top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`})}unselect(){this.selected=null,this.panel&&(this.panel.textContent="Joryio editor - click an element on the page. Esc to finish.")}select(e){const i=function(e){const i=e.ownerDocument;if(!i)return null;const n=t=>{if((e=t.id)&&e.length<=64&&!/\d{4,}/.test(e)&&!/^(ember|react|radix|headlessui|mui)[-_:]/i.test(e)&&!/:/.test(e)){const e=`#${function(t){const e=globalThis.CSS;if(e&&"function"==typeof e.escape)return e.escape(t);let i="";for(let e=0;e<t.length;e++){const n=t[e],o=t.charCodeAt(e);0===o?i+="�":/[0-9]/.test(n)&&(0===e||1===e&&"-"===t[0])?i+=`\\${o.toString(16)} `:/[A-Za-z0-9_-]/.test(n)||o>=128?i+=n:i+=`\\${n}`}return i}(t.id)}`;if(s(i,e,t))return e}var e;for(const e of o){const n=t.getAttribute(e);if(!n||n.length>100)continue;const o=`${t.tagName.toLowerCase()}[${e}="${n.replace(/["\\]/g,"\\$&")}"]`;if(s(i,o,t))return o}return null},r=n(e);if(r)return t(r)?r:null;const c=[];let a=e;for(;a&&a!==i.body&&a!==i.documentElement;){const t=c.length?n(a):null;if(t){c.unshift(t);break}const e=a.tagName.toLowerCase(),o=a.parentElement,r=o?Array.from(o.children).filter(t=>t.tagName===a.tagName):[];c.unshift(r.length>1?`${e}:nth-of-type(${r.indexOf(a)+1})`:e),a=o,a===i.body&&c.unshift("body")}const l=c.join(" > ");return l&&t(l)&&s(i,l,e)?l:null}(e);if(!this.panel)return;if(!i)return void(this.panel.textContent="This element has no stable selector. Choose its parent or another element.");this.selected=e,this.outline(e);const n=this.panel;n.textContent="";const r=(t,e=!1)=>{const i=document.createElement("div");i.textContent=t,e&&(i.style.cssText="font-family:ui-monospace,monospace;font-size:12px;opacity:.8;word-break:break-all;margin:4px 0 8px"),n.appendChild(i)};r(`<${e.tagName.toLowerCase()}> ${(e.textContent||"").trim().slice(0,60)}`),r(i,!0);const c=document.createElement("input");c.setAttribute("data-joryio-editor","value"),c.style.cssText="width:100%;box-sizing:border-box;padding:6px 8px;border-radius:6px;border:0;margin-bottom:8px;color:#0f172a",c.placeholder="New text, https:// address or placement key",n.appendChild(c);const a=document.createElement("div");a.style.cssText="display:flex;flex-wrap:wrap;gap:6px";const l={replace_text:"Replace text",replace_image:"Replace image",replace_link:"Replace link",hide:"Hide",insert_placement:"Insert placement after"};for(const t of function(t){const e=[];return"IMG"!==t.tagName&&(t.textContent||"").trim()&&e.push("replace_text"),"IMG"===t.tagName&&e.push("replace_image"),"A"===t.tagName&&e.push("replace_link"),e.push("hide","insert_placement"),e}(e)){const n=document.createElement("button");n.type="button",n.textContent=l[t],n.setAttribute("data-joryio-op",t),n.style.cssText="padding:6px 10px;border-radius:6px;border:0;background:#14b8a6;color:#fff;cursor:pointer",n.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),this.pick(e,i,t,c.value.trim())}),a.appendChild(n)}n.appendChild(a)}pick(t,e,i,n){const o={type:"joryio:editor-pick",selector:e,operation:i,tag:t.tagName.toLowerCase(),text:(t.textContent||"").trim().slice(0,200)};let s=null;if("hide"===i?s=o:"replace_text"===i?s=n||o.text?Object.assign(Object.assign({},o),{value:(n||o.text).slice(0,2e3)}):null:"replace_image"===i||"replace_link"===i?s=function(t){if("string"!=typeof t)return!1;const e=t.trim();return!(!e||e.length>2048)&&!/[\u0000-\u001f\u007f\s]/.test(e)&&/^https?:\/\/[^/?#\s]+/i.test(e)}(n)?Object.assign(Object.assign({},o),{value:n}):null:"insert_placement"===i&&(s=r.test(n)?Object.assign(Object.assign({},o),{placementKey:n,position:"after"}):null),!s){if(this.panel){const t=document.createElement("div");t.style.cssText="margin-top:6px;color:#fca5a5",t.textContent="insert_placement"===i?"Enter a placement key (lowercase letters, digits, _).":"Enter an address starting with https:// (or http://).",this.panel.appendChild(t)}return!1}return this.send(s),this.unselect(),!0}}const a={version:1,start({dashboardOrigin:t,opener:e,logger:i,onStop:n}){const o=new c(t,e,i,n);return o.start(),{stop:()=>o.stop()}}};"undefined"==typeof window||window[n]||(window[n]=a)}();
7
+ //# sourceMappingURL=joryio-editor.min.js.map