@joryio/react-native-sdk 1.4.0-beta.2 → 1.4.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,7 +1,19 @@
1
1
  import { NativeModules, NativeEventEmitter, Platform } from 'react-native';
2
+ import * as ReactNative from 'react-native';
3
+ import * as React from 'react';
2
4
 
3
5
  const { JoryioModule } = NativeModules;
4
6
 
7
+ /**
8
+ * This package's version - the same number every Joryio SDK carries
9
+ * (sdk-version-parity.spec.ts pins it; the release tooling rewrites it).
10
+ * Handed to the native SDK at initialize() as `sdkWrapperVersion`, which
11
+ * sends it on every request as `X-Joryio-SDK-Wrapper-Version` next to
12
+ * `X-Joryio-SDK-Wrapper: react-native` (D427), so the dashboard shows the
13
+ * version of THIS package, the one the app upgrades.
14
+ */
15
+ export const SDK_VERSION = '1.4.0';
16
+
5
17
  /**
6
18
  * Mirrors the backend's SUBSCRIPTION_CHANNELS and the web SDK. Five, including
7
19
  * viber - it was added to the backend and to no SDK.
@@ -138,6 +150,19 @@ export interface JoryioConfig {
138
150
  */
139
151
  holdInAppMessagesForHandler?: boolean;
140
152
 
153
+ /**
154
+ * iOS only (default false): an https link from Joryio content - an in-app
155
+ * message, a placement, a card, a push - whose host is one of your app's
156
+ * associated domains (`applinks:` entries, `*.shop.com` included) goes to
157
+ * your app's own universal-link handling (`scene(_:continue:)` /
158
+ * `application(_:continue:restorationHandler:)`) instead of Safari. With
159
+ * React Native that usually means the `Linking` 'url' event. Ignored on
160
+ * Android, which routes verified App Links to the app itself. A handler set
161
+ * with {@link JoryioSDK.setLinkHandler} runs first. Same option on iOS
162
+ * (`JoryioConfig.forwardUniversalLinks`) and Unity.
163
+ */
164
+ forwardUniversalLinks?: boolean;
165
+
141
166
  /**
142
167
  * Tracking consent at start-up. Same option and values as the web, iOS,
143
168
  * Android and Unity SDKs.
@@ -545,6 +570,13 @@ function finiteProperties(caller: string, properties: Record<string, unknown>):
545
570
  * expect - was a fatal JS error in a release build and skipped every other
546
571
  * listener of the same event. A returned promise that rejects is caught too.
547
572
  */
