@seip/bluebird-js 0.1.2 → 0.1.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.
Files changed (43) hide show
  1. package/.vscode/extensions.json +7 -0
  2. package/.vscode/settings.json +10 -0
  3. package/AGENTS.md +495 -454
  4. package/README.md +528 -353
  5. package/app/routes/web.js +47 -55
  6. package/app/views/about.jsx +98 -0
  7. package/app/views/components/Header.jsx +42 -0
  8. package/app/views/components/LiveCounter.jsx +66 -0
  9. package/app/views/dashboard.jsx +300 -0
  10. package/app/views/index.jsx +123 -0
  11. package/app/views/layouts/main/view.jsx +201 -0
  12. package/app/views/legal/terms.html +29 -19
  13. package/app/views/login.jsx +141 -0
  14. package/core/actions.d.ts +4 -0
  15. package/core/actions.js +329 -0
  16. package/core/app.js +38 -6
  17. package/core/cli/doctor.js +3 -4
  18. package/core/cli/init.js +20 -6
  19. package/core/cli/migrate.js +418 -145
  20. package/core/cli/view.js +76 -11
  21. package/core/database.js +6 -10
  22. package/core/debug.js +1 -1
  23. package/core/html.d.ts +54 -42
  24. package/core/html.js +473 -217
  25. package/core/index.d.ts +1385 -1190
  26. package/core/jsx.d.ts +38 -0
  27. package/core/jsx.js +1432 -0
  28. package/core/model.js +271 -61
  29. package/core/render-cache.js +212 -212
  30. package/core/render.d.ts +20 -2
  31. package/core/render.js +459 -51
  32. package/core/validate.js +1 -1
  33. package/core/view-loader.js +360 -24
  34. package/package.json +9 -3
  35. package/public/js/bluebird-client.js +3160 -1780
  36. package/public/js/tailwind.js +8 -0
  37. package/app/views/about.js +0 -63
  38. package/app/views/dashboard.js +0 -147
  39. package/app/views/index.js +0 -80
  40. package/app/views/layouts/main/view.js +0 -81
  41. package/app/views/login.js +0 -80
  42. package/public/css/bluebird.min.css +0 -2
  43. package/public/js/bluebird.min.js +0 -1073
@@ -2,6 +2,8 @@
2
2
 
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import readline from "node:readline/promises";
5
7
  import colors from "../util/colors.js";
6
8
  import { Database, DB_TYPE } from "../database.js";
7
9
 
@@ -9,6 +11,31 @@ try {
9
11
  process.loadEnvFile?.();
10
12
  } catch {}
11
13
 
14
+ /**
15
+ * Prompts user for yes/no confirmation via CLI.
16
+ * Returns true if answer is affirmative or if running non-interactively with defaultYes.
17
+ * @param {string} question
18
+ * @param {boolean} [defaultYes=true]
19
+ * @returns {Promise<boolean>}
20
+ */
21
+ async function promptConfirm(question, defaultYes = true) {
22
+ if (!process.stdin.isTTY) {
23
+ return defaultYes;
24
+ }
25
+ const rl = readline.createInterface({
26
+ input: process.stdin,
27
+ output: process.stdout,
28
+ });
29
+ try {
30
+ const answer = await rl.question(colors.cyan(question));
31
+ const trimmed = answer.trim().toLowerCase();
32
+ if (!trimmed) return defaultYes;
33
+ return ["y", "yes", "s", "si", "true", "1"].includes(trimmed);
34
+ } finally {
35
+ rl.close();
36
+ }
37
+ }
38
+
12
39
  /**
13
40
  * Generates current timestamp string in YYYYMMDD_HHMMSS format.
14
41
  * @returns {string}
@@ -27,152 +54,351 @@ function getTimestamp() {
27
54
 
28
55
  /**
29
56
  * Splits raw SQL content into discrete executable statements,
30
- * stripping line comments and trimming whitespace.
57
+ * correctly handling single/double quoted strings and stripping line comments.
31
58
  * @param {string} sqlText
32
59
  * @returns {string[]}
33
60
  */
