@forinda/kickjs-cli 2.0.1 → 2.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.
Files changed (118) hide show
  1. package/bin.js +8 -0
  2. package/dist/cli.mjs +6550 -0
  3. package/dist/index.d.mts +302 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +3627 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/typegen-DCnJdqP1.mjs +886 -0
  8. package/dist/typegen-DCnJdqP1.mjs.map +1 -0
  9. package/package.json +31 -13
  10. package/dist/cli.d.ts +0 -2
  11. package/dist/cli.d.ts.map +0 -1
  12. package/dist/cli.js +0 -1552
  13. package/dist/commands/add.d.ts +0 -5
  14. package/dist/commands/add.d.ts.map +0 -1
  15. package/dist/commands/custom.d.ts +0 -56
  16. package/dist/commands/custom.d.ts.map +0 -1
  17. package/dist/commands/generate.d.ts +0 -3
  18. package/dist/commands/generate.d.ts.map +0 -1
  19. package/dist/commands/info.d.ts +0 -3
  20. package/dist/commands/info.d.ts.map +0 -1
  21. package/dist/commands/init.d.ts +0 -3
  22. package/dist/commands/init.d.ts.map +0 -1
  23. package/dist/commands/inspect.d.ts +0 -3
  24. package/dist/commands/inspect.d.ts.map +0 -1
  25. package/dist/commands/remove.d.ts +0 -3
  26. package/dist/commands/remove.d.ts.map +0 -1
  27. package/dist/commands/run.d.ts +0 -3
  28. package/dist/commands/run.d.ts.map +0 -1
  29. package/dist/commands/tinker.d.ts +0 -3
  30. package/dist/commands/tinker.d.ts.map +0 -1
  31. package/dist/config-D9faxBLQ.js +0 -3108
  32. package/dist/config.d.ts +0 -131
  33. package/dist/config.d.ts.map +0 -1
  34. package/dist/generators/adapter.d.ts +0 -7
  35. package/dist/generators/adapter.d.ts.map +0 -1
  36. package/dist/generators/config.d.ts +0 -9
  37. package/dist/generators/config.d.ts.map +0 -1
  38. package/dist/generators/controller.d.ts +0 -11
  39. package/dist/generators/controller.d.ts.map +0 -1
  40. package/dist/generators/dto.d.ts +0 -11
  41. package/dist/generators/dto.d.ts.map +0 -1
  42. package/dist/generators/guard.d.ts +0 -11
  43. package/dist/generators/guard.d.ts.map +0 -1
  44. package/dist/generators/job.d.ts +0 -8
  45. package/dist/generators/job.d.ts.map +0 -1
  46. package/dist/generators/middleware.d.ts +0 -11
  47. package/dist/generators/middleware.d.ts.map +0 -1
  48. package/dist/generators/module.d.ts +0 -33
  49. package/dist/generators/module.d.ts.map +0 -1
  50. package/dist/generators/patterns/cqrs.d.ts +0 -3
  51. package/dist/generators/patterns/cqrs.d.ts.map +0 -1
  52. package/dist/generators/patterns/ddd.d.ts +0 -3
  53. package/dist/generators/patterns/ddd.d.ts.map +0 -1
  54. package/dist/generators/patterns/index.d.ts +0 -6
  55. package/dist/generators/patterns/index.d.ts.map +0 -1
  56. package/dist/generators/patterns/minimal.d.ts +0 -3
  57. package/dist/generators/patterns/minimal.d.ts.map +0 -1
  58. package/dist/generators/patterns/rest.d.ts +0 -3
  59. package/dist/generators/patterns/rest.d.ts.map +0 -1
  60. package/dist/generators/patterns/types.d.ts +0 -15
  61. package/dist/generators/patterns/types.d.ts.map +0 -1
  62. package/dist/generators/project.d.ts +0 -14
  63. package/dist/generators/project.d.ts.map +0 -1
  64. package/dist/generators/remove-module.d.ts +0 -12
  65. package/dist/generators/remove-module.d.ts.map +0 -1
  66. package/dist/generators/resolver.d.ts +0 -7
  67. package/dist/generators/resolver.d.ts.map +0 -1
  68. package/dist/generators/scaffold.d.ts +0 -20
  69. package/dist/generators/scaffold.d.ts.map +0 -1
  70. package/dist/generators/service.d.ts +0 -11
  71. package/dist/generators/service.d.ts.map +0 -1
  72. package/dist/generators/templates/constants.d.ts +0 -3
  73. package/dist/generators/templates/constants.d.ts.map +0 -1
  74. package/dist/generators/templates/controller.d.ts +0 -6
  75. package/dist/generators/templates/controller.d.ts.map +0 -1
  76. package/dist/generators/templates/cqrs.d.ts +0 -23
  77. package/dist/generators/templates/cqrs.d.ts.map +0 -1
  78. package/dist/generators/templates/domain.d.ts +0 -5
  79. package/dist/generators/templates/domain.d.ts.map +0 -1
  80. package/dist/generators/templates/drizzle/index.d.ts +0 -4
  81. package/dist/generators/templates/drizzle/index.d.ts.map +0 -1
  82. package/dist/generators/templates/dtos.d.ts +0 -5
  83. package/dist/generators/templates/dtos.d.ts.map +0 -1
  84. package/dist/generators/templates/index.d.ts +0 -14
  85. package/dist/generators/templates/index.d.ts.map +0 -1
  86. package/dist/generators/templates/module-index.d.ts +0 -13
  87. package/dist/generators/templates/module-index.d.ts.map +0 -1
  88. package/dist/generators/templates/prisma/index.d.ts +0 -3
  89. package/dist/generators/templates/prisma/index.d.ts.map +0 -1
  90. package/dist/generators/templates/project-app.d.ts +0 -9
  91. package/dist/generators/templates/project-app.d.ts.map +0 -1
  92. package/dist/generators/templates/project-config.d.ts +0 -23
  93. package/dist/generators/templates/project-config.d.ts.map +0 -1
  94. package/dist/generators/templates/project-docs.d.ts +0 -9
  95. package/dist/generators/templates/project-docs.d.ts.map +0 -1
  96. package/dist/generators/templates/repository.d.ts +0 -5
  97. package/dist/generators/templates/repository.d.ts.map +0 -1
  98. package/dist/generators/templates/rest-service.d.ts +0 -6
  99. package/dist/generators/templates/rest-service.d.ts.map +0 -1
  100. package/dist/generators/templates/tests.d.ts +0 -4
  101. package/dist/generators/templates/tests.d.ts.map +0 -1
  102. package/dist/generators/templates/types.d.ts +0 -20
  103. package/dist/generators/templates/types.d.ts.map +0 -1
  104. package/dist/generators/templates/use-cases.d.ts +0 -6
  105. package/dist/generators/templates/use-cases.d.ts.map +0 -1
  106. package/dist/generators/test.d.ts +0 -9
  107. package/dist/generators/test.d.ts.map +0 -1
  108. package/dist/index.d.ts +0 -12
  109. package/dist/index.d.ts.map +0 -1
  110. package/dist/index.js +0 -17
  111. package/dist/utils/fs.d.ts +0 -11
  112. package/dist/utils/fs.d.ts.map +0 -1
  113. package/dist/utils/naming.d.ts +0 -18
  114. package/dist/utils/naming.d.ts.map +0 -1
  115. package/dist/utils/resolve-out-dir.d.ts +0 -25
  116. package/dist/utils/resolve-out-dir.d.ts.map +0 -1
  117. package/dist/utils/shell.d.ts +0 -3
  118. package/dist/utils/shell.d.ts.map +0 -1
