@meghjs/cli 0.0.0-stage → 0.5.0

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 (74) 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 +32 -0
  9. package/dist/commands/migrate.js +177 -0
  10. package/dist/commands/new.d.ts +19 -0
  11. package/dist/commands/new.js +306 -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 +40 -0
  23. package/dist/generators/make.js +198 -0
  24. package/dist/index.d.ts +17 -0
  25. package/dist/index.js +42 -0
  26. package/dist/program.d.ts +22 -0
  27. package/dist/program.js +211 -0
  28. package/dist/utils/entry.d.ts +15 -0
  29. package/dist/utils/entry.js +55 -0
  30. package/dist/utils/env-types.d.ts +8 -0
  31. package/dist/utils/env-types.js +19 -0
  32. package/dist/utils/log.d.ts +25 -0
  33. package/dist/utils/log.js +39 -0
  34. package/dist/utils/names.d.ts +27 -0
  35. package/dist/utils/names.js +58 -0
  36. package/dist/utils/process.d.ts +18 -0
  37. package/dist/utils/process.js +84 -0
  38. package/dist/utils/project.d.ts +17 -0
  39. package/dist/utils/project.js +91 -0
  40. package/dist/utils/stubs.d.ts +15 -0
  41. package/dist/utils/stubs.js +52 -0
  42. package/dist/utils/tsconfig.d.ts +13 -0
  43. package/dist/utils/tsconfig.js +102 -0
  44. package/package.json +61 -4
  45. package/readme.md +155 -0
  46. package/stubs/config/config.stub +9 -0
  47. package/stubs/controllers/basic-controller.stub +9 -0
  48. package/stubs/controllers/resource-controller.stub +45 -0
  49. package/stubs/controllers/rest-controller.stub +29 -0
  50. package/stubs/dtos/dto.stub +11 -0
  51. package/stubs/middlewares/middleware.stub +9 -0
  52. package/stubs/migrations/alter-table.stub +9 -0
  53. package/stubs/migrations/create-table.stub +15 -0
  54. package/stubs/migrations/migration.stub +9 -0
  55. package/stubs/models/basic-model.stub +4 -0
  56. package/stubs/models/entity-model.stub +16 -0
  57. package/stubs/project/app-minimal.stub +7 -0
  58. package/stubs/project/app.stub +8 -0
  59. package/stubs/project/env.stub +3 -0
  60. package/stubs/project/gitignore.stub +5 -0
  61. package/stubs/project/home.controller.spec.stub +19 -0
  62. package/stubs/project/home.controller.stub +12 -0
  63. package/stubs/project/home.service.stub +8 -0
  64. package/stubs/project/openapi.config.stub +15 -0
  65. package/stubs/project/readme.stub +26 -0
  66. package/stubs/project/serve.stub +10 -0
  67. package/stubs/project/tsconfig.build.stub +4 -0
  68. package/stubs/project/tsconfig.stub +18 -0
  69. package/stubs/project/vitest-e2e.config.stub +10 -0
  70. package/stubs/project/vitest.config.stub +17 -0
  71. package/stubs/services/basic-service.stub +8 -0
  72. package/stubs/services/orm-rest-service.stub +61 -0
  73. package/stubs/services/rest-service.stub +34 -0
  74. package/README.md +0 -3
