@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,93 @@
1
+ /**
2
+ * The files the core loads on demand from the SDK host, next to
3
+ * `joryio.min.js`: the point-and-click editor (`joryio-editor.min.js`,
4
+ * src/core/editor-gate.ts) and the default card feed (`joryio-cards-ui.min.js`,
5
+ * src/core/cards.ts). Kept out of the core so that a visitor who never needs
6
+ * them never downloads them (BACKLOG D444).
7
+ */
8
+ import { SDK_VERSION } from './config';
9
+
10
+ export const SDK_HOST = 'https://sdk.joryio.com';
11
+
12
+ /** A core bundle's own file name: what a script tag loads (sdk.joryio.com, the npm package's dist/). */
13
+ const CORE_FILE = /\/joryio(?:\.umd)?(?:\.min)?\.js$/;
14
+
15
+ /**
16
+ * The folder the running core was loaded from (with a trailing slash), when
17
+ * it was loaded by a script tag as `joryio.min.js` over https - for example
18
+ * `https://sdk.joryio.com/web/1.4.0-beta.4/`. Null when bundled into the
19
+ * site's own code (the script is then the site's file), or not over https.
20
+ */
21
+ export function coreFolderOf(src: string | null | undefined): string | null {
22
+ if (!src || typeof src !== 'string') return null;
23
+ let u: URL;
24
+ try {
25
+ u = new URL(src);
26
+ } catch {
27
+ return null;
28
+ }
29
+ if (u.protocol !== 'https:' || !CORE_FILE.test(u.pathname)) return null;
30
+ return `${u.origin}${u.pathname.replace(/[^/]*$/, '')}`;
31
+ }
32
+
33
+ /**
34
+ * Read while this module is evaluated, i.e. while the core's script runs:
35
+ * `document.currentScript` is null afterwards (and for a module script),
36
+ * then the last `<script src=".../joryio.min.js">` on the page is used.
37
+ */
38
+ function readOwnFolder(): string | null {
39
+ if (typeof document === 'undefined') return null;
40
+ try {
41
+ const current = document.currentScript as HTMLScriptElement | null;
42
+ const fromCurrent = coreFolderOf(current && current.src);
43
+ if (fromCurrent || (current && current.src)) return fromCurrent;
44
+ const tags = document.querySelectorAll('script[src]');
45
+ for (let i = tags.length - 1; i >= 0; i--) {
46
+ const folder = coreFolderOf((tags[i] as HTMLScriptElement).src);
47
+ if (folder) return folder;
48
+ }
49
+ } catch {
50
+ /* no DOM access */
51
+ }
52
+ return null;
53
+ }
54
+ const OWN_FOLDER = readOwnFolder();
55
+
56
+ /**
57
+ * Where a lazily loaded file comes from, in order:
58
+ * 1. the folder the core itself was loaded from (`coreFolderOf`), so a core
59
+ * from `sdk.joryio.com/web/1.4.0-beta.4/` (a beta, whose SDK_VERSION
60
+ * still says 1.4.0) or from the npm package's `dist/` on a CDN loads the
61
+ * side files of the same build - unless that folder is the major channel
62
+ * `sdk.joryio.com/web/<major>/`, which moves: then 2 goes first;
63
+ * 2. the exact SDK version's folder on the SDK host (immutable, the same
64
+ * build as this core);
65
+ * 3. the major channel, as a fallback (a version not on the CDN, such as a
66
+ * local build).
67
+ * An init option (`editorScriptUrl`, `cardsUiScriptUrl`) replaces all of
68
+ * them, for a self-hosted SDK.
69
+ */
70
+ export function sdkHostFileUrls(file: string, override?: string, ownFolder: string | null = OWN_FOLDER): string[] {
71
+ if (override) return [override];
72
+ const major = SDK_VERSION.split('.')[0];
73
+ const exact = `${SDK_HOST}/web/${SDK_VERSION}/${file}`;
74
+ const channel = `${SDK_HOST}/web/${major}/${file}`;
75
+ const urls = ownFolder && ownFolder !== `${SDK_HOST}/web/${major}/` ? [`${ownFolder}${file}`, exact, channel] : [exact, channel];
76
+ return urls.filter((u, i) => urls.indexOf(u) === i);
77
+ }
78
+
79
+ /** Inject one script tag; resolves when it ran (onload), rejects on an error (a 404, a blocking CSP). */
80
+ export function loadSdkScript(src: string, marker: string): Promise<void> {
81
+ return new Promise((resolve, reject) => {
82
+ const s = document.createElement('script');
83
+ s.src = src;
84
+ s.async = true;
85
+ s.setAttribute(marker, 'bundle');
86
+ s.onload = () => resolve();
87
+ s.onerror = () => {
88
+ s.remove();
89
+ reject(new Error(`could not load ${src}`));
90
+ };
91
+ (document.head || document.documentElement).appendChild(s);
92
+ });
93
+ }
package/src/core/sdk.ts CHANGED
@@ -3,6 +3,9 @@
3
3
  * Main SDK class
