@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.
- package/LICENSE +21 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +10 -0
- package/dist/commands/build.d.ts +11 -0
- package/dist/commands/build.js +65 -0
- package/dist/commands/doctor.d.ts +10 -0
- package/dist/commands/doctor.js +96 -0
- package/dist/commands/migrate.d.ts +32 -0
- package/dist/commands/migrate.js +177 -0
- package/dist/commands/new.d.ts +19 -0
- package/dist/commands/new.js +306 -0
- package/dist/commands/route-list.d.ts +19 -0
- package/dist/commands/route-list.js +160 -0
- package/dist/commands/serve.d.ts +17 -0
- package/dist/commands/serve.js +238 -0
- package/dist/commands/start.d.ts +10 -0
- package/dist/commands/start.js +43 -0
- package/dist/compiler.d.ts +24 -0
- package/dist/compiler.js +83 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +16 -0
- package/dist/generators/make.d.ts +40 -0
- package/dist/generators/make.js +198 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +42 -0
- package/dist/program.d.ts +22 -0
- package/dist/program.js +211 -0
- package/dist/utils/entry.d.ts +15 -0
- package/dist/utils/entry.js +55 -0
- package/dist/utils/env-types.d.ts +8 -0
- package/dist/utils/env-types.js +19 -0
- package/dist/utils/log.d.ts +25 -0
- package/dist/utils/log.js +39 -0
- package/dist/utils/names.d.ts +27 -0
- package/dist/utils/names.js +58 -0
- package/dist/utils/process.d.ts +18 -0
- package/dist/utils/process.js +84 -0
- package/dist/utils/project.d.ts +17 -0
- package/dist/utils/project.js +91 -0
- package/dist/utils/stubs.d.ts +15 -0
- package/dist/utils/stubs.js +52 -0
- package/dist/utils/tsconfig.d.ts +13 -0
- package/dist/utils/tsconfig.js +102 -0
- package/package.json +61 -4
- package/readme.md +155 -0
- package/stubs/config/config.stub +9 -0
- package/stubs/controllers/basic-controller.stub +9 -0
- package/stubs/controllers/resource-controller.stub +45 -0
- package/stubs/controllers/rest-controller.stub +29 -0
- package/stubs/dtos/dto.stub +11 -0
- package/stubs/middlewares/middleware.stub +9 -0
- package/stubs/migrations/alter-table.stub +9 -0
- package/stubs/migrations/create-table.stub +15 -0
- package/stubs/migrations/migration.stub +9 -0
- package/stubs/models/basic-model.stub +4 -0
- package/stubs/models/entity-model.stub +16 -0
- package/stubs/project/app-minimal.stub +7 -0
- package/stubs/project/app.stub +8 -0
- package/stubs/project/env.stub +3 -0
- package/stubs/project/gitignore.stub +5 -0
- package/stubs/project/home.controller.spec.stub +19 -0
- package/stubs/project/home.controller.stub +12 -0
- package/stubs/project/home.service.stub +8 -0
- package/stubs/project/openapi.config.stub +15 -0
- package/stubs/project/readme.stub +26 -0
- package/stubs/project/serve.stub +10 -0
- package/stubs/project/tsconfig.build.stub +4 -0
- package/stubs/project/tsconfig.stub +18 -0
- package/stubs/project/vitest-e2e.config.stub +10 -0
- package/stubs/project/vitest.config.stub +17 -0
- package/stubs/services/basic-service.stub +8 -0
- package/stubs/services/orm-rest-service.stub +61 -0
- package/stubs/services/rest-service.stub +34 -0
- package/README.md +0 -3
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.FEATURES = exports.PACKAGE_MANAGERS = void 0;
|
|
40
|
+
exports.packageJson = packageJson;
|
|
41
|
+
exports.installCommand = installCommand;
|
|
42
|
+
exports.devCommand = devCommand;
|
|
43
|
+
exports.createApplication = createApplication;
|
|
44
|
+
const child_process_1 = require("child_process");
|
|
45
|
+
const fs_1 = __importDefault(require("fs"));
|
|
46
|
+
const path_1 = __importDefault(require("path"));
|
|
47
|
+
const errors_1 = require("../errors");
|
|
48
|
+
const log_1 = require("../utils/log");
|
|
49
|
+
const names_1 = require("../utils/names");
|
|
50
|
+
const stubs_1 = require("../utils/stubs");
|
|
51
|
+
const env_types_1 = require("../utils/env-types");
|
|
52
|
+
exports.PACKAGE_MANAGERS = ["npm", "yarn", "pnpm"];
|
|
53
|
+
exports.FEATURES = ["openapi", "cors", "typeorm", "knex", "scalar"];
|
|
54
|
+
const DEFAULT_FEATURES = ["openapi"];
|
|
55
|
+
/** Third-party versions for generated projects. */
|
|
56
|
+
const DEP_VERSIONS = {
|
|
57
|
+
"class-transformer": "^0.5.1",
|
|
58
|
+
"class-validator": "^0.14.2",
|
|
59
|
+
"reflect-metadata": "^0.2.2",
|
|
60
|
+
"@fastify/cors": "^11.0.0",
|
|
61
|
+
typeorm: "^0.3.20",
|
|
62
|
+
pg: "^8.11.0",
|
|
63
|
+
knex: "^3.1.0",
|
|
64
|
+
"@scalar/fastify-api-reference": "^1.0.0",
|
|
65
|
+
typescript: "^5.7.2",
|
|
66
|
+
"@types/node": "^22.9.3",
|
|
67
|
+
vitest: "^4.1.12",
|
|
68
|
+
"@vitest/coverage-v8": "^4.1.12",
|
|
69
|
+
"unplugin-swc": "^2.0.0",
|
|
70
|
+
"@swc/core": "^1.16.20",
|
|
71
|
+
};
|
|
72
|
+
function isDirEmpty(dir) {
|
|
73
|
+
return fs_1.default.readdirSync(dir).length === 0;
|
|
74
|
+
}
|
|
75
|
+
function validateFeatures(features) {
|
|
76
|
+
const unknown = features.filter((f) => !exports.FEATURES.includes(f));
|
|
77
|
+
if (unknown.length) {
|
|
78
|
+
throw new errors_1.CliError(`Unknown feature(s): ${unknown.join(", ")}. Choose from: ${exports.FEATURES.join(", ")}.`);
|
|
79
|
+
}
|
|
80
|
+
return features;
|
|
81
|
+
}
|
|
82
|
+
async function prompt(opts) {
|
|
83
|
+
if (opts.pm && !exports.PACKAGE_MANAGERS.includes(opts.pm)) {
|
|
84
|
+
throw new errors_1.CliError(`Unknown package manager "${opts.pm}". Choose from: ${exports.PACKAGE_MANAGERS.join(", ")}.`);
|
|
85
|
+
}
|
|
86
|
+
const interactive = !opts.yes && process.stdin.isTTY === true && process.stdout.isTTY === true;
|
|
87
|
+
let pm = opts.pm;
|
|
88
|
+
let features = opts.features ? validateFeatures(opts.features) : undefined;
|
|
89
|
+
if (opts.minimal)
|
|
90
|
+
features = [];
|
|
91
|
+
if (interactive && (!pm || !features)) {
|
|
92
|
+
const { default: inquirer } = await Promise.resolve().then(() => __importStar(require("inquirer")));
|
|
93
|
+
if (!pm) {
|
|
94
|
+
({ pm } = await inquirer.prompt([
|
|
95
|
+
{
|
|
96
|
+
type: "list",
|
|
97
|
+
name: "pm",
|
|
98
|
+
message: "Package manager:",
|
|
99
|
+
choices: [...exports.PACKAGE_MANAGERS],
|
|
100
|
+
default: "npm",
|
|
101
|
+
},
|
|
102
|
+
]));
|
|
103
|
+
}
|
|
104
|
+
if (!features) {
|
|
105
|
+
({ features } = await inquirer.prompt([
|
|
106
|
+
{
|
|
107
|
+
type: "checkbox",
|
|
108
|
+
name: "features",
|
|
109
|
+
message: "Select features to include:",
|
|
110
|
+
choices: [
|
|
111
|
+
{ name: "OpenAPI / Swagger docs", value: "openapi", checked: true },
|
|
112
|
+
{ name: "CORS support", value: "cors" },
|
|
113
|
+
{ name: "TypeORM", value: "typeorm" },
|
|
114
|
+
{ name: "Knex", value: "knex" },
|
|
115
|
+
{ name: "Scalar UI (replaces Swagger UI)", value: "scalar" },
|
|
116
|
+
],
|
|
117
|
+
},
|
|
118
|
+
]));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { pm: pm ?? "npm", features: features ?? DEFAULT_FEATURES };
|
|
122
|
+
}
|
|
123
|
+
function packageJson(name, features, minimal) {
|
|
124
|
+
const v = (0, stubs_1.cliVersion)();
|
|
125
|
+
const deps = {
|
|
126
|
+
"@meghjs/core": (0, stubs_1.coreRange)(),
|
|
127
|
+
"@meghjs/cli": `^${v}`,
|
|
128
|
+
};
|
|
129
|
+
const pick = (...names) => names.forEach((n) => (deps[n] = DEP_VERSIONS[n]));
|
|
130
|
+
pick("class-transformer", "class-validator", "reflect-metadata");
|
|
131
|
+
if (features.includes("cors"))
|
|
132
|
+
pick("@fastify/cors");
|
|
133
|
+
if (usesData(features))
|
|
134
|
+
deps["@meghjs/data"] = `^${v}`;
|
|
135
|
+
if (features.includes("typeorm"))
|
|
136
|
+
pick("typeorm", "pg");
|
|
137
|
+
if (features.includes("knex"))
|
|
138
|
+
pick("knex", "pg");
|
|
139
|
+
if (features.includes("scalar"))
|
|
140
|
+
pick("@scalar/fastify-api-reference");
|
|
141
|
+
const devDeps = {};
|
|
142
|
+
const pickDev = (...names) => names.forEach((n) => (devDeps[n] = DEP_VERSIONS[n]));
|
|
143
|
+
pickDev("@types/node", "typescript");
|
|
144
|
+
if (!minimal)
|
|
145
|
+
pickDev("@swc/core", "@vitest/coverage-v8", "unplugin-swc", "vitest");
|
|
146
|
+
const scripts = {
|
|
147
|
+
"start:dev": "megh serve",
|
|
148
|
+
build: "megh build",
|
|
149
|
+
start: "megh start",
|
|
150
|
+
};
|
|
151
|
+
if (!minimal) {
|
|
152
|
+
Object.assign(scripts, {
|
|
153
|
+
test: "vitest run",
|
|
154
|
+
"test:watch": "vitest",
|
|
155
|
+
"test:cov": "vitest run --coverage",
|
|
156
|
+
"test:e2e": "vitest run --config vitest.e2e.config.mts",
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
const pkg = {
|
|
160
|
+
name: (0, names_1.kebabCase)(name) || "megh-app",
|
|
161
|
+
version: "0.0.1",
|
|
162
|
+
private: true,
|
|
163
|
+
description: `${(0, names_1.titleCase)(name)} API built with Megh`,
|
|
164
|
+
main: "dist/serve.js",
|
|
165
|
+
scripts,
|
|
166
|
+
keywords: ["megh", "nodejs", "typescript"],
|
|
167
|
+
engines: { node: ">=20" },
|
|
168
|
+
dependencies: sortKeys(deps),
|
|
169
|
+
devDependencies: sortKeys(devDeps),
|
|
170
|
+
};
|
|
171
|
+
return JSON.stringify(pkg, null, 2) + "\n";
|
|
172
|
+
}
|
|
173
|
+
/** TypeORM and Knex come from the @meghjs/data plugin. */
|
|
174
|
+
function usesData(features) {
|
|
175
|
+
return features.includes("typeorm") || features.includes("knex");
|
|
176
|
+
}
|
|
177
|
+
function sortKeys(obj) {
|
|
178
|
+
return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
|
|
179
|
+
}
|
|
180
|
+
function appSource(features) {
|
|
181
|
+
const imports = [];
|
|
182
|
+
const setup = [];
|
|
183
|
+
if (features.includes("openapi") || features.includes("scalar")) {
|
|
184
|
+
imports.push(`import { OpenApiConfig } from './config/openapi.config';`);
|
|
185
|
+
}
|
|
186
|
+
if (features.includes("cors"))
|
|
187
|
+
setup.push(`app.useCors({ origin: '*' });`);
|
|
188
|
+
if (imports.length)
|
|
189
|
+
setup.push(`if (app.isDevelopment()) {\n app.useOpenApi(OpenApiConfig);\n}`);
|
|
190
|
+
if (features.includes("typeorm")) {
|
|
191
|
+
setup.push(`// TODO: pass your TypeORM DataSourceOptions (or an @AppConfig class)\n` +
|
|
192
|
+
`// await app.useTypeORM({ type: 'postgres', url: process.env.DATABASE_URL, entities: [] });`);
|
|
193
|
+
}
|
|
194
|
+
if (features.includes("knex")) {
|
|
195
|
+
setup.push(`// TODO: pass your Knex config (or an @AppConfig class)\n` +
|
|
196
|
+
`// await app.useKnex({ client: 'pg', connection: process.env.DATABASE_URL });`);
|
|
197
|
+
}
|
|
198
|
+
return (0, stubs_1.renderStub)("project/app.stub", {
|
|
199
|
+
Imports: imports.map((i) => i + "\n").join(""),
|
|
200
|
+
Setup: setup.map((s) => "\n" + s + "\n").join(""),
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
function installCommand(pm) {
|
|
204
|
+
return `${pm} install`;
|
|
205
|
+
}
|
|
206
|
+
function devCommand(pm) {
|
|
207
|
+
return pm === "npm" ? "npm run start:dev" : `${pm} start:dev`;
|
|
208
|
+
}
|
|
209
|
+
function runInstall(pm, cwd) {
|
|
210
|
+
return new Promise((resolve, reject) => {
|
|
211
|
+
const child = (0, child_process_1.spawn)(pm, ["install"], { cwd, stdio: "inherit", shell: process.platform === "win32" });
|
|
212
|
+
child.on("error", reject);
|
|
213
|
+
child.on("exit", (code) => (code === 0 ? resolve() : reject(new Error(`${pm} install exited with code ${code}`))));
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
async function createApplication(name, opts = {}) {
|
|
217
|
+
if (!name || !name.trim())
|
|
218
|
+
throw new errors_1.CliError("Please provide a project name, e.g. `megh new my-api`.");
|
|
219
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
220
|
+
const root = path_1.default.resolve(cwd, name);
|
|
221
|
+
const appName = path_1.default.basename(root);
|
|
222
|
+
const minimal = !!opts.minimal;
|
|
223
|
+
if (fs_1.default.existsSync(root)) {
|
|
224
|
+
if (!fs_1.default.statSync(root).isDirectory())
|
|
225
|
+
throw new errors_1.CliError(`${root} exists and is not a directory.`);
|
|
226
|
+
if (!isDirEmpty(root) && !opts.force) {
|
|
227
|
+
throw new errors_1.CliError(`Directory ${root} is not empty. Use -f or --force to scaffold into it anyway.`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const { pm, features } = await prompt(opts);
|
|
231
|
+
console.log();
|
|
232
|
+
console.log(log_1.c.bold(log_1.c.cyan(" Megh")) + log_1.c.dim(` v${(0, stubs_1.cliVersion)()}`));
|
|
233
|
+
console.log(` ${log_1.c.dim("Creating project:")} ${log_1.c.bold(appName)}${minimal ? log_1.c.dim(" (minimal)") : ""}`);
|
|
234
|
+
const rel = (f) => path_1.default.relative(cwd, f) || ".";
|
|
235
|
+
const files = [];
|
|
236
|
+
const add = (file, content) => files.push([path_1.default.join(root, file), content]);
|
|
237
|
+
if (minimal) {
|
|
238
|
+
add("src/app.ts", (0, stubs_1.renderStub)("project/app-minimal.stub"));
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
add("src/services/home.service.ts", (0, stubs_1.renderStub)("project/home.service.stub"));
|
|
242
|
+
add("src/controllers/home.controller.ts", (0, stubs_1.renderStub)("project/home.controller.stub"));
|
|
243
|
+
add("src/controllers/home.controller.spec.ts", (0, stubs_1.renderStub)("project/home.controller.spec.stub"));
|
|
244
|
+
if (features.includes("openapi") || features.includes("scalar")) {
|
|
245
|
+
add("src/config/openapi.config.ts", (0, stubs_1.renderStub)("project/openapi.config.stub", {
|
|
246
|
+
AppTitle: (0, names_1.titleCase)(appName) || appName,
|
|
247
|
+
Provider: features.includes("scalar") ? "\n provider: 'scalar'," : "",
|
|
248
|
+
}));
|
|
249
|
+
}
|
|
250
|
+
add("src/app.ts", appSource(features));
|
|
251
|
+
add("vitest.config.mts", (0, stubs_1.renderStub)("project/vitest.config.stub"));
|
|
252
|
+
add("vitest.e2e.config.mts", (0, stubs_1.renderStub)("project/vitest-e2e.config.stub"));
|
|
253
|
+
}
|
|
254
|
+
add("src/serve.ts", (0, stubs_1.renderStub)("project/serve.stub"));
|
|
255
|
+
add("package.json", packageJson(appName, features, minimal));
|
|
256
|
+
add("tsconfig.json", (0, stubs_1.renderStub)("project/tsconfig.stub"));
|
|
257
|
+
add(env_types_1.ENV_TYPES_FILE, (0, env_types_1.envTypesFile)(usesData(features) ? ["@meghjs/data"] : []));
|
|
258
|
+
add("tsconfig.build.json", (0, stubs_1.renderStub)("project/tsconfig.build.stub"));
|
|
259
|
+
add(".gitignore", (0, stubs_1.renderStub)("project/gitignore.stub"));
|
|
260
|
+
add(".env", (0, stubs_1.renderStub)("project/env.stub"));
|
|
261
|
+
add("README.md", (0, stubs_1.renderStub)("project/readme.stub", {
|
|
262
|
+
AppTitle: (0, names_1.titleCase)(appName) || appName,
|
|
263
|
+
InstallCmd: installCommand(pm),
|
|
264
|
+
DevCmd: devCommand(pm),
|
|
265
|
+
TestRow: minimal ? "" : "| `test` | Run unit tests |\n",
|
|
266
|
+
Tree: minimal
|
|
267
|
+
? ""
|
|
268
|
+
: "├── controllers/ # Route controllers\n├── services/ # Business logic\n├── config/ # App configuration\n",
|
|
269
|
+
}));
|
|
270
|
+
log_1.log.section("Generating files");
|
|
271
|
+
for (const [file, content] of files) {
|
|
272
|
+
fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
|
|
273
|
+
fs_1.default.writeFileSync(file, content, "utf8");
|
|
274
|
+
log_1.log.step(path_1.default.relative(root, file).split(path_1.default.sep).join("/"), "");
|
|
275
|
+
}
|
|
276
|
+
if (!minimal)
|
|
277
|
+
fs_1.default.mkdirSync(path_1.default.join(root, "public"), { recursive: true });
|
|
278
|
+
const skipInstall = opts.skipInstall || process.env.MEGH_SKIP_INSTALL === "1";
|
|
279
|
+
if (skipInstall) {
|
|
280
|
+
log_1.log.section("Skipping dependency install");
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
log_1.log.section(`Installing dependencies (${pm})`);
|
|
284
|
+
try {
|
|
285
|
+
await runInstall(pm, root);
|
|
286
|
+
log_1.log.success("Dependencies installed");
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
log_1.log.error(`Install failed: ${err instanceof Error ? err.message : err}`);
|
|
290
|
+
log_1.log.info(` Run it manually: cd ${rel(root)} && ${installCommand(pm)}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
console.log();
|
|
294
|
+
log_1.log.success(log_1.c.green("Project created."));
|
|
295
|
+
console.log(`\n ${log_1.c.dim("Next steps:")}`);
|
|
296
|
+
if (rel(root) !== ".")
|
|
297
|
+
console.log(log_1.c.cyan(` cd ${rel(root)}`));
|
|
298
|
+
if (skipInstall)
|
|
299
|
+
console.log(log_1.c.cyan(` ${installCommand(pm)}`));
|
|
300
|
+
console.log(log_1.c.cyan(` ${devCommand(pm)}`));
|
|
301
|
+
if (features.includes("openapi") || features.includes("scalar")) {
|
|
302
|
+
console.log(`\n ${log_1.c.dim("API docs:")} http://localhost:4000/docs`);
|
|
303
|
+
}
|
|
304
|
+
console.log();
|
|
305
|
+
return root;
|
|
306
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type Route = {
|
|
2
|
+
method: string;
|
|
3
|
+
path: string;
|
|
4
|
+
controller: string;
|
|
5
|
+
handler: string;
|
|
6
|
+
file: string;
|
|
7
|
+
};
|
|
8
|
+
export type RouteListOptions = {
|
|
9
|
+
cwd?: string;
|
|
10
|
+
json?: boolean;
|
|
11
|
+
static?: boolean;
|
|
12
|
+
};
|
|
13
|
+
export declare function joinRoute(...parts: string[]): string;
|
|
14
|
+
export declare function runtimeRoutes(root: string): Route[];
|
|
15
|
+
/** Scan `@ApiController` classes and their `@Get`/`@Post`/... methods without running any code. */
|
|
16
|
+
export declare function scanRoutes(source: string, file: string): Route[];
|
|
17
|
+
export declare function staticRoutes(root: string): Route[];
|
|
18
|
+
export declare function formatRoutes(routes: Route[]): string;
|
|
19
|
+
export declare function routeList(opts?: RouteListOptions): Route[];
|
|
@@ -0,0 +1,160 @@
|
|
|
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.joinRoute = joinRoute;
|
|
7
|
+
exports.runtimeRoutes = runtimeRoutes;
|
|
8
|
+
exports.scanRoutes = scanRoutes;
|
|
9
|
+
exports.staticRoutes = staticRoutes;
|
|
10
|
+
exports.formatRoutes = formatRoutes;
|
|
11
|
+
exports.routeList = routeList;
|
|
12
|
+
const child_process_1 = require("child_process");
|
|
13
|
+
const fs_1 = __importDefault(require("fs"));
|
|
14
|
+
const path_1 = __importDefault(require("path"));
|
|
15
|
+
const compiler_1 = require("../compiler");
|
|
16
|
+
const errors_1 = require("../errors");
|
|
17
|
+
const entry_1 = require("../utils/entry");
|
|
18
|
+
const log_1 = require("../utils/log");
|
|
19
|
+
const project_1 = require("../utils/project");
|
|
20
|
+
function joinRoute(...parts) {
|
|
21
|
+
const joined = "/" + parts.join("/");
|
|
22
|
+
const normalized = joined.replace(/\/{2,}/g, "/");
|
|
23
|
+
return normalized.length > 1 ? normalized.replace(/\/$/, "") : normalized;
|
|
24
|
+
}
|
|
25
|
+
function controllerFiles(srcDir) {
|
|
26
|
+
if (!fs_1.default.existsSync(srcDir))
|
|
27
|
+
return [];
|
|
28
|
+
return fs_1.default
|
|
29
|
+
.readdirSync(srcDir, { withFileTypes: true, recursive: true })
|
|
30
|
+
.filter((e) => e.isFile() && e.name.endsWith(".controller.ts"))
|
|
31
|
+
.map((e) => path_1.default.join(e.parentPath ?? e.path, e.name))
|
|
32
|
+
.sort();
|
|
33
|
+
}
|
|
34
|
+
// ── Runtime: compile, require, read Megh's route metadata ───────────────
|
|
35
|
+
const MARKER = "__MEGH_ROUTES__";
|
|
36
|
+
/**
|
|
37
|
+
* Runs in a child process (so the app's import side effects cannot affect the
|
|
38
|
+
* CLI). Requires each compiled controller and reads the metadata written by
|
|
39
|
+
* `@ApiController` (symbol "icontroller:options") and `@Get`/`@Post`/...
|
|
40
|
+
* ("route:method", "route:path").
|
|
41
|
+
*/
|
|
42
|
+
const WORKER = `
|
|
43
|
+
const files = JSON.parse(process.argv[process.argv.length - 1]);
|
|
44
|
+
const out = [];
|
|
45
|
+
const errors = [];
|
|
46
|
+
for (const [src, compiled] of files) {
|
|
47
|
+
let mod;
|
|
48
|
+
try { mod = require(compiled); } catch (e) { errors.push(src + ": " + (e && e.message || e)); continue; }
|
|
49
|
+
if (typeof Reflect.getOwnMetadataKeys !== "function") {
|
|
50
|
+
errors.push("reflect-metadata is not loaded; is @meghjs/core installed?");
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
for (const value of Object.values(mod)) {
|
|
54
|
+
if (typeof value !== "function") continue;
|
|
55
|
+
const key = Reflect.getOwnMetadataKeys(value).find(
|
|
56
|
+
(k) => typeof k === "symbol" && k.description === "icontroller:options");
|
|
57
|
+
if (!key) continue;
|
|
58
|
+
const meta = Reflect.getOwnMetadata(key, value) || {};
|
|
59
|
+
const proto = value.prototype;
|
|
60
|
+
for (const name of Object.getOwnPropertyNames(proto)) {
|
|
61
|
+
if (name === "constructor") continue;
|
|
62
|
+
const method = Reflect.getMetadata("route:method", proto, name);
|
|
63
|
+
if (!method) continue;
|
|
64
|
+
out.push({ controllerPath: meta.path || "/", method, path: Reflect.getMetadata("route:path", proto, name) || "/",
|
|
65
|
+
controller: value.name, handler: name, file: src });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
console.log(${JSON.stringify(MARKER)} + JSON.stringify({ routes: out, errors }));
|
|
70
|
+
process.exit(0);
|
|
71
|
+
`;
|
|
72
|
+
function runtimeRoutes(root) {
|
|
73
|
+
const layout = (0, entry_1.projectLayout)(root);
|
|
74
|
+
const cacheDir = path_1.default.join(root, "node_modules", ".cache", "megh", "route-list");
|
|
75
|
+
fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
|
|
76
|
+
const compiler = new compiler_1.SwcCompiler(layout.srcDir, cacheDir, layout.compilerOptions);
|
|
77
|
+
const failures = compiler.compileAll();
|
|
78
|
+
if (failures.size) {
|
|
79
|
+
const list = [...failures].map(([f, e]) => `${path_1.default.relative(root, f)}: ${e.split("\n")[0]}`).join("\n ");
|
|
80
|
+
throw new errors_1.CliError(`Compilation failed:\n ${list}`);
|
|
81
|
+
}
|
|
82
|
+
const files = controllerFiles(layout.srcDir).map((f) => [path_1.default.relative(root, f), compiler.outFileFor(f)]);
|
|
83
|
+
if (!files.length)
|
|
84
|
+
return [];
|
|
85
|
+
const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify(files)], {
|
|
86
|
+
cwd: root,
|
|
87
|
+
encoding: "utf8",
|
|
88
|
+
env: { ...process.env, NODE_ENV: process.env.NODE_ENV ?? "development" },
|
|
89
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
90
|
+
});
|
|
91
|
+
const line = (result.stdout ?? "").split(/\r?\n/).find((l) => l.startsWith(MARKER));
|
|
92
|
+
if (!line) {
|
|
93
|
+
throw new errors_1.CliError(`Could not load controllers:\n${result.stderr || result.stdout || result.error?.message}`);
|
|
94
|
+
}
|
|
95
|
+
const { routes, errors } = JSON.parse(line.slice(MARKER.length));
|
|
96
|
+
if (errors.length) {
|
|
97
|
+
throw new errors_1.CliError(`Could not load controllers:\n ${errors.join("\n ")}\nTry --static to scan the source instead.`);
|
|
98
|
+
}
|
|
99
|
+
return routes.map((r) => ({
|
|
100
|
+
method: String(r.method).toUpperCase(),
|
|
101
|
+
path: joinRoute(r.controllerPath, r.path),
|
|
102
|
+
controller: r.controller,
|
|
103
|
+
handler: r.handler,
|
|
104
|
+
file: r.file.split(path_1.default.sep).join("/"),
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
// ── Static: scan decorators in the source ─────────────────────────────────
|
|
108
|
+
const STRING = /^\s*(['"`])((?:(?!\1).)*)\1/;
|
|
109
|
+
function decoratorPath(args) {
|
|
110
|
+
if (!args)
|
|
111
|
+
return "/";
|
|
112
|
+
const literal = args.match(STRING);
|
|
113
|
+
if (literal)
|
|
114
|
+
return literal[2] || "/";
|
|
115
|
+
const objPath = args.match(/path\s*:\s*(['"`])((?:(?!\1).)*)\1/);
|
|
116
|
+
return objPath ? objPath[2] : "/";
|
|
117
|
+
}
|
|
118
|
+
/** Scan `@ApiController` classes and their `@Get`/`@Post`/... methods without running any code. */
|
|
119
|
+
function scanRoutes(source, file) {
|
|
120
|
+
const routes = [];
|
|
121
|
+
const ctrlRe = /@ApiController\b(?:\s*\(([^)]*)\))?[\s\S]*?\bclass\s+([A-Za-z_$][\w$]*)/g;
|
|
122
|
+
const ctrls = [...source.matchAll(ctrlRe)];
|
|
123
|
+
ctrls.forEach((m, i) => {
|
|
124
|
+
const start = m.index + m[0].length;
|
|
125
|
+
const end = i + 1 < ctrls.length ? ctrls[i + 1].index : source.length;
|
|
126
|
+
const body = source.slice(start, end);
|
|
127
|
+
const base = decoratorPath(m[1]);
|
|
128
|
+
const methodRe = /@(Get|Post|Put|Patch|Delete|Options|All)\s*\(([^)]*)\)[\s\S]*?(?<![@\w$])([A-Za-z_$][\w$]*)\s*\(/g;
|
|
129
|
+
for (const r of body.matchAll(methodRe)) {
|
|
130
|
+
routes.push({
|
|
131
|
+
method: r[1].toUpperCase(),
|
|
132
|
+
path: joinRoute(base, decoratorPath(r[2])),
|
|
133
|
+
controller: m[2],
|
|
134
|
+
handler: r[3],
|
|
135
|
+
file,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
return routes;
|
|
140
|
+
}
|
|
141
|
+
function staticRoutes(root) {
|
|
142
|
+
const layout = (0, entry_1.projectLayout)(root);
|
|
143
|
+
return controllerFiles(layout.srcDir).flatMap((f) => scanRoutes(fs_1.default.readFileSync(f, "utf8"), path_1.default.relative(root, f).split(path_1.default.sep).join("/")));
|
|
144
|
+
}
|
|
145
|
+
// ── Command ───────────────────────────────────────────────────────────────
|
|
146
|
+
function formatRoutes(routes) {
|
|
147
|
+
if (!routes.length)
|
|
148
|
+
return "No routes found.";
|
|
149
|
+
const rows = routes.map((r) => [r.method, r.path, `${r.controller}.${r.handler}`]);
|
|
150
|
+
const head = ["METHOD", "PATH", "HANDLER"];
|
|
151
|
+
const widths = head.map((h, i) => Math.max(h.length, ...rows.map((row) => row[i].length)));
|
|
152
|
+
const fmt = (row) => row.map((cell, i) => cell.padEnd(widths[i])).join(" ").trimEnd();
|
|
153
|
+
return [log_1.c.bold(fmt(head)), ...rows.map(fmt)].join("\n");
|
|
154
|
+
}
|
|
155
|
+
function routeList(opts = {}) {
|
|
156
|
+
const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
|
|
157
|
+
const routes = (opts.static ? staticRoutes(root) : runtimeRoutes(root)).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));
|
|
158
|
+
console.log(opts.json ? JSON.stringify(routes, null, 2) : formatRoutes(routes));
|
|
159
|
+
return routes;
|
|
160
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type ServeOptions = {
|
|
2
|
+
cwd?: string;
|
|
3
|
+
/** Entry file (relative to the project root), overriding package.json. */
|
|
4
|
+
entry?: string;
|
|
5
|
+
/** Run `tsc --noEmit --watch` alongside the server. Default true. */
|
|
6
|
+
typeCheck?: boolean;
|
|
7
|
+
/** Milliseconds to wait for more file events before rebuilding. Default 200. */
|
|
8
|
+
debounce?: number;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Development server: transpiles `src/` with SWC into the output dir, copies
|
|
12
|
+
* assets, runs the entry file, and restarts it on changes to sources, assets
|
|
13
|
+
* or `.env*` files. Type errors are reported by a parallel `tsc --watch` and
|
|
14
|
+
* never block a reload; syntax errors do, and stop the running app so stale
|
|
15
|
+
* JS never keeps serving.
|
|
16
|
+
*/
|
|
17
|
+
export declare function serve(opts?: ServeOptions): Promise<void>;
|