@@ -1,3108 +0,0 @@
1
- import { dirname as Q, join as p, resolve as P } from "node:path";
2
- import { createInterface as ee } from "node:readline";
3
- import { access as F, mkdir as te, readFile as L, writeFile as N } from "node:fs/promises";
4
- import { execSync as R } from "node:child_process";
5
- import { readFileSync as re } from "node:fs";
6
- import { fileURLToPath as oe } from "node:url";
7
- var W = !1;
8
- function st(r) {
9
- W = r;
10
- }
11
- async function l(r, e) {
12
- W || (await te(Q(r), { recursive: !0 }), await N(r, e, "utf-8"));
13
- }
14
- async function B(r) {
15
- try {
16
- return await F(r), !0;
17
- } catch {
18
- return !1;
19
- }
20
- }
21
- function g(r) {
22
- return r.replace(/[-_\s]+(.)?/g, (e, t) => t ? t.toUpperCase() : "").replace(/^(.)/, (e) => e.toUpperCase());
23
- }
24
- function T(r) {
25
- const e = g(r);
26
- return e.charAt(0).toLowerCase() + e.slice(1);
27
- }
28
- function y(r) {
29
- return r.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
30
- }
31
- function Y(r) {
32
- return r.endsWith("s") ? r : r.endsWith("x") || r.endsWith("z") || r.endsWith("sh") || r.endsWith("ch") ? r + "es" : r.endsWith("y") && !/[aeiou]y$/.test(r) ? r.slice(0, -1) + "ies" : r + "s";
33
- }
34
- function se(r) {
35
- return r.endsWith("s") ? r : r.endsWith("x") || r.endsWith("z") || r.endsWith("sh") || r.endsWith("ch") ? r + "es" : r.endsWith("y") && !/[aeiou]y$/i.test(r) ? r.slice(0, -1) + "ies" : r + "s";
36
- }
37
- var ie = {
38
- inmemory: "in-memory",
39
- drizzle: "Drizzle",
40
- prisma: "Prisma"
41
- };
42
- function H(r) {
43
- return r.charAt(0).toUpperCase() + r.slice(1).replace(/-([a-z])/g, (e, t) => t.toUpperCase());
44
- }
45
- function ae(r) {
46
- return r.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
47
- }
48
- function _(r) {
49
- return ie[r] ?? H(r);
50
- }
51
- function K(r, e, t) {
52
- const o = {
53
- inmemory: `InMemory${r}Repository`,
54
- drizzle: `Drizzle${r}Repository`,
55
- prisma: `Prisma${r}Repository`
56
- }, s = {
57
- inmemory: `in-memory-${e}`,
58
- drizzle: `drizzle-${e}`,
59
- prisma: `prisma-${e}`
60
- };
61
- return {
62
- repoClass: o[t] ?? `${H(t)}${r}Repository`,
63
- repoFile: s[t] ?? `${ae(t)}-${e}`
64
- };
65
- }
66
- function ne(r) {
67
- const { pascal: e, kebab: t, plural: o = "", repo: s } = r, { repoClass: i, repoFile: n } = K(e, t, s);
68
- return `/**
69
- * ${e} Module
70
- *
71
- * Self-contained feature module following Domain-Driven Design (DDD).
72
- * Registers dependencies in the DI container and declares HTTP routes.
73
- *
74
- * Structure:
75
- * presentation/ — HTTP controllers (entry points)
76
- * application/ — Use cases (orchestration) and DTOs (validation)
77
- * domain/ — Entities, value objects, repository interfaces, domain services
78
- * infrastructure/ — Repository implementations (currently ${_(s)})
79
- */
80
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
81
- import { buildRoutes } from '@forinda/kickjs'
82
- import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
83
- import { ${i} } from './infrastructure/repositories/${n}.repository'
84
- import { ${e}Controller } from './presentation/${t}.controller'
85
-
86
- // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
87
- import.meta.glob(
88
- ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
89
- { eager: true },
90
- )
91
-
92
- export class ${e}Module implements AppModule {
93
- /**
94
- * Register module dependencies in the DI container.
95
- * Bind repository interface tokens to their implementations here.
96
- * Currently wired to ${_(s)}. To swap implementations, change the factory target.
97
- */
98
- register(container: Container): void {
99
- container.registerFactory(${e.toUpperCase()}_REPOSITORY, () =>
100
- container.resolve(${i}),
101
- )
102
- }
103
-
104
- /**
105
- * Declare HTTP routes for this module.
106
- * The path is prefixed with the global apiPrefix and version (e.g. /api/v1/${o}).
107
- * Passing 'controller' enables automatic OpenAPI spec generation via SwaggerAdapter.
108
- */
109
- routes(): ModuleRoutes {
110
- return {
111
- path: '/${o}',
112
- router: buildRoutes(${e}Controller),
113
- controller: ${e}Controller,
114
- }
115
- }
116
- }
117
- `;
118
- }
119
- function ce(r) {
120
- const { pascal: e, kebab: t, plural: o = "", repo: s } = r, { repoClass: i, repoFile: n } = K(e, t, s);
121
- return `/**
122
- * ${e} Module
123
- *
124
- * REST module with a flat folder structure.
125
- * Controller delegates to service, service wraps the repository.
126
- *
127
- * Structure:
128
- * ${t}.controller.ts — HTTP routes (CRUD)
129
- * ${t}.service.ts — Business logic
130
- * ${t}.repository.ts — Repository interface
131
- * ${n}.repository.ts — Repository implementation
132
- * dtos/ — Request/response schemas
133
- */
134
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
135
- import { buildRoutes } from '@forinda/kickjs'
136
- import { ${e.toUpperCase()}_REPOSITORY } from './${t}.repository'
137
- import { ${i} } from './${n}.repository'
138
- import { ${e}Controller } from './${t}.controller'
139
-
140
- // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
141
- import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })
142
-
143
- export class ${e}Module implements AppModule {
144
- register(container: Container): void {
145
- container.registerFactory(${e.toUpperCase()}_REPOSITORY, () =>
146
- container.resolve(${i}),
147
- )
148
- }
149
-
150
- routes(): ModuleRoutes {
151
- return {
152
- path: '/${o}',
153
- router: buildRoutes(${e}Controller),
154
- controller: ${e}Controller,
155
- }
156
- }
157
- }
158
- `;
159
- }
160
- function de(r) {
161
- const { pascal: e, kebab: t, plural: o = "" } = r;
162
- return `import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
163
- import { buildRoutes } from '@forinda/kickjs'
164
- import { ${e}Controller } from './${t}.controller'
165
-
166
- export class ${e}Module implements AppModule {
167
- routes(): ModuleRoutes {
168
- return {
169
- path: '/${o}',
170
- router: buildRoutes(${e}Controller),
171
- controller: ${e}Controller,
172
- }
173
- }
174
- }
175
- `;
176
- }
177
- function pe(r) {
178
- const { pascal: e, kebab: t, plural: o = "", pluralPascal: s = "" } = r;
179
- return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams } from '@forinda/kickjs'
180
- import type { RequestContext } from '@forinda/kickjs'
181
- import { ApiTags } from '@forinda/kickjs-swagger'
182
- import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
183
- import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
184
- import { List${s}UseCase } from '../application/use-cases/list-${o}.use-case'
185
- import { Update${e}UseCase } from '../application/use-cases/update-${t}.use-case'
186
- import { Delete${e}UseCase } from '../application/use-cases/delete-${t}.use-case'
187
- import { create${e}Schema } from '../application/dtos/create-${t}.dto'
188
- import { update${e}Schema } from '../application/dtos/update-${t}.dto'
189
- import { ${e.toUpperCase()}_QUERY_CONFIG } from '../constants'
190
-
191
- @Controller()
192
- export class ${e}Controller {
193
- @Autowired() private create${e}UseCase!: Create${e}UseCase
194
- @Autowired() private get${e}UseCase!: Get${e}UseCase
195
- @Autowired() private list${s}UseCase!: List${s}UseCase
196
- @Autowired() private update${e}UseCase!: Update${e}UseCase
197
- @Autowired() private delete${e}UseCase!: Delete${e}UseCase
198
-
199
- @Get('/')
200
- @ApiTags('${e}')
201
- @ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
202
- async list(ctx: RequestContext) {
203
- return ctx.paginate(
204
- (parsed) => this.list${s}UseCase.execute(parsed),
205
- ${e.toUpperCase()}_QUERY_CONFIG,
206
- )
207
- }
208
-
209
- @Get('/:id')
210
- @ApiTags('${e}')
211
- async getById(ctx: RequestContext) {
212
- const result = await this.get${e}UseCase.execute(ctx.params.id)
213
- if (!result) return ctx.notFound('${e} not found')
214
- ctx.json(result)
215
- }
216
-
217
- @Post('/', { body: create${e}Schema, name: 'Create${e}' })
218
- @ApiTags('${e}')
219
- async create(ctx: RequestContext) {
220
- const result = await this.create${e}UseCase.execute(ctx.body)
221
- ctx.created(result)
222
- }
223
-
224
- @Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
225
- @ApiTags('${e}')
226
- async update(ctx: RequestContext) {
227
- const result = await this.update${e}UseCase.execute(ctx.params.id, ctx.body)
228
- ctx.json(result)
229
- }
230
-
231
- @Delete('/:id')
232
- @ApiTags('${e}')
233
- async remove(ctx: RequestContext) {
234
- await this.delete${e}UseCase.execute(ctx.params.id)
235
- ctx.noContent()
236
- }
237
- }
238
- `;
239
- }
240
- function le(r) {
241
- const { pascal: e, kebab: t, plural: o = "", pluralPascal: s = "" } = r, i = e.charAt(0).toLowerCase() + e.slice(1);
242
- return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams } from '@forinda/kickjs'
243
- import type { RequestContext } from '@forinda/kickjs'
244
- import { ApiTags } from '@forinda/kickjs-swagger'
245
- import { ${e}Service } from './${t}.service'
246
- import { create${e}Schema } from './dtos/create-${t}.dto'
247
- import { update${e}Schema } from './dtos/update-${t}.dto'
248
- import { ${e.toUpperCase()}_QUERY_CONFIG } from './${t}.constants'
249
-
250
- @Controller()
251
- export class ${e}Controller {
252
- @Autowired() private ${i}Service!: ${e}Service
253
-
254
- @Get('/')
255
- @ApiTags('${e}')
256
- @ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
257
- async list(ctx: RequestContext) {
258
- return ctx.paginate(
259
- (parsed) => this.${i}Service.findPaginated(parsed),
260
- ${e.toUpperCase()}_QUERY_CONFIG,
261
- )
262
- }
263
-
264
- @Get('/:id')
265
- @ApiTags('${e}')
266
- async getById(ctx: RequestContext) {
267
- const result = await this.${i}Service.findById(ctx.params.id)
268
- if (!result) return ctx.notFound('${e} not found')
269
- ctx.json(result)
270
- }
271
-
272
- @Post('/', { body: create${e}Schema, name: 'Create${e}' })
273
- @ApiTags('${e}')
274
- async create(ctx: RequestContext) {
275
- const result = await this.${i}Service.create(ctx.body)
276
- ctx.created(result)
277
- }
278
-
279
- @Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
280
- @ApiTags('${e}')
281
- async update(ctx: RequestContext) {
282
- const result = await this.${i}Service.update(ctx.params.id, ctx.body)
283
- ctx.json(result)
284
- }
285
-
286
- @Delete('/:id')
287
- @ApiTags('${e}')
288
- async remove(ctx: RequestContext) {
289
- await this.${i}Service.delete(ctx.params.id)
290
- ctx.noContent()
291
- }
292
- }
293
- `;
294
- }
295
- function ue(r) {
296
- const { pascal: e } = r;
297
- return `import type { QueryParamsConfig } from '@forinda/kickjs'
298
-
299
- export const ${e.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
300
- filterable: ['name'],
301
- sortable: ['name', 'createdAt'],
302
- searchable: ['name'],
303
- }
304
- `;
305
- }
306
- function O(r) {
307
- const { pascal: e, kebab: t } = r;
308
- return `import { z } from 'zod'
309
-
310
- /**
311
- * Create ${e} DTO — Zod schema for validating POST request bodies.
312
- * This schema is passed to @Post('/', { body: create${e}Schema }) for automatic validation.
313
- * It also generates OpenAPI request body docs when SwaggerAdapter is used.
314
- *
315
- * Add more fields as needed. Supported Zod types:
316
- * z.string(), z.number(), z.boolean(), z.enum([...]),
317
- * z.array(), z.object(), .optional(), .default(), .transform()
318
- */
319
- export const create${e}Schema = z.object({
320
- name: z.string().min(1, 'Name is required').max(200),
321
- })
322
-
323
- export type Create${e}DTO = z.infer<typeof create${e}Schema>
324
- `;
325
- }
326
- function I(r) {
327
- const { pascal: e, kebab: t } = r;
328
- return `import { z } from 'zod'
329
-
330
- export const update${e}Schema = z.object({
331
- name: z.string().min(1).max(200).optional(),
332
- })
333
-
334
- export type Update${e}DTO = z.infer<typeof update${e}Schema>
335
- `;
336
- }
337
- function S(r) {
338
- const { pascal: e, kebab: t } = r;
339
- return `export interface ${e}ResponseDTO {
340
- id: string
341
- name: string
342
- createdAt: string
343
- updatedAt: string
344
- }
345
- `;
346
- }
347
- function me(r) {
348
- const { pascal: e, kebab: t, plural: o = "", pluralPascal: s = "" } = r;
349
- return [
350
- {
351
- file: `create-${t}.use-case.ts`,
352
- content: `/**
353
- * Create ${e} Use Case
354
- *
355
- * Application layer — orchestrates a single business operation.
356
- * Use cases are thin: validate input (via DTO), call domain/repo, return response.
357
- * Keep business rules in the domain service, not here.
358
- */
359
- import { Service, Inject } from '@forinda/kickjs'
360
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
361
- import type { Create${e}DTO } from '../dtos/create-${t}.dto'
362
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
363
-
364
- @Service()
365
- export class Create${e}UseCase {
366
- constructor(
367
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
368
- ) {}
369
-
370
- async execute(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
371
- return this.repo.create(dto)
372
- }
373
- }
374
- `
375
- },
376
- {
377
- file: `get-${t}.use-case.ts`,
378
- content: `import { Service, Inject } from '@forinda/kickjs'
379
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
380
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
381
-
382
- @Service()
383
- export class Get${e}UseCase {
384
- constructor(
385
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
386
- ) {}
387
-
388
- async execute(id: string): Promise<${e}ResponseDTO | null> {
389
- return this.repo.findById(id)
390
- }
391
- }
392
- `
393
- },
394
- {
395
- file: `list-${o}.use-case.ts`,
396
- content: `import { Service, Inject } from '@forinda/kickjs'
397
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
398
- import type { ParsedQuery } from '@forinda/kickjs'
399
-
400
- @Service()
401
- export class List${s}UseCase {
402
- constructor(
403
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
404
- ) {}
405
-
406
- async execute(parsed: ParsedQuery) {
407
- return this.repo.findPaginated(parsed)
408
- }
409
- }
410
- `
411
- },
412
- {
413
- file: `update-${t}.use-case.ts`,
414
- content: `import { Service, Inject } from '@forinda/kickjs'
415
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
416
- import type { Update${e}DTO } from '../dtos/update-${t}.dto'
417
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
418
-
419
- @Service()
420
- export class Update${e}UseCase {
421
- constructor(
422
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
423
- ) {}
424
-
425
- async execute(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
426
- return this.repo.update(id, dto)
427
- }
428
- }
429
- `
430
- },
431
- {
432
- file: `delete-${t}.use-case.ts`,
433
- content: `import { Service, Inject } from '@forinda/kickjs'
434
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
435
-
436
- @Service()
437
- export class Delete${e}UseCase {
438
- constructor(
439
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
440
- ) {}
441
-
442
- async execute(id: string): Promise<void> {
443
- await this.repo.delete(id)
444
- }
445
- }
446
- `
447
- }
448
- ];
449
- }
450
- function A(r) {
451
- const { pascal: e, kebab: t, dtoPrefix: o = "../../application/dtos" } = r;
452
- return `/**
453
- * ${e} Repository Interface
454
- *
455
- * Defines the contract for data access.
456
- * The interface declares what operations are available;
457
- * implementations (in-memory, Drizzle, Prisma) fulfill the contract.
458
- *
459
- * To swap implementations, change the factory in the module's register() method.
460
- */
461
- import type { ${e}ResponseDTO } from '${o}/${t}-response.dto'
462
- import type { Create${e}DTO } from '${o}/create-${t}.dto'
463
- import type { Update${e}DTO } from '${o}/update-${t}.dto'
464
- import type { ParsedQuery } from '@forinda/kickjs'
465
-
466
- export interface I${e}Repository {
467
- findById(id: string): Promise<${e}ResponseDTO | null>
468
- findAll(): Promise<${e}ResponseDTO[]>
469
- findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }>
470
- create(dto: Create${e}DTO): Promise<${e}ResponseDTO>
471
- update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO>
472
- delete(id: string): Promise<void>
473
- }
474
-
475
- export const ${e.toUpperCase()}_REPOSITORY = Symbol('I${e}Repository')
476
- `;
477
- }
478
- function v(r) {
479
- const { pascal: e, kebab: t, repoPrefix: o = "../../domain/repositories", dtoPrefix: s = "../../application/dtos" } = r;
480
- return `/**
481
- * In-Memory ${e} Repository
482
- *
483
- * Implements the repository interface using a Map.
484
- * Useful for prototyping and testing. Replace with a database implementation
485
- * (Drizzle, Prisma, etc.) for production use.
486
- *
487
- * @Repository() registers this class in the DI container as a singleton.
488
- */
489
- import { randomUUID } from 'node:crypto'
490
- import { Repository, HttpException } from '@forinda/kickjs'
491
- import type { ParsedQuery } from '@forinda/kickjs'
492
- import type { I${e}Repository } from '${o}/${t}.repository'
493
- import type { ${e}ResponseDTO } from '${s}/${t}-response.dto'
494
- import type { Create${e}DTO } from '${s}/create-${t}.dto'
495
- import type { Update${e}DTO } from '${s}/update-${t}.dto'
496
-
497
- @Repository()
498
- export class InMemory${e}Repository implements I${e}Repository {
499
- private store = new Map<string, ${e}ResponseDTO>()
500
-
501
- async findById(id: string): Promise<${e}ResponseDTO | null> {
502
- return this.store.get(id) ?? null
503
- }
504
-
505
- async findAll(): Promise<${e}ResponseDTO[]> {
506
- return Array.from(this.store.values())
507
- }
508
-
509
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
510
- const all = Array.from(this.store.values())
511
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
512
- return { data, total: all.length }
513
- }
514
-
515
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
516
- const now = new Date().toISOString()
517
- const entity: ${e}ResponseDTO = {
518
- id: randomUUID(),
519
- name: dto.name,
520
- createdAt: now,
521
- updatedAt: now,
522
- }
523
- this.store.set(entity.id, entity)
524
- return entity
525
- }
526
-
527
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
528
- const existing = this.store.get(id)
529
- if (!existing) throw HttpException.notFound('${e} not found')
530
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
531
- this.store.set(id, updated)
532
- return updated
533
- }
534
-
535
- async delete(id: string): Promise<void> {
536
- if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
537
- this.store.delete(id)
538
- }
539
- }
540
- `;
541
- }
542
- function j(r) {
543
- const { pascal: e, kebab: t, repoType: o = "", repoPrefix: s = "../../domain/repositories", dtoPrefix: i = "../../application/dtos" } = r, n = o.charAt(0).toUpperCase() + o.slice(1).replace(/-([a-z])/g, (a, c) => c.toUpperCase());
544
- return `/**
545
- * ${n} ${e} Repository
546
- *
547
- * Stub implementation for a custom '${o}' repository.
548
- * Implements the repository interface using an in-memory Map as a placeholder.
549
- *
550
- * TODO: Replace the in-memory Map with your ${o} data-access logic.
551
- * See I${e}Repository for the interface contract.
552
- *
553
- * @Repository() registers this class in the DI container as a singleton.
554
- */
555
- import { randomUUID } from 'node:crypto'
556
- import { Repository, HttpException } from '@forinda/kickjs'
557
- import type { ParsedQuery } from '@forinda/kickjs'
558
- import type { I${e}Repository } from '${s}/${t}.repository'
559
- import type { ${e}ResponseDTO } from '${i}/${t}-response.dto'
560
- import type { Create${e}DTO } from '${i}/create-${t}.dto'
561
- import type { Update${e}DTO } from '${i}/update-${t}.dto'
562
-
563
- @Repository()
564
- export class ${n}${e}Repository implements I${e}Repository {
565
- // TODO: Replace with your ${o} client/connection
566
- private store = new Map<string, ${e}ResponseDTO>()
567
-
568
- async findById(id: string): Promise<${e}ResponseDTO | null> {
569
- // TODO: Implement with ${o}
570
- return this.store.get(id) ?? null
571
- }
572
-
573
- async findAll(): Promise<${e}ResponseDTO[]> {
574
- // TODO: Implement with ${o}
575
- return Array.from(this.store.values())
576
- }
577
-
578
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
579
- // TODO: Implement with ${o}
580
- const all = Array.from(this.store.values())
581
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
582
- return { data, total: all.length }
583
- }
584
-
585
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
586
- // TODO: Implement with ${o}
587
- const now = new Date().toISOString()
588
- const entity: ${e}ResponseDTO = {
589
- id: randomUUID(),
590
- name: dto.name,
591
- createdAt: now,
592
- updatedAt: now,
593
- }
594
- this.store.set(entity.id, entity)
595
- return entity
596
- }
597
-
598
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
599
- // TODO: Implement with ${o}
600
- const existing = this.store.get(id)
601
- if (!existing) throw HttpException.notFound('${e} not found')
602
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
603
- this.store.set(id, updated)
604
- return updated
605
- }
606
-
607
- async delete(id: string): Promise<void> {
608
- // TODO: Implement with ${o}
609
- if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
610
- this.store.delete(id)
611
- }
612
- }
613
- `;
614
- }
615
- function fe(r) {
616
- const { pascal: e, kebab: t } = r;
617
- return `/**
618
- * ${e} Domain Service
619
- *
620
- * Domain layer — contains business rules that don't belong to a single entity.
621
- * Use this for cross-entity logic, validation rules, and domain invariants.
622
- * Keep it free of HTTP/framework concerns.
623
- */
624
- import { Service, Inject, HttpException } from '@forinda/kickjs'
625
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
626
-
627
- @Service()
628
- export class ${e}DomainService {
629
- constructor(
630
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
631
- ) {}
632
-
633
- async ensureExists(id: string): Promise<void> {
634
- const entity = await this.repo.findById(id)
635
- if (!entity) {
636
- throw HttpException.notFound('${e} not found')
637
- }
638
- }
639
- }
640
- `;
641
- }
642
- function $e(r) {
643
- const { pascal: e, kebab: t } = r;
644
- return `/**
645
- * ${e} Entity
646
- *
647
- * Domain layer — the core business object.
648
- * Uses a private constructor with static factory methods (create, reconstitute)
649
- * to enforce invariants. Properties are accessed via getters to maintain encapsulation.
650
- *
651
- * Patterns used:
652
- * - Private constructor: prevents direct instantiation
653
- * - create(): factory for new entities (generates ID, sets timestamps)
654
- * - reconstitute(): factory for rebuilding from persistence (no side effects)
655
- * - changeName(): mutation method that enforces business rules
656
- */
657
- import { ${e}Id } from '../value-objects/${t}-id.vo'
658
-
659
- interface ${e}Props {
660
- id: ${e}Id
661
- name: string
662
- createdAt: Date
663
- updatedAt: Date
664
- }
665
-
666
- export class ${e} {
667
- private constructor(private props: ${e}Props) {}
668
-
669
- static create(params: { name: string }): ${e} {
670
- const now = new Date()
671
- return new ${e}({
672
- id: ${e}Id.create(),
673
- name: params.name,
674
- createdAt: now,
675
- updatedAt: now,
676
- })
677
- }
678
-
679
- static reconstitute(props: ${e}Props): ${e} {
680
- return new ${e}(props)
681
- }
682
-
683
- get id(): ${e}Id {
684
- return this.props.id
685
- }
686
- get name(): string {
687
- return this.props.name
688
- }
689
- get createdAt(): Date {
690
- return this.props.createdAt
691
- }
692
- get updatedAt(): Date {
693
- return this.props.updatedAt
694
- }
695
-
696
- changeName(name: string): void {
697
- if (!name || name.trim().length === 0) {
698
- throw new Error('Name cannot be empty')
699
- }
700
- this.props.name = name.trim()
701
- this.props.updatedAt = new Date()
702
- }
703
-
704
- toJSON() {
705
- return {
706
- id: this.props.id.toString(),
707
- name: this.props.name,
708
- createdAt: this.props.createdAt.toISOString(),
709
- updatedAt: this.props.updatedAt.toISOString(),
710
- }
711
- }
712
- }
713
- `;
714
- }
715
- function ye(r) {
716
- const { pascal: e, kebab: t } = r;
717
- return `/**
718
- * ${e} ID Value Object
719
- *
720
- * Domain layer — wraps a primitive ID with type safety and validation.
721
- * Value objects are immutable and compared by value, not reference.
722
- *
723
- * ${e}Id.create() — generate a new UUID
724
- * ${e}Id.from(id) — wrap an existing ID string (validates non-empty)
725
- * id.equals(other) — compare two IDs by value
726
- */
727
- import { randomUUID } from 'node:crypto'
728
-
729
- export class ${e}Id {
730
- private constructor(private readonly value: string) {}
731
-
732
- static create(): ${e}Id {
733
- return new ${e}Id(randomUUID())
734
- }
735
-
736
- static from(id: string): ${e}Id {
737
- if (!id || id.trim().length === 0) {
738
- throw new Error('${e}Id cannot be empty')
739
- }
740
- return new ${e}Id(id)
741
- }
742
-
743
- toString(): string {
744
- return this.value
745
- }
746
-
747
- equals(other: ${e}Id): boolean {
748
- return this.value === other.value
749
- }
750
- }
751
- `;
752
- }
753
- function E(r) {
754
- const { pascal: e, kebab: t, plural: o = "" } = r;
755
- return `import { describe, it, expect, beforeEach } from 'vitest'
756
- import { Container } from '@forinda/kickjs'
757
-
758
- describe('${e}Controller', () => {
759
- beforeEach(() => {
760
- Container.reset()
761
- })
762
-
763
- it('should be defined', () => {
764
- expect(true).toBe(true)
765
- })
766
-
767
- describe('POST /${o}', () => {
768
- it('should create a new ${t}', async () => {
769
- // TODO: Set up test module, call create endpoint, assert 201
770
- expect(true).toBe(true)
771
- })
772
- })
773
-
774
- describe('GET /${o}', () => {
775
- it('should return paginated ${o}', async () => {
776
- // TODO: Set up test module, call list endpoint, assert { data, meta }
777
- expect(true).toBe(true)
778
- })
779
- })
780
-
781
- describe('GET /${o}/:id', () => {
782
- it('should return a ${t} by id', async () => {
783
- // TODO: Create a ${t}, then fetch by id, assert match
784
- expect(true).toBe(true)
785
- })
786
-
787
- it('should return 404 for non-existent ${t}', async () => {
788
- // TODO: Fetch non-existent id, assert 404
789
- expect(true).toBe(true)
790
- })
791
- })
792
-
793
- describe('PUT /${o}/:id', () => {
794
- it('should update an existing ${t}', async () => {
795
- // TODO: Create, update, assert changes
796
- expect(true).toBe(true)
797
- })
798
- })
799
-
800
- describe('DELETE /${o}/:id', () => {
801
- it('should delete a ${t}', async () => {
802
- // TODO: Create, delete, assert gone
803
- expect(true).toBe(true)
804
- })
805
- })
806
- })
807
- `;
808
- }
809
- function U(r) {
810
- const { pascal: e, kebab: t, plural: o = "", repoPrefix: s = `../infrastructure/repositories/in-memory-${t}.repository` } = r;
811
- return `import { describe, it, expect, beforeEach } from 'vitest'
812
- import { InMemory${e}Repository } from '${s}'
813
-
814
- describe('InMemory${e}Repository', () => {
815
- let repo: InMemory${e}Repository
816
-
817
- beforeEach(() => {
818
- repo = new InMemory${e}Repository()
819
- })
820
-
821
- it('should create and retrieve a ${t}', async () => {
822
- const created = await repo.create({ name: 'Test ${e}' })
823
- expect(created).toBeDefined()
824
- expect(created.name).toBe('Test ${e}')
825
- expect(created.id).toBeDefined()
826
-
827
- const found = await repo.findById(created.id)
828
- expect(found).toEqual(created)
829
- })
830
-
831
- it('should return null for non-existent id', async () => {
832
- const found = await repo.findById('non-existent')
833
- expect(found).toBeNull()
834
- })
835
-
836
- it('should list all ${o}', async () => {
837
- await repo.create({ name: '${e} 1' })
838
- await repo.create({ name: '${e} 2' })
839
-
840
- const all = await repo.findAll()
841
- expect(all).toHaveLength(2)
842
- })
843
-
844
- it('should return paginated results', async () => {
845
- await repo.create({ name: '${e} 1' })
846
- await repo.create({ name: '${e} 2' })
847
- await repo.create({ name: '${e} 3' })
848
-
849
- const result = await repo.findPaginated({
850
- filters: [],
851
- sort: [],
852
- search: '',
853
- pagination: { page: 1, limit: 2, offset: 0 },
854
- })
855
-
856
- expect(result.data).toHaveLength(2)
857
- expect(result.total).toBe(3)
858
- })
859
-
860
- it('should update a ${t}', async () => {
861
- const created = await repo.create({ name: 'Original' })
862
- const updated = await repo.update(created.id, { name: 'Updated' })
863
- expect(updated.name).toBe('Updated')
864
- })
865
-
866
- it('should delete a ${t}', async () => {
867
- const created = await repo.create({ name: 'To Delete' })
868
- await repo.delete(created.id)
869
- const found = await repo.findById(created.id)
870
- expect(found).toBeNull()
871
- })
872
- })
873
- `;
874
- }
875
- function ge(r) {
876
- const { pascal: e, kebab: t } = r;
877
- return `import { Service, Inject, HttpException } from '@forinda/kickjs'
878
- import type { ParsedQuery } from '@forinda/kickjs'
879
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from './${t}.repository'
880
- import type { ${e}ResponseDTO } from './dtos/${t}-response.dto'
881
- import type { Create${e}DTO } from './dtos/create-${t}.dto'
882
- import type { Update${e}DTO } from './dtos/update-${t}.dto'
883
-
884
- @Service()
885
- export class ${e}Service {
886
- constructor(
887
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
888
- ) {}
889
-
890
- async findById(id: string): Promise<${e}ResponseDTO | null> {
891
- return this.repo.findById(id)
892
- }
893
-
894
- async findAll(): Promise<${e}ResponseDTO[]> {
895
- return this.repo.findAll()
896
- }
897
-
898
- async findPaginated(parsed: ParsedQuery) {
899
- return this.repo.findPaginated(parsed)
900
- }
901
-
902
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
903
- return this.repo.create(dto)
904
- }
905
-
906
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
907
- return this.repo.update(id, dto)
908
- }
909
-
910
- async delete(id: string): Promise<void> {
911
- await this.repo.delete(id)
912
- }
913
- }
914
- `;
915
- }
916
- function J(r) {
917
- const { pascal: e } = r;
918
- return `import type { QueryFieldConfig } from '@forinda/kickjs'
919
-
920
- export const ${e.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
921
- filterable: ['name'],
922
- sortable: ['name', 'createdAt'],
923
- searchable: ['name'],
924
- }
925
- `;
926
- }
927
- function he(r) {
928
- const { pascal: e, kebab: t, plural: o = "", repo: s } = r, i = {
929
- inmemory: `InMemory${e}Repository`,
930
- drizzle: `Drizzle${e}Repository`,
931
- prisma: `Prisma${e}Repository`
932
- }, n = {
933
- inmemory: `in-memory-${t}`,
934
- drizzle: `drizzle-${t}`,
935
- prisma: `prisma-${t}`
936
- }, a = i[s] ?? i.inmemory, c = n[s] ?? n.inmemory;
937
- return `/**
938
- * ${e} Module — CQRS Pattern
939
- *
940
- * Separates read (queries) and write (commands) operations.
941
- * Events are emitted after state changes and can be handled via
942
- * WebSocket broadcasts, queue jobs, or ETL pipelines.
943
- *
944
- * Structure:
945
- * commands/ — Write operations (create, update, delete)
946
- * queries/ — Read operations (get, list)
947
- * events/ — Domain events + handlers (WS broadcast, queue dispatch)
948
- * dtos/ — Request/response schemas
949
- */
950
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
951
- import { buildRoutes } from '@forinda/kickjs'
952
- import { ${e.toUpperCase()}_REPOSITORY } from './${t}.repository'
953
- import { ${a} } from './${c}.repository'
954
- import { ${e}Controller } from './${t}.controller'
955
-
956
- // Eagerly load decorated classes
957
- import.meta.glob(
958
- [
959
- './commands/**/*.ts',
960
- './queries/**/*.ts',
961
- './events/**/*.ts',
962
- '!./**/*.test.ts',
963
- ],
964
- { eager: true },
965
- )
966
-
967
- export class ${e}Module implements AppModule {
968
- register(container: Container): void {
969
- container.registerFactory(${e.toUpperCase()}_REPOSITORY, () =>
970
- container.resolve(${a}),
971
- )
972
- }
973
-
974
- routes(): ModuleRoutes {
975
- return {
976
- path: '/${o}',
977
- router: buildRoutes(${e}Controller),
978
- controller: ${e}Controller,
979
- }
980
- }
981
- }
982
- `;
983
- }
984
- function ke(r) {
985
- const { pascal: e, kebab: t, plural: o = "", pluralPascal: s = "" } = r;
986
- return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams } from '@forinda/kickjs'
987
- import type { RequestContext } from '@forinda/kickjs'
988
- import { ApiTags } from '@forinda/kickjs-swagger'
989
- import { Create${e}Command } from './commands/create-${t}.command'
990
- import { Update${e}Command } from './commands/update-${t}.command'
991
- import { Delete${e}Command } from './commands/delete-${t}.command'
992
- import { Get${e}Query } from './queries/get-${t}.query'
993
- import { List${s}Query } from './queries/list-${o}.query'
994
- import { create${e}Schema } from './dtos/create-${t}.dto'
995
- import { update${e}Schema } from './dtos/update-${t}.dto'
996
- import { ${e.toUpperCase()}_QUERY_CONFIG } from './${t}.constants'
997
-
998
- @Controller()
999
- export class ${e}Controller {
1000
- @Autowired() private create${e}Command!: Create${e}Command
1001
- @Autowired() private update${e}Command!: Update${e}Command
1002
- @Autowired() private delete${e}Command!: Delete${e}Command
1003
- @Autowired() private get${e}Query!: Get${e}Query
1004
- @Autowired() private list${s}Query!: List${s}Query
1005
-
1006
- @Get('/')
1007
- @ApiTags('${e}')
1008
- @ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
1009
- async list(ctx: RequestContext) {
1010
- return ctx.paginate(
1011
- (parsed) => this.list${s}Query.execute(parsed),
1012
- ${e.toUpperCase()}_QUERY_CONFIG,
1013
- )
1014
- }
1015
-
1016
- @Get('/:id')
1017
- @ApiTags('${e}')
1018
- async getById(ctx: RequestContext) {
1019
- const result = await this.get${e}Query.execute(ctx.params.id)
1020
- if (!result) return ctx.notFound('${e} not found')
1021
- ctx.json(result)
1022
- }
1023
-
1024
- @Post('/', { body: create${e}Schema, name: 'Create${e}' })
1025
- @ApiTags('${e}')
1026
- async create(ctx: RequestContext) {
1027
- const result = await this.create${e}Command.execute(ctx.body)
1028
- ctx.created(result)
1029
- }
1030
-
1031
- @Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
1032
- @ApiTags('${e}')
1033
- async update(ctx: RequestContext) {
1034
- const result = await this.update${e}Command.execute(ctx.params.id, ctx.body)
1035
- ctx.json(result)
1036
- }
1037
-
1038
- @Delete('/:id')
1039
- @ApiTags('${e}')
1040
- async remove(ctx: RequestContext) {
1041
- await this.delete${e}Command.execute(ctx.params.id)
1042
- ctx.noContent()
1043
- }
1044
- }
1045
- `;
1046
- }
1047
- function ve(r) {
1048
- const { pascal: e, kebab: t } = r;
1049
- return [
1050
- {
1051
- file: `create-${t}.command.ts`,
1052
- content: `import { Service, Inject } from '@forinda/kickjs'
1053
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../${t}.repository'
1054
- import type { Create${e}DTO } from '../dtos/create-${t}.dto'
1055
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
1056
- import { ${e}Events } from '../events/${t}.events'
1057
-
1058
- @Service()
1059
- export class Create${e}Command {
1060
- constructor(
1061
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
1062
- @Inject(${e}Events) private readonly events: ${e}Events,
1063
- ) {}
1064
-
1065
- async execute(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
1066
- const result = await this.repo.create(dto)
1067
- this.events.emit('${t}.created', result)
1068
- return result
1069
- }
1070
- }
1071
- `
1072
- },
1073
- {
1074
- file: `update-${t}.command.ts`,
1075
- content: `import { Service, Inject } from '@forinda/kickjs'
1076
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../${t}.repository'
1077
- import type { Update${e}DTO } from '../dtos/update-${t}.dto'
1078
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
1079
- import { ${e}Events } from '../events/${t}.events'
1080
-
1081
- @Service()
1082
- export class Update${e}Command {
1083
- constructor(
1084
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
1085
- @Inject(${e}Events) private readonly events: ${e}Events,
1086
- ) {}
1087
-
1088
- async execute(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
1089
- const result = await this.repo.update(id, dto)
1090
- this.events.emit('${t}.updated', result)
1091
- return result
1092
- }
1093
- }
1094
- `
1095
- },
1096
- {
1097
- file: `delete-${t}.command.ts`,
1098
- content: `import { Service, Inject } from '@forinda/kickjs'
1099
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../${t}.repository'
1100
- import { ${e}Events } from '../events/${t}.events'
1101
-
1102
- @Service()
1103
- export class Delete${e}Command {
1104
- constructor(
1105
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
1106
- @Inject(${e}Events) private readonly events: ${e}Events,
1107
- ) {}
1108
-
1109
- async execute(id: string): Promise<void> {
1110
- await this.repo.delete(id)
1111
- this.events.emit('${t}.deleted', { id })
1112
- }
1113
- }
1114
- `
1115
- }
1116
- ];
1117
- }
1118
- function we(r) {
1119
- const { pascal: e, kebab: t, plural: o = "", pluralPascal: s = "" } = r;
1120
- return [{
1121
- file: `get-${t}.query.ts`,
1122
- content: `import { Service, Inject } from '@forinda/kickjs'
1123
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../${t}.repository'
1124
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
1125
-
1126
- @Service()
1127
- export class Get${e}Query {
1128
- constructor(
1129
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
1130
- ) {}
1131
-
1132
- async execute(id: string): Promise<${e}ResponseDTO | null> {
1133
- return this.repo.findById(id)
1134
- }
1135
- }
1136
- `
1137
- }, {
1138
- file: `list-${o}.query.ts`,
1139
- content: `import { Service, Inject } from '@forinda/kickjs'
1140
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../${t}.repository'
1141
- import type { ParsedQuery } from '@forinda/kickjs'
1142
-
1143
- @Service()
1144
- export class List${s}Query {
1145
- constructor(
1146
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
1147
- ) {}
1148
-
1149
- async execute(parsed: ParsedQuery) {
1150
- return this.repo.findPaginated(parsed)
1151
- }
1152
- }
1153
- `
1154
- }];
1155
- }
1156
- function Re(r) {
1157
- const { pascal: e, kebab: t } = r;
1158
- return [{
1159
- file: `${t}.events.ts`,
1160
- content: `import { Service } from '@forinda/kickjs'
1161
- import { EventEmitter } from 'node:events'
1162
- import type { ${e}ResponseDTO } from '../dtos/${t}-response.dto'
1163
-
1164
- /**
1165
- * ${e} domain event types.
1166
- *
1167
- * These events are emitted by commands after state changes.
1168
- * Subscribe to them in event handlers for side effects:
1169
- * - WebSocket broadcasts (real-time UI updates)
1170
- * - Queue jobs (async processing, ETL pipelines)
1171
- * - Audit logging
1172
- * - Cache invalidation
1173
- */
1174
- export interface ${e}EventMap {
1175
- '${t}.created': ${e}ResponseDTO
1176
- '${t}.updated': ${e}ResponseDTO
1177
- '${t}.deleted': { id: string }
1178
- }
1179
-
1180
- @Service()
1181
- export class ${e}Events {
1182
- private emitter = new EventEmitter()
1183
-
1184
- emit<K extends keyof ${e}EventMap>(event: K, data: ${e}EventMap[K]): void {
1185
- this.emitter.emit(event, data)
1186
- }
1187
-
1188
- on<K extends keyof ${e}EventMap>(event: K, handler: (data: ${e}EventMap[K]) => void): void {
1189
- this.emitter.on(event, handler)
1190
- }
1191
-
1192
- off<K extends keyof ${e}EventMap>(event: K, handler: (data: ${e}EventMap[K]) => void): void {
1193
- this.emitter.off(event, handler)
1194
- }
1195
- }
1196
- `
1197
- }, {
1198
- file: `on-${t}-change.handler.ts`,
1199
- content: `import { Service, Autowired } from '@forinda/kickjs'
1200
- import { ${e}Events } from './${t}.events'
1201
-
1202
- /**
1203
- * ${e} Change Event Handler
1204
- *
1205
- * Reacts to domain events emitted by commands.
1206
- * Wire up side effects here:
1207
- *
1208
- * 1. WebSocket broadcast — notify connected clients in real-time
1209
- * import { WsGateway } from '@forinda/kickjs-ws'
1210
- * this.ws.broadcast('${t}-channel', { event, data })
1211
- *
1212
- * 2. Queue dispatch — offload heavy processing to background workers
1213
- * import { QueueService } from '@forinda/kickjs-queue'
1214
- * this.queue.add('${t}-etl', { action: event, payload: data })
1215
- *
1216
- * 3. ETL pipeline — transform and load data to external systems
1217
- * await this.etlPipeline.process(data)
1218
- */
1219
- @Service()
1220
- export class On${e}ChangeHandler {
1221
- @Autowired() private events!: ${e}Events
1222
-
1223
- // Uncomment to inject WebSocket and Queue services:
1224
- // @Autowired() private ws!: WsGateway
1225
- // @Autowired() private queue!: QueueService
1226
-
1227
- onInit(): void {
1228
- this.events.on('${t}.created', (data) => {
1229
- console.log('[${e}] Created:', data.id)
1230
- // TODO: Broadcast via WebSocket
1231
- // this.ws.broadcast('${t}-channel', { event: '${t}.created', data })
1232
- // TODO: Dispatch to queue for async processing / ETL
1233
- // this.queue.add('${t}-etl', { action: 'create', payload: data })
1234
- })
1235
-
1236
- this.events.on('${t}.updated', (data) => {
1237
- console.log('[${e}] Updated:', data.id)
1238
- // TODO: Broadcast via WebSocket
1239
- // this.ws.broadcast('${t}-channel', { event: '${t}.updated', data })
1240
- })
1241
-
1242
- this.events.on('${t}.deleted', (data) => {
1243
- console.log('[${e}] Deleted:', data.id)
1244
- // TODO: Broadcast via WebSocket
1245
- // this.ws.broadcast('${t}-channel', { event: '${t}.deleted', data })
1246
- })
1247
- }
1248
- }
1249
- `
1250
- }];
1251
- }
1252
- function M(r) {
1253
- const { pascal: e, kebab: t, repoPrefix: o = "../../domain/repositories", dtoPrefix: s = "../../application/dtos" } = r;
1254
- return `/**
1255
- * Drizzle ${e} Repository
1256
- *
1257
- * Implements the repository interface using Drizzle ORM.
1258
- * Uses buildFromColumns() with Column objects for type-safe query building.
1259
- *
1260
- * TODO: Update the schema import to match your Drizzle schema file.
1261
- * TODO: Replace DRIZZLE_DB injection token with your actual database token.
1262
- *
1263
- * @Repository() registers this class in the DI container as a singleton.
1264
- */
1265
- import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
1266
- import { Repository, HttpException, Inject } from '@forinda/kickjs'
1267
- import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
1268
- import type { ParsedQuery } from '@forinda/kickjs'
1269
- import type { I${e}Repository } from '${o}/${t}.repository'
1270
- import type { ${e}ResponseDTO } from '${s}/${t}-response.dto'
1271
- import type { Create${e}DTO } from '${s}/create-${t}.dto'
1272
- import type { Update${e}DTO } from '${s}/update-${t}.dto'
1273
- import { ${e.toUpperCase()}_QUERY_CONFIG } from '../../constants'
1274
-
1275
- // TODO: Import your Drizzle schema table — e.g.:
1276
- // import { ${t}s } from '@/db/schema'
1277
-
1278
- const queryAdapter = new DrizzleQueryAdapter({
1279
- eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
1280
- })
1281
-
1282
- @Repository()
1283
- export class Drizzle${e}Repository implements I${e}Repository {
1284
- constructor(@Inject(DRIZZLE_DB) private db: any) {}
1285
-
1286
- async findById(id: string): Promise<${e}ResponseDTO | null> {
1287
- // TODO: Implement with Drizzle
1288
- // const row = this.db.select().from(${t}s).where(eq(${t}s.id, id)).get()
1289
- // return row ?? null
1290
- throw new Error('Drizzle ${e} repository not yet implemented — update schema imports and queries')
1291
- }
1292
-
1293
- async findAll(): Promise<${e}ResponseDTO[]> {
1294
- // TODO: Implement with Drizzle
1295
- // return this.db.select().from(${t}s).all()
1296
- throw new Error('Drizzle ${e} repository not yet implemented')
1297
- }
1298
-
1299
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
1300
- // TODO: Use buildFromColumns() with your query config for type-safe filtering
1301
- // const query = queryAdapter.buildFromColumns(parsed, ${e.toUpperCase()}_QUERY_CONFIG)
1302
- //
1303
- // const data = this.db
1304
- // .select().from(${t}s).$dynamic()
1305
- // .where(query.where).orderBy(...query.orderBy)
1306
- // .limit(query.limit).offset(query.offset).all()
1307
- //
1308
- // const totalResult = this.db
1309
- // .select({ count: count() }).from(${t}s)
1310
- // .$dynamic().where(query.where).get()
1311
- //
1312
- // return { data, total: totalResult?.count ?? 0 }
1313
- throw new Error('Drizzle ${e} repository not yet implemented')
1314
- }
1315
-
1316
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
1317
- // TODO: Implement with Drizzle
1318
- // return this.db.insert(${t}s).values(dto).returning().get()
1319
- throw new Error('Drizzle ${e} repository not yet implemented')
1320
- }
1321
-
1322
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
1323
- // TODO: Implement with Drizzle
1324
- // const row = this.db.update(${t}s).set(dto).where(eq(${t}s.id, id)).returning().get()
1325
- // if (!row) throw HttpException.notFound('${e} not found')
1326
- // return row
1327
- throw new Error('Drizzle ${e} repository not yet implemented')
1328
- }
1329
-
1330
- async delete(id: string): Promise<void> {
1331
- // TODO: Implement with Drizzle
1332
- // this.db.delete(${t}s).where(eq(${t}s.id, id)).run()
1333
- throw new Error('Drizzle ${e} repository not yet implemented')
1334
- }
1335
- }
1336
- `;
1337
- }
1338
- function Ce(r) {
1339
- const { pascal: e, kebab: t } = r;
1340
- return `import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
1341
- // TODO: Import your schema table and reference actual columns for type safety
1342
- // import { ${t}s } from '@/db/schema'
1343
-
1344
- export const ${e.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
1345
- columns: {
1346
- // Replace with actual Drizzle Column references for type-safe filtering:
1347
- // name: ${t}s.name,
1348
- // status: ${t}s.status,
1349
- },
1350
- sortable: {
1351
- // name: ${t}s.name,
1352
- // createdAt: ${t}s.createdAt,
1353
- },
1354
- searchColumns: [
1355
- // ${t}s.name,
1356
- ],
1357
- }
1358
- `;
1359
- }
1360
- function q(r) {
1361
- const { pascal: e, kebab: t, repoPrefix: o = "../../domain/repositories", dtoPrefix: s = "../../application/dtos" } = r, i = t.replace(/-([a-z])/g, (n, a) => a.toUpperCase());
1362
- return `/**
1363
- * Prisma ${e} Repository
1364
- *
1365
- * Implements the repository interface using Prisma Client.
1366
- * Requires a PrismaClient instance injected via the DI container.
1367
- *
1368
- * Ensure your Prisma schema has a '${e}' model defined.
1369
- *
1370
- * For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
1371
- * @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
1372
- *
1373
- * @Repository() registers this class in the DI container as a singleton.
1374
- */
1375
- import { Repository, HttpException, Inject } from '@forinda/kickjs'
1376
- import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
1377
- import type { ParsedQuery } from '@forinda/kickjs'
1378
- import type { I${e}Repository } from '${o}/${t}.repository'
1379
- import type { ${e}ResponseDTO } from '${s}/${t}-response.dto'
1380
- import type { Create${e}DTO } from '${s}/create-${t}.dto'
1381
- import type { Update${e}DTO } from '${s}/update-${t}.dto'
1382
-
1383
- @Repository()
1384
- export class Prisma${e}Repository implements I${e}Repository {
1385
- @Inject(PRISMA_CLIENT) private prisma!: { ${i}: PrismaModelDelegate }
1386
-
1387
- async findById(id: string): Promise<${e}ResponseDTO | null> {
1388
- return this.prisma.${i}.findUnique({ where: { id } }) as Promise<${e}ResponseDTO | null>
1389
- }
1390
-
1391
- async findAll(): Promise<${e}ResponseDTO[]> {
1392
- return this.prisma.${i}.findMany() as Promise<${e}ResponseDTO[]>
1393
- }
1394
-
1395
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
1396
- const [data, total] = await Promise.all([
1397
- this.prisma.${i}.findMany({
1398
- skip: parsed.pagination.offset,
1399
- take: parsed.pagination.limit,
1400
- }) as Promise<${e}ResponseDTO[]>,
1401
- this.prisma.${i}.count(),
1402
- ])
1403
- return { data, total }
1404
- }
1405
-
1406
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
1407
- return this.prisma.${i}.create({ data: dto as Record<string, unknown> }) as Promise<${e}ResponseDTO>
1408
- }
1409
-
1410
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
1411
- const existing = await this.prisma.${i}.findUnique({ where: { id } })
1412
- if (!existing) throw HttpException.notFound('${e} not found')
1413
- return this.prisma.${i}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${e}ResponseDTO>
1414
- }
1415
-
1416
- async delete(id: string): Promise<void> {
1417
- await this.prisma.${i}.deleteMany({ where: { id } })
1418
- }
1419
- }
1420
- `;
1421
- }
1422
- async function be(r) {
1423
- const { pascal: e, kebab: t, plural: o, write: s } = r;
1424
- await s("index.ts", de({
1425
- pascal: e,
1426
- kebab: t,
1427
- plural: o
1428
- })), await s(`${t}.controller.ts`, `import { Controller, Get } from '@forinda/kickjs'
1429
- import type { RequestContext } from '@forinda/kickjs'
1430
-
1431
- @Controller()
1432
- export class ${e}Controller {
1433
- @Get('/')
1434
- async list(ctx: RequestContext) {
1435
- ctx.json({ message: '${e} list' })
1436
- }
1437
- }
1438
- `);
1439
- }
1440
- async function xe(r) {
1441
- const { pascal: e, kebab: t, plural: o, pluralPascal: s, repo: i, noTests: n, prismaClientPath: a, write: c } = r;
1442
- await c("index.ts", ce({
1443
- pascal: e,
1444
- kebab: t,
1445
- plural: o,
1446
- repo: i
1447
- })), await c(`${t}.constants.ts`, J({
1448
- pascal: e,
1449
- kebab: t
1450
- })), await c(`${t}.controller.ts`, le({
1451
- pascal: e,
1452
- kebab: t,
1453
- plural: o,
1454
- pluralPascal: s
1455
- })), await c(`${t}.service.ts`, ge({
1456
- pascal: e,
1457
- kebab: t
1458
- })), await c(`dtos/create-${t}.dto.ts`, O({
1459
- pascal: e,
1460
- kebab: t
1461
- })), await c(`dtos/update-${t}.dto.ts`, I({
1462
- pascal: e,
1463
- kebab: t
1464
- })), await c(`dtos/${t}-response.dto.ts`, S({
1465
- pascal: e,
1466
- kebab: t
1467
- })), await c(`${t}.repository.ts`, A({
1468
- pascal: e,
1469
- kebab: t,
1470
- dtoPrefix: "./dtos"
1471
- }));
1472
- const d = {
1473
- inmemory: `in-memory-${t}`,
1474
- drizzle: `drizzle-${t}`,
1475
- prisma: `prisma-${t}`
1476
- }, u = {
1477
- inmemory: () => v({
1478
- pascal: e,
1479
- kebab: t,
1480
- repoPrefix: ".",
1481
- dtoPrefix: "./dtos"
1482
- }),
1483
- drizzle: () => M({
1484
- pascal: e,
1485
- kebab: t,
1486
- repoPrefix: ".",
1487
- dtoPrefix: "./dtos"
1488
- }),
1489
- prisma: () => q({
1490
- pascal: e,
1491
- kebab: t,
1492
- repoPrefix: ".",
1493
- dtoPrefix: "./dtos",
1494
- prismaClientPath: a
1495
- })
1496
- }, m = d[i] ?? `${y(i)}-${t}`, f = u[i] ?? (() => j({
1497
- pascal: e,
1498
- kebab: t,
1499
- repoType: i,
1500
- repoPrefix: ".",
1501
- dtoPrefix: "./dtos"
1502
- }));
1503
- await c(`${m}.repository.ts`, f()), n || (i !== "inmemory" && await c(`in-memory-${t}.repository.ts`, v({
1504
- pascal: e,
1505
- kebab: t,
1506
- repoPrefix: ".",
1507
- dtoPrefix: "./dtos"
1508
- })), await c(`__tests__/${t}.controller.test.ts`, E({
1509
- pascal: e,
1510
- kebab: t,
1511
- plural: o
1512
- })), await c(`__tests__/${t}.repository.test.ts`, U({
1513
- pascal: e,
1514
- kebab: t,
1515
- plural: o,
1516
- repoPrefix: `../${d.inmemory ?? `in-memory-${t}`}.repository`
1517
- })));
1518
- }
1519
- async function De(r) {
1520
- const { pascal: e, kebab: t, plural: o, pluralPascal: s, repo: i, noTests: n, prismaClientPath: a, write: c } = r;
1521
- await c("index.ts", he({
1522
- pascal: e,
1523
- kebab: t,
1524
- plural: o,
1525
- repo: i
1526
- })), await c(`${t}.constants.ts`, J({
1527
- pascal: e,
1528
- kebab: t
1529
- })), await c(`${t}.controller.ts`, ke({
1530
- pascal: e,
1531
- kebab: t,
1532
- plural: o,
1533
- pluralPascal: s
1534
- })), await c(`dtos/create-${t}.dto.ts`, O({
1535
- pascal: e,
1536
- kebab: t
1537
- })), await c(`dtos/update-${t}.dto.ts`, I({
1538
- pascal: e,
1539
- kebab: t
1540
- })), await c(`dtos/${t}-response.dto.ts`, S({
1541
- pascal: e,
1542
- kebab: t
1543
- }));
1544
- const d = ve({
1545
- pascal: e,
1546
- kebab: t
1547
- });
1548
- for (const $ of d) await c(`commands/${$.file}`, $.content);
1549
- const u = we({
1550
- pascal: e,
1551
- kebab: t,
1552
- plural: o,
1553
- pluralPascal: s
1554
- });
1555
- for (const $ of u) await c(`queries/${$.file}`, $.content);
1556
- const m = Re({
1557
- pascal: e,
1558
- kebab: t
1559
- });
1560
- for (const $ of m) await c(`events/${$.file}`, $.content);
1561
- await c(`${t}.repository.ts`, A({
1562
- pascal: e,
1563
- kebab: t,
1564
- dtoPrefix: "./dtos"
1565
- }));
1566
- const f = {
1567
- inmemory: `in-memory-${t}`,
1568
- drizzle: `drizzle-${t}`,
1569
- prisma: `prisma-${t}`
1570
- }, w = {
1571
- inmemory: () => v({
1572
- pascal: e,
1573
- kebab: t,
1574
- repoPrefix: ".",
1575
- dtoPrefix: "./dtos"
1576
- }),
1577
- drizzle: () => M({
1578
- pascal: e,
1579
- kebab: t,
1580
- repoPrefix: ".",
1581
- dtoPrefix: "./dtos"
1582
- }),
1583
- prisma: () => q({
1584
- pascal: e,
1585
- kebab: t,
1586
- repoPrefix: ".",
1587
- dtoPrefix: "./dtos",
1588
- prismaClientPath: a
1589
- })
1590
- }, k = f[i] ?? `${y(i)}-${t}`, h = w[i] ?? (() => j({
1591
- pascal: e,
1592
- kebab: t,
1593
- repoType: i,
1594
- repoPrefix: ".",
1595
- dtoPrefix: "./dtos"
1596
- }));
1597
- await c(`${k}.repository.ts`, h()), n || (i !== "inmemory" && await c(`in-memory-${t}.repository.ts`, v({
1598
- pascal: e,
1599
- kebab: t,
1600
- repoPrefix: ".",
1601
- dtoPrefix: "./dtos"
1602
- })), await c(`__tests__/${t}.controller.test.ts`, E({
1603
- pascal: e,
1604
- kebab: t,
1605
- plural: o
1606
- })), await c(`__tests__/${t}.repository.test.ts`, U({
1607
- pascal: e,
1608
- kebab: t,
1609
- plural: o,
1610
- repoPrefix: `../${f.inmemory ?? `in-memory-${t}`}.repository`
1611
- })));
1612
- }
1613
- async function Pe(r) {
1614
- const { pascal: e, kebab: t, plural: o, pluralPascal: s, repo: i, noEntity: n, noTests: a, prismaClientPath: c, write: d } = r;
1615
- await d("index.ts", ne({
1616
- pascal: e,
1617
- kebab: t,
1618
- plural: o,
1619
- repo: i
1620
- })), await d("constants.ts", i === "drizzle" ? Ce({
1621
- pascal: e,
1622
- kebab: t
1623
- }) : ue({
1624
- pascal: e,
1625
- kebab: t
1626
- })), await d(`presentation/${t}.controller.ts`, pe({
1627
- pascal: e,
1628
- kebab: t,
1629
- plural: o,
1630
- pluralPascal: s
1631
- })), await d(`application/dtos/create-${t}.dto.ts`, O({
1632
- pascal: e,
1633
- kebab: t
1634
- })), await d(`application/dtos/update-${t}.dto.ts`, I({
1635
- pascal: e,
1636
- kebab: t
1637
- })), await d(`application/dtos/${t}-response.dto.ts`, S({
1638
- pascal: e,
1639
- kebab: t
1640
- }));
1641
- const u = me({
1642
- pascal: e,
1643
- kebab: t,
1644
- plural: o,
1645
- pluralPascal: s
1646
- });
1647
- for (const h of u) await d(`application/use-cases/${h.file}`, h.content);
1648
- await d(`domain/repositories/${t}.repository.ts`, A({
1649
- pascal: e,
1650
- kebab: t
1651
- })), await d(`domain/services/${t}-domain.service.ts`, fe({
1652
- pascal: e,
1653
- kebab: t
1654
- }));
1655
- const m = {
1656
- inmemory: `in-memory-${t}`,
1657
- drizzle: `drizzle-${t}`,
1658
- prisma: `prisma-${t}`
1659
- }, f = {
1660
- inmemory: () => v({
1661
- pascal: e,
1662
- kebab: t
1663
- }),
1664
- drizzle: () => M({
1665
- pascal: e,
1666
- kebab: t
1667
- }),
1668
- prisma: () => q({
1669
- pascal: e,
1670
- kebab: t,
1671
- prismaClientPath: c
1672
- })
1673
- }, w = m[i] ?? `${y(i)}-${t}`, k = f[i] ?? (() => j({
1674
- pascal: e,
1675
- kebab: t,
1676
- repoType: i
1677
- }));
1678
- await d(`infrastructure/repositories/${w}.repository.ts`, k()), n || (await d(`domain/entities/${t}.entity.ts`, $e({
1679
- pascal: e,
1680
- kebab: t
1681
- })), await d(`domain/value-objects/${t}-id.vo.ts`, ye({
1682
- pascal: e,
1683
- kebab: t
1684
- }))), a || (i !== "inmemory" && await d(`infrastructure/repositories/in-memory-${t}.repository.ts`, v({
1685
- pascal: e,
1686
- kebab: t
1687
- })), await d(`__tests__/${t}.controller.test.ts`, E({
1688
- pascal: e,
1689
- kebab: t,
1690
- plural: o
1691
- })), await d(`__tests__/${t}.repository.test.ts`, U({
1692
- pascal: e,
1693
- kebab: t,
1694
- plural: o
1695
- })));
1696
- }
1697
- function it(r) {
1698
- return r ? typeof r == "string" ? r : r.name : "inmemory";
1699
- }
1700
- function Te(r) {
1701
- const e = ee({
1702
- input: process.stdin,
1703
- output: process.stdout
1704
- });
1705
- return new Promise((t) => {
1706
- e.question(r, (o) => {
1707
- e.close(), t(o.trim().toLowerCase());
1708
- });
1709
- });
1710
- }
1711
- async function at(r) {
1712
- const { name: e, modulesDir: t, noEntity: o, noTests: s, repo: i = "inmemory", force: n, dryRun: a } = r, c = r.pluralize !== !1;
1713
- let d = r.pattern ?? "ddd";
1714
- r.minimal && (d = "minimal");
1715
- const u = y(e), m = g(e), f = c ? Y(u) : u, w = c ? se(m) : m, k = p(t, f), h = [];
1716
- let $ = n ?? !1;
1717
- const Z = async (D, X) => {
1718
- const x = p(k, D);
1719
- if (a) {
1720
- h.push(x);
1721
- return;
1722
- }
1723
- if (!$ && await B(x)) {
1724
- const z = await Te(` File already exists: ${D}
1725
- Overwrite? (y/n/a = yes/no/all) `);
1726
- if (z === "a") $ = !0;
1727
- else if (z !== "y") {
1728
- console.log(` Skipped: ${D}`);
1729
- return;
1730
- }
1731
- }
1732
- await l(x, X), h.push(x);
1733
- }, b = {
1734
- kebab: u,
1735
- pascal: m,
1736
- plural: f,
1737
- pluralPascal: w,
1738
- moduleDir: k,
1739
- repo: i,
1740
- noEntity: o ?? !1,
1741
- noTests: s ?? !1,
1742
- prismaClientPath: r.prismaClientPath ?? "@prisma/client",
1743
- write: Z,
1744
- files: h
1745
- };
1746
- switch (d) {
1747
- case "minimal":
1748
- await be(b);
1749
- break;
1750
- case "rest":
1751
- await xe(b);
1752
- break;
1753
- case "cqrs":
1754
- await De(b);
1755
- break;
1756
- default:
1757
- await Pe(b);
1758
- break;
1759
- }
1760
- return a || await Oe(t, m, f), h;
1761
- }
1762
- async function Oe(r, e, t) {
1763
- const o = p(r, "index.ts");
1764
- if (!await B(o)) {
1765
- await l(o, `import type { AppModuleClass } from '@forinda/kickjs'
1766
- import { ${e}Module } from './${t}'
1767
-
1768
- export const modules: AppModuleClass[] = [${e}Module]
1769
- `);
1770
- return;
1771
- }
1772
- let s = await L(o, "utf-8");
1773
- const i = `import { ${e}Module } from './${t}'`;
1774
- if (!s.includes(`${e}Module`)) {
1775
- const n = s.lastIndexOf("import ");
1776
- if (n !== -1) {
1777
- const a = s.indexOf(`
1778
- `, n);
1779
- s = s.slice(0, a + 1) + i + `
1780
- ` + s.slice(a + 1);
1781
- } else s = i + `
1782
- ` + s;
1783
- s = s.replace(/(=\s*\[)([\s\S]*?)(])/, (a, c, d, u) => {
1784
- const m = d.trim();
1785
- if (!m) return `${c}${e}Module${u}`;
1786
- const f = m.endsWith(",") ? "" : ",";
1787
- return `${c}${d.trimEnd()}${f} ${e}Module${u}`;
1788
- });
1789
- }
1790
- await N(o, s, "utf-8");
1791
- }
1792
- async function nt(r) {
1793
- const { name: e, outDir: t } = r, o = y(e), s = g(e), i = [], n = p(t, `${o}.adapter.ts`);
1794
- return await l(n, `import type { AppAdapter, AdapterContext, AdapterMiddleware } from '@forinda/kickjs'
1795
-
1796
- export interface ${s}AdapterOptions {
1797
- // Add your adapter configuration here
1798
- }
1799
-
1800
- /**
1801
- * ${s} adapter.
1802
- *
1803
- * Hooks into the Application lifecycle to add middleware, routes,
1804
- * or external service connections.
1805
- *
1806
- * Usage:
1807
- * bootstrap({
1808
- * adapters: [new ${s}Adapter({ ... })],
1809
- * })
1810
- */
1811
- export class ${s}Adapter implements AppAdapter {
1812
- name = '${s}Adapter'
1813
-
1814
- constructor(private options: ${s}AdapterOptions = {}) {}
1815
-
1816
- /**
1817
- * Return middleware entries that the Application will mount.
1818
- * Use \`phase\` to control where in the pipeline they run:
1819
- * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'
1820
- */
1821
- middleware(): AdapterMiddleware[] {
1822
- return [
1823
- // Example: add a custom header to all responses
1824
- // {
1825
- // phase: 'beforeGlobal',
1826
- // handler: (_req: any, res: any, next: any) => {
1827
- // res.setHeader('X-${s}', 'true')
1828
- // next()
1829
- // },
1830
- // },
1831
- // Example: scope middleware to a specific path
1832
- // {
1833
- // phase: 'beforeRoutes',
1834
- // path: '/api/v1/admin',
1835
- // handler: myAdminMiddleware(),
1836
- // },
1837
- ]
1838
- }
1839
-
1840
- /**
1841
- * Called before global middleware.
1842
- * Use this to mount routes that bypass the middleware stack
1843
- * (health checks, docs UI, static assets).
1844
- */
1845
- beforeMount({ app }: AdapterContext): void {
1846
- // Example: mount a status route
1847
- // app.get('/${o}/status', (_req, res) => {
1848
- // res.json({ status: 'ok' })
1849
- // })
1850
- }
1851
-
1852
- /**
1853
- * Called after modules and routes are registered, before the server starts.
1854
- * Use this for late-stage DI registrations or config validation.
1855
- */
1856
- beforeStart({ container }: AdapterContext): void {
1857
- // Example: register a service in the DI container
1858
- // container.registerInstance(MY_TOKEN, new MyService(this.options))
1859
- }
1860
-
1861
- /**
1862
- * Called after the HTTP server is listening.
1863
- * Use this to attach to the raw http.Server (Socket.IO, gRPC, etc).
1864
- */
1865
- afterStart({ server, container }: AdapterContext): void {
1866
- // Example: attach Socket.IO
1867
- // const io = new Server(server)
1868
- // container.registerInstance(SOCKET_IO, io)
1869
- }
1870
-
1871
- /**
1872
- * Called on graceful shutdown. Clean up connections.
1873
- */
1874
- async shutdown(): Promise<void> {
1875
- // Example: close a connection pool
1876
- // await this.pool.end()
1877
- }
1878
- }
1879
- `), i.push(n), i;
1880
- }
1881
- var Ie = {
1882
- controller: "presentation",
1883
- service: "domain/services",
1884
- dto: "application/dtos",
1885
- guard: "presentation/guards",
1886
- middleware: "middleware"
1887
- }, Se = {
1888
- controller: "",
1889
- service: "",
1890
- dto: "dtos",
1891
- guard: "guards",
1892
- middleware: "middleware"
1893
- }, Ae = {
1894
- controller: "",
1895
- service: "",
1896
- dto: "dtos",
1897
- guard: "guards",
1898
- middleware: "middleware",
1899
- command: "commands",
1900
- query: "queries",
1901
- event: "events"
1902
- };
1903
- function C(r) {
1904
- const { type: e, outDir: t, moduleName: o, modulesDir: s = "src/modules", defaultDir: i, pattern: n = "ddd" } = r;
1905
- if (t) return P(t);
1906
- if (o) {
1907
- const a = n === "ddd" ? Ie : n === "cqrs" ? Ae : Se, c = Y(y(o)), d = a[e] ?? "", u = p(s, c);
1908
- return P(d ? p(u, d) : u);
1909
- }
1910
- return P(i);
1911
- }
1912
- async function ct(r) {
1913
- const { name: e, moduleName: t, modulesDir: o, pattern: s } = r, i = C({
1914
- type: "middleware",
1915
- outDir: r.outDir,
1916
- moduleName: t,
1917
- modulesDir: o,
1918
- defaultDir: "src/middleware",
1919
- pattern: s
1920
- }), n = y(e), a = T(e), c = [], d = p(i, `${n}.middleware.ts`);
1921
- return await l(d, `import type { Request, Response, NextFunction } from 'express'
1922
-
1923
- export interface ${g(e)}Options {
1924
- // Add configuration options here
1925
- }
1926
-
1927
- /**
1928
- * ${g(e)} middleware.
1929
- *
1930
- * Usage in bootstrap:
1931
- * middleware: [${a}()]
1932
- *
1933
- * Usage with adapter:
1934
- * middleware() { return [{ handler: ${a}(), phase: 'afterGlobal' }] }
1935
- *
1936
- * Usage with @Middleware decorator:
1937
- * @Middleware(${a}())
1938
- */
1939
- export function ${a}(options: ${g(e)}Options = {}) {
1940
- return (req: Request, res: Response, next: NextFunction) => {
1941
- // Implement your middleware logic here
1942
- next()
1943
- }
1944
- }
1945
- `), c.push(d), c;
1946
- }
1947
- async function dt(r) {
1948
- const { name: e, moduleName: t, modulesDir: o, pattern: s } = r, i = C({
1949
- type: "guard",
1950
- outDir: r.outDir,
1951
- moduleName: t,
1952
- modulesDir: o,
1953
- defaultDir: "src/guards",
1954
- pattern: s
1955
- }), n = y(e), a = T(e), c = g(e), d = [], u = p(i, `${n}.guard.ts`);
1956
- return await l(u, `import { Container, HttpException } from '@forinda/kickjs'
1957
- import type { RequestContext } from '@forinda/kickjs'
1958
-
1959
- /**
1960
- * ${c} guard.
1961
- *
1962
- * Guards protect routes by checking conditions before the handler runs.
1963
- * Return early with an error response to block access.
1964
- *
1965
- * Usage:
1966
- * @Middleware(${a}Guard)
1967
- * @Get('/protected')
1968
- * async handler(ctx: RequestContext) { ... }
1969
- */
1970
- export async function ${a}Guard(ctx: RequestContext, next: () => void): Promise<void> {
1971
- // Example: check for an authorization header
1972
- const header = ctx.headers.authorization
1973
- if (!header?.startsWith('Bearer ')) {
1974
- ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
1975
- return
1976
- }
1977
-
1978
- const token = header.slice(7)
1979
-
1980
- try {
1981
- // Verify the token using a service from the DI container
1982
- // const container = Container.getInstance()
1983
- // const authService = container.resolve(AuthService)
1984
- // const payload = authService.verifyToken(token)
1985
- // ctx.set('auth', payload)
1986
-
1987
- next()
1988
- } catch {
1989
- ctx.res.status(401).json({ message: 'Invalid or expired token' })
1990
- }
1991
- }
1992
- `), d.push(u), d;
1993
- }
1994
- async function pt(r) {
1995
- const { name: e, moduleName: t, modulesDir: o, pattern: s } = r, i = C({
1996
- type: "service",
1997
- outDir: r.outDir,
1998
- moduleName: t,
1999
- modulesDir: o,
2000
- defaultDir: "src/services",
2001
- pattern: s
2002
- }), n = y(e), a = g(e), c = [], d = p(i, `${n}.service.ts`);
2003
- return await l(d, `import { Service } from '@forinda/kickjs'
2004
-
2005
- @Service()
2006
- export class ${a}Service {
2007
- // Inject dependencies via constructor
2008
- // constructor(
2009
- // @Inject(MY_REPO) private readonly repo: IMyRepository,
2010
- // ) {}
2011
- }
2012
- `), c.push(d), c;
2013
- }
2014
- async function lt(r) {
2015
- const { name: e, moduleName: t, modulesDir: o, pattern: s } = r, i = C({
2016
- type: "controller",
2017
- outDir: r.outDir,
2018
- moduleName: t,
2019
- modulesDir: o,
2020
- defaultDir: "src/controllers",
2021
- pattern: s
2022
- }), n = y(e), a = g(e), c = [], d = p(i, `${n}.controller.ts`);
2023
- return await l(d, `import { Controller, Get, Post, Autowired } from '@forinda/kickjs'
2024
- import type { RequestContext } from '@forinda/kickjs'
2025
-
2026
- @Controller()
2027
- export class ${a}Controller {
2028
- // @Autowired() private myService!: MyService
2029
-
2030
- @Get('/')
2031
- async list(ctx: RequestContext) {
2032
- ctx.json({ message: '${a} list' })
2033
- }
2034
-
2035
- @Post('/')
2036
- async create(ctx: RequestContext) {
2037
- ctx.created({ message: '${a} created', data: ctx.body })
2038
- }
2039
- }
2040
- `), c.push(d), c;
2041
- }
2042
- async function ut(r) {
2043
- const { name: e, moduleName: t, modulesDir: o, pattern: s } = r, i = C({
2044
- type: "dto",
2045
- outDir: r.outDir,
2046
- moduleName: t,
2047
- modulesDir: o,
2048
- defaultDir: "src/dtos",
2049
- pattern: s
2050
- }), n = y(e), a = g(e), c = T(e), d = [], u = p(i, `${n}.dto.ts`);
2051
- return await l(u, `import { z } from 'zod'
2052
-
2053
- export const ${c}Schema = z.object({
2054
- // Define your schema fields here
2055
- name: z.string().min(1).max(200),
2056
- })
2057
-
2058
- export type ${a}DTO = z.infer<typeof ${c}Schema>
2059
- `), d.push(u), d;
2060
- }
2061
- function je(r, e, t) {
2062
- const o = {
2063
- "@forinda/kickjs": t,
2064
- "@forinda/kickjs-config": t,
2065
- express: "^5.1.0",
2066
- "reflect-metadata": "^0.2.2",
2067
- zod: "^4.3.6",
2068
- pino: "^10.3.1",
2069
- "pino-pretty": "^13.1.3"
2070
- };
2071
- return e !== "minimal" && (o["@forinda/kickjs-swagger"] = t, o["@forinda/kickjs-devtools"] = t), e === "graphql" && (o["@forinda/kickjs-graphql"] = t, o.graphql = "^16.11.0"), e === "cqrs" && (o["@forinda/kickjs-queue"] = t, o["@forinda/kickjs-ws"] = t, o["@forinda/kickjs-otel"] = t), e === "ddd" && (o["@forinda/kickjs-swagger"] = t), JSON.stringify({
2072
- name: r,
2073
- version: t.replace("^", ""),
2074
- type: "module",
2075
- scripts: {
2076
- dev: "kick dev",
2077
- "dev:debug": "kick dev:debug",
2078
- build: "kick build",
2079
- start: "kick start",
2080
- test: "vitest run",
2081
- "test:watch": "vitest",
2082
- typecheck: "tsc --noEmit",
2083
- lint: "eslint src/",
2084
- format: "prettier --write src/"
2085
- },
2086
- dependencies: o,
2087
- devDependencies: {
2088
- "@forinda/kickjs-cli": t,
2089
- "@swc/core": "^1.7.28",
2090
- "@types/express": "^5.0.6",
2091
- "@types/node": "^25.0.0",
2092
- "unplugin-swc": "^1.5.9",
2093
- vite: "^8.0.2",
2094
- vitest: "^4.1.1",
2095
- typescript: "^5.9.2",
2096
- prettier: "^3.8.1"
2097
- }
2098
- }, null, 2);
2099
- }
2100
- function Ee() {
2101
- return `import { defineConfig } from 'vite'
2102
- import { resolve } from 'path'
2103
- import swc from 'unplugin-swc'
2104
-
2105
- export default defineConfig({
2106
- oxc: false,
2107
- plugins: [swc.vite()],
2108
- resolve: {
2109
- alias: {
2110
- '@': resolve(__dirname, 'src'),
2111
- },
2112
- },
2113
- ssr: {
2114
- // Don't bundle pino — its worker-thread transport needs Node.js resolution
2115
- // to find pino-pretty at runtime for colored log output
2116
- external: ['pino', 'pino-pretty'],
2117
- },
2118
- server: {
2119
- watch: { usePolling: false },
2120
- hmr: true,
2121
- },
2122
- build: {
2123
- target: 'node20',
2124
- ssr: true,
2125
- outDir: 'dist',
2126
- sourcemap: true,
2127
- rollupOptions: {
2128
- input: resolve(__dirname, 'src/index.ts'),
2129
- output: { format: 'esm' },
2130
- },
2131
- },
2132
- })
2133
- `;
2134
- }
2135
- function Ue() {
2136
- return JSON.stringify({
2137
- compilerOptions: {
2138
- target: "ES2022",
2139
- module: "ESNext",
2140
- moduleResolution: "bundler",
2141
- lib: ["ES2022"],
2142
- types: ["node", "vite/client"],
2143
- strict: !0,
2144
- esModuleInterop: !0,
2145
- skipLibCheck: !0,
2146
- sourceMap: !0,
2147
- declaration: !0,
2148
- experimentalDecorators: !0,
2149
- emitDecoratorMetadata: !0,
2150
- outDir: "dist",
2151
- rootDir: "src",
2152
- paths: { "@/*": ["./src/*"] }
2153
- },
2154
- include: ["src"]
2155
- }, null, 2);
2156
- }
2157
- function Me() {
2158
- return JSON.stringify({
2159
- semi: !1,
2160
- singleQuote: !0,
2161
- trailingComma: "all",
2162
- printWidth: 100,
2163
- tabWidth: 2
2164
- }, null, 2);
2165
- }
2166
- function qe() {
2167
- return `# https://editorconfig.org
2168
- root = true
2169
-
2170
- [*]
2171
- indent_style = space
2172
- indent_size = 2
2173
- end_of_line = lf
2174
- charset = utf-8
2175
- trim_trailing_whitespace = true
2176
- insert_final_newline = true
2177
-
2178
- [*.md]
2179
- trim_trailing_whitespace = false
2180
- `;
2181
- }
2182
- function ze() {
2183
- return `node_modules/
2184
- dist/
2185
- .env
2186
- coverage/
2187
- .DS_Store
2188
- *.tsbuildinfo
2189
- `;
2190
- }
2191
- function _e() {
2192
- return `# Auto-detect text files and normalise line endings to LF
2193
- * text=auto eol=lf
2194
-
2195
- # Explicitly mark generated / binary files
2196
- *.png binary
2197
- *.jpg binary
2198
- *.jpeg binary
2199
- *.gif binary
2200
- *.ico binary
2201
- *.woff binary
2202
- *.woff2 binary
2203
- *.ttf binary
2204
- *.eot binary
2205
-
2206
- # Lock files — treat as generated
2207
- pnpm-lock.yaml -diff linguist-generated
2208
- yarn.lock -diff linguist-generated
2209
- package-lock.json -diff linguist-generated
2210
- `;
2211
- }
2212
- function Ge() {
2213
- return `PORT=3000
2214
- NODE_ENV=development
2215
- `;
2216
- }
2217
- function Qe() {
2218
- return `PORT=3000
2219
- NODE_ENV=development
2220
- `;
2221
- }
2222
- function Fe() {
2223
- return `import { defineConfig } from 'vitest/config'
2224
- import swc from 'unplugin-swc'
2225
-
2226
- export default defineConfig({
2227
- plugins: [swc.vite()],
2228
- test: {
2229
- globals: true,
2230
- environment: 'node',
2231
- include: ['src/**/*.test.ts'],
2232
- },
2233
- })
2234
- `;
2235
- }
2236
- function Le(r, e, t) {
2237
- switch (e) {
2238
- case "graphql":
2239
- return `import 'reflect-metadata'
2240
- import { bootstrap } from '@forinda/kickjs'
2241
- import { DevToolsAdapter } from '@forinda/kickjs-devtools'
2242
- import { GraphQLAdapter } from '@forinda/kickjs-graphql'
2243
- import { modules } from './modules'
2244
-
2245
- // Import your resolvers here
2246
- // import { UserResolver } from './resolvers/user.resolver'
2247
-
2248
- bootstrap({
2249
- modules,
2250
- adapters: [
2251
- new DevToolsAdapter(),
2252
- new GraphQLAdapter({
2253
- resolvers: [/* UserResolver */],
2254
- // Add custom type definitions here:
2255
- // typeDefs: userTypeDefs,
2256
- }),
2257
- ],
2258
- })
2259
- `;
2260
- case "cqrs":
2261
- return `import 'reflect-metadata'
2262
- import { bootstrap } from '@forinda/kickjs'
2263
- import { DevToolsAdapter } from '@forinda/kickjs-devtools'
2264
- import { SwaggerAdapter } from '@forinda/kickjs-swagger'
2265
- import { OtelAdapter } from '@forinda/kickjs-otel'
2266
- // import { WsAdapter } from '@forinda/kickjs-ws'
2267
- // import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
2268
- import { modules } from './modules'
2269
-
2270
- bootstrap({
2271
- modules,
2272
- adapters: [
2273
- new OtelAdapter({ serviceName: '${r}' }),
2274
- new DevToolsAdapter(),
2275
- new SwaggerAdapter({
2276
- info: { title: '${r}', version: '${t}' },
2277
- }),
2278
- // Uncomment for WebSocket support:
2279
- // new WsAdapter(),
2280
- // Uncomment when Redis is available:
2281
- // new QueueAdapter({
2282
- // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),
2283
- // }),
2284
- ],
2285
- })
2286
- `;
2287
- case "minimal":
2288
- return `import 'reflect-metadata'
2289
- import { bootstrap } from '@forinda/kickjs'
2290
- import { modules } from './modules'
2291
-
2292
- bootstrap({ modules })
2293
- `;
2294
- default:
2295
- return `import 'reflect-metadata'
2296
- import { bootstrap } from '@forinda/kickjs'
2297
- import { DevToolsAdapter } from '@forinda/kickjs-devtools'
2298
- import { SwaggerAdapter } from '@forinda/kickjs-swagger'
2299
- import { modules } from './modules'
2300
-
2301
- bootstrap({
2302
- modules,
2303
- adapters: [
2304
- new DevToolsAdapter(),
2305
- new SwaggerAdapter({
2306
- info: { title: '${r}', version: '${t}' },
2307
- }),
2308
- ],
2309
- })
2310
- `;
2311
- }
2312
- }
2313
- function Ne() {
2314
- return `import type { AppModuleClass } from '@forinda/kickjs'
2315
-
2316
- export const modules: AppModuleClass[] = []
2317
- `;
2318
- }
2319
- function We(r, e = "inmemory") {
2320
- return `import { defineConfig } from '@forinda/kickjs-cli'
2321
-
2322
- export default defineConfig({
2323
- pattern: '${r}',
2324
- modules: {
2325
- dir: 'src/modules',
2326
- repo: '${e}',
2327
- pluralize: true,
2328
- },
2329
-
2330
- commands: [
2331
- {
2332
- name: 'test',
2333
- description: 'Run tests with Vitest',
2334
- steps: 'npx vitest run',
2335
- },
2336
- {
2337
- name: 'format',
2338
- description: 'Format code with Prettier',
2339
- steps: 'npx prettier --write src/',
2340
- },
2341
- {
2342
- name: 'format:check',
2343
- description: 'Check formatting without writing',
2344
- steps: 'npx prettier --check src/',
2345
- },
2346
- {
2347
- name: 'check',
2348
- description: 'Run typecheck + format check',
2349
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
2350
- aliases: ['verify', 'ci'],
2351
- },
2352
- ],
2353
- })
2354
- `;
2355
- }
2356
- function Be(r, e, t) {
2357
- const o = {
2358
- rest: "REST API",
2359
- graphql: "GraphQL API",
2360
- ddd: "Domain-Driven Design",
2361
- cqrs: "CQRS + Event-Driven",
2362
- minimal: "Minimal"
2363
- }, s = [
2364
- "@forinda/kickjs-core",
2365
- "@forinda/kickjs-http",
2366
- "@forinda/kickjs-config"
2367
- ];
2368
- return e !== "minimal" && s.push("@forinda/kickjs-swagger", "@forinda/kickjs-devtools"), e === "graphql" && s.push("@forinda/kickjs-graphql"), e === "cqrs" && s.push("@forinda/kickjs-queue", "@forinda/kickjs-ws", "@forinda/kickjs-otel"), `# ${r}
2369
-
2370
- A **${o[e] ?? "REST API"}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
2371
-
2372
- ## Getting Started
2373
-
2374
- \`\`\`bash
2375
- ${t} install
2376
- kick dev
2377
- \`\`\`
2378
-
2379
- ## Scripts
2380
-
2381
- | Command | Description |
2382
- |---|---|
2383
- | \`kick dev\` | Start dev server with Vite HMR |
2384
- | \`kick build\` | Production build |
2385
- | \`kick start\` | Run production build |
2386
- | \`${t} run test\` | Run tests with Vitest |
2387
- | \`kick g module <name>\` | Generate a DDD module |
2388
- | \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
2389
- | \`kick add <package>\` | Add a KickJS package |
2390
-
2391
- ## Project Structure
2392
-
2393
- \`\`\`
2394
- src/
2395
- ├── index.ts # Application entry point
2396
- ├── modules/ # Feature modules (controllers, services, repos)
2397
- │ └── index.ts # Module registry
2398
- └── ...
2399
- \`\`\`
2400
-
2401
- ## Packages
2402
-
2403
- ${s.map((i) => `- \`${i}\``).join(`
2404
- `)}
2405
-
2406
- ## Adding Features
2407
-
2408
- \`\`\`bash
2409
- kick add auth # Authentication (JWT, API key, OAuth)
2410
- kick add swagger # OpenAPI documentation
2411
- kick add ws # WebSocket support
2412
- kick add queue # Background job processing
2413
- kick add mailer # Email sending
2414
- kick add cron # Scheduled tasks
2415
- kick add --list # Show all available packages
2416
- \`\`\`
2417
-
2418
- ## Environment Variables
2419
-
2420
- Copy \`.env.example\` to \`.env\` and configure:
2421
-
2422
- | Variable | Default | Description |
2423
- |---|---|---|
2424
- | \`PORT\` | \`3000\` | Server port |
2425
- | \`NODE_ENV\` | \`development\` | Environment |
2426
-
2427
- ## Learn More
2428
-
2429
- - [KickJS Documentation](https://forinda.github.io/kick-js/)
2430
- - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
2431
- `;
2432
- }
2433
- function Ye(r, e, t) {
2434
- return `# CLAUDE.md — ${r} Development Guide
2435
-
2436
- ## Project Overview
2437
-
2438
- This is a **${{
2439
- rest: "REST API",
2440
- graphql: "GraphQL API",
2441
- ddd: "Domain-Driven Design",
2442
- cqrs: "CQRS + Event-Driven",
2443
- minimal: "Minimal Express"
2444
- }[e] ?? "REST API"}** application built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
2445
-
2446
- ## Quick Commands
2447
-
2448
- \`\`\`bash
2449
- ${t} install # Install dependencies
2450
- kick dev # Start dev server with HMR
2451
- kick build # Production build via Vite
2452
- kick start # Run production build
2453
- ${t} run test # Run tests with Vitest
2454
- ${t} run typecheck # TypeScript type checking
2455
- ${t} run format # Format code with Prettier
2456
- \`\`\`
2457
-
2458
- ## Project Structure
2459
-
2460
- \`\`\`
2461
- src/
2462
- ├── index.ts # Application bootstrap
2463
- ├── modules/ # Feature modules (DDD/CQRS pattern)
2464
- │ └── index.ts # Module registry
2465
- ${e === "graphql" ? `├── resolvers/ # GraphQL resolvers
2466
- ` : ""}└── ...
2467
- \`\`\`
2468
-
2469
- ## Package Manager
2470
-
2471
- - Always use **${t}** for this project
2472
- - Run \`${t} install\` to sync dependencies
2473
- - Never mix package managers (npm/yarn/pnpm)
2474
-
2475
- ## Code Style
2476
-
2477
- - **Prettier** — no semicolons, single quotes, trailing commas, 100 char width
2478
- - **TypeScript strict mode** — all types required
2479
- - Format before committing: \`${t} run format\`
2480
- - Type check with: \`${t} run typecheck\`
2481
-
2482
- ## Key Patterns
2483
-
2484
- ### Controllers
2485
-
2486
- Use decorators to define routes:
2487
-
2488
- \`\`\`ts
2489
- import { Controller, Get, Post, RequestContext } from '@forinda/kickjs'
2490
-
2491
- @Controller('/users')
2492
- export class UserController {
2493
- @Get('/')
2494
- async findAll(ctx: RequestContext) {
2495
- return ctx.json({ users: [] })
2496
- }
2497
-
2498
- @Post('/')
2499
- async create(ctx: RequestContext) {
2500
- const data = ctx.body
2501
- return ctx.created({ user: data })
2502
- }
2503
- }
2504
- \`\`\`
2505
-
2506
- ### Services
2507
-
2508
- Inject dependencies with \`@Service()\` and \`@Autowired()\`:
2509
-
2510
- \`\`\`ts
2511
- import { Service, Autowired } from '@forinda/kickjs'
2512
-
2513
- @Service()
2514
- export class UserService {
2515
- @Autowired()
2516
- private userRepository!: UserRepository
2517
-
2518
- async findAll() {
2519
- return this.userRepository.findAll()
2520
- }
2521
- }
2522
- \`\`\`
2523
-
2524
- ### Modules
2525
-
2526
- Register controllers and providers in modules:
2527
-
2528
- \`\`\`ts
2529
- import { Module } from '@forinda/kickjs'
2530
- import { UserController } from './user.controller'
2531
- import { UserService } from './user.service'
2532
-
2533
- @Module({
2534
- controllers: [UserController],
2535
- providers: [UserService],
2536
- })
2537
- export class UserModule {}
2538
- \`\`\`
2539
-
2540
- ### RequestContext
2541
-
2542
- Every controller method receives \`ctx: RequestContext\`:
2543
-
2544
- \`\`\`ts
2545
- ctx.body // Request body (parsed JSON)
2546
- ctx.params // Route params
2547
- ctx.query // Query string
2548
- ctx.headers // Request headers
2549
- ctx.requestId // Auto-generated request ID
2550
- ctx.session // Session data (if session middleware enabled)
2551
- ctx.file // Uploaded file (single)
2552
- ctx.files // Uploaded files (multiple)
2553
-
2554
- // Pagination helpers
2555
- ctx.qs(config) // Parse query with filters/sort/pagination
2556
- ctx.paginate(handler) // Auto-paginated response
2557
-
2558
- // Response helpers
2559
- ctx.json(data) // 200 OK with JSON
2560
- ctx.created(data) // 201 Created
2561
- ctx.noContent() // 204 No Content
2562
- ctx.notFound() // 404 Not Found
2563
- ctx.badRequest(msg) // 400 Bad Request
2564
- \`\`\`
2565
-
2566
- ## CLI Generators
2567
-
2568
- Generate code with the \`kick\` CLI:
2569
-
2570
- \`\`\`bash
2571
- kick g module <name> # Full module (controller, service, DTOs, repo)
2572
- kick g scaffold <name> <fields> # CRUD module from field definitions
2573
- kick g controller <name> # Standalone controller
2574
- kick g service <name> # Service class
2575
- kick g middleware <name> # Express middleware
2576
- kick g guard <name> # Route guard (auth, roles)
2577
- kick g adapter <name> # AppAdapter with lifecycle hooks
2578
- kick g dto <name> # Zod DTO schema
2579
- ${e === "graphql" ? `kick g resolver <name> # GraphQL resolver
2580
- ` : ""}${e === "cqrs" ? `kick g job <name> # Queue job processor
2581
- ` : ""}\`\`\`
2582
-
2583
- ## Adding Packages
2584
-
2585
- \`\`\`bash
2586
- kick add auth # JWT, API key, OAuth strategies
2587
- kick add swagger # OpenAPI docs from decorators
2588
- kick add ws # WebSocket support
2589
- kick add queue # Background jobs (BullMQ/RabbitMQ/Kafka)
2590
- kick add mailer # Email (SMTP, Resend, SES)
2591
- kick add cron # Scheduled tasks
2592
- kick add prisma # Prisma ORM adapter
2593
- kick add drizzle # Drizzle ORM adapter
2594
- kick add otel # OpenTelemetry tracing
2595
- kick add --list # Show all available packages
2596
- \`\`\`
2597
-
2598
- ## Environment Configuration
2599
-
2600
- Edit \`.env\` for environment variables. Access them with \`@Value()\` decorator:
2601
-
2602
- \`\`\`ts
2603
- import { Value } from '@forinda/kickjs-config'
2604
-
2605
- @Service()
2606
- export class ApiService {
2607
- @Value('API_KEY')
2608
- private apiKey!: string
2609
-
2610
- @Value('PORT', 3000) // With default
2611
- private port!: number
2612
- }
2613
- \`\`\`
2614
-
2615
- Or use \`ConfigService\`:
2616
-
2617
- \`\`\`ts
2618
- import { ConfigService } from '@forinda/kickjs-config'
2619
-
2620
- @Service()
2621
- export class AppService {
2622
- @Autowired()
2623
- private config!: ConfigService
2624
-
2625
- getPort() {
2626
- return this.config.get('PORT', 3000)
2627
- }
2628
- }
2629
- \`\`\`
2630
-
2631
- ## Testing
2632
-
2633
- Tests live in \`src/**/*.test.ts\`:
2634
-
2635
- \`\`\`ts
2636
- import { describe, it, expect, beforeEach } from 'vitest'
2637
- import { Container } from '@forinda/kickjs'
2638
- import { createTestApp } from '@forinda/kickjs-testing'
2639
-
2640
- describe('UserController', () => {
2641
- beforeEach(() => Container.reset())
2642
-
2643
- it('should return users', async () => {
2644
- const app = await createTestApp([UserModule])
2645
- const res = await app.get('/users')
2646
- expect(res.status).toBe(200)
2647
- })
2648
- })
2649
- \`\`\`
2650
-
2651
- Run tests:
2652
- - \`${t} run test\` — run all tests
2653
- - \`${t} run test:watch\` — watch mode
2654
-
2655
- ## Decorators Reference
2656
-
2657
- ### Route Decorators
2658
- - \`@Controller('/path')\` — define controller prefix
2659
- - \`@Get('/'), @Post('/'), @Put('/'), @Delete('/'), @Patch('/')\` — HTTP methods
2660
- - \`@Middleware(fn)\` — attach middleware
2661
- - \`@Public()\` — skip authentication (requires @forinda/kickjs-auth)
2662
- - \`@Roles('admin', 'user')\` — role-based access control
2663
-
2664
- ### DI Decorators
2665
- - \`@Module({ controllers, providers, imports })\` — define module
2666
- - \`@Service()\` — singleton service (DI-registered)
2667
- - \`@Repository()\` — repository (semantic alias for @Service)
2668
- - \`@Autowired()\` — property injection
2669
- - \`@Inject('token')\` — token-based injection
2670
- - \`@Value('ENV_VAR')\` — inject config value
2671
-
2672
- ${e === "cqrs" ? "### CQRS/Event Decorators\n- `@Job('job-name')` — queue job handler\n- `@Process('queue-name')` — queue processor\n- `@Cron('0 * * * *')` — cron schedule\n- `@WsController('/path')` — WebSocket controller\n- `@Subscribe('event')` — WebSocket event handler\n\n" : ""}${e === "graphql" ? "### GraphQL Decorators\n- `@Resolver()` — GraphQL resolver\n- `@Query()` — GraphQL query\n- `@Mutation()` — GraphQL mutation\n- `@Arg('name')` — resolver argument\n\n" : ""}## Common Pitfalls
2673
-
2674
- 1. **Decorators fire at import time** — make sure to import module classes in \`src/modules/index.ts\`
2675
- 2. **Tests need \`Container.reset()\`** — call in \`beforeEach\` to isolate DI state
2676
- 3. **Always use \`ctx.body\`** — never \`req.body\` directly
2677
- 4. **DI requires \`reflect-metadata\`** — already imported in \`src/index.ts\`
2678
- 5. **Vite HMR requires proper cleanup** — adapters should implement \`shutdown()\`
2679
-
2680
- ## Learn More
2681
-
2682
- - [KickJS Documentation](https://forinda.github.io/kick-js/)
2683
- - [API Reference](https://forinda.github.io/kick-js/api/)
2684
- - [CLI Commands](https://forinda.github.io/kick-js/guide/cli-commands.html)
2685
- - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
2686
- `;
2687
- }
2688
- function He(r, e, t) {
2689
- return `# AGENTS.md — AI Agent Guide for ${r}
2690
-
2691
- This guide helps AI agents (Claude, Copilot, etc.) work effectively on this KickJS application.
2692
-
2693
- ## Before You Start
2694
-
2695
- 1. Read \`CLAUDE.md\` for project conventions and commands
2696
- 2. Run \`${t} install\` to install dependencies
2697
- 3. Run \`kick dev\` to verify the app starts
2698
- 4. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
2699
-
2700
- ## Where to Find Things
2701
-
2702
- ### Application Structure
2703
-
2704
- | What | Where |
2705
- |------|-------|
2706
- | Entry point | \`src/index.ts\` |
2707
- | Module registry | \`src/modules/index.ts\` |
2708
- | Feature modules | \`src/modules/<module-name>/\` |
2709
- ${e === "graphql" ? "| GraphQL resolvers | `src/resolvers/` |\n" : ""}| Environment config | \`.env\` |
2710
- | TypeScript config | \`tsconfig.json\` |
2711
- | Vite config (HMR) | \`vite.config.ts\` |
2712
- | Vitest config | \`vitest.config.ts\` |
2713
- | Prettier config | \`.prettierrc\` |
2714
- | CLI config | \`kick.config.ts\` |
2715
-
2716
- ### Module Pattern (${e.toUpperCase()})
2717
-
2718
- Each module in \`src/modules/<name>/\` typically contains:
2719
-
2720
- ${e === "ddd" ? `\`\`\`
2721
- <name>/
2722
- ├── <name>.controller.ts # HTTP routes (@Controller)
2723
- ├── <name>.service.ts # Business logic (@Service)
2724
- ├── <name>.repository.ts # Data access (@Repository)
2725
- ├── <name>.dto.ts # Request/response schemas (Zod)
2726
- ├── <name>.entity.ts # Domain entity (optional)
2727
- └── <name>.module.ts # Module definition (@Module)
2728
- \`\`\`
2729
- ` : e === "cqrs" ? `\`\`\`
2730
- <name>/
2731
- ├── commands/ # Write operations
2732
- │ ├── create-<name>.command.ts
2733
- │ └── create-<name>.handler.ts
2734
- ├── queries/ # Read operations
2735
- │ ├── get-<name>.query.ts
2736
- │ └── get-<name>.handler.ts
2737
- ├── events/ # Domain events
2738
- │ └── <name>-created.event.ts
2739
- ├── <name>.controller.ts # HTTP routes
2740
- ├── <name>.repository.ts # Data access
2741
- └── <name>.module.ts # Module definition
2742
- \`\`\`
2743
- ` : e === "graphql" ? "```\nresolvers/\n├── <name>.resolver.ts # @Resolver, @Query, @Mutation\n├── <name>.types.ts # GraphQL type definitions\n└── <name>.service.ts # Business logic\n```\n" : e === "rest" ? `\`\`\`
2744
- <name>/
2745
- ├── <name>.controller.ts # HTTP routes (@Controller)
2746
- ├── <name>.service.ts # Business logic (@Service)
2747
- ├── <name>.dto.ts # Request/response schemas (Zod)
2748
- └── <name>.module.ts # Module definition (@Module)
2749
- \`\`\`
2750
- ` : "```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
2751
-
2752
- ## Checklist: Adding a Feature
2753
-
2754
- ### New Module (Recommended)
2755
-
2756
- Use the CLI generator for consistency:
2757
-
2758
- \`\`\`bash
2759
- kick g module <name> # Generate full module
2760
- # or
2761
- kick g scaffold <name> <fields> # Generate CRUD from fields
2762
- \`\`\`
2763
-
2764
- Then:
2765
- - [ ] Review generated files in \`src/modules/<name>/\`
2766
- - [ ] Verify module is registered in \`src/modules/index.ts\`
2767
- - [ ] Update DTOs in \`<name>.dto.ts\` if needed
2768
- - [ ] Implement business logic in \`<name>.service.ts\`
2769
- - [ ] Run \`kick dev\` to test with HMR
2770
- - [ ] Write tests in \`<name>.test.ts\`
2771
-
2772
- ### Manual Controller
2773
-
2774
- If not using generators:
2775
-
2776
- - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
2777
- - [ ] Add \`@Controller('/path')\` decorator
2778
- - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
2779
- - [ ] Create module file with \`@Module({ controllers: [NameController] })\`
2780
- - [ ] Register module in \`src/modules/index.ts\`
2781
- - [ ] Test with \`kick dev\`
2782
-
2783
- ### Manual Service
2784
-
2785
- - [ ] Create \`src/modules/<name>/<name>.service.ts\`
2786
- - [ ] Add \`@Service()\` decorator
2787
- - [ ] Inject dependencies with \`@Autowired()\`
2788
- - [ ] Register in module \`providers\` array
2789
- - [ ] Write unit tests
2790
-
2791
- ### New Middleware
2792
-
2793
- - [ ] Create \`src/middleware/<name>.middleware.ts\`
2794
- - [ ] Export middleware function (Express format)
2795
- - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
2796
- - [ ] Test with sample requests
2797
-
2798
- ### Adding a Package
2799
-
2800
- Use \`kick add\` to install KickJS packages with correct peer dependencies:
2801
-
2802
- - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
2803
- - [ ] Follow package-specific setup in terminal output
2804
- - [ ] Update \`src/index.ts\` to register adapter (if needed)
2805
- - [ ] Configure environment variables in \`.env\`
2806
- - [ ] Test integration with \`kick dev\`
2807
-
2808
- ## Common Tasks
2809
-
2810
- ### Generate CRUD Module
2811
-
2812
- \`\`\`bash
2813
- kick g scaffold user name:string email:string age:number
2814
- \`\`\`
2815
-
2816
- This creates a full CRUD module with:
2817
- - Controller with GET, POST, PUT, DELETE routes
2818
- - Service with business logic
2819
- - Repository with data access
2820
- - DTOs with Zod validation
2821
-
2822
- ### Add Authentication
2823
-
2824
- \`\`\`bash
2825
- kick add auth
2826
- \`\`\`
2827
-
2828
- Then configure in \`src/index.ts\`:
2829
-
2830
- \`\`\`ts
2831
- import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
2832
-
2833
- bootstrap({
2834
- modules,
2835
- adapters: [
2836
- new AuthAdapter({
2837
- strategies: [new JwtStrategy({ secret: process.env.JWT_SECRET! })],
2838
- }),
2839
- ],
2840
- })
2841
- \`\`\`
2842
-
2843
- ### Add Database (Prisma)
2844
-
2845
- \`\`\`bash
2846
- kick add prisma
2847
- ${t} install prisma @prisma/client
2848
- npx prisma init
2849
- # Edit prisma/schema.prisma
2850
- npx prisma migrate dev --name init
2851
- kick g module user --repo prisma
2852
- \`\`\`
2853
-
2854
- ### Add WebSocket Support
2855
-
2856
- \`\`\`bash
2857
- kick add ws
2858
- \`\`\`
2859
-
2860
- Then add adapter in \`src/index.ts\`:
2861
-
2862
- \`\`\`ts
2863
- import { WsAdapter } from '@forinda/kickjs-ws'
2864
-
2865
- bootstrap({
2866
- modules,
2867
- adapters: [new WsAdapter()],
2868
- })
2869
- \`\`\`
2870
-
2871
- Create WebSocket controller:
2872
-
2873
- \`\`\`bash
2874
- kick g controller chat --ws
2875
- \`\`\`
2876
-
2877
- ## Testing Guidelines
2878
-
2879
- All tests use Vitest:
2880
-
2881
- \`\`\`ts
2882
- import { describe, it, expect, beforeEach } from 'vitest'
2883
- import { Container } from '@forinda/kickjs'
2884
- import { createTestApp } from '@forinda/kickjs-testing'
2885
-
2886
- describe('UserController', () => {
2887
- beforeEach(() => {
2888
- Container.reset() // Important: isolate DI state
2889
- })
2890
-
2891
- it('should return users', async () => {
2892
- const app = await createTestApp([UserModule])
2893
- const res = await app.get('/users')
2894
-
2895
- expect(res.status).toBe(200)
2896
- expect(res.body).toHaveProperty('users')
2897
- })
2898
- })
2899
- \`\`\`
2900
-
2901
- Run tests:
2902
- - \`${t} run test\` — run all tests once
2903
- - \`${t} run test:watch\` — watch mode
2904
- - Individual file: \`${t} run test src/modules/user/user.test.ts\`
2905
-
2906
- ## Environment Variables
2907
-
2908
- Managed via \`.env\` file. Access with:
2909
-
2910
- 1. **@Value() decorator** (recommended):
2911
- \`\`\`ts
2912
- @Value('DATABASE_URL')
2913
- private dbUrl!: string
2914
- \`\`\`
2915
-
2916
- 2. **ConfigService** (for dynamic access):
2917
- \`\`\`ts
2918
- @Autowired()
2919
- private config!: ConfigService
2920
-
2921
- const port = this.config.get('PORT', 3000)
2922
- \`\`\`
2923
-
2924
- 3. **Direct access** (avoid in app code):
2925
- \`\`\`ts
2926
- process.env.PORT
2927
- \`\`\`
2928
-
2929
- ## Key Decorators
2930
-
2931
- ### HTTP Routes
2932
- | Decorator | Purpose |
2933
- |-----------|---------|
2934
- | \`@Controller('/path')\` | Define route prefix |
2935
- | \`@Get('/'), @Post('/')\` | HTTP method handlers |
2936
- | \`@Middleware(fn)\` | Attach middleware |
2937
- | \`@Public()\` | Skip auth (requires auth adapter) |
2938
- | \`@Roles('admin')\` | Role-based access |
2939
-
2940
- ### Dependency Injection
2941
- | Decorator | Purpose |
2942
- |-----------|---------|
2943
- | \`@Module({})\` | Define feature module |
2944
- | \`@Service()\` | Register singleton service |
2945
- | \`@Repository()\` | Register repository |
2946
- | \`@Autowired()\` | Property injection |
2947
- | \`@Inject('token')\` | Token-based injection |
2948
- | \`@Value('VAR')\` | Inject env variable |
2949
-
2950
- ${e === "graphql" ? "### GraphQL\n| Decorator | Purpose |\n|-----------|---------|\n| `@Resolver()` | GraphQL resolver class |\n| `@Query()` | Query handler |\n| `@Mutation()` | Mutation handler |\n| `@Arg('name')` | Resolver argument |\n\n" : ""}${e === "cqrs" ? "### Background Jobs\n| Decorator | Purpose |\n|-----------|---------|\n| `@Job('name')` | Queue job handler |\n| `@Process('queue')` | Queue processor |\n| `@Cron('0 * * * *')` | Cron schedule |\n| `@WsController()` | WebSocket controller |\n\n" : ""}## Common Pitfalls
2951
-
2952
- 1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
2953
- 2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
2954
- 3. **Tests failing randomly** — Missing \`Container.reset()\` in \`beforeEach\`
2955
- 4. **Routes not found** — Check controller path and module registration
2956
- 5. **HMR not working** — Verify \`vite.config.ts\` has \`hmr: true\`
2957
- 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
2958
-
2959
- ## CLI Commands Reference
2960
-
2961
- | Command | Description |
2962
- |---------|-------------|
2963
- | \`kick dev\` | Dev server with HMR |
2964
- | \`kick dev:debug\` | Dev server with debugger |
2965
- | \`kick build\` | Production build |
2966
- | \`kick start\` | Run production build |
2967
- | \`kick g module <names...>\` | Generate one or more modules |
2968
- | \`kick g scaffold <name> <fields>\` | Generate CRUD |
2969
- | \`kick g controller <name>\` | Generate controller |
2970
- | \`kick g service <name>\` | Generate service |
2971
- | \`kick g middleware <name>\` | Generate middleware |
2972
- | \`kick add <package>\` | Add KickJS package |
2973
- | \`kick add --list\` | List available packages |
2974
- | \`kick rm module <names...>\` | Remove one or more modules |
2975
-
2976
- > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
2977
- > \`\`\`bash
2978
- > kick new my-api -t ddd -r prisma --pm ${t} --no-git --no-install -f
2979
- > \`\`\`
2980
-
2981
- ## Learn More
2982
-
2983
- - [KickJS Docs](https://forinda.github.io/kick-js/)
2984
- - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
2985
- - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
2986
- - [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
2987
- - [Testing](https://forinda.github.io/kick-js/api/testing.html)
2988
- `;
2989
- }
2990
- var Ke = Q(oe(import.meta.url)), V = JSON.parse(re(p(Ke, "..", "package.json"), "utf-8")), Je = `^${V.version}`;
2991
- async function mt(r) {
2992
- const { name: e, directory: t, packageManager: o = "pnpm", template: s = "rest", defaultRepo: i = "inmemory" } = r, n = t, a = (u) => console.log(` ${u}`);
2993
- if (console.log(`
2994
- Creating KickJS project: ${e}
2995
- `), await l(p(n, "package.json"), je(e, s, Je)), await l(p(n, "vite.config.ts"), Ee()), await l(p(n, "tsconfig.json"), Ue()), await l(p(n, ".prettierrc"), Me()), await l(p(n, ".editorconfig"), qe()), await l(p(n, ".gitignore"), ze()), await l(p(n, ".gitattributes"), _e()), await l(p(n, ".env"), Ge()), await l(p(n, ".env.example"), Qe()), await l(p(n, "src/index.ts"), Le(e, s, V.version)), await l(p(n, "src/modules/index.ts"), Ne()), s === "graphql" && await l(p(n, "src/resolvers/.gitkeep"), ""), await l(p(n, "kick.config.ts"), We(s, i)), await l(p(n, "vitest.config.ts"), Fe()), await l(p(n, "README.md"), Be(e, s, o)), await l(p(n, "CLAUDE.md"), Ye(e, s, o)), await l(p(n, "AGENTS.md"), He(e, s, o)), r.initGit) try {
2996
- R("git init", {
2997
- cwd: n,
2998
- stdio: "pipe"
2999
- }), R("git branch -M main", {
3000
- cwd: n,
3001
- stdio: "pipe"
3002
- }), R("git add -A", {
3003
- cwd: n,
3004
- stdio: "pipe"
3005
- }), R('git commit -m "chore: initial commit from kick new"', {
3006
- cwd: n,
3007
- stdio: "pipe"
3008
- }), a("Git repository initialized");
3009
- } catch {
3010
- a("Warning: git init failed (git may not be installed)");
3011
- }
3012
- if (r.installDeps) {
3013
- console.log(`
3014
- Installing dependencies with ${o}...
3015
- `);
3016
- try {
3017
- R(`${o} install`, {
3018
- cwd: n,
3019
- stdio: "inherit"
3020
- }), console.log(`
3021
- Dependencies installed successfully!`);
3022
- } catch {
3023
- console.log(`
3024
- Warning: ${o} install failed. Run it manually.`);
3025
- }
3026
- }
3027
- console.log(`
3028
- Project scaffolded successfully!`), console.log();
3029
- const c = n !== process.cwd();
3030
- a("Next steps:"), c && a(` cd ${e}`), r.installDeps || a(` ${o} install`);
3031
- const d = {
3032
- rest: "kick g module user",
3033
- graphql: "kick g resolver user",
3034
- ddd: "kick g module user --repo drizzle",
3035
- cqrs: "kick g module user --pattern cqrs",
3036
- minimal: "# add your routes to src/index.ts"
3037
- };
3038
- a(` ${d[s] ?? d.rest}`), a(" kick dev"), a(""), a("Commands:"), a(" kick dev Start dev server with Vite HMR"), a(" kick build Production build via Vite"), a(" kick start Run production build"), a(""), a("Generators:"), a(" kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)"), a(" kick g scaffold <n> <f..> CRUD module from field definitions"), a(" kick g controller <name> Standalone controller"), a(" kick g service <name> @Service() class"), a(" kick g middleware <name> Express middleware"), a(" kick g guard <name> Route guard (auth, roles, etc.)"), a(" kick g adapter <name> AppAdapter with lifecycle hooks"), a(" kick g dto <name> Zod DTO schema"), s === "graphql" && a(" kick g resolver <name> GraphQL resolver"), s === "cqrs" && a(" kick g job <name> Queue job processor"), a(" kick g config Generate kick.config.ts"), a(""), a("Add packages:"), a(" kick add <pkg> Install a KickJS package + peers"), a(" kick add --list Show all available packages"), a(""), a("Available: auth, swagger, graphql, drizzle, prisma, ws,"), a(" cron, queue, mailer, otel, multi-tenant, notifications, testing"), a("");
3039
- }
3040
- var G = [
3041
- "drizzle",
3042
- "inmemory",
3043
- "prisma"
3044
- ];
3045
- function ft(r) {
3046
- return r;
3047
- }
3048
- function $t(r) {
3049
- if (!r) return {};
3050
- const e = {
3051
- dir: r.modules?.dir ?? r.modulesDir,
3052
- repo: r.modules?.repo ?? r.defaultRepo,
3053
- schemaDir: r.modules?.schemaDir ?? r.schemaDir,
3054
- pluralize: r.modules?.pluralize ?? r.pluralize,
3055
- prismaClientPath: r.modules?.prismaClientPath
3056
- };
3057
- return e.repo && typeof e.repo == "string" && !G.includes(e.repo) && console.warn(` Warning: modules.repo '${e.repo}' is not a built-in type (${G.join(", ")}). It will generate a stub repository. Use { name: '${e.repo}' } to silence this warning.`), e;
3058
- }
3059
- var Ve = [
3060
- "kick.config.ts",
3061
- "kick.config.js",
3062
- "kick.config.mjs",
3063
- "kick.config.json"
3064
- ];
3065
- async function yt(r) {
3066
- for (const e of Ve) {
3067
- const t = p(r, e);
3068
- try {
3069
- await F(t);
3070
- } catch {
3071
- continue;
3072
- }
3073
- if (e.endsWith(".json")) {
3074
- const o = await L(t, "utf-8");
3075
- return JSON.parse(o);
3076
- }
3077
- try {
3078
- const { pathToFileURL: o } = await import("node:url"), s = await import(o(t).href);
3079
- return s.default ?? s;
3080
- } catch {
3081
- e.endsWith(".ts") && console.warn(`Warning: Failed to load ${e}. TypeScript config files require a runtime loader (e.g. tsx, ts-node) or use kick.config.js/.mjs instead.`);
3082
- continue;
3083
- }
3084
- }
3085
- return null;
3086
- }
3087
- export {
3088
- g as _,
3089
- ut as a,
3090
- l as b,
3091
- dt as c,
3092
- at as d,
3093
- it as f,
3094
- y as g,
3095
- T as h,
3096
- mt as i,
3097
- ct as l,
3098
- se as m,
3099
- yt as n,
3100
- lt as o,
3101
- Y as p,
3102
- $t as r,
3103
- pt as s,
3104
- ft as t,
3105
- nt as u,
3106
- B as v,
3107
- st as y
3108
- };