local-lite 2.0.4 → 2.0.6

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 (39) hide show
  1. package/README.md +2 -2
  2. package/bin/local-lite.mjs +215 -2
  3. package/dist/auth/apple.js +1 -1
  4. package/dist/auth/github.js +1 -1
  5. package/dist/auth/google.js +1 -12
  6. package/dist/auth/local.js +2 -25
  7. package/dist/auth/microsoft.js +1 -12
  8. package/dist/backups/cloud-storage.js +1 -12
  9. package/dist/core/client.d.ts +3 -3
  10. package/dist/core/client.js +6 -6
  11. package/dist/devtools/BenchmarkModal.js +16 -37
  12. package/dist/devtools/SyncInspector.js +11 -43
  13. package/dist/devtools/shared.d.ts +25 -0
  14. package/dist/devtools/shared.js +39 -0
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/kv-store/index.d.ts +3 -0
  18. package/dist/kv-store/index.js +19 -0
  19. package/dist/kv-store/manager.d.ts +52 -0
  20. package/dist/kv-store/manager.js +167 -0
  21. package/dist/kv-store/store.d.ts +13 -0
  22. package/dist/kv-store/store.js +85 -0
  23. package/dist/kv-store/types.d.ts +27 -0
  24. package/dist/kv-store/types.js +2 -0
  25. package/dist/react/index.d.ts +1 -1
  26. package/dist/react/index.js +1 -1
  27. package/dist/react/kv-store.d.ts +9 -0
  28. package/dist/react/kv-store.js +53 -0
  29. package/dist/schema/index.d.ts +0 -1
  30. package/dist/schema/index.js +0 -1
  31. package/dist/server/dashboard.d.ts +16 -0
  32. package/dist/server/dashboard.js +1364 -0
  33. package/dist/server/index.d.ts +1 -0
  34. package/dist/server/index.js +1 -0
  35. package/dist/utils/oauth.d.ts +9 -0
  36. package/dist/utils/oauth.js +18 -0
  37. package/package.json +10 -5
  38. package/skills/local-lite-offline-actions/SKILL.md +11 -11
  39. package/skills/local-lite-react/SKILL.md +7 -7
package/README.md CHANGED
@@ -101,7 +101,7 @@ The package ships [Agent Skills](./skills) that AI coding assistants can load:
101
101
  * `local-lite-backups`: Cloud backups (OneDrive, Google Drive), AES-256-GCM database encryption, and restore.
102
102
  * `local-lite-schema`: Declarative cascading deletions (`onDelete`), append-only migrations, and FTS5 search.
103
103
  * `local-lite-storage`: Blob and file management, ExpoFileDriver, and cloud storage bucket sync.
104
- * `local-lite-react`: Reactive hooks (`useLiveQuery`, `useSyncStatus`, `useLocalAuth`, `useKV`), and 0ms optimistic writes.
104
+ * `local-lite-react`: Reactive hooks (`useLiveQuery`, `useSyncStatus`, `useLocalAuth`, `useKVStore`), and 0ms optimistic writes.
105
105
  * `local-lite-offline-actions`: Queued mutation outbox, encrypted secret preferences, and background scheduler.
106
106
  * `local-lite-custom-adapter`: Implementing custom REST, GraphQL, or WebSocket remote database adapters.
107
107
  * `local-lite-upgrade`: Migration checklist and breaking change reviews across version upgrades.
@@ -135,7 +135,7 @@ This recovers sync state; it does not repair corrupt SQLite files or cancel hung
135
135
  * **🔑 Google Sign-In Out of the Box:** Secure, zero-backend Google OAuth 2.0 (PKCE) authentication with automatic token refresh, user profile retrieval, persistent session storage, and `useGoogleAuth()` hook.
136
136
  * **📨 Action Outbox & Direct Email:** Enqueue transactional emails offline with 0ms local latency. Send directly via Nodemailer SMTP, Resend, SendGrid, Postmark, or Dev Mailbox. Full support for React Email JSX, auto-hydrating mobile `file://` attachments, rate limiting, and type-safe contracts (`defineAction`).
137
137
  * **🌐 Turnkey Server Endpoints (`local-lite/server`):** Mount self-hosted sync (`createSyncEndpoint`) and secure email relay (`createEmailEndpoint`) endpoints in 1 line of code for Next.js, Express, Fastify, or Node http.
138
- * **⚡ Fast Key-Value & Encrypted Preferences (`client.kv`):** Typed storage, TTL expiration, and AES-256-GCM zero-knowledge secret protection.
138
+ * **⚡ Fast Key-Value & Encrypted Preferences (`client.kvStore`):** Typed storage, TTL expiration, and AES-256-GCM zero-knowledge secret protection.
139
139
  * **🔍 Instant Full-Text Search (`client.search`):** SQLite FTS5 indexer with prefix matching, BM25 rank scoring, and highlighting.
