### Basic Setup with startSync and defineRoutes Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/examples/basic-usage.md Complete basic workflow for setting up Dexie, defining push/pull routes, starting sync, handling events, and manually syncing. Includes auth headers, conflict policy, checkpoint-based pull, and metrics retrieval. ```typescript import Dexie from 'dexie'; import { startSync, defineRoutes } from '@dexie-kit/sync'; // 1. Define your database. Primary keys are client-generated (no `++`) — // see the "ID Strategies" section of the README for why. const db = new Dexie('myapp'); db.version(1).stores({ posts: 'id, title, content, updatedAt, version', comments: 'id, postId, content, updatedAt', }); // 2. Configure routes const routes = defineRoutes({ posts: { // Push configuration (local -> server) push: { create: { method: 'POST', url: '/api/posts', body: (item) => ({ title: item.title, content: item.content, updatedAt: item.updatedAt, }), }, update: { method: 'PUT', url: (item) => `/api/posts/${item.id}`, body: (item) => ({ title: item.title, content: item.content, updatedAt: item.updatedAt, version: item.version, }), }, delete: { method: 'DELETE', url: (item) => `/api/posts/${item.id}`, }, }, // Pull configuration (server -> local) pull: { method: 'GET', url: '/api/posts', query: async (ctx) => { const lastSync = await ctx.getCheckpoint('pull:posts'); return { updated_after: lastSync || 0, limit: 100, }; }, mapResponse: (response) => response.data, onComplete: async (response, ctx) => { if (response.data.length > 0) { const latest = Math.max( ...response.data.map((p: any) => new Date(p.updatedAt).getTime()) ); await ctx.setCheckpoint('pull:posts', latest); } }, }, }, }); // 3. Start sync const syncEngine = startSync(db, { baseUrl: 'https://api.example.com', auth: { getHeaders: async () => { // Get your auth token const token = localStorage.getItem('auth_token'); return { 'Authorization': `Bearer ${token}`, }; }, onAuthError: async (error) => { if (error.status === 401) { // Refresh token or redirect to login console.log('Auth error, please login again'); } }, }, routes, conflicts: { policy: 'server-wins', // or 'client-wins', 'lww', 'custom' }, sync: { interval: 30000, // Sync every 30 seconds onOnline: true, // Sync when coming online }, }); // 4. Start the sync engine await syncEngine.start(); // 5. Use your app normally — the id is assigned on the client await db.posts.add({ id: crypto.randomUUID(), title: 'My First Post', content: 'Hello World!', updatedAt: new Date().toISOString(), version: 1, }); // Changes are automatically queued and synced! // Listen to events syncEngine.on('sync-complete', (result) => { console.log('Sync complete:', result); console.log(`Pushed: ${result.push.pushed}, Pulled: ${result.pull.pulled}`); }); syncEngine.on('sync-error', (error) => { console.error('Sync failed:', error); }); // Manually trigger sync await syncEngine.sync(); // Check status const status = syncEngine.getStatus(); console.log('Status:', status); // Get metrics const metrics = await syncEngine.getMetrics(); console.log('Queue depth:', metrics.queue.depth); console.log('Last sync:', new Date(metrics.sync.lastSyncCompleted)); ``` -------------------------------- ### Basic startSync usage Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/start-sync.md Basic usage example of startSync with a client-generated id (no auto-increment) and a full configuration including routes, auth, and conflict policy. It creates a Dexie database, defines a posts table, and starts the sync engine. ```typescript import Dexie from 'dexie'; import { startSync, defineRoutes } from '@dexie-kit/sync'; const db = new Dexie('myapp'); db.version(1).stores({ posts: 'id, title, updatedAt', // client-generated id — no `++` }); const engine = startSync(db, { baseUrl: 'https://api.example.com', routes: defineRoutes({ posts: { push: { create: { method: 'POST', url: '/api/posts', body: (item) => item }, }, pull: { method: 'GET', url: '/api/posts', mapResponse: (r) => r.data }, }, }), auth: { getHeaders: async () => ({ Authorization: `Bearer ${token}` }), }, conflicts: { policy: 'server-wins' }, }); await engine.start(); ``` -------------------------------- ### SyncEngine start method Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Starts the sync engine: elects a leader, starts change tracking, and if leader, starts the interval and performs an initial sync. No-op if already running. Throws errors from initial sync, leader election, or startTracking. ```typescript async start(): Promise ``` -------------------------------- ### start(): Promise Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Elects a leader (only the leader tab runs sync), starts change tracking on the configured tables, and if this tab is leader, starts the interval and performs an initial sync(). No-op if already running. ```APIDOC ## start(): Promise ### Description Elects a leader (only the leader tab runs sync), starts change tracking on the configured tables, and if this tab is leader, starts the interval and performs an initial sync(). No-op if already running. ### Method start ### Signature ```typescript async start(): Promise ``` ### Throws Propagates any error from the initial sync(), leader election, or startTracking. ``` -------------------------------- ### Lifecycle example with error handling Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Example lifecycle usage with error handling: start the engine, catch initial sync errors, stop on failure, then pause and resume. ```typescript const engine = startSync(db, config); try { await engine.start(); // elects leader + initial sync } catch (err) { console.error('Initial sync failed', err); await engine.stop(); } await engine.pause(); // background sync stops await engine.resume(); // sync runs immediately again ``` -------------------------------- ### Usage example - selecting a built-in policy Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/conflict-strategies.md Selects the built-in 'lww' policy when starting sync. The routes property is a placeholder for the actual routes configuration. ```typescript import { startSync } from '@dexie-kit/sync'; const engine = startSync(db, { baseUrl: 'https://api.example.com', routes /* ... */, auth: { getHeaders: async () => ({}) }, conflicts: { policy: 'lww' }, }); ``` -------------------------------- ### Example workflow for publishing with Changesets Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/PUBLISHING.md A complete example workflow: create a feature branch, create a changeset, commit and push, then merge the PR. After merging, a 'Version Packages' PR is created automatically and must be reviewed and merged to publish. ```bash # Make your changes git checkout -b feature/my-feature # Create a changeset npm run changeset # Select "minor" for a new feature # Write: "Add support for custom retry strategies" # Commit and push git add . git commit -m "feat: add custom retry strategies" git push origin feature/my-feature # Create and merge PR # The changeset file will be included # After merge, a "Version Packages" PR will be created automatically # Review and merge it to publish to npm ``` -------------------------------- ### Install dependencies Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Install @dexie-kit/sync and dexie via npm Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/README.md Install the @dexie-kit/sync package and its peer dependency Dexie.js using npm. ```bash npm install @dexie-kit/sync dexie ``` -------------------------------- ### startSync(db, config) Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/README.md Starts synchronization for a Dexie database with a given configuration. ```APIDOC ## [SYNC] [startSync(db, config)] ### Description Starts synchronization for a Dexie database with the provided configuration. ### Parameters - `db: Dexie` - Required - The Dexie database instance to sync. - `config: SyncConfig` - Required - Configuration object for sync behavior. ### Returns - `SyncEngine` - The sync engine instance for controlling and monitoring sync. ``` -------------------------------- ### Full SyncConfig example with routes, auth, and sync options Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/configuration.md Shows the complete configuration for startSync, including defineRoutes for push and pull operations, auth headers, table selection, sync interval, conflict policy, and error retry settings. All options are passed via SyncConfig; no environment variables are used. ```typescript import Dexie from 'dexie'; import { startSync, defineRoutes } from '@dexie-kit/sync'; const engine = startSync(db, { baseUrl: 'https://api.example.com', routes: defineRoutes({ posts: { push: { create: { method: 'POST', url: '/api/posts', body: (item) => item }, update: { method: 'PUT', url: (item) => `/api/posts/${item.id}`, body: (item) => item, }, delete: { method: 'DELETE', url: (item) => `/api/posts/${item.id}` }, }, pull: { method: 'GET', url: '/api/posts', query: async (ctx) => ({ updated_after: (await ctx.getCheckpoint('posts')) || 0, }), mapResponse: (response) => response.data, onComplete: async (response, ctx) => { const latest = response.data.reduce( (m, p) => Math.max(m, new Date(p.updatedAt).getTime()), 0 ); await ctx.setCheckpoint('posts', latest); }, }, }, }), auth: { getHeaders: async () => ({ Authorization: `Bearer ${await getToken()}` }), }, tables: ['posts'], // only track/sync posts sync: { interval: 30000, onOnline: true, onVisibilityChange: true, push: { batchSize: 10, concurrency: 3 }, }, conflicts: { policy: 'lww' }, errors: { maxRetries: 5, retryDelay: (attempt) => Math.min(1000 * Math.pow(2, attempt), 60000), }, }); ``` -------------------------------- ### Manual sync with status example Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Example showing how to manually trigger a sync and log the results. Includes a table-scoped sync using syncTable('posts') and error logging. ```typescript const result = await engine.sync(); console.log(result.push.pushed, result.pull.pulled); // Table-scoped const postsOnly = await syncEngine.syncTable('posts'); if (!result.success) { console.error(result.push.errors, result.pull.errors); } ``` -------------------------------- ### Example commit message Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Example of a clear, descriptive commit message with a body. ```text Add support for custom pagination strategies - Implement cursor-based pagination - Add offset-based pagination - Update documentation with examples ``` -------------------------------- ### Configure and start Dexie sync with @dexie-kit/sync Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/.github-summary.md Sets up Dexie with a posts table and configures the sync engine with push/pull routes, server-wins conflict policy, and 30-second interval sync. After starting the engine, normal Dexie operations are automatically synced. ```typescript import Dexie from 'dexie'; import { startSync, defineRoutes } from '@dexie-kit/sync'; const db = new Dexie('myapp'); db.version(1).stores({ posts: '++id, title, updatedAt', }); const syncEngine = startSync(db, { baseUrl: 'https://api.example.com', auth: { getHeaders: async () => ({ Authorization: `Bearer ${token}` }) }, routes: defineRoutes({ posts: { push: { create: { method: 'POST', url: '/api/posts' }, update: { method: 'PUT', url: (item) => `/api/posts/${item.id}` }, delete: { method: 'DELETE', url: (item) => `/api/posts/${item.id}` }, }, pull: { method: 'GET', url: '/api/posts', query: async (ctx) => ({ updated_after: await ctx.getCheckpoint('pull:posts') || 0 }), mapResponse: (res) => res.data, onComplete: async (res, ctx) => { const latest = Math.max(...res.data.map(p => new Date(p.updatedAt).getTime())); await ctx.setCheckpoint('pull:posts', latest); }, }, }, }), conflicts: { policy: 'server-wins' }, sync: { interval: 30000, onOnline: true }, }); await syncEngine.start(); // Use Dexie normally - sync happens automatically! await db.posts.add({ title: 'Hello World', updatedAt: new Date() }); ``` -------------------------------- ### Start Sync with Dexie and REST Routes Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/README.md Configure a Dexie database with client-generated primary keys, define REST sync routes for push and pull operations, then start the sync engine with authentication, conflict policy, and sync interval. ```typescript import Dexie from 'dexie'; import { startSync, defineRoutes } from '@dexie-kit/sync'; // 1. Define your database. Primary keys are client-generated (no `++`) — // see "ID Strategies" below for why. const db = new Dexie('myapp'); db.version(1).stores({ posts: 'id, title, updatedAt', comments: 'id, postId, content, updatedAt', }); // 2. Configure sync routes const routes = defineRoutes({ posts: { push: { create: { method: 'POST', url: '/api/posts', body: (item) => item, }, update: { method: 'PUT', url: (item) => `/api/posts/${item.id}`, body: (item) => item, }, delete: { method: 'DELETE', url: (item) => `/api/posts/${item.id}`, }, }, pull: { method: 'GET', url: '/api/posts', query: async (ctx) => ({ updated_after: await ctx.getCheckpoint('pull:posts') || 0, }), mapResponse: (response) => response.data, onComplete: async (response, ctx) => { const latest = Math.max( ...response.data.map(p => new Date(p.updatedAt).getTime()) ); await ctx.setCheckpoint('pull:posts', latest); }, }, }, }); // 3. Start sync const syncEngine = startSync(db, { baseUrl: 'https://api.example.com', auth: { getHeaders: async () => ({ 'Authorization': `Bearer ${await getToken()}`, }), }, routes, conflicts: { policy: 'server-wins', }, sync: { interval: 30000, // Sync every 30 seconds onOnline: true, // Sync when coming online }, }); // 4. Use your app normally — the id is assigned on the client await db.posts.add({ id: crypto.randomUUID(), title: 'Hello World' }); // Sync happens automatically! await syncEngine.start(); ``` -------------------------------- ### Conceptual ChangeTracker hook and reconciliation tagging example Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/push-pipeline.md Shows the conceptual usage of ChangeTracker internals: installing a creating hook via startTracking and tagging a transaction with reconciliationTransactions to prevent re-pushing. Note this is a conceptual example for understanding queueing behavior, not a runnable snippet. ```typescript // Conceptual — understanding when queueing happens db.table('posts').hook('creating', ...); // installed by startTracking // A reconciliation merge is tagged so it is *not* re-pushed: reconciliationTransactions.add(transaction); // (internal use by PushProcessor) ``` -------------------------------- ### on() event subscription example Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Example usage of the on method. Subscribes to 'sync-complete' and 'sync-error' events, logging results and errors. The returned unsubscribe function can be called later to remove the handler. ```typescript const off = engine.on('sync-complete', (result) => { console.log(`pushed ${result.push.pushed}, pulled ${result.pull.pulled}`); }); engine.on('sync-error', (error) => console.error('sync failed', error)); // later: off(); ``` -------------------------------- ### Using SyncContext in route callbacks Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-context.md Usage example showing how to use the SyncContext inside route callbacks. Demonstrates getCheckpoint, setCheckpoint, and emit within query and onComplete callbacks, plus engine.on to listen for events. ```typescript import { startSync, defineRoutes } from '@dexie-kit/sync'; const engine = startSync(db, { baseUrl: 'https://api.example.com', routes: defineRoutes({ posts: { push: { create: { method: 'POST', url: '/api/posts', body: (item) => item }, }, pull: { method: 'GET', url: '/api/posts', query: async (ctx) => { // ctx: SyncContext — reads the checkpoint table const since = (await ctx.getCheckpoint('posts:sync')) || 0; return { updated_after: since }; }, mapResponse: (response) => response.data, onComplete: async (response, ctx) => { if (response.pagination?.next) { // record a cursor for the next run — this is how custom // pagination state is persisted today await ctx.setCheckpoint('posts:cursor', response.pagination.next); } ctx.emit('stale', { table: 'posts', count: response.data.length }); }, }, }, }), auth: { getHeaders: async () => ({}) }, }); engine.on('stale', (data) => console.log('refresh needed', data)); ``` -------------------------------- ### SyncEngine Lifecycle Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/README.md Lifecycle methods for controlling the sync engine: start, stop, pause, and resume. ```APIDOC ## [SYNC] [syncEngine.start()] ### Description Starts the sync engine's lifecycle, initiating the sync process. ### Method Async method ### Returns - `Promise` ``` ```APIDOC ## [SYNC] [syncEngine.stop()] ### Description Stops the sync engine, halting all synchronization activity. ### Method Async method ### Returns - `Promise` ``` ```APIDOC ## [SYNC] [syncEngine.pause()] ### Description Pauses the sync engine, temporarily halting synchronization. ### Method Async method ### Returns - `Promise` ``` ```APIDOC ## [SYNC] [syncEngine.resume()] ### Description Resumes the sync engine after a pause. ### Method Async method ### Returns - `Promise` ``` -------------------------------- ### HTTP contract usage example Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/http-transport.md Comment block describing the HTTP contract the backend must implement. It lists the expected request methods and paths, and the expected response status codes and their meanings. This is a usage example for the HttpClient. ```typescript // The client sends (method + url + headers come from your route config): // GET /api/posts?updated_after=&limit=100 // POST /api/posts body: client record (with client-generated id) // PUT /api/posts/:id body: record + version (for 409 detection) // DELETE /api/posts/:id // // The client expects (see errors.md for status-code mapping): // 200/201 with JSON (object for push; object/array mapped by mapResponse for pull) // 204 for deletes (empty body -> null response) // 401/403 -> auth error 409 -> conflict (VERSION_MISMATCH) // 429 + Retry-After -> quota 5xx -> retryable server error ``` -------------------------------- ### SyncEngine Interface Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/types.md The SyncEngine interface exposes methods to start, stop, pause, resume, and synchronize data, as well as manage queues, metrics, and dead letters. ```APIDOC ## `start()` ### Description Starts the sync engine. Returns a promise that resolves when the engine has started. ### Method `start` ### Parameters None. ### Returns `Promise` ## `stop()` ### Description Stops the sync engine. Returns a promise that resolves when the engine has stopped. ### Method `stop` ### Parameters None. ### Returns `Promise` ## `pause()` ### Description Pauses the sync engine. Returns a promise that resolves when the engine is paused. ### Method `pause` ### Parameters None. ### Returns `Promise` ## `resume()` ### Description Resumes the sync engine. Returns a promise that resolves when the engine is resumed. ### Method `resume` ### Parameters None. ### Returns `Promise` ## `sync()` ### Description Performs a full synchronization. Returns a promise that resolves with a `SyncResult`. ### Method `sync` ### Parameters None. ### Returns `Promise` ## `push(table?: string)` ### Description Pushes local changes to the remote. Optionally restricts to a specific table. ### Method `push` ### Parameters - **table** (string) - Optional - The table name to push. ### Returns `Promise` ## `pull(table?: string)` ### Description Pulls remote changes to the local store. Optionally restricts to a specific table. ### Method `pull` ### Parameters - **table** (string) - Optional - The table name to pull. ### Returns `Promise` ## `syncTable(table: string)` ### Description Synchronizes a specific table. ### Method `syncTable` ### Parameters - **table** (string) - Required - The table name to synchronize. ### Returns `Promise` ## `getStatus()` ### Description Returns the current sync status. ### Method `getStatus` ### Parameters None. ### Returns `SyncStatus` ## `isOnline()` ### Description Checks if the engine is online. ### Method `isOnline` ### Parameters None. ### Returns `boolean` ## `isSyncing()` ### Description Checks if the engine is currently syncing. ### Method `isSyncing` ### Parameters None. ### Returns `boolean` ## `isLeader()` ### Description Checks if this instance is the leader. ### Method `isLeader` ### Parameters None. ### Returns `boolean` ## `getQueueDepth(table?: string)` ### Description Returns the current queue depth, optionally for a specific table. ### Method `getQueueDepth` ### Parameters - **table** (string) - Optional - The table name. ### Returns `Promise` ## `getMetrics()` ### Description Returns sync metrics. ### Method `getMetrics` ### Parameters None. ### Returns `Promise` ## `isStale(table: string, key: string | number)` ### Description Checks if a record is stale. ### Method `isStale` ### Parameters - **table** (string) - Required - The table name. - **key** (string | number) - Required - The record key. ### Returns `Promise` ## `pauseTable(table: string)` ### Description Pauses syncing for a specific table. ### Method `pauseTable` ### Parameters - **table** (string) - Required - The table name. ### Returns `Promise` ## `resumeTable(table: string)` ### Description Resumes syncing for a specific table. ### Method `resumeTable` ### Parameters - **table** (string) - Required - The table name. ### Returns `Promise` ## `on(event: SyncEvent, handler: EventHandler)` ### Description Subscribes to sync events. Returns an unsubscribe function. ### Method `on` ### Parameters - **event** (SyncEvent) - Required - The event name. - **handler** (EventHandler) - Required - The event handler. ### Returns `() => void` ## `healthCheck()` ### Description Performs a health check and returns a `HealthCheckResult`. ### Method `healthCheck` ### Parameters None. ### Returns `Promise` ## `getDeadLetters(table?: string)` ### Description Returns dead letter items, optionally for a specific table. ### Method `getDeadLetters` ### Parameters - **table** (string) - Optional - The table name. ### Returns `Promise` ## `retryDeadLetter(id: number)` ### Description Retries a dead letter item by its ID. ### Method `retryDeadLetter` ### Parameters - **id** (number) - Required - The dead letter item ID. ### Returns `Promise` ``` -------------------------------- ### Guarding on network state with isOnline Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-context.md Usage example for guarding on network state. Uses ctx.isOnline() to skip delta arguments while offline, and ctx.getCheckpoint to fetch the last sync revision. ```typescript pull: { method: 'GET', url: '/api/posts', query: async (ctx) => { if (!ctx.isOnline()) return {}; // skip delta args while offline return { updated_after: (await ctx.getCheckpoint('posts:sync')) || 0 }; }, mapResponse: (response) => response.data, }, ``` -------------------------------- ### SyncEngine interface Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/types.md Defines the public API of the SyncEngine, returned by startSync. Includes methods for lifecycle management (start, stop, pause, resume), synchronization (sync, push, pull, syncTable), status queries (getStatus, isOnline, isSyncing, isLeader), metrics and health checks (getMetrics, healthCheck), dead letter handling (getDeadLetters, retryDeadLetter), and event subscription (on). Implemented by the internal SyncEngine class. ```typescript export interface SyncEngine { start(): Promise; stop(): Promise; pause(): Promise; resume(): Promise; sync(): Promise; push(table?: string): Promise; pull(table?: string): Promise; syncTable(table: string): Promise; getStatus(): SyncStatus; isOnline(): boolean; isSyncing(): boolean; isLeader(): boolean; getQueueDepth(table?: string): Promise; getMetrics(): Promise; isStale(table: string, key: string | number): Promise; pauseTable(table: string): Promise; resumeTable(table: string): Promise; on(event: SyncEvent, handler: EventHandler): () => void; healthCheck(): Promise; getDeadLetters(table?: string): Promise; retryDeadLetter(id: number): Promise; } ``` -------------------------------- ### REST API endpoints for sync (GET, POST, PUT, DELETE) Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/examples/basic-usage.md Backend REST API endpoints for a sync-compatible server. The GET endpoint supports incremental sync via `updated_after` and `limit` query parameters. The POST endpoint requires the client-generated `id` to be accepted by the database. The PUT endpoint implements optimistic concurrency control using `expectedVersion` and returns 409 on conflict. The DELETE endpoint returns 204 on success. ```javascript // GET /api/posts?updated_after=1234567890&limit=100 app.get('/api/posts', async (req, res) => { const { updated_after = '0', limit = '100' } = req.query; const posts = await db.posts.findMany({ where: { updatedAt: { gt: new Date(Number(updated_after)) } }, orderBy: { updatedAt: 'asc' }, take: Number(limit) }); res.json({ data: posts }); }); // POST /api/posts app.post('/api/posts', async (req, res) => { // req.body.id is the client-generated id — the `id` column must accept an // externally-supplied value rather than auto-incrementing. See "ID // Strategies" in the README if your database can't do that. const post = await db.posts.create({ data: { ...req.body, updatedAt: new Date(), version: 1 } }); res.status(201).json(post); }); // PUT /api/posts/:id app.put('/api/posts/:id', async (req, res) => { const { expectedVersion, ...data } = req.body; const current = await db.posts.findUnique({ where: { id: req.params.id } }); if (!current) { return res.status(404).json({ error: 'Not found' }); } // Check version for conflict detection if (expectedVersion && current.version !== expectedVersion) { return res.status(409).json({ error: 'Version conflict', serverVersion: current.version, serverData: current }); } const updated = await db.posts.update({ where: { id: req.params.id }, data: { ...data, version: current.version + 1, updatedAt: new Date() } }); res.json(updated); }); // DELETE /api/posts/:id app.delete('/api/posts/:id', async (req, res) => { await db.posts.delete({ where: { id: req.params.id } }); res.status(204).send(); }); ``` -------------------------------- ### Usage example - composing a raw strategy Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/conflict-strategies.md Composes raw strategy functions with a hand-built ConflictInfo. lastWriteWins returns the remote record because remoteTimestamp (200) is greater than localTimestamp (100); serverWins always returns the remote record. Note that timestamps in ConflictInfo are optional; if your data uses a different field than updatedAt (e.g. editedAt), timestamps will be undefined in engine-produced conflicts and lastWriteWins will prefer the server on ties. ```typescript import { lastWriteWins, serverWins } from '@dexie-kit/sync'; // Direct use of the strategy functions with a hand-built ConflictInfo const conflict = { table: 'posts', key: 'abc', local: { id: 'abc', title: 'v1', updatedAt: 100 }, remote: { id: 'abc', title: 'v2', updatedAt: 200 }, localTimestamp: 100, remoteTimestamp: 200, }; const winner = lastWriteWins(conflict); // -> conflict.remote (v2, newer) const fallback = serverWins(conflict); // -> conflict.remote ``` -------------------------------- ### Express.js REST API CRUD endpoints with timestamp filtering (TypeScript) Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/README.md This is an Express.js REST API example (in TypeScript) demonstrating the required CRUD endpoints for a resource like posts. It includes the GET endpoint with `updated_after` timestamp filtering, the POST endpoint that accepts a client-generated `id` from `req.body.id`, and PUT/DELETE endpoints that update the `updatedAt` timestamp. The GET uses `updatedAt: { gt: new Date(Number(updated_after)) }` and orders by `updatedAt` ascending; the POST returns HTTP 201 and the DELETE returns HTTP 204. ```typescript app.get('/api/posts', async (req, res) => { const { updated_after = '0' } = req.query; const posts = await db.posts.findMany({ where: { updatedAt: { gt: new Date(Number(updated_after)) } }, orderBy: { updatedAt: 'asc' } }); res.json({ data: posts }); }); app.post('/api/posts', async (req, res) => { // req.body.id is the client-generated id — the `id` column must accept an // externally-supplied value rather than auto-incrementing. const post = await db.posts.create({ data: { ...req.body, updatedAt: new Date() } }); res.status(201).json(post); }); app.put('/api/posts/:id', async (req, res) => { const post = await db.posts.update({ where: { id: req.params.id }, data: { ...req.body, updatedAt: new Date() } }); res.json(post); }); app.delete('/api/posts/:id', async (req, res) => { await db.posts.delete({ where: { id: req.params.id } }); res.status(204).send(); }); ``` -------------------------------- ### Build the project Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Build the project to ensure it compiles successfully. ```bash npm run build ``` -------------------------------- ### SyncEngine constructor Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Creates a new SyncEngine instance. Typically you let startSync pass the database and configuration. ```APIDOC ## SyncEngine constructor ### Description Creates a new SyncEngine instance. Typically you let startSync pass the database and configuration. ### Method constructor ### Signature ```typescript export class SyncEngine implements ISyncEngine { constructor( private db: Dexie, private config: SyncConfig ) } ``` ### Parameters - **db** (Dexie) - Required - Dexie database (usually you let startSync pass it). - **config** (SyncConfig) - Required - Sync configuration. ### Notes Construction wires internal collaborators: SyncContext, RestAdapter, PushProcessor, PullProcessor, ChangeTracker, LeaderElection, OutboxManager. If config.sync.onOnline is set, a listener triggers sync() on the online event while running and leader; if onVisibilityChange is set and document exists, a visibilitychange listener triggers sync() when the tab becomes visible. ``` -------------------------------- ### startSync(db, config) Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/start-sync.md Initializes the sync engine for a Dexie database. Registers sync metadata tables, warns about auto-increment primary keys, and returns an ISyncEngine instance. ```APIDOC ## startSync(db, config) ### Description Entry point of `@dexie-kit/sync`. Registers sync metadata tables, warns about incompatible primary keys, and constructs the sync engine. ### Import Path `import { startSync } from '@dexie-kit/sync'` ### Function Signature ```typescript export function startSync(db: Dexie, config: SyncConfig): ISyncEngine ``` ### Parameters - **db** (Dexie) - Required - The Dexie database instance that will be synchronized. - **config** (SyncConfig) - Required - Full sync configuration: base URL, routes, auth, sync behavior, conflict policy, error/retry, staleness, observability. ### Return Value `ISyncEngine` — an instance of the concrete `SyncEngine` class typed against the public `SyncEngine` interface. ### Side Effects 1. **ensureSyncTables(db)** — If the `outbox`, `checkpoints`, or `deadLetters` tables are missing, they are added by bumping the database to `verno + 1` and calling `db.version(...).stores(...)`. All existing tables' schemas are preserved: ```typescript outbox: '++id, table, operation, key, createdAt, attempt, nextRetryAt', checkpoints: 'scope, revision, updatedAt', deadLetters: '++id, table, key, failedAt, [table+key]', ``` 2. **warnAboutAutoIncrementKeys(db, config)** — For every table in `config.routes`, if the Dexie primary key is auto-incrementing (`++id`), a `console.warn` is emitted. An auto-increment id is not known until after the local write, so a server-assigned id can never be linked back to it; later updates/deletes would address the wrong record. The recommended pattern is to generate ids on the client (`crypto.randomUUID()`). 3. Returns `new SyncEngine(db, config)`. ### Usage Example — basic ```typescript import Dexie from 'dexie'; import { startSync, defineRoutes } from '@dexie-kit/sync'; const db = new Dexie('myapp'); db.version(1).stores({ posts: 'id, title, updatedAt', // client-generated id — no `++` }); const engine = startSync(db, { baseUrl: 'https://api.example.com', routes: defineRoutes({ posts: { push: { create: { method: 'POST', url: '/api/posts', body: (item) => item }, }, pull: { method: 'GET', url: '/api/posts', mapResponse: (r) => r.data }, }, }), auth: { getHeaders: async () => ({ Authorization: `Bearer ${token}` }), }, conflicts: { policy: 'server-wins' }, }); await engine.start(); ``` ### Usage Example — auto-increment warning and offline guard ```typescript import Dexie from 'dexie'; import { startSync } from '@dexie-kit/sync'; import { SyncError } from '@dexie-kit/sync'; const db = new Dexie('legacy'); db.version(1).stores({ todos: '++id, text' }); // auto-increment — startSync warns const engine = startSync(db, { baseUrl: 'https://api.example.com', routes: { todos: { push: { create: { method: 'POST', url: '/api/todos', body: (item) => item } }, pull: { method: 'GET', url: '/api/todos', mapResponse: (r) => r.data }, }, }, auth: { getHeaders: async () => ({}) }, errors: { maxRetries: 5, onError: (error: SyncError, context) => { console.error(`[${error.type}] ${error.code}: ${error.message}`, context); }, }, }); try { await engine.sync(); } catch (error) { console.error('Offline or paused — sync() throws instead of resolving:', error); } ``` ### Notes - `startSync` itself does not start the background interval; call `await engine.start()` (see [SyncEngine](sync-engine.md)). - `startSync` may be called before Dexie's versioning is finalized; it appends a new Dexie version rather than throwing. - All sync metadata tables are excluded from change tracking (see `src/push/change-tracker.ts:72`). **Source:** `src/index.ts:8-13` ``` -------------------------------- ### Dead letter retry workflow example Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Example usage of getDeadLetters, healthCheck, and retryDeadLetter. Fetches dead letters for the 'posts' table, checks health, and retries each item, catching errors for already removed or invalid ids. ```typescript const dead = await engine.getDeadLetters('posts'); if (dead.length) { const health = await engine.healthCheck(); console.log('Unhealthy:', health.issues); } for (const item of dead) { try { await engine.retryDeadLetter(item.id!); } catch (e) { console.warn('Already removed or invalid id:', item.id); } } ``` -------------------------------- ### Run tests Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Run the test suite to verify changes. ```bash npm test ``` -------------------------------- ### Clone the repository Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Clone your fork of the repository and navigate into the project directory. ```bash git clone https://github.com/YOUR_USERNAME/dexie-kit-sync.git cd dexie-kit-sync ``` -------------------------------- ### Create a changeset with npm run changeset Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/PUBLISHING.md Run this command to create a changeset. It prompts you to select the type of change (major, minor, or patch) and write a summary. This creates a markdown file in the .changeset directory. ```bash npm run changeset ``` -------------------------------- ### GET /api/posts Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/examples/basic-usage.md Fetches a list of posts that have been updated after a given timestamp. Supports pagination via limit and ordering by updatedAt ascending. ```APIDOC ## GET /api/posts ### Description Fetches posts that have been updated after a specified timestamp, ordered by updatedAt ascending. Supports pagination with a limit parameter. ### Method GET ### Endpoint /api/posts ### Parameters #### Query Parameters - **updated_after** (number) - Optional - Unix timestamp in milliseconds. Only posts with updatedAt greater than this value are returned. Defaults to '0'. - **limit** (number) - Optional - Maximum number of posts to return. Defaults to '100'. ### Response #### Success Response (200) - **data** (array) - Array of post objects. #### Response Example { "data": [ { "id": "string", "title": "string", "content": "string", "updatedAt": "string", "version": 1 } ] } ``` -------------------------------- ### syncEngine.on(event, callback) Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/README.md Event listener registration for sync engine events. ```APIDOC ## [SYNC] [syncEngine.on('sync-complete', (result) => {})] ### Description Registers an event listener for the 'sync-complete' event, triggered when a sync operation completes. ### Parameters - `eventName` (string) - Required - The event name to listen for (e.g., 'sync-complete'). - `callback` (function) - Required - The callback to invoke when the event fires. ### Example ```typescript syncEngine.on('sync-complete', (result) => { console.log('Synced!', result); }); ``` ``` -------------------------------- ### Auto-increment warning and offline guard Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/start-sync.md Usage example showing the auto-increment warning (using '++id') and an offline guard. It configures error handling with maxRetries and onError, and demonstrates that sync() throws when offline or paused. ```typescript import Dexie from 'dexie'; import { startSync } from '@dexie-kit/sync'; import { SyncError } from '@dexie-kit/sync'; const db = new Dexie('legacy'); db.version(1).stores({ todos: '++id, text' }); // auto-increment — startSync warns const engine = startSync(db, { baseUrl: 'https://api.example.com', routes: { todos: { push: { create: { method: 'POST', url: '/api/todos', body: (item) => item } }, pull: { method: 'GET', url: '/api/todos', mapResponse: (r) => r.data }, }, }, auth: { getHeaders: async () => ({}) }, errors: { maxRetries: 5, onError: (error: SyncError, context) => { console.error(`[${error.type}] ${error.code}: ${error.message}`, context); }, }, }); try { await engine.sync(); } catch (error) { console.error('Offline or paused — sync() throws instead of resolving:', error); } ``` -------------------------------- ### SyncEngine constructor Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/sync-engine.md Constructor signature for the internal SyncEngine class. It takes a Dexie database instance and a SyncConfig object. Instances are created only via startSync. ```typescript export class SyncEngine implements ISyncEngine { constructor( private db: Dexie, private config: SyncConfig ) } ``` -------------------------------- ### Manual publishing commands for maintainers Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/PUBLISHING.md Use these commands to manually update the version and changelog, then build and publish. Only for maintainers with npm publish access to the @dexie-kit scope, in emergencies or when the automated workflow fails. ```bash # 1. Update version and changelog npm run version # 2. Build and publish npm run release ``` -------------------------------- ### Delta pull route with checkpoint Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/pull-pipeline.md Example route configuration for a delta pull with checkpointing. It uses ctx.getCheckpoint and ctx.setCheckpoint to track the latest updatedAt timestamp, sending it as updated_after in the query. The onComplete callback updates the checkpoint only when the response contains data. ```typescript pull: { method: 'GET', url: '/api/posts', query: async (ctx) => ({ updated_after: (await ctx.getCheckpoint('pull:posts')) || 0, limit: 100, }), mapResponse: (response) => response.data, onComplete: async (response, ctx) => { if (response.data.length > 0) { const latest = Math.max( ...response.data.map((p) => new Date(p.updatedAt).getTime()) ); await ctx.setCheckpoint('pull:posts', latest); } }, }, ``` -------------------------------- ### startSync function signature Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/api-reference/start-sync.md Function signature for the startSync entry point. It takes a Dexie database instance and a SyncConfig object, returning an ISyncEngine instance. ```typescript export function startSync(db: Dexie, config: SyncConfig): ISyncEngine ``` -------------------------------- ### Importing types from @dexie-kit/sync Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/_autodocs/types.md Shows the syntax for importing named types from the library. ```typescript import type { SyncConfig, SyncResult, ... } from '@dexie-kit/sync'; ``` -------------------------------- ### Push to fork Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Push your branch to your fork on GitHub. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Create a new branch Source: https://github.com/abdussamadbello/dexie-kit-sync/blob/main/CONTRIBUTING.md Create a new branch for your feature or fix. ```bash git checkout -b feature/your-feature-name ```