573
+ /** A flag key must be a non-empty string; otherwise the getter answers its default. */
574
+ function flagKeyOk(method: string, key: unknown): key is string {
575
+ if (typeof key === 'string' && key.length > 0) return true;
576
+ warn(`${method}() needs a flag key; the default is returned.`);
577
+ return false;
578
+ }
579
+
548
580
  function guardedCallback<T>(name: string, callback: (event: T) => unknown): (event: T) => void {
549
581
  const report = (err: unknown) => {
550
582
  // eslint-disable-next-line no-console
@@ -604,6 +636,427 @@ export const MAX_PRE_INIT_CALLS = 1000;
604
636
  */
605
637
  export const IN_APP_DISPLAY_DWELL_MS = 1000;
606
638
 
639
+ // ── Placements (docs/PLACEMENTS_PLAN.md, D444) ──────────────────────────────
640
+
641
+ /** Share of an item that must be on screen for it to count as seen - the same on every Joryio SDK. */
642
+ export const PLACEMENT_VIEWABLE_FRACTION = 0.5;
643
+ /** A placement key is fetched from the network at most once per this many seconds - the same on every Joryio SDK. */
644
+ export const PLACEMENT_MIN_REFRESH_SECONDS = 30;
645
+
646
+ /**
647
+ * A drawn product card's tap is reported as `clicked` with the elementId
648
+ * `product:<product id>` (at most 128 characters) - the same on every Joryio SDK.
649
+ */
650
+ export const PLACEMENT_PRODUCT_ELEMENT_PREFIX = 'product:';
651
+ /** Width of a drawn product card when the app does not set one (dp / points) - the same on every Joryio SDK. */
652
+ export const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
653
+ /** The elementId a product card's click is reported with - use it with `markClicked` when you draw the cards yourself. */
654
+ export function placementProductElementId(productId: string): string {
655
+ return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
656
+ }
657
+
658
+ export type PlacementEmptyBehavior = 'collapse' | 'keep_space';
659
+
660
+ export interface PlacementContent {
661
+ kind: 'native' | 'html';
662
+ title?: string;
663
+ body?: string;
664
+ imageUrl?: string;
665
+ buttons?: Array<{ id: string; text: string; action: string; url?: string }>;
666
+ closeButton?: boolean;
667
+ html?: string;
668
+ css?: string;
669
+ }
670
+
671
+ /** A product card of a recommendation placement item (D444 Phase 2b). Same names on all five SDKs. */
672
+ export interface PlacementProduct {
673
+ id: string;
674
+ title: string | null;
675
+ price: string | null;
676
+ compareAtPrice: string | null;
677
+ discountPercent: number | null;
678
+ imageUrl: string | null;
679
+ url: string | null;
680
+ }
681
+
682
+ /** An item to draw, with the calls that report what the person did with it. */
683
+ export interface PlacementItem {
684
+ id: string;
685
+ variantId?: string | null;
686
+ kind: 'native' | 'html' | 'data';
687
+ data: Record<string, string | number | boolean | null>;
688
+ content?: PlacementContent | null;
689
+ /** Products picked for the person by a recommendation model; [] when the item has none. Draw them as cards. */
690
+ products: PlacementProduct[];
691
+ /** A viewable impression (your UI drew it): once at least half of it was on screen for IN_APP_DISPLAY_DWELL_MS. */
692
+ markDisplayed(): void;
693
+ markClicked(elementId?: string): void;
694
+ markDismissed(): void;
695
+ }
696
+
697
+ export interface Placement {
698
+ placementKey: string;
699
+ items: PlacementItem[];
700
+ isControl: boolean;
701
+ emptyBehavior: PlacementEmptyBehavior;
702
+ maxItems: number;
703
+ ttlSeconds: number;
704
+ /** For a held-out person (`isControl`): the empty spot was on screen. */
705
+ markDisplayed(): void;
706
+ }
707
+
708
+ /** The bridge's product cards, defensively typed: an entry without an id is dropped. */
709
+ function toProducts(raw: unknown): PlacementProduct[] {
710
+ if (!Array.isArray(raw)) return [];
711
+ const str = (v: unknown) => (typeof v === 'string' ? v : null);
712
+ return raw
713
+ .filter((p: any) => p && typeof p === 'object' && (typeof p.id === 'string' || typeof p.id === 'number'))
714
+ .map((p: any) => ({
715
+ id: String(p.id),
716
+ title: str(p.title),
717
+ price: str(p.price),
718
+ compareAtPrice: str(p.compareAtPrice),
719
+ discountPercent: typeof p.discountPercent === 'number' ? p.discountPercent : null,
720
+ imageUrl: str(p.imageUrl),
721
+ url: str(p.url),
722
+ }));
723
+ }
724
+
725
+ /** Native JSON (Placement.toJson on iOS / Android) -> objects whose mark* calls go back to native. */
726
+ function toPlacements(json: unknown): Record<string, Placement> {
727
+ let raw: Record<string, any> = {};
728
+ try {
729
+ raw = typeof json === 'string' ? JSON.parse(json) : (json as Record<string, any>) || {};
730
+ } catch {
731
+ raw = {};
732
+ }
733
+ const mark = (key: string, itemId: string | null, action: string, elementId?: string) => {
734
+ JoryioModule?.markPlacement?.(key, itemId, action, elementId ?? null);
735
+ };
736
+ const out: Record<string, Placement> = {};
737
+ for (const [key, p] of Object.entries(raw || {})) {
738
+ if (!p || typeof p !== 'object') continue;
739
+ out[key] = {
740
+ placementKey: p.placementKey || key,
741
+ isControl: p.isControl === true,
742
+ emptyBehavior: p.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse',
743
+ maxItems: typeof p.maxItems === 'number' ? p.maxItems : 1,
744
+ ttlSeconds: typeof p.ttlSeconds === 'number' ? p.ttlSeconds : 300,
745
+ items: (Array.isArray(p.items) ? p.items : []).map((i: any) => ({
746
+ id: String(i.id),
747
+ variantId: i.variantId ?? null,
748
+ kind: i.kind,
749
+ data: i.data || {},
750
+ content: i.content ?? null,
751
+ products: toProducts(i.products),
752
+ markDisplayed: () => mark(key, String(i.id), 'displayed'),
753
+ markClicked: (elementId?: string) => mark(key, String(i.id), 'clicked', elementId),
754
+ markDismissed: () => mark(key, String(i.id), 'dismissed'),
755
+ })),
756
+ markDisplayed: () => mark(key, null, 'control'),
757
+ };
758
+ }
759
+ return out;
760
+ }
761
+
762
+ export interface JoryioPlacementProps {
763
+ placementKey: string;
764
+ style?: unknown;
765
+ /** After each draw: what was drawn and its height (0 when collapsed). */
766
+ onRender?: (info: { placementKey: string; itemCount: number; isControl: boolean; emptyBehavior: PlacementEmptyBehavior; height: number }) => void;
767
+ /**
768
+ * A `deep_link` button with an app link (`myapp://cart`) was tapped: route
769
+ * it. An http(s) link is opened by the native SDK instead, and any other
770
+ * scheme (javascript:, data:, intent:, ...) is refused - see isAppDeepLink.
771
+ * A handler set with setLinkHandler sees every link first; this one is
772
+ * called when it declines.
773
+ */
774
+ onDeepLink?: (url: string) => void;
775
+ /**
776
+ * Draw an item's recommended products as a horizontal row of product cards
777
+ * (image, title, price, optional button) - the native view does it. Default true.
778
+ */
779
+ showProducts?: boolean;
780
+ /** Label of a button on every product card; unset = no button (the whole card opens the product). */
781
+ productButtonText?: string;
782
+ /** Width of one product card in dp / points (default PLACEMENT_PRODUCT_CARD_WIDTH). */
783
+ productCardWidth?: number;
784
+ }
785
+
786
+ /** Schemes never opened nor handed to the app, whatever a link says (the backend's placement / card link rule). */
787
+ const REFUSED_LINK_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'blob', 'about', 'content', 'intent'];
788
+
789
+ /**
790
+ * An app deep link (`myapp://cart`) that may go to the app's own handler: a
791
+ * `scheme://` link whose scheme is not http(s) and not a refused one. The
792
+ * native PlacementView applies the same rule before a link reaches JS; this
793
+ * layer checks again. The same rule on every Joryio SDK.
794
+ */
795
+ export function isAppDeepLink(url: unknown): boolean {
796
+ if (typeof url !== 'string') return false;
797
+ const m = /^([a-z][a-z0-9+.-]*):\/\/./i.exec(url.trim());
798
+ if (!m) return false;
799
+ const scheme = m[1].toLowerCase();
800
+ return scheme !== 'http' && scheme !== 'https' && !REFUSED_LINK_SCHEMES.includes(scheme);
801
+ }
802
+
803
+ /**
804
+ * Where a link the SDK is about to open came from. The same wire values on
805
+ * every Joryio SDK. `push` comes from iOS only: on Android the native SDK
806
+ * never opens a push link itself - your launcher activity receives it.
807
+ */
808
+ export type JoryioLinkSource = 'in_app' | 'placement' | 'card' | 'push';
809
+
810
+ /** A link the native SDK is about to open, handed to {@link JoryioSDK.setLinkHandler} first. */
811
+ export interface JoryioLink {
812
+ /** An http(s) link or an app deep link (`myapp://cart`); a push link may be another scheme the system opens. */
813
+ url: string;
814
+ source: JoryioLinkSource;
815
+ campaignId?: string;
816
+ placementKey?: string;
817
+ itemId?: string;
818
+ cardId?: string;
819
+ /** True for an app-scheme link, false for http(s). */
820
+ isAppDeepLink: boolean;
821
+ }
822
+
823
+ /**
824
+ * Return true (or a Promise of true) to take the link over, false to let the
825
+ * native SDK open it as it does without a handler. A Promise is how to decide
826
+ * later: the link waits for it.
827
+ */
828
+ export type JoryioLinkHandler = (link: JoryioLink) => boolean | Promise<boolean>;
829
+
830
+ const LINK_SOURCES: readonly JoryioLinkSource[] = ['in_app', 'placement', 'card', 'push'];
831
+
832
+ /** The `JoryioLink` event body as a JoryioLink, or null when it is not one. */
833
+ function toLink(e: any): JoryioLink | null {
834
+ if (!e || typeof e.url !== 'string' || !LINK_SOURCES.includes(e.source)) return null;
835
+ const link: JoryioLink = { url: e.url, source: e.source, isAppDeepLink: e.isAppDeepLink === true };
836
+ for (const key of ['campaignId', 'placementKey', 'itemId', 'cardId'] as const) {
837
+ if (typeof e[key] === 'string' && e[key]) link[key] = e[key];
838
+ }
839
+ return link;
840
+ }
841
+
842
+ let nativePlacementView: any = null;
843
+
844
+ /**
845
+ * `<JoryioPlacement placementKey="home_hero" />` - the native SDK's own
846
+ * PlacementView (iOS and Android): fetching, caching, viewability, the
847
+ * holdout and the reports are the native ones. The component sizes itself to
848
+ * the drawn content (0 when the placement collapses); a `style` height wins.
849
+ */
850
+ export function JoryioPlacement(props: JoryioPlacementProps): any {
851
+ const [height, setHeight] = React.useState(0);
852
+ if (!nativePlacementView) {
853
+ const requireNative = (ReactNative as any).requireNativeComponent;
854
+ if (typeof requireNative !== 'function') return null;
855
+ nativePlacementView = requireNative('JoryioPlacementView');
856
+ }
857
+ return React.createElement(nativePlacementView, {
858
+ placementKey: props.placementKey,
859
+ // Passed to the native PlacementView's properties of the same names.
860
+ showProducts: props.showProducts !== false,
861
+ productButtonText: typeof props.productButtonText === 'string' ? props.productButtonText : null,
862
+ productCardWidth:
863
+ typeof props.productCardWidth === 'number' && Number.isFinite(props.productCardWidth) && props.productCardWidth > 0
864
+ ? props.productCardWidth
865
+ : PLACEMENT_PRODUCT_CARD_WIDTH,
866
+ style: [{ height }, props.style],
867
+ onPlacementRender: (e: any) => {
868
+ const info = e?.nativeEvent || {};
869
+ setHeight(typeof info.height === 'number' ? info.height : 0);
870
+ props.onRender?.(info);
871
+ },
872
+ onPlacementDeepLink: (e: any) => {
873
+ const url = e?.nativeEvent?.url;
874
+ if (isAppDeepLink(url)) props.onDeepLink?.(url);
875
+ },
876
+ });
877
+ }
878
+
879
+ // ── Content cards (docs/PLACEMENTS_PLAN.md section 11, D444 Phase 3) ────────
880
+
881
+ /** The feed goes to the network at most once per this many seconds; extra calls coalesce - the same on every Joryio SDK. */
882
+ export const CARD_MIN_REFRESH_SECONDS = 30;
883
+ /** How long the feed is served from the device cache before it is asked for again - the same on every Joryio SDK. */
884
+ export const CARD_FEED_TTL_SECONDS = 300;
885
+
886
+ /**
887
+ * `server`: read / clicked / dismissed are kept per person on the server, the
888
+ * same on every device. `device`: an anonymous visitor - this device keeps
889
+ * what was read and dismissed (the native SDK does it).
890
+ */
891
+ export type CardStateScope = 'server' | 'device';
892
+
893
+ /** One card of the person's feed. */
894
+ export interface Card {
895
+ /** Stable id of this card for this person. */
896
+ id: string;
897
+ /** Campaign id, or `journey:<canvasId>:<nodeId>` for a journey card. */
898
+ campaignId: string;
899
+ variantId: string | null;
900
+ title: string | null;
901
+ body: string | null;
902
+ imageUrl: string | null;
903
+ /** Button label; null = no button (the whole card opens `url` when set). */
904
+ buttonText: string | null;
905
+ /** An http(s) URL or the app's own deep link; null = nothing to open. */
906
+ url: string | null;
907
+ pinned: boolean;
908
+ /** ISO 8601. */
909
+ createdAt: string;
910
+ /** ISO 8601, or null. */
911
+ expiresAt: string | null;
912
+ read: boolean;
913
+ clicked: boolean;
914
+ }
915
+
916
+ /** The person's feed (or one page of it). */
917
+ export interface CardFeed {
918
+ /** Pinned first, then newest first. */
919
+ cards: Card[];
920
+ /** Unread cards across the whole feed, not this page: the badge. */
921
+ unreadCount: number;
922
+ /** Pass to `getCards({ cursor })` for the next page; null on the last one. */
923
+ nextCursor: string | null;
924
+ stateScope: CardStateScope;
925
+ }
926
+
927
+ const EMPTY_CARD_FEED_JSON = '{"cards":[],"unreadCount":0,"nextCursor":null,"stateScope":"server"}';
928
+
929
+ const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);
930
+
931
+ /** Native JSON (Card.toJson on iOS / Android) -> a Card, or null when it is not one. */
932
+ function toCard(c: any): Card | null {
933
+ if (!c || typeof c !== 'object' || typeof c.id !== 'string') return null;
934
+ return {
935
+ id: c.id,
936
+ campaignId: str(c.campaignId) ?? '',
937
+ variantId: str(c.variantId),
938
+ title: str(c.title),
939
+ body: str(c.body),
940
+ imageUrl: str(c.imageUrl),
941
+ buttonText: str(c.buttonText),
942
+ url: str(c.url),
943
+ pinned: c.pinned === true,
944
+ createdAt: str(c.createdAt) ?? '',
945
+ expiresAt: str(c.expiresAt),
946
+ read: c.read === true,
947
+ clicked: c.clicked === true,
948
+ };
949
+ }
950
+
951
+ const parseJson = (json: unknown): any => {
952
+ try {
953
+ return typeof json === 'string' ? JSON.parse(json) : json;
954
+ } catch {
955
+ return null;
956
+ }
957
+ };
958
+
959
+ /** Native JSON (CardFeed.toJson on iOS / Android) -> a CardFeed. A bad answer is the empty feed. */
960
+ function toCardFeed(json: unknown): CardFeed {
961
+ let raw: any = parseJson(json);
962
+ if (!raw || typeof raw !== 'object') raw = {};
963
+ const cards: Card[] = (Array.isArray(raw.cards) ? raw.cards : []).map(toCard).filter((c: Card | null): c is Card => c !== null);
964
+ return {
965
+ cards,
966
+ unreadCount: typeof raw.unreadCount === 'number' && raw.unreadCount >= 0 ? raw.unreadCount : 0,
967
+ nextCursor: str(raw.nextCursor),
968
+ stateScope: raw.stateScope === 'device' ? 'device' : 'server',
969
+ };
970
+ }
971
+
972
+ /**
973
+ * Returned by every `on...Updated` listener - `onCardsUpdated`,
974
+ * `onPlacementsUpdated` and `onFlagsUpdated`: `cancel()` stops the updates.
975
+ * It is also callable, `sub()` being `sub.cancel()`, so code that called the
976
+ * returned function keeps working. Cancelling twice is harmless.
977
+ *
978
+ * One type with the same name and the same `cancel()` on every Joryio SDK
979
+ * (iOS, Android, web; Unity `JoryioSubscription.Cancel()`).
980
+ */
981
+ export interface JoryioSubscription {
982
+ (): void;
983
+ cancel(): void;
984
+ }
985
+
986
+ function joryioSubscription(stop: () => void): JoryioSubscription {
987
+ let done = false;
988
+ const cancel = (): void => {
989
+ if (done) return;
990
+ done = true;
991
+ stop();
992
+ };
993
+ const sub = (() => cancel()) as JoryioSubscription;
994
+ sub.cancel = cancel;
995
+ return sub;
996
+ }
997
+
998
+ /** A card or its id. */
999
+ const cardIdOf = (card: Card | string): string | null => {
1000
+ const id = typeof card === 'string' ? card : card && typeof card === 'object' ? card.id : null;
1001
+ return typeof id === 'string' && id.length > 0 ? id : null;
1002
+ };
1003
+
1004
+ export interface JoryioCardFeedProps {
1005
+ /** Give it a size (e.g. `{ flex: 1 }`, the default): the feed scrolls inside it. */
1006
+ style?: unknown;
1007
+ /** Shown when the feed is empty. Default "No messages yet". */
1008
+ emptyText?: string;
1009
+ /** The marker on a pinned card. Default "Pinned". */
1010
+ pinnedLabel?: string;
1011
+ /** The accessible label of the dismiss control. Default "Dismiss". */
1012
+ dismissLabel?: string;
1013
+ /** The accessible label of the unread dot. Default "Unread". */
1014
+ unreadLabel?: string;
1015
+ /**
1016
+ * A card's url is an app deep link (`myapp://...`): route it in your app
1017
+ * (the click is already reported). Without this only an http(s) link is
1018
+ * opened; no other scheme is ever handed to the system.
1019
+ */
1020
+ onDeepLink?: (url: string, card: Card) => void;
1021
+ /** Called after each draw with the feed drawn. */
1022
+ onRender?: (feed: CardFeed) => void;
1023
+ }
1024
+
1025
+ let nativeCardFeedView: any = null;
1026
+
1027
+ /**
1028
+ * `<JoryioCardFeed />` - the person's content cards as a plain scrolling list:
1029
+ * the native SDK's own feed view (iOS CardFeedViewController, Android
1030
+ * CardFeedView), so paging, the unread dot, the dismiss control, the
1031
+ * viewed / read / clicked / dismissed reports (a card at least
1032
+ * PLACEMENT_VIEWABLE_FRACTION on screen for IN_APP_DISPLAY_DWELL_MS is viewed
1033
+ * then read) and the link rule are the native ones. The look follows the
1034
+ * system theme, dark mode included.
1035
+ */
1036
+ export function JoryioCardFeed(props: JoryioCardFeedProps): any {
1037
+ if (!nativeCardFeedView) {
1038
+ const requireNative = (ReactNative as any).requireNativeComponent;
1039
+ if (typeof requireNative !== 'function') return null;
1040
+ nativeCardFeedView = requireNative('JoryioCardFeedView');
1041
+ }
1042
+ return React.createElement(nativeCardFeedView, {
1043
+ style: [{ flex: 1 }, props.style],
1044
+ emptyText: props.emptyText,
1045
+ pinnedLabel: props.pinnedLabel,
1046
+ dismissLabel: props.dismissLabel,
1047
+ unreadLabel: props.unreadLabel,
1048
+ // The native views send the feed and the card as their toJson() (the same JSON as getCards).
1049
+ onCardFeedRender: (e: any) => {
1050
+ props.onRender?.(toCardFeed(e?.nativeEvent?.feed));
1051
+ },
1052
+ onCardDeepLink: (e: any) => {
1053
+ const url = e?.nativeEvent?.url;
1054
+ const card = toCard(parseJson(e?.nativeEvent?.card));
1055
+ if (typeof url === 'string' && card) props.onDeepLink?.(url, card);
1056
+ },
1057
+ });
1058
+ }
1059
+
607
1060
  /**
608
1061
  * What a held call is, which decides what a later privacy decision discards
609
1062
  * and what a full hold drops first.
@@ -780,6 +1233,14 @@ class JoryioSDK {
780
1233
  */
