local-lite 0.0.30 → 0.1.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 (42) hide show
  1. package/README.md +25 -20
  2. package/dist/adapters/remote/firestore.d.ts +2 -1
  3. package/dist/adapters/remote/firestore.js +21 -3
  4. package/dist/adapters/remote/index.d.ts +2 -2
  5. package/dist/adapters/remote/supabase.d.ts +1 -1
  6. package/dist/config/index.js +3 -1
  7. package/dist/config/types.d.ts +0 -5
  8. package/dist/core/client.d.ts +1 -3
  9. package/dist/core/client.js +4 -11
  10. package/dist/search/store.js +1 -12
  11. package/dist/storage/expo.d.ts +4 -66
  12. package/dist/storage/expo.js +104 -261
  13. package/dist/utils/sql.js +1 -1
  14. package/docs/.nojekyll +1 -0
  15. package/docs/README.md +108 -0
  16. package/docs/_sidebar.md +22 -0
  17. package/docs/actions-email.md +222 -0
  18. package/docs/adapters-local.md +272 -0
  19. package/docs/adapters-remote.md +291 -0
  20. package/docs/api-keys.md +114 -0
  21. package/docs/architecture.md +106 -0
  22. package/docs/auth.md +259 -0
  23. package/docs/backups.md +214 -0
  24. package/docs/breaking-changes.md +147 -0
  25. package/docs/client-api.md +412 -0
  26. package/docs/configuration.md +228 -0
  27. package/docs/conflict-resolution.md +78 -0
  28. package/docs/getting-started.md +190 -0
  29. package/docs/google-auth.md +234 -0
  30. package/docs/index.html +166 -0
  31. package/docs/kv.md +89 -0
  32. package/docs/maintenance-portability.md +133 -0
  33. package/docs/react-hooks.md +457 -0
  34. package/docs/scheduler.md +81 -0
  35. package/docs/search.md +71 -0
  36. package/docs/server.md +101 -0
  37. package/docs/session.md +129 -0
  38. package/docs/storage.md +265 -0
  39. package/package.json +3 -1
  40. package/skills/local-lite-custom-adapter/SKILL.md +59 -0
  41. package/skills/local-lite-setup/SKILL.md +21 -0
  42. package/skills/local-lite-upgrade/SKILL.md +16 -0
package/README.md CHANGED
@@ -64,9 +64,7 @@ remain configurable; the existing default conflict strategy is last-write-wins.
64
64
  - `autoSchema` now defaults to `false` in the configuration factory as well as the
65
65
  core constructor. Set `autoSchema: true` to retain inferred schema behavior.
66
66
  - Versioned `schemaMigrations` run transactionally before sync starts, including
67
- when initialization is deferred with `autoInitialize: false`. The existing
68
- `migrations` option remains available for legacy idempotent SQL that runs on
69
- every initialization.
67
+ when initialization is deferred with `autoInitialize: false`.
70
68
  - `initialize()` is safe to call repeatedly or concurrently. After `stop()`, call
71
69
  `client.syncWorker.start()` to resume. Mutations after stop remain queued.
72
70
  - `autoStart: false` prepares storage without automatic sync. Explicit push/pull
@@ -74,8 +72,30 @@ remain configurable; the existing default conflict strategy is last-write-wins.
74
72
  - Realtime changes update local rows without advancing the durable pull cursor.
75
73
  Custom pull adapters must return complete batches through their checkpoint and
76
74
  reject partial failures. Supabase table failures now reject the pull.
