@meghjs/cli 0.0.0-stage → 0.5.1

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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +10 -0
  4. package/dist/commands/build.d.ts +11 -0
  5. package/dist/commands/build.js +65 -0
  6. package/dist/commands/doctor.d.ts +10 -0
  7. package/dist/commands/doctor.js +96 -0
  8. package/dist/commands/migrate.d.ts +41 -0
  9. package/dist/commands/migrate.js +193 -0
  10. package/dist/commands/new.d.ts +24 -0
  11. package/dist/commands/new.js +377 -0
  12. package/dist/commands/route-list.d.ts +19 -0
  13. package/dist/commands/route-list.js +160 -0
  14. package/dist/commands/serve.d.ts +17 -0
  15. package/dist/commands/serve.js +238 -0
  16. package/dist/commands/start.d.ts +10 -0
  17. package/dist/commands/start.js +43 -0
  18. package/dist/compiler.d.ts +24 -0
  19. package/dist/compiler.js +83 -0
  20. package/dist/errors.d.ts +8 -0
  21. package/dist/errors.js +16 -0
  22. package/dist/generators/make.d.ts +60 -0
  23. package/dist/generators/make.js +325 -0
  24. package/dist/generators/migration-schema.d.ts +29 -0
  25. package/dist/generators/migration-schema.js +398 -0
  26. package/dist/generators/orm-model.d.ts +23 -0
  27. package/dist/generators/orm-model.js +158 -0
  28. package/dist/generators/resource.d.ts +32 -0
  29. package/dist/generators/resource.js +277 -0
  30. package/dist/index.d.ts +17 -0
  31. package/dist/index.js +42 -0
  32. package/dist/program.d.ts +22 -0
  33. package/dist/program.js +224 -0
  34. package/dist/utils/entry.d.ts +15 -0
  35. package/dist/utils/entry.js +55 -0
  36. package/dist/utils/env-types.d.ts +8 -0
  37. package/dist/utils/env-types.js +19 -0
  38. package/dist/utils/log.d.ts +25 -0
  39. package/dist/utils/log.js +39 -0
  40. package/dist/utils/names.d.ts +27 -0
  41. package/dist/utils/names.js +58 -0
  42. package/dist/utils/process.d.ts +18 -0
  43. package/dist/utils/process.js +84 -0
  44. package/dist/utils/project.d.ts +17 -0
  45. package/dist/utils/project.js +91 -0
  46. package/dist/utils/stubs.d.ts +15 -0
  47. package/dist/utils/stubs.js +52 -0
  48. package/dist/utils/tsconfig.d.ts +13 -0
  49. package/dist/utils/tsconfig.js +102 -0
  50. package/package.json +61 -4
  51. package/readme.md +155 -0
  52. package/stubs/config/config.stub +9 -0
  53. package/stubs/controllers/basic-controller.stub +9 -0
  54. package/stubs/controllers/model-controller.stub +34 -0
  55. package/stubs/controllers/resource-controller.stub +45 -0
  56. package/stubs/controllers/rest-controller.stub +29 -0
  57. package/stubs/dtos/dto.stub +11 -0
  58. package/stubs/dtos/resource-dto.stub +28 -0
  59. package/stubs/middlewares/middleware.stub +9 -0
  60. package/stubs/migrations/alter-table.stub +15 -0
  61. package/stubs/migrations/create-table.stub +15 -0
  62. package/stubs/migrations/migration.stub +11 -0
  63. package/stubs/models/entity-model.stub +16 -0
  64. package/stubs/models/orm-model-blank.stub +10 -0
  65. package/stubs/models/orm-model.stub +7 -0
  66. package/stubs/project/app-minimal.stub +7 -0
  67. package/stubs/project/app.stub +8 -0
  68. package/stubs/project/env.stub +3 -0
  69. package/stubs/project/gitignore.stub +5 -0
  70. package/stubs/project/home.controller.spec.stub +19 -0
  71. package/stubs/project/home.controller.stub +12 -0
  72. package/stubs/project/home.service.stub +8 -0
  73. package/stubs/project/openapi.config.stub +15 -0
  74. package/stubs/project/readme.stub +26 -0
  75. package/stubs/project/serve.stub +10 -0
  76. package/stubs/project/tsconfig.build.stub +4 -0
  77. package/stubs/project/tsconfig.stub +18 -0
  78. package/stubs/project/vitest-e2e.config.stub +10 -0
  79. package/stubs/project/vitest.config.stub +17 -0
  80. package/stubs/services/basic-service.stub +8 -0
  81. package/stubs/services/model-service.stub +42 -0
  82. package/stubs/services/orm-rest-service.stub +61 -0
  83. package/README.md +0 -3
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readModelSchema = readModelSchema;
4
+ exports.renderResourceDto = renderResourceDto;
5
+ const orm_model_1 = require("./orm-model");
6
+ const stubs_1 = require("../utils/stubs");
7
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
8
+ /** The string value of `static readonly <name> = "..."`. */
9
+ function staticString(source, name) {
10
+ return source.match(new RegExp(`static\\s+(?:readonly\\s+)?${name}\\s*=\\s*["'\`]([^"'\`]+)["'\`]`))?.[1];
11
+ }
12
+ function staticTrue(source, name) {
13
+ return new RegExp(`static\\s+(?:readonly\\s+)?${name}\\s*=\\s*true\\b`).test(source);
14
+ }
15
+ /** `static generated = [...]` as a list, or `undefined` when not declared. */
16
+ function staticList(source, name) {
17
+ const m = source.match(new RegExp(`static\\s+(?:readonly\\s+)?${name}\\s*=\\s*\\[([^\\]]*)\\]`));
18
+ if (!m)
19
+ return undefined;
20
+ return (m[1].match(/["'`][^"'`]+["'`]/g) ?? []).map((s) => s.slice(1, -1));
21
+ }
22
+ /** Split leading decorators off a line: `@PrimaryKey() @AutoIncrement() id?: number;`. */
23
+ function leadingDecorators(line) {
24
+ const decorators = [];
25
+ let rest = line;
26
+ for (;;) {
27
+ const head = rest.match(/^@(\w+)\s*/);
28
+ if (!head)
29
+ break;
30
+ let end = head[0].length;
31
+ if (rest[end] === "(") {
32
+ // Up to the matching ")", or the end of the line for a decorator that
33
+ // continues on the next lines.
34
+ end = rest.length;
35
+ let depth = 0;
36
+ for (let i = head[0].length; i < rest.length; i++) {
37
+ const ch = rest[i];
38
+ if (ch === '"' || ch === "'" || ch === "`") {
39
+ const close = rest.indexOf(ch, i + 1);
40
+ i = close === -1 ? rest.length : close;
41
+ }
42
+ else if (ch === "(" || ch === "{" || ch === "[")
43
+ depth++;
44
+ else if (ch === ")" || ch === "}" || ch === "]") {
45
+ depth--;
46
+ if (depth === 0) {
47
+ end = i + 1;
48
+ break;
49
+ }
50
+ }
51
+ }
52
+ }
53
+ decorators.push(head[1] + rest.slice(head[0].length, end));
54
+ rest = rest.slice(end).trim();
55
+ }
56
+ return { decorators, rest };
57
+ }
58
+ /**
59
+ * Property declarations of the model class (`name!: string;`), with the
60
+ * decorators above each one. Initialised properties (relations such as
61
+ * `posts = hasMany(...)`), statics and methods are skipped.
62
+ */
63
+ function declaredProperties(source) {
64
+ const out = [];
65
+ let decorators = [];
66
+ // Bracket depth at the start of each line: properties sit directly in the
67
+ // class body (depth 1), not inside object literals or decorator arguments.
68
+ let depth = 0;
69
+ for (const raw of source.split(/\r?\n/)) {
70
+ const line = withoutLineComment(raw).trim();
71
+ const atDepth = depth;
72
+ depth += bracketDelta(line);
73
+ if (atDepth !== 1) {
74
+ // The rest of a multi-line decorator, e.g. `@Column({ nullable: true })`.
75
+ if (decorators.length > 0)
76
+ decorators[decorators.length - 1] += " " + line;
77
+ continue;
78
+ }
79
+ const split = leadingDecorators(line);
80
+ decorators.push(...split.decorators);
81
+ // A decorator on its own line, possibly continued on the next lines.
82
+ if (split.decorators.length > 0 && !split.rest)
83
+ continue;
84
+ const prop = split.rest.match(/^(?:(?:public|declare|readonly)\s+)*(\w+|"[^"]+"|'[^']+')\s*([!?])?\s*:\s*([^=;]+?)\s*;?$/);
85
+ if (prop && !/^(static|private|protected|get|set|async)\b/.test(split.rest)) {
86
+ const name = prop[1].replace(/^["']|["']$/g, "");
87
+ const parts = prop[3].split("|").map((p) => p.trim());
88
+ const nullInType = parts.includes("null") || parts.includes("undefined");
89
+ const optional = prop[2] === "?";
90
+ const ts = parts.filter((p) => p !== "null" && p !== "undefined").join(" | ") || "unknown";
91
+ out.push({ name, ts, nullable: optional || nullInType, optional, nullInType, decorators });
92
+ }
93
+ if (line && !line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
94
+ decorators = [];
95
+ }
96
+ return out;
97
+ }
98
+ /** A line without its trailing `//` comment (a `//` inside a string is kept). */
99
+ function withoutLineComment(line) {
100
+ for (let i = 0; i < line.length; i++) {
101
+ const ch = line[i];
102
+ if (ch === '"' || ch === "'" || ch === "`") {
103
+ const end = line.indexOf(ch, i + 1);
104
+ if (end === -1)
105
+ return line;
106
+ i = end;
107
+ }
108
+ else if (ch === "/" && line[i + 1] === "/")
109
+ return line.slice(0, i);
110
+ }
111
+ return line;
112
+ }
113
+ /** Opening minus closing brackets on a line (already without its comment), ignoring strings. */
114
+ function bracketDelta(line) {
115
+ let delta = 0;
116
+ for (let i = 0; i < line.length; i++) {
117
+ const ch = line[i];
118
+ if (ch === '"' || ch === "'" || ch === "`") {
119
+ const end = line.indexOf(ch, i + 1);
120
+ if (end === -1)
121
+ break;
122
+ i = end;
123
+ }
124
+ else if (ch === "{" || ch === "(" || ch === "[")
125
+ delta++;
126
+ else if (ch === "}" || ch === ")" || ch === "]")
127
+ delta--;
128
+ }
129
+ return delta;
130
+ }
131
+ /** Read a model (Megh ORM or TypeORM) for resource generation. */
132
+ function readModelSchema(source, table) {
133
+ const byName = new Map((table?.columns ?? []).map((c) => [c.name, c]));
134
+ const withSql = (f) => {
135
+ const column = byName.get(f.name);
136
+ return column?.type ? { ...f, sqlType: column.type } : f;
137
+ };
138
+ if (/@Entity\s*\(/.test(source)) {
139
+ const props = declaredProperties(source);
140
+ const skip = /^(PrimaryGeneratedColumn|CreateDateColumn|UpdateDateColumn|DeleteDateColumn|VersionColumn|OneToMany|ManyToOne|OneToOne|ManyToMany|JoinColumn|JoinTable|RelationId)\b/;
141
+ const pk = props.find((p) => p.decorators.some((d) => /^Primary(Generated)?Column\b/.test(d)));
142
+ const columns = props.filter((p) => p.decorators.some((d) => /^(Primary)?Column\b/.test(d)));
143
+ return {
144
+ kind: "typeorm",
145
+ table: source.match(/@Entity\s*\(\s*(?:\{[^}]*name\s*:\s*)?["'`]([^"'`]+)/)?.[1],
146
+ primaryKey: pk?.name ?? "id",
147
+ primaryKeyType: pk?.ts ?? "number",
148
+ inputFields: columns
149
+ .filter((p) => !p.decorators.some((d) => skip.test(d)))
150
+ .map((p) => withSql({
151
+ name: p.name,
152
+ ts: p.ts,
153
+ nullable: p.nullable || p.decorators.some((d) => /nullable\s*:\s*true/.test(d)),
154
+ generated: p.decorators.some((d) => /default\s*:/.test(d)),
155
+ })),
156
+ };
157
+ }
158
+ if (/@Table\s*\(/.test(source))
159
+ return readDecoratedModel(source, withSql);
160
+ const primaryKey = staticString(source, "primaryKey") ?? "id";
161
+ const generated = new Set(staticList(source, "generated") ?? ["id"]);
162
+ const implicit = new Set();
163
+ if (staticTrue(source, "timestamps")) {
164
+ implicit.add(staticString(source, "createdAt") ?? "created_at");
165
+ implicit.add(staticString(source, "updatedAt") ?? "updated_at");
166
+ }
167
+ if (staticTrue(source, "softDeletes"))
168
+ implicit.add(staticString(source, "deletedAt") ?? "deleted_at");
169
+ const props = declaredProperties(source);
170
+ const pk = props.find((p) => p.name === primaryKey);
171
+ return {
172
+ kind: "megh",
173
+ table: staticString(source, "table"),
174
+ primaryKey,
175
+ primaryKeyType: pk?.ts ?? "number",
176
+ inputFields: props
177
+ // An auto-generated key and the timestamps are never sent by clients.
178
+ .filter((p) => !implicit.has(p.name) && !(p.name === primaryKey && generated.has(p.name)))
179
+ .map((p) => withSql({ name: p.name, ts: p.ts, nullable: p.nullable, generated: generated.has(p.name) })),
180
+ };
181
+ }
182
+ /**
183
+ * A model described with decorators. Only decorated columns count; fields
184
+ * declared with `?` (auto-increment, defaults) are filled in by the database.
185
+ */
186
+ function readDecoratedModel(source, withSql) {
187
+ const has = (p, name) => p.decorators.some((d) => name.test(d));
188
+ const columns = declaredProperties(source).filter((p) => has(p, /^(Column|PrimaryKey|AutoIncrement|Identity|CreatedAt|UpdatedAt|DeletedAt)\b/));
189
+ const pk = columns.find((p) => has(p, /^PrimaryKey\b/));
190
+ const primaryKey = pk?.name ?? "id";
191
+ const generated = (p) => p.optional || has(p, /^(AutoIncrement|Identity)\b/);
192
+ return {
193
+ kind: "megh",
194
+ table: source.match(/@Table\s*\(\s*["'`]([^"'`]+)["'`]/)?.[1],
195
+ primaryKey,
196
+ primaryKeyType: pk?.ts ?? "number",
197
+ inputFields: columns
198
+ // The timestamps and an auto-generated key are never sent by clients.
199
+ .filter((p) => !has(p, /^(CreatedAt|UpdatedAt|DeletedAt)\b/))
200
+ .filter((p) => !(p.name === primaryKey && generated(p)))
201
+ .map((p) => withSql({ name: p.name, ts: p.ts, nullable: p.nullInType, generated: generated(p) })),
202
+ };
203
+ }
204
+ const INTEGER = /^(int\d?|integer|smallint|mediumint|tinyint|bigint|serial\d?|smallserial|bigserial)$/;
205
+ /** class-validator decorators (and the type to declare) for one DTO field. */
206
+ function validators(field) {
207
+ const sql = field.sqlType ?? "";
208
+ const base = sql.replace(/\(.*$/, "").trim();
209
+ const ts = field.sqlType && field.ts === "unknown" ? (0, orm_model_1.fieldType)(sql).ts : field.ts;
210
+ const d = [];
211
+ switch (ts) {
212
+ case "string": {
213
+ if (/(^|_)email$/i.test(field.name))
214
+ d.push("IsEmail()");
215
+ else if (base === "uuid")
216
+ d.push("IsUUID()");
217
+ else
218
+ d.push("IsString()");
219
+ const length = sql.match(/^(?:n?varchar|n?char|character varying|character)\s*\((\d+)\)/)?.[1];
220
+ if (length)
221
+ d.push(`MaxLength(${length})`);
222
+ break;
223
+ }
224
+ case "number":
225
+ d.push(INTEGER.test(base) ? "IsInt()" : "IsNumber()");
226
+ break;
227
+ case "boolean":
228
+ d.push("IsBoolean()");
229
+ break;
230
+ case "Date":
231
+ d.push("Type(() => Date)", "IsDate()");
232
+ break;
233
+ default:
234
+ if (/^Record<|^\{/.test(ts))
235
+ d.push("IsObject()");
236
+ // Anything else (Buffer, unknown, unions) is accepted as sent.
237
+ else
238
+ d.push("Allow()");
239
+ }
240
+ return { decorators: d, ts };
241
+ }
242
+ const key = (name) => (IDENTIFIER.test(name) ? name : JSON.stringify(name));
243
+ function renderFields(fields, allOptional) {
244
+ return fields
245
+ .map((f) => {
246
+ const { decorators, ts } = validators(f);
247
+ const optional = allOptional || f.nullable || f.generated;
248
+ const lines = [...(optional ? ["@IsOptional()"] : []), ...decorators.map((x) => `@${x}`)];
249
+ const type = f.nullable ? `${ts} | null` : ts;
250
+ lines.push(`${key(f.name)}${optional ? "?" : "!"}: ${type};`);
251
+ return lines.map((l) => ` ${l}`).join("\n");
252
+ })
253
+ .join("\n\n");
254
+ }
255
+ /** `src/dtos/<model>.dto.ts`: create, update and list-query DTOs. */
256
+ function renderResourceDto(model, plural, route, schema) {
257
+ const create = renderFields(schema.inputFields, false);
258
+ const update = renderFields(schema.inputFields, true);
259
+ // The list query always uses these.
260
+ const used = new Set(["IsInt", "IsOptional", "Max", "Min"]);
261
+ for (const f of schema.inputFields) {
262
+ for (const d of validators(f).decorators) {
263
+ const name = d.match(/^\w+/)[0];
264
+ if (name !== "Type")
265
+ used.add(name);
266
+ }
267
+ }
268
+ const empty = " // No writable columns were found on the model.";
269
+ return (0, stubs_1.renderStub)("dtos/resource-dto.stub", {
270
+ validators: [...used].sort().join(", "),
271
+ Model: model,
272
+ Plural: plural,
273
+ route,
274
+ createFields: create || empty,
275
+ updateFields: update || empty,
276
+ });
277
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Library entry for `@meghjs/cli`. Importing it has no side effects; the
3
+ * executable lives in `bin.ts`.
4
+ */
5
+ export { runCli, createProgram, normalizeArgv } from "./program";
6
+ export type { RunOptions } from "./program";
7
+ export { CliError } from "./errors";
8
+ export { createApplication } from "./commands/new";
9
+ export type { NewOptions } from "./commands/new";
10
+ export { build } from "./commands/build";
11
+ export { serve } from "./commands/serve";
12
+ export { start } from "./commands/start";
13
+ export { doctor, runChecks } from "./commands/doctor";
14
+ export { routeList, scanRoutes } from "./commands/route-list";
15
+ export { makeModel, makeController, makeService, makeConfig, makeMiddleware, makeDto, } from "./generators/make";
16
+ export { resolveName, pascalCase, camelCase, kebabCase, snakeCase } from "./utils/names";
17
+ export { findProjectRoot } from "./utils/project";
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findProjectRoot = exports.snakeCase = exports.kebabCase = exports.camelCase = exports.pascalCase = exports.resolveName = exports.makeDto = exports.makeMiddleware = exports.makeConfig = exports.makeService = exports.makeController = exports.makeModel = exports.scanRoutes = exports.routeList = exports.runChecks = exports.doctor = exports.start = exports.serve = exports.build = exports.createApplication = exports.CliError = exports.normalizeArgv = exports.createProgram = exports.runCli = void 0;
4
+ /**
5
+ * Library entry for `@meghjs/cli`. Importing it has no side effects; the
6
+ * executable lives in `bin.ts`.
7
+ */
8
+ var program_1 = require("./program");
9
+ Object.defineProperty(exports, "runCli", { enumerable: true, get: function () { return program_1.runCli; } });
10
+ Object.defineProperty(exports, "createProgram", { enumerable: true, get: function () { return program_1.createProgram; } });
11
+ Object.defineProperty(exports, "normalizeArgv", { enumerable: true, get: function () { return program_1.normalizeArgv; } });
12
+ var errors_1 = require("./errors");
13
+ Object.defineProperty(exports, "CliError", { enumerable: true, get: function () { return errors_1.CliError; } });
14
+ var new_1 = require("./commands/new");
15
+ Object.defineProperty(exports, "createApplication", { enumerable: true, get: function () { return new_1.createApplication; } });
16
+ var build_1 = require("./commands/build");
17
+ Object.defineProperty(exports, "build", { enumerable: true, get: function () { return build_1.build; } });
18
+ var serve_1 = require("./commands/serve");
19
+ Object.defineProperty(exports, "serve", { enumerable: true, get: function () { return serve_1.serve; } });
20
+ var start_1 = require("./commands/start");
21
+ Object.defineProperty(exports, "start", { enumerable: true, get: function () { return start_1.start; } });
22
+ var doctor_1 = require("./commands/doctor");
23
+ Object.defineProperty(exports, "doctor", { enumerable: true, get: function () { return doctor_1.doctor; } });
24
+ Object.defineProperty(exports, "runChecks", { enumerable: true, get: function () { return doctor_1.runChecks; } });
25
+ var route_list_1 = require("./commands/route-list");
26
+ Object.defineProperty(exports, "routeList", { enumerable: true, get: function () { return route_list_1.routeList; } });
27
+ Object.defineProperty(exports, "scanRoutes", { enumerable: true, get: function () { return route_list_1.scanRoutes; } });
28
+ var make_1 = require("./generators/make");
29
+ Object.defineProperty(exports, "makeModel", { enumerable: true, get: function () { return make_1.makeModel; } });
30
+ Object.defineProperty(exports, "makeController", { enumerable: true, get: function () { return make_1.makeController; } });
31
+ Object.defineProperty(exports, "makeService", { enumerable: true, get: function () { return make_1.makeService; } });
32
+ Object.defineProperty(exports, "makeConfig", { enumerable: true, get: function () { return make_1.makeConfig; } });
33
+ Object.defineProperty(exports, "makeMiddleware", { enumerable: true, get: function () { return make_1.makeMiddleware; } });
34
+ Object.defineProperty(exports, "makeDto", { enumerable: true, get: function () { return make_1.makeDto; } });
35
+ var names_1 = require("./utils/names");
36
+ Object.defineProperty(exports, "resolveName", { enumerable: true, get: function () { return names_1.resolveName; } });
37
+ Object.defineProperty(exports, "pascalCase", { enumerable: true, get: function () { return names_1.pascalCase; } });
38
+ Object.defineProperty(exports, "camelCase", { enumerable: true, get: function () { return names_1.camelCase; } });
39
+ Object.defineProperty(exports, "kebabCase", { enumerable: true, get: function () { return names_1.kebabCase; } });
40
+ Object.defineProperty(exports, "snakeCase", { enumerable: true, get: function () { return names_1.snakeCase; } });
41
+ var project_1 = require("./utils/project");
42
+ Object.defineProperty(exports, "findProjectRoot", { enumerable: true, get: function () { return project_1.findProjectRoot; } });
@@ -0,0 +1,22 @@
1
+ import { Command } from "commander";
2
+ export type RunOptions = {
3
+ /** Working directory for the command. Defaults to `process.cwd()`. */
4
+ cwd?: string;
5
+ /** Override where commander writes help and errors (used by tests). */
6
+ writeOut?: (s: string) => void;
7
+ writeErr?: (s: string) => void;
8
+ };
9
+ /**
10
+ * Legacy spellings commander cannot express directly: `-rt` (multi-letter
11
+ * short flag) and `--rest` (second long name for `--resource`).
12
+ */
13
+ export declare function normalizeArgv(args: string[]): string[];
14
+ export declare function createProgram(run?: RunOptions): {
15
+ program: Command;
16
+ exitCode: () => number;
17
+ };
18
+ /**
19
+ * Parse and run a command line (without the `node` and script entries).
20
+ * Resolves to the process exit code instead of exiting, so it can be tested.
21
+ */
22
+ export declare function runCli(args: string[], run?: RunOptions): Promise<number>;
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeArgv = normalizeArgv;
4
+ exports.createProgram = createProgram;
5
+ exports.runCli = runCli;
6
+ const commander_1 = require("commander");
7
+ const build_1 = require("./commands/build");
8
+ const doctor_1 = require("./commands/doctor");
9
+ const new_1 = require("./commands/new");
10
+ const route_list_1 = require("./commands/route-list");
11
+ const serve_1 = require("./commands/serve");
12
+ const start_1 = require("./commands/start");
13
+ const errors_1 = require("./errors");
14
+ const migrate_1 = require("./commands/migrate");
15
+ const make_1 = require("./generators/make");
16
+ const log_1 = require("./utils/log");
17
+ const stubs_1 = require("./utils/stubs");
18
+ /**
19
+ * Legacy spellings commander cannot express directly: `-rt` (multi-letter
20
+ * short flag) and `--rest` (second long name for `--resource`).
21
+ */
22
+ function normalizeArgv(args) {
23
+ return args.map((a) => (a === "-rt" ? "--root" : a === "--rest" ? "--resource" : a));
24
+ }
25
+ function parseInteger(value) {
26
+ const n = Number(value);
27
+ if (!Number.isInteger(n) || n < 0)
28
+ throw new commander_1.InvalidArgumentError("Expected a non-negative integer.");
29
+ return n;
30
+ }
31
+ function parseList(value) {
32
+ return value
33
+ .split(",")
34
+ .map((s) => s.trim())
35
+ .filter(Boolean);
36
+ }
37
+ function createProgram(run = {}) {
38
+ const cwd = () => run.cwd ?? process.cwd();
39
+ let exitCode = 0;
40
+ const program = new commander_1.Command();
41
+ program
42
+ .name("megh")
43
+ .description("Scaffold, run and build Megh applications.")
44
+ .version((0, stubs_1.cliVersion)(), "-v, --version", "Print the CLI version")
45
+ .helpOption("-h, --help", "Show help")
46
+ .helpCommand("help [command]", "Show help for a command")
47
+ .showHelpAfterError("(run `megh --help` for usage)")
48
+ .showSuggestionAfterError(true)
49
+ .exitOverride();
50
+ if (run.writeOut || run.writeErr) {
51
+ program.configureOutput({
52
+ ...(run.writeOut ? { writeOut: run.writeOut } : {}),
53
+ ...(run.writeErr ? { writeErr: run.writeErr } : {}),
54
+ });
55
+ }
56
+ const sub = (name, description) => {
57
+ const cmd = program.command(name).description(description).helpOption("-h, --help", "Show help");
58
+ cmd.exitOverride();
59
+ if (run.writeOut || run.writeErr)
60
+ cmd.configureOutput(program.configureOutput());
61
+ return cmd;
62
+ };
63
+ // ── Project ─────────────────────────────────────────────────────────────
64
+ sub("new", "Create a new Megh application")
65
+ .argument("<name>", "Project directory (created if missing); `.` for the current directory")
66
+ .option("-m, --minimal", "Minimal app: a single functional route, no controllers, services or tests")
67
+ .option("-f, --force", "Scaffold into a non-empty directory, overwriting generated files")
68
+ .option("-y, --yes", "Skip prompts and use defaults (npm, openapi)")
69
+ .option("--pm <manager>", `Package manager: ${new_1.PACKAGE_MANAGERS.join(", ")}`)
70
+ .option("--features <list>", `Comma-separated features: ${new_1.FEATURES.join(", ")}`, parseList)
71
+ .option("--database <name>", `Set up MeghORM (the orm feature) for ${new_1.DATABASES.join(", ")}. Defaults to sqlite with orm`)
72
+ .option("--skip-install", "Do not install dependencies (or set MEGH_SKIP_INSTALL=1)")
73
+ .action(async (name, o) => {
74
+ await (0, new_1.createApplication)(name, { cwd: cwd(), ...o });
75
+ });
76
+ sub("serve", "Start the dev server: compile src/ with SWC, run the app, reload on changes")
77
+ .option("--entry <file>", "Entry file, overriding megh.entry / main in package.json")
78
+ .option("--no-type-check", "Do not run `tsc --noEmit --watch` alongside the server")
79
+ .option("--debounce <ms>", "Wait this long for more file changes before reloading", parseInteger, 200)
80
+ .action(async (o) => {
81
+ await (0, serve_1.serve)({ cwd: cwd(), entry: o.entry, typeCheck: o.typeCheck, debounce: o.debounce });
82
+ });
83
+ sub("build", "Compile with tsc (tsconfig.build.json, else tsconfig.json) and copy assets")
84
+ .option("-p, --project <file>", "Use this tsconfig instead")
85
+ .action(async (o) => {
86
+ await (0, build_1.build)({ cwd: cwd(), project: o.project });
87
+ });
88
+ sub("start", "Run the compiled app in production (NODE_ENV=production unless set)")
89
+ .option("--entry <file>", "Entry file, overriding megh.entry / main in package.json")
90
+ .action(async (o) => {
91
+ exitCode = await (0, start_1.start)({ cwd: cwd(), entry: o.entry });
92
+ });
93
+ sub("doctor", "Check Node.js, @meghjs/core, reflect-metadata and decorator settings")
94
+ .action(() => {
95
+ exitCode = (0, doctor_1.doctor)(cwd());
96
+ });
97
+ sub("route:list", "List the app's routes")
98
+ .alias("routes")
99
+ .option("--json", "Print JSON")
100
+ .option("--static", "Scan @ApiController/@Get/@Post/... decorators in src/**/*.controller.ts instead of loading the code")
101
+ .addHelpText("after", "\nBy default the sources are compiled with SWC to node_modules/.cache/megh and each\n" +
102
+ "*.controller.ts is loaded in a child process to read Megh's route metadata, so\n" +
103
+ "@meghjs/core must be installed. --static needs no dependencies but only understands\n" +
104
+ "string-literal paths.")
105
+ .action((o) => {
106
+ (0, route_list_1.routeList)({ cwd: cwd(), json: o.json, static: o.static });
107
+ });
108
+ // ── Database ────────────────────────────────────────────────────────────
109
+ const db = (name, description) => sub(name, description).addHelpText("after", "\nConnects the way app.useMeghORM() does: from DATABASE_URL (or DB_DIALECT, DB_HOST,\n" +
110
+ "DB_NAME, ...) in the environment or .env, with optional settings in megh.database in\n" +
111
+ "package.json. Migrations live in src/database/migrations; set megh.migrations to\n" +
112
+ "change it. Sources are compiled with SWC first.");
113
+ db("migrate", "Run pending migrations").action(() => {
114
+ (0, migrate_1.migrate)({ cwd: cwd() });
115
+ });
116
+ db("migrate:rollback", "Undo the last migration (or the last --step n)")
117
+ .option("--step <n>", "Number of migrations to undo", parseInteger, 1)
118
+ .action((o) => {
119
+ (0, migrate_1.migrateRollback)({ cwd: cwd(), step: o.step });
120
+ });
121
+ db("migrate:reset", "Undo every migration").action(() => {
122
+ (0, migrate_1.migrateReset)({ cwd: cwd() });
123
+ });
124
+ db("migrate:refresh", "Undo every migration, then run them all again").action(() => {
125
+ (0, migrate_1.migrateRefresh)({ cwd: cwd() });
126
+ });
127
+ db("migrate:status", "Show which migrations have run")
128
+ .option("--json", "Print JSON")
129
+ .action((o) => {
130
+ (0, migrate_1.migrateStatus)({ cwd: cwd(), json: o.json });
131
+ });
132
+ sub("make:migration", "Create a migration in src/database/migrations/<timestamp>_<name>.ts")
133
+ .alias("m:mig")
134
+ .argument("<name>", "e.g. create_users_table, add_role_to_users_table")
135
+ .option("--create <table>", "Generate a create-table migration for <table>")
136
+ .option("--table <table>", "Generate an alter-table migration for <table>")
137
+ .option("-f, --force", "Overwrite the file if it exists")
138
+ .action((name, o) => {
139
+ (0, make_1.makeMigration)(name, { cwd: cwd(), create: o.create, table: o.table, force: o.force });
140
+ });
141
+ // ── Generators ──────────────────────────────────────────────────────────
142
+ const make = (name, aliases, description) => sub(name, description)
143
+ .aliases(aliases)
144
+ .argument("<name>", "Name, optionally nested (e.g. admin/User)")
145
+ .option("-f, --force", "Overwrite the file if it exists");
146
+ make("make:model", ["m:m"], "Create a model in src/models/<name>.model.ts, with columns read from its migrations")
147
+ .option("-t, --table <table>", "Table name (default: plural snake_case name, e.g. blog_posts)")
148
+ .option("--orm", "Generate a TypeORM entity")
149
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
150
+ .action((name, o) => {
151
+ (0, make_1.makeModel)(name, { cwd: cwd(), ...o });
152
+ });
153
+ make("make:resource", ["m:r", "m:res"], "Create a REST resource for a model: its DTOs, a CRUD service and a controller")
154
+ .option("-t, --table <table>", "Table to read the columns from when the model is missing (default: plural snake_case name)")
155
+ .addHelpText("after", "\nThe model in src/models/<name>.model.ts is reused if it exists; otherwise it is\n" +
156
+ "generated from the migration that creates its table (and the command fails if\n" +
157
+ "there is none). Then src/dtos/<name>.dto.ts, src/services/<name>.service.ts and\n" +
158
+ "src/controllers/<name>.controller.ts are written, e.g. for `make:resource user`:\n" +
159
+ " GET /users?page=&perPage= POST /users GET|PUT|DELETE /users/:id")
160
+ .action((name, o) => {
161
+ (0, make_1.makeResource)(name, { cwd: cwd(), force: o.force, table: o.table });
162
+ });
163
+ make("make:controller", ["m:c"], "Create a controller in src/controllers/<name>.controller.ts")
164
+ .option("-r, --resource", "Generate a REST skeleton (also --rest)")
165
+ .option("-m, --model <model>", "Back a REST controller with <model>: also creates its DTOs, service and model (from its migration) if missing")
166
+ .option("--orm", "With -m, back the service with a TypeORM repository and entity")
167
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
168
+ .option("--base-path", "Use @ApiController without a path prefix")
169
+ .action((name, o) => {
170
+ (0, make_1.makeController)(name, { cwd: cwd(), ...o });
171
+ });
172
+ make("make:service", ["m:s"], "Create a service in src/services/<name>.service.ts")
173
+ .option("-r, --resource", "Generate a resource (CRUD) service; requires -m (also --rest)")
174
+ .option("-m, --model <model>", "Model for a resource service; creates the model from its migration if missing")
175
+ .option("--orm", "Back the resource service with a TypeORM repository and entity")
176
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
177
+ .action((name, o) => {
178
+ (0, make_1.makeService)(name, { cwd: cwd(), ...o });
179
+ });
180
+ make("make:config", ["m:cnf", "m:cfg"], "Create an @AppConfig class in src/config/<name>.config.ts")
181
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
182
+ .action((name, o) => {
183
+ (0, make_1.makeConfig)(name, { cwd: cwd(), ...o });
184
+ });
185
+ make("make:middleware", ["m:mlwr", "m:mdlr"], "Create a middleware in src/middlewares/<name>.middleware.ts")
186
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
187
+ .action((name, o) => {
188
+ (0, make_1.makeMiddleware)(name, { cwd: cwd(), ...o });
189
+ });
190
+ make("make:dto", ["m:dto"], "Create a class-validator DTO in src/dtos/<name>.dto.ts")
191
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
192
+ .action((name, o) => {
193
+ (0, make_1.makeDto)(name, { cwd: cwd(), ...o });
194
+ });
195
+ return { program, exitCode: () => exitCode };
196
+ }
197
+ /**
198
+ * Parse and run a command line (without the `node` and script entries).
199
+ * Resolves to the process exit code instead of exiting, so it can be tested.
200
+ */
201
+ async function runCli(args, run = {}) {
202
+ const { program, exitCode } = createProgram(run);
203
+ const argv = normalizeArgv(args);
204
+ if (argv.length === 0) {
205
+ program.outputHelp();
206
+ return 0;
207
+ }
208
+ try {
209
+ await program.parseAsync(argv, { from: "user" });
210
+ return exitCode();
211
+ }
212
+ catch (err) {
213
+ if (err instanceof commander_1.CommanderError) {
214
+ // Help and version are reported as "errors" with exit code 0.
215
+ return err.exitCode;
216
+ }
217
+ if (err instanceof errors_1.CliError) {
218
+ log_1.log.error(err.message);
219
+ return err.exitCode;
220
+ }
221
+ log_1.log.error(err instanceof Error ? (err.stack ?? err.message) : String(err));
222
+ return 1;
223
+ }
224
+ }
@@ -0,0 +1,15 @@
1
+ export type ProjectLayout = {
2
+ root: string;
3
+ srcDir: string;
4
+ outDir: string;
5
+ compilerOptions: Record<string, any>;
6
+ tsconfig: string | null;
7
+ };
8
+ export declare function projectLayout(root: string, preferBuildConfig?: boolean): ProjectLayout;
9
+ /**
10
+ * Candidate entry files, most specific first: `--entry`, `megh.entry` in
11
+ * package.json, `main` (mapped from `src/*.ts` to the output dir), then the
12
+ * conventional names in the output dir.
13
+ */
14
+ export declare function entryCandidates(layout: ProjectLayout, pkg: Record<string, any>, explicit?: string): string[];
15
+ export declare function resolveEntry(candidates: string[], explicit?: string): string | null;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.projectLayout = projectLayout;
7
+ exports.entryCandidates = entryCandidates;
8
+ exports.resolveEntry = resolveEntry;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const tsconfig_1 = require("./tsconfig");
12
+ function projectLayout(root, preferBuildConfig = false) {
13
+ const tsconfig = (0, tsconfig_1.findTsConfig)(root, preferBuildConfig);
14
+ const compilerOptions = tsconfig ? (0, tsconfig_1.readTsConfig)(tsconfig).compilerOptions : {};
15
+ return {
16
+ root,
17
+ tsconfig,
18
+ compilerOptions,
19
+ srcDir: compilerOptions.rootDir ?? path_1.default.join(root, "src"),
20
+ outDir: compilerOptions.outDir ?? path_1.default.join(root, "dist"),
21
+ };
22
+ }
23
+ const DEFAULT_ENTRIES = ["serve.js", "server.js", "main.js", "index.js"];
24
+ /**
25
+ * Candidate entry files, most specific first: `--entry`, `megh.entry` in
26
+ * package.json, `main` (mapped from `src/*.ts` to the output dir), then the
27
+ * conventional names in the output dir.
28
+ */
29
+ function entryCandidates(layout, pkg, explicit) {
30
+ const list = [];
31
+ const add = (p) => list.push(path_1.default.resolve(layout.root, p));
32
+ if (explicit)
33
+ add(explicit);
34
+ if (typeof pkg?.megh?.entry === "string")
35
+ add(pkg.megh.entry);
36
+ if (typeof pkg?.main === "string") {
37
+ const main = path_1.default.resolve(layout.root, pkg.main);
38
+ const rel = path_1.default.relative(layout.srcDir, main);
39
+ if (!rel.startsWith("..") && !path_1.default.isAbsolute(rel)) {
40
+ add(path_1.default.join(layout.outDir, rel).replace(/\.ts$/, ".js"));
41
+ }
42
+ else {
43
+ add(main);
44
+ }
45
+ }
46
+ for (const name of DEFAULT_ENTRIES)
47
+ add(path_1.default.join(layout.outDir, name));
48
+ return [...new Set(list)];
49
+ }
50
+ function resolveEntry(candidates, explicit) {
51
+ // An explicit --entry must exist itself; no silent fallback.
52
+ if (explicit)
53
+ return fs_1.default.existsSync(candidates[0]) ? candidates[0] : null;
54
+ return candidates.find((c) => fs_1.default.existsSync(c)) ?? null;
55
+ }