local-lite 3.0.3 → 3.0.5

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.
@@ -273,8 +273,12 @@ function generateSqlDiff(prevSchema, nextSchema, dialect = 'mysql') {
273
273
  const safeCol = !col.nullable && !col.defaultSql
274
274
  ? { ...col, nullable: true, defaultSql: 'NULL' }
275
275
  : col;
276
- up.push(`ALTER TABLE ${qTable} ADD COLUMN ${formatColumnDef(colName, safeCol, dialect)};`);
277
- down.unshift(`ALTER TABLE ${qTable} DROP COLUMN ${quoteIdent(colName, dialect)};`);
276
+ up.push(dialect === 'mysql'
277
+ ? `ALTER TABLE ${qTable} ADD COLUMN IF NOT EXISTS ${formatColumnDef(colName, safeCol, dialect)};`
278
+ : `ALTER TABLE ${qTable} ADD COLUMN ${formatColumnDef(colName, safeCol, dialect)};`);
279
+ down.unshift(dialect === 'mysql'
280
+ ? `ALTER TABLE ${qTable} DROP COLUMN IF EXISTS ${quoteIdent(colName, dialect)};`
281
+ : `ALTER TABLE ${qTable} DROP COLUMN ${quoteIdent(colName, dialect)};`);
278
282
  }
