local-lite 3.0.4 → 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 +5 -1
- package/dist/server/index.js +59 -22
- package/dist/server/scheduler.d.ts +13 -0
- package/dist/server/scheduler.js +38 -0
- package/dist/server/sqlDialect.d.ts +21 -0
- package/dist/server/sqlDialect.js +172 -0
- package/dist/server/sqlSyncStorage.d.ts +30 -0
- package/dist/server/sqlSyncStorage.js +118 -0
- package/dist/server/syncEvents.d.ts +17 -0
- package/dist/server/syncEvents.js +77 -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,8 +1,12 @@
|
|
|
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
|
+
export * from './sqlDialect.js';
|
|
7
|
+
export * from './sqlSyncStorage.js';
|
|
8
|
+
export * from './syncEvents.js';
|
|
9
|
+
export * from './scheduler.js';
|
|
6
10
|
export interface ApiRequestContext<TConfig = unknown> {
|
|
7
11
|
request: Request;
|
|
8
12
|
config: TConfig;
|
package/dist/server/index.js
CHANGED
|
@@ -20,6 +20,10 @@ __exportStar(require("./email.js"), exports);
|
|
|
20
20
|
__exportStar(require("./sync.js"), exports);
|
|
21
21
|
__exportStar(require("./auth.js"), exports);
|
|
22
22
|
__exportStar(require("./dashboard.js"), exports);
|
|
23
|
+
__exportStar(require("./sqlDialect.js"), exports);
|
|
24
|
+
__exportStar(require("./sqlSyncStorage.js"), exports);
|
|
25
|
+
__exportStar(require("./syncEvents.js"), exports);
|
|
26
|
+
__exportStar(require("./scheduler.js"), exports);
|
|
23
27
|
function normalizePath(path) {
|
|
24
28
|
const normalized = `/${path.split('/').filter(Boolean).join('/')}`;
|
|
25
29
|
return normalized === '/' ? normalized : normalized.replace(/\/$/, '');
|
|
@@ -27,6 +31,31 @@ function normalizePath(path) {
|
|
|
27
31
|
function matchPath(pattern, pathname) {
|
|
28
32
|
const patternSegments = normalizePath(pattern).split('/').filter(Boolean);
|
|
29
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
|
+
}
|
|
30
59
|
if (patternSegments.length !== pathSegments.length)
|
|
31
60
|
return null;
|
|
32
61
|
const params = {};
|
|
@@ -71,21 +100,13 @@ function createServer(config) {
|
|
|
71
100
|
path: normalizePath(path),
|
|
72
101
|
endpoint,
|
|
73
102
|
}));
|
|
74
|
-
const
|
|
75
|
-
const method = request.method.toUpperCase();
|
|
76
|
-
const url = new URL(request.url);
|
|
77
|
-
const params = matchPath(pathPattern, url.pathname);
|
|
78
|
-
const handler = endpoint[method];
|
|
103
|
+
const runWithMiddleware = async (request, pathPattern, params, finalHandler) => {
|
|
79
104
|
const context = {
|
|
80
105
|
request,
|
|
81
106
|
config: config.config,
|
|
82
107
|
path: pathPattern,
|
|
83
|
-
params
|
|
108
|
+
params,
|
|
84
109
|
};
|
|
85
|
-
if (!params)
|
|
86
|
-
return Response.json({ error: 'Not Found' }, { status: 404 });
|
|
87
|
-
if (!handler)
|
|
88
|
-
return methodNotAllowed(Object.keys(endpoint));
|
|
89
110
|
const stack = config.middleware ?? [];
|
|
90
111
|
let index = -1;
|
|
91
112
|
const dispatch = async (position) => {
|
|
@@ -94,7 +115,7 @@ function createServer(config) {
|
|
|
94
115
|
index = position;
|
|
95
116
|
const middleware = stack[position];
|
|
96
117
|
if (!middleware)
|
|
97
|
-
return await
|
|
118
|
+
return await finalHandler(context);
|
|
98
119
|
return await middleware(context, () => dispatch(position + 1));
|
|
99
120
|
};
|
|
100
121
|
try {
|
|
@@ -110,6 +131,17 @@ function createServer(config) {
|
|
|
110
131
|
return Response.json({ error: 'Internal Server Error' }, { status: 500 });
|
|
111
132
|
}
|
|
112
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
|
+
};
|
|
113
145
|
const handlers = {};
|
|
114
146
|
for (const { path, endpoint } of definitions) {
|
|
115
147
|
handlers[path] = {};
|
|
@@ -122,7 +154,8 @@ function createServer(config) {
|
|
|
122
154
|
handler(path, method) {
|
|
123
155
|
const normalized = normalizePath(path);
|
|
124
156
|
const definition = definitions.find((item) => item.path === normalized);
|
|
125
|
-
if (!definition ||
|
|
157
|
+
if (!definition ||
|
|
158
|
+
!(definition.endpoint[method] ?? definition.endpoint.ALL)) {
|
|
126
159
|
throw new Error(`No ${method} API handler is configured for '${normalized}'.`);
|
|
127
160
|
}
|
|
128
161
|
return (request) => run(request, definition.path, definition.endpoint);
|
|
@@ -132,20 +165,24 @@ function createServer(config) {
|
|
|
132
165
|
const method = request.method.toUpperCase();
|
|
133
166
|
let pathMatched = false;
|
|
134
167
|
for (const definition of definitions) {
|
|
135
|
-
|
|
168
|
+
const params = matchPath(definition.path, url.pathname);
|
|
169
|
+
if (!params)
|
|
136
170
|
continue;
|
|
137
171
|
pathMatched = true;
|
|
138
|
-
|
|
172
|
+
const handler = definition.endpoint[method] ?? definition.endpoint.ALL;
|
|
173
|
+
if (!handler)
|
|
139
174
|
continue;
|
|
140
|
-
return await
|
|
141
|
-
}
|
|
142
|
-
if (pathMatched) {
|
|
143
|
-
const allowed = definitions
|
|
144
|
-
.filter((definition) => matchPath(definition.path, url.pathname))
|
|
145
|
-
.flatMap((definition) => Object.keys(definition.endpoint));
|
|
146
|
-
return methodNotAllowed([...new Set(allowed)]);
|
|
175
|
+
return await runWithMiddleware(request, definition.path, params, handler);
|
|
147
176
|
}
|
|
148
|
-
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
|
+
});
|
|
149
186
|
},
|
|
150
187
|
};
|
|
151
188
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SqlExecutor } from './sqlDialect.js';
|
|
2
|
+
export declare function claimScheduledJob(executor: SqlExecutor, tableName: string, jobKey: string, now: number, intervalMs: number): Promise<boolean>;
|
|
3
|
+
export interface ServerCronRunnerOptions {
|
|
4
|
+
intervalMs?: number;
|
|
5
|
+
enabled?: boolean;
|
|
6
|
+
onTick: () => Promise<void>;
|
|
7
|
+
onError?: (error: unknown) => void;
|
|
8
|
+
}
|
|
9
|
+
export declare function createServerCronRunner(options: ServerCronRunnerOptions): {
|
|
10
|
+
start(): void;
|
|
11
|
+
stop(): void;
|
|
12
|
+
isRunning(): boolean;
|
|
13
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.claimScheduledJob = claimScheduledJob;
|
|
4
|
+
exports.createServerCronRunner = createServerCronRunner;
|
|
5
|
+
const sqlDialect_js_1 = require("./sqlDialect.js");
|
|
6
|
+
async function claimScheduledJob(executor, tableName, jobKey, now, intervalMs) {
|
|
7
|
+
const tbl = (0, sqlDialect_js_1.quoteIdent)(tableName, executor.dialect);
|
|
8
|
+
const cutoff = now - Math.max(intervalMs, 1);
|
|
9
|
+
const res = await executor.execute(`UPDATE ${tbl}
|
|
10
|
+
SET last_run_at = ?, last_status = 'running', updated_at = ?
|
|
11
|
+
WHERE job_key = ? AND enabled = 1 AND (last_run_at IS NULL OR last_run_at = 0 OR last_run_at <= ?)`, [now, now, jobKey, cutoff]);
|
|
12
|
+
return res.affectedRows > 0;
|
|
13
|
+
}
|
|
14
|
+
function createServerCronRunner(options) {
|
|
15
|
+
let timer = null;
|
|
16
|
+
const intervalMs = Math.max(options.intervalMs ?? 15 * 60 * 1000, 1000);
|
|
17
|
+
return {
|
|
18
|
+
start() {
|
|
19
|
+
if (options.enabled === false || timer)
|
|
20
|
+
return;
|
|
21
|
+
timer = setInterval(() => {
|
|
22
|
+
void options.onTick().catch((err) => {
|
|
23
|
+
options.onError?.(err);
|
|
24
|
+
});
|
|
25
|
+
}, intervalMs);
|
|
26
|
+
timer.unref?.();
|
|
27
|
+
},
|
|
28
|
+
stop() {
|
|
29
|
+
if (timer) {
|
|
30
|
+
clearInterval(timer);
|
|
31
|
+
timer = null;
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
isRunning() {
|
|
35
|
+
return timer !== null;
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type SqlDialect = 'mysql' | 'postgres';
|
|
2
|
+
export interface SqlExecutor {
|
|
3
|
+
dialect: SqlDialect;
|
|
4
|
+
query<T = any>(sql: string, params?: any[]): Promise<T[]>;
|
|
5
|
+
execute(sql: string, params?: any[]): Promise<{
|
|
6
|
+
affectedRows: number;
|
|
7
|
+
}>;
|
|
8
|
+
withTransaction<T>(fn: (tx: SqlExecutor) => Promise<T>): Promise<T>;
|
|
9
|
+
}
|
|
10
|
+
export declare function quoteIdent(ident: string, dialect?: SqlDialect): string;
|
|
11
|
+
export interface UpsertSqlOptions {
|
|
12
|
+
table: string;
|
|
13
|
+
conflictCols: string[];
|
|
14
|
+
insertCols: string[];
|
|
15
|
+
updateCols: string[];
|
|
16
|
+
dialect?: SqlDialect;
|
|
17
|
+
}
|
|
18
|
+
export declare function buildUpsertSql(opts: UpsertSqlOptions): string;
|
|
19
|
+
export declare function rewriteSqlTokensForPostgres(sql: string): string;
|
|
20
|
+
export declare function adaptSqlForPostgres(rawSql: string): string[];
|
|
21
|
+
export declare function createSqlExecutor(pool: any, dialect: SqlDialect): SqlExecutor;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.quoteIdent = quoteIdent;
|
|
4
|
+
exports.buildUpsertSql = buildUpsertSql;
|
|
5
|
+
exports.rewriteSqlTokensForPostgres = rewriteSqlTokensForPostgres;
|
|
6
|
+
exports.adaptSqlForPostgres = adaptSqlForPostgres;
|
|
7
|
+
exports.createSqlExecutor = createSqlExecutor;
|
|
8
|
+
function quoteIdent(ident, dialect = 'mysql') {
|
|
9
|
+
const clean = ident.replace(/[`"]/g, '');
|
|
10
|
+
return dialect === 'postgres' ? `"${clean}"` : `\`${clean}\``;
|
|
11
|
+
}
|
|
12
|
+
function buildUpsertSql(opts) {
|
|
13
|
+
const dialect = opts.dialect ?? 'mysql';
|
|
14
|
+
const q = (col) => quoteIdent(col, dialect);
|
|
15
|
+
const tbl = q(opts.table);
|
|
16
|
+
const cols = opts.insertCols.map(q).join(', ');
|
|
17
|
+
const placeholders = opts.insertCols.map(() => '?').join(', ');
|
|
18
|
+
if (dialect === 'postgres') {
|
|
19
|
+
const conflict = opts.conflictCols.map(q).join(', ');
|
|
20
|
+
if (opts.updateCols.length === 0) {
|
|
21
|
+
return `INSERT INTO ${tbl} (${cols}) VALUES (${placeholders}) ON CONFLICT (${conflict}) DO NOTHING`;
|
|
22
|
+
}
|
|
23
|
+
const updates = opts.updateCols
|
|
24
|
+
.map((c) => `${q(c)} = EXCLUDED.${q(c)}`)
|
|
25
|
+
.join(', ');
|
|
26
|
+
return `INSERT INTO ${tbl} (${cols}) VALUES (${placeholders}) ON CONFLICT (${conflict}) DO UPDATE SET ${updates}`;
|
|
27
|
+
}
|
|
28
|
+
if (opts.updateCols.length === 0) {
|
|
29
|
+
return `INSERT IGNORE INTO ${tbl} (${cols}) VALUES (${placeholders})`;
|
|
30
|
+
}
|
|
31
|
+
const updates = opts.updateCols
|
|
32
|
+
.map((c) => `${q(c)} = VALUES(${q(c)})`)
|
|
33
|
+
.join(', ');
|
|
34
|
+
return `INSERT INTO ${tbl} (${cols}) VALUES (${placeholders}) ON DUPLICATE KEY UPDATE ${updates}`;
|
|
35
|
+
}
|
|
36
|
+
function rewriteSqlTokensForPostgres(sql) {
|
|
37
|
+
let out = '';
|
|
38
|
+
let paramIdx = 1;
|
|
39
|
+
let inSingle = false;
|
|
40
|
+
let inDouble = false;
|
|
41
|
+
for (let i = 0; i < sql.length; i++) {
|
|
42
|
+
const ch = sql[i];
|
|
43
|
+
if (ch === "'" && !inDouble) {
|
|
44
|
+
inSingle = !inSingle;
|
|
45
|
+
out += ch;
|
|
46
|
+
if (inSingle && sql[i + 1] === "'") {
|
|
47
|
+
out += "'";
|
|
48
|
+
i++;
|
|
49
|
+
}
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (ch === '\\' && inSingle && i + 1 < sql.length) {
|
|
53
|
+
out += ch + sql[i + 1];
|
|
54
|
+
i++;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (ch === '`' && !inSingle) {
|
|
58
|
+
inDouble = !inDouble;
|
|
59
|
+
out += '"';
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (ch === '?' && !inSingle && !inDouble) {
|
|
63
|
+
out += `$${paramIdx++}`;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
out += ch;
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function adaptSqlForPostgres(rawSql) {
|
|
71
|
+
let sql = rawSql.trim();
|
|
72
|
+
if (!sql)
|
|
73
|
+
return [];
|
|
74
|
+
if (sql.startsWith('--') && !sql.includes('\n'))
|
|
75
|
+
return [];
|
|
76
|
+
sql = sql.replace(/\s+ENGINE\s*=\s*\w+/gi, '');
|
|
77
|
+
sql = sql.replace(/\s+DEFAULT\s+CHARSET\s*=\s*[\w-]+/gi, '');
|
|
78
|
+
sql = sql.replace(/\s+COLLATE\s*=?\s*[\w-]+/gi, '');
|
|
79
|
+
sql = sql.replace(/`([^`]+)`/g, '"$1"');
|
|
80
|
+
sql = sql.replace(/\bTINYINT\s*\(\s*1\s*\)/gi, 'SMALLINT');
|
|
81
|
+
sql = sql.replace(/\bLONGTEXT\b/gi, 'TEXT');
|
|
82
|
+
sql = sql.replace(/\bMEDIUMTEXT\b/gi, 'TEXT');
|
|
83
|
+
sql = sql.replace(/\bDOUBLE\b/gi, 'DOUBLE PRECISION');
|
|
84
|
+
sql = sql.replace(/\bENUM\s*\([^)]*\)/gi, 'VARCHAR(64)');
|
|
85
|
+
sql = sql.replace(/\bBIGINT\s+AUTO_INCREMENT\s+PRIMARY\s+KEY\b/gi, 'BIGSERIAL PRIMARY KEY');
|
|
86
|
+
sql = sql.replace(/\bINT\s+AUTO_INCREMENT\s+PRIMARY\s+KEY\b/gi, 'SERIAL PRIMARY KEY');
|
|
87
|
+
if (/^\s*INSERT\s+IGNORE\s+INTO\b/i.test(sql)) {
|
|
88
|
+
sql = sql.replace(/^\s*INSERT\s+IGNORE\s+INTO\b/i, 'INSERT INTO');
|
|
89
|
+
sql = sql.replace(/;\s*$/, '') + ' ON CONFLICT DO NOTHING';
|
|
90
|
+
return [sql];
|
|
91
|
+
}
|
|
92
|
+
const alterIdxMatch = sql.match(/^\s*ALTER\s+TABLE\s+(?:"([^"]+)"|(\S+))\s+ADD\s+(?:UNIQUE\s+)?INDEX\s+"?(\w+)"?\s*\(([^)]+)\)\s*;?\s*$/i);
|
|
93
|
+
if (alterIdxMatch) {
|
|
94
|
+
const tbl = alterIdxMatch[1] || alterIdxMatch[2];
|
|
95
|
+
const idxName = alterIdxMatch[3];
|
|
96
|
+
const cols = alterIdxMatch[4];
|
|
97
|
+
const unique = /\bADD\s+UNIQUE\s+INDEX\b/i.test(sql) ? 'UNIQUE ' : '';
|
|
98
|
+
return [
|
|
99
|
+
`CREATE ${unique}INDEX IF NOT EXISTS "${tbl}_${idxName}" ON "${tbl}" (${cols})`,
|
|
100
|
+
];
|
|
101
|
+
}
|
|
102
|
+
const tableMatch = sql.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"|(\S+))\s*\(/i);
|
|
103
|
+
const tableName = tableMatch?.[1] || tableMatch?.[2];
|
|
104
|
+
const extractedIndexes = [];
|
|
105
|
+
if (tableName) {
|
|
106
|
+
sql = sql.replace(/,\s*INDEX\s+"?(\w+)"?\s*\(([^)]+)\)/gi, (_m, idxName, cols) => {
|
|
107
|
+
extractedIndexes.push(`CREATE INDEX IF NOT EXISTS "${tableName}_${idxName}" ON "${tableName}" (${cols})`);
|
|
108
|
+
return '';
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
return [sql, ...extractedIndexes];
|
|
112
|
+
}
|
|
113
|
+
function createSqlExecutor(pool, dialect) {
|
|
114
|
+
const execOn = (conn) => ({
|
|
115
|
+
dialect,
|
|
116
|
+
async query(sql, params = []) {
|
|
117
|
+
if (dialect === 'postgres') {
|
|
118
|
+
const res = await conn.query(rewriteSqlTokensForPostgres(sql), params);
|
|
119
|
+
return (res?.rows ?? []);
|
|
120
|
+
}
|
|
121
|
+
const [rows] = await conn.query(sql, params);
|
|
122
|
+
return (Array.isArray(rows) ? rows : []);
|
|
123
|
+
},
|
|
124
|
+
async execute(sql, params = []) {
|
|
125
|
+
if (dialect === 'postgres') {
|
|
126
|
+
const res = await conn.query(rewriteSqlTokensForPostgres(sql), params);
|
|
127
|
+
return { affectedRows: Number(res?.rowCount ?? 0) };
|
|
128
|
+
}
|
|
129
|
+
const [res] = await conn.execute(sql, params);
|
|
130
|
+
return { affectedRows: Number(res?.affectedRows ?? 0) };
|
|
131
|
+
},
|
|
132
|
+
async withTransaction(fn) {
|
|
133
|
+
return fn(execOn(conn));
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
const root = execOn(pool);
|
|
137
|
+
return {
|
|
138
|
+
...root,
|
|
139
|
+
async withTransaction(fn) {
|
|
140
|
+
if (dialect === 'postgres') {
|
|
141
|
+
const client = await pool.connect();
|
|
142
|
+
try {
|
|
143
|
+
await client.query('BEGIN');
|
|
144
|
+
const result = await fn(execOn(client));
|
|
145
|
+
await client.query('COMMIT');
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
150
|
+
throw err;
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
client.release();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const conn = await pool.getConnection();
|
|
157
|
+
try {
|
|
158
|
+
await conn.beginTransaction();
|
|
159
|
+
const result = await fn(execOn(conn));
|
|
160
|
+
await conn.commit();
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
await conn.rollback().catch(() => { });
|
|
165
|
+
throw err;
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
conn.release();
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
|
@@ -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;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface SyncChangeEvent {
|
|
2
|
+
scopeId: string;
|
|
3
|
+
tableName: string;
|
|
4
|
+
checkpoint: number;
|
|
5
|
+
}
|
|
6
|
+
export interface SyncEventBroker {
|
|
7
|
+
publish(event: SyncChangeEvent): void;
|
|
8
|
+
subscribe(listener: (event: SyncChangeEvent) => void): () => void;
|
|
9
|
+
}
|
|
10
|
+
export declare function createSyncEventBroker(): SyncEventBroker;
|
|
11
|
+
export interface SyncEventsEndpointOptions {
|
|
12
|
+
broker: SyncEventBroker;
|
|
13
|
+
authenticate: (request: Request) => Promise<boolean>;
|
|
14
|
+
scopeQueryParam?: string;
|
|
15
|
+
heartbeatMs?: number;
|
|
16
|
+
}
|
|
17
|
+
export declare function createSyncEventsHandler(options: SyncEventsEndpointOptions): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createSyncEventBroker = createSyncEventBroker;
|
|
4
|
+
exports.createSyncEventsHandler = createSyncEventsHandler;
|
|
5
|
+
const node_events_1 = require("node:events");
|
|
6
|
+
function createSyncEventBroker() {
|
|
7
|
+
const emitter = new node_events_1.EventEmitter();
|
|
8
|
+
emitter.setMaxListeners(0);
|
|
9
|
+
return {
|
|
10
|
+
publish(event) {
|
|
11
|
+
if (!event.scopeId)
|
|
12
|
+
return;
|
|
13
|
+
emitter.emit('change', event);
|
|
14
|
+
},
|
|
15
|
+
subscribe(listener) {
|
|
16
|
+
emitter.on('change', listener);
|
|
17
|
+
return () => {
|
|
18
|
+
emitter.off('change', listener);
|
|
19
|
+
};
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function createSyncEventsHandler(options) {
|
|
24
|
+
const scopeParam = options.scopeQueryParam ?? 'businessId';
|
|
25
|
+
const heartbeatMs = options.heartbeatMs ?? 25_000;
|
|
26
|
+
return async (request) => {
|
|
27
|
+
if (request.method.toUpperCase() !== 'GET') {
|
|
28
|
+
return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
|
|
29
|
+
}
|
|
30
|
+
const ok = await options.authenticate(request);
|
|
31
|
+
if (!ok) {
|
|
32
|
+
return Response.json({ error: 'Unauthorized' }, { status: 401 });
|
|
33
|
+
}
|
|
34
|
+
const url = new URL(request.url);
|
|
35
|
+
const filterScope = url.searchParams.get(scopeParam)?.trim() || '';
|
|
36
|
+
const encoder = new TextEncoder();
|
|
37
|
+
let cleanup = null;
|
|
38
|
+
const stream = new ReadableStream({
|
|
39
|
+
start(controller) {
|
|
40
|
+
const send = (chunk) => {
|
|
41
|
+
try {
|
|
42
|
+
controller.enqueue(encoder.encode(chunk));
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
cleanup?.();
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
send(`event: connected\ndata: ${JSON.stringify({ ok: true })}\n\n`);
|
|
49
|
+
const unsubscribe = options.broker.subscribe((event) => {
|
|
50
|
+
if (filterScope && event.scopeId !== filterScope)
|
|
51
|
+
return;
|
|
52
|
+
send(`data: ${JSON.stringify(event)}\n\n`);
|
|
53
|
+
});
|
|
54
|
+
const heartbeat = setInterval(() => {
|
|
55
|
+
send(': keep-alive\n\n');
|
|
56
|
+
}, heartbeatMs);
|
|
57
|
+
cleanup = () => {
|
|
58
|
+
clearInterval(heartbeat);
|
|
59
|
+
unsubscribe();
|
|
60
|
+
cleanup = null;
|
|
61
|
+
};
|
|
62
|
+
request.signal.addEventListener('abort', () => cleanup?.());
|
|
63
|
+
},
|
|
64
|
+
cancel() {
|
|
65
|
+
cleanup?.();
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
return new Response(stream, {
|
|
69
|
+
status: 200,
|
|
70
|
+
headers: {
|
|
71
|
+
'Content-Type': 'text/event-stream',
|
|
72
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
73
|
+
Connection: 'keep-alive',
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
}
|
package/package.json
CHANGED