local-lite 1.0.4 → 2.0.1

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 (39) hide show
  1. package/dist/adapters/local/better-sqlite3.js +10 -3
  2. package/dist/adapters/local/expo-sqlite.js +3 -3
  3. package/dist/adapters/local/node-sqlite.js +10 -3
  4. package/dist/adapters/remote/index.d.ts +5 -2
  5. package/dist/adapters/remote/self-hosted.d.ts +3 -3
  6. package/dist/adapters/remote/self-hosted.js +17 -4
  7. package/dist/adapters/remote/supabase.d.ts +1 -2
  8. package/dist/config/index.d.ts +0 -1
  9. package/dist/config/index.js +3 -10
  10. package/dist/config/types.d.ts +5 -10
  11. package/dist/core/client.d.ts +3 -12
  12. package/dist/core/client.js +166 -59
  13. package/dist/core/outbox-store.d.ts +1 -1
  14. package/dist/core/outbox-store.js +58 -21
  15. package/dist/core/query-builder.js +36 -45
  16. package/dist/core/sync-worker.d.ts +12 -2
  17. package/dist/core/sync-worker.js +84 -21
  18. package/dist/core/table-manager.js +19 -8
  19. package/dist/core/types.d.ts +1 -0
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/payments/adapters.d.ts +49 -0
  23. package/dist/payments/adapters.js +459 -0
  24. package/dist/payments/index.d.ts +3 -0
  25. package/dist/payments/index.js +19 -0
  26. package/dist/payments/registry.d.ts +18 -0
  27. package/dist/payments/registry.js +114 -0
  28. package/dist/payments/server.d.ts +19 -0
  29. package/dist/payments/server.js +235 -0
  30. package/dist/payments/types.d.ts +106 -0
  31. package/dist/payments/types.js +2 -0
  32. package/dist/react/index.js +54 -2
  33. package/dist/server/sync.d.ts +38 -0
  34. package/dist/server/sync.js +214 -2
  35. package/dist/storage/supabase.d.ts +7 -2
  36. package/package.json +14 -5
  37. package/skills/local-lite-auth/SKILL.md +1 -1
  38. package/skills/local-lite-setup/SKILL.md +1 -1
  39. package/skills/local-lite-upgrade/SKILL.md +32 -9
@@ -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
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -161,6 +161,42 @@ function clearLiveQueryCache() {
161
161
  queryCache.clear();
162
162
  inFlightQueries.clear();
163
163
  }
