@inno-isw/react-native-rtp 0.0.0-stage → 0.2.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 (55) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +385 -2
  3. package/lib/module/client.js +391 -0
  4. package/lib/module/client.js.map +1 -0
  5. package/lib/module/constants.js +49 -0
  6. package/lib/module/constants.js.map +1 -0
  7. package/lib/module/emitter.js +46 -0
  8. package/lib/module/emitter.js.map +1 -0
  9. package/lib/module/index.js +16 -0
  10. package/lib/module/index.js.map +1 -0
  11. package/lib/module/mock/makeRtpPayload.js +54 -0
  12. package/lib/module/mock/makeRtpPayload.js.map +1 -0
  13. package/lib/module/mock/mockTransport.js +89 -0
  14. package/lib/module/mock/mockTransport.js.map +1 -0
  15. package/lib/module/package.json +1 -0
  16. package/lib/module/push.js +96 -0
  17. package/lib/module/push.js.map +1 -0
  18. package/lib/module/react/RtpProvider.js +152 -0
  19. package/lib/module/react/RtpProvider.js.map +1 -0
  20. package/lib/module/types.js +4 -0
  21. package/lib/module/types.js.map +1 -0
  22. package/lib/module/validate.js +122 -0
  23. package/lib/module/validate.js.map +1 -0
  24. package/lib/typescript/package.json +1 -0
  25. package/lib/typescript/src/client.d.ts +20 -0
  26. package/lib/typescript/src/client.d.ts.map +1 -0
  27. package/lib/typescript/src/constants.d.ts +50 -0
  28. package/lib/typescript/src/constants.d.ts.map +1 -0
  29. package/lib/typescript/src/emitter.d.ts +15 -0
  30. package/lib/typescript/src/emitter.d.ts.map +1 -0
  31. package/lib/typescript/src/index.d.ts +14 -0
  32. package/lib/typescript/src/index.d.ts.map +1 -0
  33. package/lib/typescript/src/mock/makeRtpPayload.d.ts +17 -0
  34. package/lib/typescript/src/mock/makeRtpPayload.d.ts.map +1 -0
  35. package/lib/typescript/src/mock/mockTransport.d.ts +35 -0
  36. package/lib/typescript/src/mock/mockTransport.d.ts.map +1 -0
  37. package/lib/typescript/src/push.d.ts +41 -0
  38. package/lib/typescript/src/push.d.ts.map +1 -0
  39. package/lib/typescript/src/react/RtpProvider.d.ts +60 -0
  40. package/lib/typescript/src/react/RtpProvider.d.ts.map +1 -0
  41. package/lib/typescript/src/types.d.ts +153 -0
  42. package/lib/typescript/src/types.d.ts.map +1 -0
  43. package/lib/typescript/src/validate.d.ts +33 -0
  44. package/lib/typescript/src/validate.d.ts.map +1 -0
  45. package/package.json +141 -4
  46. package/src/client.ts +428 -0
  47. package/src/constants.ts +54 -0
  48. package/src/emitter.ts +53 -0
  49. package/src/index.tsx +45 -0
  50. package/src/mock/makeRtpPayload.ts +69 -0
  51. package/src/mock/mockTransport.ts +119 -0
  52. package/src/push.ts +109 -0
  53. package/src/react/RtpProvider.tsx +235 -0
  54. package/src/types.ts +172 -0
  55. package/src/validate.ts +141 -0
