local-lite 0.2.1 → 0.2.3
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 +5 -2
- package/bin/local-lite.mjs +65 -61
- package/dist/adapters/remote/convex.d.ts +25 -1
- package/dist/adapters/remote/convex.js +59 -0
- package/dist/adapters/remote/index.d.ts +28 -0
- package/dist/adapters/remote/supabase.d.ts +25 -1
- package/dist/adapters/remote/supabase.js +90 -0
- package/dist/auth/local.d.ts +33 -1
- package/dist/auth/local.js +94 -13
- package/dist/core/client.d.ts +25 -1
- package/dist/core/client.js +56 -0
- package/package.json +1 -2
- package/skills/local-lite-auth/SKILL.md +67 -27
- package/skills/local-lite-server/SKILL.md +127 -0
- package/docs/.nojekyll +0 -1
- package/docs/README.md +0 -108
- package/docs/_sidebar.md +0 -22
- package/docs/actions-email.md +0 -222
- package/docs/adapters-local.md +0 -272
- package/docs/adapters-remote.md +0 -291
- package/docs/api-keys.md +0 -114
- package/docs/architecture.md +0 -106
- package/docs/auth.md +0 -342
- package/docs/backups.md +0 -214
- package/docs/breaking-changes.md +0 -147
- package/docs/client-api.md +0 -412
- package/docs/configuration.md +0 -228
- package/docs/conflict-resolution.md +0 -78
- package/docs/getting-started.md +0 -190
- package/docs/google-auth.md +0 -234
- package/docs/index.html +0 -166
- package/docs/kv.md +0 -89
- package/docs/maintenance-portability.md +0 -133
- package/docs/react-hooks.md +0 -457
- package/docs/scheduler.md +0 -81
- package/docs/search.md +0 -71
- package/docs/server.md +0 -101
- package/docs/session.md +0 -129
- package/docs/storage.md +0 -265
package/docs/adapters-remote.md
DELETED
|
@@ -1,291 +0,0 @@
|
|
|
1
|
-
# 🌐 Remote Backend Adapters
|
|
2
|
-
|
|
3
|
-
`local-lite` supports multiple cloud synchronization backends out of the box.
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## 1. Supabase (Postgres + Realtime)
|
|
8
|
-
|
|
9
|
-
The Supabase adapter synchronizes local SQLite tables with Supabase Postgres tables in real time.
|
|
10
|
-
|
|
11
|
-
```bash
|
|
12
|
-
npm install @supabase/supabase-js
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
### 1.1 Postgres Setup (SQL Editor)
|
|
16
|
-
|
|
17
|
-
Run the following SQL in your Supabase SQL Editor to enable timestamp triggers and soft deletes:
|
|
18
|
-
|
|
19
|
-
```sql
|
|
20
|
-
-- Ensure every application table has the soft-delete column expected by local-lite.
|
|
21
|
-
DO $$
|
|
22
|
-
DECLARE
|
|
23
|
-
table_record RECORD;
|
|
24
|
-
BEGIN
|
|
25
|
-
FOR table_record IN
|
|
26
|
-
SELECT table_schema, table_name
|
|
27
|
-
FROM information_schema.tables
|
|
28
|
-
WHERE table_schema = 'public'
|
|
29
|
-
AND table_type = 'BASE TABLE'
|
|
30
|
-
LOOP
|
|
31
|
-
EXECUTE format(
|
|
32
|
-
'ALTER TABLE %I.%I ADD COLUMN IF NOT EXISTS deleted BOOLEAN',
|
|
33
|
-
table_record.table_schema,
|
|
34
|
-
table_record.table_name
|
|
35
|
-
);
|
|
36
|
-
EXECUTE format(
|
|
37
|
-
'UPDATE %I.%I SET deleted = FALSE WHERE deleted IS NULL',
|
|
38
|
-
table_record.table_schema,
|
|
39
|
-
table_record.table_name
|
|
40
|
-
);
|
|
41
|
-
EXECUTE format(
|
|
42
|
-
'ALTER TABLE %I.%I ALTER COLUMN deleted SET DEFAULT FALSE',
|
|
43
|
-
table_record.table_schema,
|
|
44
|
-
table_record.table_name
|
|
45
|
-
);
|
|
46
|
-
EXECUTE format(
|
|
47
|
-
'ALTER TABLE %I.%I ALTER COLUMN deleted SET NOT NULL',
|
|
48
|
-
table_record.table_schema,
|
|
49
|
-
table_record.table_name
|
|
50
|
-
);
|
|
51
|
-
END LOOP;
|
|
52
|
-
END $$;
|
|
53
|
-
|
|
54
|
-
-- 1. Automatic Timestamp Trigger
|
|
55
|
-
CREATE OR REPLACE FUNCTION public.set_sync_updated_at()
|
|
56
|
-
RETURNS TRIGGER AS $$
|
|
57
|
-
BEGIN
|
|
58
|
-
NEW.updated_at = NOW();
|
|
59
|
-
RETURN NEW;
|
|
60
|
-
END;
|
|
61
|
-
$$ LANGUAGE plpgsql;
|
|
62
|
-
|
|
63
|
-
-- 2. Create your table
|
|
64
|
-
CREATE TABLE IF NOT EXISTS public.todos (
|
|
65
|
-
id TEXT PRIMARY KEY,
|
|
66
|
-
title TEXT NOT NULL,
|
|
67
|
-
completed BOOLEAN DEFAULT false,
|
|
68
|
-
deleted BOOLEAN DEFAULT false,
|
|
69
|
-
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
-- 3. Attach trigger
|
|
73
|
-
CREATE TRIGGER tr_todos_updated_at
|
|
74
|
-
BEFORE UPDATE ON public.todos
|
|
75
|
-
FOR EACH ROW EXECUTE FUNCTION public.set_sync_updated_at();
|
|
76
|
-
|
|
77
|
-
-- 4. Enable Supabase Realtime
|
|
78
|
-
ALTER PUBLICATION supabase_realtime ADD TABLE public.todos;
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
### 1.2 Client Configuration
|
|
82
|
-
|
|
83
|
-
```typescript
|
|
84
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
85
|
-
|
|
86
|
-
export const config = defineSyncConfig({
|
|
87
|
-
tables: ['todos'],
|
|
88
|
-
supabase: {
|
|
89
|
-
url: process.env.EXPO_PUBLIC_SUPABASE_URL,
|
|
90
|
-
anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY,
|
|
91
|
-
updatedAtColumn: 'updated_at',
|
|
92
|
-
deletedColumn: 'deleted',
|
|
93
|
-
deletedValue: true,
|
|
94
|
-
},
|
|
95
|
-
});
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
---
|
|
99
|
-
|
|
100
|
-
## 2. Convex (Reactive Cloud Documents)
|
|
101
|
-
|
|
102
|
-
The Convex adapter coordinates with a live Convex backend via batch mutations and delta queries.
|
|
103
|
-
|
|
104
|
-
```bash
|
|
105
|
-
npm install convex
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
### 2.1 Convex Schema (`convex/schema.ts`)
|
|
109
|
-
|
|
110
|
-
```typescript
|
|
111
|
-
// convex/schema.ts
|
|
112
|
-
import { defineSchema, defineTable } from 'convex/server';
|
|
113
|
-
import { v } from 'convex/values';
|
|
114
|
-
|
|
115
|
-
export default defineSchema({
|
|
116
|
-
todos: defineTable({
|
|
117
|
-
id: v.string(),
|
|
118
|
-
title: v.string(),
|
|
119
|
-
completed: v.boolean(),
|
|
120
|
-
deleted: v.boolean(),
|
|
121
|
-
updatedAt: v.number(),
|
|
122
|
-
}).index('by_updatedAt', ['updatedAt']),
|
|
123
|
-
});
|
|
124
|
-
```
|
|
125
|
-
|
|
126
|
-
### 2.2 Convex Sync Functions (`convex/sync.ts`)
|
|
127
|
-
|
|
128
|
-
```typescript
|
|
129
|
-
// convex/sync.ts
|
|
130
|
-
import { mutationGeneric as mutation, queryGeneric as query } from 'convex/server';
|
|
131
|
-
import { v } from 'convex/values';
|
|
132
|
-
|
|
133
|
-
export const pushBatch = mutation({
|
|
134
|
-
args: {
|
|
135
|
-
operations: v.array(
|
|
136
|
-
v.object({
|
|
137
|
-
id: v.string(),
|
|
138
|
-
tableName: v.string(),
|
|
139
|
-
rowId: v.string(),
|
|
140
|
-
operation: v.string(),
|
|
141
|
-
payload: v.any(),
|
|
142
|
-
timestamp: v.number(),
|
|
143
|
-
})
|
|
144
|
-
),
|
|
145
|
-
},
|
|
146
|
-
handler: async (ctx, args) => {
|
|
147
|
-
for (const op of args.operations) {
|
|
148
|
-
const table = op.tableName as 'todos';
|
|
149
|
-
const existing = await ctx.db
|
|
150
|
-
.query(table)
|
|
151
|
-
.filter((q) => q.eq(q.field('id'), op.rowId))
|
|
152
|
-
.first();
|
|
153
|
-
|
|
154
|
-
if (op.operation === 'DELETE') {
|
|
155
|
-
if (existing) {
|
|
156
|
-
await ctx.db.patch(existing._id, { deleted: true, updatedAt: op.timestamp });
|
|
157
|
-
}
|
|
158
|
-
} else {
|
|
159
|
-
const doc = { ...(op.payload || {}), id: op.rowId, deleted: false, updatedAt: op.timestamp };
|
|
160
|
-
if (existing) {
|
|
161
|
-
await ctx.db.patch(existing._id, doc);
|
|
162
|
-
} else {
|
|
163
|
-
await ctx.db.insert(table, doc);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return true;
|
|
168
|
-
},
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
export const pullDeltas = query({
|
|
172
|
-
args: {
|
|
173
|
-
sinceTimestamp: v.number(),
|
|
174
|
-
tables: v.array(v.string()),
|
|
175
|
-
},
|
|
176
|
-
handler: async (ctx, args) => {
|
|
177
|
-
const results: Record<string, any[]> = {};
|
|
178
|
-
for (const table of args.tables) {
|
|
179
|
-
const rows = await ctx.db
|
|
180
|
-
.query(table as 'todos')
|
|
181
|
-
.withIndex('by_updatedAt', (q) => q.gt('updatedAt', args.sinceTimestamp))
|
|
182
|
-
.collect();
|
|
183
|
-
results[table] = rows;
|
|
184
|
-
}
|
|
185
|
-
return results;
|
|
186
|
-
},
|
|
187
|
-
});
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
### 2.3 Client Configuration
|
|
191
|
-
|
|
192
|
-
```typescript
|
|
193
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
194
|
-
import { ConvexClient } from 'convex/browser';
|
|
195
|
-
|
|
196
|
-
const convexClient = new ConvexClient(process.env.EXPO_PUBLIC_CONVEX_URL!);
|
|
197
|
-
|
|
198
|
-
export const config = defineSyncConfig({
|
|
199
|
-
tables: ['todos'],
|
|
200
|
-
convex: {
|
|
201
|
-
client: convexClient,
|
|
202
|
-
pushMutation: 'sync:pushBatch',
|
|
203
|
-
pullQuery: 'sync:pullDeltas',
|
|
204
|
-
updatedAtColumn: 'updatedAt',
|
|
205
|
-
deletedColumn: 'deleted',
|
|
206
|
-
},
|
|
207
|
-
});
|
|
208
|
-
```
|
|
209
|
-
|
|
210
|
-
---
|
|
211
|
-
|
|
212
|
-
## 3. Firebase / Cloud Firestore
|
|
213
|
-
|
|
214
|
-
Synchronizes local SQLite with Google Cloud Firestore collections.
|
|
215
|
-
|
|
216
|
-
```bash
|
|
217
|
-
npm install firebase # or @react-native-firebase/firestore
|
|
218
|
-
```
|
|
219
|
-
|
|
220
|
-
### Client Configuration
|
|
221
|
-
|
|
222
|
-
```typescript
|
|
223
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
224
|
-
import { initializeApp } from 'firebase/app';
|
|
225
|
-
import { getFirestore } from 'firebase/firestore';
|
|
226
|
-
|
|
227
|
-
const app = initializeApp({
|
|
228
|
-
apiKey: process.env.EXPO_PUBLIC_FIREBASE_API_KEY,
|
|
229
|
-
projectId: process.env.EXPO_PUBLIC_FIREBASE_PROJECT_ID,
|
|
230
|
-
});
|
|
231
|
-
const firestore = getFirestore(app);
|
|
232
|
-
|
|
233
|
-
export const config = defineSyncConfig({
|
|
234
|
-
tables: ['todos'],
|
|
235
|
-
firebase: {
|
|
236
|
-
firestore,
|
|
237
|
-
updatedAtColumn: 'updatedAt',
|
|
238
|
-
deletedColumn: 'deleted',
|
|
239
|
-
},
|
|
240
|
-
});
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
---
|
|
244
|
-
|
|
245
|
-
## 4. In-Memory Simulated Demo Backend
|
|
246
|
-
|
|
247
|
-
For mock testing, automated unit tests, and prototyping when you don't have internet access or cloud credentials:
|
|
248
|
-
|
|
249
|
-
```typescript
|
|
250
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
251
|
-
|
|
252
|
-
export const config = defineSyncConfig({
|
|
253
|
-
tables: ['todos'],
|
|
254
|
-
inMemoryRemote: true, // Simulates remote with 300ms network delay
|
|
255
|
-
});
|
|
256
|
-
```
|
|
257
|
-
|
|
258
|
-
---
|
|
259
|
-
|
|
260
|
-
## 5. Custom Remote Adapters
|
|
261
|
-
|
|
262
|
-
Implement `RemoteDBAdapter` to connect `local-lite` to your own REST, GraphQL, or WebSocket servers:
|
|
263
|
-
|
|
264
|
-
```typescript
|
|
265
|
-
import { RemoteDBAdapter, SyncOperation, DeltaChanges } from 'local-lite';
|
|
266
|
-
|
|
267
|
-
export class MyCustomServerAdapter implements RemoteDBAdapter {
|
|
268
|
-
async pushChanges(operations: SyncOperation[]): Promise<boolean> {
|
|
269
|
-
const response = await fetch('https://api.mybackend.com/sync/push', {
|
|
270
|
-
method: 'POST',
|
|
271
|
-
headers: { 'Content-Type': 'application/json' },
|
|
272
|
-
body: JSON.stringify({ operations }),
|
|
273
|
-
});
|
|
274
|
-
return response.ok;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
async fetchChanges(sinceTimestamp: number): Promise<DeltaChanges> {
|
|
278
|
-
const res = await fetch(`https://api.mybackend.com/sync/pull?since=${sinceTimestamp}`);
|
|
279
|
-
return await res.json();
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
subscribeToLiveChanges(onRemoteChange: (changes: DeltaChanges) => void): () => void {
|
|
283
|
-
const ws = new WebSocket('wss://api.mybackend.com/realtime');
|
|
284
|
-
ws.onmessage = (event) => onRemoteChange(JSON.parse(event.data));
|
|
285
|
-
return () => ws.close();
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
```
|
|
289
|
-
|
|
290
|
-
`subscribeToLiveChanges()` must return a cleanup function even when no listener is
|
|
291
|
-
created; return a no-op function in that case.
|
package/docs/api-keys.md
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
# 🔐 API Keys & Signed Tokens Wrapper
|
|
2
|
-
|
|
3
|
-
`local-lite` provides a zero-dependency **API Key & Signed Token toolkit** for generating, verifying, hashing, and renewing keys and tokens. It does not replace your primary authentication (e.g. Supabase Auth, Google, Microsoft), but provides utilities for issuing developer API keys, tenant scanner keys, mobile session tokens, or signed renewal tokens.
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## ⚡ 1. Generating & Verifying Checksummed API Keys
|
|
8
|
-
|
|
9
|
-
Modern API keys (like GitHub `ghp_...` or Stripe `sk_live_...`) contain embedded checksums so their authenticity and integrity can be verified instantaneously without querying a database.
|
|
10
|
-
|
|
11
|
-
```typescript
|
|
12
|
-
import { generateApiKey, verifyApiKey, verifyApiKeyFormat } from 'local-lite/keys';
|
|
13
|
-
|
|
14
|
-
// 1. Generate an API key
|
|
15
|
-
const { key, keyHash, prefix, display } = generateApiKey({
|
|
16
|
-
prefix: 'prop', // Output: prop_x7A9..._c4f910e2
|
|
17
|
-
byteLength: 24, // 192 bits of cryptographically secure entropy
|
|
18
|
-
withChecksum: true, // Appends a 4-byte checksum
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
console.log('Plaintext Key (show to user once):', key);
|
|
22
|
-
console.log('Key Hash (safe to store in SQLite/Postgres):', keyHash);
|
|
23
|
-
console.log('Display Mask:', display); // e.g. "prop_...10e2"
|
|
24
|
-
|
|
25
|
-
// 2. Instant syntactic & checksum check (no DB required)
|
|
26
|
-
const isFormatValid = verifyApiKeyFormat(incomingKey, 'prop');
|
|
27
|
-
|
|
28
|
-
// 3. Cryptographic timing-safe verification against stored SHA-256 hash
|
|
29
|
-
const isValid = verifyApiKey(incomingKey, storedHash);
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
## ✍️ 2. Signed Tokens & Renewal (HMAC-SHA256)
|
|
35
|
-
|
|
36
|
-
For self-contained tokens that embed data (such as `{ businessId, role }`), expiration dates, and renewal capabilities without needing database lookups:
|
|
37
|
-
|
|
38
|
-
```typescript
|
|
39
|
-
import { createSignedToken, verifySignedToken, renewSignedToken } from 'local-lite/keys';
|
|
40
|
-
|
|
41
|
-
const SECRET = process.env.API_SIGNING_SECRET || 'your-secure-secret';
|
|
42
|
-
|
|
43
|
-
// 1. Create a signed token with expiration
|
|
44
|
-
const token = createSignedToken({
|
|
45
|
-
payload: { businessId: 'biz_123', role: 'admin' },
|
|
46
|
-
secret: SECRET,
|
|
47
|
-
expiresInMs: 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
// 2. Verify token signature and check expiration
|
|
51
|
-
const verification = verifySignedToken(token, SECRET);
|
|
52
|
-
if (verification.valid) {
|
|
53
|
-
console.log('Authorized Payload:', verification.payload);
|
|
54
|
-
console.log('Expires at:', new Date(verification.expiresAt!).toISOString());
|
|
55
|
-
} else if (verification.expired) {
|
|
56
|
-
console.warn('Token expired at:', verification.expiresAt);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
// 3. Renew an existing token (extends expiration with a fresh HMAC signature)
|
|
60
|
-
const renewedToken = renewSignedToken(token, SECRET, {
|
|
61
|
-
extendMs: 7 * 24 * 60 * 60 * 1000,
|
|
62
|
-
});
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
---
|
|
66
|
-
|
|
67
|
-
## 💾 3. SQLite Key Manager (`client.keys.*`)
|
|
68
|
-
|
|
69
|
-
`local-lite` includes an optional SQLite store (`_local_api_keys`) managed directly via `client.keys`:
|
|
70
|
-
|
|
71
|
-
### Creating a Key
|
|
72
|
-
```typescript
|
|
73
|
-
const { key, record } = await client.keys.create({
|
|
74
|
-
name: 'Mobile Property Scanner',
|
|
75
|
-
prefix: 'scan',
|
|
76
|
-
expiresInMs: 30 * 24 * 60 * 60 * 1000, // 30 days
|
|
77
|
-
metadata: { businessId: 'biz_99', device: 'iPad Warehouse 1' },
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
// Returns the raw key to show once, while persisting the SHA-256 hash to SQLite
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
### Verifying a Key
|
|
84
|
-
```typescript
|
|
85
|
-
const result = await client.keys.verify(incomingKey);
|
|
86
|
-
|
|
87
|
-
if (result.valid) {
|
|
88
|
-
console.log('Key is active for business:', result.record.metadata.businessId);
|
|
89
|
-
// Automatically stamps record.last_used_at in SQLite
|
|
90
|
-
} else {
|
|
91
|
-
console.error('Key verification failed:', result.status, result.error);
|
|
92
|
-
// status: 'INVALID' | 'EXPIRED' | 'REVOKED' | 'MALFORMED'
|
|
93
|
-
}
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### Revoking, Listing & Pruning
|
|
97
|
-
```typescript
|
|
98
|
-
// Revoke a compromised or deactivated key
|
|
99
|
-
await client.keys.revoke(keyId);
|
|
100
|
-
|
|
101
|
-
// List active or revoked keys
|
|
102
|
-
const keys = await client.keys.list({ revoked: false });
|
|
103
|
-
|
|
104
|
-
// Prune old revoked keys
|
|
105
|
-
await client.keys.prune({ revokedOlderThanMs: 30 * 24 * 60 * 60 * 1000 });
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
---
|
|
109
|
-
|
|
110
|
-
## 🔒 Security Guarantees
|
|
111
|
-
|
|
112
|
-
* **Timing-Safe Comparison:** Hash and signature comparisons use constant-time operations (`timingSafeEqual`) to prevent side-channel timing attacks.
|
|
113
|
-
* **Plaintext Safety:** Plaintext keys are never stored by `ApiKeyManager`; only SHA-256 digests are written to disk.
|
|
114
|
-
* **Tamper-Evident:** Signed tokens are signed using HMAC-SHA256 (`@noble/hashes`); any payload alteration invalidates the signature immediately.
|
package/docs/architecture.md
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
# 🏛️ Architecture & Concepts
|
|
2
|
-
|
|
3
|
-
`local-lite` is designed around the **Transactional Outbox Pattern**, a proven distributed systems architecture adapted for client applications.
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## The System Architecture
|
|
8
|
-
|
|
9
|
-
```
|
|
10
|
-
┌─────────────────────────────────────────────────────────────┐
|
|
11
|
-
│ React / React Native UI │
|
|
12
|
-
│ │
|
|
13
|
-
│ useLiveQuery() useSyncStatus() │
|
|
14
|
-
└────────▲──────────────────────────────────────────▲─────────┘
|
|
15
|
-
│ (Events: change:table) │ (Events: sync:status)
|
|
16
|
-
┌────────┴──────────────────────────────────────────┴─────────┐
|
|
17
|
-
│ EventEmitter │
|
|
18
|
-
└────────▲──────────────────────────────────────────▲─────────┘
|
|
19
|
-
│ (Emit) │ (Emit)
|
|
20
|
-
┌────────┴──────────────────────────────────────────┴─────────┐
|
|
21
|
-
│ LocalFirstClient │
|
|
22
|
-
│ │
|
|
23
|
-
│ insert() / update() / delete() / mutate() │
|
|
24
|
-
└────────┬──────────────────────────────────────────┬─────────┘
|
|
25
|
-
│ (Atomic Transaction) │ (Wakeup)
|
|
26
|
-
▼ ▼
|
|
27
|
-
┌─────────────────────────┐ ┌──────────────────────┐
|
|
28
|
-
│ Local SQLite Engine │ │ SyncWorker │
|
|
29
|
-
│ │ │ │
|
|
30
|
-
│ ┌─────────────────────┐ │ │ 1. Push Outbox items │
|
|
31
|
-
│ │ User Table (todos) │ │ │ 2. Fetch remote logs │
|
|
32
|
-
│ ├─────────────────────┤ │ │ 3. Resolve conflicts │
|
|
33
|
-
│ │ sync_outbox (queue) │◄┼────────────┤ 4. Update Meta Store │
|
|
34
|
-
│ ├─────────────────────┤ │ └──────────┬───────────┘
|
|
35
|
-
│ │ sync_meta (state) │ │ │
|
|
36
|
-
│ └─────────────────────┘ │ │
|
|
37
|
-
└─────────────────────────┘ ▼
|
|
38
|
-
┌──────────────────────┐
|
|
39
|
-
│ Remote Adapter │
|
|
40
|
-
│ (Supabase / Convex) │
|
|
41
|
-
└──────────────────────┘
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
## 1. Atomic Dual-Write (The Transactional Outbox)
|
|
47
|
-
|
|
48
|
-
In standard apps, if an API call fails after a state update, or if the user closes the app mid-flight, local state and remote state become desynchronized.
|
|
49
|
-
|
|
50
|
-
`local-lite` solves this by executing a single SQLite atomic transaction whenever `client.mutate()` is called:
|
|
51
|
-
1. **User Table Update:** Writes the record to the table (e.g. `INSERT INTO todos ...`).
|
|
52
|
-
2. **Outbox Entry:** Simultaneously appends a log to the internal `sync_outbox` table:
|
|
53
|
-
- `id`: Unique mutation UUID
|
|
54
|
-
- `tableName`: Table modified
|
|
55
|
-
- `rowId`: Primary key affected
|
|
56
|
-
- `operation`: `'INSERT'`, `'UPDATE'`, or `'DELETE'`
|
|
57
|
-
- `payload`: JSON data
|
|
58
|
-
- `timestamp`: Mutation timestamp
|
|
59
|
-
|
|
60
|
-
Because both operations occur inside the same SQLite transaction:
|
|
61
|
-
- If the app crashes or the battery dies, both commit or both roll back together.
|
|
62
|
-
- Pending mutations remain safely in SQLite until successfully acknowledged by the server.
|
|
63
|
-
|
|
64
|
-
---
|
|
65
|
-
|
|
66
|
-
## 2. The SyncWorker Pipeline
|
|
67
|
-
|
|
68
|
-
The `SyncWorker` is a background coordination engine that executes two main loops:
|
|
69
|
-
|
|
70
|
-
### Push Loop
|
|
71
|
-
1. Reads pending records from `sync_outbox` sorted by timestamp.
|
|
72
|
-
2. Formats mutations into a batch.
|
|
73
|
-
3. Invokes `remoteAdapter.pushChanges(batch)`.
|
|
74
|
-
4. Upon successful server acknowledgment, deletes the processed records from `sync_outbox`.
|
|
75
|
-
5. If the server fails or returns a network error, applies exponential backoff and leaves the outbox untouched.
|
|
76
|
-
|
|
77
|
-
### Pull Loop
|
|
78
|
-
1. Reads the latest sync watermark timestamp from the internal `sync_meta` table.
|
|
79
|
-
2. Calls `remoteAdapter.fetchChanges(tables, sinceTimestamp)`.
|
|
80
|
-
3. For each delta received from the server:
|
|
81
|
-
- Evaluates the configured **ConflictResolver**.
|
|
82
|
-
- If the server change wins, writes the delta into local SQLite.
|
|
83
|
-
4. Updates the high-watermark timestamp in `sync_meta`.
|
|
84
|
-
5. Emits table change events to re-render any active `useLiveQuery()` components.
|
|
85
|
-
|
|
86
|
-
---
|
|
87
|
-
|
|
88
|
-
## 3. Infinite-Loop Prevention
|
|
89
|
-
|
|
90
|
-
A common bug in bidirectional sync engines is "mutation echo":
|
|
91
|
-
`Remote pull -> Writes to local DB -> Outbox mistakenly thinks user created a new record -> Pushes back to remote`.
|
|
92
|
-
|
|
93
|
-
`local-lite` avoids this entirely:
|
|
94
|
-
- **Direct internal writes:** When `SyncWorker` applies incoming deltas, it bypasses the `client.mutate()` outbox pathway and executes direct SQLite SQL updates.
|
|
95
|
-
- **Event firing:** It triggers `events.emit('change:tableName')` so your UI updates reactively, without appending any records to `sync_outbox`.
|
|
96
|
-
|
|
97
|
-
---
|
|
98
|
-
|
|
99
|
-
## 4. Offline Resilience & Network Awareness
|
|
100
|
-
|
|
101
|
-
- `local-lite` ships with a network listener (`DefaultNetworkStatusProvider` or `@react-native-community/netinfo`).
|
|
102
|
-
- When offline:
|
|
103
|
-
- Local queries and mutations execute with **0ms latency**.
|
|
104
|
-
- Periodic network calls are paused to conserve battery and CPU.
|
|
105
|
-
- When connectivity restores:
|
|
106
|
-
- The network listener detects the change and triggers an **immediate outbox flush**.
|