pa-sdk-react-native 0.0.0-stage → 3.0.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +268 -2
  3. package/lib/api.d.ts +88 -0
  4. package/lib/api.js +163 -0
  5. package/lib/confirm.d.ts +66 -0
  6. package/lib/confirm.js +359 -0
  7. package/lib/errors.d.ts +38 -0
  8. package/lib/errors.generated.d.ts +13 -0
  9. package/lib/errors.generated.js +63 -0
  10. package/lib/errors.js +80 -0
  11. package/lib/index.d.ts +43 -0
  12. package/lib/index.js +94 -0
  13. package/lib/init.d.ts +47 -0
  14. package/lib/init.js +96 -0
  15. package/lib/locales.d.ts +36 -0
  16. package/lib/locales.generated.d.ts +22 -0
  17. package/lib/locales.generated.js +134 -0
  18. package/lib/locales.js +100 -0
  19. package/lib/poll.d.ts +61 -0
  20. package/lib/poll.js +172 -0
  21. package/lib/threeDs.d.ts +59 -0
  22. package/lib/threeDs.js +64 -0
  23. package/lib/threeDsHost.d.ts +17 -0
  24. package/lib/threeDsHost.js +159 -0
  25. package/lib/tokenize.d.ts +22 -0
  26. package/lib/tokenize.js +50 -0
  27. package/lib/types.d.ts +128 -0
  28. package/lib/types.js +17 -0
  29. package/lib/validator.d.ts +71 -0
  30. package/lib/validator.js +191 -0
  31. package/locales/en-US.json +30 -0
  32. package/locales/ms-MY.json +30 -0
  33. package/locales/zh-CN.json +30 -0
  34. package/locales/zh-TW.json +30 -0
  35. package/native/android/build.gradle +49 -0
  36. package/native/android/src/main/AndroidManifest.xml +41 -0
  37. package/native/android/src/main/java/com/pasdk/reactnative/PaSdk3dsActivity.kt +250 -0
  38. package/native/android/src/main/java/com/pasdk/reactnative/PaSdk3dsModule.kt +110 -0
  39. package/native/android/src/main/java/com/pasdk/reactnative/PaSdkReactNativePackage.kt +27 -0
  40. package/native/ios/PaSdk3ds.swift +311 -0
  41. package/native/ios/PaSdk3dsModule.m +47 -0
  42. package/pa-sdk-react-native.podspec +23 -0
  43. package/package.json +46 -3
  44. package/scripts/generate-errors.js +86 -0
  45. package/scripts/generate-locales.js +95 -0
