@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
+ /** Walk up from `start` to the nearest directory containing a `package.json`. */
2
+ export declare function findProjectRoot(start: string): string | null;
3
+ export declare function requireProjectRoot(start: string): string;
4
+ export declare function readJson<T = any>(file: string): T;
5
+ export declare function readPackageJson(root: string): Record<string, any>;
6
+ /**
7
+ * Find an installed package's directory by walking up `node_modules` folders.
8
+ * Unlike `require.resolve('<pkg>/package.json')` this works for packages whose
9
+ * `exports` map does not expose `package.json`.
10
+ */
11
+ export declare function findInstalledPackage(name: string, from: string): string | null;
12
+ export declare function installedVersion(name: string, from: string): string | null;
13
+ /** Write a file, creating parent directories. Refuses to overwrite unless `force`. */
14
+ export declare function writeFileSafe(file: string, content: string, force?: boolean): void;
15
+ /** Copy every non-TypeScript file under `srcDir` to the same relative path under `outDir`. */
16
+ export declare function copyAssets(srcDir: string, outDir: string): number;
17
+ export declare function isAsset(file: string): boolean;
@@ -0,0 +1,91 @@
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.findProjectRoot = findProjectRoot;
7
+ exports.requireProjectRoot = requireProjectRoot;
8
+ exports.readJson = readJson;
9
+ exports.readPackageJson = readPackageJson;
10
+ exports.findInstalledPackage = findInstalledPackage;
11
+ exports.installedVersion = installedVersion;
12
+ exports.writeFileSafe = writeFileSafe;
13
+ exports.copyAssets = copyAssets;
14
+ exports.isAsset = isAsset;
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const errors_1 = require("../errors");
18
+ /** Walk up from `start` to the nearest directory containing a `package.json`. */
19
+ function findProjectRoot(start) {
20
+ let dir = path_1.default.resolve(start);
21
+ for (;;) {
22
+ if (fs_1.default.existsSync(path_1.default.join(dir, "package.json")))
23
+ return dir;
24
+ const parent = path_1.default.dirname(dir);
25
+ if (parent === dir)
26
+ return null;
27
+ dir = parent;
28
+ }
29
+ }
30
+ function requireProjectRoot(start) {
31
+ const root = findProjectRoot(start);
32
+ if (!root) {
33
+ throw new errors_1.CliError(`No package.json found in ${path_1.default.resolve(start)} or any parent directory. Run this command inside a Megh project.`);
34
+ }
35
+ return root;
36
+ }
37
+ function readJson(file) {
38
+ return JSON.parse(fs_1.default.readFileSync(file, "utf8"));
39
+ }
40
+ function readPackageJson(root) {
41
+ return readJson(path_1.default.join(root, "package.json"));
42
+ }
43
+ /**
44
+ * Find an installed package's directory by walking up `node_modules` folders.
45
+ * Unlike `require.resolve('<pkg>/package.json')` this works for packages whose
46
+ * `exports` map does not expose `package.json`.
47
+ */
48
+ function findInstalledPackage(name, from) {
49
+ let dir = path_1.default.resolve(from);
50
+ for (;;) {
51
+ const candidate = path_1.default.join(dir, "node_modules", ...name.split("/"));
52
+ if (fs_1.default.existsSync(path_1.default.join(candidate, "package.json")))
53
+ return candidate;
54
+ const parent = path_1.default.dirname(dir);
55
+ if (parent === dir)
56
+ return null;
57
+ dir = parent;
58
+ }
59
+ }
60
+ function installedVersion(name, from) {
61
+ const dir = findInstalledPackage(name, from);
62
+ return dir ? readJson(path_1.default.join(dir, "package.json")).version ?? null : null;
63
+ }
64
+ /** Write a file, creating parent directories. Refuses to overwrite unless `force`. */
65
+ function writeFileSafe(file, content, force = false) {
66
+ if (fs_1.default.existsSync(file) && !force) {
67
+ throw new errors_1.CliError(`${file} already exists. Use -f or --force to overwrite it.`);
68
+ }
69
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
70
+ fs_1.default.writeFileSync(file, content, "utf8");
71
+ }
72
+ /** Copy every non-TypeScript file under `srcDir` to the same relative path under `outDir`. */
73
+ function copyAssets(srcDir, outDir) {
74
+ if (!fs_1.default.existsSync(srcDir))
75
+ return 0;
76
+ let copied = 0;
77
+ for (const entry of fs_1.default.readdirSync(srcDir, { withFileTypes: true, recursive: true })) {
78
+ if (!entry.isFile() || !isAsset(entry.name))
79
+ continue;
80
+ const parent = entry.parentPath ?? entry.path;
81
+ const from = path_1.default.join(parent, entry.name);
82
+ const to = path_1.default.join(outDir, path_1.default.relative(srcDir, from));
83
+ fs_1.default.mkdirSync(path_1.default.dirname(to), { recursive: true });
84
+ fs_1.default.copyFileSync(from, to);
85
+ copied++;
86
+ }
87
+ return copied;
88
+ }
89
+ function isAsset(file) {
90
+ return !/\.(c|m)?tsx?$/.test(file) && !path_1.default.basename(file).startsWith(".");
91
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The package root (the directory holding `stubs/` and `package.json`). Source
3
+ * files run from `src/**` under Vitest and from `dist/**` once built, so walk
4
+ * up from this file instead of assuming a fixed depth.
5
+ */
6
+ export declare const packageRoot: string;
7
+ export declare function stubPath(name: string): string;
8
+ /**
9
+ * Read a stub and replace `{Key}` placeholders. Unknown placeholders are left
10
+ * untouched so object literals in stubs are safe.
11
+ */
12
+ export declare function renderStub(name: string, vars?: Record<string, string>): string;
13
+ export declare function cliVersion(): string;
14
+ /** The `@meghjs/core` range new projects should depend on (lockstep with the CLI). */
15
+ export declare function coreRange(): string;
@@ -0,0 +1,52 @@
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.packageRoot = void 0;
7
+ exports.stubPath = stubPath;
8
+ exports.renderStub = renderStub;
9
+ exports.cliVersion = cliVersion;
10
+ exports.coreRange = coreRange;
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const path_1 = __importDefault(require("path"));
13
+ /**
14
+ * The package root (the directory holding `stubs/` and `package.json`). Source
15
+ * files run from `src/**` under Vitest and from `dist/**` once built, so walk
16
+ * up from this file instead of assuming a fixed depth.
17
+ */
18
+ exports.packageRoot = (() => {
19
+ let dir = __dirname;
20
+ for (;;) {
21
+ if (fs_1.default.existsSync(path_1.default.join(dir, "stubs")) &&
22
+ fs_1.default.existsSync(path_1.default.join(dir, "package.json"))) {
23
+ return dir;
24
+ }
25
+ const parent = path_1.default.dirname(dir);
26
+ if (parent === dir)
27
+ return path_1.default.resolve(__dirname, "..", "..");
28
+ dir = parent;
29
+ }
30
+ })();
31
+ function stubPath(name) {
32
+ return path_1.default.join(exports.packageRoot, "stubs", ...name.split("/"));
33
+ }
34
+ /**
35
+ * Read a stub and replace `{Key}` placeholders. Unknown placeholders are left
36
+ * untouched so object literals in stubs are safe.
37
+ */
38
+ function renderStub(name, vars = {}) {
39
+ let content = fs_1.default.readFileSync(stubPath(name), "utf8").replace(/\r\n/g, "\n");
40
+ for (const [key, value] of Object.entries(vars)) {
41
+ content = content.split(`{${key}}`).join(value);
42
+ }
43
+ return content;
44
+ }
45
+ function cliVersion() {
46
+ return JSON.parse(fs_1.default.readFileSync(path_1.default.join(exports.packageRoot, "package.json"), "utf8")).version;
47
+ }
48
+ /** The `@meghjs/core` range new projects should depend on (lockstep with the CLI). */
49
+ function coreRange() {
50
+ const pkg = JSON.parse(fs_1.default.readFileSync(path_1.default.join(exports.packageRoot, "package.json"), "utf8"));
51
+ return pkg.peerDependencies?.["@meghjs/core"] ?? `^${pkg.version}`;
52
+ }
@@ -0,0 +1,13 @@
1
+ export type TsConfigInfo = {
2
+ file: string;
3
+ compilerOptions: Record<string, any>;
4
+ };
5
+ /** Parse JSON that may contain comments and trailing commas, as tsconfig files do. */
6
+ export declare function parseJsonc(text: string): any;
7
+ /**
8
+ * Read a tsconfig and merge `extends` chains (relative paths and packages).
9
+ * Path-valued options (`baseUrl`, `outDir`, `rootDir`) are resolved to
10
+ * absolute paths relative to the file that declared them.
11
+ */
12
+ export declare function readTsConfig(file: string, seen?: Set<string>): TsConfigInfo;
13
+ export declare function findTsConfig(root: string, preferBuild?: boolean): string | null;
@@ -0,0 +1,102 @@
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.parseJsonc = parseJsonc;
7
+ exports.readTsConfig = readTsConfig;
8
+ exports.findTsConfig = findTsConfig;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ /** Parse JSON that may contain comments and trailing commas, as tsconfig files do. */
12
+ function parseJsonc(text) {
13
+ let out = "";
14
+ let inString = false;
15
+ for (let i = 0; i < text.length; i++) {
16
+ const ch = text[i];
17
+ const next = text[i + 1];
18
+ if (inString) {
19
+ out += ch;
20
+ if (ch === "\\") {
21
+ out += next ?? "";
22
+ i++;
23
+ }
24
+ else if (ch === '"') {
25
+ inString = false;
26
+ }
27
+ continue;
28
+ }
29
+ if (ch === '"') {
30
+ inString = true;
31
+ out += ch;
32
+ }
33
+ else if (ch === "/" && next === "/") {
34
+ while (i < text.length && text[i] !== "\n")
35
+ i++;
36
+ out += "\n";
37
+ }
38
+ else if (ch === "/" && next === "*") {
39
+ i += 2;
40
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/"))
41
+ i++;
42
+ i++;
43
+ }
44
+ else {
45
+ out += ch;
46
+ }
47
+ }
48
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
49
+ }
50
+ /**
51
+ * Read a tsconfig and merge `extends` chains (relative paths and packages).
52
+ * Path-valued options (`baseUrl`, `outDir`, `rootDir`) are resolved to
53
+ * absolute paths relative to the file that declared them.
54
+ */
55
+ function readTsConfig(file, seen = new Set()) {
56
+ const abs = path_1.default.resolve(file);
57
+ if (seen.has(abs))
58
+ return { file: abs, compilerOptions: {} };
59
+ seen.add(abs);
60
+ const raw = parseJsonc(fs_1.default.readFileSync(abs, "utf8"));
61
+ const dir = path_1.default.dirname(abs);
62
+ let base = {};
63
+ const exts = raw.extends ? [].concat(raw.extends) : [];
64
+ for (const ext of exts) {
65
+ let target = null;
66
+ if (ext.startsWith(".") || path_1.default.isAbsolute(ext)) {
67
+ target = path_1.default.resolve(dir, ext);
68
+ if (!fs_1.default.existsSync(target) && fs_1.default.existsSync(target + ".json"))
69
+ target += ".json";
70
+ }
71
+ else {
72
+ try {
73
+ target = require.resolve(ext, { paths: [dir] });
74
+ }
75
+ catch {
76
+ target = null;
77
+ }
78
+ }
79
+ if (target && fs_1.default.existsSync(target)) {
80
+ base = { ...base, ...readTsConfig(target, seen).compilerOptions };
81
+ }
82
+ }
83
+ const own = { ...(raw.compilerOptions ?? {}) };
84
+ for (const key of ["baseUrl", "outDir", "rootDir"]) {
85
+ if (typeof own[key] === "string")
86
+ own[key] = path_1.default.resolve(dir, own[key]);
87
+ }
88
+ if (own.paths && own.baseUrl === undefined && base.baseUrl === undefined) {
89
+ // TypeScript resolves `paths` relative to the declaring tsconfig when baseUrl is unset.
90
+ own.pathsBasePath = dir;
91
+ }
92
+ return { file: abs, compilerOptions: { ...base, ...own } };
93
+ }
94
+ function findTsConfig(root, preferBuild = false) {
95
+ const names = preferBuild ? ["tsconfig.build.json", "tsconfig.json"] : ["tsconfig.json"];
96
+ for (const name of names) {
97
+ const file = path_1.default.join(root, name);
98
+ if (fs_1.default.existsSync(file))
99
+ return file;
100
+ }
101
+ return null;
102
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@meghjs/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "CLI for scaffolding and running Megh applications",
5
+ "author": "Tareq Hossain",
6
+ "license": "MIT",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "bin": {
10
+ "megh": "dist/bin.js"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "stubs",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "scripts": {
22
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json",
23
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
24
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit",
25
+ "test": "vitest run",
26
+ "watch": "tsc -p tsconfig.json --watch",
27
+ "prepublishOnly": "npm run build"
28
+ },
29
+ "keywords": [
30
+ "cli",
31
+ "megh",
32
+ "backend",
33
+ "typescript"
34
+ ],
35
+ "dependencies": {
36
+ "@swc/core": "^1.13.5",
37
+ "chokidar": "^4.0.3",
38
+ "commander": "^14.0.0",
39
+ "inquirer": "^12.6.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.9.3",
43
+ "typescript": "^5.7.2",
44
+ "vitest": "^4.1.12"
45
+ },
46
+ "peerDependencies": {
47
+ "@meghjs/core": "^0.5.0"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@meghjs/core": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/meghjs/megh.git",
57
+ "directory": "packages/cli"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "gitHead": "b7dce1958b00ef1921c09461591e6379ea71e5a2"
63
+ }
package/readme.md ADDED
@@ -0,0 +1,155 @@
1
+ ### ⚠️ WARNING: NOT FOR PRODUCTION USE
2
+
3
+ > **🚧 This project is in active development.**
4
+ >
5
+ > It is **not stable** and **not ready** for live environments.
6
+ > Use **only for testing, experimentation, or internal evaluation**.
7
+ >
8
+ > #### ❗ Risks of using this in production:
9
+ >
10
+ > - 🔄 Breaking changes may be introduced at any time
11
+ > - 🧪 Features are experimental and may be unstable
12
+ > - 🔐 Security has not been audited
13
+ > - 💥 Potential for data loss or critical errors
14
+ >
15
+ > **Please do not deploy this in production environments.**
16
+
17
+ # Megh CLI
18
+
19
+ Scaffold and run [Megh](https://github.com/meghjs/megh) applications.
20
+
21
+ ## Create an Application
22
+
23
+ ```sh
24
+ npx @meghjs/cli new my_api
25
+ ```
26
+
27
+ You are prompted for a package manager and for optional features (OpenAPI,
28
+ CORS, TypeORM, Knex, Scalar UI). The generated project uses `@meghjs/core`'s
29
+ `Megh.createApplication()` and is ready to run:
30
+
31
+ ```sh
32
+ cd my_api
33
+ npm run start:dev
34
+ ```
35
+
36
+ ## Commands
37
+
38
+ | Command | Alias | Options | Description |
39
+ |---------|-------|---------|-------------|
40
+ | `new <name>` | | `-m`, `-f`, `-y`, `--pm <npm\|yarn\|pnpm>`, `--features <list>`, `--skip-install` | Create a new application |
41
+ | `serve` | | `--entry <file>`, `--no-type-check`, `--debounce <ms>` | Dev server: SWC compile, run, reload on change |
42
+ | `build` | | `-p <tsconfig>` | Compile with `tsconfig.build.json` and copy assets |
43
+ | `start` | | `--entry <file>` | Run the compiled app with `NODE_ENV=production` |
44
+ | `doctor` | | | Check Node.js, `@meghjs/core`, `reflect-metadata` and decorator settings |
45
+ | `route:list` | `routes` | `--json`, `--static` | List the app's routes |
46
+ | `make:model` | `m:m` | `-f`, `--orm`, `--root <dir>` | Create a model / TypeORM entity |
47
+ | `make:controller` | `m:c` | `-f`, `-r`, `-m <model>`, `--orm`, `--root <dir>`, `--base-path` | Create a controller |
48
+ | `make:service` | `m:s` | `-f`, `-r`, `-m <model>`, `--orm`, `--root <dir>` | Create a service |
49
+ | `make:config` | `m:cnf` | `-f`, `--root <dir>` | Create an `@AppConfig` class |
50
+ | `make:middleware` | `m:mlwr` | `-f`, `--root <dir>` | Create a middleware |
51
+ | `make:dto` | `m:dto` | `-f`, `--root <dir>` | Create a class-validator DTO |
52
+
53
+ `-f` / `--force` overwrites an existing file. `-r` / `--resource` generates a
54
+ full REST skeleton. `--root <dir>` (also `-rt`) writes under `src/<dir>`
55
+ instead of the default folder. Names may be nested, e.g. `admin/User`.
56
+ Run `megh <command> --help` for details.
57
+
58
+ Generated controllers must be registered in your app with
59
+ `app.useControllers([...])`.
60
+
61
+ ### Controller
62
+
63
+ ```sh
64
+ npx megh make:controller product
65
+ # shorthand
66
+ npx megh m:c product
67
+
68
+ # REST controller — also generates the matching service
69
+ npx megh m:c product -m product -r
70
+
71
+ # REST controller backed by a TypeORM repository
72
+ npx megh m:c product -m product -r --orm
73
+ ```
74
+
75
+ With `-m`, the generated controller delegates to `src/services/<model>.service.ts`,
76
+ which is created alongside it.
77
+
78
+ ### Model / Entity
79
+
80
+ ```sh
81
+ # plain class
82
+ npx megh make:model product
83
+
84
+ # TypeORM entity
85
+ npx megh m:m product --orm
86
+ ```
87
+
88
+ ### Service
89
+
90
+ ```sh
91
+ # basic service
92
+ npx megh make:service product
93
+
94
+ # resource service backed by an in-memory Collection
95
+ npx megh make:service product -m product -r
96
+
97
+ # resource service backed by a TypeORM repository
98
+ npx megh make:service product -m product -r --orm
99
+ ```
100
+
101
+ ### Middleware
102
+
103
+ ```sh
104
+ npx megh make:middleware auth
105
+ ```
106
+
107
+ Generates a class extending `MeghMiddleware` with an `invoke(req, res)` method.
108
+
109
+ ### Config
110
+
111
+ ```sh
112
+ npx megh make:config jwt
113
+ ```
114
+
115
+ Generates a class extending `MeghConfig`, registered via `@AppConfig`.
116
+
117
+ ## Development Server
118
+
119
+ ```sh
120
+ npx megh serve
121
+ ```
122
+
123
+ Compiles `src/` with SWC into `dist/`, starts the entry point, and restarts on
124
+ change to sources, assets or `.env*` files. The entry file is taken from
125
+ `--entry`, `megh.entry` in `package.json`, `main`, then `dist/serve.js`,
126
+ `server.js`, `main.js` or `index.js`.
127
+
128
+ Type errors are reported by a parallel `tsc --noEmit --watch` (disable with
129
+ `--no-type-check`) and never block a reload. Syntax errors stop the app until
130
+ they are fixed, so stale code never keeps serving.
131
+
132
+ ## Build and Run
133
+
134
+ ```sh
135
+ npx megh build # tsc with tsconfig.build.json, then copy non-TS assets
136
+ npx megh start # node dist/serve.js with NODE_ENV=production
137
+ ```
138
+
139
+ ## Routes
140
+
141
+ ```sh
142
+ npx megh route:list # compile and read Megh's route metadata
143
+ npx megh route:list --static # scan decorators in the source, no dependencies
144
+ npx megh routes --json
145
+ ```
146
+
147
+ ## Doctor
148
+
149
+ ```sh
150
+ npx megh doctor
151
+ ```
152
+
153
+ Checks the Node.js version, that `@meghjs/core` matches the CLI's version,
154
+ that `reflect-metadata` is installed, and that `experimentalDecorators` and
155
+ `emitDecoratorMetadata` are enabled. Exits non-zero if a check fails.
@@ -0,0 +1,9 @@
1
+ import { AppConfig, MeghConfig, Environment } from '@meghjs/core';
2
+
3
+ @AppConfig
4
+ export class {ClassName} extends MeghConfig {
5
+ config(env: Environment) {
6
+ // Return this config's values, e.g. { secret: env.get('JWT_SECRET') }.
7
+ return {};
8
+ }
9
+ }
@@ -0,0 +1,9 @@
1
+ import { ApiController, Get } from '@meghjs/core';
2
+
3
+ @ApiController('/{route}')
4
+ export class {ClassName} {
5
+ @Get()
6
+ index() {
7
+ return { message: '{ClassName} works' };
8
+ }
9
+ }
@@ -0,0 +1,45 @@
1
+ import { ApiController, Get, Post, Put, Delete, Param, Query, Body, HttpExceptions } from '@meghjs/core';
2
+ import { {ServiceClass} } from '{serviceImport}';
3
+
4
+ @ApiController('/{route}')
5
+ export class {ClassName} {
6
+ constructor(private readonly {serviceVar}: {ServiceClass}) {}
7
+
8
+ @Get()
9
+ async index(@Query() query?: any) {
10
+ if (query && query.page) {
11
+ return this.{serviceVar}.paginate(Number(query.page));
12
+ }
13
+ return this.{serviceVar}.findAll();
14
+ }
15
+
16
+ @Get('/:id')
17
+ async findOne(@Param('id') id: number) {
18
+ const {modelVar} = await this.{serviceVar}.findByPk(Number(id));
19
+ if (!{modelVar}) throw HttpExceptions.notFound('{Model} not found.');
20
+ return {modelVar};
21
+ }
22
+
23
+ @Post()
24
+ async create(@Body() body: any) {
25
+ return this.{serviceVar}.create(body);
26
+ }
27
+
28
+ @Put('/:id')
29
+ async update(@Param('id') id: number, @Body() updateBody: any) {
30
+ const {modelVar} = await this.{serviceVar}.findByPk(Number(id));
31
+ if (!{modelVar}) throw HttpExceptions.notFound('{Model} not found.');
32
+ const isUpdated = await this.{serviceVar}.update(Number(id), updateBody);
33
+ if (!isUpdated) throw HttpExceptions.internalError("Can't update {Model}");
34
+ return { message: 'Updated successfully' };
35
+ }
36
+
37
+ @Delete('/:id')
38
+ async delete(@Param('id') id: number) {
39
+ const {modelVar} = await this.{serviceVar}.findByPk(Number(id));
40
+ if (!{modelVar}) throw HttpExceptions.notFound('{Model} not found.');
41
+ const isDeleted = await this.{serviceVar}.delete(Number(id));
42
+ if (!isDeleted) throw HttpExceptions.internalError("Can't delete {Model}");
43
+ return { message: 'Deleted successfully' };
44
+ }
45
+ }
@@ -0,0 +1,29 @@
1
+ import { ApiController, Get, Post, Put, Delete, Param, Query, Body } from '@meghjs/core';
2
+
3
+ @ApiController('/{route}')
4
+ export class {ClassName} {
5
+ @Get()
6
+ async index(@Query() query?: any) {
7
+ throw new Error('Method not implemented.');
8
+ }
9
+
10
+ @Get('/:id')
11
+ async findOne(@Param('id') id: number) {
12
+ throw new Error('Method not implemented.');
13
+ }
14
+
15
+ @Post()
16
+ async create(@Body() body: any) {
17
+ throw new Error('Method not implemented.');
18
+ }
19
+
20
+ @Put('/:id')
21
+ async update(@Param('id') id: number, @Body() updateBody: any) {
22
+ throw new Error('Method not implemented.');
23
+ }
24
+
25
+ @Delete('/:id')
26
+ async delete(@Param('id') id: number) {
27
+ throw new Error('Method not implemented.');
28
+ }
29
+ }
@@ -0,0 +1,11 @@
1
+ import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
2
+
3
+ export class {ClassName} {
4
+ @IsString()
5
+ @IsNotEmpty()
6
+ name!: string;
7
+
8
+ @IsString()
9
+ @IsOptional()
10
+ description?: string;
11
+ }
@@ -0,0 +1,9 @@
1
+ import { AppMiddleware, MeghMiddleware, IRequest, IResponse } from '@meghjs/core';
2
+
3
+ @AppMiddleware
4
+ export class {ClassName} extends MeghMiddleware {
5
+ async invoke(req: IRequest, res?: IResponse) {
6
+ // your logic goes here
7
+ return req;
8
+ }
9
+ }
@@ -0,0 +1,9 @@
1
+ import type { Kysely } from "kysely";
2
+
3
+ export async function up(db: Kysely<any>): Promise<void> {
4
+ // await db.schema.alterTable("{table}").addColumn("column", "text").execute();
5
+ }
6
+
7
+ export async function down(db: Kysely<any>): Promise<void> {
8
+ // await db.schema.alterTable("{table}").dropColumn("column").execute();
9
+ }
@@ -0,0 +1,15 @@
1
+ import type { Kysely } from "kysely";
2
+
3
+ export async function up(db: Kysely<any>): Promise<void> {
4
+ await db.schema
5
+ .createTable("{table}")
6
+ {idColumn}
7
+ // .addColumn("name", "text", (col) => col.notNull())
8
+ .addColumn("created_at", "timestamp")
9
+ .addColumn("updated_at", "timestamp")
10
+ .execute();
11
+ }
12
+
13
+ export async function down(db: Kysely<any>): Promise<void> {
14
+ await db.schema.dropTable("{table}").execute();
15
+ }
@@ -0,0 +1,9 @@
1
+ import type { Kysely } from "kysely";
2
+
3
+ export async function up(db: Kysely<any>): Promise<void> {
4
+ // Schema changes: https://kysely.dev/docs/migrations
5
+ }
6
+
7
+ export async function down(db: Kysely<any>): Promise<void> {
8
+ // Undo the changes made in up().
9
+ }