local-lite 0.2.1 → 0.2.2

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/docs/README.md DELETED
@@ -1,108 +0,0 @@
1
- # ⚡ local-lite Documentation
2
-
3
- Welcome to the official documentation for **`local-lite`**, a lightweight, vendor-agnostic **local-first synchronization engine** for React Native, Expo, Web, and Node.js applications.
4
-
5
- ---
6
-
7
- ## 📚 Documentation Index
8
-
9
- 1. **[Getting Started](./getting-started.md)**
10
- - Installation & peer dependencies
11
- - 5-minute Quickstart with SQLite & Cloud
12
- 2. **[Architecture & Concepts](./architecture.md)**
13
- - The Transactional Outbox Pattern
14
- - 0ms local reads & writes
15
- - SyncWorker pipeline & infinite loop safety
16
- 3. **[Configuration Reference](./configuration.md)**
17
- - `defineSyncConfig()` and `LocalLiteConfig` options
18
- - User data isolation (`syncScope`), outbox coalescing, JSON auto-hydration, and advanced retry policies
19
- 4. **[Client API & Query Builder](./client-api.md)**
20
- - Atomic dual-write CRUD (`insert`, `update`, `delete`, `mutate`, `trackMutation`)
21
- - Batches (`batch`) and custom transactions (`transaction`)
22
- - Fluent `QueryBuilder` (`from`, `select`, `join`, `where`, `groupBy`, `orderBy`)
23
- - Native SQL aggregations (`count`, `sum`, `avg`, `aggregate`)
24
- - Telemetry & outbox management (`getMetrics`, `retryFailedMutations`, `clearFailedMutations`)
25
- 5. **[Fast Key-Value & Encrypted Preferences](./kv.md)**
26
- - Typed storage for strings, numbers, booleans, and JSON objects (`client.kv`)
27
- - TTL expiration with lazy cleanup and batch pruning
28
- - Zero-Knowledge client-side encrypted secrets (AES-256-GCM + PBKDF2)
29
- - Reactive `useKV()` React hook
30
- 6. **[Instant Full-Text Search](./search.md)**
31
- - Native SQLite FTS5 engine integration (`client.search`)
32
- - Prefix matching, BM25 ranking, and highlighted `<mark>` snippets
33
- - Reactive `useSearch()` React hook with automatic debouncing
34
- 7. **[Offline Media & Blob Storage](./storage.md)**
35
- - Decoupled binary storage from SQLite table queries (`client.storage`)
36
- - Local filesystem and in-memory file drivers with SHA-256 integrity verification
37
- - Background cloud sync queue for S3, Supabase, Cloudinary, and Firebase Storage
38
- 8. **[Offline Job Scheduler & Background Cron](./scheduler.md)**
39
- - Persistent offline job scheduling surviving app restarts (`client.scheduler`)
40
- - Human expressions (`'daily'`, `'hourly'`, `'every 15 minutes'`) and 5-part cron
41
- - Run history tracking, duration telemetry, and automatic error logging
42
- 9. **[Local SQLite Adapters](./adapters-local.md)**
43
- - Expo SQLite (`expo-sqlite`)
44
- - Bare React Native (`@op-engineering/op-sqlite`)
45
- - Node.js / Electron (`better-sqlite3`)
46
- - Built-in Node 22+ (`node:sqlite`)
47
- - Edge / Turso (`@libsql/client`)
48
- - Web / Browser (`sql.js`)
49
- 10. **[Remote Backend Adapters](./adapters-remote.md)**
50
- - Supabase (Postgres + Realtime)
51
- - Convex (Reactive documents + RPCs)
52
- - Firebase / Firestore
53
- - Memory Demo (Mock testing without cloud)
54
- - Building custom backend adapters
55
- 11. **[React & Expo Hooks](./react-hooks.md)**
56
- - `useLiveQuery()`: Zero-SQL single table reactive query
57
- - `useLiveQueries()`: Parallel multi-table queries with single atomic commit
58
- - `useLiveRow()`: Targeted single-record live query with row-level invalidation
59
- - `useLiveInfiniteQuery()`: Paginated infinite scrolling live query
60
- - `useKV()`: Reactive state binding for key-value preferences
61
- - `useSearch()`: Debounced instant full-text search hook
62
- - `useMutations()`: Null-safe memoized mutation helper methods
63
- - `useSyncStatus()`: Real-time sync engine & outbox queue inspector
64
- - `useDatabaseMaintenance()`: Reactive storage stats, outbox pruning, VACUUM, and WAL checkpoints
65
- - `<SyncInspector />` and `<BenchmarkModal />` (from `local-lite/devtools`): Developer UI debugging tools
66
- 12. **[Authentication (Google, Microsoft, GitHub, Apple)](./auth.md)**
67
- - Zero-backend OAuth 2.0 PKCE authentication
68
- - Automatic token refreshing & user profile fetching
69
- - Microsoft Graph & OneDrive integration
70
- - GitHub OAuth with verified email resolution
71
- - Sign in with Apple (Native iOS & OAuth)
72
- - Pluggable storage adapters (AsyncStorage, SecureStore, MMKV)
73
- 13. **[Google Sign-In & Drive Guide](./google-auth.md)**
74
- - Dedicated guide for zero-backend Google authentication
75
- - Unified Google Drive cloud backup synergy
76
- 14. **[Conflict Resolution & Field Merge](./conflict-resolution.md)**
77
- - Smart 3-Way field-level merge (`createFieldMergeResolver`)
78
- - Last-Write-Wins (LWW)
79
- - Client-Wins & Server-Wins
80
- - Custom conflict resolvers
81
- 15. **[Database Backups & Zero-Knowledge Encryption](./backups.md)**
82
- - Google Drive and Microsoft OneDrive sandboxed backups
83
- - Zero-Knowledge client-side encryption (AES-256-GCM + PBKDF2)
84
- - React backup hooks (`useGoogleDriveBackup`, `useOneDriveBackup`)
85
- - Universal binary database snapshots (`exportDatabase`, `importDatabase`)
86
- 16. **[Maintenance & Data Portability](./maintenance-portability.md)**
87
- - Storage breakdown, outbox pruning, VACUUM, and WAL checkpoints
88
- - PRAGMA analyze and structural integrity checks
89
- - Universal JSON & RFC-4180 CSV export and import
90
- 17. **[Action Outbox & Email Queue](./actions-email.md)**
91
- - 0ms offline transactional email enqueuing
92
- - Generic action dispatchers (push notifications, webhooks, analytics)
93
- - Idempotency deduplication, TTL expiration, and crash recovery
94
- 18. **[API Keys & Signed Tokens](./api-keys.md)**
95
- - Checksummed API key generation & verification (Stripe/GitHub pattern)
96
- - HMAC-SHA256 signed tokens with expiration and renewal
97
- - Local SQLite API key manager (`client.keys`)
98
-
99
- ---
100
-
101
- ## 💡 Core Philosophy
102
-
103
- * **Local-First By Default:** The app writes to and reads from local SQLite first. Operations never stall on slow cell connections or outages.
104
- * **Guaranteed Durability:** Every mutate operation executes in an atomic transaction that updates the user table and inserts a mutation into `sync_outbox` simultaneously. If the device restarts or loses power, pending changes are never lost.
105
- * **Zero Lock-In:** Switch seamlessly between Supabase, Convex, Firestore, or your own REST/GraphQL server without rewriting your UI layer.
106
- 5. **[Server API Routing](./server.md)**
107
- - Create server route handlers from one typed config
108
- - Add middleware and use provider-specific server services
package/docs/_sidebar.md DELETED
@@ -1,22 +0,0 @@
1
- * [🏠 Home](README.md)
2
- * [🚀 Getting Started](getting-started.md)
3
- * [🏛️ Architecture & Concepts](architecture.md)
4
- * [⚙️ Configuration](configuration.md)
5
- * [⚠️ Breaking Changes](breaking-changes.md)
6
- * [💻 Client API & Query Builder](client-api.md)
7
- * [⚡ Fast Key-Value & Preferences](kv.md)
8
- * [🔍 Full-Text Search (FTS5)](search.md)
9
- * [📁 Offline Media & Blob Storage](storage.md)
10
- * [⏰ Offline Job Scheduler & Cron](scheduler.md)
11
- * [📨 Action Outbox & Email Queue](actions-email.md)
12
- * [💾 Local SQLite Adapters](adapters-local.md)
13
- * [☁️ Remote Cloud Adapters](adapters-remote.md)
14
- * [⚛️ React & Expo Hooks](react-hooks.md)
15
- * [🔑 Authentication (Google, Microsoft, GitHub, Apple)](auth.md)
16
- * [🛡️ Offline Session Management](session.md)
17
- * [🔐 API Keys & Signed Tokens](api-keys.md)
18
- * [🌐 Google Sign-In & Drive Guide](google-auth.md)
19
- * [🔀 Conflict Resolution & Field Merge](conflict-resolution.md)
20
- * [📦 Cloud Backups & Zero-Knowledge Encryption](backups.md)
21
- * [🧹 Maintenance & Universal Data Portability](maintenance-portability.md)
22
- * [Server API Routing](server.md)
@@ -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
- ```
@@ -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.