140
140
  * **📁 Offline Media & Blob Storage (`client.storage`):** Decoupled binary attachments, SHA-256 verification, and cloud sync queue (S3/Supabase/Firebase).
141
141
  * **⏰ Offline Job Scheduler & Background Cron (`client.scheduler`):** Persistent background task runner supporting human schedules and 5-field cron.
@@ -19,10 +19,14 @@ const targets = {
19
19
  const usage = `Usage:
20
20
  local-lite install-skills [--target copilot|claude|antigravity|cursor|agent] [--dir <path>] [--force]
21
21
  local-lite db:generate --schema <path> [--tables <path>] [--out <dir>] [--name <name>] [--dialect mysql|postgres|sqlite] [--server-schema <path>] [--dry-run]
22
+ local-lite dashboard [--db <path>] [--port <number>] [--ui-port <number>] [--host <host>] [--readonly] [--token <secret>] [--title <title>] [--no-open] [--no-vite]
23
+ local-lite dev [--db <path>] [--port <number>] [--ui-port <number>] [--host <host>] [--readonly] [--token <secret>] [--title <title>] [--repo <owner/repo>] [--force] [--no-open]
22
24
 
23
25
  Commands:
24
26
  install-skills Copy bundled AI skills into your project.
25
- db:generate Generate incremental SQL migrations from a schema dictionary.`;
27
+ db:generate Generate incremental SQL migrations from a schema dictionary.
28
+ dashboard Launch the local-lite web dashboard for a SQLite database.
29
+ dev Pull the Vite dashboard from GitHub into ./dashboard, install deps, and serve it.`;
26
30
 
27
31
  function parseSkillsArgs(argv) {
28
32
  const options = { target: 'copilot', dir: undefined, force: false };
@@ -126,7 +130,7 @@ async function installSkills(options) {
126
130
 
127
131
  async function runDbGen(options) {
128
132
  const { generateSqlMigration } = await import(
129
- pathToFileURL(path.resolve(__dirname, '..', 'dist', 'schema', 'index.js')).href
133
+ pathToFileURL(path.resolve(__dirname, '..', 'dist', 'schema', 'sqlMigrations.js')).href
130
134
  );
131
135
  const schemaExports = await loadModuleExports(options.schema);
132
136
  const dictionary =
@@ -172,12 +176,221 @@ async function runDbGen(options) {
172
176
  }
173
177
  }
174
178
 
179
+ function parseDashboardArgs(argv) {
180
+ const options = {
181
+ db: ':memory:',
182
+ port: 4321,
183
+ uiPort: 5173,
184
+ host: '127.0.0.1',
185
+ readOnly: false,
186
+ token: undefined,
187
+ title: undefined,
188
+ open: true,
189
+ noVite: false,
190
+ repo: 'georgechitechi/local-lite',
191
+ force: false,
192
+ };
193
+ for (let i = 0; i < argv.length; i++) {
194
+ const arg = argv[i];
195
+ if (arg === '--readonly') options.readOnly = true;
196
+ else if (arg === '--no-open') options.open = false;
197
+ else if (arg === '--no-vite') options.noVite = true;
198
+ else if (arg === '--force') options.force = true;
199
+ else if (arg === '--repo') options.repo = argv[++i];
200
+ else if (arg === '--db') options.db = argv[++i];
201
+ else if (arg === '--port') options.port = Number(argv[++i]);
202
+ else if (arg === '--ui-port') options.uiPort = Number(argv[++i]);
203
+ else if (arg === '--host') options.host = argv[++i];
204
+ else if (arg === '--token') options.token = argv[++i];
205
+ else if (arg === '--title') options.title = argv[++i];
206
+ else if (arg !== '--') throw new Error(`Unknown option: ${arg}`);
207
+ }
208
+ if (!options.db) throw new Error('--db <path> cannot be empty.');
209
+ if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535) {
210
+ throw new Error('--port must be a valid TCP port (0-65535).');
211
+ }
212
+ if (!Number.isInteger(options.uiPort) || options.uiPort < 0 || options.uiPort > 65535) {
213
+ throw new Error('--ui-port must be a valid TCP port (0-65535).');
214
+ }
215
+ return options;
216
+ }
217
+
218
+ async function openDashboardDbAdapter(dbPath) {
219
+ const resolved = dbPath === ':memory:' ? ':memory:' : path.resolve(process.cwd(), dbPath);
220
+ try {
221
+ const nodeSqlite = await import('node:sqlite');
222
+ const mod = await import(
223
+ pathToFileURL(path.resolve(__dirname, '..', 'dist', 'adapters', 'local', 'node-sqlite.js')).href
224
+ );
225
+ const NodeSQLiteAdapter = mod.NodeSQLiteAdapter ?? mod.default?.NodeSQLiteAdapter;
226
+ const db = new nodeSqlite.DatabaseSync(resolved);
227
+ return { adapter: new NodeSQLiteAdapter(db), label: resolved, close: () => db.close() };
228
+ } catch {
229
+ // Fallback to better-sqlite3 if node:sqlite is unavailable
230
+ }
231
+
232
+ const requireFromCwd = createRequire(path.join(process.cwd(), 'package.json'));
233
+ try {
234
+ const BetterSqlite3 = requireFromCwd('better-sqlite3');
235
+ const mod = await import(
236
+ pathToFileURL(path.resolve(__dirname, '..', 'dist', 'adapters', 'local', 'better-sqlite3.js')).href
237
+ );
238
+ const BetterSQLite3Adapter = mod.BetterSQLite3Adapter ?? mod.default?.BetterSQLite3Adapter;
239
+ const db = new BetterSqlite3(resolved);
240
+ return { adapter: new BetterSQLite3Adapter(db), label: resolved, close: () => db.close() };
241
+ } catch {
242
+ throw new Error(
243
+ 'No SQLite driver available. Run on Node 22+ (node:sqlite) or install "better-sqlite3".',
244
+ );
245
+ }
246
+ }
247
+
248
+ async function runDashboard(options) {
249
+ const http = await import('node:http');
250
+ const dashboardMod = await import(
251
+ pathToFileURL(path.resolve(__dirname, '..', 'dist', 'server', 'dashboard.js')).href
252
+ );
253
+ const createDashboardHandler =
254
+ dashboardMod.createDashboardHandler ?? dashboardMod.default?.createDashboardHandler;
255
+ if (typeof createDashboardHandler !== 'function') {
256
+ throw new Error(
257
+ 'Dashboard module not built. Run "npm run build" first.',
258
+ );
259
+ }
260
+ const { adapter, label, close } = await openDashboardDbAdapter(options.db);
261
+ const handler = createDashboardHandler(adapter, {
262
+ title: options.title ?? `local-lite (${path.basename(label)})`,
263
+ readOnly: options.readOnly,
264
+ authToken: options.token,
265
+ });
266
+
267
+ const server = http.createServer(async (req, res) => {
268
+ try {
269
+ const origin = `http://${req.headers.host || `${options.host}:${options.port}`}`;
270
+ const url = new URL(req.url || '/', origin);
271
+ const chunks = [];
272
+ for await (const chunk of req) chunks.push(chunk);
273
+ const body = chunks.length > 0 ? Buffer.concat(chunks) : undefined;
274
+ const webReq = new Request(url.toString(), {
275
+ method: req.method,
276
+ headers: req.headers,
277
+ body: req.method === 'GET' || req.method === 'HEAD' ? undefined : body,
278
+ });
279
+ const webRes = await handler(webReq);
280
+ res.statusCode = webRes.status;
281
+ webRes.headers.forEach((value, key) => res.setHeader(key, value));
282
+ const buf = Buffer.from(await webRes.arrayBuffer());
283
+ res.end(buf);
284
+ } catch (err) {
285
+ res.statusCode = 500;
286
+ res.setHeader('Content-Type', 'application/json');
287
+ res.end(JSON.stringify({ error: err instanceof Error ? err.message : 'Internal error' }));
288
+ }
289
+ });
290
+
291
+ await new Promise((resolve) => server.listen(options.port, options.host, resolve));
292
+ const address = server.address();
293
+ const actualPort = typeof address === 'object' && address ? address.port : options.port;
294
+ const apiOrigin = `http://${options.host}:${actualPort}`;
295
+ const tokenSuffix = options.token ? `?token=${encodeURIComponent(options.token)}` : '';
296
+ console.log(`local-lite API server running at ${apiOrigin}/${tokenSuffix}`);
297
+ console.log(`Database: ${label} (${options.readOnly ? 'read-only' : 'read/write'})`);
298
+
299
+ let viteProc = null;
300
+ const { existsSync } = await import('node:fs');
301
+ const pkgDashboardDir = path.resolve(__dirname, '..', 'dashboard');
302
+ const cwdDashboardDir = path.resolve(process.cwd(), 'dashboard');
303
+ const dashboardDir =
304
+ options.dashboardDir ??
305
+ (existsSync(path.join(pkgDashboardDir, 'package.json')) ? pkgDashboardDir : cwdDashboardDir);
306
+ const viteBin = path.join(dashboardDir, 'node_modules', 'vite', 'bin', 'vite.js');
307
+ if (!options.noVite) {
308
+ if (existsSync(viteBin)) {
309
+ const { spawn } = await import('node:child_process');
310
+ const viteArgs = [
311
+ viteBin,
312
+ '--host',
313
+ options.host,
314
+ '--port',
315
+ String(options.uiPort),
316
+ ];
317
+ if (options.open) {
318
+ viteArgs.push('--open', tokenSuffix || '/');
319
+ }
320
+ viteProc = spawn(process.execPath, viteArgs, {
321
+ cwd: dashboardDir,
322
+ env: {
323
+ ...process.env,
324
+ LOCAL_LITE_API_TARGET: apiOrigin,
325
+ },
326
+ stdio: 'inherit',
327
+ });
328
+ } else {
329
+ console.log('Vite dashboard dependencies not installed; serving built-in fallback UI.');
330
+ }
331
+ }
332
+
333
+ const shutdown = () => {
334
+ if (viteProc && !viteProc.killed) {
335
+ try { viteProc.kill(); } catch {}
336
+ }
337
+ server.close(() => {
338
+ try { close(); } catch {}
339
+ process.exit(0);
340
+ });
341
+ };
342
+ process.on('SIGINT', shutdown);
343
+ process.on('SIGTERM', shutdown);
344
+ }
345
+
346
+ async function runDev(options) {
347
+ const { existsSync } = await import('node:fs');
348
+ const { spawnSync } = await import('node:child_process');
349
+ const targetDir = path.resolve(process.cwd(), 'dashboard');
350
+ const pkgJsonPath = path.join(targetDir, 'package.json');
351
+ const viteBin = path.join(targetDir, 'node_modules', 'vite', 'bin', 'vite.js');
352
+
353
+ if (!existsSync(pkgJsonPath) || options.force) {
354
+ console.log(`Pulling dashboard from ${options.repo}/dashboard into ./dashboard...`);
355
+ const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
356
+ const degitArgs = ['--yes', 'degit', `${options.repo}/dashboard`, 'dashboard'];
357
+ if (options.force) degitArgs.push('--force');
358
+ const pullRes = spawnSync(npxCmd, degitArgs, {
359
+ cwd: process.cwd(),
360
+ stdio: 'inherit',
361
+ shell: process.platform === 'win32',
362
+ });
363
+ if (pullRes.error || pullRes.status !== 0) {
364
+ throw new Error(`Failed to pull dashboard from ${options.repo}/dashboard.`);
365
+ }
366
+ }
367
+
368
+ if (!existsSync(viteBin)) {
369
+ console.log('Installing dashboard dependencies...');
370
+ const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
371
+ const installRes = spawnSync(npmCmd, ['--prefix', 'dashboard', 'install'], {
372
+ cwd: process.cwd(),
373
+ stdio: 'inherit',
374
+ shell: process.platform === 'win32',
375
+ });
376
+ if (installRes.error || installRes.status !== 0) {
377
+ throw new Error('Failed to install dashboard dependencies.');
378
+ }
379
+ }
380
+
381
+ await runDashboard({ ...options, dashboardDir: targetDir });
382
+ }
383
+
175
384
  const [command, ...rest] = process.argv.slice(2);
