@forinda/kickjs-cli 5.0.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v5.0.2
2
+ * @forinda/kickjs-cli v5.2.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4161 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import { createRequire } from "node:module";
12
- import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
13
- import { access, mkdir, readFile, writeFile } from "node:fs/promises";
14
- import * as clack from "@clack/prompts";
15
- import pc from "picocolors";
16
- import pkg from "pluralize";
17
- import { execSync } from "node:child_process";
18
- import { existsSync, readFileSync } from "node:fs";
19
- import { fileURLToPath } from "node:url";
20
- /** Extensions prettier can format. Anything else is written verbatim. */
21
- const FORMATTABLE = new Set([
22
- ".ts",
23
- ".tsx",
24
- ".js",
25
- ".jsx",
26
- ".mjs",
27
- ".cjs",
28
- ".json",
29
- ".md"
30
- ]);
31
- /**
32
- * Write a file, creating parent directories if needed.
33
- *
34
- * After write, runs prettier against the file when:
35
- * - format-on-write is enabled (default)
36
- * - the extension is in {@link FORMATTABLE}
37
- * - prettier resolves from the user's project (or our own cwd)
38
- *
39
- * Failures (missing prettier, unparseable source, prettier crash) are
40
- * swallowed silently — formatting is a polish step, not a correctness
41
- * gate. The pre-existing pre-commit hook still catches anything we
42
- * couldn't format.
43
- *
44
- * Skips writing entirely in dry run mode.
45
- */
46
- async function writeFileSafe(filePath, content) {
47
- await mkdir(dirname(filePath), { recursive: true });
48
- await writeFile(filePath, content, "utf-8");
49
- if (FORMATTABLE.has(extname(filePath))) await formatFile(filePath, content).catch(() => {});
50
- }
51
- let _prettier = void 0;
52
- /** Resolve prettier from the user's project; cache the result (or null) for the process. */
53
- function resolvePrettier(cwd) {
54
- if (_prettier !== void 0) return _prettier;
55
- try {
56
- _prettier = createRequire(join(cwd, "package.json"))("prettier");
57
- } catch {
58
- _prettier = null;
59
- }
60
- return _prettier;
61
- }
62
- async function formatFile(filePath, content) {
63
- const prettier = resolvePrettier(process.cwd());
64
- if (!prettier) return;
65
- if ((await prettier.getFileInfo(filePath, { resolveConfig: true })).ignored) return;
66
- const config = await prettier.resolveConfig(filePath) ?? {};
67
- const formatted = await prettier.format(content, {
68
- ...config,
69
- filepath: filePath
70
- });
71
- if (formatted === content) return;
72
- await writeFile(filePath, formatted, "utf-8");
73
- }
74
- /** Check if a file exists */
75
- async function fileExists(filePath) {
76
- try {
77
- await access(filePath);
78
- return true;
79
- } catch {
80
- return false;
81
- }
82
- }
83
- pc.green, pc.cyan, pc.yellow, pc.magenta, pc.red;
84
- pc.green("✓"), pc.red("✖"), pc.yellow("⚠"), pc.blue("ℹ");
85
- /** Handle cancellation — print message and exit */
86
- function handleCancel(value) {
87
- if (clack.isCancel(value)) {
88
- clack.cancel("Operation cancelled.");
89
- process.exit(0);
90
- }
91
- }
92
- /** Yes/no confirmation prompt */
93
- async function confirm(opts) {
94
- const value = await clack.confirm(opts);
95
- handleCancel(value);
96
- return value;
97
- }
98
- /** Log utilities for styled messages inside clack flow */
99
- const log = clack.log;
100
- //#endregion
101
- //#region src/utils/naming.ts
102
- /** Convert a name to PascalCase */
103
- function toPascalCase(name) {
104
- return name.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : "").replace(/^(.)/, (c) => c.toUpperCase());
105
- }
106
- /** Convert a name to camelCase */
107
- function toCamelCase(name) {
108
- const pascal = toPascalCase(name);
109
- return pascal.charAt(0).toLowerCase() + pascal.slice(1);
110
- }
111
- /** Convert a name to kebab-case */
112
- function toKebabCase(name) {
113
- return name.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
114
- }
115
- /**
116
- * Pluralize a kebab-case name for directory/file names.
117
- * Uses the `pluralize` npm package for correct English pluralization
118
- * including irregulars (person → people, status → statuses, child → children).
119
- */
120
- function pluralize(name) {
121
- return pkg.plural(name);
122
- }
123
- /**
124
- * Pluralize a PascalCase name for class identifiers.
125
- * Used for `List${pluralPascal}UseCase` to avoid `ListUserssUseCase`.
126
- */
127
- function pluralizePascal(name) {
128
- return pkg.plural(name);
129
- }
130
- //#endregion
131
- //#region src/generators/templates/module-index.ts
132
- const repoLabelMap = {
133
- inmemory: "in-memory",
134
- drizzle: "Drizzle",
135
- prisma: "Prisma"
136
- };
137
- function toPascalRepoType(repo) {
138
- return repo.charAt(0).toUpperCase() + repo.slice(1).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
139
- }
140
- function toKebabRepoType(repo) {
141
- return repo.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
142
- }
143
- function repoLabel(repo) {
144
- return repoLabelMap[repo] ?? toPascalRepoType(repo);
145
- }
146
- function repoMaps(pascal, kebab, repo) {
147
- const repoClassMap = {
148
- inmemory: `InMemory${pascal}Repository`,
149
- drizzle: `Drizzle${pascal}Repository`,
150
- prisma: `Prisma${pascal}Repository`
151
- };
152
- const repoFileMap = {
153
- inmemory: `in-memory-${kebab}`,
154
- drizzle: `drizzle-${kebab}`,
155
- prisma: `prisma-${kebab}`
156
- };
157
- return {
158
- repoClass: repoClassMap[repo] ?? `${toPascalRepoType(repo)}${pascal}Repository`,
159
- repoFile: repoFileMap[repo] ?? `${toKebabRepoType(repo)}-${kebab}`
160
- };
161
- }
162
- /** DDD module index — nested folders, use-cases, domain services */
163
- function generateModuleIndex(ctx) {
164
- const { pascal, kebab, plural = "", repo } = ctx;
165
- const { repoClass, repoFile } = repoMaps(pascal, kebab, repo);
166
- return `/**
167
- * ${pascal} Module
168
- *
169
- * Self-contained feature module following Domain-Driven Design (DDD).
170
- * Registers dependencies in the DI container and declares HTTP routes.
171
- *
172
- * Structure:
173
- * presentation/ — HTTP controllers (entry points)
174
- * application/ — Use cases (orchestration) and DTOs (validation)
175
- * domain/ — Entities, value objects, repository interfaces, domain services
176
- * infrastructure/ — Repository implementations (currently ${repoLabel(repo)})
177
- */
178
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
179
- import { buildRoutes } from '@forinda/kickjs'
180
- import { ${pascal.toUpperCase()}_REPOSITORY } from './domain/repositories/${kebab}.repository'
181
- import { ${repoClass} } from './infrastructure/repositories/${repoFile}.repository'
182
- import { ${pascal}Controller } from './presentation/${kebab}.controller'
183
-
184
- // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
185
- import.meta.glob(
186
- ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
187
- { eager: true },
188
- )
189
-
190
- export class ${pascal}Module implements AppModule {
191
- /**
192
- * Register module dependencies in the DI container.
193
- * Bind repository interface tokens to their implementations here.
194
- * Currently wired to ${repoLabel(repo)}. To swap implementations, change the factory target.
195
- */
196
- register(container: Container): void {
197
- container.registerFactory(${pascal.toUpperCase()}_REPOSITORY, () =>
198
- container.resolve(${repoClass}),
199
- )
200
- }
201
-
202
- /**
203
- * Declare HTTP routes for this module.
204
- * The path is prefixed with the global apiPrefix and version (e.g. /api/v1/${plural}).
205
- * Passing 'controller' enables automatic OpenAPI spec generation via SwaggerAdapter.
206
- */
207
- routes(): ModuleRoutes {
208
- return {
209
- path: '/${plural}',
210
- router: buildRoutes(${pascal}Controller),
211
- controller: ${pascal}Controller,
212
- }
213
- }
214
- }
215
- `;
216
- }
217
- /** REST module index — flat folder, service + controller, no use-cases */
218
- function generateRestModuleIndex(ctx) {
219
- const { pascal, kebab, plural = "", repo } = ctx;
220
- const { repoClass, repoFile } = repoMaps(pascal, kebab, repo);
221
- return `/**
222
- * ${pascal} Module
223
- *
224
- * REST module with a flat folder structure.
225
- * Controller delegates to service, service wraps the repository.
226
- *
227
- * Structure:
228
- * ${kebab}.controller.ts — HTTP routes (CRUD)
229
- * ${kebab}.service.ts — Business logic
230
- * ${kebab}.repository.ts — Repository interface
231
- * ${repoFile}.repository.ts — Repository implementation
232
- * dtos/ — Request/response schemas
233
- */
234
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
235
- import { buildRoutes } from '@forinda/kickjs'
236
- import { ${pascal.toUpperCase()}_REPOSITORY } from './${kebab}.repository'
237
- import { ${repoClass} } from './${repoFile}.repository'
238
- import { ${pascal}Controller } from './${kebab}.controller'
239
-
240
- // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
241
- import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })
242
-
243
- export class ${pascal}Module implements AppModule {
244
- register(container: Container): void {
245
- container.registerFactory(${pascal.toUpperCase()}_REPOSITORY, () =>
246
- container.resolve(${repoClass}),
247
- )
248
- }
249
-
250
- routes(): ModuleRoutes {
251
- return {
252
- path: '/${plural}',
253
- router: buildRoutes(${pascal}Controller),
254
- controller: ${pascal}Controller,
255
- }
256
- }
257
- }
258
- `;
259
- }
260
- /** Minimal module index — just controller, no service/repo */
261
- function generateMinimalModuleIndex(ctx) {
262
- const { pascal, kebab, plural = "" } = ctx;
263
- return `import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
264
- import { buildRoutes } from '@forinda/kickjs'
265
- import { ${pascal}Controller } from './${kebab}.controller'
266
-
267
- export class ${pascal}Module implements AppModule {
268
- routes(): ModuleRoutes {
269
- return {
270
- path: '/${plural}',
271
- router: buildRoutes(${pascal}Controller),
272
- controller: ${pascal}Controller,
273
- }
274
- }
275
- }
276
- `;
277
- }
278
- //#endregion
279
- //#region src/generators/templates/controller.ts
280
- /** DDD controller — injects use-cases, nested import paths */
281
- function generateController$1(ctx) {
282
- const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
283
- return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
284
- import { ApiTags } from '@forinda/kickjs-swagger'
285
- import { Create${pascal}UseCase } from '../application/use-cases/create-${kebab}.use-case'
286
- import { Get${pascal}UseCase } from '../application/use-cases/get-${kebab}.use-case'
287
- import { List${pluralPascal}UseCase } from '../application/use-cases/list-${plural}.use-case'
288
- import { Update${pascal}UseCase } from '../application/use-cases/update-${kebab}.use-case'
289
- import { Delete${pascal}UseCase } from '../application/use-cases/delete-${kebab}.use-case'
290
- import { create${pascal}Schema } from '../application/dtos/create-${kebab}.dto'
291
- import { update${pascal}Schema } from '../application/dtos/update-${kebab}.dto'
292
- import { ${pascal.toUpperCase()}_QUERY_CONFIG } from '../constants'
293
-
294
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${pascal}Controller['<method>']>\`
295
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
296
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
297
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
298
-
299
- @Controller()
300
- export class ${pascal}Controller {
301
- @Autowired() private readonly create${pascal}UseCase!: Create${pascal}UseCase
302
- @Autowired() private readonly get${pascal}UseCase!: Get${pascal}UseCase
303
- @Autowired() private readonly list${pluralPascal}UseCase!: List${pluralPascal}UseCase
304
- @Autowired() private readonly update${pascal}UseCase!: Update${pascal}UseCase
305
- @Autowired() private readonly delete${pascal}UseCase!: Delete${pascal}UseCase
306
-
307
- @Get('/')
308
- @ApiTags('${pascal}')
309
- @ApiQueryParams(${pascal.toUpperCase()}_QUERY_CONFIG)
310
- async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
311
- return ctx.paginate(
312
- (parsed) => this.list${pluralPascal}UseCase.execute(parsed),
313
- ${pascal.toUpperCase()}_QUERY_CONFIG,
314
- )
315
- }
316
-
317
- @Get('/:id')
318
- @ApiTags('${pascal}')
319
- async getById(ctx: Ctx<KickRoutes.${pascal}Controller['getById']>) {
320
- const result = await this.get${pascal}UseCase.execute(ctx.params.id)
321
- if (!result) return ctx.notFound('${pascal} not found')
322
- ctx.json(result)
323
- }
324
-
325
- @Post('/', { body: create${pascal}Schema, name: 'Create${pascal}' })
326
- @ApiTags('${pascal}')
327
- async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
328
- const result = await this.create${pascal}UseCase.execute(ctx.body)
329
- ctx.created(result)
330
- }
331
-
332
- @Put('/:id', { body: update${pascal}Schema, name: 'Update${pascal}' })
333
- @ApiTags('${pascal}')
334
- async update(ctx: Ctx<KickRoutes.${pascal}Controller['update']>) {
335
- const result = await this.update${pascal}UseCase.execute(ctx.params.id, ctx.body)
336
- ctx.json(result)
337
- }
338
-
339
- @Delete('/:id')
340
- @ApiTags('${pascal}')
341
- async remove(ctx: Ctx<KickRoutes.${pascal}Controller['remove']>) {
342
- await this.delete${pascal}UseCase.execute(ctx.params.id)
343
- ctx.noContent()
344
- }
345
- }
346
- `;
347
- }
348
- /** REST controller — injects service directly, flat import paths */
349
- function generateRestController(ctx) {
350
- const { pascal, kebab } = ctx;
351
- const camel = pascal.charAt(0).toLowerCase() + pascal.slice(1);
352
- return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
353
- import { ApiTags } from '@forinda/kickjs-swagger'
354
- import { ${pascal}Service } from './${kebab}.service'
355
- import { create${pascal}Schema } from './dtos/create-${kebab}.dto'
356
- import { update${pascal}Schema } from './dtos/update-${kebab}.dto'
357
- import { ${pascal.toUpperCase()}_QUERY_CONFIG } from './${kebab}.constants'
358
-
359
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${pascal}Controller['<method>']>\`
360
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
361
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
362
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
363
-
364
- @Controller()
365
- export class ${pascal}Controller {
366
- @Autowired() private readonly ${camel}Service!: ${pascal}Service
367
-
368
- @Get('/')
369
- @ApiTags('${pascal}')
370
- @ApiQueryParams(${pascal.toUpperCase()}_QUERY_CONFIG)
371
- async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
372
- return ctx.paginate(
373
- (parsed) => this.${camel}Service.findPaginated(parsed),
374
- ${pascal.toUpperCase()}_QUERY_CONFIG,
375
- )
376
- }
377
-
378
- @Get('/:id')
379
- @ApiTags('${pascal}')
380
- async getById(ctx: Ctx<KickRoutes.${pascal}Controller['getById']>) {
381
- const result = await this.${camel}Service.findById(ctx.params.id)
382
- if (!result) return ctx.notFound('${pascal} not found')
383
- ctx.json(result)
384
- }
385
-
386
- @Post('/', { body: create${pascal}Schema, name: 'Create${pascal}' })
387
- @ApiTags('${pascal}')
388
- async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
389
- const result = await this.${camel}Service.create(ctx.body)
390
- ctx.created(result)
391
- }
392
-
393
- @Put('/:id', { body: update${pascal}Schema, name: 'Update${pascal}' })
394
- @ApiTags('${pascal}')
395
- async update(ctx: Ctx<KickRoutes.${pascal}Controller['update']>) {
396
- const result = await this.${camel}Service.update(ctx.params.id, ctx.body)
397
- ctx.json(result)
398
- }
399
-
400
- @Delete('/:id')
401
- @ApiTags('${pascal}')
402
- async remove(ctx: Ctx<KickRoutes.${pascal}Controller['remove']>) {
403
- await this.${camel}Service.delete(ctx.params.id)
404
- ctx.noContent()
405
- }
406
- }
407
- `;
408
- }
409
- //#endregion
410
- //#region src/generators/templates/constants.ts
411
- function generateConstants(ctx) {
412
- const { pascal } = ctx;
413
- return `import type { QueryParamsConfig } from '@forinda/kickjs'
414
-
415
- export const ${pascal.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
416
- filterable: ['name'],
417
- sortable: ['name', 'createdAt'],
418
- searchable: ['name'],
419
- }
420
- `;
421
- }
422
- //#endregion
423
- //#region src/generators/templates/dtos.ts
424
- function generateCreateDTO(ctx) {
425
- const { pascal, kebab } = ctx;
426
- return `import { z } from 'zod'
427
-
428
- /**
429
- * Create ${pascal} DTO — Zod schema for validating POST request bodies.
430
- * This schema is passed to @Post('/', { body: create${pascal}Schema }) for automatic validation.
431
- * It also generates OpenAPI request body docs when SwaggerAdapter is used.
432
- *
433
- * Add more fields as needed. Supported Zod types:
434
- * z.string(), z.number(), z.boolean(), z.enum([...]),
435
- * z.array(), z.object(), .optional(), .default(), .transform()
436
- */
437
- export const create${pascal}Schema = z.object({
438
- name: z.string().min(1, 'Name is required').max(200),
439
- })
440
-
441
- export type Create${pascal}DTO = z.infer<typeof create${pascal}Schema>
442
- `;
443
- }
444
- function generateUpdateDTO(ctx) {
445
- const { pascal, kebab } = ctx;
446
- return `import { z } from 'zod'
447
-
448
- export const update${pascal}Schema = z.object({
449
- name: z.string().min(1).max(200).optional(),
450
- })
451
-
452
- export type Update${pascal}DTO = z.infer<typeof update${pascal}Schema>
453
- `;
454
- }
455
- function generateResponseDTO(ctx) {
456
- const { pascal, kebab } = ctx;
457
- return `export interface ${pascal}ResponseDTO {
458
- id: string
459
- name: string
460
- createdAt: string
461
- updatedAt: string
462
- }
463
- `;
464
- }
465
- //#endregion
466
- //#region src/generators/templates/use-cases.ts
467
- function generateUseCases(ctx) {
468
- const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
469
- return [
470
- {
471
- file: `create-${kebab}.use-case.ts`,
472
- content: `/**
473
- * Create ${pascal} Use Case
474
- *
475
- * Application layer — orchestrates a single business operation.
476
- * Use cases are thin: validate input (via DTO), call domain/repo, return response.
477
- * Keep business rules in the domain service, not here.
478
- */
479
- import { Service, Inject } from '@forinda/kickjs'
480
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
481
- import type { Create${pascal}DTO } from '../dtos/create-${kebab}.dto'
482
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
483
-
484
- @Service()
485
- export class Create${pascal}UseCase {
486
- constructor(
487
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
488
- ) {}
489
-
490
- async execute(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
491
- return this.repo.create(dto)
492
- }
493
- }
494
- `
495
- },
496
- {
497
- file: `get-${kebab}.use-case.ts`,
498
- content: `import { Service, Inject } from '@forinda/kickjs'
499
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
500
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
501
-
502
- @Service()
503
- export class Get${pascal}UseCase {
504
- constructor(
505
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
506
- ) {}
507
-
508
- async execute(id: string): Promise<${pascal}ResponseDTO | null> {
509
- return this.repo.findById(id)
510
- }
511
- }
512
- `
513
- },
514
- {
515
- file: `list-${plural}.use-case.ts`,
516
- content: `import { Service, Inject } from '@forinda/kickjs'
517
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
518
- import type { ParsedQuery } from '@forinda/kickjs'
519
-
520
- @Service()
521
- export class List${pluralPascal}UseCase {
522
- constructor(
523
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
524
- ) {}
525
-
526
- async execute(parsed: ParsedQuery) {
527
- return this.repo.findPaginated(parsed)
528
- }
529
- }
530
- `
531
- },
532
- {
533
- file: `update-${kebab}.use-case.ts`,
534
- content: `import { Service, Inject } from '@forinda/kickjs'
535
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
536
- import type { Update${pascal}DTO } from '../dtos/update-${kebab}.dto'
537
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
538
-
539
- @Service()
540
- export class Update${pascal}UseCase {
541
- constructor(
542
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
543
- ) {}
544
-
545
- async execute(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
546
- return this.repo.update(id, dto)
547
- }
548
- }
549
- `
550
- },
551
- {
552
- file: `delete-${kebab}.use-case.ts`,
553
- content: `import { Service, Inject } from '@forinda/kickjs'
554
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
555
-
556
- @Service()
557
- export class Delete${pascal}UseCase {
558
- constructor(
559
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
560
- ) {}
561
-
562
- async execute(id: string): Promise<void> {
563
- await this.repo.delete(id)
564
- }
565
- }
566
- `
567
- }
568
- ];
569
- }
570
- //#endregion
571
- //#region src/generators/templates/repository.ts
572
- function generateRepositoryInterface(ctx) {
573
- const { pascal, kebab, dtoPrefix = "../../application/dtos" } = ctx;
574
- return `/**
575
- * ${pascal} Repository Interface
576
- *
577
- * Defines the contract for data access.
578
- * The interface declares what operations are available;
579
- * implementations (in-memory, Drizzle, Prisma) fulfill the contract.
580
- *
581
- * To swap implementations, change the factory in the module's register() method.
582
- */
583
- import { createToken } from '@forinda/kickjs'
584
- import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
585
- import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
586
- import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
587
- import type { ParsedQuery } from '@forinda/kickjs'
588
-
589
- export interface I${pascal}Repository {
590
- findById(id: string): Promise<${pascal}ResponseDTO | null>
591
- findAll(): Promise<${pascal}ResponseDTO[]>
592
- findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }>
593
- create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO>
594
- update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO>
595
- delete(id: string): Promise<void>
596
- }
597
-
598
- /**
599
- * Collision-safe DI token bound to \`I${pascal}Repository\`.
600
- * \`container.resolve(${pascal.toUpperCase()}_REPOSITORY)\` and
601
- * \`@Inject(${pascal.toUpperCase()}_REPOSITORY)\` both return the typed
602
- * interface — no manual generic, no \`any\` cast.
603
- */
604
- export const ${pascal.toUpperCase()}_REPOSITORY = createToken<I${pascal}Repository>('app/${kebab}/repository')
605
- `;
606
- }
607
- function generateInMemoryRepository(ctx) {
608
- const { pascal, kebab, repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
609
- return `/**
610
- * In-Memory ${pascal} Repository
611
- *
612
- * Implements the repository interface using a Map.
613
- * Useful for prototyping and testing. Replace with a database implementation
614
- * (Drizzle, Prisma, etc.) for production use.
615
- *
616
- * @Repository() registers this class in the DI container as a singleton.
617
- */
618
- import { randomUUID } from 'node:crypto'
619
- import { Repository, HttpException } from '@forinda/kickjs'
620
- import type { ParsedQuery } from '@forinda/kickjs'
621
- import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
622
- import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
623
- import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
624
- import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
625
-
626
- @Repository()
627
- export class InMemory${pascal}Repository implements I${pascal}Repository {
628
- private store = new Map<string, ${pascal}ResponseDTO>()
629
-
630
- async findById(id: string): Promise<${pascal}ResponseDTO | null> {
631
- return this.store.get(id) ?? null
632
- }
633
-
634
- async findAll(): Promise<${pascal}ResponseDTO[]> {
635
- return Array.from(this.store.values())
636
- }
637
-
638
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
639
- const all = Array.from(this.store.values())
640
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
641
- return { data, total: all.length }
642
- }
643
-
644
- async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
645
- const now = new Date().toISOString()
646
- const entity: ${pascal}ResponseDTO = {
647
- id: randomUUID(),
648
- name: dto.name,
649
- createdAt: now,
650
- updatedAt: now,
651
- }
652
- this.store.set(entity.id, entity)
653
- return entity
654
- }
655
-
656
- async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
657
- const existing = this.store.get(id)
658
- if (!existing) throw HttpException.notFound('${pascal} not found')
659
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
660
- this.store.set(id, updated)
661
- return updated
662
- }
663
-
664
- async delete(id: string): Promise<void> {
665
- if (!this.store.has(id)) throw HttpException.notFound('${pascal} not found')
666
- this.store.delete(id)
667
- }
668
- }
669
- `;
670
- }
671
- function generateCustomRepository(ctx) {
672
- const { pascal, kebab, repoType = "", repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
673
- const repoTypePascal = repoType.charAt(0).toUpperCase() + repoType.slice(1).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
674
- return `/**
675
- * ${repoTypePascal} ${pascal} Repository
676
- *
677
- * Stub implementation for a custom '${repoType}' repository.
678
- * Implements the repository interface using an in-memory Map as a placeholder.
679
- *
680
- * TODO: Replace the in-memory Map with your ${repoType} data-access logic.
681
- * See I${pascal}Repository for the interface contract.
682
- *
683
- * @Repository() registers this class in the DI container as a singleton.
684
- */
685
- import { randomUUID } from 'node:crypto'
686
- import { Repository, HttpException } from '@forinda/kickjs'
687
- import type { ParsedQuery } from '@forinda/kickjs'
688
- import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
689
- import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
690
- import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
691
- import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
692
-
693
- @Repository()
694
- export class ${repoTypePascal}${pascal}Repository implements I${pascal}Repository {
695
- // TODO: Replace with your ${repoType} client/connection
696
- private store = new Map<string, ${pascal}ResponseDTO>()
697
-
698
- async findById(id: string): Promise<${pascal}ResponseDTO | null> {
699
- // TODO: Implement with ${repoType}
700
- return this.store.get(id) ?? null
701
- }
702
-
703
- async findAll(): Promise<${pascal}ResponseDTO[]> {
704
- // TODO: Implement with ${repoType}
705
- return Array.from(this.store.values())
706
- }
707
-
708
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
709
- // TODO: Implement with ${repoType}
710
- const all = Array.from(this.store.values())
711
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
712
- return { data, total: all.length }
713
- }
714
-
715
- async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
716
- // TODO: Implement with ${repoType}
717
- const now = new Date().toISOString()
718
- const entity: ${pascal}ResponseDTO = {
719
- id: randomUUID(),
720
- name: dto.name,
721
- createdAt: now,
722
- updatedAt: now,
723
- }
724
- this.store.set(entity.id, entity)
725
- return entity
726
- }
727
-
728
- async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
729
- // TODO: Implement with ${repoType}
730
- const existing = this.store.get(id)
731
- if (!existing) throw HttpException.notFound('${pascal} not found')
732
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
733
- this.store.set(id, updated)
734
- return updated
735
- }
736
-
737
- async delete(id: string): Promise<void> {
738
- // TODO: Implement with ${repoType}
739
- if (!this.store.has(id)) throw HttpException.notFound('${pascal} not found')
740
- this.store.delete(id)
741
- }
742
- }
743
- `;
744
- }
745
- //#endregion
746
- //#region src/generators/templates/domain.ts
747
- function generateDomainService(ctx) {
748
- const { pascal, kebab } = ctx;
749
- return `/**
750
- * ${pascal} Domain Service
751
- *
752
- * Domain layer — contains business rules that don't belong to a single entity.
753
- * Use this for cross-entity logic, validation rules, and domain invariants.
754
- * Keep it free of HTTP/framework concerns.
755
- */
756
- import { Service, Inject, HttpException } from '@forinda/kickjs'
757
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../repositories/${kebab}.repository'
758
-
759
- @Service()
760
- export class ${pascal}DomainService {
761
- constructor(
762
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
763
- ) {}
764
-
765
- async ensureExists(id: string): Promise<void> {
766
- const entity = await this.repo.findById(id)
767
- if (!entity) {
768
- throw HttpException.notFound('${pascal} not found')
769
- }
770
- }
771
- }
772
- `;
773
- }
774
- function generateEntity(ctx) {
775
- const { pascal, kebab } = ctx;
776
- return `/**
777
- * ${pascal} Entity
778
- *
779
- * Domain layer — the core business object.
780
- * Uses a private constructor with static factory methods (create, reconstitute)
781
- * to enforce invariants. Properties are accessed via getters to maintain encapsulation.
782
- *
783
- * Patterns used:
784
- * - Private constructor: prevents direct instantiation
785
- * - create(): factory for new entities (generates ID, sets timestamps)
786
- * - reconstitute(): factory for rebuilding from persistence (no side effects)
787
- * - changeName(): mutation method that enforces business rules
788
- */
789
- import { ${pascal}Id } from '../value-objects/${kebab}-id.vo'
790
-
791
- interface ${pascal}Props {
792
- id: ${pascal}Id
793
- name: string
794
- createdAt: Date
795
- updatedAt: Date
796
- }
797
-
798
- export class ${pascal} {
799
- private constructor(private props: ${pascal}Props) {}
800
-
801
- static create(params: { name: string }): ${pascal} {
802
- const now = new Date()
803
- return new ${pascal}({
804
- id: ${pascal}Id.create(),
805
- name: params.name,
806
- createdAt: now,
807
- updatedAt: now,
808
- })
809
- }
810
-
811
- static reconstitute(props: ${pascal}Props): ${pascal} {
812
- return new ${pascal}(props)
813
- }
814
-
815
- get id(): ${pascal}Id {
816
- return this.props.id
817
- }
818
- get name(): string {
819
- return this.props.name
820
- }
821
- get createdAt(): Date {
822
- return this.props.createdAt
823
- }
824
- get updatedAt(): Date {
825
- return this.props.updatedAt
826
- }
827
-
828
- changeName(name: string): void {
829
- if (!name || name.trim().length === 0) {
830
- throw new Error('Name cannot be empty')
831
- }
832
- this.props.name = name.trim()
833
- this.props.updatedAt = new Date()
834
- }
835
-
836
- toJSON() {
837
- return {
838
- id: this.props.id.toString(),
839
- name: this.props.name,
840
- createdAt: this.props.createdAt.toISOString(),
841
- updatedAt: this.props.updatedAt.toISOString(),
842
- }
843
- }
844
- }
845
- `;
846
- }
847
- function generateValueObject(ctx) {
848
- const { pascal, kebab } = ctx;
849
- return `/**
850
- * ${pascal} ID Value Object
851
- *
852
- * Domain layer — wraps a primitive ID with type safety and validation.
853
- * Value objects are immutable and compared by value, not reference.
854
- *
855
- * ${pascal}Id.create() — generate a new UUID
856
- * ${pascal}Id.from(id) — wrap an existing ID string (validates non-empty)
857
- * id.equals(other) — compare two IDs by value
858
- */
859
- import { randomUUID } from 'node:crypto'
860
-
861
- export class ${pascal}Id {
862
- private constructor(private readonly value: string) {}
863
-
864
- static create(): ${pascal}Id {
865
- return new ${pascal}Id(randomUUID())
866
- }
867
-
868
- static from(id: string): ${pascal}Id {
869
- if (!id || id.trim().length === 0) {
870
- throw new Error('${pascal}Id cannot be empty')
871
- }
872
- return new ${pascal}Id(id)
873
- }
874
-
875
- toString(): string {
876
- return this.value
877
- }
878
-
879
- equals(other: ${pascal}Id): boolean {
880
- return this.value === other.value
881
- }
882
- }
883
- `;
884
- }
885
- //#endregion
886
- //#region src/generators/templates/tests.ts
887
- function generateControllerTest(ctx) {
888
- const { pascal, kebab, plural = "" } = ctx;
889
- return `import { describe, it, expect, beforeEach } from 'vitest'
890
- import { Container } from '@forinda/kickjs'
891
-
892
- describe('${pascal}Controller', () => {
893
- beforeEach(() => {
894
- Container.reset()
895
- })
896
-
897
- it('should be defined', () => {
898
- expect(true).toBe(true)
899
- })
900
-
901
- describe('POST /${plural}', () => {
902
- it('should create a new ${kebab}', async () => {
903
- // TODO: Set up test module, call create endpoint, assert 201
904
- expect(true).toBe(true)
905
- })
906
- })
907
-
908
- describe('GET /${plural}', () => {
909
- it('should return paginated ${plural}', async () => {
910
- // TODO: Set up test module, call list endpoint, assert { data, meta }
911
- expect(true).toBe(true)
912
- })
913
- })
914
-
915
- describe('GET /${plural}/:id', () => {
916
- it('should return a ${kebab} by id', async () => {
917
- // TODO: Create a ${kebab}, then fetch by id, assert match
918
- expect(true).toBe(true)
919
- })
920
-
921
- it('should return 404 for non-existent ${kebab}', async () => {
922
- // TODO: Fetch non-existent id, assert 404
923
- expect(true).toBe(true)
924
- })
925
- })
926
-
927
- describe('PUT /${plural}/:id', () => {
928
- it('should update an existing ${kebab}', async () => {
929
- // TODO: Create, update, assert changes
930
- expect(true).toBe(true)
931
- })
932
- })
933
-
934
- describe('DELETE /${plural}/:id', () => {
935
- it('should delete a ${kebab}', async () => {
936
- // TODO: Create, delete, assert gone
937
- expect(true).toBe(true)
938
- })
939
- })
940
- })
941
- `;
942
- }
943
- function generateRepositoryTest(ctx) {
944
- const { pascal, kebab, plural = "", repoPrefix = `../infrastructure/repositories/in-memory-${kebab}.repository` } = ctx;
945
- return `import { describe, it, expect, beforeEach } from 'vitest'
946
- import { InMemory${pascal}Repository } from '${repoPrefix}'
947
-
948
- describe('InMemory${pascal}Repository', () => {
949
- let repo: InMemory${pascal}Repository
950
-
951
- beforeEach(() => {
952
- repo = new InMemory${pascal}Repository()
953
- })
954
-
955
- it('should create and retrieve a ${kebab}', async () => {
956
- const created = await repo.create({ name: 'Test ${pascal}' })
957
- expect(created).toBeDefined()
958
- expect(created.name).toBe('Test ${pascal}')
959
- expect(created.id).toBeDefined()
960
-
961
- const found = await repo.findById(created.id)
962
- expect(found).toEqual(created)
963
- })
964
-
965
- it('should return null for non-existent id', async () => {
966
- const found = await repo.findById('non-existent')
967
- expect(found).toBeNull()
968
- })
969
-
970
- it('should list all ${plural}', async () => {
971
- await repo.create({ name: '${pascal} 1' })
972
- await repo.create({ name: '${pascal} 2' })
973
-
974
- const all = await repo.findAll()
975
- expect(all).toHaveLength(2)
976
- })
977
-
978
- it('should return paginated results', async () => {
979
- await repo.create({ name: '${pascal} 1' })
980
- await repo.create({ name: '${pascal} 2' })
981
- await repo.create({ name: '${pascal} 3' })
982
-
983
- const result = await repo.findPaginated({
984
- filters: [],
985
- sort: [],
986
- search: '',
987
- pagination: { page: 1, limit: 2, offset: 0 },
988
- })
989
-
990
- expect(result.data).toHaveLength(2)
991
- expect(result.total).toBe(3)
992
- })
993
-
994
- it('should update a ${kebab}', async () => {
995
- const created = await repo.create({ name: 'Original' })
996
- const updated = await repo.update(created.id, { name: 'Updated' })
997
- expect(updated.name).toBe('Updated')
998
- })
999
-
1000
- it('should delete a ${kebab}', async () => {
1001
- const created = await repo.create({ name: 'To Delete' })
1002
- await repo.delete(created.id)
1003
- const found = await repo.findById(created.id)
1004
- expect(found).toBeNull()
1005
- })
1006
- })
1007
- `;
1008
- }
1009
- //#endregion
1010
- //#region src/generators/templates/rest-service.ts
1011
- /** REST service — wraps repository with CRUD methods, replaces use-cases for flat pattern */
1012
- function generateRestService(ctx) {
1013
- const { pascal, kebab } = ctx;
1014
- return `import { Service, Inject, HttpException } from '@forinda/kickjs'
1015
- import type { ParsedQuery } from '@forinda/kickjs'
1016
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from './${kebab}.repository'
1017
- import type { ${pascal}ResponseDTO } from './dtos/${kebab}-response.dto'
1018
- import type { Create${pascal}DTO } from './dtos/create-${kebab}.dto'
1019
- import type { Update${pascal}DTO } from './dtos/update-${kebab}.dto'
1020
-
1021
- @Service()
1022
- export class ${pascal}Service {
1023
- constructor(
1024
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
1025
- ) {}
1026
-
1027
- async findById(id: string): Promise<${pascal}ResponseDTO | null> {
1028
- return this.repo.findById(id)
1029
- }
1030
-
1031
- async findAll(): Promise<${pascal}ResponseDTO[]> {
1032
- return this.repo.findAll()
1033
- }
1034
-
1035
- async findPaginated(parsed: ParsedQuery) {
1036
- return this.repo.findPaginated(parsed)
1037
- }
1038
-
1039
- async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
1040
- return this.repo.create(dto)
1041
- }
1042
-
1043
- async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
1044
- return this.repo.update(id, dto)
1045
- }
1046
-
1047
- async delete(id: string): Promise<void> {
1048
- await this.repo.delete(id)
1049
- }
1050
- }
1051
- `;
1052
- }
1053
- /** REST constants — query config for flat pattern */
1054
- function generateRestConstants(ctx) {
1055
- const { pascal } = ctx;
1056
- return `import type { QueryFieldConfig } from '@forinda/kickjs'
1057
-
1058
- export const ${pascal.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
1059
- filterable: ['name'],
1060
- sortable: ['name', 'createdAt'],
1061
- searchable: ['name'],
1062
- }
1063
- `;
1064
- }
1065
- //#endregion
1066
- //#region src/generators/templates/cqrs.ts
1067
- /** CQRS module index — commands, queries, events, WebSocket + queue integration */
1068
- function generateCqrsModuleIndex(ctx) {
1069
- const { pascal, kebab, plural = "", repo } = ctx;
1070
- const repoClassMap = {
1071
- inmemory: `InMemory${pascal}Repository`,
1072
- drizzle: `Drizzle${pascal}Repository`,
1073
- prisma: `Prisma${pascal}Repository`
1074
- };
1075
- const repoFileMap = {
1076
- inmemory: `in-memory-${kebab}`,
1077
- drizzle: `drizzle-${kebab}`,
1078
- prisma: `prisma-${kebab}`
1079
- };
1080
- const repoClass = repoClassMap[repo] ?? repoClassMap.inmemory;
1081
- const repoFile = repoFileMap[repo] ?? repoFileMap.inmemory;
1082
- return `/**
1083
- * ${pascal} Module — CQRS Pattern
1084
- *
1085
- * Separates read (queries) and write (commands) operations.
1086
- * Events are emitted after state changes and can be handled via
1087
- * WebSocket broadcasts, queue jobs, or ETL pipelines.
1088
- *
1089
- * Structure:
1090
- * commands/ — Write operations (create, update, delete)
1091
- * queries/ — Read operations (get, list)
1092
- * events/ — Domain events + handlers (WS broadcast, queue dispatch)
1093
- * dtos/ — Request/response schemas
1094
- */
1095
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1096
- import { buildRoutes } from '@forinda/kickjs'
1097
- import { ${pascal.toUpperCase()}_REPOSITORY } from './${kebab}.repository'
1098
- import { ${repoClass} } from './${repoFile}.repository'
1099
- import { ${pascal}Controller } from './${kebab}.controller'
1100
-
1101
- // Eagerly load decorated classes
1102
- import.meta.glob(
1103
- [
1104
- './commands/**/*.ts',
1105
- './queries/**/*.ts',
1106
- './events/**/*.ts',
1107
- '!./**/*.test.ts',
1108
- ],
1109
- { eager: true },
1110
- )
1111
-
1112
- export class ${pascal}Module implements AppModule {
1113
- register(container: Container): void {
1114
- container.registerFactory(${pascal.toUpperCase()}_REPOSITORY, () =>
1115
- container.resolve(${repoClass}),
1116
- )
1117
- }
1118
-
1119
- routes(): ModuleRoutes {
1120
- return {
1121
- path: '/${plural}',
1122
- router: buildRoutes(${pascal}Controller),
1123
- controller: ${pascal}Controller,
1124
- }
1125
- }
1126
- }
1127
- `;
1128
- }
1129
- /** CQRS controller — dispatches to command/query handlers */
1130
- function generateCqrsController(ctx) {
1131
- const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
1132
- return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
1133
- import { ApiTags } from '@forinda/kickjs-swagger'
1134
- import { Create${pascal}Command } from './commands/create-${kebab}.command'
1135
- import { Update${pascal}Command } from './commands/update-${kebab}.command'
1136
- import { Delete${pascal}Command } from './commands/delete-${kebab}.command'
1137
- import { Get${pascal}Query } from './queries/get-${kebab}.query'
1138
- import { List${pluralPascal}Query } from './queries/list-${plural}.query'
1139
- import { create${pascal}Schema } from './dtos/create-${kebab}.dto'
1140
- import { update${pascal}Schema } from './dtos/update-${kebab}.dto'
1141
- import { ${pascal.toUpperCase()}_QUERY_CONFIG } from './${kebab}.constants'
1142
-
1143
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${pascal}Controller['<method>']>\`
1144
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
1145
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
1146
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
1147
-
1148
- @Controller()
1149
- export class ${pascal}Controller {
1150
- @Autowired() private readonly create${pascal}Command!: Create${pascal}Command
1151
- @Autowired() private readonly update${pascal}Command!: Update${pascal}Command
1152
- @Autowired() private readonly delete${pascal}Command!: Delete${pascal}Command
1153
- @Autowired() private readonly get${pascal}Query!: Get${pascal}Query
1154
- @Autowired() private readonly list${pluralPascal}Query!: List${pluralPascal}Query
1155
-
1156
- @Get('/')
1157
- @ApiTags('${pascal}')
1158
- @ApiQueryParams(${pascal.toUpperCase()}_QUERY_CONFIG)
1159
- async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
1160
- return ctx.paginate(
1161
- (parsed) => this.list${pluralPascal}Query.execute(parsed),
1162
- ${pascal.toUpperCase()}_QUERY_CONFIG,
1163
- )
1164
- }
1165
-
1166
- @Get('/:id')
1167
- @ApiTags('${pascal}')
1168
- async getById(ctx: Ctx<KickRoutes.${pascal}Controller['getById']>) {
1169
- const result = await this.get${pascal}Query.execute(ctx.params.id)
1170
- if (!result) return ctx.notFound('${pascal} not found')
1171
- ctx.json(result)
1172
- }
1173
-
1174
- @Post('/', { body: create${pascal}Schema, name: 'Create${pascal}' })
1175
- @ApiTags('${pascal}')
1176
- async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
1177
- const result = await this.create${pascal}Command.execute(ctx.body)
1178
- ctx.created(result)
1179
- }
1180
-
1181
- @Put('/:id', { body: update${pascal}Schema, name: 'Update${pascal}' })
1182
- @ApiTags('${pascal}')
1183
- async update(ctx: Ctx<KickRoutes.${pascal}Controller['update']>) {
1184
- const result = await this.update${pascal}Command.execute(ctx.params.id, ctx.body)
1185
- ctx.json(result)
1186
- }
1187
-
1188
- @Delete('/:id')
1189
- @ApiTags('${pascal}')
1190
- async remove(ctx: Ctx<KickRoutes.${pascal}Controller['remove']>) {
1191
- await this.delete${pascal}Command.execute(ctx.params.id)
1192
- ctx.noContent()
1193
- }
1194
- }
1195
- `;
1196
- }
1197
- /** CQRS commands — write operations that emit events */
1198
- function generateCqrsCommands(ctx) {
1199
- const { pascal, kebab } = ctx;
1200
- return [
1201
- {
1202
- file: `create-${kebab}.command.ts`,
1203
- content: `import { Service, Inject } from '@forinda/kickjs'
1204
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
1205
- import type { Create${pascal}DTO } from '../dtos/create-${kebab}.dto'
1206
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
1207
- import { ${pascal}Events } from '../events/${kebab}.events'
1208
-
1209
- @Service()
1210
- export class Create${pascal}Command {
1211
- constructor(
1212
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
1213
- @Inject(${pascal}Events) private readonly events: ${pascal}Events,
1214
- ) {}
1215
-
1216
- async execute(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
1217
- const result = await this.repo.create(dto)
1218
- this.events.emit('${kebab}.created', result)
1219
- return result
1220
- }
1221
- }
1222
- `
1223
- },
1224
- {
1225
- file: `update-${kebab}.command.ts`,
1226
- content: `import { Service, Inject } from '@forinda/kickjs'
1227
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
1228
- import type { Update${pascal}DTO } from '../dtos/update-${kebab}.dto'
1229
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
1230
- import { ${pascal}Events } from '../events/${kebab}.events'
1231
-
1232
- @Service()
1233
- export class Update${pascal}Command {
1234
- constructor(
1235
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
1236
- @Inject(${pascal}Events) private readonly events: ${pascal}Events,
1237
- ) {}
1238
-
1239
- async execute(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
1240
- const result = await this.repo.update(id, dto)
1241
- this.events.emit('${kebab}.updated', result)
1242
- return result
1243
- }
1244
- }
1245
- `
1246
- },
1247
- {
1248
- file: `delete-${kebab}.command.ts`,
1249
- content: `import { Service, Inject } from '@forinda/kickjs'
1250
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
1251
- import { ${pascal}Events } from '../events/${kebab}.events'
1252
-
1253
- @Service()
1254
- export class Delete${pascal}Command {
1255
- constructor(
1256
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
1257
- @Inject(${pascal}Events) private readonly events: ${pascal}Events,
1258
- ) {}
1259
-
1260
- async execute(id: string): Promise<void> {
1261
- await this.repo.delete(id)
1262
- this.events.emit('${kebab}.deleted', { id })
1263
- }
1264
- }
1265
- `
1266
- }
1267
- ];
1268
- }
1269
- /** CQRS queries — read operations */
1270
- function generateCqrsQueries(ctx) {
1271
- const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
1272
- return [{
1273
- file: `get-${kebab}.query.ts`,
1274
- content: `import { Service, Inject } from '@forinda/kickjs'
1275
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
1276
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
1277
-
1278
- @Service()
1279
- export class Get${pascal}Query {
1280
- constructor(
1281
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
1282
- ) {}
1283
-
1284
- async execute(id: string): Promise<${pascal}ResponseDTO | null> {
1285
- return this.repo.findById(id)
1286
- }
1287
- }
1288
- `
1289
- }, {
1290
- file: `list-${plural}.query.ts`,
1291
- content: `import { Service, Inject } from '@forinda/kickjs'
1292
- import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
1293
- import type { ParsedQuery } from '@forinda/kickjs'
1294
-
1295
- @Service()
1296
- export class List${pluralPascal}Query {
1297
- constructor(
1298
- @Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
1299
- ) {}
1300
-
1301
- async execute(parsed: ParsedQuery) {
1302
- return this.repo.findPaginated(parsed)
1303
- }
1304
- }
1305
- `
1306
- }];
1307
- }
1308
- /** CQRS events — domain event emitter + handler with WS/queue integration */
1309
- function generateCqrsEvents(ctx) {
1310
- const { pascal, kebab } = ctx;
1311
- return [{
1312
- file: `${kebab}.events.ts`,
1313
- content: `import { Service } from '@forinda/kickjs'
1314
- import { EventEmitter } from 'node:events'
1315
- import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
1316
-
1317
- /**
1318
- * ${pascal} domain event types.
1319
- *
1320
- * These events are emitted by commands after state changes.
1321
- * Subscribe to them in event handlers for side effects:
1322
- * - WebSocket broadcasts (real-time UI updates)
1323
- * - Queue jobs (async processing, ETL pipelines)
1324
- * - Audit logging
1325
- * - Cache invalidation
1326
- */
1327
- export interface ${pascal}EventMap {
1328
- '${kebab}.created': ${pascal}ResponseDTO
1329
- '${kebab}.updated': ${pascal}ResponseDTO
1330
- '${kebab}.deleted': { id: string }
1331
- }
1332
-
1333
- @Service()
1334
- export class ${pascal}Events {
1335
- private emitter = new EventEmitter()
1336
-
1337
- emit<K extends keyof ${pascal}EventMap>(event: K, data: ${pascal}EventMap[K]): void {
1338
- this.emitter.emit(event, data)
1339
- }
1340
-
1341
- on<K extends keyof ${pascal}EventMap>(event: K, handler: (data: ${pascal}EventMap[K]) => void): void {
1342
- this.emitter.on(event, handler)
1343
- }
1344
-
1345
- off<K extends keyof ${pascal}EventMap>(event: K, handler: (data: ${pascal}EventMap[K]) => void): void {
1346
- this.emitter.off(event, handler)
1347
- }
1348
- }
1349
- `
1350
- }, {
1351
- file: `on-${kebab}-change.handler.ts`,
1352
- content: `import { Service, Autowired } from '@forinda/kickjs'
1353
- import { ${pascal}Events } from './${kebab}.events'
1354
-
1355
- /**
1356
- * ${pascal} Change Event Handler
1357
- *
1358
- * Reacts to domain events emitted by commands.
1359
- * Wire up side effects here:
1360
- *
1361
- * 1. WebSocket broadcast — notify connected clients in real-time
1362
- * import { WsGateway } from '@forinda/kickjs-ws'
1363
- * this.ws.broadcast('${kebab}-channel', { event, data })
1364
- *
1365
- * 2. Queue dispatch — offload heavy processing to background workers
1366
- * import { QueueService } from '@forinda/kickjs-queue'
1367
- * this.queue.add('${kebab}-etl', { action: event, payload: data })
1368
- *
1369
- * 3. ETL pipeline — transform and load data to external systems
1370
- * await this.etlPipeline.process(data)
1371
- */
1372
- @Service()
1373
- export class On${pascal}ChangeHandler {
1374
- @Autowired() private events!: ${pascal}Events
1375
-
1376
- // Uncomment to inject WebSocket and Queue services:
1377
- // @Autowired() private ws!: WsGateway
1378
- // @Autowired() private queue!: QueueService
1379
-
1380
- onInit(): void {
1381
- this.events.on('${kebab}.created', (data) => {
1382
- console.log('[${pascal}] Created:', data.id)
1383
- // TODO: Broadcast via WebSocket
1384
- // this.ws.broadcast('${kebab}-channel', { event: '${kebab}.created', data })
1385
- // TODO: Dispatch to queue for async processing / ETL
1386
- // this.queue.add('${kebab}-etl', { action: 'create', payload: data })
1387
- })
1388
-
1389
- this.events.on('${kebab}.updated', (data) => {
1390
- console.log('[${pascal}] Updated:', data.id)
1391
- // TODO: Broadcast via WebSocket
1392
- // this.ws.broadcast('${kebab}-channel', { event: '${kebab}.updated', data })
1393
- })
1394
-
1395
- this.events.on('${kebab}.deleted', (data) => {
1396
- console.log('[${pascal}] Deleted:', data.id)
1397
- // TODO: Broadcast via WebSocket
1398
- // this.ws.broadcast('${kebab}-channel', { event: '${kebab}.deleted', data })
1399
- })
1400
- }
1401
- }
1402
- `
1403
- }];
1404
- }
1405
- //#endregion
1406
- //#region src/generators/templates/drizzle/index.ts
1407
- function generateDrizzleRepository(ctx) {
1408
- const { pascal, kebab, repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
1409
- return `/**
1410
- * Drizzle ${pascal} Repository
1411
- *
1412
- * Implements the repository interface using Drizzle ORM.
1413
- * Uses buildFromColumns() with Column objects for type-safe query building.
1414
- *
1415
- * TODO: Update the schema import to match your Drizzle schema file.
1416
- * TODO: Replace DRIZZLE_DB injection token with your actual database token.
1417
- *
1418
- * @Repository() registers this class in the DI container as a singleton.
1419
- */
1420
- import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
1421
- import { Repository, HttpException, Inject } from '@forinda/kickjs'
1422
- import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
1423
- import type { ParsedQuery } from '@forinda/kickjs'
1424
- import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
1425
- import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
1426
- import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
1427
- import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
1428
- import { ${pascal.toUpperCase()}_QUERY_CONFIG } from '../../constants'
1429
-
1430
- // TODO: Import your Drizzle schema table — e.g.:
1431
- // import { ${kebab}s } from '@/db/schema'
1432
-
1433
- const queryAdapter = new DrizzleQueryAdapter({
1434
- eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
1435
- })
1436
-
1437
- @Repository()
1438
- export class Drizzle${pascal}Repository implements I${pascal}Repository {
1439
- constructor(@Inject(DRIZZLE_DB) private db: any) {}
1440
-
1441
- async findById(id: string): Promise<${pascal}ResponseDTO | null> {
1442
- // TODO: Implement with Drizzle
1443
- // const row = this.db.select().from(${kebab}s).where(eq(${kebab}s.id, id)).get()
1444
- // return row ?? null
1445
- throw new Error('Drizzle ${pascal} repository not yet implemented — update schema imports and queries')
1446
- }
1447
-
1448
- async findAll(): Promise<${pascal}ResponseDTO[]> {
1449
- // TODO: Implement with Drizzle
1450
- // return this.db.select().from(${kebab}s).all()
1451
- throw new Error('Drizzle ${pascal} repository not yet implemented')
1452
- }
1453
-
1454
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
1455
- // TODO: Use buildFromColumns() with your query config for type-safe filtering
1456
- // const query = queryAdapter.buildFromColumns(parsed, ${pascal.toUpperCase()}_QUERY_CONFIG)
1457
- //
1458
- // const data = this.db
1459
- // .select().from(${kebab}s).$dynamic()
1460
- // .where(query.where).orderBy(...query.orderBy)
1461
- // .limit(query.limit).offset(query.offset).all()
1462
- //
1463
- // const totalResult = this.db
1464
- // .select({ count: count() }).from(${kebab}s)
1465
- // .$dynamic().where(query.where).get()
1466
- //
1467
- // return { data, total: totalResult?.count ?? 0 }
1468
- throw new Error('Drizzle ${pascal} repository not yet implemented')
1469
- }
1470
-
1471
- async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
1472
- // TODO: Implement with Drizzle
1473
- // return this.db.insert(${kebab}s).values(dto).returning().get()
1474
- throw new Error('Drizzle ${pascal} repository not yet implemented')
1475
- }
1476
-
1477
- async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
1478
- // TODO: Implement with Drizzle
1479
- // const row = this.db.update(${kebab}s).set(dto).where(eq(${kebab}s.id, id)).returning().get()
1480
- // if (!row) throw HttpException.notFound('${pascal} not found')
1481
- // return row
1482
- throw new Error('Drizzle ${pascal} repository not yet implemented')
1483
- }
1484
-
1485
- async delete(id: string): Promise<void> {
1486
- // TODO: Implement with Drizzle
1487
- // this.db.delete(${kebab}s).where(eq(${kebab}s.id, id)).run()
1488
- throw new Error('Drizzle ${pascal} repository not yet implemented')
1489
- }
1490
- }
1491
- `;
1492
- }
1493
- function generateDrizzleConstants(ctx) {
1494
- const { pascal, kebab } = ctx;
1495
- return `import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
1496
- // TODO: Import your schema table and reference actual columns for type safety
1497
- // import { ${kebab}s } from '@/db/schema'
1498
-
1499
- export const ${pascal.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
1500
- columns: {
1501
- // Replace with actual Drizzle Column references for type-safe filtering:
1502
- // name: ${kebab}s.name,
1503
- // status: ${kebab}s.status,
1504
- },
1505
- sortable: {
1506
- // name: ${kebab}s.name,
1507
- // createdAt: ${kebab}s.createdAt,
1508
- },
1509
- searchColumns: [
1510
- // ${kebab}s.name,
1511
- ],
1512
- }
1513
- `;
1514
- }
1515
- //#endregion
1516
- //#region src/generators/templates/prisma/index.ts
1517
- function generatePrismaRepository(ctx) {
1518
- const { pascal, kebab, repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
1519
- const camel = kebab.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1520
- return `/**
1521
- * Prisma ${pascal} Repository
1522
- *
1523
- * Implements the repository interface using Prisma Client.
1524
- * Requires a PrismaClient instance injected via the DI container.
1525
- *
1526
- * Ensure your Prisma schema has a '${pascal}' model defined.
1527
- *
1528
- * For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
1529
- * @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
1530
- *
1531
- * @Repository() registers this class in the DI container as a singleton.
1532
- */
1533
- import { Repository, HttpException, Inject } from '@forinda/kickjs'
1534
- import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
1535
- import type { ParsedQuery } from '@forinda/kickjs'
1536
- import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
1537
- import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
1538
- import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
1539
- import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
1540
-
1541
- @Repository()
1542
- export class Prisma${pascal}Repository implements I${pascal}Repository {
1543
- @Inject(PRISMA_CLIENT) private prisma!: { ${camel}: PrismaModelDelegate }
1544
-
1545
- async findById(id: string): Promise<${pascal}ResponseDTO | null> {
1546
- return this.prisma.${camel}.findUnique({ where: { id } }) as Promise<${pascal}ResponseDTO | null>
1547
- }
1548
-
1549
- async findAll(): Promise<${pascal}ResponseDTO[]> {
1550
- return this.prisma.${camel}.findMany() as Promise<${pascal}ResponseDTO[]>
1551
- }
1552
-
1553
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
1554
- const [data, total] = await Promise.all([
1555
- this.prisma.${camel}.findMany({
1556
- skip: parsed.pagination.offset,
1557
- take: parsed.pagination.limit,
1558
- }) as Promise<${pascal}ResponseDTO[]>,
1559
- this.prisma.${camel}.count(),
1560
- ])
1561
- return { data, total }
1562
- }
1563
-
1564
- async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
1565
- return this.prisma.${camel}.create({ data: dto as Record<string, unknown> }) as Promise<${pascal}ResponseDTO>
1566
- }
1567
-
1568
- async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
1569
- const existing = await this.prisma.${camel}.findUnique({ where: { id } })
1570
- if (!existing) throw HttpException.notFound('${pascal} not found')
1571
- return this.prisma.${camel}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${pascal}ResponseDTO>
1572
- }
1573
-
1574
- async delete(id: string): Promise<void> {
1575
- await this.prisma.${camel}.deleteMany({ where: { id } })
1576
- }
1577
- }
1578
- `;
1579
- }
1580
- //#endregion
1581
- //#region src/generators/templates/project-app.ts
1582
- /**
1583
- * Generate src/index.ts entry file with template-specific bootstrap.
1584
- *
1585
- * All templates export the app for the Vite plugin (dev mode).
1586
- * In production, bootstrap() auto-starts the HTTP server when
1587
- * `globalThis.__kickjs_httpServer` is not set.
1588
- */
1589
- function generateEntryFile(name, template, version, packages = []) {
1590
- switch (template) {
1591
- case "cqrs": {
1592
- const cqrsImports = [];
1593
- const cqrsAdapters = [];
1594
- if (packages.includes("devtools")) {
1595
- cqrsImports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`);
1596
- cqrsAdapters.push(` DevToolsAdapter(),`);
1597
- }
1598
- if (packages.includes("swagger")) {
1599
- cqrsImports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`);
1600
- cqrsAdapters.push(` SwaggerAdapter({\n info: { title: '${name}', version: '${version}' },\n }),`);
1601
- }
1602
- return `import 'reflect-metadata'
1603
- // Side-effect import — registers the extended env schema with kickjs
1604
- // **before** any controller / service / @Value gets resolved. Without
1605
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
1606
- // cached schema would still be the base shape. See guide/configuration.
1607
- import './config'
1608
- import { bootstrap } from '@forinda/kickjs'
1609
- // import { WsAdapter } from '@forinda/kickjs-ws'
1610
- // import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
1611
- ${cqrsImports.length ? cqrsImports.join("\n") + "\n" : ""}import { modules } from './modules'
1612
-
1613
- // Export the app for the Vite plugin (dev mode)
1614
- export const app = await bootstrap({
1615
- modules,${cqrsImports.length ? `\n adapters: [\n${cqrsAdapters.join("\n")}\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],` : `\n adapters: [\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],`}
1616
- })
1617
- `;
1618
- }
1619
- case "minimal": {
1620
- const imports = [];
1621
- const adapters = [];
1622
- if (packages.includes("swagger")) {
1623
- imports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`);
1624
- adapters.push(` SwaggerAdapter({ info: { title: '${name}', version: '${version}' } }),`);
1625
- }
1626
- if (packages.includes("devtools")) {
1627
- imports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`);
1628
- adapters.push(` DevToolsAdapter(),`);
1629
- }
1630
- return `import 'reflect-metadata'
1631
- // Side-effect import — registers the extended env schema with kickjs
1632
- // **before** any controller / service / @Value gets resolved. Without
1633
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
1634
- // cached schema would still be the base shape. See guide/configuration.
1635
- import './config'
1636
- import { bootstrap } from '@forinda/kickjs'
1637
- ${imports.length ? imports.join("\n") + "\n" : ""}import { modules } from './modules'
1638
-
1639
- // Export the app for the Vite plugin (dev mode)
1640
- export const app = await bootstrap({ modules${adapters.length ? `,\n adapters: [\n${adapters.join("\n")}\n ]` : ""} })
1641
- `;
1642
- }
1643
- default: {
1644
- const restImports = [];
1645
- const restAdapters = [];
1646
- if (packages.includes("devtools")) {
1647
- restImports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`);
1648
- restAdapters.push(` DevToolsAdapter(),`);
1649
- }
1650
- if (packages.includes("swagger")) {
1651
- restImports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`);
1652
- restAdapters.push(` SwaggerAdapter({\n info: { title: '${name}', version: '${version}' },\n }),`);
1653
- }
1654
- return `import 'reflect-metadata'
1655
- // Side-effect import — registers the extended env schema with kickjs
1656
- // **before** any controller / service / @Value gets resolved. Without
1657
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
1658
- // cached schema would still be the base shape. See guide/configuration.
1659
- import './config'
1660
- import express from 'express'
1661
- import {
1662
- bootstrap,
1663
- requestId,
1664
- requestLogger,
1665
- helmet,
1666
- cors,
1667
- } from '@forinda/kickjs'
1668
- ${restImports.length ? restImports.join("\n") + "\n" : ""}import { modules } from './modules'
1669
-
1670
- // Export the app for the Vite plugin (dev mode)
1671
- export const app = await bootstrap({
1672
- modules,${restAdapters.length ? `\n adapters: [\n${restAdapters.join("\n")}\n ],` : ""}
1673
- middleware: [
1674
- helmet(),
1675
- cors({ origin: '*' }),
1676
- requestId(),
1677
- requestLogger(),
1678
- express.json(),
1679
- ],
1680
- })
1681
- `;
1682
- }
1683
- }
1684
- }
1685
- /** Generate src/modules/index.ts module registry */
1686
- function generateModulesIndex() {
1687
- return `import type { AppModuleClass } from '@forinda/kickjs'
1688
- import { HelloModule } from './hello/hello.module'
1689
-
1690
- // Remove HelloModule and run: kick g module <name>
1691
- export const modules: AppModuleClass[] = [HelloModule]
1692
- `;
1693
- }
1694
- /**
1695
- * Generate `src/config/index.ts` — the project's typed env schema.
1696
- *
1697
- * Default-exports a `defineEnv(...)` schema so `kick typegen` can
1698
- * infer it into the global `KickEnv` registry, and *also* calls
1699
- * `loadEnv(envSchema)` as a module-load side effect so `ConfigService`
1700
- * and `@Value()` see the extended shape from the very first DI
1701
- * resolution. The companion `src/index.ts` template adds
1702
- * `import './config'` immediately after `reflect-metadata` so the
1703
- * registration runs before `bootstrap()` constructs anything.
1704
- *
1705
- * After typegen runs:
1706
- *
1707
- * @Value('DATABASE_URL') private url!: Env<'DATABASE_URL'>
1708
- * process.env.DATABASE_URL // typed as string
1709
- *
1710
- * Both autocomplete and type-check at compile time.
1711
- */
1712
- function generateEnvFile() {
1713
- return `import { defineEnv, loadEnv } from '@forinda/kickjs/config'
1714
- import { z } from 'zod'
1715
-
1716
- /**
1717
- * Project environment schema.
1718
- *
1719
- * Extend the base schema with your application's variables. The
1720
- * default export is the contract \`kick typegen\` reads to populate
1721
- * the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
1722
- * autocomplete and \`process.env.FOO\` typed.
1723
- *
1724
- * @example
1725
- * DATABASE_URL: z.string().url(),
1726
- * JWT_SECRET: z.string().min(32),
1727
- * REDIS_URL: z.string().url().optional(),
1728
- */
1729
- const envSchema = defineEnv((base) =>
1730
- base.extend({
1731
- // DATABASE_URL: z.string().url(),
1732
- }),
1733
- )
1734
-
1735
- /**
1736
- * IMPORTANT — side effect: register the schema with kickjs's env cache
1737
- * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
1738
- * this cache, and they will fall back to the base schema (or undefined)
1739
- * if no extended schema has been registered before they're resolved.
1740
- *
1741
- * As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
1742
- * top — before \`bootstrap()\` runs — every controller and service in the
1743
- * app sees the typed extended values.
1744
- */
1745
- export const env = loadEnv(envSchema)
1746
-
1747
- export default envSchema
1748
- `;
1749
- }
1750
- /** Generate src/modules/hello/hello.service.ts */
1751
- function generateHelloService() {
1752
- return `import { Service } from '@forinda/kickjs'
1753
-
1754
- @Service()
1755
- export class HelloService {
1756
- greet(name: string) {
1757
- return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
1758
- }
1759
-
1760
- healthCheck() {
1761
- return { status: 'ok', uptime: process.uptime() }
1762
- }
1763
- }
1764
- `;
1765
- }
1766
- /** Generate src/modules/hello/hello.controller.ts */
1767
- function generateHelloController() {
1768
- return `import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
1769
- import { HelloService } from './hello.service'
1770
-
1771
- // \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
1772
- // \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
1773
- // scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
1774
- // See https://forinda.github.io/kick-js/guide/typegen.
1775
-
1776
- @Controller()
1777
- export class HelloController {
1778
- @Autowired() private readonly helloService!: HelloService
1779
-
1780
- @Get('/')
1781
- index(ctx: Ctx<KickRoutes.HelloController['index']>) {
1782
- ctx.json(this.helloService.greet('World'))
1783
- }
1784
-
1785
- @Get('/health')
1786
- health(ctx: Ctx<KickRoutes.HelloController['health']>) {
1787
- ctx.json(this.helloService.healthCheck())
1788
- }
1789
- }
1790
- `;
1791
- }
1792
- /** Generate src/modules/hello/hello.module.ts */
1793
- function generateHelloModule() {
1794
- return `import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
1795
- import { HelloController } from './hello.controller'
1796
-
1797
- export class HelloModule implements AppModule {
1798
- // \`register(container)\` is optional — only implement it when you need
1799
- // to bind a token to a concrete implementation, e.g.
1800
- // register(container) {
1801
- // container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
1802
- // }
1803
- // The HelloService uses @Service() so the decorator handles registration.
1804
-
1805
- routes(): ModuleRoutes {
1806
- return {
1807
- path: '/hello',
1808
- router: buildRoutes(HelloController),
1809
- controller: HelloController,
1810
- }
1811
- }
1812
- }
1813
- `;
1814
- }
1815
- /** Generate kick.config.ts CLI configuration */
1816
- function generateKickConfig(template, defaultRepo = "inmemory", packageManager = "pnpm") {
1817
- return `import { defineConfig } from '@forinda/kickjs-cli'
1818
-
1819
- export default defineConfig({
1820
- pattern: '${template}',
1821
- // Pinned so \`kick add\` and other dep-installing commands always use the
1822
- // project's intended package manager, regardless of which lockfile exists.
1823
- packageManager: '${packageManager}',
1824
- modules: {
1825
- dir: 'src/modules',
1826
- repo: ${[
1827
- "drizzle",
1828
- "inmemory",
1829
- "prisma"
1830
- ].includes(defaultRepo) ? `'${defaultRepo}'` : `{ name: '${defaultRepo}' }`},
1831
- pluralize: true,
1832
- },
1833
-
1834
- // \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
1835
- // resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
1836
- // Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
1837
- typegen: {
1838
- schemaValidator: 'zod',
1839
- },
1840
-
1841
- commands: [
1842
- {
1843
- name: 'test',
1844
- description: 'Run tests with Vitest',
1845
- steps: 'npx vitest run',
1846
- },
1847
- {
1848
- name: 'format',
1849
- description: 'Format code with Prettier',
1850
- steps: 'npx prettier --write src/',
1851
- },
1852
- {
1853
- name: 'format:check',
1854
- description: 'Check formatting without writing',
1855
- steps: 'npx prettier --check src/',
1856
- },
1857
- {
1858
- name: 'ci:check',
1859
- description: 'Run typecheck + format check',
1860
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
1861
- aliases: ['verify'],
1862
- },
1863
- ],
1864
- })
1865
- `;
1866
- }
1867
- //#endregion
1868
- //#region src/generators/patterns/minimal.ts
1869
- async function generateMinimalFiles(ctx) {
1870
- const { pascal, kebab, plural, write } = ctx;
1871
- await write(`${kebab}.module.ts`, generateMinimalModuleIndex({
1872
- pascal,
1873
- kebab,
1874
- plural
1875
- }));
1876
- await write(`${kebab}.controller.ts`, `import { Controller, Get, type Ctx } from '@forinda/kickjs'
1877
-
1878
- // \`Ctx<KickRoutes.${pascal}Controller['<method>']>\` is generated by
1879
- // \`kick typegen\` (auto-run on \`kick dev\`).
1880
-
1881
- @Controller()
1882
- export class ${pascal}Controller {
1883
- @Get('/')
1884
- async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
1885
- ctx.json({ message: '${pascal} list' })
1886
- }
1887
- }
1888
- `);
1889
- }
1890
- //#endregion
1891
- //#region src/generators/patterns/rest.ts
1892
- async function generateRestFiles(ctx) {
1893
- const { pascal, kebab, plural, pluralPascal, repo, noTests, prismaClientPath, write } = ctx;
1894
- await write(`${kebab}.module.ts`, generateRestModuleIndex({
1895
- pascal,
1896
- kebab,
1897
- plural,
1898
- repo
1899
- }));
1900
- await write(`${kebab}.constants.ts`, generateRestConstants({
1901
- pascal,
1902
- kebab
1903
- }));
1904
- await write(`${kebab}.controller.ts`, generateRestController({
1905
- pascal,
1906
- kebab,
1907
- plural,
1908
- pluralPascal
1909
- }));
1910
- await write(`${kebab}.service.ts`, generateRestService({
1911
- pascal,
1912
- kebab
1913
- }));
1914
- await write(`dtos/create-${kebab}.dto.ts`, generateCreateDTO({
1915
- pascal,
1916
- kebab
1917
- }));
1918
- await write(`dtos/update-${kebab}.dto.ts`, generateUpdateDTO({
1919
- pascal,
1920
- kebab
1921
- }));
1922
- await write(`dtos/${kebab}-response.dto.ts`, generateResponseDTO({
1923
- pascal,
1924
- kebab
1925
- }));
1926
- await write(`${kebab}.repository.ts`, generateRepositoryInterface({
1927
- pascal,
1928
- kebab,
1929
- dtoPrefix: "./dtos"
1930
- }));
1931
- const builtinRepoFileMap = {
1932
- inmemory: `in-memory-${kebab}`,
1933
- drizzle: `drizzle-${kebab}`,
1934
- prisma: `prisma-${kebab}`
1935
- };
1936
- const builtinRepoGeneratorMap = {
1937
- inmemory: () => generateInMemoryRepository({
1938
- pascal,
1939
- kebab,
1940
- repoPrefix: ".",
1941
- dtoPrefix: "./dtos"
1942
- }),
1943
- drizzle: () => generateDrizzleRepository({
1944
- pascal,
1945
- kebab,
1946
- repoPrefix: ".",
1947
- dtoPrefix: "./dtos"
1948
- }),
1949
- prisma: () => generatePrismaRepository({
1950
- pascal,
1951
- kebab,
1952
- repoPrefix: ".",
1953
- dtoPrefix: "./dtos",
1954
- prismaClientPath
1955
- })
1956
- };
1957
- const repoFile = builtinRepoFileMap[repo] ?? `${toKebabCase(repo)}-${kebab}`;
1958
- const repoGenerator = builtinRepoGeneratorMap[repo] ?? (() => generateCustomRepository({
1959
- pascal,
1960
- kebab,
1961
- repoType: repo,
1962
- repoPrefix: ".",
1963
- dtoPrefix: "./dtos"
1964
- }));
1965
- await write(`${repoFile}.repository.ts`, repoGenerator());
1966
- if (!noTests) {
1967
- if (repo !== "inmemory") await write(`in-memory-${kebab}.repository.ts`, generateInMemoryRepository({
1968
- pascal,
1969
- kebab,
1970
- repoPrefix: ".",
1971
- dtoPrefix: "./dtos"
1972
- }));
1973
- await write(`__tests__/${kebab}.controller.test.ts`, generateControllerTest({
1974
- pascal,
1975
- kebab,
1976
- plural
1977
- }));
1978
- await write(`__tests__/${kebab}.repository.test.ts`, generateRepositoryTest({
1979
- pascal,
1980
- kebab,
1981
- plural,
1982
- repoPrefix: `../${builtinRepoFileMap.inmemory ?? `in-memory-${kebab}`}.repository`
1983
- }));
1984
- }
1985
- }
1986
- //#endregion
1987
- //#region src/generators/patterns/cqrs.ts
1988
- async function generateCqrsFiles(ctx) {
1989
- const { pascal, kebab, plural, pluralPascal, repo, noTests, prismaClientPath, write } = ctx;
1990
- await write(`${kebab}.module.ts`, generateCqrsModuleIndex({
1991
- pascal,
1992
- kebab,
1993
- plural,
1994
- repo
1995
- }));
1996
- await write(`${kebab}.constants.ts`, generateRestConstants({
1997
- pascal,
1998
- kebab
1999
- }));
2000
- await write(`${kebab}.controller.ts`, generateCqrsController({
2001
- pascal,
2002
- kebab,
2003
- plural,
2004
- pluralPascal
2005
- }));
2006
- await write(`dtos/create-${kebab}.dto.ts`, generateCreateDTO({
2007
- pascal,
2008
- kebab
2009
- }));
2010
- await write(`dtos/update-${kebab}.dto.ts`, generateUpdateDTO({
2011
- pascal,
2012
- kebab
2013
- }));
2014
- await write(`dtos/${kebab}-response.dto.ts`, generateResponseDTO({
2015
- pascal,
2016
- kebab
2017
- }));
2018
- const commands = generateCqrsCommands({
2019
- pascal,
2020
- kebab
2021
- });
2022
- for (const cmd of commands) await write(`commands/${cmd.file}`, cmd.content);
2023
- const queries = generateCqrsQueries({
2024
- pascal,
2025
- kebab,
2026
- plural,
2027
- pluralPascal
2028
- });
2029
- for (const q of queries) await write(`queries/${q.file}`, q.content);
2030
- const events = generateCqrsEvents({
2031
- pascal,
2032
- kebab
2033
- });
2034
- for (const e of events) await write(`events/${e.file}`, e.content);
2035
- await write(`${kebab}.repository.ts`, generateRepositoryInterface({
2036
- pascal,
2037
- kebab,
2038
- dtoPrefix: "./dtos"
2039
- }));
2040
- const builtinRepoFileMap = {
2041
- inmemory: `in-memory-${kebab}`,
2042
- drizzle: `drizzle-${kebab}`,
2043
- prisma: `prisma-${kebab}`
2044
- };
2045
- const builtinRepoGeneratorMap = {
2046
- inmemory: () => generateInMemoryRepository({
2047
- pascal,
2048
- kebab,
2049
- repoPrefix: ".",
2050
- dtoPrefix: "./dtos"
2051
- }),
2052
- drizzle: () => generateDrizzleRepository({
2053
- pascal,
2054
- kebab,
2055
- repoPrefix: ".",
2056
- dtoPrefix: "./dtos"
2057
- }),
2058
- prisma: () => generatePrismaRepository({
2059
- pascal,
2060
- kebab,
2061
- repoPrefix: ".",
2062
- dtoPrefix: "./dtos",
2063
- prismaClientPath
2064
- })
2065
- };
2066
- const repoFile = builtinRepoFileMap[repo] ?? `${toKebabCase(repo)}-${kebab}`;
2067
- const repoGenerator = builtinRepoGeneratorMap[repo] ?? (() => generateCustomRepository({
2068
- pascal,
2069
- kebab,
2070
- repoType: repo,
2071
- repoPrefix: ".",
2072
- dtoPrefix: "./dtos"
2073
- }));
2074
- await write(`${repoFile}.repository.ts`, repoGenerator());
2075
- if (!noTests) {
2076
- if (repo !== "inmemory") await write(`in-memory-${kebab}.repository.ts`, generateInMemoryRepository({
2077
- pascal,
2078
- kebab,
2079
- repoPrefix: ".",
2080
- dtoPrefix: "./dtos"
2081
- }));
2082
- await write(`__tests__/${kebab}.controller.test.ts`, generateControllerTest({
2083
- pascal,
2084
- kebab,
2085
- plural
2086
- }));
2087
- await write(`__tests__/${kebab}.repository.test.ts`, generateRepositoryTest({
2088
- pascal,
2089
- kebab,
2090
- plural,
2091
- repoPrefix: `../${builtinRepoFileMap.inmemory ?? `in-memory-${kebab}`}.repository`
2092
- }));
2093
- }
2094
- }
2095
- //#endregion
2096
- //#region src/generators/patterns/ddd.ts
2097
- async function generateDddFiles(ctx) {
2098
- const { pascal, kebab, plural, pluralPascal, repo, noEntity, noTests, prismaClientPath, write } = ctx;
2099
- await write(`${kebab}.module.ts`, generateModuleIndex({
2100
- pascal,
2101
- kebab,
2102
- plural,
2103
- repo
2104
- }));
2105
- await write("constants.ts", repo === "drizzle" ? generateDrizzleConstants({
2106
- pascal,
2107
- kebab
2108
- }) : generateConstants({
2109
- pascal,
2110
- kebab
2111
- }));
2112
- await write(`presentation/${kebab}.controller.ts`, generateController$1({
2113
- pascal,
2114
- kebab,
2115
- plural,
2116
- pluralPascal
2117
- }));
2118
- await write(`application/dtos/create-${kebab}.dto.ts`, generateCreateDTO({
2119
- pascal,
2120
- kebab
2121
- }));
2122
- await write(`application/dtos/update-${kebab}.dto.ts`, generateUpdateDTO({
2123
- pascal,
2124
- kebab
2125
- }));
2126
- await write(`application/dtos/${kebab}-response.dto.ts`, generateResponseDTO({
2127
- pascal,
2128
- kebab
2129
- }));
2130
- const useCases = generateUseCases({
2131
- pascal,
2132
- kebab,
2133
- plural,
2134
- pluralPascal
2135
- });
2136
- for (const uc of useCases) await write(`application/use-cases/${uc.file}`, uc.content);
2137
- await write(`domain/repositories/${kebab}.repository.ts`, generateRepositoryInterface({
2138
- pascal,
2139
- kebab
2140
- }));
2141
- await write(`domain/services/${kebab}-domain.service.ts`, generateDomainService({
2142
- pascal,
2143
- kebab
2144
- }));
2145
- const builtinRepoFileMap = {
2146
- inmemory: `in-memory-${kebab}`,
2147
- drizzle: `drizzle-${kebab}`,
2148
- prisma: `prisma-${kebab}`
2149
- };
2150
- const builtinRepoGeneratorMap = {
2151
- inmemory: () => generateInMemoryRepository({
2152
- pascal,
2153
- kebab
2154
- }),
2155
- drizzle: () => generateDrizzleRepository({
2156
- pascal,
2157
- kebab
2158
- }),
2159
- prisma: () => generatePrismaRepository({
2160
- pascal,
2161
- kebab,
2162
- prismaClientPath
2163
- })
2164
- };
2165
- const repoFile = builtinRepoFileMap[repo] ?? `${toKebabCase(repo)}-${kebab}`;
2166
- const repoGenerator = builtinRepoGeneratorMap[repo] ?? (() => generateCustomRepository({
2167
- pascal,
2168
- kebab,
2169
- repoType: repo
2170
- }));
2171
- await write(`infrastructure/repositories/${repoFile}.repository.ts`, repoGenerator());
2172
- if (!noEntity) {
2173
- await write(`domain/entities/${kebab}.entity.ts`, generateEntity({
2174
- pascal,
2175
- kebab
2176
- }));
2177
- await write(`domain/value-objects/${kebab}-id.vo.ts`, generateValueObject({
2178
- pascal,
2179
- kebab
2180
- }));
2181
- }
2182
- if (!noTests) {
2183
- if (repo !== "inmemory") await write(`infrastructure/repositories/in-memory-${kebab}.repository.ts`, generateInMemoryRepository({
2184
- pascal,
2185
- kebab
2186
- }));
2187
- await write(`__tests__/${kebab}.controller.test.ts`, generateControllerTest({
2188
- pascal,
2189
- kebab,
2190
- plural
2191
- }));
2192
- await write(`__tests__/${kebab}.repository.test.ts`, generateRepositoryTest({
2193
- pascal,
2194
- kebab,
2195
- plural
2196
- }));
2197
- }
2198
- }
2199
- //#endregion
2200
- //#region src/generators/module.ts
2201
- /**
2202
- * Generate a module — structure depends on the project pattern.
2203
- *
2204
- * Patterns:
2205
- * rest — flat folder: controller + service + DTOs + repo
2206
- * ddd — nested DDD: presentation/ application/ domain/ infrastructure/
2207
- * cqrs — commands, queries, events with WS/queue integration
2208
- * minimal — just controller + module index
2209
- */
2210
- async function generateModule(options) {
2211
- const { name, modulesDir, noEntity, noTests, repo = "inmemory", force, dryRun } = options;
2212
- const shouldPluralize = options.pluralize !== false;
2213
- let pattern = options.pattern ?? "ddd";
2214
- if (options.minimal) pattern = "minimal";
2215
- const kebab = toKebabCase(name);
2216
- const pascal = toPascalCase(name);
2217
- const plural = shouldPluralize ? pluralize(kebab) : kebab;
2218
- const pluralPascal = shouldPluralize ? pluralizePascal(pascal) : pascal;
2219
- const moduleDir = join(modulesDir, plural);
2220
- const files = [];
2221
- let overwriteAll = force ?? false;
2222
- const write = async (relativePath, content) => {
2223
- const fullPath = join(moduleDir, relativePath);
2224
- if (dryRun) {
2225
- files.push(fullPath);
2226
- return;
2227
- }
2228
- if (!overwriteAll && await fileExists(fullPath)) {
2229
- if (!await confirm({
2230
- message: `File exists: ${pc.dim(relativePath)}. Overwrite?`,
2231
- initialValue: false
2232
- })) {
2233
- log.warn(`Skipped: ${relativePath}`);
2234
- return;
2235
- }
2236
- }
2237
- await writeFileSafe(fullPath, content);
2238
- files.push(fullPath);
2239
- };
2240
- const ctx = {
2241
- kebab,
2242
- pascal,
2243
- plural,
2244
- pluralPascal,
2245
- moduleDir,
2246
- repo,
2247
- noEntity: noEntity ?? false,
2248
- noTests: noTests ?? false,
2249
- prismaClientPath: options.prismaClientPath ?? "@prisma/client",
2250
- write,
2251
- files
2252
- };
2253
- switch (pattern) {
2254
- case "minimal":
2255
- await generateMinimalFiles(ctx);
2256
- break;
2257
- case "rest":
2258
- await generateRestFiles(ctx);
2259
- break;
2260
- case "cqrs":
2261
- await generateCqrsFiles(ctx);
2262
- break;
2263
- default:
2264
- await generateDddFiles(ctx);
2265
- break;
2266
- }
2267
- if (!dryRun) await autoRegisterModule(modulesDir, pascal, plural, kebab);
2268
- return files;
2269
- }
2270
- /** Add the new module to src/modules/index.ts */
2271
- async function autoRegisterModule(modulesDir, pascal, plural, kebab) {
2272
- const indexPath = join(modulesDir, "index.ts");
2273
- const exists = await fileExists(indexPath);
2274
- const importPath = `./${plural}/${kebab}.module`;
2275
- if (!exists) {
2276
- await writeFileSafe(indexPath, `import type { AppModuleClass } from '@forinda/kickjs'
2277
- import { ${pascal}Module } from '${importPath}'
2278
-
2279
- export const modules: AppModuleClass[] = [${pascal}Module]
2280
- `);
2281
- return;
2282
- }
2283
- let content = await readFile(indexPath, "utf-8");
2284
- const importLine = `import { ${pascal}Module } from '${importPath}'`;
2285
- if (!content.includes(`${pascal}Module`)) {
2286
- const lastImportIdx = content.lastIndexOf("import ");
2287
- if (lastImportIdx !== -1) {
2288
- const lineEnd = content.indexOf("\n", lastImportIdx);
2289
- content = content.slice(0, lineEnd + 1) + importLine + "\n" + content.slice(lineEnd + 1);
2290
- } else content = importLine + "\n" + content;
2291
- content = content.replace(/(=\s*\[)([\s\S]*?)(])/, (_match, open, existing, close) => {
2292
- const trimmed = existing.trim();
2293
- if (!trimmed) return `${open}${pascal}Module${close}`;
2294
- const needsComma = trimmed.endsWith(",") ? "" : ",";
2295
- return `${open}${existing.trimEnd()}${needsComma} ${pascal}Module${close}`;
2296
- });
2297
- }
2298
- await writeFile(indexPath, content, "utf-8");
2299
- }
2300
- //#endregion
2301
- //#region src/generators/adapter.ts
2302
- /**
2303
- * Scaffold a `defineAdapter()` factory under `src/adapters/<name>.adapter.ts`.
2304
- *
2305
- * v4 dropped the `class implements AppAdapter` pattern in favour of the
2306
- * `defineAdapter()` factory (architecture.md §21.3.4). The generated
2307
- * template uses the new factory shape so adopters get a working
2308
- * adapter with all four lifecycle hooks (beforeMount, beforeStart,
2309
- * afterStart, shutdown), a typed config object with defaults, and the
2310
- * factory's call / `.scoped()` / `.async()` surfaces — without
2311
- * writing a single class.
2312
- */
2313
- async function generateAdapter(options) {
2314
- const { name, outDir } = options;
2315
- const kebab = toKebabCase(name);
2316
- const pascal = toPascalCase(name);
2317
- const files = [];
2318
- const filePath = join(outDir, `${kebab}.adapter.ts`);
2319
- await writeFileSafe(filePath, `import {
2320
- defineAdapter,
2321
- type AdapterContext,
2322
- type AdapterMiddleware,
2323
- type ContributorRegistrations,
2324
- type Constructor,
2325
- } from '@forinda/kickjs'
2326
-
2327
- /**
2328
- * Configuration for the ${pascal} adapter.
2329
- *
2330
- * Adapters typically take a small config object so callers can tune
2331
- * behaviour at bootstrap time. Keep the shape narrow — anything
2332
- * derived from the environment should be read inside the build
2333
- * function via getEnv(), not forced onto the caller.
2334
- */
2335
- export interface ${pascal}AdapterConfig {
2336
- // Add your adapter configuration here, e.g.:
2337
- // enabled?: boolean
2338
- // apiKey?: string
2339
- }
2340
-
2341
- /**
2342
- * ${pascal} adapter — built via \`defineAdapter()\` so callers get the
2343
- * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
2344
- *
2345
- * Hooks into the Application lifecycle to add middleware, routes,
2346
- * Context Contributors, or external service connections.
2347
- *
2348
- * Every lifecycle hook below is OPTIONAL. The scaffold emits all of
2349
- * them so adopters can browse what's available and delete what they
2350
- * don't need — \`build()\` returning \`{}\` is also valid for an adapter
2351
- * that only contributes config defaults.
2352
- *
2353
- * @example
2354
- * \`\`\`ts
2355
- * import { bootstrap } from '@forinda/kickjs'
2356
- * import { ${pascal}Adapter } from './adapters/${kebab}.adapter'
2357
- *
2358
- * bootstrap({
2359
- * modules,
2360
- * adapters: [${pascal}Adapter({ /* config overrides *\\/ })],
2361
- * })
2362
- * \`\`\`
2363
- */
2364
- export const ${pascal}Adapter = defineAdapter<${pascal}AdapterConfig>({
2365
- name: '${pascal}Adapter',
2366
- defaults: {
2367
- // Default config values go here. The adopter's overrides shallow-merge
2368
- // on top of these before \`build()\` runs.
2369
- },
2370
- build: (_config, { name: _name }) => {
2371
- // Closures inside \`build()\` are how each adapter instance owns its
2372
- // own state (database client, Map, timer handle, …). The same
2373
- // \`_config\` is visible to every hook below.
2374
-
2375
- return {
2376
- /**
2377
- * Express middleware entries the Application mounts at named phases.
2378
- *
2379
- * \`phase\` controls where each handler sits in the pipeline:
2380
- * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
2381
- *
2382
- * \`path\` (optional) scopes the entry to a path prefix.
2383
- *
2384
- * Delete this hook entirely if you don't add middleware.
2385
- */
2386
- middleware(): AdapterMiddleware[] {
2387
- return [
2388
- // Example: add a custom header to all responses
2389
- // {
2390
- // phase: 'beforeGlobal',
2391
- // handler: (_req, res, next) => {
2392
- // res.setHeader('X-${pascal}', 'true')
2393
- // next()
2394
- // },
2395
- // },
2396
- // Example: scope a rate limiter to one path prefix
2397
- // {
2398
- // phase: 'beforeRoutes',
2399
- // path: '/api/v1/auth',
2400
- // handler: rateLimit({ max: 10 }),
2401
- // },
2402
- ]
2403
- },
2404
-
2405
- /**
2406
- * Runs BEFORE global middleware. Mount routes that should bypass the
2407
- * middleware stack — health checks, docs UI, static assets, OAuth
2408
- * callbacks. Anything you want reachable even if a global middleware
2409
- * later in the chain rejects requests.
2410
- *
2411
- * Delete this hook if you have no early routes.
2412
- */
2413
- beforeMount(_ctx: AdapterContext): void {
2414
- // Example:
2415
- // _ctx.app.get('/${kebab}/status', (_req, res) => res.json({ status: 'ok' }))
2416
- },
2417
-
2418
- /**
2419
- * Fires once per controller class as the router mounts. Use this to
2420
- * collect route metadata for OpenAPI specs, dependency graphs, route
2421
- * inventories, devtools dashboards.
2422
- *
2423
- * Delete this hook unless your adapter introspects the route registry.
2424
- */
2425
- onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
2426
- // Example (Swagger-style): collect routes for the spec.
2427
- // openApiSpec.addController(_controllerClass, _mountPath)
2428
- },
2429
-
2430
- /**
2431
- * Runs AFTER modules + routes are wired, BEFORE the server starts.
2432
- * Right place for late-stage DI registrations or final config validation.
2433
- *
2434
- * Delete this hook if there's nothing to wire post-modules.
2435
- */
2436
- beforeStart(_ctx: AdapterContext): void {
2437
- // Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
2438
- },
2439
-
2440
- /**
2441
- * Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
2442
- * available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
2443
- * gRPC, GraphQL subscriptions), warm caches, log a banner.
2444
- *
2445
- * Delete this hook if you don't need the running server reference.
2446
- */
2447
- afterStart(_ctx: AdapterContext): void {
2448
- // Example: const io = new Server(_ctx.server)
2449
- },
2450
-
2451
- /**
2452
- * Returns Context Contributors to merge into every route's pipeline
2453
- * at the \`'adapter'\` precedence level. Per-route handlers can
2454
- * override the value at the method / class / module level.
2455
- *
2456
- * Delete this hook unless your adapter ships typed per-request values
2457
- * (auth user, tenant, locale, feature flags, geo, etc).
2458
- */
2459
- contributors(): ContributorRegistrations {
2460
- return [
2461
- // Example:
2462
- // import { defineHttpContextDecorator } from '@forinda/kickjs'
2463
- // declare module '@forinda/kickjs' { interface ContextMeta { ${kebab}: { id: string } } }
2464
- // const Load${pascal} = defineHttpContextDecorator({
2465
- // key: '${kebab}',
2466
- // resolve: (ctx) => ({ id: ctx.req.headers['x-${kebab}-id'] as string }),
2467
- // })
2468
- // return [Load${pascal}.registration]
2469
- ]
2470
- },
2471
-
2472
- /**
2473
- * Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
2474
- * resources the adapter owns: close connections, flush buffers,
2475
- * cancel timers. The framework runs every adapter's \`shutdown\`
2476
- * concurrently via \`Promise.allSettled\` — one failure won't block
2477
- * sibling adapters.
2478
- *
2479
- * Delete this hook if your adapter holds no resources.
2480
- */
2481
- async shutdown(): Promise<void> {
2482
- // Example: await this.pool.end()
2483
- // Example: clearInterval(this.heartbeatTimer)
2484
- },
2485
- }
2486
- },
2487
- })
2488
- `);
2489
- files.push(filePath);
2490
- return files;
2491
- }
2492
- //#endregion
2493
- //#region src/utils/resolve-out-dir.ts
2494
- /**
2495
- * DDD folder mapping — nested layered architecture.
2496
- */
2497
- const DDD_FOLDER_MAP = {
2498
- controller: "presentation",
2499
- service: "domain/services",
2500
- dto: "application/dtos",
2501
- guard: "presentation/guards",
2502
- middleware: "middleware"
2503
- };
2504
- /**
2505
- * Flat folder mapping — REST/GraphQL/minimal patterns.
2506
- * Files live at the module root or in minimal subdirectories.
2507
- */
2508
- const FLAT_FOLDER_MAP = {
2509
- controller: "",
2510
- service: "",
2511
- dto: "dtos",
2512
- guard: "guards",
2513
- middleware: "middleware"
2514
- };
2515
- /**
2516
- * CQRS folder mapping — commands, queries, events.
2517
- */
2518
- const CQRS_FOLDER_MAP = {
2519
- controller: "",
2520
- service: "",
2521
- dto: "dtos",
2522
- guard: "guards",
2523
- middleware: "middleware",
2524
- command: "commands",
2525
- query: "queries",
2526
- event: "events"
2527
- };
2528
- /**
2529
- * Resolve the output directory for a generator artifact.
2530
- *
2531
- * Priority:
2532
- * 1. Explicit --out flag (always wins)
2533
- * 2. --module flag → maps into module's folder (DDD or flat based on pattern)
2534
- * 3. Standalone default directory
2535
- */
2536
- function resolveOutDir(options) {
2537
- const { type, outDir, moduleName, modulesDir = "src/modules", defaultDir, pattern = "ddd", shouldPluralize = true } = options;
2538
- if (outDir) return resolve(outDir);
2539
- if (moduleName) {
2540
- const folderMap = pattern === "ddd" ? DDD_FOLDER_MAP : pattern === "cqrs" ? CQRS_FOLDER_MAP : FLAT_FOLDER_MAP;
2541
- const kebab = toKebabCase(moduleName);
2542
- const folder = shouldPluralize ? pluralize(kebab) : kebab;
2543
- const subfolder = folderMap[type] ?? "";
2544
- const base = join(modulesDir, folder);
2545
- return resolve(subfolder ? join(base, subfolder) : base);
2546
- }
2547
- return resolve(defaultDir);
2548
- }
2549
- //#endregion
2550
- //#region src/generators/middleware.ts
2551
- async function generateMiddleware(options) {
2552
- const { name, moduleName, modulesDir, pattern } = options;
2553
- const outDir = resolveOutDir({
2554
- type: "middleware",
2555
- outDir: options.outDir,
2556
- moduleName,
2557
- modulesDir,
2558
- defaultDir: "src/middleware",
2559
- pattern,
2560
- shouldPluralize: options.pluralize ?? true
2561
- });
2562
- const kebab = toKebabCase(name);
2563
- const camel = toCamelCase(name);
2564
- const files = [];
2565
- const filePath = join(outDir, `${kebab}.middleware.ts`);
2566
- await writeFileSafe(filePath, `import type { Request, Response, NextFunction } from 'express'
2567
-
2568
- export interface ${toPascalCase(name)}Options {
2569
- // Add configuration options here
2570
- }
2571
-
2572
- /**
2573
- * ${toPascalCase(name)} middleware.
2574
- *
2575
- * Usage in bootstrap:
2576
- * middleware: [${camel}()]
2577
- *
2578
- * Usage with adapter:
2579
- * middleware() { return [{ handler: ${camel}(), phase: 'afterGlobal' }] }
2580
- *
2581
- * Usage with @Middleware decorator:
2582
- * @Middleware(${camel}())
2583
- */
2584
- export function ${camel}(options: ${toPascalCase(name)}Options = {}) {
2585
- return (req: Request, res: Response, next: NextFunction) => {
2586
- // Implement your middleware logic here
2587
- next()
2588
- }
2589
- }
2590
- `);
2591
- files.push(filePath);
2592
- return files;
2593
- }
2594
- //#endregion
2595
- //#region src/generators/guard.ts
2596
- async function generateGuard(options) {
2597
- const { name, moduleName, modulesDir, pattern } = options;
2598
- const outDir = resolveOutDir({
2599
- type: "guard",
2600
- outDir: options.outDir,
2601
- moduleName,
2602
- modulesDir,
2603
- defaultDir: "src/guards",
2604
- pattern,
2605
- shouldPluralize: options.pluralize ?? true
2606
- });
2607
- const kebab = toKebabCase(name);
2608
- const camel = toCamelCase(name);
2609
- const pascal = toPascalCase(name);
2610
- const files = [];
2611
- const filePath = join(outDir, `${kebab}.guard.ts`);
2612
- await writeFileSafe(filePath, `import { Container, HttpException } from '@forinda/kickjs'
2613
- import type { RequestContext } from '@forinda/kickjs'
2614
-
2615
- /**
2616
- * ${pascal} guard.
2617
- *
2618
- * Guards protect routes by checking conditions before the handler runs.
2619
- * Return early with an error response to block access.
2620
- *
2621
- * Usage:
2622
- * @Middleware(${camel}Guard)
2623
- * @Get('/protected')
2624
- * async handler(ctx: RequestContext) { ... }
2625
- */
2626
- export async function ${camel}Guard(ctx: RequestContext, next: () => void): Promise<void> {
2627
- // Example: check for an authorization header
2628
- const header = ctx.headers.authorization
2629
- if (!header?.startsWith('Bearer ')) {
2630
- ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
2631
- return
2632
- }
2633
-
2634
- const token = header.slice(7)
2635
-
2636
- try {
2637
- // Verify the token using a service from the DI container
2638
- // const container = Container.getInstance()
2639
- // const authService = container.resolve(AuthService)
2640
- // const payload = authService.verifyToken(token)
2641
- // ctx.set('auth', payload)
2642
-
2643
- next()
2644
- } catch {
2645
- ctx.res.status(401).json({ message: 'Invalid or expired token' })
2646
- }
2647
- }
2648
- `);
2649
- files.push(filePath);
2650
- return files;
2651
- }
2652
- //#endregion
2653
- //#region src/generators/service.ts
2654
- async function generateService(options) {
2655
- const { name, moduleName, modulesDir, pattern } = options;
2656
- const outDir = resolveOutDir({
2657
- type: "service",
2658
- outDir: options.outDir,
2659
- moduleName,
2660
- modulesDir,
2661
- defaultDir: "src/services",
2662
- pattern,
2663
- shouldPluralize: options.pluralize ?? true
2664
- });
2665
- const kebab = toKebabCase(name);
2666
- const pascal = toPascalCase(name);
2667
- const files = [];
2668
- const filePath = join(outDir, `${kebab}.service.ts`);
2669
- await writeFileSafe(filePath, `import { Service } from '@forinda/kickjs'
2670
-
2671
- @Service()
2672
- export class ${pascal}Service {
2673
- // Inject dependencies via constructor
2674
- // constructor(
2675
- // @Inject(MY_REPO) private readonly repo: IMyRepository,
2676
- // ) {}
2677
- }
2678
- `);
2679
- files.push(filePath);
2680
- return files;
2681
- }
2682
- //#endregion
2683
- //#region src/generators/controller.ts
2684
- async function generateController(options) {
2685
- const { name, moduleName, modulesDir, pattern } = options;
2686
- const outDir = resolveOutDir({
2687
- type: "controller",
2688
- outDir: options.outDir,
2689
- moduleName,
2690
- modulesDir,
2691
- defaultDir: "src/controllers",
2692
- pattern,
2693
- shouldPluralize: options.pluralize ?? true
2694
- });
2695
- const kebab = toKebabCase(name);
2696
- const pascal = toPascalCase(name);
2697
- const files = [];
2698
- const filePath = join(outDir, `${kebab}.controller.ts`);
2699
- await writeFileSafe(filePath, `import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
2700
-
2701
- // \`Ctx<KickRoutes.${pascal}Controller['<method>']>\` is generated by
2702
- // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
2703
- // will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
2704
- // See https://forinda.github.io/kick-js/guide/typegen for details.
2705
-
2706
- @Controller()
2707
- export class ${pascal}Controller {
2708
- // @Autowired() private readonly myService!: MyService
2709
-
2710
- @Get('/')
2711
- async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
2712
- ctx.json({ message: '${pascal} list' })
2713
- }
2714
-
2715
- @Post('/')
2716
- async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
2717
- ctx.created({ message: '${pascal} created', data: ctx.body })
2718
- }
2719
- }
2720
- `);
2721
- files.push(filePath);
2722
- return files;
2723
- }
2724
- //#endregion
2725
- //#region src/generators/dto.ts
2726
- async function generateDto(options) {
2727
- const { name, moduleName, modulesDir, pattern } = options;
2728
- const outDir = resolveOutDir({
2729
- type: "dto",
2730
- outDir: options.outDir,
2731
- moduleName,
2732
- modulesDir,
2733
- defaultDir: "src/dtos",
2734
- pattern,
2735
- shouldPluralize: options.pluralize ?? true
2736
- });
2737
- const kebab = toKebabCase(name);
2738
- const pascal = toPascalCase(name);
2739
- const camel = toCamelCase(name);
2740
- const files = [];
2741
- const filePath = join(outDir, `${kebab}.dto.ts`);
2742
- await writeFileSafe(filePath, `import { z } from 'zod'
2743
-
2744
- export const ${camel}Schema = z.object({
2745
- // Define your schema fields here
2746
- name: z.string().min(1).max(200),
2747
- })
2748
-
2749
- export type ${pascal}DTO = z.infer<typeof ${camel}Schema>
2750
- `);
2751
- files.push(filePath);
2752
- return files;
2753
- }
2754
- //#endregion
2755
- //#region src/generators/templates/project-config.ts
2756
- /** Map of optional package names to their npm package identifiers */
2757
- const PACKAGE_DEPS = {
2758
- auth: "@forinda/kickjs-auth",
2759
- swagger: "@forinda/kickjs-swagger",
2760
- ws: "@forinda/kickjs-ws",
2761
- queue: "@forinda/kickjs-queue",
2762
- devtools: "@forinda/kickjs-devtools"
2763
- };
2764
- /** Generate package.json with template-aware dependencies */
2765
- function generatePackageJson(name, template, kickjsVersion, packages = []) {
2766
- const baseDeps = {
2767
- "@forinda/kickjs": kickjsVersion,
2768
- dotenv: "^17.3.1",
2769
- express: "^5.1.0",
2770
- "reflect-metadata": "^0.2.2",
2771
- zod: "^4.3.6",
2772
- pino: "^10.3.1",
2773
- "pino-pretty": "^13.1.3"
2774
- };
2775
- for (const pkg of packages) {
2776
- const dep = PACKAGE_DEPS[pkg];
2777
- if (dep && !baseDeps[dep]) baseDeps[dep] = kickjsVersion;
2778
- }
2779
- return JSON.stringify({
2780
- name,
2781
- version: kickjsVersion.replace("^", ""),
2782
- type: "module",
2783
- scripts: {
2784
- dev: "vite",
2785
- "dev:debug": "kick dev:debug",
2786
- build: "kick build",
2787
- start: "kick start",
2788
- test: "vitest run",
2789
- "test:watch": "vitest",
2790
- typecheck: "tsc --noEmit",
2791
- typegen: "kick typegen",
2792
- lint: "eslint src/",
2793
- format: "prettier --write src/"
2794
- },
2795
- dependencies: baseDeps,
2796
- devDependencies: {
2797
- "@forinda/kickjs-cli": kickjsVersion,
2798
- "@forinda/kickjs-vite": kickjsVersion,
2799
- "@swc/core": "^1.15.21",
2800
- "@types/express": "^5.0.6",
2801
- "@types/node": "^25.0.0",
2802
- "unplugin-swc": "^1.5.9",
2803
- vite: "^8.0.3",
2804
- vitest: "^4.1.2",
2805
- typescript: "^6.0.3",
2806
- prettier: "^3.8.1"
2807
- }
2808
- }, null, 2);
2809
- }
2810
- /**
2811
- * Generate vite.config.ts with the KickJS Vite plugin.
2812
- *
2813
- * The plugin handles:
2814
- * - SSR environment setup for backend Node.js code
2815
- * - Virtual module generation (virtual:kickjs/app)
2816
- * - Module auto-discovery (scans *.module.ts files)
2817
- * - HMR with selective container invalidation
2818
- * - Express mounting via configureServer() post-hook
2819
- * - httpServer piping to adapters (WsAdapter, Socket.IO, etc.)
2820
- */
2821
- function generateViteConfig() {
2822
- return `import { defineConfig } from 'vite'
2823
- import { resolve } from 'node:path'
2824
- import swc from 'unplugin-swc'
2825
- import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
2826
-
2827
- export default defineConfig({
2828
- oxc: false,
2829
- plugins: [
2830
- swc.vite(),
2831
- kickjsVitePlugin({ entry: 'src/index.ts' }),
2832
- // Watches .env files and triggers a full reload on change so the
2833
- // dev server picks up env tweaks without a manual restart.
2834
- envWatchPlugin(),
2835
- ],
2836
- resolve: {
2837
- alias: {
2838
- '@': resolve(__dirname, 'src'),
2839
- },
2840
- },
2841
- ssr: {
2842
- // Don't bundle pino — its worker-thread transport needs Node.js resolution
2843
- // to find pino-pretty at runtime for colored log output
2844
- external: ['pino', 'pino-pretty'],
2845
- },
2846
- build: {
2847
- target: 'node20',
2848
- ssr: true,
2849
- outDir: 'dist',
2850
- sourcemap: true,
2851
- rollupOptions: {
2852
- input: resolve(__dirname, 'src/index.ts'),
2853
- output: { format: 'esm' },
2854
- },
2855
- },
2856
- })
2857
- `;
2858
- }
2859
- /** Generate tsconfig.json with decorator support */
2860
- function generateTsConfig() {
2861
- return JSON.stringify({
2862
- compilerOptions: {
2863
- target: "ES2022",
2864
- module: "ESNext",
2865
- moduleResolution: "bundler",
2866
- lib: ["ES2022"],
2867
- types: ["node", "vite/client"],
2868
- strict: true,
2869
- esModuleInterop: true,
2870
- skipLibCheck: true,
2871
- sourceMap: true,
2872
- declaration: true,
2873
- experimentalDecorators: true,
2874
- emitDecoratorMetadata: true,
2875
- outDir: "dist",
2876
- paths: { "@/*": ["./src/*"] }
2877
- },
2878
- include: [
2879
- "src",
2880
- ".kickjs/types/**/*.d.ts",
2881
- ".kickjs/types/**/*.ts"
2882
- ]
2883
- }, null, 2);
2884
- }
2885
- /** Generate .prettierrc with project formatting rules */
2886
- function generatePrettierConfig() {
2887
- return JSON.stringify({
2888
- semi: false,
2889
- singleQuote: true,
2890
- trailingComma: "all",
2891
- printWidth: 100,
2892
- tabWidth: 2
2893
- }, null, 2);
2894
- }
2895
- /** Generate .editorconfig for consistent editor settings */
2896
- function generateEditorConfig() {
2897
- return `# https://editorconfig.org
2898
- root = true
2899
-
2900
- [*]
2901
- indent_style = space
2902
- indent_size = 2
2903
- end_of_line = lf
2904
- charset = utf-8
2905
- trim_trailing_whitespace = true
2906
- insert_final_newline = true
2907
-
2908
- [*.md]
2909
- trim_trailing_whitespace = false
2910
- `;
2911
- }
2912
- /** Generate .gitignore with common Node.js patterns */
2913
- function generateGitIgnore() {
2914
- return `node_modules/
2915
- dist/
2916
- .env
2917
- coverage/
2918
- .DS_Store
2919
- *.tsbuildinfo
2920
- .kickjs/
2921
- `;
2922
- }
2923
- /** Generate .gitattributes for consistent line endings */
2924
- function generateGitAttributes() {
2925
- return `# Auto-detect text files and normalise line endings to LF
2926
- * text=auto eol=lf
2927
-
2928
- # Explicitly mark generated / binary files
2929
- *.png binary
2930
- *.jpg binary
2931
- *.jpeg binary
2932
- *.gif binary
2933
- *.ico binary
2934
- *.woff binary
2935
- *.woff2 binary
2936
- *.ttf binary
2937
- *.eot binary
2938
-
2939
- # Lock files — treat as generated
2940
- pnpm-lock.yaml -diff linguist-generated
2941
- yarn.lock -diff linguist-generated
2942
- package-lock.json -diff linguist-generated
2943
- `;
2944
- }
2945
- /** Generate .env file with default environment variables */
2946
- function generateEnv() {
2947
- return `PORT=3000
2948
- NODE_ENV=development
2949
- `;
2950
- }
2951
- /** Generate .env.example file as a template */
2952
- function generateEnvExample() {
2953
- return `PORT=3000
2954
- NODE_ENV=development
2955
- `;
2956
- }
2957
- /** Generate vitest.config.ts for test configuration */
2958
- function generateVitestConfig() {
2959
- return `import { defineConfig } from 'vitest/config'
2960
- import swc from 'unplugin-swc'
2961
-
2962
- export default defineConfig({
2963
- plugins: [swc.vite()],
2964
- test: {
2965
- globals: true,
2966
- environment: 'node',
2967
- include: ['src/**/*.test.ts'],
2968
- },
2969
- })
2970
- `;
2971
- }
2972
- //#endregion
2973
- //#region src/generators/templates/project-docs.ts
2974
- /** Generate README.md with project documentation */
2975
- function generateReadme(name, template, pm) {
2976
- const templateLabels = {
2977
- rest: "REST API",
2978
- ddd: "Domain-Driven Design",
2979
- cqrs: "CQRS + Event-Driven",
2980
- minimal: "Minimal"
2981
- };
2982
- const packages = ["@forinda/kickjs", "@forinda/kickjs-vite"];
2983
- if (template !== "minimal") packages.push("@forinda/kickjs-swagger", "@forinda/kickjs-devtools");
2984
- if (template === "cqrs") packages.push("@forinda/kickjs-queue", "@forinda/kickjs-ws");
2985
- return `# ${name}
2986
-
2987
- A **${templateLabels[template] ?? "REST API"}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
2988
-
2989
- ## Getting Started
2990
-
2991
- \`\`\`bash
2992
- ${pm} install
2993
- kick dev
2994
- \`\`\`
2995
-
2996
- ## Scripts
2997
-
2998
- | Command | Description |
2999
- |---|---|
3000
- | \`kick dev\` | Start dev server with Vite HMR |
3001
- | \`kick build\` | Production build |
3002
- | \`kick start\` | Run production build |
3003
- | \`${pm} run test\` | Run tests with Vitest |
3004
- | \`kick g module <name>\` | Generate a DDD module |
3005
- | \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
3006
- | \`kick add <package>\` | Add a KickJS package |
3007
-
3008
- ## Project Structure
3009
-
3010
- \`\`\`
3011
- src/
3012
- ├── index.ts # Application entry point
3013
- ├── modules/ # Feature modules (controllers, services, repos)
3014
- │ └── index.ts # Module registry
3015
- └── ...
3016
- \`\`\`
3017
-
3018
- ## Packages
3019
-
3020
- ${packages.map((p) => `- \`${p}\``).join("\n")}
3021
-
3022
- ## Adding Features
3023
-
3024
- \`\`\`bash
3025
- kick add auth # Authentication (JWT, API key, OAuth)
3026
- kick add swagger # OpenAPI documentation
3027
- kick add ws # WebSocket support
3028
- kick add queue # Background job processing
3029
- kick add --list # Show all available packages
3030
- \`\`\`
3031
-
3032
- For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://forinda.github.io/kick-js/guide/) — they wire the upstream library through \`defineAdapter()\` / \`definePlugin()\` directly, so you keep control of the integration.
3033
-
3034
- ## Environment Variables
3035
-
3036
- Copy \`.env.example\` to \`.env\` and configure:
3037
-
3038
- | Variable | Default | Description |
3039
- |---|---|---|
3040
- | \`PORT\` | \`3000\` | Server port |
3041
- | \`NODE_ENV\` | \`development\` | Environment |
3042
-
3043
- ## Learn More
3044
-
3045
- - [KickJS Documentation](https://forinda.github.io/kick-js/)
3046
- - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
3047
- `;
3048
- }
3049
- /**
3050
- * Generate CLAUDE.md.
3051
- *
3052
- * v4 update: this file is intentionally thin. AGENTS.md is the
3053
- * canonical, multi-agent project reference (Claude / Copilot /
3054
- * Codex / Gemini / etc.) — duplicating it here meant two files
3055
- * drifting out of sync after every framework change. The generated
3056
- * CLAUDE.md now redirects there + adds Claude-specific affordances
3057
- * only.
3058
- */
3059
- function generateClaude(name, _template, pm) {
3060
- return `# CLAUDE.md — ${name}
3061
-
3062
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
3063
- reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
3064
- project conventions, structure, decorator patterns, env wiring, CLI
3065
- generators, every gotcha.
3066
-
3067
- **Then read \`./kickjs-skills.md\`.** That file is the task-oriented
3068
- skill index — short, rigid recipes keyed to triggers ("add-module",
3069
- "write-controller-test", "bootstrap-export", "deny-list", …). Use it
3070
- as the playbook when executing common KickJS workflows.
3071
-
3072
- This file is a thin Claude-specific layer on top of those two; when
3073
- they disagree on anything substantive, treat \`AGENTS.md\` as
3074
- authoritative and flag the discrepancy.
3075
-
3076
- ## Why two files
3077
-
3078
- \`AGENTS.md\` is what every agent reads. \`CLAUDE.md\` is what
3079
- Claude Code automatically loads as project context on each
3080
- conversation. Keeping CLAUDE.md slim avoids two files drifting; the
3081
- redirect above ensures Claude pulls the canonical content without
3082
- us copy-pasting.
3083
-
3084
- ## Claude-specific notes
3085
-
3086
- - **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
3087
- to refresh project memory if AGENTS.md changes substantially.
3088
- - **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
3089
- - **Persistent memory** — Claude maintains user/feedback/project/
3090
- reference memories under \`.claude/memory/\`. If you ask for
3091
- something that contradicts a remembered preference, Claude flags
3092
- it before acting; corrections update memory automatically.
3093
- - **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
3094
- or background work. Useful for "wait for the deploy then open a
3095
- cleanup PR" or "every Monday triage the issue board" patterns.
3096
-
3097
- ## Quick reference (full version in AGENTS.md)
3098
-
3099
- \`\`\`bash
3100
- ${pm} install # Install dependencies
3101
- kick dev # Dev server with HMR + typegen
3102
- kick build && kick start # Production
3103
- ${pm} run test # Vitest
3104
- ${pm} run typecheck # tsc --noEmit
3105
- ${pm} run format # Prettier
3106
- \`\`\`
3107
-
3108
- ## v4 framework reminders
3109
-
3110
- When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`AGENTS.md\`:
3111
-
3112
- - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
3113
- - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
3114
- - **DI tokens**: slash-delimited \`<scope>/<area>/<key>\` (e.g. \`'app/users/repository'\`). First-party uses the reserved \`'kick/'\` prefix; this project owns its own scope.
3115
- - **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
3116
- - **Module entry file** MUST be named \`<name>.module.ts\` and live under \`src/modules/<name>/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed \`projects.ts\` silently degrades every save into a full restart.
3117
- - **Env**: schema lives in \`src/config/index.ts\`; \`import './config'\` MUST be the first import in \`src/index.ts\` (side-effect registers the schema before any \`@Value\` resolves).
3118
- - **Assets**: drop new template files into \`src/templates/<namespace>/\`; the dev watcher auto-rebuilds the \`KickAssets\` augmentation + \`assets.x.y()\` re-walks on next call. No restart, no manual build.
3119
- - **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
3120
- - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
3121
- - **Bootstrap export**: \`src/index.ts\` must end with \`export const app = await bootstrap({ ... })\`. The Vite plugin and \`createTestApp\` import the named \`app\`; without the export, HMR silently degrades to full restarts.
3122
- - **Thin entry file**: aggregate \`modules\`, \`middleware\`, \`plugins\`, \`adapters\` in their own folders (\`src/modules/index.ts\`, \`src/middleware/index.ts\`, …) and pass them by name to \`bootstrap()\` — never inline the lists in \`src/index.ts\`.
3123
- - **Refresh these files**: \`kick g agents -f\` regenerates \`AGENTS.md\` + \`CLAUDE.md\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \`AGENTS.local.md\`.
3124
-
3125
- For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`AGENTS.md\`.
3126
- `;
3127
- }
3128
- /** Generate AGENTS.md with AI agent guide */
3129
- function generateAgents(name, template, pm) {
3130
- return `# AGENTS.md — AI Agent Guide for ${name}
3131
-
3132
- This guide is the **canonical, multi-agent reference** for this KickJS
3133
- application — Claude, Copilot, Codex, Gemini, etc. all read it first.
3134
- Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
3135
- add tool-specific affordances on top.
3136
-
3137
- ## Before You Start
3138
-
3139
- 1. Run \`${pm} install\` to install dependencies
3140
- 2. Run \`kick dev\` to verify the app starts
3141
- 3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
3142
-
3143
- ## v4 Conventions (don't skip)
3144
-
3145
- KickJS v4 made a handful of structural changes from v3. Internalise these
3146
- before generating or modifying code — they are the source of most agent
3147
- mistakes:
3148
-
3149
- - **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
3150
-
3151
- \`\`\`ts
3152
- export const MyAdapter = defineAdapter<MyOptions>({
3153
- name: 'MyAdapter',
3154
- defaults: { ... },
3155
- build: (config) => ({
3156
- beforeMount({ app }) { /* ... */ },
3157
- afterStart({ server }) { /* ... */ },
3158
- }),
3159
- })
3160
- \`\`\`
3161
-
3162
- - **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
3163
-
3164
- - **DI tokens** — slash-delimited \`<scope>/<area>/<key>\`, lower-case, no \`:\` separators:
3165
-
3166
- \`\`\`ts
3167
- const USERS_REPO = createToken<UsersRepo>('app/users/repository')
3168
- const DB = createToken<Database>('app/db/connection')
3169
- \`\`\`
3170
-
3171
- The \`kick/\` prefix is reserved for first-party packages; this project
3172
- owns its own scope (\`app/\`, your domain name, etc.).
3173
-
3174
- - **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
3175
- the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
3176
- is a v3 leftover; the linter and codegen reject it.
3177
-
3178
- - **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
3179
- side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
3180
- import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
3181
- returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
3182
- (Zod coercion + defaults silently skipped).
3183
-
3184
- - **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
3185
- HMR contract at the top of "Module Pattern" below. The CLI enforces this;
3186
- hand-rolled files must too.
3187
-
3188
- - **Assets** — drop new template files into \`src/templates/<namespace>/\`
3189
- (or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
3190
- \`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
3191
- no manual build step.
3192
-
3193
- - **Context over \`@Middleware()\`** — when a middleware's only job is to
3194
- populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
3195
- (HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
3196
- Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
3197
- Reserve \`@Middleware()\` for response short-circuit / stream mutation /
3198
- pre-route-matching work.
3199
-
3200
- Two ground rules around the data flow — both stem from the fact that
3201
- every per-request stage gets its OWN \`RequestContext\` instance, all
3202
- reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
3203
- - **\`resolve\` and \`onError\` must RETURN the value.** The runner
3204
- writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
3205
- property assignment (\`ctx.tenant = …\`) sticks to the contributor
3206
- instance only — the handler instance never sees it.
3207
- - **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
3208
- \`getRequestValue(key)\` from a service that has no \`ctx\` reference
3209
- — typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
3210
- Express request is shared; bespoke property assignments don't.
3211
-
3212
- - **Test isolation** — default to \`Container.create()\` for fresh DI state.
3213
- Never \`new Container()\` and never \`getInstance().reset()\` — both leak
3214
- registrations between tests.
3215
-
3216
- \`\`\`ts
3217
- const container = Container.create()
3218
- // ... register test-scoped providers, run, discard
3219
- \`\`\`
3220
-
3221
- - **Bootstrap export** — \`src/index.ts\` MUST end with
3222
- \`export const app = await bootstrap({ ... })\`. The Vite plugin imports
3223
- the named \`app\` symbol to drive HMR module swaps; testing helpers
3224
- (\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
3225
- the \`export\` and \`kick dev\` will silently fall back to a full restart
3226
- on every save while \`createTestApp\` complains about a missing handle.
3227
-
3228
- - **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
3229
- adapters in dedicated folders and re-export aggregated arrays. Do **not**
3230
- inline registration in the entry file:
3231
-
3232
- \`\`\`ts
3233
- // src/modules/index.ts
3234
- export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
3235
-
3236
- // src/middleware/index.ts
3237
- export const middleware = [helmet(), cors(), requestId(), ...]
3238
-
3239
- // src/plugins/index.ts
3240
- export const plugins = [MetricsPlugin(), AuditPlugin()]
3241
-
3242
- // src/adapters/index.ts
3243
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
3244
- \`\`\`
3245
-
3246
- \`\`\`ts
3247
- // src/index.ts — stays small; one import per category
3248
- import 'reflect-metadata'
3249
- import './config'
3250
- import { bootstrap } from '@forinda/kickjs'
3251
- import { modules } from './modules'
3252
- import { middleware } from './middleware'
3253
- import { plugins } from './plugins'
3254
- import { adapters } from './adapters'
3255
-
3256
- export const app = await bootstrap({ modules, middleware, plugins, adapters })
3257
- \`\`\`
3258
-
3259
- This keeps the entry file diff-friendly, scales to dozens of modules
3260
- without git churn, and lets each domain own its own registration list.
3261
- The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
3262
- \`kick g adapter\`) follow this layout — manual additions should too.
3263
-
3264
- Everything else (controllers, services, modules, RequestContext API, generators,
3265
- package additions, env access patterns, troubleshooting) is detailed below.
3266
-
3267
- ## Where to Find Things
3268
-
3269
- ### Application Structure
3270
-
3271
- | What | Where |
3272
- |------|-------|
3273
- | Entry point | \`src/index.ts\` |
3274
- | Module registry | \`src/modules/index.ts\` |
3275
- | Feature modules | \`src/modules/<module-name>/\` |
3276
- | **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
3277
- | Env values | \`.env\` |
3278
- | Env schema (Zod) | \`src/config/index.ts\` |
3279
- | TypeScript config | \`tsconfig.json\` |
3280
- | Vite config (HMR) | \`vite.config.ts\` |
3281
- | Vitest config | \`vitest.config.ts\` |
3282
- | Prettier config | \`.prettierrc\` |
3283
- | CLI config | \`kick.config.ts\` |
3284
-
3285
- ### Module Pattern (${template.toUpperCase()})
3286
-
3287
- > **Vite HMR auto-discovery contract:** module files **must** be named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and live under \`src/modules/\`. The Vite plugin scans for \`*.module.[tj]sx?\` to drive graceful HMR rebuilds; renaming a file to \`projects.ts\` (no \`.module\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\`kick g module <name>\`) follows the convention; manual files must too.
3288
-
3289
- Each module in \`src/modules/<name>/\` typically contains:
3290
-
3291
- ${template === "ddd" ? `\`\`\`
3292
- <name>/
3293
- ├── <name>.controller.ts # HTTP routes (@Controller)
3294
- ├── <name>.service.ts # Business logic (@Service)
3295
- ├── <name>.repository.ts # Data access (@Repository)
3296
- ├── <name>.dto.ts # Request/response schemas (Zod)
3297
- ├── <name>.entity.ts # Domain entity (optional)
3298
- └── <name>.module.ts # Module definition (implements AppModule)
3299
- \`\`\`
3300
- ` : template === "cqrs" ? `\`\`\`
3301
- <name>/
3302
- ├── commands/ # Write operations
3303
- │ ├── create-<name>.command.ts
3304
- │ └── create-<name>.handler.ts
3305
- ├── queries/ # Read operations
3306
- │ ├── get-<name>.query.ts
3307
- │ └── get-<name>.handler.ts
3308
- ├── events/ # Domain events
3309
- │ └── <name>-created.event.ts
3310
- ├── <name>.controller.ts # HTTP routes
3311
- ├── <name>.repository.ts # Data access
3312
- └── <name>.module.ts # Module definition (implements AppModule)
3313
- \`\`\`
3314
- ` : template === "rest" ? `\`\`\`
3315
- <name>/
3316
- ├── <name>.controller.ts # HTTP routes (@Controller)
3317
- ├── <name>.service.ts # Business logic (@Service)
3318
- ├── <name>.dto.ts # Request/response schemas (Zod)
3319
- └── <name>.module.ts # Module definition (implements AppModule)
3320
- \`\`\`
3321
- ` : `\`\`\`
3322
- src/
3323
- ├── index.ts # Add routes here
3324
- └── ... # Custom structure
3325
- \`\`\`
3326
- `}
3327
-
3328
- ## Checklist: Adding a Feature
3329
-
3330
- ### New Module (Recommended)
3331
-
3332
- Use the CLI generator for consistency:
3333
-
3334
- \`\`\`bash
3335
- kick g module <name> # Generate full module
3336
- # or
3337
- kick g scaffold <name> <fields> # Generate CRUD from fields
3338
- \`\`\`
3339
-
3340
- Then:
3341
- - [ ] Review generated files in \`src/modules/<name>/\`
3342
- - [ ] Verify module is registered in \`src/modules/index.ts\`
3343
- - [ ] Update DTOs in \`<name>.dto.ts\` if needed
3344
- - [ ] Implement business logic in \`<name>.service.ts\`
3345
- - [ ] Run \`kick dev\` to test with HMR
3346
- - [ ] Write tests in \`<name>.test.ts\`
3347
-
3348
- ### Manual Controller
3349
-
3350
- If not using generators:
3351
-
3352
- - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
3353
- - [ ] Add \`@Controller()\` decorator
3354
- - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
3355
- - [ ] Create module file implementing \`AppModule\` with \`routes()\` returning \`{ path, router: buildRoutes(Controller), controller }\`
3356
- - [ ] Register module in \`src/modules/index.ts\` (\`AppModuleClass[]\` array)
3357
- - [ ] Test with \`kick dev\`
3358
-
3359
- ### Manual Service
3360
-
3361
- - [ ] Create \`src/modules/<name>/<name>.service.ts\`
3362
- - [ ] Add \`@Service()\` decorator
3363
- - [ ] Inject dependencies with \`@Autowired()\`
3364
- - [ ] Inject via \`@Autowired()\` where needed
3365
- - [ ] Write unit tests
3366
-
3367
- ### New Middleware
3368
-
3369
- - [ ] Create \`src/middleware/<name>.middleware.ts\`
3370
- - [ ] Export middleware function (Express format)
3371
- - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
3372
- - [ ] Test with sample requests
3373
-
3374
- ### Adding a Package
3375
-
3376
- Use \`kick add\` to install KickJS packages with correct peer dependencies:
3377
-
3378
- - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
3379
- - [ ] Follow package-specific setup in terminal output
3380
- - [ ] Update \`src/index.ts\` to register adapter (if needed)
3381
- - [ ] Configure environment variables in \`.env\`
3382
- - [ ] Test integration with \`kick dev\`
3383
-
3384
- ## Common Tasks
3385
-
3386
- ### Generate CRUD Module
3387
-
3388
- \`\`\`bash
3389
- kick g scaffold user name:string email:string:optional age:number
3390
- \`\`\`
3391
-
3392
- Append \`:optional\` for optional fields (shell-safe, no quoting needed).
3393
- Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
3394
-
3395
- This creates a full CRUD module with:
3396
- - Controller with GET, POST, PUT, DELETE routes
3397
- - Service with business logic
3398
- - Repository with data access
3399
- - DTOs with Zod validation
3400
-
3401
- ### Add Authentication
3402
-
3403
- \`\`\`bash
3404
- kick add auth
3405
- \`\`\`
3406
-
3407
- Then configure in \`src/index.ts\`:
3408
-
3409
- \`\`\`ts
3410
- import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
3411
-
3412
- bootstrap({
3413
- modules,
3414
- adapters: [
3415
- AuthAdapter({
3416
- strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
3417
- }),
3418
- ],
3419
- })
3420
- \`\`\`
3421
-
3422
- ### Add Database (Prisma)
3423
-
3424
- \`\`\`bash
3425
- kick add prisma
3426
- ${pm} install prisma @prisma/client
3427
- npx prisma init
3428
- # Edit prisma/schema.prisma
3429
- npx prisma migrate dev --name init
3430
- kick g module user --repo prisma
3431
- \`\`\`
3432
-
3433
- ### Add WebSocket Support
3434
-
3435
- \`\`\`bash
3436
- kick add ws
3437
- \`\`\`
3438
-
3439
- Then add adapter in \`src/index.ts\`:
3440
-
3441
- \`\`\`ts
3442
- import { WsAdapter } from '@forinda/kickjs-ws'
3443
-
3444
- bootstrap({
3445
- modules,
3446
- adapters: [WsAdapter()],
3447
- })
3448
- \`\`\`
3449
-
3450
- Create WebSocket controller:
3451
-
3452
- \`\`\`bash
3453
- kick g controller chat --ws
3454
- \`\`\`
3455
-
3456
- ## Testing Guidelines
3457
-
3458
- All tests use Vitest:
3459
-
3460
- \`\`\`ts
3461
- import { describe, it, expect, beforeEach } from 'vitest'
3462
- import { Container } from '@forinda/kickjs'
3463
- import { createTestApp } from '@forinda/kickjs-testing'
3464
-
3465
- describe('UserController', () => {
3466
- it('should return users', async () => {
3467
- // Container.create() — isolated DI state per test, never new Container()
3468
- // and never getInstance().reset() (both leak registrations between tests).
3469
- const container = Container.create()
3470
- const app = await createTestApp([UserModule], { container })
3471
- const res = await app.get('/users')
3472
-
3473
- expect(res.status).toBe(200)
3474
- expect(res.body).toHaveProperty('users')
3475
- })
3476
- })
3477
- \`\`\`
3478
-
3479
- Run tests:
3480
- - \`${pm} run test\` — run all tests once
3481
- - \`${pm} run test:watch\` — watch mode
3482
- - Individual file: \`${pm} run test src/modules/user/user.test.ts\`
3483
-
3484
- ## Environment Variables
3485
-
3486
- Schema is declared in \`src/config/index.ts\` (extends the base
3487
- \`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
3488
- with kickjs at module load. \`src/index.ts\` imports it via
3489
- \`import './config'\` **before** \`bootstrap()\` so the cache is populated
3490
- in time for DI. Add new keys to the schema, drop their values into
3491
- \`.env\`, and they're typed everywhere.
3492
-
3493
- Access patterns:
3494
-
3495
- 1. **@Value() decorator** (recommended for known-at-construction keys):
3496
- \`\`\`ts
3497
- @Value('DATABASE_URL')
3498
- private dbUrl!: string
3499
- \`\`\`
3500
-
3501
- 2. **ConfigService** (recommended for dynamic / method-scoped access):
3502
- \`\`\`ts
3503
- @Autowired()
3504
- private config!: ConfigService
3505
-
3506
- const port = this.config.get('PORT') // typed: number
3507
- \`\`\`
3508
-
3509
- 3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
3510
- \`\`\`ts
3511
- import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
3512
-
3513
- const env = loadEnv(schema) // Parse + validate all vars
3514
- const port = getEnv('PORT') // Single value lookup
3515
- reloadEnv() // Re-read .env from disk
3516
- resetEnvCache() // Full reset (for tests)
3517
- \`\`\`
3518
-
3519
- 4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
3520
- coercion and the typed \`KickEnv\` registry.
3521
-
3522
- > **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
3523
- > If the schema is not registered before DI runs, \`config.get()\`
3524
- > returns \`undefined\` for user keys (the base shape only) and
3525
- > \`@Value()\` only works because of its raw \`process.env\` fallback —
3526
- > Zod coercion + schema defaults are silently skipped.
3527
-
3528
- ## Standalone Utilities (No DI Required)
3529
-
3530
- These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
3531
-
3532
- | Utility | Import | Example |
3533
- |---------|--------|---------|
3534
- | \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
3535
- | \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
3536
- | \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/db/url')\` |
3537
- | \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
3538
- | \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
3539
- | \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
3540
- | \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
3541
- | \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
3542
- | \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
3543
-
3544
- ## Key Decorators
3545
-
3546
- ### HTTP Routes
3547
- | Decorator | Purpose |
3548
- |-----------|---------|
3549
- | \`@Controller()\` | Define route prefix |
3550
- | \`@Get('/'), @Post('/')\` | HTTP method handlers |
3551
- | \`@Middleware(fn)\` | Attach middleware |
3552
- | \`@Public()\` | Skip auth (requires auth adapter) |
3553
- | \`@Roles('admin')\` | Role-based access |
3554
-
3555
- ### Dependency Injection
3556
- | Decorator | Purpose |
3557
- |-----------|---------|
3558
- | \`AppModule\` interface | Define feature module (implements \`routes()\`) |
3559
- | \`@Service()\` | Register singleton service |
3560
- | \`@Repository()\` | Register repository |
3561
- | \`@Autowired()\` | Property injection |
3562
- | \`@Inject('token')\` | Token-based injection |
3563
- | \`@Value('VAR')\` | Inject env variable |
3564
-
3565
- ### Context Decorators
3566
-
3567
- Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
3568
- Use this **instead of \`@Middleware()\`** when the middleware's only output
3569
- is a value other code reads off \`ctx\`.
3570
-
3571
- | Concept | Where it lives |
3572
- |---------|----------------|
3573
- | \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
3574
- | Method/class decorator | \`@LoadX\` on a controller method/class |
3575
- | Module hook | \`AppModule.contributors?(): ContributorRegistration[]\` |
3576
- | Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
3577
- | Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
3578
- | Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
3579
-
3580
- Precedence high → low: **method > class > module > adapter > global**.
3581
- Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
3582
- fast). The \`onError\` hook is async-permitted.
3583
-
3584
- Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
3585
-
3586
- ${template === "cqrs" ? `### Background Jobs
3587
- | Decorator | Purpose |
3588
- |-----------|---------|
3589
- | \`@Job('name')\` | Queue job handler |
3590
- | \`@Process('queue')\` | Queue processor |
3591
- | \`@Cron('0 * * * *')\` | Cron schedule |
3592
- | \`@WsController()\` | WebSocket controller |
3593
-
3594
- ` : ""}## Common Pitfalls
3595
-
3596
- 1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
3597
- 2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
3598
- 3. **Tests failing randomly** — Sharing the global container between tests. Default to \`Container.create()\` per test (or per \`beforeEach\`) instead of \`new Container()\` / \`getInstance().reset()\`
3599
- 4. **Routes not found** — Check controller path and module registration
3600
- 5. **HMR not working** — Two checks: (a) \`vite.config.ts\` has \`hmr: true\`; (b) module file is named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and lives under \`src/modules/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed module file (e.g., \`projects.ts\`) silently degrades to a full restart on every save.
3601
- 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
3602
- 7. **\`config.get('YOUR_KEY')\` returns \`undefined\`** — \`src/index.ts\` is missing \`import './config'\`. That side-effect import registers the env schema with kickjs (\`loadEnv(envSchema)\` runs at module load). Without it, \`ConfigService\` falls back to the base schema (\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` only) and every user-defined key reads as \`undefined\`. \`@Value()\` may *appear* to work because of a raw \`process.env\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \`src/index.ts\` and \`src/config/index.ts\` first.
3603
- 8. **Used \`@Middleware()\` to compute a value for \`ctx\`** — prefer \`defineContextDecorator()\` (see Context Decorators above). It's typed via \`ContextMeta\`, supports \`dependsOn\` for ordering, and validates the pipeline at boot. \`@Middleware()\` is for response short-circuiting, stream mutation, and pre-route-matching work.
3604
- 9. **Context contributor's \`dependsOn\` key not produced anywhere** — boot throws \`MissingContributorError\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).
3605
- 10. **\`bootstrap()\` not exported** — \`src/index.ts\` calls \`await bootstrap({ ... })\` but discards the return value (no \`export const app = ...\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \`createTestApp\`/\`@forinda/kickjs-testing\` consumers can't import the handle either. Always: \`export const app = await bootstrap({ ... })\`.
3606
- 11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \`kick g agents -f\` (or \`kick g agent-docs -f\`) to regenerate from the latest CLI templates after \`kick add\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \`AGENTS.local.md\`.
3607
-
3608
- ## CLI Commands Reference
3609
-
3610
- | Command | Description |
3611
- |---------|-------------|
3612
- | \`kick dev\` | Dev server with HMR |
3613
- | \`kick dev:debug\` | Dev server with debugger |
3614
- | \`kick build\` | Production build |
3615
- | \`kick start\` | Run production build |
3616
- | \`kick g module <names...>\` | Generate one or more modules |
3617
- | \`kick g scaffold <name> <fields>\` | Generate CRUD |
3618
- | \`kick g controller <name>\` | Generate controller |
3619
- | \`kick g service <name>\` | Generate service |
3620
- | \`kick g middleware <name>\` | Generate middleware |
3621
- | \`kick add <package>\` | Add KickJS package |
3622
- | \`kick add --list\` | List available packages |
3623
- | \`kick rm module <names...>\` | Remove one or more modules |
3624
-
3625
- > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
3626
- > \`\`\`bash
3627
- > kick new my-api -t ddd -r prisma --pm ${pm} --no-git --no-install -f
3628
- > \`\`\`
3629
-
3630
- ## Learn More
3631
-
3632
- - [KickJS Docs](https://forinda.github.io/kick-js/)
3633
- - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
3634
- - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
3635
- - [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
3636
- - [Testing](https://forinda.github.io/kick-js/api/testing.html)
3637
- `;
3638
- }
3639
- /**
3640
- * Generate `kickjs-skills.md` — task-oriented "skill" recipes for AI
3641
- * agents (Claude superpowers, Copilot, etc.). Where AGENTS.md is the
3642
- * narrative reference, this file lists short, rigid workflows the agent
3643
- * should follow when it sees the corresponding trigger.
3644
- */
3645
- function generateKickJsSkills(name, _template, pm) {
3646
- return `# kickjs-skills.md — Task Skills for AI Agents (${name})
3647
-
3648
- This file is the agent-facing **skills index** for KickJS work in this
3649
- repo. Each block below is a short, rigid workflow keyed to a specific
3650
- trigger ("user wants to add a module", "tests are leaking state", etc.).
3651
-
3652
- - Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
3653
- - Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
3654
- - **This file** → step-by-step recipes the agent should *execute*.
3655
-
3656
- Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
3657
-
3658
- ---
3659
-
3660
- ## Skill: add-module
3661
-
3662
- \`\`\`yaml
3663
- name: kickjs-add-module
3664
- description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
3665
- \`\`\`
3666
-
3667
- **Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
3668
-
3669
- **Steps**:
3670
- 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
3671
- 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
3672
- 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
3673
- 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
3674
- 5. Run \`${pm} run typecheck\` and \`${pm} run test\` before claiming done.
3675
-
3676
- **Red flags** (stop and ask):
3677
- - File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
3678
- - Module not registered in \`src/modules/index.ts\`.
3679
- - \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
3680
-
3681
- ---
3682
-
3683
- ## Skill: add-adapter
3684
-
3685
- \`\`\`yaml
3686
- name: kickjs-add-adapter
3687
- description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
3688
- \`\`\`
3689
-
3690
- **Steps**:
3691
- 1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
3692
- 2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
3693
- 3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
3694
- 4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
3695
- 5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
3696
-
3697
- **Red flags**:
3698
- - Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
3699
- - Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
3700
-
3701
- ---
3702
-
3703
- ## Skill: write-controller-test
3704
-
3705
- \`\`\`yaml
3706
- name: kickjs-write-controller-test
3707
- description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
3708
- \`\`\`
3709
-
3710
- **Template** (copy/paste, adjust):
3711
-
3712
- \`\`\`ts
3713
- import { describe, it, expect } from 'vitest'
3714
- import { Container } from '@forinda/kickjs'
3715
- import { createTestApp } from '@forinda/kickjs-testing'
3716
-
3717
- describe('UserController', () => {
3718
- it('returns users', async () => {
3719
- const container = Container.create() // isolated DI per test
3720
- const app = await createTestApp([UserModule], { container })
3721
- const res = await app.get('/users')
3722
- expect(res.status).toBe(200)
3723
- })
3724
- })
3725
- \`\`\`
3726
-
3727
- **Red flags**:
3728
- - \`new Container()\` — wrong; use \`Container.create()\`.
3729
- - \`Container.getInstance().reset()\` — wrong; same fix.
3730
- - Sharing a container across \`it()\` blocks — leaks registrations.
3731
-
3732
- ---
3733
-
3734
- ## Skill: env-wiring-check
3735
-
3736
- \`\`\`yaml
3737
- name: kickjs-env-wiring-check
3738
- description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
3739
- \`\`\`
3740
-
3741
- **Diagnosis**:
3742
- 1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
3743
- 2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
3744
- 3. The new key MUST be declared in the Zod schema there. \`@Value('NEW_KEY')\` won't work without a schema entry (it'll fall back to raw \`process.env\` and skip Zod coercion silently).
3745
-
3746
- **Fix**: add the key to the schema; ensure both side-effect imports above are present.
3747
-
3748
- ---
3749
-
3750
- ## Skill: bootstrap-export
3751
-
3752
- \`\`\`yaml
3753
- name: kickjs-bootstrap-export
3754
- description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
3755
- \`\`\`
3756
-
3757
- **Check** \`src/index.ts\`'s last line:
3758
-
3759
- \`\`\`ts
3760
- // CORRECT
3761
- export const app = await bootstrap({ ... })
3762
-
3763
- // WRONG (HMR degrades to full restart, createTestApp loses the handle)
3764
- await bootstrap({ ... })
3765
- \`\`\`
3766
-
3767
- The Vite plugin imports the named \`app\` symbol; testing helpers do too.
3768
-
3769
- ---
3770
-
3771
- ## Skill: thin-entry-file
3772
-
3773
- \`\`\`yaml
3774
- name: kickjs-thin-entry-file
3775
- description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
3776
- \`\`\`
3777
-
3778
- **Refactor target**:
3779
-
3780
- \`\`\`ts
3781
- // src/modules/index.ts
3782
- export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
3783
-
3784
- // src/middleware/index.ts
3785
- export const middleware = [helmet(), cors(), requestId(), ...]
3786
-
3787
- // src/plugins/index.ts
3788
- export const plugins = [MetricsPlugin(), ...]
3789
-
3790
- // src/adapters/index.ts
3791
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
3792
-
3793
- // src/index.ts — stays small
3794
- import 'reflect-metadata'
3795
- import './config'
3796
- import { bootstrap } from '@forinda/kickjs'
3797
- import { modules } from './modules'
3798
- import { middleware } from './middleware'
3799
- import { plugins } from './plugins'
3800
- import { adapters } from './adapters'
3801
- export const app = await bootstrap({ modules, middleware, plugins, adapters })
3802
- \`\`\`
3803
-
3804
- **Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
3805
-
3806
- ---
3807
-
3808
- ## Skill: context-contributor
3809
-
3810
- \`\`\`yaml
3811
- name: kickjs-context-contributor
3812
- description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
3813
- \`\`\`
3814
-
3815
- **Pattern** (HTTP — most common):
3816
-
3817
- \`\`\`ts
3818
- import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
3819
-
3820
- const LoadTenant = defineHttpContextDecorator({
3821
- key: 'tenant',
3822
- deps: { repo: TENANT_REPO },
3823
- resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
3824
- })
3825
-
3826
- const LoadProject = defineHttpContextDecorator({
3827
- key: 'project',
3828
- dependsOn: ['tenant'],
3829
- resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
3830
- })
3831
-
3832
- @LoadTenant
3833
- @LoadProject
3834
- @Get('/projects/:id')
3835
- getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
3836
- \`\`\`
3837
-
3838
- Use \`defineContextDecorator\` (no Http prefix) when authoring a contributor that must run across HTTP, WebSocket, queue, and cron transports — \`Ctx\` defaults to the smaller \`ExecutionContext\` surface (\`get\` / \`set\` / \`requestId\` only, no \`req\`).
3839
-
3840
- Precedence high → low: **method > class > module > adapter > global**.
3841
- Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
3842
-
3843
- **Critical rules — all stem from the same shared-via-ALS instance model**:
3844
- - Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
3845
- - **\`resolve\` and \`onError\` must RETURN the value** — the runner writes it via \`ctx.set(key, value)\`. Direct property assignment (\`ctx.tenant = …\`) sticks to one instance only and the handler instance never sees it.
3846
- - \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
3847
- - Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
3848
- - **No \`setRequestValue\` — writes flow through \`ctx.set\` or a contributor's return value.** Avoids "spooky action at a distance" where any service can pollute the per-request bag.
3849
-
3850
- **Don't use this for**: response short-circuit, stream mutation, or
3851
- pre-route-matching work — keep \`@Middleware()\` for those.
3852
-
3853
- ---
3854
-
3855
- ## Skill: refresh-agent-docs
3856
-
3857
- \`\`\`yaml
3858
- name: kickjs-refresh-agent-docs
3859
- description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
3860
- \`\`\`
3861
-
3862
- **Steps**:
3863
- 1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
3864
- 2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
3865
- 3. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate \`AGENTS.local.md\` or appended section.
3866
- 4. Commit as \`docs(agents): sync from CLI vX.Y\`.
3867
-
3868
- ---
3869
-
3870
- ## Skill: deny-list
3871
-
3872
- \`\`\`yaml
3873
- name: kickjs-deny-list
3874
- description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
3875
- \`\`\`
3876
-
3877
- - \`class implements AppAdapter\` → use \`defineAdapter()\`.
3878
- - \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
3879
- - \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
3880
- - \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
3881
- - DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
3882
- - \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
3883
- - Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
3884
-
3885
- ---
3886
-
3887
- ## Learn More
3888
-
3889
- - [KickJS Docs](https://forinda.github.io/kick-js/)
3890
- - [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
3891
- - [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
3892
- - [Testing](https://forinda.github.io/kick-js/api/testing.html)
3893
- `;
3894
- }
3895
- //#endregion
3896
- //#region src/generators/project.ts
3897
- const __dirname = dirname(fileURLToPath(import.meta.url));
3898
- const cliPkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8"));
3899
- const KICKJS_VERSION = `^${cliPkg.version}`;
3900
- /** Scaffold a new KickJS project */
3901
- async function initProject(options) {
3902
- const { name, directory, packageManager = "pnpm", template = "rest", defaultRepo = "inmemory", packages = [] } = options;
3903
- const dir = directory;
3904
- const log = (msg) => console.log(` ${msg}`);
3905
- console.log(`\n Creating KickJS project: ${name}\n`);
3906
- await writeFileSafe(join(dir, "package.json"), generatePackageJson(name, template, KICKJS_VERSION, packages));
3907
- await writeFileSafe(join(dir, "vite.config.ts"), generateViteConfig());
3908
- await writeFileSafe(join(dir, "tsconfig.json"), generateTsConfig());
3909
- await writeFileSafe(join(dir, ".prettierrc"), generatePrettierConfig());
3910
- await writeFileSafe(join(dir, ".editorconfig"), generateEditorConfig());
3911
- await writeFileSafe(join(dir, ".gitignore"), generateGitIgnore());
3912
- await writeFileSafe(join(dir, ".gitattributes"), generateGitAttributes());
3913
- await writeFileSafe(join(dir, ".env"), generateEnv());
3914
- await writeFileSafe(join(dir, ".env.example"), generateEnvExample());
3915
- await writeFileSafe(join(dir, "src/config/index.ts"), generateEnvFile());
3916
- await writeFileSafe(join(dir, "src/index.ts"), generateEntryFile(name, template, cliPkg.version, packages));
3917
- await writeFileSafe(join(dir, "src/modules/index.ts"), generateModulesIndex());
3918
- await writeFileSafe(join(dir, "src/modules/hello/hello.service.ts"), generateHelloService());
3919
- await writeFileSafe(join(dir, "src/modules/hello/hello.controller.ts"), generateHelloController());
3920
- await writeFileSafe(join(dir, "src/modules/hello/hello.module.ts"), generateHelloModule());
3921
- await writeFileSafe(join(dir, "kick.config.ts"), generateKickConfig(template, defaultRepo, packageManager));
3922
- await writeFileSafe(join(dir, "vitest.config.ts"), generateVitestConfig());
3923
- await writeFileSafe(join(dir, "README.md"), generateReadme(name, template, packageManager));
3924
- await writeFileSafe(join(dir, "CLAUDE.md"), generateClaude(name, template, packageManager));
3925
- await writeFileSafe(join(dir, "AGENTS.md"), generateAgents(name, template, packageManager));
3926
- await writeFileSafe(join(dir, "kickjs-skills.md"), generateKickJsSkills(name, template, packageManager));
3927
- if (options.installDeps) {
3928
- console.log(`\n Installing dependencies with ${packageManager}...\n`);
3929
- try {
3930
- execSync(`${packageManager} install`, {
3931
- cwd: dir,
3932
- stdio: "inherit"
3933
- });
3934
- console.log("\n Dependencies installed successfully!");
3935
- } catch {
3936
- console.log(`\n Warning: ${packageManager} install failed. Run it manually.`);
3937
- }
3938
- }
3939
- try {
3940
- const { runTypegen } = await import("./typegen-D8MJ2hPX.mjs");
3941
- await runTypegen({
3942
- cwd: dir,
3943
- allowDuplicates: true,
3944
- silent: true
3945
- });
3946
- } catch {}
3947
- if (options.initGit) try {
3948
- execSync("git init", {
3949
- cwd: dir,
3950
- stdio: "pipe"
3951
- });
3952
- execSync("git branch -M main", {
3953
- cwd: dir,
3954
- stdio: "pipe"
3955
- });
3956
- execSync("git add -A", {
3957
- cwd: dir,
3958
- stdio: "pipe"
3959
- });
3960
- execSync("git commit -m \"chore: initial commit from kick new\"", {
3961
- cwd: dir,
3962
- stdio: "pipe"
3963
- });
3964
- log("Git repository initialized");
3965
- } catch {
3966
- log("Warning: git init failed (git may not be installed)");
3967
- }
3968
- console.log("\n Project scaffolded successfully!");
3969
- console.log();
3970
- const needsCd = dir !== process.cwd();
3971
- log("Next steps:");
3972
- if (needsCd) log(` cd ${name}`);
3973
- if (!options.installDeps) log(` ${packageManager} install`);
3974
- const genHint = {
3975
- rest: "kick g module user",
3976
- ddd: "kick g module user --repo drizzle",
3977
- cqrs: "kick g module user --pattern cqrs",
3978
- minimal: "# add your routes to src/index.ts"
3979
- };
3980
- log(` ${genHint[template] ?? genHint.rest}`);
3981
- log(" kick dev");
3982
- log("");
3983
- log("Commands:");
3984
- log(" kick dev Start dev server with Vite HMR");
3985
- log(" kick build Production build via Vite");
3986
- log(" kick start Run production build");
3987
- log("");
3988
- log("Generators:");
3989
- log(" kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)");
3990
- log(" kick g scaffold <n> <f..> CRUD module from field definitions");
3991
- log(" kick g controller <name> Standalone controller");
3992
- log(" kick g service <name> @Service() class");
3993
- log(" kick g middleware <name> Express middleware");
3994
- log(" kick g guard <name> Route guard (auth, roles, etc.)");
3995
- log(" kick g adapter <name> AppAdapter with lifecycle hooks");
3996
- log(" kick g dto <name> Zod DTO schema");
3997
- if (template === "cqrs") log(" kick g job <name> Queue job processor");
3998
- log(" kick g config Generate kick.config.ts");
3999
- log("");
4000
- log("Add packages:");
4001
- log(" kick add <pkg> Install a KickJS package + peers");
4002
- log(" kick add --list Show all available packages");
4003
- log("");
4004
- log("Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing");
4005
- log("");
4006
- }
4007
- //#endregion
4008
- //#region src/config.ts
4009
- /** Helper to define a type-safe kick.config.ts */
4010
- function defineConfig(config) {
4011
- return config;
4012
- }
4013
- const CONFIG_FILES = [
4014
- "kick.config.ts",
4015
- "kick.config.js",
4016
- "kick.config.mjs",
4017
- "kick.config.json"
4018
- ];
4019
- /** Load kick.config.* from the project root */
4020
- async function loadKickConfig(cwd) {
4021
- for (const filename of CONFIG_FILES) {
4022
- const filepath = join(cwd, filename);
4023
- try {
4024
- await access(filepath);
4025
- } catch {
4026
- continue;
4027
- }
4028
- if (filename.endsWith(".json")) {
4029
- const content = await readFile(filepath, "utf-8");
4030
- return JSON.parse(content);
4031
- }
4032
- try {
4033
- const { pathToFileURL } = await import("node:url");
4034
- const mod = await import(pathToFileURL(filepath).href);
4035
- const config = mod.default ?? mod;
4036
- const warnings = validateAssetMap(config, cwd);
4037
- for (const warning of warnings) console.warn(` Warning: ${warning}`);
4038
- return config;
4039
- } catch (err) {
4040
- if (filename.endsWith(".ts")) console.warn(`Warning: Failed to load ${filename}. TypeScript config files require a runtime loader (e.g. tsx, ts-node) or use kick.config.js/.mjs instead.`);
4041
- continue;
4042
- }
4043
- }
4044
- return null;
4045
- }
4046
- /**
4047
- * Validate `assetMap` entries on a loaded config. Returns a list of
4048
- * human-readable warnings; the caller decides how to surface them
4049
- * (typically `console.warn`). Never throws — `kick g` and other
4050
- * unrelated commands should keep working even when the assetMap is
4051
- * misconfigured.
4052
- *
4053
- * Checks:
4054
- *
4055
- * - Each entry's `src` is a non-empty string.
4056
- * - The `src` directory exists on disk (otherwise the typegen + build
4057
- * steps will fail later with cryptic errors).
4058
- * - `dest` doesn't escape the project root (defensive — a `dest:
4059
- * '../../etc'` typo could write files outside the workspace).
4060
- * - The namespace key is a non-empty string and doesn't include a
4061
- * `/` (would conflict with the `<namespace>/<key>` manifest format).
4062
- */
4063
- function validateAssetMap(config, cwd) {
4064
- const warnings = [];
4065
- if (!config?.assetMap) return warnings;
4066
- const root = resolve(cwd);
4067
- for (const [namespace, entry] of Object.entries(config.assetMap)) {
4068
- if (!namespace || namespace.includes("/")) {
4069
- warnings.push(`assetMap key '${namespace}' is invalid — must be a non-empty string without '/'`);
4070
- continue;
4071
- }
4072
- if (typeof entry?.src !== "string" || entry.src.length === 0) {
4073
- warnings.push(`assetMap.${namespace} is missing a non-empty 'src' field`);
4074
- continue;
4075
- }
4076
- if (!existsSync(resolve(cwd, entry.src))) warnings.push(`assetMap.${namespace}.src ('${entry.src}') does not exist — typegen + build will fail`);
4077
- if (entry.dest) {
4078
- if (escapesRoot(resolve(cwd, entry.dest), root)) warnings.push(`assetMap.${namespace}.dest ('${entry.dest}') resolves outside the project root — refusing to copy`);
4079
- }
4080
- }
4081
- return warnings;
4082
- }
4083
- /**
4084
- * Returns true when `path` (absolute) resolves outside of `root`
4085
- * (also absolute). Uses `path.relative` for accuracy:
4086
- *
4087
- * - The result is empty when paths are identical (inside).
4088
- * - It starts with `..` when the path traverses outside the root.
4089
- * - It's absolute (Windows: cross-drive) when there's no relative
4090
- * path between them.
4091
- *
4092
- * Avoids the prefix-match pitfalls of `startsWith` (e.g. `/app`
4093
- * matching `/app2/...`, or case-mismatches on macOS / Windows).
4094
- */
4095
- function escapesRoot(path, root) {
4096
- const rel = relative(root, path);
4097
- return rel === "" ? false : rel.startsWith("..") || isAbsolute(rel);
4098
- }
4099
- //#endregion
4100
- //#region src/generator-extension/define.ts
4101
- /**
4102
- * Identity factory — returns the spec verbatim. Exists for type
4103
- * inference and forward-compatibility (future fields can be added with
4104
- * defaults).
4105
- *
4106
- * @example
4107
- * ```ts
4108
- * import { defineGenerator } from '@forinda/kickjs-cli'
4109
- *
4110
- * export default [
4111
- * defineGenerator({
4112
- * name: 'command',
4113
- * description: 'Generate a CQRS command + handler',
4114
- * files: (ctx) => [
4115
- * {
4116
- * path: `src/modules/${ctx.kebab}/commands/${ctx.kebab}.command.ts`,
4117
- * content: `// command for ${ctx.pascal}`,
4118
- * },
4119
- * ],
4120
- * }),
4121
- * ]
4122
- * ```
4123
- */
4124
- function defineGenerator(spec) {
4125
- return spec;
4126
- }
4127
- //#endregion
4128
- //#region src/generator-extension/context.ts
4129
- /** Convert any string to snake_case (`UserPost` / `user-post` → `user_post`). */
4130
- function toSnakeCase(name) {
4131
- return toKebabCase(name).replace(/-/g, "_");
4132
- }
4133
- /**
4134
- * Build a {@link GeneratorContext} from the raw name + invocation
4135
- * arguments. Centralises the case-transformation logic so every plugin
4136
- * generator sees the same shape regardless of how the name was typed
4137
- * on the command line (`Post` vs `post` vs `user_post`).
4138
- */
4139
- function buildGeneratorContext(input) {
4140
- const cwd = input.cwd ?? process.cwd();
4141
- const usePlural = input.pluralize ?? true;
4142
- const pascal = toPascalCase(input.name);
4143
- const camel = toCamelCase(input.name);
4144
- const kebab = toKebabCase(input.name);
4145
- const snake = toSnakeCase(input.name);
4146
- const ctx = {
4147
- name: input.name,
4148
- pascal,
4149
- camel,
4150
- kebab,
4151
- snake,
4152
- modulesDir: input.modulesDir ?? "src/modules",
4153
- cwd,
4154
- args: input.args ?? [],
4155
- flags: input.flags ?? {}
4156
- };
4157
- if (usePlural) {
4158
- const pluralKebab = pluralize(kebab);
4159
- ctx.pluralKebab = pluralKebab;
4160
- ctx.pluralPascal = toPascalCase(pluralKebab);
4161
- ctx.pluralCamel = toCamelCase(pluralKebab);
4162
- }
4163
- return ctx;
4164
- }
4165
- //#endregion
4166
- export { buildGeneratorContext, defineConfig, defineGenerator, generateAdapter, generateController, generateDto, generateGuard, generateMiddleware, generateModule, generateService, initProject, loadKickConfig, pluralize, toCamelCase, toKebabCase, toPascalCase };
4167
-
4168
- //# sourceMappingURL=index.mjs.map
11
+ import { _ as pluralize, a as initProject, b as toKebabCase, d as generateService, f as generateGuard, h as generateModule, i as defineGenerator, l as generateDto, m as generateAdapter, p as generateMiddleware, r as buildGeneratorContext, u as generateController, x as toPascalCase, y as toCamelCase } from "./generator-extension-DRNQpoZP.mjs";
12
+ import { i as loadKickConfig, r as defineConfig } from "./config-DDrgs-I3.mjs";
13
+ import { n as defineCliPlugin, t as KickPluginConflictError } from "./types-CGB8BiQh.mjs";
14
+ export { KickPluginConflictError, buildGeneratorContext, defineCliPlugin, defineConfig, defineGenerator, generateAdapter, generateController, generateDto, generateGuard, generateMiddleware, generateModule, generateService, initProject, loadKickConfig, pluralize, toCamelCase, toKebabCase, toPascalCase };