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.
- package/bin/local-lite.mjs +134 -10
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/payments/adapters.d.ts +49 -0
- package/dist/payments/adapters.js +459 -0
- package/dist/payments/index.d.ts +3 -0
- package/dist/payments/index.js +19 -0
- package/dist/payments/registry.d.ts +18 -0
- package/dist/payments/registry.js +114 -0
- package/dist/payments/server.d.ts +19 -0
- package/dist/payments/server.js +235 -0
- package/dist/payments/types.d.ts +106 -0
- package/dist/payments/types.js +2 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/index.js +1 -0
- package/dist/schema/sqlMigrations.d.ts +59 -0
- package/dist/schema/sqlMigrations.js +582 -0
- package/package.json +11 -1
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.sha256Hex = sha256Hex;
|
|
7
|
+
exports.createCallbackToken = createCallbackToken;
|
|
8
|
+
exports.createMemoryPaymentStore = createMemoryPaymentStore;
|
|
9
|
+
exports.createPaymentServerHandler = createPaymentServerHandler;
|
|
10
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
11
|
+
function sha256Hex(value) {
|
|
12
|
+
return node_crypto_1.default.createHash('sha256').update(value).digest('hex');
|
|
13
|
+
}
|
|
14
|
+
function createCallbackToken() {
|
|
15
|
+
return node_crypto_1.default.randomBytes(32).toString('hex');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* In-memory PaymentReservationStore useful for testing and prototypes.
|
|
19
|
+
*/
|
|
20
|
+
function createMemoryPaymentStore() {
|
|
21
|
+
const byActionId = new Map();
|
|
22
|
+
return {
|
|
23
|
+
async findByActionId(actionId) {
|
|
24
|
+
return byActionId.get(actionId) ?? null;
|
|
25
|
+
},
|
|
26
|
+
async findByCallbackHash(callbackHash) {
|
|
27
|
+
for (const record of byActionId.values()) {
|
|
28
|
+
if (record.callbackHash === callbackHash)
|
|
29
|
+
return record;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
},
|
|
33
|
+
async findByProviderRef(providerRef) {
|
|
34
|
+
for (const record of byActionId.values()) {
|
|
35
|
+
if (record.providerRef === providerRef)
|
|
36
|
+
return record;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
},
|
|
40
|
+
async reserve(record) {
|
|
41
|
+
if (byActionId.has(record.actionId)) {
|
|
42
|
+
throw new Error(`Action ID "${record.actionId}" is already reserved.`);
|
|
43
|
+
}
|
|
44
|
+
byActionId.set(record.actionId, { ...record });
|
|
45
|
+
},
|
|
46
|
+
async markPending(actionId, update) {
|
|
47
|
+
const existing = byActionId.get(actionId);
|
|
48
|
+
if (!existing)
|
|
49
|
+
return;
|
|
50
|
+
byActionId.set(actionId, {
|
|
51
|
+
...existing,
|
|
52
|
+
status: 'pending',
|
|
53
|
+
providerRef: update.providerRef ?? existing.providerRef,
|
|
54
|
+
merchantRequestId: update.merchantRequestId ?? existing.merchantRequestId,
|
|
55
|
+
customerMessage: update.customerMessage ?? existing.customerMessage,
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
async markFinal(actionId, status, error = null) {
|
|
59
|
+
const existing = byActionId.get(actionId);
|
|
60
|
+
if (!existing)
|
|
61
|
+
return;
|
|
62
|
+
byActionId.set(actionId, {
|
|
63
|
+
...existing,
|
|
64
|
+
status,
|
|
65
|
+
error,
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates a framework-agnostic Fetch Request handler for idempotent payment
|
|
72
|
+
* initiation and webhook/callback verification across registered providers.
|
|
73
|
+
*/
|
|
74
|
+
function createPaymentServerHandler(options) {
|
|
75
|
+
const { registry, store, callbackBaseUrl, onCompleted } = options;
|
|
76
|
+
async function handleInitiate(request) {
|
|
77
|
+
const body = await request.json();
|
|
78
|
+
const actionId = body?.actionId;
|
|
79
|
+
const provider = body?.provider || 'daraja';
|
|
80
|
+
const amount = Number(body?.amount);
|
|
81
|
+
const currency = String(body?.currency || '').trim().toUpperCase();
|
|
82
|
+
if (typeof actionId !== 'string' ||
|
|
83
|
+
!actionId ||
|
|
84
|
+
actionId.length > 128 ||
|
|
85
|
+
!Number.isFinite(amount) ||
|
|
86
|
+
amount <= 0 ||
|
|
87
|
+
!currency) {
|
|
88
|
+
return Response.json({ error: 'Valid actionId, provider, currency, and amount are required.' }, { status: 400 });
|
|
89
|
+
}
|
|
90
|
+
if (!registry.supports(provider, { currency, isOnline: true })) {
|
|
91
|
+
return Response.json({ error: `Provider "${provider}" is not enabled for ${currency}.` }, { status: 400 });
|
|
92
|
+
}
|
|
93
|
+
const existing = await store.findByActionId(actionId);
|
|
94
|
+
if (existing) {
|
|
95
|
+
if (existing.provider !== provider ||
|
|
96
|
+
existing.currency !== currency ||
|
|
97
|
+
Number(existing.amount) !== amount) {
|
|
98
|
+
return Response.json({ error: 'Action ID is already in use.' }, { status: 409 });
|
|
99
|
+
}
|
|
100
|
+
if (!existing.providerRef && existing.status !== 'completed') {
|
|
101
|
+
return Response.json({ error: 'Payment is already reserved. Reconcile before retrying.' }, { status: 409 });
|
|
102
|
+
}
|
|
103
|
+
return Response.json({
|
|
104
|
+
success: true,
|
|
105
|
+
duplicate: true,
|
|
106
|
+
status: existing.status,
|
|
107
|
+
provider: existing.provider,
|
|
108
|
+
providerRef: existing.providerRef,
|
|
109
|
+
merchantRequestId: existing.merchantRequestId,
|
|
110
|
+
customerMessage: existing.customerMessage,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
const callbackToken = createCallbackToken();
|
|
114
|
+
const callbackUrl = callbackBaseUrl
|
|
115
|
+
? (() => {
|
|
116
|
+
const url = new URL(callbackBaseUrl);
|
|
117
|
+
url.searchParams.set('callback_token', callbackToken);
|
|
118
|
+
url.searchParams.set('provider', provider);
|
|
119
|
+
return url.toString();
|
|
120
|
+
})()
|
|
121
|
+
: body?.callbackUrl;
|
|
122
|
+
await store.reserve({
|
|
123
|
+
actionId,
|
|
124
|
+
provider,
|
|
125
|
+
currency,
|
|
126
|
+
amount,
|
|
127
|
+
businessId: body?.businessId,
|
|
128
|
+
userId: body?.userId,
|
|
129
|
+
tenantId: body?.tenantId,
|
|
130
|
+
contractId: body?.contractId,
|
|
131
|
+
phone: body?.phone,
|
|
132
|
+
email: body?.email,
|
|
133
|
+
callbackHash: sha256Hex(callbackToken),
|
|
134
|
+
status: 'initializing',
|
|
135
|
+
metadata: body?.metadata,
|
|
136
|
+
});
|
|
137
|
+
try {
|
|
138
|
+
const input = {
|
|
139
|
+
actionId,
|
|
140
|
+
provider,
|
|
141
|
+
amount,
|
|
142
|
+
currency,
|
|
143
|
+
businessId: body?.businessId,
|
|
144
|
+
tenantId: body?.tenantId,
|
|
145
|
+
contractId: body?.contractId,
|
|
146
|
+
userId: body?.userId,
|
|
147
|
+
phone: body?.phone,
|
|
148
|
+
email: body?.email,
|
|
149
|
+
callbackUrl,
|
|
150
|
+
returnUrl: body?.returnUrl,
|
|
151
|
+
description: body?.description,
|
|
152
|
+
metadata: body?.metadata,
|
|
153
|
+
};
|
|
154
|
+
const result = await registry.initiate(input);
|
|
155
|
+
if (result.status === 'completed') {
|
|
156
|
+
await store.markFinal(actionId, 'completed', null);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
await store.markPending(actionId, {
|
|
160
|
+
providerRef: result.providerRef,
|
|
161
|
+
merchantRequestId: result.merchantRequestId,
|
|
162
|
+
customerMessage: result.customerMessage,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return Response.json(result);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
await store
|
|
169
|
+
.markFinal(actionId, 'failed', error instanceof Error ? error.message : 'Initiation failed')
|
|
170
|
+
.catch(() => { });
|
|
171
|
+
return Response.json({
|
|
172
|
+
error: error instanceof Error
|
|
173
|
+
? error.message
|
|
174
|
+
: 'Payment initiation failed.',
|
|
175
|
+
}, { status: 502 });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function handleCallback(request) {
|
|
179
|
+
const url = new URL(request.url);
|
|
180
|
+
const token = url.searchParams.get('callback_token');
|
|
181
|
+
let reservation = null;
|
|
182
|
+
if (token && /^[a-f0-9]{64}$/.test(token) && store.findByCallbackHash) {
|
|
183
|
+
reservation = await store.findByCallbackHash(sha256Hex(token));
|
|
184
|
+
}
|
|
185
|
+
const providerId = url.searchParams.get('provider') || reservation?.provider || 'daraja';
|
|
186
|
+
const adapter = registry.getProvider(providerId);
|
|
187
|
+
if (!adapter?.verifyWebhook) {
|
|
188
|
+
return Response.json({ error: 'Unsupported payment callback provider.' }, { status: 400 });
|
|
189
|
+
}
|
|
190
|
+
const webhook = await adapter.verifyWebhook(request);
|
|
191
|
+
if (!webhook.verified) {
|
|
192
|
+
return Response.json({ error: webhook.error || 'Callback could not be verified.' }, { status: 400 });
|
|
193
|
+
}
|
|
194
|
+
if (!reservation && webhook.actionId) {
|
|
195
|
+
reservation = await store.findByActionId(webhook.actionId);
|
|
196
|
+
}
|
|
197
|
+
if (!reservation && webhook.providerRef && store.findByProviderRef) {
|
|
198
|
+
reservation = await store.findByProviderRef(webhook.providerRef);
|
|
199
|
+
}
|
|
200
|
+
if (!reservation) {
|
|
201
|
+
return Response.json({ error: 'Payment reservation not found.' }, { status: 404 });
|
|
202
|
+
}
|
|
203
|
+
if (['completed', 'failed'].includes(reservation.status)) {
|
|
204
|
+
return Response.json({ ResultCode: 0, ResultDesc: 'Already processed' });
|
|
205
|
+
}
|
|
206
|
+
if (webhook.status === 'completed') {
|
|
207
|
+
if (typeof webhook.amount === 'number' &&
|
|
208
|
+
Math.round(webhook.amount * 100) !== Math.round(reservation.amount * 100)) {
|
|
209
|
+
return Response.json({ error: 'Callback amount mismatch.' }, { status: 400 });
|
|
210
|
+
}
|
|
211
|
+
if (webhook.currency &&
|
|
212
|
+
webhook.currency.toUpperCase() !== reservation.currency.toUpperCase()) {
|
|
213
|
+
return Response.json({ error: 'Callback currency mismatch.' }, { status: 400 });
|
|
214
|
+
}
|
|
215
|
+
if (onCompleted) {
|
|
216
|
+
await onCompleted(reservation, webhook);
|
|
217
|
+
}
|
|
218
|
+
await store.markFinal(reservation.actionId, 'completed', null);
|
|
219
|
+
}
|
|
220
|
+
else if (webhook.status === 'failed') {
|
|
221
|
+
await store.markFinal(reservation.actionId, 'failed', webhook.error || 'Payment failed');
|
|
222
|
+
}
|
|
223
|
+
return Response.json({ ResultCode: 0, ResultDesc: 'Accepted' });
|
|
224
|
+
}
|
|
225
|
+
return async (request) => {
|
|
226
|
+
if (request.method !== 'POST') {
|
|
227
|
+
return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
|
|
228
|
+
}
|
|
229
|
+
const pathname = new URL(request.url).pathname;
|
|
230
|
+
if (pathname.endsWith('/callback')) {
|
|
231
|
+
return handleCallback(request);
|
|
232
|
+
}
|
|
233
|
+
return handleInitiate(request);
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
export type PaymentProviderId = 'daraja' | 'stripe' | 'paystack' | 'flutterwave' | 'manual' | (string & {});
|
|
2
|
+
export type PaymentStatus = 'initializing' | 'pending' | 'completed' | 'failed' | 'unknown';
|
|
3
|
+
export interface PaymentContext {
|
|
4
|
+
currency?: string;
|
|
5
|
+
country?: string;
|
|
6
|
+
isOnline?: boolean;
|
|
7
|
+
enabledProviders?: string[];
|
|
8
|
+
}
|
|
9
|
+
export interface PaymentMethodOption {
|
|
10
|
+
id: PaymentProviderId;
|
|
11
|
+
label: string;
|
|
12
|
+
description?: string;
|
|
13
|
+
supportedCurrencies: string[] | '*';
|
|
14
|
+
supportedCountries?: string[] | '*';
|
|
15
|
+
requiresOnline: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface PaymentInitiateInput {
|
|
18
|
+
actionId: string;
|
|
19
|
+
provider: PaymentProviderId;
|
|
20
|
+
amount: number;
|
|
21
|
+
currency: string;
|
|
22
|
+
businessId?: string;
|
|
23
|
+
tenantId?: string;
|
|
24
|
+
contractId?: string;
|
|
25
|
+
userId?: string;
|
|
26
|
+
phone?: string;
|
|
27
|
+
email?: string;
|
|
28
|
+
callbackUrl?: string;
|
|
29
|
+
returnUrl?: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
metadata?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
export interface PaymentInitiateResult {
|
|
34
|
+
success: boolean;
|
|
35
|
+
status: PaymentStatus;
|
|
36
|
+
provider: PaymentProviderId;
|
|
37
|
+
actionId: string;
|
|
38
|
+
duplicate?: boolean;
|
|
39
|
+
providerRef?: string;
|
|
40
|
+
merchantRequestId?: string;
|
|
41
|
+
checkoutUrl?: string;
|
|
42
|
+
customerMessage?: string;
|
|
43
|
+
raw?: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface PaymentWebhookResult {
|
|
46
|
+
verified: boolean;
|
|
47
|
+
actionId?: string;
|
|
48
|
+
providerRef?: string;
|
|
49
|
+
merchantRequestId?: string;
|
|
50
|
+
receiptNumber?: string;
|
|
51
|
+
amount?: number;
|
|
52
|
+
currency?: string;
|
|
53
|
+
phone?: string;
|
|
54
|
+
status: 'completed' | 'failed' | 'pending';
|
|
55
|
+
error?: string;
|
|
56
|
+
rawPayload?: unknown;
|
|
57
|
+
}
|
|
58
|
+
export interface PaymentProviderAdapter {
|
|
59
|
+
id: PaymentProviderId;
|
|
60
|
+
label: string;
|
|
61
|
+
description?: string;
|
|
62
|
+
supportedCurrencies: string[] | '*';
|
|
63
|
+
supportedCountries?: string[] | '*';
|
|
64
|
+
requiresOnline?: boolean;
|
|
65
|
+
supports?: (context: PaymentContext) => boolean;
|
|
66
|
+
initiate: (input: PaymentInitiateInput) => Promise<PaymentInitiateResult>;
|
|
67
|
+
verifyWebhook?: (request: Request, context?: {
|
|
68
|
+
rawBody?: string;
|
|
69
|
+
}) => Promise<PaymentWebhookResult>;
|
|
70
|
+
}
|
|
71
|
+
export interface PaymentRegistryConfig {
|
|
72
|
+
providers?: PaymentProviderAdapter[];
|
|
73
|
+
enabledProviders?: string[];
|
|
74
|
+
defaultCurrency?: string;
|
|
75
|
+
}
|
|
76
|
+
export interface PaymentReservationRecord {
|
|
77
|
+
actionId: string;
|
|
78
|
+
provider: PaymentProviderId;
|
|
79
|
+
currency: string;
|
|
80
|
+
amount: number;
|
|
81
|
+
businessId?: string;
|
|
82
|
+
userId?: string;
|
|
83
|
+
tenantId?: string;
|
|
84
|
+
contractId?: string;
|
|
85
|
+
phone?: string;
|
|
86
|
+
email?: string;
|
|
87
|
+
callbackHash?: string;
|
|
88
|
+
providerRef?: string;
|
|
89
|
+
merchantRequestId?: string;
|
|
90
|
+
customerMessage?: string;
|
|
91
|
+
status: PaymentStatus;
|
|
92
|
+
error?: string | null;
|
|
93
|
+
metadata?: Record<string, unknown>;
|
|
94
|
+
}
|
|
95
|
+
export interface PaymentReservationStore {
|
|
96
|
+
findByActionId: (actionId: string) => Promise<PaymentReservationRecord | null>;
|
|
97
|
+
findByCallbackHash?: (callbackHash: string) => Promise<PaymentReservationRecord | null>;
|
|
98
|
+
findByProviderRef?: (providerRef: string) => Promise<PaymentReservationRecord | null>;
|
|
99
|
+
reserve: (record: PaymentReservationRecord) => Promise<void>;
|
|
100
|
+
markPending: (actionId: string, update: {
|
|
101
|
+
providerRef?: string;
|
|
102
|
+
merchantRequestId?: string;
|
|
103
|
+
customerMessage?: string;
|
|
104
|
+
}) => Promise<void>;
|
|
105
|
+
markFinal: (actionId: string, status: Extract<PaymentStatus, 'completed' | 'failed' | 'unknown'>, error?: string | null) => Promise<void>;
|
|
106
|
+
}
|
package/dist/schema/index.d.ts
CHANGED
package/dist/schema/index.js
CHANGED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export type SchemaFieldType = 'string' | 'string | null' | 'number' | 'number | null' | 'boolean' | 'boolean | null' | 'json' | 'json | null' | 'string[]' | 'string[] | null';
|
|
2
|
+
export type SchemaDictionary = Record<string, Record<string, SchemaFieldType>>;
|
|
3
|
+
export interface SqlColumnDef {
|
|
4
|
+
sqlType: string;
|
|
5
|
+
nullable: boolean;
|
|
6
|
+
defaultSql: string | null;
|
|
7
|
+
primaryKey?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface SqlIndexDef {
|
|
10
|
+
name: string;
|
|
11
|
+
columns: string[];
|
|
12
|
+
}
|
|
13
|
+
export interface SqlTableDef {
|
|
14
|
+
columns: Record<string, SqlColumnDef>;
|
|
15
|
+
indexes: SqlIndexDef[];
|
|
16
|
+
}
|
|
17
|
+
export interface SqlSchemaState {
|
|
18
|
+
version: number;
|
|
19
|
+
tables: Record<string, SqlTableDef>;
|
|
20
|
+
}
|
|
21
|
+
export type SqlDialect = 'mysql' | 'postgres' | 'sqlite';
|
|
22
|
+
export interface GenerateSqlMigrationOptions {
|
|
23
|
+
dictionary: SchemaDictionary;
|
|
24
|
+
migrationsDir: string;
|
|
25
|
+
dialect?: SqlDialect;
|
|
26
|
+
tableOrder?: readonly string[];
|
|
27
|
+
name?: string;
|
|
28
|
+
dryRun?: boolean;
|
|
29
|
+
serverSchemaPath?: string;
|
|
30
|
+
longTextColumns?: Iterable<string>;
|
|
31
|
+
bigintColumns?: Iterable<string>;
|
|
32
|
+
}
|
|
33
|
+
export interface GenerateSqlMigrationResult {
|
|
34
|
+
up: string[];
|
|
35
|
+
down: string[];
|
|
36
|
+
warnings: string[];
|
|
37
|
+
sql: string;
|
|
38
|
+
migrationPath?: string;
|
|
39
|
+
serverSchemaPath?: string;
|
|
40
|
+
schema: SqlSchemaState;
|
|
41
|
+
}
|
|
42
|
+
export declare function mapFieldTypeToSql(colName: string, fieldType: SchemaFieldType, options?: {
|
|
43
|
+
dialect?: SqlDialect;
|
|
44
|
+
longTextColumns?: Set<string>;
|
|
45
|
+
bigintColumns?: Set<string>;
|
|
46
|
+
}): SqlColumnDef;
|
|
47
|
+
export declare function buildSqlTargetSchema(dictionary: SchemaDictionary, tableOrder?: readonly string[], options?: {
|
|
48
|
+
dialect?: SqlDialect;
|
|
49
|
+
longTextColumns?: Iterable<string>;
|
|
50
|
+
bigintColumns?: Iterable<string>;
|
|
51
|
+
}): SqlSchemaState;
|
|
52
|
+
export declare function generateSqlDiff(prevSchema: SqlSchemaState | null, nextSchema: SqlSchemaState, dialect?: SqlDialect): {
|
|
53
|
+
up: string[];
|
|
54
|
+
down: string[];
|
|
55
|
+
warnings: string[];
|
|
56
|
+
};
|
|
57
|
+
export declare function loadSqlSchemaFromMigrations(migrationsDir: string): SqlSchemaState | null;
|
|
58
|
+
export declare function formatSyncedSchemaTs(schema: SqlSchemaState): string;
|
|
59
|
+
export declare function generateSqlMigration(options: GenerateSqlMigrationOptions): GenerateSqlMigrationResult;
|