77
- - Custom realtime adapters may return an unsubscribe function. Legacy adapters
78
- returning void remain supported; stopped workers ignore their later callbacks.
75
+ - Custom realtime adapters must return an unsubscribe function; stopped workers
76
+ ignore callbacks from a previous subscription.
77
+
78
+ For an application-level upgrade checklist or AI-assisted code review, see the
79
+ [Breaking Changes and AI Code-Review Guide](./docs/breaking-changes.md).
80
+
81
+ ### Breaking changes in 0.0.30
82
+
83
+ - The repeat-on-initialize `migrations` option has been removed. Move SQL into
84
+ versioned `schemaMigrations`.
85
+ - `ExpoFileDriver` now requires the Expo SDK 58+ `File`, `Directory`, and `Paths`
86
+ APIs. Replace `fileSystem` injection with those named options.
87
+ - Custom `RemoteDBAdapter.subscribeToLiveChanges()` implementations must return
88
+ a cleanup function, including when no subscription is established.
89
+ - `_migrations` is no longer treated as an internal table name.
90
+ - FTS table creation no longer retries without the configured tokenizer; SQLite
91
+ tokenizer errors now propagate.
92
+
93
+ ## AI Skills
94
+
95
+ The package ships [Agent Skills](./skills) that AI coding assistants can load:
96
+ `local-lite-setup`, `local-lite-custom-adapter` and `local-lite-upgrade`. Copy
97
+ the folders from `node_modules/local-lite/skills/` into `.github/skills/`
98
+ (Copilot) or `.claude/skills/` (Claude Code).
79
99
 
80
100
  ## Features
81
101
 
@@ -522,21 +542,6 @@ SyncWorker
522
542
 
523
543
  ---
524
544
 
525
- ## Example App
526
-
527
- An interactive Expo app is included in the [`example/`](./example) directory demonstrating:
528
- - Rental property & tenant management application
529
- - Live SQLite reads and atomic dual-writes
530
- - Network online/offline toggle simulation
531
- - Real-time `sync_outbox` inspector
532
- - Simulated server delta broadcasts
533
-
534
- To run the example:
535
- ```bash
536
- cd example
537
- npm start
538
- ```
539
-
540
545
  ---
541
546
 
542
547
  ## Testing
