@joryio/react-native-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.
package/lib/index.js CHANGED
@@ -1,8 +1,56 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ecommerce = exports.IN_APP_DISPLAY_DWELL_MS = exports.MAX_PRE_INIT_CALLS = exports.CLICK_IDENTITY_PARAM = void 0;
36
+ exports.ecommerce = exports.CARD_FEED_TTL_SECONDS = exports.CARD_MIN_REFRESH_SECONDS = exports.PLACEMENT_PRODUCT_CARD_WIDTH = exports.PLACEMENT_PRODUCT_ELEMENT_PREFIX = exports.PLACEMENT_MIN_REFRESH_SECONDS = exports.PLACEMENT_VIEWABLE_FRACTION = exports.IN_APP_DISPLAY_DWELL_MS = exports.MAX_PRE_INIT_CALLS = exports.CLICK_IDENTITY_PARAM = exports.SDK_VERSION = void 0;
37
+ exports.placementProductElementId = placementProductElementId;
38
+ exports.isAppDeepLink = isAppDeepLink;
39
+ exports.JoryioPlacement = JoryioPlacement;
40
+ exports.JoryioCardFeed = JoryioCardFeed;
4
41
  const react_native_1 = require("react-native");
42
+ const ReactNative = __importStar(require("react-native"));
43
+ const React = __importStar(require("react"));
5
44
  const { JoryioModule } = react_native_1.NativeModules;
45
+ /**
46
+ * This package's version - the same number every Joryio SDK carries
47
+ * (sdk-version-parity.spec.ts pins it; the release tooling rewrites it).
48
+ * Handed to the native SDK at initialize() as `sdkWrapperVersion`, which
49
+ * sends it on every request as `X-Joryio-SDK-Wrapper-Version` next to
50
+ * `X-Joryio-SDK-Wrapper: react-native` (D427), so the dashboard shows the
51
+ * version of THIS package, the one the app upgrades.
52
+ */
53
+ exports.SDK_VERSION = '1.4.0';
6
54
  const MODULE_MISSING_MESSAGE = '@joryio/react-native-sdk: NativeModule not found. ' +
7
55
  'Make sure you ran `pod install` (iOS) / rebuilt the app (Android). ' +
8
56
  'All Joryio calls will be no-ops until the native module is linked.';
