local-lite 0.0.29 → 0.1.0
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 +25 -20
- package/dist/adapters/remote/convex.d.ts +7 -2
- package/dist/adapters/remote/convex.js +73 -40
- package/dist/adapters/remote/firestore.d.ts +2 -1
- package/dist/adapters/remote/firestore.js +21 -3
- package/dist/adapters/remote/index.d.ts +3 -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 +7 -3
- package/dist/core/client.js +14 -11
- package/dist/core/meta-store.d.ts +3 -3
- package/dist/core/meta-store.js +6 -6
- package/dist/core/outbox-store.d.ts +9 -0
- package/dist/core/outbox-store.js +31 -0
- package/dist/core/sync-worker.d.ts +6 -0
- package/dist/core/sync-worker.js +68 -25
- 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 +3 -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
package/docs/kv.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Fast Key-Value & Encrypted Preferences (`client.kv`)
|
|
2
|
+
|
|
3
|
+
`local-lite` includes a built-in, lightning-fast key-value store directly inside your SQLite database (`_local_kv`), providing zero-overhead storage for application state, user preferences, offline session flags, and zero-knowledge encrypted secrets.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Typed Storage**: Transparently handles strings, numbers, booleans, and JSON objects.
|
|
10
|
+
- **TTL Support**: Built-in TTL expiration (e.g., tokens expiring in 15 minutes, caches expiring in 24 hours).
|
|
11
|
+
- **Lazy & Immediate Cleanup**: Expired keys return `undefined` on access and are automatically purged via `client.kv.pruneExpired()`.
|
|
12
|
+
- **Zero-Knowledge Encrypted Preferences**: Store sensitive tokens, API credentials, and personal encryption keys using military-grade **AES-256-GCM** + **PBKDF2** encryption.
|
|
13
|
+
- **Cross-Platform**: Works everywhere without native dependencies on Web, Expo/React Native, and Node.js.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Basic Usage
|
|
18
|
+
|
|
19
|
+
Access the store directly from your `LocalFirstClient` instance:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
// Strings
|
|
23
|
+
await client.kv.set('theme', 'dark');
|
|
24
|
+
const theme = await client.kv.get('theme'); // 'dark'
|
|
25
|
+
|
|
26
|
+
// Numbers & Booleans
|
|
27
|
+
await client.kv.set('retryCount', 3);
|
|
28
|
+
await client.kv.set('offlineMode', true);
|
|
29
|
+
|
|
30
|
+
// JSON Objects
|
|
31
|
+
await client.kv.set('userPreferences', {
|
|
32
|
+
language: 'en-US',
|
|
33
|
+
currency: 'USD',
|
|
34
|
+
notifications: true,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const prefs = await client.kv.get('userPreferences');
|
|
38
|
+
console.log(prefs.currency); // 'USD'
|
|
39
|
+
|
|
40
|
+
// Check existence
|
|
41
|
+
const hasTheme = await client.kv.has('theme'); // true
|
|
42
|
+
|
|
43
|
+
// Delete key
|
|
44
|
+
await client.kv.delete('theme');
|
|
45
|
+
|
|
46
|
+
// List keys
|
|
47
|
+
const allKeys = await client.kv.keys();
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## TTL & Expiration
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// Expire in 10 minutes (600,000 ms)
|
|
56
|
+
await client.kv.set('tempSessionToken', 'session_123', {
|
|
57
|
+
ttlMs: 10 * 60 * 1000,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// Or set an absolute timestamp
|
|
61
|
+
await client.kv.set('flashPromo', { discount: 20 }, {
|
|
62
|
+
expiresAt: Date.now() + 3600000,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// Prune expired entries
|
|
66
|
+
await client.kv.pruneExpired();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Encrypted Preferences (AES-256-GCM)
|
|
72
|
+
|
|
73
|
+
Protect sensitive secrets, OAuth refresh tokens, and payment API keys at rest on the client:
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
const userPassphrase = 'user-provided-secure-passphrase';
|
|
77
|
+
|
|
78
|
+
// Store encrypted secret
|
|
79
|
+
await client.kv.setSecret('stripe_config', {
|
|
80
|
+
secretKey: 'sk_live_123456789',
|
|
81
|
+
webhookSecret: 'whsec_abcdef',
|
|
82
|
+
}, {
|
|
83
|
+
passphrase: userPassphrase,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// Decrypt secret
|
|
87
|
+
const stripeConfig = await client.kv.getSecret('stripe_config', userPassphrase);
|
|
88
|
+
console.log(stripeConfig.secretKey); // 'sk_live_123456789'
|
|
89
|
+
```
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# 🧹 Database Maintenance & Universal Data Portability
|
|
2
|
+
|
|
3
|
+
Keep your local SQLite database lean, responsive, and easily exportable.
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
import {
|
|
7
|
+
exportTablesToJson,
|
|
8
|
+
importTablesFromJson,
|
|
9
|
+
exportTableToCsv,
|
|
10
|
+
importTableFromCsv,
|
|
11
|
+
} from 'local-lite';
|
|
12
|
+
|
|
13
|
+
import { useDatabaseMaintenance } from 'local-lite/react';
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 🧹 1. Database Maintenance (`client.maintenance`)
|
|
19
|
+
|
|
20
|
+
`LocalFirstClient` includes a dedicated `DatabaseMaintenance` instance:
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
// 1. Get complete storage metrics breakdown
|
|
24
|
+
const stats = await client.maintenance.getStorageStats();
|
|
25
|
+
console.log('Database size on disk:', stats.databaseSizeBytes, 'bytes');
|
|
26
|
+
console.log('Table rows:', stats.tables);
|
|
27
|
+
console.log('Outbox queue status:', stats.outbox);
|
|
28
|
+
|
|
29
|
+
// 2. Prune old or completed sync outbox records
|
|
30
|
+
const pruned = await client.maintenance.pruneOutbox({
|
|
31
|
+
retentionDays: 14, // Delete records older than 14 days
|
|
32
|
+
maxEntries: 1000, // Keep at most 1,000 completed/failed records
|
|
33
|
+
statuses: ['COMPLETED', 'FAILED'],
|
|
34
|
+
});
|
|
35
|
+
console.log(`Pruned ${pruned} outbox records`);
|
|
36
|
+
|
|
37
|
+
// 3. Defragment database and reclaim unused pages
|
|
38
|
+
await client.maintenance.vacuum();
|
|
39
|
+
|
|
40
|
+
// 4. Force WAL log checkpointing back into database file
|
|
41
|
+
// Modes: 'PASSIVE' | 'FULL' | 'RESTART' | 'TRUNCATE'
|
|
42
|
+
await client.maintenance.checkpoint('TRUNCATE');
|
|
43
|
+
|
|
44
|
+
// 5. Query planner optimization (PRAGMA optimize / analyze)
|
|
45
|
+
await client.maintenance.analyze();
|
|
46
|
+
|
|
47
|
+
// 6. SQLite structural integrity check (PRAGMA integrity_check)
|
|
48
|
+
const isHealthy = await client.maintenance.integrityCheck();
|
|
49
|
+
console.log('Database health:', isHealthy ? 'OK' : 'Corrupted');
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## ⚛️ 2. React Maintenance Hook (`useDatabaseMaintenance`)
|
|
55
|
+
|
|
56
|
+
Manage database health directly from your settings screen:
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
import React from 'react';
|
|
60
|
+
import { View, Text, Button } from 'react-native';
|
|
61
|
+
import { useDatabaseMaintenance } from 'local-lite/react';
|
|
62
|
+
|
|
63
|
+
export function StorageSettings({ client }) {
|
|
64
|
+
const {
|
|
65
|
+
stats,
|
|
66
|
+
loading,
|
|
67
|
+
refreshStats,
|
|
68
|
+
pruneOutbox,
|
|
69
|
+
vacuum,
|
|
70
|
+
checkpoint,
|
|
71
|
+
} = useDatabaseMaintenance(client);
|
|
72
|
+
|
|
73
|
+
return (
|
|
74
|
+
<View style={{ padding: 16 }}>
|
|
75
|
+
<Text style={{ fontSize: 18, fontWeight: 'bold' }}>Database Storage</Text>
|
|
76
|
+
<Text>Database Size: {stats?.databaseSizeBytes ? `${(stats.databaseSizeBytes / 1024).toFixed(1)} KB` : '...'}</Text>
|
|
77
|
+
<Text>Pending Mutations: {stats?.outbox.pending ?? 0}</Text>
|
|
78
|
+
<Text>Completed History: {stats?.outbox.completed ?? 0}</Text>
|
|
79
|
+
|
|
80
|
+
<Button
|
|
81
|
+
title="Prune Old Outbox Records"
|
|
82
|
+
onPress={() => pruneOutbox({ retentionDays: 7 })}
|
|
83
|
+
/>
|
|
84
|
+
<Button
|
|
85
|
+
title="Reclaim Free Disk Space (VACUUM)"
|
|
86
|
+
onPress={vacuum}
|
|
87
|
+
/>
|
|
88
|
+
<Button
|
|
89
|
+
title="Checkpoint WAL File"
|
|
90
|
+
onPress={() => checkpoint('TRUNCATE')}
|
|
91
|
+
/>
|
|
92
|
+
</View>
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## 📤 3. Universal Data Portability (JSON & CSV)
|
|
100
|
+
|
|
101
|
+
Allow users to export and import their data at any time for GDPR compliance, account switching, local backups, or spreadsheet analysis.
|
|
102
|
+
|
|
103
|
+
### JSON Export & Import:
|
|
104
|
+
```typescript
|
|
105
|
+
// Export specific tables (or all managed tables) to JSON string
|
|
106
|
+
const jsonString = await client.exportToJson(['milestones', 'vaccines'], {
|
|
107
|
+
pretty: true,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// Import tables from JSON string
|
|
111
|
+
const summary = await client.importFromJson(jsonString, {
|
|
112
|
+
mode: 'merge', // 'merge' (updates existing rows by ID & inserts new) or 'replace' (deletes all existing rows first)
|
|
113
|
+
skipOutbox: true, // When true, does not re-queue restored rows to the sync outbox
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
console.log('Import summary:', summary.tables, summary.rowCounts);
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### RFC-4180 CSV Export & Import:
|
|
120
|
+
```typescript
|
|
121
|
+
// Export a single table to CSV
|
|
122
|
+
const csvData = await client.exportToCsv('vaccines', {
|
|
123
|
+
delimiter: ',',
|
|
124
|
+
includeHeaders: true,
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// Import CSV data with auto-detection of numbers, booleans, and JSON structures
|
|
128
|
+
const { rowCount } = await client.importFromCsv('vaccines', csvData, {
|
|
129
|
+
mode: 'merge', // 'merge' or 'replace'
|
|
130
|
+
skipOutbox: true,
|
|
131
|
+
});
|
|
132
|
+
console.log(`Successfully imported ${rowCount} rows`);
|
|
133
|
+
```
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
# ⚛️ React & Expo Hooks
|
|
2
|
+
|
|
3
|
+
`local-lite` provides first-class reactive hooks and UI developer tools for React, React Native, and Expo applications via `local-lite/react`.
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
import {
|
|
7
|
+
useLiveQuery,
|
|
8
|
+
useLiveQueries,
|
|
9
|
+
useLiveRow,
|
|
10
|
+
useLiveInfiniteQuery,
|
|
11
|
+
useMutations,
|
|
12
|
+
useSyncStatus,
|
|
13
|
+
useDatabaseMaintenance,
|
|
14
|
+
useGoogleAuth,
|
|
15
|
+
useMicrosoftAuth,
|
|
16
|
+
useOneDriveAuth,
|
|
17
|
+
useGitHubAuth,
|
|
18
|
+
useAppleAuth,
|
|
19
|
+
useCloudBackup,
|
|
20
|
+
useGoogleDriveBackup,
|
|
21
|
+
useOneDriveBackup,
|
|
22
|
+
} from 'local-lite/react';
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 1. `useLiveQuery`
|
|
28
|
+
|
|
29
|
+
`useLiveQuery` executes a reactive SQLite query against your local database. It automatically re-runs and re-renders your component whenever the table is modified locally or via incoming remote delta. It uses an in-memory LRU read-through cache to deliver **0ms mount latency with zero UI flicker**.
|
|
30
|
+
|
|
31
|
+
### Signature:
|
|
32
|
+
```typescript
|
|
33
|
+
function useLiveQuery<T = any>(
|
|
34
|
+
client: LocalFirstClient | null | undefined,
|
|
35
|
+
tableName: string,
|
|
36
|
+
queryOrOptions?: QueryOptions | ((client: LocalFirstClient) => Promise<T[]> | T[])
|
|
37
|
+
): {
|
|
38
|
+
data: T[];
|
|
39
|
+
loading: boolean;
|
|
40
|
+
refetch: () => Promise<void>;
|
|
41
|
+
};
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Usage Examples:
|
|
45
|
+
|
|
46
|
+
```tsx
|
|
47
|
+
import { useLiveQuery } from 'local-lite/react';
|
|
48
|
+
|
|
49
|
+
export function TodoList({ client }) {
|
|
50
|
+
// 1. Declarative filtering and sorting without SQL
|
|
51
|
+
const { data: todos, loading } = useLiveQuery(client, 'todos', {
|
|
52
|
+
where: { completed: 0, priority: { $gte: 2 } },
|
|
53
|
+
orderBy: 'updatedAt',
|
|
54
|
+
order: 'desc',
|
|
55
|
+
limit: 50,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
if (loading) return <Text>Loading...</Text>;
|
|
59
|
+
|
|
60
|
+
return (
|
|
61
|
+
<FlatList
|
|
62
|
+
data={todos}
|
|
63
|
+
keyExtractor={(item) => item.id}
|
|
64
|
+
renderItem={({ item }) => <Text>{item.title}</Text>}
|
|
65
|
+
/>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```tsx
|
|
71
|
+
// 2. Custom SQL Query with joins or aggregations
|
|
72
|
+
const { data: stats } = useLiveQuery(client, 'todos', async (c) => {
|
|
73
|
+
return await c.query(`
|
|
74
|
+
SELECT
|
|
75
|
+
categories.name AS category,
|
|
76
|
+
COUNT(todos.id) AS total_count
|
|
77
|
+
FROM categories
|
|
78
|
+
LEFT JOIN todos ON todos.category_id = categories.id
|
|
79
|
+
GROUP BY categories.id
|
|
80
|
+
`);
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 2. `useLiveQueries` (Multi-Table Live Queries)
|
|
87
|
+
|
|
88
|
+
When a screen requires data from multiple tables (e.g. projects, tasks, and users), calling multiple individual hooks causes cascading re-renders and UI stutter.
|
|
89
|
+
|
|
90
|
+
`useLiveQueries` solves this by:
|
|
91
|
+
* Fetching all tables concurrently with `Promise.all`.
|
|
92
|
+
* Committing results in a **single atomic React state update**.
|
|
93
|
+
* Coalescing multi-table change events so dependent computations execute only once.
|
|
94
|
+
|
|
95
|
+
### Signature:
|
|
96
|
+
```typescript
|
|
97
|
+
function useLiveQueries<T extends Record<string, any[]> = Record<string, any[]>>(
|
|
98
|
+
client: LocalFirstClient | null | undefined,
|
|
99
|
+
queries:
|
|
100
|
+
| Array<string | (QueryOptions & { table: string })>
|
|
101
|
+
| Record<string, string | (QueryOptions & { table?: string }) | LiveQueryFn<any>>
|
|
102
|
+
): {
|
|
103
|
+
data: T;
|
|
104
|
+
loading: boolean;
|
|
105
|
+
refetch: () => Promise<void>;
|
|
106
|
+
};
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Usage Example:
|
|
110
|
+
```tsx
|
|
111
|
+
import { useLiveQueries } from 'local-lite/react';
|
|
112
|
+
|
|
113
|
+
export function DashboardScreen({ client }) {
|
|
114
|
+
const { data, loading } = useLiveQueries(client, {
|
|
115
|
+
projects: 'projects',
|
|
116
|
+
activeTasks: {
|
|
117
|
+
table: 'tasks',
|
|
118
|
+
where: { completed: 0 },
|
|
119
|
+
orderBy: 'created_at',
|
|
120
|
+
order: 'desc',
|
|
121
|
+
},
|
|
122
|
+
members: 'team_members',
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
if (loading) return <ActivityIndicator />;
|
|
126
|
+
|
|
127
|
+
return (
|
|
128
|
+
<View>
|
|
129
|
+
<Text>Active Projects: {data.projects.length}</Text>
|
|
130
|
+
<Text>Pending Tasks: {data.activeTasks.length}</Text>
|
|
131
|
+
<Text>Team Members: {data.members.length}</Text>
|
|
132
|
+
</View>
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## 3. `useLiveRow` (Targeted Single-Row Live Query)
|
|
140
|
+
|
|
141
|
+
Queries a single row by primary key with **row-level invalidation**. Unlike table-level queries that re-render whenever *any* row in the table changes, `useLiveRow` only triggers re-renders when mutations affect this specific `rowId`.
|
|
142
|
+
|
|
143
|
+
### Signature:
|
|
144
|
+
```typescript
|
|
145
|
+
function useLiveRow<T = any>(
|
|
146
|
+
client: LocalFirstClient | null | undefined,
|
|
147
|
+
tableName: string,
|
|
148
|
+
rowId: string | null | undefined,
|
|
149
|
+
options?: { includeDeleted?: boolean }
|
|
150
|
+
): {
|
|
151
|
+
data: T | null;
|
|
152
|
+
loading: boolean;
|
|
153
|
+
refetch: () => Promise<void>;
|
|
154
|
+
};
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Usage Example:
|
|
158
|
+
```tsx
|
|
159
|
+
import { useLiveRow } from 'local-lite/react';
|
|
160
|
+
|
|
161
|
+
export function TodoItemDetails({ client, todoId }) {
|
|
162
|
+
const { data: todo, loading } = useLiveRow(client, 'todos', todoId);
|
|
163
|
+
|
|
164
|
+
if (loading) return <Text>Loading...</Text>;
|
|
165
|
+
if (!todo) return <Text>Item not found</Text>;
|
|
166
|
+
|
|
167
|
+
return (
|
|
168
|
+
<View>
|
|
169
|
+
<Text style={{ fontWeight: 'bold' }}>{todo.title}</Text>
|
|
170
|
+
<Text>Status: {todo.completed ? 'Done' : 'Pending'}</Text>
|
|
171
|
+
</View>
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## 4. `useLiveInfiniteQuery` (Paginated Infinite Scrolling)
|
|
179
|
+
|
|
180
|
+
Progressively loads pages of records with automatic live updates when underlying items are inserted, edited, or deleted.
|
|
181
|
+
|
|
182
|
+
### Signature:
|
|
183
|
+
```typescript
|
|
184
|
+
function useLiveInfiniteQuery<T = any>(
|
|
185
|
+
client: LocalFirstClient | null | undefined,
|
|
186
|
+
tableName: string,
|
|
187
|
+
options?: InfiniteQueryOptions // { pageSize?: number; where?: WhereFilter; orderBy?: string; order?: 'asc' | 'desc' }
|
|
188
|
+
): {
|
|
189
|
+
data: T[];
|
|
190
|
+
loading: boolean;
|
|
191
|
+
isFetchingNextPage: boolean;
|
|
192
|
+
hasNextPage: boolean;
|
|
193
|
+
fetchNextPage: () => Promise<void>;
|
|
194
|
+
refetch: () => Promise<void>;
|
|
195
|
+
};
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### Usage Example:
|
|
199
|
+
```tsx
|
|
200
|
+
import { useLiveInfiniteQuery } from 'local-lite/react';
|
|
201
|
+
|
|
202
|
+
export function InfiniteFeed({ client }) {
|
|
203
|
+
const {
|
|
204
|
+
data: items,
|
|
205
|
+
loading,
|
|
206
|
+
hasNextPage,
|
|
207
|
+
isFetchingNextPage,
|
|
208
|
+
fetchNextPage,
|
|
209
|
+
} = useLiveInfiniteQuery(client, 'feed_items', {
|
|
210
|
+
pageSize: 20,
|
|
211
|
+
orderBy: 'created_at',
|
|
212
|
+
order: 'desc',
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
return (
|
|
216
|
+
<FlatList
|
|
217
|
+
data={items}
|
|
218
|
+
keyExtractor={(item) => item.id}
|
|
219
|
+
renderItem={({ item }) => <Text>{item.text}</Text>}
|
|
220
|
+
onEndReached={() => {
|
|
221
|
+
if (hasNextPage && !isFetchingNextPage) fetchNextPage();
|
|
222
|
+
}}
|
|
223
|
+
onEndReachedThreshold={0.5}
|
|
224
|
+
ListFooterComponent={isFetchingNextPage ? <ActivityIndicator /> : null}
|
|
225
|
+
/>
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## 5. `useMutations` (Universal Mutation Helpers)
|
|
233
|
+
|
|
234
|
+
Provides memoized, null-safe helper methods for performing database operations without checking `if (!client)` manually.
|
|
235
|
+
|
|
236
|
+
### Signature:
|
|
237
|
+
```typescript
|
|
238
|
+
const {
|
|
239
|
+
insert,
|
|
240
|
+
insertMany,
|
|
241
|
+
update,
|
|
242
|
+
updateMany,
|
|
243
|
+
delete: remove,
|
|
244
|
+
batch,
|
|
245
|
+
transaction,
|
|
246
|
+
} = useMutations(client);
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
### Usage Example:
|
|
250
|
+
```tsx
|
|
251
|
+
import { useMutations } from 'local-lite/react';
|
|
252
|
+
|
|
253
|
+
export function TaskEditor({ client }) {
|
|
254
|
+
const mutations = useMutations(client);
|
|
255
|
+
|
|
256
|
+
const handleCreate = async () => {
|
|
257
|
+
const id = await mutations.insert('tasks', {
|
|
258
|
+
title: 'New Task',
|
|
259
|
+
completed: 0,
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const handleToggle = async (id: string, current: number) => {
|
|
264
|
+
await mutations.update('tasks', id, { completed: current ? 0 : 1 });
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const handleBatchArchive = async (ids: string[]) => {
|
|
268
|
+
await mutations.updateMany(
|
|
269
|
+
'tasks',
|
|
270
|
+
ids.map((id) => ({ id, payload: { archived: 1 } }))
|
|
271
|
+
);
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
return (
|
|
275
|
+
<Button title="Create Task" onPress={handleCreate} />
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## 6. `useSyncStatus`
|
|
283
|
+
|
|
284
|
+
Inspects real-time sync worker activity, network connectivity, and pending outbox mutations.
|
|
285
|
+
|
|
286
|
+
### Signature:
|
|
287
|
+
```typescript
|
|
288
|
+
function useSyncStatus(client: LocalFirstClient | null | undefined): {
|
|
289
|
+
isOnline: boolean; // True when internet connectivity is active
|
|
290
|
+
isSyncing: boolean; // True while actively pushing or pulling
|
|
291
|
+
isPushing: boolean; // True while pushing local mutations to remote
|
|
292
|
+
isPulling: boolean; // True while pulling remote deltas
|
|
293
|
+
pendingCount: number; // Number of mutations queued in local SQLite outbox
|
|
294
|
+
pendingRecords: any[]; // Array of pending outbox queue records
|
|
295
|
+
lastSyncedAt: number | null; // Timestamp of last successful sync
|
|
296
|
+
refresh: () => Promise<void>;
|
|
297
|
+
};
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### Usage Example:
|
|
301
|
+
```tsx
|
|
302
|
+
import { useSyncStatus } from 'local-lite/react';
|
|
303
|
+
|
|
304
|
+
export function SyncBadge({ client }) {
|
|
305
|
+
const { isOnline, isSyncing, pendingCount, lastSyncedAt } = useSyncStatus(client);
|
|
306
|
+
|
|
307
|
+
if (!isOnline) {
|
|
308
|
+
return <Text style={{ color: '#ef4444' }}>📶 Offline (Changes saved locally)</Text>;
|
|
309
|
+
}
|
|
310
|
+
if (isSyncing) {
|
|
311
|
+
return <Text style={{ color: '#0284c7' }}>🔄 Syncing with cloud...</Text>;
|
|
312
|
+
}
|
|
313
|
+
if (pendingCount > 0) {
|
|
314
|
+
return <Text style={{ color: '#f59e0b' }}>⏳ {pendingCount} change(s) pending</Text>;
|
|
315
|
+
}
|
|
316
|
+
return (
|
|
317
|
+
<Text style={{ color: '#10b981' }}>
|
|
318
|
+
✅ Synced {lastSyncedAt ? new Date(lastSyncedAt).toLocaleTimeString() : ''}
|
|
319
|
+
</Text>
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
---
|
|
325
|
+
|
|
326
|
+
## 7. `useDatabaseMaintenance`
|
|
327
|
+
|
|
328
|
+
Provides reactive controls to monitor database disk usage, prune outbox logs, vacuum defragmentation, and force WAL checkpoints.
|
|
329
|
+
|
|
330
|
+
```tsx
|
|
331
|
+
import { useDatabaseMaintenance } from 'local-lite/react';
|
|
332
|
+
|
|
333
|
+
export function MaintenanceScreen({ client }) {
|
|
334
|
+
const {
|
|
335
|
+
stats,
|
|
336
|
+
loading,
|
|
337
|
+
refreshStats,
|
|
338
|
+
pruneOutbox,
|
|
339
|
+
vacuum,
|
|
340
|
+
checkpoint,
|
|
341
|
+
} = useDatabaseMaintenance(client);
|
|
342
|
+
|
|
343
|
+
return (
|
|
344
|
+
<View>
|
|
345
|
+
<Text>Database Size: {stats?.databaseSizeBytes ?? 0} bytes</Text>
|
|
346
|
+
<Text>Pending Outbox: {stats?.outbox.pending ?? 0}</Text>
|
|
347
|
+
<Button title="Prune Outbox (>14 days)" onPress={() => pruneOutbox({ retentionDays: 14 })} />
|
|
348
|
+
<Button title="Defragment (VACUUM)" onPress={vacuum} />
|
|
349
|
+
<Button title="Truncate WAL" onPress={() => checkpoint('TRUNCATE')} />
|
|
350
|
+
</View>
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
## 8. Authentication Hooks
|
|
358
|
+
|
|
359
|
+
* `useGoogleAuth(googleAuthClient)`
|
|
360
|
+
* `useMicrosoftAuth(oneDriveAuthClient)`
|
|
361
|
+
* `useOneDriveAuth(oneDriveAuthClient)`
|
|
362
|
+
* `useGitHubAuth(gitHubAuthClient)`
|
|
363
|
+
* `useAppleAuth(appleAuthClient)`
|
|
364
|
+
|
|
365
|
+
Each hook returns `{ user, isSignedIn, loading, error, signIn, signOut }`. See **[Authentication](auth.md)** for complete details.
|
|
366
|
+
|
|
367
|
+
---
|
|
368
|
+
|
|
369
|
+
## 9. Cloud Backup Hooks
|
|
370
|
+
|
|
371
|
+
* `useCloudBackup(backupClient, database, options)`
|
|
372
|
+
* `useGoogleDriveBackup(googleDriveClient, database, options)`
|
|
373
|
+
* `useOneDriveBackup(oneDriveClient, database, options)`
|
|
374
|
+
|
|
375
|
+
Provides complete cloud backup lifecycle in React:
|
|
376
|
+
|
|
377
|
+
```tsx
|
|
378
|
+
import { useGoogleDriveBackup } from 'local-lite/react';
|
|
379
|
+
import { googleDriveBackup } from './backup-client';
|
|
380
|
+
|
|
381
|
+
export function BackupManager({ client }) {
|
|
382
|
+
const {
|
|
383
|
+
isConnected,
|
|
384
|
+
isLoading,
|
|
385
|
+
isBackingUp,
|
|
386
|
+
isRestoring,
|
|
387
|
+
backups,
|
|
388
|
+
backup,
|
|
389
|
+
restore,
|
|
390
|
+
deleteBackup,
|
|
391
|
+
} = useGoogleDriveBackup(googleDriveBackup, client, {
|
|
392
|
+
passphrase: 'user-secret-passphrase', // Optional zero-knowledge encryption
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
return (
|
|
396
|
+
<View>
|
|
397
|
+
<Button
|
|
398
|
+
title={isBackingUp ? 'Backing up...' : 'Backup to Google Drive'}
|
|
399
|
+
disabled={isBackingUp}
|
|
400
|
+
onPress={() => backup()}
|
|
401
|
+
/>
|
|
402
|
+
{backups.map((b) => (
|
|
403
|
+
<View key={b.id}>
|
|
404
|
+
<Text>{b.name} ({new Date(b.createdAt).toLocaleDateString()})</Text>
|
|
405
|
+
<Button title="Restore" onPress={() => restore(b.name)} />
|
|
406
|
+
<Button title="Delete" onPress={() => deleteBackup(b.id)} />
|
|
407
|
+
</View>
|
|
408
|
+
))}
|
|
409
|
+
</View>
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
---
|
|
415
|
+
|
|
416
|
+
## 10. Developer Tools & Components
|
|
417
|
+
|
|
418
|
+
`local-lite/devtools` includes ready-to-use developer UI components for testing, monitoring, and stress testing your sync engine. They live in their own entry point so production bundles that only import `local-lite/react` never include them.
|
|
419
|
+
|
|
420
|
+
### `<SyncInspector />`
|
|
421
|
+
A floating or inline developer widget displaying real-time outbox queues, active sync status, connection indicators, push/pull controls, theme toggling, and benchmark runner.
|
|
422
|
+
|
|
423
|
+
```tsx
|
|
424
|
+
import { SyncInspector } from 'local-lite/devtools';
|
|
425
|
+
import { client } from './sync.config';
|
|
426
|
+
|
|
427
|
+
export default function App() {
|
|
428
|
+
return (
|
|
429
|
+
<View style={{ flex: 1 }}>
|
|
430
|
+
<YourAppContent />
|
|
431
|
+
|
|
432
|
+
{/* Developer Sync Inspector */}
|
|
433
|
+
{__DEV__ && (
|
|
434
|
+
<SyncInspector
|
|
435
|
+
client={client}
|
|
436
|
+
position="bottom-right"
|
|
437
|
+
variant="pill" // 'pill' | 'compact' | 'icon' | 'minimal'
|
|
438
|
+
theme="auto" // 'auto' | 'dark' | 'light'
|
|
439
|
+
enableBenchmark={true}
|
|
440
|
+
/>
|
|
441
|
+
)}
|
|
442
|
+
</View>
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
### `<BenchmarkModal />`
|
|
448
|
+
An automated in-app stress test runner measuring:
|
|
449
|
+
* Atomic batch ingestion throughput (records/sec)
|
|
450
|
+
* SQLite indexing & query responsiveness
|
|
451
|
+
* ACID rollback isolation integrity
|
|
452
|
+
* Non-blocking WAL concurrency
|
|
453
|
+
* Outbox queue flushing performance
|
|
454
|
+
|
|
455
|
+
The workload scales by 1x per 1,000 app records, capped at 10x, and includes bounded samples of real app rows in its temporary benchmark payloads. Mutating benchmarks are isolated to temporary tables that are cleaned up when the run finishes.
|
|
456
|
+
|
|
457
|
+
It also runs read-only scans and `findById()` lookups against your three largest real tables (reported under the **App Data** category). These use a warm-up pass and the median of 5 timed runs, with sub-millisecond timing. Tables are discovered automatically, excluding internal ones; note that app tables whose names start with `sync_` are treated as internal and skipped.
|