@outerjoyn/react-native 1.1.0

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.
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Offline Cache — Non-sensitive data caching for the OuterJoyn RN SDK
3
+ *
4
+ * Uses the StorageAdapter interface (defaults to AsyncStorage, MMKV injectable).
5
+ *
6
+ * Caches:
7
+ * - Profile name, tier, program branding (TTL: 24h)
8
+ * - Brand logos and colors (TTL: 24h)
9
+ * - Last-known balance (TTL: 5min, shown with staleness indicator)
10
+ *
11
+ * Does NOT cache:
12
+ * - Full transaction details with financial amounts
13
+ * - Redemption eligibility / approval status
14
+ *
15
+ * Does NOT queue mutations:
16
+ * - earn/redeem/exchange/pay require server validation
17
+ * - Queuing financial operations offline is unsafe
18
+ */
19
+
20
+ import type { StorageAdapter, LinkedProgram, BrandConfig } from './types';
21
+
22
+ // =============================================================================
23
+ // Constants
24
+ // =============================================================================
25
+
26
+ const CACHE_VERSION = 1;
27
+ const PREFIX = 'oj_sdk_cache_';
28
+
29
+ const TTL = {
30
+ profile: 24 * 60 * 60 * 1000, // 24 hours
31
+ programs: 24 * 60 * 60 * 1000, // 24 hours
32
+ brandConfig: 24 * 60 * 60 * 1000, // 24 hours
33
+ balances: 5 * 60 * 1000, // 5 minutes
34
+ };
35
+
36
+ // =============================================================================
37
+ // Types
38
+ // =============================================================================
39
+
40
+ interface CacheEntry<T> {
41
+ data: T;
42
+ timestamp: number;
43
+ version: number;
44
+ }
45
+
46
+ export interface CachedState {
47
+ linkedPrograms: LinkedProgram[] | null;
48
+ brandConfig: BrandConfig | null;
49
+ lastUpdated: number | null;
50
+ }
51
+
52
+ // =============================================================================
53
+ // Offline Cache
54
+ // =============================================================================
55
+
56
+ export class OfflineCache {
57
+ private storage: StorageAdapter;
58
+ private memberId: string;
59
+
60
+ constructor(storage: StorageAdapter, memberId: string) {
61
+ this.storage = storage;
62
+ this.memberId = memberId;
63
+ }
64
+
65
+ /** Save linked programs to cache */
66
+ async savePrograms(programs: LinkedProgram[]): Promise<void> {
67
+ await this.set('programs', programs);
68
+ }
69
+
70
+ /** Load cached programs (returns null if expired or missing) */
71
+ async loadPrograms(): Promise<LinkedProgram[] | null> {
72
+ return this.get<LinkedProgram[]>('programs', TTL.programs);
73
+ }
74
+
75
+ /** Save brand config */
76
+ async saveBrandConfig(config: BrandConfig): Promise<void> {
77
+ await this.set('brand_config', config);
78
+ }
79
+
80
+ /** Load cached brand config */
81
+ async loadBrandConfig(): Promise<BrandConfig | null> {
82
+ return this.get<BrandConfig>('brand_config', TTL.brandConfig);
83
+ }
84
+
85
+ /** Get the full cached state (for offline display) */
86
+ async getCachedState(): Promise<CachedState> {
87
+ const [programs, brandConfig] = await Promise.all([
88
+ this.loadPrograms(),
89
+ this.loadBrandConfig(),
90
+ ]);
91
+
92
+ // Get the most recent timestamp
93
+ let lastUpdated: number | null = null;
94
+ try {
95
+ const raw = await this.storage.get(this.key('programs'));
96
+ if (raw) {
97
+ const entry: CacheEntry<any> = JSON.parse(raw);
98
+ lastUpdated = entry.timestamp;
99
+ }
100
+ } catch { /* ignore */ }
101
+
102
+ return { linkedPrograms: programs, brandConfig, lastUpdated };
103
+ }
104
+
105
+ /** Clear all cached data for this member */
106
+ async clear(): Promise<void> {
107
+ await Promise.all([
108
+ this.storage.remove(this.key('programs')),
109
+ this.storage.remove(this.key('brand_config')),
110
+ ]);
111
+ }
112
+
113
+ // ==========================================================================
114
+ // Internal
115
+ // ==========================================================================
116
+
117
+ private key(suffix: string): string {
118
+ return `${PREFIX}${this.memberId}_${suffix}`;
119
+ }
120
+
121
+ private async get<T>(suffix: string, ttl: number): Promise<T | null> {
122
+ try {
123
+ const raw = await this.storage.get(this.key(suffix));
124
+ if (!raw) return null;
125
+
126
+ const entry: CacheEntry<T> = JSON.parse(raw);
127
+ if (entry.version !== CACHE_VERSION) return null;
128
+ if (Date.now() - entry.timestamp > ttl) return null;
129
+
130
+ return entry.data;
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+
136
+ private async set<T>(suffix: string, data: T): Promise<void> {
137
+ const entry: CacheEntry<T> = {
138
+ data,
139
+ timestamp: Date.now(),
140
+ version: CACHE_VERSION,
141
+ };
142
+ try {
143
+ await this.storage.set(this.key(suffix), JSON.stringify(entry));
144
+ } catch {
145
+ // storage full or unavailable — drop silently
146
+ }
147
+ }
148
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Core types for @outerjoyn/react-native SDK
3
+ *
4
+ * Derived from API response schemas documented in RN-SDK-REFACTOR-PLAN.md.
5
+ * These are the source of truth for the RN SDK's state model.
6
+ */
7
+
8
+ // =============================================================================
9
+ // API Response Types
10
+ // =============================================================================
11
+
12
+ export interface CreateSessionResponse {
13
+ token: string;
14
+ status: 'ready' | 'link_required';
15
+ expires_at: string;
16
+ member_context?: {
17
+ member_id: number;
18
+ display_name?: string;
19
+ linked_programs?: Array<{ program_name: string; currency_name: string }>;
20
+ };
21
+ payable_balances?: PayableBalance[];
22
+ }
23
+
24
+ export interface SessionContextResponse {
25
+ status: string;
26
+ member_id: number | null;
27
+ display_name?: string;
28
+ business_unit_id: number;
29
+ scopes: string[];
30
+ expires_at: string;
31
+ payable_balances?: PayableBalance[];
32
+ brand_config?: BrandConfig;
33
+ returning_user?: boolean;
34
+ }
35
+
36
+ export interface PayableBalance {
37
+ // Go gateway returns camelCase
38
+ memberCurrencyId?: number;
39
+ currencyId?: number;
40
+ currencyName?: string;
41
+ currencyCode?: string;
42
+ brandName?: string;
43
+ brandLogoUrl?: string | null;
44
+ brandColor?: string | null;
45
+ balance?: number;
46
+ pointValueAmount?: number;
47
+ valueAmount?: number;
48
+ partnershipId?: number;
49
+ // Express returns snake_case
50
+ member_currency_id?: number;
51
+ currency_id?: number;
52
+ currency_name?: string;
53
+ currency_code?: string;
54
+ brand_name?: string;
55
+ brand_logo_url?: string | null;
56
+ brand_color?: string | null;
57
+ point_value_amount?: number;
58
+ value_amount?: number;
59
+ partnership_id?: number;
60
+ }
61
+
62
+ export interface BrandConfig {
63
+ theme?: Partial<SDKTheme>;
64
+ enabled?: Record<string, boolean>;
65
+ availability?: Record<string, any>;
66
+ logo_url?: string;
67
+ brand_name?: string;
68
+ }
69
+
70
+ // =============================================================================
71
+ // Client-Side Models
72
+ // =============================================================================
73
+
74
+ /** Normalized linked program — what components consume */
75
+ export interface LinkedProgram {
76
+ id: string;
77
+ brandName: string;
78
+ membershipId: string;
79
+ pointsBalance: number;
80
+ currencyName: string;
81
+ currencyCode: string;
82
+ iconColor: string;
83
+ conversionRate: number;
84
+ memberCurrencyId: number | string;
85
+ currencyId: number | string;
86
+ pointValueAmount: number;
87
+ brandLogoUrl: string | null;
88
+ brandColor: string | null;
89
+ /** Partnership ID — used for disconnect. May be undefined for demo programs. */
90
+ partnershipId?: number;
91
+ }
92
+
93
+ // =============================================================================
94
+ // Theme
95
+ // =============================================================================
96
+
97
+ export interface SDKTheme {
98
+ primaryColor?: string;
99
+ accentColor?: string;
100
+ backgroundColor?: string;
101
+ surfaceColor?: string;
102
+ textColor?: string;
103
+ mutedTextColor?: string;
104
+ borderColor?: string;
105
+ borderRadius?: number | string;
106
+ colorScheme?: 'light' | 'dark' | 'auto';
107
+ fontFamily?: string;
108
+ buttonStyle?: 'filled' | 'outline' | 'soft';
109
+ shadow?: 'none' | 'sm' | 'md' | 'lg';
110
+ spacing?: 'compact' | 'comfortable' | 'spacious';
111
+ }
112
+
113
+ export interface AppearanceConfig {
114
+ colors?: {
115
+ primary?: string;
116
+ accent?: string;
117
+ background?: string;
118
+ surface?: string;
119
+ text?: string;
120
+ border?: string;
121
+ success?: string;
122
+ error?: string;
123
+ };
124
+ borderRadius?: number;
125
+ fontFamily?: string;
126
+ }
127
+
128
+ // =============================================================================
129
+ // Provider
130
+ // =============================================================================
131
+
132
+ export interface IdentityHints {
133
+ phone?: string;
134
+ email?: string;
135
+ }
136
+
137
+ export interface StorageAdapter {
138
+ get(key: string): Promise<string | null>;
139
+ set(key: string, value: string): Promise<void>;
140
+ remove(key: string): Promise<void>;
141
+ }
142
+
143
+ export interface OuterJoynProviderProps {
144
+ /** ojsdk_* session token from your backend (required) */
145
+ sessionToken: string;
146
+ /** API base URL (defaults to https://api.outerjoyn.com) */
147
+ apiBaseUrl?: string;
148
+ /** Appearance overrides (optional — uses platform brand_config if not set) */
149
+ appearance?: AppearanceConfig;
150
+ /** Identity hints for returning Joyn Wallet user detection (optional) */
151
+ identityHints?: IdentityHints;
152
+ /** Storage adapter (defaults to AsyncStorage) */
153
+ storageAdapter?: StorageAdapter;
154
+ /** Locale override (auto-detected from device if not set) */
155
+ locale?: string;
156
+ /** Called when SDK is initialized and ready */
157
+ onReady?: (context: SessionContextResponse) => void;
158
+ /** Called on initialization error */
159
+ onError?: (error: Error) => void;
160
+ /** Enable real-time SSE updates (default: false). Only enable when backend supports /api/sdk/events. */
161
+ realTimeUpdates?: boolean;
162
+ /** Children */
163
+ children: React.ReactNode;
164
+ }
165
+
166
+ export interface OuterJoynContextValue {
167
+ // State
168
+ isReady: boolean;
169
+ isLinked: boolean;
170
+ isReturningUser: boolean;
171
+ linkedPrograms: LinkedProgram[];
172
+ /** Programs linked in Joyn Wallet or other apps, portable to this BU via ConsumerIdentity. */
173
+ portablePrograms: LinkedProgram[];
174
+ /** Cross-BU consumer identity ID, if resolved. */
175
+ consumerIdentityId: string | null;
176
+ totalAvailablePoints: number;
177
+ totalAvailableValue: number;
178
+ loading: boolean;
179
+ error: Error | null;
180
+ demoMode: boolean;
181
+ brandConfig: BrandConfig | null;
182
+
183
+ // Actions
184
+ refreshBalances: () => Promise<void>;
185
+ openConnect: (opts?: { institutionId?: string }) => void;
186
+ openExchange: (opts?: { sourceCurrencyId?: number }) => void;
187
+ openRedeem: (opts?: { category?: string }) => void;
188
+ openPay: (opts: { orderTotalCents: number; merchantOrderId?: string }) => void;
189
+ openAccount: () => void;
190
+ closeSheet: () => void;
191
+ unlinkProgram: (programId: string) => void;
192
+
193
+ // Session
194
+ sessionToken: string;
195
+ sessionStatus: 'idle' | 'loading' | 'ready' | 'link_required' | 'error';
196
+
197
+ // Shared API client (fix #11 — screens use this instead of creating their own)
198
+ apiClient: import('./api-client').APIClient | null;
199
+ apiBaseUrl: string;
200
+
201
+ // i18n
202
+ t: (key: string, params?: Record<string, string | number>) => string;
203
+ }
204
+
205
+ // =============================================================================
206
+ // Sheet State
207
+ // =============================================================================
208
+
209
+ export type SheetType = 'connect' | 'pay' | 'exchange' | 'redeem' | 'account' | null;
210
+
211
+ export interface SheetState {
212
+ activeSheet: SheetType;
213
+ sheetProps: Record<string, any>;
214
+ }
@@ -0,0 +1,2 @@
1
+ /** Single source of truth for SDK version. Imported by api-client and analytics. */
2
+ export const SDK_VERSION = '1.0.0';
package/src/html.ts ADDED
@@ -0,0 +1,154 @@
1
+ import type { OuterJoynConfig } from './types';
2
+
3
+ const SDK_URL = 'https://sdk.outerjoyn.com/v1/outerjoyn.js';
4
+
5
+ /**
6
+ * Generate HTML for a WebView that loads the OuterJoyn SDK and opens a specific widget.
7
+ *
8
+ * The SDK's postmessage.ts already detects `window.ReactNativeWebView` and calls
9
+ * `ReactNativeWebView.postMessage()` for events. This HTML bridges the gap by
10
+ * initializing the SDK and forwarding lifecycle events back to the native layer.
11
+ */
12
+ export function generateWidgetHTML(
13
+ module: string,
14
+ config: OuterJoynConfig,
15
+ options?: Record<string, any>,
16
+ ): string {
17
+ const themeJSON = config.theme ? JSON.stringify(config.theme) : 'undefined';
18
+ const optionsJSON = options ? JSON.stringify(options) : '{}';
19
+ const apiBaseUrl = config.apiBaseUrl || 'https://api.outerjoyn.com';
20
+
21
+ return `
22
+ <!DOCTYPE html>
23
+ <html>
24
+ <head>
25
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
26
+ <style>
27
+ * { margin: 0; padding: 0; box-sizing: border-box; }
28
+ html, body { width: 100%; height: 100%; overflow: hidden; background: transparent; }
29
+ #widget-container { width: 100%; height: 100%; }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <div id="widget-container"></div>
34
+ <script src="${SDK_URL}"><\/script>
35
+ <script>
36
+ function sendToNative(msg) {
37
+ if (window.ReactNativeWebView) {
38
+ window.ReactNativeWebView.postMessage(JSON.stringify(msg));
39
+ }
40
+ }
41
+
42
+ function initWidget() {
43
+ try {
44
+ var oj = window.OuterJoyn;
45
+ if (!oj) {
46
+ sendToNative({ type: 'sdk_error', error: { code: 'SDK_LOAD_FAILED', message: 'OuterJoyn SDK not available' } });
47
+ return;
48
+ }
49
+
50
+ oj.init({
51
+ sessionToken: ${JSON.stringify(config.sessionToken)},
52
+ apiBaseUrl: ${JSON.stringify(apiBaseUrl)},
53
+ theme: ${themeJSON}
54
+ }).then(function() {
55
+ sendToNative({ type: 'sdk_ready' });
56
+
57
+ var mod = oj.${module};
58
+ if (!mod || typeof mod.open !== 'function') {
59
+ sendToNative({ type: 'sdk_error', error: { code: 'MODULE_NOT_FOUND', message: 'Module ${module} not available' } });
60
+ return;
61
+ }
62
+
63
+ mod.open(Object.assign({
64
+ container: document.getElementById('widget-container'),
65
+ onSuccess: function(result) { sendToNative({ type: 'sdk_success', result: result }); },
66
+ onError: function(err) { sendToNative({ type: 'sdk_error', error: err }); },
67
+ onClose: function() { sendToNative({ type: 'sdk_close' }); },
68
+ onEvent: function(name, meta) { sendToNative({ type: 'sdk_event', event: name, data: meta }); }
69
+ }, ${optionsJSON}));
70
+ }).catch(function(err) {
71
+ sendToNative({ type: 'sdk_error', error: { code: 'INIT_FAILED', message: err.message || String(err) } });
72
+ });
73
+ } catch (e) {
74
+ sendToNative({ type: 'sdk_error', error: { code: 'INIT_FAILED', message: e.message || String(e) } });
75
+ }
76
+ }
77
+
78
+ if (window.OuterJoyn) {
79
+ initWidget();
80
+ } else {
81
+ document.querySelector('script[src*="outerjoyn"]').addEventListener('load', initWidget);
82
+ }
83
+ <\/script>
84
+ </body>
85
+ </html>`;
86
+ }
87
+
88
+ /**
89
+ * Generate HTML for the promotions widget (uses configure + render pattern).
90
+ */
91
+ export function generatePromotionsHTML(
92
+ config: OuterJoynConfig,
93
+ arrayId: string,
94
+ layout?: string,
95
+ ): string {
96
+ const apiBaseUrl = config.apiBaseUrl || 'https://api.outerjoyn.com';
97
+ const themeJSON = config.theme ? JSON.stringify(config.theme) : 'undefined';
98
+
99
+ return `
100
+ <!DOCTYPE html>
101
+ <html>
102
+ <head>
103
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
104
+ <style>
105
+ * { margin: 0; padding: 0; box-sizing: border-box; }
106
+ html, body { width: 100%; height: 100%; overflow: auto; background: transparent; }
107
+ #promo-container { width: 100%; min-height: 100%; }
108
+ </style>
109
+ </head>
110
+ <body>
111
+ <div id="promo-container"></div>
112
+ <script src="${SDK_URL}"><\/script>
113
+ <script>
114
+ function sendToNative(msg) {
115
+ if (window.ReactNativeWebView) {
116
+ window.ReactNativeWebView.postMessage(JSON.stringify(msg));
117
+ }
118
+ }
119
+
120
+ function initPromo() {
121
+ try {
122
+ var oj = window.OuterJoyn;
123
+ if (!oj || !oj.promotions) {
124
+ sendToNative({ type: 'sdk_error', error: { code: 'SDK_LOAD_FAILED', message: 'OuterJoyn SDK not available' } });
125
+ return;
126
+ }
127
+
128
+ oj.promotions.configure({
129
+ sessionToken: ${JSON.stringify(config.sessionToken)},
130
+ apiBaseUrl: ${JSON.stringify(apiBaseUrl)},
131
+ theme: ${themeJSON}
132
+ });
133
+
134
+ oj.promotions.render({
135
+ container: document.getElementById('promo-container'),
136
+ arrayId: ${JSON.stringify(arrayId)},
137
+ layout: ${JSON.stringify(layout || 'carousel')}
138
+ });
139
+
140
+ sendToNative({ type: 'sdk_ready' });
141
+ } catch (e) {
142
+ sendToNative({ type: 'sdk_error', error: { code: 'INIT_FAILED', message: e.message || String(e) } });
143
+ }
144
+ }
145
+
146
+ if (window.OuterJoyn) {
147
+ initPromo();
148
+ } else {
149
+ document.querySelector('script[src*="outerjoyn"]').addEventListener('load', initPromo);
150
+ }
151
+ <\/script>
152
+ </body>
153
+ </html>`;
154
+ }
package/src/index.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @outerjoyn/react-native — Drop-in loyalty SDK for React Native
3
+ *
4
+ * Works in Expo Go — no native modules required.
5
+ *
6
+ * ## Quick Start
7
+ * ```tsx
8
+ * import { OuterJoynProvider, useOuterJoyn, LoyaltyBanner } from '@outerjoyn/react-native';
9
+ *
10
+ * // Wrap your app
11
+ * <OuterJoynProvider sessionToken={token}>
12
+ * <App />
13
+ * </OuterJoynProvider>
14
+ *
15
+ * // Show a banner on any screen
16
+ * <LoyaltyBanner />
17
+ *
18
+ * // Pay with points at checkout
19
+ * const { openPay } = useOuterJoyn();
20
+ * <Button onPress={() => openPay({ orderTotalCents: 4999 })} title="Pay with Points" />
21
+ * ```
22
+ */
23
+
24
+ // Provider + Hook (Phase 1)
25
+ export { OuterJoynProvider } from './OuterJoynProvider';
26
+ export { useOuterJoyn } from './useOuterJoyn';
27
+
28
+ // Sheet components — modal bottom sheets (Phase 2)
29
+ export { PaySheet, ConnectSheet, ExchangeSheet, RedeemSheet, AccountSheet } from './widgets';
30
+
31
+ // Inline components — pure RN, no WebView (Phase 3)
32
+ export {
33
+ LoyaltyBanner,
34
+ BalanceSummary,
35
+ CheckoutPointsApply,
36
+ LoyaltyProfileSection,
37
+ PostCheckoutSavePrompt,
38
+ } from './components';
39
+
40
+ export type {
41
+ LoyaltyBannerProps,
42
+ BalanceSummaryProps,
43
+ CheckoutPointsApplyProps,
44
+ CheckoutPointsApplyHandle,
45
+ AppliedPoints,
46
+ PointsChangedPayload,
47
+ LoyaltyProfileSectionProps,
48
+ PostCheckoutSavePromptProps,
49
+ SaveResult,
50
+ } from './components';
51
+
52
+ // Full-screen native screens (Phase 4)
53
+ export { ConnectScreen, ExchangeScreen, RedeemScreen, AccountScreen } from './screens';
54
+ export type { ConnectScreenProps, ConnectResult as ConnectScreenResult, ExchangeScreenProps, RedeemScreenProps, AccountScreenProps } from './screens';
55
+
56
+ // Promotions (existing)
57
+ export { PromotionsView } from './PromotionsView';
58
+
59
+ // Base component (for custom/advanced usage)
60
+ export { OuterJoynSheet } from './OuterJoynSheet';
61
+
62
+ // Imperative API (Tier 4)
63
+ export { OuterJoynSDK, OuterJoynImperativeSheets } from './OuterJoynSDK';
64
+ export type {
65
+ ImperativeSDKConfig,
66
+ ImperativeWidgetType,
67
+ ImperativePayOptions,
68
+ ImperativePresentOptions,
69
+ ImperativePresentResult,
70
+ } from './OuterJoynSDK';
71
+
72
+ // Core
73
+ export { APIClient, SDKError } from './core/api-client';
74
+ export { OuterJoynErrorBoundary } from './core/ErrorBoundary';
75
+ export { SDK_VERSION } from './core/version';
76
+
77
+ // Types
78
+ export type {
79
+ LinkedProgram,
80
+ BrandConfig,
81
+ PayableBalance,
82
+ AppearanceConfig,
83
+ IdentityHints,
84
+ StorageAdapter,
85
+ OuterJoynProviderProps,
86
+ OuterJoynContextValue,
87
+ } from './core/types';
88
+
89
+ export type {
90
+ OuterJoynConfig,
91
+ OuterJoynTheme,
92
+ PaySheetProps,
93
+ ConnectSheetProps,
94
+ ExchangeSheetProps,
95
+ RedeemSheetProps,
96
+ WalletPassButtonProps,
97
+ PromotionsViewProps,
98
+ PayResult,
99
+ ConnectResult,
100
+ ExchangeResult,
101
+ RedeemResult,
102
+ } from './types';