local-lite 0.1.4 → 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.
Files changed (48) hide show
  1. package/README.md +5 -2
  2. package/bin/local-lite.mjs +65 -61
  3. package/dist/auth/apple.d.ts +3 -4
  4. package/dist/auth/apple.js +26 -3
  5. package/dist/auth/github.d.ts +3 -5
  6. package/dist/auth/github.js +18 -4
  7. package/dist/auth/google.d.ts +3 -6
  8. package/dist/auth/google.js +19 -5
  9. package/dist/auth/identity.d.ts +42 -0
  10. package/dist/auth/identity.js +63 -0
  11. package/dist/auth/index.d.ts +2 -0
  12. package/dist/auth/index.js +2 -0
  13. package/dist/auth/local.d.ts +33 -1
  14. package/dist/auth/local.js +94 -13
  15. package/dist/auth/microsoft.d.ts +3 -5
  16. package/dist/auth/microsoft.js +16 -3
  17. package/dist/auth/session.d.ts +4 -0
  18. package/dist/auth/session.js +19 -1
  19. package/dist/auth/unified.d.ts +73 -0
  20. package/dist/auth/unified.js +188 -0
  21. package/package.json +1 -2
  22. package/skills/local-lite-auth/SKILL.md +67 -27
  23. package/skills/local-lite-server/SKILL.md +127 -0
  24. package/docs/.nojekyll +0 -1
  25. package/docs/README.md +0 -108
  26. package/docs/_sidebar.md +0 -22
  27. package/docs/actions-email.md +0 -222
  28. package/docs/adapters-local.md +0 -272
  29. package/docs/adapters-remote.md +0 -291
  30. package/docs/api-keys.md +0 -114
  31. package/docs/architecture.md +0 -106
  32. package/docs/auth.md +0 -342
  33. package/docs/backups.md +0 -214
  34. package/docs/breaking-changes.md +0 -147
  35. package/docs/client-api.md +0 -412
  36. package/docs/configuration.md +0 -228
  37. package/docs/conflict-resolution.md +0 -78
  38. package/docs/getting-started.md +0 -190
  39. package/docs/google-auth.md +0 -234
  40. package/docs/index.html +0 -166
  41. package/docs/kv.md +0 -89
  42. package/docs/maintenance-portability.md +0 -133
  43. package/docs/react-hooks.md +0 -457
  44. package/docs/scheduler.md +0 -81
  45. package/docs/search.md +0 -71
  46. package/docs/server.md +0 -101
  47. package/docs/session.md +0 -129
  48. package/docs/storage.md +0 -265
