create-tigra 3.3.0 → 4.0.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 (203) hide show
  1. package/README.md +81 -12
  2. package/bin/create-tigra.js +495 -472
  3. package/lib/patchers/email-verification.patcher.js +72 -10
  4. package/modules/email-verification/client/hooks/useVerification.ts +4 -1
  5. package/modules/email-verification/server/__tests__/verification.integration.test.ts +115 -0
  6. package/modules/email-verification/server/verification.controller.ts +3 -1
  7. package/modules/email-verification/server/verification.service.ts +44 -13
  8. package/package.json +3 -2
  9. package/template/.github/dependabot.yml +47 -0
  10. package/template/.github/workflows/audit.yml +36 -0
  11. package/template/.github/workflows/ci.yml +79 -0
  12. package/template/AGENTS.md +18 -9
  13. package/template/client/.dockerignore +1 -0
  14. package/template/client/.env.example.production +13 -2
  15. package/template/client/AGENTS.md +13 -5
  16. package/template/client/Dockerfile +186 -14
  17. package/template/client/next.config.ts +1 -1
  18. package/template/client/package-lock.json +15983 -14181
  19. package/template/client/package.json +56 -48
  20. package/template/client/scripts/check-sharp.mjs +53 -0
  21. package/template/client/scripts/next-dev.cjs +5 -1
  22. package/template/client/src/__tests__/proxy.test.ts +92 -0
  23. package/template/client/src/app/healthz/route.ts +16 -0
  24. package/template/client/src/app/layout.tsx +9 -3
  25. package/template/client/src/app/page.tsx +2 -2
  26. package/template/client/src/app/providers.tsx +23 -4
  27. package/template/client/src/components/layout/Header.tsx +7 -3
  28. package/template/client/src/features/admin/hooks/useAdminSessions.ts +2 -1
  29. package/template/client/src/features/admin/hooks/useAdminUsers.ts +3 -1
  30. package/template/client/src/features/admin/types/admin.types.ts +2 -3
  31. package/template/client/src/features/auth/components/AuthInitializer.tsx +35 -18
  32. package/template/client/src/features/auth/components/ForgotPasswordForm.tsx +107 -0
  33. package/template/client/src/features/auth/components/LimitNotice.tsx +28 -0
  34. package/template/client/src/features/auth/components/LoginForm.tsx +13 -2
  35. package/template/client/src/features/auth/components/RegisterForm.tsx +23 -7
  36. package/template/client/src/features/auth/hooks/useAuth.ts +11 -1
  37. package/template/client/src/features/auth/hooks/usePasswordReset.ts +7 -1
  38. package/template/client/src/features/auth/services/auth.service.ts +8 -3
  39. package/template/client/src/features/auth/store/authSlice.ts +7 -2
  40. package/template/client/src/lib/api/__tests__/axios.config.test.ts +183 -0
  41. package/template/client/src/lib/api/api.types.ts +14 -0
  42. package/template/client/src/lib/api/axios.config.ts +101 -15
  43. package/template/client/src/lib/api/hard-redirect.ts +8 -0
  44. package/template/client/src/lib/api/session-events.ts +29 -0
  45. package/template/client/src/lib/constants/routes.ts +12 -0
  46. package/template/client/src/lib/observability/sentry-scrub.ts +1 -1
  47. package/template/client/src/lib/utils/__tests__/error.test.ts +119 -0
  48. package/template/client/src/lib/utils/__tests__/form.test.ts +42 -0
  49. package/template/client/src/lib/utils/__tests__/paths.test.ts +43 -0
  50. package/template/client/src/lib/utils/__tests__/security.test.ts +40 -0
  51. package/template/client/src/lib/utils/__tests__/session-marker.test.ts +27 -0
  52. package/template/client/src/lib/utils/error.ts +81 -0
  53. package/template/client/src/lib/utils/form.ts +31 -0
  54. package/template/client/src/lib/utils/paths.ts +18 -0
  55. package/template/client/src/lib/utils/session-marker.ts +24 -0
  56. package/template/client/src/{middleware.ts → proxy.ts} +25 -11
  57. package/template/client/src/store/__tests__/store.test.ts +44 -0
  58. package/template/client/src/store/index.ts +26 -8
  59. package/template/client/vitest.config.mts +48 -0
  60. package/template/server/.env.example +280 -270
  61. package/template/server/.env.example.production +283 -242
  62. package/template/server/AGENTS.md +13 -4
  63. package/template/server/Dockerfile +176 -14
  64. package/template/server/docker-compose.yml +4 -2
  65. package/template/server/docs/deployment.md +63 -0
  66. package/template/server/docs/logging.md +52 -4
  67. package/template/server/docs/rate-limits.md +153 -0
  68. package/template/server/docs/testing.md +63 -0
  69. package/template/server/eslint.config.mjs +19 -0
  70. package/template/server/package-lock.json +8784 -8743
  71. package/template/server/package.json +79 -75
  72. package/template/server/prisma/migrations/0_init/migration.sql +82 -0
  73. package/template/server/prisma/migrations/migration_lock.toml +3 -0
  74. package/template/server/prisma/schema.prisma +0 -3
  75. package/template/server/scripts/check-heic.mjs +40 -0
  76. package/template/server/scripts/check-sharp.mjs +53 -0
  77. package/template/server/src/__tests__/routes.integration.test.ts +280 -0
  78. package/template/server/src/app.ts +248 -346
  79. package/template/server/src/config/__tests__/env.test.ts +219 -0
  80. package/template/server/src/config/__tests__/rate-limit.config.test.ts +158 -0
  81. package/template/server/src/config/env.ts +326 -182
  82. package/template/server/src/config/rate-limit.config.ts +157 -106
  83. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +60 -8
  84. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +44 -0
  85. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +88 -0
  86. package/template/server/src/jobs/__tests__/schedule.test.ts +92 -0
  87. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +38 -36
  88. package/template/server/src/jobs/cleanup-expired-auth.job.ts +32 -24
  89. package/template/server/src/jobs/index.ts +12 -2
  90. package/template/server/src/jobs/refresh-cloudflare-ranges.job.ts +28 -0
  91. package/template/server/src/jobs/schedule.ts +50 -0
  92. package/template/server/src/libs/__tests__/auth.test.ts +98 -7
  93. package/template/server/src/libs/__tests__/client-ip.test.ts +257 -121
  94. package/template/server/src/libs/__tests__/cloudflare-ranges.test.ts +79 -0
  95. package/template/server/src/libs/__tests__/cookies.test.ts +53 -2
  96. package/template/server/src/libs/__tests__/email-quota.test.ts +81 -0
  97. package/template/server/src/libs/__tests__/email.test.ts +68 -0
  98. package/template/server/src/libs/__tests__/error-handler.test.ts +162 -0
  99. package/template/server/src/libs/__tests__/health-db-down.integration.test.ts +37 -0
  100. package/template/server/src/libs/__tests__/health-redis-down.integration.test.ts +45 -0
  101. package/template/server/src/libs/__tests__/health-routes.test.ts +83 -0
  102. package/template/server/src/libs/__tests__/health.integration.test.ts +118 -0
  103. package/template/server/src/libs/__tests__/http.test.ts +74 -2
  104. package/template/server/src/libs/__tests__/ip-block.test.ts +179 -62
  105. package/template/server/src/libs/__tests__/logger.test.ts +50 -0
  106. package/template/server/src/libs/__tests__/monitoring.test.ts +185 -0
  107. package/template/server/src/libs/__tests__/outbound.integration.test.ts +48 -0
  108. package/template/server/src/libs/__tests__/prisma-client.test.ts +28 -0
  109. package/template/server/src/libs/__tests__/query-counter.integration.test.ts +53 -0
  110. package/template/server/src/libs/__tests__/rate-limiting.test.ts +146 -0
  111. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +53 -0
  112. package/template/server/src/libs/__tests__/redis-required.test.ts +30 -0
  113. package/template/server/src/libs/__tests__/redis.test.ts +38 -2
  114. package/template/server/src/libs/__tests__/request-id.test.ts +25 -0
  115. package/template/server/src/libs/__tests__/requestLogger.test.ts +126 -0
  116. package/template/server/src/libs/__tests__/safe-http.test.ts +138 -0
  117. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +82 -80
  118. package/template/server/src/libs/__tests__/shutdown.test.ts +89 -0
  119. package/template/server/src/libs/__tests__/url-safety.test.ts +130 -80
  120. package/template/server/src/libs/auth.ts +39 -10
  121. package/template/server/src/libs/client-ip.ts +158 -77
  122. package/template/server/src/libs/cloudflare-ranges.ts +132 -0
  123. package/template/server/src/libs/cookies.ts +53 -14
  124. package/template/server/src/libs/email-quota.ts +74 -0
  125. package/template/server/src/libs/email.ts +46 -9
  126. package/template/server/src/libs/error-handler.ts +111 -0
  127. package/template/server/src/libs/health-routes.ts +53 -0
  128. package/template/server/src/libs/http.ts +139 -47
  129. package/template/server/src/libs/ip-address.ts +37 -0
  130. package/template/server/src/libs/ip-block.ts +284 -221
  131. package/template/server/src/libs/logger.ts +41 -12
  132. package/template/server/src/libs/monitoring.ts +127 -41
  133. package/template/server/src/libs/observability/sentry.ts +1 -1
  134. package/template/server/src/libs/origin-check.ts +9 -7
  135. package/template/server/src/libs/prisma.ts +47 -4
  136. package/template/server/src/libs/query-counter.ts +71 -59
  137. package/template/server/src/libs/rate-limiting.ts +110 -0
  138. package/template/server/src/libs/redis-required.ts +28 -0
  139. package/template/server/src/libs/redis.ts +27 -1
  140. package/template/server/src/libs/request-id.ts +18 -0
  141. package/template/server/src/libs/requestLogger.ts +112 -17
  142. package/template/server/src/libs/safe-http.ts +101 -0
  143. package/template/server/src/libs/shutdown.ts +87 -0
  144. package/template/server/src/libs/storage/__tests__/fixtures/tiny-heic.ts +13 -0
  145. package/template/server/src/libs/storage/__tests__/image-optimizer.test.ts +59 -0
  146. package/template/server/src/libs/storage/__tests__/multipart-limits.test.ts +91 -0
  147. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +52 -0
  148. package/template/server/src/libs/storage/file-storage.service.ts +94 -84
  149. package/template/server/src/libs/storage/file-validator.ts +48 -46
  150. package/template/server/src/libs/storage/image-optimizer.service.ts +16 -5
  151. package/template/server/src/libs/token-hash.ts +18 -0
  152. package/template/server/src/libs/url-safety.ts +127 -121
  153. package/template/server/src/libs/validation-errors.ts +86 -0
  154. package/template/server/src/modules/admin/__tests__/admin-actions.integration.test.ts +255 -0
  155. package/template/server/src/modules/admin/__tests__/admin.health.test.ts +82 -0
  156. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +55 -0
  157. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +38 -0
  158. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +162 -0
  159. package/template/server/src/modules/admin/admin.controller.ts +66 -49
  160. package/template/server/src/modules/admin/admin.repo.ts +49 -10
  161. package/template/server/src/modules/admin/admin.routes.ts +48 -2
  162. package/template/server/src/modules/admin/admin.schemas.ts +18 -6
  163. package/template/server/src/modules/admin/admin.service.ts +66 -4
  164. package/template/server/src/modules/auth/__tests__/auth.controller.test.ts +39 -0
  165. package/template/server/src/modules/auth/__tests__/auth.integration.test.ts +9 -3
  166. package/template/server/src/modules/auth/__tests__/auth.service.dummy-hash.test.ts +34 -0
  167. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +197 -37
  168. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +39 -0
  169. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +246 -0
  170. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +119 -0
  171. package/template/server/src/modules/auth/auth.controller.ts +133 -128
  172. package/template/server/src/modules/auth/auth.repo.ts +44 -44
  173. package/template/server/src/modules/auth/auth.schemas.ts +4 -2
  174. package/template/server/src/modules/auth/auth.service.ts +167 -96
  175. package/template/server/src/modules/auth/session.repo.ts +12 -0
  176. package/template/server/src/modules/files/__tests__/files.integration.test.ts +5 -5
  177. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +120 -0
  178. package/template/server/src/modules/users/__tests__/name-rules.test.ts +46 -0
  179. package/template/server/src/modules/users/__tests__/users.integration.test.ts +295 -0
  180. package/template/server/src/modules/users/__tests__/users.repo.test.ts +37 -0
  181. package/template/server/src/modules/users/__tests__/users.service.test.ts +129 -0
  182. package/template/server/src/modules/users/users.controller.ts +9 -38
  183. package/template/server/src/modules/users/users.repo.ts +23 -7
  184. package/template/server/src/modules/users/users.routes.ts +3 -22
  185. package/template/server/src/modules/users/users.schemas.ts +15 -9
  186. package/template/server/src/modules/users/users.service.ts +105 -93
  187. package/template/server/src/scripts/make-admin.ts +48 -0
  188. package/template/server/src/server.ts +48 -26
  189. package/template/server/src/shared/errors/AppError.ts +27 -1
  190. package/template/server/src/shared/errors/errors.ts +42 -5
  191. package/template/server/src/shared/responses/successResponse.ts +22 -3
  192. package/template/server/src/shared/types/index.ts +7 -0
  193. package/template/server/src/test/__tests__/integration-services.test.ts +66 -0
  194. package/template/server/src/test/integration-helpers.ts +343 -0
  195. package/template/server/src/test/integration-services.ts +74 -0
  196. package/template/server/src/test/integration.global-setup.ts +144 -0
  197. package/template/server/src/test/integration.setup.ts +35 -158
  198. package/template/server/src/test/setup.ts +3 -10
  199. package/template/server/tsconfig.build.json +1 -1
  200. package/template/server/tsconfig.json +1 -0
  201. package/template/server/vitest.config.ts +17 -4
  202. package/template/server/vitest.integration.config.ts +18 -13
  203. package/template/server/src/libs/storage/filename-sanitizer.ts +0 -71
