@avleon/cli 0.0.47 → 0.4.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 (82) 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/new.d.ts +19 -0
  9. package/dist/commands/new.js +306 -0
  10. package/dist/commands/route-list.d.ts +19 -0
  11. package/dist/commands/route-list.js +160 -0
  12. package/dist/commands/serve.d.ts +17 -0
  13. package/dist/commands/serve.js +238 -0
  14. package/dist/commands/start.d.ts +10 -0
  15. package/dist/commands/start.js +43 -0
  16. package/dist/compiler.d.ts +24 -0
  17. package/dist/compiler.js +83 -0
  18. package/dist/errors.d.ts +8 -0
  19. package/dist/errors.js +16 -0
  20. package/dist/generators/make.d.ts +24 -0
  21. package/dist/generators/make.js +157 -0
  22. package/dist/index.d.ts +17 -0
  23. package/dist/index.js +40 -15
  24. package/dist/program.d.ts +22 -0
  25. package/dist/program.js +178 -0
  26. package/dist/utils/entry.d.ts +15 -0
  27. package/dist/utils/entry.js +55 -0
  28. package/dist/utils/env-types.d.ts +8 -0
  29. package/dist/utils/env-types.js +19 -0
  30. package/dist/utils/log.d.ts +25 -0
  31. package/dist/utils/log.js +39 -0
  32. package/dist/utils/names.d.ts +27 -0
  33. package/dist/utils/names.js +58 -0
  34. package/dist/utils/process.d.ts +18 -0
  35. package/dist/utils/process.js +84 -0
  36. package/dist/utils/project.d.ts +17 -0
  37. package/dist/utils/project.js +91 -0
  38. package/dist/utils/stubs.d.ts +15 -0
  39. package/dist/utils/stubs.js +52 -0
  40. package/dist/utils/tsconfig.d.ts +13 -0
  41. package/dist/utils/tsconfig.js +102 -0
  42. package/package.json +28 -27
  43. package/readme.md +50 -11
  44. package/stubs/config/config.stub +9 -0
  45. package/stubs/controllers/basic-controller.stub +3 -3
  46. package/stubs/controllers/resource-controller.stub +45 -0
  47. package/stubs/controllers/rest-controller.stub +2 -2
  48. package/stubs/dtos/dto.stub +11 -0
  49. package/stubs/middlewares/middleware.stub +9 -0
  50. package/stubs/models/basic-model.stub +2 -2
  51. package/stubs/models/entity-model.stub +6 -8
  52. package/stubs/{app → project}/app-minimal.stub +1 -1
  53. package/stubs/{app/app-controller.stub → project/app.stub} +2 -7
  54. package/stubs/project/env.stub +3 -0
  55. package/stubs/project/gitignore.stub +5 -0
  56. package/stubs/project/home.controller.spec.stub +19 -0
  57. package/stubs/project/home.controller.stub +12 -0
  58. package/stubs/project/home.service.stub +8 -0
  59. package/stubs/{config.stub → project/openapi.config.stub} +4 -4
  60. package/stubs/project/readme.stub +26 -0
  61. package/stubs/{serve.stub → project/serve.stub} +1 -1
  62. package/stubs/project/tsconfig.build.stub +4 -0
  63. package/stubs/project/tsconfig.stub +18 -0
  64. package/stubs/project/vitest-e2e.config.stub +10 -0
  65. package/stubs/project/vitest.config.stub +17 -0
  66. package/stubs/services/basic-service.stub +1 -1
  67. package/stubs/services/orm-rest-service.stub +15 -14
  68. package/stubs/services/rest-service.stub +9 -9
  69. package/dist/av-cli.js +0 -60
  70. package/dist/avcli.js +0 -26
  71. package/dist/cli.interface.js +0 -2
  72. package/dist/cli.js +0 -332
  73. package/dist/commands.js +0 -63
  74. package/dist/controller.js +0 -96
  75. package/dist/create.js +0 -512
  76. package/dist/helpers/file-helper.js +0 -30
  77. package/dist/helpers/path-helper.js +0 -36
  78. package/dist/paths.js +0 -32
  79. package/dist/scripts/serve.js +0 -290
  80. package/dist/serve.js +0 -311
  81. package/dist/service.js +0 -69
  82. package/stubs/controllers/orm-rest-controller.stub +0 -45
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: "@avleon/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)("@avleon/core", root);
37
+ if (!core) {
38
+ checks.push({ name: "@avleon/core", status: "fail", detail: "not installed (npm install @avleon/core)" });
39
+ }
40
+ else if (major(core) !== major(cli)) {
41
+ checks.push({
42
+ name: "@avleon/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: "@avleon/core", status: "warn", detail: `v${core}, CLI is v${cli} (minor versions differ)` });
49
+ }
50
+ else {
51
+ checks.push({ name: "@avleon/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,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 `AVLEON_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>;
@@ -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
+ "@avleon/core": (0, stubs_1.coreRange)(),
127
+ "@avleon/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["@avleon/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": "avleon serve",
148
+ build: "avleon build",
149
+ start: "avleon 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) || "avleon-app",
161
+ version: "0.0.1",
162
+ private: true,
163
+ description: `${(0, names_1.titleCase)(name)} API built with Avleon`,
164
+ main: "dist/serve.js",
165
+ scripts,
166
+ keywords: ["avleon", "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 @avleon/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. `avleon 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(" Avleon")) + 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) ? ["@avleon/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.AVLEON_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[];