servcraft 0.1.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 (106) hide show
  1. package/.dockerignore +45 -0
  2. package/.env.example +46 -0
  3. package/.husky/commit-msg +1 -0
  4. package/.husky/pre-commit +1 -0
  5. package/.prettierignore +4 -0
  6. package/.prettierrc +11 -0
  7. package/Dockerfile +76 -0
  8. package/Dockerfile.dev +31 -0
  9. package/README.md +232 -0
  10. package/commitlint.config.js +24 -0
  11. package/dist/cli/index.cjs +3968 -0
  12. package/dist/cli/index.cjs.map +1 -0
  13. package/dist/cli/index.d.cts +1 -0
  14. package/dist/cli/index.d.ts +1 -0
  15. package/dist/cli/index.js +3945 -0
  16. package/dist/cli/index.js.map +1 -0
  17. package/dist/index.cjs +2458 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +828 -0
  20. package/dist/index.d.ts +828 -0
  21. package/dist/index.js +2332 -0
  22. package/dist/index.js.map +1 -0
  23. package/docker-compose.prod.yml +118 -0
  24. package/docker-compose.yml +147 -0
  25. package/eslint.config.js +27 -0
  26. package/npm-cache/_cacache/content-v2/sha512/1c/d0/03440d500a0487621aad1d6402978340698976602046db8e24fa03c01ee6c022c69b0582f969042d9442ee876ac35c038e960dd427d1e622fa24b8eb7dba +0 -0
  27. package/npm-cache/_cacache/content-v2/sha512/42/55/28b493ca491833e5aab0e9c3108d29ab3f36c248ca88f45d4630674fce9130959e56ae308797ac2b6328fa7f09a610b9550ed09cb971d039876d293fc69d +0 -0
  28. package/npm-cache/_cacache/content-v2/sha512/e0/12/f360dc9315ee5f17844a0c8c233ee6bf7c30837c4a02ea0d56c61c7f7ab21c0e958e50ed2c57c59f983c762b93056778c9009b2398ffc26def0183999b13 +0 -0
  29. package/npm-cache/_cacache/content-v2/sha512/ed/b0/fae1161902898f4c913c67d7f6cdf6be0665aec3b389b9c4f4f0a101ca1da59badf1b59c4e0030f5223023b8d63cfe501c46a32c20c895d4fb3f11ca2232 +0 -0
  30. package/npm-cache/_cacache/index-v5/58/94/c2cba79e0f16b4c10e95a87e32255741149e8222cc314a476aab67c39cc0 +5 -0
  31. package/npm-cache/_update-notifier-last-checked +0 -0
  32. package/package.json +112 -0
  33. package/prisma/schema.prisma +157 -0
  34. package/src/cli/commands/add-module.ts +422 -0
  35. package/src/cli/commands/db.ts +137 -0
  36. package/src/cli/commands/docs.ts +16 -0
  37. package/src/cli/commands/generate.ts +459 -0
  38. package/src/cli/commands/init.ts +640 -0
  39. package/src/cli/index.ts +32 -0
  40. package/src/cli/templates/controller.ts +67 -0
  41. package/src/cli/templates/dynamic-prisma.ts +89 -0
  42. package/src/cli/templates/dynamic-schemas.ts +232 -0
  43. package/src/cli/templates/dynamic-types.ts +60 -0
  44. package/src/cli/templates/module-index.ts +33 -0
  45. package/src/cli/templates/prisma-model.ts +17 -0
  46. package/src/cli/templates/repository.ts +104 -0
  47. package/src/cli/templates/routes.ts +70 -0
  48. package/src/cli/templates/schemas.ts +26 -0
  49. package/src/cli/templates/service.ts +58 -0
  50. package/src/cli/templates/types.ts +27 -0
  51. package/src/cli/utils/docs-generator.ts +47 -0
  52. package/src/cli/utils/field-parser.ts +315 -0
  53. package/src/cli/utils/helpers.ts +89 -0
  54. package/src/config/env.ts +80 -0
  55. package/src/config/index.ts +97 -0
  56. package/src/core/index.ts +5 -0
  57. package/src/core/logger.ts +43 -0
  58. package/src/core/server.ts +132 -0
  59. package/src/database/index.ts +7 -0
  60. package/src/database/prisma.ts +54 -0
  61. package/src/database/seed.ts +59 -0
  62. package/src/index.ts +63 -0
  63. package/src/middleware/error-handler.ts +73 -0
  64. package/src/middleware/index.ts +3 -0
  65. package/src/middleware/security.ts +116 -0
  66. package/src/modules/audit/audit.service.ts +192 -0
  67. package/src/modules/audit/index.ts +2 -0
  68. package/src/modules/audit/types.ts +37 -0
  69. package/src/modules/auth/auth.controller.ts +182 -0
  70. package/src/modules/auth/auth.middleware.ts +87 -0
  71. package/src/modules/auth/auth.routes.ts +123 -0
  72. package/src/modules/auth/auth.service.ts +142 -0
  73. package/src/modules/auth/index.ts +49 -0
  74. package/src/modules/auth/schemas.ts +52 -0
  75. package/src/modules/auth/types.ts +69 -0
  76. package/src/modules/email/email.service.ts +212 -0
  77. package/src/modules/email/index.ts +10 -0
  78. package/src/modules/email/templates.ts +213 -0
  79. package/src/modules/email/types.ts +57 -0
  80. package/src/modules/swagger/index.ts +3 -0
  81. package/src/modules/swagger/schema-builder.ts +263 -0
  82. package/src/modules/swagger/swagger.service.ts +169 -0
  83. package/src/modules/swagger/types.ts +68 -0
  84. package/src/modules/user/index.ts +30 -0
  85. package/src/modules/user/schemas.ts +49 -0
  86. package/src/modules/user/types.ts +78 -0
  87. package/src/modules/user/user.controller.ts +139 -0
  88. package/src/modules/user/user.repository.ts +156 -0
  89. package/src/modules/user/user.routes.ts +199 -0
  90. package/src/modules/user/user.service.ts +145 -0
  91. package/src/modules/validation/index.ts +18 -0
  92. package/src/modules/validation/validator.ts +104 -0
  93. package/src/types/common.ts +61 -0
  94. package/src/types/index.ts +10 -0
  95. package/src/utils/errors.ts +66 -0
  96. package/src/utils/index.ts +33 -0
  97. package/src/utils/pagination.ts +38 -0
  98. package/src/utils/response.ts +63 -0
  99. package/tests/integration/auth.test.ts +59 -0
  100. package/tests/setup.ts +17 -0
  101. package/tests/unit/modules/validation.test.ts +88 -0
  102. package/tests/unit/utils/errors.test.ts +113 -0
  103. package/tests/unit/utils/pagination.test.ts +82 -0
  104. package/tsconfig.json +33 -0
  105. package/tsup.config.ts +14 -0
  106. package/vitest.config.ts +34 -0
