local-lite 0.1.3 → 0.2.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 +9 -1
- package/dist/auth/apple.d.ts +3 -4
- package/dist/auth/apple.js +26 -3
- package/dist/auth/github.d.ts +3 -5
- package/dist/auth/github.js +18 -4
- package/dist/auth/google.d.ts +3 -6
- package/dist/auth/google.js +19 -5
- package/dist/auth/identity.d.ts +42 -0
- package/dist/auth/identity.js +63 -0
- package/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.js +2 -0
- package/dist/auth/microsoft.d.ts +3 -5
- package/dist/auth/microsoft.js +16 -3
- package/dist/auth/session.d.ts +4 -0
- package/dist/auth/session.js +19 -1
- package/dist/auth/unified.d.ts +73 -0
- package/dist/auth/unified.js +188 -0
- package/dist/utils/dynamic.js +0 -3
- package/package.json +1 -1
- package/skills/local-lite-auth/SKILL.md +189 -0
- package/skills/local-lite-backups/SKILL.md +164 -0
- package/skills/local-lite-offline-actions/SKILL.md +122 -0
- package/skills/local-lite-react/SKILL.md +124 -0
- package/skills/local-lite-schema/SKILL.md +171 -0
- package/skills/local-lite-setup/SKILL.md +203 -21
- package/skills/local-lite-storage/SKILL.md +116 -0
- package/skills/local-lite-upgrade/SKILL.md +45 -16
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-react
|
|
3
|
+
description: Master reactive patterns, hooks, live queries, and optimistic state in React and React Native with local-lite. Use when writing useLiveQuery, useSyncStatus, useLocalAuth, useKV, useSearch, useQueryBuilder, or optimizing component re-renders.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite React & React Native Integration
|
|
7
|
+
|
|
8
|
+
Comprehensive guide to building reactive, offline-first user interfaces using `local-lite/react`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Core Hooks Overview
|
|
13
|
+
|
|
14
|
+
| Hook | Purpose |
|
|
15
|
+
| :--- | :--- |
|
|
16
|
+
| `useLiveQuery(client, sql, params, deps)` | Reactive SQLite query. Auto-re-runs whenever relevant tables mutate. |
|
|
17
|
+
| `useSyncStatus(client)` | Tracks online/offline status, sync worker state, and outbox changes. |
|
|
18
|
+
| `useLocalAuth(client.auth)` | Manages zero-backend SQLite authentication, user profiles, and sessions. |
|
|
19
|
+
| `useKV(client.kv, key, default)` | Reactive key-value store for preferences and application state. |
|
|
20
|
+
| `useEncryptedKV(client.kv, key, pass)` | End-to-end encrypted secret preferences with AES-256-GCM. |
|
|
21
|
+
| `useSearch(client, ftsTable, query)` | Real-time full-text search powered by SQLite FTS5. |
|
|
22
|
+
| `useQueryBuilder(client, table, filter)` | Declarative MongoDB-style query filters. |
|
|
23
|
+
| `useCloudBackup(backupClient, db)` | Cloud backups (OneDrive / Google Drive) with live progress. |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. Live Queries (`useLiveQuery`)
|
|
28
|
+
|
|
29
|
+
`useLiveQuery` executes raw SQLite queries and re-runs them reactively when affected tables change:
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
import React, { useMemo } from 'react';
|
|
33
|
+
import { FlatList, Text, View } from 'react-native';
|
|
34
|
+
import { useLiveQuery } from 'local-lite/react';
|
|
35
|
+
import type { LocalFirstClient } from 'local-lite/config';
|
|
36
|
+
|
|
37
|
+
interface Todo {
|
|
38
|
+
id: string;
|
|
39
|
+
title: string;
|
|
40
|
+
completed: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function TodoList({ client, projectId }: { client: LocalFirstClient; projectId: string }) {
|
|
44
|
+
// Always memoize params to prevent unnecessary query executions
|
|
45
|
+
const params = useMemo(() => [projectId], [projectId]);
|
|
46
|
+
|
|
47
|
+
const { data: todos, loading, error, refetch } = useLiveQuery<Todo>(
|
|
48
|
+
client,
|
|
49
|
+
'SELECT * FROM todos WHERE project_id = ? ORDER BY updated_at DESC;',
|
|
50
|
+
params
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
if (loading) return <Text>Loading...</Text>;
|
|
54
|
+
if (error) return <Text>Query error: {error.message}</Text>;
|
|
55
|
+
|
|
56
|
+
return (
|
|
57
|
+
<FlatList
|
|
58
|
+
data={todos}
|
|
59
|
+
keyExtractor={(item) => item.id}
|
|
60
|
+
renderItem={({ item }) => (
|
|
61
|
+
<Text style={{ textDecorationLine: item.completed ? 'line-through' : 'none' }}>
|
|
62
|
+
{item.title}
|
|
63
|
+
</Text>
|
|
64
|
+
)}
|
|
65
|
+
/>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 3. Optimistic 0ms Writes (`client.mutate`)
|
|
73
|
+
|
|
74
|
+
For zero-latency user experiences, perform writes using `client.mutate()`. This writes directly to local SQLite in an atomic transaction and automatically triggers all matching `useLiveQuery` hooks across the UI:
|
|
75
|
+
|
|
76
|
+
```tsx
|
|
77
|
+
import { generateUUID } from 'local-lite';
|
|
78
|
+
|
|
79
|
+
async function addTodo(client: LocalFirstClient, title: string, projectId: string) {
|
|
80
|
+
const newTodo = {
|
|
81
|
+
id: generateUUID(),
|
|
82
|
+
project_id: projectId,
|
|
83
|
+
title,
|
|
84
|
+
completed: 0,
|
|
85
|
+
updated_at: Date.now(),
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// 1. Dual-writes to local SQLite and queues in outbox for sync
|
|
89
|
+
await client.mutate('todos', 'INSERT', newTodo);
|
|
90
|
+
// All useLiveQuery hooks listening to 'todos' update instantly (0ms)!
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## 4. Reactive Preferences & Encrypted KV
|
|
97
|
+
|
|
98
|
+
```tsx
|
|
99
|
+
import { useKV, useEncryptedKV } from 'local-lite/react';
|
|
100
|
+
|
|
101
|
+
export function SettingsScreen({ client }) {
|
|
102
|
+
// 1. Plain reactive setting
|
|
103
|
+
const [theme, setTheme] = useKV<'light' | 'dark'>(client?.kv, 'app_theme', 'light');
|
|
104
|
+
|
|
105
|
+
// 2. Encrypted setting (AES-256-GCM)
|
|
106
|
+
const [apiKey, setApiKey] = useEncryptedKV(client?.kv, 'openai_key', 'UserPassphrase!');
|
|
107
|
+
|
|
108
|
+
return (
|
|
109
|
+
<View>
|
|
110
|
+
<Text>Theme: {theme}</Text>
|
|
111
|
+
<Button title="Toggle Theme" onPress={() => setTheme(theme === 'light' ? 'dark' : 'light')} />
|
|
112
|
+
</View>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## 5. Performance Best Practices
|
|
120
|
+
|
|
121
|
+
1. **Memoize Query Parameters**: Pass memoized arrays or primitives to `useLiveQuery` to avoid re-triggering queries on every parent component render.
|
|
122
|
+
2. **Selective Column Projections**: In high-frequency queries, select only required columns (`SELECT id, title FROM ...`) instead of `SELECT *` to reduce SQLite serialization overhead.
|
|
123
|
+
3. **Batch Mutations**: Wrap bulk inserts in transactions or `client.mutateBatch()` rather than issuing individual `INSERT` statements in loops.
|
|
124
|
+
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-schema
|
|
3
|
+
description: Design schemas, write migrations, configure cascading deletions, and build queries in local-lite. Use when defining foreign key relationships with onDelete (cascade, restrict, setNull), writing schemaMigrations, enabling touchUpdatedAt, setting up SQLite FTS5 search, or using query operators.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Schema, Migrations & Queries
|
|
7
|
+
|
|
8
|
+
Guide for schema design, migrations, relationship management, and query execution in `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Schema Conventions
|
|
13
|
+
|
|
14
|
+
Every synchronized table in `local-lite` requires two mandatory columns:
|
|
15
|
+
* `id TEXT PRIMARY KEY`: Typically an RFC4122 v4 UUID generated via `generateUUID()`.
|
|
16
|
+
* `updated_at INTEGER NOT NULL`: Epoch millisecond timestamp (`Date.now()`).
|
|
17
|
+
|
|
18
|
+
```sql
|
|
19
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
20
|
+
id TEXT PRIMARY KEY,
|
|
21
|
+
name TEXT NOT NULL,
|
|
22
|
+
created_at INTEGER NOT NULL,
|
|
23
|
+
updated_at INTEGER NOT NULL
|
|
24
|
+
);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Foreign Key Relationships & Cascading Deletions (`onDelete`)
|
|
30
|
+
|
|
31
|
+
Configure declarative relationship metadata directly in your client configuration so deletions automatically cascade or enforce integrity:
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { defineSyncConfig } from 'local-lite/config';
|
|
35
|
+
|
|
36
|
+
export const syncConfig = defineSyncConfig({
|
|
37
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
38
|
+
tables: ['projects', 'tasks', 'comments'],
|
|
39
|
+
|
|
40
|
+
relationships: [
|
|
41
|
+
{
|
|
42
|
+
parentTable: 'projects',
|
|
43
|
+
childTable: 'tasks',
|
|
44
|
+
foreignKey: 'project_id',
|
|
45
|
+
onDelete: 'cascade', // When a project is deleted, all its tasks are deleted
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
parentTable: 'tasks',
|
|
49
|
+
childTable: 'comments',
|
|
50
|
+
foreignKey: 'task_id',
|
|
51
|
+
onDelete: 'cascade', // Cascades down multiple levels
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
parentTable: 'users',
|
|
55
|
+
childTable: 'tasks',
|
|
56
|
+
foreignKey: 'assignee_id',
|
|
57
|
+
onDelete: 'setNull', // Sets task.assignee_id = NULL if user is removed
|
|
58
|
+
},
|
|
59
|
+
],
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Supported `onDelete` Actions:
|
|
64
|
+
* `'cascade'`: Deletes all matching child records when the parent record is deleted.
|
|
65
|
+
* `'restrict'`: Throws an error preventing parent deletion if child records exist.
|
|
66
|
+
* `'setNull'`: Updates the foreign key column on child records to `NULL`.
|
|
67
|
+
* `'noAction'`: Leaves child records intact without performing automated changes.
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## 3. Schema Migrations (`schemaMigrations`)
|
|
72
|
+
|
|
73
|
+
Migrations are managed via the append-only `schemaMigrations` array. Applied versions are tracked in SQLite in the `_migrations` internal table.
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
schemaMigrations: [
|
|
77
|
+
{
|
|
78
|
+
version: 1,
|
|
79
|
+
up: [
|
|
80
|
+
`CREATE TABLE IF NOT EXISTS users (
|
|
81
|
+
id TEXT PRIMARY KEY,
|
|
82
|
+
email TEXT NOT NULL,
|
|
83
|
+
updated_at INTEGER NOT NULL
|
|
84
|
+
);`,
|
|
85
|
+
],
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
version: 2,
|
|
89
|
+
up: [
|
|
90
|
+
// Add a column or index in a new version
|
|
91
|
+
`ALTER TABLE users ADD COLUMN display_name TEXT;`,
|
|
92
|
+
`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);`,
|
|
93
|
+
],
|
|
94
|
+
},
|
|
95
|
+
]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Rules:
|
|
99
|
+
1. **Never edit an applied migration**: Modifying an existing migration version causes version drift. Always append a new `{ version: N + 1, up: [...] }`.
|
|
100
|
+
2. **Idempotence**: Prefer `IF NOT EXISTS` for table and index creation.
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 4. Automatic Timestamp Maintenance (`touchUpdatedAt`)
|
|
105
|
+
|
|
106
|
+
Ensure `updated_at` timestamps are always refreshed on every write by enabling `touchUpdatedAt`:
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
export const syncConfig = defineSyncConfig({
|
|
110
|
+
// Automatically updates updated_at on all mutations
|
|
111
|
+
touchUpdatedAt: true,
|
|
112
|
+
|
|
113
|
+
// Or customize the timestamp column name
|
|
114
|
+
// touchUpdatedAt: 'modified_at',
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## 5. Full-Text Search (SQLite FTS5)
|
|
121
|
+
|
|
122
|
+
Enable lightning-fast full-text search using SQLite's FTS5 virtual tables:
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
// 1. Create the FTS5 virtual table in a schema migration
|
|
126
|
+
schemaMigrations: [
|
|
127
|
+
{
|
|
128
|
+
version: 3,
|
|
129
|
+
up: [
|
|
130
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(
|
|
131
|
+
title,
|
|
132
|
+
content,
|
|
133
|
+
content='notes',
|
|
134
|
+
content_rowid='rowid'
|
|
135
|
+
);`,
|
|
136
|
+
],
|
|
137
|
+
},
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
// 2. Perform searches using client.search()
|
|
141
|
+
const results = await client.search('notes_fts', 'react native offline');
|
|
142
|
+
|
|
143
|
+
// 3. Or use the reactive React hook:
|
|
144
|
+
const { results, isSearching } = useSearch(client, 'notes_fts', searchQuery);
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## 6. Query Builder & Complex Operators
|
|
150
|
+
|
|
151
|
+
Execute filtered queries with MongoDB-like declarative operators using `queryBuilder` or `useQueryBuilder`:
|
|
152
|
+
|
|
153
|
+
```typescript
|
|
154
|
+
const tasks = await client.query('tasks', {
|
|
155
|
+
status: { $in: ['todo', 'in_progress'] },
|
|
156
|
+
priority: { $gte: 2 },
|
|
157
|
+
title: { $like: '%release%' },
|
|
158
|
+
}, {
|
|
159
|
+
orderBy: { updated_at: 'DESC' },
|
|
160
|
+
limit: 20,
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### Supported Operators:
|
|
165
|
+
* `$eq`, `$ne`: Equal, Not Equal
|
|
166
|
+
* `$gt`, `$gte`: Greater Than, Greater Than or Equal
|
|
167
|
+
* `$lt`, `$lte`: Less Than, Less Than or Equal
|
|
168
|
+
* `$in`, `$nin`: In Array, Not In Array
|
|
169
|
+
* `$like`: SQL LIKE pattern matching
|
|
170
|
+
* `$null`: Is NULL or Not NULL (`{ deleted_at: { $null: true } }`)
|
|
171
|
+
|
|
@@ -1,21 +1,203 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: local-lite-setup
|
|
3
|
-
description: Set up the local-lite local-first SQLite sync engine in a React / React Native / Expo / Node app. Use when adding local-lite, writing a sync config with defineSyncConfig, schemaMigrations,
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# local-lite setup
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
1.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-setup
|
|
3
|
+
description: Set up the local-lite local-first SQLite sync engine in a React / React Native / Expo / Web / Node app. Use when adding local-lite, writing a sync config with defineSyncConfig, schemaMigrations, configuring local authentication, foreign key cascading deletions, cloud backups, or wiring useLiveQuery and useLocalAuth.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite setup
|
|
7
|
+
|
|
8
|
+
Guide for initializing and configuring `local-lite` across mobile (iOS/Android), web (React/SPA), and desktop/backend (Node.js/Electron).
|
|
9
|
+
|
|
10
|
+
## 1. Installation
|
|
11
|
+
|
|
12
|
+
Install `local-lite` and the appropriate SQLite driver for your target platform:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
# Expo / React Native
|
|
16
|
+
npx expo install local-lite expo-sqlite
|
|
17
|
+
|
|
18
|
+
# Node.js / Electron / Desktop
|
|
19
|
+
npm install local-lite better-sqlite3 # or @libsql/client
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
If connecting to a remote backend, also install the matching client SDK:
|
|
23
|
+
* **Supabase**: `@supabase/supabase-js`
|
|
24
|
+
* **Convex**: `convex`
|
|
25
|
+
* **Firestore**: `firebase`
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 2. Platform Bundler Setup (Expo & Web)
|
|
30
|
+
|
|
31
|
+
If targeting **Expo Web**, configure `metro.config.js` to support WebAssembly SQLite (`wa-sqlite.wasm`) and avoid dual React resolutions in monorepos:
|
|
32
|
+
|
|
33
|
+
```javascript
|
|
34
|
+
// metro.config.js
|
|
35
|
+
const { getDefaultConfig } = require('expo/metro-config');
|
|
36
|
+
const path = require('path');
|
|
37
|
+
|
|
38
|
+
const config = getDefaultConfig(__dirname);
|
|
39
|
+
|
|
40
|
+
// Enable WebAssembly (.wasm) for expo-sqlite on the web
|
|
41
|
+
config.resolver.assetExts.push('wasm');
|
|
42
|
+
|
|
43
|
+
// Handle web vs native react-native module aliasing
|
|
44
|
+
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
45
|
+
if (platform === 'web' && moduleName === 'react-native') {
|
|
46
|
+
return context.resolveRequest(context, 'react-native-web', platform);
|
|
47
|
+
}
|
|
48
|
+
return context.resolveRequest(context, moduleName, platform);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
module.exports = config;
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
In `app.json`, set client-side single-page output for the web:
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"expo": {
|
|
58
|
+
"web": {
|
|
59
|
+
"output": "single"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 3. Configuration (`sync.config.ts`)
|
|
68
|
+
|
|
69
|
+
Create a singleton client configuration with `defineSyncConfig` and `createSyncClient`:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import * as SQLite from 'expo-sqlite';
|
|
73
|
+
import { defineSyncConfig, createSyncClient, type LocalFirstClient } from 'local-lite/config';
|
|
74
|
+
|
|
75
|
+
export const syncConfig = defineSyncConfig({
|
|
76
|
+
// 1. Local Database instance or factory
|
|
77
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
78
|
+
|
|
79
|
+
// 2. Synced table names
|
|
80
|
+
tables: ['todos', 'projects'],
|
|
81
|
+
|
|
82
|
+
// 3. Schema Migrations (strictly append-only)
|
|
83
|
+
schemaMigrations: [
|
|
84
|
+
{
|
|
85
|
+
version: 1,
|
|
86
|
+
up: [
|
|
87
|
+
`CREATE TABLE IF NOT EXISTS projects (
|
|
88
|
+
id TEXT PRIMARY KEY,
|
|
89
|
+
name TEXT NOT NULL,
|
|
90
|
+
updated_at INTEGER NOT NULL
|
|
91
|
+
);`,
|
|
92
|
+
`CREATE TABLE IF NOT EXISTS todos (
|
|
93
|
+
id TEXT PRIMARY KEY,
|
|
94
|
+
project_id TEXT,
|
|
95
|
+
title TEXT NOT NULL,
|
|
96
|
+
completed INTEGER NOT NULL DEFAULT 0,
|
|
97
|
+
updated_at INTEGER NOT NULL
|
|
98
|
+
);`,
|
|
99
|
+
],
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
|
|
103
|
+
// 4. Foreign key relationships and cascading deletions
|
|
104
|
+
relationships: [
|
|
105
|
+
{
|
|
106
|
+
parentTable: 'projects',
|
|
107
|
+
childTable: 'todos',
|
|
108
|
+
foreignKey: 'project_id',
|
|
109
|
+
onDelete: 'cascade', // 'cascade' | 'restrict' | 'setNull' | 'noAction'
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
|
|
113
|
+
// 5. Automatic updated_at timestamp maintenance
|
|
114
|
+
touchUpdatedAt: true,
|
|
115
|
+
|
|
116
|
+
// 6. Zero-backend local SQLite authentication
|
|
117
|
+
localAuth: {
|
|
118
|
+
minPasswordLength: 8,
|
|
119
|
+
maxFailedAttempts: 5,
|
|
120
|
+
lockoutDurationMs: 15 * 60 * 1000, // 15 minutes
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
// 7. Remote Backend (choose one or omit for local-only)
|
|
124
|
+
// localOnly: true, // Set to true if not syncing to a remote server
|
|
125
|
+
supabase: {
|
|
126
|
+
url: process.env.EXPO_PUBLIC_SUPABASE_URL!,
|
|
127
|
+
anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
// 8. Sync tuning
|
|
131
|
+
pushIntervalMs: 500,
|
|
132
|
+
pullIntervalMs: 5000,
|
|
133
|
+
conflictResolver: 'last-write-wins',
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// Singleton client promise
|
|
137
|
+
let clientPromise: Promise<LocalFirstClient> | null = null;
|
|
138
|
+
export function getSyncClient(): Promise<LocalFirstClient> {
|
|
139
|
+
if (!clientPromise) {
|
|
140
|
+
clientPromise = createSyncClient(syncConfig);
|
|
141
|
+
}
|
|
142
|
+
return clientPromise;
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## 4. Schema & Migration Rules
|
|
149
|
+
|
|
150
|
+
1. Every synced table **must** include:
|
|
151
|
+
* `id TEXT PRIMARY KEY`
|
|
152
|
+
* `updated_at INTEGER NOT NULL`
|
|
153
|
+
2. Never edit an applied migration. Always increment the `version` and append a new migration object to `schemaMigrations`.
|
|
154
|
+
3. Use `generateUUID()` from `local-lite` to create unique IDs.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 5. React Integration
|
|
159
|
+
|
|
160
|
+
Use `local-lite/react` hooks for reactive data binding and local authentication:
|
|
161
|
+
|
|
162
|
+
```tsx
|
|
163
|
+
import React, { useState, useEffect } from 'react';
|
|
164
|
+
import { View, Text, Button } from 'react-native';
|
|
165
|
+
import { useLiveQuery, useSyncStatus, useLocalAuth } from 'local-lite/react';
|
|
166
|
+
import { getSyncClient } from './sync.config';
|
|
167
|
+
import type { LocalFirstClient } from 'local-lite/config';
|
|
168
|
+
|
|
169
|
+
export function App() {
|
|
170
|
+
const [client, setClient] = useState<LocalFirstClient | null>(null);
|
|
171
|
+
|
|
172
|
+
useEffect(() => {
|
|
173
|
+
getSyncClient().then(setClient);
|
|
174
|
+
}, []);
|
|
175
|
+
|
|
176
|
+
// 1. Reactive live SQLite query (auto-updates when table mutates)
|
|
177
|
+
const { data: todos } = useLiveQuery<{ id: string; title: string }>(
|
|
178
|
+
client,
|
|
179
|
+
'SELECT * FROM todos ORDER BY updated_at DESC;',
|
|
180
|
+
[]
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
// 2. Real-time sync engine connectivity & outbox metrics
|
|
184
|
+
const { isOnline, isSyncing, pendingChanges } = useSyncStatus(client);
|
|
185
|
+
|
|
186
|
+
// 3. Reactive zero-backend local authentication
|
|
187
|
+
const { user, isSignedIn, signIn, signOut } = useLocalAuth(client?.auth);
|
|
188
|
+
|
|
189
|
+
return (
|
|
190
|
+
<View>
|
|
191
|
+
<Text>Status: {isOnline ? 'Online' : 'Offline'} ({pendingChanges} pending)</Text>
|
|
192
|
+
{isSignedIn ? (
|
|
193
|
+
<View>
|
|
194
|
+
<Text>Welcome, {user?.displayName || user?.email}!</Text>
|
|
195
|
+
<Button title="Sign Out" onPress={() => signOut()} />
|
|
196
|
+
</View>
|
|
197
|
+
) : (
|
|
198
|
+
<Button title="Sign In" onPress={() => signIn('user@example.com', 'Password123!')} />
|
|
199
|
+
)}
|
|
200
|
+
</View>
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
```
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: local-lite-storage
|
|
3
|
+
description: Manage binary files, images, and attachments with offline caching and cloud sync in local-lite. Use when configuring BlobStorageManager, ExpoFileDriver, syncing files to Supabase Storage, Firebase Storage, or Convex, and using useStorage or useBlobUpload.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# local-lite Blob & File Storage
|
|
7
|
+
|
|
8
|
+
Guide for managing binary files, media, and attachments with local offline caching and cloud bucket synchronization in `local-lite`.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Storage Architecture
|
|
13
|
+
|
|
14
|
+
`local-lite/storage` decouples file metadata in SQLite from the actual binary data on disk:
|
|
15
|
+
* **Local File Drivers**: Persists binary blobs to disk (`ExpoFileDriver` on mobile, `NodeFsFileDriver` on Node.js/Electron).
|
|
16
|
+
* **Remote Storage Providers**: Synchronizes files to remote cloud buckets (Supabase Storage, Firebase Storage, Convex Files).
|
|
17
|
+
* **Metadata Store**: Automatically maintains offline status, upload progress, mime types, and SHA-256 checksums in the `_local_blobs` SQLite table.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Configuration
|
|
22
|
+
|
|
23
|
+
Enable storage in `defineSyncConfig`:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { defineSyncConfig } from 'local-lite/config';
|
|
27
|
+
import { ExpoFileDriver } from 'local-lite/storage';
|
|
28
|
+
|
|
29
|
+
export const syncConfig = defineSyncConfig({
|
|
30
|
+
database: () => SQLite.openDatabaseAsync('app.db'),
|
|
31
|
+
tables: ['documents', 'photos'],
|
|
32
|
+
|
|
33
|
+
// Blob storage configuration
|
|
34
|
+
storage: {
|
|
35
|
+
// 1. Local storage driver
|
|
36
|
+
driver: new ExpoFileDriver({
|
|
37
|
+
baseDirectory: 'attachments', // Stored in private app document directory
|
|
38
|
+
}),
|
|
39
|
+
|
|
40
|
+
// 2. Remote storage provider (e.g. Supabase Storage bucket)
|
|
41
|
+
provider: {
|
|
42
|
+
type: 'supabase',
|
|
43
|
+
bucket: 'user-attachments',
|
|
44
|
+
url: process.env.EXPO_PUBLIC_SUPABASE_URL!,
|
|
45
|
+
anonKey: process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!,
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
// 3. Auto-sync uploads when online
|
|
49
|
+
autoSync: true,
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 3. Saving & Reading Files
|
|
57
|
+
|
|
58
|
+
### Save a File (Immediate Offline Access)
|
|
59
|
+
```typescript
|
|
60
|
+
import { getSyncClient } from './sync.config';
|
|
61
|
+
|
|
62
|
+
const client = await getSyncClient();
|
|
63
|
+
|
|
64
|
+
// Saves to local disk immediately and queues for background cloud sync
|
|
65
|
+
const blob = await client.storage.save({
|
|
66
|
+
id: 'avatar-user-123.jpg',
|
|
67
|
+
data: fileBytes, // Uint8Array or Blob
|
|
68
|
+
mimeType: 'image/jpeg',
|
|
69
|
+
metadata: { userId: '123' },
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
console.log('Saved locally at:', blob.localPath);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Retrieve a File
|
|
76
|
+
```typescript
|
|
77
|
+
// Read as raw Uint8Array
|
|
78
|
+
const data = await client.storage.read('avatar-user-123.jpg');
|
|
79
|
+
|
|
80
|
+
// Or get local file URI for <Image source={{ uri }} />
|
|
81
|
+
const uri = await client.storage.getLocalUri('avatar-user-123.jpg');
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 4. React Integration (`useStorage` & `useBlobUpload`)
|
|
87
|
+
|
|
88
|
+
Use reactive hooks from `local-lite/react` for image pickers, file attachments, and upload progress:
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
import React from 'react';
|
|
92
|
+
import { View, Image, Text, Button } from 'react-native';
|
|
93
|
+
import { useStorage } from 'local-lite/react';
|
|
94
|
+
import { getSyncClient } from './sync.config';
|
|
95
|
+
|
|
96
|
+
export function DocumentViewer({ fileId }: { fileId: string }) {
|
|
97
|
+
const [client, setClient] = React.useState(null);
|
|
98
|
+
React.useEffect(() => { getSyncClient().then(setClient); }, []);
|
|
99
|
+
|
|
100
|
+
const { fileUri, isSyncing, progress, error } = useStorage(client?.storage, fileId);
|
|
101
|
+
|
|
102
|
+
if (error) return <Text>Error loading file: {error.message}</Text>;
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<View>
|
|
106
|
+
{fileUri ? (
|
|
107
|
+
<Image source={{ uri: fileUri }} style={{ width: 300, height: 300 }} />
|
|
108
|
+
) : (
|
|
109
|
+
<Text>Loading file from local storage...</Text>
|
|
110
|
+
)}
|
|
111
|
+
{isSyncing && <Text>Syncing to cloud: {progress}%</Text>}
|
|
112
|
+
</View>
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|