local-lite 2.0.0 → 2.0.2

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,459 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatKenyanPhone = formatKenyanPhone;
4
+ exports.createManualPaymentAdapter = createManualPaymentAdapter;
5
+ exports.createDarajaAdapter = createDarajaAdapter;
6
+ exports.createPaystackAdapter = createPaystackAdapter;
7
+ exports.createStripeCheckoutAdapter = createStripeCheckoutAdapter;
8
+ function toBase64(value) {
9
+ if (typeof Buffer !== 'undefined') {
10
+ return Buffer.from(value, 'utf8').toString('base64');
11
+ }
12
+ if (typeof btoa === 'function') {
13
+ return btoa(value);
14
+ }
15
+ throw new Error('No base64 encoder available in this runtime.');
16
+ }
17
+ function timingSafeEqualHex(a, b) {
18
+ const left = a.trim().toLowerCase();
19
+ const right = b.trim().toLowerCase();
20
+ if (!left || left.length !== right.length)
21
+ return false;
22
+ let diff = 0;
23
+ for (let i = 0; i < left.length; i += 1) {
24
+ diff |= left.charCodeAt(i) ^ right.charCodeAt(i);
25
+ }
26
+ return diff === 0;
27
+ }
28
+ async function hmacHex(algorithm, secret, payload) {
29
+ const subtle = globalThis.crypto?.subtle;
30
+ if (!subtle) {
31
+ throw new Error('Web Crypto subtle API is required for webhook verification.');
32
+ }
33
+ const encoder = new TextEncoder();
34
+ const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: algorithm }, false, ['sign']);
35
+ const sig = await subtle.sign('HMAC', key, encoder.encode(payload));
36
+ return Array.from(new Uint8Array(sig))
37
+ .map((b) => b.toString(16).padStart(2, '0'))
38
+ .join('');
39
+ }
40
+ function formatKenyanPhone(phone) {
41
+ if (!phone)
42
+ return '';
43
+ const cleaned = String(phone).replace(/[^\d]/g, '');
44
+ if (cleaned.startsWith('254'))
45
+ return cleaned;
46
+ if (cleaned.startsWith('0'))
47
+ return `254${cleaned.slice(1)}`;
48
+ if (cleaned.length === 9)
49
+ return `254${cleaned}`;
50
+ return cleaned;
51
+ }
52
+ /**
53
+ * Offline-capable manual payment adapter (cash, bank transfer, cheque, etc.).
54
+ */
55
+ function createManualPaymentAdapter(options = {}) {
56
+ const id = options.id ?? 'manual';
57
+ return {
58
+ id,
59
+ label: options.label ?? 'Manual / Offline Payment',
60
+ description: options.description ??
61
+ 'Record cash, bank transfer, or external payment offline.',
62
+ supportedCurrencies: options.supportedCurrencies ?? '*',
63
+ supportedCountries: '*',
64
+ requiresOnline: false,
65
+ async initiate(input) {
66
+ return {
67
+ success: true,
68
+ status: 'completed',
69
+ provider: id,
70
+ actionId: input.actionId,
71
+ providerRef: input.actionId,
72
+ customerMessage: 'Recorded locally.',
73
+ };
74
+ },
75
+ };
76
+ }
77
+ /**
78
+ * Safaricom M-Pesa Daraja STK Push adapter (Kenya / KES).
79
+ */
80
+ function createDarajaAdapter(options) {
81
+ const fetchImpl = options.fetch ?? globalThis.fetch;
82
+ const baseUrl = (options.apiUrl?.trim() ||
83
+ (options.env === 'live' || options.env === 'production'
84
+ ? 'https://api.safaricom.co.ke'
85
+ : 'https://sandbox.safaricom.co.ke')).replace(/\/+$/, '');
86
+ return {
87
+ id: 'daraja',
88
+ label: 'M-Pesa (Safaricom Daraja)',
89
+ description: 'Instant STK Push prompt to a Kenyan M-Pesa number.',
90
+ supportedCurrencies: ['KES'],
91
+ supportedCountries: ['KE'],
92
+ requiresOnline: true,
93
+ async initiate(input) {
94
+ const phone = formatKenyanPhone(input.phone ?? '');
95
+ if (!/^254\d{9}$/.test(phone)) {
96
+ throw new Error('Valid Kenyan phone number (254XXXXXXXXX) is required.');
97
+ }
98
+ const amount = Math.round(input.amount);
99
+ if (!Number.isInteger(amount) || amount < 1 || amount > 250000) {
100
+ throw new Error('M-Pesa amount must be an integer between 1 and 250000.');
101
+ }
102
+ const callbackUrl = (input.callbackUrl ?? options.callbackUrl).trim();
103
+ if (!callbackUrl.startsWith('https://')) {
104
+ throw new Error('Daraja callbackUrl must use HTTPS.');
105
+ }
106
+ const authHeader = `Basic ${toBase64(`${options.consumerKey}:${options.consumerSecret}`)}`;
107
+ const oauthRes = await fetchImpl(`${baseUrl}/oauth/v1/generate?grant_type=client_credentials`, {
108
+ method: 'GET',
109
+ headers: { Authorization: authHeader },
110
+ });
111
+ if (!oauthRes.ok) {
112
+ const text = await oauthRes.text();
113
+ throw new Error(`Daraja OAuth failed (${oauthRes.status}): ${text}`);
114
+ }
115
+ const oauthJson = await oauthRes.json();
116
+ const accessToken = oauthJson?.access_token;
117
+ if (!accessToken) {
118
+ throw new Error('Daraja OAuth did not return an access_token.');
119
+ }
120
+ const timestamp = new Date(Date.now() + 3 * 3600000)
121
+ .toISOString()
122
+ .replace(/[-:TZ.]/g, '')
123
+ .slice(0, 14);
124
+ const password = toBase64(`${options.shortcode}${options.passkey}${timestamp}`);
125
+ const stkRes = await fetchImpl(`${baseUrl}/mpesa/stkpush/v1/processrequest`, {
126
+ method: 'POST',
127
+ headers: {
128
+ Authorization: `Bearer ${accessToken}`,
129
+ 'Content-Type': 'application/json',
130
+ },
131
+ body: JSON.stringify({
132
+ BusinessShortCode: options.shortcode,
133
+ Password: password,
134
+ Timestamp: timestamp,
135
+ TransactionType: options.transactionType?.trim() || 'CustomerPayBillOnline',
136
+ Amount: amount,
137
+ PartyA: phone,
138
+ PartyB: options.partyB?.trim() || options.shortcode,
139
+ PhoneNumber: phone,
140
+ CallBackURL: callbackUrl,
141
+ AccountReference: (input.contractId || input.actionId).slice(0, 12),
142
+ TransactionDesc: input.description || 'Payment',
143
+ }),
144
+ });
145
+ const data = await stkRes.json();
146
+ if (!stkRes.ok ||
147
+ data?.ResponseCode !== '0' ||
148
+ !data?.CheckoutRequestID ||
149
+ !data?.MerchantRequestID) {
150
+ throw new Error(data?.errorMessage ||
151
+ data?.ResponseDescription ||
152
+ 'Daraja did not confirm payment initiation.');
153
+ }
154
+ return {
155
+ success: true,
156
+ status: 'pending',
157
+ provider: 'daraja',
158
+ actionId: input.actionId,
159
+ providerRef: data.CheckoutRequestID,
160
+ merchantRequestId: data.MerchantRequestID,
161
+ customerMessage: data.CustomerMessage || '',
162
+ raw: data,
163
+ };
164
+ },
165
+ async verifyWebhook(request) {
166
+ const payload = await request.json();
167
+ const callback = payload?.Body?.stkCallback;
168
+ if (!callback || !Number.isInteger(callback.ResultCode)) {
169
+ return {
170
+ verified: false,
171
+ status: 'failed',
172
+ error: 'Invalid Daraja callback payload.',
173
+ rawPayload: payload,
174
+ };
175
+ }
176
+ if (callback.ResultCode !== 0) {
177
+ return {
178
+ verified: true,
179
+ providerRef: callback.CheckoutRequestID,
180
+ merchantRequestId: callback.MerchantRequestID,
181
+ status: 'failed',
182
+ error: String(callback.ResultDesc || 'Payment failed'),
183
+ rawPayload: callback,
184
+ };
185
+ }
186
+ const items = callback.CallbackMetadata?.Item;
187
+ if (!Array.isArray(items)) {
188
+ return {
189
+ verified: false,
190
+ providerRef: callback.CheckoutRequestID,
191
+ merchantRequestId: callback.MerchantRequestID,
192
+ status: 'failed',
193
+ error: 'Missing Daraja callback metadata.',
194
+ rawPayload: callback,
195
+ };
196
+ }
197
+ const readItem = (name) => items.find((entry) => entry?.Name === name)?.Value;
198
+ const receipt = readItem('MpesaReceiptNumber');
199
+ const amount = Number(readItem('Amount'));
200
+ const phone = String(readItem('PhoneNumber') ?? '');
201
+ if (typeof receipt !== 'string' || !receipt || !Number.isFinite(amount)) {
202
+ return {
203
+ verified: false,
204
+ providerRef: callback.CheckoutRequestID,
205
+ merchantRequestId: callback.MerchantRequestID,
206
+ status: 'failed',
207
+ error: 'Incomplete Daraja callback metadata.',
208
+ rawPayload: callback,
209
+ };
210
+ }
211
+ return {
212
+ verified: true,
213
+ providerRef: callback.CheckoutRequestID,
214
+ merchantRequestId: callback.MerchantRequestID,
215
+ receiptNumber: receipt,
216
+ amount,
217
+ currency: 'KES',
218
+ phone,
219
+ status: 'completed',
220
+ rawPayload: callback,
221
+ };
222
+ },
223
+ };
224
+ }
225
+ /**
226
+ * Paystack Checkout adapter (NGN, GHS, ZAR, KES, USD, etc.).
227
+ */
228
+ function createPaystackAdapter(options) {
229
+ const fetchImpl = options.fetch ?? globalThis.fetch;
230
+ return {
231
+ id: 'paystack',
232
+ label: 'Paystack (Card / Bank / Mobile Money)',
233
+ description: 'Hosted checkout for cards, bank transfers, and mobile money.',
234
+ supportedCurrencies: options.supportedCurrencies ?? [
235
+ 'NGN',
236
+ 'GHS',
237
+ 'ZAR',
238
+ 'KES',
239
+ 'USD',
240
+ ],
241
+ supportedCountries: options.supportedCountries ?? '*',
242
+ requiresOnline: true,
243
+ async initiate(input) {
244
+ if (!input.email) {
245
+ throw new Error('Customer email is required for Paystack payments.');
246
+ }
247
+ const res = await fetchImpl('https://api.paystack.co/transaction/initialize', {
248
+ method: 'POST',
249
+ headers: {
250
+ Authorization: `Bearer ${options.secretKey}`,
251
+ 'Content-Type': 'application/json',
252
+ },
253
+ body: JSON.stringify({
254
+ email: input.email,
255
+ amount: Math.round(input.amount * 100),
256
+ currency: input.currency,
257
+ reference: input.actionId,
258
+ callback_url: input.returnUrl || input.callbackUrl,
259
+ metadata: input.metadata,
260
+ }),
261
+ });
262
+ const data = await res.json();
263
+ if (!res.ok || !data?.status || !data?.data?.authorization_url) {
264
+ throw new Error(data?.message || 'Paystack did not confirm payment initialization.');
265
+ }
266
+ return {
267
+ success: true,
268
+ status: 'pending',
269
+ provider: 'paystack',
270
+ actionId: input.actionId,
271
+ providerRef: data.data.reference || input.actionId,
272
+ checkoutUrl: data.data.authorization_url,
273
+ raw: data,
274
+ };
275
+ },
276
+ async verifyWebhook(request, context) {
277
+ const signature = request.headers.get('x-paystack-signature') || '';
278
+ const rawBody = context?.rawBody ?? (await request.text());
279
+ if (!signature || !rawBody) {
280
+ return {
281
+ verified: false,
282
+ status: 'failed',
283
+ error: 'Missing Paystack signature or payload.',
284
+ };
285
+ }
286
+ const expected = await hmacHex('SHA-512', options.secretKey, rawBody);
287
+ if (!timingSafeEqualHex(signature, expected)) {
288
+ return {
289
+ verified: false,
290
+ status: 'failed',
291
+ error: 'Invalid Paystack webhook signature.',
292
+ };
293
+ }
294
+ const event = JSON.parse(rawBody);
295
+ const data = event?.data || {};
296
+ const eventName = String(event?.event || '');
297
+ if (eventName === 'charge.success') {
298
+ return {
299
+ verified: true,
300
+ actionId: data.reference,
301
+ providerRef: data.reference,
302
+ receiptNumber: String(data.id || data.reference || ''),
303
+ amount: typeof data.amount === 'number' ? data.amount / 100 : undefined,
304
+ currency: data.currency ? String(data.currency).toUpperCase() : undefined,
305
+ status: 'completed',
306
+ rawPayload: event,
307
+ };
308
+ }
309
+ if (eventName === 'charge.failed') {
310
+ return {
311
+ verified: true,
312
+ actionId: data.reference,
313
+ providerRef: data.reference,
314
+ status: 'failed',
315
+ error: String(data.gateway_response || 'Paystack charge failed.'),
316
+ rawPayload: event,
317
+ };
318
+ }
319
+ return {
320
+ verified: true,
321
+ actionId: data.reference,
322
+ providerRef: data.reference,
323
+ status: 'pending',
324
+ rawPayload: event,
325
+ };
326
+ },
327
+ };
328
+ }
329
+ /**
330
+ * Stripe Checkout Session adapter for global card/wallet/bank payments.
331
+ */
332
+ function createStripeCheckoutAdapter(options) {
333
+ const fetchImpl = options.fetch ?? globalThis.fetch;
334
+ return {
335
+ id: 'stripe',
336
+ label: 'Stripe (Card / Apple Pay / Google Pay)',
337
+ description: 'Global card and digital wallet checkout via Stripe.',
338
+ supportedCurrencies: options.supportedCurrencies ?? '*',
339
+ supportedCountries: options.supportedCountries ?? '*',
340
+ requiresOnline: true,
341
+ async initiate(input) {
342
+ if (!input.returnUrl) {
343
+ throw new Error('returnUrl is required for Stripe Checkout sessions.');
344
+ }
345
+ const params = new URLSearchParams({
346
+ mode: 'payment',
347
+ success_url: input.returnUrl,
348
+ cancel_url: input.returnUrl,
349
+ client_reference_id: input.actionId,
350
+ 'line_items[0][price_data][currency]': input.currency.toLowerCase(),
351
+ 'line_items[0][price_data][product_data][name]': input.description || 'Payment',
352
+ 'line_items[0][price_data][unit_amount]': String(Math.round(input.amount * 100)),
353
+ 'line_items[0][quantity]': '1',
354
+ });
355
+ if (input.email) {
356
+ params.set('customer_email', input.email);
357
+ }
358
+ const res = await fetchImpl('https://api.stripe.com/v1/checkout/sessions', {
359
+ method: 'POST',
360
+ headers: {
361
+ Authorization: `Bearer ${options.secretKey}`,
362
+ 'Content-Type': 'application/x-www-form-urlencoded',
363
+ },
364
+ body: params.toString(),
365
+ });
366
+ const data = await res.json();
367
+ if (!res.ok || !data?.id || !data?.url) {
368
+ throw new Error(data?.error?.message || 'Stripe did not create a checkout session.');
369
+ }
370
+ return {
371
+ success: true,
372
+ status: 'pending',
373
+ provider: 'stripe',
374
+ actionId: input.actionId,
375
+ providerRef: data.id,
376
+ checkoutUrl: data.url,
377
+ raw: data,
378
+ };
379
+ },
380
+ async verifyWebhook(request, context) {
381
+ if (!options.webhookSecret) {
382
+ return {
383
+ verified: false,
384
+ status: 'failed',
385
+ error: 'Stripe webhookSecret is not configured.',
386
+ };
387
+ }
388
+ const header = request.headers.get('stripe-signature') || '';
389
+ const rawBody = context?.rawBody ?? (await request.text());
390
+ const parts = Object.fromEntries(header.split(',').map((part) => {
391
+ const [k, v] = part.split('=');
392
+ return [k?.trim(), v?.trim()];
393
+ }));
394
+ const timestamp = parts.t;
395
+ const v1 = parts.v1;
396
+ if (!timestamp || !v1 || !rawBody) {
397
+ return {
398
+ verified: false,
399
+ status: 'failed',
400
+ error: 'Missing Stripe signature or payload.',
401
+ };
402
+ }
403
+ const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
404
+ if (!Number.isFinite(ageSeconds) || ageSeconds > 300) {
405
+ return {
406
+ verified: false,
407
+ status: 'failed',
408
+ error: 'Stripe webhook timestamp is outside tolerance.',
409
+ };
410
+ }
411
+ const expected = await hmacHex('SHA-256', options.webhookSecret, `${timestamp}.${rawBody}`);
412
+ if (!timingSafeEqualHex(v1, expected)) {
413
+ return {
414
+ verified: false,
415
+ status: 'failed',
416
+ error: 'Invalid Stripe webhook signature.',
417
+ };
418
+ }
419
+ const event = JSON.parse(rawBody);
420
+ const session = event?.data?.object || {};
421
+ const eventType = String(event?.type || '');
422
+ if (eventType === 'checkout.session.completed' ||
423
+ eventType === 'checkout.session.async_payment_succeeded') {
424
+ return {
425
+ verified: true,
426
+ actionId: session.client_reference_id,
427
+ providerRef: session.id,
428
+ receiptNumber: String(session.payment_intent || session.id || ''),
429
+ amount: typeof session.amount_total === 'number'
430
+ ? session.amount_total / 100
431
+ : undefined,
432
+ currency: session.currency
433
+ ? String(session.currency).toUpperCase()
434
+ : undefined,
435
+ status: 'completed',
436
+ rawPayload: event,
437
+ };
438
+ }
439
+ if (eventType === 'checkout.session.expired' ||
440
+ eventType === 'checkout.session.async_payment_failed') {
441
+ return {
442
+ verified: true,
443
+ actionId: session.client_reference_id,
444
+ providerRef: session.id,
445
+ status: 'failed',
446
+ error: 'Stripe checkout failed or expired.',
447
+ rawPayload: event,
448
+ };
449
+ }
450
+ return {
451
+ verified: true,
452
+ actionId: session.client_reference_id,
453
+ providerRef: session.id,
454
+ status: 'pending',
455
+ rawPayload: event,
456
+ };
457
+ },
458
+ };
459
+ }
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './registry.js';
3
+ export * from './adapters.js';
@@ -0,0 +1,19 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types.js"), exports);
18
+ __exportStar(require("./registry.js"), exports);
19
+ __exportStar(require("./adapters.js"), exports);
@@ -0,0 +1,18 @@
1
+ import type { PaymentContext, PaymentInitiateInput, PaymentInitiateResult, PaymentMethodOption, PaymentProviderAdapter, PaymentProviderId, PaymentRegistryConfig } from './types.js';
2
+ export interface PaymentRegistry {
3
+ register: (adapter: PaymentProviderAdapter) => void;
4
+ unregister: (id: PaymentProviderId) => boolean;
5
+ configure: (config: Pick<PaymentRegistryConfig, 'enabledProviders' | 'defaultCurrency'>) => void;
6
+ getProvider: (id: PaymentProviderId) => PaymentProviderAdapter | undefined;
7
+ listProviders: () => PaymentProviderAdapter[];
8
+ supports: (id: PaymentProviderId, context?: PaymentContext) => boolean;
9
+ getAvailableOptions: (context?: PaymentContext) => PaymentMethodOption[];
10
+ initiate: (input: Omit<PaymentInitiateInput, 'currency'> & {
11
+ currency?: string;
12
+ }) => Promise<PaymentInitiateResult>;
13
+ }
14
+ /**
15
+ * Creates a configurable payment provider registry that filters available
16
+ * payment methods by currency, country, online status, and enabled provider list.
17
+ */
18
+ export declare function createPaymentRegistry(initialConfig?: PaymentRegistryConfig): PaymentRegistry;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPaymentRegistry = createPaymentRegistry;
4
+ function normalizeCode(value) {
5
+ return String(value ?? '')
6
+ .trim()
7
+ .toUpperCase();
8
+ }
9
+ /**
10
+ * Creates a configurable payment provider registry that filters available
11
+ * payment methods by currency, country, online status, and enabled provider list.
12
+ */
13
+ function createPaymentRegistry(initialConfig = {}) {
14
+ const providers = new Map();
15
+ let enabledProviders = initialConfig.enabledProviders
16
+ ? new Set(initialConfig.enabledProviders)
17
+ : null;
18
+ let defaultCurrency = initialConfig.defaultCurrency
19
+ ? normalizeCode(initialConfig.defaultCurrency)
20
+ : 'USD';
21
+ for (const adapter of initialConfig.providers ?? []) {
22
+ providers.set(adapter.id, adapter);
23
+ }
24
+ function supports(id, context = {}) {
25
+ const adapter = providers.get(id);
26
+ if (!adapter)
27
+ return false;
28
+ const allowedList = context.enabledProviders ?? (enabledProviders ? [...enabledProviders] : null);
29
+ if (allowedList && !allowedList.includes(id)) {
30
+ return false;
31
+ }
32
+ const requiresOnline = adapter.requiresOnline ?? true;
33
+ if (requiresOnline && context.isOnline === false) {
34
+ return false;
35
+ }
36
+ const currency = normalizeCode(context.currency ?? defaultCurrency);
37
+ if (currency &&
38
+ adapter.supportedCurrencies !== '*' &&
39
+ !adapter.supportedCurrencies.map(normalizeCode).includes(currency)) {
40
+ return false;
41
+ }
42
+ const country = normalizeCode(context.country);
43
+ if (country &&
44
+ adapter.supportedCountries &&
45
+ adapter.supportedCountries !== '*' &&
46
+ !adapter.supportedCountries.map(normalizeCode).includes(country)) {
47
+ return false;
48
+ }
49
+ if (adapter.supports && !adapter.supports(context)) {
50
+ return false;
51
+ }
52
+ return true;
53
+ }
54
+ return {
55
+ register(adapter) {
56
+ providers.set(adapter.id, adapter);
57
+ },
58
+ unregister(id) {
59
+ return providers.delete(id);
60
+ },
61
+ configure(config) {
62
+ if (config.enabledProviders !== undefined) {
63
+ enabledProviders = config.enabledProviders
64
+ ? new Set(config.enabledProviders)
65
+ : null;
66
+ }
67
+ if (config.defaultCurrency !== undefined) {
68
+ defaultCurrency = normalizeCode(config.defaultCurrency) || defaultCurrency;
69
+ }
70
+ },
71
+ getProvider(id) {
72
+ return providers.get(id);
73
+ },
74
+ listProviders() {
75
+ return [...providers.values()];
76
+ },
77
+ supports,
78
+ getAvailableOptions(context = {}) {
79
+ return [...providers.values()]
80
+ .filter((adapter) => supports(adapter.id, context))
81
+ .map((adapter) => ({
82
+ id: adapter.id,
83
+ label: adapter.label,
84
+ description: adapter.description,
85
+ supportedCurrencies: adapter.supportedCurrencies,
86
+ supportedCountries: adapter.supportedCountries,
87
+ requiresOnline: adapter.requiresOnline ?? true,
88
+ }));
89
+ },
90
+ async initiate(input) {
91
+ const adapter = providers.get(input.provider);
92
+ if (!adapter) {
93
+ throw new Error(`Payment provider "${input.provider}" is not registered.`);
94
+ }
95
+ const currency = normalizeCode(input.currency ?? defaultCurrency);
96
+ if (!currency) {
97
+ throw new Error('Payment currency is required.');
98
+ }
99
+ if (!Number.isFinite(input.amount) || input.amount <= 0) {
100
+ throw new Error('Payment amount must be greater than zero.');
101
+ }
102
+ if (!input.actionId || typeof input.actionId !== 'string') {
103
+ throw new Error('Payment actionId is required.');
104
+ }
105
+ if (!supports(adapter.id, { currency })) {
106
+ throw new Error(`Payment provider "${adapter.id}" does not support currency "${currency}".`);
107
+ }
108
+ return adapter.initiate({
109
+ ...input,
110
+ currency,
111
+ });
112
+ },
113
+ };
114
+ }
@@ -0,0 +1,19 @@
1
+ import type { PaymentRegistry } from './registry.js';
2
+ import type { PaymentReservationRecord, PaymentReservationStore, PaymentWebhookResult } from './types.js';
3
+ export declare function sha256Hex(value: string): string;
4
+ export declare function createCallbackToken(): string;
5
+ /**
6
+ * In-memory PaymentReservationStore useful for testing and prototypes.
7
+ */
8
+ export declare function createMemoryPaymentStore(): PaymentReservationStore;
9
+ export interface PaymentServerHandlerOptions {
10
+ registry: PaymentRegistry;
11
+ store: PaymentReservationStore;
12
+ callbackBaseUrl?: string;
13
+ onCompleted?: (reservation: PaymentReservationRecord, webhook: PaymentWebhookResult) => Promise<void>;
14
+ }
15
+ /**
16
+ * Creates a framework-agnostic Fetch Request handler for idempotent payment
17
+ * initiation and webhook/callback verification across registered providers.
18
+ */
19
+ export declare function createPaymentServerHandler(options: PaymentServerHandlerOptions): (request: Request) => Promise<Response>;