@meghjs/cli 0.5.3 → 0.5.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 (47) hide show
  1. package/dist/generators/auth-files.d.ts +37 -0
  2. package/dist/generators/auth-files.js +198 -0
  3. package/dist/generators/auth.d.ts +26 -0
  4. package/dist/generators/auth.js +542 -0
  5. package/dist/generators/make.d.ts +8 -0
  6. package/dist/generators/make.js +12 -0
  7. package/dist/generators/migration-schema.d.ts +5 -0
  8. package/dist/generators/migration-schema.js +17 -0
  9. package/dist/generators/scaffold.d.ts +76 -0
  10. package/dist/generators/scaffold.js +353 -0
  11. package/dist/program.js +125 -3
  12. package/dist/templates/cascade.d.ts +37 -0
  13. package/dist/templates/cascade.js +87 -0
  14. package/dist/templates/catalog/common.d.ts +1 -0
  15. package/dist/templates/catalog/common.js +63 -0
  16. package/dist/templates/catalog/construction.d.ts +1 -0
  17. package/dist/templates/catalog/construction.js +138 -0
  18. package/dist/templates/catalog/crm.d.ts +1 -0
  19. package/dist/templates/catalog/crm.js +81 -0
  20. package/dist/templates/catalog/ecommerce.d.ts +1 -0
  21. package/dist/templates/catalog/ecommerce.js +143 -0
  22. package/dist/templates/catalog/education.d.ts +1 -0
  23. package/dist/templates/catalog/education.js +80 -0
  24. package/dist/templates/catalog/hr.d.ts +1 -0
  25. package/dist/templates/catalog/hr.js +83 -0
  26. package/dist/templates/catalog/logistics.d.ts +1 -0
  27. package/dist/templates/catalog/logistics.js +60 -0
  28. package/dist/templates/catalog/marketing.d.ts +1 -0
  29. package/dist/templates/catalog/marketing.js +104 -0
  30. package/dist/templates/catalog/medical.d.ts +1 -0
  31. package/dist/templates/catalog/medical.js +147 -0
  32. package/dist/templates/catalog/pos.d.ts +1 -0
  33. package/dist/templates/catalog/pos.js +110 -0
  34. package/dist/templates/catalog/real-estate.d.ts +1 -0
  35. package/dist/templates/catalog/real-estate.js +171 -0
  36. package/dist/templates/fields.d.ts +64 -0
  37. package/dist/templates/fields.js +331 -0
  38. package/dist/templates/index.d.ts +27 -0
  39. package/dist/templates/index.js +175 -0
  40. package/dist/templates/migration.d.ts +7 -0
  41. package/dist/templates/migration.js +80 -0
  42. package/dist/templates/template.d.ts +37 -0
  43. package/dist/templates/template.js +36 -0
  44. package/dist/utils/dialect.d.ts +8 -0
  45. package/dist/utils/dialect.js +57 -0
  46. package/package.json +17 -5
  47. package/readme.md +26 -1
