local-lite 3.0.5 → 3.0.6
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/dist/adapters/remote/self-hosted.d.ts +12 -0
- package/dist/adapters/remote/self-hosted.js +46 -0
- package/dist/payments/server.d.ts +6 -0
- package/dist/payments/server.js +135 -2
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.js +56 -22
- package/dist/server/sqlSyncStorage.d.ts +30 -0
- package/dist/server/sqlSyncStorage.js +118 -0
- package/package.json +1 -1
|
@@ -37,6 +37,14 @@ export interface SelfHostedRemoteAdapterOptions {
|
|
|
37
37
|
* Optional WebSocket constructor override (defaults to globalThis.WebSocket).
|
|
38
38
|
*/
|
|
39
39
|
WebSocketImpl?: typeof WebSocket;
|
|
40
|
+
/**
|
|
41
|
+
* Optional Server-Sent Events (SSE) URL for instant push delta notifications.
|
|
42
|
+
*/
|
|
43
|
+
sseUrl?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Optional EventSource constructor override (defaults to globalThis.EventSource).
|
|
46
|
+
*/
|
|
47
|
+
EventSourceImpl?: typeof EventSource;
|
|
40
48
|
}
|
|
41
49
|
/**
|
|
42
50
|
* Universal client remote adapter for self-hosted local-lite sync backends.
|
|
@@ -56,6 +64,9 @@ export declare class SelfHostedRemoteAdapter implements RemoteDBAdapter {
|
|
|
56
64
|
private wsUrl?;
|
|
57
65
|
private WebSocketImpl?;
|
|
58
66
|
private ws?;
|
|
67
|
+
private sseUrl?;
|
|
68
|
+
private EventSourceImpl?;
|
|
69
|
+
private sse?;
|
|
59
70
|
constructor(options: SelfHostedRemoteAdapterOptions);
|
|
60
71
|
private getRequestHeaders;
|
|
61
72
|
/**
|
|
@@ -70,6 +81,7 @@ export declare class SelfHostedRemoteAdapter implements RemoteDBAdapter {
|
|
|
70
81
|
* Subscribes to live server changes via periodic polling.
|
|
71
82
|
*/
|
|
72
83
|
subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
|
|
84
|
+
private connectSse;
|
|
73
85
|
private connectWebSocket;
|
|
74
86
|
private startPolling;
|
|
75
87
|
setSyncScope(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
|
|
@@ -19,6 +19,9 @@ class SelfHostedRemoteAdapter {
|
|
|
19
19
|
wsUrl;
|
|
20
20
|
WebSocketImpl;
|
|
21
21
|
ws;
|
|
22
|
+
sseUrl;
|
|
23
|
+
EventSourceImpl;
|
|
24
|
+
sse;
|
|
22
25
|
constructor(options) {
|
|
23
26
|
if (!options.url) {
|
|
24
27
|
throw new Error("A valid 'url' is required for SelfHostedRemoteAdapter.");
|
|
@@ -31,6 +34,9 @@ class SelfHostedRemoteAdapter {
|
|
|
31
34
|
this.pollIntervalMs = options.pollIntervalMs ?? 5000;
|
|
32
35
|
this.wsUrl = options.wsUrl;
|
|
33
36
|
this.WebSocketImpl = options.WebSocketImpl ?? globalThis.WebSocket;
|
|
37
|
+
this.sseUrl = options.sseUrl;
|
|
38
|
+
this.EventSourceImpl =
|
|
39
|
+
options.EventSourceImpl ?? globalThis.EventSource;
|
|
34
40
|
if (!this.fetchFn) {
|
|
35
41
|
throw new Error('A global or configured fetch function is required for SelfHostedRemoteAdapter.');
|
|
36
42
|
}
|
|
@@ -111,6 +117,11 @@ class SelfHostedRemoteAdapter {
|
|
|
111
117
|
this.connectWebSocket();
|
|
112
118
|
}
|
|
113
119
|
}
|
|
120
|
+
else if (this.sseUrl && typeof this.EventSourceImpl === 'function') {
|
|
121
|
+
if (!this.sse) {
|
|
122
|
+
this.connectSse();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
114
125
|
else if (!this.pollTimer) {
|
|
115
126
|
this.startPolling();
|
|
116
127
|
}
|
|
@@ -128,6 +139,41 @@ class SelfHostedRemoteAdapter {
|
|
|
128
139
|
catch { }
|
|
129
140
|
this.ws = undefined;
|
|
130
141
|
}
|
|
142
|
+
if (this.sse) {
|
|
143
|
+
try {
|
|
144
|
+
this.sse.close();
|
|
145
|
+
}
|
|
146
|
+
catch { }
|
|
147
|
+
this.sse = undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
connectSse() {
|
|
153
|
+
if (!this.sseUrl || typeof this.EventSourceImpl !== 'function')
|
|
154
|
+
return;
|
|
155
|
+
const urlWithAuth = this.token
|
|
156
|
+
? `${this.sseUrl}${this.sseUrl.includes('?') ? '&' : '?'}token=${encodeURIComponent(this.token)}`
|
|
157
|
+
: this.sseUrl;
|
|
158
|
+
const source = new this.EventSourceImpl(urlWithAuth);
|
|
159
|
+
this.sse = source;
|
|
160
|
+
source.onmessage = () => {
|
|
161
|
+
this.fetchChanges(this.lastPollCursor, this.syncScope)
|
|
162
|
+
.then((deltas) => {
|
|
163
|
+
if (deltas.changes.length > 0) {
|
|
164
|
+
this.activeSubscribers.forEach((cb) => cb(deltas));
|
|
165
|
+
}
|
|
166
|
+
})
|
|
167
|
+
.catch(() => { });
|
|
168
|
+
};
|
|
169
|
+
source.onerror = () => {
|
|
170
|
+
try {
|
|
171
|
+
source.close();
|
|
172
|
+
}
|
|
173
|
+
catch { }
|
|
174
|
+
this.sse = undefined;
|
|
175
|
+
if (this.activeSubscribers.size > 0 && !this.pollTimer) {
|
|
176
|
+
this.startPolling();
|
|
131
177
|
}
|
|
132
178
|
};
|
|
133
179
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SqlExecutor } from '../server/sqlDialect.js';
|
|
1
2
|
import type { PaymentRegistry } from './registry.js';
|
|
2
3
|
import type { PaymentReservationRecord, PaymentReservationStore, PaymentWebhookResult } from './types.js';
|
|
3
4
|
export declare function sha256Hex(value: string): string;
|
|
@@ -6,11 +7,16 @@ export declare function createCallbackToken(): string;
|
|
|
6
7
|
* In-memory PaymentReservationStore useful for testing and prototypes.
|
|
7
8
|
*/
|
|
8
9
|
export declare function createMemoryPaymentStore(): PaymentReservationStore;
|
|
10
|
+
/**
|
|
11
|
+
* SQL-backed PaymentReservationStore for MySQL and PostgreSQL servers.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createSqlPaymentStore(executor: SqlExecutor, tableName?: string): PaymentReservationStore;
|
|
9
14
|
export interface PaymentServerHandlerOptions {
|
|
10
15
|
registry: PaymentRegistry;
|
|
11
16
|
store: PaymentReservationStore;
|
|
12
17
|
callbackBaseUrl?: string;
|
|
13
18
|
onCompleted?: (reservation: PaymentReservationRecord, webhook: PaymentWebhookResult) => Promise<void>;
|
|
19
|
+
onReconcile?: (reservation: PaymentReservationRecord, request: Request) => Promise<Response>;
|
|
14
20
|
}
|
|
15
21
|
/**
|
|
16
22
|
* Creates a framework-agnostic Fetch Request handler for idempotent payment
|
package/dist/payments/server.js
CHANGED
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.sha256Hex = sha256Hex;
|
|
7
7
|
exports.createCallbackToken = createCallbackToken;
|
|
8
8
|
exports.createMemoryPaymentStore = createMemoryPaymentStore;
|
|
9
|
+
exports.createSqlPaymentStore = createSqlPaymentStore;
|
|
9
10
|
exports.createPaymentServerHandler = createPaymentServerHandler;
|
|
10
11
|
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
11
12
|
function sha256Hex(value) {
|
|
@@ -67,12 +68,81 @@ function createMemoryPaymentStore() {
|
|
|
67
68
|
},
|
|
68
69
|
};
|
|
69
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* SQL-backed PaymentReservationStore for MySQL and PostgreSQL servers.
|
|
73
|
+
*/
|
|
74
|
+
function createSqlPaymentStore(executor, tableName = '_payment_requests') {
|
|
75
|
+
const mapRow = (row) => {
|
|
76
|
+
if (!row)
|
|
77
|
+
return null;
|
|
78
|
+
return {
|
|
79
|
+
actionId: String(row.action_id),
|
|
80
|
+
provider: (row.provider || 'daraja'),
|
|
81
|
+
amount: Number(row.amount),
|
|
82
|
+
currency: String(row.currency || 'KES'),
|
|
83
|
+
businessId: String(row.business_id),
|
|
84
|
+
tenantId: String(row.tenant_id),
|
|
85
|
+
contractId: String(row.contract_id),
|
|
86
|
+
userId: String(row.user_id),
|
|
87
|
+
phone: row.phone ? String(row.phone) : undefined,
|
|
88
|
+
callbackHash: String(row.callback_hash),
|
|
89
|
+
status: row.status,
|
|
90
|
+
providerRef: row.checkout_id ? String(row.checkout_id) : undefined,
|
|
91
|
+
merchantRequestId: row.merchant_id ? String(row.merchant_id) : undefined,
|
|
92
|
+
customerMessage: row.customer_message
|
|
93
|
+
? String(row.customer_message)
|
|
94
|
+
: undefined,
|
|
95
|
+
error: row.error ? String(row.error) : null,
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
async findByActionId(actionId) {
|
|
100
|
+
const rows = await executor.query(`SELECT * FROM ${tableName} WHERE action_id = ? LIMIT 1`, [actionId]);
|
|
101
|
+
return mapRow(rows[0]);
|
|
102
|
+
},
|
|
103
|
+
async findByCallbackHash(callbackHash) {
|
|
104
|
+
const rows = await executor.query(`SELECT * FROM ${tableName} WHERE callback_hash = ? LIMIT 1`, [callbackHash]);
|
|
105
|
+
return mapRow(rows[0]);
|
|
106
|
+
},
|
|
107
|
+
async findByProviderRef(providerRef) {
|
|
108
|
+
const rows = await executor.query(`SELECT * FROM ${tableName} WHERE checkout_id = ? OR action_id = ? LIMIT 1`, [providerRef, providerRef]);
|
|
109
|
+
return mapRow(rows[0]);
|
|
110
|
+
},
|
|
111
|
+
async reserve(record) {
|
|
112
|
+
await executor.execute(`INSERT INTO ${tableName} (action_id, business_id, user_id, tenant_id, contract_id, provider, currency, phone, amount, callback_hash, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
113
|
+
record.actionId,
|
|
114
|
+
record.businessId,
|
|
115
|
+
record.userId,
|
|
116
|
+
record.tenantId,
|
|
117
|
+
record.contractId,
|
|
118
|
+
record.provider,
|
|
119
|
+
record.currency,
|
|
120
|
+
record.phone || '',
|
|
121
|
+
record.amount,
|
|
122
|
+
record.callbackHash,
|
|
123
|
+
record.status,
|
|
124
|
+
]);
|
|
125
|
+
},
|
|
126
|
+
async markPending(actionId, update) {
|
|
127
|
+
await executor.execute(`UPDATE ${tableName} SET status = ?, checkout_id = ?, merchant_id = ?, customer_message = ? WHERE action_id = ?`, [
|
|
128
|
+
'pending',
|
|
129
|
+
update.providerRef || actionId,
|
|
130
|
+
update.merchantRequestId || null,
|
|
131
|
+
update.customerMessage || '',
|
|
132
|
+
actionId,
|
|
133
|
+
]);
|
|
134
|
+
},
|
|
135
|
+
async markFinal(actionId, status, error = null) {
|
|
136
|
+
await executor.execute(`UPDATE ${tableName} SET status = ?, error = ? WHERE action_id = ?`, [status, error, actionId]);
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
70
140
|
/**
|
|
71
141
|
* Creates a framework-agnostic Fetch Request handler for idempotent payment
|
|
72
142
|
* initiation and webhook/callback verification across registered providers.
|
|
73
143
|
*/
|
|
74
144
|
function createPaymentServerHandler(options) {
|
|
75
|
-
const { registry, store, callbackBaseUrl, onCompleted } = options;
|
|
145
|
+
const { registry, store, callbackBaseUrl, onCompleted, onReconcile } = options;
|
|
76
146
|
async function handleInitiate(request) {
|
|
77
147
|
const body = await request.json();
|
|
78
148
|
const actionId = body?.actionId;
|
|
@@ -222,14 +292,77 @@ function createPaymentServerHandler(options) {
|
|
|
222
292
|
}
|
|
223
293
|
return Response.json({ ResultCode: 0, ResultDesc: 'Accepted' });
|
|
224
294
|
}
|
|
295
|
+
async function handleOptions(request) {
|
|
296
|
+
const url = new URL(request.url);
|
|
297
|
+
let currency = url.searchParams.get('currency') || undefined;
|
|
298
|
+
let country = url.searchParams.get('country') || undefined;
|
|
299
|
+
if (request.method === 'POST') {
|
|
300
|
+
const body = await request.json().catch(() => null);
|
|
301
|
+
currency = body?.currency || currency;
|
|
302
|
+
country = body?.country || country;
|
|
303
|
+
}
|
|
304
|
+
return Response.json({
|
|
305
|
+
options: registry.getAvailableOptions({
|
|
306
|
+
currency,
|
|
307
|
+
country,
|
|
308
|
+
isOnline: true,
|
|
309
|
+
}),
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
async function handleStatus(request) {
|
|
313
|
+
const url = new URL(request.url);
|
|
314
|
+
const ref = url.searchParams.get('checkoutRequestId') ||
|
|
315
|
+
url.searchParams.get('actionId') ||
|
|
316
|
+
'';
|
|
317
|
+
if (!ref) {
|
|
318
|
+
return Response.json({ error: 'checkoutRequestId is required.' }, { status: 400 });
|
|
319
|
+
}
|
|
320
|
+
const row = (store.findByProviderRef ? await store.findByProviderRef(ref) : null) ??
|
|
321
|
+
(await store.findByActionId(ref));
|
|
322
|
+
if (!row) {
|
|
323
|
+
return Response.json({ status: 'pending' });
|
|
324
|
+
}
|
|
325
|
+
return Response.json({
|
|
326
|
+
status: row.status,
|
|
327
|
+
error: row.error || undefined,
|
|
328
|
+
amount: row.amount,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
async function handleReconcile(request) {
|
|
332
|
+
if (!onReconcile) {
|
|
333
|
+
return Response.json({ error: 'Payment reconciliation is not configured.' }, { status: 501 });
|
|
334
|
+
}
|
|
335
|
+
const body = await request.json().catch(() => null);
|
|
336
|
+
const actionId = body?.actionId;
|
|
337
|
+
if (typeof actionId !== 'string' || !actionId || actionId.length > 128) {
|
|
338
|
+
return Response.json({ error: 'Valid actionId is required.' }, { status: 400 });
|
|
339
|
+
}
|
|
340
|
+
const reservation = await store.findByActionId(actionId);
|
|
341
|
+
if (!reservation) {
|
|
342
|
+
return Response.json({ error: 'Payment request not found.' }, { status: 404 });
|
|
343
|
+
}
|
|
344
|
+
return await onReconcile(reservation, request);
|
|
345
|
+
}
|
|
225
346
|
return async (request) => {
|
|
347
|
+
const pathname = new URL(request.url).pathname;
|
|
348
|
+
if (pathname.endsWith('/options')) {
|
|
349
|
+
if (!['GET', 'POST'].includes(request.method)) {
|
|
350
|
+
return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
|
|
351
|
+
}
|
|
352
|
+
return handleOptions(request);
|
|
353
|
+
}
|
|
354
|
+
if (pathname.endsWith('/status') && request.method === 'GET') {
|
|
355
|
+
return handleStatus(request);
|
|
356
|
+
}
|
|
226
357
|
if (request.method !== 'POST') {
|
|
227
358
|
return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
|
|
228
359
|
}
|
|
229
|
-
const pathname = new URL(request.url).pathname;
|
|
230
360
|
if (pathname.endsWith('/callback')) {
|
|
231
361
|
return handleCallback(request);
|
|
232
362
|
}
|
|
363
|
+
if (pathname.endsWith('/reconcile')) {
|
|
364
|
+
return handleReconcile(request);
|
|
365
|
+
}
|
|
233
366
|
return handleInitiate(request);
|
|
234
367
|
};
|
|
235
368
|
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
export type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
1
|
+
export type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'ALL';
|
|
2
2
|
export * from './email.js';
|
|
3
3
|
export * from './sync.js';
|
|
4
4
|
export * from './auth.js';
|
|
5
5
|
export * from './dashboard.js';
|
|
6
6
|
export * from './sqlDialect.js';
|
|
7
|
+
export * from './sqlSyncStorage.js';
|
|
7
8
|
export * from './syncEvents.js';
|
|
8
9
|
export * from './scheduler.js';
|
|
9
10
|
export interface ApiRequestContext<TConfig = unknown> {
|
package/dist/server/index.js
CHANGED
|
@@ -21,6 +21,7 @@ __exportStar(require("./sync.js"), exports);
|
|
|
21
21
|
__exportStar(require("./auth.js"), exports);
|
|
22
22
|
__exportStar(require("./dashboard.js"), exports);
|
|
23
23
|
__exportStar(require("./sqlDialect.js"), exports);
|
|
24
|
+
__exportStar(require("./sqlSyncStorage.js"), exports);
|
|
24
25
|
__exportStar(require("./syncEvents.js"), exports);
|
|
25
26
|
__exportStar(require("./scheduler.js"), exports);
|
|
26
27
|
function normalizePath(path) {
|
|
@@ -30,6 +31,31 @@ function normalizePath(path) {
|
|
|
30
31
|
function matchPath(pattern, pathname) {
|
|
31
32
|
const patternSegments = normalizePath(pattern).split('/').filter(Boolean);
|
|
32
33
|
const pathSegments = normalizePath(pathname).split('/').filter(Boolean);
|
|
34
|
+
const hasWildcard = patternSegments.length > 0 &&
|
|
35
|
+
patternSegments[patternSegments.length - 1] === '*';
|
|
36
|
+
if (hasWildcard) {
|
|
37
|
+
const prefixSegments = patternSegments.slice(0, -1);
|
|
38
|
+
if (pathSegments.length < prefixSegments.length)
|
|
39
|
+
return null;
|
|
40
|
+
const params = {};
|
|
41
|
+
for (let index = 0; index < prefixSegments.length; index += 1) {
|
|
42
|
+
const expected = prefixSegments[index];
|
|
43
|
+
const actual = pathSegments[index];
|
|
44
|
+
if (expected.startsWith(':')) {
|
|
45
|
+
try {
|
|
46
|
+
params[expected.slice(1)] = decodeURIComponent(actual);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
else if (expected !== actual) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
params['*'] = pathSegments.slice(prefixSegments.length).join('/');
|
|
57
|
+
return params;
|
|
58
|
+
}
|
|
33
59
|
if (patternSegments.length !== pathSegments.length)
|
|
34
60
|
return null;
|
|
35
61
|
const params = {};
|
|
@@ -74,21 +100,13 @@ function createServer(config) {
|
|
|
74
100
|
path: normalizePath(path),
|
|
75
101
|
endpoint,
|
|
76
102
|
}));
|
|
77
|
-
const
|
|
78
|
-
const method = request.method.toUpperCase();
|
|
79
|
-
const url = new URL(request.url);
|
|
80
|
-
const params = matchPath(pathPattern, url.pathname);
|
|
81
|
-
const handler = endpoint[method];
|
|
103
|
+
const runWithMiddleware = async (request, pathPattern, params, finalHandler) => {
|
|
82
104
|
const context = {
|
|
83
105
|
request,
|
|
84
106
|
config: config.config,
|
|
85
107
|
path: pathPattern,
|
|
86
|
-
params
|
|
108
|
+
params,
|
|
87
109
|
};
|
|
88
|
-
if (!params)
|
|
89
|
-
return Response.json({ error: 'Not Found' }, { status: 404 });
|
|
90
|
-
if (!handler)
|
|
91
|
-
return methodNotAllowed(Object.keys(endpoint));
|
|
92
110
|
const stack = config.middleware ?? [];
|
|
93
111
|
let index = -1;
|
|
94
112
|
const dispatch = async (position) => {
|
|
@@ -97,7 +115,7 @@ function createServer(config) {
|
|
|
97
115
|
index = position;
|
|
98
116
|
const middleware = stack[position];
|
|
99
117
|
if (!middleware)
|
|
100
|
-
return await
|
|
118
|
+
return await finalHandler(context);
|
|
101
119
|
return await middleware(context, () => dispatch(position + 1));
|
|
102
120
|
};
|
|
103
121
|
try {
|
|
@@ -113,6 +131,17 @@ function createServer(config) {
|
|
|
113
131
|
return Response.json({ error: 'Internal Server Error' }, { status: 500 });
|
|
114
132
|
}
|
|
115
133
|
};
|
|
134
|
+
const run = async (request, pathPattern, endpoint) => {
|
|
135
|
+
const method = request.method.toUpperCase();
|
|
136
|
+
const url = new URL(request.url);
|
|
137
|
+
const params = matchPath(pathPattern, url.pathname);
|
|
138
|
+
const handler = endpoint[method] ?? endpoint.ALL;
|
|
139
|
+
if (!params)
|
|
140
|
+
return Response.json({ error: 'Not Found' }, { status: 404 });
|
|
141
|
+
if (!handler)
|
|
142
|
+
return methodNotAllowed(Object.keys(endpoint));
|
|
143
|
+
return await runWithMiddleware(request, pathPattern, params, handler);
|
|
144
|
+
};
|
|
116
145
|
const handlers = {};
|
|
117
146
|
for (const { path, endpoint } of definitions) {
|
|
118
147
|
handlers[path] = {};
|
|
@@ -125,7 +154,8 @@ function createServer(config) {
|
|
|
125
154
|
handler(path, method) {
|
|
126
155
|
const normalized = normalizePath(path);
|
|
127
156
|
const definition = definitions.find((item) => item.path === normalized);
|
|
128
|
-
if (!definition ||
|
|
157
|
+
if (!definition ||
|
|
158
|
+
!(definition.endpoint[method] ?? definition.endpoint.ALL)) {
|
|
129
159
|
throw new Error(`No ${method} API handler is configured for '${normalized}'.`);
|
|
130
160
|
}
|
|
131
161
|
return (request) => run(request, definition.path, definition.endpoint);
|
|
@@ -135,20 +165,24 @@ function createServer(config) {
|
|
|
135
165
|
const method = request.method.toUpperCase();
|
|
136
166
|
let pathMatched = false;
|
|
137
167
|
for (const definition of definitions) {
|
|
138
|
-
|
|
168
|
+
const params = matchPath(definition.path, url.pathname);
|
|
169
|
+
if (!params)
|
|
139
170
|
continue;
|
|
140
171
|
pathMatched = true;
|
|
141
|
-
|
|
172
|
+
const handler = definition.endpoint[method] ?? definition.endpoint.ALL;
|
|
173
|
+
if (!handler)
|
|
142
174
|
continue;
|
|
143
|
-
return await
|
|
144
|
-
}
|
|
145
|
-
if (pathMatched) {
|
|
146
|
-
const allowed = definitions
|
|
147
|
-
.filter((definition) => matchPath(definition.path, url.pathname))
|
|
148
|
-
.flatMap((definition) => Object.keys(definition.endpoint));
|
|
149
|
-
return methodNotAllowed([...new Set(allowed)]);
|
|
175
|
+
return await runWithMiddleware(request, definition.path, params, handler);
|
|
150
176
|
}
|
|
151
|
-
return
|
|
177
|
+
return await runWithMiddleware(request, url.pathname, {}, () => {
|
|
178
|
+
if (pathMatched) {
|
|
179
|
+
const allowed = definitions
|
|
180
|
+
.filter((definition) => matchPath(definition.path, url.pathname))
|
|
181
|
+
.flatMap((definition) => Object.keys(definition.endpoint));
|
|
182
|
+
return methodNotAllowed([...new Set(allowed)]);
|
|
183
|
+
}
|
|
184
|
+
return Response.json({ error: 'Not Found' }, { status: 404 });
|
|
185
|
+
});
|
|
152
186
|
},
|
|
153
187
|
};
|
|
154
188
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { DeltaChanges, SyncOperation } from '../core/types.js';
|
|
2
|
+
import { type SqlExecutor } from './sqlDialect.js';
|
|
3
|
+
import type { ServerSyncStorage } from './sync.js';
|
|
4
|
+
import type { SyncEventBroker } from './syncEvents.js';
|
|
5
|
+
export interface SqlServerSyncStorageOptions {
|
|
6
|
+
changesTable?: string;
|
|
7
|
+
clockTable?: string;
|
|
8
|
+
scopeField?: string;
|
|
9
|
+
broker?: SyncEventBroker;
|
|
10
|
+
}
|
|
11
|
+
export declare class SqlServerSyncStorage implements ServerSyncStorage {
|
|
12
|
+
private executor;
|
|
13
|
+
private changesTable;
|
|
14
|
+
private clockTable;
|
|
15
|
+
private scopeField;
|
|
16
|
+
private broker?;
|
|
17
|
+
constructor(executor: SqlExecutor, options?: SqlServerSyncStorageOptions);
|
|
18
|
+
applyOperations(operations: SyncOperation[], overrideTime?: number): Promise<{
|
|
19
|
+
applied: number;
|
|
20
|
+
successfulIds: string[];
|
|
21
|
+
serverTime: number;
|
|
22
|
+
cursor: number;
|
|
23
|
+
}>;
|
|
24
|
+
getDeltas(tables: string[], since: number, limit?: number): Promise<{
|
|
25
|
+
changes: DeltaChanges;
|
|
26
|
+
cursor: number;
|
|
27
|
+
hasMore: boolean;
|
|
28
|
+
serverTime: number;
|
|
29
|
+
}>;
|
|
30
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SqlServerSyncStorage = void 0;
|
|
4
|
+
const sqlDialect_js_1 = require("./sqlDialect.js");
|
|
5
|
+
class SqlServerSyncStorage {
|
|
6
|
+
executor;
|
|
7
|
+
changesTable;
|
|
8
|
+
clockTable;
|
|
9
|
+
scopeField;
|
|
10
|
+
broker;
|
|
11
|
+
constructor(executor, options = {}) {
|
|
12
|
+
this.executor = executor;
|
|
13
|
+
this.changesTable = options.changesTable ?? '_server_changes';
|
|
14
|
+
this.clockTable = options.clockTable ?? '_server_sync_clock';
|
|
15
|
+
this.scopeField = options.scopeField ?? 'business_id';
|
|
16
|
+
this.broker = options.broker;
|
|
17
|
+
}
|
|
18
|
+
async applyOperations(operations, overrideTime) {
|
|
19
|
+
const serverTime = overrideTime ?? Date.now();
|
|
20
|
+
const qChanges = (0, sqlDialect_js_1.quoteIdent)(this.changesTable, this.executor.dialect);
|
|
21
|
+
const qClock = (0, sqlDialect_js_1.quoteIdent)(this.clockTable, this.executor.dialect);
|
|
22
|
+
const qTs = (0, sqlDialect_js_1.quoteIdent)('timestamp', this.executor.dialect);
|
|
23
|
+
const successfulIds = [];
|
|
24
|
+
const emitted = [];
|
|
25
|
+
const lastCursor = await this.executor.withTransaction(async (tx) => {
|
|
26
|
+
const clockRows = await tx.query(`SELECT checkpoint FROM ${qClock} WHERE id = 1`);
|
|
27
|
+
const latestRows = await tx.query(`SELECT COALESCE(MAX(${qTs}), 0) AS checkpoint FROM ${qChanges}`);
|
|
28
|
+
let checkpoint = Math.max(serverTime, Number(clockRows[0]?.checkpoint ?? 0), Number(latestRows[0]?.checkpoint ?? 0));
|
|
29
|
+
for (const op of operations) {
|
|
30
|
+
if (!op.tableName || !op.rowId)
|
|
31
|
+
continue;
|
|
32
|
+
checkpoint += 1;
|
|
33
|
+
const payload = op.payload || {};
|
|
34
|
+
const scopeId = String(payload[this.scopeField] ||
|
|
35
|
+
(op.tableName === 'businesses' ? op.rowId : ''));
|
|
36
|
+
const userId = String(payload.user_id || '');
|
|
37
|
+
const operation = op.operation || 'UPDATE';
|
|
38
|
+
await tx.execute(`INSERT INTO ${qChanges} (table_name, row_id, ${(0, sqlDialect_js_1.quoteIdent)(this.scopeField, this.executor.dialect)}, user_id, payload, operation, ${qTs}) VALUES (?, ?, ?, ?, ?, ?, ?)`, [
|
|
39
|
+
op.tableName,
|
|
40
|
+
String(op.rowId),
|
|
41
|
+
scopeId,
|
|
42
|
+
userId,
|
|
43
|
+
JSON.stringify(payload),
|
|
44
|
+
operation,
|
|
45
|
+
checkpoint,
|
|
46
|
+
]);
|
|
47
|
+
successfulIds.push(op.id || op.rowId);
|
|
48
|
+
if (scopeId) {
|
|
49
|
+
emitted.push({ scopeId, tableName: op.tableName, checkpoint });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
await tx.execute(`UPDATE ${qClock} SET checkpoint = ? WHERE id = 1`, [checkpoint]);
|
|
53
|
+
return checkpoint;
|
|
54
|
+
});
|
|
55
|
+
if (this.broker) {
|
|
56
|
+
for (const ev of emitted) {
|
|
57
|
+
this.broker.publish(ev);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
applied: successfulIds.length,
|
|
62
|
+
successfulIds,
|
|
63
|
+
serverTime,
|
|
64
|
+
cursor: lastCursor,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
async getDeltas(tables, since, limit = 500) {
|
|
68
|
+
const qChanges = (0, sqlDialect_js_1.quoteIdent)(this.changesTable, this.executor.dialect);
|
|
69
|
+
const qTs = (0, sqlDialect_js_1.quoteIdent)('timestamp', this.executor.dialect);
|
|
70
|
+
const safeLimit = Math.min(Math.max(Number(limit) || 500, 1), 1000);
|
|
71
|
+
const params = [since];
|
|
72
|
+
let sql = `SELECT table_name, row_id, payload, operation, ${qTs} AS ts FROM ${qChanges} WHERE ${qTs} > ?`;
|
|
73
|
+
if (tables.length > 0) {
|
|
74
|
+
const placeholders = tables.map(() => '?').join(', ');
|
|
75
|
+
sql += ` AND table_name IN (${placeholders})`;
|
|
76
|
+
params.push(...tables);
|
|
77
|
+
}
|
|
78
|
+
sql += ` ORDER BY ${qTs} ASC LIMIT ?`;
|
|
79
|
+
params.push(safeLimit + 1);
|
|
80
|
+
const rows = await this.executor.query(sql, params);
|
|
81
|
+
const hasMore = rows.length > safeLimit;
|
|
82
|
+
const slice = hasMore ? rows.slice(0, safeLimit) : rows;
|
|
83
|
+
let maxTs = since;
|
|
84
|
+
const changes = [];
|
|
85
|
+
for (const row of slice) {
|
|
86
|
+
const ts = Number(row.ts ?? 0);
|
|
87
|
+
if (ts > maxTs)
|
|
88
|
+
maxTs = ts;
|
|
89
|
+
let payload = row.payload;
|
|
90
|
+
if (typeof payload === 'string') {
|
|
91
|
+
try {
|
|
92
|
+
payload = JSON.parse(payload);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
payload = {};
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
changes.push({
|
|
99
|
+
tableName: String(row.table_name),
|
|
100
|
+
rowId: String(row.row_id),
|
|
101
|
+
operation: row.operation,
|
|
102
|
+
payload: payload || {},
|
|
103
|
+
timestamp: ts,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
changes: {
|
|
108
|
+
timestamp: maxTs,
|
|
109
|
+
changes,
|
|
110
|
+
hasMore,
|
|
111
|
+
},
|
|
112
|
+
cursor: maxTs,
|
|
113
|
+
hasMore,
|
|
114
|
+
serverTime: Date.now(),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
exports.SqlServerSyncStorage = SqlServerSyncStorage;
|
package/package.json
CHANGED