@@ -1,457 +0,0 @@
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.
package/docs/scheduler.md DELETED
@@ -1,81 +0,0 @@
1
- # Offline Job Scheduler & Background Cron (`client.scheduler`)
2
-
3
- Local-first applications need to run background maintenance, compute recurring reminders, check rent due dates, and prune expired tokens even when completely offline. `client.scheduler` provides a persistent, offline-first cron and periodic task runner.
4
-
5
- ---
6
-
7
- ## Features
8
-
9
- - **Persistent Job Registry**: Registered tasks and next-run timestamps survive app restarts in `_local_scheduled_jobs`.
10
- - **Run History & Telemetry**: Logs each execution in `_local_job_runs` with start/finish timestamps, durations, and error traces.
11
- - **Human & Standard Cron Schedules**: Supports `'daily'`, `'hourly'`, `'every 15 minutes'`, standard 5-part cron expressions (`*/15 * * * *`), or millisecond intervals.
12
- - **Automatic Ticker**: Background interval runs tasks as they become due without blocking the main event loop.
13
-
14
- ---
15
-
16
- ## Registering Jobs
17
-
18
- ```typescript
19
- // Register a daily database maintenance task
20
- await client.scheduler.register({
21
- id: 'daily-maintenance',
22
- name: 'Database Vacuum & Pruning',
23
- schedule: 'daily',
24
- handler: async (job) => {
25
- await client.maintenance.vacuum();
26
- await client.kv.pruneExpired();
27
- },
28
- });
29
-
30
- // Register an hourly backup job
31
- await client.scheduler.register({
32
- id: 'hourly-backup',
33
- schedule: 'every 1 hour',
34
- handler: async () => {
35
- console.log('Running hourly client backup...');
36
- },
37
- });
38
-
39
- // Standard 5-field cron: every 15 minutes
40
- await client.scheduler.register({
41
- id: 'sync-audit',
42
- schedule: '*/15 * * * *',
43
- handler: async () => {
44
- await client.sync();
45
- },
46
- });
47
- ```
48
-
49
- ---
50
-
51
- ## Starting the Scheduler
52
-
53
- ```typescript
54
- // Start the scheduler loop (checks every 30 seconds by default)
55
- client.scheduler.start();
56
-
57
- // Or configure explicit check interval
58
- client.scheduler.start(10000); // 10 seconds
59
-
60
- // Stop scheduler when closing or unmounting
61
- client.scheduler.stop();
62
- ```
63
-
64
- ---
65
-
66
- ## Manual Execution & History
67
-
68
- ```typescript
69
- // Force trigger a job immediately
70
- const run = await client.scheduler.trigger('daily-maintenance');
71
- console.log(`Status: ${run.status}, Duration: ${run.durationMs}ms`);
72
-
73
- // Inspect execution history
74
- const history = await client.scheduler.getHistory('daily-maintenance', 20);
75
- for (const entry of history) {
76
- console.log(`[${new Date(entry.startedAt).toISOString()}] ${entry.status} (${entry.durationMs}ms)`);
77
- }
78
-
79
- // Prune old history logs older than 7 days
80
- await client.scheduler.pruneHistory(7 * 24 * 60 * 60 * 1000);
81
- ```
package/docs/search.md DELETED
@@ -1,71 +0,0 @@
1
- # Instant Full-Text Search (`client.search`)
2
-
3
- `local-lite` provides high-performance Full-Text Search (FTS5) for your local tables. Search through thousands of property listings, tenant notes, documents, and messages offline in milliseconds with BM25 ranking and keyword highlighting snippets.
4
-
5
- ---
6
-
7
- ## Features
8
-
9
- - **SQLite FTS5 Native Engine**: Fast text indexing with Porter stemming and Unicode tokenizers.
10
- - **Prefix & Multi-term Match**: Type-ahead search (`"apart"*`, `"luxury villa"*`).
11
- - **Highlight Snippets**: Automatic `<mark>` match highlighting.
12
- - **Auto-Sync Hooks**: Seamlessly updates search indices whenever `client.mutate()` or reactive writes occur.
13
- - **Hydration**: Returns matched `rowId`, relevance `rank`, and the complete hydrated table row.
14
-
15
- ---
16
-
17
- ## Creating an Index
18
-
19
- Create an FTS index on any table:
20
-
21
- ```typescript
22
- await client.search.createIndex({
23
- table: 'properties',
24
- columns: ['title', 'address', 'description'],
25
- tokenize: 'unicode61', // optional, defaults to 'unicode61'
26
- });
27
- ```
28
-
29
- ---
30
-
31
- ## Querying
32
-
33
- ```typescript
34
- // Instant full-text search
35
- const results = await client.search.query('properties', 'beachfront pool', {
36
- limit: 20,
37
- highlight: true,
38
- hydrateRow: true, // attaches base table row in .data
39
- });
40
-
41
- for (const match of results) {
42
- console.log(`ID: ${match.rowId}`);
43
- console.log(`Rank: ${match.rank}`);
44
- console.log(`Snippet: ${match.snippet}`);
45
- console.log(`Title: ${match.data.title}`);
46
- }
47
- ```
48
-
49
- ---
50
-
51
- ## Manual Index Management
52
-
53
- When syncing or importing data in bulk:
54
-
55
- ```typescript
56
- // Index single record manually
57
- await client.search.indexRecord('properties', 'prop-1', {
58
- title: 'Penthouse Apartment',
59
- address: '101 Skyline Ave',
60
- });
61
-
62
- // Remove from search index
63
- await client.search.removeRecord('properties', 'prop-1');
64
-
65
- // Rebuild index from existing database records
66
- const properties = await client.findMany('properties');
67
- await client.search.rebuildIndex('properties', properties);
68
-
69
- // Drop search index
70
- await client.search.dropIndex('properties');
71
- ```
package/docs/server.md DELETED
@@ -1,101 +0,0 @@
1
- # Server API Routing
2
-
3
- `local-lite/server` creates framework-neutral `Request`/`Response` API handlers from one server configuration. Define route paths, methods, app services, and optional middleware once, then export generated handlers from your framework's route files or use the single `fetch()` dispatcher.
4
-
5
- The server module does not choose or create a database client. Pass server-side services for the configured backend (for example, a Supabase or Convex adapter) through `config`. Keep provider selection consistent with the backend used by `local-lite` sync. Never pass a device's SQLite client or mobile-only configuration to a server handler.
6
-
7
- ## Define server configuration
8
-
9
- ```ts
10
- // src/server/api.ts
11
- import { createServer, defineServerConfig } from 'local-lite/server';
12
-
13
- interface AppServerConfig {
14
- bookings: {
15
- create(input: Record<string, unknown>): Promise<{ id: string }>;
16
- get(id: string): Promise<Record<string, unknown> | null>;
17
- };
18
- verifyApiKey(request: Request): Promise<boolean>;
19
- }
20
-
21
- const config = defineServerConfig<AppServerConfig>({
22
- // Inject backend-specific server services. Keep secrets on the server.
23
- config: createConfiguredBackendServices(),
24
- middleware: [async ({ request, config }, next) => {
25
- if (!await config.verifyApiKey(request)) {
26
- return Response.json({ error: 'Unauthorized' }, { status: 401 });
27
- }
28
- return next();
29
- }],
30
- endpoints: {
31
- '/api/bookings': {
32
- POST: async ({ request, config }) => {
33
- const input = await request.json();
34
- const booking = await config.bookings.create(input);
35
- return Response.json({ success: true, ...booking }, { status: 201 });
36
- },
37
- },
38
- '/api/bookings/:bookingId': {
39
- GET: async ({ params, config }) => {
40
- const booking = await config.bookings.get(params.bookingId);
41
- if (!booking) return Response.json({ error: 'Not Found' }, { status: 404 });
42
- return Response.json(booking);
43
- },
44
- },
45
- },
46
- onError(error, context) {
47
- // Report details to server logs/telemetry; responses remain generic.
48
- console.error('API request failed', context.path, error);
49
- },
50
- });
51
-
52
- export const apiServer = createServer(config);
53
- ```
54
-
55
- `createConfiguredBackendServices()` above is app-owned: it should select the server adapter using the same explicit provider setting as sync and provide only the operations the routes need. Do not silently fall back to another backend when the selected provider is unavailable.
56
-
57
- ## Export generated handlers from route files
58
-
59
- A framework route can export a generated handler for its method and path:
60
-
61
- ```ts
62
- // app/api/bookings/index+api.ts (Expo Router API route)
63
- import { apiServer } from '@/server/api';
64
-
65
- export const POST = apiServer.handler('/api/bookings', 'POST');
66
- ```
67
-
68
- ```ts
69
- // app/api/bookings/[bookingId]+api.ts
70
- import { apiServer } from '@/server/api';
71
-
72
- export const GET = apiServer.handler('/api/bookings/:bookingId', 'GET');
73
- ```
74
-
75
- `handler(path, method)` throws during setup if that endpoint is not configured, so route configuration mistakes are caught early. Generated handlers receive the original `Request`; dynamic path segments are decoded into `params`.
76
-
77
- ## Use a single dispatcher
78
-
79
- For a server runtime that mounts one catch-all handler, `fetch()` matches the URL path and method against the configured routes:
80
-
81
- ```ts
82
- import { apiServer } from './api';
83
-
84
- export const GET = (request: Request) => apiServer.fetch(request);
85
- export const POST = (request: Request) => apiServer.fetch(request);
86
- ```
87
-
88
- Unknown paths return `404`; paths with no configured method return `405` and an `Allow` header. Unhandled endpoint or middleware errors are reported to `onError` and return a generic `500` response.
89
-
90
- ## Middleware
91
-
92
- Middleware runs in declaration order and can authenticate, add request-level checks, or short-circuit with a response. Call `next()` exactly once to continue. Put route-specific authorization and input validation in the endpoint or a narrowly scoped middleware; registering an endpoint does not itself grant access to its data.
93
-
94
- ## API reference
95
-
96
- - `defineServerConfig(config)` validates the endpoint map and preserves its configuration type.
97
- - `createServer(config)` returns `handlers`, `handler(path, method)`, and `fetch(request)`.
98
- - Endpoint context contains `request`, `config`, normalized `path`, and decoded `params`.
99
- - Supported methods: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS`.
100
-
101
- The package centralizes route registration and handler generation. Apps still define their endpoint behavior, authorization rules, provider adapters, and response contracts.