local-lite 2.0.7 → 3.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.
Files changed (82) hide show
  1. package/README.md +0 -30
  2. package/dist/adapters/local/index.d.ts +1 -0
  3. package/dist/adapters/local/index.js +1 -0
  4. package/dist/adapters/local/sqlite-wasm.d.ts +25 -0
  5. package/dist/adapters/local/sqlite-wasm.js +55 -0
  6. package/dist/adapters/remote/convex.d.ts +1 -1
  7. package/dist/adapters/remote/convex.js +25 -3
  8. package/dist/adapters/remote/demo.d.ts +3 -3
  9. package/dist/adapters/remote/demo.js +11 -3
  10. package/dist/adapters/remote/firestore.d.ts +1 -1
  11. package/dist/adapters/remote/firestore.js +57 -91
  12. package/dist/adapters/remote/index.d.ts +2 -1
  13. package/dist/adapters/remote/index.js +1 -0
  14. package/dist/adapters/remote/postgres.d.ts +37 -0
  15. package/dist/adapters/remote/postgres.js +119 -0
  16. package/dist/adapters/remote/self-hosted.d.ts +12 -0
  17. package/dist/adapters/remote/self-hosted.js +55 -4
  18. package/dist/adapters/remote/supabase.d.ts +1 -1
  19. package/dist/adapters/remote/supabase.js +22 -5
  20. package/dist/auth/apple.js +0 -6
  21. package/dist/auth/github.js +0 -3
  22. package/dist/auth/google.js +0 -3
  23. package/dist/auth/identity.d.ts +0 -5
  24. package/dist/auth/identity.js +0 -3
  25. package/dist/auth/microsoft.js +0 -3
  26. package/dist/auth/unified.d.ts +5 -5
  27. package/dist/auth/unified.js +1 -1
  28. package/dist/config/index.d.ts +0 -12
  29. package/dist/config/index.js +3 -26
  30. package/dist/config/types.d.ts +3 -2
  31. package/dist/core/audit.d.ts +52 -0
  32. package/dist/core/audit.js +153 -0
  33. package/dist/core/client.d.ts +4 -0
  34. package/dist/core/client.js +7 -0
  35. package/dist/core/conflict.d.ts +24 -0
  36. package/dist/core/conflict.js +77 -0
  37. package/dist/core/field-encryption.d.ts +25 -0
  38. package/dist/core/field-encryption.js +128 -0
  39. package/dist/core/index.d.ts +2 -0
  40. package/dist/core/index.js +2 -0
  41. package/dist/core/query-builder.d.ts +51 -0
  42. package/dist/core/query-builder.js +278 -35
  43. package/dist/core/query.js +6 -1
  44. package/dist/core/types.d.ts +2 -1
  45. package/dist/devtools/BenchmarkModal.js +285 -1
  46. package/dist/email/index.d.ts +1 -1
  47. package/dist/email/index.js +2 -2
  48. package/dist/index.d.ts +2 -27
  49. package/dist/index.js +2 -27
  50. package/dist/presence/index.d.ts +45 -0
  51. package/dist/presence/index.js +142 -0
  52. package/dist/reactive/event-emitter.d.ts +10 -1
  53. package/dist/reactive/event-emitter.js +44 -1
  54. package/dist/reactive/live-query.d.ts +18 -0
  55. package/dist/reactive/live-query.js +71 -0
  56. package/dist/schema/index.d.ts +1 -0
  57. package/dist/schema/index.js +1 -0
  58. package/dist/schema/typed.d.ts +38 -0
  59. package/dist/schema/typed.js +33 -0
  60. package/dist/server/dashboard.d.ts +2 -0
  61. package/dist/server/dashboard.js +182 -2
  62. package/dist/solid/index.d.ts +24 -0
  63. package/dist/solid/index.js +35 -0
  64. package/dist/storage/firebase.d.ts +3 -3
  65. package/dist/storage/firebase.js +40 -94
  66. package/dist/svelte/index.d.ts +15 -0
  67. package/dist/svelte/index.js +27 -0
  68. package/dist/testing/index.d.ts +22 -0
  69. package/dist/testing/index.js +74 -0
  70. package/dist/vue/index.d.ts +27 -0
  71. package/dist/vue/index.js +37 -0
  72. package/package.json +46 -9
  73. package/dist/kv/index.d.ts +0 -3
  74. package/dist/kv/index.js +0 -19
  75. package/dist/kv/manager.d.ts +0 -52
  76. package/dist/kv/manager.js +0 -167
  77. package/dist/kv/store.d.ts +0 -13
  78. package/dist/kv/store.js +0 -85
  79. package/dist/kv/types.d.ts +0 -27
  80. package/dist/kv/types.js +0 -2
  81. package/dist/react/kv.d.ts +0 -9
  82. package/dist/react/kv.js +0 -53
