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/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.
|
package/docs/session.md
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
# Offline-First Session Management (`client.session` & `useSession`)
|
|
2
|
-
|
|
3
|
-
In traditional web applications, authentication depends on continuous pings to a remote authorization server. When the device loses internet connectivity, token refresh calls fail, causing apps to mistakenly clear the session and boot users back to the login screen.
|
|
4
|
-
|
|
5
|
-
`local-lite` provides **persistent, offline-first session management** in SQLite (`_local_sessions`), ensuring authenticated users stay logged in and productive even when completely offline.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## Features
|
|
10
|
-
|
|
11
|
-
- **Persistent SQLite Storage**: Session metadata, user profiles, permissions, and tokens are stored in `_local_sessions`.
|
|
12
|
-
- **Offline Grace Period**: Configurable offline access duration (default: 30 days, or unlimited). If server tokens expire while offline, the local session remains valid and active until connectivity is restored.
|
|
13
|
-
- **Multi-Account Switching**: Store and switch between multiple user profiles or organizations without signing out.
|
|
14
|
-
- **Provider Agnostic**: Works with **Google**, **Microsoft**, **GitHub**, **Apple**, **Supabase Auth**, **Firebase Auth**, or custom JWT/password backends.
|
|
15
|
-
- **Reactive React Hook (`useSession`)**: Component state updates automatically on session creation, profile updates, account switches, or sign out.
|
|
16
|
-
|
|
17
|
-
---
|
|
18
|
-
|
|
19
|
-
## Basic Usage
|
|
20
|
-
|
|
21
|
-
### 1. Creating a Session (on Sign-In)
|
|
22
|
-
|
|
23
|
-
When your user signs in (via OAuth, email/password, biometric PIN, or Supabase Auth):
|
|
24
|
-
|
|
25
|
-
```typescript
|
|
26
|
-
// Create and persist active session
|
|
27
|
-
await client.session.createSession({
|
|
28
|
-
userId: 'usr_123',
|
|
29
|
-
user: {
|
|
30
|
-
id: 'usr_123',
|
|
31
|
-
name: 'Sarah Connor',
|
|
32
|
-
email: 'sarah@example.com',
|
|
33
|
-
role: 'ADMIN',
|
|
34
|
-
organizationId: 'org_omega',
|
|
35
|
-
},
|
|
36
|
-
token: 'jwt_access_token...',
|
|
37
|
-
refreshToken: 'refresh_token...',
|
|
38
|
-
provider: 'supabase', // or 'google', 'custom', etc.
|
|
39
|
-
offlineDurationMs: 30 * 24 * 60 * 60 * 1000, // 30-day offline access
|
|
40
|
-
});
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
---
|
|
44
|
-
|
|
45
|
-
### 2. Checking Authentication State
|
|
46
|
-
|
|
47
|
-
```typescript
|
|
48
|
-
// True both online AND offline:
|
|
49
|
-
const isAuthenticated = await client.session.isAuthenticated();
|
|
50
|
-
|
|
51
|
-
// Retrieve cached user profile offline:
|
|
52
|
-
const user = await client.session.getUser();
|
|
53
|
-
console.log(user?.name); // 'Sarah Connor'
|
|
54
|
-
|
|
55
|
-
// Retrieve active session record:
|
|
56
|
-
const session = await client.session.getActiveSession();
|
|
57
|
-
console.log(session?.lastActiveAt);
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
---
|
|
61
|
-
|
|
62
|
-
### 3. Updating User Profile & Tokens
|
|
63
|
-
|
|
64
|
-
```typescript
|
|
65
|
-
// Update user metadata in SQLite:
|
|
66
|
-
await client.session.updateUser({
|
|
67
|
-
role: 'SUPER_ADMIN',
|
|
68
|
-
avatarUrl: 'https://cdn.example.com/sarah.jpg',
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
// Update tokens after remote refresh:
|
|
72
|
-
await client.session.updateTokens({
|
|
73
|
-
token: 'new_access_token...',
|
|
74
|
-
expiresAt: Date.now() + 3600000,
|
|
75
|
-
});
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
---
|
|
79
|
-
|
|
80
|
-
### 4. Multi-Account Switching Offline
|
|
81
|
-
|
|
82
|
-
Switch between cached accounts without requiring a network round-trip:
|
|
83
|
-
|
|
84
|
-
```typescript
|
|
85
|
-
// List all accounts stored on device:
|
|
86
|
-
const sessions = await client.session.listSessions();
|
|
87
|
-
|
|
88
|
-
// Switch active user:
|
|
89
|
-
await client.session.switchSession('usr_456');
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
---
|
|
93
|
-
|
|
94
|
-
### 5. Signing Out
|
|
95
|
-
|
|
96
|
-
```typescript
|
|
97
|
-
await client.session.clearSession();
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
---
|
|
101
|
-
|
|
102
|
-
## React & Expo Integration (`useSession`)
|
|
103
|
-
|
|
104
|
-
Use the `useSession` hook in your React or Expo components:
|
|
105
|
-
|
|
106
|
-
```tsx
|
|
107
|
-
import React from 'react';
|
|
108
|
-
import { useSession } from 'local-lite/react';
|
|
109
|
-
|
|
110
|
-
export function UserHeader({ client }) {
|
|
111
|
-
const { user, isAuthenticated, isOffline, signOut } = useSession(client);
|
|
112
|
-
|
|
113
|
-
if (!isAuthenticated) {
|
|
114
|
-
return <p>Please sign in</p>;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
return (
|
|
118
|
-
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
|
119
|
-
<span>Welcome, {user.name}!</span>
|
|
120
|
-
{isOffline && (
|
|
121
|
-
<span style={{ color: 'orange', fontSize: '12px' }}>
|
|
122
|
-
(Offline Mode - Active Session)
|
|
123
|
-
</span>
|
|
124
|
-
)}
|
|
125
|
-
<button onClick={signOut}>Sign Out</button>
|
|
126
|
-
</div>
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
```
|
package/docs/storage.md
DELETED
|
@@ -1,265 +0,0 @@
|
|
|
1
|
-
# Offline Media & Blob Storage (`client.storage`)
|
|
2
|
-
|
|
3
|
-
In local-first applications, large files like inspection photos, tenant contracts, audio recordings, and PDF documents should never bloat your SQLite queries or database caches. `client.storage` keeps binary files efficiently on disk (or in-memory / cache) while tracking rich metadata and offline sync states in SQLite (`_local_blobs`).
|
|
4
|
-
|
|
5
|
-
`local-lite` supports **Supabase Storage**, **Convex File Storage**, and **Firebase Cloud Storage** out of the box.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## Features
|
|
10
|
-
|
|
11
|
-
- **Decoupled Architecture**: Separates heavy binary payloads from SQLite table scans.
|
|
12
|
-
- **Integrity Checksums**: Auto-computes SHA-256 digests to ensure binary integrity and prevent duplicates.
|
|
13
|
-
- **Pluggable Local Drivers**: `MemoryFileDriver` (testing & web), `NodeFileDriver` (Node.js filesystem), and `ExpoFileDriver` (Expo & React Native filesystem).
|
|
14
|
-
- **Out-of-the-Box Cloud Uploaders**:
|
|
15
|
-
- ⚡ **Supabase Storage**: Buckets, public URLs, and signed URLs.
|
|
16
|
-
- 🌐 **Convex File Storage**: `generateUploadUrl`, POST upload, `storageId`, and reactive serving queries.
|
|
17
|
-
- 🔥 **Firebase Cloud Storage**: Modular v9+ SDK & compat SDK, custom metadata, and download URLs.
|
|
18
|
-
- **Auto-Wiring**: Pass `bucket` or `uploadMutation` to `client.storage` and local-lite automatically connects to your active remote database adapter.
|
|
19
|
-
- **Mobile-Ready**: Direct URI resolution (`file://`) and zero-memory-leak local file import (`saveFromUri`) from `expo-image-picker` or `expo-document-picker`.
|
|
20
|
-
|
|
21
|
-
`ExpoFileDriver` requires Expo SDK 58 or newer and the modern `File`, `Directory`,
|
|
22
|
-
and `Paths` APIs from `expo-file-system`. Older `FileSystem` module APIs and the
|
|
23
|
-
`fileSystem` constructor option are no longer supported.
|
|
24
|
-
|
|
25
|
-
---
|
|
26
|
-
|
|
27
|
-
## 1. Supabase Storage Setup
|
|
28
|
-
|
|
29
|
-
```typescript
|
|
30
|
-
import { SupabaseAdapter } from 'local-lite/supabase';
|
|
31
|
-
import { ExpoFileDriver } from 'local-lite/storage';
|
|
32
|
-
import { File, Directory, Paths } from 'expo-file-system';
|
|
33
|
-
|
|
34
|
-
const remote = new SupabaseAdapter(supabaseClient, {
|
|
35
|
-
tables: ['properties', 'units'],
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
const client = new LocalLiteClient({
|
|
39
|
-
db: new ExpoSQLiteAdapter(expoDb),
|
|
40
|
-
remote,
|
|
41
|
-
storage: {
|
|
42
|
-
driver: new ExpoFileDriver({ File, Directory, Paths }),
|
|
43
|
-
// Explicit uploader:
|
|
44
|
-
uploader: remote.createStorageUploader({
|
|
45
|
-
bucket: 'property-photos',
|
|
46
|
-
urlType: 'public', // or 'signed'
|
|
47
|
-
upsert: true,
|
|
48
|
-
}),
|
|
49
|
-
// Or auto-wired: simply pass bucket: 'property-photos'
|
|
50
|
-
},
|
|
51
|
-
});
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
---
|
|
55
|
-
|
|
56
|
-
## 2. Convex File Storage Setup
|
|
57
|
-
|
|
58
|
-
```typescript
|
|
59
|
-
import { ConvexRemoteAdapter } from 'local-lite/convex';
|
|
60
|
-
import { ExpoFileDriver } from 'local-lite/storage';
|
|
61
|
-
import { api } from '../convex/_generated/api';
|
|
62
|
-
|
|
63
|
-
const remote = new ConvexRemoteAdapter(convexClient, {
|
|
64
|
-
tables: ['messages', 'documents'],
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
const client = new LocalLiteClient({
|
|
68
|
-
db: new ExpoSQLiteAdapter(expoDb),
|
|
69
|
-
remote,
|
|
70
|
-
storage: {
|
|
71
|
-
driver: new ExpoFileDriver({ File, Directory, Paths }),
|
|
72
|
-
// Explicit uploader:
|
|
73
|
-
uploader: remote.createStorageUploader({
|
|
74
|
-
uploadMutation: api.files.generateUploadUrl, // or 'sync:generateUploadUrl'
|
|
75
|
-
getUrlQuery: api.files.getUrl, // optional query resolving storageId -> serving URL
|
|
76
|
-
saveFileMutation: api.files.saveFile, // optional metadata persistence
|
|
77
|
-
}),
|
|
78
|
-
},
|
|
79
|
-
});
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
---
|
|
83
|
-
|
|
84
|
-
## 3. Firebase Cloud Storage Setup
|
|
85
|
-
|
|
86
|
-
Works seamlessly with modular (`firebase/storage`) and compat SDKs:
|
|
87
|
-
|
|
88
|
-
```typescript
|
|
89
|
-
import { FirestoreAdapter } from 'local-lite/firebase';
|
|
90
|
-
import { ExpoFileDriver } from 'local-lite/storage';
|
|
91
|
-
import * as storageModule from 'firebase/storage';
|
|
92
|
-
|
|
93
|
-
const remote = new FirestoreAdapter(firestoreDb, {
|
|
94
|
-
tables: ['properties', 'tenants'],
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
const client = new LocalLiteClient({
|
|
98
|
-
db: new ExpoSQLiteAdapter(expoDb),
|
|
99
|
-
remote,
|
|
100
|
-
storage: {
|
|
101
|
-
driver: new ExpoFileDriver({ File, Directory, Paths }),
|
|
102
|
-
// Explicit uploader:
|
|
103
|
-
uploader: remote.createStorageUploader({
|
|
104
|
-
basePath: 'property-media',
|
|
105
|
-
storageModule, // pass modular SDK { ref, uploadBytes, getDownloadURL }
|
|
106
|
-
cacheControl: 'public, max-age=31536000',
|
|
107
|
-
}),
|
|
108
|
-
},
|
|
109
|
-
});
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
---
|
|
113
|
-
|
|
114
|
-
## Universal Factory: `createStorageUploader`
|
|
115
|
-
|
|
116
|
-
If creating uploaders standalone without `remote` adapter:
|
|
117
|
-
|
|
118
|
-
```typescript
|
|
119
|
-
import { createStorageUploader } from 'local-lite/storage';
|
|
120
|
-
|
|
121
|
-
// Supabase
|
|
122
|
-
const supabaseUploader = createStorageUploader('supabase', supabaseClient, {
|
|
123
|
-
bucket: 'avatars',
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
// Convex
|
|
127
|
-
const convexUploader = createStorageUploader('convex', convexClient, {
|
|
128
|
-
uploadMutation: api.files.generateUploadUrl,
|
|
129
|
-
getUrlQuery: api.files.getUrl,
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
// Firebase
|
|
133
|
-
const firebaseUploader = createStorageUploader('firebase', firebaseStorage, {
|
|
134
|
-
basePath: 'documents',
|
|
135
|
-
});
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
---
|
|
139
|
-
|
|
140
|
-
## Direct Mobile Camera / Picker Import (`saveFromUri`)
|
|
141
|
-
|
|
142
|
-
When a user captures a photo or picks a document using `expo-image-picker` or `expo-document-picker`, avoid reading large byte arrays into JavaScript memory. Use `saveFromUri`:
|
|
143
|
-
|
|
144
|
-
```typescript
|
|
145
|
-
import * as ImagePicker from 'expo-image-picker';
|
|
146
|
-
|
|
147
|
-
const result = await ImagePicker.launchImageLibraryAsync({
|
|
148
|
-
mediaTypes: ImagePicker.MediaTypeOptions.Images,
|
|
149
|
-
quality: 0.8,
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
if (!result.canceled && result.assets[0]) {
|
|
153
|
-
const asset = result.assets[0];
|
|
154
|
-
|
|
155
|
-
// Directly copies the file without JS memory overhead and queues for cloud upload
|
|
156
|
-
const record = await client.storage.saveFromUri(
|
|
157
|
-
`properties/${propertyId}/hero.jpg`,
|
|
158
|
-
asset.uri,
|
|
159
|
-
{
|
|
160
|
-
name: 'hero.jpg',
|
|
161
|
-
mimeType: 'image/jpeg',
|
|
162
|
-
metadata: { propertyId },
|
|
163
|
-
}
|
|
164
|
-
);
|
|
165
|
-
|
|
166
|
-
console.log('Saved to local storage at:', record.localPath);
|
|
167
|
-
console.log('Remote Cloud URL (if online):', record.remoteUrl);
|
|
168
|
-
}
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
---
|
|
172
|
-
|
|
173
|
-
## Displaying in React Native (`getLocalUri`)
|
|
174
|
-
|
|
175
|
-
To render a locally stored image in React Native `<Image />` without reading bytes into memory:
|
|
176
|
-
|
|
177
|
-
```tsx
|
|
178
|
-
import React, { useEffect, useState } from 'react';
|
|
179
|
-
import { Image, View } from 'react-native';
|
|
180
|
-
|
|
181
|
-
export function PropertyHeroImage({ imageKey }: { imageKey: string }) {
|
|
182
|
-
const [uri, setUri] = useState<string | null>(null);
|
|
183
|
-
|
|
184
|
-
useEffect(() => {
|
|
185
|
-
client.storage.getLocalUri(imageKey).then(setUri);
|
|
186
|
-
}, [imageKey]);
|
|
187
|
-
|
|
188
|
-
if (!uri) return null;
|
|
189
|
-
|
|
190
|
-
return <Image source={{ uri }} style={{ width: 300, height: 200, borderRadius: 8 }} />;
|
|
191
|
-
}
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
---
|
|
195
|
-
|
|
196
|
-
## Saving Raw Bytes Offline
|
|
197
|
-
|
|
198
|
-
```typescript
|
|
199
|
-
const imageBytes = new Uint8Array([...]);
|
|
200
|
-
|
|
201
|
-
const record = await client.storage.save('inspections/kitchen-1.jpg', imageBytes, {
|
|
202
|
-
name: 'kitchen-1.jpg',
|
|
203
|
-
mimeType: 'image/jpeg',
|
|
204
|
-
metadata: { unitId: 'unit-4b', inspectionId: 'insp-123' },
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
console.log(record.id); // Unique blob UUID
|
|
208
|
-
console.log(record.sha256); // Hex SHA-256 hash
|
|
209
|
-
console.log(record.size); // File size in bytes
|
|
210
|
-
console.log(record.status); // 'PENDING' (or 'UPLOADED' if online)
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
---
|
|
214
|
-
|
|
215
|
-
## Retrieving and Deleting Files
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
// Get metadata and raw binary data
|
|
219
|
-
const result = await client.storage.get('inspections/kitchen-1.jpg');
|
|
220
|
-
if (result) {
|
|
221
|
-
const { record, data } = result;
|
|
222
|
-
console.log(`Loaded ${record.name} (${data.byteLength} bytes)`);
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Get only raw bytes
|
|
226
|
-
const bytes = await client.storage.getData('inspections/kitchen-1.jpg');
|
|
227
|
-
|
|
228
|
-
// Get remote URL
|
|
229
|
-
const url = await client.storage.getDownloadUrl('inspections/kitchen-1.jpg');
|
|
230
|
-
|
|
231
|
-
// Delete file locally (and optionally remotely if deleteRemoteOnDelete is true)
|
|
232
|
-
await client.storage.delete('inspections/kitchen-1.jpg');
|
|
233
|
-
```
|
|
234
|
-
|
|
235
|
-
---
|
|
236
|
-
|
|
237
|
-
## Provider Options Reference
|
|
238
|
-
|
|
239
|
-
### Supabase Storage Options
|
|
240
|
-
| Option | Type | Default | Description |
|
|
241
|
-
|---|---|---|---|
|
|
242
|
-
| `bucket` | `string` | *(required)* | Name of the Supabase Storage bucket |
|
|
243
|
-
| `upsert` | `boolean` | `true` | Overwrites files with identical remote path |
|
|
244
|
-
| `urlType` | `'public' \| 'signed'` | `'public'` | Uses `getPublicUrl` or `createSignedUrl` |
|
|
245
|
-
| `signedUrlExpiresIn` | `number` | `86400` | Expiration in seconds for signed URLs |
|
|
246
|
-
| `pathTransform` | `(key, blob) => string` | `identity` | Custom mapping from local key to bucket path |
|
|
247
|
-
| `cacheControl` | `string` | `undefined` | Cache-Control HTTP header |
|
|
248
|
-
|
|
249
|
-
### Convex File Storage Options
|
|
250
|
-
| Option | Type | Default | Description |
|
|
251
|
-
|---|---|---|---|
|
|
252
|
-
| `uploadMutation` | `any` | `'sync:generateUploadUrl'` | Mutation reference or name generating upload URL |
|
|
253
|
-
| `uploadMutationArgs` | `object \| fn` | `{}` | Optional arguments for upload mutation |
|
|
254
|
-
| `getUrlQuery` | `any` | `undefined` | Optional query resolving `storageId` to serving URL |
|
|
255
|
-
| `saveFileMutation` | `any` | `undefined` | Optional mutation called to link file to Convex schema |
|
|
256
|
-
| `deleteMutation` | `any` | `undefined` | Optional mutation called when deleting from Convex |
|
|
257
|
-
|
|
258
|
-
### Firebase Cloud Storage Options
|
|
259
|
-
| Option | Type | Default | Description |
|
|
260
|
-
|---|---|---|---|
|
|
261
|
-
| `bucket` | `string` | `undefined` | Optional bucket name / gs:// URI |
|
|
262
|
-
| `basePath` | `string` | `undefined` | Prefix path inside bucket (e.g. `'uploads'`) |
|
|
263
|
-
| `storageModule` | `object` | `undefined` | Modular Firebase SDK (`{ ref, uploadBytes, getDownloadURL, deleteObject }`) |
|
|
264
|
-
| `customMetadata` | `object \| fn` | `undefined` | Custom metadata attached to storage object |
|
|
265
|
-
| `cacheControl` | `string` | `undefined` | Cache-Control HTTP header |
|