164
+ function isPlainEqualityMatch(actual, expected) {
165
+ if (typeof expected === 'boolean') {
166
+ return actual === expected || actual === (expected ? 1 : 0);
167
+ }
168
+ return actual === expected;
169
+ }
170
+ function shouldInvalidateLiveQuery(event, options, currentRows, primaryKey) {
171
+ if (!event || !event.rowId || event.rowId === 'batch')
172
+ return true;
173
+ if (!options || !options.where || typeof options.where === 'function') {
174
+ return true;
175
+ }
176
+ const rowIdStr = String(event.rowId);
177
+ const inResult = currentRows.some((r) => r && r[primaryKey] !== undefined && String(r[primaryKey]) === rowIdStr);
178
+ if (event.operation === 'DELETE') {
179
+ return inResult;
180
+ }
181
+ if ((event.operation === 'INSERT' || event.operation === 'UPDATE') &&
182
+ !inResult &&
183
+ event.payload &&
184
+ typeof event.payload === 'object') {
185
+ const whereObj = options.where;
186
+ if ('$or' in whereObj || '$and' in whereObj)
187
+ return true;
188
+ for (const [key, expected] of Object.entries(whereObj)) {
189
+ if (expected !== null && typeof expected === 'object')
190
+ continue;
191
+ if (Object.prototype.hasOwnProperty.call(event.payload, key)) {
192
+ if (!isPlainEqualityMatch(event.payload[key], expected)) {
193
+ return false;
194
+ }
195
+ }
196
+ }
197
+ }
198
+ return true;
199
+ }
164
200
  /**
165
201
  * Hook to execute a live reactive table query that automatically re-runs
166
202
  * whenever the table is mutated locally or via incoming remote delta.
@@ -224,11 +260,21 @@ function useLiveQuery(client, tableName, queryOrOptions) {
224
260
  }
225
261
  }, [client, tableName, cacheKey]);
226
262
  const scheduleRefetch = (0, runner_js_1.useCoalescedRunner)(refetch);
263
+ const dataRef = (0, react_1.useRef)(data);
264
+ dataRef.current = data;
227
265
  (0, react_1.useEffect)(() => {
228
266
  if (!client || !client.db)
229
267
  return;
230
268
  refetch();
231
- const unsubscribe = client.events.on(tableName, () => {
269
+ const pk = client.getPrimaryKey();
270
+ const unsubscribe = client.events.on(tableName, (event) => {
271
+ const opts = typeof queryParamRef.current === 'object' &&
272
+ queryParamRef.current !== null
273
+ ? queryParamRef.current
274
+ : undefined;
275
+ if (!shouldInvalidateLiveQuery(event, opts, dataRef.current, pk)) {
276
+ return;
277
+ }
232
278
  advanceTableVersion(client, tableName);
233
279
  scheduleRefetch();
234
280
  });
@@ -545,6 +591,8 @@ function useLiveInfiniteQuery(client, tableName, options = {}) {
545
591
  await loadData(pageCountRef.current, false);
546
592
  }, [loadData]);
547
593
  const scheduleRefetch = (0, runner_js_1.useCoalescedRunner)(refetch);
594
+ const dataRef = (0, react_1.useRef)(data);
595
+ dataRef.current = data;
548
596
  const fetchNextPage = (0, react_1.useCallback)(async () => {
549
597
  if (!hasNextPage || isFetchingNextPage)
550
598
  return;
@@ -556,7 +604,11 @@ function useLiveInfiniteQuery(client, tableName, options = {}) {
556
604
  if (!client || !client.db)
557
605
  return;
558
606
  loadData(1, false);
559
- const unsubscribe = client.events.on(tableName, () => {
607
+ const pk = client.getPrimaryKey();
608
+ const unsubscribe = client.events.on(tableName, (event) => {
609
+ if (!shouldInvalidateLiveQuery(event, optionsRef.current, dataRef.current, pk)) {
610
+ return;
611
+ }
560
612
  advanceTableVersion(client, tableName);
561
613
  scheduleRefetch();
562
614
  });
@@ -1,4 +1,5 @@
1
1
  import type { DeltaChanges, SyncOperation, SyncOp } from '../core/types.js';
2
+ import type { LocalDBAdapter } from '../adapters/local/index.js';
2
3
  import type { ApiEndpoint } from './index.js';
3
4
  export interface ServerSyncRecord {
4
5
  rowId: string;
@@ -36,6 +37,10 @@ export declare class MemoryServerSyncStorage implements ServerSyncStorage {
36
37
  private tables;
37
38
  private changeLog;
38
39
  private monotonicCursor;
40
+ private maxChangeLogEntries;
41
+ constructor(options?: {
42
+ maxChangeLogEntries?: number;
43
+ });
39
44
  applyOperations(operations: SyncOperation[], overrideTime?: number): Promise<{
40
45
  applied: number;
41
46
  successfulIds: string[];
@@ -53,6 +58,39 @@ export declare class MemoryServerSyncStorage implements ServerSyncStorage {
53
58
  */
54
59
  clear(): void;
55
60
  }
61
+ export interface SQLiteServerSyncStorageOptions {
62
+ /**
63
+ * Optional maximum changelog entries to retain. Older entries are compacted after writes.
64
+ */
65
+ maxChangeLogEntries?: number;
66
+ }
67
+ /**
68
+ * Persistent SQLite-backed ServerSyncStorage for production self-hosted sync servers.
69
+ * Works with any LocalDBAdapter (e.g. BetterSQLite3Adapter, NodeSQLiteAdapter, LibSQLAdapter).
70
+ */
71
+ export declare class SQLiteServerSyncStorage implements ServerSyncStorage {
72
+ private db;
73
+ private initPromise?;
74
+ private maxChangeLogEntries?;
75
+ constructor(db: LocalDBAdapter, options?: SQLiteServerSyncStorageOptions);
76
+ private ensureSchema;
77
+ applyOperations(operations: SyncOperation[], overrideTime?: number): Promise<{
78
+ applied: number;
79
+ successfulIds: string[];
80
+ serverTime: number;
81
+ cursor: number;
82
+ }>;
83
+ getDeltas(tables: string[], since: number, limit?: number): Promise<{
84
+ changes: DeltaChanges;
85
+ cursor: number;
86
+ hasMore: boolean;
87
+ serverTime: number;
88
+ }>;
89
+ /**
90
+ * Compacts older changelog entries, retaining the most recent `retentionCount` rows.
91
+ */
92
+ compactChangeLog(retentionCount?: number): Promise<void>;
93
+ }
56
94
  export interface ServerSyncEndpointOptions {
57
95
  /**
58
96
  * Optional secret token expected in `Authorization: Bearer <token>` or `x-sync-secret`.