package/README.md CHANGED
@@ -59,39 +59,9 @@ to discard failed writes belong to the caller. The core does not inspect backend
59
59
  error codes to delete failed mutations. Conflict resolution and retry settings
60
60
  remain configurable; the existing default conflict strategy is last-write-wins.
61
61
 
62
- ### Compatibility changes from 0.0.3
63
-
64
- - Missing remote configuration now throws. Temporary demo behavior requires
65
- `inMemoryRemote: true`; it must never silently acknowledge production writes.
66
- - `autoSchema` now defaults to `false` in the configuration factory as well as the
67
- core constructor. Set `autoSchema: true` to retain inferred schema behavior.
68
- - Versioned `schemaMigrations` run transactionally before sync starts, including
69
- when initialization is deferred with `autoInitialize: false`.
70
- - `initialize()` is safe to call repeatedly or concurrently. After `stop()`, call
71
- `client.syncWorker.start()` to resume. Mutations after stop remain queued.
72
- - `autoStart: false` prepares storage without automatic sync. Explicit push/pull
73
- methods remain available. Stop does not cancel adapter calls already in flight.
74
- - Realtime changes update local rows without advancing the durable pull cursor.
75
- Custom pull adapters must return complete batches through their checkpoint and
76
- reject partial failures. Supabase table failures now reject the pull.
77
- - Custom realtime adapters must return an unsubscribe function; stopped workers
78
- ignore callbacks from a previous subscription.
79
-
80
62
  For an application-level upgrade checklist or AI-assisted code review, see the
81
63
  [Breaking Changes and AI Code-Review Guide](./docs/breaking-changes.md).
82
64
 
83
- ### Breaking changes in 0.0.30
84
-
85
- - The repeat-on-initialize `migrations` option has been removed. Move SQL into
86
- versioned `schemaMigrations`.
87
- - `ExpoFileDriver` now requires the Expo SDK 58+ `File`, `Directory`, and `Paths`
88
- APIs. Replace `fileSystem` injection with those named options.
89
- - Custom `RemoteDBAdapter.subscribeToLiveChanges()` implementations must return
90
- a cleanup function, including when no subscription is established.
91
- - `_migrations` is no longer treated as an internal table name.
92
- - FTS table creation no longer retries without the configured tokenizer; SQLite
93
- tokenizer errors now propagate.
94
-
95
65
  ## AI Skills
96
66
 
97
67
  The package ships [Agent Skills](./skills) that AI coding assistants can load:
@@ -14,3 +14,4 @@ export * from './better-sqlite3.js';
14
14
  export * from './libsql.js';
15
15
  export * from './sql-js.js';
16
16
  export * from './node-sqlite.js';
17
+ export * from './sqlite-wasm.js';
@@ -20,3 +20,4 @@ __exportStar(require("./better-sqlite3.js"), exports);
20
20
  __exportStar(require("./libsql.js"), exports);
21
21
  __exportStar(require("./sql-js.js"), exports);
22
22
  __exportStar(require("./node-sqlite.js"), exports);