@@ -203,6 +251,13 @@ function finiteProperties(caller, properties) {
203
251
  * expect - was a fatal JS error in a release build and skipped every other
204
252
  * listener of the same event. A returned promise that rejects is caught too.
205
253
  */
254
+ /** A flag key must be a non-empty string; otherwise the getter answers its default. */
255
+ function flagKeyOk(method, key) {
256
+ if (typeof key === 'string' && key.length > 0)
257
+ return true;
258
+ warn(`${method}() needs a flag key; the default is returned.`);
259
+ return false;
260
+ }
206
261
  function guardedCallback(name, callback) {
207
262
  const report = (err) => {
208
263
  // eslint-disable-next-line no-console
@@ -256,6 +311,227 @@ exports.MAX_PRE_INIT_CALLS = 1000;
256
311
  * apply the same rule - see {@link Joryio.trackInAppImpression}.
257
312
  */
258
313
  exports.IN_APP_DISPLAY_DWELL_MS = 1000;
314
+ // ── Placements (docs/PLACEMENTS_PLAN.md, D444) ──────────────────────────────
315
+ /** Share of an item that must be on screen for it to count as seen - the same on every Joryio SDK. */
316
+ exports.PLACEMENT_VIEWABLE_FRACTION = 0.5;
317
+ /** A placement key is fetched from the network at most once per this many seconds - the same on every Joryio SDK. */
318
+ exports.PLACEMENT_MIN_REFRESH_SECONDS = 30;
319
+ /**
320
+ * A drawn product card's tap is reported as `clicked` with the elementId
321
+ * `product:<product id>` (at most 128 characters) - the same on every Joryio SDK.
322
+ */
323
+ exports.PLACEMENT_PRODUCT_ELEMENT_PREFIX = 'product:';
324
+ /** Width of a drawn product card when the app does not set one (dp / points) - the same on every Joryio SDK. */
325
+ exports.PLACEMENT_PRODUCT_CARD_WIDTH = 160;
326
+ /** The elementId a product card's click is reported with - use it with `markClicked` when you draw the cards yourself. */
327
+ function placementProductElementId(productId) {
328
+ return `${exports.PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
329
+ }
330
+ /** The bridge's product cards, defensively typed: an entry without an id is dropped. */
331
+ function toProducts(raw) {
332
+ if (!Array.isArray(raw))
333
+ return [];
334
+ const str = (v) => (typeof v === 'string' ? v : null);
335
+ return raw
336
+ .filter((p) => p && typeof p === 'object' && (typeof p.id === 'string' || typeof p.id === 'number'))
337
+ .map((p) => ({
338
+ id: String(p.id),
339
+ title: str(p.title),
340
+ price: str(p.price),
341
+ compareAtPrice: str(p.compareAtPrice),
342
+ discountPercent: typeof p.discountPercent === 'number' ? p.discountPercent : null,
343
+ imageUrl: str(p.imageUrl),
344
+ url: str(p.url),
345
+ }));
346
+ }
347
+ /** Native JSON (Placement.toJson on iOS / Android) -> objects whose mark* calls go back to native. */
348
+ function toPlacements(json) {
349
+ let raw = {};
350
+ try {
351
+ raw = typeof json === 'string' ? JSON.parse(json) : json || {};
352
+ }
353
+ catch {
354
+ raw = {};
355
+ }
356
+ const mark = (key, itemId, action, elementId) => {
357
+ JoryioModule?.markPlacement?.(key, itemId, action, elementId ?? null);
358
+ };
359
+ const out = {};
360
+ for (const [key, p] of Object.entries(raw || {})) {
361
+ if (!p || typeof p !== 'object')
362
+ continue;
363
+ out[key] = {
364
+ placementKey: p.placementKey || key,
365
+ isControl: p.isControl === true,
366
+ emptyBehavior: p.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse',
367
+ maxItems: typeof p.maxItems === 'number' ? p.maxItems : 1,
368
+ ttlSeconds: typeof p.ttlSeconds === 'number' ? p.ttlSeconds : 300,
369
+ items: (Array.isArray(p.items) ? p.items : []).map((i) => ({
370
+ id: String(i.id),
371
+ variantId: i.variantId ?? null,
372
+ kind: i.kind,
373
+ data: i.data || {},
374
+ content: i.content ?? null,
375
+ products: toProducts(i.products),
376
+ markDisplayed: () => mark(key, String(i.id), 'displayed'),
377
+ markClicked: (elementId) => mark(key, String(i.id), 'clicked', elementId),
378
+ markDismissed: () => mark(key, String(i.id), 'dismissed'),
379
+ })),
380
+ markDisplayed: () => mark(key, null, 'control'),
381
+ };
382
+ }
383
+ return out;
384
+ }
385
+ /** Schemes never opened nor handed to the app, whatever a link says (the backend's placement / card link rule). */
386
+ const REFUSED_LINK_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'blob', 'about', 'content', 'intent'];
387
+ /**
388
+ * An app deep link (`myapp://cart`) that may go to the app's own handler: a
389
+ * `scheme://` link whose scheme is not http(s) and not a refused one. The
390
+ * native PlacementView applies the same rule before a link reaches JS; this
391
+ * layer checks again. The same rule on every Joryio SDK.
392
+ */
393
+ function isAppDeepLink(url) {
394
+ if (typeof url !== 'string')
395
+ return false;
396
+ const m = /^([a-z][a-z0-9+.-]*):\/\/./i.exec(url.trim());
397
+ if (!m)
398
+ return false;
399
+ const scheme = m[1].toLowerCase();
400
+ return scheme !== 'http' && scheme !== 'https' && !REFUSED_LINK_SCHEMES.includes(scheme);
401
+ }
402
+ const LINK_SOURCES = ['in_app', 'placement', 'card', 'push'];
403
+ /** The `JoryioLink` event body as a JoryioLink, or null when it is not one. */
404
+ function toLink(e) {
405
+ if (!e || typeof e.url !== 'string' || !LINK_SOURCES.includes(e.source))
406
+ return null;
407
+ const link = { url: e.url, source: e.source, isAppDeepLink: e.isAppDeepLink === true };
408
+ for (const key of ['campaignId', 'placementKey', 'itemId', 'cardId']) {
409
+ if (typeof e[key] === 'string' && e[key])
410
+ link[key] = e[key];
411
+ }
412
+ return link;
413
+ }
414
+ let nativePlacementView = null;
415
+ /**
416
+ * `<JoryioPlacement placementKey="home_hero" />` - the native SDK's own
417
+ * PlacementView (iOS and Android): fetching, caching, viewability, the
418
+ * holdout and the reports are the native ones. The component sizes itself to
419
+ * the drawn content (0 when the placement collapses); a `style` height wins.
420
+ */
421
+ function JoryioPlacement(props) {
422
+ const [height, setHeight] = React.useState(0);
423
+ if (!nativePlacementView) {
424
+ const requireNative = ReactNative.requireNativeComponent;
425
+ if (typeof requireNative !== 'function')
426
+ return null;
427
+ nativePlacementView = requireNative('JoryioPlacementView');
428
+ }
429
+ return React.createElement(nativePlacementView, {
430
+ placementKey: props.placementKey,
431
+ // Passed to the native PlacementView's properties of the same names.
432
+ showProducts: props.showProducts !== false,
433
+ productButtonText: typeof props.productButtonText === 'string' ? props.productButtonText : null,
434
+ productCardWidth: typeof props.productCardWidth === 'number' && Number.isFinite(props.productCardWidth) && props.productCardWidth > 0
435
+ ? props.productCardWidth
436
+ : exports.PLACEMENT_PRODUCT_CARD_WIDTH,
437
+ style: [{ height }, props.style],
438
+ onPlacementRender: (e) => {
439
+ const info = e?.nativeEvent || {};
440
+ setHeight(typeof info.height === 'number' ? info.height : 0);
441
+ props.onRender?.(info);
442
+ },
443
+ onPlacementDeepLink: (e) => {
444
+ const url = e?.nativeEvent?.url;
445
+ if (isAppDeepLink(url))
446
+ props.onDeepLink?.(url);
447
+ },
448
+ });
449
+ }
450
+ // ── Content cards (docs/PLACEMENTS_PLAN.md section 11, D444 Phase 3) ────────
451
+ /** The feed goes to the network at most once per this many seconds; extra calls coalesce - the same on every Joryio SDK. */
452
+ exports.CARD_MIN_REFRESH_SECONDS = 30;
453
+ /** How long the feed is served from the device cache before it is asked for again - the same on every Joryio SDK. */
454
+ exports.CARD_FEED_TTL_SECONDS = 300;
455
+ const EMPTY_CARD_FEED_JSON = '{"cards":[],"unreadCount":0,"nextCursor":null,"stateScope":"server"}';
456
+ const str = (v) => (typeof v === 'string' ? v : null);
457
+ /** Native JSON (CardFeed.toJson on iOS / Android) -> a CardFeed. A bad answer is the empty feed. */
458
+ function toCardFeed(json) {
459
+ let raw = null;
460
+ try {
461
+ raw = typeof json === 'string' ? JSON.parse(json) : json;
462
+ }
463
+ catch {
464
+ raw = null;
465
+ }
466
+ if (!raw || typeof raw !== 'object')
467
+ raw = {};
468
+ const cards = (Array.isArray(raw.cards) ? raw.cards : [])
469
+ .filter((c) => c && typeof c === 'object' && typeof c.id === 'string')
470
+ .map((c) => ({
471
+ id: c.id,
472
+ campaignId: str(c.campaignId) ?? '',
473
+ variantId: str(c.variantId),
474
+ title: str(c.title),
475
+ body: str(c.body),
476
+ imageUrl: str(c.imageUrl),
477
+ buttonText: str(c.buttonText),
478
+ url: str(c.url),
479
+ pinned: c.pinned === true,
480
+ createdAt: str(c.createdAt) ?? '',
481
+ expiresAt: str(c.expiresAt),
482
+ read: c.read === true,
483
+ clicked: c.clicked === true,
484
+ }));
485
+ return {
486
+ cards,
487
+ unreadCount: typeof raw.unreadCount === 'number' && raw.unreadCount >= 0 ? raw.unreadCount : 0,
488
+ nextCursor: str(raw.nextCursor),
489
+ stateScope: raw.stateScope === 'device' ? 'device' : 'server',
490
+ };
491
+ }
492
+ /** A card or its id. */
493
+ const cardIdOf = (card) => {
494
+ const id = typeof card === 'string' ? card : card && typeof card === 'object' ? card.id : null;
495
+ return typeof id === 'string' && id.length > 0 ? id : null;
496
+ };
497
+ let nativeCardFeedView = null;
498
+ /**
499
+ * `<JoryioCardFeed />` - the person's content cards as a plain scrolling list:
500
+ * the native SDK's own feed view (iOS CardFeedViewController, Android
501
+ * CardFeedView), so paging, the unread dot, the dismiss control, the
502
+ * viewed / read / clicked / dismissed reports (a card at least
503
+ * PLACEMENT_VIEWABLE_FRACTION on screen for IN_APP_DISPLAY_DWELL_MS is viewed
504
+ * then read) and the link rule are the native ones. The look follows the
505
+ * system theme, dark mode included.
506
+ */
507
+ function JoryioCardFeed(props) {
508
+ if (!nativeCardFeedView) {
509
+ const requireNative = ReactNative.requireNativeComponent;
510
+ if (typeof requireNative !== 'function')
511
+ return null;
512
+ nativeCardFeedView = requireNative('JoryioCardFeedView');
513
+ }
514
+ return React.createElement(nativeCardFeedView, {
515
+ style: [{ flex: 1 }, props.style],
516
+ emptyText: props.emptyText,
517
+ pinnedLabel: props.pinnedLabel,
518
+ dismissLabel: props.dismissLabel,
519
+ unreadLabel: props.unreadLabel,
520
+ onCardFeedRender: (e) => {
521
+ const info = e?.nativeEvent || {};
522
+ props.onRender?.({
523
+ cardCount: typeof info.cardCount === 'number' ? info.cardCount : 0,
524
+ unreadCount: typeof info.unreadCount === 'number' ? info.unreadCount : 0,
525
+ });
526
+ },
527
+ onCardDeepLink: (e) => {
528
+ const url = e?.nativeEvent?.url;
529
+ const cardId = e?.nativeEvent?.cardId;
530
+ if (typeof url === 'string')
531
+ props.onDeepLink?.(url, typeof cardId === 'string' ? cardId : '');
532
+ },
533
+ });
534
+ }
259
535
  /** Tell each discarded held call (never throws). */
260
536
  function settleDropped(calls) {
261
537
  for (const call of calls) {
@@ -346,6 +622,10 @@ class JoryioSDK {
346
622
  * decide whether the start-up hold ends with native drawing.
347
623
  */
348
624
  this._inAppHandedToJs = false;
625
+ this._placementListeners = 0;
626
+ this._cardListeners = 0;
627
+ this._linkHandler = null;
628
+ this._linkSubscription = null;
349
629
  this._ready = new Promise((resolve) => {
350
630
  this._markReady = resolve;
351
631
  });
@@ -850,6 +1130,8 @@ class JoryioSDK {
850
1130
  if (forNative.optOut === true)
851
1131
  this._initConfigOptedOut = true;
852
1132
  }
1133
+ // The bridge names itself on every request (D427); not an app option.
1134
+ forNative.sdkWrapperVersion = exports.SDK_VERSION;
853
1135
  try {
854
1136
  await JoryioModule.initialize(sdkKey, apiHost, forNative);
855
1137
  }
@@ -980,8 +1262,10 @@ class JoryioSDK {
980
1262
  *
981
1263
  * Pass the URL that opened the app - `Linking.getInitialURL()` at start
982
1264
  * and each `Linking.addEventListener('url', ...)` event. When it carries the
983
- * `jr_t` token the click redirect added, this visitor is attached to the
984
- * contact the message was sent to. Fire-and-forget; a URL without `jr_t`
1265
+ * `jr_t` token the click redirect added, this app's events are attributed
1266
+ * to the contact the message was sent to. Attribution only: the person is
1267
+ * not identified and this profile is never merged into the contact (only
1268
+ * `identify()` does that). Fire-and-forget; a URL without `jr_t`
985
1269
  * does nothing.
986
1270
  *
987
1271
  * Nothing happens when the person is already identified, has opted out or
@@ -1761,6 +2045,289 @@ class JoryioSDK {
1761
2045
  syncInAppCampaigns() {
1762
2046
  this._dispatch(() => JoryioModule.syncInAppCampaigns?.());
1763
2047
  }
2048
+ // ─── Feature flags (BACKLOG D446) ───────────────────────────────────────
2049
+ //
2050
+ // The native SDK holds the answer and logs exposures; these route to it.
2051
+ // The getters resolve at once with what the device holds - they never wait
2052
+ // for the network - and with the in-code default before initialize(), for a
2053
+ // flag Joryio did not send, for a value of another type, or without
2054
+ // tracking consent. A Promise because every native call crosses the bridge
2055
+ // asynchronously; the names and the wire are the same on all five SDKs.
2056
+ /** A flag's value of any type, or `defaultValue`. The first read in a session logs an exposure. */
2057
+ getFlag(key, defaultValue) {
2058
+ if (!flagKeyOk('getFlag', key))
2059
+ return Promise.resolve(defaultValue);
2060
+ return this._query('getFlag', null, () => {
2061
+ return JoryioModule.getFlag(key, defaultValue ?? null);
2062
+ }).then((r) => (r && typeof r === 'object' && 'value' in r ? r.value : defaultValue));
2063
+ }
2064
+ /** A boolean flag, or `defaultValue` (also for a flag of another type). */
2065
+ getBoolFlag(key, defaultValue) {
2066
+ if (!flagKeyOk('getBoolFlag', key))
2067
+ return Promise.resolve(defaultValue);
2068
+ return this._query('getBoolFlag', defaultValue, () => {
2069
+ return JoryioModule.getBoolFlag(key, !!defaultValue);
2070
+ });
2071
+ }
2072
+ /** A string flag, or `defaultValue`. */
2073
+ getStringFlag(key, defaultValue) {
2074
+ if (!flagKeyOk('getStringFlag', key))
2075
+ return Promise.resolve(defaultValue);
2076
+ return this._query('getStringFlag', defaultValue, () => {
2077
+ return JoryioModule.getStringFlag(key, String(defaultValue ?? ''));
2078
+ });
2079
+ }
2080
+ /** A number flag, or `defaultValue`. */
2081
+ getNumberFlag(key, defaultValue) {
2082
+ if (!flagKeyOk('getNumberFlag', key))
2083
+ return Promise.resolve(defaultValue);
2084
+ return this._query('getNumberFlag', defaultValue, () => {
2085
+ return JoryioModule.getNumberFlag(key, Number(defaultValue));
2086
+ });
2087
+ }
2088
+ /** A JSON flag (object, array or scalar), or `defaultValue`. */
2089
+ getJsonFlag(key, defaultValue) {
2090
+ if (!flagKeyOk('getJsonFlag', key))
2091
+ return Promise.resolve(defaultValue);
2092
+ return this._query('getJsonFlag', null, () => {
2093
+ return JoryioModule.getJsonFlag(key, defaultValue ?? null);
2094
+ }).then((r) => (r && typeof r === 'object' && 'value' in r ? r.value : defaultValue));
2095
+ }
2096
+ /** Every flag held for this person, key -> value. Logs no exposure. */
2097
+ getAllFlags() {
2098
+ return this._query('getAllFlags', {}, () => {
2099
+ return JoryioModule.getAllFlags();
2100
+ });
2101
+ }
2102
+ /** Ask the server now; resolves when the answer is in (or the request failed: the held flags stay). */
2103
+ refreshFlags() {
2104
+ return this._query('refreshFlags', undefined, () => {
2105
+ return JoryioModule.refreshFlags();
2106
+ }).then(() => undefined);
2107
+ }
2108
+ /**
2109
+ * `callback(keys)` is called with the keys whose value changed. Returns an
2110
+ * unsubscribe function. Safe before initialize(): updates start once the
2111
+ * SDK runs.
2112
+ */
2113
+ onFlagsUpdated(callback) {
2114
+ if (typeof callback !== 'function') {
2115
+ warn('onFlagsUpdated() needs a callback function; ignored.');
2116
+ return () => { };
2117
+ }
2118
+ if (!isModuleAvailable || !emitter)
2119
+ return () => { };
2120
+ const guarded = guardedCallback('onFlagsUpdated', callback);
2121
+ const subscription = emitter.addListener('JoryioFlagsUpdated', (event) => {
2122
+ const keys = event?.keys;
2123
+ guarded(Array.isArray(keys) ? keys.filter((k) => typeof k === 'string') : []);
2124
+ });
2125
+ // One native subscription for the module, held until initialize() like
2126
+ // any control call; native ignores a second enable.
2127
+ this._dispatch(() => JoryioModule.enableFlagsUpdates?.());
2128
+ return () => subscription.remove();
2129
+ }
2130
+ /**
2131
+ * The placements for `placementKeys`, to draw with your own components
2132
+ * (or use `<JoryioPlacement placementKey=... />`). Report with
2133
+ * `item.markDisplayed()` once at least half of it was on screen for
2134
+ * IN_APP_DISPLAY_DWELL_MS, `item.markClicked()`, `item.markDismissed()`,
2135
+ * and `placement.markDisplayed()` for a held-out person's empty spot.
2136
+ * Waits for initialize(); resolves `{}` without the native module.
2137
+ */
2138
+ getPlacements(placementKeys) {
2139
+ const keys = Array.isArray(placementKeys) ? placementKeys.filter((k) => typeof k === 'string') : [];
2140
+ // A read: waits for initialize() like the other queries.
2141
+ return this._query('getPlacements', '{}', () => {
2142
+ return JoryioModule.getPlacements(keys);
2143
+ }).then(toPlacements);
2144
+ }
2145
+ /** Ask the server again (all placements on screen when no keys). At most once per key per PLACEMENT_MIN_REFRESH_SECONDS. */
2146
+ refreshPlacements(placementKeys) {
2147
+ this._dispatch(() => JoryioModule.refreshPlacements?.(Array.isArray(placementKeys) ? placementKeys : null));
2148
+ }
2149
+ /**
2150
+ * Called with the placements whose content changed. Returns an unsubscribe.
2151
+ * An app with its own push messaging handler should call
2152
+ * refreshPlacements() on a `jry_sync: "placements"` data message; the
2153
+ * native SDKs handle it themselves otherwise.
2154
+ */
2155
+ onPlacementsUpdated(callback) {
2156
+ if (typeof callback !== 'function' || !isModuleAvailable || !emitter)
2157
+ return () => { };
2158
+ const subscription = emitter.addListener('JoryioPlacementsUpdated', (e) => {
2159
+ try {
2160
+ callback(toPlacements(e?.json));
2161
+ }
2162
+ catch (error) {
2163
+ warn(`onPlacementsUpdated callback threw: ${String(error)}`);
2164
+ }
2165
+ });
2166
+ this._placementListeners += 1;
2167
+ this._dispatch(() => JoryioModule.enablePlacementsUpdates?.());
2168
+ let removed = false;
2169
+ return () => {
2170
+ if (removed)
2171
+ return;
2172
+ removed = true;
2173
+ subscription.remove();
2174
+ this._placementListeners = Math.max(0, this._placementListeners - 1);
2175
+ if (this._placementListeners === 0)
2176
+ this._dispatch(() => JoryioModule.disablePlacementsUpdates?.());
2177
+ };
2178
+ }
2179
+ /**
2180
+ * The person's content cards - pinned first, newest first - with the unread
2181
+ * count for a badge, from the native SDK's cache for CARD_FEED_TTL_SECONDS.
2182
+ * Pass a feed's `nextCursor` as `{ cursor }` for the next page (the native
2183
+ * SDK adds it to the cached feed). Draw it with `<JoryioCardFeed />`, or
2184
+ * yourself and report with markCardViewed / markCardRead /
2185
+ * markCardClicked / dismissCard. Waits for initialize(); resolves the empty
2186
+ * feed without the native module.
2187
+ */
2188
+ getCards(options) {
2189
+ const cursor = typeof options?.cursor === 'string' && options.cursor.length > 0 ? options.cursor : null;
2190
+ // A read: waits for initialize() like the other queries.
2191
+ return this._query('getCards', EMPTY_CARD_FEED_JSON, () => {
2192
+ return JoryioModule.getCards(cursor);
2193
+ }).then(toCardFeed);
2194
+ }
2195
+ /**
2196
+ * Unread cards, from the native SDK's cache (never a network call): the
2197
+ * badge. A Promise here because every React Native read crosses the bridge;
2198
+ * the native SDKs answer synchronously.
2199
+ */
2200
+ getUnreadCardCount() {
2201
+ return this._query('getUnreadCardCount', 0, () => {
2202
+ return JoryioModule.getUnreadCardCount();
2203
+ }).then((n) => (typeof n === 'number' && n >= 0 ? n : 0));
2204
+ }
2205
+ /** The card was on screen (`viewed`). Once per card; `<JoryioCardFeed />` does it itself. */
2206
+ markCardViewed(card) {
2207
+ const id = cardIdOf(card);
2208
+ if (id)
2209
+ this._dispatch(() => JoryioModule.markCardViewed?.(id), 'data');
2210
+ }
2211
+ /** The person read the card (`read`): it stops counting as unread at once. */
2212
+ markCardRead(card) {
2213
+ const id = cardIdOf(card);
2214
+ if (id)
2215
+ this._dispatch(() => JoryioModule.markCardRead?.(id), 'data');
2216
+ }
2217
+ /** The person tapped the card or its button (`clicked`, which also marks it read). Open its url yourself. */
2218
+ markCardClicked(card) {
2219
+ const id = cardIdOf(card);
2220
+ if (id)
2221
+ this._dispatch(() => JoryioModule.markCardClicked?.(id), 'data');
2222
+ }
2223
+ /** The person removed the card (`dismissed`): it leaves the feed at once and never comes back. */
2224
+ dismissCard(card) {
2225
+ const id = cardIdOf(card);
2226
+ if (id)
2227
+ this._dispatch(() => JoryioModule.dismissCard?.(id), 'data');
2228
+ }
2229
+ /**
2230
+ * Ask the server for the feed again. At most once per
2231
+ * CARD_MIN_REFRESH_SECONDS; extra calls coalesce. An app with its own push
2232
+ * messaging handler calls this on a `jry_sync: "cards"` data message; the
2233
+ * native SDKs handle it themselves otherwise.
2234
+ */
2235
+ refreshCards() {
2236
+ this._dispatch(() => JoryioModule.refreshCards?.());
2237
+ }
2238
+ /** Called with the whole feed whenever it changes (a refresh, a report, an identity change). Returns an unsubscribe. */
2239
+ onCardsUpdated(callback) {
2240
+ if (typeof callback !== 'function' || !isModuleAvailable || !emitter)
2241
+ return () => { };
2242
+ const subscription = emitter.addListener('JoryioCardsUpdated', (e) => {
2243
+ try {
2244
+ callback(toCardFeed(e?.json));
2245
+ }
2246
+ catch (error) {
2247
+ warn(`onCardsUpdated callback threw: ${String(error)}`);
2248
+ }
2249
+ });
2250
+ this._cardListeners += 1;
2251
+ this._dispatch(() => JoryioModule.enableCardsUpdates?.());
2252
+ let removed = false;
2253
+ return () => {
2254
+ if (removed)
2255
+ return;
2256
+ removed = true;
2257
+ subscription.remove();
2258
+ this._cardListeners = Math.max(0, this._cardListeners - 1);
2259
+ if (this._cardListeners === 0)
2260
+ this._dispatch(() => JoryioModule.disableCardsUpdates?.());
2261
+ };
2262
+ }
2263
+ /**
2264
+ * Receive EVERY link the native SDK is about to open - an in-app message
2265
+ * button or link, a `<JoryioPlacement />` button, a `<JoryioCardFeed />`
2266
+ * tap, an iOS push tap - before it opens: http(s) links and app deep links
2267
+ * (`myapp://cart`) alike, with where it came from (`link.source`) and the
2268
+ * ids that go with it. Return true to take the link over (navigate in your
2269
+ * app), false to let the native SDK open it as it does without a handler -
2270
+ * http(s) to the system (or your universal-link handling with
2271
+ * `forwardUniversalLinks` on iOS), an app deep link to the component's
2272
+ * `onDeepLink`. A Promise decides later. A refused scheme (javascript:,
2273
+ * data:, intent:, ...) never reaches it. One handler: a second call
2274
+ * replaces the first. Works before initialize(). Same name on iOS,
2275
+ * Android, web and Unity (`SetLinkHandler`).
2276
+ */
2277
+ setLinkHandler(handler) {
2278
+ if (typeof handler !== 'function') {
2279
+ warn('setLinkHandler() needs a function; use clearLinkHandler() to remove one');
2280
+ return;
2281
+ }
2282
+ this._linkHandler = handler;
2283
+ if (!isModuleAvailable || !emitter)
2284
+ return;
2285
+ if (!this._linkSubscription) {
2286
+ this._linkSubscription = emitter.addListener('JoryioLink', (e) => this._onLink(e));
2287
+ }
2288
+ // Not held for initialize(): the native handler is app-wide and works before it.
2289
+ JoryioModule.enableLinkHandler?.();
2290
+ }
2291
+ /** Remove the handler set with setLinkHandler: links open as they do without one. */
2292
+ clearLinkHandler() {
2293
+ this._linkHandler = null;
2294
+ this._linkSubscription?.remove();
2295
+ this._linkSubscription = null;
2296
+ if (isModuleAvailable)
2297
+ JoryioModule.disableLinkHandler?.();
2298
+ }
2299
+ /** A link from native: ask the handler, then tell native whether it was taken. */
2300
+ _onLink(e) {
2301
+ const linkId = e?.linkId;
2302
+ if (typeof linkId !== 'string')
2303
+ return;
2304
+ const complete = (handled) => JoryioModule.completeLink?.(linkId, handled === true);
2305
+ const handler = this._linkHandler;
2306
+ const link = toLink(e);
2307
+ if (!handler || !link) {
2308
+ complete(false);
2309
+ return;
2310
+ }
2311
+ let result;
2312
+ try {
2313
+ result = handler(link);
2314
+ }
2315
+ catch (error) {
2316
+ // A throwing handler declines: the link still opens.
2317
+ warn(`setLinkHandler handler threw; the link opens as without one: ${String(error)}`);
2318
+ complete(false);
2319
+ return;
2320
+ }
2321
+ if (result && typeof result.then === 'function') {
2322
+ result.then(complete, (error) => {
2323
+ warn(`setLinkHandler handler rejected; the link opens as without one: ${String(error)}`);
2324
+ complete(false);
2325
+ });
2326
+ }
2327
+ else {
2328
+ complete(result);
2329
+ }
2330
+ }
1764
2331
  /**
1765
2332
  * Forget which in-app campaigns have already been shown on this device.
1766
2333
  *