@@ -41,6 +41,7 @@ export declare class FirestoreRemoteAdapter implements RemoteDBAdapter {
41
41
  private updatedAtColumn;
42
42
  private firestoreModule;
43
43
  private unsubscribers;
44
+ private liveGeneration;
44
45
  logger: SyncLogger;
45
46
  constructor(db: any, options?: FirestoreAdapterOptions);
46
47
  setTables(tables: string[]): void;
@@ -58,7 +59,7 @@ export declare class FirestoreRemoteAdapter implements RemoteDBAdapter {
58
59
  /**
59
60
  * Subscribes to live real-time query updates via onSnapshot.
60
61
  */
61
- subscribeToLiveChanges(callback: (changes: DeltaChanges) => void): void;
62
+ subscribeToLiveChanges(callback: (changes: DeltaChanges) => void): () => void;
62
63
  /**
63
64
  * Cleans up all active real-time listeners.
64
65
  */
@@ -46,6 +46,7 @@ class FirestoreRemoteAdapter {
46
46
  updatedAtColumn;
47
47
  firestoreModule;
48
48
  unsubscribers = [];
49
+ liveGeneration = 0;
49
50
  logger;
50
51
  constructor(db, options = {}) {
51
52
  if (!db) {
@@ -250,17 +251,25 @@ class FirestoreRemoteAdapter {
250
251
  */
251
252
  subscribeToLiveChanges(callback) {
252
253
  this.destroy();
254
+ const generation = this.liveGeneration;
253
255
  if (!this.tables || this.tables.length === 0) {
254
- return;
256
+ return () => {
257
+ if (generation === this.liveGeneration)
258
+ this.destroy();
259
+ };
255
260
  }
256
261
  const setupListeners = async () => {
257
262
  const isCompat = typeof this.db.collection === 'function';
258
263
  const mod = isCompat ? null : await this.getModule();
264
+ if (generation !== this.liveGeneration)
265
+ return;
259
266
  const currentCursor = Date.now() - 2000;
260
267
  for (const table of this.tables) {
268
+ if (generation !== this.liveGeneration)
269
+ return;
261
270
  try {
262
271
  const handleSnapshot = (snapshot) => {
263
- if (!snapshot)
272
+ if (generation !== this.liveGeneration || !snapshot)
264
273
  return;
265
274
  let docList = [];
266
275
  if (typeof snapshot.docChanges === 'function') {
@@ -328,12 +337,21 @@ class FirestoreRemoteAdapter {
328
337
  }
329
338
  }
330
339
  };
331
- setupListeners();
340
+ void setupListeners().catch((err) => {
341
+ if (generation === this.liveGeneration) {
342
+ console.warn('Failed to initialize Firestore live listeners:', err);
343
+ }
344
+ });
345
+ return () => {
346
+ if (generation === this.liveGeneration)
347
+ this.destroy();
348
+ };
332
349
  }
333
350
  /**
334
351
  * Cleans up all active real-time listeners.
335
352
  */
336
353
  destroy() {
354
+ this.liveGeneration++;
337
355
  for (const unsub of this.unsubscribers) {
338
356
  try {
339
357
  unsub();
@@ -3,8 +3,8 @@ export interface RemoteDBAdapter {
3
3
  pushChanges(operations: SyncOperation[]): Promise<boolean | PushResult>;
4
4
  /** Return a complete batch through timestamp; reject on partial failure. Supports optional scope for data filtering. */
5
5
  fetchChanges(sinceTimestamp: number, scope?: Record<string, any>): Promise<DeltaChanges>;
6
- /** Live events do not advance the durable pull checkpoint. Return cleanup when supported. */
7
- subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void | (() => void);
6
+ /** Live events do not advance the durable pull checkpoint; return a cleanup function. */
7
+ subscribeToLiveChanges(callback: (changes: DeltaChanges) => void, scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): () => void;
8
8
  setSyncScope?(scope?: Record<string, any> | (() => Record<string, any> | Promise<Record<string, any>>)): void;
9
9
  }
10
10
  export * from './supabase.js';
@@ -119,7 +119,7 @@ export declare class SupabaseRemoteAdapter implements RemoteDBAdapter {
119
119
  * Subscribes to live realtime postgres_changes from Supabase.
120
120
  * Batches rapid burst events in the same microtask turn into a single SQLite sync transaction.
121
121
  */
122
- subscribeToLiveChanges(callback: (changes: DeltaChanges) => void): (() => void) | void;
122
+ subscribeToLiveChanges(callback: (changes: DeltaChanges) => void): () => void;
123
123
  /**
124
124
  * Clean up active realtime channels.
125
125
  */
@@ -62,6 +62,9 @@ function defineSyncConfig(config) {
62
62
  * Factory that instantiates, wires up, and initializes a LocalFirstClient from a LocalLiteConfig.
63
63
  */
64
64
  async function createSyncClient(config) {
65
+ if ('migrations' in config) {
66
+ throw new TypeError('The migrations option has been removed. Use schemaMigrations instead.');
67
+ }
65
68
  // 1. Resolve Local Database Adapter
66
69
  const localAdapter = await (0, resolve_local_js_1.resolveLocalAdapter)(config);
67
70
  // 2. Resolve Remote Cloud Adapter
@@ -85,7 +88,6 @@ async function createSyncClient(config) {
85
88
  autoSchema,
86
89
  tables: config.tables ?? [],
87
90
  relationships: config.relationships ?? [],
88
- migrations: config.migrations,
89
91
  schemaMigrations: config.schemaMigrations,
90
92
  autoStart: config.autoStart,
91
93
  jsonColumns: config.jsonColumns,
@@ -90,11 +90,6 @@ export interface LocalLiteConfig {
90
90
  * Deletes through client.delete(), client.mutate(..., 'DELETE'), or batch are handled atomically.
91
91
  */
92
92
  relationships?: RelationshipDefinition[];
93
- /**
94
- * Legacy idempotent SQL statements executed transactionally on every initialization.
95
- * e.g. ["CREATE TABLE IF NOT EXISTS todos (id TEXT PRIMARY KEY, title TEXT);"]
96
- */
97
- migrations?: string[];
98
93
  /**
99
94
  * Versioned application schema migrations. Versions must be consecutive integers
100
95
  * starting at 1; each migration is applied once and recorded in schema_migrations.
@@ -43,7 +43,6 @@ export interface LocalFirstClientConfig {
43
43
  autoSchema?: boolean;
44
44
  tables?: string[];
45
45
  relationships?: RelationshipDefinition[];
46
- migrations?: string[];
47
46
  schemaMigrations?: SchemaMigration[];
48
47
  autoStart?: boolean;
49
48
  coalesceOutbox?: boolean;
@@ -124,7 +123,6 @@ export declare class LocalFirstClient {
124
123
  readonly scheduler: JobScheduler;
125
124
  readonly session: SessionManager;
126
125
  private primaryKey;
127
- private migrations;
128
126
  private schemaMigrations;
129
127
  private autoStart;
130
128
  private initialization?;
@@ -152,7 +150,7 @@ export declare class LocalFirstClient {
152
150
  recordOutboxMutation(tx: LocalTransaction, tableName: string, rowId: string, operation: SyncOp, payload: Record<string, any> | null, timestamp: number, pendingOutboxMap?: Map<string, OutboxRecord>): Promise<string | undefined>;
153
151
  /**
154
152
  * Initializes the client: creates sync_outbox schema, ensures autoSchema tables if enabled,
155
- * applies migrations, and optionally starts automatic sync. Concurrent/repeated calls
153
+ * applies schema migrations, and optionally starts automatic sync. Concurrent/repeated calls
156
154
  * share initialization; failures can be retried. After stop(), explicitly start the worker.
157
155
  */
158
156
  initialize(): Promise<void>;
@@ -247,11 +247,13 @@ class LocalFirstClient {
247
247
  scheduler;
248
248
  session;
249
249
  primaryKey;
250
- migrations;
251
250
  schemaMigrations;
252
251
  autoStart;
253
252
  initialization;
254
253
  constructor(config) {
254
+ if ('migrations' in config) {
255
+ throw new TypeError('The migrations option has been removed. Use schemaMigrations instead.');
256
+ }
255
257
  this.db = config.local;
256
258
  this.remote = config.remote;
257
259
  this.events = new event_emitter_js_1.EventEmitter();
@@ -284,7 +286,6 @@ class LocalFirstClient {
284
286
  }
285
287
  relationshipKeys.add(key);
286
288
  }
287
- this.migrations = config.migrations ?? [];
288
289
  this.schemaMigrations = normalizeSchemaMigrations(config.schemaMigrations ?? []);
289
290
  this.autoStart = config.autoStart ?? true;
290
291
  this.jsonColumns = config.jsonColumns ?? {};
@@ -470,7 +471,7 @@ class LocalFirstClient {
470
471
  }
471
472
  /**
472
473
  * Initializes the client: creates sync_outbox schema, ensures autoSchema tables if enabled,
473
- * applies migrations, and optionally starts automatic sync. Concurrent/repeated calls
474
+ * applies schema migrations, and optionally starts automatic sync. Concurrent/repeated calls
474
475
  * share initialization; failures can be retried. After stop(), explicitly start the worker.
475
476
  */
476
477
  async initialize() {
@@ -501,14 +502,6 @@ class LocalFirstClient {
501
502
  await this.storage.initialize();
502
503
  await this.scheduler.initialize();
503
504
  await this.session.initialize();
504
- if (this.migrations.length > 0) {
505
- await this.db.transaction(async (tx) => {
506
- for (const query of this.migrations) {
507
- if (query.trim())
508
- await tx.execute(query);
509
- }
510
- });
511
- }
512
505
  await this.applySchemaMigrations();
513
506
  if (this.autoSchema && this.tables.length > 0) {
514
507
  for (const table of this.tables) {
@@ -16,18 +16,7 @@ class SearchStore {
16
16
  // row_id is UNINDEXED in FTS5 so it does not pollute search tokens
17
17
  const columnDefs = ['row_id UNINDEXED', ...cols].join(', ');
18
18
  const sql = `CREATE VIRTUAL TABLE IF NOT EXISTS ${ftsTable} USING fts5(${columnDefs}, tokenize='${tokenize}');`;
19
- try {
20
- await db.execute(sql);
21
- }
22
- catch (err) {
23
- // In case tokenize='unicode61' isn't supported by legacy SQLite build, retry without tokenize option
24
- if (err?.message?.includes('tokenize') || err?.message?.includes('unknown tokenizer')) {
25
- await db.execute(`CREATE VIRTUAL TABLE IF NOT EXISTS ${ftsTable} USING fts5(${columnDefs});`);
26
- }
27
- else {
28
- throw err;
29
- }
30
- }
19
+ await db.execute(sql);
31
20
  }
32
21
  /**
33
22
  * Drops the FTS5 virtual table.
@@ -1,59 +1,7 @@
1
1
  import { FileDriver } from './types.js';
2
- export interface ExpoFileSystemModule {
3
- File?: any;
4
- Directory?: any;
5
- Paths?: any;
6
- documentDirectory?: string | null;
7
- cacheDirectory?: string | null;
8
- EncodingType?: {
9
- UTF8: string;
10
- Base64: string;
11
- };
12
- getInfoAsync?(fileUri: string, options?: {
13
- md5?: boolean;
14
- size?: boolean;
15
- }): Promise<{
16
- exists: boolean;
17
- isDirectory?: boolean;
18
- size?: number;
19
- uri?: string;
20
- }>;
21
- writeAsStringAsync?(fileUri: string, contents: string, options?: {
22
- encoding?: string;
23
- }): Promise<void>;
24
- readAsStringAsync?(fileUri: string, options?: {
25
- encoding?: string;
26
- length?: number;
27
- position?: number;
28
- }): Promise<string>;
29
- makeDirectoryAsync?(fileUri: string, options?: {
30
- intermediates?: boolean;
31
- }): Promise<void>;
32
- deleteAsync?(fileUri: string, options?: {
33
- idempotent?: boolean;
34
- }): Promise<void>;
35
- copyAsync?(options: {
36
- from: string;
37
- to: string;
38
- }): Promise<void>;
39
- moveAsync?(options: {
40
- from: string;
41
- to: string;
42
- }): Promise<void>;
43
- downloadAsync?(url: string, fileUri: string, options?: {
44
- md5?: boolean;
45
- headers?: Record<string, string>;
46
- sessionType?: any;
47
- }): Promise<{
48
- uri: string;
49
- status: number;
50
- headers: Record<string, string>;
51
- md5?: string;
52
- }>;
53
- }
54
2
  export interface ExpoFileDriverOptions {
55
3
  /**
56
- * The modern `File` class from `expo-file-system` (SDK >57/58).
4
+ * The modern `File` class from `expo-file-system` (SDK 57+).
57
5
  * e.g. `import { File } from 'expo-file-system'`
58
6
  */
59
7
  File?: any;
@@ -67,11 +15,6 @@ export interface ExpoFileDriverOptions {
67
15
  * e.g. `import { Paths } from 'expo-file-system'`
68
16
  */
69
17
  Paths?: any;
70
- /**
71
- * The `expo-file-system` module instance.
72
- * e.g. `import * as FileSystem from 'expo-file-system'`
73
- */
74
- fileSystem?: ExpoFileSystemModule | any;
75
18
  /**
76
19
  * Base directory path or `Directory` instance for storing files.
77
20
  * Defaults to: `new Directory(Paths.document, 'local-lite-blobs')`
@@ -91,30 +34,25 @@ export declare function bytesToBase64(bytes: Uint8Array): string;
91
34
  export declare function base64ToBytes(base64: string): Uint8Array;
92
35
  /**
93
36
  * FileDriver implementation for Expo / React Native environments.
94
- * Uses modern Expo (>57/58) `File`, `Directory`, and `Paths` APIs when available,
95
- * with seamless fallback for legacy `expo-file-system` environments.
37
+ * Uses the Expo SDK 58+ `File`, `Directory`, and `Paths` APIs.
96
38
  */
97
39
  export declare class ExpoFileDriver implements FileDriver {
98
40
  private FileClass?;
99
41
  private DirectoryClass?;
100
42
  private PathsObj?;
101
- private legacyFs?;
102
43
  private baseDirOption?;
103
44
  private useCache;
104
45
  private resolvedBaseDir;
105
46
  private resolvedBaseDirPath;
106
- private ensuredDirs;
107
47
  constructor(options?: ExpoFileDriverOptions);
108
48
  private resolveClasses;
109
49
  private getBaseDirectory;
110
50
  /**
111
- * Resolves a key to a modern Expo `File` instance (if File class is available)
112
- * or a string URI path.
51
+ * Resolves a key to a modern Expo `File` instance.
113
52
  */
114
- private resolveFileOrUri;
53
+ private resolveFile;
115
54
  resolveUri(key: string): Promise<string>;
116
55
  getUri(key: string): Promise<string>;
117
- private ensureDirectory;
118
56
  write(key: string, data: Uint8Array): Promise<string>;
119
57
  read(key: string): Promise<Uint8Array | null>;
120
58
  delete(key: string): Promise<void>;