4
4
  */
5
5
 
6
+ import { PageEditManager } from './page-edits';
7
+ import { EditorGate, editorRequested } from './editor-gate';
8
+ import { PageContextTracker } from './page-context';
6
9
  import { InitConfig, ResolvedConfig, resolveConfig, SDK_VERSION } from './config';
7
10
  import { StorageManager } from './storage';
8
11
  import { SessionManager, SESSION_ID_KEY } from './session';
@@ -18,6 +21,10 @@ import {
18
21
  } from './network';
19
22
  import { UTMManager } from './utm';
20
23
  import { InAppMessagingManager, InAppCampaign } from './inapp';
24
+ import { PlacementManager, Placement, PlacementHandle, InsertPlacementOptions, PlacementsUpdatedCallback, PlacementConsent } from './placements';
25
+ import { CardManager, Card, CardFeed, CardFeedHandle, CardsUpdatedCallback, GetCardsOptions, MountCardFeedOptions } from './cards';
26
+ import { LinkRouter, JoryioLinkHandler } from './links';
27
+ import { FlagsManager, FlagsUpdatedCallback } from './flags';
21
28
  import { User } from './user';
22
29
  import { Logger } from '../utils/logger';
23
30
  import { getDeviceProperties } from './device';
@@ -254,6 +261,17 @@ export class JoryioSDK {
254
261
  private network!: NetworkClient;
255
262
  private utm!: UTMManager;
256
263
  private inapp!: InAppMessagingManager;
264
+ /** Placements: spots inside the page filled per visitor (placements.ts). */
265
+ private placements!: PlacementManager;
266
+ /** Content cards: the person's feed (cards.ts). */
267
+ private cards!: CardManager;
268
+ // Created with the instance, so setLinkHandler works before init().
269
+ private links = new LinkRouter((error) => this.logger?.error('Your link handler threw; the link opens as without one:', error));
270
+ private pageContext!: PageContextTracker;
271
+ private pageEdits!: PageEditManager;
272
+ private editor: EditorGate | null = null;
273
+ /** Feature flags + remote config (flags.ts). */
274
+ private flags!: FlagsManager;
257
275
  private _user!: User;
258
276
  private _push!: PushManager;
259
277
  private _ecommerce: EcommerceTracker | null = null;
@@ -531,6 +549,86 @@ export class JoryioSDK {
531
549
  // false, so every HTML campaign is refused with no way to opt in.
532
550
  this.inapp.setAllowHtmlJsInAppMessages(this.config.inApp.allowHtmlJsInAppMessages);
533
551
 
552
+ // Page context (D444 Phase 4): one tracker for overlays, placements and page edits.
553
+ this.pageContext = new PageContextTracker(this.config.pageContext);
554
+ // UTM page rules (D444 Phase 4 follow-up): the UTM this SDK already recorded, when capture is on.
555
+ this.pageContext.setUtmSource(() => (this.config.captureUTM && this.utm ? this.utm.getUTMData() : null));
556
+ this.inapp.setPageContext(this.pageContext);
557
+
558
+ this.placements = new PlacementManager(
559
+ this.config.apiEndpoint,
560
+ this.config.sdkKey,
561
+ this.identity,
562
+ this.session,
563
+ this.logger,
564
+ {
565
+ consent: () => this.placementConsent(),
566
+ allowHtml: () => this.config.inApp.allowHtmlJsInAppMessages,
567
+ requestTimeoutMs: this.config.requestTimeout,
568
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
569
+ bridge: {
570
+ logCustomEvent: (name, properties) => this.track(name, properties),
571
+ setCustomUserAttribute: (key, value) => this.setAttribute(key, value),
572
+ changeUser: (userId) => this.identify(userId),
573
+ requestPushPermission: () => {
574
+ this._push.subscribe().catch((error) => this.logger.warn('Push subscribe failed:', error));
575
+ },
576
+ },
577
+ },
578
+ this.network,
579
+ );
580
+ this.placements.setPageContext(this.pageContext);
581
+
582
+ // Page edits (D444 Phase 4): selector edits from page-edit campaigns.
583
+ this.pageEdits = new PageEditManager(
584
+ this.config.apiEndpoint,
585
+ this.config.sdkKey,
586
+ this.identity,
587
+ this.session,
588
+ this.logger,
589
+ {
590
+ consent: () => this.placementConsent(),
591
+ requestTimeoutMs: this.config.requestTimeout,
592
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
593
+ },
594
+ this.network,
595
+ );
596
+ this.pageEdits.setPageContext(this.pageContext);
597
+
598
+ this.cards = new CardManager(
599
+ this.config.apiEndpoint,
600
+ this.config.sdkKey,
601
+ this.identity,
602
+ this.session,
603
+ this.logger,
604
+ {
605
+ consent: () => this.placementConsent(),
606
+ requestTimeoutMs: this.config.requestTimeout,
607
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
608
+ cardsUiScriptUrl: this.config.cardsUiScriptUrl,
609
+ },
610
+ this.network,
611
+ );
612
+
613
+ // One link router for every surface that opens a link (setLinkHandler).
614
+ this.inapp.links = this.links;
615
+ this.placements.links = this.links;
616
+ this.cards.links = this.links;
617
+
618
+ this.flags = new FlagsManager(
619
+ this.config.apiEndpoint,
620
+ this.config.sdkKey,
621
+ this.identity,
622
+ this.session,
623
+ this.logger,
624
+ {
625
+ canSend: () => this.isInitialized && !this.disabled && !this.network.isSuspended() && this.canSend(),
626
+ requestTimeoutMs: this.config.requestTimeout,
627
+ noteStatus: (status, data) => this.network.noteSuspended(status, data),
628
+ },
629
+ this.network,
630
+ );
631
+
534
632
  // Initialize user object for subscription management
535
633
  this._user = new User(
536
634
  this.logger,
@@ -645,6 +743,26 @@ export class JoryioSDK {
645
743
  if (!this.disabled) JoryioSDK.instance = this;
646
744
  this.logger.info('SDK initialized successfully');
647
745
 
746
+ // <div data-joryio-placement="key"> elements, now and as the page changes.
747
+ if (!this.disabled && this.config.inApp.autoMountPlacements) this.placements.autoMount();
748
+ // Route changes, scroll depth, time on page, exit intent (D444 Phase 4).
749
+ if (!this.disabled) this.pageContext.start();
750
+ // `pageEdits: false` (init): no page edit, no anti-flicker, no editor - whatever the server says.
751
+ if (!this.disabled && this.config.pageEdits) {
752
+ if (editorRequested()) {
753
+ // The dashboard's point-and-click editor opened this tab: the page as
754
+ // the site draws it (no page edits), and the picker once the token is
755
+ // vouched for - only then is the editor's own file loaded. Nothing
756
+ // happens for a tab that was not opened that way.
757
+ this.editor = new EditorGate(this.config.apiEndpoint, this.config.sdkKey, this.logger, { scriptUrl: this.config.editorScriptUrl });
758
+ this.editor.start();
759
+ } else {
760
+ this.pageEdits.start();
761
+ }
762
+ }
763
+ // Flags: the stored answer is readable at once; refresh it now and when the page is shown again.
764
+ if (!this.disabled) this.flags.start();
765
+
648
766
  // Report permission state now the SDK is live - only when this site uses
649
767
  // web push (see pushPermissionReported), and only on a change.
650
768
  this.reportPushPermissionIfChanged();
@@ -958,6 +1076,11 @@ export class JoryioSDK {
958
1076
  this.pinAnonymousWrites();
959
1077
  this.network.switchUser(userId);
960
1078
  this.identity.adopt(anonymousId, userId);
1079
+ this.placements.invalidate();
1080
+ // Another person: the anonymous visitor's card state goes too.
1081
+ this.cards.invalidate(true);
1082
+ this.pageEdits?.invalidate();
1083
+ this.flags.onIdentityChanged();
961
1084
  // Whoever was kept for withdrawals here belongs to the old identity.
962
1085
  this.withdrawalUserId = null;
963
1086
  if (loggedOut) {
@@ -1345,6 +1468,15 @@ export class JoryioSDK {
1345
1468
  if (wasOptedOut !== this.isOptedOut || wasPending !== this.consentPending) {
1346
1469
  // In-app answers requested under the previous state are stale.
1347
1470
  this.inapp.invalidate();
1471
+ // Placement answers too: a grant turns generic answers personal, a
1472
+ // refusal turns personal answers generic.
1473
+ this.placements?.invalidate();
1474
+ // The card feed is asked for only with consent: a grant fetches it, a refusal empties it.
1475
+ this.cards?.invalidate(false);
1476
+ // Consent changed: the stored site settings go too (as every per-workspace store).
1477
+ this.pageEdits?.invalidate({ siteSettings: true });
1478
+ // Flags too: without consent nothing is read or sent; a grant fetches.
1479
+ this.flags?.onIdentityChanged();
1348
1480
  }
1349
1481
 
1350
1482
  if (this.isOptedOut) {
@@ -1738,6 +1870,7 @@ export class JoryioSDK {
1738
1870
  if (this.canSend()) {
1739
1871
  try {
1740
1872
  this.inapp?.onEventTracked(eventName, eventProperties);
1873
+ this.placements?.onEventTracked(eventName, eventProperties);
1741
1874
  } catch (error) {
1742
1875
  this.logger.error('In-app trigger evaluation failed:', error);
1743
1876
  }
@@ -1814,7 +1947,13 @@ export class JoryioSDK {
1814
1947
  // set is B's own. Also keeps the user id for auth-failure reporting.
1815
1948
  this.network.switchUser(userId);
1816
1949
  // In-app answers requested for the previous identity are stale.
1817
- if (previousUserId !== userId) this.inapp.invalidate();
1950
+ if (previousUserId !== userId) {
1951
+ this.inapp.invalidate();
1952
+ this.placements.invalidate();
1953
+ this.cards.invalidate(true);
1954
+ this.pageEdits?.invalidate();
1955
+ this.flags.onIdentityChanged();
1956
+ }
1818
1957
 
1819
1958
  if (!this.canSend()) return; // consent pending: sent when granted
1820
1959
 
@@ -2375,7 +2514,12 @@ export class JoryioSDK {
2375
2514
  // New anonymous id, no user id.
2376
2515
  this.pinAnonymousWrites();
2377
2516
  this.identity.reset(anonymousId);
2517
+ this.flags.onIdentityChanged();
2378
2518
  this.network.setCurrentUserId(this.identity.getUserId());
2519
+ this.placements.invalidate();
2520
+ this.cards.invalidate(true);
2521
+ // reset / resetTo: the stored site settings go too (identify keeps them - the same for every visitor).
2522
+ this.pageEdits?.invalidate({ siteSettings: true });
2379
2523
 
2380
2524
  // UTM before the session: the new session's Session Start (tracked by the
2381
2525
  // session's onNewSession hook) must not carry the outgoing user's campaign.
@@ -2482,7 +2626,11 @@ export class JoryioSDK {
2482
2626
  this.forgetDeferredIdentify();
2483
2627
  this.pinAnonymousWrites();
2484
2628
  this.identity.reset();
2629
+ this.flags.onIdentityChanged();
2485
2630
  this.network.setCurrentUserId(null);
2631
+ this.placements.invalidate();
2632
+ this.cards?.invalidate(true);
2633
+ this.pageEdits?.invalidate({ siteSettings: true });
2486
2634
  this.utm.reset();
2487
2635
  this.session.clear();
2488
2636
  this.lastTrackedUrl = null;
@@ -3249,6 +3397,229 @@ export class JoryioSDK {
3249
3397
  }
3250
3398
  }
3251
3399
 
3400
+ /**
3401
+ * What a placement request may carry (docs/PLACEMENTS_PLAN.md 3.9): null =
3402
+ * nothing may be sent at all; `granted` = the visitor is named and their
3403
+ * interactions reported; `pending` / `denied` (opted out and Do Not Track
3404
+ * included) = an anonymous request for generic content, nothing reported.
3405
+ */
3406
+ private placementConsent(): PlacementConsent | null {
3407
+ if (!this.isInitialized || this.disabled || this.network.isSuspended()) return null;
3408
+ if (this.canSend()) return 'granted';
3409
+ return this.consentPending ? 'pending' : 'denied';
3410
+ }
3411
+
3412
+ /**
3413
+ * Receive EVERY link the SDK is about to open - an in-app message button or
3414
+ * link, a placement button, a card click - before it opens: http(s) links
3415
+ * and app deep links (`myapp://cart`) alike, with where it came from
3416
+ * (`link.source`: in_app, placement, card) and the ids that go with it.
3417
+ * Return true to take the link over - route it with your single-page app's
3418
+ * router instead of a new tab - or false to let the SDK open it as it does
3419
+ * without a handler. A refused scheme (javascript:, data:, ...) never
3420
+ * reaches it. Synchronous on purpose: the click's user activation still
3421
+ * holds when the SDK opens a tab. Works before init(). Same name on iOS,
3422
+ * Android, React Native and Unity (`SetLinkHandler`).
3423
+ */
3424
+ setLinkHandler(handler: JoryioLinkHandler): void {
3425
+ if (typeof handler !== 'function') {
3426
+ this.logger?.warn('setLinkHandler() needs a function; use clearLinkHandler() to remove one');
3427
+ return;
3428
+ }
3429
+ this.links.setHandler(handler);
3430
+ }
3431
+
3432
+ /** Remove the handler set with setLinkHandler: links open as they do without one. */
3433
+ clearLinkHandler(): void {
3434
+ this.links.setHandler(null);
3435
+ }
3436
+
3437
+ /**
3438
+ * Draw placement `placementKey` into `element` (docs: Placements). The SDK
3439
+ * fetches, caches and refreshes it, measures viewability and reports
3440
+ * impressions, clicks and dismissals. Returns a handle whose `remove()`
3441
+ * stops it; null for an invalid key or element.
3442
+ */
3443
+ /**
3444
+ * The page's own variables for page targeting (D444 Phase 4), e.g.
3445
+ * `{ pageType: 'product', category: 'shoes' }`. Replaces what was set
3446
+ * before; `null` clears it. Primitives only, at most 20. Call it on every
3447
+ * page (and after each route change in a single-page app). Safe before
3448
+ * init.
3449
+ */
3450
+ setPageVariables(variables: Record<string, string | number | boolean> | null): void {
3451
+ try {
3452
+ this.pageContext?.setPageVariables(variables);
3453
+ } catch (error) {
3454
+ this.logger.warn('setPageVariables failed:', error);
3455
+ }
3456
+ }
3457
+
3458
+ insertPlacement(placementKey: string, element: HTMLElement, options?: InsertPlacementOptions): PlacementHandle | null {
3459
+ if (!this.isInitialized) {
3460
+ this.logger.error('SDK not initialized');
3461
+ return null;
3462
+ }
3463
+ return this.placements.insertPlacement(placementKey, element, options);
3464
+ }
3465
+
3466
+ /**
3467
+ * The placements for `placementKeys`, to draw with your own UI. Report what
3468
+ * the person did with `item.markDisplayed()` (once it was viewable),
3469
+ * `item.markClicked()` and `item.markDismissed()`; for a held-out visitor
3470
+ * (`isControl`), `placement.markDisplayed()` when the empty spot was viewable.
3471
+ */
3472
+ async getPlacements(placementKeys: string[]): Promise<Record<string, Placement>> {
3473
+ if (!this.isInitialized) {
3474
+ this.logger.error('SDK not initialized');
3475
+ return {};
3476
+ }
3477
+ return this.placements.getPlacements(placementKeys);
3478
+ }
3479
+
3480
+ /** Ask the server again (default: every placement on the page). At most once per key per PLACEMENT_MIN_REFRESH_SECONDS. */
3481
+ async refreshPlacements(placementKeys?: string[]): Promise<void> {
3482
+ if (!this.isInitialized) return;
3483
+ await this.placements.refreshPlacements(placementKeys);
3484
+ }
3485
+
3486
+ /** Called with the placements whose content changed. Returns an unsubscribe function. */
3487
+ onPlacementsUpdated(callback: PlacementsUpdatedCallback): () => void {
3488
+ if (!this.isInitialized) {
3489
+ this.logger.error('SDK not initialized');
3490
+ return () => undefined;
3491
+ }
3492
+ return this.placements.onPlacementsUpdated(callback);
3493
+ }
3494
+
3495
+ /**
3496
+ * The person's content cards (docs: Content cards): from the cache while it
3497
+ * is fresh (CARD_FEED_TTL_SECONDS), from the server otherwise. With
3498
+ * `{ cursor: feed.nextCursor }`, the next page - added to the cached feed.
3499
+ * Without tracking consent the feed is empty and nothing is asked.
3500
+ */
3501
+ async getCards(options?: GetCardsOptions): Promise<CardFeed> {
3502
+ if (!this.isInitialized) {
3503
+ this.logger.error('SDK not initialized');
3504
+ return { cards: [], unreadCount: 0, nextCursor: null, stateScope: 'server' };
3505
+ }
3506
+ return this.cards.getCards(options);
3507
+ }
3508
+
3509
+ /** Unread cards in the cached feed (the badge). Never goes to the network. */
3510
+ getUnreadCardCount(): number {
3511
+ if (!this.isInitialized) return 0;
3512
+ return this.cards.getUnreadCardCount();
3513
+ }
3514
+
3515
+ /** Report that a card (or card id) was on screen - the feed drawn by mountCardFeed does this itself. */
3516
+ markCardViewed(card: Card | string): void {
3517
+ if (!this.isInitialized) return;
3518
+ this.cards.markCardViewed(card);
3519
+ }
3520
+
3521
+ /** Mark a card read: the unread count drops at once. A card already read sends nothing. */
3522
+ markCardRead(card: Card | string): void {
3523
+ if (!this.isInitialized) return;
3524
+ this.cards.markCardRead(card);
3525
+ }
3526
+
3527
+ /** Report a tap on a card (it counts as read too). Open `card.url` yourself when you draw the feed. */
3528
+ markCardClicked(card: Card | string): void {
3529
+ if (!this.isInitialized) return;
3530
+ this.cards.markCardClicked(card);
3531
+ }
3532
+
3533
+ /** Dismiss a card: it leaves the feed at once, on every device for a known person. */
3534
+ dismissCard(card: Card | string): void {
3535
+ if (!this.isInitialized) return;
3536
+ this.cards.dismissCard(card);
3537
+ }
3538
+
3539
+ /** Ask the server for the feed again. At most once per CARD_MIN_REFRESH_SECONDS; extra calls coalesce. */
3540
+ async refreshCards(): Promise<void> {
3541
+ if (!this.isInitialized) return;
3542
+ await this.cards.refreshCards();
3543
+ }
3544
+
3545
+ /** Called with the whole feed whenever it changes. Returns an unsubscribe function. */
3546
+ onCardsUpdated(callback: CardsUpdatedCallback): () => void {
3547
+ if (!this.isInitialized) {
3548
+ this.logger.error('SDK not initialized');
3549
+ return () => undefined;
3550
+ }
3551
+ return this.cards.onCardsUpdated(callback);
3552
+ }
3553
+
3554
+ /**
3555
+ * Draw the person's card feed into `element` and keep it up to date. Cards
3556
+ * are reported viewed and read once half of one was on screen for a second,
3557
+ * clicked on a tap (then its http(s) link opens, or a deep link goes to
3558
+ * `onDeepLink`), dismissed on its x. Returns a handle whose `remove()` stops it.
3559
+ * The drawing code is `joryio-cards-ui.min.js`, loaded from the SDK host the
3560
+ * first time a feed is mounted (`cardsUiScriptUrl` to self-host): the handle
3561
+ * comes back at once and the feed appears when the file has loaded. If it
3562
+ * cannot load, a warning is logged and the element gets
3563
+ * `data-joryio-card-feed-state="unavailable"`; the data API keeps working.
3564
+ */
3565
+ mountCardFeed(element: HTMLElement, options?: MountCardFeedOptions): CardFeedHandle | null {
3566
+ if (!this.isInitialized) {
3567
+ this.logger.error('SDK not initialized');
3568
+ return null;
3569
+ }
3570
+ return this.cards.mountCardFeed(element, options);
3571
+ }
3572
+
3573
+ /**
3574
+ * A flag's value for this visitor, or `defaultValue` before the first answer,
3575
+ * for a flag the server did not send, or without tracking consent. Never
3576
+ * waits for the network. The first read in a session logs an exposure.
3577
+ */
3578
+ getFlag<T = unknown>(key: string, defaultValue: T): T {
3579
+ if (!this.isInitialized) return defaultValue;
3580
+ return this.flags.getFlag(key, defaultValue);
3581
+ }
3582
+
3583
+ /** A boolean flag, or `defaultValue` (also for a flag of another type). */
3584
+ getBoolFlag(key: string, defaultValue: boolean): boolean {
3585
+ return this.isInitialized ? this.flags.getBoolFlag(key, defaultValue) : defaultValue;
3586
+ }
3587
+
3588
+ /** A string flag, or `defaultValue`. */
3589
+ getStringFlag(key: string, defaultValue: string): string {
3590
+ return this.isInitialized ? this.flags.getStringFlag(key, defaultValue) : defaultValue;
3591
+ }
3592
+
3593
+ /** A number flag, or `defaultValue`. */
3594
+ getNumberFlag(key: string, defaultValue: number): number {
3595
+ return this.isInitialized ? this.flags.getNumberFlag(key, defaultValue) : defaultValue;
3596
+ }
3597
+
3598
+ /** A JSON flag (object, array or scalar), or `defaultValue`. */
3599
+ getJsonFlag<T = unknown>(key: string, defaultValue: T): T {
3600
+ return this.isInitialized ? this.flags.getJsonFlag(key, defaultValue) : defaultValue;
3601
+ }
3602
+
3603
+ /** Every flag held for this visitor, key -> value. Logs no exposure. */
3604
+ getAllFlags(): Record<string, unknown> {
3605
+ return this.isInitialized ? this.flags.getAllFlags() : {};
3606
+ }
3607
+
3608
+ /** Fetch the flags now. */
3609
+ async refreshFlags(): Promise<void> {
3610
+ if (!this.isInitialized) return;
3611
+ await this.flags.refreshFlags();
3612
+ }
3613
+
3614
+ /** Called with the keys whose value changed. Returns an unsubscribe function. */
3615
+ onFlagsUpdated(callback: FlagsUpdatedCallback): () => void {
3616
+ if (!this.isInitialized) {
3617
+ this.logger.error('SDK not initialized');
3618
+ return () => undefined;
3619
+ }
3620
+ return this.flags.onFlagsUpdated(callback);
3621
+ }
3622
+
3252
3623
  /**
3253
3624
  * Destroy the SDK instance
3254
3625
  */
@@ -3310,6 +3681,12 @@ export class JoryioSDK {
3310
3681
  // Clear in-app messaging (every timer included)
3311
3682
  this.inapp.clearAll();
3312
3683
  this.inapp.destroy();
3684
+ this.placements.destroy();
3685
+ this.cards.destroy();
3686
+ this.pageEdits?.destroy();
3687
+ this.editor?.stop();
3688
+ this.pageContext?.destroy();
3689
+ this.flags.destroy();
3313
3690
 
3314
3691
  this.isInitialized = false;
3315
3692
  if (JoryioSDK.instance === this) JoryioSDK.instance = null;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The visual editor bundle - `joryio-editor.min.js` on the SDK host, next to
3
+ * `joryio.min.js` (BACKLOG D444 Phase 4 follow-up).
4
+ *
5
+ * Loaded by the core's EditorGate (src/core/editor-gate.ts) only in a tab the
6
+ * Joryio dashboard opened for the point-and-click editor, and only after the
7
+ * server vouched for the editor token. It registers one global and does
8
+ * nothing else on its own: no request, no listener, until the gate calls
9
+ * `start` with the verified dashboard origin.
10
+ */
11
+ import { VisualEditor } from './visual-editor';
12
+ import { EDITOR_API_VERSION, EDITOR_GLOBAL, type EditorBundleApi } from '../core/editor-gate';
13
+
14
+ const api: EditorBundleApi = {
15
+ version: EDITOR_API_VERSION,
16
+ start({ dashboardOrigin, opener, logger, onStop }) {
17
+ const editor = new VisualEditor(dashboardOrigin, opener, logger, onStop);
18
+ editor.start();
19
+ return { stop: () => editor.stop() };
20
+ },
21
+ };
22
+
23
+ if (typeof window !== 'undefined' && !(window as any)[EDITOR_GLOBAL]) {
24
+ (window as any)[EDITOR_GLOBAL] = api;
25
+ }
26
+
27
+ export { api as editorApi };