local-lite 1.0.3 → 2.0.0

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 CHANGED
@@ -361,9 +361,10 @@ const emailAction = await client.actions.sendEmail({
361
361
 
362
362
  // ⚡ 2. Direct email dispatch (Nodemailer SMTP, Resend, SendGrid, Postmark, or HTTP webhook)
363
363
  import { createEmailHandler } from 'local-lite/email';
364
+ import { createNodemailerHandler } from 'local-lite/server';
364
365
 
365
- // Nodemailer transport:
366
- client.actions.registerEmailHandler(createEmailHandler({
366
+ // Nodemailer transport (server only):
367
+ client.actions.registerEmailHandler(createNodemailerHandler({
367
368
  transport: { host: 'smtp.example.com', port: 587, auth: { user: '...', pass: '...' } },
368
369
  defaultFrom: 'Support <support@mycompany.com>',
369
370
  }));
@@ -371,7 +372,7 @@ client.actions.registerEmailHandler(createEmailHandler({
371
372
  // Or HTTP provider (e.g., Resend):
372
373
  // client.actions.registerEmailHandler(createEmailHandler({ provider: 'resend', apiKey: '...' }));
373
374
 
374
- // Or configure directly in defineSyncConfig({ email: { transport: { ... } } })!
375
+ // HTTP providers can be configured directly in defineSyncConfig.
375
376
 
376
377
  // ⚡ 3. Enqueue arbitrary asynchronous actions (e.g., push notifications, analytics)
377
378
  await client.actions.enqueue({
@@ -1,6 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BetterSQLite3Adapter = void 0;
4
+ const READ_QUERY_REGEX = /^(?:SELECT|WITH|EXPLAIN)\b/i;
5
+ const READ_ONLY_PRAGMA_REGEX = /^PRAGMA\b/i;
6
+ const MUTATING_PRAGMA_REGEX = /=|wal_checkpoint|shrink_memory|optimize/i;
7
+ function isReadQuery(sql) {
8
+ if (READ_QUERY_REGEX.test(sql))
9
+ return true;
10
+ return READ_ONLY_PRAGMA_REGEX.test(sql) && !MUTATING_PRAGMA_REGEX.test(sql);
11
+ }
4
12
  /**
5
13
  * Adapter for better-sqlite3 in Node.js, Electron, Next.js, and server environments.
6
14
  */
@@ -28,9 +36,8 @@ class BetterSQLite3Adapter {
28
36
  }
29
37
  async execute(query, params = []) {
30
38
  const trimmed = query.trim();
31
- const isReader = /^SELECT|^PRAGMA/i.test(trimmed);
32
39
  // Fast-path: Readers execute directly and synchronously without artificial promise queue delay
33
- if (isReader) {
40
+ if (isReadQuery(trimmed)) {
34
41
  const stmt = this.getStatement(trimmed);
35
42
  return stmt.all(...params);
36
43
  }
@@ -55,7 +62,7 @@ class BetterSQLite3Adapter {
55
62
  execute: async (q, p = []) => {
56
63
  const trimmed = q.trim();
57
64
  const stmt = this.getStatement(trimmed);
58
- if (stmt.reader || /^SELECT|^PRAGMA/i.test(trimmed)) {
65
+ if (stmt.reader || isReadQuery(trimmed)) {
59
66
  return stmt.all(...p);
60
67
  }
61
68
  return [stmt.run(...p)];
@@ -24,12 +24,12 @@ class ExpoSQLiteAdapter {
24
24
  await this.db.execAsync(trimmed);
25
25
  return [];
26
26
  }
27
- // Modern Expo SQLite (SDK 51+): runAsync is optimized for writes without dummy row allocation
27
+ // Expo SQLite (SDK 54+): runAsync is required for parameterized writes
28
28
  if (typeof this.db.runAsync === 'function') {
29
29
  const res = await this.db.runAsync(trimmed, params);
30
30
  return [res];
31
31
  }
32
- return this.db.getAllAsync(trimmed, params);
32
+ throw new Error('ExpoSQLiteAdapter requires Expo SQLite SDK 54+ with runAsync() support.');
33
33
  };
34
34
  const next = this.writeQueue.then(run, run);
35
35
  this.writeQueue = next.catch(() => { });
@@ -54,7 +54,7 @@ class ExpoSQLiteAdapter {
54
54
  const res = await this.db.runAsync(trimmed, p);
55
55
  return [res];
56
56
  }
57
- return this.db.getAllAsync(trimmed, p);
57
+ throw new Error('ExpoSQLiteAdapter requires Expo SQLite SDK 54+ with runAsync() support.');
58
58
  },
59
59
  };
60
60
  result = await action(txWrapper);
@@ -1,6 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.NodeSQLiteAdapter = void 0;
4
+ const READ_QUERY_REGEX = /^(?:SELECT|WITH|EXPLAIN)\b/i;
5
+ const READ_ONLY_PRAGMA_REGEX = /^PRAGMA\b/i;
6
+ const MUTATING_PRAGMA_REGEX = /=|wal_checkpoint|shrink_memory|optimize/i;
7
+ function isReadQuery(sql) {
8
+ if (READ_QUERY_REGEX.test(sql))
9
+ return true;
10
+ return READ_ONLY_PRAGMA_REGEX.test(sql) && !MUTATING_PRAGMA_REGEX.test(sql);
11
+ }
4
12
  /**
5
13
  * Adapter for Node.js 22+ built-in `node:sqlite` (DatabaseSync).
6
14
  * Provides zero-dependency, native SQLite on modern Node.js runtimes.
@@ -29,9 +37,8 @@ class NodeSQLiteAdapter {
29
37
  }
30
38
  async execute(query, params = []) {
31
39
  const trimmed = query.trim();
32
- const isReader = /^SELECT|^PRAGMA/i.test(trimmed);
33
40
  // Fast-path: Readers execute directly and synchronously without queuing delay
34
- if (isReader) {
41
+ if (isReadQuery(trimmed)) {
35
42
  const stmt = this.getStatement(trimmed);
36
43
  return stmt.all(...params);
37
44
  }
@@ -52,7 +59,7 @@ class NodeSQLiteAdapter {
52
59
  execute: async (q, p = []) => {
53
60
  const trimmed = q.trim();
54
61
  const stmt = this.getStatement(trimmed);
55
- if (/^SELECT|^PRAGMA/i.test(trimmed)) {
62
+ if (isReadQuery(trimmed)) {
56
63
  return stmt.all(...p);
57
64
  }
58
65
  return [stmt.run(...p)];
@@ -15,10 +15,13 @@ export interface RemoteBackupArchive {
15
15
  error?: string;
16
16
  downloadUrl: string | null;
17
17
  }
18
+ export interface RemoteRequestOptions {
19
+ signal?: AbortSignal;
20
+ }
18
21
  export interface RemoteDBAdapter {
19
- pushChanges(operations: SyncOperation[]): Promise<boolean | PushResult>;
22
+ pushChanges(operations: SyncOperation[], options?: RemoteRequestOptions): Promise<boolean | PushResult>;
20
23
  /** Return a complete batch through timestamp; reject on partial failure. Supports optional scope for data filtering. */
21
- fetchChanges(sinceTimestamp: number, scope?: Record<string, any>): Promise<DeltaChanges>;
24
+ fetchChanges(sinceTimestamp: number, scope?: Record<string, any>, options?: RemoteRequestOptions): Promise<DeltaChanges>;
22
25
  /** Live events do not advance the durable pull checkpoint; return a cleanup function. */
23
26
  subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
24
27
  setSyncScope?(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
@@ -1,4 +1,4 @@
1
- import { RemoteDBAdapter, RemoteBackupArchive, RemoteAutomationJob } from './index.js';
1
+ import { RemoteDBAdapter, RemoteBackupArchive, RemoteAutomationJob, RemoteRequestOptions } from './index.js';
2
2
  import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
3
3
  export interface SelfHostedRemoteAdapterOptions {
4
4
  /**
@@ -50,11 +50,11 @@ export declare class SelfHostedRemoteAdapter implements RemoteDBAdapter {
50
50
  /**
51
51
  * Pushes client mutations to the self-hosted sync backend.
52
52
  */
53
- pushChanges(operations: SyncOperation[]): Promise<PushResult>;
53
+ pushChanges(operations: SyncOperation[], options?: RemoteRequestOptions): Promise<PushResult>;
54
54
  /**
55
55
  * Pulls delta changes from the self-hosted sync backend since a given timestamp or cursor.
56
56
  */
57
- fetchChanges(sinceTimestamp: number, _scope?: Record<string, any>): Promise<DeltaChanges>;
57
+ fetchChanges(sinceTimestamp: number, _scope?: Record<string, any>, options?: RemoteRequestOptions): Promise<DeltaChanges>;
58
58
  /**
59
59
  * Subscribes to live server changes via periodic polling.
60
60
  */
@@ -43,7 +43,7 @@ class SelfHostedRemoteAdapter {
43
43
  /**
44
44
  * Pushes client mutations to the self-hosted sync backend.
45
45
  */
46
- async pushChanges(operations) {
46
+ async pushChanges(operations, options) {
47
47
  if (operations.length === 0) {
48
48
  return { success: true, successfulIds: [] };
49
49
  }
@@ -51,6 +51,7 @@ class SelfHostedRemoteAdapter {
51
51
  method: 'POST',
52
52
  headers: this.getRequestHeaders(),
53
53
  body: JSON.stringify({ operations }),
54
+ signal: options?.signal,
54
55
  });
55
56
  if (!response.ok) {
56
57
  const errText = await response.text().catch(() => response.statusText);
@@ -65,20 +66,32 @@ class SelfHostedRemoteAdapter {
65
66
  /**
66
67
  * Pulls delta changes from the self-hosted sync backend since a given timestamp or cursor.
67
68
  */
68
- async fetchChanges(sinceTimestamp, _scope) {
69
+ async fetchChanges(sinceTimestamp, _scope, options) {
69
70
  const tablesParam = encodeURIComponent(this.tables.join(','));
70
71
  const url = `${this.url}?tables=${tablesParam}&since=${encodeURIComponent(String(sinceTimestamp))}`;
71
72
  const response = await this.fetchFn(url, {
72
73
  method: 'GET',
73
74
  headers: this.getRequestHeaders(),
75
+ signal: options?.signal,
74
76
  });
75
77
  if (!response.ok) {
76
78
  const errText = await response.text().catch(() => response.statusText);
77
79
  throw new Error(`Self-hosted sync pull failed (${response.status}): ${errText}`);
78
80
  }
79
81
  const data = await response.json();
80
- this.lastPollCursor = Math.max(this.lastPollCursor, data.cursor ?? sinceTimestamp);
81
- return data.changes ?? { timestamp: Date.now(), changes: [] };
82
+ const nextCursor = typeof data.cursor === 'number' ? data.cursor : sinceTimestamp;
83
+ this.lastPollCursor = Math.max(this.lastPollCursor, nextCursor);
84
+ const deltas = data.changes ?? {
85
+ timestamp: nextCursor,
86
+ changes: [],
87
+ };
88
+ if (typeof data.cursor === 'number') {
89
+ deltas.timestamp = data.cursor;
90
+ }
91
+ if (data.hasMore !== undefined && deltas.hasMore === undefined) {
92
+ deltas.hasMore = Boolean(data.hasMore);
93
+ }
94
+ return deltas;
82
95
  }
83
96
  /**
84
97
  * Subscribes to live server changes via periodic polling.
@@ -1,4 +1,3 @@
1
- import type { SupabaseClient } from '@supabase/supabase-js';
2
1
  import { RemoteAutomationJob, RemoteBackupArchive, RemoteDBAdapter } from './index.js';
3
2
  import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
4
3
  import { SyncLogger, CustomLogger, LogLevel } from '../../utils/logger.js';
@@ -63,7 +62,7 @@ export interface SupabaseAdapterOptions {
63
62
  */
64
63
  fetchLimit?: number;
65
64
  }
66
- export type AnySupabaseClient = SupabaseClient<any, any, any> | any;
65
+ export type AnySupabaseClient = any;
67
66
  export type SupabaseClientResolver = AnySupabaseClient | (() => AnySupabaseClient | null | undefined) | null | undefined;
68
67
  export declare class SupabaseRemoteAdapter implements RemoteDBAdapter {
69
68
  private clientResolver?;
@@ -14,7 +14,6 @@ export { SupabaseRemoteAdapter } from '../adapters/remote/supabase.js';
14
14
  export { ConvexRemoteAdapter } from '../adapters/remote/convex.js';
15
15
  export { FirestoreRemoteAdapter } from '../adapters/remote/firestore.js';
16
16
  export { SelfHostedRemoteAdapter } from '../adapters/remote/self-hosted.js';
17
- export { MemoryDemoRemoteAdapter, NoopRemoteAdapter, } from '../adapters/remote/demo.js';
18
17
  export type { RemoteDBAdapter } from '../adapters/remote/index.js';
19
18
  /**
20
19
  * Type-safe configuration helper function (similar to defineConfig in Vite/Tailwind).
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.NoopRemoteAdapter = exports.MemoryDemoRemoteAdapter = exports.SelfHostedRemoteAdapter = exports.FirestoreRemoteAdapter = exports.ConvexRemoteAdapter = exports.SupabaseRemoteAdapter = exports.NodeSQLiteAdapter = exports.SqlJsAdapter = exports.LibSQLAdapter = exports.BetterSQLite3Adapter = exports.OpSQLiteAdapter = exports.ExpoSQLiteAdapter = exports.LocalFirstClient = exports.resolveRemoteAdapter = exports.resolveLocalAdapter = void 0;
17
+ exports.SelfHostedRemoteAdapter = exports.FirestoreRemoteAdapter = exports.ConvexRemoteAdapter = exports.SupabaseRemoteAdapter = exports.NodeSQLiteAdapter = exports.SqlJsAdapter = exports.LibSQLAdapter = exports.BetterSQLite3Adapter = exports.OpSQLiteAdapter = exports.ExpoSQLiteAdapter = exports.LocalFirstClient = exports.resolveRemoteAdapter = exports.resolveLocalAdapter = void 0;
18
18
  exports.defineSyncConfig = defineSyncConfig;
19
19
  exports.createSyncClient = createSyncClient;
20
20
  const client_js_1 = require("../core/client.js");
@@ -51,9 +51,6 @@ var firestore_js_1 = require("../adapters/remote/firestore.js");
51
51
  Object.defineProperty(exports, "FirestoreRemoteAdapter", { enumerable: true, get: function () { return firestore_js_1.FirestoreRemoteAdapter; } });
52
52
  var self_hosted_js_1 = require("../adapters/remote/self-hosted.js");
53
53
  Object.defineProperty(exports, "SelfHostedRemoteAdapter", { enumerable: true, get: function () { return self_hosted_js_1.SelfHostedRemoteAdapter; } });
54
- var demo_js_1 = require("../adapters/remote/demo.js");
55
- Object.defineProperty(exports, "MemoryDemoRemoteAdapter", { enumerable: true, get: function () { return demo_js_1.MemoryDemoRemoteAdapter; } });
56
- Object.defineProperty(exports, "NoopRemoteAdapter", { enumerable: true, get: function () { return demo_js_1.NoopRemoteAdapter; } });
57
54
  /**
58
55
  * Type-safe configuration helper function (similar to defineConfig in Vite/Tailwind).
59
56
  */
@@ -64,9 +61,6 @@ function defineSyncConfig(config) {
64
61
  * Factory that instantiates, wires up, and initializes a LocalFirstClient from a LocalLiteConfig.
65
62
  */
66
63
  async function createSyncClient(config) {
67
- if ('migrations' in config) {
68
- throw new TypeError('The migrations option has been removed. Use schemaMigrations instead.');
69
- }
70
64
  // 1. Resolve Local Database Adapter
71
65
  const localAdapter = await (0, resolve_local_js_1.resolveLocalAdapter)(config);
72
66
  // 2. Resolve Remote Cloud Adapter
@@ -83,7 +77,7 @@ async function createSyncClient(config) {
83
77
  conflictResolver: config.conflictResolver ?? 'last-write-wins',
84
78
  pushIntervalMs: config.pushIntervalMs ?? 5000,
85
79
  pullIntervalMs: config.pullIntervalMs ?? 10000,
86
- maxRetries: config.maxRetries ?? 5,
80
+ requestTimeoutMs: config.requestTimeoutMs,
87
81
  retry: config.retry,
88
82
  logger: config.logger,
89
83
  logLevel: config.logLevel,
@@ -93,11 +87,10 @@ async function createSyncClient(config) {
93
87
  schemaMigrations: config.schemaMigrations,
94
88
  autoStart: config.autoStart,
95
89
  jsonColumns: config.jsonColumns,
96
- autoHydrateJSON: config.autoHydrateJSON,
97
90
  syncScope: config.syncScope,
98
91
  autoPauseOnBackground: config.autoPauseOnBackground,
99
92
  touchUpdatedAt: config.touchUpdatedAt,
100
- auth: config.auth ?? config.localAuth,
93
+ auth: config.auth,
101
94
  });
102
95
  // 5. Execute Migrations & Auto-initialize
103
96
  if (config.autoInitialize !== false) {
@@ -105,6 +98,9 @@ async function createSyncClient(config) {
105
98
  }
106
99
  // 6. Direct Email Dispatch (Nodemailer, Resend, SendGrid, Postmark, HTTP, etc.)
107
100
  if (config.email) {
101
+ if (config.email.transport || config.email.provider === 'nodemailer') {
102
+ throw new Error("Nodemailer email delivery is server-only. Import 'local-lite/server' and register createNodemailerHandler from your server runtime.");
103
+ }
108
104
  const { createEmailHandler } = await import('../email/index.js');
109
105
  const emailHandler = createEmailHandler({
110
106
  provider: config.email.provider,
@@ -212,6 +212,10 @@ export interface LocalLiteConfig {
212
212
  * Periodic remote pull interval in ms. Default: 10000
213
213
  */
214
214
  pullIntervalMs?: number;
215
+ /**
216
+ * Timeout in milliseconds for remote push/pull requests (0 to disable). Default: 30000
217
+ */
218
+ requestTimeoutMs?: number;
215
219
  /**
216
220
  * Automatically pause recurring sync timers and listeners when the app is backgrounded
217
221
  * (React Native AppState or Web Page Visibility API), and resume when foregrounded.
@@ -219,11 +223,7 @@ export interface LocalLiteConfig {
219
223
  */
220
224
  autoPauseOnBackground?: boolean;
221
225
  /**
222
- * Maximum retry attempts for failed push items. Default: 5
223
- */
224
- maxRetries?: number;
225
- /**
226
- * Advanced retry configuration with exponential backoff and custom retry predicates.
226
+ * Retry configuration (number of retries or detailed RetryConfig).
227
227
  */
228
228
  retry?: number | RetryConfig;
229
229
  /**
@@ -253,10 +253,6 @@ export interface LocalLiteConfig {
253
253
  * Explicitly configured JSON column map per table name.
254
254
  */
255
255
  jsonColumns?: Record<string, string[]>;
256
- /**
257
- * Automatically detect and hydrate stringified JSON objects and arrays across all columns.
258
- */
259
- autoHydrateJSON?: boolean;
260
256
  /**
261
257
  * Scoped synchronization filter (e.g. { org_id: '...' } or dynamic resolver callback).
262
258
  */
@@ -274,7 +270,6 @@ export interface LocalLiteConfig {
274
270
  * Options for the fully local, zero-backend authentication engine (`client.auth`).
275
271
  */
276
272
  auth?: LocalAuthEngineOptions;
277
- localAuth?: LocalAuthEngineOptions;
278
273
  /**
279
274
  * Direct email delivery configuration (Nodemailer SMTP, Resend, SendGrid, Postmark, or custom HTTP).
280
275
  * When set, `local-lite` handles all offline-queued emails directly without needing Convex,
@@ -37,7 +37,7 @@ export interface LocalFirstClientConfig {
37
37
  primaryKey?: string;
38
38
  pushIntervalMs?: number;
39
39
  pullIntervalMs?: number;
40
- maxRetries?: number;
40
+ requestTimeoutMs?: number;
41
41
  retry?: number | RetryConfig;
42
42
  logger?: SyncLogger | CustomLogger | boolean;
43
43
  logLevel?: LogLevel;
@@ -48,7 +48,6 @@ export interface LocalFirstClientConfig {
48
48
  autoStart?: boolean;
49
49
  coalesceOutbox?: boolean;
50
50
  jsonColumns?: Record<string, string[]>;
51
- autoHydrateJSON?: boolean;
52
51
  syncScope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>);
53
52
  autoPauseOnBackground?: boolean;
54
53
  /**
@@ -66,7 +65,6 @@ export interface LocalFirstClientConfig {
66
65
  storage?: BlobStorageManagerOptions;
67
66
  scheduler?: JobSchedulerOptions;
68
67
  session?: SessionManagerOptions;
69
- localAuth?: LocalAuthEngineOptions;
70
68
  auth?: LocalAuthEngineOptions;
71
69
  }
72
70
  export declare class TransactionalClient {
@@ -80,6 +78,8 @@ export declare class TransactionalClient {
80
78
  }>, queuedOutboxIds: string[]);
81
79
  mutate(tableName: string, rowId: string, operation: SyncOp, payload: Record<string, any> | null, options?: MutateOptions): Promise<void>;
82
80
  private deleteRelated;
81
+ private batchSetNull;
82
+ private batchDeleteRows;
83
83
  private applyMutation;
84
84
  insert(tableName: string, rowIdOrPayload: string | Record<string, any>, payloadOrOptions?: Record<string, any> | MutateOptions, options?: MutateOptions): Promise<string>;
85
85
  update(tableName: string, rowId: string, payload: Record<string, any>, options?: MutateOptions): Promise<void>;
@@ -95,10 +95,6 @@ export declare class TransactionalClient {
95
95
  includeDeleted?: boolean;
96
96
  }): Promise<T[]>;
97
97
  findMany<T = any>(tableName: string, options?: QueryOptions): Promise<T[]>;
98
- /**
99
- * Alias for findMany().
100
- */
101
- find<T = any>(tableName: string, options?: QueryOptions): Promise<T[]>;
102
98
  query<T = any>(sql: string, params?: any[]): Promise<T[]>;
103
99
  from<T = any>(tableName: string): QueryBuilder<T>;
104
100
  get rawTx(): LocalTransaction;
@@ -114,7 +110,6 @@ export declare class LocalFirstClient {
114
110
  tables: string[];
115
111
  relationships: RelationshipDefinition[];
116
112
  jsonColumns: Record<string, string[]>;
117
- autoHydrateJSON: boolean;
118
113
  /** Local column stamped on INSERT/UPDATE writes, or null when disabled. */
119
114
  touchColumn: string | null;
120
115
  readonly maintenance: DatabaseMaintenance;
@@ -298,10 +293,6 @@ export declare class LocalFirstClient {
298
293
  */
299
294
  aggregate(tableName: string, spec: AggregateSpec): Promise<AggregateResult>;
300
295
  findMany<T = any>(tableName: string, options?: QueryOptions): Promise<T[]>;
301
- /**
302
- * Alias for findMany().
303
- */
304
- find<T = any>(tableName: string, options?: QueryOptions): Promise<T[]>;
305
296
  /**
306
297
  * Returns true if client storage has successfully initialized.
307
298
  */