@@ -1,472 +1,495 @@
1
- #!/usr/bin/env node
2
-
3
- import { Command } from 'commander';
4
- import prompts from 'prompts';
5
- import chalk from 'chalk';
6
- import ora from 'ora';
7
- import fs from 'fs-extra';
8
- import path from 'path';
9
- import { fileURLToPath } from 'url';
10
- import crypto from 'crypto';
11
-
12
- const __filename = fileURLToPath(import.meta.url);
13
- const __dirname = path.dirname(__filename);
14
-
15
- const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
16
- const VERSION = packageJson.version;
17
-
18
- const TEMPLATE_DIR = path.join(__dirname, '..', 'template');
19
-
20
- // Non-secret placeholder written into the COMMITTED server/.env.example.
21
- // The real secret replaces it only in the git-ignored server/.env.
22
- const JWT_SECRET_PLACEHOLDER = 'CHANGE_ME_generate_with_openssl_rand_hex_48';
23
-
24
- // Files that contain template variables and need replacement
25
- const FILES_TO_REPLACE = [
26
- 'AGENTS.md',
27
- 'server/package.json',
28
- 'server/.env.example',
29
- 'server/docker-compose.yml',
30
- 'client/package.json',
31
- 'client/.env.example',
32
- 'client/.env.example.production',
33
- 'server/postman/collection.json',
34
- 'server/postman/environment.json',
35
- ];
36
-
37
- // Directories/files to skip when copying
38
- const SKIP_PATTERNS = [
39
- 'node_modules',
40
- '.next',
41
- 'dist',
42
- 'out',
43
- '.env',
44
- '.env.local',
45
- '.env.*.local',
46
- 'package-lock.json',
47
- 'pnpm-lock.yaml',
48
- 'yarn.lock',
49
- ];
50
-
51
- function toKebabCase(str) {
52
- return str
53
- .toLowerCase()
54
- .replace(/[^a-z0-9-]/g, '-')
55
- .replace(/-+/g, '-')
56
- .replace(/^-|-$/g, '');
57
- }
58
-
59
- function toSnakeCase(str) {
60
- return str.replace(/-/g, '_');
61
- }
62
-
63
- function toTitleCase(str) {
64
- return str
65
- .split('-')
66
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
67
- .join(' ');
68
- }
69
-
70
- function validateProjectName(name) {
71
- if (!name || name.trim().length === 0) {
72
- return 'Project name cannot be empty';
73
- }
74
- const kebab = toKebabCase(name);
75
- if (kebab.length === 0) {
76
- return 'Project name must contain at least one alphanumeric character';
77
- }
78
- if (kebab.length > 214) {
79
- return 'Project name is too long (max 214 characters)';
80
- }
81
- return true;
82
- }
83
-
84
- function shouldSkip(filePath) {
85
- const parts = filePath.split(path.sep);
86
- return parts.some((part) =>
87
- SKIP_PATTERNS.some((pattern) => {
88
- if (pattern.includes('*')) {
89
- const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
90
- return regex.test(part);
91
- }
92
- return part === pattern;
93
- })
94
- );
95
- }
96
-
97
- async function copyTemplate(templateDir, targetDir) {
98
- const entries = await fs.readdir(templateDir, { withFileTypes: true });
99
-
100
- for (const entry of entries) {
101
- const srcPath = path.join(templateDir, entry.name);
102
- const relativePath = path.relative(TEMPLATE_DIR, srcPath);
103
-
104
- if (shouldSkip(relativePath)) {
105
- continue;
106
- }
107
-
108
- // The repository stores the gitignore without a leading dot so npm reliably
109
- // includes it in the published template; generated projects receive the dotfile.
110
- let destName = entry.name;
111
- if (entry.name === 'gitignore') destName = '.gitignore';
112
-
113
- const destPath = path.join(targetDir, destName);
114
-
115
- if (entry.isDirectory()) {
116
- await fs.ensureDir(destPath);
117
- await copyTemplate(srcPath, destPath);
118
- } else {
119
- await fs.copy(srcPath, destPath);
120
- }
121
- }
122
- }
123
-
124
- function replaceVariables(content, variables) {
125
- let result = content;
126
- for (const [key, value] of Object.entries(variables)) {
127
- result = result.replaceAll(`{{${key}}}`, value);
128
- }
129
- return result;
130
- }
131
-
132
- // When stdin is closed/non-interactive, `prompts` never settles its promise:
133
- // the event loop drains and Node exits 0 mid-await — no scaffold, no error.
134
- // That silently "succeeds" in CI. Track the in-flight prompt and fail loudly.
135
- let activePromptMessage = null;
136
-
137
- process.on('exit', (code) => {
138
- if (activePromptMessage !== null && code === 0) {
139
- // writeSync: stderr writes via console.error can be lost in an 'exit'
140
- // handler when stderr is a pipe (async on Windows).
141
- fs.writeSync(
142
- 2,
143
- `\n Aborted: the prompt "${activePromptMessage}" was not answered ` +
144
- `(stdin is closed or non-interactive).\n` +
145
- ` Run in an interactive terminal, or pipe answers via stdin.\n\n`,
146
- );
147
- process.exitCode = 1;
148
- }
149
- });
150
-
151
- async function ask(question) {
152
- activePromptMessage = question.message;
153
- const response = await prompts(question, {
154
- onCancel: () => {
155
- console.error(chalk.red('\n Cancelled.\n'));
156
- process.exit(1);
157
- },
158
- });
159
- activePromptMessage = null;
160
- if (response[question.name] === undefined) {
161
- console.error(
162
- chalk.red(`\n Aborted: no answer received for "${question.message}".\n`),
163
- );
164
- process.exit(1);
165
- }
166
- return response;
167
- }
168
-
169
- function registerAddCommand(program) {
170
- program
171
- .command('add <module>')
172
- .description('Add a module to an existing Tigra project')
173
- .action(async (moduleName) => {
174
- console.log();
175
- console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`) + chalk.dim(' — add module'));
176
- console.log();
177
-
178
- const projectDir = process.cwd();
179
-
180
- // Detect if we're inside a Tigra project
181
- const hasServer = await fs.pathExists(path.join(projectDir, 'server', 'src', 'modules', 'auth'));
182
- const hasClient = await fs.pathExists(path.join(projectDir, 'client', 'src', 'features', 'auth'));
183
-
184
- if (!hasServer || !hasClient) {
185
- console.error(chalk.red(' This does not appear to be a Tigra project.'));
186
- console.error(chalk.dim(' Run this command from the root of your project (the folder containing server/ and client/).'));
187
- console.log();
188
- process.exit(1);
189
- }
190
-
191
- const availableModules = ['email-verification'];
192
-
193
- if (!availableModules.includes(moduleName)) {
194
- console.error(chalk.red(` Unknown module: "${moduleName}"`));
195
- console.log();
196
- console.log(chalk.dim(' Available modules:'));
197
- for (const m of availableModules) {
198
- console.log(chalk.cyan(` - ${m}`));
199
- }
200
- console.log();
201
- process.exit(1);
202
- }
203
-
204
- if (moduleName === 'email-verification') {
205
- // Check if already applied
206
- const alreadyApplied = await fs.pathExists(
207
- path.join(projectDir, 'server', 'src', 'modules', 'auth', 'verification.service.ts'),
208
- );
209
- if (alreadyApplied) {
210
- console.log(chalk.yellow(' Email verification is already installed in this project.'));
211
- console.log();
212
- process.exit(0);
213
- }
214
-
215
- const spinner = ora('Adding email verification module...').start();
216
-
217
- try {
218
- const { applyEmailVerificationModule } = await import(
219
- '../lib/patchers/email-verification.patcher.js'
220
- );
221
- await applyEmailVerificationModule(projectDir);
222
-
223
- // Set REQUIRE_USER_VERIFICATION=true in .env if it's currently false
224
- for (const envFile of ['server/.env.example', 'server/.env']) {
225
- const envPath = path.join(projectDir, envFile);
226
- if (await fs.pathExists(envPath)) {
227
- const content = await fs.readFile(envPath, 'utf-8');
228
- if (content.includes('REQUIRE_USER_VERIFICATION=false')) {
229
- await fs.writeFile(
230
- envPath,
231
- content.replace('REQUIRE_USER_VERIFICATION=false', 'REQUIRE_USER_VERIFICATION=true'),
232
- 'utf-8',
233
- );
234
- }
235
- }
236
- }
237
-
238
- spinner.succeed('Email verification module added!');
239
- } catch (error) {
240
- spinner.fail('Failed to add email verification module');
241
- console.error(chalk.red(`\n ${error.message}\n`));
242
- process.exit(1);
243
- }
244
-
245
- const dim = chalk.dim;
246
- const cyan = chalk.cyan;
247
- const green = chalk.green;
248
-
249
- console.log();
250
- console.log(green(' ✓ ') + 'Files added:');
251
- console.log(dim(' server/src/modules/auth/verification.service.ts'));
252
- console.log(dim(' server/src/modules/auth/verification.controller.ts'));
253
- console.log(dim(' client/src/features/auth/services/verification.service.ts'));
254
- console.log(dim(' client/src/features/auth/hooks/useVerification.ts'));
255
- console.log();
256
- console.log(green(' ✓ ') + 'Files patched:');
257
- console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts, auth.repo.ts'));
258
- console.log(dim(' rate-limit.config.ts, api-endpoints.ts, error.ts, useAuth.ts'));
259
- console.log(dim(' postman/collection.json'));
260
- console.log();
261
- console.log(green(' ✓ ') + 'REQUIRE_USER_VERIFICATION=true in server/.env');
262
- console.log();
263
- console.log(dim(' Next steps:'));
264
- console.log(cyan(' 1 ') + 'Set ' + chalk.bold('RESEND_API_KEY') + ' in server/.env');
265
- console.log(cyan(' 2 ') + 'Restart the server');
266
- console.log();
267
- }
268
- });
269
- }
270
-
271
- async function main() {
272
- const program = new Command();
273
-
274
- // Define the add subcommand BEFORE the default command so Commander recognizes it
275
- program
276
- .name('create-tigra')
277
- .description('Create a production-ready full-stack app with Next.js + Fastify + Prisma + Redis')
278
- .version(VERSION);
279
-
280
- // ─── Add module subcommand ────────────────────────────────────
281
- registerAddCommand(program);
282
-
283
- // ─── Default: scaffold new project ────────────────────────────
284
- program
285
- .argument('[project-name]', 'Name for your new project')
286
- .action(async (projectNameArg) => {
287
- console.log();
288
- console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`));
289
- console.log();
290
-
291
- let projectName = projectNameArg;
292
-
293
- if (!projectName) {
294
- const response = await ask({
295
- type: 'text',
296
- name: 'projectName',
297
- message: 'What is your project name?',
298
- validate: validateProjectName,
299
- });
300
- projectName = response.projectName;
301
- }
302
-
303
- // Validate and normalize
304
- const validation = validateProjectName(projectName);
305
- if (validation !== true) {
306
- console.error(chalk.red(`\n ${validation}\n`));
307
- process.exit(1);
308
- }
309
-
310
- projectName = toKebabCase(projectName);
311
-
312
- const targetDir = path.resolve(process.cwd(), projectName);
313
-
314
- // Check if directory exists and is non-empty
315
- if (await fs.pathExists(targetDir)) {
316
- const files = await fs.readdir(targetDir);
317
- if (files.length > 0) {
318
- console.error(chalk.red(`\n Directory "${projectName}" already exists and is not empty.\n`));
319
- process.exit(1);
320
- }
321
- }
322
-
323
- // Ask about email verification
324
- const { enableVerification } = await ask({
325
- type: 'toggle',
326
- name: 'enableVerification',
327
- message: 'Enable email verification for new users?',
328
- initial: false,
329
- active: 'Yes',
330
- inactive: 'No',
331
- hint: 'Users must verify email before accessing the app',
332
- });
333
-
334
- // Generate random port offset (1-200) so multiple projects don't conflict
335
- const portOffset = crypto.randomInt(1, 201);
336
-
337
- // Derive all variables.
338
- // SECURITY: everything in this map is written into COMMITTED files
339
- // (.env.example, docker-compose.yml, ...) — never put a real secret here.
340
- // JWT_SECRET gets an instructional placeholder; the real secret is
341
- // generated below and written ONLY to the git-ignored .env.
342
- const variables = {
343
- PROJECT_NAME: projectName,
344
- PROJECT_NAME_SNAKE: toSnakeCase(projectName),
345
- PROJECT_DISPLAY_NAME: toTitleCase(projectName),
346
- DATABASE_NAME: `${toSnakeCase(projectName)}_db`,
347
- JWT_SECRET: JWT_SECRET_PLACEHOLDER,
348
- MYSQL_PORT: String(3306 + portOffset),
349
- PHPMYADMIN_PORT: String(8080 + portOffset),
350
- REDIS_PORT: String(6379 + portOffset),
351
- REDIS_COMMANDER_PORT: String(8081 + portOffset),
352
- };
353
-
354
- // Copy template
355
- const spinner = ora('Scaffolding project...').start();
356
-
357
- try {
358
- await fs.ensureDir(targetDir);
359
- await copyTemplate(TEMPLATE_DIR, targetDir);
360
-
361
- // Replace template variables in specific files
362
- for (const filePath of FILES_TO_REPLACE) {
363
- const fullPath = path.join(targetDir, filePath);
364
- if (await fs.pathExists(fullPath)) {
365
- const content = await fs.readFile(fullPath, 'utf-8');
366
- const replaced = replaceVariables(content, variables);
367
- await fs.writeFile(fullPath, replaced, 'utf-8');
368
- }
369
- }
370
-
371
- // Generate .env from .env.example (so users don't have to copy manually).
372
- // The real JWT secret is injected HERE and only here — .env is
373
- // git-ignored, while .env.example is committed and must keep the
374
- // CHANGE_ME placeholder.
375
- const jwtSecret = crypto.randomBytes(48).toString('hex');
376
- for (const envExample of ['server/.env.example', 'client/.env.example']) {
377
- const examplePath = path.join(targetDir, envExample);
378
- const envPath = path.join(targetDir, envExample.replace('.env.example', '.env'));
379
- if (await fs.pathExists(examplePath)) {
380
- const content = await fs.readFile(examplePath, 'utf-8');
381
- await fs.writeFile(
382
- envPath,
383
- content.replaceAll(JWT_SECRET_PLACEHOLDER, jwtSecret),
384
- 'utf-8',
385
- );
386
- }
387
- }
388
-
389
- // Apply email verification module if selected
390
- if (enableVerification) {
391
- const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
392
- await applyEmailVerificationModule(targetDir);
393
- } else {
394
- // Disable verification requirement in .env files
395
- for (const envFile of ['server/.env.example', 'server/.env']) {
396
- const envPath = path.join(targetDir, envFile);
397
- if (await fs.pathExists(envPath)) {
398
- const content = await fs.readFile(envPath, 'utf-8');
399
- await fs.writeFile(
400
- envPath,
401
- content.replace('REQUIRE_USER_VERIFICATION=true', 'REQUIRE_USER_VERIFICATION=false'),
402
- 'utf-8',
403
- );
404
- }
405
- }
406
- }
407
-
408
- spinner.succeed('Project scaffolded successfully!');
409
- } catch (error) {
410
- spinner.fail('Failed to scaffold project');
411
- console.error(chalk.red(`\n ${error.message}\n`));
412
- process.exit(1);
413
- }
414
-
415
- // Print next steps
416
- const dim = chalk.dim;
417
- const bold = chalk.bold;
418
- const cyan = chalk.cyan;
419
- const green = chalk.green;
420
- const line = dim(' ─────────────────────────────────────────');
421
-
422
- console.log();
423
- console.log(green.bold(' ✓ Created ') + cyan.bold(projectName) + dim(` at ${targetDir}`));
424
- console.log();
425
- console.log(' ┌─────────────────────────────────────────┐');
426
- console.log(' │' + bold(' Getting Started ') + '│');
427
- console.log(' └─────────────────────────────────────────┘');
428
- console.log();
429
- console.log(bold(' SERVER') + dim(' cd ') + cyan(`${projectName}/server`));
430
- console.log();
431
- console.log(cyan(' 1 ') + 'Install & start infrastructure');
432
- console.log(dim(' npm install'));
433
- console.log(dim(' npm run docker:up'));
434
- console.log();
435
- console.log(cyan(' 2 ') + 'Set up database');
436
- console.log(dim(' npm run prisma:generate'));
437
- console.log(dim(' npm run prisma:migrate:dev -- --name init'));
438
- console.log();
439
- console.log(cyan(' 3 ') + 'Start the server');
440
- console.log(dim(' npm run dev'));
441
- console.log();
442
- console.log(bold(' CLIENT') + dim(' (new terminal) cd ') + cyan(`${projectName}/client`));
443
- console.log();
444
- console.log(cyan(' 4 ') + 'Start the client');
445
- console.log(dim(' npm install'));
446
- console.log(dim(' npm run dev'));
447
- console.log();
448
- console.log(line);
449
- console.log();
450
- console.log(dim(' App ') + cyan('http://localhost:3000'));
451
- console.log(dim(' API ') + cyan('http://localhost:8000'));
452
- console.log(dim(' DB/Redis UIs ') + 'optional — start with ' + cyan('npm run docker:tools'));
453
- console.log(dim(' phpMyAdmin ') + cyan(`http://localhost:${variables.PHPMYADMIN_PORT}`));
454
- console.log(dim(' Redis CMD ') + cyan(`http://localhost:${variables.REDIS_COMMANDER_PORT}`));
455
- console.log();
456
- console.log(line);
457
- console.log();
458
- if (enableVerification) {
459
- console.log(dim(' Email verification: ') + green('enabled'));
460
- console.log(dim(' Set RESEND_API_KEY in server/.env to send emails'));
461
- console.log();
462
- }
463
- console.log(dim(' Tip: ') + 'npm run docker:down' + dim(' to stop infrastructure'));
464
- console.log();
465
- console.log(dim(' Happy coding! 🚀'));
466
- console.log();
467
- });
468
-
469
- program.parse();
470
- }
471
-
472
- main();
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import prompts from 'prompts';
5
+ import chalk from 'chalk';
6
+ import ora from 'ora';
7
+ import fs from 'fs-extra';
8
+ import path from 'path';
9
+ import { fileURLToPath } from 'url';
10
+ import crypto from 'crypto';
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
14
+
15
+ const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'));
16
+ const VERSION = packageJson.version;
17
+
18
+ const TEMPLATE_DIR = path.join(__dirname, '..', 'template');
19
+
20
+ // Non-secret placeholder written into the COMMITTED server/.env.example.
21
+ // The real secret replaces it only in the git-ignored server/.env.
22
+ const JWT_SECRET_PLACEHOLDER = 'CHANGE_ME_generate_with_openssl_rand_hex_48';
23
+
24
+ // Files that contain template variables and need replacement
25
+ const FILES_TO_REPLACE = [
26
+ 'AGENTS.md',
27
+ 'server/package.json',
28
+ 'server/.env.example',
29
+ 'server/docker-compose.yml',
30
+ 'client/package.json',
31
+ // The shipped lockfiles carry {{PROJECT_NAME}} in their root "name" fields.
32
+ 'server/package-lock.json',
33
+ 'client/package-lock.json',
34
+ 'client/.env.example',
35
+ 'client/.env.example.production',
36
+ 'server/postman/collection.json',
37
+ 'server/postman/environment.json',
38
+ ];
39
+
40
+ // Directories/files to skip when copying
41
+ const SKIP_PATTERNS = [
42
+ 'node_modules',
43
+ '.next',
44
+ 'dist',
45
+ 'out',
46
+ '.env',
47
+ '.env.local',
48
+ '.env.*.local',
49
+ // package-lock.json is NOT skipped: new projects get the template's tested
50
+ // lockfiles, written with the npm in the Dockerfiles' image, so the first
51
+ // `npm ci` (locally and in Docker) installs exactly the versions we tested.
52
+ // Without them every project resolved fresh versions on first install.
53
+ 'pnpm-lock.yaml',
54
+ 'yarn.lock',
55
+ ];
56
+
57
+ function toKebabCase(str) {
58
+ return str
59
+ .toLowerCase()
60
+ .replace(/[^a-z0-9-]/g, '-')
61
+ .replace(/-+/g, '-')
62
+ .replace(/^-|-$/g, '');
63
+ }
64
+
65
+ function toSnakeCase(str) {
66
+ return str.replace(/-/g, '_');
67
+ }
68
+
69
+ function toTitleCase(str) {
70
+ return str
71
+ .split('-')
72
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
73
+ .join(' ');
74
+ }
75
+
76
+ function validateProjectName(name) {
77
+ if (!name || name.trim().length === 0) {
78
+ return 'Project name cannot be empty';
79
+ }
80
+ const kebab = toKebabCase(name);
81
+ if (kebab.length === 0) {
82
+ return 'Project name must contain at least one alphanumeric character';
83
+ }
84
+ if (kebab.length > 214) {
85
+ return 'Project name is too long (max 214 characters)';
86
+ }
87
+ return true;
88
+ }
89
+
90
+ // The generated apps need newer tools than this CLI itself (which runs on Node
91
+ // 22.12+): Node 24+ (their package.json engines and Docker images) and npm
92
+ // 11.19+ (the npm in those images; an older npm writes lockfiles that the
93
+ // image's `npm ci` rejects at deploy time). Warn, never stop: the project is
94
+ // still created, and the tools can be updated before the first `npm ci`.
95
+ const APP_MIN_NODE_MAJOR = 24;
96
+ const APP_MIN_NPM = { major: 11, minor: 19 };
97
+
98
+ function appRuntimeWarnings() {
99
+ const warnings = [];
100
+ const nodeMajor = Number(process.versions.node.split('.')[0]);
101
+ if (nodeMajor < APP_MIN_NODE_MAJOR) {
102
+ warnings.push(`Node ${process.versions.node} found: the new project needs Node ${APP_MIN_NODE_MAJOR} or newer.`);
103
+ }
104
+ // npm names itself in npm_config_user_agent ("npm/11.6.1 node/v24.11.0 ...")
105
+ // when it launches this CLI (npx, npm create, npm run). Launched any other
106
+ // way, npm is not checked rather than spawning it.
107
+ const npm = /\bnpm\/(\d+)\.(\d+)\./.exec(process.env.npm_config_user_agent ?? '');
108
+ if (npm) {
109
+ const major = Number(npm[1]);
110
+ const minor = Number(npm[2]);
111
+ if (major < APP_MIN_NPM.major || (major === APP_MIN_NPM.major && minor < APP_MIN_NPM.minor)) {
112
+ warnings.push(
113
+ `npm ${major}.${minor} found: use npm ${APP_MIN_NPM.major}.${APP_MIN_NPM.minor} or newer ` +
114
+ `(npm install -g npm@${APP_MIN_NPM.major}), or the Docker build rejects your lockfiles.`,
115
+ );
116
+ }
117
+ }
118
+ return warnings;
119
+ }
120
+
121
+ function shouldSkip(filePath) {
122
+ const parts = filePath.split(path.sep);
123
+ return parts.some((part) =>
124
+ SKIP_PATTERNS.some((pattern) => {
125
+ if (pattern.includes('*')) {
126
+ const regex = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
127
+ return regex.test(part);
128
+ }
129
+ return part === pattern;
130
+ })
131
+ );
132
+ }
133
+
134
+ async function copyTemplate(templateDir, targetDir) {
135
+ const entries = await fs.readdir(templateDir, { withFileTypes: true });
136
+
137
+ for (const entry of entries) {
138
+ const srcPath = path.join(templateDir, entry.name);
139
+ const relativePath = path.relative(TEMPLATE_DIR, srcPath);
140
+
141
+ if (shouldSkip(relativePath)) {
142
+ continue;
143
+ }
144
+
145
+ // The repository stores the gitignore without a leading dot so npm reliably
146
+ // includes it in the published template; generated projects receive the dotfile.
147
+ let destName = entry.name;
148
+ if (entry.name === 'gitignore') destName = '.gitignore';
149
+
150
+ const destPath = path.join(targetDir, destName);
151
+
152
+ if (entry.isDirectory()) {
153
+ await fs.ensureDir(destPath);
154
+ await copyTemplate(srcPath, destPath);
155
+ } else {
156
+ await fs.copy(srcPath, destPath);
157
+ }
158
+ }
159
+ }
160
+
161
+ function replaceVariables(content, variables) {
162
+ let result = content;
163
+ for (const [key, value] of Object.entries(variables)) {
164
+ result = result.replaceAll(`{{${key}}}`, value);
165
+ }
166
+ return result;
167
+ }
168
+
169
+ // When stdin is closed/non-interactive, `prompts` never settles its promise:
170
+ // the event loop drains and Node exits 0 mid-await — no scaffold, no error.
171
+ // That silently "succeeds" in CI. Track the in-flight prompt and fail loudly.
172
+ let activePromptMessage = null;
173
+
174
+ process.on('exit', (code) => {
175
+ if (activePromptMessage !== null && code === 0) {
176
+ // writeSync: stderr writes via console.error can be lost in an 'exit'
177
+ // handler when stderr is a pipe (async on Windows).
178
+ fs.writeSync(
179
+ 2,
180
+ `\n Aborted: the prompt "${activePromptMessage}" was not answered ` +
181
+ `(stdin is closed or non-interactive).\n` +
182
+ ` Run in an interactive terminal, or pipe answers via stdin.\n\n`,
183
+ );
184
+ process.exitCode = 1;
185
+ }
186
+ });
187
+
188
+ async function ask(question) {
189
+ activePromptMessage = question.message;
190
+ const response = await prompts(question, {
191
+ onCancel: () => {
192
+ console.error(chalk.red('\n Cancelled.\n'));
193
+ process.exit(1);
194
+ },
195
+ });
196
+ activePromptMessage = null;
197
+ if (response[question.name] === undefined) {
198
+ console.error(
199
+ chalk.red(`\n Aborted: no answer received for "${question.message}".\n`),
200
+ );
201
+ process.exit(1);
202
+ }
203
+ return response;
204
+ }
205
+
206
+ function registerAddCommand(program) {
207
+ program
208
+ .command('add <module>')
209
+ .description('Add a module to an existing Tigra project')
210
+ .action(async (moduleName) => {
211
+ console.log();
212
+ console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`) + chalk.dim(' — add module'));
213
+ console.log();
214
+
215
+ const projectDir = process.cwd();
216
+
217
+ // Detect if we're inside a Tigra project
218
+ const hasServer = await fs.pathExists(path.join(projectDir, 'server', 'src', 'modules', 'auth'));
219
+ const hasClient = await fs.pathExists(path.join(projectDir, 'client', 'src', 'features', 'auth'));
220
+
221
+ if (!hasServer || !hasClient) {
222
+ console.error(chalk.red(' This does not appear to be a Tigra project.'));
223
+ console.error(chalk.dim(' Run this command from the root of your project (the folder containing server/ and client/).'));
224
+ console.log();
225
+ process.exit(1);
226
+ }
227
+
228
+ const availableModules = ['email-verification'];
229
+
230
+ if (!availableModules.includes(moduleName)) {
231
+ console.error(chalk.red(` Unknown module: "${moduleName}"`));
232
+ console.log();
233
+ console.log(chalk.dim(' Available modules:'));
234
+ for (const m of availableModules) {
235
+ console.log(chalk.cyan(` - ${m}`));
236
+ }
237
+ console.log();
238
+ process.exit(1);
239
+ }
240
+
241
+ if (moduleName === 'email-verification') {
242
+ // Check if already applied
243
+ const alreadyApplied = await fs.pathExists(
244
+ path.join(projectDir, 'server', 'src', 'modules', 'auth', 'verification.service.ts'),
245
+ );
246
+ if (alreadyApplied) {
247
+ console.log(chalk.yellow(' Email verification is already installed in this project.'));
248
+ console.log();
249
+ process.exit(0);
250
+ }
251
+
252
+ const spinner = ora('Adding email verification module...').start();
253
+
254
+ try {
255
+ const { applyEmailVerificationModule } = await import(
256
+ '../lib/patchers/email-verification.patcher.js'
257
+ );
258
+ // Also switches REQUIRE_USER_VERIFICATION on (env.ts default + every
259
+ // server env file), exactly as at scaffold time.
260
+ await applyEmailVerificationModule(projectDir);
261
+
262
+ spinner.succeed('Email verification module added!');
263
+ } catch (error) {
264
+ spinner.fail('Failed to add email verification module');
265
+ console.error(chalk.red(`\n ${error.message}\n`));
266
+ process.exit(1);
267
+ }
268
+
269
+ const dim = chalk.dim;
270
+ const cyan = chalk.cyan;
271
+ const green = chalk.green;
272
+
273
+ console.log();
274
+ console.log(green(' ✓ ') + 'Files added:');
275
+ console.log(dim(' server/src/modules/auth/verification.service.ts'));
276
+ console.log(dim(' server/src/modules/auth/verification.controller.ts'));
277
+ console.log(dim(' client/src/features/auth/services/verification.service.ts'));
278
+ console.log(dim(' client/src/features/auth/hooks/useVerification.ts'));
279
+ console.log();
280
+ console.log(green(' ✓ ') + 'Files patched:');
281
+ console.log(dim(' auth.routes.ts, auth.schemas.ts, auth.service.ts, auth.repo.ts'));
282
+ console.log(dim(' rate-limit.config.ts, api-endpoints.ts, error.ts, useAuth.ts'));
283
+ console.log(dim(' postman/collection.json'));
284
+ console.log();
285
+ console.log(green(' ✓ ') + 'REQUIRE_USER_VERIFICATION=true in server/.env');
286
+ console.log();
287
+ console.log(dim(' Next steps:'));
288
+ console.log(cyan(' 1 ') + 'Set ' + chalk.bold('RESEND_API_KEY') + ' in server/.env');
289
+ console.log(cyan(' 2 ') + 'Restart the server');
290
+ console.log();
291
+ }
292
+ });
293
+ }
294
+
295
+ async function main() {
296
+ const program = new Command();
297
+
298
+ // Define the add subcommand BEFORE the default command so Commander recognizes it
299
+ program
300
+ .name('create-tigra')
301
+ .description('Create a production-ready full-stack app with Next.js + Fastify + Prisma + Redis')
302
+ .version(VERSION);
303
+
304
+ // ─── Add module subcommand ────────────────────────────────────
305
+ registerAddCommand(program);
306
+
307
+ // ─── Default: scaffold new project ────────────────────────────
308
+ program
309
+ .argument('[project-name]', 'Name for your new project')
310
+ .action(async (projectNameArg) => {
311
+ console.log();
312
+ console.log(chalk.bold(' Create Tigra') + chalk.dim(` v${VERSION}`));
313
+ console.log();
314
+ const runtimeWarnings = appRuntimeWarnings();
315
+ for (const warning of runtimeWarnings) {
316
+ console.log(chalk.yellow(` ! ${warning}`));
317
+ }
318
+ if (runtimeWarnings.length > 0) console.log();
319
+
320
+ let projectName = projectNameArg;
321
+
322
+ if (!projectName) {
323
+ const response = await ask({
324
+ type: 'text',
325
+ name: 'projectName',
326
+ message: 'What is your project name?',
327
+ validate: validateProjectName,
328
+ });
329
+ projectName = response.projectName;
330
+ }
331
+
332
+ // Validate and normalize
333
+ const validation = validateProjectName(projectName);
334
+ if (validation !== true) {
335
+ console.error(chalk.red(`\n ${validation}\n`));
336
+ process.exit(1);
337
+ }
338
+
339
+ projectName = toKebabCase(projectName);
340
+
341
+ const targetDir = path.resolve(process.cwd(), projectName);
342
+
343
+ // Check if directory exists and is non-empty
344
+ if (await fs.pathExists(targetDir)) {
345
+ const files = await fs.readdir(targetDir);
346
+ if (files.length > 0) {
347
+ console.error(chalk.red(`\n Directory "${projectName}" already exists and is not empty.\n`));
348
+ process.exit(1);
349
+ }
350
+ }
351
+
352
+ // Ask about email verification
353
+ const { enableVerification } = await ask({
354
+ type: 'toggle',
355
+ name: 'enableVerification',
356
+ message: 'Enable email verification for new users?',
357
+ initial: false,
358
+ active: 'Yes',
359
+ inactive: 'No',
360
+ hint: 'Users must verify email before accessing the app',
361
+ });
362
+
363
+ // Generate random port offset (1-200) so multiple projects don't conflict
364
+ const portOffset = crypto.randomInt(1, 201);
365
+
366
+ // Derive all variables.
367
+ // SECURITY: everything in this map is written into COMMITTED files
368
+ // (.env.example, docker-compose.yml, ...) — never put a real secret here.
369
+ // JWT_SECRET gets an instructional placeholder; the real secret is
370
+ // generated below and written ONLY to the git-ignored .env.
371
+ const variables = {
372
+ PROJECT_NAME: projectName,
373
+ PROJECT_NAME_SNAKE: toSnakeCase(projectName),
374
+ PROJECT_DISPLAY_NAME: toTitleCase(projectName),
375
+ DATABASE_NAME: `${toSnakeCase(projectName)}_db`,
376
+ JWT_SECRET: JWT_SECRET_PLACEHOLDER,
377
+ MYSQL_PORT: String(3306 + portOffset),
378
+ PHPMYADMIN_PORT: String(8080 + portOffset),
379
+ REDIS_PORT: String(6379 + portOffset),
380
+ REDIS_COMMANDER_PORT: String(8081 + portOffset),
381
+ };
382
+
383
+ // Copy template
384
+ const spinner = ora('Scaffolding project...').start();
385
+
386
+ try {
387
+ await fs.ensureDir(targetDir);
388
+ await copyTemplate(TEMPLATE_DIR, targetDir);
389
+
390
+ // Replace template variables in specific files
391
+ for (const filePath of FILES_TO_REPLACE) {
392
+ const fullPath = path.join(targetDir, filePath);
393
+ if (await fs.pathExists(fullPath)) {
394
+ const content = await fs.readFile(fullPath, 'utf-8');
395
+ const replaced = replaceVariables(content, variables);
396
+ await fs.writeFile(fullPath, replaced, 'utf-8');
397
+ }
398
+ }
399
+
400
+ // Generate .env from .env.example (so users don't have to copy manually).
401
+ // The real JWT secret is injected HERE and only here — .env is
402
+ // git-ignored, while .env.example is committed and must keep the
403
+ // CHANGE_ME placeholder.
404
+ const jwtSecret = crypto.randomBytes(48).toString('hex');
405
+ for (const envExample of ['server/.env.example', 'client/.env.example']) {
406
+ const examplePath = path.join(targetDir, envExample);
407
+ const envPath = path.join(targetDir, envExample.replace('.env.example', '.env'));
408
+ if (await fs.pathExists(examplePath)) {
409
+ const content = await fs.readFile(examplePath, 'utf-8');
410
+ await fs.writeFile(
411
+ envPath,
412
+ content.replaceAll(JWT_SECRET_PLACEHOLDER, jwtSecret),
413
+ 'utf-8',
414
+ );
415
+ }
416
+ }
417
+
418
+ // Apply email verification module if selected. The template ships with
419
+ // REQUIRE_USER_VERIFICATION off everywhere (no verify route without the
420
+ // module); the patcher switches it on in env.ts and every env file.
421
+ if (enableVerification) {
422
+ const { applyEmailVerificationModule } = await import('../lib/patchers/email-verification.patcher.js');
423
+ await applyEmailVerificationModule(targetDir);
424
+ }
425
+
426
+ spinner.succeed('Project scaffolded successfully!');
427
+ } catch (error) {
428
+ spinner.fail('Failed to scaffold project');
429
+ console.error(chalk.red(`\n ${error.message}\n`));
430
+ process.exit(1);
431
+ }
432
+
433
+ // Print next steps
434
+ const dim = chalk.dim;
435
+ const bold = chalk.bold;
436
+ const cyan = chalk.cyan;
437
+ const green = chalk.green;
438
+ const line = dim(' ─────────────────────────────────────────');
439
+
440
+ console.log();
441
+ console.log(green.bold(' ✓ Created ') + cyan.bold(projectName) + dim(` at ${targetDir}`));
442
+ console.log();
443
+ console.log(' ┌─────────────────────────────────────────┐');
444
+ console.log(' │' + bold(' Getting Started ') + '│');
445
+ console.log(' └─────────────────────────────────────────┘');
446
+ console.log();
447
+ console.log(bold(' SERVER') + dim(' cd ') + cyan(`${projectName}/server`));
448
+ console.log();
449
+ console.log(cyan(' 1 ') + 'Install & start infrastructure');
450
+ // `npm ci`, not `npm install`: it installs the shipped lockfile as-is.
451
+ // `npm install` on an older local npm rewrites the lockfile into a shape
452
+ // the image's npm then rejects at deploy time.
453
+ console.log(dim(' npm ci'));
454
+ console.log(dim(' npm run docker:up'));
455
+ console.log();
456
+ console.log(cyan(' 2 ') + 'Set up database');
457
+ console.log(dim(' npm run prisma:generate'));
458
+ // No `--name init`: the template ships prisma/migrations/0_init, so this
459
+ // only applies it (creating the tables) unless the schema was changed.
460
+ console.log(dim(' npm run prisma:migrate:dev'));
461
+ console.log();
462
+ console.log(cyan(' 3 ') + 'Start the server');
463
+ console.log(dim(' npm run dev'));
464
+ console.log();
465
+ console.log(bold(' CLIENT') + dim(' (new terminal) cd ') + cyan(`${projectName}/client`));
466
+ console.log();
467
+ console.log(cyan(' 4 ') + 'Start the client');
468
+ console.log(dim(' npm ci'));
469
+ console.log(dim(' npm run dev'));
470
+ console.log();
471
+ console.log(line);
472
+ console.log();
473
+ console.log(dim(' App ') + cyan('http://localhost:3000'));
474
+ console.log(dim(' API ') + cyan('http://localhost:8000'));
475
+ console.log(dim(' DB/Redis UIs ') + 'optional — start with ' + cyan('npm run docker:tools'));
476
+ console.log(dim(' phpMyAdmin ') + cyan(`http://localhost:${variables.PHPMYADMIN_PORT}`));
477
+ console.log(dim(' Redis CMD ') + cyan(`http://localhost:${variables.REDIS_COMMANDER_PORT}`));
478
+ console.log();
479
+ console.log(line);
480
+ console.log();
481
+ if (enableVerification) {
482
+ console.log(dim(' Email verification: ') + green('enabled'));
483
+ console.log(dim(' Set RESEND_API_KEY in server/.env to send emails'));
484
+ console.log();
485
+ }
486
+ console.log(dim(' Tip: ') + 'npm run docker:down' + dim(' to stop infrastructure'));
487
+ console.log();
488
+ console.log(dim(' Happy coding! 🚀'));
489
+ console.log();
490
+ });
491
+
492
+ program.parse();
493
+ }
494
+
495
+ main();