package/src/client.ts ADDED
@@ -0,0 +1,428 @@
1
+ import { RTP_ERROR, RTP_EVENT, RTP_STATUS } from './constants';
2
+ import type { RtpError, RtpStatus } from './constants';
3
+ import { createEmitter, defaultNow, noopLogger } from './emitter';
4
+ import {
5
+ findValidationErrors,
6
+ isExpired,
7
+ isRtpPayload,
8
+ mergeRequest,
9
+ toRequestPatch,
10
+ toRtpRequest,
11
+ } from './validate';
12
+ import type {
13
+ RtpClient,
14
+ RtpClientOptions,
15
+ RtpCredential,
16
+ RtpPayload,
17
+ RtpReceiveOutcome,
18
+ RtpRequest,
19
+ RtpResult,
20
+ } from './types';
21
+
22
+ interface Entry {
23
+ request: RtpRequest;
24
+ status: RtpStatus;
25
+ }
26
+
27
+ /** Statuses after which a request is finished with. */
28
+ const TERMINAL_STATUSES: ReadonlySet<RtpStatus> = new Set([
29
+ RTP_STATUS.ACCEPTED,
30
+ RTP_STATUS.DECLINED,
31
+ RTP_STATUS.EXPIRED,
32
+ RTP_STATUS.FAILED,
33
+ ]);
34
+
35
+ /**
36
+ * Map a backend status string onto the normalized SDK status.
37
+ *
38
+ * Unknown values are deliberately **not** treated as success — they map to
39
+ * `undefined` so the caller can decide, rather than silently reporting an
40
+ * approved payment for a status the client does not understand.
41
+ */
42
+ export function normalizeBackendStatus(raw: unknown): RtpStatus | undefined {
43
+ if (typeof raw !== 'string') {
44
+ return undefined;
45
+ }
46
+ switch (raw.toUpperCase()) {
47
+ case 'ACCEPTED':
48
+ case 'APPROVED':
49
+ case 'SUCCESS':
50
+ case 'SUCCESSFUL':
51
+ return RTP_STATUS.ACCEPTED;
52
+ case 'DECLINED':
53
+ case 'USER_DECLINED':
54
+ return RTP_STATUS.DECLINED;
55
+ case 'EXPIRED':
56
+ return RTP_STATUS.EXPIRED;
57
+ case 'PENDING':
58
+ case 'PROCESSING':
59
+ return RTP_STATUS.PENDING;
60
+ case 'FAILED':
61
+ case 'REJECTED':
62
+ return RTP_STATUS.FAILED;
63
+ default:
64
+ return undefined;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Create a portable Request-to-Pay client.
70
+ *
71
+ * The client owns validation, de-duplication, expiry, status computation and
72
+ * the accept/decline/retrieve calls. It owns no UI, no navigation and no
73
+ * crypto. Every external effect is injected so the same contract can be
74
+ * re-implemented on other platforms.
75
+ */
76
+ export function createRtpClient(options: RtpClientOptions): RtpClient {
77
+ const {
78
+ transport,
79
+ getAuthHeaders = async () => ({}),
80
+ getCurrentUser = () => null,
81
+ now = defaultNow,
82
+ logger = noopLogger,
83
+ basePath = '/rtp',
84
+ } = options;
85
+
86
+ if (!transport) {
87
+ throw new Error('[react-native-rtp] `transport` is required');
88
+ }
89
+
90
+ const emitter = createEmitter();
91
+ const entries = new Map<string, Entry>();
92
+
93
+ // --- expiry scheduling --------------------------------------------------
94
+ // Expiry is not only evaluated lazily: an inactive timer fires at `expiresAt`
95
+ // so a request cannot remain actionable after it has lapsed (INDV-3807/3808).
96
+ let expiryTimer: ReturnType<typeof setTimeout> | undefined;
97
+ let expiryTimerId: string | undefined;
98
+
99
+ function clearExpiryTimer(): void {
100
+ if (expiryTimer !== undefined) {
101
+ clearTimeout(expiryTimer);
102
+ }
103
+ expiryTimer = undefined;
104
+ expiryTimerId = undefined;
105
+ }
106
+
107
+ function scheduleExpiry(entry: Entry): void {
108
+ clearExpiryTimer();
109
+
110
+ const expiry = new Date(entry.request.expiresAt).getTime();
111
+ if (Number.isNaN(expiry)) {
112
+ return;
113
+ }
114
+
115
+ const id = entry.request.id;
116
+ expiryTimerId = id;
117
+ expiryTimer = setTimeout(
118
+ () => {
119
+ const current = entries.get(id);
120
+ if (!current || TERMINAL_STATUSES.has(current.status)) {
121
+ return;
122
+ }
123
+ logger('[react-native-rtp] request expired:', id);
124
+ emitResult({ id, status: RTP_STATUS.EXPIRED });
125
+ },
126
+ Math.max(0, expiry - now())
127
+ );
128
+
129
+ // Never keep a Node process (e.g. Jest) alive for a pending expiry.
130
+ const handle = expiryTimer as unknown as { unref?: () => void };
131
+ if (typeof handle?.unref === 'function') {
132
+ handle.unref();
133
+ }
134
+ }
135
+
136
+ function setStatus(id: string, status: RtpStatus): void {
137
+ const entry = entries.get(id);
138
+ if (entry) {
139
+ entry.status = status;
140
+ }
141
+ if (TERMINAL_STATUSES.has(status) && expiryTimerId === id) {
142
+ clearExpiryTimer();
143
+ }
144
+ emitter.emit(RTP_EVENT.STATE, { id, status });
145
+ }
146
+
147
+ function emitResult(result: RtpResult): RtpResult {
148
+ setStatus(result.id, result.status);
149
+ emitter.emit(RTP_EVENT.RESULT, result);
150
+ return result;
151
+ }
152
+
153
+ function fail(id: string, error: RtpError | string): RtpResult {
154
+ return emitResult({ id, status: RTP_STATUS.FAILED, error });
155
+ }
156
+
157
+ async function receive(payload: unknown): Promise<RtpReceiveOutcome> {
158
+ if (!isRtpPayload(payload)) {
159
+ return { handled: false };
160
+ }
161
+
162
+ const id = payload.rtpId;
163
+
164
+ // Idempotency: the same request can arrive twice (foreground + background,
165
+ // or a double tap). Never re-emit for an id we have already seen.
166
+ const existing = entries.get(id);
167
+ if (existing) {
168
+ return {
169
+ handled: true,
170
+ request: existing.request,
171
+ status: existing.status,
172
+ };
173
+ }
174
+
175
+ const errors = findValidationErrors(payload);
176
+ if (errors.length > 0) {
177
+ logger('[react-native-rtp] invalid payload, missing:', errors.join(', '));
178
+ return { handled: true, error: RTP_ERROR.INVALID_PAYLOAD };
179
+ }
180
+
181
+ const request = toRtpRequest(payload);
182
+ const entry: Entry = { request, status: RTP_STATUS.RECEIVED };
183
+ entries.set(id, entry);
184
+
185
+ if (isExpired(request, now())) {
186
+ const result = emitResult({ id, status: RTP_STATUS.EXPIRED });
187
+ return { handled: true, request, status: result.status };
188
+ }
189
+
190
+ const currentUser = getCurrentUser();
191
+
192
+ if (!currentUser) {
193
+ setStatus(id, RTP_STATUS.AWAITING_AUTH);
194
+ scheduleExpiry(entry);
195
+ return { handled: true, request, status: RTP_STATUS.AWAITING_AUTH };
196
+ }
197
+
198
+ if (request.recipient && currentUser !== request.recipient) {
199
+ const result = fail(id, RTP_ERROR.RECIPIENT_MISMATCH);
200
+ return {
201
+ handled: true,
202
+ request,
203
+ status: result.status,
204
+ error: result.error,
205
+ };
206
+ }
207
+
208
+ setStatus(id, RTP_STATUS.READY);
209
+ scheduleExpiry(entry);
210
+ emitter.emit(RTP_EVENT.REQUEST, request);
211
+ return { handled: true, request, status: RTP_STATUS.READY };
212
+ }
213
+
214
+ /**
215
+ * Fetch (or refresh) authorization details for a request from the backend,
216
+ * and reconcile the backend status. This is the "retrieve details" step the
217
+ * authorization page needs before it can be trusted (INDV-3804).
218
+ */
219
+ async function retrieve(id: string): Promise<RtpResult> {
220
+ const entry = entries.get(id);
221
+ if (!entry) {
222
+ return fail(id, RTP_ERROR.UNKNOWN);
223
+ }
224
+
225
+ if (isExpired(entry.request, now())) {
226
+ return emitResult({ id, status: RTP_STATUS.EXPIRED });
227
+ }
228
+
229
+ if (TERMINAL_STATUSES.has(entry.status)) {
230
+ return { id, status: entry.status };
231
+ }
232
+
233
+ setStatus(id, RTP_STATUS.RETRIEVING);
234
+
235
+ try {
236
+ const headers = await getAuthHeaders();
237
+ const res = await transport.get(`${basePath}/${id}`, headers);
238
+ const data = (res?.data ?? {}) as Record<string, unknown>;
239
+
240
+ const mapped = normalizeBackendStatus(data.status);
241
+
242
+ if (
243
+ mapped === RTP_STATUS.EXPIRED ||
244
+ mapped === RTP_STATUS.DECLINED ||
245
+ mapped === RTP_STATUS.FAILED
246
+ ) {
247
+ return emitResult({
248
+ id,
249
+ status: mapped,
250
+ data,
251
+ error:
252
+ mapped === RTP_STATUS.FAILED
253
+ ? RTP_ERROR.BACKEND_REJECTED
254
+ : undefined,
255
+ });
256
+ }
257
+
258
+ if (mapped === RTP_STATUS.ACCEPTED) {
259
+ return emitResult({ id, status: RTP_STATUS.ACCEPTED, data });
260
+ }
261
+
262
+ if (mapped === RTP_STATUS.PENDING) {
263
+ return emitResult({ id, status: RTP_STATUS.PENDING, data });
264
+ }
265
+
266
+ // Merge any returned details (a full payload, or nested under `request`).
267
+ const incoming = (data.request ?? data) as
268
+ Partial<RtpPayload> | undefined;
269
+ if (incoming && typeof incoming === 'object') {
270
+ entry.request = mergeRequest(entry.request, toRequestPatch(incoming));
271
+ }
272
+
273
+ if (isExpired(entry.request, now())) {
274
+ return emitResult({ id, status: RTP_STATUS.EXPIRED });
275
+ }
276
+
277
+ setStatus(id, RTP_STATUS.READY);
278
+ scheduleExpiry(entry);
279
+ emitter.emit(RTP_EVENT.REQUEST, entry.request);
280
+ return { id, status: RTP_STATUS.READY, data };
281
+ } catch (err) {
282
+ logger('[react-native-rtp] retrieve failed:', err);
283
+ return fail(id, RTP_ERROR.RETRIEVE_FAILED);
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Called by the host after a successful login to release any requests that
289
+ * were waiting on the auth gate.
290
+ */
291
+ function resumeAuth(): void {
292
+ for (const [id, entry] of entries) {
293
+ if (entry.status !== RTP_STATUS.AWAITING_AUTH) {
294
+ continue;
295
+ }
296
+
297
+ if (isExpired(entry.request, now())) {
298
+ const result = emitResult({ id, status: RTP_STATUS.EXPIRED });
299
+ logger(
300
+ '[react-native-rtp] request expired while awaiting auth:',
301
+ id,
302
+ result.status
303
+ );
304
+ continue;
305
+ }
306
+
307
+ const currentUser = getCurrentUser();
308
+ if (
309
+ entry.request.recipient &&
310
+ currentUser &&
311
+ currentUser !== entry.request.recipient
312
+ ) {
313
+ fail(id, RTP_ERROR.RECIPIENT_MISMATCH);
314
+ continue;
315
+ }
316
+
317
+ setStatus(id, RTP_STATUS.READY);
318
+ scheduleExpiry(entry);
319
+ emitter.emit(RTP_EVENT.REQUEST, entry.request);
320
+ }
321
+ }
322
+
323
+ async function accept(params: {
324
+ id: string;
325
+ credential?: RtpCredential;
326
+ }): Promise<RtpResult> {
327
+ const { id, credential } = params;
328
+ const entry = entries.get(id);
329
+ if (!entry) {
330
+ return fail(id, RTP_ERROR.UNKNOWN);
331
+ }
332
+
333
+ if (isExpired(entry.request, now())) {
334
+ return emitResult({ id, status: RTP_STATUS.EXPIRED });
335
+ }
336
+
337
+ setStatus(id, RTP_STATUS.PROCESSING);
338
+
339
+ try {
340
+ const headers = await getAuthHeaders();
341
+ const res = await transport.post(
342
+ `${basePath}/${id}/accept`,
343
+ { credential },
344
+ headers
345
+ );
346
+ const data = (res?.data ?? {}) as Record<string, unknown>;
347
+
348
+ // If the backend returned a status we recognise, honour it. If it
349
+ // returned no status at all, the accept call itself succeeded. If it
350
+ // returned a status we do NOT understand, fail closed rather than
351
+ // showing the customer an approved payment we cannot vouch for.
352
+ const hasStatus = data.status !== undefined && data.status !== null;
353
+ const mapped = normalizeBackendStatus(data.status);
354
+ const status: RtpStatus = hasStatus
355
+ ? (mapped ?? RTP_STATUS.FAILED)
356
+ : RTP_STATUS.ACCEPTED;
357
+
358
+ return emitResult({
359
+ id,
360
+ status,
361
+ data,
362
+ error:
363
+ status === RTP_STATUS.FAILED ? RTP_ERROR.BACKEND_REJECTED : undefined,
364
+ });
365
+ } catch (err) {
366
+ logger('[react-native-rtp] accept failed:', err);
367
+ return fail(id, RTP_ERROR.NETWORK_ERROR);
368
+ }
369
+ }
370
+
371
+ async function decline(params: {
372
+ id: string;
373
+ reason?: string;
374
+ }): Promise<RtpResult> {
375
+ const { id, reason } = params;
376
+ const entry = entries.get(id);
377
+ if (!entry) {
378
+ return fail(id, RTP_ERROR.UNKNOWN);
379
+ }
380
+
381
+ setStatus(id, RTP_STATUS.PROCESSING);
382
+
383
+ try {
384
+ const headers = await getAuthHeaders();
385
+ const res = await transport.post(
386
+ `${basePath}/${id}/decline`,
387
+ { reason },
388
+ headers
389
+ );
390
+ const data = (res?.data ?? {}) as Record<string, unknown>;
391
+
392
+ const mapped = normalizeBackendStatus(data.status);
393
+ const status: RtpStatus =
394
+ mapped === RTP_STATUS.EXPIRED || mapped === RTP_STATUS.FAILED
395
+ ? mapped
396
+ : RTP_STATUS.DECLINED;
397
+
398
+ return emitResult({
399
+ id,
400
+ status,
401
+ data,
402
+ error:
403
+ status === RTP_STATUS.FAILED ? RTP_ERROR.BACKEND_REJECTED : undefined,
404
+ });
405
+ } catch (err) {
406
+ logger('[react-native-rtp] decline failed:', err);
407
+ return fail(id, RTP_ERROR.NETWORK_ERROR);
408
+ }
409
+ }
410
+
411
+ return {
412
+ isRtp: isRtpPayload,
413
+ receive,
414
+ retrieve,
415
+ resumeAuth,
416
+ accept,
417
+ decline,
418
+ getStatus: (id: string) => entries.get(id)?.status,
419
+ getRequest: (id: string) => entries.get(id)?.request,
420
+ acknowledge: (id: string) => {
421
+ if (expiryTimerId === id) {
422
+ clearExpiryTimer();
423
+ }
424
+ entries.delete(id);
425
+ },
426
+ on: emitter.on,
427
+ };
428
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Normalized RTP status.
3
+ *
4
+ * The SDK is the single source of truth for these values so that every host
5
+ * platform (React Native, Kotlin, Swift) renders the same UI states.
6
+ */
7
+ export const RTP_STATUS = {
8
+ /** Payload arrived and passed validation, but is not yet actionable. */
9
+ RECEIVED: 'RECEIVED',
10
+ /** Authorization details are being fetched from the backend. */
11
+ RETRIEVING: 'RETRIEVING',
12
+ /** Expired before it could be actioned. */
13
+ EXPIRED: 'EXPIRED',
14
+ /** Valid, but the user is not authenticated yet (login gate). */
15
+ AWAITING_AUTH: 'AWAITING_AUTH',
16
+ /** Valid, authenticated, and ready for the user to accept/decline. */
17
+ READY: 'READY',
18
+ /** Accept/decline in flight. */
19
+ PROCESSING: 'PROCESSING',
20
+ /** Backend accepted the action but a final decision is still pending. */
21
+ PENDING: 'PENDING',
22
+ /** Backend confirmed acceptance. */
23
+ ACCEPTED: 'ACCEPTED',
24
+ /** Backend confirmed (or user initiated) a decline. */
25
+ DECLINED: 'DECLINED',
26
+ /** Terminal failure (network, validation, recipient mismatch, etc.). */
27
+ FAILED: 'FAILED',
28
+ } as const;
29
+
30
+ export type RtpStatus = (typeof RTP_STATUS)[keyof typeof RTP_STATUS];
31
+
32
+ /** Events emitted by the client. */
33
+ export const RTP_EVENT = {
34
+ /** A new, actionable request is available. */
35
+ REQUEST: 'request',
36
+ /** Status transition for a request. */
37
+ STATE: 'state',
38
+ /** Terminal outcome for a request. */
39
+ RESULT: 'result',
40
+ } as const;
41
+
42
+ export type RtpEvent = (typeof RTP_EVENT)[keyof typeof RTP_EVENT];
43
+
44
+ /** Reasons a request can end in FAILED, exposed for UI/diagnostics. */
45
+ export const RTP_ERROR = {
46
+ INVALID_PAYLOAD: 'INVALID_PAYLOAD',
47
+ RECIPIENT_MISMATCH: 'RECIPIENT_MISMATCH',
48
+ RETRIEVE_FAILED: 'RETRIEVE_FAILED',
49
+ NETWORK_ERROR: 'NETWORK_ERROR',
50
+ BACKEND_REJECTED: 'BACKEND_REJECTED',
51
+ UNKNOWN: 'UNKNOWN',
52
+ } as const;
53
+
54
+ export type RtpError = (typeof RTP_ERROR)[keyof typeof RTP_ERROR];
package/src/emitter.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { RtpClientOptions, RtpEventMap, RtpUnsubscribe } from './types';
2
+
3
+ type AnyHandler = (payload: any) => void;
4
+
5
+ /**
6
+ * Tiny typed event emitter. Deliberately dependency-free so the same contract
7
+ * is trivial to re-implement in Kotlin/Swift.
8
+ */
9
+ export function createEmitter() {
10
+ const listeners: Record<keyof RtpEventMap, Set<AnyHandler>> = {
11
+ request: new Set(),
12
+ state: new Set(),
13
+ result: new Set(),
14
+ };
15
+
16
+ function on<E extends keyof RtpEventMap>(
17
+ event: E,
18
+ handler: RtpEventMap[E]
19
+ ): RtpUnsubscribe {
20
+ const set = listeners[event];
21
+ if (!set) {
22
+ throw new Error(`[react-native-rtp] Unknown event: ${String(event)}`);
23
+ }
24
+ set.add(handler as AnyHandler);
25
+ return () => {
26
+ set.delete(handler as AnyHandler);
27
+ };
28
+ }
29
+
30
+ function emit<E extends keyof RtpEventMap>(
31
+ event: E,
32
+ payload: Parameters<RtpEventMap[E]>[0]
33
+ ): void {
34
+ // Copy to a snapshot so handlers can unsubscribe during emit.
35
+ for (const handler of Array.from(listeners[event])) {
36
+ handler(payload);
37
+ }
38
+ }
39
+
40
+ function clear(): void {
41
+ listeners.request.clear();
42
+ listeners.state.clear();
43
+ listeners.result.clear();
44
+ }
45
+
46
+ return { on, emit, clear };
47
+ }
48
+
49
+ /** Default logger used when the host does not provide one. */
50
+ export const noopLogger: NonNullable<RtpClientOptions['logger']> = () => {};
51
+
52
+ /** Default clock. */
53
+ export const defaultNow = () => Date.now();
package/src/index.tsx ADDED
@@ -0,0 +1,45 @@
1
+ // Core (platform-agnostic)
2
+ export { createRtpClient, normalizeBackendStatus } from './client';
3
+ export { RTP_STATUS, RTP_EVENT, RTP_ERROR } from './constants';
4
+ export type { RtpStatus, RtpEvent, RtpError } from './constants';
5
+ export {
6
+ isRtpPayload,
7
+ findValidationErrors,
8
+ toRtpRequest,
9
+ toRequestPatch,
10
+ mergeRequest,
11
+ isExpired,
12
+ } from './validate';
13
+ export { mapPushToRtp } from './push';
14
+ export type { PushEnvelope } from './push';
15
+
16
+ // Types
17
+ export type {
18
+ RtpPayload,
19
+ RtpParty,
20
+ RtpRequest,
21
+ RtpCredential,
22
+ RtpResult,
23
+ RtpReceiveOutcome,
24
+ RtpTransport,
25
+ RtpStorage,
26
+ RtpHttpResponse,
27
+ RtpClient,
28
+ RtpClientOptions,
29
+ RtpEventMap,
30
+ RtpUnsubscribe,
31
+ } from './types';
32
+
33
+ // React adapter
34
+ export { RtpProvider, useRtp, RtpContext } from './react/RtpProvider';
35
+ export type { RtpProviderProps, RtpContextValue } from './react/RtpProvider';
36
+
37
+ // Mocks (for tests / example app)
38
+ export { createMockTransport } from './mock/mockTransport';
39
+ export type {
40
+ MockTransport,
41
+ MockTransportOptions,
42
+ RecordedCall,
43
+ } from './mock/mockTransport';
44
+ export { makeRtpPayload, makeExpiredPayload } from './mock/makeRtpPayload';
45
+ export type { MakeRtpPayloadOverrides } from './mock/makeRtpPayload';
@@ -0,0 +1,69 @@
1
+ import type { RtpPayload } from '../types';
2
+
3
+ /** Number of ms in a minute, for readable fixture offsets. */
4
+ const MINUTE = 60_000;
5
+
6
+ let counter = 0;
7
+
8
+ export interface MakeRtpPayloadOverrides extends Partial<
9
+ Omit<RtpPayload, 'type' | 'payer' | 'payee' | 'expiresAt'>
10
+ > {
11
+ payer?: Partial<RtpPayload['payer']>;
12
+ payee?: Partial<RtpPayload['payee']>;
13
+ /** Milliseconds from `now` until expiry (negative = already expired). */
14
+ expiresInMs?: number;
15
+ /** Base time to compute expiry from. Defaults to Date.now(). */
16
+ from?: number;
17
+ }
18
+
19
+ /**
20
+ * Build a valid RTP payload for tests, fixtures and the example app.
21
+ * Every field is overridable so edge cases are trivial to express.
22
+ */
23
+ export function makeRtpPayload(
24
+ overrides: MakeRtpPayloadOverrides = {}
25
+ ): RtpPayload {
26
+ const {
27
+ payer,
28
+ payee,
29
+ expiresInMs = 15 * MINUTE,
30
+ from = Date.now(),
31
+ ...rest
32
+ } = overrides;
33
+
34
+ counter += 1;
35
+
36
+ return {
37
+ version: '1.0',
38
+ type: 'RTP',
39
+ rtpId: `RTP-${from}-${counter}`,
40
+ amount: 250000,
41
+ currency: 'NGN',
42
+ narration: 'Payment for invoice 1042',
43
+ transactionRef: `TRX-${from}-${counter}`,
44
+ orderNumber: `ORD-${from}-${counter}`,
45
+ deepLink: `quickteller://rtp/${from}-${counter}`,
46
+ actionMessage: 'Review and approve this payment request',
47
+ recipient: 'john.doe@quickteller.com',
48
+ expiresAt: new Date(from + expiresInMs).toISOString(),
49
+ payer: {
50
+ name: 'Ajibola Shadrach',
51
+ accountNumber: '0123456789',
52
+ bank: 'Quickteller MFB',
53
+ ...payer,
54
+ },
55
+ payee: {
56
+ name: 'Michael Chinweike',
57
+ accountNumber: '9876543210',
58
+ ...payee,
59
+ },
60
+ ...rest,
61
+ };
62
+ }
63
+
64
+ /** A payload that has already expired. */
65
+ export function makeExpiredPayload(
66
+ overrides: MakeRtpPayloadOverrides = {}
67
+ ): RtpPayload {
68
+ return makeRtpPayload({ ...overrides, expiresInMs: -MINUTE });
69
+ }