local-lite 2.0.1 → 2.0.2

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.
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { cp, mkdir, readdir } from 'node:fs/promises';
2
+ import { cp, mkdir, readdir, readFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
3
4
  import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import vm from 'node:vm';
5
7
 
6
- const skillsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills');
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const skillsRoot = path.resolve(__dirname, '..', 'skills');
7
10
  const targets = {
8
11
  copilot: '.github/skills',
9
12
  claude: '.claude/skills',
@@ -13,14 +16,15 @@ const targets = {
13
16
  agent: '.agent/skills',
14
17
  };
15
18
 
16
- const usage = `Usage: local-lite install-skills [--target copilot|claude|antigravity|cursor|agent] [--dir <path>] [--force]
19
+ const usage = `Usage:
20
+ local-lite install-skills [--target copilot|claude|antigravity|cursor|agent] [--dir <path>] [--force]
21
+ local-lite db:generate --schema <path> [--tables <path>] [--out <dir>] [--name <name>] [--dialect mysql|postgres|sqlite] [--server-schema <path>] [--dry-run]
17
22
 
18
- Copies the bundled AI skills into your project.
19
- --target copilot (default, .github/skills), claude (.claude/skills), antigravity (.gemini/skills), cursor (.cursor/skills), agent (.agent/skills)
20
- --dir custom destination directory (overrides --target)
21
- --force overwrite existing skill files`;
23
+ Commands:
24
+ install-skills Copy bundled AI skills into your project.
25
+ db:generate Generate incremental SQL migrations from a schema dictionary.`;
22
26
 
23
- function parseArgs(argv) {
27
+ function parseSkillsArgs(argv) {
24
28
  const options = { target: 'copilot', dir: undefined, force: false };
25
29
  for (let i = 0; i < argv.length; i++) {
26
30
  const arg = argv[i];
@@ -37,6 +41,76 @@ function parseArgs(argv) {
37
41
  return options;
38
42
  }
39
43
 
44
+ function parseDbGenArgs(argv) {
45
+ const options = {
46
+ schema: undefined,
47
+ tables: undefined,
48
+ out: 'server/migrations',
49
+ name: 'auto_schema',
50
+ dialect: 'mysql',
51
+ serverSchema: undefined,
52
+ dryRun: false,
53
+ };
54
+ for (let i = 0; i < argv.length; i++) {
55
+ const arg = argv[i];
56
+ if (arg === '--dry-run') options.dryRun = true;
57
+ else if (arg === '--schema') options.schema = argv[++i];
58
+ else if (arg === '--tables') options.tables = argv[++i];
59
+ else if (arg === '--out') options.out = argv[++i];
60
+ else if (arg === '--name') options.name = argv[++i];
61
+ else if (arg === '--dialect') options.dialect = argv[++i];
62
+ else if (arg === '--server-schema') options.serverSchema = argv[++i];
63
+ else if (arg !== '--') throw new Error(`Unknown option: ${arg}`);
64
+ }
65
+ if (!options.schema) {
66
+ throw new Error('--schema <path> is required for db:generate.');
67
+ }
68
+ if (!['mysql', 'postgres', 'sqlite'].includes(options.dialect)) {
69
+ throw new Error(`Unsupported dialect "${options.dialect}". Use mysql, postgres, or sqlite.`);
70
+ }
71
+ return options;
72
+ }
73
+
74
+ async function loadModuleExports(filePath) {
75
+ const absPath = path.resolve(process.cwd(), filePath);
76
+ if (absPath.endsWith('.json')) {
77
+ return JSON.parse(await readFile(absPath, 'utf8'));
78
+ }
79
+ if (!absPath.endsWith('.ts') && !absPath.endsWith('.mts')) {
80
+ return await import(pathToFileURL(absPath).href);
81
+ }
82
+
83
+ try {
84
+ return await import(pathToFileURL(absPath).href);
85
+ } catch {
86
+ const requireFromCwd = createRequire(path.join(process.cwd(), 'package.json'));
87
+ let ts;
88
+ try {
89
+ ts = requireFromCwd('typescript');
90
+ } catch {
91
+ throw new Error(
92
+ `Cannot load TypeScript file "${filePath}". Install "typescript" in your project or pass a .js/.mjs/.json file.`,
93
+ );
94
+ }
95
+ const source = await readFile(absPath, 'utf8');
96
+ const transpiled = ts.transpileModule(source, {
97
+ compilerOptions: {
98
+ module: ts.ModuleKind.CommonJS,
99
+ target: ts.ScriptTarget.ES2022,
100
+ esModuleInterop: true,
101
+ },
102
+ fileName: absPath,
103
+ });
104
+ const moduleObj = { exports: {} };
105
+ const fn = new vm.Script(
106
+ `(function(exports, require, module) {\n${transpiled.outputText}\n})`,
107
+ { filename: absPath },
108
+ );
109
+ fn.runInThisContext()(moduleObj.exports, () => ({}), moduleObj);
110
+ return moduleObj.exports;
111
+ }
112
+ }
113
+
40
114
  async function installSkills(options) {
41
115
  const destination = path.resolve(process.cwd(), options.dir ?? targets[options.target]);
42
116
  await mkdir(destination, { recursive: true });
@@ -51,10 +125,60 @@ async function installSkills(options) {
51
125
  }
52
126
  }
53
127
 
128
+ async function runDbGen(options) {
129
+ const { generateSqlMigration } = await import(
130
+ pathToFileURL(path.resolve(__dirname, '..', 'dist', 'schema', 'index.js')).href
131
+ );
132
+ const schemaExports = await loadModuleExports(options.schema);
133
+ const dictionary =
134
+ schemaExports.SCHEMA_DICTIONARY || schemaExports.default || schemaExports;
135
+
136
+ let tableOrder = [];
137
+ if (options.tables) {
138
+ const tablesExports = await loadModuleExports(options.tables);
139
+ tableOrder = tablesExports.CORE_TABLES || tablesExports.default || [];
140
+ }
141
+
142
+ const result = generateSqlMigration({
143
+ dictionary,
144
+ tableOrder,
145
+ dialect: options.dialect,
146
+ migrationsDir: path.resolve(process.cwd(), options.out),
147
+ name: options.name,
148
+ dryRun: options.dryRun,
149
+ serverSchemaPath: options.serverSchema
150
+ ? path.resolve(process.cwd(), options.serverSchema)
151
+ : undefined,
152
+ });
153
+
154
+ for (const warning of result.warnings) {
155
+ console.warn(`[warn] ${warning}`);
156
+ }
157
+
158
+ if (result.up.length === 0) {
159
+ console.log('No schema changes detected.');
160
+ return;
161
+ }
162
+
163
+ if (options.dryRun) {
164
+ console.log(result.sql);
165
+ return;
166
+ }
167
+
168
+ if (result.migrationPath) {
169
+ console.log(`Generated migration: ${path.relative(process.cwd(), result.migrationPath)}`);
170
+ }
171
+ if (result.serverSchemaPath) {
172
+ console.log(`Updated schema map: ${path.relative(process.cwd(), result.serverSchemaPath)}`);
173
+ }
174
+ }
175
+
54
176
  const [command, ...rest] = process.argv.slice(2);
55
177
  try {
56
178
  if (command === 'install-skills') {
57
- await installSkills(parseArgs(rest));
179
+ await installSkills(parseSkillsArgs(rest));
180
+ } else if (command === 'db:generate') {
181
+ await runDbGen(parseDbGenArgs(rest));
58
182
  } else {
59
183
  console.log(usage);
60
184
  process.exitCode = command && command !== '--help' && command !== '-h' ? 1 : 0;
@@ -1 +1,2 @@
1
1
  export * from './generator.js';
2
+ export * from './sqlMigrations.js';
@@ -15,3 +15,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./generator.js"), exports);
18
+ __exportStar(require("./sqlMigrations.js"), exports);
@@ -0,0 +1,59 @@
1
+ export type SchemaFieldType = 'string' | 'string | null' | 'number' | 'number | null' | 'boolean' | 'boolean | null' | 'json' | 'json | null' | 'string[]' | 'string[] | null';
2
+ export type SchemaDictionary = Record<string, Record<string, SchemaFieldType>>;
3
+ export interface SqlColumnDef {
4
+ sqlType: string;
5
+ nullable: boolean;
6
+ defaultSql: string | null;
7
+ primaryKey?: boolean;
8
+ }
9
+ export interface SqlIndexDef {
10
+ name: string;
11
+ columns: string[];
12
+ }
13
+ export interface SqlTableDef {
14
+ columns: Record<string, SqlColumnDef>;
15
+ indexes: SqlIndexDef[];
16
+ }
17
+ export interface SqlSchemaState {
18
+ version: number;
19
+ tables: Record<string, SqlTableDef>;
20
+ }
21
+ export type SqlDialect = 'mysql' | 'postgres' | 'sqlite';
22
+ export interface GenerateSqlMigrationOptions {
23
+ dictionary: SchemaDictionary;
24
+ migrationsDir: string;
25
+ dialect?: SqlDialect;
26
+ tableOrder?: readonly string[];
27
+ name?: string;
28
+ dryRun?: boolean;
29
+ serverSchemaPath?: string;
30
+ longTextColumns?: Iterable<string>;
31
+ bigintColumns?: Iterable<string>;
32
+ }
33
+ export interface GenerateSqlMigrationResult {
34
+ up: string[];
35
+ down: string[];
36
+ warnings: string[];
37
+ sql: string;
38
+ migrationPath?: string;
39
+ serverSchemaPath?: string;
40
+ schema: SqlSchemaState;
41
+ }
42
+ export declare function mapFieldTypeToSql(colName: string, fieldType: SchemaFieldType, options?: {
43
+ dialect?: SqlDialect;
44
+ longTextColumns?: Set<string>;
45
+ bigintColumns?: Set<string>;
46
+ }): SqlColumnDef;
47
+ export declare function buildSqlTargetSchema(dictionary: SchemaDictionary, tableOrder?: readonly string[], options?: {
48
+ dialect?: SqlDialect;
49
+ longTextColumns?: Iterable<string>;
50
+ bigintColumns?: Iterable<string>;
51
+ }): SqlSchemaState;
52
+ export declare function generateSqlDiff(prevSchema: SqlSchemaState | null, nextSchema: SqlSchemaState, dialect?: SqlDialect): {
53
+ up: string[];
54
+ down: string[];
55
+ warnings: string[];
56
+ };
57
+ export declare function loadSqlSchemaFromMigrations(migrationsDir: string): SqlSchemaState | null;
58
+ export declare function formatSyncedSchemaTs(schema: SqlSchemaState): string;
59
+ export declare function generateSqlMigration(options: GenerateSqlMigrationOptions): GenerateSqlMigrationResult;
@@ -0,0 +1,582 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.mapFieldTypeToSql = mapFieldTypeToSql;
7
+ exports.buildSqlTargetSchema = buildSqlTargetSchema;
8
+ exports.generateSqlDiff = generateSqlDiff;
9
+ exports.loadSqlSchemaFromMigrations = loadSqlSchemaFromMigrations;
10
+ exports.formatSyncedSchemaTs = formatSyncedSchemaTs;
11
+ exports.generateSqlMigration = generateSqlMigration;
12
+ const node_fs_1 = __importDefault(require("node:fs"));
13
+ const node_path_1 = __importDefault(require("node:path"));
14
+ const DEFAULT_LONG_TEXT_COLUMNS = new Set([
15
+ 'remarks',
16
+ 'notes',
17
+ 'description',
18
+ 'body',
19
+ 'content',
20
+ 'message',
21
+ 'html',
22
+ 'template',
23
+ 'error',
24
+ 'reason',
25
+ 'summary',
26
+ 'terms',
27
+ 'signature',
28
+ 'payload',
29
+ 'raw_payload',
30
+ 'secret',
31
+ 'backup_codes',
32
+ ]);
33
+ const DEFAULT_BIGINT_COLUMNS = new Set([
34
+ 'timestamp',
35
+ 'expires_at',
36
+ 'used_at',
37
+ 'revoked_at',
38
+ 'sort_order',
39
+ ]);
40
+ const TAIL_COLUMN_ORDER = ['deleted', 'created_at', 'updated_at'];
41
+ function columnOrderRank(name) {
42
+ if (name === 'id')
43
+ return -1;
44
+ const tailIdx = TAIL_COLUMN_ORDER.indexOf(name);
45
+ return tailIdx === -1 ? 0 : 1 + tailIdx;
46
+ }
47
+ function quoteIdent(name, dialect) {
48
+ return dialect === 'mysql' ? `\`${name}\`` : `"${name}"`;
49
+ }
50
+ function mapFieldTypeToSql(colName, fieldType, options) {
51
+ const dialect = options?.dialect ?? 'mysql';
52
+ const longText = options?.longTextColumns ?? DEFAULT_LONG_TEXT_COLUMNS;
53
+ const bigintCols = options?.bigintColumns ?? DEFAULT_BIGINT_COLUMNS;
54
+ const nullable = fieldType.endsWith(' | null');
55
+ const baseType = nullable ? fieldType.slice(0, -' | null'.length) : fieldType;
56
+ if (dialect === 'sqlite') {
57
+ if (colName === 'id') {
58
+ return { sqlType: 'TEXT', nullable: false, defaultSql: null, primaryKey: true };
59
+ }
60
+ if (colName === 'deleted') {
61
+ return { sqlType: 'INTEGER', nullable: false, defaultSql: '0' };
62
+ }
63
+ if (colName === 'updated_at') {
64
+ return { sqlType: 'INTEGER', nullable: false, defaultSql: '0' };
65
+ }
66
+ if (baseType === 'json' || baseType === 'string[]') {
67
+ return { sqlType: 'TEXT', nullable: true, defaultSql: null };
68
+ }
69
+ if (baseType === 'boolean') {
70
+ return {
71
+ sqlType: 'INTEGER',
72
+ nullable,
73
+ defaultSql: nullable ? 'NULL' : '0',
74
+ };
75
+ }
76
+ if (baseType === 'number') {
77
+ return {
78
+ sqlType: bigintCols.has(colName) ? 'INTEGER' : 'REAL',
79
+ nullable,
80
+ defaultSql: nullable ? 'NULL' : null,
81
+ };
82
+ }
83
+ return {
84
+ sqlType: 'TEXT',
85
+ nullable: nullable || longText.has(colName),
86
+ defaultSql: nullable || longText.has(colName) ? 'NULL' : null,
87
+ };
88
+ }
89
+ if (dialect === 'postgres') {
90
+ if (colName === 'id') {
91
+ return { sqlType: 'VARCHAR(128)', nullable: false, defaultSql: null, primaryKey: true };
92
+ }
93
+ if (colName === 'deleted') {
94
+ return { sqlType: 'BOOLEAN', nullable: false, defaultSql: 'FALSE' };
95
+ }
96
+ if (colName === 'updated_at') {
97
+ return { sqlType: 'BIGINT', nullable: false, defaultSql: '0' };
98
+ }
99
+ if (baseType === 'json' || baseType === 'string[]') {
100
+ return { sqlType: 'JSONB', nullable: true, defaultSql: null };
101
+ }
102
+ if (baseType === 'boolean') {
103
+ return {
104
+ sqlType: 'BOOLEAN',
105
+ nullable,
106
+ defaultSql: nullable ? 'NULL' : 'FALSE',
107
+ };
108
+ }
109
+ if (baseType === 'number') {
110
+ return {
111
+ sqlType: bigintCols.has(colName) ? 'BIGINT' : 'DOUBLE PRECISION',
112
+ nullable,
113
+ defaultSql: nullable ? 'NULL' : null,
114
+ };
115
+ }
116
+ }
117
+ if (colName === 'id') {
118
+ return { sqlType: 'VARCHAR(128)', nullable: false, defaultSql: null, primaryKey: true };
119
+ }
120
+ if (colName === 'deleted') {
121
+ return { sqlType: 'TINYINT(1)', nullable: false, defaultSql: '0' };
122
+ }
123
+ if (colName === 'updated_at') {
124
+ return { sqlType: 'BIGINT', nullable: false, defaultSql: '0' };
125
+ }
126
+ if (baseType === 'json' || baseType === 'string[]') {
127
+ return { sqlType: 'JSON', nullable: true, defaultSql: null };
128
+ }
129
+ if (baseType === 'boolean') {
130
+ return {
131
+ sqlType: 'TINYINT(1)',
132
+ nullable,
133
+ defaultSql: nullable ? 'NULL' : '0',
134
+ };
135
+ }
136
+ if (baseType === 'number') {
137
+ const sqlType = bigintCols.has(colName) ? 'BIGINT' : 'DOUBLE';
138
+ return {
139
+ sqlType,
140
+ nullable,
141
+ defaultSql: nullable ? 'NULL' : null,
142
+ };
143
+ }
144
+ let sqlType = 'VARCHAR(255)';
145
+ if (colName.endsWith('_id') || colName === 'user_id' || colName === 'business_id') {
146
+ sqlType = 'VARCHAR(128)';
147
+ }
148
+ else if (longText.has(colName)) {
149
+ sqlType = 'TEXT';
150
+ }
151
+ else if (colName.endsWith('_url') || colName === 'address') {
152
+ sqlType = 'VARCHAR(512)';
153
+ }
154
+ else if (colName === 'date' || colName.endsWith('_date') || colName.endsWith('_at')) {
155
+ sqlType = 'VARCHAR(64)';
156
+ }
157
+ return {
158
+ sqlType,
159
+ nullable: nullable || sqlType === 'TEXT',
160
+ defaultSql: nullable || sqlType === 'TEXT' ? 'NULL' : null,
161
+ };
162
+ }
163
+ function buildSqlTargetSchema(dictionary, tableOrder = [], options) {
164
+ const dialect = options?.dialect ?? 'mysql';
165
+ const longTextColumns = options?.longTextColumns
166
+ ? new Set(options.longTextColumns)
167
+ : DEFAULT_LONG_TEXT_COLUMNS;
168
+ const bigintColumns = options?.bigintColumns
169
+ ? new Set(options.bigintColumns)
170
+ : DEFAULT_BIGINT_COLUMNS;
171
+ const tables = {};
172
+ const orderedNames = [
173
+ ...tableOrder.filter((name) => Object.prototype.hasOwnProperty.call(dictionary, name)),
174
+ ...Object.keys(dictionary).filter((name) => !tableOrder.includes(name)),
175
+ ];
176
+ for (const tableName of orderedNames) {
177
+ const fields = dictionary[tableName];
178
+ const rawColumns = {};
179
+ for (const [colName, fieldType] of Object.entries(fields)) {
180
+ rawColumns[colName] = mapFieldTypeToSql(colName, fieldType, {
181
+ dialect,
182
+ longTextColumns,
183
+ bigintColumns,
184
+ });
185
+ }
186
+ if (!rawColumns.updated_at) {
187
+ rawColumns.updated_at = mapFieldTypeToSql('updated_at', 'number', {
188
+ dialect,
189
+ longTextColumns,
190
+ bigintColumns,
191
+ });
192
+ }
193
+ if (!rawColumns.deleted) {
194
+ rawColumns.deleted = mapFieldTypeToSql('deleted', 'boolean', {
195
+ dialect,
196
+ longTextColumns,
197
+ bigintColumns,
198
+ });
199
+ }
200
+ const columns = {};
201
+ for (const colName of Object.keys(rawColumns).sort((a, b) => columnOrderRank(a) - columnOrderRank(b))) {
202
+ columns[colName] = rawColumns[colName];
203
+ }
204
+ const idxName = (suffix) => dialect === 'mysql' ? `idx_${suffix}` : `idx_${tableName}_${suffix}`;
205
+ const indexes = [];
206
+ if (columns.business_id) {
207
+ indexes.push({
208
+ name: idxName('business_updated'),
209
+ columns: ['business_id', 'updated_at'],
210
+ });
211
+ }
212
+ indexes.push({
213
+ name: idxName('updated_at'),
214
+ columns: ['updated_at'],
215
+ });
216
+ for (const colName of Object.keys(columns)) {
217
+ if (colName.endsWith('_id') &&
218
+ colName !== 'business_id' &&
219
+ colName !== 'user_id' &&
220
+ colName !== 'entity_id') {
221
+ indexes.push({
222
+ name: idxName(colName),
223
+ columns: [colName],
224
+ });
225
+ }
226
+ }
227
+ tables[tableName] = { columns, indexes };
228
+ }
229
+ return { version: 1, tables };
230
+ }
231
+ function formatColumnDef(colName, col, dialect) {
232
+ const parts = [quoteIdent(colName, dialect), col.sqlType];
233
+ if (col.primaryKey) {
234
+ parts.push('NOT NULL', 'PRIMARY KEY');
235
+ }
236
+ else {
237
+ parts.push(col.nullable ? 'NULL' : 'NOT NULL');
238
+ if (col.defaultSql && col.defaultSql !== 'NULL') {
239
+ parts.push(`DEFAULT ${col.defaultSql}`);
240
+ }
241
+ }
242
+ return parts.join(' ');
243
+ }
244
+ function generateSqlDiff(prevSchema, nextSchema, dialect = 'mysql') {
245
+ const up = [];
246
+ const down = [];
247
+ const warnings = [];
248
+ const prevTables = prevSchema?.tables || {};
249
+ for (const [tableName, nextTable] of Object.entries(nextSchema.tables)) {
250
+ const prevTable = prevTables[tableName];
251
+ const qTable = quoteIdent(tableName, dialect);
252
+ if (!prevTable) {
253
+ const colLines = Object.entries(nextTable.columns).map(([colName, col]) => ` ${formatColumnDef(colName, col, dialect)}`);
254
+ if (dialect === 'mysql') {
255
+ const idxLines = (nextTable.indexes || []).map((idx) => ` INDEX ${quoteIdent(idx.name, dialect)} (${idx.columns.map((c) => quoteIdent(c, dialect)).join(', ')})`);
256
+ const body = [...colLines, ...idxLines].join(',\n');
257
+ up.push(`CREATE TABLE IF NOT EXISTS ${qTable} (\n${body}\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;`);
258
+ }
259
+ else {
260
+ const body = colLines.join(',\n');
261
+ const idxStmts = (nextTable.indexes || []).map((idx) => {
262
+ const cols = idx.columns.map((c) => quoteIdent(c, dialect)).join(', ');
263
+ return `CREATE INDEX IF NOT EXISTS ${quoteIdent(idx.name, dialect)} ON ${qTable} (${cols});`;
264
+ });
265
+ up.push([`CREATE TABLE IF NOT EXISTS ${qTable} (\n${body}\n);`, ...idxStmts].join('\n'));
266
+ }
267
+ down.unshift(`DROP TABLE IF EXISTS ${qTable};`);
268
+ continue;
269
+ }
270
+ for (const [colName, col] of Object.entries(nextTable.columns)) {
271
+ const prevCol = prevTable.columns?.[colName];
272
+ if (!prevCol) {
273
+ const safeCol = !col.nullable && !col.defaultSql
274
+ ? { ...col, nullable: true, defaultSql: 'NULL' }
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)};`);
278
+ }
279
+ else if (prevCol.sqlType !== col.sqlType) {
280
+ warnings.push(`Column type changed for ${tableName}.${colName} (${prevCol.sqlType} -> ${col.sqlType}); review manually before altering.`);
281
+ }
282
+ }
283
+ for (const prevColName of Object.keys(prevTable.columns || {})) {
284
+ if (!nextTable.columns[prevColName]) {
285
+ warnings.push(`Column removed from schema: ${tableName}.${prevColName}; skipped DROP COLUMN to preserve data.`);
286
+ }
287
+ }
288
+ const prevIdxNames = new Set((prevTable.indexes || []).map((i) => i.name));
289
+ for (const idx of nextTable.indexes || []) {
290
+ if (!prevIdxNames.has(idx.name)) {
291
+ const cols = idx.columns.map((c) => quoteIdent(c, dialect)).join(', ');
292
+ const qIdx = quoteIdent(idx.name, dialect);
293
+ if (dialect === 'mysql') {
294
+ up.push(`CREATE INDEX ${qIdx} ON ${qTable} (${cols});`);
295
+ down.unshift(`DROP INDEX ${qIdx} ON ${qTable};`);
296
+ }
297
+ else {
298
+ up.push(`CREATE INDEX IF NOT EXISTS ${qIdx} ON ${qTable} (${cols});`);
299
+ down.unshift(`DROP INDEX IF EXISTS ${qIdx};`);
300
+ }
301
+ }
302
+ }
303
+ }
304
+ for (const prevTableName of Object.keys(prevTables)) {
305
+ if (prevTableName.startsWith('_'))
306
+ continue;
307
+ if (!nextSchema.tables[prevTableName]) {
308
+ warnings.push(`Table removed from schema: ${prevTableName}; skipped DROP TABLE to preserve data.`);
309
+ }
310
+ }
311
+ return { up, down, warnings };
312
+ }
313
+ function extractUpSql(rawSql) {
314
+ const lines = [];
315
+ let active = null;
316
+ for (const line of rawSql.split(/\r?\n/)) {
317
+ const marker = line.trim().toLowerCase();
318
+ if (marker === '-- +up') {
319
+ active = 'up';
320
+ continue;
321
+ }
322
+ if (marker === '-- +down' || marker === '-- +up-optional' || marker === '-- +down-optional') {
323
+ active = 'other';
324
+ continue;
325
+ }
326
+ if (active === 'up')
327
+ lines.push(line);
328
+ }
329
+ return lines.join('\n');
330
+ }
331
+ function splitTopLevel(input, delimiter = ';') {
332
+ const parts = [];
333
+ let current = '';
334
+ let quote = null;
335
+ let depth = 0;
336
+ let inLineComment = false;
337
+ for (let i = 0; i < input.length; i++) {
338
+ const ch = input[i];
339
+ const next = input[i + 1];
340
+ if (inLineComment) {
341
+ if (ch === '\n')
342
+ inLineComment = false;
343
+ continue;
344
+ }
345
+ if (!quote && ch === '-' && next === '-') {
346
+ inLineComment = true;
347
+ i++;
348
+ continue;
349
+ }
350
+ if (quote) {
351
+ current += ch;
352
+ if (ch === '\\' && next) {
353
+ current += next;
354
+ i++;
355
+ continue;
356
+ }
357
+ if (ch === quote)
358
+ quote = null;
359
+ continue;
360
+ }
361
+ if (ch === "'" || ch === '"' || ch === '`') {
362
+ quote = ch;
363
+ current += ch;
364
+ continue;
365
+ }
366
+ if (ch === '(')
367
+ depth++;
368
+ else if (ch === ')' && depth > 0)
369
+ depth--;
370
+ if (ch === delimiter && depth === 0) {
371
+ const trimmed = current.trim();
372
+ if (trimmed)
373
+ parts.push(trimmed);
374
+ current = '';
375
+ continue;
376
+ }
377
+ current += ch;
378
+ }
379
+ const trailing = current.trim();
380
+ if (trailing)
381
+ parts.push(trailing);
382
+ return parts;
383
+ }
384
+ function parseSqlType(rest) {
385
+ const match = rest
386
+ .trim()
387
+ .match(/^([A-Za-z]+(?:\s*\([^)]*\))?(?:\s+UNSIGNED)?)/i);
388
+ return match ? match[1].replace(/\s+/g, ' ').toUpperCase() : '';
389
+ }
390
+ function parseColumnList(rawCols) {
391
+ return rawCols
392
+ .split(',')
393
+ .map((c) => c.trim().replace(/^[`"]|[`"]$/g, '').split(/\s+/)[0])
394
+ .filter(Boolean);
395
+ }
396
+ function applySqlStatement(tables, stmt) {
397
+ const createTableMatch = stmt.match(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s*\(([\s\S]*)\)\s*(?:ENGINE=|DEFAULT|CHARSET|COLLATE|;|$)/i);
398
+ if (createTableMatch) {
399
+ const tableName = createTableMatch[1];
400
+ const body = createTableMatch[2];
401
+ const columns = {};
402
+ const indexes = [];
403
+ for (const item of splitTopLevel(body, ',')) {
404
+ const idxMatch = item.match(/^(?:UNIQUE\s+)?(?:INDEX|KEY)\s+[`"]?(\w+)[`"]?\s*\(([^)]+)\)/i);
405
+ if (idxMatch) {
406
+ indexes.push({ name: idxMatch[1], columns: parseColumnList(idxMatch[2]) });
407
+ continue;
408
+ }
409
+ if (/^(?:PRIMARY\s+KEY|CONSTRAINT|FOREIGN\s+KEY|FULLTEXT|SPATIAL|CHECK)\b/i.test(item)) {
410
+ continue;
411
+ }
412
+ const colMatch = item.match(/^[`"]?(\w+)[`"]?\s+([\s\S]+)$/);
413
+ if (colMatch) {
414
+ columns[colMatch[1]] = {
415
+ sqlType: parseSqlType(colMatch[2]),
416
+ nullable: !/\bNOT\s+NULL\b/i.test(colMatch[2]),
417
+ defaultSql: null,
418
+ };
419
+ }
420
+ }
421
+ tables[tableName] = { columns, indexes };
422
+ return;
423
+ }
424
+ const dropTableMatch = stmt.match(/^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?(\w+)[`"]?/i);
425
+ if (dropTableMatch) {
426
+ delete tables[dropTableMatch[1]];
427
+ return;
428
+ }
429
+ const createIdxMatch = stmt.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s+ON\s+[`"]?(\w+)[`"]?\s*\(([^)]+)\)/i);
430
+ if (createIdxMatch) {
431
+ const [, idxName, tableName, rawCols] = createIdxMatch;
432
+ if (tables[tableName]) {
433
+ tables[tableName].indexes.push({ name: idxName, columns: parseColumnList(rawCols) });
434
+ }
435
+ return;
436
+ }
437
+ const dropIdxMatch = stmt.match(/^DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?[`"]?(\w+)[`"]?(?:\s+ON\s+[`"]?(\w+)[`"]?)?/i);
438
+ if (dropIdxMatch) {
439
+ const [, idxName, tableName] = dropIdxMatch;
440
+ if (tableName && tables[tableName]) {
441
+ tables[tableName].indexes = tables[tableName].indexes.filter((i) => i.name !== idxName);
442
+ }
443
+ else if (!tableName) {
444
+ for (const tbl of Object.values(tables)) {
445
+ tbl.indexes = tbl.indexes.filter((i) => i.name !== idxName);
446
+ }
447
+ }
448
+ return;
449
+ }
450
+ const alterMatch = stmt.match(/^ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
451
+ if (alterMatch) {
452
+ const tableName = alterMatch[1];
453
+ const table = tables[tableName];
454
+ if (!table)
455
+ return;
456
+ for (const clause of splitTopLevel(alterMatch[2], ',')) {
457
+ const addCol = clause.match(/^ADD\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
458
+ if (addCol && !/^(?:UNIQUE|INDEX|KEY|CONSTRAINT|PRIMARY|FOREIGN)\b/i.test(addCol[1])) {
459
+ table.columns[addCol[1]] = {
460
+ sqlType: parseSqlType(addCol[2]),
461
+ nullable: !/\bNOT\s+NULL\b/i.test(addCol[2]),
462
+ defaultSql: null,
463
+ };
464
+ continue;
465
+ }
466
+ const dropCol = clause.match(/^DROP\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?$/i);
467
+ if (dropCol) {
468
+ delete table.columns[dropCol[1]];
469
+ continue;
470
+ }
471
+ const modCol = clause.match(/^MODIFY\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
472
+ if (modCol) {
473
+ table.columns[modCol[1]] = {
474
+ sqlType: parseSqlType(modCol[2]),
475
+ nullable: !/\bNOT\s+NULL\b/i.test(modCol[2]),
476
+ defaultSql: null,
477
+ };
478
+ continue;
479
+ }
480
+ const changeCol = clause.match(/^CHANGE\s+(?:COLUMN\s+)?[`"]?(\w+)[`"]?\s+[`"]?(\w+)[`"]?\s+([\s\S]+)$/i);
481
+ if (changeCol) {
482
+ delete table.columns[changeCol[1]];
483
+ table.columns[changeCol[2]] = {
484
+ sqlType: parseSqlType(changeCol[3]),
485
+ nullable: !/\bNOT\s+NULL\b/i.test(changeCol[3]),
486
+ defaultSql: null,
487
+ };
488
+ continue;
489
+ }
490
+ const addIdx = clause.match(/^ADD\s+(?:UNIQUE\s+)?(?:INDEX|KEY)\s+[`"]?(\w+)[`"]?\s*\(([^)]+)\)/i);
491
+ if (addIdx) {
492
+ table.indexes.push({ name: addIdx[1], columns: parseColumnList(addIdx[2]) });
493
+ continue;
494
+ }
495
+ const dropIdx = clause.match(/^DROP\s+(?:INDEX|KEY)\s+[`"]?(\w+)[`"]?$/i);
496
+ if (dropIdx) {
497
+ table.indexes = table.indexes.filter((i) => i.name !== dropIdx[1]);
498
+ }
499
+ }
500
+ }
501
+ }
502
+ function loadSqlSchemaFromMigrations(migrationsDir) {
503
+ if (!node_fs_1.default.existsSync(migrationsDir))
504
+ return null;
505
+ const files = node_fs_1.default
506
+ .readdirSync(migrationsDir)
507
+ .filter((f) => f.endsWith('.sql'))
508
+ .sort();
509
+ if (files.length === 0)
510
+ return null;
511
+ const tables = {};
512
+ for (const file of files) {
513
+ const rawSql = node_fs_1.default.readFileSync(node_path_1.default.join(migrationsDir, file), 'utf8');
514
+ const upSql = extractUpSql(rawSql);
515
+ for (const stmt of splitTopLevel(upSql, ';')) {
516
+ applySqlStatement(tables, stmt);
517
+ }
518
+ }
519
+ return { version: 1, tables };
520
+ }
521
+ function formatSyncedSchemaTs(schema) {
522
+ const entries = Object.entries(schema.tables).map(([tableName, table]) => {
523
+ const cols = Object.keys(table.columns)
524
+ .map((c) => `'${c}'`)
525
+ .join(', ');
526
+ return ` ${tableName}: [${cols}],`;
527
+ });
528
+ return [
529
+ '// Auto-generated by local-lite db:generate',
530
+ 'export const SYNCED_TABLE_COLUMNS: Record<string, readonly string[]> = {',
531
+ ...entries,
532
+ '};',
533
+ '',
534
+ ].join('\n');
535
+ }
536
+ function formatTimestamp(date = new Date()) {
537
+ const pad = (n) => String(n).padStart(2, '0');
538
+ return [
539
+ date.getUTCFullYear(),
540
+ pad(date.getUTCMonth() + 1),
541
+ pad(date.getUTCDate()),
542
+ pad(date.getUTCHours()),
543
+ pad(date.getUTCMinutes()),
544
+ pad(date.getUTCSeconds()),
545
+ ].join('');
546
+ }
547
+ function generateSqlMigration(options) {
548
+ const dialect = options.dialect ?? 'mysql';
549
+ const nextSchema = buildSqlTargetSchema(options.dictionary, options.tableOrder, {
550
+ dialect,
551
+ longTextColumns: options.longTextColumns,
552
+ bigintColumns: options.bigintColumns,
553
+ });
554
+ const prevSchema = loadSqlSchemaFromMigrations(options.migrationsDir);
555
+ const { up, down, warnings } = generateSqlDiff(prevSchema, nextSchema, dialect);
556
+ const sql = up.length > 0 ? `-- +up\n${up.join('\n\n')}\n\n-- +down\n${down.join('\n')}\n` : '';
557
+ const result = {
558
+ up,
559
+ down,
560
+ warnings,
561
+ sql,
562
+ schema: nextSchema,
563
+ };
564
+ if (options.dryRun) {
565
+ return result;
566
+ }
567
+ if (up.length > 0) {
568
+ node_fs_1.default.mkdirSync(options.migrationsDir, { recursive: true });
569
+ const safeName = (options.name || 'auto_schema')
570
+ .replace(/[^a-z0-9_]+/gi, '_')
571
+ .toLowerCase();
572
+ const outPath = node_path_1.default.join(options.migrationsDir, `${formatTimestamp()}_${safeName}.sql`);
573
+ node_fs_1.default.writeFileSync(outPath, sql, 'utf8');
574
+ result.migrationPath = outPath;
575
+ }
576
+ if (options.serverSchemaPath && (up.length > 0 || !node_fs_1.default.existsSync(options.serverSchemaPath))) {
577
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(options.serverSchemaPath), { recursive: true });
578
+ node_fs_1.default.writeFileSync(options.serverSchemaPath, formatSyncedSchemaTs(nextSchema), 'utf8');
579
+ result.serverSchemaPath = options.serverSchemaPath;
580
+ }
581
+ return result;
582
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-lite",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
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",