@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Tareq Hossain
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const program_1 = require("./program");
5
+ (0, program_1.runCli)(process.argv.slice(2)).then((code) => {
6
+ process.exitCode = code;
7
+ }, (err) => {
8
+ console.error(err);
9
+ process.exitCode = 1;
10
+ });
@@ -0,0 +1,11 @@
1
+ export type BuildOptions = {
2
+ cwd?: string;
3
+ project?: string;
4
+ quiet?: boolean;
5
+ };
6
+ /**
7
+ * Compile the project with its own `tsc`, using `tsconfig.build.json` (or
8
+ * `tsconfig.json` when there is none), then copy non-TS assets from the
9
+ * source dir into the output dir.
10
+ */
11
+ export declare function build(opts?: BuildOptions): Promise<string>;
@@ -0,0 +1,65 @@
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.build = build;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const errors_1 = require("../errors");
10
+ const tsconfig_1 = require("../utils/tsconfig");
11
+ const log_1 = require("../utils/log");
12
+ const project_1 = require("../utils/project");
13
+ const process_1 = require("../utils/process");
14
+ /**
15
+ * Compile the project with its own `tsc`, using `tsconfig.build.json` (or
16
+ * `tsconfig.json` when there is none), then copy non-TS assets from the
17
+ * source dir into the output dir.
18
+ */
19
+ async function build(opts = {}) {
20
+ const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
21
+ let config;
22
+ if (opts.project) {
23
+ config = path_1.default.resolve(opts.cwd ?? process.cwd(), opts.project);
24
+ if (!fs_1.default.existsSync(config))
25
+ throw new errors_1.CliError(`${config} not found.`);
26
+ }
27
+ else if (fs_1.default.existsSync(path_1.default.join(root, "tsconfig.build.json"))) {
28
+ config = path_1.default.join(root, "tsconfig.build.json");
29
+ }
30
+ else if (fs_1.default.existsSync(path_1.default.join(root, "tsconfig.json"))) {
31
+ config = path_1.default.join(root, "tsconfig.json");
32
+ log_1.log.warn("tsconfig.build.json not found; building with tsconfig.json.");
33
+ }
34
+ else {
35
+ throw new errors_1.CliError(`No tsconfig.build.json or tsconfig.json found in ${root}.`);
36
+ }
37
+ const tsc = (0, process_1.findTsc)(root);
38
+ if (!tsc)
39
+ throw new errors_1.CliError("TypeScript is not installed in this project. Run `npm install -D typescript`.");
40
+ const configLayout = layoutOf(config, root);
41
+ fs_1.default.rmSync(configLayout.outDir, { recursive: true, force: true });
42
+ if (!opts.quiet)
43
+ log_1.log.info(`Compiling with ${path_1.default.relative(root, config)}...`);
44
+ const code = await (0, process_1.runNode)(tsc, ["--project", config], root);
45
+ if (code !== 0)
46
+ throw new errors_1.CliError(`Build failed: tsc exited with code ${code}.`, code || 1);
47
+ // tsc mirrors rootDir (or the common source root) into outDir.
48
+ const nestedOut = path_1.default.join(configLayout.outDir, path_1.default.relative(root, configLayout.srcDir));
49
+ const assetOut = !configLayout.explicitRootDir && fs_1.default.existsSync(nestedOut) ? nestedOut : configLayout.outDir;
50
+ const copied = (0, project_1.copyAssets)(configLayout.srcDir, assetOut);
51
+ if (!opts.quiet) {
52
+ if (copied)
53
+ log_1.log.info(`Copied ${copied} asset file(s) to ${path_1.default.relative(root, assetOut)}.`);
54
+ log_1.log.success("Build complete.");
55
+ }
56
+ return configLayout.outDir;
57
+ }
58
+ function layoutOf(config, root) {
59
+ const opts = (0, tsconfig_1.readTsConfig)(config).compilerOptions;
60
+ return {
61
+ outDir: opts.outDir ?? path_1.default.join(root, "dist"),
62
+ srcDir: opts.rootDir ?? path_1.default.join(root, "src"),
63
+ explicitRootDir: typeof opts.rootDir === "string",
64
+ };
65
+ }
@@ -0,0 +1,10 @@
1
+ export type CheckStatus = "ok" | "warn" | "fail";
2
+ export type Check = {
3
+ name: string;
4
+ status: CheckStatus;
5
+ detail: string;
6
+ };
7
+ /** Run the environment checks. Pure apart from reading files, so it is easy to test. */
8
+ export declare function runChecks(cwd: string, nodeVersion?: string): Check[];
9
+ /** Print the checks and return the exit code: 1 if any check failed. */
10
+ export declare function doctor(cwd?: string): number;
@@ -0,0 +1,96 @@
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.runChecks = runChecks;
7
+ exports.doctor = doctor;
8
+ const path_1 = __importDefault(require("path"));
9
+ const log_1 = require("../utils/log");
10
+ const project_1 = require("../utils/project");
11
+ const stubs_1 = require("../utils/stubs");
12
+ const tsconfig_1 = require("../utils/tsconfig");
13
+ const MIN_NODE_MAJOR = 20;
14
+ const major = (v) => Number(v.replace(/^[^\d]*/, "").split(".")[0]);
15
+ const minor = (v) => Number(v.replace(/^[^\d]*/, "").split(".")[1] ?? 0);
16
+ /** Run the environment checks. Pure apart from reading files, so it is easy to test. */
17
+ function runChecks(cwd, nodeVersion = process.versions.node) {
18
+ const checks = [];
19
+ const cli = (0, stubs_1.cliVersion)();
20
+ checks.push({
21
+ name: "Node.js",
22
+ status: major(nodeVersion) >= MIN_NODE_MAJOR ? "ok" : "fail",
23
+ detail: `v${nodeVersion} (requires >=${MIN_NODE_MAJOR})`,
24
+ });
25
+ checks.push({ name: "@meghjs/cli", status: "ok", detail: `v${cli}` });
26
+ const root = (0, project_1.findProjectRoot)(cwd);
27
+ if (!root) {
28
+ checks.push({
29
+ name: "Project",
30
+ status: "fail",
31
+ detail: `no package.json found in ${path_1.default.resolve(cwd)} or its parents`,
32
+ });
33
+ return checks;
34
+ }
35
+ checks.push({ name: "Project", status: "ok", detail: root });
36
+ const core = (0, project_1.installedVersion)("@meghjs/core", root);
37
+ if (!core) {
38
+ checks.push({ name: "@meghjs/core", status: "fail", detail: "not installed (npm install @meghjs/core)" });
39
+ }
40
+ else if (major(core) !== major(cli)) {
41
+ checks.push({
42
+ name: "@meghjs/core",
43
+ status: "fail",
44
+ detail: `v${core} does not match CLI v${cli} (major versions must match)`,
45
+ });
46
+ }
47
+ else if (minor(core) !== minor(cli)) {
48
+ checks.push({ name: "@meghjs/core", status: "warn", detail: `v${core}, CLI is v${cli} (minor versions differ)` });
49
+ }
50
+ else {
51
+ checks.push({ name: "@meghjs/core", status: "ok", detail: `v${core} (matches CLI)` });
52
+ }
53
+ const reflect = (0, project_1.installedVersion)("reflect-metadata", root);
54
+ checks.push(reflect
55
+ ? { name: "reflect-metadata", status: "ok", detail: `v${reflect}` }
56
+ : { name: "reflect-metadata", status: "fail", detail: "not installed (npm install reflect-metadata)" });
57
+ const tsconfig = (0, tsconfig_1.findTsConfig)(root);
58
+ if (!tsconfig) {
59
+ checks.push({ name: "tsconfig.json", status: "fail", detail: "not found" });
60
+ }
61
+ else {
62
+ let opts = null;
63
+ try {
64
+ opts = (0, tsconfig_1.readTsConfig)(tsconfig).compilerOptions;
65
+ }
66
+ catch (err) {
67
+ checks.push({ name: "tsconfig.json", status: "fail", detail: `cannot parse: ${err.message}` });
68
+ }
69
+ if (opts) {
70
+ for (const flag of ["experimentalDecorators", "emitDecoratorMetadata"]) {
71
+ checks.push({
72
+ name: flag,
73
+ status: opts[flag] === true ? "ok" : "fail",
74
+ detail: opts[flag] === true ? "enabled" : `set "${flag}": true in compilerOptions`,
75
+ });
76
+ }
77
+ }
78
+ }
79
+ return checks;
80
+ }
81
+ /** Print the checks and return the exit code: 1 if any check failed. */
82
+ function doctor(cwd = process.cwd()) {
83
+ const checks = runChecks(cwd);
84
+ const marks = { ok: log_1.icon.success, warn: log_1.icon.warn, fail: log_1.icon.error };
85
+ for (const check of checks) {
86
+ console.log(`${marks[check.status]} ${check.name.padEnd(24)}${log_1.c.dim(check.detail)}`);
87
+ }
88
+ const failed = checks.filter((x) => x.status === "fail").length;
89
+ const warned = checks.filter((x) => x.status === "warn").length;
90
+ console.log();
91
+ if (failed)
92
+ console.log(log_1.c.red(`${failed} check(s) failed${warned ? `, ${warned} warning(s)` : ""}.`));
93
+ else
94
+ console.log(log_1.c.green(`All checks passed${warned ? ` with ${warned} warning(s)` : ""}.`));
95
+ return failed ? 1 : 0;
96
+ }
@@ -0,0 +1,32 @@
1
+ export declare const DEFAULT_CONNECTION = "src/database/connection.ts";
2
+ export declare const DEFAULT_MIGRATIONS = "src/database/migrations";
3
+ export type DatabasePaths = {
4
+ /** Module exporting the app's Kysely instance (`default` or `db`). */
5
+ connection: string;
6
+ /** Folder of migration files. */
7
+ migrations: string;
8
+ };
9
+ /** `megh.database` / `megh.migrations` from package.json, else the defaults. */
10
+ export declare function databasePaths(root: string, pkg?: Record<string, any>): DatabasePaths;
11
+ export type MigrateAction = "latest" | "rollback" | "reset" | "refresh" | "status";
12
+ export type MigrateOptions = {
13
+ cwd?: string;
14
+ step?: number;
15
+ };
16
+ /** Run a migration action in a child process and return its result. */
17
+ export declare function runMigrations(action: MigrateAction, opts?: MigrateOptions): any;
18
+ export declare function migrate(opts?: MigrateOptions): string[];
19
+ export declare function migrateRollback(opts?: MigrateOptions): string[];
20
+ export declare function migrateReset(opts?: MigrateOptions): string[];
21
+ export declare function migrateRefresh(opts?: MigrateOptions): {
22
+ down: string[];
23
+ up: string[];
24
+ };
25
+ export type MigrationStatusRow = {
26
+ name: string;
27
+ executedAt: string | null;
28
+ };
29
+ export declare function formatStatus(rows: MigrationStatusRow[]): string;
30
+ export declare function migrateStatus(opts?: MigrateOptions & {
31
+ json?: boolean;
32
+ }): MigrationStatusRow[];
@@ -0,0 +1,177 @@
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.DEFAULT_MIGRATIONS = exports.DEFAULT_CONNECTION = void 0;
7
+ exports.databasePaths = databasePaths;
8
+ exports.runMigrations = runMigrations;
9
+ exports.migrate = migrate;
10
+ exports.migrateRollback = migrateRollback;
11
+ exports.migrateReset = migrateReset;
12
+ exports.migrateRefresh = migrateRefresh;
13
+ exports.formatStatus = formatStatus;
14
+ exports.migrateStatus = migrateStatus;
15
+ const child_process_1 = require("child_process");
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const path_1 = __importDefault(require("path"));
18
+ const compiler_1 = require("../compiler");
19
+ const errors_1 = require("../errors");
20
+ const entry_1 = require("../utils/entry");
21
+ const log_1 = require("../utils/log");
22
+ const project_1 = require("../utils/project");
23
+ exports.DEFAULT_CONNECTION = "src/database/connection.ts";
24
+ exports.DEFAULT_MIGRATIONS = "src/database/migrations";
25
+ /** `megh.database` / `megh.migrations` from package.json, else the defaults. */
26
+ function databasePaths(root, pkg = (0, project_1.readPackageJson)(root)) {
27
+ const conf = pkg?.megh ?? {};
28
+ return {
29
+ connection: path_1.default.resolve(root, typeof conf.database === "string" ? conf.database : exports.DEFAULT_CONNECTION),
30
+ migrations: path_1.default.resolve(root, typeof conf.migrations === "string" ? conf.migrations : exports.DEFAULT_MIGRATIONS),
31
+ };
32
+ }
33
+ const MARKER = "__MEGH_MIGRATE__";
34
+ /**
35
+ * Runs in a child process: loads `.env`, the compiled connection module and
36
+ * @meghjs/core from the project, runs the action, prints the result as JSON
37
+ * after MARKER and closes the connection.
38
+ */
39
+ const WORKER = `
40
+ const fs = require("fs");
41
+ const path = require("path");
42
+ const [root, connection, folder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
43
+ const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(value));
44
+ (async () => {
45
+ let db;
46
+ try {
47
+ const env = path.join(root, ".env");
48
+ if (fs.existsSync(env) && typeof process.loadEnvFile === "function") process.loadEnvFile(env);
49
+ let core;
50
+ try { core = require(require.resolve("@meghjs/core", { paths: [root] })); }
51
+ catch { throw new Error("@meghjs/core is not installed in this project."); }
52
+ if (typeof core.Migrations !== "function") throw new Error("This @meghjs/core version has no migrations; upgrade it.");
53
+ const mod = require(connection);
54
+ db = mod && (mod.default || mod.db);
55
+ if (!db || typeof db.schema !== "object" || typeof db.destroy !== "function") {
56
+ throw new Error("The connection module must export a Kysely instance as its default export or as \`db\`.");
57
+ }
58
+ const migrations = new core.Migrations(db, { folder });
59
+ send({ ok: true, result: await migrations[action](...args) });
60
+ } catch (e) {
61
+ send({ ok: false, error: (e && e.message) || String(e), completed: (e && e.completed) || [] });
62
+ } finally {
63
+ if (db) await db.destroy().catch(() => {});
64
+ process.exit(0);
65
+ }
66
+ })();
67
+ `;
68
+ function compiled(root) {
69
+ const layout = (0, entry_1.projectLayout)(root);
70
+ const paths = databasePaths(root);
71
+ const rel = (p) => path_1.default.relative(root, p).split(path_1.default.sep).join("/");
72
+ if (!fs_1.default.existsSync(paths.connection)) {
73
+ throw new errors_1.CliError(`No database connection module at ${rel(paths.connection)}.\n` +
74
+ "Create it and export your Kysely instance (export default db), or point " +
75
+ '"megh.database" in package.json at it.');
76
+ }
77
+ const cacheDir = path_1.default.join(root, "node_modules", ".cache", "megh", "migrate");
78
+ fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
79
+ const inside = (dir, file) => {
80
+ const r = path_1.default.relative(dir, file);
81
+ return !r.startsWith("..") && !path_1.default.isAbsolute(r);
82
+ };
83
+ const app = new compiler_1.SwcCompiler(layout.srcDir, path_1.default.join(cacheDir, "app"), layout.compilerOptions);
84
+ const failures = app.compileAll();
85
+ // Migrations outside the source folder are compiled on their own.
86
+ const migrationsCompiler = inside(layout.srcDir, paths.migrations)
87
+ ? app
88
+ : new compiler_1.SwcCompiler(paths.migrations, path_1.default.join(cacheDir, "migrations"), layout.compilerOptions);
89
+ if (migrationsCompiler !== app) {
90
+ for (const [file, error] of migrationsCompiler.compileAll())
91
+ failures.set(file, error);
92
+ }
93
+ if (failures.size) {
94
+ const list = [...failures].map(([f, e]) => `${rel(f)}: ${e.split("\n")[0]}`).join("\n ");
95
+ throw new errors_1.CliError(`Compilation failed:\n ${list}`);
96
+ }
97
+ if (!inside(layout.srcDir, paths.connection)) {
98
+ throw new errors_1.CliError(`The connection module ${rel(paths.connection)} must be inside ${rel(layout.srcDir)}/.`);
99
+ }
100
+ return {
101
+ connection: app.outFileFor(paths.connection),
102
+ // outFileFor maps a file; map a placeholder inside the folder and take its directory.
103
+ migrations: path_1.default.dirname(migrationsCompiler.outFileFor(path_1.default.join(paths.migrations, "x.ts"))),
104
+ };
105
+ }
106
+ /** Run a migration action in a child process and return its result. */
107
+ function runMigrations(action, opts = {}) {
108
+ const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
109
+ const files = compiled(root);
110
+ const args = action === "rollback" ? [opts.step ?? 1] : [];
111
+ const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.migrations, action, args])], {
112
+ cwd: root,
113
+ encoding: "utf8",
114
+ env: { ...process.env, NODE_ENV: process.env.NODE_ENV ?? "development" },
115
+ maxBuffer: 64 * 1024 * 1024,
116
+ });
117
+ // Anything the app logs while loading is passed through.
118
+ const lines = (result.stdout ?? "").split(/\r?\n/);
119
+ const line = lines.find((l) => l.startsWith(MARKER));
120
+ for (const l of lines)
121
+ if (l && !l.startsWith(MARKER))
122
+ console.log(l);
123
+ if (!line) {
124
+ throw new errors_1.CliError(`Could not run migrations:\n${result.stderr || result.stdout || result.error?.message}`);
125
+ }
126
+ const out = JSON.parse(line.slice(MARKER.length));
127
+ if (!out.ok) {
128
+ const done = out.completed.length ? `\nCompleted before the failure:\n ${out.completed.join("\n ")}` : "";
129
+ throw new errors_1.CliError(`${out.error}${done}`);
130
+ }
131
+ return out.result;
132
+ }
133
+ function list(names, verb, empty) {
134
+ if (names.length === 0) {
135
+ log_1.log.info(empty);
136
+ return;
137
+ }
138
+ for (const name of names)
139
+ log_1.log.success(`${verb} ${name}`);
140
+ }
141
+ function migrate(opts = {}) {
142
+ const names = runMigrations("latest", opts);
143
+ list(names, "Migrated:", "Nothing to migrate.");
144
+ return names;
145
+ }
146
+ function migrateRollback(opts = {}) {
147
+ const names = runMigrations("rollback", opts);
148
+ list(names, "Rolled back:", "Nothing to roll back.");
149
+ return names;
150
+ }
151
+ function migrateReset(opts = {}) {
152
+ const names = runMigrations("reset", opts);
153
+ list(names, "Rolled back:", "Nothing to roll back.");
154
+ return names;
155
+ }
156
+ function migrateRefresh(opts = {}) {
157
+ const result = runMigrations("refresh", opts);
158
+ list(result.down, "Rolled back:", "Nothing to roll back.");
159
+ list(result.up, "Migrated:", "Nothing to migrate.");
160
+ return result;
161
+ }
162
+ function formatStatus(rows) {
163
+ if (rows.length === 0)
164
+ return "No migrations found.";
165
+ const width = Math.max("MIGRATION".length, ...rows.map((r) => r.name.length));
166
+ const head = log_1.c.bold(`${"RAN".padEnd(5)}${"MIGRATION".padEnd(width + 2)}EXECUTED AT`);
167
+ // Pad before coloring: color codes would count towards the width.
168
+ const body = rows.map((r) => (r.executedAt ? log_1.c.green("✔".padEnd(5)) : log_1.c.yellow("·".padEnd(5))) +
169
+ r.name.padEnd(width + 2) +
170
+ (r.executedAt ? new Date(r.executedAt).toISOString() : log_1.c.dim("pending")));
171
+ return [head, ...body].join("\n");
172
+ }
173
+ function migrateStatus(opts = {}) {
174
+ const rows = runMigrations("status", opts);
175
+ console.log(opts.json ? JSON.stringify(rows, null, 2) : formatStatus(rows));
176
+ return rows;
177
+ }
@@ -0,0 +1,19 @@
1
+ export declare const PACKAGE_MANAGERS: readonly ["npm", "yarn", "pnpm"];
2
+ export type PackageManager = (typeof PACKAGE_MANAGERS)[number];
3
+ export declare const FEATURES: readonly ["openapi", "cors", "typeorm", "knex", "scalar"];
4
+ export type Feature = (typeof FEATURES)[number];
5
+ export type NewOptions = {
6
+ cwd?: string;
7
+ minimal?: boolean;
8
+ force?: boolean;
9
+ /** Skip prompts and use defaults for anything not given. */
10
+ yes?: boolean;
11
+ pm?: string;
12
+ features?: string[];
13
+ /** Skip `<pm> install`. Also enabled by the `MEGH_SKIP_INSTALL=1` environment variable. */
14
+ skipInstall?: boolean;
15
+ };
16
+ export declare function packageJson(name: string, features: Feature[], minimal: boolean): string;
17
+ export declare function installCommand(pm: PackageManager): string;
18
+ export declare function devCommand(pm: PackageManager): string;
19
+ export declare function createApplication(name: string, opts?: NewOptions): Promise<string>;