@meghjs/cli 0.5.1 → 0.5.3

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,6 +1,8 @@
1
1
  /** Where apps used to export their own Kysely instance. Still used when present. */
2
2
  export declare const LEGACY_CONNECTION = "src/database/connection.ts";
3
3
  export declare const DEFAULT_MIGRATIONS = "src/database/migrations";
4
+ export declare const DEFAULT_SEEDERS = "src/database/seeders";
5
+ export declare const DEFAULT_FACTORIES = "src/database/factories";
4
6
  export type DatabasePaths = {
5
7
  /**
6
8
  * A module exporting the app's own Kysely instance (`default` or `db`),
@@ -14,20 +16,36 @@ export type DatabasePaths = {
14
16
  settings: Record<string, unknown>;
15
17
  /** Folder of migration files. */
16
18
  migrations: string;
19
+ /** Folder of seeder files. */
20
+ seeders: string;
21
+ /** Folder of model factory files. */
22
+ factories: string;
17
23
  };
18
- /** `megh.database` / `megh.migrations` from package.json, else the defaults. */
24
+ /** `megh.database` / `megh.migrations` / `megh.seeders` from package.json, else the defaults. */
19
25
  export declare function databasePaths(root: string, pkg?: Record<string, any>): DatabasePaths;
20
- export type MigrateAction = "latest" | "rollback" | "reset" | "refresh" | "status";
26
+ export type MigrateAction = "latest" | "rollback" | "reset" | "refresh" | "status" | "seed";
21
27
  export type MigrateOptions = {
22
28
  cwd?: string;
23
29
  step?: number;
24
30
  };
25
31
  /** Run a migration action in a child process and return its result. */
26
- export declare function runMigrations(action: MigrateAction, opts?: MigrateOptions): any;
27
- export declare function migrate(opts?: MigrateOptions): string[];
32
+ export declare function runMigrations(action: MigrateAction, opts?: MigrateOptions & SeedOptions): any;
33
+ export type SeedOptions = {
34
+ /** Run this seeder instead of the `database` seeder (or all of them). */
35
+ seeder?: string;
36
+ /** Seed even when NODE_ENV is production. */
37
+ force?: boolean;
38
+ };
39
+ /** Run the seeders: `seeder`, else the `database` seeder, else all in file order. */
40
+ export declare function dbSeed(opts?: MigrateOptions & SeedOptions): string[];
41
+ export declare function migrate(opts?: MigrateOptions & SeedOptions & {
42
+ seed?: boolean;
43
+ }): string[];
28
44
  export declare function migrateRollback(opts?: MigrateOptions): string[];
29
45
  export declare function migrateReset(opts?: MigrateOptions): string[];