34
61
  function splitSqlStatements(sqlText) {
35
- return sqlText
36
- .split(";")
37
- .map((chunk) =>
38
- chunk
39
- .split("\n")
40
- .map((line) => line.trim())
41
- .filter((line) => !line.startsWith("--"))
42
- .join("\n")
43
- .trim()
44
- )
45
- .filter((chunk) => chunk.length > 0);
62
+ const statements = [];
63
+ let current = "";
64
+ let inSingleQuote = false;
65
+ let inDoubleQuote = false;
66
+ let inComment = false;
67
+
68
+ for (let i = 0; i < sqlText.length; i++) {
69
+ const char = sqlText[i];
70
+ const nextChar = sqlText[i + 1];
71
+
72
+ if (inComment) {
73
+ if (char === "\n" || char === "\r") {
74
+ inComment = false;
75
+ }
76
+ continue;
77
+ }
78
+
79
+ if (!inSingleQuote && !inDoubleQuote && char === "-" && nextChar === "-") {
80
+ inComment = true;
81
+ i++;
82
+ continue;
83
+ }
84
+
85
+ if (char === "'" && !inDoubleQuote) {
86
+ if (inSingleQuote && nextChar === "'") {
87
+ current += "''";
88
+ i++;
89
+ continue;
90
+ }
91
+ inSingleQuote = !inSingleQuote;
92
+ current += char;
93
+ continue;
94
+ }
95
+
96
+ if (char === '"' && !inSingleQuote) {
97
+ if (inDoubleQuote && nextChar === '"') {
98
+ current += '""';
99
+ i++;
100
+ continue;
101
+ }
102
+ inDoubleQuote = !inDoubleQuote;
103
+ current += char;
104
+ continue;
105
+ }
106
+
107
+ if (char === ";" && !inSingleQuote && !inDoubleQuote) {
108
+ const trimmed = current.trim();
109
+ if (trimmed.length > 0) {
110
+ statements.push(trimmed);
111
+ }
112
+ current = "";
113
+ continue;
114
+ }
115
+
116
+ current += char;
117
+ }
118
+
119
+ const trimmed = current.trim();
120
+ if (trimmed.length > 0) {
121
+ statements.push(trimmed);
122
+ }
123
+
124
+ return statements;
46
125
  }
47
126
 
48
127
  /**
49
- * Creates a new migration file in database/migrations/.
50
- * Optionally inspects a Model class to generate automatic DDL,
51
- * or batch generates migrations for all models in app/models/.
52
- * @param {string} [name]
53
- * @param {string} [modelName]
54
- * @param {boolean} [isAll=false]
128
+ * Inspects whether a table exists and retrieves its existing column names.
129
+ * @param {Database} db
130
+ * @param {string} tableName
131
+ * @returns {Promise<{exists: boolean, columns: string[]}>}
55
132
  */