package/lib/poll.js ADDED
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * AppState-aware polling (RN-20 / COM-06, the app analog of WEB-50/51).
4
+ *
5
+ * Schedule: 2s x 15, then 5s x 12 (CONF-08 budget). While the app is
6
+ * backgrounded (user switched to a banking app during 3DS, screen off, etc.)
7
+ * the poll timer is suspended and suspended time does NOT consume the
8
+ * budget — the budget is a number of polls, not wall-clock time. On return
9
+ * to the foreground polling resumes where it stopped.
10
+ *
11
+ * On budget exhaustion the poller resolves undefined and the caller maps
12
+ * that to `processing` — never `failed` (COM-06).
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AppStateAwarePoller = exports.DEFAULT_POLLER_OPTIONS = void 0;
16
+ exports.pollUntil = pollUntil;
17
+ const react_native_1 = require("react-native");
18
+ const types_1 = require("./types");
19
+ exports.DEFAULT_POLLER_OPTIONS = {
20
+ fastIntervalMs: types_1.POLL_FAST_INTERVAL_MS,
21
+ fastAttempts: types_1.POLL_FAST_ATTEMPTS,
22
+ slowIntervalMs: types_1.POLL_SLOW_INTERVAL_MS,
23
+ slowAttempts: types_1.POLL_SLOW_ATTEMPTS,
24
+ };
25
+ class AppStateAwarePoller {
26
+ constructor(options = {}) {
27
+ this.check = null;
28
+ this.timer = null;
29
+ this.appStateSubscription = null;
30
+ this.completed = 0;
31
+ this.stopped = true;
32
+ this.inFlight = false;
33
+ this.resolveRun = null;
34
+ this.lastAppState = 'active';
35
+ this.handleAppStateChange = (state) => {
36
+ const previous = this.lastAppState;
37
+ this.lastAppState = state;
38
+ if (this.stopped || !this.check) {
39
+ return;
40
+ }
41
+ if (previous === 'active' && state !== 'active') {
42
+ // Backgrounded: cancel the pending timer. The budget is polls, not
43
+ // time, so nothing is consumed while suspended.
44
+ if (this.timer != null) {
45
+ clearTimeout(this.timer);
46
+ this.timer = null;
47
+ }
48
+ }
49
+ else if (state === 'active' && previous !== 'active') {
50
+ // Foreground again: resume immediately — the pending interval already
51
+ // elapsed while we were away, and suspension did not cost a poll.
52
+ this.scheduleNext(0);
53
+ }
54
+ };
55
+ this.options = { ...exports.DEFAULT_POLLER_OPTIONS, ...options };
56
+ }
57
+ /** Total polls across the fast and slow phases. */
58
+ get budget() {
59
+ return this.options.fastAttempts + this.options.slowAttempts;
60
+ }
61
+ /** Polls completed so far in this run. */
62
+ get pollsCompleted() {
63
+ return this.completed;
64
+ }
65
+ /** Interval (ms) for the next poll given the polls completed so far. */
66
+ nextInterval() {
67
+ return this.completed < this.options.fastAttempts ? this.options.fastIntervalMs : this.options.slowIntervalMs;
68
+ }
69
+ /**
70
+ * Run `check` on the schedule until it reports done, the budget is
71
+ * exhausted, or stop() is called. Resolves the done value, or undefined
72
+ * when polling ended without a terminal answer (caller -> `processing`).
73
+ */
74
+ run(check) {
75
+ this.teardown();
76
+ this.check = check;
77
+ this.completed = 0;
78
+ this.stopped = false;
79
+ this.inFlight = false;
80
+ this.lastAppState = react_native_1.AppState.currentState;
81
+ return new Promise((resolve) => {
82
+ this.resolveRun = resolve;
83
+ this.appStateSubscription = react_native_1.AppState.addEventListener('change', this.handleAppStateChange);
84
+ this.scheduleNext(0);
85
+ });
86
+ }
87
+ /** Cancel polling; the pending run() resolves undefined immediately. */
88
+ stop() {
89
+ this.teardown();
90
+ this.deliver(undefined);
91
+ }
92
+ teardown() {
93
+ this.stopped = true;
94
+ this.check = null;
95
+ if (this.timer != null) {
96
+ clearTimeout(this.timer);
97
+ this.timer = null;
98
+ }
99
+ if (this.appStateSubscription) {
100
+ this.appStateSubscription.remove();
101
+ this.appStateSubscription = null;
102
+ }
103
+ }
104
+ deliver(value) {
105
+ const resolve = this.resolveRun;
106
+ this.resolveRun = null;
107
+ if (resolve) {
108
+ resolve(value);
109
+ }
110
+ }
111
+ scheduleNext(delayMs) {
112
+ if (this.stopped || !this.check) {
113
+ return;
114
+ }
115
+ if (this.timer != null) {
116
+ clearTimeout(this.timer);
117
+ }
118
+ this.timer = setTimeout(() => {
119
+ this.timer = null;
120
+ void this.tick();
121
+ }, delayMs);
122
+ }
123
+ async tick() {
124
+ const check = this.check;
125
+ if (this.stopped || !check || this.inFlight) {
126
+ return;
127
+ }
128
+ if (this.completed >= this.budget) {
129
+ this.teardown();
130
+ this.deliver(undefined);
131
+ return;
132
+ }
133
+ this.inFlight = true;
134
+ let outcome;
135
+ try {
136
+ outcome = await check();
137
+ }
138
+ catch {
139
+ // A failed poll (e.g. a network blip) is not terminal — keep going
140
+ // within the budget; exhaustion maps to `processing` (COM-06).
141
+ outcome = { done: false };
142
+ }
143
+ this.inFlight = false;
144
+ if (this.stopped) {
145
+ return;
146
+ }
147
+ if (outcome.done) {
148
+ this.teardown();
149
+ this.deliver(outcome.value);
150
+ return;
151
+ }
152
+ this.completed += 1;
153
+ if (this.completed >= this.budget) {
154
+ this.teardown();
155
+ this.deliver(undefined);
156
+ return;
157
+ }
158
+ if (react_native_1.AppState.currentState === 'active') {
159
+ this.scheduleNext(this.nextInterval());
160
+ }
161
+ // else: backgrounded between ticks — resume via handleAppStateChange.
162
+ }
163
+ }
164
+ exports.AppStateAwarePoller = AppStateAwarePoller;
165
+ /**
166
+ * Convenience wrapper: run a poller until done or budget exhaustion.
167
+ * Resolves the terminal value, or undefined (caller -> `processing`).
168
+ */
169
+ async function pollUntil(check, options) {
170
+ const poller = new AppStateAwarePoller(options);
171
+ return poller.run(check);
172
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * 3DS challenge presentation bridge (RN-18 / RN-19).
3
+ *
4
+ * Primary path: the SDK's own native modules
5
+ * - iOS: PaSdk3ds (Swift WKWebView view controller, see native/ios)
6
+ * - Android: PaSdk3dsModule + PaSdk3dsActivity (see native/android)
7
+ * both presenting a full-screen WebView that POSTs the challenge payload
8
+ * (Cardinal JWT or ACS creq) to the challenge URL.
9
+ *
10
+ * The bridge uses the classic NativeModules API. On the New Architecture it
11
+ * runs through React Native's interop layer (RN 0.79+ default), no codegen
12
+ * spec needed.
13
+ *
14
+ * Fallback path (no native module available): a React host component
15
+ * (PaSdk3dsHost, backed by react-native-webview) can register itself here
16
+ * via setThreeDsPresenter().
17
+ */
18
+ /** Strings the native chrome needs, already resolved for the runtime locale (WEB-45 analog / RN-29). */
19
+ export interface ThreeDsStrings {
20
+ title: string;
21
+ cancel: string;
22
+ close: string;
23
+ processing: string;
24
+ redirecting: string;
25
+ }
26
+ export interface ThreeDsParams {
27
+ /** Challenge URL — Cardinal StepUp URL or issuer ACS URL. */
28
+ url: string;
29
+ /** Form fields to POST, e.g. { JWT: '...' } or { creq: '...' }. */
30
+ fields: {
31
+ [name: string]: string;
32
+ };
33
+ strings: ThreeDsStrings;
34
+ /** 3DS return URLs (RN-20) — consumed by the SDK, not the app's handler. */
35
+ returnUrlScheme?: string;
36
+ returnUrlUniversalHost?: string;
37
+ }
38
+ export interface ThreeDsDismissal {
39
+ /** true when the user closed the challenge themselves -> result `cancelled`. */
40
+ cancelled: boolean;
41
+ /** Android only: the challenge returned via flow:// / universal link and
42
+ * the SDK consumed the return (RN-20). */
43
+ returnUrlConsumed?: boolean;
44
+ }
45
+ export type ThreeDsPresenter = (params: ThreeDsParams) => Promise<ThreeDsDismissal>;
46
+ /** Register the JS fallback presenter (PaSdk3dsHost). */
47
+ export declare function setThreeDsPresenter(presenter: ThreeDsPresenter | null): void;
48
+ /** True when the SDK can present the 3DS challenge on this installation. */
49
+ export declare function canPresentThreeDs(): boolean;
50
+ /**
51
+ * Present the challenge. Fires `onWillPresent` immediately before the
52
+ * challenge appears (RN-19 — Flow dismisses its loading overlay then).
53
+ * Resolves when the challenge is dismissed by the user (cancelled: true)
54
+ * or by closeThreeDs() after the server-side outcome was observed.
55
+ */
56
+ export declare function presentThreeDs(params: ThreeDsParams, onWillPresent?: () => void): Promise<ThreeDsDismissal>;
57
+ /** Close a presented challenge (called once polling observed a terminal
58
+ * state; the native side dismisses the WebView and resolves present()). */
59
+ export declare function closeThreeDs(): void;
package/lib/threeDs.js ADDED
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ /**
3
+ * 3DS challenge presentation bridge (RN-18 / RN-19).
4
+ *
5
+ * Primary path: the SDK's own native modules
6
+ * - iOS: PaSdk3ds (Swift WKWebView view controller, see native/ios)
7
+ * - Android: PaSdk3dsModule + PaSdk3dsActivity (see native/android)
8
+ * both presenting a full-screen WebView that POSTs the challenge payload
9
+ * (Cardinal JWT or ACS creq) to the challenge URL.
10
+ *
11
+ * The bridge uses the classic NativeModules API. On the New Architecture it
12
+ * runs through React Native's interop layer (RN 0.79+ default), no codegen
13
+ * spec needed.
14
+ *
15
+ * Fallback path (no native module available): a React host component
16
+ * (PaSdk3dsHost, backed by react-native-webview) can register itself here
17
+ * via setThreeDsPresenter().
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.setThreeDsPresenter = setThreeDsPresenter;
21
+ exports.canPresentThreeDs = canPresentThreeDs;
22
+ exports.presentThreeDs = presentThreeDs;
23
+ exports.closeThreeDs = closeThreeDs;
24
+ const react_native_1 = require("react-native");
25
+ const errors_1 = require("./errors");
26
+ const nativeModule = react_native_1.NativeModules.PaSdk3ds;
27
+ let fallbackPresenter = null;
28
+ /** Register the JS fallback presenter (PaSdk3dsHost). */
29
+ function setThreeDsPresenter(presenter) {
30
+ fallbackPresenter = presenter;
31
+ }
32
+ /** True when the SDK can present the 3DS challenge on this installation. */
33
+ function canPresentThreeDs() {
34
+ return Boolean(nativeModule) || fallbackPresenter !== null;
35
+ }
36
+ /**
37
+ * Present the challenge. Fires `onWillPresent` immediately before the
38
+ * challenge appears (RN-19 — Flow dismisses its loading overlay then).
39
+ * Resolves when the challenge is dismissed by the user (cancelled: true)
40
+ * or by closeThreeDs() after the server-side outcome was observed.
41
+ */
42
+ async function presentThreeDs(params, onWillPresent) {
43
+ if (!canPresentThreeDs()) {
44
+ throw new errors_1.PaError('internal_error', {
45
+ developerMessage: 'No 3DS presenter available. Install the SDK native modules (pod install / gradle) or mount <PaSdk3dsHost /> as a fallback.',
46
+ });
47
+ }
48
+ if (onWillPresent) {
49
+ onWillPresent();
50
+ }
51
+ if (nativeModule) {
52
+ return nativeModule.present(params);
53
+ }
54
+ return fallbackPresenter(params);
55
+ }
56
+ /** Close a presented challenge (called once polling observed a terminal
57
+ * state; the native side dismisses the WebView and resolves present()). */
58
+ function closeThreeDs() {
59
+ if (nativeModule) {
60
+ nativeModule.close().catch(() => {
61
+ /* the challenge may already be gone — nothing to do */
62
+ });
63
+ }
64
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * PaSdk3dsHost — pure-JS fallback for the SDK-presented 3DS challenge
3
+ * (RN-19). Used only when the native module (native/ios, native/android) is
4
+ * not installed. Renders a full-screen Modal with a react-native-webview
5
+ * that POSTs the challenge payload to the challenge URL, mirroring the
6
+ * native presentation: cancel button, localized chrome, no swipe-to-dismiss.
7
+ *
8
+ * Mount it once, anywhere in the tree (usually above your navigator):
9
+ *
10
+ * import { PaSdk3dsHost } from 'pa-sdk-react-native';
11
+ * <PaSdk3dsHost />
12
+ */
13
+ import React from 'react';
14
+ import { type ThreeDsParams } from './threeDs';
15
+ /** Build the auto-submitting POST form; identical technique to the native side. */
16
+ export declare function buildPostHtml(params: ThreeDsParams): string;
17
+ export declare function PaSdk3dsHost(): React.JSX.Element;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /**
3
+ * PaSdk3dsHost — pure-JS fallback for the SDK-presented 3DS challenge
4
+ * (RN-19). Used only when the native module (native/ios, native/android) is
5
+ * not installed. Renders a full-screen Modal with a react-native-webview
6
+ * that POSTs the challenge payload to the challenge URL, mirroring the
7
+ * native presentation: cancel button, localized chrome, no swipe-to-dismiss.
8
+ *
9
+ * Mount it once, anywhere in the tree (usually above your navigator):
10
+ *
11
+ * import { PaSdk3dsHost } from 'pa-sdk-react-native';
12
+ * <PaSdk3dsHost />
13
+ */
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
27
+ }) : function(o, v) {
28
+ o["default"] = v;
29
+ });
30
+ var __importStar = (this && this.__importStar) || (function () {
31
+ var ownKeys = function(o) {
32
+ ownKeys = Object.getOwnPropertyNames || function (o) {
33
+ var ar = [];
34
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
+ return ar;
36
+ };
37
+ return ownKeys(o);
38
+ };
39
+ return function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ })();
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.buildPostHtml = buildPostHtml;
49
+ exports.PaSdk3dsHost = PaSdk3dsHost;
50
+ const react_1 = __importStar(require("react"));
51
+ const react_native_1 = require("react-native");
52
+ const react_native_webview_1 = require("react-native-webview");
53
+ const threeDs_1 = require("./threeDs");
54
+ /** Build the auto-submitting POST form; identical technique to the native side. */
55
+ function buildPostHtml(params) {
56
+ const inputs = Object.keys(params.fields)
57
+ .map((name) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(params.fields[name])}">`)
58
+ .join('');
59
+ return [
60
+ '<!DOCTYPE html><html><head><meta charset="utf-8">',
61
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
62
+ '</head><body>',
63
+ `<form id="f" method="POST" action="${escapeHtml(params.url)}">${inputs}</form>`,
64
+ '<script>document.getElementById("f").submit();</script>',
65
+ '</body></html>',
66
+ ].join('');
67
+ }
68
+ function escapeHtml(value) {
69
+ return String(value)
70
+ .replace(/&/g, '&amp;')
71
+ .replace(/</g, '&lt;')
72
+ .replace(/>/g, '&gt;')
73
+ .replace(/"/g, '&quot;');
74
+ }
75
+ function PaSdk3dsHost() {
76
+ const [challenge, setChallenge] = (0, react_1.useState)(null);
77
+ const [loading, setLoading] = (0, react_1.useState)(true);
78
+ const challengeRef = (0, react_1.useRef)(null);
79
+ (0, react_1.useEffect)(() => {
80
+ (0, threeDs_1.setThreeDsPresenter)((params) => new Promise((resolve) => {
81
+ const active = { params, resolve };
82
+ challengeRef.current = active;
83
+ setLoading(true);
84
+ setChallenge(active);
85
+ }));
86
+ return () => {
87
+ (0, threeDs_1.setThreeDsPresenter)(null);
88
+ challengeRef.current = null;
89
+ };
90
+ }, []);
91
+ const finish = (dismissal) => {
92
+ const active = challengeRef.current;
93
+ challengeRef.current = null;
94
+ setChallenge(null);
95
+ if (active) {
96
+ active.resolve(dismissal);
97
+ }
98
+ };
99
+ (0, react_1.useEffect)(() => {
100
+ if (!challenge) {
101
+ return undefined;
102
+ }
103
+ const subscription = react_native_1.BackHandler.addEventListener('hardwareBackPress', () => {
104
+ finish({ cancelled: true });
105
+ return true;
106
+ });
107
+ return () => subscription.remove();
108
+ }, [challenge]);
109
+ if (!challenge) {
110
+ return react_1.default.createElement(react_native_1.View, null);
111
+ }
112
+ const { strings } = challenge.params;
113
+ return (react_1.default.createElement(react_native_1.Modal, { visible: true, animationType: "slide", onRequestClose: () => finish({ cancelled: true }) },
114
+ react_1.default.createElement(react_native_1.View, { style: styles.container },
115
+ react_1.default.createElement(react_native_1.View, { style: styles.header },
116
+ react_1.default.createElement(react_native_1.Text, { style: styles.title, numberOfLines: 1 }, strings.title),
117
+ react_1.default.createElement(react_native_1.TouchableOpacity, { style: styles.cancelButton, onPress: () => finish({ cancelled: true }), accessibilityLabel: strings.cancel },
118
+ react_1.default.createElement(react_native_1.Text, { style: styles.cancelText }, strings.cancel))),
119
+ react_1.default.createElement(react_native_1.View, { style: styles.webContainer },
120
+ react_1.default.createElement(react_native_webview_1.WebView, { source: { html: buildPostHtml(challenge.params) }, originWhitelist: ['*'], javaScriptEnabled: true, domStorageEnabled: true, onLoadStart: () => setLoading(true), onLoadEnd: () => setLoading(false), onNavigationStateChange: (state) => {
121
+ // RN-20: a navigation to the configured 3DS return URLs is the
122
+ // challenge ending — consume it here so the app's link handler
123
+ // never sees it, and let polling observe the server-side result.
124
+ const scheme = challenge.params.returnUrlScheme;
125
+ const universalLinkHost = challenge.params.returnUrlUniversalHost;
126
+ const url = state.url || '';
127
+ const matchesScheme = scheme ? url.startsWith(scheme) : false;
128
+ const matchesHost = universalLinkHost ? url.startsWith(universalLinkHost) : false;
129
+ if (matchesScheme || matchesHost) {
130
+ finish({ cancelled: false, returnUrlConsumed: true });
131
+ }
132
+ } }),
133
+ loading ? (react_1.default.createElement(react_native_1.View, { style: styles.loading, pointerEvents: "none" },
134
+ react_1.default.createElement(react_native_1.ActivityIndicator, { size: "large" }),
135
+ react_1.default.createElement(react_native_1.Text, { style: styles.loadingText }, strings.processing))) : null))));
136
+ }
137
+ const styles = react_native_1.StyleSheet.create({
138
+ container: { flex: 1, backgroundColor: '#ffffff' },
139
+ header: {
140
+ height: 52,
141
+ flexDirection: 'row',
142
+ alignItems: 'center',
143
+ justifyContent: 'space-between',
144
+ paddingHorizontal: 16,
145
+ borderBottomWidth: react_native_1.StyleSheet.hairlineWidth,
146
+ borderBottomColor: '#dddddd',
147
+ },
148
+ title: { fontSize: 16, fontWeight: '600', color: '#111111', flex: 1 },
149
+ cancelButton: { paddingHorizontal: 8, paddingVertical: 6 },
150
+ cancelText: { fontSize: 15, color: '#0a84ff' },
151
+ webContainer: { flex: 1 },
152
+ loading: {
153
+ ...react_native_1.StyleSheet.absoluteFillObject,
154
+ alignItems: 'center',
155
+ justifyContent: 'center',
156
+ backgroundColor: 'rgba(255,255,255,0.7)',
157
+ },
158
+ loadingText: { marginTop: 12, fontSize: 14, color: '#444444' },
159
+ });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Direct tokenization (COM-02 / RN-13).
3
+ *
4
+ * Card data goes from Flow's UI through the SDK straight to PA and never
5
+ * touches Flow's servers. Two calls:
6
+ * 1. createElementSession — POST /{merchantToken}/element-sessions
7
+ * 2. tokenizeCard — POST /tokenize
8
+ */
9
+ import type { ApiClient } from './api';
10
+ import type { CardInput, TokenizeOutput } from './types';
11
+ /** Create a short-lived public session. `merchantToken` is the publishable
12
+ * credential of the (market-specific) merchant account — COM-01 / COM-41. */
13
+ export declare function createElementSession(api: ApiClient, merchantToken: string): Promise<string>;
14
+ /** Tokenize a card. Creates the element session automatically when the
15
+ * caller does not already hold one. */
16
+ export declare function tokenizeCard(api: ApiClient, params: {
17
+ card: CardInput;
18
+ /** Existing session token; a fresh one is created when omitted. */
19
+ sessionToken?: string;
20
+ /** Publishable merchantToken of the market account to tokenize under. */
21
+ merchantToken: string;
22
+ }): Promise<TokenizeOutput>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ /**
3
+ * Direct tokenization (COM-02 / RN-13).
4
+ *
5
+ * Card data goes from Flow's UI through the SDK straight to PA and never
6
+ * touches Flow's servers. Two calls:
7
+ * 1. createElementSession — POST /{merchantToken}/element-sessions
8
+ * 2. tokenizeCard — POST /tokenize
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.createElementSession = createElementSession;
12
+ exports.tokenizeCard = tokenizeCard;
13
+ const errors_1 = require("./errors");
14
+ const validator_1 = require("./validator");
15
+ /** Create a short-lived public session. `merchantToken` is the publishable
16
+ * credential of the (market-specific) merchant account — COM-01 / COM-41. */
17
+ async function createElementSession(api, merchantToken) {
18
+ const payload = await api.createElementSession(merchantToken);
19
+ if (!payload || !payload.session_token) {
20
+ throw new errors_1.PaError('provider_error', {
21
+ developerMessage: 'element-sessions returned no session_token.',
22
+ });
23
+ }
24
+ return payload.session_token;
25
+ }
26
+ /** Tokenize a card. Creates the element session automatically when the
27
+ * caller does not already hold one. */
28
+ async function tokenizeCard(api, params) {
29
+ const sessionToken = params.sessionToken || (await createElementSession(api, params.merchantToken));
30
+ const payload = await api.tokenize({
31
+ sessionToken,
32
+ cardNumber: (0, validator_1.sanitizeCardNumber)(params.card.cardNumber),
33
+ expiryMonth: params.card.expiryMonth,
34
+ expiryYear: params.card.expiryYear,
35
+ cvc: params.card.cvc,
36
+ cardHolderName: params.card.cardHolderName,
37
+ });
38
+ if (!payload || !payload.pa_token) {
39
+ throw new errors_1.PaError('provider_error', {
40
+ developerMessage: 'tokenize returned no pa_token.',
41
+ });
42
+ }
43
+ const result = {
44
+ paToken: payload.pa_token,
45
+ last4: payload.last4,
46
+ brand: payload.brand,
47
+ sessionExpiry: null,
48
+ };
49
+ return { sessionToken, result };
50
+ }
package/lib/types.d.ts ADDED
@@ -0,0 +1,128 @@
1
+ /**
2
+ * PA SDK React Native — shared types.
3
+ *
4
+ * The result states are exactly the five states of the shared payment
5
+ * contract (requirement A3 / RN-28). `requires_action` must never be a
6
+ * resolved value (COM-05) — any 3DS is handled inside confirm.
7
+ */
8
+ /** Environments (COM-03) — selected once at init. */
9
+ export type Environment = 'production' | 'sandbox';
10
+ /** SDK result states (A3). */
11
+ export type ResultStatus = 'succeeded' | 'authorized' | 'processing' | 'cancelled' | 'failed';
12
+ /** Field codes reported by validation (COM-26 / RN-12). */
13
+ export type FieldErrorCode = 'incomplete_number' | 'invalid_number' | 'incomplete_expiry' | 'invalid_expiry' | 'incomplete_cvc' | 'invalid_cvc' | 'unsupported_brand';
14
+ /** Published brand vocabulary (COM-29). Scope is Visa + Mastercard (COM-30); the
15
+ * other values exist so a non-scope scheme can be detected early and blocked. */
16
+ export type CardBrand = 'visa' | 'mastercard' | 'amex' | 'diners' | 'discover' | 'jcb' | 'unionpay' | 'maestro' | 'unknown';
17
+ /** Card input collected by Flow's own UI (RN-13 — Flow owns the fields). */
18
+ export interface CardInput {
19
+ /** Full card number, spaces and dashes tolerated. */
20
+ cardNumber: string;
21
+ /** Expiry month 1–12 (number or zero-padded string). */
22
+ expiryMonth: number | string;
23
+ /** Expiry year — 2-digit ("29") or 4-digit ("2029"). */
24
+ expiryYear: number | string;
25
+ /** Security code. */
26
+ cvc: string;
27
+ /** Optional; never required (COM-23). */
28
+ cardHolderName?: string;
29
+ }
30
+ /** Optional pass-through billing details (COM-22 / COM-23 / RN-15).
31
+ * Postal address is optional and never required. */
32
+ export interface BillingDetails {
33
+ cardholderName?: string;
34
+ firstName?: string;
35
+ lastName?: string;
36
+ email?: string;
37
+ /** Full phone number including dial code, e.g. "+85291234567". */
38
+ phone?: string;
39
+ /** Optional separate dial code, e.g. "+852" (used when `phone` is national). */
40
+ phoneDialCode?: string;
41
+ /** Optional postal address — absent must never fail (COM-22). */
42
+ address?: {
43
+ line1?: string;
44
+ line2?: string;
45
+ city?: string;
46
+ state?: string;
47
+ postalCode?: string;
48
+ countryCode?: string;
49
+ };
50
+ }
51
+ /** Init options (RN-08 / RN-09 / COM-40): one initialisation serves multiple
52
+ * merchant accounts, keyed by market. Currency and country are per intent. */
53
+ export interface InitOptions {
54
+ environment: Environment;
55
+ /** market (e.g. "HK", "MY") -> publishable merchantToken. */
56
+ accounts: {
57
+ [market: string]: string;
58
+ };
59
+ /** Which market key to use when a call does not name one. */
60
+ defaultAccount: string;
61
+ /** A10 locale tag; underscore/hyphen and case-insensitive (COM-34). */
62
+ locale?: string;
63
+ /** App origin sent with API calls where the gateway recommends one,
64
+ * e.g. "https://app.flowtheroom.com". */
65
+ origin?: string;
66
+ /** 3DS return URL configuration (RN-20). */
67
+ threeDsReturnUrls?: {
68
+ /** Custom scheme, e.g. "flow://" — no trailing slash. */
69
+ scheme?: string;
70
+ /** Universal-link host, e.g. "https://app.flowtheroom.com". */
71
+ universalLinkHost?: string;
72
+ };
73
+ }
74
+ /** The single result object confirm resolves with, exactly once (COM-05). */
75
+ export interface PaymentResult {
76
+ status: ResultStatus;
77
+ intentToken?: string;
78
+ /** PA's reference for this transaction attempt. */
79
+ requestReference?: string | null;
80
+ /** Flow's own order number, echoed by the gateway when present. */
81
+ merchantReference?: string | null;
82
+ /** Saved-card token — set when a card was saved on any path (COM-16 / RN-25). */
83
+ paToken?: string | null;
84
+ brand?: string | null;
85
+ last4?: string | null;
86
+ /** Shared-table error code for `failed` (A8); null otherwise. */
87
+ errorCode?: string | null;
88
+ /** English developer message for `failed` (optional per A3). */
89
+ errorMessage?: string | null;
90
+ /** Localized user message for `failed` (COM-28 / RN-29). */
91
+ userMessage?: string | null;
92
+ }
93
+ /** Tokenization result (RN-13). */
94
+ export interface TokenizeResult {
95
+ paToken: string;
96
+ last4: string;
97
+ brand: CardBrand | string;
98
+ /** Session expiry time as returned by the gateway, if present. */
99
+ sessionExpiry?: string | null;
100
+ }
101
+ export interface TokenizeOutput {
102
+ sessionToken: string;
103
+ result: TokenizeResult;
104
+ }
105
+ /** Polling schedule (WEB-51 analog / CONF-08): 2s x 15 then 5s x 12 —
106
+ * suspended time while the app is backgrounded does not count (RN-20,
107
+ * WEB-50 analog). */
108
+ export declare const POLL_FAST_INTERVAL_MS = 2000;
109
+ export declare const POLL_FAST_ATTEMPTS = 15;
110
+ export declare const POLL_SLOW_INTERVAL_MS = 5000;
111
+ export declare const POLL_SLOW_ATTEMPTS = 12;
112
+ /** Internal gateway payload shapes (envelope.payload). */
113
+ export interface ConfirmGatewayPayload {
114
+ status?: string;
115
+ request_reference?: string | null;
116
+ merchant_reference?: string | null;
117
+ pa_token?: string | null;
118
+ brand?: string | null;
119
+ last4?: string | null;
120
+ error_code?: string | null;
121
+ error_message?: string | null;
122
+ threeds_data?: {
123
+ cardinal_url?: string;
124
+ jwt?: string;
125
+ acs_url?: string;
126
+ creq?: string;
127
+ } | null;
128
+ }