279
283
  else if (prevCol.sqlType !== col.sqlType) {
280
284
  warnings.push(`Column type changed for ${tableName}.${colName} (${prevCol.sqlType} -> ${col.sqlType}); review manually before altering.`);
@@ -454,7 +458,7 @@ function applySqlStatement(tables, stmt) {
454
458
  if (!table)
455
459
  return;
456
460
  for (const clause of splitTopLevel(alterMatch[2], ',')) {
457
- const addCol = clause.match(/^ADD\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
461
+ const addCol = clause.match(/^ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
458
462
  if (addCol && !/^(?:UNIQUE|INDEX|KEY|CONSTRAINT|PRIMARY|FOREIGN)\b/i.test(addCol[1])) {
459
463
  table.columns[addCol[1]] = {
460
464
  sqlType: parseSqlType(addCol[2]),
@@ -463,7 +467,7 @@ function applySqlStatement(tables, stmt) {
463
467
  };
464
468
  continue;
465
469
  }
466
- const dropCol = clause.match(/^DROP\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?$/i);
470
+ const dropCol = clause.match(/^DROP\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?[`"]?(\w+)[`"]?$/i);
467
471
  if (dropCol) {
468
472
  delete table.columns[dropCol[1]];
469
473
  continue;
@@ -3,6 +3,9 @@ export * from './email.js';
3
3
  export * from './sync.js';
4
4
  export * from './auth.js';
5
5
  export * from './dashboard.js';
6
+ export * from './sqlDialect.js';
7
+ export * from './syncEvents.js';
8
+ export * from './scheduler.js';
6
9
  export interface ApiRequestContext<TConfig = unknown> {
7
10
  request: Request;
8
11
  config: TConfig;
@@ -20,6 +20,9 @@ __exportStar(require("./email.js"), exports);
20
20
  __exportStar(require("./sync.js"), exports);
21
21
  __exportStar(require("./auth.js"), exports);
22
22
  __exportStar(require("./dashboard.js"), exports);
23
+ __exportStar(require("./sqlDialect.js"), exports);
24
+ __exportStar(require("./syncEvents.js"), exports);
25
+ __exportStar(require("./scheduler.js"), exports);
23
26
  function normalizePath(path) {
24
27
  const normalized = `/${path.split('/').filter(Boolean).join('/')}`;
25
28
  return normalized === '/' ? normalized : normalized.replace(/\/$/, '');
@@ -0,0 +1,13 @@
1
+ import { type SqlExecutor } from './sqlDialect.js';
2
+ export declare function claimScheduledJob(executor: SqlExecutor, tableName: string, jobKey: string, now: number, intervalMs: number): Promise<boolean>;
3
+ export interface ServerCronRunnerOptions {
4
+ intervalMs?: number;
5
+ enabled?: boolean;
6
+ onTick: () => Promise<void>;
7
+ onError?: (error: unknown) => void;
8
+ }
9
+ export declare function createServerCronRunner(options: ServerCronRunnerOptions): {
10
+ start(): void;
11
+ stop(): void;
12
+ isRunning(): boolean;
13
+ };
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.claimScheduledJob = claimScheduledJob;
4
+ exports.createServerCronRunner = createServerCronRunner;
5
+ const sqlDialect_js_1 = require("./sqlDialect.js");
6
+ async function claimScheduledJob(executor, tableName, jobKey, now, intervalMs) {
7
+ const tbl = (0, sqlDialect_js_1.quoteIdent)(tableName, executor.dialect);
8
+ const cutoff = now - Math.max(intervalMs, 1);
9
+ const res = await executor.execute(`UPDATE ${tbl}
10
+ SET last_run_at = ?, last_status = 'running', updated_at = ?
11
+ WHERE job_key = ? AND enabled = 1 AND (last_run_at IS NULL OR last_run_at = 0 OR last_run_at <= ?)`, [now, now, jobKey, cutoff]);
12
+ return res.affectedRows > 0;
13
+ }
14
+ function createServerCronRunner(options) {
15
+ let timer = null;
16
+ const intervalMs = Math.max(options.intervalMs ?? 15 * 60 * 1000, 1000);
17
+ return {
18
+ start() {
19
+ if (options.enabled === false || timer)
20
+ return;
21
+ timer = setInterval(() => {
22
+ void options.onTick().catch((err) => {
23
+ options.onError?.(err);
24
+ });
25
+ }, intervalMs);
26
+ timer.unref?.();
27
+ },
28
+ stop() {
29
+ if (timer) {
30
+ clearInterval(timer);
31
+ timer = null;
32
+ }
33
+ },
34
+ isRunning() {
35
+ return timer !== null;
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,21 @@
1
+ export type SqlDialect = 'mysql' | 'postgres';
2
+ export interface SqlExecutor {
3
+ dialect: SqlDialect;
4
+ query<T = any>(sql: string, params?: any[]): Promise<T[]>;
5
+ execute(sql: string, params?: any[]): Promise<{
6
+ affectedRows: number;
7
+ }>;
8
+ withTransaction<T>(fn: (tx: SqlExecutor) => Promise<T>): Promise<T>;
9
+ }
10
+ export declare function quoteIdent(ident: string, dialect?: SqlDialect): string;
11
+ export interface UpsertSqlOptions {
12
+ table: string;
13
+ conflictCols: string[];
14
+ insertCols: string[];
15
+ updateCols: string[];
16
+ dialect?: SqlDialect;
17
+ }
18
+ export declare function buildUpsertSql(opts: UpsertSqlOptions): string;
19
+ export declare function rewriteSqlTokensForPostgres(sql: string): string;
20
+ export declare function adaptSqlForPostgres(rawSql: string): string[];
21
+ export declare function createSqlExecutor(pool: any, dialect: SqlDialect): SqlExecutor;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.quoteIdent = quoteIdent;
4
+ exports.buildUpsertSql = buildUpsertSql;
5
+ exports.rewriteSqlTokensForPostgres = rewriteSqlTokensForPostgres;
6
+ exports.adaptSqlForPostgres = adaptSqlForPostgres;
7
+ exports.createSqlExecutor = createSqlExecutor;
8
+ function quoteIdent(ident, dialect = 'mysql') {
9
+ const clean = ident.replace(/[`"]/g, '');
10
+ return dialect === 'postgres' ? `"${clean}"` : `\`${clean}\``;
11
+ }
12
+ function buildUpsertSql(opts) {
13
+ const dialect = opts.dialect ?? 'mysql';
14
+ const q = (col) => quoteIdent(col, dialect);
15
+ const tbl = q(opts.table);
16
+ const cols = opts.insertCols.map(q).join(', ');
17
+ const placeholders = opts.insertCols.map(() => '?').join(', ');
18
+ if (dialect === 'postgres') {
19
+ const conflict = opts.conflictCols.map(q).join(', ');
20
+ if (opts.updateCols.length === 0) {
21
+ return `INSERT INTO ${tbl} (${cols}) VALUES (${placeholders}) ON CONFLICT (${conflict}) DO NOTHING`;
22
+ }
23
+ const updates = opts.updateCols
24
+ .map((c) => `${q(c)} = EXCLUDED.${q(c)}`)
25
+ .join(', ');
26
+ return `INSERT INTO ${tbl} (${cols}) VALUES (${placeholders}) ON CONFLICT (${conflict}) DO UPDATE SET ${updates}`;
27
+ }
28
+ if (opts.updateCols.length === 0) {
29
+ return `INSERT IGNORE INTO ${tbl} (${cols}) VALUES (${placeholders})`;
30
+ }
31
+ const updates = opts.updateCols
32
+ .map((c) => `${q(c)} = VALUES(${q(c)})`)
33
+ .join(', ');
34
+ return `INSERT INTO ${tbl} (${cols}) VALUES (${placeholders}) ON DUPLICATE KEY UPDATE ${updates}`;
35
+ }
36
+ function rewriteSqlTokensForPostgres(sql) {
37
+ let out = '';
38
+ let paramIdx = 1;
39
+ let inSingle = false;
40
+ let inDouble = false;
41
+ for (let i = 0; i < sql.length; i++) {
42
+ const ch = sql[i];
43
+ if (ch === "'" && !inDouble) {
44
+ inSingle = !inSingle;
45
+ out += ch;
46
+ if (inSingle && sql[i + 1] === "'") {
47
+ out += "'";
48
+ i++;
49
+ }
50
+ continue;
51
+ }
52
+ if (ch === '\\' && inSingle && i + 1 < sql.length) {
53
+ out += ch + sql[i + 1];
54
+ i++;
55
+ continue;
56
+ }
57
+ if (ch === '`' && !inSingle) {
58
+ inDouble = !inDouble;
59
+ out += '"';
60
+ continue;
61
+ }
62
+ if (ch === '?' && !inSingle && !inDouble) {
63
+ out += `$${paramIdx++}`;
64
+ continue;
65
+ }
66
+ out += ch;
67
+ }
68
+ return out;
69
+ }
70
+ function adaptSqlForPostgres(rawSql) {
71
+ let sql = rawSql.trim();
72
+ if (!sql)
73
+ return [];
74
+ if (sql.startsWith('--') && !sql.includes('\n'))
75
+ return [];
76
+ sql = sql.replace(/\s+ENGINE\s*=\s*\w+/gi, '');
77
+ sql = sql.replace(/\s+DEFAULT\s+CHARSET\s*=\s*[\w-]+/gi, '');
78
+ sql = sql.replace(/\s+COLLATE\s*=?\s*[\w-]+/gi, '');
79
+ sql = sql.replace(/`([^`]+)`/g, '"$1"');
80
+ sql = sql.replace(/\bTINYINT\s*\(\s*1\s*\)/gi, 'SMALLINT');
81
+ sql = sql.replace(/\bLONGTEXT\b/gi, 'TEXT');
82
+ sql = sql.replace(/\bMEDIUMTEXT\b/gi, 'TEXT');
83
+ sql = sql.replace(/\bDOUBLE\b/gi, 'DOUBLE PRECISION');
84
+ sql = sql.replace(/\bENUM\s*\([^)]*\)/gi, 'VARCHAR(64)');
85
+ sql = sql.replace(/\bBIGINT\s+AUTO_INCREMENT\s+PRIMARY\s+KEY\b/gi, 'BIGSERIAL PRIMARY KEY');
86
+ sql = sql.replace(/\bINT\s+AUTO_INCREMENT\s+PRIMARY\s+KEY\b/gi, 'SERIAL PRIMARY KEY');
87
+ if (/^\s*INSERT\s+IGNORE\s+INTO\b/i.test(sql)) {
88
+ sql = sql.replace(/^\s*INSERT\s+IGNORE\s+INTO\b/i, 'INSERT INTO');
89
+ sql = sql.replace(/;\s*$/, '') + ' ON CONFLICT DO NOTHING';
90
+ return [sql];
91
+ }
92
+ const alterIdxMatch = sql.match(/^\s*ALTER\s+TABLE\s+(?:"([^"]+)"|(\S+))\s+ADD\s+(?:UNIQUE\s+)?INDEX\s+"?(\w+)"?\s*\(([^)]+)\)\s*;?\s*$/i);
93
+ if (alterIdxMatch) {
94
+ const tbl = alterIdxMatch[1] || alterIdxMatch[2];
95
+ const idxName = alterIdxMatch[3];
96
+ const cols = alterIdxMatch[4];
97
+ const unique = /\bADD\s+UNIQUE\s+INDEX\b/i.test(sql) ? 'UNIQUE ' : '';
98
+ return [
99
+ `CREATE ${unique}INDEX IF NOT EXISTS "${tbl}_${idxName}" ON "${tbl}" (${cols})`,
100
+ ];
101
+ }
102
+ const tableMatch = sql.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"|(\S+))\s*\(/i);
103
+ const tableName = tableMatch?.[1] || tableMatch?.[2];
104
+ const extractedIndexes = [];
105
+ if (tableName) {
106
+ sql = sql.replace(/,\s*INDEX\s+"?(\w+)"?\s*\(([^)]+)\)/gi, (_m, idxName, cols) => {
107
+ extractedIndexes.push(`CREATE INDEX IF NOT EXISTS "${tableName}_${idxName}" ON "${tableName}" (${cols})`);
108
+ return '';
109
+ });
110
+ }
111
+ return [sql, ...extractedIndexes];
112
+ }
113
+ function createSqlExecutor(pool, dialect) {
114
+ const execOn = (conn) => ({
115
+ dialect,
116
+ async query(sql, params = []) {
117
+ if (dialect === 'postgres') {
118
+ const res = await conn.query(rewriteSqlTokensForPostgres(sql), params);
119
+ return (res?.rows ?? []);
120
+ }
121
+ const [rows] = await conn.query(sql, params);
122
+ return (Array.isArray(rows) ? rows : []);
123
+ },
124
+ async execute(sql, params = []) {
125
+ if (dialect === 'postgres') {
126
+ const res = await conn.query(rewriteSqlTokensForPostgres(sql), params);
127
+ return { affectedRows: Number(res?.rowCount ?? 0) };
128
+ }
129
+ const [res] = await conn.execute(sql, params);
130
+ return { affectedRows: Number(res?.affectedRows ?? 0) };
131
+ },
132
+ async withTransaction(fn) {
133
+ return fn(execOn(conn));
134
+ },
135
+ });
136
+ const root = execOn(pool);
137
+ return {
138
+ ...root,
139
+ async withTransaction(fn) {
140
+ if (dialect === 'postgres') {
141
+ const client = await pool.connect();
142
+ try {
143
+ await client.query('BEGIN');
144
+ const result = await fn(execOn(client));
145
+ await client.query('COMMIT');
146
+ return result;
147
+ }
148
+ catch (err) {
149
+ await client.query('ROLLBACK').catch(() => { });
150
+ throw err;
151
+ }
152
+ finally {
153
+ client.release();
154
+ }
155
+ }
156
+ const conn = await pool.getConnection();
157
+ try {
158
+ await conn.beginTransaction();
159
+ const result = await fn(execOn(conn));
160
+ await conn.commit();
161
+ return result;
162
+ }
163
+ catch (err) {
164
+ await conn.rollback().catch(() => { });
165
+ throw err;
166
+ }
167
+ finally {
168
+ conn.release();
169
+ }
170
+ },
171
+ };
172
+ }
@@ -0,0 +1,17 @@
1
+ export interface SyncChangeEvent {
2
+ scopeId: string;
3
+ tableName: string;
4
+ checkpoint: number;
5
+ }
6
+ export interface SyncEventBroker {
7
+ publish(event: SyncChangeEvent): void;
8
+ subscribe(listener: (event: SyncChangeEvent) => void): () => void;
9
+ }
10
+ export declare function createSyncEventBroker(): SyncEventBroker;
11
+ export interface SyncEventsEndpointOptions {
12
+ broker: SyncEventBroker;
13
+ authenticate: (request: Request) => Promise<boolean>;
14
+ scopeQueryParam?: string;
15
+ heartbeatMs?: number;
16
+ }
17
+ export declare function createSyncEventsHandler(options: SyncEventsEndpointOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSyncEventBroker = createSyncEventBroker;
4
+ exports.createSyncEventsHandler = createSyncEventsHandler;
5
+ const node_events_1 = require("node:events");
6
+ function createSyncEventBroker() {
7
+ const emitter = new node_events_1.EventEmitter();
8
+ emitter.setMaxListeners(0);
9
+ return {
10
+ publish(event) {
11
+ if (!event.scopeId)
12
+ return;
13
+ emitter.emit('change', event);
14
+ },
15
+ subscribe(listener) {
16
+ emitter.on('change', listener);
17
+ return () => {
18
+ emitter.off('change', listener);
19
+ };
20
+ },
21
+ };
22
+ }
23
+ function createSyncEventsHandler(options) {
24
+ const scopeParam = options.scopeQueryParam ?? 'businessId';
25
+ const heartbeatMs = options.heartbeatMs ?? 25_000;
26
+ return async (request) => {
27
+ if (request.method.toUpperCase() !== 'GET') {
28
+ return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
29
+ }
30
+ const ok = await options.authenticate(request);
31
+ if (!ok) {
32
+ return Response.json({ error: 'Unauthorized' }, { status: 401 });
33
+ }
34
+ const url = new URL(request.url);
35
+ const filterScope = url.searchParams.get(scopeParam)?.trim() || '';
36
+ const encoder = new TextEncoder();
37
+ let cleanup = null;
38
+ const stream = new ReadableStream({
39
+ start(controller) {
40
+ const send = (chunk) => {
41
+ try {
42
+ controller.enqueue(encoder.encode(chunk));
43
+ }
44
+ catch {
45
+ cleanup?.();
46
+ }
47
+ };
48
+ send(`event: connected\ndata: ${JSON.stringify({ ok: true })}\n\n`);
49
+ const unsubscribe = options.broker.subscribe((event) => {
50
+ if (filterScope && event.scopeId !== filterScope)
51
+ return;
52
+ send(`data: ${JSON.stringify(event)}\n\n`);
53
+ });
54
+ const heartbeat = setInterval(() => {
55
+ send(': keep-alive\n\n');
56
+ }, heartbeatMs);
57
+ cleanup = () => {
58
+ clearInterval(heartbeat);
59
+ unsubscribe();
60
+ cleanup = null;
61
+ };
62
+ request.signal.addEventListener('abort', () => cleanup?.());
63
+ },
64
+ cancel() {
65
+ cleanup?.();
66
+ },
67
+ });
68
+ return new Response(stream, {
69
+ status: 200,
70
+ headers: {
71
+ 'Content-Type': 'text/event-stream',
72
+ 'Cache-Control': 'no-cache, no-transform',
73
+ Connection: 'keep-alive',
74
+ },
75
+ });
76
+ };
77
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-lite",
3
- "version": "3.0.3",
3
+ "version": "3.0.5",
4
4
  "description": "Never let a lost connection break a promise. Local-first sync that faithfully keeps data safe until you're back online.",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",