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
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 |