781
1234
  private _inAppHandedToJs = false;
782
1235
 
1236
+ private _placementListeners = 0;
1237
+
1238
+ private _cardListeners = 0;
1239
+
1240
+ private _linkHandler: JoryioLinkHandler | null = null;
1241
+
1242
+ private _linkSubscription: { remove: () => void } | null = null;
1243
+
783
1244
  constructor() {
784
1245
  this._ready = new Promise<void>((resolve) => {
785
1246
  this._markReady = resolve;
@@ -1273,6 +1734,8 @@ class JoryioSDK {
1273
1734
  if (forNative.trackingConsent === 'denied') this._initConfigDenied = true;
1274
1735
  if (forNative.optOut === true) this._initConfigOptedOut = true;
1275
1736
  }
1737
+ // The bridge names itself on every request (D427); not an app option.
1738
+ forNative.sdkWrapperVersion = SDK_VERSION;
1276
1739
  try {
1277
1740
  await JoryioModule.initialize(sdkKey, apiHost, forNative);
1278
1741
  } catch (e) {
@@ -2224,6 +2687,292 @@ class JoryioSDK {
2224
2687
  this._dispatch(() => JoryioModule.syncInAppCampaigns?.());
2225
2688
  }
2226
2689
 
2690
+ // ─── Feature flags (BACKLOG D446) ───────────────────────────────────────
2691
+ //
2692
+ // The native SDK holds the answer and logs exposures; these route to it.
2693
+ // The getters resolve at once with what the device holds - they never wait
2694
+ // for the network - and with the in-code default before initialize(), for a
2695
+ // flag Joryio did not send, for a value of another type, or without
2696
+ // tracking consent. A Promise because every native call crosses the bridge
2697
+ // asynchronously; the names and the wire are the same on all five SDKs.
2698
+
2699
+ /** A flag's value of any type, or `defaultValue`. The first read in a session logs an exposure. */
2700
+ getFlag<T = unknown>(key: string, defaultValue: T): Promise<T> {
2701
+ if (!flagKeyOk('getFlag', key)) return Promise.resolve(defaultValue);
2702
+ return this._query<{ value: T } | null>('getFlag', null, () => {
2703
+ return JoryioModule.getFlag(key, defaultValue ?? null);
2704
+ }).then(
2705
+ (r) => (r && typeof r === 'object' && 'value' in r ? (r.value as T) : defaultValue),
2706
+ );
2707
+ }
2708
+
2709
+ /** A boolean flag, or `defaultValue` (also for a flag of another type). */
2710
+ getBoolFlag(key: string, defaultValue: boolean): Promise<boolean> {
2711
+ if (!flagKeyOk('getBoolFlag', key)) return Promise.resolve(defaultValue);
2712
+ return this._query('getBoolFlag', defaultValue, () => {
2713
+ return JoryioModule.getBoolFlag(key, !!defaultValue);
2714
+ });
2715
+ }
2716
+
2717
+ /** A string flag, or `defaultValue`. */
2718
+ getStringFlag(key: string, defaultValue: string): Promise<string> {
2719
+ if (!flagKeyOk('getStringFlag', key)) return Promise.resolve(defaultValue);
2720
+ return this._query('getStringFlag', defaultValue, () => {
2721
+ return JoryioModule.getStringFlag(key, String(defaultValue ?? ''));
2722
+ });
2723
+ }
2724
+
2725
+ /** A number flag, or `defaultValue`. */
2726
+ getNumberFlag(key: string, defaultValue: number): Promise<number> {
2727
+ if (!flagKeyOk('getNumberFlag', key)) return Promise.resolve(defaultValue);
2728
+ return this._query('getNumberFlag', defaultValue, () => {
2729
+ return JoryioModule.getNumberFlag(key, Number(defaultValue));
2730
+ });
2731
+ }
2732
+
2733
+ /** A JSON flag (object, array or scalar), or `defaultValue`. */
2734
+ getJsonFlag<T = unknown>(key: string, defaultValue: T): Promise<T> {
2735
+ if (!flagKeyOk('getJsonFlag', key)) return Promise.resolve(defaultValue);
2736
+ return this._query<{ value: T } | null>('getJsonFlag', null, () => {
2737
+ return JoryioModule.getJsonFlag(key, defaultValue ?? null);
2738
+ }).then(
2739
+ (r) => (r && typeof r === 'object' && 'value' in r ? (r.value as T) : defaultValue),
2740
+ );
2741
+ }
2742
+
2743
+ /** Every flag held for this person, key -> value. Logs no exposure. */
2744
+ getAllFlags(): Promise<Record<string, unknown>> {
2745
+ return this._query<Record<string, unknown>>('getAllFlags', {}, () => {
2746
+ return JoryioModule.getAllFlags();
2747
+ });
2748
+ }
2749
+
2750
+ /** Ask the server now; resolves when the answer is in (or the request failed: the held flags stay). */
2751
+ refreshFlags(): Promise<void> {
2752
+ return this._query<void>('refreshFlags', undefined, () => {
2753
+ return JoryioModule.refreshFlags();
2754
+ }).then(() => undefined);
2755
+ }
2756
+
2757
+ /**
2758
+ * `callback(keys)` is called with the keys whose value changed. Returns a
2759
+ * JoryioSubscription: `cancel()` it to stop (calling it is the same). Safe
2760
+ * before initialize(): updates start once the SDK runs.
2761
+ */
2762
+ onFlagsUpdated(callback: (keys: string[]) => unknown): JoryioSubscription {
2763
+ if (typeof callback !== 'function') {
2764
+ warn('onFlagsUpdated() needs a callback function; ignored.');
2765
+ return joryioSubscription(() => {});
2766
+ }
2767
+ if (!isModuleAvailable || !emitter) return joryioSubscription(() => {});
2768
+ const guarded = guardedCallback<string[]>('onFlagsUpdated', callback);
2769
+ const subscription = emitter.addListener('JoryioFlagsUpdated', (event: unknown) => {
2770
+ const keys = (event as { keys?: unknown } | null)?.keys;
2771
+ guarded(Array.isArray(keys) ? keys.filter((k): k is string => typeof k === 'string') : []);
2772
+ });
2773
+ // One native subscription for the module, held until initialize() like
2774
+ // any control call; native ignores a second enable.
2775
+ this._dispatch(() => JoryioModule.enableFlagsUpdates?.());
2776
+ return joryioSubscription(() => subscription.remove());
2777
+ }
2778
+
2779
+ /**
2780
+ * The placements for `placementKeys`, to draw with your own components
2781
+ * (or use `<JoryioPlacement placementKey=... />`). Report with
2782
+ * `item.markDisplayed()` once at least half of it was on screen for
2783
+ * IN_APP_DISPLAY_DWELL_MS, `item.markClicked()`, `item.markDismissed()`,
2784
+ * and `placement.markDisplayed()` for a held-out person's empty spot.
2785
+ * Waits for initialize(); resolves `{}` without the native module.
2786
+ */
2787
+ getPlacements(placementKeys: string[]): Promise<Record<string, Placement>> {
2788
+ const keys = Array.isArray(placementKeys) ? placementKeys.filter((k) => typeof k === 'string') : [];
2789
+ // A read: waits for initialize() like the other queries.
2790
+ return this._query<string>('getPlacements', '{}', () => {
2791
+ return JoryioModule.getPlacements(keys);
2792
+ }).then(toPlacements);
2793
+ }
2794
+
2795
+ /** Ask the server again (all placements on screen when no keys). At most once per key per PLACEMENT_MIN_REFRESH_SECONDS. */
2796
+ refreshPlacements(placementKeys?: string[]): void {
2797
+ this._dispatch(() => JoryioModule.refreshPlacements?.(Array.isArray(placementKeys) ? placementKeys : null));
2798
+ }
2799
+
2800
+ /**
2801
+ * Called with the placements whose content changed. Returns a
2802
+ * JoryioSubscription: `cancel()` it to stop (calling it is the same).
2803
+ * An app with its own push messaging handler should call
2804
+ * refreshPlacements() on a `jry_sync: "placements"` data message; the
2805
+ * native SDKs handle it themselves otherwise.
2806
+ */
2807
+ onPlacementsUpdated(callback: (placements: Record<string, Placement>) => unknown): JoryioSubscription {
2808
+ if (typeof callback !== 'function' || !isModuleAvailable || !emitter) return joryioSubscription(() => {});
2809
+ const subscription = emitter.addListener('JoryioPlacementsUpdated', (e: any) => {
2810
+ try {
2811
+ callback(toPlacements(e?.json));
2812
+ } catch (error) {
2813
+ warn(`onPlacementsUpdated callback threw: ${String(error)}`);
2814
+ }
2815
+ });
2816
+ this._placementListeners += 1;
2817
+ this._dispatch(() => JoryioModule.enablePlacementsUpdates?.());
2818
+ return joryioSubscription(() => {
2819
+ subscription.remove();
2820
+ this._placementListeners = Math.max(0, this._placementListeners - 1);
2821
+ if (this._placementListeners === 0) this._dispatch(() => JoryioModule.disablePlacementsUpdates?.());
2822
+ });
2823
+ }
2824
+
2825
+ /**
2826
+ * The person's content cards - pinned first, newest first - with the unread
2827
+ * count for a badge, from the native SDK's cache for CARD_FEED_TTL_SECONDS.
2828
+ * Pass a feed's `nextCursor` as `{ cursor }` for the next page (the native
2829
+ * SDK adds it to the cached feed). Draw it with `<JoryioCardFeed />`, or
2830
+ * yourself and report with markCardViewed / markCardRead /
2831
+ * markCardClicked / dismissCard. Waits for initialize(); resolves the empty
2832
+ * feed without the native module.
2833
+ */
2834
+ getCards(options?: { cursor?: string | null }): Promise<CardFeed> {
2835
+ const cursor = typeof options?.cursor === 'string' && options.cursor.length > 0 ? options.cursor : null;
2836
+ // A read: waits for initialize() like the other queries.
2837
+ return this._query<string>('getCards', EMPTY_CARD_FEED_JSON, () => {
2838
+ return JoryioModule.getCards(cursor);
2839
+ }).then(toCardFeed);
2840
+ }
2841
+
2842
+ /**
2843
+ * Unread cards, from the native SDK's cache (never a network call): the
2844
+ * badge. A Promise here because every React Native read crosses the bridge;
2845
+ * the native SDKs answer synchronously.
2846
+ */
2847
+ getUnreadCardCount(): Promise<number> {
2848
+ return this._query<number>('getUnreadCardCount', 0, () => {
2849
+ return JoryioModule.getUnreadCardCount();
2850
+ }).then((n) => (typeof n === 'number' && n >= 0 ? n : 0));
2851
+ }
2852
+
2853
+ /** The card was on screen (`viewed`). Once per card; `<JoryioCardFeed />` does it itself. */
2854
+ markCardViewed(card: Card | string): void {
2855
+ const id = cardIdOf(card);
2856
+ if (id) this._dispatch(() => JoryioModule.markCardViewed?.(id), 'data');
2857
+ }
2858
+
2859
+ /** The person read the card (`read`): it stops counting as unread at once. */
2860
+ markCardRead(card: Card | string): void {
2861
+ const id = cardIdOf(card);
2862
+ if (id) this._dispatch(() => JoryioModule.markCardRead?.(id), 'data');
2863
+ }
2864
+
2865
+ /** The person tapped the card or its button (`clicked`, which also marks it read). Open its url yourself. */
2866
+ markCardClicked(card: Card | string): void {
2867
+ const id = cardIdOf(card);
2868
+ if (id) this._dispatch(() => JoryioModule.markCardClicked?.(id), 'data');
2869
+ }
2870
+
2871
+ /** The person removed the card (`dismissed`): it leaves the feed at once and never comes back. */
2872
+ dismissCard(card: Card | string): void {
2873
+ const id = cardIdOf(card);
2874
+ if (id) this._dispatch(() => JoryioModule.dismissCard?.(id), 'data');
2875
+ }
2876
+
2877
+ /**
2878
+ * Ask the server for the feed again. At most once per
2879
+ * CARD_MIN_REFRESH_SECONDS; extra calls coalesce. An app with its own push
2880
+ * messaging handler calls this on a `jry_sync: "cards"` data message; the
2881
+ * native SDKs handle it themselves otherwise.
2882
+ */
2883
+ refreshCards(): void {
2884
+ this._dispatch(() => JoryioModule.refreshCards?.());
2885
+ }
2886
+
2887
+ /**
2888
+ * Called with the whole feed whenever it changes (a refresh, a report, an
2889
+ * identity change). Returns a JoryioSubscription: `cancel()` it to stop
2890
+ * (calling it, `sub()`, is the same).
2891
+ */
2892
+ onCardsUpdated(callback: (feed: CardFeed) => unknown): JoryioSubscription {
2893
+ if (typeof callback !== 'function' || !isModuleAvailable || !emitter) return joryioSubscription(() => {});
2894
+ const subscription = emitter.addListener('JoryioCardsUpdated', (e: any) => {
2895
+ try {
2896
+ callback(toCardFeed(e?.json));
2897
+ } catch (error) {
2898
+ warn(`onCardsUpdated callback threw: ${String(error)}`);
2899
+ }
2900
+ });
2901
+ this._cardListeners += 1;
2902
+ this._dispatch(() => JoryioModule.enableCardsUpdates?.());
2903
+ return joryioSubscription(() => {
2904
+ subscription.remove();
2905
+ this._cardListeners = Math.max(0, this._cardListeners - 1);
2906
+ if (this._cardListeners === 0) this._dispatch(() => JoryioModule.disableCardsUpdates?.());
2907
+ });
2908
+ }
2909
+
2910
+ /**
2911
+ * Receive EVERY link the native SDK is about to open - an in-app message
2912
+ * button or link, a `<JoryioPlacement />` button, a `<JoryioCardFeed />`
2913
+ * tap, an iOS push tap - before it opens: http(s) links and app deep links
2914
+ * (`myapp://cart`) alike, with where it came from (`link.source`) and the
2915
+ * ids that go with it. Return true to take the link over (navigate in your
2916
+ * app), false to let the native SDK open it as it does without a handler -
2917
+ * http(s) to the system (or your universal-link handling with
2918
+ * `forwardUniversalLinks` on iOS), an app deep link to the component's
2919
+ * `onDeepLink`. A Promise decides later. A refused scheme (javascript:,
2920
+ * data:, intent:, ...) never reaches it. One handler: a second call
2921
+ * replaces the first. Works before initialize(). Same name on iOS,
2922
+ * Android, web and Unity (`SetLinkHandler`).
2923
+ */
2924
+ setLinkHandler(handler: JoryioLinkHandler): void {
2925
+ if (typeof handler !== 'function') {
2926
+ warn('setLinkHandler() needs a function; use clearLinkHandler() to remove one');
2927
+ return;
2928
+ }
2929
+ this._linkHandler = handler;
2930
+ if (!isModuleAvailable || !emitter) return;
2931
+ if (!this._linkSubscription) {
2932
+ this._linkSubscription = emitter.addListener('JoryioLink', (e: any) => this._onLink(e));
2933
+ }
2934
+ // Not held for initialize(): the native handler is app-wide and works before it.
2935
+ JoryioModule.enableLinkHandler?.();
2936
+ }
2937
+
2938
+ /** Remove the handler set with setLinkHandler: links open as they do without one. */
2939
+ clearLinkHandler(): void {
2940
+ this._linkHandler = null;
2941
+ this._linkSubscription?.remove();
2942
+ this._linkSubscription = null;
2943
+ if (isModuleAvailable) JoryioModule.disableLinkHandler?.();
2944
+ }
2945
+
2946
+ /** A link from native: ask the handler, then tell native whether it was taken. */
2947
+ private _onLink(e: any): void {
2948
+ const linkId = e?.linkId;
2949
+ if (typeof linkId !== 'string') return;
2950
+ const complete = (handled: unknown) => JoryioModule.completeLink?.(linkId, handled === true);
2951
+ const handler = this._linkHandler;
2952
+ const link = toLink(e);
2953
+ if (!handler || !link) {
2954
+ complete(false);
2955
+ return;
2956
+ }
2957
+ let result: boolean | Promise<boolean>;
2958
+ try {
2959
+ result = handler(link);
2960
+ } catch (error) {
2961
+ // A throwing handler declines: the link still opens.
2962
+ warn(`setLinkHandler handler threw; the link opens as without one: ${String(error)}`);
2963
+ complete(false);
2964
+ return;
2965
+ }
2966
+ if (result && typeof (result as Promise<boolean>).then === 'function') {
2967
+ (result as Promise<boolean>).then(complete, (error) => {
2968
+ warn(`setLinkHandler handler rejected; the link opens as without one: ${String(error)}`);
2969
+ complete(false);
2970
+ });
2971
+ } else {
2972
+ complete(result);
2973
+ }
2974
+ }
2975
+
2227
2976
  /**
2228
2977
  * Forget which in-app campaigns have already been shown on this device.
2229
2978
  *