@@ -0,0 +1,542 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.ROLE_MODES = exports.AUTH_STRATEGIES = void 0;
40
+ exports.scaffoldAuth = scaffoldAuth;
41
+ exports.scaffoldRbac = scaffoldRbac;
42
+ const crypto_1 = __importDefault(require("crypto"));
43
+ const fs_1 = __importDefault(require("fs"));
44
+ const path_1 = __importDefault(require("path"));
45
+ const errors_1 = require("../errors");
46
+ const migrate_1 = require("../commands/migrate");
47
+ const log_1 = require("../utils/log");
48
+ const project_1 = require("../utils/project");
49
+ const make_1 = require("./make");
50
+ const migration_schema_1 = require("./migration-schema");
51
+ const scaffold_1 = require("./scaffold");
52
+ const templates_1 = require("../templates");
53
+ const fields_1 = require("../templates/fields");
54
+ const migration_1 = require("../templates/migration");
55
+ const cascade_1 = require("../templates/cascade");
56
+ const dialect_1 = require("../utils/dialect");
57
+ const auth_files_1 = require("./auth-files");
58
+ exports.AUTH_STRATEGIES = ["jwt", "api-key", "both"];
59
+ exports.ROLE_MODES = ["none", "single", "multiple"];
60
+ const relPath = (root, file) => path_1.default.relative(root, file).split(path_1.default.sep).join("/");
61
+ const paths = {
62
+ rel(from, to) {
63
+ let rel = path_1.default.posix.relative(path_1.default.posix.dirname(from), to).replace(/\.ts$/, "");
64
+ if (!rel.startsWith("."))
65
+ rel = "./" + rel;
66
+ return rel;
67
+ },
68
+ };
69
+ const isInteractive = (o) => o.interactive === true && process.stdin.isTTY === true && process.stdout.isTTY === true;
70
+ async function ask(opts, withStrategy, defaultRoles) {
71
+ let strategy = opts.strategy;
72
+ let roles = opts.roles;
73
+ let permissions = opts.permissions;
74
+ if (strategy !== undefined && !exports.AUTH_STRATEGIES.includes(strategy)) {
75
+ throw new errors_1.CliError(`Unknown strategy "${strategy}". Choose from: ${exports.AUTH_STRATEGIES.join(", ")}.`);
76
+ }
77
+ if (roles !== undefined && !exports.ROLE_MODES.includes(roles)) {
78
+ throw new errors_1.CliError(`Unknown --roles "${roles}". Choose from: ${exports.ROLE_MODES.join(", ")}.`);
79
+ }
80
+ if (isInteractive(opts)) {
81
+ const prompt = (await Promise.resolve().then(() => __importStar(require("inquirer")))).default;
82
+ if (withStrategy && !strategy) {
83
+ ({ strategy } = await prompt.prompt([
84
+ {
85
+ type: "list",
86
+ name: "strategy",
87
+ message: "How do clients sign in?",
88
+ choices: [
89
+ { name: "JWT: POST /auth/login returns a Bearer token", value: "jwt" },
90
+ { name: "API keys: X-API-Key header, keys created per user", value: "api-key" },
91
+ { name: "Both: Bearer tokens and API keys", value: "both" },
92
+ ],
93
+ default: "jwt",
94
+ },
95
+ ]));
96
+ }
97
+ if (!roles) {
98
+ ({ roles } = await prompt.prompt([
99
+ {
100
+ type: "list",
101
+ name: "roles",
102
+ message: "Roles (RBAC):",
103
+ choices: [
104
+ { name: "None", value: "none" },
105
+ { name: "Single: one role per user (users.role_id)", value: "single" },
106
+ { name: "Multiple: any number of roles per user (user_roles)", value: "multiple" },
107
+ ],
108
+ default: defaultRoles,
109
+ },
110
+ ]));
111
+ }
112
+ if (roles !== "none" && permissions === undefined) {
113
+ ({ permissions } = await prompt.prompt([
114
+ { type: "confirm", name: "permissions", message: "Should roles grant permissions?", default: true },
115
+ ]));
116
+ }
117
+ }
118
+ roles ??= defaultRoles;
119
+ return {
120
+ strategy: withStrategy ? (strategy ?? "jwt") : undefined,
121
+ roles,
122
+ permissions: roles !== "none" && permissions === true,
123
+ };
124
+ }
125
+ /** Tables the plan needs, as templates. */
126
+ function tableTemplates(projectRoot, plan) {
127
+ const domains = (0, templates_1.allDomains)(projectRoot);
128
+ const t = (name) => (0, templates_1.findTemplate)(domains, `common/${name}`);
129
+ let users = t("user");
130
+ if (plan.roles === "single")
131
+ users = { ...users, fields: [...users.fields, ...(0, fields_1.parseFieldSpec)("role_id:nullOnDelete")] };
132
+ const others = [];
133
+ if ((0, auth_files_1.usesRoles)(plan))
134
+ others.push(t("role"));
135
+ if (plan.permissions)
136
+ others.push(t("permission"), t("role_permission"));
137
+ if (plan.roles === "multiple")
138
+ others.push(t("user_role"));
139
+ if ((0, auth_files_1.usesApiKeys)(plan))
140
+ others.push(t("api_key"));
141
+ return { users, others };
142
+ }
143
+ /** Columns the users table needs for this plan. */
144
+ function requiredUserColumns(plan, users) {
145
+ const names = [...(plan.strategy ? ["email", "password"] : []), ...(plan.roles === "single" ? ["role_id"] : [])];
146
+ return users.fields.filter((f) => names.includes(f.name));
147
+ }
148
+ /** `schema.table("users", ...)` adding columns to an existing table. They are nullable: the table may have rows. */
149
+ function renderAlterMigration(table, fields, dialect) {
150
+ const add = fields.map((f) => ` ${(0, migration_1.renderColumn)({ ...f, nullable: true }, dialect)}`).join("\n");
151
+ return `import { defineMigration } from "@meghjs/core";
152
+
153
+ export default defineMigration({
154
+ async up(schema) {
155
+ await schema.table(${JSON.stringify(table)}, (table) => {
156
+ ${add}
157
+ });
158
+ },
159
+
160
+ async down(schema) {
161
+ await schema.table(${JSON.stringify(table)}, (table) => {
162
+ table.dropColumn(${fields.map((f) => JSON.stringify(f.name)).join(", ")});
163
+ });
164
+ },
165
+ });
166
+ `;
167
+ }
168
+ /** Add relations / methods to a generated model. Returns whether it changed. */
169
+ function patchModel(projectRoot, file, patch) {
170
+ const rel = relPath(projectRoot, file);
171
+ if (!fs_1.default.existsSync(file))
172
+ return false;
173
+ let source = fs_1.default.readFileSync(file, "utf8");
174
+ const members = patch.members.filter((m) => !m.has.test(source));
175
+ if (!members.length)
176
+ return false;
177
+ if (!/@Table\s*\(/.test(source) || !/\n}\s*$/.test(source)) {
178
+ log_1.log.warn(`${rel} is not a decorated Megh ORM model, so add these by hand:\n${members.map((m) => m.code).join("\n")}`);
179
+ return false;
180
+ }
181
+ const coreImport = /import\s*\{([^}]*)\}\s*from\s*(["'])@meghjs\/core\2;?/;
182
+ const match = source.match(coreImport);
183
+ if (patch.core?.length) {
184
+ if (match) {
185
+ const names = new Set(match[1].split(",").map((s) => s.trim()).filter(Boolean));
186
+ for (const n of patch.core)
187
+ names.add(n);
188
+ source = source.replace(coreImport, `import { ${[...names].sort().join(", ")} } from ${match[2]}@meghjs/core${match[2]};`);
189
+ }
190
+ else {
191
+ source = `import { ${patch.core.join(", ")} } from "@meghjs/core";\n` + source;
192
+ }
193
+ }
194
+ for (const line of patch.imports ?? []) {
195
+ if (source.includes(line))
196
+ continue;
197
+ const at = source.match(coreImport);
198
+ source = at ? source.replace(at[0], `${at[0]}\n${line}`) : `${line}\n${source}`;
199
+ }
200
+ const end = source.lastIndexOf("}");
201
+ source = `${source.slice(0, end).trimEnd()}\n\n${members.map((m) => m.code).join("\n\n")}\n}\n`;
202
+ fs_1.default.writeFileSync(file, source, "utf8");
203
+ log_1.log.success(`Model updated: ${rel}`);
204
+ return true;
205
+ }
206
+ const hideColumns = (columns) => ({
207
+ has: /\btoJSON\s*\(/,
208
+ code: [
209
+ ` /** Never send ${columns.join(" or ")} in responses. */`,
210
+ ` toJSON(): Record<string, unknown> {`,
211
+ ` const json = super.toJSON();`,
212
+ ...columns.map((c) => ` delete json.${c};`),
213
+ ` return json;`,
214
+ ` }`,
215
+ ].join("\n"),
216
+ });
217
+ function patchModels(projectRoot, plan) {
218
+ const files = (name) => (0, make_1.generatedFiles)(projectRoot, name).model;
219
+ const hidden = ["password", "remember_token"].filter((c) => plan.userColumns.has(c));
220
+ const userMembers = [];
221
+ const core = [];
222
+ const imports = [];
223
+ if (plan.roles === "multiple") {
224
+ core.push("BelongsToMany");
225
+ imports.push(`import { Role } from "./role.model";`);
226
+ userMembers.push({
227
+ has: /\broles\s*[!?]?\s*:/,
228
+ code: ` @BelongsToMany(() => Role, { table: "user_roles" })\n roles!: BelongsToMany<Role>;`,
229
+ });
230
+ }
231
+ else if (plan.roles === "single") {
232
+ core.push("BelongsTo");
233
+ imports.push(`import { Role } from "./role.model";`);
234
+ userMembers.push({ has: /\brole\s*[!?]?\s*:/, code: ` @BelongsTo(() => Role)\n role!: BelongsTo<Role>;` });
235
+ }
236
+ if (hidden.length)
237
+ userMembers.push(hideColumns(hidden));
238
+ patchModel(projectRoot, files("User"), { core, imports, members: userMembers });
239
+ if (plan.permissions) {
240
+ patchModel(projectRoot, files("Role"), {
241
+ core: ["BelongsToMany"],
242
+ imports: [`import { Permission } from "./permission.model";`],
243
+ members: [
244
+ {
245
+ has: /\bpermissions\s*[!?]?\s*:/,
246
+ code: ` @BelongsToMany(() => Permission, { table: "role_permissions" })\n permissions!: BelongsToMany<Permission>;`,
247
+ },
248
+ ],
249
+ });
250
+ }
251
+ if ((0, auth_files_1.usesApiKeys)(plan))
252
+ patchModel(projectRoot, files("ApiKey"), { members: [hideColumns(["key_hash"])] });
253
+ }
254
+ /** Register the handlers (and controller) in src/app.ts. */
255
+ function patchApp(projectRoot, plan) {
256
+ const file = path_1.default.join(projectRoot, "src", "app.ts");
257
+ const register = [];
258
+ if (plan.strategy) {
259
+ register.push({
260
+ name: "AppAuthentication",
261
+ from: "./auth/authentication",
262
+ line: "app.useAuthentication(AppAuthentication);",
263
+ has: /\.useAuthentication\s*\(/,
264
+ });
265
+ }
266
+ register.push({
267
+ name: "AppAuthorization",
268
+ from: "./auth/authorization",
269
+ line: "app.useAuthorization(AppAuthorization);",
270
+ has: /\.useAuthorization\s*\(/,
271
+ });
272
+ const manual = () => {
273
+ const steps = [
274
+ ...register.map((r) => `import { ${r.name} } from "${r.from}"; ${r.line}`),
275
+ ...(plan.strategy ? [`import { AuthController } from "./controllers/auth.controller"; app.useControllers([..., AuthController])`] : []),
276
+ ];
277
+ log_1.log.info(` Register them in your app:\n${steps.map((s) => ` ${s}`).join("\n")}`);
278
+ };
279
+ if (!fs_1.default.existsSync(file))
280
+ return manual();
281
+ let source = fs_1.default.readFileSync(file, "utf8");
282
+ const quote = /from\s+'/.test(source) ? "'" : '"';
283
+ const add = register.filter((r) => !r.has.test(source));
284
+ for (const r of register) {
285
+ if (r.has.test(source) && !source.includes(r.name)) {
286
+ log_1.log.warn(`src/app.ts already calls ${r.line.split("(")[0]}(...): check that it uses ${r.name}.`);
287
+ }
288
+ }
289
+ const imports = add.map((r) => `import { ${r.name} } from ${quote}${r.from}${quote};`);
290
+ const controllers = /\.useControllers\s*\(\s*\[([^\]]*)\]/;
291
+ const addController = !!plan.strategy && !/\bAuthController\b/.test(source);
292
+ if (addController)
293
+ imports.push(`import { AuthController } from ${quote}./controllers/auth.controller${quote};`);
294
+ if (!imports.length)
295
+ return;
296
+ const last = [...source.matchAll(/^import .*;[ \t]*$/gm)].pop();
297
+ if (last) {
298
+ const end = last.index + last[0].length;
299
+ source = `${source.slice(0, end)}\n${imports.join("\n")}${source.slice(end)}`;
300
+ }
301
+ else {
302
+ source = `${imports.join("\n")}\n${source}`;
303
+ }
304
+ if (add.length) {
305
+ const lines = add.map((r) => r.line).join("\n");
306
+ const at = source.search(/^.*\.useControllers\s*\(/m);
307
+ const exportAt = source.search(/^export default/m);
308
+ const index = at !== -1 ? at : exportAt !== -1 ? exportAt : source.length;
309
+ source = `${source.slice(0, index)}${lines}\n\n${source.slice(index)}`;
310
+ }
311
+ let registered = !addController;
312
+ if (addController) {
313
+ const m = source.match(controllers);
314
+ if (m) {
315
+ const list = m[1].trim();
316
+ source = source.replace(controllers, (whole) => whole.replace(`[${m[1]}]`, `[${list ? `${list.replace(/,\s*$/, "")}, ` : ""}AuthController]`));
317
+ registered = true;
318
+ }
319
+ }
320
+ fs_1.default.writeFileSync(file, source, "utf8");
321
+ log_1.log.success("Updated: src/app.ts");
322
+ if (!registered)
323
+ log_1.log.info(" Add AuthController to your app's controllers: app.useControllers([..., AuthController])");
324
+ }
325
+ /** JWT_SECRET and JWT_EXPIRES_IN in .env (and .env.example, without the secret). */
326
+ function patchEnv(projectRoot) {
327
+ const append = (name, values, create) => {
328
+ const file = path_1.default.join(projectRoot, name);
329
+ if (!fs_1.default.existsSync(file) && !create)
330
+ return;
331
+ const source = fs_1.default.existsSync(file) ? fs_1.default.readFileSync(file, "utf8") : "";
332
+ const missing = Object.entries(values).filter(([k]) => !new RegExp(`^\\s*${k}\\s*=`, "m").test(source));
333
+ if (!missing.length)
334
+ return;
335
+ const block = [
336
+ "# Auth (megh scaffold:auth): signing key for access tokens and their lifetime.",
337
+ ...missing.map(([k, v]) => `${k}=${v}`),
338
+ ].join("\n");
339
+ const head = source.trimEnd();
340
+ fs_1.default.writeFileSync(file, `${head ? `${head}\n\n` : ""}${block}\n`, "utf8");
341
+ log_1.log.success(`Updated: ${name} (${missing.map(([k]) => k).join(", ")})`);
342
+ };
343
+ append(".env", { JWT_SECRET: crypto_1.default.randomBytes(48).toString("hex"), JWT_EXPIRES_IN: "1d" }, true);
344
+ append(".env.example", { JWT_SECRET: "", JWT_EXPIRES_IN: "1d" }, false);
345
+ }
346
+ /**
347
+ * Make `db:seed` run the roles seeder: when the entry seeder
348
+ * (database.seeder.ts) exists, it runs instead of every seeder, so "roles"
349
+ * is added to its calls.
350
+ */
351
+ function patchEntrySeeder(projectRoot, seedersDir) {
352
+ const file = path_1.default.join(seedersDir, "database.seeder.ts");
353
+ const rel = relPath(projectRoot, file);
354
+ if (!fs_1.default.existsSync(file))
355
+ return;
356
+ const source = fs_1.default.readFileSync(file, "utf8");
357
+ // Code lines only: the stub's comment shows `await call("roles", "users")`.
358
+ const lines = source.split("\n");
359
+ const isCode = (line) => !/^\s*(\/\/|\*|\/\*)/.test(line);
360
+ if (lines.some((l) => isCode(l) && /call\([^)]*["']roles["']/.test(l)))
361
+ return;
362
+ // An empty run() (comments only), as make:seeder database writes it.
363
+ const empty = /async\s+run\s*\(\s*\)\s*\{(?:\s*\/\/[^\n]*)*\s*\}/;
364
+ const callLine = lines.findIndex((l) => isCode(l) && /await\s+call\(/.test(l));
365
+ let next;
366
+ if (empty.test(source))
367
+ next = source.replace(empty, `async run({ call }) {\n await call("roles");\n }`);
368
+ else if (callLine !== -1) {
369
+ lines[callLine] = lines[callLine].replace(/await\s+call\(/, `await call("roles", `);
370
+ next = lines.join("\n");
371
+ }
372
+ if (!next) {
373
+ log_1.log.info(` Run the roles seeder from ${rel}: await call("roles");`);
374
+ return;
375
+ }
376
+ fs_1.default.writeFileSync(file, next, "utf8");
377
+ log_1.log.success(`Updated: ${rel} (calls "roles")`);
378
+ }
379
+ /** `auth: "bearer"` in src/config/openapi.config.ts, for Swagger UI's Authorize button. */
380
+ function patchOpenApi(projectRoot, plan) {
381
+ const file = path_1.default.join(projectRoot, "src", "config", "openapi.config.ts");
382
+ if (!fs_1.default.existsSync(file))
383
+ return;
384
+ const source = fs_1.default.readFileSync(file, "utf8");
385
+ if (/\bauth\s*:/.test(source))
386
+ return;
387
+ const scheme = (0, auth_files_1.usesJwt)(plan) ? "bearer" : "apiKey";
388
+ const quote = /'/.test(source) ? "'" : '"';
389
+ const next = source.replace(/^(\s*)routePrefix\s*:.*$/m, (line, indent) => `${line}\n${indent}auth: ${quote}${scheme}${quote},`);
390
+ if (next === source)
391
+ return;
392
+ fs_1.default.writeFileSync(file, next, "utf8");
393
+ log_1.log.success(`Updated: src/config/openapi.config.ts (auth: "${scheme}")`);
394
+ }
395
+ async function generate(projectRoot, choice, opts) {
396
+ const { migrations: migrationsDir, seeders } = (0, migrate_1.databasePaths)(projectRoot);
397
+ const at = (rel) => path_1.default.join(projectRoot, ...rel.split("/"));
398
+ const seederRel = relPath(projectRoot, path_1.default.join(seeders, "roles.seeder.ts"));
399
+ const files = {};
400
+ if (choice.strategy) {
401
+ files["src/auth/password.ts"] = auth_files_1.renderPassword;
402
+ if ((0, auth_files_1.usesJwt)(choice))
403
+ files["src/auth/jwt.ts"] = auth_files_1.renderJwt;
404
+ if ((0, auth_files_1.usesApiKeys)(choice))
405
+ files["src/auth/api-keys.ts"] = auth_files_1.renderApiKeys;
406
+ files["src/auth/authentication.ts"] = (p) => (0, auth_files_1.renderAuthentication)(p, paths);
407
+ files["src/dtos/auth.dto.ts"] = auth_files_1.renderAuthDto;
408
+ files["src/services/auth.service.ts"] = (p) => (0, auth_files_1.renderAuthService)(p, paths);
409
+ files["src/controllers/auth.controller.ts"] = (p) => (0, auth_files_1.renderAuthController)(p, paths);
410
+ }
411
+ files["src/auth/authorization.ts"] = (p) => (0, auth_files_1.renderAuthorization)(p, paths);
412
+ if ((0, auth_files_1.usesRoles)(choice)) {
413
+ files["src/auth/rbac.ts"] = (p) => (0, auth_files_1.renderRbac)(p, paths);
414
+ files[seederRel] = (p) => (0, auth_files_1.renderRolesSeeder)(p, paths, seederRel);
415
+ }
416
+ // Tables: create the missing ones, add missing columns to an existing users table.
417
+ const { users, others } = tableTemplates(projectRoot, choice);
418
+ const before = (0, migration_schema_1.readMigrationSchema)(migrationsDir);
419
+ const existingUsers = before.get("users");
420
+ const addColumns = existingUsers
421
+ ? requiredUserColumns(choice, users).filter((f) => !existingUsers.columns.some((c) => c.name === f.name))
422
+ : [];
423
+ // Check before writing anything. A file that already has exactly the
424
+ // content it would get (e.g. rbac.ts from an earlier scaffold:rbac) is kept.
425
+ const expectedColumns = new Set([
426
+ ...(existingUsers ? existingUsers.columns.map((c) => c.name) : ["id", ...users.fields.map((f) => f.name)]),
427
+ ...addColumns.map((f) => f.name),
428
+ ]);
429
+ const expected = { ...choice, userColumns: expectedColumns };
430
+ const same = (rel) => fs_1.default.existsSync(at(rel)) && fs_1.default.readFileSync(at(rel), "utf8") === files[rel](expected);
431
+ if (!opts.force) {
432
+ const taken = Object.keys(files).filter((f) => fs_1.default.existsSync(at(f)) && !same(f));
433
+ if (taken.length) {
434
+ throw new errors_1.CliError(`Already exists: ${taken.join(", ")}. Use -f or --force to overwrite ` +
435
+ "(e.g. to switch between single and multiple roles).");
436
+ }
437
+ }
438
+ const targets = [
439
+ ...(existingUsers ? [] : [{ template: users, model: "User", table: "users", requested: true }]),
440
+ ...others.map((t) => ({ template: t, model: modelName(t.name), table: t.table, requested: true })),
441
+ ];
442
+ await (0, scaffold_1.scaffold)(projectRoot, targets, { cwd: projectRoot, mode: "model", reuseExisting: true, now: opts.now });
443
+ if (addColumns.length) {
444
+ const stamp = (0, make_1.migrationTimestamp)((0, scaffold_1.firstFreeTimestamp)(migrationsDir, opts.now ?? new Date()));
445
+ const file = path_1.default.join(migrationsDir, `${stamp}_add_auth_columns_to_users_table.ts`);
446
+ const dialect = (0, dialect_1.projectDialect)(projectRoot);
447
+ let columns = addColumns;
448
+ if (dialect === "mssql") {
449
+ const limited = (0, cascade_1.limitCascadePaths)((0, cascade_1.cascadeEdges)((0, migration_schema_1.readMigrationSchema)(migrationsDir)), [
450
+ { table: "users", fields: addColumns },
451
+ ]);
452
+ columns = limited.fields.get("users");
453
+ for (const d of limited.dropped) {
454
+ log_1.log.info(` SQL Server: ${d.table}.${d.column} gets no ON DELETE action (${d.reason}).`);
455
+ }
456
+ }
457
+ (0, project_1.writeFileSafe)(file, renderAlterMigration("users", columns, dialect));
458
+ log_1.log.success(`Migration created: ${relPath(projectRoot, file)} (${addColumns.map((f) => f.name).join(", ")})`);
459
+ if (fs_1.default.existsSync((0, make_1.generatedFiles)(projectRoot, "User").model))
460
+ (0, make_1.updateModel)("User", { cwd: projectRoot });
461
+ else
462
+ (0, make_1.makeModel)("User", { cwd: projectRoot });
463
+ }
464
+ else if (existingUsers && !fs_1.default.existsSync((0, make_1.generatedFiles)(projectRoot, "User").model)) {
465
+ (0, make_1.makeModel)("User", { cwd: projectRoot });
466
+ }
467
+ const usersTable = (0, migration_schema_1.readMigrationSchema)(migrationsDir).get("users");
468
+ const plan = { ...choice, userColumns: new Set(usersTable?.columns.map((c) => c.name) ?? []) };
469
+ patchModels(projectRoot, plan);
470
+ for (const [rel, render] of Object.entries(files)) {
471
+ const content = render(plan);
472
+ if (fs_1.default.existsSync(at(rel)) && fs_1.default.readFileSync(at(rel), "utf8") === content) {
473
+ log_1.log.info(` Up to date: ${rel}`);
474
+ continue;
475
+ }
476
+ (0, project_1.writeFileSafe)(at(rel), content, opts.force);
477
+ log_1.log.success(`Created: ${rel}`);
478
+ }
479
+ patchApp(projectRoot, plan);
480
+ if ((0, auth_files_1.usesRoles)(plan))
481
+ patchEntrySeeder(projectRoot, seeders);
482
+ if ((0, auth_files_1.usesJwt)(plan))
483
+ patchEnv(projectRoot);
484
+ if (plan.strategy)
485
+ patchOpenApi(projectRoot, plan);
486
+ return plan;
487
+ }
488
+ const modelName = (snake) => snake.replace(/(^|_)(\w)/g, (_, __, c) => c.toUpperCase());
489
+ function warnPackages(projectRoot, plan) {
490
+ const missing = [];
491
+ const missingDev = [];
492
+ if ((0, auth_files_1.usesJwt)(plan) && !(0, project_1.installedVersion)("jsonwebtoken", projectRoot))
493
+ missing.push("jsonwebtoken");
494
+ if ((0, auth_files_1.usesJwt)(plan) && !(0, project_1.installedVersion)("@types/jsonwebtoken", projectRoot))
495
+ missingDev.push("@types/jsonwebtoken");
496
+ if (plan.strategy) {
497
+ for (const pkg of ["class-validator", "class-transformer"])
498
+ if (!(0, project_1.installedVersion)(pkg, projectRoot))
499
+ missing.push(pkg);
500
+ }
501
+ if (missing.length)
502
+ log_1.log.warn(`Install: npm install ${missing.join(" ")}`);
503
+ if (missingDev.length)
504
+ log_1.log.warn(`Install: npm install -D ${missingDev.join(" ")}`);
505
+ }
506
+ /**
507
+ * `scaffold:auth`: sign-up and sign-in with JWTs, API keys or both, and
508
+ * optionally roles (one or many per user) with permissions.
509
+ */
510
+ async function scaffoldAuth(opts = {}) {
511
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
512
+ const choice = await ask(opts, true, "none");
513
+ const plan = await generate(projectRoot, choice, opts);
514
+ warnPackages(projectRoot, plan);
515
+ log_1.log.info([
516
+ "",
517
+ " Routes:",
518
+ " POST /auth/register { name, email, password }",
519
+ ` POST /auth/login { email, password } → ${(0, auth_files_1.usesJwt)(plan) ? "{ access_token, ... }" : "{ api_key, ... }"}`,
520
+ " GET /auth/me",
521
+ ...((0, auth_files_1.usesApiKeys)(plan) ? [" GET|POST /auth/api-keys, DELETE /auth/api-keys/:id"] : []),
522
+ ` Protect a route with @Authorized()${(0, auth_files_1.usesRoles)(plan) ? ', or @Authorized({ roles: ["admin"] })' : ""}${plan.permissions ? ' / { permissions: ["users.manage"] }' : ""}.`,
523
+ ` Next: megh migrate${(0, auth_files_1.usesRoles)(plan) ? " --seed (creates the admin and user roles)" : ""}`,
524
+ ].join("\n"));
525
+ return plan;
526
+ }
527
+ /** `scaffold:rbac`: roles (and permissions) for an app's users, without sign-in. */
528
+ async function scaffoldRbac(opts = {}) {
529
+ const projectRoot = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
530
+ const choice = await ask(opts, false, "multiple");
531
+ if (choice.roles === "none")
532
+ throw new errors_1.CliError('scaffold:rbac needs --roles single or multiple.');
533
+ const plan = await generate(projectRoot, choice, opts);
534
+ log_1.log.info([
535
+ "",
536
+ ' Check roles with @Authorized({ roles: ["admin"] })' + (plan.permissions ? ' or { permissions: ["users.manage"] }' : "") + ",",
537
+ " or in code: hasRole(user, [\"admin\"]) from src/auth/rbac.ts. AppAuthorization reads request.user,",
538
+ " so register an authentication handler that sets it (megh scaffold:auth generates one).",
539
+ " Next: megh migrate --seed (creates the admin and user roles)",
540
+ ].join("\n"));
541
+ return plan;
542
+ }
@@ -20,6 +20,14 @@ export type MakeServiceOptions = MakeBaseOptions & {
20
20
  export type MakeControllerOptions = MakeServiceOptions & {
21
21
  basePath?: boolean;
22
22
  };
23
+ /** Files `make:model` / `make:resource` / `make:factory` write for model `name`. */
24
+ export declare function generatedFiles(projectRoot: string, name: string): {
25
+ model: string;
26
+ dto: string;
27
+ service: string;
28
+ controller: string;
29
+ factory: string;
30
+ };
23
31
  /**
24
32
  * Create a Megh ORM model (or, with `orm`, a TypeORM entity). The model's
25
33
  * columns come from the migration that creates its table, if there is one;
@@ -3,6 +3,7 @@ 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.generatedFiles = generatedFiles;
6
7
  exports.makeModel = makeModel;
7
8
  exports.updateModel = updateModel;
8
9
  exports.makeService = makeService;
@@ -43,6 +44,17 @@ function targetDir(projectRoot, kind, dirs, root) {
43
44
  throw new errors_1.CliError(`Invalid --root "${root}".`);
44
45
  return path_1.default.join(projectRoot, "src", ...folder, ...dirs);
45
46
  }
47
+ /** Files `make:model` / `make:resource` / `make:factory` write for model `name`. */
48
+ function generatedFiles(projectRoot, name) {
49
+ const n = (0, names_1.resolveName)(name, "Model");
50
+ return {
51
+ model: path_1.default.join(targetDir(projectRoot, "model", n.dirs), `${n.fileBase}.model.ts`),
52
+ dto: path_1.default.join(targetDir(projectRoot, "dto", n.dirs), `${n.fileBase}.dto.ts`),
53
+ service: path_1.default.join(targetDir(projectRoot, "service", n.dirs), `${n.fileBase}.service.ts`),
54
+ controller: path_1.default.join(targetDir(projectRoot, "controller", n.dirs), `${n.fileBase}.controller.ts`),
55
+ factory: path_1.default.join((0, migrate_1.databasePaths)(projectRoot).factories, ...n.dirs, `${n.fileBase}.factory.ts`),
56
+ };
57
+ }
46
58
  /** A relative module specifier from `fromFile` to `toFile` (without extension), always using `/`. */
47
59
  function importPath(fromFile, toFile) {
48
60
  let rel = path_1.default.relative(path_1.default.dirname(fromFile), toFile).replace(/\.ts$/, "").split(path_1.default.sep).join("/");
@@ -18,6 +18,11 @@ export interface MigrationColumn {
18
18
  generated: boolean;
19
19
  /** Auto-increment / identity / serial (as opposed to a default value). */
20
20
  autoIncrement: boolean;
21
+ /** The foreign key, when the migration declares one on the column. */
22
+ references?: {
23
+ table: string;
24
+ onDelete?: string;
25
+ };
21
26
  }
22
27
  export interface MigrationTable {
23
28
  name: string;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.readMigrationSchema = readMigrationSchema;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
+ const orm_model_1 = require("./orm-model");
9
10
  const EXTENSIONS = /\.(c?js|mjs|c?ts|mts)$/;
10
11
  const DECLARATION = /\.d\.[cm]?ts$/;
11
12
  /** Every table the migrations in `folder` leave behind, keyed by name. */
@@ -240,8 +241,23 @@ function parseColumn(name, typeArg, build) {
240
241
  primaryKey,
241
242
  autoIncrement,
242
243
  generated: autoIncrement || /\.(defaultTo|generatedAlwaysAs)\s*\(/.test(build),
244
+ ...foreignKey(name, build),
243
245
  };
244
246
  }
247
+ /** `.constrained("t")` / `.references("t.id")` and the ON DELETE action in a column's chain. */
248
+ function foreignKey(column, chain) {
249
+ const constrained = chain.match(/\.constrained\s*\(\s*(?:["'`]([^"'`]+)["'`])?/);
250
+ const references = chain.match(/\.references\s*\(\s*["'`]([^"'`.]+)/);
251
+ const table = constrained ? (constrained[1] ?? (0, orm_model_1.pluralize)(column.replace(/_id$/, ""))) : references?.[1];
252
+ if (!table)
253
+ return {};
254
+ const onDelete = /\.cascadeOnDelete\s*\(/.test(chain)
255
+ ? "cascade"
256
+ : /\.nullOnDelete\s*\(/.test(chain)
257
+ ? "set null"
258
+ : chain.match(/\.onDelete\s*\(\s*["'`]([^"'`]+)/)?.[1].toLowerCase();
259
+ return { references: onDelete ? { table, onDelete } : { table } };
260
+ }
245
261
  // ── Megh's schema builder (defineMigration) ──────────────────────────────
246
262
  const SCHEMA_STATEMENT = /\b\w+\s*\.\s*(create|table|drop|dropIfExists|rename)\s*\(/g;
247
263
  /** SQL types the builder's column methods create, as `fieldType` reads them. */
@@ -400,5 +416,6 @@ function applyBlueprintCall(table, method, args, chain) {
400
416
  primaryKey,
401
417
  autoIncrement,
402
418
  generated: autoIncrement || /\.(default|useCurrent)\s*\(/.test(chain),
419
+ ...foreignKey(columnName, chain),
403
420
  });
404
421
  }