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/actions-email.md
DELETED
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
# 📨 Generic Action Outbox & Inbuilt Email Queue
|
|
2
|
-
|
|
3
|
-
In addition to database table synchronization, `local-lite` provides a dedicated **Generic Action Outbox** (`client.actions`). This engine is specifically designed for offline-queued commands and asynchronous side effects—such as **transactional emails, push notifications, webhooks, or payment intents**—that must execute reliably without data loss when network connectivity is intermittent.
|
|
4
|
-
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## 🎯 Why an Action Outbox?
|
|
8
|
-
|
|
9
|
-
Standard database record synchronization (CRUD) and external actions (RPC) have fundamentally different requirements:
|
|
10
|
-
|
|
11
|
-
| Property | Standard Data Sync (CRUD) | Action Outbox (RPC / Side Effects) |
|
|
12
|
-
| :--- | :--- | :--- |
|
|
13
|
-
| **Example** | Update user profile, edit a note | Send order receipt email, send push alert |
|
|
14
|
-
| **Duplicates** | Safe (Idempotent: last-write-wins) | **Dangerous** (Duplicate execution sends multiple emails or double charges) |
|
|
15
|
-
| **Lifecycle** | Permanent SQLite records | **Transient**: `PENDING` ➔ `EXECUTING` ➔ `COMPLETED` / `FAILED` ➔ Pruned |
|
|
16
|
-
| **Direction** | Two-way sync (push local, pull remote) | **One-way command execution** with a persistent receipt/result |
|
|
17
|
-
| **Time Sensitivity** | Changes stay valid indefinitely | **Needs TTL / Expiration** (e.g. don't send time-sensitive alerts 2 days later) |
|
|
18
|
-
|
|
19
|
-
`client.actions` solves these problems by providing atomic storage in a local `_local_actions` table, strict idempotency deduplication, crash recovery, and configurable retries.
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
## 📧 Inbuilt Email Queueing
|
|
24
|
-
|
|
25
|
-
`local-lite` offers first-class, typed helpers for enqueuing and dispatching emails:
|
|
26
|
-
|
|
27
|
-
### Enqueuing an Email Offline
|
|
28
|
-
|
|
29
|
-
Enqueuing an email is an instantaneous (0ms) local write to SQLite. If the user is offline or the app suddenly closes, the email is safely preserved in local storage.
|
|
30
|
-
|
|
31
|
-
```typescript
|
|
32
|
-
import { client } from './sync.config';
|
|
33
|
-
|
|
34
|
-
const emailAction = await client.actions.sendEmail({
|
|
35
|
-
to: 'customer@example.com',
|
|
36
|
-
subject: 'Order #1042 Confirmed',
|
|
37
|
-
html: '<h1>Thank you for your purchase!</h1>',
|
|
38
|
-
text: 'Thank you for your purchase!',
|
|
39
|
-
template: 'order_receipt',
|
|
40
|
-
templateData: { orderId: 1042, total: '$49.99' },
|
|
41
|
-
|
|
42
|
-
// Guarantees at-most-once execution even if pressed multiple times
|
|
43
|
-
idempotencyKey: 'receipt_order_1042',
|
|
44
|
-
|
|
45
|
-
// Time-to-live: expire if device remains offline for > 24 hours
|
|
46
|
-
ttlMs: 24 * 60 * 60 * 1000,
|
|
47
|
-
|
|
48
|
-
// Maximum retry attempts before marking status as FAILED
|
|
49
|
-
maxRetries: 3,
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
console.log('Enqueued email ID:', emailAction.id);
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
### Email Options Reference
|
|
56
|
-
|
|
57
|
-
| Option | Type | Description |
|
|
58
|
-
| :--- | :--- | :--- |
|
|
59
|
-
| `to` | `string \| string[]` | **Required.** Recipient email address(es). |
|
|
60
|
-
| `subject` | `string` | **Required.** Email subject line. |
|
|
61
|
-
| `html` | `string` | Optional HTML email body. |
|
|
62
|
-
| `text` | `string` | Optional plaintext fallback. |
|
|
63
|
-
| `from` | `string` | Optional sender address (e.g. `support@yourdomain.com`). |
|
|
64
|
-
| `replyTo` | `string` | Optional reply-to address. |
|
|
65
|
-
| `cc` | `string \| string[]` | Optional carbon copy recipient(s). |
|
|
66
|
-
| `bcc` | `string \| string[]` | Optional blind carbon copy recipient(s). |
|
|
67
|
-
| `template` | `string` | Optional template identifier (for template-based engines). |
|
|
68
|
-
| `templateData` | `Record<string, any>` | Optional variables passed to your email template. |
|
|
69
|
-
| `attachments` | `EmailAttachment[]` | Array of `{ filename, content?, url?, contentType? }`. |
|
|
70
|
-
| `headers` | `Record<string, string>` | Optional custom MIME headers. |
|
|
71
|
-
| `idempotencyKey` | `string` | Unique key preventing duplicate action execution. |
|
|
72
|
-
| `ttlMs` | `number` | Expiration window in milliseconds from time of enqueuing. |
|
|
73
|
-
| `expiresAt` | `number` | Explicit Unix timestamp (ms) when the action expires. |
|
|
74
|
-
| `maxRetries` | `number` | Maximum delivery attempts before marking as `FAILED` (default: `3`). |
|
|
75
|
-
|
|
76
|
-
---
|
|
77
|
-
|
|
78
|
-
## 🚀 Dispatching Emails
|
|
79
|
-
|
|
80
|
-
There are two primary patterns for executing enqueued email actions:
|
|
81
|
-
|
|
82
|
-
### Pattern 1: Local Dispatcher via Provider API (Resend, SendGrid, etc.)
|
|
83
|
-
|
|
84
|
-
Register a local handler that triggers whenever the device is online and flushes pending emails:
|
|
85
|
-
|
|
86
|
-
```typescript
|
|
87
|
-
// Register handler (e.g. in your app initialization)
|
|
88
|
-
client.actions.registerEmailHandler(async (email, action, context) => {
|
|
89
|
-
// Call your email delivery service (e.g., Resend)
|
|
90
|
-
const response = await fetch('https://api.resend.com/emails', {
|
|
91
|
-
method: 'POST',
|
|
92
|
-
headers: {
|
|
93
|
-
'Authorization': `Bearer ${process.env.RESEND_API_KEY}`,
|
|
94
|
-
'Content-Type': 'application/json',
|
|
95
|
-
},
|
|
96
|
-
body: JSON.stringify({
|
|
97
|
-
from: email.from || 'Acme <onboarding@resend.dev>',
|
|
98
|
-
to: email.to,
|
|
99
|
-
subject: email.subject,
|
|
100
|
-
html: email.html,
|
|
101
|
-
}),
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
if (!response.ok) {
|
|
105
|
-
const error = await response.json();
|
|
106
|
-
throw new Error(error.message || 'Failed to dispatch email');
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const data = await response.json();
|
|
110
|
-
// Return result to store receipt in SQLite
|
|
111
|
-
return { messageId: data.id };
|
|
112
|
-
});
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
### Pattern 2: Cloud Function Trigger (Supabase / Convex / Firebase)
|
|
116
|
-
|
|
117
|
-
If you prefer **not** to embed API keys in your mobile or web app, do not register a local handler. The pending actions in `_local_actions` will sync to your remote backend via `local-lite`'s normal table replication:
|
|
118
|
-
|
|
119
|
-
1. **Supabase:** Configure a Postgres Database Webhook on `_local_actions` for `action = 'send_email'`. An Edge Function executes the email send and updates the record's status to `COMPLETED`.
|
|
120
|
-
2. **Convex:** Define a Convex action watching `_local_actions` that invokes your email provider using secure server-side environment variables.
|
|
121
|
-
3. **Firebase:** Attach a Cloud Function `onDocumentCreated('_local_actions/{id}')` to send the email via SendGrid/Postmark.
|
|
122
|
-
|
|
123
|
-
The updated `COMPLETED` status syncs back down to SQLite, updating your local client UI.
|
|
124
|
-
|
|
125
|
-
---
|
|
126
|
-
|
|
127
|
-
## ⚡ Generic Offline Actions
|
|
128
|
-
|
|
129
|
-
You can use the action engine for any arbitrary offline command:
|
|
130
|
-
|
|
131
|
-
```typescript
|
|
132
|
-
// 1. Register a handler for push notifications
|
|
133
|
-
client.actions.registerHandler('push_notification', async (action, context) => {
|
|
134
|
-
const { deviceToken, title, body } = action.payload;
|
|
135
|
-
|
|
136
|
-
const res = await fetch('https://exp.host/--/api/v2/push/send', {
|
|
137
|
-
method: 'POST',
|
|
138
|
-
headers: { 'Content-Type': 'application/json' },
|
|
139
|
-
body: JSON.stringify({ to: deviceToken, title, body }),
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
return await res.json();
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
// 2. Enqueue from anywhere in your app while offline
|
|
146
|
-
await client.actions.enqueue({
|
|
147
|
-
action: 'push_notification',
|
|
148
|
-
payload: {
|
|
149
|
-
deviceToken: 'ExponentPushToken[xxxxxxxxxxxxxx]',
|
|
150
|
-
title: 'New Chat Message',
|
|
151
|
-
body: 'You received a message from Sarah',
|
|
152
|
-
},
|
|
153
|
-
idempotencyKey: 'msg_push_4812',
|
|
154
|
-
ttlMs: 60 * 60 * 1000, // 1 hour TTL
|
|
155
|
-
});
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
---
|
|
159
|
-
|
|
160
|
-
## 🛠️ Action Management & Operations
|
|
161
|
-
|
|
162
|
-
### Manual Flush
|
|
163
|
-
Trigger an immediate execution of all pending actions whose handlers are registered:
|
|
164
|
-
|
|
165
|
-
```typescript
|
|
166
|
-
const result = await client.actions.flush();
|
|
167
|
-
console.log(`Processed: ${result.processed}, Completed: ${result.completed}, Failed: ${result.failed}`);
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
### Querying Actions
|
|
171
|
-
Query actions by ID, status, or action type:
|
|
172
|
-
|
|
173
|
-
```typescript
|
|
174
|
-
// Get specific action by ID
|
|
175
|
-
const action = await client.actions.get('action-uuid-123');
|
|
176
|
-
|
|
177
|
-
// List actions by status
|
|
178
|
-
const pendingEmails = await client.actions.list({
|
|
179
|
-
action: 'send_email',
|
|
180
|
-
status: 'PENDING',
|
|
181
|
-
limit: 20,
|
|
182
|
-
});
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
### Cancelling an Action
|
|
186
|
-
Cancel a pending action before it is executed:
|
|
187
|
-
|
|
188
|
-
```typescript
|
|
189
|
-
const wasCancelled = await client.actions.cancel('action-uuid-123');
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
### Pruning Old Records
|
|
193
|
-
Clean up completed, failed, or expired action records:
|
|
194
|
-
|
|
195
|
-
```typescript
|
|
196
|
-
// Prune records completed more than 7 days ago
|
|
197
|
-
await client.actions.prune({
|
|
198
|
-
completedOlderThanMs: 7 * 24 * 60 * 60 * 1000,
|
|
199
|
-
failedOlderThanMs: 30 * 24 * 60 * 60 * 1000,
|
|
200
|
-
expiredOlderThanMs: 24 * 60 * 60 * 1000,
|
|
201
|
-
});
|
|
202
|
-
```
|
|
203
|
-
|
|
204
|
-
---
|
|
205
|
-
|
|
206
|
-
## 🛡️ Reliability & Crash Recovery
|
|
207
|
-
|
|
208
|
-
1. **At-Most-Once Delivery (Idempotency):**
|
|
209
|
-
Passing `idempotencyKey` ensures that multiple calls (e.g. from a user tapping "Submit" multiple times) return the existing action record without creating duplicate outbox rows or sending multiple emails.
|
|
210
|
-
2. **Crash Recovery:**
|
|
211
|
-
If the mobile app is terminated or crashes while an action is `EXECUTING`, on the next app launch `client.initialize()` automatically resets stale `EXECUTING` records back to `PENDING` so they can complete safely.
|
|
212
|
-
3. **Automatic Retries:**
|
|
213
|
-
If a handler throws an error (e.g. temporary network error or rate limit), `retry_count` is incremented. The action is marked `FAILED` only after exceeding `maxRetries`.
|
|
214
|
-
4. **Lifecycle Events:**
|
|
215
|
-
Listen to action lifecycle events directly through `client.events`:
|
|
216
|
-
```typescript
|
|
217
|
-
client.events.on('action:enqueued', (action) => console.log('Enqueued:', action.id));
|
|
218
|
-
client.events.on('action:executing', (action) => console.log('Executing:', action.id));
|
|
219
|
-
client.events.on('action:completed', (action) => console.log('Completed:', action.id));
|
|
220
|
-
client.events.on('action:failed', (action) => console.error('Failed:', action.id, action.lastError));
|
|
221
|
-
client.events.on('action:expired', (action) => console.warn('Expired without executing:', action.id));
|
|
222
|
-
```
|
package/docs/adapters-local.md
DELETED
|
@@ -1,272 +0,0 @@
|
|
|
1
|
-
# 💾 Local SQLite Adapters
|
|
2
|
-
|
|
3
|
-
`local-lite` supports any SQLite driver across mobile, desktop, and web environments.
|
|
4
|
-
|
|
5
|
-
The configuration helper automatically detects the driver passed to `config.database`. Alternatively, you can import and instantiate any adapter directly.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## 1. Expo SQLite (`expo-sqlite`)
|
|
10
|
-
|
|
11
|
-
Recommended for **Expo & React Native** apps.
|
|
12
|
-
|
|
13
|
-
```bash
|
|
14
|
-
npx expo install expo-sqlite
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
### Auto-Detection via `defineSyncConfig`:
|
|
18
|
-
```typescript
|
|
19
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
20
|
-
import * as SQLite from 'expo-sqlite';
|
|
21
|
-
|
|
22
|
-
export const config = defineSyncConfig({
|
|
23
|
-
database: () => SQLite.openDatabaseAsync('my_app.db'),
|
|
24
|
-
tables: ['todos'],
|
|
25
|
-
});
|
|
26
|
-
```
|
|
27
|
-
|
|
28
|
-
### Standalone Adapter:
|
|
29
|
-
```typescript
|
|
30
|
-
import { ExpoSQLiteAdapter } from 'local-lite/expo-sqlite';
|
|
31
|
-
import * as SQLite from 'expo-sqlite';
|
|
32
|
-
|
|
33
|
-
const db = await SQLite.openDatabaseAsync('my_app.db');
|
|
34
|
-
const adapter = new ExpoSQLiteAdapter(db);
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
---
|
|
38
|
-
|
|
39
|
-
## 2. OP-SQLite (`@op-engineering/op-sqlite`)
|
|
40
|
-
|
|
41
|
-
High-performance JSI SQLite driver for **bare React Native** apps.
|
|
42
|
-
|
|
43
|
-
```bash
|
|
44
|
-
npm install @op-engineering/op-sqlite
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
### Usage:
|
|
48
|
-
```typescript
|
|
49
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
50
|
-
import { open } from '@op-engineering/op-sqlite';
|
|
51
|
-
|
|
52
|
-
const db = open({ name: 'my_app.db' });
|
|
53
|
-
|
|
54
|
-
export const config = defineSyncConfig({
|
|
55
|
-
database: db,
|
|
56
|
-
tables: ['todos'],
|
|
57
|
-
});
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
---
|
|
61
|
-
|
|
62
|
-
## 3. Better-SQLite3 (`better-sqlite3`)
|
|
63
|
-
|
|
64
|
-
Synchronous, ultra-fast SQLite driver for **Node.js, Electron, Next.js, and server environments**.
|
|
65
|
-
|
|
66
|
-
```bash
|
|
67
|
-
npm install better-sqlite3
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
### Usage:
|
|
71
|
-
```typescript
|
|
72
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
73
|
-
import Database from 'better-sqlite3';
|
|
74
|
-
|
|
75
|
-
const db = new Database('my_app.db');
|
|
76
|
-
|
|
77
|
-
export const config = defineSyncConfig({
|
|
78
|
-
database: db,
|
|
79
|
-
tables: ['todos'],
|
|
80
|
-
});
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
---
|
|
84
|
-
|
|
85
|
-
## 4. Node.js 22+ Built-in (`node:sqlite`)
|
|
86
|
-
|
|
87
|
-
Zero-dependency SQLite bundled directly inside Node.js v22.5.0+.
|
|
88
|
-
|
|
89
|
-
### Usage:
|
|
90
|
-
```typescript
|
|
91
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
92
|
-
import { DatabaseSync } from 'node:sqlite';
|
|
93
|
-
|
|
94
|
-
const db = new DatabaseSync('my_app.db');
|
|
95
|
-
|
|
96
|
-
export const config = defineSyncConfig({
|
|
97
|
-
database: db,
|
|
98
|
-
tables: ['todos'],
|
|
99
|
-
});
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
---
|
|
103
|
-
|
|
104
|
-
## 5. LibSQL / Turso (`@libsql/client`)
|
|
105
|
-
|
|
106
|
-
Supports edge workers, local files, and embedded replicas via Turso / LibSQL.
|
|
107
|
-
|
|
108
|
-
```bash
|
|
109
|
-
npm install @libsql/client
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
### Usage:
|
|
113
|
-
```typescript
|
|
114
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
115
|
-
import { createClient } from '@libsql/client';
|
|
116
|
-
|
|
117
|
-
const client = createClient({
|
|
118
|
-
url: 'file:my_app.db',
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
export const config = defineSyncConfig({
|
|
122
|
-
database: client,
|
|
123
|
-
tables: ['todos'],
|
|
124
|
-
});
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
---
|
|
128
|
-
|
|
129
|
-
## 6. Sql.js (WebAssembly / Browser)
|
|
130
|
-
|
|
131
|
-
Pure WebAssembly SQLite for client-side web applications and PWAs.
|
|
132
|
-
|
|
133
|
-
```bash
|
|
134
|
-
npm install sql.js
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
### Usage:
|
|
138
|
-
```typescript
|
|
139
|
-
import { defineSyncConfig } from 'local-lite/config';
|
|
140
|
-
import initSqlJs from 'sql.js';
|
|
141
|
-
|
|
142
|
-
const SQL = await initSqlJs();
|
|
143
|
-
const db = new SQL.Database();
|
|
144
|
-
|
|
145
|
-
export const config = defineSyncConfig({
|
|
146
|
-
database: db,
|
|
147
|
-
tables: ['todos'],
|
|
148
|
-
});
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
---
|
|
152
|
-
|
|
153
|
-
## Custom Local Database Adapters
|
|
154
|
-
|
|
155
|
-
If you use a custom or proprietary SQLite binding, implement the `LocalDBAdapter` interface:
|
|
156
|
-
|
|
157
|
-
```typescript
|
|
158
|
-
import { LocalDBAdapter, LocalTransaction } from 'local-lite';
|
|
159
|
-
|
|
160
|
-
export class CustomSQLiteAdapter implements LocalDBAdapter {
|
|
161
|
-
async execute(sql: string, params?: any[]): Promise<any> {
|
|
162
|
-
// Execute query and return result rows
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
async transaction<T>(action: (tx: LocalTransaction) => Promise<T>): Promise<T> {
|
|
166
|
-
// Execute multiple statements atomically
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
async close(): Promise<void> {
|
|
170
|
-
// Optional cleanup
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
## Database Backups
|
|
176
|
-
|
|
177
|
-
The `local-lite/backups` entry point creates SQLite snapshots from database bytes supplied
|
|
178
|
-
by your platform adapter. Its Google Drive backup client handles OAuth authorization-code
|
|
179
|
-
+ PKCE, code exchange, token refresh, and file storage.
|
|
180
|
-
The app supplies its OAuth client ID, callback URI/browser authorization, and secure token
|
|
181
|
-
storage; these platform-specific capabilities cannot safely be assumed by a
|
|
182
|
-
framework-neutral package. Backups do not alter or replace the remote adapter used for
|
|
183
|
-
live synchronization.
|
|
184
|
-
|
|
185
|
-
```typescript
|
|
186
|
-
import {
|
|
187
|
-
createDatabaseBackup,
|
|
188
|
-
GoogleDriveBackupClient,
|
|
189
|
-
createGoogleDriveTokenStore,
|
|
190
|
-
} from 'local-lite/backups';
|
|
191
|
-
|
|
192
|
-
const tokenStore = createGoogleDriveTokenStore(secureKeyValueStorage);
|
|
193
|
-
const drive = new GoogleDriveBackupClient({
|
|
194
|
-
clientId: googleOAuthClientId,
|
|
195
|
-
redirectUri,
|
|
196
|
-
authorize: openAuthorizationUrlInSystemBrowser,
|
|
197
|
-
tokenStore,
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
await drive.connect();
|
|
201
|
-
await createDatabaseBackup(database, drive);
|
|
202
|
-
```
|
|
203
|
-
|
|
204
|
-
The `authorize` callback opens the supplied `authorizationUrl` and returns the
|
|
205
|
-
authorization `code` and `state` from the registered `redirectUri`, or `null` if the user
|
|
206
|
-
cancels. The client validates the OAuth state and performs the PKCE code exchange.
|
|
207
|
-
`tokenStore` implements `get`, `set`, and `remove`; use your platform's secure credential
|
|
208
|
-
storage, not plain preferences. The client refreshes expired tokens automatically, and its
|
|
209
|
-
`list()` method returns backup metadata for restore-selection screens. For apps that
|
|
210
|
-
already manage OAuth, `GoogleDriveBackupStorage` remains available and accepts an
|
|
211
|
-
access-token callback.
|
|
212
|
-
|
|
213
|
-
For example, an Expo app can provide the browser and secure-store bridges:
|
|
214
|
-
|
|
215
|
-
```typescript
|
|
216
|
-
const tokenStore = createGoogleDriveTokenStore(secureStorage, 'drive-backup-tokens');
|
|
217
|
-
const googleClientId = process.env.EXPO_PUBLIC_GOOGLE_DRIVE_CLIENT_ID;
|
|
218
|
-
if (!googleClientId) throw new Error('Google Drive OAuth client ID is required.');
|
|
219
|
-
|
|
220
|
-
const drive = new GoogleDriveBackupClient({
|
|
221
|
-
clientId: googleClientId,
|
|
222
|
-
redirectUri: makeRedirectUri({ scheme: 'myapp', path: 'oauth' }),
|
|
223
|
-
tokenStore,
|
|
224
|
-
authorize: async ({ authorizationUrl, redirectUri }) => {
|
|
225
|
-
const result = await WebBrowser.openAuthSessionAsync(
|
|
226
|
-
authorizationUrl,
|
|
227
|
-
redirectUri,
|
|
228
|
-
);
|
|
229
|
-
if (result.type !== 'success') return null;
|
|
230
|
-
|
|
231
|
-
const callback = new URL(result.url);
|
|
232
|
-
return {
|
|
233
|
-
code: callback.searchParams.get('code') ?? '',
|
|
234
|
-
state: callback.searchParams.get('state') ?? '',
|
|
235
|
-
};
|
|
236
|
-
},
|
|
237
|
-
});
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
Register the exact redirect URI with the Google OAuth client. OAuth client IDs and
|
|
241
|
-
redirect behavior differ by target platform; no generic library can register the app or
|
|
242
|
-
create those provider credentials on the developer's behalf.
|
|
243
|
-
|
|
244
|
-
```typescript
|
|
245
|
-
import {
|
|
246
|
-
createDatabaseBackup,
|
|
247
|
-
restoreDatabaseBackup,
|
|
248
|
-
type BackupDatabase,
|
|
249
|
-
type BackupStorage,
|
|
250
|
-
} from 'local-lite/backups';
|
|
251
|
-
|
|
252
|
-
const database: BackupDatabase = {
|
|
253
|
-
exportDatabase: () => sqliteDatabase.serializeAsync(),
|
|
254
|
-
importDatabase: async bytes => {
|
|
255
|
-
// Validate and restore using the SQLite driver's platform-specific backup APIs.
|
|
256
|
-
await restoreSQLiteSnapshot(sqliteDatabase, bytes);
|
|
257
|
-
},
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
const storage: BackupStorage = {
|
|
261
|
-
save: async (name, bytes) => writeIntoPrivateBackupsDirectory(name, bytes),
|
|
262
|
-
read: async name => readFromPrivateBackupsDirectory(name),
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
const name = await createDatabaseBackup(database, storage);
|
|
266
|
-
await restoreDatabaseBackup(database, storage, name);
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
Backups are stored as plain `.db` files, so anyone with access to the cloud file can read
|
|
270
|
-
the database. Use this only when that exposure is acceptable and protect access through
|
|
271
|
-
the cloud account. Stop concurrent writes and synchronization before restoring, and use
|
|
272
|
-
the platform's database backup API rather than replacing a live SQLite file directly.
|