23
+ __exportStar(require("./sqlite-wasm.js"), exports);
@@ -0,0 +1,25 @@
1
+ import { LocalDBAdapter, LocalTransaction } from './index.js';
2
+ export interface SqliteWasmExecOptions {
3
+ sql: string;
4
+ bind?: any[];
5
+ rowMode?: 'object' | 'array' | 'stmt';
6
+ returnValue?: 'resultRows' | 'saveSql';
7
+ }
8
+ export interface SqliteWasmDatabase {
9
+ exec(options: SqliteWasmExecOptions): any[];
10
+ exec(sql: string, options?: Omit<SqliteWasmExecOptions, 'sql'>): any[];
11
+ transaction?<T>(fn: () => T): T;
12
+ close?(): void;
13
+ }
14
+ /**
15
+ * Adapter for `@sqlite.org/sqlite-wasm` (oo1.DB / OpfsDb) for persistent OPFS-backed browser SQLite.
16
+ */
17
+ export declare class SqliteWasmAdapter implements LocalDBAdapter {
18
+ readonly supportsSqlPushdown = true;
19
+ private db;
20
+ private txQueue;
21
+ constructor(db: SqliteWasmDatabase);
22
+ execute(query: string, params?: any[]): Promise<any[]>;
23
+ transaction<T>(action: (tx: LocalTransaction) => Promise<T>): Promise<T>;
24
+ close(): void;
25
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SqliteWasmAdapter = void 0;
4
+ /**
5
+ * Adapter for `@sqlite.org/sqlite-wasm` (oo1.DB / OpfsDb) for persistent OPFS-backed browser SQLite.
6
+ */
7
+ class SqliteWasmAdapter {
8
+ supportsSqlPushdown = true;
9
+ db;
10
+ txQueue = Promise.resolve();
11
+ constructor(db) {
12
+ this.db = db;
13
+ }
14
+ async execute(query, params = []) {
15
+ const trimmed = query.trim();
16
+ const rows = this.db.exec({
17
+ sql: trimmed,
18
+ bind: params.length > 0 ? params : undefined,
19
+ rowMode: 'object',
20
+ returnValue: 'resultRows',
21
+ });
22
+ return Array.isArray(rows) ? rows : [];
23
+ }
24
+ async transaction(action) {
25
+ let release;
26
+ const prev = this.txQueue;
27
+ this.txQueue = new Promise((resolve) => {
28
+ release = resolve;
29
+ });
30
+ await prev;
31
+ const tx = {
32
+ execute: (query, params = []) => this.execute(query, params),
33
+ };
34
+ try {
35
+ await this.execute('BEGIN IMMEDIATE');
36
+ const result = await action(tx);
37
+ await this.execute('COMMIT');
38
+ return result;
39
+ }
40
+ catch (err) {
41
+ try {
42
+ await this.execute('ROLLBACK');
43
+ }
44
+ catch { }
45
+ throw err;
46
+ }
47
+ finally {
48
+ release();
49
+ }
50
+ }
51
+ close() {
52
+ this.db.close?.();
53
+ }
54
+ }
55
+ exports.SqliteWasmAdapter = SqliteWasmAdapter;
@@ -59,7 +59,7 @@ export declare class ConvexRemoteAdapter implements RemoteDBAdapter {
59
59
  /**
60
60
  * Pushes outbox operations as a batch mutation to Convex.
61
61
  */
62
- pushChanges(operations: SyncOperation[]): Promise<boolean | PushResult>;
62
+ pushChanges(operations: SyncOperation[]): Promise<PushResult>;
63
63
  /**
64
64
  * Fetches delta changes from Convex since a given timestamp.
65
65
  */
@@ -59,7 +59,7 @@ class ConvexRemoteAdapter {
59
59
  */
60
60
  async pushChanges(operations) {
61
61
  if (!operations || operations.length === 0) {
62
- return true;
62
+ return { success: true, successfulIds: [], failedIds: [] };
63
63
  }
64
64
  try {
65
65
  const payload = operations.map((op) => ({
@@ -74,17 +74,39 @@ class ConvexRemoteAdapter {
74
74
  operations: payload,
75
75
  });
76
76
  if (res && typeof res === 'object' && Array.isArray(res.failedIds)) {
77
+ const failedSet = new Set(res.failedIds);
77
78
  return {
78
79
  success: res.failedIds.length === 0,
80
+ successfulIds: operations
81
+ .filter((op) => !failedSet.has(op.id))
82
+ .map((op) => op.id),
79
83
  failedIds: res.failedIds,
80
84
  errors: res.errors,
81
85
  };
82
86
  }
83
- return res !== false;
87
+ if (res === false) {
88
+ return {
89
+ success: false,
90
+ successfulIds: [],
91
+ failedIds: operations.map((op) => op.id),
92
+ };
93
+ }
94
+ return {
95
+ success: true,
96
+ successfulIds: operations.map((op) => op.id),
97
+ failedIds: [],
98
+ };
84
99
  }
85
100
  catch (error) {
86
101
  this.logger.error((0, logger_js_1.formatConvexError)(error, { operation: 'pushChanges' }));
87
- return false;
102
+ return {
103
+ success: false,
104
+ successfulIds: [],
105
+ failedIds: operations.map((op) => op.id),
106
+ errors: {
107
+ _batch: error instanceof Error ? error.message : String(error),
108
+ },
109
+ };
88
110
  }
89
111
  }
90
112
  /**
@@ -1,5 +1,5 @@
1
1
  import { RemoteDBAdapter } from './index.js';
2
- import { DeltaChanges, SyncOperation } from '../../core/types.js';
2
+ import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
3
3
  /**
4
4
  * Built-in In-Memory Demo Remote Adapter.
5
5
  * Useful for prototyping, offline testing, and previewing without a live backend.
@@ -10,7 +10,7 @@ export declare class MemoryDemoRemoteAdapter implements RemoteDBAdapter {
10
10
  private liveSubscribers;
11
11
  private simulatedLatencyMs;
12
12
  constructor(simulatedLatencyMs?: number);
13
- pushChanges(operations: SyncOperation[]): Promise<boolean>;
13
+ pushChanges(operations: SyncOperation[]): Promise<PushResult>;
14
14
  fetchChanges(_sinceTimestamp: number): Promise<DeltaChanges>;
15
15
  subscribeToLiveChanges(callback: (changes: DeltaChanges) => void): () => void;
16
16
  /**
@@ -25,7 +25,7 @@ export declare class MemoryDemoRemoteAdapter implements RemoteDBAdapter {
25
25
  * and maintains zero cloud backend connections.
26
26
  */
27
27
  export declare class NoopRemoteAdapter implements RemoteDBAdapter {
28
- pushChanges(_operations: SyncOperation[]): Promise<boolean>;
28
+ pushChanges(operations: SyncOperation[]): Promise<PushResult>;
29
29
  fetchChanges(_sinceTimestamp: number): Promise<DeltaChanges>;
30
30
  subscribeToLiveChanges(_callback: (changes: DeltaChanges) => void): () => void;
31
31
  }
@@ -19,7 +19,11 @@ class MemoryDemoRemoteAdapter {
19
19
  }
20
20
  this.pushedBatches.push(operations);
21
21
  this.allPushedOperations.push(...operations);
22
- return true;
22
+ return {
23
+ success: true,
24
+ successfulIds: operations.map((op) => op.id),
25
+ failedIds: [],
26
+ };
23
27
  }
24
28
  async fetchChanges(_sinceTimestamp) {
25
29
  return {
@@ -53,8 +57,12 @@ exports.MemoryDemoRemoteAdapter = MemoryDemoRemoteAdapter;
53
57
  * and maintains zero cloud backend connections.
54
58
  */
55
59
  class NoopRemoteAdapter {
56
- async pushChanges(_operations) {
57
- return true;
60
+ async pushChanges(operations) {
61
+ return {
62
+ success: true,
63
+ successfulIds: operations.map((op) => op.id),
64
+ failedIds: [],
65
+ };
58
66
  }
59
67
  async fetchChanges(_sinceTimestamp) {
60
68
  return {
@@ -51,7 +51,7 @@ export declare class FirestoreRemoteAdapter implements RemoteDBAdapter {
51
51
  * Chunks operations into batches of 450 (below Firestore 500-write limit).
52
52
  * Falls back to individual writes if a batch fails, returning partial push results.
53
53
  */
54
- pushChanges(operations: SyncOperation[]): Promise<boolean | PushResult>;
54
+ pushChanges(operations: SyncOperation[]): Promise<PushResult>;
55
55
  /**
56
56
  * Fetches delta changes across tracked collections where updatedAt > sinceTimestamp.
57
57
  */
@@ -83,14 +83,15 @@ class FirestoreRemoteAdapter {
83
83
  */
84
84
  async pushChanges(operations) {
85
85
  if (!operations || operations.length === 0) {
86
- return true;
86
+ return { success: true, successfulIds: [], failedIds: [] };
87
87
  }
88
88
  const failedIds = [];
89
89
  const errors = {};
90
90
  try {
91
- const isCompat = typeof this.db.batch === 'function' &&
92
- typeof this.db.collection === 'function';
93
- const mod = isCompat ? null : await this.getModule();
91
+ const mod = await this.getModule();
92
+ if (!mod || typeof mod.writeBatch !== 'function') {
93
+ throw new Error('Modular firebase/firestore SDK (writeBatch, collection, doc) is required in local-lite v3.');
94
+ }
94
95
  const CHUNK_SIZE = 450;
95
96
  for (let i = 0; i < operations.length; i += CHUNK_SIZE) {
96
97
  const chunk = operations.slice(i, i + CHUNK_SIZE);
@@ -112,75 +113,61 @@ class FirestoreRemoteAdapter {
112
113
  };
113
114
  }
114
115
  };
115
- if (isCompat) {
116
- // React Native Firebase / Compat SDK
117
- try {
118
- const batch = this.db.batch();
119
- for (const op of chunk) {
120
- const docRef = this.db.collection(op.tableName).doc(op.rowId);
121
- batch.set(docRef, buildDocData(op), { merge: true });
122
- }
123
- await batch.commit();
124
- }
125
- catch (batchError) {
126
- this.logger.warn(`[Firestore] Batch write failed, falling back to per-document writes: ${batchError?.message || batchError}`);
127
- for (const op of chunk) {
128
- try {
129
- const docRef = this.db.collection(op.tableName).doc(op.rowId);
130
- await docRef.set(buildDocData(op), { merge: true });
131
- }
132
- catch (opErr) {
133
- failedIds.push(op.id);
134
- errors[op.id] = opErr?.message || String(opErr);
135
- }
136
- }
116
+ try {
117
+ const batch = mod.writeBatch(this.db);
118
+ for (const op of chunk) {
119
+ const docRef = mod.doc(mod.collection(this.db, op.tableName), op.rowId);
120
+ batch.set(docRef, buildDocData(op), { merge: true });
137
121
  }
122
+ await batch.commit();
138
123
  }
139
- else if (mod && typeof mod.writeBatch === 'function') {
140
- // Modular Firebase SDK
141
- try {
142
- const batch = mod.writeBatch(this.db);
143
- for (const op of chunk) {
124
+ catch (batchError) {
125
+ this.logger.warn(`[Firestore] Batch write failed, falling back to per-document writes: ${batchError?.message || batchError}`);
126
+ for (const op of chunk) {
127
+ try {
144
128
  const docRef = mod.doc(mod.collection(this.db, op.tableName), op.rowId);
145
- batch.set(docRef, buildDocData(op), { merge: true });
146
- }
147
- await batch.commit();
148
- }
149
- catch (batchError) {
150
- this.logger.warn(`[Firestore] Batch write failed, falling back to per-document writes: ${batchError?.message || batchError}`);
151
- for (const op of chunk) {
152
- try {
153
- const docRef = mod.doc(mod.collection(this.db, op.tableName), op.rowId);
154
- if (typeof mod.setDoc === 'function') {
155
- await mod.setDoc(docRef, buildDocData(op), { merge: true });
156
- }
157
- else {
158
- throw batchError;
159
- }
129
+ if (typeof mod.setDoc === 'function') {
130
+ await mod.setDoc(docRef, buildDocData(op), { merge: true });
160
131
  }
161
- catch (opErr) {
162
- failedIds.push(op.id);
163
- errors[op.id] = opErr?.message || String(opErr);
132
+ else {
133
+ throw batchError;
164
134
  }
165
135
  }
136
+ catch (opErr) {
137
+ failedIds.push(op.id);
138
+ errors[op.id] = opErr?.message || String(opErr);
139
+ }
166
140
  }
167
141
  }
168
- else {
169
- throw new Error('Firestore client does not have .batch() and modular firebase/firestore writeBatch could not be loaded.');
170
- }
171
142
  }
143
+ const failedSet = new Set(failedIds);
144
+ const successfulIds = operations
145
+ .filter((op) => !failedSet.has(op.id))
146
+ .map((op) => op.id);
172
147
  if (failedIds.length > 0) {
173
148
  return {
174
149
  success: false,
150
+ successfulIds,
175
151
  failedIds,
176
152
  errors,
177
153
  };
178
154
  }
179
- return true;
155
+ return {
156
+ success: true,
157
+ successfulIds,
158
+ failedIds: [],
159
+ };
180
160
  }
181
161
  catch (error) {
182
162
  this.logger.error((0, logger_js_1.formatFirestoreError)(error, { operation: 'pushChanges' }));
183
- return false;
163
+ return {
164
+ success: false,
165
+ successfulIds: [],
166
+ failedIds: operations.map((op) => op.id),
167
+ errors: {
168
+ _batch: error instanceof Error ? error.message : String(error),
169
+ },
170
+ };
184
171
  }
185
172
  }
186
173
  /**
@@ -191,28 +178,19 @@ class FirestoreRemoteAdapter {
191
178
  return { timestamp: sinceTimestamp, changes: [] };
192
179
  }
193
180
  try {
194
- const isCompat = typeof this.db.collection === 'function';
195
- const mod = isCompat ? null : await this.getModule();
181
+ const mod = await this.getModule();
182
+ if (!mod || typeof mod.getDocs !== 'function') {
183
+ throw new Error('Modular firebase/firestore SDK (getDocs, query, collection, where) is required in local-lite v3.');
184
+ }
196
185
  let maxServerTimestamp = sinceTimestamp;
197
186
  const changes = [];
198
187
  const CHUNK_SIZE = 5;
199
188
  for (let i = 0; i < this.tables.length; i += CHUNK_SIZE) {
200
189
  const chunk = this.tables.slice(i, i + CHUNK_SIZE);
201
190
  const results = await Promise.all(chunk.map(async (table) => {
202
- let docs = [];
203
- if (isCompat) {
204
- const snapshot = await this.db
205
- .collection(table)
206
- .where(this.updatedAtColumn, '>', sinceTimestamp)
207
- .get();
208
- docs = snapshot.docs || [];
209
- }
210
- else if (mod && typeof mod.getDocs === 'function') {
211
- const q = mod.query(mod.collection(this.db, table), mod.where(this.updatedAtColumn, '>', sinceTimestamp));
212
- const snapshot = await mod.getDocs(q);
213
- docs = snapshot.docs || [];
214
- }
215
- return { table, docs };
191
+ const q = mod.query(mod.collection(this.db, table), mod.where(this.updatedAtColumn, '>', sinceTimestamp));
192
+ const snapshot = await mod.getDocs(q);
193
+ return { table, docs: snapshot.docs || [] };
216
194
  }));
217
195
  for (const { table, docs } of results) {
218
196
  for (const doc of docs) {
@@ -260,10 +238,11 @@ class FirestoreRemoteAdapter {
260
238
  };
261
239
  }
262
240
  const setupListeners = async () => {
263
- const isCompat = typeof this.db.collection === 'function';
264
- const mod = isCompat ? null : await this.getModule();
241
+ const mod = await this.getModule();
265
242
  if (generation !== this.liveGeneration)
266
243
  return;
244
+ if (!mod || typeof mod.onSnapshot !== 'function')
245
+ return;
267
246
  const currentCursor = Date.now() - 2000;
268
247
  for (const table of this.tables) {
269
248
  if (generation !== this.liveGeneration)
@@ -315,25 +294,12 @@ class FirestoreRemoteAdapter {
315
294
  });
316
295
  }
317
296
  };
318
- if (isCompat) {
319
- const unsub = this.db
320
- .collection(table)
321
- .where(this.updatedAtColumn, '>', currentCursor)
322
- .onSnapshot(handleSnapshot, (err) => {
323
- console.warn(`Firestore onSnapshot error on ${table}:`, err);
324
- });
325
- if (typeof unsub === 'function') {
326
- this.unsubscribers.push(unsub);
327
- }
328
- }
329
- else if (mod && typeof mod.onSnapshot === 'function') {
330
- const q = mod.query(mod.collection(this.db, table), mod.where(this.updatedAtColumn, '>', currentCursor));
331
- const unsub = mod.onSnapshot(q, handleSnapshot, (err) => {
332
- console.warn(`Firestore modular onSnapshot error on ${table}:`, err);
333
- });
334
- if (typeof unsub === 'function') {
335
- this.unsubscribers.push(unsub);
336
- }
297
+ const q = mod.query(mod.collection(this.db, table), mod.where(this.updatedAtColumn, '>', currentCursor));
298
+ const unsub = mod.onSnapshot(q, handleSnapshot, (err) => {
299
+ console.warn(`Firestore modular onSnapshot error on ${table}:`, err);
300
+ });
301
+ if (typeof unsub === 'function') {
302
+ this.unsubscribers.push(unsub);
337
303
  }
338
304
  }
339
305
  catch (err) {
@@ -19,7 +19,7 @@ export interface RemoteRequestOptions {
19
19
  signal?: AbortSignal;
20
20
  }
21
21
  export interface RemoteDBAdapter {
22
- pushChanges(operations: SyncOperation[], options?: RemoteRequestOptions): Promise<boolean | PushResult>;
22
+ pushChanges(operations: SyncOperation[], options?: RemoteRequestOptions): Promise<PushResult>;
23
23
  /** Return a complete batch through timestamp; reject on partial failure. Supports optional scope for data filtering. */
24
24
  fetchChanges(sinceTimestamp: number, scope?: Record<string, any>, options?: RemoteRequestOptions): Promise<DeltaChanges>;
25
25
  /** Live events do not advance the durable pull checkpoint; return a cleanup function. */
@@ -43,3 +43,4 @@ export * from './demo.js';
43
43
  export * from './convex.js';
44
44
  export * from './firestore.js';
45
45
  export * from './self-hosted.js';
46
+ export * from './postgres.js';
@@ -19,3 +19,4 @@ __exportStar(require("./demo.js"), exports);
19
19
  __exportStar(require("./convex.js"), exports);
20
20
  __exportStar(require("./firestore.js"), exports);
21
21
  __exportStar(require("./self-hosted.js"), exports);
22
+ __exportStar(require("./postgres.js"), exports);
@@ -0,0 +1,37 @@
1
+ import { RemoteDBAdapter, RemoteRequestOptions } from './index.js';
2
+ import { DeltaChanges, PushResult, SyncOperation } from '../../core/types.js';
3
+ export interface PostgresQueryResult<T = any> {
4
+ rows: T[];
5
+ }
6
+ export interface PostgresExecutor {
7
+ query<T = any>(sql: string, params?: any[]): Promise<PostgresQueryResult<T>>;
8
+ }
9
+ export interface PostgresRemoteAdapterOptions {
10
+ /** Any `pg.Pool`, `pg.Client`, `@vercel/postgres`, or Drizzle-compatible query executor. */
11
+ executor: PostgresExecutor;
12
+ /** Tables to sync during pullChanges. */
13
+ tables: string[];
14
+ /** Primary key column name (default: 'id'). */
15
+ primaryKey?: string;
16
+ /** Timestamp column used for incremental pulls (default: 'updated_at'). */
17
+ updatedAtColumn?: string;
18
+ /** Optional PostgreSQL schema prefix (default: 'public'). */
19
+ schema?: string;
20
+ }
21
+ /**
22
+ * Turnkey PostgreSQL RemoteDBAdapter for Node/Serverless backends (pg, Vercel Postgres, Drizzle).
23
+ */
24
+ export declare class PostgresRemoteAdapter implements RemoteDBAdapter {
25
+ private executor;
26
+ private tables;
27
+ private primaryKey;
28
+ private updatedAtColumn;
29
+ private schema;
30
+ private syncScope?;
31
+ constructor(options: PostgresRemoteAdapterOptions);
32
+ private qualTable;
33
+ setSyncScope(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
34
+ pushChanges(operations: SyncOperation[], _options?: RemoteRequestOptions): Promise<PushResult>;
35
+ fetchChanges(sinceTimestamp: number, scope?: Record<string, any>, _options?: RemoteRequestOptions): Promise<DeltaChanges>;
36
+ subscribeToLiveChanges(_callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
37
+ }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PostgresRemoteAdapter = void 0;
4
+ function quotePgIdent(ident) {
5
+ return `"${ident.replace(/"/g, '""')}"`;
6
+ }
7
+ /**
8
+ * Turnkey PostgreSQL RemoteDBAdapter for Node/Serverless backends (pg, Vercel Postgres, Drizzle).
9
+ */
10
+ class PostgresRemoteAdapter {
11
+ executor;
12
+ tables;
13
+ primaryKey;
14
+ updatedAtColumn;
15
+ schema;
16
+ syncScope;
17
+ constructor(options) {
18
+ this.executor = options.executor;
19
+ this.tables = options.tables;
20
+ this.primaryKey = options.primaryKey ?? 'id';
21
+ this.updatedAtColumn = options.updatedAtColumn ?? 'updated_at';
22
+ this.schema = options.schema ?? 'public';
23
+ }
24
+ qualTable(table) {
25
+ return `${quotePgIdent(this.schema)}.${quotePgIdent(table)}`;
26
+ }
27
+ setSyncScope(scope) {
28
+ this.syncScope = scope;
29
+ }
30
+ async pushChanges(operations, _options) {
31
+ const successfulIds = [];
32
+ const failedIds = [];
33
+ for (const op of operations) {
34
+ const tableRef = this.qualTable(op.tableName);
35
+ const pkCol = quotePgIdent(this.primaryKey);
36
+ const tsCol = quotePgIdent(this.updatedAtColumn);
37
+ try {
38
+ if (op.operation === 'DELETE') {
39
+ await this.executor.query(`UPDATE ${tableRef} SET "deleted" = true, ${tsCol} = $1 WHERE ${pkCol} = $2`, [op.timestamp, op.rowId]);
40
+ }
41
+ else {
42
+ const payload = { ...(op.payload ?? {}) };
43
+ if (payload[this.primaryKey] === undefined) {
44
+ payload[this.primaryKey] = op.rowId;
45
+ }
46
+ if (payload[this.updatedAtColumn] === undefined) {
47
+ payload[this.updatedAtColumn] = op.timestamp;
48
+ }
49
+ const cols = Object.keys(payload);
50
+ const colIdents = cols.map(quotePgIdent).join(', ');
51
+ const placeholders = cols.map((_, idx) => `$${idx + 1}`).join(', ');
52
+ const values = cols.map((c) => payload[c]);
53
+ const updateSet = cols
54
+ .filter((c) => c !== this.primaryKey)
55
+ .map((c) => `${quotePgIdent(c)} = EXCLUDED.${quotePgIdent(c)}`)
56
+ .join(', ');
57
+ const sql = updateSet
58
+ ? `INSERT INTO ${tableRef} (${colIdents}) VALUES (${placeholders}) ON CONFLICT (${pkCol}) DO UPDATE SET ${updateSet}`
59
+ : `INSERT INTO ${tableRef} (${colIdents}) VALUES (${placeholders}) ON CONFLICT (${pkCol}) DO NOTHING`;
60
+ await this.executor.query(sql, values);
61
+ }
62
+ successfulIds.push(op.id);
63
+ }
64
+ catch {
65
+ failedIds.push(op.id);
66
+ }
67
+ }
68
+ return {
69
+ success: failedIds.length === 0,
70
+ successfulIds,
71
+ failedIds,
72
+ };
73
+ }
74
+ async fetchChanges(sinceTimestamp, scope, _options) {
75
+ const resolvedScope = scope ??
76
+ (typeof this.syncScope === 'function'
77
+ ? await this.syncScope()
78
+ : this.syncScope);
79
+ const changes = [];
80
+ let maxTimestamp = sinceTimestamp;
81
+ const tsCol = quotePgIdent(this.updatedAtColumn);
82
+ for (const table of this.tables) {
83
+ const tableRef = this.qualTable(table);
84
+ const params = [sinceTimestamp];
85
+ const whereParts = [`${tsCol} > $1`];
86
+ if (resolvedScope && typeof resolvedScope === 'object') {
87
+ for (const [k, v] of Object.entries(resolvedScope)) {
88
+ if (v !== undefined) {
89
+ params.push(v);
90
+ whereParts.push(`${quotePgIdent(k)} = $${params.length}`);
91
+ }
92
+ }
93
+ }
94
+ const sql = `SELECT * FROM ${tableRef} WHERE ${whereParts.join(' AND ')} ORDER BY ${tsCol} ASC`;
95
+ const res = await this.executor.query(sql, params);
96
+ for (const row of res.rows ?? []) {
97
+ const ts = Number(row?.[this.updatedAtColumn]) || Date.now();
98
+ if (ts > maxTimestamp)
99
+ maxTimestamp = ts;
100
+ const isDeleted = row?.deleted === true || row?.deleted === 1 || row?.deleted === 'true';
101
+ changes.push({
102
+ tableName: table,
103
+ rowId: String(row?.[this.primaryKey] ?? ''),
104
+ operation: isDeleted ? 'DELETE' : 'UPDATE',
105
+ payload: isDeleted ? null : row,
106
+ timestamp: ts,
107
+ });
108
+ }
109
+ }
110
+ return { timestamp: maxTimestamp, changes };
111
+ }
112
+ subscribeToLiveChanges(_callback, scope) {
113
+ if (scope) {
114
+ this.syncScope = scope;
115
+ }
116
+ return () => { };
117
+ }
118
+ }
119
+ exports.PostgresRemoteAdapter = PostgresRemoteAdapter;