local-lite 1.0.0 → 1.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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { RemoteDBAdapter } from './index.js';
|
|
1
|
+
import { RemoteDBAdapter, RemoteBackupArchive, RemoteAutomationJob } from './index.js';
|
|
2
2
|
import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
|
|
3
3
|
export interface SelfHostedRemoteAdapterOptions {
|
|
4
4
|
/**
|
|
@@ -61,4 +61,28 @@ export declare class SelfHostedRemoteAdapter implements RemoteDBAdapter {
|
|
|
61
61
|
subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
|
|
62
62
|
private startPolling;
|
|
63
63
|
setSyncScope(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
|
|
64
|
+
/**
|
|
65
|
+
* Executes a remote function call or RPC across self-hosted endpoints.
|
|
66
|
+
*/
|
|
67
|
+
call<T = any>(functionName: string, args?: Record<string, any>): Promise<T>;
|
|
68
|
+
/**
|
|
69
|
+
* Queries a remote function or view across self-hosted endpoints.
|
|
70
|
+
*/
|
|
71
|
+
queryRemote<T = any>(queryName: string, args?: Record<string, any>): Promise<T>;
|
|
72
|
+
/**
|
|
73
|
+
* Lists cloud backup archives stored on self-hosted backend.
|
|
74
|
+
*/
|
|
75
|
+
listBackups(): Promise<RemoteBackupArchive[]>;
|
|
76
|
+
/**
|
|
77
|
+
* Gets a direct download URL for a file stored on self-hosted backend.
|
|
78
|
+
*/
|
|
79
|
+
getDownloadUrl(fileIdOrKey: string): Promise<string | null>;
|
|
80
|
+
/**
|
|
81
|
+
* Lists automated cron jobs configured on self-hosted backend.
|
|
82
|
+
*/
|
|
83
|
+
listAutomations(): Promise<RemoteAutomationJob[]>;
|
|
84
|
+
/**
|
|
85
|
+
* Enables or disables an automated cron job on self-hosted backend.
|
|
86
|
+
*/
|
|
87
|
+
setAutomationEnabled(jobId: string, enabled: boolean): Promise<void>;
|
|
64
88
|
}
|
|
@@ -37,7 +37,6 @@ class SelfHostedRemoteAdapter {
|
|
|
37
37
|
};
|
|
38
38
|
if (this.token) {
|
|
39
39
|
headers['Authorization'] = `Bearer ${this.token}`;
|
|
40
|
-
headers['X-Sync-Secret'] = this.token;
|
|
41
40
|
}
|
|
42
41
|
return headers;
|
|
43
42
|
}
|
|
@@ -122,5 +121,142 @@ class SelfHostedRemoteAdapter {
|
|
|
122
121
|
setSyncScope(scope) {
|
|
123
122
|
this.syncScope = scope;
|
|
124
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Executes a remote function call or RPC across self-hosted endpoints.
|
|
126
|
+
*/
|
|
127
|
+
async call(functionName, args = {}) {
|
|
128
|
+
const actionEndpoints = {
|
|
129
|
+
'payments/stk': '/payments/stk',
|
|
130
|
+
'contracts/renewal': '/contracts/renewal',
|
|
131
|
+
'contracts/termination': '/contracts/termination',
|
|
132
|
+
'tenant-self-service': '/tenant-self-service',
|
|
133
|
+
'email': '/email',
|
|
134
|
+
'backups/create': '/backups/create',
|
|
135
|
+
'backups/list': '/backups',
|
|
136
|
+
'crons/toggle': '/crons/toggle',
|
|
137
|
+
'crons/daily': '/crons/daily',
|
|
138
|
+
'business-access/invite': '/business-access/invite',
|
|
139
|
+
'business-access/accept': '/business-access/accept',
|
|
140
|
+
'business-access/reject': '/business-access/reject',
|
|
141
|
+
'business-access/update': '/business-access/update',
|
|
142
|
+
'business-access/revoke': '/business-access/revoke',
|
|
143
|
+
};
|
|
144
|
+
const normalized = functionName
|
|
145
|
+
.replace(/^functions\//, '')
|
|
146
|
+
.replace('contracts:sendRenewalReminder', 'contracts/renewal')
|
|
147
|
+
.replace('contracts:sendTerminationNotice', 'contracts/termination')
|
|
148
|
+
.replace('payments:initiateDaraja', 'payments/stk')
|
|
149
|
+
.replace('tenantSelfService:createSelfServiceLink', 'tenant-self-service')
|
|
150
|
+
.replace('email:send', 'email')
|
|
151
|
+
.replace('convexBackups:listMyBackups', 'backups/list')
|
|
152
|
+
.replace('convexBackups:createBackup', 'backups/create')
|
|
153
|
+
.replace('automations:listMine', 'crons')
|
|
154
|
+
.replace('automations:setEnabled', 'crons/toggle')
|
|
155
|
+
.replace(':', '/');
|
|
156
|
+
if (normalized === 'backups/list' || normalized === 'crons') {
|
|
157
|
+
const isBackups = normalized === 'backups/list';
|
|
158
|
+
const endpoint = isBackups ? '/backups' : '/crons';
|
|
159
|
+
const fullUrl = `${this.url}${endpoint}`;
|
|
160
|
+
const response = await this.fetchFn(fullUrl, {
|
|
161
|
+
method: 'GET',
|
|
162
|
+
headers: this.getRequestHeaders(),
|
|
163
|
+
});
|
|
164
|
+
if (!response.ok) {
|
|
165
|
+
const errText = await response.text().catch(() => response.statusText);
|
|
166
|
+
throw new Error(`Self-hosted function call "${functionName}" failed (${response.status}): ${errText}`);
|
|
167
|
+
}
|
|
168
|
+
const data = await response.json();
|
|
169
|
+
return (isBackups ? data.archives || [] : data.automations || []);
|
|
170
|
+
}
|
|
171
|
+
const endpoint = actionEndpoints[normalized] || `/${normalized}`;
|
|
172
|
+
const fullUrl = `${this.url}${endpoint.startsWith('/') ? endpoint : '/' + endpoint}`;
|
|
173
|
+
const response = await this.fetchFn(fullUrl, {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: this.getRequestHeaders(),
|
|
176
|
+
body: JSON.stringify(args),
|
|
177
|
+
});
|
|
178
|
+
if (!response.ok) {
|
|
179
|
+
const errText = await response.text().catch(() => response.statusText);
|
|
180
|
+
throw new Error(`Self-hosted function call "${functionName}" failed (${response.status}): ${errText}`);
|
|
181
|
+
}
|
|
182
|
+
const contentType = response.headers.get('content-type') || '';
|
|
183
|
+
if (contentType.includes('application/json')) {
|
|
184
|
+
return (await response.json());
|
|
185
|
+
}
|
|
186
|
+
return (await response.text());
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Queries a remote function or view across self-hosted endpoints.
|
|
190
|
+
*/
|
|
191
|
+
async queryRemote(queryName, args = {}) {
|
|
192
|
+
if (queryName.includes('listMyBackups') || queryName.includes('listBackups')) {
|
|
193
|
+
return (await this.listBackups());
|
|
194
|
+
}
|
|
195
|
+
if (queryName.includes('listMine') || queryName.includes('listAutomations')) {
|
|
196
|
+
return (await this.listAutomations());
|
|
197
|
+
}
|
|
198
|
+
return this.call(queryName, args);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Lists cloud backup archives stored on self-hosted backend.
|
|
202
|
+
*/
|
|
203
|
+
async listBackups() {
|
|
204
|
+
const fullUrl = `${this.url}/backups`;
|
|
205
|
+
const response = await this.fetchFn(fullUrl, {
|
|
206
|
+
method: 'GET',
|
|
207
|
+
headers: this.getRequestHeaders(),
|
|
208
|
+
});
|
|
209
|
+
if (!response.ok) {
|
|
210
|
+
const errText = await response.text().catch(() => response.statusText);
|
|
211
|
+
throw new Error(`Self-hosted listBackups failed (${response.status}): ${errText}`);
|
|
212
|
+
}
|
|
213
|
+
const data = await response.json();
|
|
214
|
+
return (data.archives || []);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Gets a direct download URL for a file stored on self-hosted backend.
|
|
218
|
+
*/
|
|
219
|
+
async getDownloadUrl(fileIdOrKey) {
|
|
220
|
+
if (!fileIdOrKey)
|
|
221
|
+
return null;
|
|
222
|
+
return `${this.url}/backups/download/${encodeURIComponent(fileIdOrKey)}`;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Lists automated cron jobs configured on self-hosted backend.
|
|
226
|
+
*/
|
|
227
|
+
async listAutomations() {
|
|
228
|
+
const fullUrl = `${this.url}/crons`;
|
|
229
|
+
const response = await this.fetchFn(fullUrl, {
|
|
230
|
+
method: 'GET',
|
|
231
|
+
headers: this.getRequestHeaders(),
|
|
232
|
+
});
|
|
233
|
+
if (!response.ok) {
|
|
234
|
+
return [
|
|
235
|
+
{
|
|
236
|
+
id: 'daily_contract_reminders',
|
|
237
|
+
name: 'Daily Contract Reminders',
|
|
238
|
+
description: 'Automated contract expiration notifications and renewal checks',
|
|
239
|
+
enabled: true,
|
|
240
|
+
},
|
|
241
|
+
];
|
|
242
|
+
}
|
|
243
|
+
const data = await response.json();
|
|
244
|
+
return (data.automations || []);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Enables or disables an automated cron job on self-hosted backend.
|
|
248
|
+
*/
|
|
249
|
+
async setAutomationEnabled(jobId, enabled) {
|
|
250
|
+
const fullUrl = `${this.url}/crons/toggle`;
|
|
251
|
+
const response = await this.fetchFn(fullUrl, {
|
|
252
|
+
method: 'POST',
|
|
253
|
+
headers: this.getRequestHeaders(),
|
|
254
|
+
body: JSON.stringify({ jobId, enabled }),
|
|
255
|
+
});
|
|
256
|
+
if (!response.ok) {
|
|
257
|
+
const errText = await response.text().catch(() => response.statusText);
|
|
258
|
+
throw new Error(`Self-hosted setAutomationEnabled failed (${response.status}): ${errText}`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
125
261
|
}
|
|
126
262
|
exports.SelfHostedRemoteAdapter = SelfHostedRemoteAdapter;
|
package/dist/server/sync.d.ts
CHANGED
|
@@ -69,7 +69,26 @@ export interface ServerSyncEndpointOptions {
|
|
|
69
69
|
/**
|
|
70
70
|
* Hook called before applying mutations to authorize or mutate incoming operations.
|
|
71
71
|
*/
|
|
72
|
-
onBeforePush?: (operations: SyncOperation[], request: Request) => Promise<SyncOperation[] | void> | SyncOperation[] | void;
|
|
72
|
+
onBeforePush?: (operations: SyncOperation[], request: Request, auth?: any) => Promise<SyncOperation[] | void> | SyncOperation[] | void;
|
|
73
|
+
/**
|
|
74
|
+
* Custom authentication / authorization validator (e.g. JWT, OAuth, RLS user).
|
|
75
|
+
* If returns false, returns 401 Unauthorized. If returns user data, passes to hooks.
|
|
76
|
+
*/
|
|
77
|
+
authHandler?: (request: Request) => Promise<any> | any;
|
|
78
|
+
/**
|
|
79
|
+
* Hook called before pulling deltas to filter or scope the query (e.g. for Row-Level Security).
|
|
80
|
+
*/
|
|
81
|
+
onBeforePull?: (tables: string[], since: number, limit: number, request: Request, auth?: any) => Promise<{
|
|
82
|
+
tables?: string[];
|
|
83
|
+
since?: number;
|
|
84
|
+
limit?: number;
|
|
85
|
+
filter?: any;
|
|
86
|
+
} | void> | {
|
|
87
|
+
tables?: string[];
|
|
88
|
+
since?: number;
|
|
89
|
+
limit?: number;
|
|
90
|
+
filter?: any;
|
|
91
|
+
} | void;
|
|
73
92
|
}
|
|
74
93
|
/**
|
|
75
94
|
* Creates turnkey push and pull API endpoints for self-hosted multi-device data synchronization.
|
package/dist/server/sync.js
CHANGED
|
@@ -101,18 +101,26 @@ function createSyncEndpoint(options = {}) {
|
|
|
101
101
|
const corsHeaders = {
|
|
102
102
|
'Access-Control-Allow-Origin': options.corsOrigin || '*',
|
|
103
103
|
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
104
|
-
'Access-Control-Allow-Headers': 'Content-Type, Authorization
|
|
104
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
105
105
|
};
|
|
106
|
-
const verifyAuth = (request) => {
|
|
106
|
+
const verifyAuth = async (request) => {
|
|
107
|
+
if (options.authHandler) {
|
|
108
|
+
const authUser = await options.authHandler(request);
|
|
109
|
+
if (!authUser)
|
|
110
|
+
return false;
|
|
111
|
+
return authUser;
|
|
112
|
+
}
|
|
107
113
|
if (!options.secret)
|
|
108
114
|
return true;
|
|
109
|
-
const authHeader = request.headers.get('authorization')
|
|
110
|
-
|
|
115
|
+
const authHeader = request.headers.get('authorization');
|
|
116
|
+
const match = authHeader === `Bearer ${options.secret}`;
|
|
117
|
+
return match ? { type: 'admin', isAdmin: true } : false;
|
|
111
118
|
};
|
|
112
119
|
// POST: Push batch of mutations (or combined push+pull batch)
|
|
113
120
|
const handlePost = async ({ request }) => {
|
|
114
|
-
|
|
115
|
-
|
|
121
|
+
const auth = await verifyAuth(request);
|
|
122
|
+
if (!auth) {
|
|
123
|
+
return Response.json({ error: 'Unauthorized: Invalid sync authentication' }, { status: 401, headers: corsHeaders });
|
|
116
124
|
}
|
|
117
125
|
let body;
|
|
118
126
|
try {
|
|
@@ -123,15 +131,26 @@ function createSyncEndpoint(options = {}) {
|
|
|
123
131
|
}
|
|
124
132
|
let operations = Array.isArray(body?.operations) ? body.operations : [];
|
|
125
133
|
if (options.onBeforePush) {
|
|
126
|
-
const modified = await options.onBeforePush(operations, request);
|
|
134
|
+
const modified = await options.onBeforePush(operations, request, auth);
|
|
127
135
|
if (Array.isArray(modified))
|
|
128
136
|
operations = modified;
|
|
129
137
|
}
|
|
130
138
|
const pushResult = await storage.applyOperations(operations);
|
|
131
139
|
// If client requested a combined batch sync (push + pull in single roundtrip):
|
|
132
140
|
if (Array.isArray(body?.tables)) {
|
|
133
|
-
|
|
134
|
-
|
|
141
|
+
let tables = body.tables;
|
|
142
|
+
let since = Number(body.since ?? 0);
|
|
143
|
+
let limit = body.limit ? Number(body.limit) : 500;
|
|
144
|
+
if (options.onBeforePull) {
|
|
145
|
+
const pullMod = await options.onBeforePull(tables, since, limit, request, auth);
|
|
146
|
+
if (pullMod?.tables)
|
|
147
|
+
tables = pullMod.tables;
|
|
148
|
+
if (pullMod?.since !== undefined)
|
|
149
|
+
since = pullMod.since;
|
|
150
|
+
if (pullMod?.limit !== undefined)
|
|
151
|
+
limit = pullMod.limit;
|
|
152
|
+
}
|
|
153
|
+
const pullResult = await storage.getDeltas(tables, since, limit);
|
|
135
154
|
return Response.json({
|
|
136
155
|
success: true,
|
|
137
156
|
push: pushResult,
|
|
@@ -148,16 +167,26 @@ function createSyncEndpoint(options = {}) {
|
|
|
148
167
|
};
|
|
149
168
|
// GET: Pull deltas since cursor/timestamp
|
|
150
169
|
const handleGet = async ({ request }) => {
|
|
151
|
-
|
|
152
|
-
|
|
170
|
+
const auth = await verifyAuth(request);
|
|
171
|
+
if (!auth) {
|
|
172
|
+
return Response.json({ error: 'Unauthorized: Invalid sync authentication' }, { status: 401, headers: corsHeaders });
|
|
153
173
|
}
|
|
154
174
|
const url = new URL(request.url);
|
|
155
175
|
const tablesParam = url.searchParams.get('tables');
|
|
156
176
|
const sinceParam = url.searchParams.get('since');
|
|
157
177
|
const limitParam = url.searchParams.get('limit');
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
178
|
+
let tables = tablesParam ? tablesParam.split(',').map((t) => t.trim()).filter(Boolean) : [];
|
|
179
|
+
let since = sinceParam ? Number(sinceParam) : 0;
|
|
180
|
+
let limit = limitParam ? Number(limitParam) : 500;
|
|
181
|
+
if (options.onBeforePull) {
|
|
182
|
+
const pullMod = await options.onBeforePull(tables, since, limit, request, auth);
|
|
183
|
+
if (pullMod?.tables)
|
|
184
|
+
tables = pullMod.tables;
|
|
185
|
+
if (pullMod?.since !== undefined)
|
|
186
|
+
since = pullMod.since;
|
|
187
|
+
if (pullMod?.limit !== undefined)
|
|
188
|
+
limit = pullMod.limit;
|
|
189
|
+
}
|
|
161
190
|
const result = await storage.getDeltas(tables, since, limit);
|
|
162
191
|
return Response.json({
|
|
163
192
|
success: true,
|
package/package.json
CHANGED
|
@@ -150,6 +150,85 @@ export const apiServer = createServer(
|
|
|
150
150
|
|
|
151
151
|
Clients connect to this simply by setting `server: { url: 'https://api.domain.com/api/sync', token: '...' }` in `defineSyncConfig`.
|
|
152
152
|
|
|
153
|
+
### Production MySQL Storage Recipe
|
|
154
|
+
|
|
155
|
+
```typescript
|
|
156
|
+
import mysql from 'mysql2/promise';
|
|
157
|
+
import { createServer, defineServerConfig, createSyncEndpoint, type ServerSyncStorage } from 'local-lite/server';
|
|
158
|
+
|
|
159
|
+
const pool = mysql.createPool({
|
|
160
|
+
uri: process.env.DATABASE_URL,
|
|
161
|
+
waitForConnections: true,
|
|
162
|
+
connectionLimit: 10,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const mysqlStorage: ServerSyncStorage = {
|
|
166
|
+
async applyOperations(operations, serverTime = Date.now()) {
|
|
167
|
+
const conn = await pool.getConnection();
|
|
168
|
+
const successfulIds: string[] = [];
|
|
169
|
+
let applied = 0;
|
|
170
|
+
try {
|
|
171
|
+
await conn.beginTransaction();
|
|
172
|
+
for (const op of operations) {
|
|
173
|
+
if (!op.tableName || !op.rowId) continue;
|
|
174
|
+
const opTime = op.timestamp || serverTime;
|
|
175
|
+
await conn.execute(
|
|
176
|
+
'INSERT INTO _server_changes (table_name, row_id, payload, operation, timestamp) VALUES (?, ?, ?, ?, ?)',
|
|
177
|
+
[op.tableName, String(op.rowId), JSON.stringify(op.payload || {}), op.operation, opTime]
|
|
178
|
+
);
|
|
179
|
+
successfulIds.push(op.id);
|
|
180
|
+
applied++;
|
|
181
|
+
}
|
|
182
|
+
const [cursorRows]: any = await conn.query('SELECT COALESCE(MAX(`cursor`), 0) AS max_cursor FROM _server_changes');
|
|
183
|
+
await conn.commit();
|
|
184
|
+
return { applied, successfulIds, serverTime, cursor: Number(cursorRows[0]?.max_cursor || 0) };
|
|
185
|
+
} catch (err) {
|
|
186
|
+
await conn.rollback();
|
|
187
|
+
throw err;
|
|
188
|
+
} finally {
|
|
189
|
+
conn.release();
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
async getDeltas(tables, since, limit = 200) {
|
|
194
|
+
if (tables.length === 0) return { changes: { timestamp: Date.now(), changes: [] }, cursor: since, hasMore: false, serverTime: Date.now() };
|
|
195
|
+
const placeholders = tables.map(() => '?').join(',');
|
|
196
|
+
const [rows]: any = await pool.query(
|
|
197
|
+
`SELECT * FROM _server_changes WHERE \`cursor\` > ? AND table_name IN (${placeholders}) ORDER BY \`cursor\` ASC LIMIT ?`,
|
|
198
|
+
[since, ...tables, Number(limit)]
|
|
199
|
+
);
|
|
200
|
+
const changes = {
|
|
201
|
+
timestamp: Date.now(),
|
|
202
|
+
changes: rows.map((r: any) => ({
|
|
203
|
+
tableName: r.table_name,
|
|
204
|
+
rowId: r.row_id,
|
|
205
|
+
operation: r.operation,
|
|
206
|
+
payload: typeof r.payload === 'string' ? JSON.parse(r.payload) : r.payload,
|
|
207
|
+
timestamp: Number(r.timestamp),
|
|
208
|
+
})),
|
|
209
|
+
};
|
|
210
|
+
const maxCursor = rows.length > 0 ? Number(rows[rows.length - 1].cursor) : since;
|
|
211
|
+
return { changes, cursor: maxCursor, hasMore: rows.length === Number(limit), serverTime: Date.now() };
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
export const apiServer = createServer(
|
|
216
|
+
defineServerConfig({
|
|
217
|
+
config: {},
|
|
218
|
+
endpoints: {
|
|
219
|
+
'/api/sync': createSyncEndpoint({
|
|
220
|
+
storage: mysqlStorage,
|
|
221
|
+
secret: process.env.SYNC_SECRET_TOKEN,
|
|
222
|
+
}),
|
|
223
|
+
},
|
|
224
|
+
})
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
export const POST = apiServer.handler('/api/sync', 'POST');
|
|
228
|
+
export const GET = apiServer.handler('/api/sync', 'GET');
|
|
229
|
+
export const OPTIONS = apiServer.handler('/api/sync', 'OPTIONS');
|
|
230
|
+
```
|
|
231
|
+
|
|
153
232
|
---
|
|
154
233
|
|
|
155
234
|
## 7. Turnkey Email Relay Endpoint (`createEmailEndpoint`)
|