30
- export declare function migrateRefresh(opts?: MigrateOptions): {
46
+ export declare function migrateRefresh(opts?: MigrateOptions & SeedOptions & {
47
+ seed?: boolean;
48
+ }): {
31
49
  down: string[];
32
50
  up: string[];
33
51
  };
@@ -3,9 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_MIGRATIONS = exports.LEGACY_CONNECTION = void 0;
6
+ exports.DEFAULT_FACTORIES = exports.DEFAULT_SEEDERS = exports.DEFAULT_MIGRATIONS = exports.LEGACY_CONNECTION = void 0;
7
7
  exports.databasePaths = databasePaths;
8
8
  exports.runMigrations = runMigrations;
9
+ exports.dbSeed = dbSeed;
9
10
  exports.migrate = migrate;
10
11
  exports.migrateRollback = migrateRollback;
11
12
  exports.migrateReset = migrateReset;
@@ -23,7 +24,9 @@ const project_1 = require("../utils/project");
23
24
  /** Where apps used to export their own Kysely instance. Still used when present. */
24
25
  exports.LEGACY_CONNECTION = "src/database/connection.ts";
25
26
  exports.DEFAULT_MIGRATIONS = "src/database/migrations";
26
- /** `megh.database` / `megh.migrations` from package.json, else the defaults. */
27
+ exports.DEFAULT_SEEDERS = "src/database/seeders";
28
+ exports.DEFAULT_FACTORIES = "src/database/factories";
29
+ /** `megh.database` / `megh.migrations` / `megh.seeders` from package.json, else the defaults. */
27
30
  function databasePaths(root, pkg = (0, project_1.readPackageJson)(root)) {
28
31
  const conf = pkg?.megh ?? {};
29
32
  const legacy = path_1.default.resolve(root, exports.LEGACY_CONNECTION);
@@ -36,6 +39,8 @@ function databasePaths(root, pkg = (0, project_1.readPackageJson)(root)) {
36
39
  connection,
37
40
  settings: conf.database && typeof conf.database === "object" ? conf.database : {},
38
41
  migrations: path_1.default.resolve(root, typeof conf.migrations === "string" ? conf.migrations : exports.DEFAULT_MIGRATIONS),
42
+ seeders: path_1.default.resolve(root, typeof conf.seeders === "string" ? conf.seeders : exports.DEFAULT_SEEDERS),
43
+ factories: path_1.default.resolve(root, typeof conf.factories === "string" ? conf.factories : exports.DEFAULT_FACTORIES),
39
44
  };
40
45
  }
41
46
  const MARKER = "__MEGH_MIGRATE__";
@@ -48,7 +53,7 @@ const MARKER = "__MEGH_MIGRATE__";
48
53
  const WORKER = `
49
54
  const fs = require("fs");
50
55
  const path = require("path");
51
- const [root, connection, settings, folder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
56
+ const [root, connection, settings, folder, seedersFolder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
52
57
  const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(value));
53
58
  (async () => {
54
59
  let db;
@@ -71,6 +76,18 @@ const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(v
71
76
  }
72
77
  db = core.createDatabase(core.resolveDatabaseOptions(settings));
73
78
  }
79
+ if (action === "seed") {
80
+ const [name, force] = args;
81
+ if (typeof core.Seeders !== "function") throw new Error("This @meghjs/core version has no seeders; upgrade it.");
82
+ if (process.env.NODE_ENV === "production" && !force) {
83
+ throw new Error("NODE_ENV is production. Pass --force to seed anyway.");
84
+ }
85
+ // Models in the seeders use the ORM connection.
86
+ if (core.Model && typeof core.Model.useConnection === "function") core.Model.useConnection(db);
87
+ const seeders = new core.Seeders(db, { folder: seedersFolder });
88
+ send({ ok: true, result: await seeders.run(name || undefined) });
89
+ return;
90
+ }
74
91
  const migrations = new core.Migrations(db, { folder });
75
92
  send({ ok: true, result: await migrations[action](...args) });
76
93
  } catch (e) {
@@ -105,6 +122,14 @@ function compiled(root) {
105
122
  for (const [file, error] of migrationsCompiler.compileAll())
106
123
  failures.set(file, error);
107
124
  }
125
+ // Seeders likewise; a missing folder just has no seeders.
126
+ const seedersCompiler = inside(layout.srcDir, paths.seeders)
127
+ ? app
128
+ : new compiler_1.SwcCompiler(paths.seeders, path_1.default.join(cacheDir, "seeders"), layout.compilerOptions);
129
+ if (seedersCompiler !== app && fs_1.default.existsSync(paths.seeders)) {
130
+ for (const [file, error] of seedersCompiler.compileAll())
131
+ failures.set(file, error);
132
+ }
108
133
  if (failures.size) {
109
134
  const list = [...failures].map(([f, e]) => `${rel(f)}: ${e.split("\n")[0]}`).join("\n ");
110
135
  throw new errors_1.CliError(`Compilation failed:\n ${list}`);
@@ -117,14 +142,15 @@ function compiled(root) {
117
142
  settings: paths.settings,
118
143
  // outFileFor maps a file; map a placeholder inside the folder and take its directory.
119
144
  migrations: path_1.default.dirname(migrationsCompiler.outFileFor(path_1.default.join(paths.migrations, "x.ts"))),
145
+ seeders: path_1.default.dirname(seedersCompiler.outFileFor(path_1.default.join(paths.seeders, "x.ts"))),
120
146
  };
121
147
  }
122
148
  /** Run a migration action in a child process and return its result. */
123
149
  function runMigrations(action, opts = {}) {
124
150
  const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
125
151
  const files = compiled(root);
126
- const args = action === "rollback" ? [opts.step ?? 1] : [];
127
- const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.settings, files.migrations, action, args])], {
152
+ const args = action === "rollback" ? [opts.step ?? 1] : action === "seed" ? [opts.seeder ?? null, opts.force === true] : [];
153
+ const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.settings, files.migrations, files.seeders, action, args])], {
128
154
  cwd: root,
129
155
  encoding: "utf8",
130
156
  env: { ...process.env, NODE_ENV: process.env.NODE_ENV ?? "development" },
@@ -142,7 +168,9 @@ function runMigrations(action, opts = {}) {
142
168
  const out = JSON.parse(line.slice(MARKER.length));
143
169
  if (!out.ok) {
144
170
  const done = out.completed.length ? `\nCompleted before the failure:\n ${out.completed.join("\n ")}` : "";
145
- throw new errors_1.CliError(`${out.error}${done}`);
171
+ // A seed runs in one transaction: a failure saves nothing.
172
+ const rolledBack = action === "seed" && /^Seeder /.test(out.error) ? "\nNothing was saved." : "";
173
+ throw new errors_1.CliError(`${out.error}${done}${rolledBack}`);
146
174
  }
147
175
  return out.result;
148
176
  }
@@ -154,9 +182,17 @@ function list(names, verb, empty) {
154
182
  for (const name of names)
155
183
  log_1.log.success(`${verb} ${name}`);
156
184
  }
185
+ /** Run the seeders: `seeder`, else the `database` seeder, else all in file order. */
186
+ function dbSeed(opts = {}) {
187
+ const names = runMigrations("seed", opts);
188
+ list(names, "Seeded:", "Nothing to seed: there are no seeders. Create one with: megh make:seeder <name>");
189
+ return names;
190
+ }
157
191
  function migrate(opts = {}) {
158
192
  const names = runMigrations("latest", opts);
159
193
  list(names, "Migrated:", "Nothing to migrate.");
194
+ if (opts.seed)
195
+ dbSeed(opts);
160
196
  return names;
161
197
  }
162
198
  function migrateRollback(opts = {}) {
@@ -173,6 +209,8 @@ function migrateRefresh(opts = {}) {
173
209
  const result = runMigrations("refresh", opts);
174
210
  list(result.down, "Rolled back:", "Nothing to roll back.");
175
211
  list(result.up, "Migrated:", "Nothing to migrate.");
212
+ if (opts.seed)
213
+ dbSeed(opts);
176
214
  return result;
177
215
  }
178
216
  function formatStatus(rows) {
@@ -47,6 +47,7 @@ const path_1 = __importDefault(require("path"));
47
47
  const errors_1 = require("../errors");
48
48
  const log_1 = require("../utils/log");
49
49
  const names_1 = require("../utils/names");
50
+ const make_1 = require("../generators/make");
50
51
  const stubs_1 = require("../utils/stubs");
51
52
  const env_types_1 = require("../utils/env-types");
52
53
  exports.PACKAGE_MANAGERS = ["npm", "yarn", "pnpm"];
@@ -86,6 +87,7 @@ const DEP_VERSIONS = {
86
87
  "@vitest/coverage-v8": "^4.1.12",
87
88
  "unplugin-swc": "^2.0.0",
88
89
  "@swc/core": "^1.16.20",
90
+ "@faker-js/faker": "^10.6.0",
89
91
  };
90
92
  function isDirEmpty(dir) {
91
93
  return fs_1.default.readdirSync(dir).length === 0;
@@ -195,6 +197,9 @@ function packageJson(name, features, minimal, database = DEFAULT_DATABASE) {
195
197
  pickDev("@types/node", "typescript");
196
198
  if (!minimal)
197
199
  pickDev("@swc/core", "@vitest/coverage-v8", "unplugin-swc", "vitest");
200
+ // Model factories (megh make:factory) fill rows with Faker values.
201
+ if (features.includes("orm"))
202
+ pickDev("@faker-js/faker");
198
203
  const scripts = {
199
204
  "start:dev": "megh serve",
200
205
  build: "megh build",
@@ -320,6 +325,7 @@ async function createApplication(name, opts = {}) {
320
325
  if (database === "sqlite")
321
326
  gitignore = gitignore.replace(/\n*$/, "\n") + "database.sqlite\n";
322
327
  add("src/database/migrations/.gitkeep", "");
328
+ add("src/database/seeders/database.seeder.ts", (0, make_1.renderEntrySeeder)([]));
323
329
  }
324
330
  add(".gitignore", gitignore);
325
331
  add(".env", env);
@@ -366,7 +372,7 @@ async function createApplication(name, opts = {}) {
366
372
  if (database !== "sqlite")
367
373
  console.log(log_1.c.dim(" # set DATABASE_URL in .env"));
368
374
  console.log(log_1.c.cyan(" npx megh make:migration create_users_table"));
369
- console.log(log_1.c.cyan(" npx megh migrate"));
375
+ console.log(log_1.c.cyan(" npx megh migrate --seed"));
370
376
  }
371
377
  console.log(log_1.c.cyan(` ${devCommand(pm)}`));
372
378
  if (features.includes("openapi") || features.includes("scalar")) {
@@ -0,0 +1,25 @@
1
+ import type { ResourceField } from "./resource";
2
+ /**
3
+ * Renders a model factory for `make:factory`: one Faker call per column,
4
+ * picked from the column's name and type (`email` → `faker.internet.email()`,
5
+ * a `Date` → `faker.date.recent()`, …). Foreign keys use the related
6
+ * model's factory when there is one.
7
+ */
8
+ /** A foreign key column (`role_id`) and the factory that can fill it, if any. */
9
+ export interface ForeignKey {
10
+ column: string;
11
+ /** e.g. `RoleFactory`, when src/database/factories/role.factory.ts exists. */
12
+ factory?: string;
13
+ /** Import path of that factory, relative to the new factory file. */
14
+ factoryImport?: string;
15
+ /** Model name for the hint when there is no factory, e.g. `role`. */
16
+ model: string;
17
+ }
18
+ /** A Faker expression for a column, or `undefined` when none fits. */
19
+ export declare function fakeValue(field: ResourceField, model: string): string | undefined;
20
+ export declare function renderFactory(opts: {
21
+ model: string;
22
+ modelImport: string;
23
+ fields: ResourceField[];
24
+ foreignKeys: ForeignKey[];
25
+ }): string;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fakeValue = fakeValue;
4
+ exports.renderFactory = renderFactory;
5
+ const has = (name, pattern) => pattern.test(name);
6
+ /** A Faker expression for a column, or `undefined` when none fits. */
7
+ function fakeValue(field, model) {
8
+ const name = field.name.toLowerCase();
9
+ const sql = (field.sqlType ?? "").toLowerCase();
10
+ const length = Number(sql.match(/^n?(?:var)?char\((\d+)\)/)?.[1]) || undefined;
11
+ if (field.ts === "boolean")
12
+ return "faker.datatype.boolean()";
13
+ if (field.ts === "Date") {
14
+ if (has(name, /birth|born|dob/))
15
+ return "faker.date.birthdate()";
16
+ if (has(name, /expire|expiry|due|until|ends?_|deadline|scheduled/))
17
+ return "faker.date.future()";
18
+ return "faker.date.recent()";
19
+ }
20
+ if (field.ts === "number") {
21
+ if (has(name, /price|amount|cost|total|balance|credit|debit|salary|fee|rate|latitude|longitude/) ||
22
+ /^(decimal|numeric|real|float|double|money)/.test(sql)) {
23
+ if (has(name, /latitude/))
24
+ return "faker.location.latitude()";
25
+ if (has(name, /longitude/))
26
+ return "faker.location.longitude()";
27
+ return "faker.number.float({ min: 0, max: 1000, fractionDigits: 2 })";
28
+ }
29
+ if (has(name, /(^|_)age$/))
30
+ return "faker.number.int({ min: 18, max: 90 })";
31
+ if (has(name, /year/))
32
+ return "faker.date.past({ years: 30 }).getFullYear()";
33
+ if (has(name, /quantity|qty|count|stock/))
34
+ return "faker.number.int({ min: 0, max: 100 })";
35
+ return "faker.number.int({ min: 1, max: 1000 })";
36
+ }
37
+ if (field.ts === "string") {
38
+ const value = fakeString(name, sql, length, model);
39
+ // Keep values within a short varchar(n): faker's can run longer.
40
+ const fixed = /^faker\.string\.(uuid|alphanumeric)\(/.test(value);
41
+ return length !== undefined && length < 60 && !fixed ? `${value}.slice(0, ${length})` : value;
42
+ }
43
+ if (field.ts.startsWith("Record<") || field.ts === "object")
44
+ return "{}";
45
+ return undefined;
46
+ }
47
+ function fakeString(name, sql, length, model) {
48
+ {
49
+ if (has(name, /email/))
50
+ return "faker.internet.email()";
51
+ if (has(name, /^first_?name$/))
52
+ return "faker.person.firstName()";
53
+ if (has(name, /^last_?name$|surname/))
54
+ return "faker.person.lastName()";
55
+ if (has(name, /user_?name|login|handle/))
56
+ return "faker.internet.username()";
57
+ if (has(name, /password|secret/))
58
+ return "faker.internet.password()";
59
+ if (has(name, /phone|mobile|tel/))
60
+ return 'faker.phone.number({ style: "international" })';
61
+ if (has(name, /uuid|guid/) || sql === "uuid" || sql === "uniqueidentifier")
62
+ return "faker.string.uuid()";
63
+ if (has(name, /avatar/))
64
+ return "faker.image.avatar()";
65
+ if (has(name, /image|photo|picture|thumbnail/))
66
+ return "faker.image.url()";
67
+ if (has(name, /url|website|link|homepage/))
68
+ return "faker.internet.url()";
69
+ if (has(name, /slug/))
70
+ return "faker.lorem.slug()";
71
+ if (has(name, /street|address/))
72
+ return "faker.location.streetAddress()";
73
+ if (has(name, /city|town/))
74
+ return "faker.location.city()";
75
+ if (has(name, /country/))
76
+ return "faker.location.country()";
77
+ if (has(name, /zip|postal|postcode/))
78
+ return "faker.location.zipCode()";
79
+ if (has(name, /company|organi[sz]ation|employer/))
80
+ return "faker.company.name()";
81
+ if (has(name, /job|position|occupation/))
82
+ return "faker.person.jobTitle()";
83
+ if (has(name, /color|colour/))
84
+ return "faker.color.human()";
85
+ if (has(name, /currency/))
86
+ return "faker.finance.currencyCode()";
87
+ if (has(name, /(^|_)ip(_|$)|ip_?address/))
88
+ return "faker.internet.ip()";
89
+ if (has(name, /(^|_)(code|sku|reference|ref)$/)) {
90
+ return `faker.string.alphanumeric(${Math.min(length ?? 8, 8)}).toUpperCase()`;
91
+ }
92
+ if (has(name, /title|subject|headline/))
93
+ return "faker.lorem.sentence()";
94
+ if (has(name, /description|body|content|bio|about|text|notes?|summary|message|comment/) ||
95
+ /^(n?text|longtext|mediumtext)$/.test(sql)) {
96
+ return "faker.lorem.paragraph()";
97
+ }
98
+ if (has(name, /(^|_)name$/) || name === "name")
99
+ return nameFor(model);
100
+ if (length !== undefined && length < 24)
101
+ return `faker.string.alphanumeric(${Math.min(length, 10)})`;
102
+ return "faker.lorem.words(3)";
103
+ }
104
+ }
105
+ /** `name` means a person on a user, a word on a role, a product on a product… */
106
+ function nameFor(model) {
107
+ const m = model.toLowerCase();
108
+ if (/role|category|tag|group|team|permission|status|type|label/.test(m))
109
+ return "faker.word.noun()";
110
+ if (/product|item|article|good/.test(m))
111
+ return "faker.commerce.productName()";
112
+ if (/company|organi[sz]ation|account|vendor|supplier|tenant|brand/.test(m))
113
+ return "faker.company.name()";
114
+ if (/city|town/.test(m))
115
+ return "faker.location.city()";
116
+ if (/country/.test(m))
117
+ return "faker.location.country()";
118
+ return "faker.person.fullName()";
119
+ }
120
+ const key = (name) => (/^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name));
121
+ function renderFactory(opts) {
122
+ const fk = new Map(opts.foreignKeys.map((f) => [f.column, f]));
123
+ const lines = [];
124
+ const imports = new Map(); // factory → import path
125
+ for (const field of opts.fields) {
126
+ const foreign = fk.get(field.name);
127
+ if (foreign) {
128
+ if (foreign.factory) {
129
+ lines.push(`${key(field.name)}: ${foreign.factory},`);
130
+ imports.set(foreign.factory, foreign.factoryImport);
131
+ }
132
+ else if (field.nullable) {
133
+ lines.push(`${key(field.name)}: null,`);
134
+ }
135
+ else {
136
+ lines.push(`// ${key(field.name)}: ${pascal(foreign.model)}Factory, (create it: megh make:factory ${foreign.model})`);
137
+ }
138
+ continue;
139
+ }
140
+ const value = fakeValue(field, opts.model);
141
+ if (value)
142
+ lines.push(`${key(field.name)}: ${value},`);
143
+ else
144
+ lines.push(`// ${key(field.name)}: set a value (no fake value fits ${field.ts}),`);
145
+ }
146
+ const usesFaker = lines.some((l) => !l.startsWith("//") && l.includes("faker."));
147
+ const header = [
148
+ `import { defineFactory } from "@meghjs/core";`,
149
+ `import { ${opts.model} } from "${opts.modelImport}";`,
150
+ ...[...imports].map(([name, from]) => `import { ${name} } from "${from}";`),
151
+ ];
152
+ return (header.join("\n") +
153
+ "\n\n" +
154
+ `export const ${opts.model}Factory = defineFactory(${opts.model}, (${usesFaker ? "{ faker }" : ""}) => ({\n` +
155
+ lines.map((l) => ` ${l}`).join("\n") +
156
+ (lines.length ? "\n" : "") +
157
+ `}));\n`);
158
+ }
159
+ const pascal = (snake) => snake.replace(/(^|_)(\w)/g, (_, __, c) => c.toUpperCase());
@@ -1,3 +1,4 @@
1
+ import { type ModelChanges } from "./update-model";
1
2
  export type MakeBaseOptions = {
2
3
  /** Directory to start the project-root search from. Defaults to `process.cwd()`. */
3
4
  cwd?: string;
@@ -25,6 +26,20 @@ export type MakeControllerOptions = MakeServiceOptions & {
25
26
  * otherwise it gets placeholder columns.
26
27
  */
27
28
  export declare function makeModel(name: string, opts?: MakeModelOptions): string;
29
+ export type UpdateModelOptions = Pick<MakeBaseOptions, "cwd" | "root"> & {
30
+ /** Table to read (default: the model's `@Table`, else the plural snake_case name). */
31
+ table?: string;
32
+ /** Also rewrite the model's DTO file from the updated columns. */
33
+ dto?: boolean;
34
+ /** Report the changes without writing anything. */
35
+ dryRun?: boolean;
36
+ };
37
+ /**
38
+ * `update:model user`: sync an existing model's column fields with its table
39
+ * as the migrations now leave it (after an alter-table migration, say). Only
40
+ * the column declarations change; relations, methods and other code stay.
41
+ */
42
+ export declare function updateModel(name: string, opts?: UpdateModelOptions): ModelChanges;
28
43
  export declare function makeService(name: string, opts?: MakeServiceOptions): string;
29
44
  export declare function makeController(name: string, opts?: MakeControllerOptions): string;
30
45
  export type MakeResourceOptions = Pick<MakeBaseOptions, "cwd" | "force"> & {
@@ -58,3 +73,18 @@ export declare function migrationTimestamp(date?: Date): string;
58
73
  * remove/drop/alter/change/update) an alter-table one, anything else a blank one.
59
74
  */
60
75
  export declare function makeMigration(name: string, opts?: MakeMigrationOptions): string;
76
+ export type MakeSeederOptions = Pick<MakeBaseOptions, "cwd" | "force">;
77
+ /**
78
+ * Create `<seeders>/<name>.seeder.ts`. `make:seeder database` writes the
79
+ * entry seeder that `db:seed` runs, calling the seeders that already exist.
80
+ */
81
+ export declare function makeSeeder(name: string, opts?: MakeSeederOptions): string;
82
+ /** The `database` seeder, calling `others` in order. */
83
+ export declare function renderEntrySeeder(others: string[]): string;
84
+ export type MakeFactoryOptions = Pick<MakeBaseOptions, "cwd" | "force">;
85
+ /**
86
+ * `make:factory user`: `<factories>/user.factory.ts` exporting `UserFactory`,
87
+ * with a Faker value for each of the model's columns. Foreign keys use the
88
+ * related model's factory when it exists.
89
+ */
90
+ export declare function makeFactory(name: string, opts?: MakeFactoryOptions): string;
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeModel = makeModel;
7
+ exports.updateModel = updateModel;
7
8
  exports.makeService = makeService;
8
9
  exports.makeController = makeController;
9
10
  exports.makeResource = makeResource;
@@ -12,6 +13,9 @@ exports.makeMiddleware = makeMiddleware;
12
13
  exports.makeDto = makeDto;
13
14
  exports.migrationTimestamp = migrationTimestamp;
14
15
  exports.makeMigration = makeMigration;
16
+ exports.makeSeeder = makeSeeder;
17
+ exports.renderEntrySeeder = renderEntrySeeder;
18
+ exports.makeFactory = makeFactory;
15
19
  const fs_1 = __importDefault(require("fs"));
16
20
  const path_1 = __importDefault(require("path"));
17
21
  const errors_1 = require("../errors");
@@ -23,6 +27,8 @@ const migrate_1 = require("../commands/migrate");
23
27
  const migration_schema_1 = require("./migration-schema");
24
28
  const orm_model_1 = require("./orm-model");
25
29
  const resource_1 = require("./resource");
30
+ const update_model_1 = require("./update-model");
31
+ const factory_1 = require("./factory");
26
32
  const DEFAULT_DIRS = {
27
33
  model: "models",
28
34
  service: "services",
@@ -89,6 +95,71 @@ function makeModel(name, opts = {}) {
89
95
  }
90
96
  return file;
91
97
  }
98
+ /**
99
+ * `update:model user`: sync an existing model's column fields with its table
100
+ * as the migrations now leave it (after an alter-table migration, say). Only
101
+ * the column declarations change; relations, methods and other code stay.
102
+ */
103
+ function updateModel(name, opts = {}) {
104
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
105
+ const n = (0, names_1.resolveName)(name, "Model");
106
+ const file = path_1.default.join(targetDir(projectRoot, "model", n.dirs, opts.root), `${n.fileBase}.model.ts`);
107
+ const rel = (p) => relPath(projectRoot, p);
108
+ if (!fs_1.default.existsSync(file)) {
109
+ throw new errors_1.CliError(`There is no ${n.base} model (${rel(file)}). Create it: megh make:model ${name}`);
110
+ }
111
+ const source = fs_1.default.readFileSync(file, "utf8");
112
+ if (/@Entity\s*\(/.test(source)) {
113
+ throw new errors_1.CliError(`${rel(file)} is a TypeORM entity; update:model only updates Megh ORM models.`);
114
+ }
115
+ if (!/@Table\s*\(/.test(source)) {
116
+ throw new errors_1.CliError(`${rel(file)} declares its columns without decorators (static table/casts), which update:model ` +
117
+ `can't edit safely. Regenerate it with: megh make:model ${name} --force (then re-add relations and methods).`);
118
+ }
119
+ const { migrations } = (0, migrate_1.databasePaths)(projectRoot);
120
+ const snake = (0, names_1.snakeCase)(n.base);
121
+ const declared = source.match(/@Table\s*\(\s*["'`]([^"'`]+)["'`]/)?.[1];
122
+ const candidates = opts.table ? [opts.table] : [declared, (0, orm_model_1.pluralize)(snake), snake].filter((t) => !!t);
123
+ const tables = (0, migration_schema_1.readMigrationSchema)(migrations);
124
+ const table = candidates.map((t) => tables.get(t)).find((t) => t !== undefined);
125
+ if (!table) {
126
+ throw new errors_1.CliError(`No migration in ${rel(migrations)} creates the "${candidates[0]}" table, so there is nothing to sync. ` +
127
+ `Pass the table with --table if it has another name.`);
128
+ }
129
+ const result = (0, update_model_1.syncModelSource)(source, table);
130
+ const { added, removed, updated, kept } = result.changes;
131
+ const changed = result.source !== source;
132
+ const prefix = opts.dryRun ? "Would update" : "Model updated";
133
+ if (!changed) {
134
+ log_1.log.info(`${rel(file)} already matches the "${table.name}" table.`);
135
+ }
136
+ else {
137
+ if (!opts.dryRun)
138
+ fs_1.default.writeFileSync(file, result.source, "utf8");
139
+ log_1.log.success(`${prefix}: ${rel(file)}`);
140
+ }
141
+ for (const c of added)
142
+ log_1.log.info(` + ${c}`);
143
+ for (const c of removed)
144
+ log_1.log.info(` - ${c}`);
145
+ for (const c of updated)
146
+ log_1.log.info(` ~ ${c}`);
147
+ for (const c of kept) {
148
+ log_1.log.warn(` ${c} has hand-made changes, so it was kept as written; check it against the migration.`);
149
+ }
150
+ const dtoFile = path_1.default.join(targetDir(projectRoot, "dto", n.dirs), `${n.fileBase}.dto.ts`);
151
+ if (opts.dto) {
152
+ const model = { name: n, file, schema: (0, resource_1.readModelSchema)(result.source, table), typeorm: false };
153
+ if (opts.dryRun)
154
+ log_1.log.info(` Would rewrite ${rel(dtoFile)}`);
155
+ else
156
+ write(dtoFile, renderDtoFor(model), true, "DTO", projectRoot);
157
+ }
158
+ else if (changed && fs_1.default.existsSync(dtoFile)) {
159
+ log_1.log.info(` ${rel(dtoFile)} may be out of date: rerun with --dto to rewrite it.`);
160
+ }
161
+ return result.changes;
162
+ }
92
163
  function renderEntityModel(model) {
93
164
  return (0, stubs_1.renderStub)("models/entity-model.stub", { Model: model, table: (0, names_1.snakeCase)(model) });
94
165
  }
@@ -161,6 +232,7 @@ function renderResourceController(model, controllerFile, className, route, servi
161
232
  const numeric = model.schema.primaryKeyType === "number";
162
233
  return (0, stubs_1.renderStub)("controllers/model-controller.stub", {
163
234
  ...vars,
235
+ modelImport: importPath(controllerFile, model.file),
164
236
  Plural: (0, names_1.pascalCase)((0, orm_model_1.pluralize)((0, names_1.snakeCase)(m.base))),
165
237
  dtoImport: importPath(controllerFile, dtoFile),
166
238
  primaryKeyType: numeric ? "number" : "string",
@@ -323,3 +395,95 @@ function makeMigration(name, opts = {}) {
323
395
  const file = path_1.default.join(migrations, `${migrationTimestamp(opts.now)}_${snake}.ts`);
324
396
  return write(file, content, opts.force, "Migration", projectRoot);
325
397
  }
398
+ /**
399
+ * Create `<seeders>/<name>.seeder.ts`. `make:seeder database` writes the
400
+ * entry seeder that `db:seed` runs, calling the seeders that already exist.
401
+ */
402
+ function makeSeeder(name, opts = {}) {
403
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
404
+ if (/[\/]/.test(name))
405
+ throw new errors_1.CliError(`Seeders live in one folder: use a plain name, not "${name}".`);
406
+ // `UserSeeder`, `user_seeder` and `users` all name the file after the table.
407
+ const snake = (0, names_1.snakeCase)(name.replace(/[-_]?seeder$/i, ""));
408
+ if (!snake)
409
+ throw new errors_1.CliError(`Invalid seeder name "${name}".`);
410
+ const { seeders } = (0, migrate_1.databasePaths)(projectRoot);
411
+ const file = path_1.default.join(seeders, `${snake}.seeder.ts`);
412
+ const rel = (p) => relPath(projectRoot, p);
413
+ let content;
414
+ if (snake === "database") {
415
+ content = renderEntrySeeder(existingSeeders(seeders).filter((s) => s !== "database"));
416
+ }
417
+ else {
418
+ content = (0, stubs_1.renderStub)("seeders/seeder.stub", { table: (0, orm_model_1.pluralRoute)(snake) });
419
+ }
420
+ write(file, content, opts.force, "Seeder", projectRoot);
421
+ if (snake !== "database") {
422
+ const entry = path_1.default.join(seeders, "database.seeder.ts");
423
+ if (fs_1.default.existsSync(entry)) {
424
+ log_1.log.info(` Run it from ${rel(entry)}: await call(${JSON.stringify(snake)});`);
425
+ }
426
+ else {
427
+ log_1.log.info(" megh db:seed runs every seeder in file-name order. To choose the order, " +
428
+ "create the entry seeder: megh make:seeder database");
429
+ }
430
+ }
431
+ return file;
432
+ }
433
+ /** The `database` seeder, calling `others` in order. */
434
+ function renderEntrySeeder(others) {
435
+ return (0, stubs_1.renderStub)("seeders/database-seeder.stub", {
436
+ params: others.length ? "{ call }" : "",
437
+ body: others.length
438
+ ? `await call(${others.map((s) => JSON.stringify(s)).join(", ")});`
439
+ : `// Add { call } to run()'s parameters, then: await call("roles", "users");`,
440
+ });
441
+ }
442
+ /** Names of the seeders in `folder`, in file-name order. */
443
+ function existingSeeders(folder) {
444
+ if (!fs_1.default.existsSync(folder))
445
+ return [];
446
+ return fs_1.default
447
+ .readdirSync(folder)
448
+ .filter((f) => /\.(c?js|mjs|c?ts|mts)$/.test(f) && !/\.d\.[cm]?ts$/.test(f))
449
+ .sort()
450
+ .map((f) => f.replace(/\.(c?js|mjs|c?ts|mts)$/, "").replace(/\.seeder$/, ""));
451
+ }
452
+ /**
453
+ * `make:factory user`: `<factories>/user.factory.ts` exporting `UserFactory`,
454
+ * with a Faker value for each of the model's columns. Foreign keys use the
455
+ * related model's factory when it exists.
456
+ */
457
+ function makeFactory(name, opts = {}) {
458
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
459
+ const n = (0, names_1.resolveName)(name.replace(/[-_.]?factory$/i, ""), "Model");
460
+ const modelFile = path_1.default.join(targetDir(projectRoot, "model", n.dirs), `${n.fileBase}.model.ts`);
461
+ if (!fs_1.default.existsSync(modelFile)) {
462
+ throw new errors_1.CliError(`There is no ${n.base} model (${relPath(projectRoot, modelFile)}) to build a factory for. ` +
463
+ `Create it first: megh make:model ${n.base}`);
464
+ }
465
+ const model = resolveResourceModel(projectRoot, [...n.dirs, n.base].join("/"));
466
+ if (model.typeorm)
467
+ throw new errors_1.CliError(`${relPath(projectRoot, modelFile)} is a TypeORM entity; factories build Megh ORM models.`);
468
+ const { factories } = (0, migrate_1.databasePaths)(projectRoot);
469
+ const file = path_1.default.join(factories, ...n.dirs, `${n.fileBase}.factory.ts`);
470
+ const fields = model.schema.inputFields;
471
+ const foreignKeys = fields
472
+ .filter((f) => /_id$/.test(f.name) && (f.ts === "number" || f.ts === "string"))
473
+ .map((f) => {
474
+ const related = (0, names_1.resolveName)(f.name.replace(/_id$/, ""), "Model");
475
+ const factoryFile = path_1.default.join(factories, `${related.fileBase}.factory.ts`);
476
+ const exists = fs_1.default.existsSync(factoryFile);
477
+ return {
478
+ column: f.name,
479
+ model: (0, names_1.snakeCase)(related.base),
480
+ ...(exists ? { factory: `${related.base}Factory`, factoryImport: importPath(file, factoryFile) } : {}),
481
+ };
482
+ });
483
+ write(file, (0, factory_1.renderFactory)({ model: n.base, modelImport: importPath(file, modelFile), fields, foreignKeys }), opts.force, "Factory", projectRoot);
484
+ log_1.log.info(` Use it in a seeder or test: await ${n.base}Factory.createMany(10);`);
485
+ if (!(0, project_1.installedVersion)("@faker-js/faker", projectRoot)) {
486
+ log_1.log.warn("Factories use Faker for fake values. Install it: npm install -D @faker-js/faker");
487
+ }
488
+ return file;
489
+ }
@@ -111,6 +111,10 @@ function literal(arg) {
111
111
  return undefined;
112
112
  return m[2];
113
113
  }
114
+ /** The value of a plain number literal, else `undefined`. */
115
+ function literalNumber(arg) {
116
+ return arg !== undefined && /^\d+$/.test(arg.trim()) ? Number(arg.trim()) : undefined;
117
+ }
114
118
  /** A column data type argument: `"text"`, `sql\`varchar(255)\``, … */
115
119
  function dataType(arg) {
116
120
  if (!arg)
@@ -378,9 +382,11 @@ function applyBlueprintCall(table, method, args, chain) {
378
382
  return;
379
383
  }
380
384
  }
381
- const type = BUILDER_TYPES[method];
382
- if (!type)
385
+ const builderType = BUILDER_TYPES[method];
386
+ if (!builderType)
383
387
  return;
388
+ // string(name, length = 255) is a varchar(length) column.
389
+ const type = method === "string" ? `varchar(${Number(literalNumber(args[1]) ?? 255)})` : builderType;
384
390
  const columnName = name ?? (method === "id" ? "id" : undefined);
385
391
  if (!columnName)
386
392
  return;
@@ -1,4 +1,4 @@
1
- import type { MigrationTable } from "./migration-schema";
1
+ import type { MigrationColumn, MigrationTable } from "./migration-schema";
2
2
  /** Plural of a snake_case name, inflecting the last word: `blog_post` → `blog_posts`. */
3
3
  export declare function pluralize(snake: string): string;
4
4
  /**
@@ -18,6 +18,11 @@ interface FieldType {
18
18
  export declare function fieldType(sqlType: string): FieldType;
19
19
  /** A model class for `table`, declaring the columns its migrations create. */
20
20
  export declare function renderOrmModel(model: string, table: MigrationTable): string;
21
+ /** The decorators and declaration of one column. */
22
+ export declare function renderField(column: MigrationColumn): {
23
+ decorators: string[];
24
+ field: string;
25
+ };
21
26
  /** A model class for a table with no migration yet: placeholder columns. */
22
27
  export declare function renderBlankOrmModel(model: string, table: string): string;
23
28
  export {};
@@ -5,6 +5,7 @@ exports.singularize = singularize;
5
5
  exports.pluralRoute = pluralRoute;
6
6
  exports.fieldType = fieldType;
7
7
  exports.renderOrmModel = renderOrmModel;
8
+ exports.renderField = renderField;
8
9
  exports.renderBlankOrmModel = renderBlankOrmModel;
9
10
  const stubs_1 = require("../utils/stubs");
10
11
  /**
@@ -139,8 +140,15 @@ function renderField(column) {
139
140
  options.push("nullable: true");
140
141
  if (cast && CAST_TYPES[cast])
141
142
  options.push(`type: ${q(CAST_TYPES[cast])}`);
142
- else if (cast === "number")
143
- options.push(`cast: "number"`); // e.g. Postgres bigint, read as text
143
+ else {
144
+ // A `T | null` field's emitted type is `Object`, so name the column type
145
+ // (for OpenAPI schemas); it doesn't change how values convert.
146
+ const sqlType = !column.notNull ? plainColumnType(column.type) : undefined;
147
+ if (sqlType)
148
+ options.push(`type: ${q(sqlType)}`);
149
+ if (cast === "number")
150
+ options.push(`cast: "number"`); // e.g. Postgres bigint, read as text
151
+ }
144
152
  // Key columns are already declared by @PrimaryKey / @AutoIncrement.
145
153
  if (options.length > 0 || decorators.length === 0) {
146
154
  decorators.push(options.length ? `@Column({ ${options.join(", ")} })` : "@Column()");
@@ -149,6 +157,27 @@ function renderField(column) {
149
157
  const mark = column.generated ? "?" : "!";
150
158
  return { decorators, field: `${name}${mark}: ${column.notNull ? ts : `${ts} | null`};` };
151
159
  }
160
+ /** The model column type for a SQL type that needs no cast, or `undefined`. */
161
+ function plainColumnType(sqlType) {
162
+ const base = sqlType.replace(/\(.*$/, "").trim();
163
+ if (/^(varchar|char|character|character varying|nvarchar|nchar|citext|enum|inet|cidr|macaddr)$/.test(base))
164
+ return "string";
165
+ if (/^(text|tinytext|mediumtext|longtext|ntext)$/.test(base))
166
+ return "text";
167
+ if (base === "uuid" || base === "uniqueidentifier")
168
+ return "uuid";
169
+ if (/^(int\d?|integer|smallint|mediumint|tinyint|serial\d?|smallserial)$/.test(base))
170
+ return "integer";
171
+ if (/^(bigint|bigserial)$/.test(base))
172
+ return "bigint";
173
+ if (/^(decimal|numeric|money)$/.test(base))
174
+ return "decimal";
175
+ if (/^(real|float\d?|double|double precision)$/.test(base))
176
+ return "double";
177
+ if (/^(time|timetz|time with(out)? time zone)$/.test(base))
178
+ return "time";
179
+ return undefined;
180
+ }
152
181
  /** A model class for a table with no migration yet: placeholder columns. */
153
182
  function renderBlankOrmModel(model, table) {
154
183
  return (0, stubs_1.renderStub)("models/orm-model-blank.stub", { Model: model, table: q(table) });
@@ -26,6 +26,27 @@ export interface ResourceSchema {
26
26
  /** Columns a client may send when creating or updating a row. */
27
27
  inputFields: ResourceField[];
28
28
  }
29
+ export interface Declared {
30
+ name: string;
31
+ ts: string;
32
+ /** `| null`, `| undefined` or `?`. */
33
+ nullable: boolean;
34
+ /** Declared with `?`. */
35
+ optional: boolean;
36
+ /** `| null` or `| undefined` in the type. */
37
+ nullInType: boolean;
38
+ decorators: string[];
39
+ /** First line (0-based) of the declaration, including its decorators. */
40
+ startLine: number;
41
+ /** Line (0-based) of the property itself. */
42
+ endLine: number;
43
+ }
44
+ /**
45
+ * Property declarations of the model class (`name!: string;`), with the
46
+ * decorators above each one. Initialised properties (relations such as
47
+ * `posts = hasMany(...)`), statics and methods are skipped.
48
+ */
49
+ export declare function declaredProperties(source: string): Declared[];
29
50
  /** Read a model (Megh ORM or TypeORM) for resource generation. */
30
51
  export declare function readModelSchema(source: string, table?: MigrationTable): ResourceSchema;
31
52
  /** `src/dtos/<model>.dto.ts`: create, update and list-query DTOs. */
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.declaredProperties = declaredProperties;
3
4
  exports.readModelSchema = readModelSchema;
4
5
  exports.renderResourceDto = renderResourceDto;
5
6
  const orm_model_1 = require("./orm-model");
@@ -63,11 +64,13 @@ function leadingDecorators(line) {
63
64
  function declaredProperties(source) {
64
65
  const out = [];
65
66
  let decorators = [];
67
+ let startLine = -1;
66
68
  // Bracket depth at the start of each line: properties sit directly in the
67
69
  // class body (depth 1), not inside object literals or decorator arguments.
68
70
  let depth = 0;
69
- for (const raw of source.split(/\r?\n/)) {
70
- const line = withoutLineComment(raw).trim();
71
+ const lines = source.split(/\r?\n/);
72
+ for (let index = 0; index < lines.length; index++) {
73
+ const line = withoutLineComment(lines[index]).trim();
71
74
  const atDepth = depth;
72
75
  depth += bracketDelta(line);
73
76
  if (atDepth !== 1) {
@@ -77,6 +80,8 @@ function declaredProperties(source) {
77
80
  continue;
78
81
  }
79
82
  const split = leadingDecorators(line);
83
+ if (split.decorators.length > 0 && decorators.length === 0)
84
+ startLine = index;
80
85
  decorators.push(...split.decorators);
81
86
  // A decorator on its own line, possibly continued on the next lines.
82
87
  if (split.decorators.length > 0 && !split.rest)
@@ -88,7 +93,16 @@ function declaredProperties(source) {
88
93
  const nullInType = parts.includes("null") || parts.includes("undefined");
89
94
  const optional = prop[2] === "?";
90
95
  const ts = parts.filter((p) => p !== "null" && p !== "undefined").join(" | ") || "unknown";
91
- out.push({ name, ts, nullable: optional || nullInType, optional, nullInType, decorators });
96
+ out.push({
97
+ name,
98
+ ts,
99
+ nullable: optional || nullInType,
100
+ optional,
101
+ nullInType,
102
+ decorators,
103
+ startLine: decorators.length > 0 ? startLine : index,
104
+ endLine: index,
105
+ });
92
106
  }
93
107
  if (line && !line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
94
108
  decorators = [];
@@ -0,0 +1,21 @@
1
+ import type { MigrationTable } from "./migration-schema";
2
+ /**
3
+ * Brings a decorated Megh ORM model's column fields in line with its table as
4
+ * the migrations leave it, for `update:model`. Only the column declarations
5
+ * change: new columns are added (in migration order), dropped ones removed,
6
+ * and fields still in the shape `make:model` writes are rewritten with the
7
+ * current type and nullability. Fields with hand-made changes (a `name:`
8
+ * mapping, a custom cast, extra options or decorators) are kept as written.
9
+ * Relations, methods, statics and comments are left alone.
10
+ */
11
+ export interface ModelChanges {
12
+ added: string[];
13
+ removed: string[];
14
+ updated: string[];
15
+ /** Customized fields kept as written although the migration differs. */
16
+ kept: string[];
17
+ }
18
+ export declare function syncModelSource(source: string, table: MigrationTable): {
19
+ source: string;
20
+ changes: ModelChanges;
21
+ };
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncModelSource = syncModelSource;
4
+ const names_1 = require("../utils/names");
5
+ const orm_model_1 = require("./orm-model");
6
+ const resource_1 = require("./resource");
7
+ const COLUMN_DECORATOR = /^(Column|PrimaryKey|AutoIncrement|Identity|CreatedAt|UpdatedAt|DeletedAt)\b/;
8
+ const DECORATOR_IMPORTS = ["AutoIncrement", "Column", "CreatedAt", "DeletedAt", "Identity", "PrimaryKey", "UpdatedAt"];
9
+ /** `@Column({ … })` options `make:model` writes. */
10
+ const GENERATED_OPTIONS = new Set(["nullable", "type", "cast"]);
11
+ /** The column a field maps to: its `name:` option, else the property name. */
12
+ function columnOf(field) {
13
+ for (const d of field.decorators) {
14
+ const name = d.match(/\bname\s*:\s*["'`]([^"'`]+)["'`]/)?.[1];
15
+ if (name)
16
+ return name;
17
+ }
18
+ return field.name;
19
+ }
20
+ /** Whether a field still looks the way `make:model` wrote it. */
21
+ function isGenerated(field) {
22
+ if (columnOf(field) !== field.name)
23
+ return false;
24
+ return field.decorators.every((d) => {
25
+ if (/^(PrimaryKey|AutoIncrement|CreatedAt|UpdatedAt|DeletedAt)\(\s*\)$/.test(d))
26
+ return true;
27
+ const column = d.match(/^Column\(\s*(?:\{([^{}]*)\})?\s*\)$/);
28
+ if (!column)
29
+ return false;
30
+ const keys = [...(column[1] ?? "").matchAll(/([\w$]+)\s*:/g)].map((m) => m[1]);
31
+ return keys.every((k) => GENERATED_OPTIONS.has(k));
32
+ });
33
+ }
34
+ const normalize = (text) => text.replace(/\s+/g, " ").replace(/\s*([(){},:;])\s*/g, "$1").trim();
35
+ /** Comment lines directly above `line` (a doc comment for the field). */
36
+ function commentAbove(lines, line) {
37
+ let start = line;
38
+ while (start > 0 && /^\s*(\/\/|\/\*|\*)/.test(lines[start - 1]))
39
+ start--;
40
+ return start;
41
+ }
42
+ function syncModelSource(source, table) {
43
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
44
+ const lines = source.split(/\r?\n/);
45
+ const fields = (0, resource_1.declaredProperties)(source).filter((p) => p.decorators.some((d) => COLUMN_DECORATOR.test(d)));
46
+ const changes = { added: [], removed: [], updated: [], kept: [] };
47
+ const columnNames = new Set(table.columns.map((c) => c.name));
48
+ const byColumn = new Map(fields.map((f) => [columnOf(f), f]));
49
+ // A property the naming strategy maps to the column: `firstName` ↔ `first_name`.
50
+ const find = (column) => byColumn.get(column) ?? fields.find((f) => !columnNames.has(columnOf(f)) && (0, names_1.snakeCase)(f.name) === column);
51
+ const classLine = lines.findIndex((l) => /\bclass\s+[\w$]+[^{]*\{/.test(l));
52
+ if (classLine === -1 && fields.length === 0) {
53
+ throw new Error("No model class found.");
54
+ }
55
+ const indent = fields.length > 0 ? lines[fields[0].startLine].match(/^\s*/)[0] : " ";
56
+ const replace = new Map(); // first line of a span → its new text
57
+ const drop = new Set(); // lines removed
58
+ const insertAfter = new Map();
59
+ const used = new Set();
60
+ // New columns go after the previous column in migration order.
61
+ let anchor = fields.length > 0 ? commentAbove(lines, fields[0].startLine) - 1 : classLine;
62
+ for (const column of table.columns) {
63
+ const { decorators, field } = (0, orm_model_1.renderField)(column);
64
+ const fresh = `${decorators.join(" ")} ${field}`;
65
+ const existing = find(column.name);
66
+ if (!existing) {
67
+ insertAfter.set(anchor, [...(insertAfter.get(anchor) ?? []), indent + fresh]);
68
+ changes.added.push(column.name);
69
+ continue;
70
+ }
71
+ used.add(existing);
72
+ anchor = existing.endLine;
73
+ const span = lines.slice(existing.startLine, existing.endLine + 1).join(" ");
74
+ if (normalize(span) === normalize(fresh))
75
+ continue;
76
+ if (!isGenerated(existing)) {
77
+ changes.kept.push(column.name);
78
+ continue;
79
+ }
80
+ replace.set(existing.startLine, lines[existing.startLine].match(/^\s*/)[0] + fresh);
81
+ for (let i = existing.startLine + 1; i <= existing.endLine; i++)
82
+ drop.add(i);
83
+ changes.updated.push(column.name);
84
+ }
85
+ for (const field of fields) {
86
+ if (used.has(field))
87
+ continue;
88
+ for (let i = commentAbove(lines, field.startLine); i <= field.endLine; i++)
89
+ drop.add(i);
90
+ changes.removed.push(columnOf(field));
91
+ }
92
+ const out = [];
93
+ for (const extra of insertAfter.get(-1) ?? [])
94
+ out.push(extra);
95
+ lines.forEach((line, i) => {
96
+ if (replace.has(i))
97
+ out.push(replace.get(i));
98
+ else if (!drop.has(i))
99
+ out.push(line);
100
+ for (const extra of insertAfter.get(i) ?? [])
101
+ out.push(extra);
102
+ });
103
+ return { source: fixImports(out.join(eol)), changes };
104
+ }
105
+ /** Import the column decorators the model uses from `@meghjs/core`, and drop unused ones. */
106
+ function fixImports(source) {
107
+ const match = source.match(/import\s*\{([^}]*)\}\s*from\s*(["'])@meghjs\/core\2\s*;?/);
108
+ if (!match)
109
+ return source;
110
+ const body = source.slice(match.index + match[0].length);
111
+ const uses = (name) => new RegExp(String.raw `@${name}\s*\(`).test(body);
112
+ const names = match[1]
113
+ .split(",")
114
+ .map((n) => n.trim())
115
+ .filter(Boolean);
116
+ const local = (n) => n.replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim();
117
+ const kept = names.filter((n) => !DECORATOR_IMPORTS.includes(local(n)) || uses(local(n)));
118
+ const missing = DECORATOR_IMPORTS.filter((d) => uses(d) && !names.some((n) => local(n) === d));
119
+ if (missing.length === 0 && kept.length === names.length)
120
+ return source;
121
+ const all = [...kept, ...missing];
122
+ // Keep a sorted list sorted (make:model writes one).
123
+ const sorted = names.every((n, i) => i === 0 || local(names[i - 1]).localeCompare(local(n)) <= 0);
124
+ if (sorted)
125
+ all.sort((a, b) => local(a).localeCompare(local(b)));
126
+ const quote = match[2];
127
+ const statement = `import { ${all.join(", ")} } from ${quote}@meghjs/core${quote};`;
128
+ return source.slice(0, match.index) + statement + body;
129
+ }
package/dist/program.js CHANGED
@@ -110,8 +110,11 @@ function createProgram(run = {}) {
110
110
  "DB_NAME, ...) in the environment or .env, with optional settings in megh.database in\n" +
111
111
  "package.json. Migrations live in src/database/migrations; set megh.migrations to\n" +
112
112
  "change it. Sources are compiled with SWC first.");
113
- db("migrate", "Run pending migrations").action(() => {
114
- (0, migrate_1.migrate)({ cwd: cwd() });
113
+ db("migrate", "Run pending migrations")
114
+ .option("--seed", "Run the seeders afterwards (see db:seed)")
115
+ .option("--force", "With --seed: seed even when NODE_ENV is production")
116
+ .action((o) => {
117
+ (0, migrate_1.migrate)({ cwd: cwd(), seed: o.seed, force: o.force });
115
118
  });
116
119
  db("migrate:rollback", "Undo the last migration (or the last --step n)")
117
120
  .option("--step <n>", "Number of migrations to undo", parseInteger, 1)
@@ -121,8 +124,21 @@ function createProgram(run = {}) {
121
124
  db("migrate:reset", "Undo every migration").action(() => {
122
125
  (0, migrate_1.migrateReset)({ cwd: cwd() });
123
126
  });
124
- db("migrate:refresh", "Undo every migration, then run them all again").action(() => {
125
- (0, migrate_1.migrateRefresh)({ cwd: cwd() });
127
+ db("migrate:refresh", "Undo every migration, then run them all again")
128
+ .option("--seed", "Run the seeders afterwards (see db:seed)")
129
+ .option("--force", "With --seed: seed even when NODE_ENV is production")
130
+ .action((o) => {
131
+ (0, migrate_1.migrateRefresh)({ cwd: cwd(), seed: o.seed, force: o.force });
132
+ });
133
+ db("db:seed", "Fill the database: run the database seeder, or every seeder in file order")
134
+ .option("-s, --seeder <name>", "Run only this seeder, e.g. users for users.seeder.ts")
135
+ .option("--force", "Seed even when NODE_ENV is production")
136
+ .addHelpText("after", "\nSeeders live in src/database/seeders (set megh.seeders to change it). Without\n" +
137
+ "--seeder, database.seeder.ts runs and calls the others in its order; without it,\n" +
138
+ "every seeder runs in file-name order. A run is one transaction: if a seeder\n" +
139
+ "throws, nothing is saved.")
140
+ .action((o) => {
141
+ (0, migrate_1.dbSeed)({ cwd: cwd(), seeder: o.seeder, force: o.force });
126
142
  });
127
143
  db("migrate:status", "Show which migrations have run")
128
144
  .option("--json", "Print JSON")
@@ -138,6 +154,23 @@ function createProgram(run = {}) {
138
154
  .action((name, o) => {
139
155
  (0, make_1.makeMigration)(name, { cwd: cwd(), create: o.create, table: o.table, force: o.force });
140
156
  });
157
+ sub("make:seeder", "Create a seeder in src/database/seeders/<name>.seeder.ts")
158
+ .alias("m:sd")
159
+ .argument("<name>", "e.g. users, or database for the entry seeder db:seed runs")
160
+ .option("-f, --force", "Overwrite the file if it exists")
161
+ .action((name, o) => {
162
+ (0, make_1.makeSeeder)(name, { cwd: cwd(), force: o.force });
163
+ });
164
+ sub("make:factory", "Create a model factory in src/database/factories/<name>.factory.ts")
165
+ .alias("m:f")
166
+ .argument("<model>", "Model name, e.g. user for src/models/user.model.ts")
167
+ .option("-f, --force", "Overwrite the file if it exists")
168
+ .addHelpText("after", "\nWrites UserFactory = defineFactory(User, ({ faker }) => ({ ... })) with a Faker value\n" +
169
+ "for each column, picked from its name and type. A foreign key such as role_id uses\n" +
170
+ "RoleFactory when src/database/factories/role.factory.ts exists. Needs @faker-js/faker.")
171
+ .action((name, o) => {
172
+ (0, make_1.makeFactory)(name, { cwd: cwd(), force: o.force });
173
+ });
141
174
  // ── Generators ──────────────────────────────────────────────────────────
142
175
  const make = (name, aliases, description) => sub(name, description)
143
176
  .aliases(aliases)
@@ -150,6 +183,20 @@ function createProgram(run = {}) {
150
183
  .action((name, o) => {
151
184
  (0, make_1.makeModel)(name, { cwd: cwd(), ...o });
152
185
  });
186
+ sub("update:model", "Sync a model's columns with its migrations, keeping relations and methods")
187
+ .alias("u:m")
188
+ .argument("<name>", "Model name, optionally nested (e.g. admin/User)")
189
+ .option("-t, --table <table>", "Table to read (default: the model's @Table, else the plural snake_case name)")
190
+ .option("--dto", "Also rewrite src/dtos/<name>.dto.ts from the updated columns")
191
+ .option("--dry-run", "Show what would change without writing")
192
+ .option("--root <dir>", "Folder under src/ the model is in (also -rt)")
193
+ .addHelpText("after", "\nAfter an alter-table migration, e.g. schema.table(\"users\", t => { t.string(\"phone\"); t.dropColumn(\"age\") }):\n" +
194
+ "new columns are added to the model, dropped ones removed, and fields still as make:model\n" +
195
+ "wrote them get the current type and nullability. Fields you customized (a name: mapping,\n" +
196
+ "a custom cast, extra options) are kept and reported.")
197
+ .action((name, o) => {
198
+ (0, make_1.updateModel)(name, { cwd: cwd(), table: o.table, dto: o.dto, dryRun: o.dryRun, root: o.root });
199
+ });
153
200
  make("make:resource", ["m:r", "m:res"], "Create a REST resource for a model: its DTOs, a CRUD service and a controller")
154
201
  .option("-t, --table <table>", "Table to read the columns from when the model is missing (default: plural snake_case name)")
155
202
  .addHelpText("after", "\nThe model in src/models/<name>.model.ts is reused if it exists; otherwise it is\n" +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meghjs/cli",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "CLI for scaffolding and running Megh applications",
5
5
  "author": "Tareq Hossain",
6
6
  "license": "MIT",
@@ -44,7 +44,7 @@
44
44
  "vitest": "^4.1.12"
45
45
  },
46
46
  "peerDependencies": {
47
- "@meghjs/core": "^0.5.1"
47
+ "@meghjs/core": "^0.5.3"
48
48
  },
49
49
  "peerDependenciesMeta": {
50
50
  "@meghjs/core": {
@@ -59,5 +59,5 @@
59
59
  "publishConfig": {
60
60
  "access": "public"
61
61
  },
62
- "gitHead": "77cdb018997e7907d58d4877aa855e5e3bd2be3c"
62
+ "gitHead": "65437cf19a7f0ac6d6ed61ab8c69e10ef148dab0"
63
63
  }
package/readme.md CHANGED
@@ -44,11 +44,15 @@ npm run start:dev
44
44
  | `doctor` | | | Check Node.js, `@meghjs/core`, `reflect-metadata` and decorator settings |
45
45
  | `route:list` | `routes` | `--json`, `--static` | List the app's routes |
46
46
  | `make:model` | `m:m` | `-f`, `--orm`, `--root <dir>` | Create a model / TypeORM entity |
47
+ | `update:model` | `u:m` | `-t <table>`, `--dto`, `--dry-run`, `--root <dir>` | Sync a model's columns with its migrations, keeping relations and methods |
47
48
  | `make:controller` | `m:c` | `-f`, `-r`, `-m <model>`, `--orm`, `--root <dir>`, `--base-path` | Create a controller |
48
49
  | `make:service` | `m:s` | `-f`, `-r`, `-m <model>`, `--orm`, `--root <dir>` | Create a service |
49
50
  | `make:config` | `m:cnf` | `-f`, `--root <dir>` | Create an `@AppConfig` class |
50
51
  | `make:middleware` | `m:mlwr` | `-f`, `--root <dir>` | Create a middleware |
51
52
  | `make:dto` | `m:dto` | `-f`, `--root <dir>` | Create a class-validator DTO |
53
+ | `make:seeder` | `m:sd` | `-f` | Create a seeder in `src/database/seeders` (`database` for the entry seeder) |
54
+ | `db:seed` | | `-s <name>`, `--force` | Run the seeders in one transaction (also `migrate --seed`) |
55
+ | `make:factory` | `m:f` | `-f` | Create a model factory in `src/database/factories`, with Faker values per column |
52
56
 
53
57
  `-f` / `--force` overwrites an existing file. `-r` / `--resource` generates a
54
58
  full REST skeleton. `--root <dir>` (also `-rt`) writes under `src/<dir>`
@@ -1,4 +1,5 @@
1
- import { ApiController, Body, Delete, Get, Param, Post, Put, Query } from '@meghjs/core';
1
+ import { ApiController, ApiResponse, Body, Delete, Get, Paginated, Param, Post, Put, Query } from '@meghjs/core';
2
+ import { {Model} } from '{modelImport}';
2
3
  import { Create{Model}Dto, List{Plural}Query, Update{Model}Dto } from '{dtoImport}';
3
4
  import { {ServiceClass} } from '{serviceImport}';
4
5
 
@@ -7,26 +8,34 @@ export class {ClassName} {
7
8
  constructor(private readonly {serviceVar}: {ServiceClass}) {}
8
9
 
9
10
  @Get()
11
+ @ApiResponse(200, Paginated({Model}))
10
12
  index(@Query() query: List{Plural}Query) {
11
13
  return this.{serviceVar}.paginate(query);
12
14
  }
13
15
 
14
16
  @Get('/:id')
17
+ @ApiResponse(200, {Model})
18
+ @ApiResponse(404)
15
19
  show(@Param('id') id: {primaryKeyType}) {
16
20
  return this.{serviceVar}.findOrFail({idArg});
17
21
  }
18
22
 
19
23
  @Post()
24
+ @ApiResponse(200, {Model})
20
25
  create(@Body() body: Create{Model}Dto) {
21
26
  return this.{serviceVar}.create(body);
22
27
  }
23
28
 
24
29
  @Put('/:id')
30
+ @ApiResponse(200, {Model})
31
+ @ApiResponse(404)
25
32
  update(@Param('id') id: {primaryKeyType}, @Body() body: Update{Model}Dto) {
26
33
  return this.{serviceVar}.update({idArg}, body);
27
34
  }
28
35
 
29
36
  @Delete('/:id')
37
+ @ApiResponse(200, { type: 'object', properties: { message: { type: 'string' } } })
38
+ @ApiResponse(404)
30
39
  async delete(@Param('id') id: {primaryKeyType}) {
31
40
  await this.{serviceVar}.delete({idArg});
32
41
  return { message: '{Model} deleted.' };
@@ -0,0 +1,8 @@
1
+ import { defineSeeder } from "@meghjs/core";
2
+
3
+ // `megh db:seed` runs this seeder. Call the others from here, in order.
4
+ export default defineSeeder({
5
+ async run({params}) {
6
+ {body}
7
+ },
8
+ });
@@ -0,0 +1,10 @@
1
+ import { defineSeeder } from "@meghjs/core";
2
+
3
+ export default defineSeeder({
4
+ async run() {
5
+ // Insert rows with factories, models or the query builder, e.g.
6
+ // await UserFactory.createMany(10); // megh make:factory user
7
+ // await Role.create({ name: "Admin" });
8
+ // await DB.table("{table}").insert([{ ... }]);
9
+ },
10
+ });