@@ -0,0 +1,3968 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli/index.ts
27
+ var import_commander6 = require("commander");
28
+
29
+ // src/cli/commands/init.ts
30
+ var import_commander = require("commander");
31
+ var import_path2 = __toESM(require("path"), 1);
32
+ var import_promises2 = __toESM(require("fs/promises"), 1);
33
+ var import_ora = __toESM(require("ora"), 1);
34
+ var import_inquirer = __toESM(require("inquirer"), 1);
35
+ var import_chalk2 = __toESM(require("chalk"), 1);
36
+ var import_child_process = require("child_process");
37
+
38
+ // src/cli/utils/helpers.ts
39
+ var import_promises = __toESM(require("fs/promises"), 1);
40
+ var import_path = __toESM(require("path"), 1);
41
+ var import_chalk = __toESM(require("chalk"), 1);
42
+ function toPascalCase(str) {
43
+ return str.split(/[-_\s]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
44
+ }
45
+ function toCamelCase(str) {
46
+ const pascal = toPascalCase(str);
47
+ return pascal.charAt(0).toLowerCase() + pascal.slice(1);
48
+ }
49
+ function toKebabCase(str) {
50
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
51
+ }
52
+ function pluralize(str) {
53
+ if (str.endsWith("y")) {
54
+ return str.slice(0, -1) + "ies";
55
+ }
56
+ if (str.endsWith("s") || str.endsWith("x") || str.endsWith("ch") || str.endsWith("sh")) {
57
+ return str + "es";
58
+ }
59
+ return str + "s";
60
+ }
61
+ async function fileExists(filePath) {
62
+ try {
63
+ await import_promises.default.access(filePath);
64
+ return true;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+ async function ensureDir(dirPath) {
70
+ await import_promises.default.mkdir(dirPath, { recursive: true });
71
+ }
72
+ async function writeFile(filePath, content) {
73
+ await ensureDir(import_path.default.dirname(filePath));
74
+ await import_promises.default.writeFile(filePath, content, "utf-8");
75
+ }
76
+ function success(message) {
77
+ console.log(import_chalk.default.green("\u2713"), message);
78
+ }
79
+ function error(message) {
80
+ console.error(import_chalk.default.red("\u2717"), message);
81
+ }
82
+ function warn(message) {
83
+ console.log(import_chalk.default.yellow("\u26A0"), message);
84
+ }
85
+ function info(message) {
86
+ console.log(import_chalk.default.blue("\u2139"), message);
87
+ }
88
+ function getProjectRoot() {
89
+ return process.cwd();
90
+ }
91
+ function getSourceDir() {
92
+ return import_path.default.join(getProjectRoot(), "src");
93
+ }
94
+ function getModulesDir() {
95
+ return import_path.default.join(getSourceDir(), "modules");
96
+ }
97
+
98
+ // src/cli/commands/init.ts
99
+ var initCommand = new import_commander.Command("init").alias("new").description("Initialize a new Servcraft project").argument("[name]", "Project name").option("-y, --yes", "Skip prompts and use defaults").option("--ts, --typescript", "Use TypeScript (default)").option("--js, --javascript", "Use JavaScript").option("--db <database>", "Database type (postgresql, mysql, sqlite, mongodb, none)").action(async (name, cmdOptions) => {
100
+ console.log(import_chalk2.default.blue(`
101
+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
102
+ \u2551 \u2551
103
+ \u2551 ${import_chalk2.default.bold("\u{1F680} Servcraft Project Generator")} \u2551
104
+ \u2551 \u2551
105
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
106
+ `));
107
+ let options;
108
+ if (cmdOptions?.yes) {
109
+ options = {
110
+ name: name || "my-servcraft-app",
111
+ language: cmdOptions.javascript ? "javascript" : "typescript",
112
+ database: cmdOptions.db || "postgresql",
113
+ validator: "zod",
114
+ features: ["auth", "users", "email"]
115
+ };
116
+ } else {
117
+ const answers = await import_inquirer.default.prompt([
118
+ {
119
+ type: "input",
120
+ name: "name",
121
+ message: "Project name:",
122
+ default: name || "my-servcraft-app",
123
+ validate: (input) => {
124
+ if (!/^[a-z0-9-_]+$/i.test(input)) {
125
+ return "Project name can only contain letters, numbers, hyphens, and underscores";
126
+ }
127
+ return true;
128
+ }
129
+ },
130
+ {
131
+ type: "list",
132
+ name: "language",
133
+ message: "Select language:",
134
+ choices: [
135
+ { name: "TypeScript (Recommended)", value: "typescript" },
136
+ { name: "JavaScript", value: "javascript" }
137
+ ],
138
+ default: "typescript"
139
+ },
140
+ {
141
+ type: "list",
142
+ name: "database",
143
+ message: "Select database:",
144
+ choices: [
145
+ { name: "PostgreSQL (Recommended)", value: "postgresql" },
146
+ { name: "MySQL", value: "mysql" },
147
+ { name: "SQLite (Development)", value: "sqlite" },
148
+ { name: "MongoDB", value: "mongodb" },
149
+ { name: "None (Add later)", value: "none" }
150
+ ],
151
+ default: "postgresql"
152
+ },
153
+ {
154
+ type: "list",
155
+ name: "validator",
156
+ message: "Select validation library:",
157
+ choices: [
158
+ { name: "Zod (Recommended - TypeScript-first)", value: "zod" },
159
+ { name: "Joi (Battle-tested, feature-rich)", value: "joi" },
160
+ { name: "Yup (Inspired by Joi, lighter)", value: "yup" }
161
+ ],
162
+ default: "zod"
163
+ },
164
+ {
165
+ type: "checkbox",
166
+ name: "features",
167
+ message: "Select features to include:",
168
+ choices: [
169
+ { name: "Authentication (JWT)", value: "auth", checked: true },
170
+ { name: "User Management", value: "users", checked: true },
171
+ { name: "Email Service", value: "email", checked: true },
172
+ { name: "Audit Logs", value: "audit", checked: false },
173
+ { name: "File Upload", value: "upload", checked: false },
174
+ { name: "Redis Cache", value: "redis", checked: false }
175
+ ]
176
+ }
177
+ ]);
178
+ options = answers;
179
+ }
180
+ const projectDir = import_path2.default.resolve(process.cwd(), options.name);
181
+ const spinner = (0, import_ora.default)("Creating project...").start();
182
+ try {
183
+ try {
184
+ await import_promises2.default.access(projectDir);
185
+ spinner.stop();
186
+ error(`Directory "${options.name}" already exists`);
187
+ return;
188
+ } catch {
189
+ }
190
+ await ensureDir(projectDir);
191
+ spinner.text = "Generating project files...";
192
+ const packageJson = generatePackageJson(options);
193
+ await writeFile(import_path2.default.join(projectDir, "package.json"), JSON.stringify(packageJson, null, 2));
194
+ if (options.language === "typescript") {
195
+ await writeFile(import_path2.default.join(projectDir, "tsconfig.json"), generateTsConfig());
196
+ await writeFile(import_path2.default.join(projectDir, "tsup.config.ts"), generateTsupConfig());
197
+ } else {
198
+ await writeFile(import_path2.default.join(projectDir, "jsconfig.json"), generateJsConfig());
199
+ }
200
+ await writeFile(import_path2.default.join(projectDir, ".env.example"), generateEnvExample(options));
201
+ await writeFile(import_path2.default.join(projectDir, ".env"), generateEnvExample(options));
202
+ await writeFile(import_path2.default.join(projectDir, ".gitignore"), generateGitignore());
203
+ await writeFile(import_path2.default.join(projectDir, "Dockerfile"), generateDockerfile(options));
204
+ await writeFile(import_path2.default.join(projectDir, "docker-compose.yml"), generateDockerCompose(options));
205
+ const ext = options.language === "typescript" ? "ts" : "js";
206
+ const dirs = [
207
+ "src/core",
208
+ "src/config",
209
+ "src/modules",
210
+ "src/middleware",
211
+ "src/utils",
212
+ "src/types",
213
+ "tests/unit",
214
+ "tests/integration"
215
+ ];
216
+ if (options.database !== "none" && options.database !== "mongodb") {
217
+ dirs.push("prisma");
218
+ }
219
+ for (const dir of dirs) {
220
+ await ensureDir(import_path2.default.join(projectDir, dir));
221
+ }
222
+ await writeFile(
223
+ import_path2.default.join(projectDir, `src/index.${ext}`),
224
+ generateEntryFile(options)
225
+ );
226
+ await writeFile(
227
+ import_path2.default.join(projectDir, `src/core/server.${ext}`),
228
+ generateServerFile(options)
229
+ );
230
+ await writeFile(
231
+ import_path2.default.join(projectDir, `src/core/logger.${ext}`),
232
+ generateLoggerFile(options)
233
+ );
234
+ if (options.database !== "none" && options.database !== "mongodb") {
235
+ await writeFile(
236
+ import_path2.default.join(projectDir, "prisma/schema.prisma"),
237
+ generatePrismaSchema(options)
238
+ );
239
+ }
240
+ spinner.succeed("Project files generated!");
241
+ const installSpinner = (0, import_ora.default)("Installing dependencies...").start();
242
+ try {
243
+ (0, import_child_process.execSync)("npm install", { cwd: projectDir, stdio: "pipe" });
244
+ installSpinner.succeed("Dependencies installed!");
245
+ } catch {
246
+ installSpinner.warn("Failed to install dependencies automatically");
247
+ warn(' Run "npm install" manually in the project directory');
248
+ }
249
+ console.log("\n" + import_chalk2.default.green("\u2728 Project created successfully!"));
250
+ console.log("\n" + import_chalk2.default.bold("\u{1F4C1} Project structure:"));
251
+ console.log(`
252
+ ${options.name}/
253
+ \u251C\u2500\u2500 src/
254
+ \u2502 \u251C\u2500\u2500 core/ # Core server, logger
255
+ \u2502 \u251C\u2500\u2500 config/ # Configuration
256
+ \u2502 \u251C\u2500\u2500 modules/ # Feature modules
257
+ \u2502 \u251C\u2500\u2500 middleware/ # Middlewares
258
+ \u2502 \u251C\u2500\u2500 utils/ # Utilities
259
+ \u2502 \u2514\u2500\u2500 index.${ext} # Entry point
260
+ \u251C\u2500\u2500 tests/ # Tests
261
+ \u251C\u2500\u2500 prisma/ # Database schema
262
+ \u251C\u2500\u2500 docker-compose.yml
263
+ \u2514\u2500\u2500 package.json
264
+ `);
265
+ console.log(import_chalk2.default.bold("\u{1F680} Get started:"));
266
+ console.log(`
267
+ ${import_chalk2.default.cyan(`cd ${options.name}`)}
268
+ ${options.database !== "none" ? import_chalk2.default.cyan("npm run db:push # Setup database") : ""}
269
+ ${import_chalk2.default.cyan("npm run dev # Start development server")}
270
+ `);
271
+ console.log(import_chalk2.default.bold("\u{1F4DA} Available commands:"));
272
+ console.log(`
273
+ ${import_chalk2.default.yellow("servcraft generate module <name>")} Generate a new module
274
+ ${import_chalk2.default.yellow("servcraft generate controller <name>")} Generate a controller
275
+ ${import_chalk2.default.yellow("servcraft generate service <name>")} Generate a service
276
+ ${import_chalk2.default.yellow("servcraft add auth")} Add authentication module
277
+ `);
278
+ } catch (err) {
279
+ spinner.fail("Failed to create project");
280
+ error(err instanceof Error ? err.message : String(err));
281
+ }
282
+ });
283
+ function generatePackageJson(options) {
284
+ const isTS = options.language === "typescript";
285
+ const pkg = {
286
+ name: options.name,
287
+ version: "0.1.0",
288
+ description: "A Servcraft application",
289
+ main: isTS ? "dist/index.js" : "src/index.js",
290
+ type: "module",
291
+ scripts: {
292
+ dev: isTS ? "tsx watch src/index.ts" : "node --watch src/index.js",
293
+ build: isTS ? "tsup" : 'echo "No build needed for JS"',
294
+ start: isTS ? "node dist/index.js" : "node src/index.js",
295
+ test: "vitest",
296
+ lint: isTS ? "eslint src --ext .ts" : "eslint src --ext .js"
297
+ },
298
+ dependencies: {
299
+ fastify: "^4.28.1",
300
+ "@fastify/cors": "^9.0.1",
301
+ "@fastify/helmet": "^11.1.1",
302
+ "@fastify/jwt": "^8.0.1",
303
+ "@fastify/rate-limit": "^9.1.0",
304
+ "@fastify/cookie": "^9.3.1",
305
+ pino: "^9.5.0",
306
+ "pino-pretty": "^11.3.0",
307
+ bcryptjs: "^2.4.3",
308
+ dotenv: "^16.4.5"
309
+ },
310
+ devDependencies: {
311
+ vitest: "^2.1.8"
312
+ }
313
+ };
314
+ switch (options.validator) {
315
+ case "zod":
316
+ pkg.dependencies.zod = "^3.23.8";
317
+ break;
318
+ case "joi":
319
+ pkg.dependencies.joi = "^17.13.3";
320
+ break;
321
+ case "yup":
322
+ pkg.dependencies.yup = "^1.4.0";
323
+ break;
324
+ }
325
+ if (isTS) {
326
+ pkg.devDependencies.typescript = "^5.7.2";
327
+ pkg.devDependencies.tsx = "^4.19.2";
328
+ pkg.devDependencies.tsup = "^8.3.5";
329
+ pkg.devDependencies["@types/node"] = "^22.10.1";
330
+ pkg.devDependencies["@types/bcryptjs"] = "^2.4.6";
331
+ }
332
+ if (options.database !== "none" && options.database !== "mongodb") {
333
+ pkg.dependencies["@prisma/client"] = "^5.22.0";
334
+ pkg.devDependencies.prisma = "^5.22.0";
335
+ pkg.scripts["db:generate"] = "prisma generate";
336
+ pkg.scripts["db:migrate"] = "prisma migrate dev";
337
+ pkg.scripts["db:push"] = "prisma db push";
338
+ pkg.scripts["db:studio"] = "prisma studio";
339
+ }
340
+ if (options.database === "mongodb") {
341
+ pkg.dependencies.mongoose = "^8.8.4";
342
+ }
343
+ if (options.features.includes("email")) {
344
+ pkg.dependencies.nodemailer = "^6.9.15";
345
+ pkg.dependencies.handlebars = "^4.7.8";
346
+ if (isTS) {
347
+ pkg.devDependencies["@types/nodemailer"] = "^6.4.17";
348
+ }
349
+ }
350
+ if (options.features.includes("redis")) {
351
+ pkg.dependencies.ioredis = "^5.4.1";
352
+ }
353
+ return pkg;
354
+ }
355
+ function generateTsConfig() {
356
+ return JSON.stringify({
357
+ compilerOptions: {
358
+ target: "ES2022",
359
+ module: "NodeNext",
360
+ moduleResolution: "NodeNext",
361
+ lib: ["ES2022"],
362
+ outDir: "./dist",
363
+ rootDir: "./src",
364
+ strict: true,
365
+ esModuleInterop: true,
366
+ skipLibCheck: true,
367
+ forceConsistentCasingInFileNames: true,
368
+ resolveJsonModule: true,
369
+ declaration: true,
370
+ sourceMap: true
371
+ },
372
+ include: ["src/**/*"],
373
+ exclude: ["node_modules", "dist"]
374
+ }, null, 2);
375
+ }
376
+ function generateJsConfig() {
377
+ return JSON.stringify({
378
+ compilerOptions: {
379
+ module: "NodeNext",
380
+ moduleResolution: "NodeNext",
381
+ target: "ES2022",
382
+ checkJs: true
383
+ },
384
+ include: ["src/**/*"],
385
+ exclude: ["node_modules"]
386
+ }, null, 2);
387
+ }
388
+ function generateTsupConfig() {
389
+ return `import { defineConfig } from 'tsup';
390
+
391
+ export default defineConfig({
392
+ entry: ['src/index.ts'],
393
+ format: ['esm'],
394
+ dts: true,
395
+ clean: true,
396
+ sourcemap: true,
397
+ target: 'node18',
398
+ });
399
+ `;
400
+ }
401
+ function generateEnvExample(options) {
402
+ let env2 = `# Server
403
+ NODE_ENV=development
404
+ PORT=3000
405
+ HOST=0.0.0.0
406
+
407
+ # JWT
408
+ JWT_SECRET=your-super-secret-key-min-32-characters
409
+ JWT_ACCESS_EXPIRES_IN=15m
410
+ JWT_REFRESH_EXPIRES_IN=7d
411
+
412
+ # Security
413
+ CORS_ORIGIN=http://localhost:3000
414
+ RATE_LIMIT_MAX=100
415
+
416
+ # Logging
417
+ LOG_LEVEL=info
418
+ `;
419
+ if (options.database === "postgresql") {
420
+ env2 += `
421
+ # Database (PostgreSQL)
422
+ DATABASE_PROVIDER=postgresql
423
+ DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
424
+ `;
425
+ } else if (options.database === "mysql") {
426
+ env2 += `
427
+ # Database (MySQL)
428
+ DATABASE_PROVIDER=mysql
429
+ DATABASE_URL="mysql://user:password@localhost:3306/mydb"
430
+ `;
431
+ } else if (options.database === "sqlite") {
432
+ env2 += `
433
+ # Database (SQLite)
434
+ DATABASE_PROVIDER=sqlite
435
+ DATABASE_URL="file:./dev.db"
436
+ `;
437
+ } else if (options.database === "mongodb") {
438
+ env2 += `
439
+ # Database (MongoDB)
440
+ MONGODB_URI="mongodb://localhost:27017/mydb"
441
+ `;
442
+ }
443
+ if (options.features.includes("email")) {
444
+ env2 += `
445
+ # Email
446
+ SMTP_HOST=smtp.example.com
447
+ SMTP_PORT=587
448
+ SMTP_USER=
449
+ SMTP_PASS=
450
+ SMTP_FROM="App <noreply@example.com>"
451
+ `;
452
+ }
453
+ if (options.features.includes("redis")) {
454
+ env2 += `
455
+ # Redis
456
+ REDIS_URL=redis://localhost:6379
457
+ `;
458
+ }
459
+ return env2;
460
+ }
461
+ function generateGitignore() {
462
+ return `node_modules/
463
+ dist/
464
+ .env
465
+ .env.local
466
+ *.log
467
+ coverage/
468
+ .DS_Store
469
+ *.db
470
+ `;
471
+ }
472
+ function generateDockerfile(options) {
473
+ const isTS = options.language === "typescript";
474
+ return `FROM node:20-alpine
475
+ WORKDIR /app
476
+ COPY package*.json ./
477
+ RUN npm ci --only=production
478
+ COPY ${isTS ? "dist" : "src"} ./${isTS ? "dist" : "src"}
479
+ ${options.database !== "none" && options.database !== "mongodb" ? "COPY prisma ./prisma\nRUN npx prisma generate" : ""}
480
+ EXPOSE 3000
481
+ CMD ["node", "${isTS ? "dist" : "src"}/index.js"]
482
+ `;
483
+ }
484
+ function generateDockerCompose(options) {
485
+ let compose = `version: '3.8'
486
+
487
+ services:
488
+ app:
489
+ build: .
490
+ ports:
491
+ - "\${PORT:-3000}:3000"
492
+ environment:
493
+ - NODE_ENV=development
494
+ `;
495
+ if (options.database === "postgresql") {
496
+ compose += ` - DATABASE_URL=postgresql://postgres:postgres@postgres:5432/mydb
497
+ depends_on:
498
+ - postgres
499
+
500
+ postgres:
501
+ image: postgres:16-alpine
502
+ environment:
503
+ POSTGRES_USER: postgres
504
+ POSTGRES_PASSWORD: postgres
505
+ POSTGRES_DB: mydb
506
+ ports:
507
+ - "5432:5432"
508
+ volumes:
509
+ - postgres-data:/var/lib/postgresql/data
510
+
511
+ volumes:
512
+ postgres-data:
513
+ `;
514
+ } else if (options.database === "mysql") {
515
+ compose += ` - DATABASE_URL=mysql://root:root@mysql:3306/mydb
516
+ depends_on:
517
+ - mysql
518
+
519
+ mysql:
520
+ image: mysql:8.0
521
+ environment:
522
+ MYSQL_ROOT_PASSWORD: root
523
+ MYSQL_DATABASE: mydb
524
+ ports:
525
+ - "3306:3306"
526
+ volumes:
527
+ - mysql-data:/var/lib/mysql
528
+
529
+ volumes:
530
+ mysql-data:
531
+ `;
532
+ }
533
+ if (options.features.includes("redis")) {
534
+ compose += `
535
+ redis:
536
+ image: redis:7-alpine
537
+ ports:
538
+ - "6379:6379"
539
+ `;
540
+ }
541
+ return compose;
542
+ }
543
+ function generatePrismaSchema(options) {
544
+ const provider = options.database === "sqlite" ? "sqlite" : options.database;
545
+ return `generator client {
546
+ provider = "prisma-client-js"
547
+ }
548
+
549
+ datasource db {
550
+ provider = "${provider}"
551
+ url = env("DATABASE_URL")
552
+ }
553
+
554
+ model User {
555
+ id String @id @default(uuid())
556
+ email String @unique
557
+ password String
558
+ name String?
559
+ role String @default("user")
560
+ status String @default("active")
561
+ emailVerified Boolean @default(false)
562
+ createdAt DateTime @default(now())
563
+ updatedAt DateTime @updatedAt
564
+
565
+ @@map("users")
566
+ }
567
+ `;
568
+ }
569
+ function generateEntryFile(options) {
570
+ const isTS = options.language === "typescript";
571
+ return `${isTS ? "import { createServer } from './core/server.js';\nimport { logger } from './core/logger.js';" : "const { createServer } = require('./core/server.js');\nconst { logger } = require('./core/logger.js');"}
572
+
573
+ async function main()${isTS ? ": Promise<void>" : ""} {
574
+ const server = createServer();
575
+
576
+ try {
577
+ await server.start();
578
+ } catch (error) {
579
+ logger.error({ err: error }, 'Failed to start server');
580
+ process.exit(1);
581
+ }
582
+ }
583
+
584
+ main();
585
+ `;
586
+ }
587
+ function generateServerFile(options) {
588
+ const isTS = options.language === "typescript";
589
+ return `${isTS ? `import Fastify from 'fastify';
590
+ import type { FastifyInstance } from 'fastify';
591
+ import { logger } from './logger.js';` : `const Fastify = require('fastify');
592
+ const { logger } = require('./logger.js');`}
593
+
594
+ ${isTS ? "export function createServer(): { instance: FastifyInstance; start: () => Promise<void> }" : "function createServer()"} {
595
+ const app = Fastify({ logger });
596
+
597
+ // Health check
598
+ app.get('/health', async () => ({
599
+ status: 'ok',
600
+ timestamp: new Date().toISOString(),
601
+ }));
602
+
603
+ // Graceful shutdown
604
+ const signals${isTS ? ": NodeJS.Signals[]" : ""} = ['SIGINT', 'SIGTERM'];
605
+ signals.forEach((signal) => {
606
+ process.on(signal, async () => {
607
+ logger.info(\`Received \${signal}, shutting down...\`);
608
+ await app.close();
609
+ process.exit(0);
610
+ });
611
+ });
612
+
613
+ return {
614
+ instance: app,
615
+ start: async ()${isTS ? ": Promise<void>" : ""} => {
616
+ const port = parseInt(process.env.PORT || '3000', 10);
617
+ const host = process.env.HOST || '0.0.0.0';
618
+ await app.listen({ port, host });
619
+ logger.info(\`Server listening on \${host}:\${port}\`);
620
+ },
621
+ };
622
+ }
623
+
624
+ ${isTS ? "" : "module.exports = { createServer };"}
625
+ `;
626
+ }
627
+ function generateLoggerFile(options) {
628
+ const isTS = options.language === "typescript";
629
+ return `${isTS ? "import pino from 'pino';\nimport type { Logger } from 'pino';" : "const pino = require('pino');"}
630
+
631
+ ${isTS ? "export const logger: Logger" : "const logger"} = pino({
632
+ level: process.env.LOG_LEVEL || 'info',
633
+ transport: process.env.NODE_ENV !== 'production' ? {
634
+ target: 'pino-pretty',
635
+ options: { colorize: true },
636
+ } : undefined,
637
+ });
638
+
639
+ ${isTS ? "" : "module.exports = { logger };"}
640
+ `;
641
+ }
642
+
643
+ // src/cli/commands/generate.ts
644
+ var import_commander2 = require("commander");
645
+ var import_path4 = __toESM(require("path"), 1);
646
+ var import_ora3 = __toESM(require("ora"), 1);
647
+ var import_inquirer2 = __toESM(require("inquirer"), 1);
648
+
649
+ // src/cli/utils/field-parser.ts
650
+ var tsTypeMap = {
651
+ string: "string",
652
+ number: "number",
653
+ boolean: "boolean",
654
+ date: "Date",
655
+ datetime: "Date",
656
+ text: "string",
657
+ json: "Record<string, unknown>",
658
+ email: "string",
659
+ url: "string",
660
+ uuid: "string",
661
+ int: "number",
662
+ float: "number",
663
+ decimal: "number",
664
+ enum: "string"
665
+ };
666
+ var prismaTypeMap = {
667
+ string: "String",
668
+ number: "Int",
669
+ boolean: "Boolean",
670
+ date: "DateTime",
671
+ datetime: "DateTime",
672
+ text: "String",
673
+ json: "Json",
674
+ email: "String",
675
+ url: "String",
676
+ uuid: "String",
677
+ int: "Int",
678
+ float: "Float",
679
+ decimal: "Decimal",
680
+ enum: "String"
681
+ };
682
+ var zodTypeMap = {
683
+ string: "z.string()",
684
+ number: "z.number()",
685
+ boolean: "z.boolean()",
686
+ date: "z.coerce.date()",
687
+ datetime: "z.coerce.date()",
688
+ text: "z.string()",
689
+ json: "z.record(z.unknown())",
690
+ email: "z.string().email()",
691
+ url: "z.string().url()",
692
+ uuid: "z.string().uuid()",
693
+ int: "z.number().int()",
694
+ float: "z.number()",
695
+ decimal: "z.number()",
696
+ enum: "z.string()"
697
+ };
698
+ var joiTypeMap = {
699
+ string: "Joi.string()",
700
+ number: "Joi.number()",
701
+ boolean: "Joi.boolean()",
702
+ date: "Joi.date()",
703
+ datetime: "Joi.date()",
704
+ text: "Joi.string()",
705
+ json: "Joi.object()",
706
+ email: "Joi.string().email()",
707
+ url: "Joi.string().uri()",
708
+ uuid: "Joi.string().uuid()",
709
+ int: "Joi.number().integer()",
710
+ float: "Joi.number()",
711
+ decimal: "Joi.number()",
712
+ enum: "Joi.string()"
713
+ };
714
+ var yupTypeMap = {
715
+ string: "yup.string()",
716
+ number: "yup.number()",
717
+ boolean: "yup.boolean()",
718
+ date: "yup.date()",
719
+ datetime: "yup.date()",
720
+ text: "yup.string()",
721
+ json: "yup.object()",
722
+ email: "yup.string().email()",
723
+ url: "yup.string().url()",
724
+ uuid: "yup.string().uuid()",
725
+ int: "yup.number().integer()",
726
+ float: "yup.number()",
727
+ decimal: "yup.number()",
728
+ enum: "yup.string()"
729
+ };
730
+ function parseField(fieldStr) {
731
+ const parts = fieldStr.split(":");
732
+ let name = parts[0] || "";
733
+ let typeStr = parts[1] || "string";
734
+ const modifiers = parts.slice(2);
735
+ const isOptional = name.endsWith("?") || typeStr.endsWith("?");
736
+ name = name.replace("?", "");
737
+ typeStr = typeStr.replace("?", "");
738
+ const isArray = typeStr.endsWith("[]");
739
+ typeStr = typeStr.replace("[]", "");
740
+ const validTypes = [
741
+ "string",
742
+ "number",
743
+ "boolean",
744
+ "date",
745
+ "datetime",
746
+ "text",
747
+ "json",
748
+ "email",
749
+ "url",
750
+ "uuid",
751
+ "int",
752
+ "float",
753
+ "decimal",
754
+ "enum"
755
+ ];
756
+ let type = "string";
757
+ if (validTypes.includes(typeStr)) {
758
+ type = typeStr;
759
+ }
760
+ let isUnique = false;
761
+ let defaultValue;
762
+ let relation;
763
+ for (const mod of modifiers) {
764
+ if (mod === "unique") {
765
+ isUnique = true;
766
+ } else if (mod.startsWith("default=")) {
767
+ defaultValue = mod.replace("default=", "");
768
+ } else if (typeStr === "relation") {
769
+ relation = {
770
+ model: mod,
771
+ type: "many-to-one"
772
+ };
773
+ type = "string";
774
+ }
775
+ }
776
+ return {
777
+ name,
778
+ type,
779
+ isOptional,
780
+ isArray,
781
+ isUnique,
782
+ defaultValue,
783
+ relation
784
+ };
785
+ }
786
+ function parseFields(fieldsStr) {
787
+ if (!fieldsStr) return [];
788
+ return fieldsStr.split(/\s+/).filter(Boolean).map(parseField);
789
+ }
790
+
791
+ // src/cli/templates/controller.ts
792
+ function controllerTemplate(name, pascalName, camelName) {
793
+ return `import type { FastifyRequest, FastifyReply } from 'fastify';
794
+ import type { ${pascalName}Service } from './${name}.service.js';
795
+ import { create${pascalName}Schema, update${pascalName}Schema, ${camelName}QuerySchema } from './${name}.schemas.js';
796
+ import { success, created, noContent } from '../../utils/response.js';
797
+ import { parsePaginationParams } from '../../utils/pagination.js';
798
+ import { validateBody, validateQuery } from '../validation/validator.js';
799
+
800
+ export class ${pascalName}Controller {
801
+ constructor(private ${camelName}Service: ${pascalName}Service) {}
802
+
803
+ async list(request: FastifyRequest, reply: FastifyReply): Promise<void> {
804
+ const query = validateQuery(${camelName}QuerySchema, request.query);
805
+ const pagination = parsePaginationParams(query);
806
+ const filters = {
807
+ search: query.search,
808
+ };
809
+
810
+ const result = await this.${camelName}Service.findMany(pagination, filters);
811
+ success(reply, result);
812
+ }
813
+
814
+ async getById(
815
+ request: FastifyRequest<{ Params: { id: string } }>,
816
+ reply: FastifyReply
817
+ ): Promise<void> {
818
+ const item = await this.${camelName}Service.findById(request.params.id);
819
+
820
+ if (!item) {
821
+ return reply.status(404).send({
822
+ success: false,
823
+ message: '${pascalName} not found',
824
+ });
825
+ }
826
+
827
+ success(reply, item);
828
+ }
829
+
830
+ async create(request: FastifyRequest, reply: FastifyReply): Promise<void> {
831
+ const data = validateBody(create${pascalName}Schema, request.body);
832
+ const item = await this.${camelName}Service.create(data);
833
+ created(reply, item);
834
+ }
835
+
836
+ async update(
837
+ request: FastifyRequest<{ Params: { id: string } }>,
838
+ reply: FastifyReply
839
+ ): Promise<void> {
840
+ const data = validateBody(update${pascalName}Schema, request.body);
841
+ const item = await this.${camelName}Service.update(request.params.id, data);
842
+ success(reply, item);
843
+ }
844
+
845
+ async delete(
846
+ request: FastifyRequest<{ Params: { id: string } }>,
847
+ reply: FastifyReply
848
+ ): Promise<void> {
849
+ await this.${camelName}Service.delete(request.params.id);
850
+ noContent(reply);
851
+ }
852
+ }
853
+
854
+ export function create${pascalName}Controller(${camelName}Service: ${pascalName}Service): ${pascalName}Controller {
855
+ return new ${pascalName}Controller(${camelName}Service);
856
+ }
857
+ `;
858
+ }
859
+
860
+ // src/cli/templates/service.ts
861
+ function serviceTemplate(name, pascalName, camelName) {
862
+ return `import type { PaginatedResult, PaginationParams } from '../../types/index.js';
863
+ import { NotFoundError, ConflictError } from '../../utils/errors.js';
864
+ import { ${pascalName}Repository, create${pascalName}Repository } from './${name}.repository.js';
865
+ import type { ${pascalName}, Create${pascalName}Data, Update${pascalName}Data, ${pascalName}Filters } from './${name}.types.js';
866
+ import { logger } from '../../core/logger.js';
867
+
868
+ export class ${pascalName}Service {
869
+ constructor(private repository: ${pascalName}Repository) {}
870
+
871
+ async findById(id: string): Promise<${pascalName} | null> {
872
+ return this.repository.findById(id);
873
+ }
874
+
875
+ async findMany(
876
+ params: PaginationParams,
877
+ filters?: ${pascalName}Filters
878
+ ): Promise<PaginatedResult<${pascalName}>> {
879
+ return this.repository.findMany(params, filters);
880
+ }
881
+
882
+ async create(data: Create${pascalName}Data): Promise<${pascalName}> {
883
+ const item = await this.repository.create(data);
884
+ logger.info({ ${camelName}Id: item.id }, '${pascalName} created');
885
+ return item;
886
+ }
887
+
888
+ async update(id: string, data: Update${pascalName}Data): Promise<${pascalName}> {
889
+ const existing = await this.repository.findById(id);
890
+ if (!existing) {
891
+ throw new NotFoundError('${pascalName}');
892
+ }
893
+
894
+ const updated = await this.repository.update(id, data);
895
+ if (!updated) {
896
+ throw new NotFoundError('${pascalName}');
897
+ }
898
+
899
+ logger.info({ ${camelName}Id: id }, '${pascalName} updated');
900
+ return updated;
901
+ }
902
+
903
+ async delete(id: string): Promise<void> {
904
+ const existing = await this.repository.findById(id);
905
+ if (!existing) {
906
+ throw new NotFoundError('${pascalName}');
907
+ }
908
+
909
+ await this.repository.delete(id);
910
+ logger.info({ ${camelName}Id: id }, '${pascalName} deleted');
911
+ }
912
+ }
913
+
914
+ export function create${pascalName}Service(repository?: ${pascalName}Repository): ${pascalName}Service {
915
+ return new ${pascalName}Service(repository || create${pascalName}Repository());
916
+ }
917
+ `;
918
+ }
919
+
920
+ // src/cli/templates/repository.ts
921
+ function repositoryTemplate(name, pascalName, camelName, pluralName) {
922
+ return `import { randomUUID } from 'crypto';
923
+ import type { PaginatedResult, PaginationParams } from '../../types/index.js';
924
+ import { createPaginatedResult, getSkip } from '../../utils/pagination.js';
925
+ import type { ${pascalName}, Create${pascalName}Data, Update${pascalName}Data, ${pascalName}Filters } from './${name}.types.js';
926
+
927
+ // In-memory storage (will be replaced by Prisma in production)
928
+ const ${pluralName} = new Map<string, ${pascalName}>();
929
+
930
+ export class ${pascalName}Repository {
931
+ async findById(id: string): Promise<${pascalName} | null> {
932
+ return ${pluralName}.get(id) || null;
933
+ }
934
+
935
+ async findMany(
936
+ params: PaginationParams,
937
+ filters?: ${pascalName}Filters
938
+ ): Promise<PaginatedResult<${pascalName}>> {
939
+ let items = Array.from(${pluralName}.values());
940
+
941
+ // Apply filters
942
+ if (filters?.search) {
943
+ const search = filters.search.toLowerCase();
944
+ items = items.filter((item) =>
945
+ JSON.stringify(item).toLowerCase().includes(search)
946
+ );
947
+ }
948
+
949
+ // Sort
950
+ if (params.sortBy) {
951
+ const sortKey = params.sortBy as keyof ${pascalName};
952
+ items.sort((a, b) => {
953
+ const aVal = a[sortKey];
954
+ const bVal = b[sortKey];
955
+ if (aVal === undefined || bVal === undefined) return 0;
956
+ if (aVal < bVal) return params.sortOrder === 'desc' ? 1 : -1;
957
+ if (aVal > bVal) return params.sortOrder === 'desc' ? -1 : 1;
958
+ return 0;
959
+ });
960
+ }
961
+
962
+ const total = items.length;
963
+ const skip = getSkip(params);
964
+ const data = items.slice(skip, skip + params.limit);
965
+
966
+ return createPaginatedResult(data, total, params);
967
+ }
968
+
969
+ async create(data: Create${pascalName}Data): Promise<${pascalName}> {
970
+ const now = new Date();
971
+ const item: ${pascalName} = {
972
+ id: randomUUID(),
973
+ ...data,
974
+ createdAt: now,
975
+ updatedAt: now,
976
+ };
977
+
978
+ ${pluralName}.set(item.id, item);
979
+ return item;
980
+ }
981
+
982
+ async update(id: string, data: Update${pascalName}Data): Promise<${pascalName} | null> {
983
+ const item = ${pluralName}.get(id);
984
+ if (!item) return null;
985
+
986
+ const updated: ${pascalName} = {
987
+ ...item,
988
+ ...data,
989
+ updatedAt: new Date(),
990
+ };
991
+
992
+ ${pluralName}.set(id, updated);
993
+ return updated;
994
+ }
995
+
996
+ async delete(id: string): Promise<boolean> {
997
+ return ${pluralName}.delete(id);
998
+ }
999
+
1000
+ async count(filters?: ${pascalName}Filters): Promise<number> {
1001
+ if (!filters) return ${pluralName}.size;
1002
+
1003
+ let count = 0;
1004
+ for (const item of ${pluralName}.values()) {
1005
+ if (filters.search) {
1006
+ const search = filters.search.toLowerCase();
1007
+ if (!JSON.stringify(item).toLowerCase().includes(search)) continue;
1008
+ }
1009
+ count++;
1010
+ }
1011
+ return count;
1012
+ }
1013
+
1014
+ // Clear all (for testing)
1015
+ async clear(): Promise<void> {
1016
+ ${pluralName}.clear();
1017
+ }
1018
+ }
1019
+
1020
+ export function create${pascalName}Repository(): ${pascalName}Repository {
1021
+ return new ${pascalName}Repository();
1022
+ }
1023
+ `;
1024
+ }
1025
+
1026
+ // src/cli/templates/types.ts
1027
+ function typesTemplate(name, pascalName) {
1028
+ return `import type { BaseEntity } from '../../types/index.js';
1029
+
1030
+ export interface ${pascalName} extends BaseEntity {
1031
+ // Add your ${pascalName} specific fields here
1032
+ name: string;
1033
+ description?: string;
1034
+ // status?: string;
1035
+ // metadata?: Record<string, unknown>;
1036
+ }
1037
+
1038
+ export interface Create${pascalName}Data {
1039
+ name: string;
1040
+ description?: string;
1041
+ }
1042
+
1043
+ export interface Update${pascalName}Data {
1044
+ name?: string;
1045
+ description?: string;
1046
+ }
1047
+
1048
+ export interface ${pascalName}Filters {
1049
+ search?: string;
1050
+ // Add more filters as needed
1051
+ }
1052
+ `;
1053
+ }
1054
+
1055
+ // src/cli/templates/schemas.ts
1056
+ function schemasTemplate(name, pascalName, camelName) {
1057
+ return `import { z } from 'zod';
1058
+
1059
+ export const create${pascalName}Schema = z.object({
1060
+ name: z.string().min(1, 'Name is required').max(255),
1061
+ description: z.string().max(1000).optional(),
1062
+ });
1063
+
1064
+ export const update${pascalName}Schema = z.object({
1065
+ name: z.string().min(1).max(255).optional(),
1066
+ description: z.string().max(1000).optional(),
1067
+ });
1068
+
1069
+ export const ${camelName}QuerySchema = z.object({
1070
+ page: z.string().transform(Number).optional(),
1071
+ limit: z.string().transform(Number).optional(),
1072
+ sortBy: z.string().optional(),
1073
+ sortOrder: z.enum(['asc', 'desc']).optional(),
1074
+ search: z.string().optional(),
1075
+ });
1076
+
1077
+ export type Create${pascalName}Input = z.infer<typeof create${pascalName}Schema>;
1078
+ export type Update${pascalName}Input = z.infer<typeof update${pascalName}Schema>;
1079
+ export type ${pascalName}QueryInput = z.infer<typeof ${camelName}QuerySchema>;
1080
+ `;
1081
+ }
1082
+
1083
+ // src/cli/templates/routes.ts
1084
+ function routesTemplate(name, pascalName, camelName, pluralName, fields = []) {
1085
+ const serializedFields = JSON.stringify(fields, null, 2);
1086
+ return `import type { FastifyInstance } from 'fastify';
1087
+ import type { ${pascalName}Controller } from './${name}.controller.js';
1088
+ import type { AuthService } from '../auth/auth.service.js';
1089
+ import { createAuthMiddleware, createRoleMiddleware } from '../auth/auth.middleware.js';
1090
+ import { generateRouteSchema } from '../swagger/schema-builder.js';
1091
+ import type { FieldDefinition } from '../cli/utils/field-parser.js';
1092
+
1093
+ const ${camelName}Fields: FieldDefinition[] = ${serializedFields};
1094
+ const ${camelName}Schemas = {
1095
+ list: generateRouteSchema('${pascalName}', ${camelName}Fields, 'list'),
1096
+ get: generateRouteSchema('${pascalName}', ${camelName}Fields, 'get'),
1097
+ create: generateRouteSchema('${pascalName}', ${camelName}Fields, 'create'),
1098
+ update: generateRouteSchema('${pascalName}', ${camelName}Fields, 'update'),
1099
+ delete: generateRouteSchema('${pascalName}', ${camelName}Fields, 'delete'),
1100
+ };
1101
+
1102
+ export function register${pascalName}Routes(
1103
+ app: FastifyInstance,
1104
+ controller: ${pascalName}Controller,
1105
+ authService: AuthService
1106
+ ): void {
1107
+ const authenticate = createAuthMiddleware(authService);
1108
+ const isAdmin = createRoleMiddleware(['admin', 'super_admin']);
1109
+
1110
+ // Public routes (if any)
1111
+ // app.get('/${pluralName}/public', controller.publicList.bind(controller));
1112
+
1113
+ // Protected routes
1114
+ app.get(
1115
+ '/${pluralName}',
1116
+ { preHandler: [authenticate], ...${camelName}Schemas.list },
1117
+ controller.list.bind(controller)
1118
+ );
1119
+
1120
+ app.get(
1121
+ '/${pluralName}/:id',
1122
+ { preHandler: [authenticate], ...${camelName}Schemas.get },
1123
+ controller.getById.bind(controller)
1124
+ );
1125
+
1126
+ app.post(
1127
+ '/${pluralName}',
1128
+ { preHandler: [authenticate], ...${camelName}Schemas.create },
1129
+ controller.create.bind(controller)
1130
+ );
1131
+
1132
+ app.patch(
1133
+ '/${pluralName}/:id',
1134
+ { preHandler: [authenticate], ...${camelName}Schemas.update },
1135
+ controller.update.bind(controller)
1136
+ );
1137
+
1138
+ app.delete(
1139
+ '/${pluralName}/:id',
1140
+ { preHandler: [authenticate, isAdmin], ...${camelName}Schemas.delete },
1141
+ controller.delete.bind(controller)
1142
+ );
1143
+ }
1144
+ `;
1145
+ }
1146
+
1147
+ // src/cli/templates/module-index.ts
1148
+ function moduleIndexTemplate(name, pascalName, camelName) {
1149
+ return `import type { FastifyInstance } from 'fastify';
1150
+ import { logger } from '../../core/logger.js';
1151
+ import { ${pascalName}Service, create${pascalName}Service } from './${name}.service.js';
1152
+ import { ${pascalName}Controller, create${pascalName}Controller } from './${name}.controller.js';
1153
+ import { ${pascalName}Repository, create${pascalName}Repository } from './${name}.repository.js';
1154
+ import { register${pascalName}Routes } from './${name}.routes.js';
1155
+ import type { AuthService } from '../auth/auth.service.js';
1156
+
1157
+ export async function register${pascalName}Module(
1158
+ app: FastifyInstance,
1159
+ authService: AuthService
1160
+ ): Promise<void> {
1161
+ // Create repository and service
1162
+ const repository = create${pascalName}Repository();
1163
+ const ${camelName}Service = create${pascalName}Service(repository);
1164
+
1165
+ // Create controller
1166
+ const ${camelName}Controller = create${pascalName}Controller(${camelName}Service);
1167
+
1168
+ // Register routes
1169
+ register${pascalName}Routes(app, ${camelName}Controller, authService);
1170
+
1171
+ logger.info('${pascalName} module registered');
1172
+ }
1173
+
1174
+ export { ${pascalName}Service, create${pascalName}Service } from './${name}.service.js';
1175
+ export { ${pascalName}Controller, create${pascalName}Controller } from './${name}.controller.js';
1176
+ export { ${pascalName}Repository, create${pascalName}Repository } from './${name}.repository.js';
1177
+ export * from './${name}.types.js';
1178
+ export * from './${name}.schemas.js';
1179
+ `;
1180
+ }
1181
+
1182
+ // src/cli/templates/prisma-model.ts
1183
+ function prismaModelTemplate(name, pascalName, tableName) {
1184
+ return `
1185
+ // Add this model to your prisma/schema.prisma file
1186
+
1187
+ model ${pascalName} {
1188
+ id String @id @default(uuid())
1189
+ name String
1190
+ description String?
1191
+
1192
+ createdAt DateTime @default(now())
1193
+ updatedAt DateTime @updatedAt
1194
+
1195
+ @@index([name])
1196
+ @@map("${tableName}")
1197
+ }
1198
+ `;
1199
+ }
1200
+
1201
+ // src/cli/templates/dynamic-types.ts
1202
+ function dynamicTypesTemplate(name, pascalName, fields) {
1203
+ const fieldLines = fields.map((field) => {
1204
+ const tsType = tsTypeMap[field.type];
1205
+ const arrayMark = field.isArray ? "[]" : "";
1206
+ const optionalMark = field.isOptional ? "?" : "";
1207
+ return ` ${field.name}${optionalMark}: ${tsType}${arrayMark};`;
1208
+ });
1209
+ const createFieldLines = fields.filter((f) => !f.isOptional).map((field) => {
1210
+ const tsType = tsTypeMap[field.type];
1211
+ const arrayMark = field.isArray ? "[]" : "";
1212
+ return ` ${field.name}: ${tsType}${arrayMark};`;
1213
+ });
1214
+ const createOptionalLines = fields.filter((f) => f.isOptional).map((field) => {
1215
+ const tsType = tsTypeMap[field.type];
1216
+ const arrayMark = field.isArray ? "[]" : "";
1217
+ return ` ${field.name}?: ${tsType}${arrayMark};`;
1218
+ });
1219
+ const updateFieldLines = fields.map((field) => {
1220
+ const tsType = tsTypeMap[field.type];
1221
+ const arrayMark = field.isArray ? "[]" : "";
1222
+ return ` ${field.name}?: ${tsType}${arrayMark};`;
1223
+ });
1224
+ return `import type { BaseEntity } from '../../types/index.js';
1225
+
1226
+ export interface ${pascalName} extends BaseEntity {
1227
+ ${fieldLines.join("\n")}
1228
+ }
1229
+
1230
+ export interface Create${pascalName}Data {
1231
+ ${[...createFieldLines, ...createOptionalLines].join("\n")}
1232
+ }
1233
+
1234
+ export interface Update${pascalName}Data {
1235
+ ${updateFieldLines.join("\n")}
1236
+ }
1237
+
1238
+ export interface ${pascalName}Filters {
1239
+ search?: string;
1240
+ ${fields.filter((f) => ["string", "enum", "boolean"].includes(f.type)).map((f) => ` ${f.name}?: ${tsTypeMap[f.type]};`).join("\n")}
1241
+ }
1242
+ `;
1243
+ }
1244
+
1245
+ // src/cli/templates/dynamic-schemas.ts
1246
+ function dynamicSchemasTemplate(name, pascalName, camelName, fields, validator = "zod") {
1247
+ switch (validator) {
1248
+ case "joi":
1249
+ return generateJoiSchemas(pascalName, camelName, fields);
1250
+ case "yup":
1251
+ return generateYupSchemas(pascalName, camelName, fields);
1252
+ default:
1253
+ return generateZodSchemas(pascalName, camelName, fields);
1254
+ }
1255
+ }
1256
+ function generateZodSchemas(pascalName, camelName, fields) {
1257
+ const createFields = fields.map((field) => {
1258
+ let validator = zodTypeMap[field.type];
1259
+ if (field.isArray) {
1260
+ validator = `z.array(${validator})`;
1261
+ }
1262
+ if (field.isOptional) {
1263
+ validator += ".optional()";
1264
+ }
1265
+ if (field.defaultValue) {
1266
+ validator += `.default(${field.defaultValue})`;
1267
+ }
1268
+ if (field.type === "string" && !field.isOptional) {
1269
+ validator = validator.replace("z.string()", "z.string().min(1)");
1270
+ }
1271
+ return ` ${field.name}: ${validator},`;
1272
+ });
1273
+ const updateFields = fields.map((field) => {
1274
+ let validator = zodTypeMap[field.type];
1275
+ if (field.isArray) {
1276
+ validator = `z.array(${validator})`;
1277
+ }
1278
+ validator += ".optional()";
1279
+ return ` ${field.name}: ${validator},`;
1280
+ });
1281
+ return `import { z } from 'zod';
1282
+
1283
+ export const create${pascalName}Schema = z.object({
1284
+ ${createFields.join("\n")}
1285
+ });
1286
+
1287
+ export const update${pascalName}Schema = z.object({
1288
+ ${updateFields.join("\n")}
1289
+ });
1290
+
1291
+ export const ${camelName}QuerySchema = z.object({
1292
+ page: z.string().transform(Number).optional(),
1293
+ limit: z.string().transform(Number).optional(),
1294
+ sortBy: z.string().optional(),
1295
+ sortOrder: z.enum(['asc', 'desc']).optional(),
1296
+ search: z.string().optional(),
1297
+ });
1298
+
1299
+ export type Create${pascalName}Input = z.infer<typeof create${pascalName}Schema>;
1300
+ export type Update${pascalName}Input = z.infer<typeof update${pascalName}Schema>;
1301
+ export type ${pascalName}QueryInput = z.infer<typeof ${camelName}QuerySchema>;
1302
+ `;
1303
+ }
1304
+ function generateJoiSchemas(pascalName, camelName, fields) {
1305
+ const createFields = fields.map((field) => {
1306
+ let validator = joiTypeMap[field.type];
1307
+ if (field.isArray) {
1308
+ validator = `Joi.array().items(${validator})`;
1309
+ }
1310
+ if (!field.isOptional) {
1311
+ validator += ".required()";
1312
+ }
1313
+ if (field.defaultValue) {
1314
+ validator += `.default(${field.defaultValue})`;
1315
+ }
1316
+ return ` ${field.name}: ${validator},`;
1317
+ });
1318
+ const updateFields = fields.map((field) => {
1319
+ let validator = joiTypeMap[field.type];
1320
+ if (field.isArray) {
1321
+ validator = `Joi.array().items(${validator})`;
1322
+ }
1323
+ return ` ${field.name}: ${validator},`;
1324
+ });
1325
+ return `import Joi from 'joi';
1326
+
1327
+ export const create${pascalName}Schema = Joi.object({
1328
+ ${createFields.join("\n")}
1329
+ });
1330
+
1331
+ export const update${pascalName}Schema = Joi.object({
1332
+ ${updateFields.join("\n")}
1333
+ });
1334
+
1335
+ export const ${camelName}QuerySchema = Joi.object({
1336
+ page: Joi.number().integer().min(1),
1337
+ limit: Joi.number().integer().min(1).max(100),
1338
+ sortBy: Joi.string(),
1339
+ sortOrder: Joi.string().valid('asc', 'desc'),
1340
+ search: Joi.string(),
1341
+ });
1342
+
1343
+ export type Create${pascalName}Input = {
1344
+ ${fields.map((f) => ` ${f.name}${f.isOptional ? "?" : ""}: ${getJsType(f)};`).join("\n")}
1345
+ };
1346
+
1347
+ export type Update${pascalName}Input = Partial<Create${pascalName}Input>;
1348
+ export type ${pascalName}QueryInput = {
1349
+ page?: number;
1350
+ limit?: number;
1351
+ sortBy?: string;
1352
+ sortOrder?: 'asc' | 'desc';
1353
+ search?: string;
1354
+ };
1355
+ `;
1356
+ }
1357
+ function generateYupSchemas(pascalName, camelName, fields) {
1358
+ const createFields = fields.map((field) => {
1359
+ let validator = yupTypeMap[field.type];
1360
+ if (field.isArray) {
1361
+ validator = `yup.array().of(${validator})`;
1362
+ }
1363
+ if (!field.isOptional) {
1364
+ validator += ".required()";
1365
+ }
1366
+ if (field.defaultValue) {
1367
+ validator += `.default(${field.defaultValue})`;
1368
+ }
1369
+ return ` ${field.name}: ${validator},`;
1370
+ });
1371
+ const updateFields = fields.map((field) => {
1372
+ let validator = yupTypeMap[field.type];
1373
+ if (field.isArray) {
1374
+ validator = `yup.array().of(${validator})`;
1375
+ }
1376
+ validator += ".optional()";
1377
+ return ` ${field.name}: ${validator},`;
1378
+ });
1379
+ return `import * as yup from 'yup';
1380
+
1381
+ export const create${pascalName}Schema = yup.object({
1382
+ ${createFields.join("\n")}
1383
+ });
1384
+
1385
+ export const update${pascalName}Schema = yup.object({
1386
+ ${updateFields.join("\n")}
1387
+ });
1388
+
1389
+ export const ${camelName}QuerySchema = yup.object({
1390
+ page: yup.number().integer().min(1),
1391
+ limit: yup.number().integer().min(1).max(100),
1392
+ sortBy: yup.string(),
1393
+ sortOrder: yup.string().oneOf(['asc', 'desc']),
1394
+ search: yup.string(),
1395
+ });
1396
+
1397
+ export type Create${pascalName}Input = yup.InferType<typeof create${pascalName}Schema>;
1398
+ export type Update${pascalName}Input = yup.InferType<typeof update${pascalName}Schema>;
1399
+ export type ${pascalName}QueryInput = yup.InferType<typeof ${camelName}QuerySchema>;
1400
+ `;
1401
+ }
1402
+ function getJsType(field) {
1403
+ const typeMap = {
1404
+ string: "string",
1405
+ number: "number",
1406
+ boolean: "boolean",
1407
+ date: "Date",
1408
+ datetime: "Date",
1409
+ text: "string",
1410
+ json: "Record<string, unknown>",
1411
+ email: "string",
1412
+ url: "string",
1413
+ uuid: "string",
1414
+ int: "number",
1415
+ float: "number",
1416
+ decimal: "number",
1417
+ enum: "string"
1418
+ };
1419
+ const baseType = typeMap[field.type] || "unknown";
1420
+ return field.isArray ? `${baseType}[]` : baseType;
1421
+ }
1422
+
1423
+ // src/cli/templates/dynamic-prisma.ts
1424
+ function dynamicPrismaTemplate(modelName, tableName, fields) {
1425
+ const fieldLines = [];
1426
+ for (const field of fields) {
1427
+ const prismaType = prismaTypeMap[field.type];
1428
+ const optionalMark = field.isOptional ? "?" : "";
1429
+ const arrayMark = field.isArray ? "[]" : "";
1430
+ const annotations = [];
1431
+ if (field.isUnique) {
1432
+ annotations.push("@unique");
1433
+ }
1434
+ if (field.defaultValue !== void 0) {
1435
+ if (field.type === "boolean") {
1436
+ annotations.push(`@default(${field.defaultValue})`);
1437
+ } else if (field.type === "number" || field.type === "int" || field.type === "float") {
1438
+ annotations.push(`@default(${field.defaultValue})`);
1439
+ } else {
1440
+ annotations.push(`@default("${field.defaultValue}")`);
1441
+ }
1442
+ }
1443
+ if (field.type === "text") {
1444
+ annotations.push("@db.Text");
1445
+ }
1446
+ if (field.type === "decimal") {
1447
+ annotations.push("@db.Decimal(10, 2)");
1448
+ }
1449
+ const annotationStr = annotations.length > 0 ? " " + annotations.join(" ") : "";
1450
+ const typePart = `${prismaType}${optionalMark}${arrayMark}`;
1451
+ fieldLines.push(` ${field.name.padEnd(15)} ${typePart.padEnd(12)}${annotationStr}`);
1452
+ }
1453
+ const indexLines = [];
1454
+ const uniqueFields = fields.filter((f) => f.isUnique);
1455
+ for (const field of uniqueFields) {
1456
+ indexLines.push(` @@index([${field.name}])`);
1457
+ }
1458
+ const searchableFields = fields.filter(
1459
+ (f) => ["string", "email"].includes(f.type) && !f.isUnique
1460
+ );
1461
+ if (searchableFields.length > 0) {
1462
+ const firstSearchable = searchableFields[0];
1463
+ if (firstSearchable) {
1464
+ indexLines.push(` @@index([${firstSearchable.name}])`);
1465
+ }
1466
+ }
1467
+ return `
1468
+ // ==========================================
1469
+ // Add this model to your prisma/schema.prisma file
1470
+ // ==========================================
1471
+
1472
+ model ${modelName} {
1473
+ id String @id @default(uuid())
1474
+
1475
+ ${fieldLines.join("\n")}
1476
+
1477
+ createdAt DateTime @default(now())
1478
+ updatedAt DateTime @updatedAt
1479
+
1480
+ ${indexLines.join("\n")}
1481
+ @@map("${tableName}")
1482
+ }
1483
+
1484
+ // ==========================================
1485
+ // After adding the model, run:
1486
+ // npm run db:migrate -- --name add_${tableName}
1487
+ // ==========================================
1488
+ `;
1489
+ }
1490
+
1491
+ // src/cli/utils/docs-generator.ts
1492
+ var import_promises3 = __toESM(require("fs/promises"), 1);
1493
+ var import_path3 = __toESM(require("path"), 1);
1494
+ var import_ora2 = __toESM(require("ora"), 1);
1495
+
1496
+ // src/core/server.ts
1497
+ var import_fastify = __toESM(require("fastify"), 1);
1498
+
1499
+ // src/core/logger.ts
1500
+ var import_pino = __toESM(require("pino"), 1);
1501
+ var defaultConfig = {
1502
+ level: process.env.LOG_LEVEL || "info",
1503
+ pretty: process.env.NODE_ENV !== "production",
1504
+ name: "servcraft"
1505
+ };
1506
+ function createLogger(config2 = {}) {
1507
+ const mergedConfig = { ...defaultConfig, ...config2 };
1508
+ const transport = mergedConfig.pretty ? {
1509
+ target: "pino-pretty",
1510
+ options: {
1511
+ colorize: true,
1512
+ translateTime: "SYS:standard",
1513
+ ignore: "pid,hostname"
1514
+ }
1515
+ } : void 0;
1516
+ return (0, import_pino.default)({
1517
+ name: mergedConfig.name,
1518
+ level: mergedConfig.level,
1519
+ transport,
1520
+ formatters: {
1521
+ level: (label) => ({ level: label })
1522
+ },
1523
+ timestamp: import_pino.default.stdTimeFunctions.isoTime
1524
+ });
1525
+ }
1526
+ var logger = createLogger();
1527
+
1528
+ // src/core/server.ts
1529
+ var defaultConfig2 = {
1530
+ port: parseInt(process.env.PORT || "3000", 10),
1531
+ host: process.env.HOST || "0.0.0.0",
1532
+ trustProxy: true,
1533
+ bodyLimit: 1048576,
1534
+ // 1MB
1535
+ requestTimeout: 3e4
1536
+ // 30s
1537
+ };
1538
+ var Server = class {
1539
+ app;
1540
+ config;
1541
+ logger;
1542
+ isShuttingDown = false;
1543
+ constructor(config2 = {}) {
1544
+ this.config = { ...defaultConfig2, ...config2 };
1545
+ this.logger = this.config.logger || logger;
1546
+ const fastifyOptions = {
1547
+ logger: this.logger,
1548
+ trustProxy: this.config.trustProxy,
1549
+ bodyLimit: this.config.bodyLimit,
1550
+ requestTimeout: this.config.requestTimeout
1551
+ };
1552
+ this.app = (0, import_fastify.default)(fastifyOptions);
1553
+ this.setupHealthCheck();
1554
+ this.setupGracefulShutdown();
1555
+ }
1556
+ get instance() {
1557
+ return this.app;
1558
+ }
1559
+ setupHealthCheck() {
1560
+ this.app.get("/health", async (_request, reply) => {
1561
+ const healthcheck = {
1562
+ status: "ok",
1563
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1564
+ uptime: process.uptime(),
1565
+ memory: process.memoryUsage(),
1566
+ version: process.env.npm_package_version || "0.1.0"
1567
+ };
1568
+ return reply.status(200).send(healthcheck);
1569
+ });
1570
+ this.app.get("/ready", async (_request, reply) => {
1571
+ if (this.isShuttingDown) {
1572
+ return reply.status(503).send({ status: "shutting_down" });
1573
+ }
1574
+ return reply.status(200).send({ status: "ready" });
1575
+ });
1576
+ }
1577
+ setupGracefulShutdown() {
1578
+ const signals = ["SIGINT", "SIGTERM", "SIGQUIT"];
1579
+ signals.forEach((signal) => {
1580
+ process.on(signal, async () => {
1581
+ this.logger.info(`Received ${signal}, starting graceful shutdown...`);
1582
+ await this.shutdown();
1583
+ });
1584
+ });
1585
+ process.on("uncaughtException", async (error2) => {
1586
+ this.logger.error({ err: error2 }, "Uncaught exception");
1587
+ await this.shutdown(1);
1588
+ });
1589
+ process.on("unhandledRejection", async (reason) => {
1590
+ this.logger.error({ err: reason }, "Unhandled rejection");
1591
+ await this.shutdown(1);
1592
+ });
1593
+ }
1594
+ async shutdown(exitCode = 0) {
1595
+ if (this.isShuttingDown) {
1596
+ return;
1597
+ }
1598
+ this.isShuttingDown = true;
1599
+ this.logger.info("Graceful shutdown initiated...");
1600
+ const shutdownTimeout = setTimeout(() => {
1601
+ this.logger.error("Graceful shutdown timeout, forcing exit");
1602
+ process.exit(1);
1603
+ }, 3e4);
1604
+ try {
1605
+ await this.app.close();
1606
+ this.logger.info("Server closed successfully");
1607
+ clearTimeout(shutdownTimeout);
1608
+ process.exit(exitCode);
1609
+ } catch (error2) {
1610
+ this.logger.error({ err: error2 }, "Error during shutdown");
1611
+ clearTimeout(shutdownTimeout);
1612
+ process.exit(1);
1613
+ }
1614
+ }
1615
+ async start() {
1616
+ try {
1617
+ await this.app.listen({
1618
+ port: this.config.port,
1619
+ host: this.config.host
1620
+ });
1621
+ this.logger.info(`Server listening on ${this.config.host}:${this.config.port}`);
1622
+ } catch (error2) {
1623
+ this.logger.error({ err: error2 }, "Failed to start server");
1624
+ throw error2;
1625
+ }
1626
+ }
1627
+ };
1628
+ function createServer(config2 = {}) {
1629
+ return new Server(config2);
1630
+ }
1631
+
1632
+ // src/utils/errors.ts
1633
+ var AppError = class _AppError extends Error {
1634
+ statusCode;
1635
+ isOperational;
1636
+ errors;
1637
+ constructor(message, statusCode = 500, isOperational = true, errors) {
1638
+ super(message);
1639
+ this.statusCode = statusCode;
1640
+ this.isOperational = isOperational;
1641
+ this.errors = errors;
1642
+ Object.setPrototypeOf(this, _AppError.prototype);
1643
+ Error.captureStackTrace(this, this.constructor);
1644
+ }
1645
+ };
1646
+ var NotFoundError = class extends AppError {
1647
+ constructor(resource = "Resource") {
1648
+ super(`${resource} not found`, 404);
1649
+ }
1650
+ };
1651
+ var UnauthorizedError = class extends AppError {
1652
+ constructor(message = "Unauthorized") {
1653
+ super(message, 401);
1654
+ }
1655
+ };
1656
+ var ForbiddenError = class extends AppError {
1657
+ constructor(message = "Forbidden") {
1658
+ super(message, 403);
1659
+ }
1660
+ };
1661
+ var BadRequestError = class extends AppError {
1662
+ constructor(message = "Bad request", errors) {
1663
+ super(message, 400, true, errors);
1664
+ }
1665
+ };
1666
+ var ConflictError = class extends AppError {
1667
+ constructor(message = "Resource already exists") {
1668
+ super(message, 409);
1669
+ }
1670
+ };
1671
+ var ValidationError = class extends AppError {
1672
+ constructor(errors) {
1673
+ super("Validation failed", 422, true, errors);
1674
+ }
1675
+ };
1676
+ function isAppError(error2) {
1677
+ return error2 instanceof AppError;
1678
+ }
1679
+
1680
+ // src/config/env.ts
1681
+ var import_zod = require("zod");
1682
+ var import_dotenv = __toESM(require("dotenv"), 1);
1683
+ import_dotenv.default.config();
1684
+ var envSchema = import_zod.z.object({
1685
+ // Server
1686
+ NODE_ENV: import_zod.z.enum(["development", "staging", "production", "test"]).default("development"),
1687
+ PORT: import_zod.z.string().transform(Number).default("3000"),
1688
+ HOST: import_zod.z.string().default("0.0.0.0"),
1689
+ // Database
1690
+ DATABASE_URL: import_zod.z.string().optional(),
1691
+ // JWT
1692
+ JWT_SECRET: import_zod.z.string().min(32).optional(),
1693
+ JWT_ACCESS_EXPIRES_IN: import_zod.z.string().default("15m"),
1694
+ JWT_REFRESH_EXPIRES_IN: import_zod.z.string().default("7d"),
1695
+ // Security
1696
+ CORS_ORIGIN: import_zod.z.string().default("*"),
1697
+ RATE_LIMIT_MAX: import_zod.z.string().transform(Number).default("100"),
1698
+ RATE_LIMIT_WINDOW_MS: import_zod.z.string().transform(Number).default("60000"),
1699
+ // Email
1700
+ SMTP_HOST: import_zod.z.string().optional(),
1701
+ SMTP_PORT: import_zod.z.string().transform(Number).optional(),
1702
+ SMTP_USER: import_zod.z.string().optional(),
1703
+ SMTP_PASS: import_zod.z.string().optional(),
1704
+ SMTP_FROM: import_zod.z.string().optional(),
1705
+ // Redis (optional)
1706
+ REDIS_URL: import_zod.z.string().optional(),
1707
+ // Swagger/OpenAPI
1708
+ SWAGGER_ENABLED: import_zod.z.union([import_zod.z.literal("true"), import_zod.z.literal("false")]).default("true").transform((val) => val === "true"),
1709
+ SWAGGER_ROUTE: import_zod.z.string().default("/docs"),
1710
+ SWAGGER_TITLE: import_zod.z.string().default("Servcraft API"),
1711
+ SWAGGER_DESCRIPTION: import_zod.z.string().default("API documentation"),
1712
+ SWAGGER_VERSION: import_zod.z.string().default("1.0.0"),
1713
+ // Logging
1714
+ LOG_LEVEL: import_zod.z.enum(["fatal", "error", "warn", "info", "debug", "trace"]).default("info")
1715
+ });
1716
+ function validateEnv() {
1717
+ const parsed = envSchema.safeParse(process.env);
1718
+ if (!parsed.success) {
1719
+ logger.error({ errors: parsed.error.flatten().fieldErrors }, "Invalid environment variables");
1720
+ throw new Error("Invalid environment variables");
1721
+ }
1722
+ return parsed.data;
1723
+ }
1724
+ var env = validateEnv();
1725
+ function isProduction() {
1726
+ return env.NODE_ENV === "production";
1727
+ }
1728
+
1729
+ // src/config/index.ts
1730
+ function parseCorsOrigin(origin) {
1731
+ if (origin === "*") return "*";
1732
+ if (origin.includes(",")) {
1733
+ return origin.split(",").map((o) => o.trim());
1734
+ }
1735
+ return origin;
1736
+ }
1737
+ function createConfig() {
1738
+ return {
1739
+ env,
1740
+ server: {
1741
+ port: env.PORT,
1742
+ host: env.HOST
1743
+ },
1744
+ jwt: {
1745
+ secret: env.JWT_SECRET || "change-me-in-production-please-32chars",
1746
+ accessExpiresIn: env.JWT_ACCESS_EXPIRES_IN,
1747
+ refreshExpiresIn: env.JWT_REFRESH_EXPIRES_IN
1748
+ },
1749
+ security: {
1750
+ corsOrigin: parseCorsOrigin(env.CORS_ORIGIN),
1751
+ rateLimit: {
1752
+ max: env.RATE_LIMIT_MAX,
1753
+ windowMs: env.RATE_LIMIT_WINDOW_MS
1754
+ }
1755
+ },
1756
+ email: {
1757
+ host: env.SMTP_HOST,
1758
+ port: env.SMTP_PORT,
1759
+ user: env.SMTP_USER,
1760
+ pass: env.SMTP_PASS,
1761
+ from: env.SMTP_FROM
1762
+ },
1763
+ database: {
1764
+ url: env.DATABASE_URL
1765
+ },
1766
+ redis: {
1767
+ url: env.REDIS_URL
1768
+ },
1769
+ swagger: {
1770
+ enabled: env.SWAGGER_ENABLED,
1771
+ route: env.SWAGGER_ROUTE,
1772
+ title: env.SWAGGER_TITLE,
1773
+ description: env.SWAGGER_DESCRIPTION,
1774
+ version: env.SWAGGER_VERSION
1775
+ }
1776
+ };
1777
+ }
1778
+ var config = createConfig();
1779
+
1780
+ // src/middleware/error-handler.ts
1781
+ function registerErrorHandler(app) {
1782
+ app.setErrorHandler(
1783
+ (error2, request, reply) => {
1784
+ logger.error(
1785
+ {
1786
+ err: error2,
1787
+ requestId: request.id,
1788
+ method: request.method,
1789
+ url: request.url
1790
+ },
1791
+ "Request error"
1792
+ );
1793
+ if (isAppError(error2)) {
1794
+ return reply.status(error2.statusCode).send({
1795
+ success: false,
1796
+ message: error2.message,
1797
+ errors: error2.errors,
1798
+ ...isProduction() ? {} : { stack: error2.stack }
1799
+ });
1800
+ }
1801
+ if ("validation" in error2 && error2.validation) {
1802
+ const errors = {};
1803
+ for (const err of error2.validation) {
1804
+ const field = err.instancePath?.replace("/", "") || "body";
1805
+ if (!errors[field]) {
1806
+ errors[field] = [];
1807
+ }
1808
+ errors[field].push(err.message || "Invalid value");
1809
+ }
1810
+ return reply.status(400).send({
1811
+ success: false,
1812
+ message: "Validation failed",
1813
+ errors
1814
+ });
1815
+ }
1816
+ if ("statusCode" in error2 && typeof error2.statusCode === "number") {
1817
+ return reply.status(error2.statusCode).send({
1818
+ success: false,
1819
+ message: error2.message,
1820
+ ...isProduction() ? {} : { stack: error2.stack }
1821
+ });
1822
+ }
1823
+ return reply.status(500).send({
1824
+ success: false,
1825
+ message: isProduction() ? "Internal server error" : error2.message,
1826
+ ...isProduction() ? {} : { stack: error2.stack }
1827
+ });
1828
+ }
1829
+ );
1830
+ app.setNotFoundHandler((request, reply) => {
1831
+ return reply.status(404).send({
1832
+ success: false,
1833
+ message: `Route ${request.method} ${request.url} not found`
1834
+ });
1835
+ });
1836
+ }
1837
+
1838
+ // src/middleware/security.ts
1839
+ var import_helmet = __toESM(require("@fastify/helmet"), 1);
1840
+ var import_cors = __toESM(require("@fastify/cors"), 1);
1841
+ var import_rate_limit = __toESM(require("@fastify/rate-limit"), 1);
1842
+ var defaultOptions = {
1843
+ helmet: true,
1844
+ cors: true,
1845
+ rateLimit: true
1846
+ };
1847
+ async function registerSecurity(app, options = {}) {
1848
+ const opts = { ...defaultOptions, ...options };
1849
+ if (opts.helmet) {
1850
+ await app.register(import_helmet.default, {
1851
+ contentSecurityPolicy: {
1852
+ directives: {
1853
+ defaultSrc: ["'self'"],
1854
+ styleSrc: ["'self'", "'unsafe-inline'"],
1855
+ scriptSrc: ["'self'"],
1856
+ imgSrc: ["'self'", "data:", "https:"]
1857
+ }
1858
+ },
1859
+ crossOriginEmbedderPolicy: false
1860
+ });
1861
+ logger.debug("Helmet security headers enabled");
1862
+ }
1863
+ if (opts.cors) {
1864
+ await app.register(import_cors.default, {
1865
+ origin: config.security.corsOrigin,
1866
+ credentials: true,
1867
+ methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
1868
+ allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
1869
+ exposedHeaders: ["X-Total-Count", "X-Page", "X-Limit"],
1870
+ maxAge: 86400
1871
+ // 24 hours
1872
+ });
1873
+ logger.debug({ origin: config.security.corsOrigin }, "CORS enabled");
1874
+ }
1875
+ if (opts.rateLimit) {
1876
+ await app.register(import_rate_limit.default, {
1877
+ max: config.security.rateLimit.max,
1878
+ timeWindow: config.security.rateLimit.windowMs,
1879
+ errorResponseBuilder: (_request, context) => ({
1880
+ success: false,
1881
+ message: "Too many requests, please try again later",
1882
+ retryAfter: context.after
1883
+ }),
1884
+ keyGenerator: (request) => {
1885
+ return request.headers["x-forwarded-for"]?.toString().split(",")[0] || request.ip || "unknown";
1886
+ }
1887
+ });
1888
+ logger.debug(
1889
+ {
1890
+ max: config.security.rateLimit.max,
1891
+ windowMs: config.security.rateLimit.windowMs
1892
+ },
1893
+ "Rate limiting enabled"
1894
+ );
1895
+ }
1896
+ }
1897
+
1898
+ // src/modules/swagger/swagger.service.ts
1899
+ var import_swagger = __toESM(require("@fastify/swagger"), 1);
1900
+ var import_swagger_ui = __toESM(require("@fastify/swagger-ui"), 1);
1901
+ var defaultConfig3 = {
1902
+ enabled: true,
1903
+ route: "/docs",
1904
+ title: "Servcraft API",
1905
+ description: "API documentation generated by Servcraft",
1906
+ version: "1.0.0",
1907
+ tags: [
1908
+ { name: "Auth", description: "Authentication endpoints" },
1909
+ { name: "Users", description: "User management endpoints" },
1910
+ { name: "Health", description: "Health check endpoints" }
1911
+ ]
1912
+ };
1913
+ async function registerSwagger(app, customConfig) {
1914
+ const swaggerConfig = { ...defaultConfig3, ...customConfig };
1915
+ if (swaggerConfig.enabled === false) {
1916
+ logger.info("Swagger documentation disabled");
1917
+ return;
1918
+ }
1919
+ await app.register(import_swagger.default, {
1920
+ openapi: {
1921
+ openapi: "3.0.3",
1922
+ info: {
1923
+ title: swaggerConfig.title,
1924
+ description: swaggerConfig.description,
1925
+ version: swaggerConfig.version,
1926
+ contact: swaggerConfig.contact,
1927
+ license: swaggerConfig.license
1928
+ },
1929
+ servers: swaggerConfig.servers || [
1930
+ {
1931
+ url: `http://localhost:${config.server.port}`,
1932
+ description: "Development server"
1933
+ }
1934
+ ],
1935
+ tags: swaggerConfig.tags,
1936
+ components: {
1937
+ securitySchemes: {
1938
+ bearerAuth: {
1939
+ type: "http",
1940
+ scheme: "bearer",
1941
+ bearerFormat: "JWT",
1942
+ description: "Enter your JWT token"
1943
+ }
1944
+ }
1945
+ }
1946
+ }
1947
+ });
1948
+ await app.register(import_swagger_ui.default, {
1949
+ routePrefix: swaggerConfig.route || "/docs",
1950
+ uiConfig: {
1951
+ docExpansion: "list",
1952
+ deepLinking: true,
1953
+ displayRequestDuration: true,
1954
+ filter: true,
1955
+ showExtensions: true,
1956
+ showCommonExtensions: true
1957
+ },
1958
+ staticCSP: true,
1959
+ transformStaticCSP: (header) => header
1960
+ });
1961
+ logger.info("Swagger documentation registered at /docs");
1962
+ }
1963
+ var commonResponses = {
1964
+ success: {
1965
+ type: "object",
1966
+ properties: {
1967
+ success: { type: "boolean", example: true },
1968
+ data: { type: "object" }
1969
+ }
1970
+ },
1971
+ error: {
1972
+ type: "object",
1973
+ properties: {
1974
+ success: { type: "boolean", example: false },
1975
+ message: { type: "string" },
1976
+ errors: {
1977
+ type: "object",
1978
+ additionalProperties: {
1979
+ type: "array",
1980
+ items: { type: "string" }
1981
+ }
1982
+ }
1983
+ }
1984
+ },
1985
+ unauthorized: {
1986
+ type: "object",
1987
+ properties: {
1988
+ success: { type: "boolean", example: false },
1989
+ message: { type: "string", example: "Unauthorized" }
1990
+ }
1991
+ },
1992
+ notFound: {
1993
+ type: "object",
1994
+ properties: {
1995
+ success: { type: "boolean", example: false },
1996
+ message: { type: "string", example: "Resource not found" }
1997
+ }
1998
+ },
1999
+ paginated: {
2000
+ type: "object",
2001
+ properties: {
2002
+ success: { type: "boolean", example: true },
2003
+ data: {
2004
+ type: "object",
2005
+ properties: {
2006
+ data: { type: "array", items: { type: "object" } },
2007
+ meta: {
2008
+ type: "object",
2009
+ properties: {
2010
+ total: { type: "number" },
2011
+ page: { type: "number" },
2012
+ limit: { type: "number" },
2013
+ totalPages: { type: "number" },
2014
+ hasNextPage: { type: "boolean" },
2015
+ hasPrevPage: { type: "boolean" }
2016
+ }
2017
+ }
2018
+ }
2019
+ }
2020
+ }
2021
+ }
2022
+ };
2023
+ var paginationQuery = {
2024
+ type: "object",
2025
+ properties: {
2026
+ page: { type: "integer", minimum: 1, default: 1, description: "Page number" },
2027
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Items per page" },
2028
+ sortBy: { type: "string", description: "Field to sort by" },
2029
+ sortOrder: { type: "string", enum: ["asc", "desc"], default: "asc", description: "Sort order" },
2030
+ search: { type: "string", description: "Search query" }
2031
+ }
2032
+ };
2033
+ var idParam = {
2034
+ type: "object",
2035
+ properties: {
2036
+ id: { type: "string", format: "uuid", description: "Resource ID" }
2037
+ },
2038
+ required: ["id"]
2039
+ };
2040
+
2041
+ // src/modules/auth/index.ts
2042
+ var import_jwt = __toESM(require("@fastify/jwt"), 1);
2043
+ var import_cookie = __toESM(require("@fastify/cookie"), 1);
2044
+
2045
+ // src/modules/auth/auth.service.ts
2046
+ var import_bcryptjs = __toESM(require("bcryptjs"), 1);
2047
+ var tokenBlacklist = /* @__PURE__ */ new Set();
2048
+ var AuthService = class {
2049
+ app;
2050
+ SALT_ROUNDS = 12;
2051
+ constructor(app) {
2052
+ this.app = app;
2053
+ }
2054
+ async hashPassword(password) {
2055
+ return import_bcryptjs.default.hash(password, this.SALT_ROUNDS);
2056
+ }
2057
+ async verifyPassword(password, hash) {
2058
+ return import_bcryptjs.default.compare(password, hash);
2059
+ }
2060
+ generateTokenPair(user) {
2061
+ const accessPayload = {
2062
+ sub: user.id,
2063
+ email: user.email,
2064
+ role: user.role,
2065
+ type: "access"
2066
+ };
2067
+ const refreshPayload = {
2068
+ sub: user.id,
2069
+ email: user.email,
2070
+ role: user.role,
2071
+ type: "refresh"
2072
+ };
2073
+ const accessToken = this.app.jwt.sign(accessPayload, {
2074
+ expiresIn: config.jwt.accessExpiresIn
2075
+ });
2076
+ const refreshToken = this.app.jwt.sign(refreshPayload, {
2077
+ expiresIn: config.jwt.refreshExpiresIn
2078
+ });
2079
+ const expiresIn = this.parseExpiration(config.jwt.accessExpiresIn);
2080
+ return { accessToken, refreshToken, expiresIn };
2081
+ }
2082
+ parseExpiration(expiration) {
2083
+ const match = expiration.match(/^(\d+)([smhd])$/);
2084
+ if (!match) return 900;
2085
+ const value = parseInt(match[1] || "0", 10);
2086
+ const unit = match[2];
2087
+ switch (unit) {
2088
+ case "s":
2089
+ return value;
2090
+ case "m":
2091
+ return value * 60;
2092
+ case "h":
2093
+ return value * 3600;
2094
+ case "d":
2095
+ return value * 86400;
2096
+ default:
2097
+ return 900;
2098
+ }
2099
+ }
2100
+ async verifyAccessToken(token) {
2101
+ try {
2102
+ if (this.isTokenBlacklisted(token)) {
2103
+ throw new UnauthorizedError("Token has been revoked");
2104
+ }
2105
+ const payload = this.app.jwt.verify(token);
2106
+ if (payload.type !== "access") {
2107
+ throw new UnauthorizedError("Invalid token type");
2108
+ }
2109
+ return payload;
2110
+ } catch (error2) {
2111
+ if (error2 instanceof UnauthorizedError) throw error2;
2112
+ logger.debug({ err: error2 }, "Token verification failed");
2113
+ throw new UnauthorizedError("Invalid or expired token");
2114
+ }
2115
+ }
2116
+ async verifyRefreshToken(token) {
2117
+ try {
2118
+ if (this.isTokenBlacklisted(token)) {
2119
+ throw new UnauthorizedError("Token has been revoked");
2120
+ }
2121
+ const payload = this.app.jwt.verify(token);
2122
+ if (payload.type !== "refresh") {
2123
+ throw new UnauthorizedError("Invalid token type");
2124
+ }
2125
+ return payload;
2126
+ } catch (error2) {
2127
+ if (error2 instanceof UnauthorizedError) throw error2;
2128
+ logger.debug({ err: error2 }, "Refresh token verification failed");
2129
+ throw new UnauthorizedError("Invalid or expired refresh token");
2130
+ }
2131
+ }
2132
+ blacklistToken(token) {
2133
+ tokenBlacklist.add(token);
2134
+ logger.debug("Token blacklisted");
2135
+ }
2136
+ isTokenBlacklisted(token) {
2137
+ return tokenBlacklist.has(token);
2138
+ }
2139
+ // Clear expired tokens from blacklist periodically
2140
+ cleanupBlacklist() {
2141
+ tokenBlacklist.clear();
2142
+ logger.debug("Token blacklist cleared");
2143
+ }
2144
+ };
2145
+ function createAuthService(app) {
2146
+ return new AuthService(app);
2147
+ }
2148
+
2149
+ // src/modules/auth/schemas.ts
2150
+ var import_zod2 = require("zod");
2151
+ var loginSchema = import_zod2.z.object({
2152
+ email: import_zod2.z.string().email("Invalid email address"),
2153
+ password: import_zod2.z.string().min(1, "Password is required")
2154
+ });
2155
+ var registerSchema = import_zod2.z.object({
2156
+ email: import_zod2.z.string().email("Invalid email address"),
2157
+ password: import_zod2.z.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number"),
2158
+ name: import_zod2.z.string().min(2, "Name must be at least 2 characters").optional()
2159
+ });
2160
+ var refreshTokenSchema = import_zod2.z.object({
2161
+ refreshToken: import_zod2.z.string().min(1, "Refresh token is required")
2162
+ });
2163
+ var passwordResetRequestSchema = import_zod2.z.object({
2164
+ email: import_zod2.z.string().email("Invalid email address")
2165
+ });
2166
+ var passwordResetConfirmSchema = import_zod2.z.object({
2167
+ token: import_zod2.z.string().min(1, "Token is required"),
2168
+ password: import_zod2.z.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number")
2169
+ });
2170
+ var changePasswordSchema = import_zod2.z.object({
2171
+ currentPassword: import_zod2.z.string().min(1, "Current password is required"),
2172
+ newPassword: import_zod2.z.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number")
2173
+ });
2174
+
2175
+ // src/utils/response.ts
2176
+ function success3(reply, data, statusCode = 200) {
2177
+ const response = {
2178
+ success: true,
2179
+ data
2180
+ };
2181
+ return reply.status(statusCode).send(response);
2182
+ }
2183
+ function created(reply, data) {
2184
+ return success3(reply, data, 201);
2185
+ }
2186
+ function noContent(reply) {
2187
+ return reply.status(204).send();
2188
+ }
2189
+
2190
+ // src/modules/validation/validator.ts
2191
+ var import_zod3 = require("zod");
2192
+ function validateBody(schema, data) {
2193
+ const result = schema.safeParse(data);
2194
+ if (!result.success) {
2195
+ throw new ValidationError(formatZodErrors(result.error));
2196
+ }
2197
+ return result.data;
2198
+ }
2199
+ function validateQuery(schema, data) {
2200
+ const result = schema.safeParse(data);
2201
+ if (!result.success) {
2202
+ throw new ValidationError(formatZodErrors(result.error));
2203
+ }
2204
+ return result.data;
2205
+ }
2206
+ function formatZodErrors(error2) {
2207
+ const errors = {};
2208
+ for (const issue of error2.issues) {
2209
+ const path6 = issue.path.join(".") || "root";
2210
+ if (!errors[path6]) {
2211
+ errors[path6] = [];
2212
+ }
2213
+ errors[path6].push(issue.message);
2214
+ }
2215
+ return errors;
2216
+ }
2217
+ var idParamSchema = import_zod3.z.object({
2218
+ id: import_zod3.z.string().uuid("Invalid ID format")
2219
+ });
2220
+ var paginationSchema = import_zod3.z.object({
2221
+ page: import_zod3.z.string().transform(Number).optional().default("1"),
2222
+ limit: import_zod3.z.string().transform(Number).optional().default("20"),
2223
+ sortBy: import_zod3.z.string().optional(),
2224
+ sortOrder: import_zod3.z.enum(["asc", "desc"]).optional().default("asc")
2225
+ });
2226
+ var searchSchema = import_zod3.z.object({
2227
+ q: import_zod3.z.string().min(1, "Search query is required").optional(),
2228
+ search: import_zod3.z.string().min(1).optional()
2229
+ });
2230
+ var emailSchema = import_zod3.z.string().email("Invalid email address");
2231
+ var passwordSchema = import_zod3.z.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number").regex(/[^A-Za-z0-9]/, "Password must contain at least one special character");
2232
+ var urlSchema = import_zod3.z.string().url("Invalid URL format");
2233
+ var phoneSchema = import_zod3.z.string().regex(
2234
+ /^\+?[1-9]\d{1,14}$/,
2235
+ "Invalid phone number format"
2236
+ );
2237
+ var dateSchema = import_zod3.z.coerce.date();
2238
+ var futureDateSchema = import_zod3.z.coerce.date().refine(
2239
+ (date) => date > /* @__PURE__ */ new Date(),
2240
+ "Date must be in the future"
2241
+ );
2242
+ var pastDateSchema = import_zod3.z.coerce.date().refine(
2243
+ (date) => date < /* @__PURE__ */ new Date(),
2244
+ "Date must be in the past"
2245
+ );
2246
+
2247
+ // src/modules/auth/auth.controller.ts
2248
+ var AuthController = class {
2249
+ constructor(authService, userService) {
2250
+ this.authService = authService;
2251
+ this.userService = userService;
2252
+ }
2253
+ async register(request, reply) {
2254
+ const data = validateBody(registerSchema, request.body);
2255
+ const existingUser = await this.userService.findByEmail(data.email);
2256
+ if (existingUser) {
2257
+ throw new BadRequestError("Email already registered");
2258
+ }
2259
+ const hashedPassword = await this.authService.hashPassword(data.password);
2260
+ const user = await this.userService.create({
2261
+ email: data.email,
2262
+ password: hashedPassword,
2263
+ name: data.name
2264
+ });
2265
+ const tokens = this.authService.generateTokenPair({
2266
+ id: user.id,
2267
+ email: user.email,
2268
+ role: user.role
2269
+ });
2270
+ created(reply, {
2271
+ user: {
2272
+ id: user.id,
2273
+ email: user.email,
2274
+ name: user.name,
2275
+ role: user.role
2276
+ },
2277
+ ...tokens
2278
+ });
2279
+ }
2280
+ async login(request, reply) {
2281
+ const data = validateBody(loginSchema, request.body);
2282
+ const user = await this.userService.findByEmail(data.email);
2283
+ if (!user) {
2284
+ throw new UnauthorizedError("Invalid credentials");
2285
+ }
2286
+ if (user.status !== "active") {
2287
+ throw new UnauthorizedError("Account is not active");
2288
+ }
2289
+ const isValidPassword = await this.authService.verifyPassword(data.password, user.password);
2290
+ if (!isValidPassword) {
2291
+ throw new UnauthorizedError("Invalid credentials");
2292
+ }
2293
+ await this.userService.updateLastLogin(user.id);
2294
+ const tokens = this.authService.generateTokenPair({
2295
+ id: user.id,
2296
+ email: user.email,
2297
+ role: user.role
2298
+ });
2299
+ success3(reply, {
2300
+ user: {
2301
+ id: user.id,
2302
+ email: user.email,
2303
+ name: user.name,
2304
+ role: user.role
2305
+ },
2306
+ ...tokens
2307
+ });
2308
+ }
2309
+ async refresh(request, reply) {
2310
+ const data = validateBody(refreshTokenSchema, request.body);
2311
+ const payload = await this.authService.verifyRefreshToken(data.refreshToken);
2312
+ const user = await this.userService.findById(payload.sub);
2313
+ if (!user || user.status !== "active") {
2314
+ throw new UnauthorizedError("User not found or inactive");
2315
+ }
2316
+ this.authService.blacklistToken(data.refreshToken);
2317
+ const tokens = this.authService.generateTokenPair({
2318
+ id: user.id,
2319
+ email: user.email,
2320
+ role: user.role
2321
+ });
2322
+ success3(reply, tokens);
2323
+ }
2324
+ async logout(request, reply) {
2325
+ const authHeader = request.headers.authorization;
2326
+ if (authHeader?.startsWith("Bearer ")) {
2327
+ const token = authHeader.substring(7);
2328
+ this.authService.blacklistToken(token);
2329
+ }
2330
+ success3(reply, { message: "Logged out successfully" });
2331
+ }
2332
+ async me(request, reply) {
2333
+ const authRequest = request;
2334
+ const user = await this.userService.findById(authRequest.user.id);
2335
+ if (!user) {
2336
+ throw new UnauthorizedError("User not found");
2337
+ }
2338
+ success3(reply, {
2339
+ id: user.id,
2340
+ email: user.email,
2341
+ name: user.name,
2342
+ role: user.role,
2343
+ status: user.status,
2344
+ createdAt: user.createdAt
2345
+ });
2346
+ }
2347
+ async changePassword(request, reply) {
2348
+ const authRequest = request;
2349
+ const data = validateBody(changePasswordSchema, request.body);
2350
+ const user = await this.userService.findById(authRequest.user.id);
2351
+ if (!user) {
2352
+ throw new UnauthorizedError("User not found");
2353
+ }
2354
+ const isValidPassword = await this.authService.verifyPassword(
2355
+ data.currentPassword,
2356
+ user.password
2357
+ );
2358
+ if (!isValidPassword) {
2359
+ throw new BadRequestError("Current password is incorrect");
2360
+ }
2361
+ const hashedPassword = await this.authService.hashPassword(data.newPassword);
2362
+ await this.userService.updatePassword(user.id, hashedPassword);
2363
+ success3(reply, { message: "Password changed successfully" });
2364
+ }
2365
+ };
2366
+ function createAuthController(authService, userService) {
2367
+ return new AuthController(authService, userService);
2368
+ }
2369
+
2370
+ // src/modules/auth/auth.middleware.ts
2371
+ function createAuthMiddleware(authService) {
2372
+ return async function authenticate(request, reply) {
2373
+ const authHeader = request.headers.authorization;
2374
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
2375
+ throw new UnauthorizedError("Missing or invalid authorization header");
2376
+ }
2377
+ const token = authHeader.substring(7);
2378
+ const payload = await authService.verifyAccessToken(token);
2379
+ request.user = {
2380
+ id: payload.sub,
2381
+ email: payload.email,
2382
+ role: payload.role
2383
+ };
2384
+ };
2385
+ }
2386
+ function createRoleMiddleware(allowedRoles) {
2387
+ return async function authorize(request, _reply) {
2388
+ const user = request.user;
2389
+ if (!user) {
2390
+ throw new UnauthorizedError("Authentication required");
2391
+ }
2392
+ if (!allowedRoles.includes(user.role)) {
2393
+ throw new ForbiddenError("Insufficient permissions");
2394
+ }
2395
+ };
2396
+ }
2397
+
2398
+ // src/modules/auth/auth.routes.ts
2399
+ var credentialsBody = {
2400
+ type: "object",
2401
+ required: ["email", "password"],
2402
+ properties: {
2403
+ email: { type: "string", format: "email" },
2404
+ password: { type: "string", minLength: 8 }
2405
+ }
2406
+ };
2407
+ var changePasswordBody = {
2408
+ type: "object",
2409
+ required: ["currentPassword", "newPassword"],
2410
+ properties: {
2411
+ currentPassword: { type: "string", minLength: 8 },
2412
+ newPassword: { type: "string", minLength: 8 }
2413
+ }
2414
+ };
2415
+ function registerAuthRoutes(app, controller, authService) {
2416
+ const authenticate = createAuthMiddleware(authService);
2417
+ app.post("/auth/register", {
2418
+ schema: {
2419
+ tags: ["Auth"],
2420
+ summary: "Register a new user",
2421
+ body: credentialsBody,
2422
+ response: {
2423
+ 201: commonResponses.success,
2424
+ 400: commonResponses.error,
2425
+ 409: commonResponses.error
2426
+ }
2427
+ },
2428
+ handler: controller.register.bind(controller)
2429
+ });
2430
+ app.post("/auth/login", {
2431
+ schema: {
2432
+ tags: ["Auth"],
2433
+ summary: "Login and obtain tokens",
2434
+ body: credentialsBody,
2435
+ response: {
2436
+ 200: commonResponses.success,
2437
+ 400: commonResponses.error,
2438
+ 401: commonResponses.unauthorized
2439
+ }
2440
+ },
2441
+ handler: controller.login.bind(controller)
2442
+ });
2443
+ app.post("/auth/refresh", {
2444
+ schema: {
2445
+ tags: ["Auth"],
2446
+ summary: "Refresh access token",
2447
+ body: {
2448
+ type: "object",
2449
+ required: ["refreshToken"],
2450
+ properties: {
2451
+ refreshToken: { type: "string" }
2452
+ }
2453
+ },
2454
+ response: {
2455
+ 200: commonResponses.success,
2456
+ 401: commonResponses.unauthorized
2457
+ }
2458
+ },
2459
+ handler: controller.refresh.bind(controller)
2460
+ });
2461
+ app.post("/auth/logout", {
2462
+ preHandler: [authenticate],
2463
+ schema: {
2464
+ tags: ["Auth"],
2465
+ summary: "Logout current user",
2466
+ security: [{ bearerAuth: [] }],
2467
+ response: {
2468
+ 200: commonResponses.success,
2469
+ 401: commonResponses.unauthorized
2470
+ }
2471
+ },
2472
+ handler: controller.logout.bind(controller)
2473
+ });
2474
+ app.get("/auth/me", {
2475
+ preHandler: [authenticate],
2476
+ schema: {
2477
+ tags: ["Auth"],
2478
+ summary: "Get current user profile",
2479
+ security: [{ bearerAuth: [] }],
2480
+ response: {
2481
+ 200: commonResponses.success,
2482
+ 401: commonResponses.unauthorized
2483
+ }
2484
+ },
2485
+ handler: controller.me.bind(controller)
2486
+ });
2487
+ app.post("/auth/change-password", {
2488
+ preHandler: [authenticate],
2489
+ schema: {
2490
+ tags: ["Auth"],
2491
+ summary: "Change current user password",
2492
+ security: [{ bearerAuth: [] }],
2493
+ body: changePasswordBody,
2494
+ response: {
2495
+ 200: commonResponses.success,
2496
+ 400: commonResponses.error,
2497
+ 401: commonResponses.unauthorized
2498
+ }
2499
+ },
2500
+ handler: controller.changePassword.bind(controller)
2501
+ });
2502
+ }
2503
+
2504
+ // src/modules/user/user.repository.ts
2505
+ var import_crypto = require("crypto");
2506
+
2507
+ // src/utils/pagination.ts
2508
+ var DEFAULT_PAGE = 1;
2509
+ var DEFAULT_LIMIT = 20;
2510
+ var MAX_LIMIT = 100;
2511
+ function parsePaginationParams(query) {
2512
+ const page = Math.max(1, parseInt(String(query.page || DEFAULT_PAGE), 10));
2513
+ const limit = Math.min(MAX_LIMIT, Math.max(1, parseInt(String(query.limit || DEFAULT_LIMIT), 10)));
2514
+ const sortBy = typeof query.sortBy === "string" ? query.sortBy : void 0;
2515
+ const sortOrder = query.sortOrder === "desc" ? "desc" : "asc";
2516
+ return { page, limit, sortBy, sortOrder };
2517
+ }
2518
+ function createPaginatedResult(data, total, params) {
2519
+ const totalPages = Math.ceil(total / params.limit);
2520
+ return {
2521
+ data,
2522
+ meta: {
2523
+ total,
2524
+ page: params.page,
2525
+ limit: params.limit,
2526
+ totalPages,
2527
+ hasNextPage: params.page < totalPages,
2528
+ hasPrevPage: params.page > 1
2529
+ }
2530
+ };
2531
+ }
2532
+ function getSkip(params) {
2533
+ return (params.page - 1) * params.limit;
2534
+ }
2535
+
2536
+ // src/modules/user/user.repository.ts
2537
+ var users = /* @__PURE__ */ new Map();
2538
+ var UserRepository = class {
2539
+ async findById(id) {
2540
+ return users.get(id) || null;
2541
+ }
2542
+ async findByEmail(email) {
2543
+ for (const user of users.values()) {
2544
+ if (user.email.toLowerCase() === email.toLowerCase()) {
2545
+ return user;
2546
+ }
2547
+ }
2548
+ return null;
2549
+ }
2550
+ async findMany(params, filters) {
2551
+ let filteredUsers = Array.from(users.values());
2552
+ if (filters) {
2553
+ if (filters.status) {
2554
+ filteredUsers = filteredUsers.filter((u) => u.status === filters.status);
2555
+ }
2556
+ if (filters.role) {
2557
+ filteredUsers = filteredUsers.filter((u) => u.role === filters.role);
2558
+ }
2559
+ if (filters.emailVerified !== void 0) {
2560
+ filteredUsers = filteredUsers.filter((u) => u.emailVerified === filters.emailVerified);
2561
+ }
2562
+ if (filters.search) {
2563
+ const search = filters.search.toLowerCase();
2564
+ filteredUsers = filteredUsers.filter(
2565
+ (u) => u.email.toLowerCase().includes(search) || u.name?.toLowerCase().includes(search)
2566
+ );
2567
+ }
2568
+ }
2569
+ if (params.sortBy) {
2570
+ const sortKey = params.sortBy;
2571
+ filteredUsers.sort((a, b) => {
2572
+ const aVal = a[sortKey];
2573
+ const bVal = b[sortKey];
2574
+ if (aVal === void 0 || bVal === void 0) return 0;
2575
+ if (aVal < bVal) return params.sortOrder === "desc" ? 1 : -1;
2576
+ if (aVal > bVal) return params.sortOrder === "desc" ? -1 : 1;
2577
+ return 0;
2578
+ });
2579
+ }
2580
+ const total = filteredUsers.length;
2581
+ const skip = getSkip(params);
2582
+ const data = filteredUsers.slice(skip, skip + params.limit);
2583
+ return createPaginatedResult(data, total, params);
2584
+ }
2585
+ async create(data) {
2586
+ const now = /* @__PURE__ */ new Date();
2587
+ const user = {
2588
+ id: (0, import_crypto.randomUUID)(),
2589
+ email: data.email,
2590
+ password: data.password,
2591
+ name: data.name,
2592
+ role: data.role || "user",
2593
+ status: "active",
2594
+ emailVerified: false,
2595
+ createdAt: now,
2596
+ updatedAt: now
2597
+ };
2598
+ users.set(user.id, user);
2599
+ return user;
2600
+ }
2601
+ async update(id, data) {
2602
+ const user = users.get(id);
2603
+ if (!user) return null;
2604
+ const updatedUser = {
2605
+ ...user,
2606
+ ...data,
2607
+ updatedAt: /* @__PURE__ */ new Date()
2608
+ };
2609
+ users.set(id, updatedUser);
2610
+ return updatedUser;
2611
+ }
2612
+ async updatePassword(id, password) {
2613
+ const user = users.get(id);
2614
+ if (!user) return null;
2615
+ const updatedUser = {
2616
+ ...user,
2617
+ password,
2618
+ updatedAt: /* @__PURE__ */ new Date()
2619
+ };
2620
+ users.set(id, updatedUser);
2621
+ return updatedUser;
2622
+ }
2623
+ async updateLastLogin(id) {
2624
+ const user = users.get(id);
2625
+ if (!user) return null;
2626
+ const updatedUser = {
2627
+ ...user,
2628
+ lastLoginAt: /* @__PURE__ */ new Date(),
2629
+ updatedAt: /* @__PURE__ */ new Date()
2630
+ };
2631
+ users.set(id, updatedUser);
2632
+ return updatedUser;
2633
+ }
2634
+ async delete(id) {
2635
+ return users.delete(id);
2636
+ }
2637
+ async count(filters) {
2638
+ let count = 0;
2639
+ for (const user of users.values()) {
2640
+ if (filters) {
2641
+ if (filters.status && user.status !== filters.status) continue;
2642
+ if (filters.role && user.role !== filters.role) continue;
2643
+ if (filters.emailVerified !== void 0 && user.emailVerified !== filters.emailVerified)
2644
+ continue;
2645
+ }
2646
+ count++;
2647
+ }
2648
+ return count;
2649
+ }
2650
+ // Helper to clear all users (for testing)
2651
+ async clear() {
2652
+ users.clear();
2653
+ }
2654
+ };
2655
+ function createUserRepository() {
2656
+ return new UserRepository();
2657
+ }
2658
+
2659
+ // src/modules/user/types.ts
2660
+ var DEFAULT_ROLE_PERMISSIONS = {
2661
+ user: ["profile:read", "profile:update"],
2662
+ moderator: [
2663
+ "profile:read",
2664
+ "profile:update",
2665
+ "users:read",
2666
+ "content:read",
2667
+ "content:update",
2668
+ "content:delete"
2669
+ ],
2670
+ admin: [
2671
+ "profile:read",
2672
+ "profile:update",
2673
+ "users:read",
2674
+ "users:update",
2675
+ "users:delete",
2676
+ "content:manage",
2677
+ "settings:read"
2678
+ ],
2679
+ super_admin: ["*:manage"]
2680
+ // All permissions
2681
+ };
2682
+
2683
+ // src/modules/user/user.service.ts
2684
+ var UserService = class {
2685
+ constructor(repository) {
2686
+ this.repository = repository;
2687
+ }
2688
+ async findById(id) {
2689
+ return this.repository.findById(id);
2690
+ }
2691
+ async findByEmail(email) {
2692
+ return this.repository.findByEmail(email);
2693
+ }
2694
+ async findMany(params, filters) {
2695
+ const result = await this.repository.findMany(params, filters);
2696
+ return {
2697
+ ...result,
2698
+ data: result.data.map(({ password, ...user }) => user)
2699
+ };
2700
+ }
2701
+ async create(data) {
2702
+ const existing = await this.repository.findByEmail(data.email);
2703
+ if (existing) {
2704
+ throw new ConflictError("User with this email already exists");
2705
+ }
2706
+ const user = await this.repository.create(data);
2707
+ logger.info({ userId: user.id, email: user.email }, "User created");
2708
+ return user;
2709
+ }
2710
+ async update(id, data) {
2711
+ const user = await this.repository.findById(id);
2712
+ if (!user) {
2713
+ throw new NotFoundError("User");
2714
+ }
2715
+ if (data.email && data.email !== user.email) {
2716
+ const existing = await this.repository.findByEmail(data.email);
2717
+ if (existing) {
2718
+ throw new ConflictError("Email already in use");
2719
+ }
2720
+ }
2721
+ const updatedUser = await this.repository.update(id, data);
2722
+ if (!updatedUser) {
2723
+ throw new NotFoundError("User");
2724
+ }
2725
+ logger.info({ userId: id }, "User updated");
2726
+ return updatedUser;
2727
+ }
2728
+ async updatePassword(id, hashedPassword) {
2729
+ const user = await this.repository.updatePassword(id, hashedPassword);
2730
+ if (!user) {
2731
+ throw new NotFoundError("User");
2732
+ }
2733
+ logger.info({ userId: id }, "User password updated");
2734
+ return user;
2735
+ }
2736
+ async updateLastLogin(id) {
2737
+ const user = await this.repository.updateLastLogin(id);
2738
+ if (!user) {
2739
+ throw new NotFoundError("User");
2740
+ }
2741
+ return user;
2742
+ }
2743
+ async delete(id) {
2744
+ const user = await this.repository.findById(id);
2745
+ if (!user) {
2746
+ throw new NotFoundError("User");
2747
+ }
2748
+ await this.repository.delete(id);
2749
+ logger.info({ userId: id }, "User deleted");
2750
+ }
2751
+ async suspend(id) {
2752
+ return this.update(id, { status: "suspended" });
2753
+ }
2754
+ async ban(id) {
2755
+ return this.update(id, { status: "banned" });
2756
+ }
2757
+ async activate(id) {
2758
+ return this.update(id, { status: "active" });
2759
+ }
2760
+ async verifyEmail(id) {
2761
+ return this.update(id, { emailVerified: true });
2762
+ }
2763
+ async changeRole(id, role) {
2764
+ return this.update(id, { role });
2765
+ }
2766
+ // RBAC helpers
2767
+ hasPermission(role, permission) {
2768
+ const permissions = DEFAULT_ROLE_PERMISSIONS[role] || [];
2769
+ if (permissions.includes("*:manage")) {
2770
+ return true;
2771
+ }
2772
+ if (permissions.includes(permission)) {
2773
+ return true;
2774
+ }
2775
+ const [resource, action] = permission.split(":");
2776
+ const managePermission = `${resource}:manage`;
2777
+ if (permissions.includes(managePermission)) {
2778
+ return true;
2779
+ }
2780
+ return false;
2781
+ }
2782
+ getPermissions(role) {
2783
+ return DEFAULT_ROLE_PERMISSIONS[role] || [];
2784
+ }
2785
+ };
2786
+ function createUserService(repository) {
2787
+ return new UserService(repository || createUserRepository());
2788
+ }
2789
+
2790
+ // src/modules/auth/index.ts
2791
+ async function registerAuthModule(app) {
2792
+ await app.register(import_jwt.default, {
2793
+ secret: config.jwt.secret,
2794
+ sign: {
2795
+ algorithm: "HS256"
2796
+ }
2797
+ });
2798
+ await app.register(import_cookie.default, {
2799
+ secret: config.jwt.secret,
2800
+ hook: "onRequest"
2801
+ });
2802
+ const authService = createAuthService(app);
2803
+ const userService = createUserService();
2804
+ const authController = createAuthController(authService, userService);
2805
+ registerAuthRoutes(app, authController, authService);
2806
+ logger.info("Auth module registered");
2807
+ return authService;
2808
+ }
2809
+
2810
+ // src/modules/user/schemas.ts
2811
+ var import_zod4 = require("zod");
2812
+ var userStatusEnum = import_zod4.z.enum(["active", "inactive", "suspended", "banned"]);
2813
+ var userRoleEnum = import_zod4.z.enum(["user", "admin", "moderator", "super_admin"]);
2814
+ var createUserSchema = import_zod4.z.object({
2815
+ email: import_zod4.z.string().email("Invalid email address"),
2816
+ password: import_zod4.z.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number"),
2817
+ name: import_zod4.z.string().min(2, "Name must be at least 2 characters").optional(),
2818
+ role: userRoleEnum.optional().default("user")
2819
+ });
2820
+ var updateUserSchema = import_zod4.z.object({
2821
+ email: import_zod4.z.string().email("Invalid email address").optional(),
2822
+ name: import_zod4.z.string().min(2, "Name must be at least 2 characters").optional(),
2823
+ role: userRoleEnum.optional(),
2824
+ status: userStatusEnum.optional(),
2825
+ emailVerified: import_zod4.z.boolean().optional(),
2826
+ metadata: import_zod4.z.record(import_zod4.z.unknown()).optional()
2827
+ });
2828
+ var updateProfileSchema = import_zod4.z.object({
2829
+ name: import_zod4.z.string().min(2, "Name must be at least 2 characters").optional(),
2830
+ metadata: import_zod4.z.record(import_zod4.z.unknown()).optional()
2831
+ });
2832
+ var userQuerySchema = import_zod4.z.object({
2833
+ page: import_zod4.z.string().transform(Number).optional(),
2834
+ limit: import_zod4.z.string().transform(Number).optional(),
2835
+ sortBy: import_zod4.z.string().optional(),
2836
+ sortOrder: import_zod4.z.enum(["asc", "desc"]).optional(),
2837
+ status: userStatusEnum.optional(),
2838
+ role: userRoleEnum.optional(),
2839
+ search: import_zod4.z.string().optional(),
2840
+ emailVerified: import_zod4.z.string().transform((val) => val === "true").optional()
2841
+ });
2842
+
2843
+ // src/modules/user/user.controller.ts
2844
+ var UserController = class {
2845
+ constructor(userService) {
2846
+ this.userService = userService;
2847
+ }
2848
+ async list(request, reply) {
2849
+ const query = validateQuery(userQuerySchema, request.query);
2850
+ const pagination = parsePaginationParams(query);
2851
+ const filters = {
2852
+ status: query.status,
2853
+ role: query.role,
2854
+ search: query.search,
2855
+ emailVerified: query.emailVerified
2856
+ };
2857
+ const result = await this.userService.findMany(pagination, filters);
2858
+ success3(reply, result);
2859
+ }
2860
+ async getById(request, reply) {
2861
+ const user = await this.userService.findById(request.params.id);
2862
+ if (!user) {
2863
+ return reply.status(404).send({
2864
+ success: false,
2865
+ message: "User not found"
2866
+ });
2867
+ }
2868
+ const { password, ...userData } = user;
2869
+ success3(reply, userData);
2870
+ }
2871
+ async update(request, reply) {
2872
+ const data = validateBody(updateUserSchema, request.body);
2873
+ const user = await this.userService.update(request.params.id, data);
2874
+ const { password, ...userData } = user;
2875
+ success3(reply, userData);
2876
+ }
2877
+ async delete(request, reply) {
2878
+ const authRequest = request;
2879
+ if (authRequest.user.id === request.params.id) {
2880
+ throw new ForbiddenError("Cannot delete your own account");
2881
+ }
2882
+ await this.userService.delete(request.params.id);
2883
+ noContent(reply);
2884
+ }
2885
+ async suspend(request, reply) {
2886
+ const authRequest = request;
2887
+ if (authRequest.user.id === request.params.id) {
2888
+ throw new ForbiddenError("Cannot suspend your own account");
2889
+ }
2890
+ const user = await this.userService.suspend(request.params.id);
2891
+ const { password, ...userData } = user;
2892
+ success3(reply, userData);
2893
+ }
2894
+ async ban(request, reply) {
2895
+ const authRequest = request;
2896
+ if (authRequest.user.id === request.params.id) {
2897
+ throw new ForbiddenError("Cannot ban your own account");
2898
+ }
2899
+ const user = await this.userService.ban(request.params.id);
2900
+ const { password, ...userData } = user;
2901
+ success3(reply, userData);
2902
+ }
2903
+ async activate(request, reply) {
2904
+ const user = await this.userService.activate(request.params.id);
2905
+ const { password, ...userData } = user;
2906
+ success3(reply, userData);
2907
+ }
2908
+ // Profile routes (for authenticated user)
2909
+ async getProfile(request, reply) {
2910
+ const authRequest = request;
2911
+ const user = await this.userService.findById(authRequest.user.id);
2912
+ if (!user) {
2913
+ return reply.status(404).send({
2914
+ success: false,
2915
+ message: "User not found"
2916
+ });
2917
+ }
2918
+ const { password, ...userData } = user;
2919
+ success3(reply, userData);
2920
+ }
2921
+ async updateProfile(request, reply) {
2922
+ const authRequest = request;
2923
+ const data = validateBody(updateProfileSchema, request.body);
2924
+ const user = await this.userService.update(authRequest.user.id, data);
2925
+ const { password, ...userData } = user;
2926
+ success3(reply, userData);
2927
+ }
2928
+ };
2929
+ function createUserController(userService) {
2930
+ return new UserController(userService);
2931
+ }
2932
+
2933
+ // src/modules/user/user.routes.ts
2934
+ var userTag = "Users";
2935
+ var userResponse = {
2936
+ type: "object",
2937
+ properties: {
2938
+ success: { type: "boolean", example: true },
2939
+ data: { type: "object" }
2940
+ }
2941
+ };
2942
+ function registerUserRoutes(app, controller, authService) {
2943
+ const authenticate = createAuthMiddleware(authService);
2944
+ const isAdmin = createRoleMiddleware(["admin", "super_admin"]);
2945
+ const isModerator = createRoleMiddleware(["moderator", "admin", "super_admin"]);
2946
+ app.get(
2947
+ "/profile",
2948
+ {
2949
+ preHandler: [authenticate],
2950
+ schema: {
2951
+ tags: [userTag],
2952
+ summary: "Get current user profile",
2953
+ security: [{ bearerAuth: [] }],
2954
+ response: {
2955
+ 200: userResponse,
2956
+ 401: commonResponses.unauthorized
2957
+ }
2958
+ }
2959
+ },
2960
+ controller.getProfile.bind(controller)
2961
+ );
2962
+ app.patch(
2963
+ "/profile",
2964
+ {
2965
+ preHandler: [authenticate],
2966
+ schema: {
2967
+ tags: [userTag],
2968
+ summary: "Update current user profile",
2969
+ security: [{ bearerAuth: [] }],
2970
+ body: { type: "object" },
2971
+ response: {
2972
+ 200: userResponse,
2973
+ 401: commonResponses.unauthorized,
2974
+ 400: commonResponses.error
2975
+ }
2976
+ }
2977
+ },
2978
+ controller.updateProfile.bind(controller)
2979
+ );
2980
+ app.get(
2981
+ "/users",
2982
+ {
2983
+ preHandler: [authenticate, isModerator],
2984
+ schema: {
2985
+ tags: [userTag],
2986
+ summary: "List users",
2987
+ security: [{ bearerAuth: [] }],
2988
+ querystring: {
2989
+ ...paginationQuery,
2990
+ properties: {
2991
+ ...paginationQuery.properties,
2992
+ status: { type: "string", enum: ["active", "inactive", "suspended", "banned"] },
2993
+ role: { type: "string", enum: ["user", "admin", "moderator", "super_admin"] },
2994
+ search: { type: "string" },
2995
+ emailVerified: { type: "boolean" }
2996
+ }
2997
+ },
2998
+ response: {
2999
+ 200: commonResponses.paginated,
3000
+ 401: commonResponses.unauthorized
3001
+ }
3002
+ }
3003
+ },
3004
+ controller.list.bind(controller)
3005
+ );
3006
+ app.get(
3007
+ "/users/:id",
3008
+ {
3009
+ preHandler: [authenticate, isModerator],
3010
+ schema: {
3011
+ tags: [userTag],
3012
+ summary: "Get user by id",
3013
+ security: [{ bearerAuth: [] }],
3014
+ params: idParam,
3015
+ response: {
3016
+ 200: userResponse,
3017
+ 401: commonResponses.unauthorized,
3018
+ 404: commonResponses.notFound
3019
+ }
3020
+ }
3021
+ },
3022
+ controller.getById.bind(controller)
3023
+ );
3024
+ app.patch(
3025
+ "/users/:id",
3026
+ {
3027
+ preHandler: [authenticate, isAdmin],
3028
+ schema: {
3029
+ tags: [userTag],
3030
+ summary: "Update user",
3031
+ security: [{ bearerAuth: [] }],
3032
+ params: idParam,
3033
+ body: { type: "object" },
3034
+ response: {
3035
+ 200: userResponse,
3036
+ 401: commonResponses.unauthorized,
3037
+ 404: commonResponses.notFound
3038
+ }
3039
+ }
3040
+ },
3041
+ controller.update.bind(controller)
3042
+ );
3043
+ app.delete(
3044
+ "/users/:id",
3045
+ {
3046
+ preHandler: [authenticate, isAdmin],
3047
+ schema: {
3048
+ tags: [userTag],
3049
+ summary: "Delete user",
3050
+ security: [{ bearerAuth: [] }],
3051
+ params: idParam,
3052
+ response: {
3053
+ 204: { description: "User deleted" },
3054
+ 401: commonResponses.unauthorized,
3055
+ 404: commonResponses.notFound
3056
+ }
3057
+ }
3058
+ },
3059
+ controller.delete.bind(controller)
3060
+ );
3061
+ app.post(
3062
+ "/users/:id/suspend",
3063
+ {
3064
+ preHandler: [authenticate, isAdmin],
3065
+ schema: {
3066
+ tags: [userTag],
3067
+ summary: "Suspend user",
3068
+ security: [{ bearerAuth: [] }],
3069
+ params: idParam,
3070
+ response: {
3071
+ 200: userResponse,
3072
+ 401: commonResponses.unauthorized,
3073
+ 404: commonResponses.notFound
3074
+ }
3075
+ }
3076
+ },
3077
+ controller.suspend.bind(controller)
3078
+ );
3079
+ app.post(
3080
+ "/users/:id/ban",
3081
+ {
3082
+ preHandler: [authenticate, isAdmin],
3083
+ schema: {
3084
+ tags: [userTag],
3085
+ summary: "Ban user",
3086
+ security: [{ bearerAuth: [] }],
3087
+ params: idParam,
3088
+ response: {
3089
+ 200: userResponse,
3090
+ 401: commonResponses.unauthorized,
3091
+ 404: commonResponses.notFound
3092
+ }
3093
+ }
3094
+ },
3095
+ controller.ban.bind(controller)
3096
+ );
3097
+ app.post(
3098
+ "/users/:id/activate",
3099
+ {
3100
+ preHandler: [authenticate, isAdmin],
3101
+ schema: {
3102
+ tags: [userTag],
3103
+ summary: "Activate user",
3104
+ security: [{ bearerAuth: [] }],
3105
+ params: idParam,
3106
+ response: {
3107
+ 200: userResponse,
3108
+ 401: commonResponses.unauthorized,
3109
+ 404: commonResponses.notFound
3110
+ }
3111
+ }
3112
+ },
3113
+ controller.activate.bind(controller)
3114
+ );
3115
+ }
3116
+
3117
+ // src/modules/user/index.ts
3118
+ async function registerUserModule(app, authService) {
3119
+ const repository = createUserRepository();
3120
+ const userService = createUserService(repository);
3121
+ const userController = createUserController(userService);
3122
+ registerUserRoutes(app, userController, authService);
3123
+ logger.info("User module registered");
3124
+ }
3125
+
3126
+ // src/cli/utils/docs-generator.ts
3127
+ async function generateDocs(outputPath = "openapi.json", silent = false) {
3128
+ const spinner = silent ? null : (0, import_ora2.default)("Generating OpenAPI documentation...").start();
3129
+ try {
3130
+ const server = createServer({
3131
+ port: config.server.port,
3132
+ host: config.server.host
3133
+ });
3134
+ const app = server.instance;
3135
+ registerErrorHandler(app);
3136
+ await registerSecurity(app);
3137
+ await registerSwagger(app, {
3138
+ enabled: true,
3139
+ route: config.swagger.route,
3140
+ title: config.swagger.title,
3141
+ description: config.swagger.description,
3142
+ version: config.swagger.version
3143
+ });
3144
+ const authService = await registerAuthModule(app);
3145
+ await registerUserModule(app, authService);
3146
+ await app.ready();
3147
+ const spec = app.swagger();
3148
+ const absoluteOutput = import_path3.default.resolve(outputPath);
3149
+ await import_promises3.default.mkdir(import_path3.default.dirname(absoluteOutput), { recursive: true });
3150
+ await import_promises3.default.writeFile(absoluteOutput, JSON.stringify(spec, null, 2), "utf8");
3151
+ spinner?.succeed(`OpenAPI spec generated at ${absoluteOutput}`);
3152
+ await app.close();
3153
+ return absoluteOutput;
3154
+ } catch (error2) {
3155
+ spinner?.fail("Failed to generate OpenAPI documentation");
3156
+ throw error2;
3157
+ }
3158
+ }
3159
+
3160
+ // src/cli/commands/generate.ts
3161
+ var generateCommand = new import_commander2.Command("generate").alias("g").description("Generate resources (module, controller, service, etc.)");
3162
+ generateCommand.command("module <name> [fields...]").alias("m").description("Generate a complete module with controller, service, repository, types, schemas, and routes").option("--no-routes", "Skip routes generation").option("--no-repository", "Skip repository generation").option("--prisma", "Generate Prisma model suggestion").option("--validator <type>", "Validator type: zod, joi, yup", "zod").option("-i, --interactive", "Interactive mode to define fields").action(async (name, fieldsArgs, options) => {
3163
+ let fields = [];
3164
+ if (options.interactive) {
3165
+ fields = await promptForFields();
3166
+ } else if (fieldsArgs.length > 0) {
3167
+ fields = parseFields(fieldsArgs.join(" "));
3168
+ }
3169
+ const spinner = (0, import_ora3.default)("Generating module...").start();
3170
+ try {
3171
+ const kebabName = toKebabCase(name);
3172
+ const pascalName = toPascalCase(name);
3173
+ const camelName = toCamelCase(name);
3174
+ const pluralName = pluralize(kebabName);
3175
+ const tableName = pluralize(kebabName.replace(/-/g, "_"));
3176
+ const validatorType = options.validator || "zod";
3177
+ const moduleDir = import_path4.default.join(getModulesDir(), kebabName);
3178
+ if (await fileExists(moduleDir)) {
3179
+ spinner.stop();
3180
+ error(`Module "${kebabName}" already exists`);
3181
+ return;
3182
+ }
3183
+ const hasFields = fields.length > 0;
3184
+ const files = [
3185
+ {
3186
+ name: `${kebabName}.types.ts`,
3187
+ content: hasFields ? dynamicTypesTemplate(kebabName, pascalName, fields) : typesTemplate(kebabName, pascalName)
3188
+ },
3189
+ {
3190
+ name: `${kebabName}.schemas.ts`,
3191
+ content: hasFields ? dynamicSchemasTemplate(kebabName, pascalName, camelName, fields, validatorType) : schemasTemplate(kebabName, pascalName, camelName)
3192
+ },
3193
+ { name: `${kebabName}.service.ts`, content: serviceTemplate(kebabName, pascalName, camelName) },
3194
+ { name: `${kebabName}.controller.ts`, content: controllerTemplate(kebabName, pascalName, camelName) },
3195
+ { name: "index.ts", content: moduleIndexTemplate(kebabName, pascalName, camelName) }
3196
+ ];
3197
+ if (options.repository !== false) {
3198
+ files.push({
3199
+ name: `${kebabName}.repository.ts`,
3200
+ content: repositoryTemplate(kebabName, pascalName, camelName, pluralName)
3201
+ });
3202
+ }
3203
+ if (options.routes !== false) {
3204
+ files.push({
3205
+ name: `${kebabName}.routes.ts`,
3206
+ content: routesTemplate(kebabName, pascalName, camelName, pluralName, fields)
3207
+ });
3208
+ }
3209
+ for (const file of files) {
3210
+ await writeFile(import_path4.default.join(moduleDir, file.name), file.content);
3211
+ }
3212
+ spinner.succeed(`Module "${pascalName}" generated successfully!`);
3213
+ if (options.prisma || hasFields) {
3214
+ console.log("\n" + "\u2500".repeat(50));
3215
+ info("Prisma model suggestion:");
3216
+ if (hasFields) {
3217
+ console.log(dynamicPrismaTemplate(pascalName, tableName, fields));
3218
+ } else {
3219
+ console.log(prismaModelTemplate(kebabName, pascalName, tableName));
3220
+ }
3221
+ }
3222
+ if (hasFields) {
3223
+ console.log("\n\u{1F4CB} Fields defined:");
3224
+ fields.forEach((f) => {
3225
+ const opts = [];
3226
+ if (f.isOptional) opts.push("optional");
3227
+ if (f.isArray) opts.push("array");
3228
+ if (f.isUnique) opts.push("unique");
3229
+ const optsStr = opts.length > 0 ? ` (${opts.join(", ")})` : "";
3230
+ success(` ${f.name}: ${f.type}${optsStr}`);
3231
+ });
3232
+ }
3233
+ console.log("\n\u{1F4C1} Files created:");
3234
+ files.forEach((f) => success(` src/modules/${kebabName}/${f.name}`));
3235
+ console.log("\n\u{1F4CC} Next steps:");
3236
+ if (!hasFields) {
3237
+ info(` 1. Update the types in ${kebabName}.types.ts`);
3238
+ info(` 2. Update the schemas in ${kebabName}.schemas.ts`);
3239
+ info(" 3. Register the module in your app");
3240
+ } else {
3241
+ info(" 1. Review generated types and schemas");
3242
+ info(" 2. Register the module in your app");
3243
+ }
3244
+ if (options.prisma || hasFields) {
3245
+ info(` ${hasFields ? "3" : "4"}. Add the Prisma model to schema.prisma`);
3246
+ info(` ${hasFields ? "4" : "5"}. Run: npm run db:migrate`);
3247
+ }
3248
+ const { generateDocsNow } = await import_inquirer2.default.prompt([
3249
+ {
3250
+ type: "confirm",
3251
+ name: "generateDocsNow",
3252
+ message: "Generate Swagger/OpenAPI documentation now?",
3253
+ default: true
3254
+ }
3255
+ ]);
3256
+ if (generateDocsNow) {
3257
+ await generateDocs("openapi.json", true);
3258
+ }
3259
+ } catch (err) {
3260
+ spinner.fail("Failed to generate module");
3261
+ error(err instanceof Error ? err.message : String(err));
3262
+ }
3263
+ });
3264
+ generateCommand.command("controller <name>").alias("c").description("Generate a controller").option("-m, --module <module>", "Target module name").action(async (name, options) => {
3265
+ const spinner = (0, import_ora3.default)("Generating controller...").start();
3266
+ try {
3267
+ const kebabName = toKebabCase(name);
3268
+ const pascalName = toPascalCase(name);
3269
+ const camelName = toCamelCase(name);
3270
+ const moduleName = options.module ? toKebabCase(options.module) : kebabName;
3271
+ const moduleDir = import_path4.default.join(getModulesDir(), moduleName);
3272
+ const filePath = import_path4.default.join(moduleDir, `${kebabName}.controller.ts`);
3273
+ if (await fileExists(filePath)) {
3274
+ spinner.stop();
3275
+ error(`Controller "${kebabName}" already exists`);
3276
+ return;
3277
+ }
3278
+ await writeFile(filePath, controllerTemplate(kebabName, pascalName, camelName));
3279
+ spinner.succeed(`Controller "${pascalName}Controller" generated!`);
3280
+ success(` src/modules/${moduleName}/${kebabName}.controller.ts`);
3281
+ } catch (err) {
3282
+ spinner.fail("Failed to generate controller");
3283
+ error(err instanceof Error ? err.message : String(err));
3284
+ }
3285
+ });
3286
+ generateCommand.command("service <name>").alias("s").description("Generate a service").option("-m, --module <module>", "Target module name").action(async (name, options) => {
3287
+ const spinner = (0, import_ora3.default)("Generating service...").start();
3288
+ try {
3289
+ const kebabName = toKebabCase(name);
3290
+ const pascalName = toPascalCase(name);
3291
+ const camelName = toCamelCase(name);
3292
+ const moduleName = options.module ? toKebabCase(options.module) : kebabName;
3293
+ const moduleDir = import_path4.default.join(getModulesDir(), moduleName);
3294
+ const filePath = import_path4.default.join(moduleDir, `${kebabName}.service.ts`);
3295
+ if (await fileExists(filePath)) {
3296
+ spinner.stop();
3297
+ error(`Service "${kebabName}" already exists`);
3298
+ return;
3299
+ }
3300
+ await writeFile(filePath, serviceTemplate(kebabName, pascalName, camelName));
3301
+ spinner.succeed(`Service "${pascalName}Service" generated!`);
3302
+ success(` src/modules/${moduleName}/${kebabName}.service.ts`);
3303
+ } catch (err) {
3304
+ spinner.fail("Failed to generate service");
3305
+ error(err instanceof Error ? err.message : String(err));
3306
+ }
3307
+ });
3308
+ generateCommand.command("repository <name>").alias("r").description("Generate a repository").option("-m, --module <module>", "Target module name").action(async (name, options) => {
3309
+ const spinner = (0, import_ora3.default)("Generating repository...").start();
3310
+ try {
3311
+ const kebabName = toKebabCase(name);
3312
+ const pascalName = toPascalCase(name);
3313
+ const camelName = toCamelCase(name);
3314
+ const pluralName = pluralize(kebabName);
3315
+ const moduleName = options.module ? toKebabCase(options.module) : kebabName;
3316
+ const moduleDir = import_path4.default.join(getModulesDir(), moduleName);
3317
+ const filePath = import_path4.default.join(moduleDir, `${kebabName}.repository.ts`);
3318
+ if (await fileExists(filePath)) {
3319
+ spinner.stop();
3320
+ error(`Repository "${kebabName}" already exists`);
3321
+ return;
3322
+ }
3323
+ await writeFile(filePath, repositoryTemplate(kebabName, pascalName, camelName, pluralName));
3324
+ spinner.succeed(`Repository "${pascalName}Repository" generated!`);
3325
+ success(` src/modules/${moduleName}/${kebabName}.repository.ts`);
3326
+ } catch (err) {
3327
+ spinner.fail("Failed to generate repository");
3328
+ error(err instanceof Error ? err.message : String(err));
3329
+ }
3330
+ });
3331
+ generateCommand.command("types <name>").alias("t").description("Generate types/interfaces").option("-m, --module <module>", "Target module name").action(async (name, options) => {
3332
+ const spinner = (0, import_ora3.default)("Generating types...").start();
3333
+ try {
3334
+ const kebabName = toKebabCase(name);
3335
+ const pascalName = toPascalCase(name);
3336
+ const moduleName = options.module ? toKebabCase(options.module) : kebabName;
3337
+ const moduleDir = import_path4.default.join(getModulesDir(), moduleName);
3338
+ const filePath = import_path4.default.join(moduleDir, `${kebabName}.types.ts`);
3339
+ if (await fileExists(filePath)) {
3340
+ spinner.stop();
3341
+ error(`Types file "${kebabName}.types.ts" already exists`);
3342
+ return;
3343
+ }
3344
+ await writeFile(filePath, typesTemplate(kebabName, pascalName));
3345
+ spinner.succeed(`Types for "${pascalName}" generated!`);
3346
+ success(` src/modules/${moduleName}/${kebabName}.types.ts`);
3347
+ } catch (err) {
3348
+ spinner.fail("Failed to generate types");
3349
+ error(err instanceof Error ? err.message : String(err));
3350
+ }
3351
+ });
3352
+ generateCommand.command("schema <name>").alias("v").description("Generate validation schemas").option("-m, --module <module>", "Target module name").action(async (name, options) => {
3353
+ const spinner = (0, import_ora3.default)("Generating schemas...").start();
3354
+ try {
3355
+ const kebabName = toKebabCase(name);
3356
+ const pascalName = toPascalCase(name);
3357
+ const camelName = toCamelCase(name);
3358
+ const moduleName = options.module ? toKebabCase(options.module) : kebabName;
3359
+ const moduleDir = import_path4.default.join(getModulesDir(), moduleName);
3360
+ const filePath = import_path4.default.join(moduleDir, `${kebabName}.schemas.ts`);
3361
+ if (await fileExists(filePath)) {
3362
+ spinner.stop();
3363
+ error(`Schemas file "${kebabName}.schemas.ts" already exists`);
3364
+ return;
3365
+ }
3366
+ await writeFile(filePath, schemasTemplate(kebabName, pascalName, camelName));
3367
+ spinner.succeed(`Schemas for "${pascalName}" generated!`);
3368
+ success(` src/modules/${moduleName}/${kebabName}.schemas.ts`);
3369
+ } catch (err) {
3370
+ spinner.fail("Failed to generate schemas");
3371
+ error(err instanceof Error ? err.message : String(err));
3372
+ }
3373
+ });
3374
+ generateCommand.command("routes <name>").description("Generate routes").option("-m, --module <module>", "Target module name").action(async (name, options) => {
3375
+ const spinner = (0, import_ora3.default)("Generating routes...").start();
3376
+ try {
3377
+ const kebabName = toKebabCase(name);
3378
+ const pascalName = toPascalCase(name);
3379
+ const camelName = toCamelCase(name);
3380
+ const pluralName = pluralize(kebabName);
3381
+ const moduleName = options.module ? toKebabCase(options.module) : kebabName;
3382
+ const moduleDir = import_path4.default.join(getModulesDir(), moduleName);
3383
+ const filePath = import_path4.default.join(moduleDir, `${kebabName}.routes.ts`);
3384
+ if (await fileExists(filePath)) {
3385
+ spinner.stop();
3386
+ error(`Routes file "${kebabName}.routes.ts" already exists`);
3387
+ return;
3388
+ }
3389
+ await writeFile(filePath, routesTemplate(kebabName, pascalName, camelName, pluralName));
3390
+ spinner.succeed(`Routes for "${pascalName}" generated!`);
3391
+ success(` src/modules/${moduleName}/${kebabName}.routes.ts`);
3392
+ } catch (err) {
3393
+ spinner.fail("Failed to generate routes");
3394
+ error(err instanceof Error ? err.message : String(err));
3395
+ }
3396
+ });
3397
+ async function promptForFields() {
3398
+ const fields = [];
3399
+ console.log("\n\u{1F4DD} Define your model fields (press Enter with empty name to finish)\n");
3400
+ const fieldTypes = [
3401
+ "string",
3402
+ "number",
3403
+ "boolean",
3404
+ "date",
3405
+ "datetime",
3406
+ "text",
3407
+ "email",
3408
+ "url",
3409
+ "uuid",
3410
+ "int",
3411
+ "float",
3412
+ "decimal",
3413
+ "json"
3414
+ ];
3415
+ let addMore = true;
3416
+ while (addMore) {
3417
+ const answers = await import_inquirer2.default.prompt([
3418
+ {
3419
+ type: "input",
3420
+ name: "name",
3421
+ message: "Field name (empty to finish):"
3422
+ }
3423
+ ]);
3424
+ if (!answers.name) {
3425
+ addMore = false;
3426
+ continue;
3427
+ }
3428
+ const fieldDetails = await import_inquirer2.default.prompt([
3429
+ {
3430
+ type: "list",
3431
+ name: "type",
3432
+ message: `Type for "${answers.name}":`,
3433
+ choices: fieldTypes,
3434
+ default: "string"
3435
+ },
3436
+ {
3437
+ type: "confirm",
3438
+ name: "isOptional",
3439
+ message: "Is optional?",
3440
+ default: false
3441
+ },
3442
+ {
3443
+ type: "confirm",
3444
+ name: "isUnique",
3445
+ message: "Is unique?",
3446
+ default: false
3447
+ },
3448
+ {
3449
+ type: "confirm",
3450
+ name: "isArray",
3451
+ message: "Is array?",
3452
+ default: false
3453
+ }
3454
+ ]);
3455
+ fields.push({
3456
+ name: answers.name,
3457
+ type: fieldDetails.type,
3458
+ isOptional: fieldDetails.isOptional,
3459
+ isUnique: fieldDetails.isUnique,
3460
+ isArray: fieldDetails.isArray
3461
+ });
3462
+ console.log(` \u2713 Added: ${answers.name}: ${fieldDetails.type}
3463
+ `);
3464
+ }
3465
+ return fields;
3466
+ }
3467
+
3468
+ // src/cli/commands/add-module.ts
3469
+ var import_commander3 = require("commander");
3470
+ var import_path5 = __toESM(require("path"), 1);
3471
+ var import_ora4 = __toESM(require("ora"), 1);
3472
+ var import_chalk3 = __toESM(require("chalk"), 1);
3473
+ var AVAILABLE_MODULES = {
3474
+ auth: {
3475
+ name: "Authentication",
3476
+ description: "JWT authentication with access/refresh tokens",
3477
+ files: ["auth.service", "auth.controller", "auth.routes", "auth.middleware", "auth.schemas", "auth.types", "index"]
3478
+ },
3479
+ users: {
3480
+ name: "User Management",
3481
+ description: "User CRUD with RBAC (roles & permissions)",
3482
+ files: ["user.service", "user.controller", "user.repository", "user.routes", "user.schemas", "user.types", "index"]
3483
+ },
3484
+ email: {
3485
+ name: "Email Service",
3486
+ description: "SMTP email with templates (Handlebars)",
3487
+ files: ["email.service", "email.templates", "email.types", "index"]
3488
+ },
3489
+ audit: {
3490
+ name: "Audit Logs",
3491
+ description: "Activity logging and audit trail",
3492
+ files: ["audit.service", "audit.types", "index"]
3493
+ },
3494
+ upload: {
3495
+ name: "File Upload",
3496
+ description: "File upload with local/S3 storage",
3497
+ files: ["upload.service", "upload.controller", "upload.routes", "upload.types", "index"]
3498
+ },
3499
+ cache: {
3500
+ name: "Redis Cache",
3501
+ description: "Redis caching service",
3502
+ files: ["cache.service", "cache.types", "index"]
3503
+ },
3504
+ notifications: {
3505
+ name: "Notifications",
3506
+ description: "In-app and push notifications",
3507
+ files: ["notification.service", "notification.types", "index"]
3508
+ },
3509
+ settings: {
3510
+ name: "Settings",
3511
+ description: "Application settings management",
3512
+ files: ["settings.service", "settings.controller", "settings.routes", "settings.types", "index"]
3513
+ }
3514
+ };
3515
+ var addModuleCommand = new import_commander3.Command("add").description("Add a pre-built module to your project").argument("[module]", "Module to add (auth, users, email, audit, upload, cache, notifications, settings)").option("-l, --list", "List available modules").action(async (moduleName, options) => {
3516
+ if (options?.list || !moduleName) {
3517
+ console.log(import_chalk3.default.bold("\n\u{1F4E6} Available Modules:\n"));
3518
+ for (const [key, mod] of Object.entries(AVAILABLE_MODULES)) {
3519
+ console.log(` ${import_chalk3.default.cyan(key.padEnd(15))} ${mod.name}`);
3520
+ console.log(` ${" ".repeat(15)} ${import_chalk3.default.gray(mod.description)}
3521
+ `);
3522
+ }
3523
+ console.log(import_chalk3.default.bold("Usage:"));
3524
+ console.log(` ${import_chalk3.default.yellow("servcraft add auth")} Add authentication module`);
3525
+ console.log(` ${import_chalk3.default.yellow("servcraft add users")} Add user management module`);
3526
+ console.log(` ${import_chalk3.default.yellow("servcraft add email")} Add email service module
3527
+ `);
3528
+ return;
3529
+ }
3530
+ const module2 = AVAILABLE_MODULES[moduleName];
3531
+ if (!module2) {
3532
+ error(`Unknown module: ${moduleName}`);
3533
+ info('Run "servcraft add --list" to see available modules');
3534
+ return;
3535
+ }
3536
+ const spinner = (0, import_ora4.default)(`Adding ${module2.name} module...`).start();
3537
+ try {
3538
+ const moduleDir = import_path5.default.join(getModulesDir(), moduleName);
3539
+ if (await fileExists(moduleDir)) {
3540
+ spinner.stop();
3541
+ warn(`Module "${moduleName}" already exists`);
3542
+ return;
3543
+ }
3544
+ await ensureDir(moduleDir);
3545
+ switch (moduleName) {
3546
+ case "auth":
3547
+ await generateAuthModule(moduleDir);
3548
+ break;
3549
+ case "users":
3550
+ await generateUsersModule(moduleDir);
3551
+ break;
3552
+ case "email":
3553
+ await generateEmailModule(moduleDir);
3554
+ break;
3555
+ case "audit":
3556
+ await generateAuditModule(moduleDir);
3557
+ break;
3558
+ case "upload":
3559
+ await generateUploadModule(moduleDir);
3560
+ break;
3561
+ case "cache":
3562
+ await generateCacheModule(moduleDir);
3563
+ break;
3564
+ default:
3565
+ await generateGenericModule(moduleDir, moduleName);
3566
+ }
3567
+ spinner.succeed(`${module2.name} module added successfully!`);
3568
+ console.log("\n\u{1F4C1} Files created:");
3569
+ module2.files.forEach((f) => success(` src/modules/${moduleName}/${f}.ts`));
3570
+ console.log("\n\u{1F4CC} Next steps:");
3571
+ info(" 1. Register the module in your main app file");
3572
+ info(" 2. Configure any required environment variables");
3573
+ info(" 3. Run database migrations if needed");
3574
+ } catch (err) {
3575
+ spinner.fail("Failed to add module");
3576
+ error(err instanceof Error ? err.message : String(err));
3577
+ }
3578
+ });
3579
+ async function generateAuthModule(dir) {
3580
+ const files = {
3581
+ "auth.types.ts": `export interface JwtPayload {
3582
+ sub: string;
3583
+ email: string;
3584
+ role: string;
3585
+ type: 'access' | 'refresh';
3586
+ }
3587
+
3588
+ export interface TokenPair {
3589
+ accessToken: string;
3590
+ refreshToken: string;
3591
+ expiresIn: number;
3592
+ }
3593
+
3594
+ export interface AuthUser {
3595
+ id: string;
3596
+ email: string;
3597
+ role: string;
3598
+ }
3599
+ `,
3600
+ "auth.schemas.ts": `import { z } from 'zod';
3601
+
3602
+ export const loginSchema = z.object({
3603
+ email: z.string().email(),
3604
+ password: z.string().min(1),
3605
+ });
3606
+
3607
+ export const registerSchema = z.object({
3608
+ email: z.string().email(),
3609
+ password: z.string().min(8),
3610
+ name: z.string().min(2).optional(),
3611
+ });
3612
+
3613
+ export const refreshTokenSchema = z.object({
3614
+ refreshToken: z.string().min(1),
3615
+ });
3616
+ `,
3617
+ "index.ts": `export * from './auth.types.js';
3618
+ export * from './auth.schemas.js';
3619
+ // Export services, controllers, etc.
3620
+ `
3621
+ };
3622
+ for (const [name, content] of Object.entries(files)) {
3623
+ await writeFile(import_path5.default.join(dir, name), content);
3624
+ }
3625
+ }
3626
+ async function generateUsersModule(dir) {
3627
+ const files = {
3628
+ "user.types.ts": `export type UserStatus = 'active' | 'inactive' | 'suspended' | 'banned';
3629
+ export type UserRole = 'user' | 'admin' | 'moderator' | 'super_admin';
3630
+
3631
+ export interface User {
3632
+ id: string;
3633
+ email: string;
3634
+ password: string;
3635
+ name?: string;
3636
+ role: UserRole;
3637
+ status: UserStatus;
3638
+ createdAt: Date;
3639
+ updatedAt: Date;
3640
+ }
3641
+ `,
3642
+ "user.schemas.ts": `import { z } from 'zod';
3643
+
3644
+ export const createUserSchema = z.object({
3645
+ email: z.string().email(),
3646
+ password: z.string().min(8),
3647
+ name: z.string().min(2).optional(),
3648
+ role: z.enum(['user', 'admin', 'moderator']).optional(),
3649
+ });
3650
+
3651
+ export const updateUserSchema = z.object({
3652
+ email: z.string().email().optional(),
3653
+ name: z.string().min(2).optional(),
3654
+ role: z.enum(['user', 'admin', 'moderator', 'super_admin']).optional(),
3655
+ status: z.enum(['active', 'inactive', 'suspended', 'banned']).optional(),
3656
+ });
3657
+ `,
3658
+ "index.ts": `export * from './user.types.js';
3659
+ export * from './user.schemas.js';
3660
+ `
3661
+ };
3662
+ for (const [name, content] of Object.entries(files)) {
3663
+ await writeFile(import_path5.default.join(dir, name), content);
3664
+ }
3665
+ }
3666
+ async function generateEmailModule(dir) {
3667
+ const files = {
3668
+ "email.types.ts": `export interface EmailOptions {
3669
+ to: string | string[];
3670
+ subject: string;
3671
+ html?: string;
3672
+ text?: string;
3673
+ template?: string;
3674
+ data?: Record<string, unknown>;
3675
+ }
3676
+
3677
+ export interface EmailResult {
3678
+ success: boolean;
3679
+ messageId?: string;
3680
+ error?: string;
3681
+ }
3682
+ `,
3683
+ "email.service.ts": `import nodemailer from 'nodemailer';
3684
+ import type { EmailOptions, EmailResult } from './email.types.js';
3685
+
3686
+ export class EmailService {
3687
+ private transporter;
3688
+
3689
+ constructor() {
3690
+ this.transporter = nodemailer.createTransport({
3691
+ host: process.env.SMTP_HOST,
3692
+ port: parseInt(process.env.SMTP_PORT || '587', 10),
3693
+ auth: {
3694
+ user: process.env.SMTP_USER,
3695
+ pass: process.env.SMTP_PASS,
3696
+ },
3697
+ });
3698
+ }
3699
+
3700
+ async send(options: EmailOptions): Promise<EmailResult> {
3701
+ try {
3702
+ const result = await this.transporter.sendMail({
3703
+ from: process.env.SMTP_FROM,
3704
+ ...options,
3705
+ });
3706
+ return { success: true, messageId: result.messageId };
3707
+ } catch (error) {
3708
+ return { success: false, error: String(error) };
3709
+ }
3710
+ }
3711
+ }
3712
+
3713
+ export const emailService = new EmailService();
3714
+ `,
3715
+ "index.ts": `export * from './email.types.js';
3716
+ export { EmailService, emailService } from './email.service.js';
3717
+ `
3718
+ };
3719
+ for (const [name, content] of Object.entries(files)) {
3720
+ await writeFile(import_path5.default.join(dir, name), content);
3721
+ }
3722
+ }
3723
+ async function generateAuditModule(dir) {
3724
+ const files = {
3725
+ "audit.types.ts": `export interface AuditLogEntry {
3726
+ userId?: string;
3727
+ action: string;
3728
+ resource: string;
3729
+ resourceId?: string;
3730
+ oldValue?: Record<string, unknown>;
3731
+ newValue?: Record<string, unknown>;
3732
+ ipAddress?: string;
3733
+ userAgent?: string;
3734
+ createdAt: Date;
3735
+ }
3736
+ `,
3737
+ "audit.service.ts": `import type { AuditLogEntry } from './audit.types.js';
3738
+
3739
+ const logs: AuditLogEntry[] = [];
3740
+
3741
+ export class AuditService {
3742
+ async log(entry: Omit<AuditLogEntry, 'createdAt'>): Promise<void> {
3743
+ logs.push({ ...entry, createdAt: new Date() });
3744
+ console.log('[AUDIT]', entry.action, entry.resource);
3745
+ }
3746
+
3747
+ async query(filters: Partial<AuditLogEntry>): Promise<AuditLogEntry[]> {
3748
+ return logs.filter((log) => {
3749
+ for (const [key, value] of Object.entries(filters)) {
3750
+ if (log[key as keyof AuditLogEntry] !== value) return false;
3751
+ }
3752
+ return true;
3753
+ });
3754
+ }
3755
+ }
3756
+
3757
+ export const auditService = new AuditService();
3758
+ `,
3759
+ "index.ts": `export * from './audit.types.js';
3760
+ export { AuditService, auditService } from './audit.service.js';
3761
+ `
3762
+ };
3763
+ for (const [name, content] of Object.entries(files)) {
3764
+ await writeFile(import_path5.default.join(dir, name), content);
3765
+ }
3766
+ }
3767
+ async function generateUploadModule(dir) {
3768
+ const files = {
3769
+ "upload.types.ts": `export interface UploadedFile {
3770
+ id: string;
3771
+ filename: string;
3772
+ originalName: string;
3773
+ mimetype: string;
3774
+ size: number;
3775
+ path: string;
3776
+ url: string;
3777
+ createdAt: Date;
3778
+ }
3779
+
3780
+ export interface UploadOptions {
3781
+ maxSize?: number;
3782
+ allowedTypes?: string[];
3783
+ destination?: string;
3784
+ }
3785
+ `,
3786
+ "index.ts": `export * from './upload.types.js';
3787
+ `
3788
+ };
3789
+ for (const [name, content] of Object.entries(files)) {
3790
+ await writeFile(import_path5.default.join(dir, name), content);
3791
+ }
3792
+ }
3793
+ async function generateCacheModule(dir) {
3794
+ const files = {
3795
+ "cache.types.ts": `export interface CacheOptions {
3796
+ ttl?: number;
3797
+ prefix?: string;
3798
+ }
3799
+ `,
3800
+ "cache.service.ts": `import type { CacheOptions } from './cache.types.js';
3801
+
3802
+ // In-memory cache (replace with Redis in production)
3803
+ const cache = new Map<string, { value: unknown; expiry: number }>();
3804
+
3805
+ export class CacheService {
3806
+ async get<T>(key: string): Promise<T | null> {
3807
+ const item = cache.get(key);
3808
+ if (!item) return null;
3809
+ if (Date.now() > item.expiry) {
3810
+ cache.delete(key);
3811
+ return null;
3812
+ }
3813
+ return item.value as T;
3814
+ }
3815
+
3816
+ async set(key: string, value: unknown, ttl = 3600): Promise<void> {
3817
+ cache.set(key, { value, expiry: Date.now() + ttl * 1000 });
3818
+ }
3819
+
3820
+ async del(key: string): Promise<void> {
3821
+ cache.delete(key);
3822
+ }
3823
+
3824
+ async clear(): Promise<void> {
3825
+ cache.clear();
3826
+ }
3827
+ }
3828
+
3829
+ export const cacheService = new CacheService();
3830
+ `,
3831
+ "index.ts": `export * from './cache.types.js';
3832
+ export { CacheService, cacheService } from './cache.service.js';
3833
+ `
3834
+ };
3835
+ for (const [name, content] of Object.entries(files)) {
3836
+ await writeFile(import_path5.default.join(dir, name), content);
3837
+ }
3838
+ }
3839
+ async function generateGenericModule(dir, name) {
3840
+ const files = {
3841
+ [`${name}.types.ts`]: `// ${name} types
3842
+ export interface ${name.charAt(0).toUpperCase() + name.slice(1)}Data {
3843
+ // Define your types here
3844
+ }
3845
+ `,
3846
+ "index.ts": `export * from './${name}.types.js';
3847
+ `
3848
+ };
3849
+ for (const [fileName, content] of Object.entries(files)) {
3850
+ await writeFile(import_path5.default.join(dir, fileName), content);
3851
+ }
3852
+ }
3853
+
3854
+ // src/cli/commands/db.ts
3855
+ var import_commander4 = require("commander");
3856
+ var import_child_process2 = require("child_process");
3857
+ var import_ora5 = __toESM(require("ora"), 1);
3858
+ var import_chalk4 = __toESM(require("chalk"), 1);
3859
+ var dbCommand = new import_commander4.Command("db").description("Database management commands");
3860
+ dbCommand.command("migrate").description("Run database migrations").option("-n, --name <name>", "Migration name").action(async (options) => {
3861
+ const spinner = (0, import_ora5.default)("Running migrations...").start();
3862
+ try {
3863
+ const cmd = options.name ? `npx prisma migrate dev --name ${options.name}` : "npx prisma migrate dev";
3864
+ (0, import_child_process2.execSync)(cmd, { stdio: "inherit" });
3865
+ spinner.succeed("Migrations completed!");
3866
+ } catch (err) {
3867
+ spinner.fail("Migration failed");
3868
+ error(err instanceof Error ? err.message : String(err));
3869
+ }
3870
+ });
3871
+ dbCommand.command("push").description("Push schema changes to database (no migration)").action(async () => {
3872
+ const spinner = (0, import_ora5.default)("Pushing schema...").start();
3873
+ try {
3874
+ (0, import_child_process2.execSync)("npx prisma db push", { stdio: "inherit" });
3875
+ spinner.succeed("Schema pushed successfully!");
3876
+ } catch (err) {
3877
+ spinner.fail("Push failed");
3878
+ error(err instanceof Error ? err.message : String(err));
3879
+ }
3880
+ });
3881
+ dbCommand.command("generate").description("Generate Prisma client").action(async () => {
3882
+ const spinner = (0, import_ora5.default)("Generating Prisma client...").start();
3883
+ try {
3884
+ (0, import_child_process2.execSync)("npx prisma generate", { stdio: "inherit" });
3885
+ spinner.succeed("Prisma client generated!");
3886
+ } catch (err) {
3887
+ spinner.fail("Generation failed");
3888
+ error(err instanceof Error ? err.message : String(err));
3889
+ }
3890
+ });
3891
+ dbCommand.command("studio").description("Open Prisma Studio").action(async () => {
3892
+ info("Opening Prisma Studio...");
3893
+ const studio = (0, import_child_process2.spawn)("npx", ["prisma", "studio"], {
3894
+ stdio: "inherit",
3895
+ shell: true
3896
+ });
3897
+ studio.on("close", (code) => {
3898
+ if (code !== 0) {
3899
+ error("Prisma Studio closed with error");
3900
+ }
3901
+ });
3902
+ });
3903
+ dbCommand.command("seed").description("Run database seed").action(async () => {
3904
+ const spinner = (0, import_ora5.default)("Seeding database...").start();
3905
+ try {
3906
+ (0, import_child_process2.execSync)("npx prisma db seed", { stdio: "inherit" });
3907
+ spinner.succeed("Database seeded!");
3908
+ } catch (err) {
3909
+ spinner.fail("Seeding failed");
3910
+ error(err instanceof Error ? err.message : String(err));
3911
+ }
3912
+ });
3913
+ dbCommand.command("reset").description("Reset database (drop all data and re-run migrations)").option("-f, --force", "Skip confirmation").action(async (options) => {
3914
+ if (!options.force) {
3915
+ console.log(import_chalk4.default.yellow("\n\u26A0\uFE0F WARNING: This will delete all data in your database!\n"));
3916
+ const readline = await import("readline");
3917
+ const rl = readline.createInterface({
3918
+ input: process.stdin,
3919
+ output: process.stdout
3920
+ });
3921
+ const answer = await new Promise((resolve) => {
3922
+ rl.question("Are you sure you want to continue? (y/N) ", resolve);
3923
+ });
3924
+ rl.close();
3925
+ if (answer.toLowerCase() !== "y") {
3926
+ info("Operation cancelled");
3927
+ return;
3928
+ }
3929
+ }
3930
+ const spinner = (0, import_ora5.default)("Resetting database...").start();
3931
+ try {
3932
+ (0, import_child_process2.execSync)("npx prisma migrate reset --force", { stdio: "inherit" });
3933
+ spinner.succeed("Database reset completed!");
3934
+ } catch (err) {
3935
+ spinner.fail("Reset failed");
3936
+ error(err instanceof Error ? err.message : String(err));
3937
+ }
3938
+ });
3939
+ dbCommand.command("status").description("Show migration status").action(async () => {
3940
+ try {
3941
+ (0, import_child_process2.execSync)("npx prisma migrate status", { stdio: "inherit" });
3942
+ } catch (err) {
3943
+ error("Failed to get migration status");
3944
+ }
3945
+ });
3946
+
3947
+ // src/cli/commands/docs.ts
3948
+ var import_commander5 = require("commander");
3949
+ var docsCommand = new import_commander5.Command("docs").description("Generate Swagger/OpenAPI documentation").option("-o, --output <path>", "Output file path", "openapi.json").action(async (options) => {
3950
+ try {
3951
+ const outputPath = await generateDocs(options.output);
3952
+ success(`Documentation written to ${outputPath}`);
3953
+ } catch (err) {
3954
+ error(err instanceof Error ? err.message : String(err));
3955
+ process.exitCode = 1;
3956
+ }
3957
+ });
3958
+
3959
+ // src/cli/index.ts
3960
+ var program = new import_commander6.Command();
3961
+ program.name("servcraft").description("Servcraft - A modular Node.js backend framework CLI").version("0.1.0");
3962
+ program.addCommand(initCommand);
3963
+ program.addCommand(generateCommand);
3964
+ program.addCommand(addModuleCommand);
3965
+ program.addCommand(dbCommand);
3966
+ program.addCommand(docsCommand);
3967
+ program.parse();
3968
+ //# sourceMappingURL=index.cjs.map