176
385
  try {
177
386
  if (command === 'install-skills') {
178
387
  await installSkills(parseSkillsArgs(rest));
179
388
  } else if (command === 'db:generate') {
180
389
  await runDbGen(parseDbGenArgs(rest));
390
+ } else if (command === 'dashboard') {
391
+ await runDashboard(parseDashboardArgs(rest));
392
+ } else if (command === 'dev') {
393
+ await runDev(parseDashboardArgs(rest));
181
394
  } else {
182
395
  console.log(usage);
183
396
  process.exitCode = command && command !== '--help' && command !== '-h' ? 1 : 0;
@@ -98,7 +98,7 @@ class AppleAuthClient {
98
98
  if (!this.options.redirectUri) {
99
99
  throw new Error('Apple OAuth redirectUri is required for web authorization flow.');
100
100
  }
101
- const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
101
+ const randomBytes = this.options.randomBytes ?? crypto_js_1.requireSecureRandomBytes;
102
102
  const state = (0, crypto_js_1.base64UrlEncode)(randomBytes(32));
103
103
  const nonce = (0, crypto_js_1.base64UrlEncode)(randomBytes(32));
104
104
  const scopes = this.options.scopes && this.options.scopes.length > 0
@@ -73,7 +73,7 @@ class GitHubAuthClient {
73
73
  }
74
74
  }
75
75
  async signIn() {
76
- const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
76
+ const randomBytes = this.options.randomBytes ?? crypto_js_1.requireSecureRandomBytes;
77
77
  const stateBytes = randomBytes(32);
78
78
  if (stateBytes.length !== 32) {
79
79
  throw new Error('The randomBytes provider returned an invalid number of bytes.');
@@ -4,9 +4,6 @@ exports.GoogleAuthClient = exports.DEFAULT_GOOGLE_AUTH_SCOPES = exports.GOOGLE_U
4
4
  exports.createInMemoryGoogleTokenStore = createInMemoryGoogleTokenStore;
5
5
  exports.createGoogleAuthTokenStore = createGoogleAuthTokenStore;
6
6
  const identity_js_1 = require("./identity.js");
7
- const sha2_js_1 = require("@noble/hashes/sha2.js");
8
- const utils_js_1 = require("@noble/hashes/utils.js");
9
- const crypto_js_1 = require("../utils/crypto.js");
10
7
  const oauth_js_1 = require("../utils/oauth.js");
11
8
  const cloud_storage_js_1 = require("../backups/cloud-storage.js");
12
9
  exports.GOOGLE_AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth';
@@ -86,15 +83,7 @@ class GoogleAuthClient {
86
83
  }
87
84
  }
88
85
  async signIn() {
89
- const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
90
- const verifierBytes = randomBytes(32);
91
- const stateBytes = randomBytes(32);
92
- if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
93
- throw new Error('The randomBytes provider returned an invalid number of bytes.');
94
- }
95
- const codeVerifier = (0, crypto_js_1.base64UrlEncode)(verifierBytes);
96
- const codeChallenge = (0, crypto_js_1.base64UrlEncode)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
97
- const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
86
+ const { codeVerifier, codeChallenge, state } = (0, oauth_js_1.createPkceChallengePair)(this.options.randomBytes);
98
87
  const scopes = this.options.scopes && this.options.scopes.length > 0
99
88
  ? this.options.scopes
100
89
  : exports.DEFAULT_GOOGLE_AUTH_SCOPES;
@@ -13,6 +13,7 @@ const utils_js_1 = require("@noble/hashes/utils.js");
13
13
  const event_emitter_js_1 = require("../reactive/event-emitter.js");
14
14
  const uuid_js_1 = require("../utils/uuid.js");
15
15
  const sql_js_1 = require("../utils/sql.js");
16
+ const crypto_js_1 = require("../utils/crypto.js");
16
17
  const generator_js_1 = require("../keys/generator.js");
17
18
  const session_js_1 = require("./session.js");
18
19
  exports.DEFAULT_USERS_TABLE = '_local_users';
@@ -28,31 +29,7 @@ exports.DEFAULT_MIN_PASSWORD_LENGTH = 8;
28
29
  * Generates cryptographically secure random bytes across Web, Expo/React Native, and Node.js.
29
30
  */
30
31
  function getCryptoRandomBytes(length) {
31
- const cryptoObj = typeof globalThis !== 'undefined' ? globalThis.crypto : undefined;
32
- if (cryptoObj?.getRandomValues) {
33
- try {
34
- return cryptoObj.getRandomValues(new Uint8Array(length));
35
- }
36
- catch {
37
- // Fallback below
38
- }
39
- }
40
- try {
41
- const nodeCrypto = globalThis.process?.versions?.node
42
- ? globalThis.require('node:crypto')
43
- : null;
44
- if (nodeCrypto?.randomBytes) {
45
- return new Uint8Array(nodeCrypto.randomBytes(length));
46
- }
47
- }
48
- catch {
49
- // Fallback ignored
50
- }
51
- const fallback = new Uint8Array(length);
52
- for (let i = 0; i < length; i++) {
53
- fallback[i] = Math.floor(Math.random() * 256);
54
- }
55
- return fallback;
32
+ return (0, crypto_js_1.getRandomBytes)(length);
56
33
  }
57
34
  /**
58
35
  * Derives PBKDF2 keys using hardware-accelerated WebCrypto if available,
@@ -4,9 +4,6 @@ exports.MicrosoftAuthClient = exports.DEFAULT_MICROSOFT_AUTH_SCOPES = exports.MI
4
4
  exports.createInMemoryMicrosoftTokenStore = createInMemoryMicrosoftTokenStore;
5
5
  exports.createMicrosoftAuthTokenStore = createMicrosoftAuthTokenStore;
6
6
  const identity_js_1 = require("./identity.js");
7
- const sha2_js_1 = require("@noble/hashes/sha2.js");
8
- const utils_js_1 = require("@noble/hashes/utils.js");
9
- const crypto_js_1 = require("../utils/crypto.js");
10
7
  const oauth_js_1 = require("../utils/oauth.js");
11
8
  const onedrive_js_1 = require("../backups/onedrive.js");
12
9
  exports.MICROSOFT_GRAPH_ENDPOINT = 'https://graph.microsoft.com/v1.0';
@@ -91,15 +88,7 @@ class MicrosoftAuthClient {
91
88
  }
92
89
  }
93
90
  async signIn() {
94
- const randomBytes = this.options.randomBytes ?? crypto_js_1.getRandomBytes;
95
- const verifierBytes = randomBytes(32);
96
- const stateBytes = randomBytes(32);
97
- if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
98
- throw new Error('The randomBytes provider returned an invalid number of bytes.');
99
- }
100
- const codeVerifier = (0, crypto_js_1.base64UrlEncode)(verifierBytes);
101
- const codeChallenge = (0, crypto_js_1.base64UrlEncode)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
102
- const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
91
+ const { codeVerifier, codeChallenge, state } = (0, oauth_js_1.createPkceChallengePair)(this.options.randomBytes);
103
92
  const scopes = this.options.scopes && this.options.scopes.length > 0
104
93
  ? this.options.scopes
105
94
  : exports.DEFAULT_MICROSOFT_AUTH_SCOPES;
@@ -3,10 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GoogleDriveBackupClient = exports.GoogleDriveBackupStorage = exports.GOOGLE_DRIVE_SCOPE = void 0;
4
4
  exports.createInMemoryGoogleDriveTokenStore = createInMemoryGoogleDriveTokenStore;
5
5
  exports.createGoogleDriveTokenStore = createGoogleDriveTokenStore;
6
- const sha2_js_1 = require("@noble/hashes/sha2.js");
7
- const utils_js_1 = require("@noble/hashes/utils.js");
8
6
  const operations_js_1 = require("./operations.js");
9
- const crypto_js_1 = require("../utils/crypto.js");
10
7
  const oauth_js_1 = require("../utils/oauth.js");
11
8
  const GOOGLE_API = 'https://www.googleapis.com/drive/v3';
12
9
  const GOOGLE_UPLOAD_API = 'https://www.googleapis.com/upload/drive/v3';
@@ -238,15 +235,7 @@ class GoogleDriveBackupClient {
238
235
  this.notify(connected);
239
236
  return connected;
240
237
  }
241
- const randomBytes = this.options.randomBytes ?? crypto_js_1.requireSecureRandomBytes;
242
- const verifierBytes = randomBytes(32);
243
- const stateBytes = randomBytes(32);
244
- if (verifierBytes.length !== 32 || stateBytes.length !== 32) {
245
- throw new Error('The randomBytes provider returned an invalid number of bytes.');
246
- }
247
- const codeVerifier = (0, crypto_js_1.base64UrlEncode)(verifierBytes);
248
- const codeChallenge = (0, crypto_js_1.base64UrlEncode)((0, sha2_js_1.sha256)((0, utils_js_1.utf8ToBytes)(codeVerifier)));
249
- const state = (0, crypto_js_1.base64UrlEncode)(stateBytes);
238
+ const { codeVerifier, codeChallenge, state } = (0, oauth_js_1.createPkceChallengePair)(this.options.randomBytes);
250
239
  const authorizationParams = new URLSearchParams({
251
240
  client_id: this.options.clientId,
252
241
  redirect_uri: this.options.redirectUri,
@@ -12,7 +12,7 @@ import { type ExportJsonOptions, type ImportJsonOptions, type ExportCsvOptions,
12
12
  import { type BackupStorage, type CreateDatabaseBackupOptions, type EncryptedBackupOptions, type RestoreEncryptedBackupOptions } from '../backups/index.js';
13
13
  import { ActionManager, type ActionManagerOptions } from '../actions/index.js';
14
14
  import { ApiKeyManager, type ApiKeyManagerOptions } from '../keys/index.js';
15
- import { KVManager, type KVStoreOptions } from '../kv/index.js';
15
+ import { KVStoreManager, type KVStoreOptions } from '../kv-store/index.js';
16
16
  import { SearchManager } from '../search/index.js';
17
17
  import { BlobStorageManager, type BlobStorageManagerOptions } from '../storage/index.js';
18
18
  import { JobScheduler, type JobSchedulerOptions } from '../scheduler/index.js';
@@ -61,7 +61,7 @@ export interface LocalFirstClientConfig {
61
61
  touchUpdatedAt?: boolean | string;
62
62
  actions?: ActionManagerOptions;
63
63
  keys?: ApiKeyManagerOptions;
64
- kv?: KVStoreOptions;
64
+ kvStore?: KVStoreOptions;
65
65
  storage?: BlobStorageManagerOptions;
66
66
  scheduler?: JobSchedulerOptions;
67
67
  session?: SessionManagerOptions;
@@ -115,7 +115,7 @@ export declare class LocalFirstClient {
115
115
  readonly maintenance: DatabaseMaintenance;
116
116
  readonly actions: ActionManager;
117
117
  readonly keys: ApiKeyManager;
118
- readonly kv: KVManager;
118
+ readonly kvStore: KVStoreManager;
119
119
  readonly search: SearchManager;
120
120
  readonly storage: BlobStorageManager;
121
121
  readonly scheduler: JobScheduler;
@@ -16,7 +16,7 @@ const portability_js_1 = require("../utils/portability.js");
16
16
  const index_js_1 = require("../backups/index.js");
17
17
  const index_js_2 = require("../actions/index.js");
18
18
  const index_js_3 = require("../keys/index.js");
19
- const index_js_4 = require("../kv/index.js");
19
+ const index_js_4 = require("../kv-store/index.js");
20
20
  const index_js_5 = require("../search/index.js");
21
21
  const index_js_6 = require("../storage/index.js");
22
22
  const index_js_7 = require("../scheduler/index.js");
@@ -379,7 +379,7 @@ class LocalFirstClient {
379
379
  maintenance;
380
380
  actions;
381
381
  keys;
382
- kv;
382
+ kvStore;
383
383
  search;
384
384
  storage;
385
385
  scheduler;
@@ -438,7 +438,7 @@ class LocalFirstClient {
438
438
  this.schemaManager = new schema_manager_js_1.SchemaManager();
439
439
  this.maintenance = new maintenance_js_1.DatabaseMaintenance(this.db, () => [
440
440
  ...this.tables,
441
- '_local_kv',
441
+ '_local_kv_store',
442
442
  '_local_blobs',
443
443
  '_local_scheduled_jobs',
444
444
  '_local_job_runs',
@@ -450,7 +450,7 @@ class LocalFirstClient {
450
450
  ]);
451
451
  const actionNetwork = config.actions?.network ?? config.network;
452
452
  this.keys = new index_js_3.ApiKeyManager(this.db, config.keys);
453
- this.kv = new index_js_4.KVManager(this.db, this.events, config.kv);
453
+ this.kvStore = new index_js_4.KVStoreManager(this.db, this.events, config.kvStore);
454
454
  this.search = new index_js_5.SearchManager(this.db, this.events, (table, id) => this.findById(table, id));
455
455
  let storageUploader = config.storage?.uploader;
456
456
  if (!storageUploader && config.storage) {
@@ -697,7 +697,7 @@ class LocalFirstClient {
697
697
  await outbox_store_js_1.OutboxStore.resetStaleProcessing(this.db);
698
698
  await this.actions.initialize();
699
699
  await this.keys.initialize();
700
- await this.kv.initialize();
700
+ await this.kvStore.initialize();
701
701
  await this.storage.initialize();
702
702
  await this.scheduler.initialize();
703
703
  await this.session.initialize();
@@ -1303,7 +1303,7 @@ class LocalFirstClient {
1303
1303
  async reset(options = {}) {
1304
1304
  this.stop();
1305
1305
  const internalTables = [
1306
- '_local_kv',
1306
+ '_local_kv_store',
1307
1307
  '_local_blobs',
1308
1308
  '_local_scheduled_jobs',
1309
1309
  '_local_job_runs',
@@ -39,20 +39,7 @@ const jsx_runtime_1 = require("react/jsx-runtime");
39
39
  const react_1 = __importStar(require("react"));
40
40
  const theme_js_1 = require("../react/theme.js");
41
41
  const sql_js_1 = require("../utils/sql.js");
42
- let RN;
43
- try {
44
- RN = require('react-native');
45
- }
46
- catch {
47
- // Web / DOM environment
48
- }
49
- let RNSafeArea;
50
- try {
51
- RNSafeArea = require('react-native-safe-area-context');
52
- }
53
- catch {
54
- // Web / DOM environment or not installed
55
- }
42
+ const shared_js_1 = require("./shared.js");
56
43
  const now = () => typeof performance !== 'undefined' && typeof performance.now === 'function'
57
44
  ? performance.now()
58
45
  : Date.now();
@@ -573,7 +560,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
573
560
  const [progress, setProgress] = (0, react_1.useState)(0);
574
561
  const [results, setResults] = (0, react_1.useState)([]);
575
562
  const [copied, setCopied] = (0, react_1.useState)(false);
576
- const systemColorScheme = RN?.useColorScheme ? RN.useColorScheme() : null;
563
+ const systemColorScheme = shared_js_1.RN?.useColorScheme ? shared_js_1.RN.useColorScheme() : null;
577
564
  const currentTheme = react_1.default.useMemo(() => (0, theme_js_1.resolveSyncTheme)(theme, systemColorScheme), [theme, systemColorScheme]);
578
565
  const startBenchmark = async () => {
579
566
  if (!client)
@@ -600,7 +587,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
600
587
  return;
601
588
  const report = [
602
589
  '# ⚡ local-lite SQLite Benchmark Report',
603
- `- Platform: ${RN && RN.Platform ? RN.Platform.OS : 'web'}`,
590
+ `- Platform: ${shared_js_1.RN && shared_js_1.RN.Platform ? shared_js_1.RN.Platform.OS : 'web'}`,
604
591
  `- Date: ${new Date().toLocaleString()}`,
605
592
  ...(results[0]?.note ? [`- App dataset: ${results[0].note}`] : []),
606
593
  '',
@@ -610,8 +597,8 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
610
597
  ].join('\n');
611
598
  let isCopied = false;
612
599
  try {
613
- if (RN && RN.Clipboard && typeof RN.Clipboard.setString === 'function') {
614
- RN.Clipboard.setString(report);
600
+ if (shared_js_1.RN && shared_js_1.RN.Clipboard && typeof shared_js_1.RN.Clipboard.setString === 'function') {
601
+ shared_js_1.RN.Clipboard.setString(report);
615
602
  isCopied = true;
616
603
  }
617
604
  }
@@ -629,9 +616,9 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
629
616
  if (!visible)
630
617
  return null;
631
618
  // React Native renderer (Full-height modal)
632
- if (RN && RN.View) {
633
- const { View, Text, TouchableOpacity, ScrollView, Modal, ActivityIndicator, Platform, StatusBar, } = RN;
634
- const SafeComp = RNSafeArea?.SafeAreaView || RN.SafeAreaView || View;
619
+ if (shared_js_1.RN && shared_js_1.RN.View) {
620
+ const { View, Text, TouchableOpacity, ScrollView, Modal, ActivityIndicator, Platform, StatusBar, } = shared_js_1.RN;
621
+ const SafeComp = shared_js_1.RNSafeArea?.SafeAreaView || shared_js_1.RN.SafeAreaView || View;
635
622
  const isAndroid = Platform?.OS === 'android';
636
623
  const statusBarHeight = isAndroid ? StatusBar?.currentHeight || 24 : 0;
637
624
  return ((0, jsx_runtime_1.jsx)(Modal, { visible: visible, animationType: "slide", presentationStyle: "fullScreen", statusBarTranslucent: true, onRequestClose: onDismiss, children: (0, jsx_runtime_1.jsxs)(SafeComp, { style: [styles.fullScreenSafe, { backgroundColor: currentTheme.bg }], edges: ['top', 'bottom', 'left', 'right'], children: [(0, jsx_runtime_1.jsxs)(View, { style: [
@@ -640,7 +627,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
640
627
  backgroundColor: currentTheme.surface,
641
628
  borderBottomColor: currentTheme.border,
642
629
  },
643
- !RNSafeArea?.SafeAreaView &&
630
+ !shared_js_1.RNSafeArea?.SafeAreaView &&
644
631
  isAndroid && { paddingTop: statusBarHeight + 10 },
645
632
  ], children: [(0, jsx_runtime_1.jsxs)(View, { style: { flex: 1 }, children: [(0, jsx_runtime_1.jsx)(Text, { style: [styles.topBarTitle, { color: currentTheme.text }], children: "\u26A1 SQLite Benchmark" }), (0, jsx_runtime_1.jsx)(Text, { style: [styles.topBarSub, { color: currentTheme.textMuted }], children: "Inbuilt local-lite throughput & ACID test suite" })] }), (0, jsx_runtime_1.jsx)(TouchableOpacity, { onPress: onDismiss, style: [
646
633
  styles.closeCircle,
@@ -718,7 +705,7 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
718
705
  backgroundColor: currentTheme.surface,
719
706
  borderTopColor: currentTheme.border,
720
707
  },
721
- !RNSafeArea?.SafeAreaView && isAndroid && { paddingBottom: 32 },
708
+ !shared_js_1.RNSafeArea?.SafeAreaView && isAndroid && { paddingBottom: 32 },
722
709
  ], children: [(0, jsx_runtime_1.jsx)(TouchableOpacity, { onPress: startBenchmark, disabled: isRunning, style: [
723
710
  styles.footerBtn,
724
711
  { backgroundColor: isRunning ? '#6D28D9' : '#8B5CF6' },
@@ -869,32 +856,24 @@ function BenchmarkModal({ client, visible, onDismiss, theme = 'auto', }) {
869
856
  cursor: 'pointer',
870
857
  }, children: copied ? '✓ Copied' : 'Copy Report' }))] })] }));
871
858
  }
872
- const styles = RN && RN.StyleSheet
873
- ? RN.StyleSheet.create({
859
+ const styles = shared_js_1.RN && shared_js_1.RN.StyleSheet
860
+ ? shared_js_1.RN.StyleSheet.create({
874
861
  fullScreenSafe: {
875
- flex: 1,
876
- height: '100%',
862
+ ...shared_js_1.devtoolsBaseRNStyles.fullScreenSafe,
877
863
  backgroundColor: '#111827',
878
864
  },
879
865
  topBar: {
880
- flexDirection: 'row',
881
- alignItems: 'center',
882
- justifyContent: 'space-between',
883
- paddingHorizontal: 18,
884
- paddingVertical: 14,
866
+ ...shared_js_1.devtoolsBaseRNStyles.topBar,
885
867
  backgroundColor: '#1F2937',
886
- borderBottomWidth: 1,
887
868
  borderBottomColor: '#374151',
888
869
  },
889
870
  topBarTitle: {
871
+ ...shared_js_1.devtoolsBaseRNStyles.topBarTitle,
890
872
  color: '#F9FAFB',
891
- fontSize: 17,
892
- fontWeight: '700',
893
873
  },
894
874
  topBarSub: {
875
+ ...shared_js_1.devtoolsBaseRNStyles.topBarSub,
895
876
  color: '#9CA3AF',
896
- fontSize: 11,
897
- marginTop: 2,
898
877
  },
899
878
  closeCircle: {
900
879
  width: 32,