56
- async function makeMigration(name, modelName = null, isAll = false) {
57
- const migrationsDir = path.resolve(process.cwd(), "database/migrations");
133
+ async function inspectDatabaseSchema(db, tableName) {
134
+ try {
135
+ if (DB_TYPE === "sqlite") {
136
+ const rows = (await db.query(`PRAGMA table_info("${tableName}")`)) || [];
137
+ if (!Array.isArray(rows) || rows.length === 0) {
138
+ return { exists: false, columns: [] };
139
+ }
140
+ return { exists: true, columns: rows.map((r) => r.name) };
141
+ }
142
+ if (DB_TYPE === "mysql") {
143
+ const rows = (await db.query(`SHOW COLUMNS FROM \`${tableName}\``)) || [];
144
+ if (!Array.isArray(rows) || rows.length === 0) {
145
+ return { exists: false, columns: [] };
146
+ }
147
+ return { exists: true, columns: rows.map((r) => r.Field) };
148
+ }
149
+ if (DB_TYPE === "postgres") {
150
+ const rows =
151
+ (await db.query(
152
+ "SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ?",
153
+ [tableName]
154
+ )) || [];
155
+ if (!Array.isArray(rows) || rows.length === 0) {
156
+ return { exists: false, columns: [] };
157
+ }
158
+ return { exists: true, columns: rows.map((r) => r.column_name) };
159
+ }
160
+ } catch {
161
+ return { exists: false, columns: [] };
162
+ }
163
+ return { exists: false, columns: [] };
164
+ }
165
+
166
+ /**
167
+ * Discovers and loads all Model classes defined in app/models/,
168
+ * sorted topologically based on schema foreign key references.
169
+ * @returns {Promise<Array<{name: string, ModelClass: any}>>}
170
+ */
171
+ async function loadAllModels() {
58
172
  const modelsDir = path.resolve(process.cwd(), "app/models");
173
+ if (!fs.existsSync(modelsDir)) return [];
59
174
 
60
- if (!fs.existsSync(migrationsDir)) {
61
- fs.mkdirSync(migrationsDir, { recursive: true });
175
+ const files = fs
176
+ .readdirSync(modelsDir)
177
+ .filter((f) => (f.endsWith(".js") || f.endsWith(".ts")) && !f.endsWith(".d.ts"));
178
+
179
+ const loaded = [];
180
+ for (const file of files) {
181
+ const modelPath = path.join(modelsDir, file);
182
+ try {
183
+ const mod = await import(pathToFileURL(modelPath).href);
184
+ const ModelClass = mod.default || mod[Object.keys(mod)[0]];
185
+ if (ModelClass && typeof ModelClass.toDDL === "function" && ModelClass.table) {
186
+ loaded.push({
187
+ name: ModelClass.name || path.basename(file, path.extname(file)),
188
+ ModelClass,
189
+ });
190
+ }
191
+ } catch {}
62
192
  }
63
193
 
64
- if (isAll) {
65
- if (!fs.existsSync(modelsDir)) {
66
- console.log(colors.yellow("[WARN] Directory app/models/ does not exist."));
67
- return;
194
+ const tableToModel = new Map();
195
+ for (const item of loaded) {
196
+ tableToModel.set(item.ModelClass.table, item);
197
+ }
198
+
199
+ const visited = new Set();
200
+ const sorted = [];
201
+
202
+ function visit(item) {
203
+ if (visited.has(item.ModelClass.table)) return;
204
+ visited.add(item.ModelClass.table);
205
+
206
+ const schema = item.ModelClass.schema || {};
207
+ for (const def of Object.values(schema)) {
208
+ if (def && def.references) {
209
+ const refTable =
210
+ typeof def.references === "string"
211
+ ? def.references.split(".")[0]
212
+ : def.references.table;
213
+ if (refTable && refTable !== item.ModelClass.table && tableToModel.has(refTable)) {
214
+ visit(tableToModel.get(refTable));
215
+ }
216
+ }
68
217
  }
69
218
 
70
- const modelFiles = fs.readdirSync(modelsDir).filter(
71
- (f) => (f.endsWith(".js") || f.endsWith(".ts")) && !f.endsWith(".d.ts")
72
- );
219
+ sorted.push(item);
220
+ }
73
221
 
74
- if (modelFiles.length === 0) {
75
- console.log(colors.yellow("[WARN] No model files found in app/models/."));
76
- return;
222
+ for (const item of loaded) {
223
+ visit(item);
224
+ }
225
+
226
+ return sorted;
227
+ }
228
+
229
+ /**
230
+ * Compares all models against the current database schema.
231
+ * @param {Database} db
232
+ * @param {Array<{name: string, ModelClass: any}>} models
233
+ * @returns {Promise<{missingTables: Array<{ModelClass: any, ddl: string}>, missingColumns: Array<{table: string, col: string, def: any, sql: string}>}>}
234
+ */
235
+ async function detectModelDiffs(db, models) {
236
+ const missingTables = [];
237
+ const missingColumns = [];
238
+
239
+ for (const { ModelClass } of models) {
240
+ const tableName = ModelClass.table;
241
+ const { exists, columns } = await inspectDatabaseSchema(db, tableName);
242
+
243
+ if (!exists) {
244
+ missingTables.push({
245
+ ModelClass,
246
+ ddl: ModelClass.toDDL(DB_TYPE),
247
+ });
248
+ continue;
77
249
  }
78
250
 
79
- let count = 0;
80
- for (const file of modelFiles) {
81
- const baseName = path.basename(file, path.extname(file));
82
- const modelPath = path.join(modelsDir, file);
83
- try {
84
- const mod = await import(`file://${modelPath}`);
85
- const ModelClass = mod.default || mod[Object.keys(mod)[0]];
86
- if (ModelClass && typeof ModelClass.toDDL === "function") {
87
- const tableName = ModelClass.table || `${baseName.toLowerCase()}s`;
88
- const migrationName = `create_${tableName}_table`;
89
- const filename = `${getTimestamp()}_${migrationName}.sql`;
90
- const filePath = path.join(migrationsDir, filename);
91
-
92
- const ddl = ModelClass.toDDL(DB_TYPE);
93
- const template = `-- =============================================================\n-- Migration: ${migrationName}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${ddl}\n\n-- Down\nDROP TABLE IF EXISTS ${tableName};\n`;
94
-
95
- fs.writeFileSync(filePath, template, "utf-8");
96
- console.log(colors.green(`[OK] Migration created for model '${ModelClass.name || baseName}': database/migrations/${filename}`));
97
- count++;
98
- await new Promise((r) => setTimeout(r, 1050));
99
- }
100
- } catch (err) {
101
- console.warn(colors.yellow(`[WARN] Could not process model '${file}': ${err.message}`));
251
+ const existingSet = new Set(columns.map((c) => c.toLowerCase()));
252
+ const schema = ModelClass.schema || {};
253
+
254
+ for (const [col, def] of Object.entries(schema)) {
255
+ if (!existingSet.has(col.toLowerCase())) {
256
+ missingColumns.push({
257
+ table: tableName,
258
+ col,
259
+ def,
260
+ sql: ModelClass.columnToSQL(col, def, DB_TYPE),
261
+ });
102
262
  }
103
263
  }
104
264
 
105
- console.log(colors.bold.green(`\n[OK] Generated ${count} migrations from app/models/.`));
106
- return;
265
+ if (ModelClass.timestamps) {
266
+ if (!existingSet.has("created_at") && !schema.created_at) {
267
+ const sql =
268
+ DB_TYPE === "mysql"
269
+ ? "created_at DATETIME DEFAULT CURRENT_TIMESTAMP"
270
+ : "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP";
271
+ missingColumns.push({ table: tableName, col: "created_at", def: {}, sql });
272
+ }
273
+ if (!existingSet.has("updated_at") && !schema.updated_at) {
274
+ const sql =
275
+ DB_TYPE === "mysql"
276
+ ? "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
277
+ : "updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP";
278
+ missingColumns.push({ table: tableName, col: "updated_at", def: {}, sql });
279
+ }
280
+ }
281
+
282
+ if (ModelClass.softDelete && !existingSet.has("deleted_at") && !schema.deleted_at) {
283
+ const sql = DB_TYPE === "mysql" ? "deleted_at DATETIME NULL" : "deleted_at TIMESTAMP NULL";
284
+ missingColumns.push({ table: tableName, col: "deleted_at", def: {}, sql });
285
+ }
107
286
  }
108
287
 
109
- let cleanName = name ? name.toLowerCase().replace(/[^a-z0-9_]/g, "_") : "";
110
- let tableName = cleanName;
111
- let ddl = "";
288
+ return { missingTables, missingColumns };
289
+ }
112
290
 
291
+ /**
292
+ * Creates a new migration file in database/migrations/.
293
+ * Automatically compares models against database schema to generate consolidated DDL.
294
+ * @param {string} [name]
295
+ * @param {string} [modelName]
296
+ * @param {boolean} [isAll=false]
297
+ * @param {boolean} [autoRun=false]
298
+ */
299
+ async function makeMigration(name, modelName = null, isAll = false, autoRun = false) {
300
+ const migrationsDir = path.resolve(process.cwd(), "database/migrations");
301
+ const modelsDir = path.resolve(process.cwd(), "app/models");
302
+
303
+ if (!fs.existsSync(migrationsDir)) {
304
+ fs.mkdirSync(migrationsDir, { recursive: true });
305
+ }
306
+
307
+ let db;
308
+ try {
309
+ db = new Database(5);
310
+ } catch (err) {
311
+ console.error(colors.red("[ERROR] Could not connect to database:"), err.message);
312
+ process.exit(1);
313
+ }
314
+
315
+ let targetModels = [];
113
316
  if (modelName) {
114
- const modelPathJs = path.resolve(process.cwd(), `app/models/${modelName.toLowerCase()}.js`);
115
- const modelPathTs = path.resolve(process.cwd(), `app/models/${modelName.toLowerCase()}.ts`);
317
+ const modelPathJs = path.resolve(modelsDir, `${modelName.toLowerCase()}.js`);
318
+ const modelPathTs = path.resolve(modelsDir, `${modelName.toLowerCase()}.ts`);
116
319
  const targetPath = fs.existsSync(modelPathJs) ? modelPathJs : (fs.existsSync(modelPathTs) ? modelPathTs : null);
117
320
 
118
321
  if (targetPath) {
119
322
  try {
120
- const mod = await import(`file://${targetPath}`);
323
+ const mod = await import(pathToFileURL(targetPath).href);
121
324
  const ModelClass = mod.default || mod[modelName];
122
325
  if (ModelClass && typeof ModelClass.toDDL === "function") {
123
- ddl = ModelClass.toDDL(DB_TYPE);
124
- tableName = ModelClass.table || modelName.toLowerCase();
125
- if (!cleanName) {
126
- cleanName = `create_${tableName}_table`;
127
- }
326
+ targetModels.push({ name: modelName, ModelClass });
128
327
  }
129
328
  } catch (err) {
130
329
  console.warn(colors.yellow(`[WARN] Could not load model '${modelName}': ${err.message}`));
131
330
  }
132
- } else {
133
- console.warn(colors.yellow(`[WARN] Model file for '${modelName}' not found in app/models/.`));
134
331
  }
332
+ } else {
333
+ targetModels = await loadAllModels();
135
334
  }
136
335
 
137
- if (!cleanName) {
138
- console.log(colors.red("[ERROR] Missing migration name or target model."));
139
- console.log("");
140
- console.log("Usage:");
141
- console.log(" npx blue-bird make:migration <name> Create blank migration");
142
- console.log(" npx blue-bird make:migration --model <ModelName> Generate migration from Model schema");
143
- console.log(" npx blue-bird make:migration <name> --model <Model> Custom migration name for Model");
144
- console.log(" npx blue-bird make:migration --all Generate migrations for all models");
145
-
146
- if (fs.existsSync(modelsDir)) {
147
- const availableModels = fs.readdirSync(modelsDir)
148
- .filter((f) => (f.endsWith(".js") || f.endsWith(".ts")) && !f.endsWith(".d.ts"))
149
- .map((f) => path.basename(f, path.extname(f)));
150
- if (availableModels.length > 0) {
151
- console.log(colors.cyan(`\nModels available in app/models/: ${availableModels.join(", ")}`));
152
- }
336
+ const { missingTables, missingColumns } = await detectModelDiffs(db, targetModels);
337
+ await db.close();
338
+ const hasDiffs = missingTables.length > 0 || missingColumns.length > 0;
339
+
340
+ let cleanName = name ? name.toLowerCase().replace(/[^a-z0-9_]/g, "_") : "";
341
+
342
+ if (!hasDiffs && !cleanName && !modelName && !isAll) {
343
+ console.log(colors.green("[INFO] All models in app/models/ are already synchronized with the database."));
344
+ process.exit(0);
345
+ }
346
+
347
+ if (hasDiffs) {
348
+ const upBlocks = [];
349
+ const downBlocks = [];
350
+
351
+ console.log(colors.cyan("\n[INFO] Detected database schema changes:"));
352
+
353
+ for (const { ModelClass, ddl } of missingTables) {
354
+ console.log(colors.green(` + CREATE TABLE: ${ModelClass.table}`));
355
+ upBlocks.push(ddl);
356
+ downBlocks.unshift(`DROP TABLE IF EXISTS ${ModelClass.table};`);
153
357
  }
154
- process.exit(1);
358
+
359
+ for (const { table, col, sql } of missingColumns) {
360
+ console.log(colors.green(` + ADD COLUMN: ${table}.${col}`));
361
+ upBlocks.push(`ALTER TABLE ${table} ADD COLUMN ${sql};`);
362
+ downBlocks.unshift(`ALTER TABLE ${table} DROP COLUMN ${col};`);
363
+ }
364
+
365
+ const migrationTitle = cleanName || "auto_migration";
366
+ const filename = `${getTimestamp()}_${migrationTitle}.sql`;
367
+ const filePath = path.join(migrationsDir, filename);
368
+
369
+ const template = `-- =============================================================\n-- Migration: ${migrationTitle}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${upBlocks.join("\n\n")}\n\n-- Down\n${downBlocks.join("\n")}\n`;
370
+
371
+ fs.writeFileSync(filePath, template, "utf-8");
372
+ console.log(colors.bold.green(`\n[OK] Migration created: database/migrations/${filename}\n`));
373
+
374
+ const shouldRun = autoRun || (await promptConfirm("? Do you want to execute pending migrations now? (Y/n): ", true));
375
+ if (shouldRun) {
376
+ await runMigrations(true);
377
+ }
378
+ return;
155
379
  }
156
380
 
157
- if (!tableName) {
158
- tableName = cleanName;
381
+ if (!cleanName) {
382
+ cleanName = modelName ? `create_${modelName.toLowerCase()}_table` : "custom_migration";
159
383
  }
160
384
 
161
385
  const filename = `${getTimestamp()}_${cleanName}.sql`;
162
386
  const filePath = path.join(migrationsDir, filename);
163
387
 
164
- if (!ddl) {
165
- let idCol = "id INTEGER PRIMARY KEY AUTOINCREMENT";
166
- if (DB_TYPE === "postgres") idCol = "id SERIAL PRIMARY KEY";
167
- if (DB_TYPE === "mysql") idCol = "id INT AUTO_INCREMENT PRIMARY KEY";
388
+ let idCol = "id INTEGER PRIMARY KEY AUTOINCREMENT";
389
+ if (DB_TYPE === "postgres") idCol = "id SERIAL PRIMARY KEY";
390
+ if (DB_TYPE === "mysql") idCol = "id INT AUTO_INCREMENT PRIMARY KEY";
168
391
 
169
- ddl = `CREATE TABLE IF NOT EXISTS ${tableName} (\n ${idCol},\n name VARCHAR(255) NOT NULL,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);`;
170
- }
171
-
172
- const template = `-- =============================================================\n-- Migration: ${cleanName}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${ddl}\n\n-- Down\nDROP TABLE IF EXISTS ${tableName};\n`;
392
+ const ddl = `CREATE TABLE IF NOT EXISTS ${cleanName} (\n ${idCol},\n name VARCHAR(255) NOT NULL,\n description TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);`;
393
+ const template = `-- =============================================================\n-- Migration: ${cleanName}\n-- Created At: ${new Date().toISOString()}\n-- Driver Compatibility: ${DB_TYPE}\n-- =============================================================\n\n-- Up\n${ddl}\n\n-- Down\nDROP TABLE IF EXISTS ${cleanName};\n`;
173
394
 
174
395
  fs.writeFileSync(filePath, template, "utf-8");
175
396
  console.log(colors.green(`[OK] Migration created: database/migrations/${filename}`));
397
+
398
+ const shouldRun = autoRun || (await promptConfirm("? Do you want to execute pending migrations now? (Y/n): ", true));
399
+ if (shouldRun) {
400
+ await runMigrations(true);
401
+ }
176
402
  }
177
403
 
178
404
  /**
@@ -182,7 +408,7 @@ async function makeMigration(name, modelName = null, isAll = false) {
182
408
  function makeSeed(name) {
183
409
  if (!name) {
184
410
  console.log(colors.red("[ERROR] Missing seed name."));
185
- console.log("Usage: npx blue-bird make:seed <name>");
411
+ console.log("Usage: npx bluebird-js make:seed <name>");
186
412
  process.exit(1);
187
413
  }
188
414
 
@@ -242,14 +468,40 @@ async function ensureMigrationsTable(db) {
242
468
 
243
469
  /**
244
470
  * Executes pending database migrations.
471
+ * @param {boolean} [exitOnFinish=true]
472
+ * @param {boolean} [autoYes=false]
245
473
  */
246
- async function runMigrations() {
474
+ async function runMigrations(exitOnFinish = true, autoYes = false) {
247
475
  const migrationsDir = path.resolve(process.cwd(), "database/migrations");
248
476
  if (!fs.existsSync(migrationsDir)) {
249
- console.log(colors.yellow("[INFO] No 'database/migrations' directory found. Nothing to migrate."));
477
+ fs.mkdirSync(migrationsDir, { recursive: true });
478
+ }
479
+
480
+ let db;
481
+ try {
482
+ db = new Database(5);
483
+ await ensureMigrationsTable(db);
484
+ } catch (err) {
485
+ console.error(colors.red("[ERROR] Could not connect to database to run migrations:"), err.message);
486
+ if (exitOnFinish) process.exit(1);
250
487
  return;
251
488
  }
252
489
 
490
+ const allModels = await loadAllModels();
491
+ if (allModels.length > 0) {
492
+ const { missingTables, missingColumns } = await detectModelDiffs(db, allModels);
493
+ if (missingTables.length > 0 || missingColumns.length > 0) {
494
+ console.log(colors.yellow(`[WARN] Detected ${missingTables.length} missing table(s) and ${missingColumns.length} missing column(s) in app/models/.`));
495
+ const shouldGenerate = autoYes || (await promptConfirm("? Detected unmigrated changes in app/models/. Generate and run migration SQL now? (Y/n): ", true));
496
+ if (shouldGenerate) {
497
+ await db.close();
498
+ await makeMigration(null, null, true, true);
499
+ if (exitOnFinish) process.exit(0);
500
+ return;
501
+ }
502
+ }
503
+ }
504
+
253
505
  const files = fs
254
506
  .readdirSync(migrationsDir)
255
507
  .filter((f) => f.endsWith(".sql") || f.endsWith(".js") || f.endsWith(".ts"))
@@ -257,18 +509,11 @@ async function runMigrations() {
257
509
 
258
510
  if (files.length === 0) {
259
511
  console.log(colors.yellow("[INFO] No migration files found in 'database/migrations'."));
512
+ await db.close();
513
+ if (exitOnFinish) process.exit(0);
260
514
  return;
261
515
  }
262
516
 
263
- let db;
264
- try {
265
- db = new Database(5);
266
- await ensureMigrationsTable(db);
267
- } catch (err) {
268
- console.error(colors.red("[ERROR] Could not connect to database to run migrations:"), err.message);
269
- process.exit(1);
270
- }
271
-
272
517
  const appliedRows = (await db.query("SELECT name, batch FROM _bluebird_migrations ORDER BY id ASC")) || [];
273
518
  const appliedSet = new Set(appliedRows.map((r) => r.name));
274
519
 
@@ -279,7 +524,9 @@ async function runMigrations() {
279
524
 
280
525
  if (pending.length === 0) {
281
526
  console.log(colors.green("[INFO] Database is up to date. No pending migrations."));
282
- process.exit(0);
527
+ await db.close();
528
+ if (exitOnFinish) process.exit(0);
529
+ return;
283
530
  }
284
531
 
285
532
  console.log(colors.cyan(`[INFO] Running ${pending.length} pending migration(s) (Batch #${currentBatch})...\n`));
@@ -302,8 +549,7 @@ async function runMigrations() {
302
549
  );
303
550
  });
304
551
  } else {
305
- const modulePath = `file://${filePath}`;
306
- const migrationModule = await import(modulePath);
552
+ const migrationModule = await import(pathToFileURL(filePath).href);
307
553
  if (typeof migrationModule.up === "function") {
308
554
  await db.transaction(async (tx) => {
309
555
  await migrationModule.up(tx);
@@ -318,12 +564,15 @@ async function runMigrations() {
318
564
  console.log(colors.green(` [MIGRATED] ${file}`));
319
565
  } catch (err) {
320
566
  console.error(colors.red(` [FAILED] ${file}: ${err.message}`));
321
- process.exit(1);
567
+ await db.close();
568
+ if (exitOnFinish) process.exit(1);
569
+ return;
322
570
  }
323
571
  }
324
572
 
573
+ await db.close();
325
574
  console.log(colors.bold.green("\n[OK] All pending migrations executed successfully."));
326
- process.exit(0);
575
+ if (exitOnFinish) process.exit(0);
327
576
  }
328
577
 
329
578
  /**
@@ -350,6 +599,7 @@ async function rollbackMigrations() {
350
599
 
351
600
  if (!lastBatch) {
352
601
  console.log(colors.yellow("[INFO] No migrations found to rollback."));
602
+ await db.close();
353
603
  process.exit(0);
354
604
  }
355
605
 
@@ -378,7 +628,7 @@ async function rollbackMigrations() {
378
628
  await db.query("DELETE FROM _bluebird_migrations WHERE name = ?", [file]);
379
629
  }
380
630
  } else {
381
- const mod = await import(`file://${filePath}`);
631
+ const mod = await import(pathToFileURL(filePath).href);
382
632
  if (typeof mod.down === "function") {
383
633
  await db.transaction(async (tx) => {
384
634
  await mod.down(tx);
@@ -395,10 +645,12 @@ async function rollbackMigrations() {
395
645
  console.log(colors.green(` [ROLLED BACK] ${file}`));
396
646
  } catch (err) {
397
647
  console.error(colors.red(` [FAILED] ${file}: ${err.message}`));
648
+ await db.close();
398
649
  process.exit(1);
399
650
  }
400
651
  }
401
652
 
653
+ await db.close();
402
654
  console.log(colors.bold.green("\n[OK] Rollback completed successfully."));
403
655
  process.exit(0);
404
656
  }
@@ -444,6 +696,7 @@ async function showMigrationStatus() {
444
696
  }
445
697
 
446
698
  console.log("");
699
+ await db.close();
447
700
  process.exit(0);
448
701
  }
449
702
 
@@ -490,8 +743,7 @@ async function runSeeds() {
490
743
  }
491
744
  });
492
745
  } else {
493
- const modulePath = `file://${filePath}`;
494
- const seedModule = await import(modulePath);
746
+ const seedModule = await import(pathToFileURL(filePath).href);
495
747
  if (typeof seedModule.seed === "function") {
496
748
  await db.transaction(async (tx) => {
497
749
  await seedModule.seed(tx);
@@ -502,40 +754,61 @@ async function runSeeds() {
502
754
  console.log(colors.green(` [SEEDED] ${file}`));
503
755
  } catch (err) {
504
756
  console.error(colors.red(` [FAILED] ${file}: ${err.message}`));
757
+ await db.close();
505
758
  process.exit(1);
506
759
  }
507
760
  }
508
761
 
762
+ await db.close();
509
763
  console.log(colors.bold.green("\n[OK] Database seeding completed."));
510
764
  process.exit(0);
511
765
  }
512
766
 
513
- const rawArgs = process.argv.slice(2);
514
- const cmd = rawArgs[0];
515
-
516
- if (cmd === "make:migration") {
517
- const modelIdx = rawArgs.indexOf("--model");
518
- const modelName = modelIdx !== -1 ? rawArgs[modelIdx + 1] : null;
519
- const isAll = rawArgs.includes("--all") || rawArgs.includes("-a");
520
-
521
- const positionalArgs = rawArgs.slice(1).filter((arg, i, arr) => {
522
- if (arg.startsWith("-")) return false;
523
- const prev = arr[i - 1];
524
- if (prev === "--model" || prev === "-m") return false;
525
- return true;
526
- });
527
-
528
- const name = positionalArgs[0] || null;
529
- makeMigration(name, modelName, isAll);
530
-
531
- } else if (cmd === "make:seed") {
532
- makeSeed(rawArgs[1]);
533
- } else if (cmd === "migrate:status") {
534
- showMigrationStatus();
535
- } else if (cmd === "migrate:rollback") {
536
- rollbackMigrations();
537
- } else if (cmd === "seed") {
538
- runSeeds();
539
- } else {
540
- runMigrations();
767
+ const isMain = process.argv[1] && (
768
+ process.argv[1].endsWith("migrate.js") ||
769
+ process.argv[1].endsWith("migrate")
770
+ );
771
+
772
+ if (isMain) {
773
+ const rawArgs = process.argv.slice(2);
774
+ const cmd = rawArgs[0];
775
+ const autoYes = rawArgs.includes("--yes") || rawArgs.includes("-y") || rawArgs.includes("--run");
776
+
777
+ if (cmd === "make:migration") {
778
+ const modelIdx = rawArgs.indexOf("--model");
779
+ const modelName = modelIdx !== -1 ? rawArgs[modelIdx + 1] : null;
780
+ const isAll = rawArgs.includes("--all") || rawArgs.includes("-a");
781
+
782
+ const positionalArgs = rawArgs.slice(1).filter((arg, i, arr) => {
783
+ if (arg.startsWith("-")) return false;
784
+ const prev = arr[i - 1];
785
+ if (prev === "--model" || prev === "-m") return false;
786
+ return true;
787
+ });
788
+
789
+ const name = positionalArgs[0] || null;
790
+ await makeMigration(name, modelName, isAll, autoYes);
791
+ } else if (cmd === "make:seed") {
792
+ makeSeed(rawArgs[1]);
793
+ } else if (cmd === "migrate:status") {
794
+ await showMigrationStatus();
795
+ } else if (cmd === "migrate:rollback") {
796
+ await rollbackMigrations();
797
+ } else if (cmd === "seed") {
798
+ await runSeeds();
799
+ } else {
800
+ await runMigrations(true, autoYes);
801
+ }
541
802
  }
803
+
804
+ export {
805
+ splitSqlStatements,
806
+ inspectDatabaseSchema,
807
+ loadAllModels,
808
+ makeMigration,
809
+ runMigrations,
810
+ rollbackMigrations,
811
+ showMigrationStatus,
812
+ makeSeed,
813
+ runSeeds,
814
+ };