local-lite 0.0.30 → 0.1.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.
- package/README.md +32 -20
- package/bin/local-lite.mjs +62 -0
- package/dist/adapters/remote/firestore.d.ts +2 -1
- package/dist/adapters/remote/firestore.js +21 -3
- package/dist/adapters/remote/index.d.ts +2 -2
- package/dist/adapters/remote/supabase.d.ts +1 -1
- package/dist/config/index.js +3 -1
- package/dist/config/types.d.ts +0 -5
- package/dist/core/client.d.ts +1 -3
- package/dist/core/client.js +4 -11
- package/dist/search/store.js +1 -12
- package/dist/storage/expo.d.ts +4 -66
- package/dist/storage/expo.js +104 -261
- package/dist/utils/sql.js +1 -1
- package/docs/.nojekyll +1 -0
- package/docs/README.md +108 -0
- package/docs/_sidebar.md +22 -0
- package/docs/actions-email.md +222 -0
- package/docs/adapters-local.md +272 -0
- package/docs/adapters-remote.md +291 -0
- package/docs/api-keys.md +114 -0
- package/docs/architecture.md +106 -0
- package/docs/auth.md +259 -0
- package/docs/backups.md +214 -0
- package/docs/breaking-changes.md +147 -0
- package/docs/client-api.md +412 -0
- package/docs/configuration.md +228 -0
- package/docs/conflict-resolution.md +78 -0
- package/docs/getting-started.md +190 -0
- package/docs/google-auth.md +234 -0
- package/docs/index.html +166 -0
- package/docs/kv.md +89 -0
- package/docs/maintenance-portability.md +133 -0
- package/docs/react-hooks.md +457 -0
- package/docs/scheduler.md +81 -0
- package/docs/search.md +71 -0
- package/docs/server.md +101 -0
- package/docs/session.md +129 -0
- package/docs/storage.md +265 -0
- package/package.json +7 -1
- package/skills/local-lite-custom-adapter/SKILL.md +59 -0
- package/skills/local-lite-setup/SKILL.md +21 -0
- package/skills/local-lite-upgrade/SKILL.md +16 -0
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
# 💻 Client API & Query Builder
|
|
2
|
+
|
|
3
|
+
The `LocalFirstClient` is the core synchronization and database interface for `local-lite`. It manages local SQLite operations, the transactional outbox queue, background synchronization, and reactive listeners.
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
import { LocalFirstClient } from 'local-lite';
|
|
7
|
+
// or from 'local-lite/config' via createSyncClient(config)
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Lifecycle & Connection Management
|
|
13
|
+
|
|
14
|
+
### `client.initialize(): Promise<void>`
|
|
15
|
+
Initializes SQLite storage: sets PRAGMA modes (WAL, synchronous NORMAL), ensures internal tables (`sync_outbox`, `sync_meta`), applies configured versioned `schemaMigrations`, creates tables if `autoSchema: true`, and starts background sync loops if `autoStart: true`. Migrations are applied once and recorded locally before sync starts.
|
|
16
|
+
Safe to call concurrently or repeatedly.
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
await client.initialize();
|
|
20
|
+
console.log('Client ready:', client.isReady);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### `client.stop(): void`
|
|
24
|
+
Pauses all background sync loops, intervals, and network event listeners. Queued mutations remain safe in the outbox.
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
client.stop();
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### `client.close(): Promise<void>`
|
|
31
|
+
Stops sync workers, destroys remote subscriptions, and closes the local SQLite connection, safely releasing native database locks.
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
await client.close();
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### `client.reset(options?: { dropTables?: boolean }): Promise<void>`
|
|
38
|
+
Resets local state by stopping sync, deleting or dropping all managed tables, clearing `sync_outbox` and `sync_meta`, and resetting the sync watermark cursor.
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
// Clear all rows from managed tables and reset outbox
|
|
42
|
+
await client.reset();
|
|
43
|
+
|
|
44
|
+
// Or completely drop all tables from SQLite
|
|
45
|
+
await client.reset({ dropTables: true });
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 2. Atomic Dual-Write Mutations (CRUD)
|
|
51
|
+
|
|
52
|
+
Every write operation executes inside an atomic SQLite transaction that modifies the target table and appends a record to `sync_outbox` simultaneously.
|
|
53
|
+
|
|
54
|
+
### `client.insert(table, payload, options?): Promise<string>`
|
|
55
|
+
Inserts a record and generates a UUID v4 if an `id` is not provided.
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
// Auto-generated UUID
|
|
59
|
+
const todoId = await client.insert('todos', {
|
|
60
|
+
title: 'Review PR',
|
|
61
|
+
completed: 0,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// Explicit ID
|
|
65
|
+
await client.insert('todos', 'custom-uuid-123', {
|
|
66
|
+
title: 'Custom ID Item',
|
|
67
|
+
completed: 0,
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### `client.insertMany(table, records, options?): Promise<string[]>`
|
|
72
|
+
Inserts multiple records in a single atomic database transaction.
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
const ids = await client.insertMany('todos', [
|
|
76
|
+
{ title: 'Task 1', completed: 0 },
|
|
77
|
+
{ title: 'Task 2', completed: 1 },
|
|
78
|
+
]);
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### `client.update(table, id, payload, options?): Promise<void>`
|
|
82
|
+
Updates an existing record by its primary key.
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
await client.update('todos', todoId, {
|
|
86
|
+
completed: 1,
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `client.updateMany(table, updates, options?): Promise<void>`
|
|
91
|
+
Updates multiple records atomically in a single transaction.
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
await client.updateMany('todos', [
|
|
95
|
+
{ id: 'id-1', payload: { completed: 1 } },
|
|
96
|
+
{ id: 'id-2', payload: { completed: 0 } },
|
|
97
|
+
]);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### `client.delete(table, id, options?): Promise<void>`
|
|
101
|
+
Deletes a record by its primary key.
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
await client.delete('todos', todoId);
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### `client.mutate(table, id, operation, payload, options?): Promise<void>`
|
|
108
|
+
Low-level atomic dual-write method:
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
await client.mutate('todos', 'todo-1', 'UPDATE', { completed: 1 }, {
|
|
112
|
+
skipOutbox: false, // Set true to skip cloud sync (local only)
|
|
113
|
+
customTimestamp: Date.now(), // Override mutation timestamp
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### `client.trackMutation(table, id, operation, payload, options?): Promise<string>`
|
|
118
|
+
Appends a mutation to `sync_outbox` without modifying the local table. Useful when performing custom raw SQL operations that need to be synchronized with the remote backend.
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## 3. Atomic Batches & Custom Transactions
|
|
123
|
+
|
|
124
|
+
### `client.batch(mutations, options?): Promise<string[]>`
|
|
125
|
+
Executes multiple diverse operations across multiple tables atomically.
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
await client.batch([
|
|
129
|
+
{
|
|
130
|
+
tableName: 'projects',
|
|
131
|
+
rowId: 'proj-1',
|
|
132
|
+
operation: 'INSERT',
|
|
133
|
+
payload: { name: 'Mobile App' },
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
tableName: 'tasks',
|
|
137
|
+
operation: 'INSERT',
|
|
138
|
+
payload: { project_id: 'proj-1', title: 'Setup Expo' },
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
tableName: 'notifications',
|
|
142
|
+
rowId: 'notif-99',
|
|
143
|
+
operation: 'DELETE',
|
|
144
|
+
},
|
|
145
|
+
]);
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### `client.transaction(action): Promise<T>`
|
|
149
|
+
Executes an arbitrary callback inside an ACID transaction with a scoped `TransactionalClient`. If an error is thrown, all SQLite changes and outbox records roll back, and no change events are emitted.
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
await client.transaction(async (txClient) => {
|
|
153
|
+
await txClient.insert('accounts', { id: 'acc-1', balance: 500 });
|
|
154
|
+
await txClient.update('transfers', 'tr-1', { status: 'COMPLETED' });
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## 4. Reading Data & Declarative Queries
|
|
161
|
+
|
|
162
|
+
### `client.findById(table, id, options?): Promise<T | null>`
|
|
163
|
+
Fetches a single record by its primary key. Excludes soft-deleted records by default.
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
const todo = await client.findById('todos', 'todo-1');
|
|
167
|
+
// Include soft-deleted rows:
|
|
168
|
+
const deletedTodo = await client.findById('todos', 'todo-1', { includeDeleted: true });
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### `client.findByIds(table, ids, options?): Promise<T[]>`
|
|
172
|
+
Fetches multiple records by their primary keys in a single `WHERE id IN (...)` query.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
const items = await client.findByIds('todos', ['todo-1', 'todo-2', 'todo-3']);
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### `client.findMany(table, options?): Promise<T[]>`
|
|
179
|
+
Fetches records matching declarative filtering and sorting options.
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
const activeWork = await client.findMany('tasks', {
|
|
183
|
+
where: {
|
|
184
|
+
completed: 0,
|
|
185
|
+
priority: { $gte: 2 },
|
|
186
|
+
tags: { $contains: 'urgent' },
|
|
187
|
+
},
|
|
188
|
+
orderBy: 'due_date',
|
|
189
|
+
order: 'asc',
|
|
190
|
+
limit: 25,
|
|
191
|
+
offset: 0,
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### Supported Query Operators:
|
|
196
|
+
|
|
197
|
+
| Operator | Syntax | Description | Example |
|
|
198
|
+
| :--- | :--- | :--- | :--- |
|
|
199
|
+
| **`$eq`** | `{ col: { $eq: val } }` or `{ col: val }` | Equal to | `{ status: 'ACTIVE' }` |
|
|
200
|
+
| **`$ne`** | `{ col: { $ne: val } }` | Not equal to | `{ status: { $ne: 'DELETED' } }` |
|
|
201
|
+
| **`$gt` / `$gte`** | `{ col: { $gt: val } }` | Greater than (or equal) | `{ age: { $gte: 18 } }` |
|
|
202
|
+
| **`$lt` / `$lte`** | `{ col: { $lt: val } }` | Less than (or equal) | `{ price: { $lte: 99.99 } }` |
|
|
203
|
+
| **`$in`** | `{ col: { $in: [a, b] } }` | In set | `{ role: { $in: ['admin', 'manager'] } }` |
|
|
204
|
+
| **`$nin`** | `{ col: { $nin: [a, b] } }` | Not in set | `{ status: { $nin: ['archived'] } }` |
|
|
205
|
+
| **`$like`** | `{ col: { $like: '%term%' } }` | SQL LIKE pattern | `{ name: { $like: 'John%' } }` |
|
|
206
|
+
| **`$contains`** | `{ col: { $contains: 'word' } }` | Case-insensitive substring | `{ email: { $contains: '@gmail' } }` |
|
|
207
|
+
| **`$between`** | `{ col: { $between: [min, max] } }` | Between range (inclusive) | `{ score: { $between: [70, 100] } }` |
|
|
208
|
+
| **`$isNull`** | `{ col: { $isNull: true } }` | IS NULL | `{ deleted_at: { $isNull: true } }` |
|
|
209
|
+
| **`$isNotNull`** | `{ col: { $isNotNull: true } }` | IS NOT NULL | `{ verified_at: { $isNotNull: true } }` |
|
|
210
|
+
| **`$or`** | `{ $or: [condA, condB] }` | Logical OR | `{ $or: [{ role: 'admin' }, { points: { $gt: 100 } }] }` |
|
|
211
|
+
| **`$and`** | `{ $and: [condA, condB] }` | Logical AND | `{ $and: [{ active: 1 }, { verified: 1 }] }` |
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## 5. Fluent SQL QueryBuilder (`client.from()`)
|
|
216
|
+
|
|
217
|
+
Build optimized relational queries with joins, grouping, and method chaining:
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
const report = await client
|
|
221
|
+
.from('orders')
|
|
222
|
+
.select(
|
|
223
|
+
'orders.id',
|
|
224
|
+
'orders.total',
|
|
225
|
+
'customers.name AS customer_name',
|
|
226
|
+
'customers.email'
|
|
227
|
+
)
|
|
228
|
+
.join('customers', 'orders.customer_id', 'customers.id')
|
|
229
|
+
.leftJoin('discounts', 'orders.discount_id', 'discounts.id')
|
|
230
|
+
.where({
|
|
231
|
+
'orders.status': 'COMPLETED',
|
|
232
|
+
'orders.total': { $gte: 100 },
|
|
233
|
+
})
|
|
234
|
+
.orderBy('orders.created_at', 'desc')
|
|
235
|
+
.limit(50)
|
|
236
|
+
.execute();
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## 6. Native SQL Aggregations
|
|
242
|
+
|
|
243
|
+
Compute metrics natively in SQLite without fetching all rows into memory:
|
|
244
|
+
|
|
245
|
+
### Simple Aggregates:
|
|
246
|
+
```typescript
|
|
247
|
+
const totalUsers = await client.count('users', { where: { active: 1 } });
|
|
248
|
+
const totalRevenue = await client.sum('orders', 'total', { where: { status: 'PAID' } });
|
|
249
|
+
const avgRating = await client.avg('reviews', 'rating');
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Multi-Metric Aggregation:
|
|
253
|
+
Calculate count, sums, averages, minimums, and maximums in a single query:
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
const stats = await client.aggregate('receipts', {
|
|
257
|
+
where: { business_id: 'biz_01' },
|
|
258
|
+
count: true,
|
|
259
|
+
sum: ['amount', 'tax', 'discount'],
|
|
260
|
+
avg: ['amount'],
|
|
261
|
+
min: ['created_at'],
|
|
262
|
+
max: ['amount'],
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
console.log(stats.count); // e.g. 150
|
|
266
|
+
console.log(stats.sum?.amount); // e.g. 4520.50
|
|
267
|
+
console.log(stats.avg?.amount); // e.g. 30.14
|
|
268
|
+
console.log(stats.max?.amount); // e.g. 500.00
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
## 7. Direct Raw SQL (`client.query`)
|
|
274
|
+
|
|
275
|
+
Execute arbitrary SQL statements directly on SQLite with bound parameters:
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
const result = await client.query(`
|
|
279
|
+
SELECT
|
|
280
|
+
strftime('%Y-%m', created_at) AS month,
|
|
281
|
+
COUNT(*) AS total_count,
|
|
282
|
+
SUM(amount) AS monthly_revenue
|
|
283
|
+
FROM invoices
|
|
284
|
+
WHERE deleted = 0
|
|
285
|
+
GROUP BY month
|
|
286
|
+
ORDER BY month DESC
|
|
287
|
+
`);
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
---
|
|
291
|
+
|
|
292
|
+
## 8. JSON Columns & Auto-Hydration
|
|
293
|
+
|
|
294
|
+
SQLite stores JSON as text strings. `local-lite` supports automatic serialization on write and auto-deserialization on read:
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
export const client = new LocalFirstClient({
|
|
298
|
+
local: dbAdapter,
|
|
299
|
+
remote: remoteAdapter,
|
|
300
|
+
// Automatically deserialize specific table columns
|
|
301
|
+
jsonColumns: {
|
|
302
|
+
patients: ['allergies', 'emergency_contacts', 'metadata'],
|
|
303
|
+
milestones: ['measurements'],
|
|
304
|
+
},
|
|
305
|
+
// Or automatically hydrate any column containing valid JSON object/array strings
|
|
306
|
+
autoHydrateJSON: true,
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// Write normal JavaScript objects:
|
|
310
|
+
await client.insert('patients', {
|
|
311
|
+
name: 'Jane Doe',
|
|
312
|
+
allergies: ['Penicillin', 'Peanuts'],
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
// Read automatically returns arrays/objects, not JSON strings:
|
|
316
|
+
const patient = await client.findById('patients', id);
|
|
317
|
+
console.log(Array.isArray(patient.allergies)); // true
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
---
|
|
321
|
+
|
|
322
|
+
## 9. Dynamic Multi-Tenant User Data Isolation (`syncScope`)
|
|
323
|
+
|
|
324
|
+
For multi-tenant apps or applications where users should only pull and push their own data:
|
|
325
|
+
|
|
326
|
+
```typescript
|
|
327
|
+
export const client = new LocalFirstClient({
|
|
328
|
+
local: dbAdapter,
|
|
329
|
+
remote: remoteAdapter,
|
|
330
|
+
// Static scope:
|
|
331
|
+
syncScope: { user_id: 'user_abc123' },
|
|
332
|
+
|
|
333
|
+
// Or dynamic async scope function:
|
|
334
|
+
syncScope: async () => {
|
|
335
|
+
const session = await authClient.getUser();
|
|
336
|
+
return session ? { user_id: session.id, organization_id: session.orgId } : {};
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
// Update tenant or active user dynamically upon login or switch:
|
|
341
|
+
client.setSyncScope({ user_id: 'new_user_456' });
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
---
|
|
345
|
+
|
|
346
|
+
## 10. Outbox Inspection & Telemetry
|
|
347
|
+
|
|
348
|
+
Inspect and control the transactional outbox:
|
|
349
|
+
|
|
350
|
+
```typescript
|
|
351
|
+
// 1. Get real-time performance telemetry
|
|
352
|
+
const metrics = await client.getMetrics();
|
|
353
|
+
console.log(metrics.totalPushedMutations);
|
|
354
|
+
console.log(metrics.totalPulledDeltas);
|
|
355
|
+
console.log(metrics.lastPushDurationMs);
|
|
356
|
+
console.log(metrics.lastPullDurationMs);
|
|
357
|
+
|
|
358
|
+
// 2. Fetch pending or failed outbox records
|
|
359
|
+
const records = await client.getOutboxRecords({
|
|
360
|
+
status: 'FAILED',
|
|
361
|
+
limit: 50,
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
// 3. Retry failed mutations (resets status to PENDING and triggers immediate push)
|
|
365
|
+
await client.retryFailedMutations();
|
|
366
|
+
|
|
367
|
+
// 4. Remove poison-pill mutations permanently
|
|
368
|
+
await client.clearFailedMutations();
|
|
369
|
+
|
|
370
|
+
// 5. Inspect and reset pull cursor
|
|
371
|
+
const lastSyncedAt = await client.getLastSyncedAt();
|
|
372
|
+
await client.resetSyncCursor(); // Forces next pull to re-fetch all cloud data
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
---
|
|
376
|
+
|
|
377
|
+
## 11. Action Outbox & Email Queue (`client.actions`)
|
|
378
|
+
|
|
379
|
+
Enqueues asynchronous actions (emails, notifications, webhooks) with offline durability, idempotency deduplication, and automatic retries.
|
|
380
|
+
|
|
381
|
+
```typescript
|
|
382
|
+
// Enqueue an email offline (instant 0ms local write)
|
|
383
|
+
const emailAction = await client.actions.sendEmail({
|
|
384
|
+
to: 'customer@example.com',
|
|
385
|
+
subject: 'Order Confirmed',
|
|
386
|
+
html: '<h1>Thank you!</h1>',
|
|
387
|
+
idempotencyKey: 'order_123',
|
|
388
|
+
ttlMs: 24 * 60 * 60 * 1000,
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
// Register an email dispatcher
|
|
392
|
+
client.actions.registerEmailHandler(async (email) => {
|
|
393
|
+
const res = await sendWithProvider(email);
|
|
394
|
+
return { messageId: res.id };
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
// Enqueue generic offline actions
|
|
398
|
+
await client.actions.enqueue({
|
|
399
|
+
action: 'push_notification',
|
|
400
|
+
payload: { title: 'New message', token: 'fcm-xxx' },
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
// Flush pending actions immediately
|
|
404
|
+
await client.actions.flush();
|
|
405
|
+
|
|
406
|
+
// Query, cancel, or prune actions
|
|
407
|
+
const action = await client.actions.get(emailAction.id);
|
|
408
|
+
await client.actions.cancel(emailAction.id);
|
|
409
|
+
await client.actions.prune({ completedOlderThanMs: 86400000 });
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
See the dedicated [**Action Outbox & Email Queue Guide**](./actions-email.md) for full architecture, cloud function integration, and options reference.
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# ⚙️ Configuration Reference
|
|
2
|
+
|
|
3
|
+
The configuration engine uses `defineSyncConfig(config)` to provide full TypeScript autocompletion and compile-time validation.
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
import { defineSyncConfig, createSyncClient } from 'local-lite/config';
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Complete `LocalLiteConfig` Options
|
|
12
|
+
|
|
13
|
+
### Database, Tables & Schema
|
|
14
|
+
|
|
15
|
+
| Option | Type | Default | Description |
|
|
16
|
+
| :--- | :--- | :--- | :--- |
|
|
17
|
+
| `database` | `any \| string \| (() => Promise<any>) \| LocalDBAdapter` | Optional | Database instance, factory function, or custom adapter. |
|
|
18
|
+
| `databaseName` | `string` | Not set | Database filename when auto-opening via `expo-sqlite`. |
|
|
19
|
+
| `tables` | `string[]` | `[]` | List of table names to synchronize. |
|
|
20
|
+
| `relationships` | `RelationshipDefinition[]` | `[]` | Parent-child relationships and delete behavior handled by local-lite mutation methods. |
|
|
21
|
+
| `autoSchema` | `boolean` | `false` | When true, automatically creates tables and adds missing columns dynamically on insert/update. |
|
|
22
|
+
| `primaryKey` | `string` | `'id'` | Primary key column name used across tables. |
|
|
23
|
+
| `schemaMigrations` | `SchemaMigration[]` | `[]` | Consecutive, versioned SQL migrations applied once and recorded in the local `schema_migrations` table. |
|
|
24
|
+
| `autoStart` | `boolean` | `true` | Start automatic sync after initialization. Set false to queue writes and push/pull manually. |
|
|
25
|
+
| `autoInitialize` | `boolean` | `true` | Automatically creates internal outbox tables and initializes the client on startup. |
|
|
26
|
+
|
|
27
|
+
### Relationship delete behavior
|
|
28
|
+
|
|
29
|
+
Configure child-table foreign keys in `relationships`. When a parent is deleted through
|
|
30
|
+
`client.delete()`, `client.mutate(..., 'DELETE')`, a transaction, or `client.batch()`,
|
|
31
|
+
local-lite applies each relationship's `onDelete` action atomically and records the
|
|
32
|
+
resulting child mutations in the outbox. Include both parent and child tables in
|
|
33
|
+
`tables` when that list is configured. Relationship table/column names are checked
|
|
34
|
+
for required values and supported delete actions are validated during client setup.
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
const config = defineSyncConfig({
|
|
38
|
+
tables: ['children', 'milestones', 'visits'],
|
|
39
|
+
relationships: [
|
|
40
|
+
{
|
|
41
|
+
table: 'milestones',
|
|
42
|
+
foreignKey: 'childId',
|
|
43
|
+
references: 'children',
|
|
44
|
+
onDelete: 'cascade',
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
table: 'visits',
|
|
48
|
+
foreignKey: 'childId',
|
|
49
|
+
references: 'children',
|
|
50
|
+
onDelete: 'restrict',
|
|
51
|
+
},
|
|
52
|
+
],
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Supported actions are `cascade` (delete referencing rows recursively), `restrict`
|
|
57
|
+
(reject when referencing rows exist), `setNull` (clear the foreign key), and `noAction`
|
|
58
|
+
(the default, which also rejects immediately when referencing rows exist). `restrict`
|
|
59
|
+
and `noAction` therefore have the same behavior in local-lite. The child foreign-key
|
|
60
|
+
column must allow `NULL` when using `setNull`. `references` names the parent table;
|
|
61
|
+
local-lite uses the configured primary key, which defaults to `id`.
|
|
62
|
+
|
|
63
|
+
### Versioned schema migrations
|
|
64
|
+
|
|
65
|
+
Use `schemaMigrations` to apply app schema changes once in ascending version order.
|
|
66
|
+
Keep the full migration history in the app so an older local database can catch up
|
|
67
|
+
after an upgrade. Versions must be consecutive integers starting at `1`. Each
|
|
68
|
+
migration runs in the database transaction and is recorded only after its SQL
|
|
69
|
+
succeeds. A migration failure rolls back the migration batch and prevents sync
|
|
70
|
+
from starting. Migrations only move forward; write additive SQL when old app
|
|
71
|
+
versions or stored data must remain compatible.
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
schemaMigrations: [
|
|
75
|
+
{
|
|
76
|
+
version: 1,
|
|
77
|
+
up: 'CREATE TABLE todos (id TEXT PRIMARY KEY, title TEXT NOT NULL)',
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
version: 2,
|
|
81
|
+
up: 'ALTER TABLE todos ADD COLUMN completed INTEGER NOT NULL DEFAULT 0',
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The legacy `migrations` option has been removed. Move each SQL statement into a
|
|
87
|
+
versioned entry in `schemaMigrations`; migrations now run once and are tracked in
|
|
88
|
+
the local `schema_migrations` table.
|
|
89
|
+
|
|
90
|
+
`autoSchema` remains available for inferred schemas, but explicit migrations are
|
|
91
|
+
recommended when you need predictable upgrades. If both are configured, migrations
|
|
92
|
+
run before `autoSchema`.
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
### Sync Performance & Advanced SQLite Policies
|
|
97
|
+
|
|
98
|
+
| Option | Type | Default | Description |
|
|
99
|
+
| :--- | :--- | :--- | :--- |
|
|
100
|
+
| `coalesceOutbox` | `boolean` | `true` | When true, multiple pending mutations for the same row are coalesced into a single outbox record before pushing (e.g. intermediate updates are merged, and an insert followed by an offline delete is discarded), drastically reducing bandwidth. |
|
|
101
|
+
| `touchUpdatedAt` | `boolean \| string` | `true` | Stamps an `updated_at` (or specified column name) on every local INSERT/UPDATE write in SQLite so reactive queries (which compare rows by `id` + `updated_at`) immediately detect offline edits. Only the local row is stamped; remote outbox payloads are untouched. |
|
|
102
|
+
| `autoPauseOnBackground` | `boolean` | `true` | When true on React Native/Expo, automatically pauses polling intervals and timers when the app moves to the background to conserve device battery and CPU, and resumes immediately upon foregrounding. |
|
|
103
|
+
| `jsonColumns` | `Record<string, string[]>` | `{}` | Map of table names to arrays of column names containing JSON data. These columns are automatically serialized to JSON strings on write and parsed back to JavaScript objects/arrays on read. |
|
|
104
|
+
| `autoHydrateJSON` | `boolean` | `false` | When true, any string value that begins and ends with `{}` or `[]` is automatically parsed with `JSON.parse` upon query execution. |
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
### Dynamic User Data Isolation & Multi-Tenancy (`syncScope`)
|
|
109
|
+
|
|
110
|
+
For multi-tenant apps or applications where users should only push and pull records matching their account ID:
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
export const syncConfig = defineSyncConfig({
|
|
114
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
115
|
+
tables: ['milestones', 'records'],
|
|
116
|
+
|
|
117
|
+
// Static user scope:
|
|
118
|
+
syncScope: { user_id: 'user_123' },
|
|
119
|
+
|
|
120
|
+
// Or dynamic async scope function:
|
|
121
|
+
syncScope: async () => {
|
|
122
|
+
const user = await authClient.getUser();
|
|
123
|
+
return user ? { user_id: user.id } : {};
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
* The active scope is passed down to `remoteAdapter.fetchChanges(since, syncScope)` to filter remote delta queries.
|
|
129
|
+
* In Supabase, queries filter matching columns automatically.
|
|
130
|
+
* You can update the scope dynamically after login with `client.setSyncScope({ user_id: user.id })`.
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
### Remote Cloud Backends
|
|
135
|
+
|
|
136
|
+
Provide **one** of the following backend options:
|
|
137
|
+
|
|
138
|
+
#### `supabase`
|
|
139
|
+
```typescript
|
|
140
|
+
supabase: {
|
|
141
|
+
url?: string; // Supabase Project URL (e.g. process.env.EXPO_PUBLIC_SUPABASE_URL)
|
|
142
|
+
anonKey?: string; // Supabase Anon / Publishable Key
|
|
143
|
+
client?: SupabaseClient; // Optional pre-instantiated Supabase client
|
|
144
|
+
schema?: string; // Postgres schema (Default: 'public')
|
|
145
|
+
updatedAtColumn?: string; // Timestamp column for deltas (Default: 'updated_at')
|
|
146
|
+
deletedColumn?: string; // Column for soft deletes (Default: 'deleted')
|
|
147
|
+
deletedValue?: any; // Value for deleted rows (Default: true)
|
|
148
|
+
pushRpcName?: string; // Optional custom RPC name for bulk operations
|
|
149
|
+
channelName?: string; // Realtime broadcast channel name (Default: 'local_first_sync')
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
#### `convex`
|
|
154
|
+
```typescript
|
|
155
|
+
convex: {
|
|
156
|
+
client: ConvexClient; // Instantiated ConvexClient
|
|
157
|
+
pushMutation?: any; // Mutation function/name for pushes (Default: 'sync:pushBatch')
|
|
158
|
+
pullQuery?: any; // Query function/name for deltas (Default: 'sync:pullDeltas')
|
|
159
|
+
primaryKey?: string; // Primary key column name (Default: 'id')
|
|
160
|
+
deletedColumn?: string; // Column for soft deletes (Default: 'deleted')
|
|
161
|
+
updatedAtColumn?: string; // Timestamp column for deltas (Default: 'updatedAt')
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### `firebase`
|
|
166
|
+
```typescript
|
|
167
|
+
firebase: {
|
|
168
|
+
firestore: Firestore; // Modular Firestore instance or @react-native-firebase/firestore
|
|
169
|
+
primaryKey?: string; // Primary key field (Default: 'id')
|
|
170
|
+
updatedAtColumn?: string; // Timestamp field for delta pulls (Default: 'updatedAt')
|
|
171
|
+
deletedColumn?: string; // Boolean field for soft deletes (Default: 'deleted')
|
|
172
|
+
firestoreModule?: any; // Optional reference to modular firebase/firestore SDK
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
#### `remote`
|
|
177
|
+
Pass an object implementing `RemoteDBAdapter` to connect to custom REST, GraphQL, or WebSocket servers.
|
|
178
|
+
|
|
179
|
+
#### `inMemoryRemote`
|
|
180
|
+
* Type: `boolean` (Default: `false`)
|
|
181
|
+
* Missing backend configuration throws unless `inMemoryRemote: true` is explicitly enabled.
|
|
182
|
+
* Simulates an in-memory remote backend with 300ms artificial network delay for unit testing and offline development.
|
|
183
|
+
|
|
184
|
+
---
|
|
185
|
+
|
|
186
|
+
### Timing, Retry & Exponential Backoff
|
|
187
|
+
|
|
188
|
+
| Option | Type | Default | Description |
|
|
189
|
+
| :--- | :--- | :--- | :--- |
|
|
190
|
+
| `pushIntervalMs` | `number` | `5000` | Periodic timer interval (in ms) to flush pending outbox records to remote. |
|
|
191
|
+
| `pullIntervalMs` | `number` | `10000` | Periodic timer interval (in ms) to fetch remote deltas. |
|
|
192
|
+
| `maxRetries` | `number` | `5` | Maximum push attempts before a failing mutation is marked as `FAILED`. |
|
|
193
|
+
| `retry` | `number \| RetryConfig` | — | Advanced retry settings with exponential backoff and jitter. |
|
|
194
|
+
|
|
195
|
+
#### Advanced Retry Configuration:
|
|
196
|
+
```typescript
|
|
197
|
+
retry: {
|
|
198
|
+
maxRetries: Infinity, // Supports infinite retries for persistent background sync
|
|
199
|
+
initialDelayMs: 1000, // Delay before the first retry (1 second)
|
|
200
|
+
maxDelayMs: 30000, // Max ceiling delay (30 seconds)
|
|
201
|
+
backoffMultiplier: 1.5, // Exponential backoff multiplier
|
|
202
|
+
jitter: true, // Add randomized jitter to avoid synchronized server stampedes
|
|
203
|
+
shouldRetry: (err, op) => {
|
|
204
|
+
// Only retry transient network/server errors; fail immediately on 400 Bad Request
|
|
205
|
+
if (err?.status === 400) return false;
|
|
206
|
+
return true;
|
|
207
|
+
},
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
### Logging & Diagnostics
|
|
214
|
+
|
|
215
|
+
| Option | Type | Default | Description |
|
|
216
|
+
| :--- | :--- | :--- | :--- |
|
|
217
|
+
| `logLevel` | `'debug' \| 'info' \| 'warn' \| 'error' \| 'none'` | `'info'` | Minimum log verbosity. |
|
|
218
|
+
| `logger` | `SyncLogger \| CustomLogger \| boolean` | Default | Pass `false` to silence all logs, or supply a custom logger (e.g., Sentry, Winston, Datadog). |
|
|
219
|
+
|
|
220
|
+
#### Custom Logger Example:
|
|
221
|
+
```typescript
|
|
222
|
+
logger: {
|
|
223
|
+
debug: (msg, ...args) => console.debug('[Sync]', msg, ...args),
|
|
224
|
+
info: (msg, ...args) => console.info('[Sync]', msg, ...args),
|
|
225
|
+
warn: (msg, ...args) => console.warn('[Sync]', msg, ...args),
|
|
226
|
+
error: (msg, ...args) => Sentry.captureMessage(msg),
|
|
227
|
+
}
|
|
228
|
+
```
|