@@ -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,211 @@
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("--skip-install", "Do not install dependencies (or set MEGH_SKIP_INSTALL=1)")
72
+ .action(async (name, o) => {
73
+ await (0, new_1.createApplication)(name, { cwd: cwd(), ...o });
74
+ });
75
+ sub("serve", "Start the dev server: compile src/ with SWC, run the app, reload on changes")
76
+ .option("--entry <file>", "Entry file, overriding megh.entry / main in package.json")
77
+ .option("--no-type-check", "Do not run `tsc --noEmit --watch` alongside the server")
78
+ .option("--debounce <ms>", "Wait this long for more file changes before reloading", parseInteger, 200)
79
+ .action(async (o) => {
80
+ await (0, serve_1.serve)({ cwd: cwd(), entry: o.entry, typeCheck: o.typeCheck, debounce: o.debounce });
81
+ });
82
+ sub("build", "Compile with tsc (tsconfig.build.json, else tsconfig.json) and copy assets")
83
+ .option("-p, --project <file>", "Use this tsconfig instead")
84
+ .action(async (o) => {
85
+ await (0, build_1.build)({ cwd: cwd(), project: o.project });
86
+ });
87
+ sub("start", "Run the compiled app in production (NODE_ENV=production unless set)")
88
+ .option("--entry <file>", "Entry file, overriding megh.entry / main in package.json")
89
+ .action(async (o) => {
90
+ exitCode = await (0, start_1.start)({ cwd: cwd(), entry: o.entry });
91
+ });
92
+ sub("doctor", "Check Node.js, @meghjs/core, reflect-metadata and decorator settings")
93
+ .action(() => {
94
+ exitCode = (0, doctor_1.doctor)(cwd());
95
+ });
96
+ sub("route:list", "List the app's routes")
97
+ .alias("routes")
98
+ .option("--json", "Print JSON")
99
+ .option("--static", "Scan @ApiController/@Get/@Post/... decorators in src/**/*.controller.ts instead of loading the code")
100
+ .addHelpText("after", "\nBy default the sources are compiled with SWC to node_modules/.cache/megh and each\n" +
101
+ "*.controller.ts is loaded in a child process to read Megh's route metadata, so\n" +
102
+ "@meghjs/core must be installed. --static needs no dependencies but only understands\n" +
103
+ "string-literal paths.")
104
+ .action((o) => {
105
+ (0, route_list_1.routeList)({ cwd: cwd(), json: o.json, static: o.static });
106
+ });
107
+ // ── Database ────────────────────────────────────────────────────────────
108
+ const db = (name, description) => sub(name, description).addHelpText("after", "\nThe Kysely instance is the default (or `db`) export of src/database/connection.ts and\n" +
109
+ "migrations live in src/database/migrations; set megh.database / megh.migrations in\n" +
110
+ "package.json to change them. Sources are compiled with SWC first, and .env is loaded.");
111
+ db("migrate", "Run pending migrations").action(() => {
112
+ (0, migrate_1.migrate)({ cwd: cwd() });
113
+ });
114
+ db("migrate:rollback", "Undo the last migration (or the last --step n)")
115
+ .option("--step <n>", "Number of migrations to undo", parseInteger, 1)
116
+ .action((o) => {
117
+ (0, migrate_1.migrateRollback)({ cwd: cwd(), step: o.step });
118
+ });
119
+ db("migrate:reset", "Undo every migration").action(() => {
120
+ (0, migrate_1.migrateReset)({ cwd: cwd() });
121
+ });
122
+ db("migrate:refresh", "Undo every migration, then run them all again").action(() => {
123
+ (0, migrate_1.migrateRefresh)({ cwd: cwd() });
124
+ });
125
+ db("migrate:status", "Show which migrations have run")
126
+ .option("--json", "Print JSON")
127
+ .action((o) => {
128
+ (0, migrate_1.migrateStatus)({ cwd: cwd(), json: o.json });
129
+ });
130
+ sub("make:migration", "Create a migration in src/database/migrations/<timestamp>_<name>.ts")
131
+ .alias("m:mig")
132
+ .argument("<name>", "e.g. create_users_table, add_role_to_users_table")
133
+ .option("--create <table>", "Generate a create-table migration for <table>")
134
+ .option("--table <table>", "Generate an alter-table migration for <table>")
135
+ .option("-f, --force", "Overwrite the file if it exists")
136
+ .action((name, o) => {
137
+ (0, make_1.makeMigration)(name, { cwd: cwd(), create: o.create, table: o.table, force: o.force });
138
+ });
139
+ // ── Generators ──────────────────────────────────────────────────────────
140
+ const make = (name, aliases, description) => sub(name, description)
141
+ .aliases(aliases)
142
+ .argument("<name>", "Name, optionally nested (e.g. admin/User)")
143
+ .option("-f, --force", "Overwrite the file if it exists");
144
+ make("make:model", ["m:m"], "Create a model in src/models/<name>.model.ts")
145
+ .option("--orm", "Generate a TypeORM entity")
146
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
147
+ .action((name, o) => {
148
+ (0, make_1.makeModel)(name, { cwd: cwd(), ...o });
149
+ });
150
+ make("make:controller", ["m:c"], "Create a controller in src/controllers/<name>.controller.ts")
151
+ .option("-r, --resource", "Generate a REST skeleton (also --rest)")
152
+ .option("-m, --model <model>", "Back a REST controller with <model>: also creates its service and model if missing")
153
+ .option("--orm", "With -m, back the service with a TypeORM repository and entity")
154
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
155
+ .option("--base-path", "Use @ApiController without a path prefix")
156
+ .action((name, o) => {
157
+ (0, make_1.makeController)(name, { cwd: cwd(), ...o });
158
+ });
159
+ make("make:service", ["m:s"], "Create a service in src/services/<name>.service.ts")
160
+ .option("-r, --resource", "Generate a resource (CRUD) service; requires -m (also --rest)")
161
+ .option("-m, --model <model>", "Model for a resource service; creates the model if missing")
162
+ .option("--orm", "Back the resource service with a TypeORM repository and entity")
163
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
164
+ .action((name, o) => {
165
+ (0, make_1.makeService)(name, { cwd: cwd(), ...o });
166
+ });
167
+ make("make:config", ["m:cnf", "m:cfg"], "Create an @AppConfig class in src/config/<name>.config.ts")
168
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
169
+ .action((name, o) => {
170
+ (0, make_1.makeConfig)(name, { cwd: cwd(), ...o });
171
+ });
172
+ make("make:middleware", ["m:mlwr", "m:mdlr"], "Create a middleware in src/middlewares/<name>.middleware.ts")
173
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
174
+ .action((name, o) => {
175
+ (0, make_1.makeMiddleware)(name, { cwd: cwd(), ...o });
176
+ });
177
+ make("make:dto", ["m:dto"], "Create a class-validator DTO in src/dtos/<name>.dto.ts")
178
+ .option("--root <dir>", "Folder under src/ to write to (also -rt)")
179
+ .action((name, o) => {
180
+ (0, make_1.makeDto)(name, { cwd: cwd(), ...o });
181
+ });
182
+ return { program, exitCode: () => exitCode };
183
+ }
184
+ /**
185
+ * Parse and run a command line (without the `node` and script entries).
186
+ * Resolves to the process exit code instead of exiting, so it can be tested.
187
+ */
188
+ async function runCli(args, run = {}) {
189
+ const { program, exitCode } = createProgram(run);
190
+ const argv = normalizeArgv(args);
191
+ if (argv.length === 0) {
192
+ program.outputHelp();
193
+ return 0;
194
+ }
195
+ try {
196
+ await program.parseAsync(argv, { from: "user" });
197
+ return exitCode();
198
+ }
199
+ catch (err) {
200
+ if (err instanceof commander_1.CommanderError) {
201
+ // Help and version are reported as "errors" with exit code 0.
202
+ return err.exitCode;
203
+ }
204
+ if (err instanceof errors_1.CliError) {
205
+ log_1.log.error(err.message);
206
+ return err.exitCode;
207
+ }
208
+ log_1.log.error(err instanceof Error ? (err.stack ?? err.message) : String(err));
209
+ return 1;
210
+ }
211
+ }
@@ -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
+ }
@@ -0,0 +1,8 @@
1
+ /** File name of the generated declarations that load the app's plugin types. */
2
+ export declare const ENV_TYPES_FILE = "megh-env.d.ts";
3
+ /**
4
+ * Contents of `megh-env.d.ts`. Each Megh plugin adds its app methods
5
+ * (such as `app.useKnex()` from `@meghjs/data`) through declaration merging,
6
+ * which TypeScript only sees once the plugin's types are part of the project.
7
+ */
8
+ export declare function envTypesFile(plugins: string[]): string;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ENV_TYPES_FILE = void 0;
4
+ exports.envTypesFile = envTypesFile;
5
+ /** File name of the generated declarations that load the app's plugin types. */
6
+ exports.ENV_TYPES_FILE = "megh-env.d.ts";
7
+ /**
8
+ * Contents of `megh-env.d.ts`. Each Megh plugin adds its app methods
9
+ * (such as `app.useKnex()` from `@meghjs/data`) through declaration merging,
10
+ * which TypeScript only sees once the plugin's types are part of the project.
11
+ */
12
+ function envTypesFile(plugins) {
13
+ return [
14
+ "// Generated by the Megh CLI. Do not edit: it is rewritten when plugins change.",
15
+ "// It loads the types of the Megh plugins this app depends on.",
16
+ ...[...plugins].sort().map((name) => `/// <reference types="${name}" />`),
17
+ "",
18
+ ].join("\n");
19
+ }
@@ -0,0 +1,25 @@
1
+ export declare const c: {
2
+ dim: (s: string) => string;
3
+ bold: (s: string) => string;
4
+ cyan: (s: string) => string;
5
+ green: (s: string) => string;
6
+ yellow: (s: string) => string;
7
+ red: (s: string) => string;
8
+ white: (s: string) => string;
9
+ };
10
+ export declare const icon: {
11
+ success: string;
12
+ error: string;
13
+ warn: string;
14
+ arrow: string;
15
+ };
16
+ export declare const log: {
17
+ info: (msg: string) => void;
18
+ step: (label: string, detail?: string) => void;
19
+ success: (msg: string) => void;
20
+ warn: (msg: string) => void;
21
+ error: (msg: string) => void;
22
+ section: (title: string) => void;
23
+ };
24
+ /** Timestamped, category-prefixed logging used by the long-running commands. */
25
+ export declare function tagged(category: string, color?: (s: string) => string): (message: string) => void;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.log = exports.icon = exports.c = void 0;
4
+ exports.tagged = tagged;
5
+ const useColor = !process.env.NO_COLOR && (process.env.FORCE_COLOR !== undefined || process.stdout.isTTY === true);
6
+ const code = (open) => (s) => (useColor ? `\x1b[${open}m${s}\x1b[0m` : s);
7
+ exports.c = {
8
+ dim: code("90"),
9
+ bold: code("1"),
10
+ cyan: code("36"),
11
+ green: code("32"),
12
+ yellow: code("33"),
13
+ red: code("31"),
14
+ white: code("37"),
15
+ };
16
+ exports.icon = {
17
+ success: exports.c.green("✔"),
18
+ error: exports.c.red("✖"),
19
+ warn: exports.c.yellow("⚠"),
20
+ arrow: exports.c.dim("→"),
21
+ };
22
+ exports.log = {
23
+ info: (msg) => console.log(msg),
24
+ step: (label, detail) => console.log(` ${exports.icon.arrow} ${label.padEnd(30, " ")}${detail ? exports.c.dim(detail) : ""}`),
25
+ success: (msg) => console.log(`${exports.icon.success} ${msg}`),
26
+ warn: (msg) => console.warn(`${exports.icon.warn} ${exports.c.yellow(msg)}`),
27
+ error: (msg) => console.error(`${exports.icon.error} ${exports.c.red(msg)}`),
28
+ section: (title) => {
29
+ console.log(`\n${exports.c.bold(exports.c.cyan(` ${title}`))}`);
30
+ console.log(` ${"─".repeat(40)}`);
31
+ },
32
+ };
33
+ /** Timestamped, category-prefixed logging used by the long-running commands. */
34
+ function tagged(category, color = exports.c.white) {
35
+ return (message) => {
36
+ const ts = new Date().toTimeString().split(" ")[0];
37
+ console.log(`${exports.c.dim(`[${ts}]`)} ${color(`[${category}]`)} ${message}`);
38
+ };
39
+ }
@@ -0,0 +1,27 @@
1
+ /** Split an identifier into words: `JwtAuth`, `jwt-auth`, `jwt_auth` and `jwtAuth` all give `[jwt, auth]`. */
2
+ export declare function words(input: string): string[];
3
+ export declare const pascalCase: (input: string) => string;
4
+ export declare const camelCase: (input: string) => string;
5
+ export declare const kebabCase: (input: string) => string;
6
+ export declare const snakeCase: (input: string) => string;
7
+ /** Human-readable title, e.g. `my_api` -> `My Api`. */
8
+ export declare const titleCase: (input: string) => string;
9
+ export type ResolvedName = {
10
+ /** Sub-directories requested in the name, e.g. `["admin"]` for `admin/User`. */
11
+ dirs: string[];
12
+ /** PascalCase name without the suffix, e.g. `JwtAuth`. */
13
+ base: string;
14
+ /** PascalCase class name with the suffix, e.g. `JwtAuthConfig`. */
15
+ className: string;
16
+ /** camelCase base, e.g. `jwtAuth`. */
17
+ varName: string;
18
+ /** kebab-case base, e.g. `jwt-auth`. */
19
+ fileBase: string;
20
+ };
21
+ /**
22
+ * Resolve a user-supplied artifact name (optionally nested, e.g. `admin/User`
23
+ * or `admin\User`) into class and file names. A trailing suffix such as
24
+ * `Controller` is dropped before it is re-added, so `UserController` and `User`
25
+ * give the same result.
26
+ */
27
+ export declare function resolveName(input: string, suffix?: string): ResolvedName;
@@ -0,0 +1,58 @@
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.titleCase = exports.snakeCase = exports.kebabCase = exports.camelCase = exports.pascalCase = void 0;
7
+ exports.words = words;
8
+ exports.resolveName = resolveName;
9
+ const path_1 = __importDefault(require("path"));
10
+ const errors_1 = require("../errors");
11
+ /** Split an identifier into words: `JwtAuth`, `jwt-auth`, `jwt_auth` and `jwtAuth` all give `[jwt, auth]`. */
12
+ function words(input) {
13
+ const matches = input.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g);
14
+ return (matches ?? []).map((w) => w.toLowerCase());
15
+ }
16
+ const upperFirst = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
17
+ const pascalCase = (input) => words(input).map(upperFirst).join("");
18
+ exports.pascalCase = pascalCase;
19
+ const camelCase = (input) => {
20
+ const p = (0, exports.pascalCase)(input);
21
+ return p ? p[0].toLowerCase() + p.slice(1) : p;
22
+ };
23
+ exports.camelCase = camelCase;
24
+ const kebabCase = (input) => words(input).join("-");
25
+ exports.kebabCase = kebabCase;
26
+ const snakeCase = (input) => words(input).join("_");
27
+ exports.snakeCase = snakeCase;
28
+ /** Human-readable title, e.g. `my_api` -> `My Api`. */
29
+ const titleCase = (input) => words(input).map(upperFirst).join(" ");
30
+ exports.titleCase = titleCase;
31
+ /**
32
+ * Resolve a user-supplied artifact name (optionally nested, e.g. `admin/User`
33
+ * or `admin\User`) into class and file names. A trailing suffix such as
34
+ * `Controller` is dropped before it is re-added, so `UserController` and `User`
35
+ * give the same result.
36
+ */
37
+ function resolveName(input, suffix = "") {
38
+ if (!input || !input.trim())
39
+ throw new errors_1.CliError("A name is required.");
40
+ const parts = input.split(/[\\/]+/).filter(Boolean);
41
+ const last = parts.pop() ?? "";
42
+ for (const dir of parts) {
43
+ if (dir === "." || dir === ".." || path_1.default.isAbsolute(dir)) {
44
+ throw new errors_1.CliError(`Invalid name "${input}": use a relative path without "." or "..".`);
45
+ }
46
+ }
47
+ const stripped = suffix ? last.replace(new RegExp(`[-_.]?${suffix}$`, "i"), "") : last;
48
+ const base = (0, exports.pascalCase)(stripped);
49
+ if (!base)
50
+ throw new errors_1.CliError(`Invalid name "${input}".`);
51
+ return {
52
+ dirs: parts.map((d) => (0, exports.kebabCase)(d) || d),
53
+ base,
54
+ className: base + suffix,
55
+ varName: (0, exports.camelCase)(base),
56
+ fileBase: (0, exports.kebabCase)(base),
57
+ };
58
+ }
@@ -0,0 +1,18 @@
1
+ import { ChildProcess } from "child_process";
2
+ /**
3
+ * Stop a child process and everything it spawned. On POSIX the child must
4
+ * have been started with `detached: true` so it leads its own process group;
5
+ * we send SIGTERM to the group and escalate to SIGKILL after `timeoutMs`.
6
+ * Windows has no SIGTERM for console processes, so the tree is ended with
7
+ * `taskkill /T /F`.
8
+ */
9
+ export declare function killTree(child: ChildProcess | null, timeoutMs?: number): Promise<void>;
10
+ /** Spawn options that make `killTree` work on every platform. */
11
+ export declare const treeSpawnOptions: {
12
+ readonly detached: boolean;
13
+ readonly windowsHide: true;
14
+ };
15
+ /** Locate the project's own TypeScript compiler (`typescript/bin/tsc`). */
16
+ export declare function findTsc(root: string): string | null;
17
+ /** Run a node script to completion with inherited stdio, resolving to its exit code. */
18
+ export declare function runNode(script: string, args: string[], cwd: string, env?: NodeJS.ProcessEnv): Promise<number>;
@@ -0,0 +1,84 @@
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.treeSpawnOptions = void 0;
7
+ exports.killTree = killTree;
8
+ exports.findTsc = findTsc;
9
+ exports.runNode = runNode;
10
+ const child_process_1 = require("child_process");
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const isWindows = process.platform === "win32";
14
+ /**
15
+ * Stop a child process and everything it spawned. On POSIX the child must
16
+ * have been started with `detached: true` so it leads its own process group;
17
+ * we send SIGTERM to the group and escalate to SIGKILL after `timeoutMs`.
18
+ * Windows has no SIGTERM for console processes, so the tree is ended with
19
+ * `taskkill /T /F`.
20
+ */
21
+ function killTree(child, timeoutMs = 3000) {
22
+ return new Promise((resolve) => {
23
+ if (!child || child.pid === undefined || child.exitCode !== null || child.signalCode !== null) {
24
+ return resolve();
25
+ }
26
+ const pid = child.pid;
27
+ let done = false;
28
+ const finish = () => {
29
+ if (done)
30
+ return;
31
+ done = true;
32
+ clearTimeout(timer);
33
+ resolve();
34
+ };
35
+ child.once("exit", finish);
36
+ if (isWindows) {
37
+ (0, child_process_1.spawnSync)("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
38
+ }
39
+ else {
40
+ signalGroup(pid, "SIGTERM");
41
+ }
42
+ const timer = setTimeout(() => {
43
+ if (!isWindows)
44
+ signalGroup(pid, "SIGKILL");
45
+ setTimeout(finish, 200);
46
+ }, timeoutMs);
47
+ });
48
+ }
49
+ function signalGroup(pid, signal) {
50
+ try {
51
+ process.kill(-pid, signal);
52
+ }
53
+ catch {
54
+ try {
55
+ process.kill(pid, signal);
56
+ }
57
+ catch {
58
+ /* already gone */
59
+ }
60
+ }
61
+ }
62
+ /** Spawn options that make `killTree` work on every platform. */
63
+ exports.treeSpawnOptions = { detached: !isWindows, windowsHide: true };
64
+ /** Locate the project's own TypeScript compiler (`typescript/bin/tsc`). */
65
+ function findTsc(root) {
66
+ let dir = path_1.default.resolve(root);
67
+ for (;;) {
68
+ const candidate = path_1.default.join(dir, "node_modules", "typescript", "bin", "tsc");
69
+ if (fs_1.default.existsSync(candidate))
70
+ return candidate;
71
+ const parent = path_1.default.dirname(dir);
72
+ if (parent === dir)
73
+ return null;
74
+ dir = parent;
75
+ }
76
+ }
77
+ /** Run a node script to completion with inherited stdio, resolving to its exit code. */
78
+ function runNode(script, args, cwd, env = process.env) {
79
+ return new Promise((resolve, reject) => {
80
+ const child = (0, child_process_1.spawn)(process.execPath, [script, ...args], { cwd, stdio: "inherit", env });
81
+ child.on("error", reject);
82
+ child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
83
+ });
84
+ }