@forinda/kickjs-cli 5.5.1 → 5.8.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 (31) hide show
  1. package/README.md +1 -1
  2. package/dist/{run-plugins-tnHiahkq.mjs → builtins-CYSzLo7U.mjs} +2 -2
  3. package/dist/cli.mjs +4086 -2
  4. package/dist/config-ierHW69f.mjs +12 -0
  5. package/dist/{config-Buzo7RE1.mjs.map → config-ierHW69f.mjs.map} +1 -1
  6. package/dist/{generator-extension-m04pTdQi.mjs → generator-extension-BXLt3Tp_.mjs} +314 -78
  7. package/dist/generator-extension-BXLt3Tp_.mjs.map +1 -0
  8. package/dist/index.d.mts +141 -31
  9. package/dist/index.d.mts.map +1 -1
  10. package/dist/index.mjs +3 -2
  11. package/dist/index.mjs.map +1 -0
  12. package/dist/{plugin-BnIpCxAe.mjs → plugin-D_nBy6VP.mjs} +3 -3
  13. package/dist/{plugin-BnIpCxAe.mjs.map → plugin-D_nBy6VP.mjs.map} +1 -1
  14. package/dist/project-root-CqGZOrRR.mjs +12 -0
  15. package/dist/project-root-CqGZOrRR.mjs.map +1 -0
  16. package/dist/{rolldown-runtime-Dnwyy6jt.mjs → rolldown-runtime-B8-Ifyj3.mjs} +1 -1
  17. package/dist/{builtins-DXPOvADa.mjs → run-plugins-Cvgyo_th.mjs} +90 -288
  18. package/dist/run-plugins-Cvgyo_th.mjs.map +1 -0
  19. package/dist/{typegen-CYaoTJ6r.mjs → typegen-C3G375CR.mjs} +4 -4
  20. package/dist/{typegen-CYaoTJ6r.mjs.map → typegen-C3G375CR.mjs.map} +1 -1
  21. package/dist/{types-RTdCiPdS.mjs → types-Kj2ldTnQ.mjs} +2 -2
  22. package/dist/types-Kj2ldTnQ.mjs.map +1 -0
  23. package/package.json +7 -6
  24. package/dist/builtins-DXPOvADa.mjs.map +0 -1
  25. package/dist/builtins-DYktFyU-.mjs +0 -3952
  26. package/dist/config-Bu3PcPYn.mjs +0 -11
  27. package/dist/config-Buzo7RE1.mjs +0 -12
  28. package/dist/generator-extension-m04pTdQi.mjs.map +0 -1
  29. package/dist/plugin-DZZsizSI.mjs +0 -11
  30. package/dist/typegen-COED-VIb.mjs +0 -116
  31. package/dist/types-RTdCiPdS.mjs.map +0 -1
@@ -1,3952 +0,0 @@
1
- /**
2
- * @forinda/kickjs-cli v5.5.1
3
- *
4
- * Copyright (c) Felix Orinda
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import{t as e}from"./rolldown-runtime-Dnwyy6jt.mjs";import{a as t,i as n,r,t as i}from"./config-Bu3PcPYn.mjs";import{n as a,r as o}from"./plugin-DZZsizSI.mjs";import{a as s,c,i as l,n as u,o as d,s as f,t as p}from"./typegen-COED-VIb.mjs";import{createRequire as m}from"node:module";import{cpSync as h,existsSync as g,mkdirSync as _,readFileSync as v,readdirSync as y,rmSync as ee,statSync as te,writeFileSync as ne}from"node:fs";import b,{basename as re,dirname as x,extname as ie,isAbsolute as ae,join as S,relative as C,resolve as w,sep as oe}from"node:path";import{fileURLToPath as se,pathToFileURL as T}from"node:url";import{execFileSync as ce,execSync as E,fork as le,spawn as ue,spawnSync as de}from"node:child_process";import{access as fe,copyFile as pe,mkdir as me,readFile as D,readdir as he,rm as ge,stat as _e,writeFile as O}from"node:fs/promises";import*as k from"@clack/prompts";import A from"picocolors";import ve from"pluralize";import{glob as ye}from"glob";import{groupAssetKeys as be}from"@forinda/kickjs";import{arch as xe,platform as Se,release as Ce}from"node:os";import{detectCompositeReferences as we,generate as Te,migrateDown as Ee,migrateLatest as De,migrateRollback as Oe,migrateStatus as ke,migrateUp as Ae,renderSchemaSource as je,resolveDbConfig as Me}from"@forinda/kickjs-db";function Ne(e,t,n){E(e,{cwd:t,stdio:`inherit`,env:n?{...process.env,...n}:process.env})}function Pe(e,t,n){let r=de(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}let Fe=!1;function j(e){Fe=e}const Ie=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function M(e,t){Fe||(await me(x(e),{recursive:!0}),await O(e,t,`utf-8`),Ie.has(ie(e))&&await Re(e,t).catch(()=>{}))}let N;async function Le(e){if(N!==void 0)return N;try{N=await import(m(S(e,`package.json`)).resolve(`oxfmt`))}catch{N=null}return N}async function Re(e,t){let n=await Le(process.cwd());if(!n)return;let r=await ze(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await O(e,i.code,`utf-8`)}const P=new Map;async function ze(e){let t=x(e),n=t;if(P.has(n))return P.get(n);for(;;){let e=S(t,`.oxfmtrc.json`);if(g(e))try{let t=await D(e,`utf-8`),r=JSON.parse(t);return delete r.$schema,delete r.ignorePatterns,P.set(n,r),r}catch{return P.set(n,null),null}let r=x(t);if(r===t)return P.set(n,null),null;t=r}}async function Be(e){try{return await fe(e),!0}catch{return!1}}const Ve={auth:`@forinda/kickjs-auth`,swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function He(e,t){let n=e[t];if(!n)throw Error(`generatePackageJson: missing resolved version for ${t}. Add it to SIBLING_PACKAGES in generators/project.ts.`);return n}function Ue(e,t,n,r=[]){let i={"@forinda/kickjs":He(n,`@forinda/kickjs`),dotenv:`^17.3.1`,express:`^5.1.0`,"reflect-metadata":`^0.2.2`,zod:`^4.3.6`,pino:`^10.3.1`,"pino-pretty":`^13.1.3`};for(let e of r){let t=Ve[e];t&&!i[t]&&(i[t]=He(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,"dev:debug":`kick dev:debug`,build:`kick build`,start:`kick start`,test:`vitest run`,"test:watch":`vitest`,typecheck:`tsc --noEmit`,typegen:`kick typegen`,lint:`eslint src/`,format:`prettier --write src/`},dependencies:i,devDependencies:{"@forinda/kickjs-cli":He(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":He(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,"@types/express":`^5.0.6`,"@types/node":`^25.0.0`,"unplugin-swc":`^1.5.9`,vite:`^8.0.3`,vitest:`^4.1.2`,typescript:`^6.0.3`,prettier:`^3.8.1`}},null,2)}function We(){return`import { defineConfig } from 'vite'
12
- import { resolve } from 'node:path'
13
- import swc from 'unplugin-swc'
14
- import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
15
-
16
- export default defineConfig({
17
- oxc: false,
18
- plugins: [
19
- swc.vite(),
20
- kickjsVitePlugin({ entry: 'src/index.ts' }),
21
- // Watches .env files and triggers a full reload on change so the
22
- // dev server picks up env tweaks without a manual restart.
23
- envWatchPlugin(),
24
- ],
25
- resolve: {
26
- alias: {
27
- '@': resolve(__dirname, 'src'),
28
- },
29
- },
30
- ssr: {
31
- // Don't bundle pino — its worker-thread transport needs Node.js resolution
32
- // to find pino-pretty at runtime for colored log output
33
- external: ['pino', 'pino-pretty'],
34
- },
35
- build: {
36
- target: 'node20',
37
- ssr: true,
38
- outDir: 'dist',
39
- sourcemap: true,
40
- rollupOptions: {
41
- input: resolve(__dirname, 'src/index.ts'),
42
- output: { format: 'esm' },
43
- },
44
- },
45
- })
46
- `}function Ge(){return JSON.stringify({compilerOptions:{target:`ES2022`,module:`ESNext`,moduleResolution:`bundler`,lib:[`ES2022`],types:[`node`,`vite/client`],strict:!0,esModuleInterop:!0,skipLibCheck:!0,sourceMap:!0,declaration:!0,experimentalDecorators:!0,emitDecoratorMetadata:!0,outDir:`dist`,paths:{"@/*":[`./src/*`]}},include:[`src`,`.kickjs/types/**/*.d.ts`,`.kickjs/types/**/*.ts`]},null,2)}function Ke(){return JSON.stringify({semi:!1,singleQuote:!0,trailingComma:`all`,printWidth:100,tabWidth:2},null,2)}function qe(){return`# https://editorconfig.org
47
- root = true
48
-
49
- [*]
50
- indent_style = space
51
- indent_size = 2
52
- end_of_line = lf
53
- charset = utf-8
54
- trim_trailing_whitespace = true
55
- insert_final_newline = true
56
-
57
- [*.md]
58
- trim_trailing_whitespace = false
59
- `}function Je(){return`node_modules/
60
- dist/
61
- .env
62
- coverage/
63
- .DS_Store
64
- *.tsbuildinfo
65
- .kickjs/
66
- `}function Ye(){return`# Auto-detect text files and normalise line endings to LF
67
- * text=auto eol=lf
68
-
69
- # Explicitly mark generated / binary files
70
- *.png binary
71
- *.jpg binary
72
- *.jpeg binary
73
- *.gif binary
74
- *.ico binary
75
- *.woff binary
76
- *.woff2 binary
77
- *.ttf binary
78
- *.eot binary
79
-
80
- # Lock files — treat as generated
81
- pnpm-lock.yaml -diff linguist-generated
82
- yarn.lock -diff linguist-generated
83
- package-lock.json -diff linguist-generated
84
- `}function Xe(){return`PORT=3000
85
- NODE_ENV=development
86
- `}function Ze(){return`PORT=3000
87
- NODE_ENV=development
88
- `}function Qe(){return`import { defineConfig } from 'vitest/config'
89
- import swc from 'unplugin-swc'
90
-
91
- export default defineConfig({
92
- plugins: [swc.vite()],
93
- test: {
94
- globals: true,
95
- environment: 'node',
96
- include: ['src/**/*.test.ts'],
97
- },
98
- })
99
- `}function $e(e,t,n,r=[]){switch(t){case`cqrs`:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
100
- // Side-effect import — registers the extended env schema with kickjs
101
- // **before** any controller / service / @Value gets resolved. Without
102
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
103
- // cached schema would still be the base shape. See guide/configuration.
104
- import './config'
105
- import { bootstrap } from '@forinda/kickjs'
106
- // import { WsAdapter } from '@forinda/kickjs-ws'
107
- // import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
108
- ${t.length?t.join(`
109
- `)+`
110
- `:``}import { modules } from './modules'
111
-
112
- // Export the app for the Vite plugin (dev mode)
113
- export const app = await bootstrap({
114
- modules,${t.length?`\n adapters: [\n${i.join(`
115
- `)}\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],`:`
116
- adapters: [
117
- // Uncomment for WebSocket support:
118
- // WsAdapter(),
119
- // Uncomment when Redis is available:
120
- // QueueAdapter({
121
- // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),
122
- // }),
123
- ],`}
124
- })
125
- `}case`minimal`:{let t=[],i=[];return r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({ info: { title: '${e}', version: '${n}' } }),`)),r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),`import 'reflect-metadata'
126
- // Side-effect import — registers the extended env schema with kickjs
127
- // **before** any controller / service / @Value gets resolved. Without
128
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
129
- // cached schema would still be the base shape. See guide/configuration.
130
- import './config'
131
- import { bootstrap } from '@forinda/kickjs'
132
- ${t.length?t.join(`
133
- `)+`
134
- `:``}import { modules } from './modules'
135
-
136
- // Export the app for the Vite plugin (dev mode)
137
- export const app = await bootstrap({ modules${i.length?`,\n adapters: [\n${i.join(`
138
- `)}\n ]`:``} })
139
- `}default:{let t=[],i=[];return r.includes(`devtools`)&&(t.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`),i.push(` DevToolsAdapter(),`)),r.includes(`swagger`)&&(t.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`),i.push(` SwaggerAdapter({\n info: { title: '${e}', version: '${n}' },\n }),`)),`import 'reflect-metadata'
140
- // Side-effect import — registers the extended env schema with kickjs
141
- // **before** any controller / service / @Value gets resolved. Without
142
- // this line ConfigService.get('YOUR_KEY') returns undefined because the
143
- // cached schema would still be the base shape. See guide/configuration.
144
- import './config'
145
- import express from 'express'
146
- import {
147
- bootstrap,
148
- requestId,
149
- requestLogger,
150
- helmet,
151
- cors,
152
- } from '@forinda/kickjs'
153
- ${t.length?t.join(`
154
- `)+`
155
- `:``}import { modules } from './modules'
156
-
157
- // Export the app for the Vite plugin (dev mode)
158
- export const app = await bootstrap({
159
- modules,${i.length?`\n adapters: [\n${i.join(`
160
- `)}\n ],`:``}
161
- middleware: [
162
- helmet(),
163
- cors({ origin: '*' }),
164
- requestId(),
165
- requestLogger(),
166
- express.json(),
167
- ],
168
- })
169
- `}}}function et(){return`import { defineModules } from '@forinda/kickjs'
170
- import { HelloModule } from './hello/hello.module'
171
-
172
- // Remove HelloModule and run: kick g module <name>
173
- // \`defineModules()\` returns a chainable list — \`kick g module\` appends
174
- // \`.mount(NewModule())\` to the chain on every generation.
175
- export const modules = defineModules().mount(HelloModule())
176
- `}function tt(){return`import { defineEnv, loadEnv } from '@forinda/kickjs/config'
177
- import { z } from 'zod'
178
-
179
- /**
180
- * Project environment schema.
181
- *
182
- * Extend the base schema with your application's variables. The
183
- * default export is the contract \`kick typegen\` reads to populate
184
- * the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
185
- * autocomplete and \`process.env.FOO\` typed.
186
- *
187
- * @example
188
- * DATABASE_URL: z.string().url(),
189
- * JWT_SECRET: z.string().min(32),
190
- * REDIS_URL: z.string().url().optional(),
191
- */
192
- const envSchema = defineEnv((base) =>
193
- base.extend({
194
- // DATABASE_URL: z.string().url(),
195
- }),
196
- )
197
-
198
- /**
199
- * IMPORTANT — side effect: register the schema with kickjs's env cache
200
- * **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
201
- * this cache, and they will fall back to the base schema (or undefined)
202
- * if no extended schema has been registered before they're resolved.
203
- *
204
- * As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
205
- * top — before \`bootstrap()\` runs — every controller and service in the
206
- * app sees the typed extended values.
207
- */
208
- export const env = loadEnv(envSchema)
209
-
210
- export default envSchema
211
- `}function nt(){return`import { Service } from '@forinda/kickjs'
212
-
213
- @Service()
214
- export class HelloService {
215
- greet(name: string) {
216
- return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
217
- }
218
-
219
- healthCheck() {
220
- return { status: 'ok', uptime: process.uptime() }
221
- }
222
- }
223
- `}function rt(){return`import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
224
- import { HelloService } from './hello.service'
225
-
226
- // \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
227
- // \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
228
- // scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
229
- // See https://forinda.github.io/kick-js/guide/typegen.
230
-
231
- @Controller()
232
- export class HelloController {
233
- @Autowired() private readonly helloService!: HelloService
234
-
235
- @Get('/')
236
- index(ctx: Ctx<KickRoutes.HelloController['index']>) {
237
- ctx.json(this.helloService.greet('World'))
238
- }
239
-
240
- @Get('/health')
241
- health(ctx: Ctx<KickRoutes.HelloController['health']>) {
242
- ctx.json(this.helloService.healthCheck())
243
- }
244
- }
245
- `}function it(){return`import { defineModule } from '@forinda/kickjs'
246
- import { HelloController } from './hello.controller'
247
-
248
- export const HelloModule = defineModule({
249
- name: 'HelloModule',
250
- build: () => ({
251
- // \`register(container)\` is optional — only implement it when you need
252
- // to bind a token to a concrete implementation, e.g.
253
- // register(container) {
254
- // container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
255
- // }
256
- // The HelloService uses @Service() so the decorator handles registration.
257
-
258
- routes() {
259
- return {
260
- path: '/hello',
261
- controller: HelloController,
262
- }
263
- },
264
- }),
265
- })
266
- `}function at(e,t=`inmemory`,n=`pnpm`){return`import { defineConfig } from '@forinda/kickjs-cli'
267
-
268
- export default defineConfig({
269
- pattern: '${e}',
270
- // Pinned so \`kick add\` and other dep-installing commands always use the
271
- // project's intended package manager, regardless of which lockfile exists.
272
- packageManager: '${n}',
273
- modules: {
274
- dir: 'src/modules',
275
- repo: ${[`drizzle`,`inmemory`,`prisma`].includes(t)?`'${t}'`:`{ name: '${t}' }`},
276
- pluralize: true,
277
- },
278
-
279
- // \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
280
- // resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
281
- // Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
282
- typegen: {
283
- schemaValidator: 'zod',
284
- },
285
-
286
- commands: [
287
- {
288
- name: 'test',
289
- description: 'Run tests with Vitest',
290
- steps: 'npx vitest run',
291
- },
292
- {
293
- name: 'format',
294
- description: 'Format code with Prettier',
295
- steps: 'npx prettier --write src/',
296
- },
297
- {
298
- name: 'format:check',
299
- description: 'Check formatting without writing',
300
- steps: 'npx prettier --check src/',
301
- },
302
- {
303
- name: 'ci:check',
304
- description: 'Run typecheck + format check',
305
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
306
- aliases: ['verify'],
307
- },
308
- ],
309
- })
310
- `}function ot(e,t,n){let r={rest:`REST API`,ddd:`Domain-Driven Design`,cqrs:`CQRS + Event-Driven`,minimal:`Minimal`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`),t===`cqrs`&&i.push(`@forinda/kickjs-queue`,`@forinda/kickjs-ws`),`# ${e}
311
-
312
- A **${r[t]??`REST API`}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
313
-
314
- ## Getting Started
315
-
316
- \`\`\`bash
317
- ${n} install
318
- kick dev
319
- \`\`\`
320
-
321
- ## Scripts
322
-
323
- | Command | Description |
324
- |---|---|
325
- | \`kick dev\` | Start dev server with Vite HMR |
326
- | \`kick build\` | Production build |
327
- | \`kick start\` | Run production build |
328
- | \`${n} run test\` | Run tests with Vitest |
329
- | \`kick g module <name>\` | Generate a DDD module |
330
- | \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
331
- | \`kick add <package>\` | Add a KickJS package |
332
-
333
- ## Project Structure
334
-
335
- \`\`\`
336
- src/
337
- ├── index.ts # Application entry point
338
- ├── modules/ # Feature modules (controllers, services, repos)
339
- │ └── index.ts # Module registry
340
- └── ...
341
- \`\`\`
342
-
343
- ## Packages
344
-
345
- ${i.map(e=>`- \`${e}\``).join(`
346
- `)}
347
-
348
- ## Adding Features
349
-
350
- \`\`\`bash
351
- kick add auth # Authentication (JWT, API key, OAuth)
352
- kick add swagger # OpenAPI documentation
353
- kick add ws # WebSocket support
354
- kick add queue # Background job processing
355
- kick add --list # Show all available packages
356
- \`\`\`
357
-
358
- For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://forinda.github.io/kick-js/guide/) — they wire the upstream library through \`defineAdapter()\` / \`definePlugin()\` directly, so you keep control of the integration.
359
-
360
- ## Environment Variables
361
-
362
- Copy \`.env.example\` to \`.env\` and configure:
363
-
364
- | Variable | Default | Description |
365
- |---|---|---|
366
- | \`PORT\` | \`3000\` | Server port |
367
- | \`NODE_ENV\` | \`development\` | Environment |
368
-
369
- ## Learn More
370
-
371
- - [KickJS Documentation](https://forinda.github.io/kick-js/)
372
- - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
373
- `}function st(e,t,n){return`# CLAUDE.md — ${e}
374
-
375
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
376
- reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
377
- project conventions, structure, decorator patterns, env wiring, CLI
378
- generators, every gotcha.
379
-
380
- **Then read \`./kickjs-skills.md\`.** That file is the task-oriented
381
- skill index — short, rigid recipes keyed to triggers ("add-module",
382
- "write-controller-test", "bootstrap-export", "deny-list", …). Use it
383
- as the playbook when executing common KickJS workflows.
384
-
385
- This file is a thin Claude-specific layer on top of those two; when
386
- they disagree on anything substantive, treat \`AGENTS.md\` as
387
- authoritative and flag the discrepancy.
388
-
389
- ## Why two files
390
-
391
- \`AGENTS.md\` is what every agent reads. \`CLAUDE.md\` is what
392
- Claude Code automatically loads as project context on each
393
- conversation. Keeping CLAUDE.md slim avoids two files drifting; the
394
- redirect above ensures Claude pulls the canonical content without
395
- us copy-pasting.
396
-
397
- ## Claude-specific notes
398
-
399
- - **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
400
- to refresh project memory if AGENTS.md changes substantially.
401
- - **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
402
- - **Persistent memory** — Claude maintains user/feedback/project/
403
- reference memories under \`.claude/memory/\`. If you ask for
404
- something that contradicts a remembered preference, Claude flags
405
- it before acting; corrections update memory automatically.
406
- - **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
407
- or background work. Useful for "wait for the deploy then open a
408
- cleanup PR" or "every Monday triage the issue board" patterns.
409
-
410
- ## Quick reference (full version in AGENTS.md)
411
-
412
- \`\`\`bash
413
- ${n} install # Install dependencies
414
- kick dev # Dev server with HMR + typegen
415
- kick build && kick start # Production
416
- ${n} run test # Vitest
417
- ${n} run typecheck # tsc --noEmit
418
- ${n} run format # Prettier
419
- \`\`\`
420
-
421
- ## v4 framework reminders
422
-
423
- When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`AGENTS.md\`:
424
-
425
- - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
426
- - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
427
- - **DI tokens**: \`<scope>/<PascalKey>[/<suffix>]\` — scope is lowercase, the key segment is **PascalCase** (e.g. \`'app/Users/repository'\`, \`'mycorp/Cache/redis'\`). First-party uses the reserved \`'kick/'\` prefix; this project owns its own scope.
428
- - **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
429
- - **Module entry file** MUST be named \`<name>.module.ts\` and live under \`src/modules/<name>/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed \`projects.ts\` silently degrades every save into a full restart.
430
- - **Env**: schema lives in \`src/config/index.ts\`; \`import './config'\` MUST be the first import in \`src/index.ts\` (side-effect registers the schema before any \`@Value\` resolves).
431
- - **Assets**: drop new template files into \`src/templates/<namespace>/\`; the dev watcher auto-rebuilds the \`KickAssets\` augmentation + \`assets.x.y()\` re-walks on next call. No restart, no manual build.
432
- - **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
433
- - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
434
- - **Bootstrap export**: \`src/index.ts\` must end with \`export const app = await bootstrap({ ... })\`. The Vite plugin and \`createTestApp\` import the named \`app\`; without the export, HMR silently degrades to full restarts.
435
- - **Thin entry file**: aggregate \`modules\`, \`middleware\`, \`plugins\`, \`adapters\` in their own folders (\`src/modules/index.ts\`, \`src/middleware/index.ts\`, …) and pass them by name to \`bootstrap()\` — never inline the lists in \`src/index.ts\`.
436
- - **Refresh these files**: \`kick g agents -f\` regenerates \`AGENTS.md\` + \`CLAUDE.md\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \`AGENTS.local.md\`.
437
-
438
- For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`AGENTS.md\`.
439
- `}function ct(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
440
-
441
- This guide is the **canonical, multi-agent reference** for this KickJS
442
- application — Claude, Copilot, Codex, Gemini, etc. all read it first.
443
- Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
444
- add tool-specific affordances on top.
445
-
446
- ## Before You Start
447
-
448
- 1. Run \`${n} install\` to install dependencies
449
- 2. Run \`kick dev\` to verify the app starts
450
- 3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
451
-
452
- ## v4 Conventions (don't skip)
453
-
454
- KickJS v4 made a handful of structural changes from v3. Internalise these
455
- before generating or modifying code — they are the source of most agent
456
- mistakes:
457
-
458
- - **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
459
-
460
- \`\`\`ts
461
- export const MyAdapter = defineAdapter<MyOptions>({
462
- name: 'MyAdapter',
463
- defaults: { ... },
464
- build: (config) => ({
465
- beforeMount({ app }) { /* ... */ },
466
- afterStart({ server }) { /* ... */ },
467
- }),
468
- })
469
- \`\`\`
470
-
471
- - **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
472
-
473
- - **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
474
- the key segment is **PascalCase** (the regex enforces both):
475
-
476
- \`\`\`ts
477
- const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
478
- const DB = createToken<Database>('app/Db/connection')
479
- \`\`\`
480
-
481
- The \`kick/\` prefix is reserved for first-party packages; this project
482
- owns its own scope (\`app/\`, your domain name, etc.).
483
-
484
- - **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
485
- the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
486
- is a v3 leftover; the linter and codegen reject it.
487
-
488
- - **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
489
- side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
490
- import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
491
- returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
492
- (Zod coercion + defaults silently skipped).
493
-
494
- - **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
495
- HMR contract at the top of "Module Pattern" below. The CLI enforces this;
496
- hand-rolled files must too.
497
-
498
- - **Assets** — drop new template files into \`src/templates/<namespace>/\`
499
- (or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
500
- \`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
501
- no manual build step.
502
-
503
- - **Context over \`@Middleware()\`** — when a middleware's only job is to
504
- populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
505
- (HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
506
- Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
507
- Reserve \`@Middleware()\` for response short-circuit / stream mutation /
508
- pre-route-matching work.
509
-
510
- Two ground rules around the data flow — both stem from the fact that
511
- every per-request stage gets its OWN \`RequestContext\` instance, all
512
- reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
513
- - **\`resolve\` and \`onError\` must RETURN the value.** The runner
514
- writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
515
- property assignment (\`ctx.tenant = …\`) sticks to the contributor
516
- instance only — the handler instance never sees it.
517
- - **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
518
- \`getRequestValue(key)\` from a service that has no \`ctx\` reference
519
- — typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
520
- Express request is shared; bespoke property assignments don't.
521
-
522
- - **Test isolation** — default to \`Container.create()\` for fresh DI state.
523
- Never \`new Container()\` and never \`getInstance().reset()\` — both leak
524
- registrations between tests.
525
-
526
- \`\`\`ts
527
- const container = Container.create()
528
- // ... register test-scoped providers, run, discard
529
- \`\`\`
530
-
531
- - **Bootstrap export** — \`src/index.ts\` MUST end with
532
- \`export const app = await bootstrap({ ... })\`. The Vite plugin imports
533
- the named \`app\` symbol to drive HMR module swaps; testing helpers
534
- (\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
535
- the \`export\` and \`kick dev\` will silently fall back to a full restart
536
- on every save while \`createTestApp\` complains about a missing handle.
537
-
538
- - **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
539
- adapters in dedicated folders and re-export aggregated arrays. Do **not**
540
- inline registration in the entry file:
541
-
542
- \`\`\`ts
543
- // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
544
- export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
545
- // OR with \`modules.style: 'class'\`:
546
- // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
547
-
548
- // src/middleware/index.ts
549
- export const middleware = [helmet(), cors(), requestId(), ...]
550
-
551
- // src/plugins/index.ts
552
- export const plugins = [MetricsPlugin(), AuditPlugin()]
553
-
554
- // src/adapters/index.ts
555
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
556
- \`\`\`
557
-
558
- \`\`\`ts
559
- // src/index.ts — stays small; one import per category
560
- import 'reflect-metadata'
561
- import './config'
562
- import { bootstrap } from '@forinda/kickjs'
563
- import { modules } from './modules'
564
- import { middleware } from './middleware'
565
- import { plugins } from './plugins'
566
- import { adapters } from './adapters'
567
-
568
- export const app = await bootstrap({ modules, middleware, plugins, adapters })
569
- \`\`\`
570
-
571
- This keeps the entry file diff-friendly, scales to dozens of modules
572
- without git churn, and lets each domain own its own registration list.
573
- The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
574
- \`kick g adapter\`) follow this layout — manual additions should too.
575
-
576
- Everything else (controllers, services, modules, RequestContext API, generators,
577
- package additions, env access patterns, troubleshooting) is detailed below.
578
-
579
- ## Where to Find Things
580
-
581
- ### Application Structure
582
-
583
- | What | Where |
584
- |------|-------|
585
- | Entry point | \`src/index.ts\` |
586
- | Module registry | \`src/modules/index.ts\` |
587
- | Feature modules | \`src/modules/<module-name>/\` |
588
- | **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
589
- | Env values | \`.env\` |
590
- | Env schema (Zod) | \`src/config/index.ts\` |
591
- | TypeScript config | \`tsconfig.json\` |
592
- | Vite config (HMR) | \`vite.config.ts\` |
593
- | Vitest config | \`vitest.config.ts\` |
594
- | Prettier config | \`.prettierrc\` |
595
- | CLI config | \`kick.config.ts\` |
596
-
597
- ### Module Pattern (${t.toUpperCase()})
598
-
599
- > **Vite HMR auto-discovery contract:** module files **must** be named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and live under \`src/modules/\`. The Vite plugin scans for \`*.module.[tj]sx?\` to drive graceful HMR rebuilds; renaming a file to \`projects.ts\` (no \`.module\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\`kick g module <name>\`) follows the convention; manual files must too.
600
-
601
- Each module in \`src/modules/<name>/\` typically contains:
602
-
603
- ${t===`ddd`?`\`\`\`
604
- <name>/
605
- ├── <name>.controller.ts # HTTP routes (@Controller)
606
- ├── <name>.service.ts # Business logic (@Service)
607
- ├── <name>.repository.ts # Data access (@Repository)
608
- ├── <name>.dto.ts # Request/response schemas (Zod)
609
- ├── <name>.entity.ts # Domain entity (optional)
610
- └── <name>.module.ts # Module definition (defineModule factory)
611
- \`\`\`
612
- `:t===`cqrs`?`\`\`\`
613
- <name>/
614
- ├── commands/ # Write operations
615
- │ ├── create-<name>.command.ts
616
- │ └── create-<name>.handler.ts
617
- ├── queries/ # Read operations
618
- │ ├── get-<name>.query.ts
619
- │ └── get-<name>.handler.ts
620
- ├── events/ # Domain events
621
- │ └── <name>-created.event.ts
622
- ├── <name>.controller.ts # HTTP routes
623
- ├── <name>.repository.ts # Data access
624
- └── <name>.module.ts # Module definition (defineModule factory)
625
- \`\`\`
626
- `:t===`rest`?`\`\`\`
627
- <name>/
628
- ├── <name>.controller.ts # HTTP routes (@Controller)
629
- ├── <name>.service.ts # Business logic (@Service)
630
- ├── <name>.dto.ts # Request/response schemas (Zod)
631
- └── <name>.module.ts # Module definition (defineModule factory)
632
- \`\`\`
633
- `:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
634
-
635
- ## Checklist: Adding a Feature
636
-
637
- ### New Module (Recommended)
638
-
639
- Use the CLI generator for consistency:
640
-
641
- \`\`\`bash
642
- kick g module <name> # Generate full module
643
- # or
644
- kick g scaffold <name> <fields> # Generate CRUD from fields
645
- \`\`\`
646
-
647
- Then:
648
- - [ ] Review generated files in \`src/modules/<name>/\`
649
- - [ ] Verify module is registered in \`src/modules/index.ts\`
650
- - [ ] Update DTOs in \`<name>.dto.ts\` if needed
651
- - [ ] Implement business logic in \`<name>.service.ts\`
652
- - [ ] Run \`kick dev\` to test with HMR
653
- - [ ] Write tests in \`<name>.test.ts\`
654
-
655
- ### Manual Controller
656
-
657
- If not using generators:
658
-
659
- - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
660
- - [ ] Add \`@Controller()\` decorator
661
- - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
662
- - [ ] Create module file with \`defineModule({ name, build: () => ({ routes() { return { path, controller } } }) })\` — the framework derives the Express router from the controller. Class-form (\`class XModule implements AppModule\`) is the legacy alternative; toggle via \`kick.config.ts > modules.style\`.
663
- - [ ] Register module in \`src/modules/index.ts\`. Default form is the fluent chain: \`defineModules().mount(MyModule()).mount(...)\`. \`kick g module <name>\` appends \`.mount(NewModule())\` automatically.
664
- - [ ] Test with \`kick dev\`
665
-
666
- ### Manual Service
667
-
668
- - [ ] Create \`src/modules/<name>/<name>.service.ts\`
669
- - [ ] Add \`@Service()\` decorator
670
- - [ ] Inject dependencies with \`@Autowired()\`
671
- - [ ] Inject via \`@Autowired()\` where needed
672
- - [ ] Write unit tests
673
-
674
- ### New Middleware
675
-
676
- - [ ] Create \`src/middleware/<name>.middleware.ts\`
677
- - [ ] Export middleware function (Express format)
678
- - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
679
- - [ ] Test with sample requests
680
-
681
- ### Adding a Package
682
-
683
- Use \`kick add\` to install KickJS packages with correct peer dependencies:
684
-
685
- - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
686
- - [ ] Follow package-specific setup in terminal output
687
- - [ ] Update \`src/index.ts\` to register adapter (if needed)
688
- - [ ] Configure environment variables in \`.env\`
689
- - [ ] Test integration with \`kick dev\`
690
-
691
- ## Common Tasks
692
-
693
- ### Generate CRUD Module
694
-
695
- \`\`\`bash
696
- kick g scaffold user name:string email:string:optional age:number
697
- \`\`\`
698
-
699
- Append \`:optional\` for optional fields (shell-safe, no quoting needed).
700
- Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
701
-
702
- This creates a full CRUD module with:
703
- - Controller with GET, POST, PUT, DELETE routes
704
- - Service with business logic
705
- - Repository with data access
706
- - DTOs with Zod validation
707
-
708
- ### Add Authentication
709
-
710
- \`\`\`bash
711
- kick add auth
712
- \`\`\`
713
-
714
- Then configure in \`src/index.ts\`:
715
-
716
- \`\`\`ts
717
- import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
718
-
719
- bootstrap({
720
- modules,
721
- adapters: [
722
- AuthAdapter({
723
- strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
724
- }),
725
- ],
726
- })
727
- \`\`\`
728
-
729
- ### Add Database (Prisma)
730
-
731
- \`\`\`bash
732
- kick add prisma
733
- ${n} install prisma @prisma/client
734
- npx prisma init
735
- # Edit prisma/schema.prisma
736
- npx prisma migrate dev --name init
737
- kick g module user --repo prisma
738
- \`\`\`
739
-
740
- ### Add WebSocket Support
741
-
742
- \`\`\`bash
743
- kick add ws
744
- \`\`\`
745
-
746
- Then add adapter in \`src/index.ts\`:
747
-
748
- \`\`\`ts
749
- import { WsAdapter } from '@forinda/kickjs-ws'
750
-
751
- bootstrap({
752
- modules,
753
- adapters: [WsAdapter()],
754
- })
755
- \`\`\`
756
-
757
- Create WebSocket controller:
758
-
759
- \`\`\`bash
760
- kick g controller chat --ws
761
- \`\`\`
762
-
763
- ## Testing Guidelines
764
-
765
- All tests use Vitest:
766
-
767
- \`\`\`ts
768
- import { describe, it, expect, beforeEach } from 'vitest'
769
- import { Container } from '@forinda/kickjs'
770
- import { createTestApp } from '@forinda/kickjs-testing'
771
-
772
- describe('UserController', () => {
773
- it('should return users', async () => {
774
- // Container.create() — isolated DI state per test, never new Container()
775
- // and never getInstance().reset() (both leak registrations between tests).
776
- const container = Container.create()
777
- const app = await createTestApp([UserModule], { container })
778
- const res = await app.get('/users')
779
-
780
- expect(res.status).toBe(200)
781
- expect(res.body).toHaveProperty('users')
782
- })
783
- })
784
- \`\`\`
785
-
786
- Run tests:
787
- - \`${n} run test\` — run all tests once
788
- - \`${n} run test:watch\` — watch mode
789
- - Individual file: \`${n} run test src/modules/user/user.test.ts\`
790
-
791
- ## Environment Variables
792
-
793
- Schema is declared in \`src/config/index.ts\` (extends the base
794
- \`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
795
- with kickjs at module load. \`src/index.ts\` imports it via
796
- \`import './config'\` **before** \`bootstrap()\` so the cache is populated
797
- in time for DI. Add new keys to the schema, drop their values into
798
- \`.env\`, and they're typed everywhere.
799
-
800
- Access patterns:
801
-
802
- 1. **@Value() decorator** (recommended for known-at-construction keys):
803
- \`\`\`ts
804
- @Value('DATABASE_URL')
805
- private dbUrl!: string
806
- \`\`\`
807
-
808
- 2. **ConfigService** (recommended for dynamic / method-scoped access):
809
- \`\`\`ts
810
- @Autowired()
811
- private config!: ConfigService
812
-
813
- const port = this.config.get('PORT') // typed: number
814
- \`\`\`
815
-
816
- 3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
817
- \`\`\`ts
818
- import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
819
-
820
- const env = loadEnv(schema) // Parse + validate all vars
821
- const port = getEnv('PORT') // Single value lookup
822
- reloadEnv() // Re-read .env from disk
823
- resetEnvCache() // Full reset (for tests)
824
- \`\`\`
825
-
826
- 4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
827
- coercion and the typed \`KickEnv\` registry.
828
-
829
- > **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
830
- > If the schema is not registered before DI runs, \`config.get()\`
831
- > returns \`undefined\` for user keys (the base shape only) and
832
- > \`@Value()\` only works because of its raw \`process.env\` fallback —
833
- > Zod coercion + schema defaults are silently skipped.
834
-
835
- ## Standalone Utilities (No DI Required)
836
-
837
- These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
838
-
839
- | Utility | Import | Example |
840
- |---------|--------|---------|
841
- | \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
842
- | \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
843
- | \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
844
- | \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
845
- | \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
846
- | \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
847
- | \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
848
- | \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
849
- | \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
850
-
851
- ## Key Decorators
852
-
853
- ### HTTP Routes
854
- | Decorator | Purpose |
855
- |-----------|---------|
856
- | \`@Controller()\` | Define route prefix |
857
- | \`@Get('/'), @Post('/')\` | HTTP method handlers |
858
- | \`@Middleware(fn)\` | Attach middleware |
859
- | \`@Public()\` | Skip auth (requires auth adapter) |
860
- | \`@Roles('admin')\` | Role-based access |
861
-
862
- ### Dependency Injection
863
- | Decorator | Purpose |
864
- |-----------|---------|
865
- | \`defineModule({...})\` | Define feature module (factory; preferred — paired with \`defineModules()\` registry) |
866
- | \`defineModules()\` | Build the modules registry as a chainable list (\`.mount(X())\`) |
867
- | \`AppModule\` interface | Legacy module shape — \`class X implements AppModule\` (toggle via \`modules.style: 'class'\`) |
868
- | \`@Service()\` | Register singleton service |
869
- | \`@Repository()\` | Register repository |
870
- | \`@Autowired()\` | Property injection |
871
- | \`@Inject('token')\` | Token-based injection |
872
- | \`@Value('VAR')\` | Inject env variable |
873
-
874
- ### Context Decorators
875
-
876
- Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
877
- Use this **instead of \`@Middleware()\`** when the middleware's only output
878
- is a value other code reads off \`ctx\`.
879
-
880
- | Concept | Where it lives |
881
- |---------|----------------|
882
- | \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
883
- | Method/class decorator | \`@LoadX\` on a controller method/class |
884
- | Module hook | \`build: () => ({ contributors() { return [...] } })\` (\`defineModule\`) — or \`AppModule.contributors?()\` for class form |
885
- | Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
886
- | Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
887
- | Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
888
-
889
- Precedence high → low: **method > class > module > adapter > global**.
890
- Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
891
- fast). The \`onError\` hook is async-permitted.
892
-
893
- Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
894
-
895
- ${t===`cqrs`?`### Background Jobs
896
- | Decorator | Purpose |
897
- |-----------|---------|
898
- | \`@Job('name')\` | Queue job handler |
899
- | \`@Process('queue')\` | Queue processor |
900
- | \`@Cron('0 * * * *')\` | Cron schedule |
901
- | \`@WsController()\` | WebSocket controller |
902
-
903
- `:``}## Common Pitfalls
904
-
905
- 1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
906
- 2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
907
- 3. **Tests failing randomly** — Sharing the global container between tests. Default to \`Container.create()\` per test (or per \`beforeEach\`) instead of \`new Container()\` / \`getInstance().reset()\`
908
- 4. **Routes not found** — Check controller path and module registration
909
- 5. **HMR not working** — Two checks: (a) \`vite.config.ts\` has \`hmr: true\`; (b) module file is named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and lives under \`src/modules/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed module file (e.g., \`projects.ts\`) silently degrades to a full restart on every save.
910
- 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
911
- 7. **\`config.get('YOUR_KEY')\` returns \`undefined\`** — \`src/index.ts\` is missing \`import './config'\`. That side-effect import registers the env schema with kickjs (\`loadEnv(envSchema)\` runs at module load). Without it, \`ConfigService\` falls back to the base schema (\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` only) and every user-defined key reads as \`undefined\`. \`@Value()\` may *appear* to work because of a raw \`process.env\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \`src/index.ts\` and \`src/config/index.ts\` first.
912
- 8. **Used \`@Middleware()\` to compute a value for \`ctx\`** — prefer \`defineContextDecorator()\` (see Context Decorators above). It's typed via \`ContextMeta\`, supports \`dependsOn\` for ordering, and validates the pipeline at boot. \`@Middleware()\` is for response short-circuiting, stream mutation, and pre-route-matching work.
913
- 9. **Context contributor's \`dependsOn\` key not produced anywhere** — boot throws \`MissingContributorError\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).
914
- 10. **\`bootstrap()\` not exported** — \`src/index.ts\` calls \`await bootstrap({ ... })\` but discards the return value (no \`export const app = ...\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \`createTestApp\`/\`@forinda/kickjs-testing\` consumers can't import the handle either. Always: \`export const app = await bootstrap({ ... })\`.
915
- 11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \`kick g agents -f\` (or \`kick g agent-docs -f\`) to regenerate from the latest CLI templates after \`kick add\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \`AGENTS.local.md\`.
916
-
917
- ## CLI Commands Reference
918
-
919
- | Command | Description |
920
- |---------|-------------|
921
- | \`kick dev\` | Dev server with HMR |
922
- | \`kick dev:debug\` | Dev server with debugger |
923
- | \`kick build\` | Production build |
924
- | \`kick start\` | Run production build |
925
- | \`kick g module <names...>\` | Generate one or more modules |
926
- | \`kick g scaffold <name> <fields>\` | Generate CRUD |
927
- | \`kick g controller <name>\` | Generate controller |
928
- | \`kick g service <name>\` | Generate service |
929
- | \`kick g middleware <name>\` | Generate middleware |
930
- | \`kick add <package>\` | Add KickJS package |
931
- | \`kick add --list\` | List available packages |
932
- | \`kick rm module <names...>\` | Remove one or more modules |
933
-
934
- > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
935
- > \`\`\`bash
936
- > kick new my-api -t ddd -r prisma --pm ${n} --no-git --no-install -f
937
- > \`\`\`
938
-
939
- ## Learn More
940
-
941
- - [KickJS Docs](https://forinda.github.io/kick-js/)
942
- - [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
943
- - [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
944
- - [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
945
- - [Testing](https://forinda.github.io/kick-js/api/testing.html)
946
- `}function lt(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
947
-
948
- This file is the agent-facing **skills index** for KickJS work in this
949
- repo. Each block below is a short, rigid workflow keyed to a specific
950
- trigger ("user wants to add a module", "tests are leaking state", etc.).
951
-
952
- - Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
953
- - Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
954
- - **This file** → step-by-step recipes the agent should *execute*.
955
-
956
- Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
957
-
958
- ---
959
-
960
- ## Skill: add-module
961
-
962
- \`\`\`yaml
963
- name: kickjs-add-module
964
- description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
965
- \`\`\`
966
-
967
- **Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
968
-
969
- **Steps**:
970
- 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
971
- 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
972
- 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
973
- 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
974
- 5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
975
-
976
- **Red flags** (stop and ask):
977
- - File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
978
- - Module not registered in \`src/modules/index.ts\`.
979
- - \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
980
-
981
- ---
982
-
983
- ## Skill: add-adapter
984
-
985
- \`\`\`yaml
986
- name: kickjs-add-adapter
987
- description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
988
- \`\`\`
989
-
990
- **Steps**:
991
- 1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
992
- 2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
993
- 3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
994
- 4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
995
- 5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
996
-
997
- **Red flags**:
998
- - Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
999
- - Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
1000
-
1001
- ---
1002
-
1003
- ## Skill: write-controller-test
1004
-
1005
- \`\`\`yaml
1006
- name: kickjs-write-controller-test
1007
- description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
1008
- \`\`\`
1009
-
1010
- **Template** (copy/paste, adjust):
1011
-
1012
- \`\`\`ts
1013
- import { describe, it, expect } from 'vitest'
1014
- import { Container } from '@forinda/kickjs'
1015
- import { createTestApp } from '@forinda/kickjs-testing'
1016
-
1017
- describe('UserController', () => {
1018
- it('returns users', async () => {
1019
- const container = Container.create() // isolated DI per test
1020
- const app = await createTestApp([UserModule], { container })
1021
- const res = await app.get('/users')
1022
- expect(res.status).toBe(200)
1023
- })
1024
- })
1025
- \`\`\`
1026
-
1027
- **Red flags**:
1028
- - \`new Container()\` — wrong; use \`Container.create()\`.
1029
- - \`Container.getInstance().reset()\` — wrong; same fix.
1030
- - Sharing a container across \`it()\` blocks — leaks registrations.
1031
-
1032
- ---
1033
-
1034
- ## Skill: env-wiring-check
1035
-
1036
- \`\`\`yaml
1037
- name: kickjs-env-wiring-check
1038
- description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
1039
- \`\`\`
1040
-
1041
- **Diagnosis**:
1042
- 1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
1043
- 2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
1044
- 3. The new key MUST be declared in the Zod schema there. \`@Value('NEW_KEY')\` won't work without a schema entry (it'll fall back to raw \`process.env\` and skip Zod coercion silently).
1045
-
1046
- **Fix**: add the key to the schema; ensure both side-effect imports above are present.
1047
-
1048
- ---
1049
-
1050
- ## Skill: bootstrap-export
1051
-
1052
- \`\`\`yaml
1053
- name: kickjs-bootstrap-export
1054
- description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
1055
- \`\`\`
1056
-
1057
- **Check** \`src/index.ts\`'s last line:
1058
-
1059
- \`\`\`ts
1060
- // CORRECT
1061
- export const app = await bootstrap({ ... })
1062
-
1063
- // WRONG (HMR degrades to full restart, createTestApp loses the handle)
1064
- await bootstrap({ ... })
1065
- \`\`\`
1066
-
1067
- The Vite plugin imports the named \`app\` symbol; testing helpers do too.
1068
-
1069
- ---
1070
-
1071
- ## Skill: thin-entry-file
1072
-
1073
- \`\`\`yaml
1074
- name: kickjs-thin-entry-file
1075
- description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
1076
- \`\`\`
1077
-
1078
- **Refactor target**:
1079
-
1080
- \`\`\`ts
1081
- // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
1082
- export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
1083
- // OR for class-form projects (\`modules.style: 'class'\`):
1084
- // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
1085
-
1086
- // src/middleware/index.ts
1087
- export const middleware = [helmet(), cors(), requestId(), ...]
1088
-
1089
- // src/plugins/index.ts
1090
- export const plugins = [MetricsPlugin(), ...]
1091
-
1092
- // src/adapters/index.ts
1093
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
1094
-
1095
- // src/index.ts — stays small
1096
- import 'reflect-metadata'
1097
- import './config'
1098
- import { bootstrap } from '@forinda/kickjs'
1099
- import { modules } from './modules'
1100
- import { middleware } from './middleware'
1101
- import { plugins } from './plugins'
1102
- import { adapters } from './adapters'
1103
- export const app = await bootstrap({ modules, middleware, plugins, adapters })
1104
- \`\`\`
1105
-
1106
- **Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
1107
-
1108
- ---
1109
-
1110
- ## Skill: context-contributor
1111
-
1112
- \`\`\`yaml
1113
- name: kickjs-context-contributor
1114
- description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
1115
- \`\`\`
1116
-
1117
- **Pattern** (HTTP — most common):
1118
-
1119
- \`\`\`ts
1120
- import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
1121
-
1122
- const LoadTenant = defineHttpContextDecorator({
1123
- key: 'tenant',
1124
- deps: { repo: TENANT_REPO },
1125
- resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
1126
- })
1127
-
1128
- const LoadProject = defineHttpContextDecorator({
1129
- key: 'project',
1130
- dependsOn: ['tenant'],
1131
- resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
1132
- })
1133
-
1134
- @LoadTenant
1135
- @LoadProject
1136
- @Get('/projects/:id')
1137
- getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
1138
- \`\`\`
1139
-
1140
- Use \`defineContextDecorator\` (no Http prefix) when authoring a contributor that must run across HTTP, WebSocket, queue, and cron transports — \`Ctx\` defaults to the smaller \`ExecutionContext\` surface (\`get\` / \`set\` / \`requestId\` only, no \`req\`).
1141
-
1142
- Precedence high → low: **method > class > module > adapter > global**.
1143
- Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
1144
-
1145
- **Critical rules — all stem from the same shared-via-ALS instance model**:
1146
- - Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
1147
- - **\`resolve\` and \`onError\` must RETURN the value** — the runner writes it via \`ctx.set(key, value)\`. Direct property assignment (\`ctx.tenant = …\`) sticks to one instance only and the handler instance never sees it.
1148
- - \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
1149
- - Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
1150
- - **No \`setRequestValue\` — writes flow through \`ctx.set\` or a contributor's return value.** Avoids "spooky action at a distance" where any service can pollute the per-request bag.
1151
-
1152
- **Don't use this for**: response short-circuit, stream mutation, or
1153
- pre-route-matching work — keep \`@Middleware()\` for those.
1154
-
1155
- ---
1156
-
1157
- ## Skill: refresh-agent-docs
1158
-
1159
- \`\`\`yaml
1160
- name: kickjs-refresh-agent-docs
1161
- description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
1162
- \`\`\`
1163
-
1164
- **Steps**:
1165
- 1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
1166
- 2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
1167
- 3. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate \`AGENTS.local.md\` or appended section.
1168
- 4. Commit as \`docs(agents): sync from CLI vX.Y\`.
1169
-
1170
- ---
1171
-
1172
- ## Skill: deny-list
1173
-
1174
- \`\`\`yaml
1175
- name: kickjs-deny-list
1176
- description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
1177
- \`\`\`
1178
-
1179
- - \`class implements AppAdapter\` → use \`defineAdapter()\`.
1180
- - \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
1181
- - \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
1182
- - \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
1183
- - DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
1184
- - \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
1185
- - Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
1186
-
1187
- ---
1188
-
1189
- ## Learn More
1190
-
1191
- - [KickJS Docs](https://forinda.github.io/kick-js/)
1192
- - [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
1193
- - [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
1194
- - [Testing](https://forinda.github.io/kick-js/api/testing.html)
1195
- `}const ut=x(se(import.meta.url)),dt=JSON.parse(v(S(ut,`..`,`package.json`),`utf-8`)),ft=`^${dt.version}`,pt=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`,`@forinda/kickjs-auth`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`];async function mt(){let e=await Promise.all(pt.map(async e=>{try{let t=ce(`npm`,[`view`,e,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(t&&/^\d+\.\d+\.\d+/.test(t))return[e,`^${t}`]}catch{}return[e,ft]}));return Object.fromEntries(e)}async function ht(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:i=`rest`,defaultRepo:a=`inmemory`,packages:o=[]}=e,s=n,c=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),c(`Resolving package versions...`);let l=await mt();if(await M(S(s,`package.json`),Ue(t,i,l,o)),await M(S(s,`vite.config.ts`),We()),await M(S(s,`tsconfig.json`),Ge()),await M(S(s,`.prettierrc`),Ke()),await M(S(s,`.editorconfig`),qe()),await M(S(s,`.gitignore`),Je()),await M(S(s,`.gitattributes`),Ye()),await M(S(s,`.env`),Xe()),await M(S(s,`.env.example`),Ze()),await M(S(s,`src/config/index.ts`),tt()),await M(S(s,`src/index.ts`),$e(t,i,dt.version,o)),await M(S(s,`src/modules/index.ts`),et()),await M(S(s,`src/modules/hello/hello.service.ts`),nt()),await M(S(s,`src/modules/hello/hello.controller.ts`),rt()),await M(S(s,`src/modules/hello/hello.module.ts`),it()),await M(S(s,`kick.config.ts`),at(i,a,r)),await M(S(s,`vitest.config.ts`),Qe()),await M(S(s,`README.md`),ot(t,i,r)),await M(S(s,`CLAUDE.md`),st(t,i,r)),await M(S(s,`AGENTS.md`),ct(t,i,r)),await M(S(s,`kickjs-skills.md`),lt(t,i,r)),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{E(`${r} install`,{cwd:s,stdio:`inherit`}),console.log(`
1196
- Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-COED-VIb.mjs`).then(e=>e.r);await e({cwd:s,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{E(`git init`,{cwd:s,stdio:`pipe`}),E(`git branch -M main`,{cwd:s,stdio:`pipe`}),E(`git add -A`,{cwd:s,stdio:`pipe`}),E(`git commit -m "chore: initial commit from kick new"`,{cwd:s,stdio:`pipe`}),c(`Git repository initialized`)}catch{c(`Warning: git init failed (git may not be installed)`)}console.log(`
1197
- Project scaffolded successfully!`),console.log();let u=s!==process.cwd();c(`Next steps:`),u&&c(` cd ${t}`),e.installDeps||c(` ${r} install`);let d={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};c(` ${d[i]??d.rest}`),c(` kick dev`),c(``),c(`Commands:`),c(` kick dev Start dev server with Vite HMR`),c(` kick build Production build via Vite`),c(` kick start Run production build`),c(``),c(`Generators:`),c(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),c(` kick g scaffold <n> <f..> CRUD module from field definitions`),c(` kick g controller <name> Standalone controller`),c(` kick g service <name> @Service() class`),c(` kick g middleware <name> Express middleware`),c(` kick g guard <name> Route guard (auth, roles, etc.)`),c(` kick g adapter <name> AppAdapter with lifecycle hooks`),c(` kick g dto <name> Zod DTO schema`),i===`cqrs`&&c(` kick g job <name> Queue job processor`),c(` kick g config Generate kick.config.ts`),c(``),c(`Add packages:`),c(` kick add <pkg> Install a KickJS package + peers`),c(` kick add --list Show all available packages`),c(``),c(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),c(``)}const gt={GET:A.green,POST:A.cyan,PUT:A.yellow,PATCH:A.magenta,DELETE:A.red};function _t(e){return(gt[e]??A.dim)(e.padEnd(7))}function vt(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return A.red(t);case`WARNING`:return A.yellow(t);case`INFO`:return A.blue(A.dim(t));default:return t}}A.green(`✓`),A.red(`✖`),A.yellow(`⚠`),A.blue(`ℹ`);function yt(e){k.intro(A.bgCyan(A.black(` ${e} `)))}function bt(e){k.outro(e)}function xt(e){k.isCancel(e)&&(k.cancel(`Operation cancelled.`),process.exit(0))}async function St(e){let t=await k.text(e);return xt(t),t}async function Ct(e){let t=await k.select(e);return xt(t),t}async function wt(e){let t=await k.multiselect(e);return xt(t),t}async function F(e){let t=await k.confirm(e);return xt(t),t}function Tt(){return k.spinner()}const I=k.log,Et={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},"db-pg":{pkg:`@forinda/kickjs-db-pg`,peers:[`pg`],description:`kick/db PostgreSQL dialect + adapter (pgDialect, pgAdapter)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},auth:{pkg:`@forinda/kickjs-auth`,peers:[`jsonwebtoken`],description:`Authentication — JWT, API key, and custom strategies`},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},mcp:{pkg:`@forinda/kickjs-mcp`,peers:[`@modelcontextprotocol/sdk`],description:`Model Context Protocol server — expose @Controller endpoints as AI tools`},testing:{pkg:`@forinda/kickjs-testing`,peers:[],description:`Test utilities and TestModule builder`,dev:!0}};function L(e,t=process.cwd()){let n=t;for(;;){if(g(w(n,e)))return n;let t=x(n);if(t===n)return null;n=t}}function Dt(){return L(`pnpm-lock.yaml`)?`pnpm`:L(`yarn.lock`)?`yarn`:L(`bun.lockb`)||L(`bun.lock`)?`bun`:L(`package-lock.json`)?`npm`:null}function Ot(){let e=process.cwd();for(;e;){let t=w(e,`package.json`);if(g(t))try{let e=JSON.parse(v(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(i.includes(t))return t}}catch{}let n=x(e);if(n===e)return null;e=n}return null}async function kt(e){if(e&&i.includes(e))return{pm:e,source:`flag`};let t=await r(process.cwd());if(t?.packageManager&&i.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=Ot();if(n)return{pm:n,source:`package.json`};let a=Dt();return a?{pm:a,source:`lockfile`}:{pm:`npm`,source:`default`}}async function At(e){let{pm:t}=await kt(e);return t}function jt(e=!1){let t=Object.entries(Et),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``;return` ${r} ${t.description}${i}`};console.log(`
1198
- Core packages (always installed by \`kick new\`):
1199
- `);for(let e of r)console.log(a(e));if(e){console.log(`
1200
- Optional packages (add as needed):
1201
- `);for(let e of i)console.log(a(e))}else console.log(`\n Plus ${i.length} optional packages (auth, swagger, db, queue, …).`),console.log(" Run `kick add --list --all` for the full catalog.");console.log(`
1202
- Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function Mt(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{jt(!!e.all)})}function Nt(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){jt(!!t.all);return}let{pm:n,source:r}=await kt(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=t.dev,a=new Set,o=new Set,s=[];for(let t of e){let e=Et[t];if(!e){s.push(t);continue}let n=i||e.dev?o:a;n.add(e.pkg);for(let t of e.peers)n.add(t)}if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
1203
- `),a.size===0&&o.size===0))){if(a.size>0){let e=Array.from(a),t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{E(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.size>0){let e=Array.from(o),t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{E(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
1204
- `)}})}const Pt=[{value:`auth`,label:`Auth`,hint:`JWT, OAuth, API keys`},{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function Ft(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | ddd | cqrs | minimal`).option(`-r, --repo <type>`,`Default repository: prisma | drizzle | inmemory | custom`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{yt(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await St({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=w(`.`),e=re(r)):r=w(t.directory||e),g(r)){let i=y(r);if(i.length>0){if(t.force)I.warn(`Clearing existing files in ${r}`);else if(n){I.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),bt(`Aborted.`);return}else{I.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)I.message(` - ${e}`);if(i.length>5&&I.message(` ... and ${i.length-5} more`),!await F({message:A.red(`Remove all existing files and proceed?`),initialValue:!1})){bt(`Aborted.`);return}}for(let e of i)ee(w(r,e),{recursive:!0,force:!0})}}let i=t.template;i||=n?`minimal`:await Ct({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`ddd`,label:`DDD`,hint:`Domain-Driven Design modules`},{value:`cqrs`,label:`CQRS`,hint:`Commands, Queries, Events + WS/Queue`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let a=t.pm;a||=n?await At(void 0):await Ct({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let o=t.repo;o||(n?o=`inmemory`:(o=await Ct({message:`Default repository/ORM`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle`},{value:`inmemory`,label:`In-Memory`},{value:`custom`,label:`Custom`,hint:`specify later`}]}),o===`custom`&&(o=await St({message:`Custom repository name`,defaultValue:`custom`}))));let s;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();s=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else s=n?[]:await wt({message:`Select packages to include`,options:[...Pt],required:!1});let c;c=t.git===void 0?n?!0:await F({message:`Initialize git repository?`,initialValue:!0}):t.git;let l;l=t.install===void 0?n?!0:await F({message:`Install dependencies?`,initialValue:!0}):t.install,await ht({name:e,directory:r,packageManager:a,initGit:c,installDeps:l,template:i,defaultRepo:o,packages:s}),bt(`Done! Next steps: ${A.cyan(`cd ${e} && ${a} dev`)}`)})}function R(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function z(e){let t=R(e);return t.charAt(0).toLowerCase()+t.slice(1)}function B(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function V(e){return ve.plural(e)}function It(e){return ve.plural(e)}function Lt(e){return B(e).replace(/-/g,`_`)}function Rt(e){let t=e.cwd??process.cwd(),n=e.pluralize??!0,r=R(e.name),i=z(e.name),a=B(e.name),o=Lt(e.name),s={name:e.name,pascal:r,camel:i,kebab:a,snake:o,modulesDir:e.modulesDir??`src/modules`,cwd:t,args:e.args??[],flags:e.flags??{}};if(n){let e=V(a);s.pluralKebab=e,s.pluralPascal=R(e),s.pluralCamel=z(e)}return s}function zt(e,t){return w(e.cwd,t)}async function Bt(e){return import(T(e).href)}const Vt=new Map;async function Ht(e){let t=Vt.get(e);if(t)return t;let n=Ut(e);return Vt.set(e,n),n}async function Ut(e){let t=w(e,`package.json`);if(!g(t))return{generators:[],loaded:[],failed:[]};let n=Wt(JSON.parse(await D(t,`utf-8`))),r=m(w(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await D(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=w(x(t),s);if(!g(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await Bt(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u)){o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of u){if(!Gt(t)){o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}i.push({source:e,spec:t})}a.push(e)}return{generators:i,loaded:a,failed:o}}function Wt(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function Gt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function Kt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Yt(r.spec,r.source,e,n);let i=Jt(await Ht(n),e.generatorName);return i?Yt(i.spec,i.source,e,n):null}async function qt(e,t=[]){let n=await Ht(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function Jt(e,t){return e.generators.find(e=>e.spec.name===t)}async function Yt(e,t,n,r){let i=Rt({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r}),a=await e.files(i),o=[];for(let e of a){let t=zt(i,e.path);await M(t,e.content),o.push(t)}return{files:o,source:t}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Xt={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function Zt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Qt(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function $t(e){return Xt[e]??Zt(e)}function en(e,t,n){let r={inmemory:`InMemory${e}Repository`,drizzle:`Drizzle${e}Repository`,prisma:`Prisma${e}Repository`},i={inmemory:`in-memory-${t}`,drizzle:`drizzle-${t}`,prisma:`prisma-${t}`};return{repoClass:r[n]??`${Zt(n)}${e}Repository`,repoFile:i[n]??`${Qt(n)}-${t}`}}function tn(e){return e??`define`}function nn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=en(t,n,i),c=tn(a),l=`/**
1205
- * ${t} Module
1206
- *
1207
- * Self-contained feature module following Domain-Driven Design (DDD).
1208
- * Registers dependencies in the DI container and declares HTTP routes.
1209
- *
1210
- * Structure:
1211
- * presentation/ — HTTP controllers (entry points)
1212
- * application/ — Use cases (orchestration) and DTOs (validation)
1213
- * domain/ — Entities, value objects, repository interfaces, domain services
1214
- * infrastructure/ — Repository implementations (currently ${$t(i)})
1215
- */`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './domain/repositories/${n}.repository'
1216
- import { ${o} } from './infrastructure/repositories/${s}.repository'
1217
- import { ${t}Controller } from './presentation/${n}.controller'
1218
-
1219
- // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
1220
- import.meta.glob(
1221
- ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
1222
- { eager: true },
1223
- )`,d=` /**
1224
- * Declare HTTP routes for this module. Return value shape:
1225
- *
1226
- * - \`path\` — URL prefix for this route set, mounted under
1227
- * \`/{apiPrefix}/v{version}{path}\`.
1228
- * - \`controller\` — Controller class. Used both for the route
1229
- * handler bindings and OpenAPI spec generation.
1230
- * - \`version\` — Optional. Overrides the app-wide API version
1231
- * for this route set only.
1232
- *
1233
- * Return an **array** to mount multiple route sets under the
1234
- * same module (e.g. side-by-side v1 + v2 controllers):
1235
- *
1236
- * return [
1237
- * { path: '/${r}', version: 1, controller: ${t}V1Controller },
1238
- * { path: '/${r}', version: 2, controller: ${t}V2Controller },
1239
- * ]
1240
- */`;return c===`class`?`${l}
1241
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1242
- ${u}
1243
-
1244
- export class ${t}Module implements AppModule {
1245
- /**
1246
- * Register module dependencies in the DI container.
1247
- * Bind repository interface tokens to their implementations here.
1248
- * Currently wired to ${$t(i)}. To swap implementations, change the factory target.
1249
- */
1250
- register(container: Container): void {
1251
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1252
- container.resolve(${o}),
1253
- )
1254
- }
1255
-
1256
- ${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
1257
- routes(): ModuleRoutes {
1258
- return {
1259
- path: '/${r}',
1260
- controller: ${t}Controller,
1261
- }
1262
- }
1263
- }
1264
- `:`${l}
1265
- import { defineModule } from '@forinda/kickjs'
1266
- ${u}
1267
-
1268
- export const ${t}Module = defineModule({
1269
- name: '${t}Module',
1270
- build: () => ({
1271
- /**
1272
- * Register module dependencies in the DI container.
1273
- * Bind repository interface tokens to their implementations here.
1274
- * Currently wired to ${$t(i)}. To swap implementations, change the factory target.
1275
- */
1276
- register(container) {
1277
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1278
- container.resolve(${o}),
1279
- )
1280
- },
1281
-
1282
- ${d}
1283
- routes() {
1284
- return {
1285
- path: '/${r}',
1286
- controller: ${t}Controller,
1287
- }
1288
- },
1289
- }),
1290
- })
1291
- `}function rn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=en(t,n,i),c=tn(a),l=`/**
1292
- * ${t} Module
1293
- *
1294
- * REST module with a flat folder structure.
1295
- * Controller delegates to service, service wraps the repository.
1296
- *
1297
- * Structure:
1298
- * ${n}.controller.ts — HTTP routes (CRUD)
1299
- * ${n}.service.ts — Business logic
1300
- * ${n}.repository.ts — Repository interface
1301
- * ${s}.repository.ts — Repository implementation
1302
- * dtos/ — Request/response schemas
1303
- */`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
1304
- import { ${o} } from './${s}.repository'
1305
- import { ${t}Controller } from './${n}.controller'
1306
-
1307
- // Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
1308
- import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })`,d=` /**
1309
- * Declare HTTP routes for this module. Return value shape:
1310
- *
1311
- * - \`path\` — URL prefix for this route set.
1312
- * - \`controller\` — Controller class (also drives OpenAPI).
1313
- * - \`version\` — Optional. Overrides the app-wide API version.
1314
- *
1315
- * Return an **array** to mount multiple route sets — admin
1316
- * surfaces, side-by-side v1 + v2 controllers, etc:
1317
- *
1318
- * return [
1319
- * { path: '/${r}', version: 1, controller: ${t}V1Controller },
1320
- * { path: '/${r}', version: 2, controller: ${t}V2Controller },
1321
- * ]
1322
- */`;return c===`class`?`${l}
1323
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1324
- ${u}
1325
-
1326
- export class ${t}Module implements AppModule {
1327
- register(container: Container): void {
1328
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1329
- container.resolve(${o}),
1330
- )
1331
- }
1332
-
1333
- ${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
1334
- routes(): ModuleRoutes {
1335
- return {
1336
- path: '/${r}',
1337
- controller: ${t}Controller,
1338
- }
1339
- }
1340
- }
1341
- `:`${l}
1342
- import { defineModule } from '@forinda/kickjs'
1343
- ${u}
1344
-
1345
- export const ${t}Module = defineModule({
1346
- name: '${t}Module',
1347
- build: () => ({
1348
- register(container) {
1349
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
1350
- container.resolve(${o}),
1351
- )
1352
- },
1353
-
1354
- ${d}
1355
- routes() {
1356
- return {
1357
- path: '/${r}',
1358
- controller: ${t}Controller,
1359
- }
1360
- },
1361
- }),
1362
- })
1363
- `}function an(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=tn(i),o=` /**
1364
- * Declare HTTP routes. Return value shape:
1365
- *
1366
- * - \`path\` — URL prefix for this route set.
1367
- * - \`controller\` — Controller class (also drives OpenAPI).
1368
- * - \`version\` — Optional. Overrides the app-wide API version.
1369
- *
1370
- * Return an array to mount multiple route sets:
1371
- *
1372
- * return [
1373
- * { path: '/${r}', version: 1, controller: ${t}V1Controller },
1374
- * { path: '/${r}', version: 2, controller: ${t}V2Controller },
1375
- * ]
1376
- */`;return a===`class`?`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
1377
- import { ${t}Controller } from './${n}.controller'
1378
-
1379
- export class ${t}Module implements AppModule {
1380
- ${o.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
1381
- routes(): ModuleRoutes {
1382
- return {
1383
- path: '/${r}',
1384
- controller: ${t}Controller,
1385
- }
1386
- }
1387
- }
1388
- `:`import { defineModule } from '@forinda/kickjs'
1389
- import { ${t}Controller } from './${n}.controller'
1390
-
1391
- export const ${t}Module = defineModule({
1392
- name: '${t}Module',
1393
- build: () => ({
1394
- ${o}
1395
- routes() {
1396
- return {
1397
- path: '/${r}',
1398
- controller: ${t}Controller,
1399
- }
1400
- },
1401
- }),
1402
- })
1403
- `}function on(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
1404
- import { ApiTags } from '@forinda/kickjs-swagger'
1405
- import { Create${t}UseCase } from '../application/use-cases/create-${n}.use-case'
1406
- import { Get${t}UseCase } from '../application/use-cases/get-${n}.use-case'
1407
- import { List${i}UseCase } from '../application/use-cases/list-${r}.use-case'
1408
- import { Update${t}UseCase } from '../application/use-cases/update-${n}.use-case'
1409
- import { Delete${t}UseCase } from '../application/use-cases/delete-${n}.use-case'
1410
- import { create${t}Schema } from '../application/dtos/create-${n}.dto'
1411
- import { update${t}Schema } from '../application/dtos/update-${n}.dto'
1412
- import { ${t.toUpperCase()}_QUERY_CONFIG } from '../constants'
1413
-
1414
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
1415
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
1416
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
1417
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
1418
-
1419
- @Controller()
1420
- export class ${t}Controller {
1421
- @Autowired() private readonly create${t}UseCase!: Create${t}UseCase
1422
- @Autowired() private readonly get${t}UseCase!: Get${t}UseCase
1423
- @Autowired() private readonly list${i}UseCase!: List${i}UseCase
1424
- @Autowired() private readonly update${t}UseCase!: Update${t}UseCase
1425
- @Autowired() private readonly delete${t}UseCase!: Delete${t}UseCase
1426
-
1427
- @Get('/')
1428
- @ApiTags('${t}')
1429
- @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
1430
- async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1431
- return ctx.paginate(
1432
- (parsed) => this.list${i}UseCase.execute(parsed),
1433
- ${t.toUpperCase()}_QUERY_CONFIG,
1434
- )
1435
- }
1436
-
1437
- @Get('/:id')
1438
- @ApiTags('${t}')
1439
- async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
1440
- const result = await this.get${t}UseCase.execute(ctx.params.id)
1441
- if (!result) return ctx.notFound('${t} not found')
1442
- ctx.json(result)
1443
- }
1444
-
1445
- @Post('/', { body: create${t}Schema, name: 'Create${t}' })
1446
- @ApiTags('${t}')
1447
- async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
1448
- const result = await this.create${t}UseCase.execute(ctx.body)
1449
- ctx.created(result)
1450
- }
1451
-
1452
- @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
1453
- @ApiTags('${t}')
1454
- async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
1455
- const result = await this.update${t}UseCase.execute(ctx.params.id, ctx.body)
1456
- ctx.json(result)
1457
- }
1458
-
1459
- @Delete('/:id')
1460
- @ApiTags('${t}')
1461
- async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
1462
- await this.delete${t}UseCase.execute(ctx.params.id)
1463
- ctx.noContent()
1464
- }
1465
- }
1466
- `}function sn(e){let{pascal:t,kebab:n}=e,r=t.charAt(0).toLowerCase()+t.slice(1);return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
1467
- import { ApiTags } from '@forinda/kickjs-swagger'
1468
- import { ${t}Service } from './${n}.service'
1469
- import { create${t}Schema } from './dtos/create-${n}.dto'
1470
- import { update${t}Schema } from './dtos/update-${n}.dto'
1471
- import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
1472
-
1473
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
1474
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
1475
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
1476
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
1477
-
1478
- @Controller()
1479
- export class ${t}Controller {
1480
- @Autowired() private readonly ${r}Service!: ${t}Service
1481
-
1482
- @Get('/')
1483
- @ApiTags('${t}')
1484
- @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
1485
- async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
1486
- return ctx.paginate(
1487
- (parsed) => this.${r}Service.findPaginated(parsed),
1488
- ${t.toUpperCase()}_QUERY_CONFIG,
1489
- )
1490
- }
1491
-
1492
- @Get('/:id')
1493
- @ApiTags('${t}')
1494
- async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
1495
- const result = await this.${r}Service.findById(ctx.params.id)
1496
- if (!result) return ctx.notFound('${t} not found')
1497
- ctx.json(result)
1498
- }
1499
-
1500
- @Post('/', { body: create${t}Schema, name: 'Create${t}' })
1501
- @ApiTags('${t}')
1502
- async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
1503
- const result = await this.${r}Service.create(ctx.body)
1504
- ctx.created(result)
1505
- }
1506
-
1507
- @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
1508
- @ApiTags('${t}')
1509
- async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
1510
- const result = await this.${r}Service.update(ctx.params.id, ctx.body)
1511
- ctx.json(result)
1512
- }
1513
-
1514
- @Delete('/:id')
1515
- @ApiTags('${t}')
1516
- async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
1517
- await this.${r}Service.delete(ctx.params.id)
1518
- ctx.noContent()
1519
- }
1520
- }
1521
- `}function cn(e){let{pascal:t}=e;return`import type { QueryParamsConfig } from '@forinda/kickjs'
1522
-
1523
- export const ${t.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
1524
- filterable: ['name'],
1525
- sortable: ['name', 'createdAt'],
1526
- searchable: ['name'],
1527
- }
1528
- `}function ln(e){let{pascal:t}=e;return`import { z } from 'zod'
1529
-
1530
- /**
1531
- * Create ${t} DTO — Zod schema for validating POST request bodies.
1532
- * This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
1533
- * It also generates OpenAPI request body docs when SwaggerAdapter is used.
1534
- *
1535
- * Add more fields as needed. Supported Zod types:
1536
- * z.string(), z.number(), z.boolean(), z.enum([...]),
1537
- * z.array(), z.object(), .optional(), .default(), .transform()
1538
- */
1539
- export const create${t}Schema = z.object({
1540
- name: z.string().min(1, 'Name is required').max(200),
1541
- })
1542
-
1543
- export type Create${t}DTO = z.infer<typeof create${t}Schema>
1544
- `}function un(e){let{pascal:t}=e;return`import { z } from 'zod'
1545
-
1546
- export const update${t}Schema = z.object({
1547
- name: z.string().min(1).max(200).optional(),
1548
- })
1549
-
1550
- export type Update${t}DTO = z.infer<typeof update${t}Schema>
1551
- `}function dn(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
1552
- id: string
1553
- name: string
1554
- createdAt: string
1555
- updatedAt: string
1556
- }
1557
- `}function fn(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`create-${n}.use-case.ts`,content:`/**
1558
- * Create ${t} Use Case
1559
- *
1560
- * Application layer — orchestrates a single business operation.
1561
- * Use cases are thin: validate input (via DTO), call domain/repo, return response.
1562
- * Keep business rules in the domain service, not here.
1563
- */
1564
- import { Service, Inject } from '@forinda/kickjs'
1565
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1566
- import type { Create${t}DTO } from '../dtos/create-${n}.dto'
1567
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1568
-
1569
- @Service()
1570
- export class Create${t}UseCase {
1571
- constructor(
1572
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1573
- ) {}
1574
-
1575
- async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1576
- return this.repo.create(dto)
1577
- }
1578
- }
1579
- `},{file:`get-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1580
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1581
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1582
-
1583
- @Service()
1584
- export class Get${t}UseCase {
1585
- constructor(
1586
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1587
- ) {}
1588
-
1589
- async execute(id: string): Promise<${t}ResponseDTO | null> {
1590
- return this.repo.findById(id)
1591
- }
1592
- }
1593
- `},{file:`list-${r}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1594
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1595
- import type { ParsedQuery } from '@forinda/kickjs'
1596
-
1597
- @Service()
1598
- export class List${i}UseCase {
1599
- constructor(
1600
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1601
- ) {}
1602
-
1603
- async execute(parsed: ParsedQuery) {
1604
- return this.repo.findPaginated(parsed)
1605
- }
1606
- }
1607
- `},{file:`update-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1608
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1609
- import type { Update${t}DTO } from '../dtos/update-${n}.dto'
1610
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
1611
-
1612
- @Service()
1613
- export class Update${t}UseCase {
1614
- constructor(
1615
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1616
- ) {}
1617
-
1618
- async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1619
- return this.repo.update(id, dto)
1620
- }
1621
- }
1622
- `},{file:`delete-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
1623
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../../domain/repositories/${n}.repository'
1624
-
1625
- @Service()
1626
- export class Delete${t}UseCase {
1627
- constructor(
1628
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1629
- ) {}
1630
-
1631
- async execute(id: string): Promise<void> {
1632
- await this.repo.delete(id)
1633
- }
1634
- }
1635
- `}]}function pn(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
1636
- * ${t} Repository Interface
1637
- *
1638
- * Defines the contract for data access.
1639
- * The interface declares what operations are available;
1640
- * implementations (in-memory, Drizzle, Prisma) fulfill the contract.
1641
- *
1642
- * To swap implementations, change the factory in the module's register() method.
1643
- */
1644
- import { createToken } from '@forinda/kickjs'
1645
- import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
1646
- import type { Create${t}DTO } from '${r}/create-${n}.dto'
1647
- import type { Update${t}DTO } from '${r}/update-${n}.dto'
1648
- import type { ParsedQuery } from '@forinda/kickjs'
1649
-
1650
- export interface I${t}Repository {
1651
- findById(id: string): Promise<${t}ResponseDTO | null>
1652
- findAll(): Promise<${t}ResponseDTO[]>
1653
- findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
1654
- create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
1655
- update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
1656
- delete(id: string): Promise<void>
1657
- }
1658
-
1659
- /**
1660
- * Collision-safe DI token bound to \`I${t}Repository\`.
1661
- * \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
1662
- * \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
1663
- * interface — no manual generic, no \`any\` cast.
1664
- *
1665
- * The \`'${i}/'\` prefix matches the project scope so
1666
- * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
1667
- * adopters must NOT use the reserved \`'kick/'\` namespace.
1668
- */
1669
- export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
1670
- `}function U(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
1671
- * In-Memory ${t} Repository
1672
- *
1673
- * Implements the repository interface using a Map.
1674
- * Useful for prototyping and testing. Replace with a database implementation
1675
- * (Drizzle, Prisma, etc.) for production use.
1676
- *
1677
- * @Repository() registers this class in the DI container as a singleton.
1678
- */
1679
- import { randomUUID } from 'node:crypto'
1680
- import { Repository, HttpException } from '@forinda/kickjs'
1681
- import type { ParsedQuery } from '@forinda/kickjs'
1682
- import type { I${t}Repository } from '${r}/${n}.repository'
1683
- import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
1684
- import type { Create${t}DTO } from '${i}/create-${n}.dto'
1685
- import type { Update${t}DTO } from '${i}/update-${n}.dto'
1686
-
1687
- @Repository()
1688
- export class InMemory${t}Repository implements I${t}Repository {
1689
- private store = new Map<string, ${t}ResponseDTO>()
1690
-
1691
- async findById(id: string): Promise<${t}ResponseDTO | null> {
1692
- return this.store.get(id) ?? null
1693
- }
1694
-
1695
- async findAll(): Promise<${t}ResponseDTO[]> {
1696
- return Array.from(this.store.values())
1697
- }
1698
-
1699
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1700
- const all = Array.from(this.store.values())
1701
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
1702
- return { data, total: all.length }
1703
- }
1704
-
1705
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1706
- const now = new Date().toISOString()
1707
- const entity: ${t}ResponseDTO = {
1708
- id: randomUUID(),
1709
- name: dto.name,
1710
- createdAt: now,
1711
- updatedAt: now,
1712
- }
1713
- this.store.set(entity.id, entity)
1714
- return entity
1715
- }
1716
-
1717
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1718
- const existing = this.store.get(id)
1719
- if (!existing) throw HttpException.notFound('${t} not found')
1720
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
1721
- this.store.set(id, updated)
1722
- return updated
1723
- }
1724
-
1725
- async delete(id: string): Promise<void> {
1726
- if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
1727
- this.store.delete(id)
1728
- }
1729
- }
1730
- `}function mn(e){let{pascal:t,kebab:n,repoType:r=``,repoPrefix:i=`../../domain/repositories`,dtoPrefix:a=`../../application/dtos`}=e,o=r.charAt(0).toUpperCase()+r.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return`/**
1731
- * ${o} ${t} Repository
1732
- *
1733
- * Stub implementation for a custom '${r}' repository.
1734
- * Implements the repository interface using an in-memory Map as a placeholder.
1735
- *
1736
- * TODO: Replace the in-memory Map with your ${r} data-access logic.
1737
- * See I${t}Repository for the interface contract.
1738
- *
1739
- * @Repository() registers this class in the DI container as a singleton.
1740
- */
1741
- import { randomUUID } from 'node:crypto'
1742
- import { Repository, HttpException } from '@forinda/kickjs'
1743
- import type { ParsedQuery } from '@forinda/kickjs'
1744
- import type { I${t}Repository } from '${i}/${n}.repository'
1745
- import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
1746
- import type { Create${t}DTO } from '${a}/create-${n}.dto'
1747
- import type { Update${t}DTO } from '${a}/update-${n}.dto'
1748
-
1749
- @Repository()
1750
- export class ${o}${t}Repository implements I${t}Repository {
1751
- // TODO: Replace with your ${r} client/connection
1752
- private store = new Map<string, ${t}ResponseDTO>()
1753
-
1754
- async findById(id: string): Promise<${t}ResponseDTO | null> {
1755
- // TODO: Implement with ${r}
1756
- return this.store.get(id) ?? null
1757
- }
1758
-
1759
- async findAll(): Promise<${t}ResponseDTO[]> {
1760
- // TODO: Implement with ${r}
1761
- return Array.from(this.store.values())
1762
- }
1763
-
1764
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
1765
- // TODO: Implement with ${r}
1766
- const all = Array.from(this.store.values())
1767
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
1768
- return { data, total: all.length }
1769
- }
1770
-
1771
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
1772
- // TODO: Implement with ${r}
1773
- const now = new Date().toISOString()
1774
- const entity: ${t}ResponseDTO = {
1775
- id: randomUUID(),
1776
- name: dto.name,
1777
- createdAt: now,
1778
- updatedAt: now,
1779
- }
1780
- this.store.set(entity.id, entity)
1781
- return entity
1782
- }
1783
-
1784
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
1785
- // TODO: Implement with ${r}
1786
- const existing = this.store.get(id)
1787
- if (!existing) throw HttpException.notFound('${t} not found')
1788
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
1789
- this.store.set(id, updated)
1790
- return updated
1791
- }
1792
-
1793
- async delete(id: string): Promise<void> {
1794
- // TODO: Implement with ${r}
1795
- if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
1796
- this.store.delete(id)
1797
- }
1798
- }
1799
- `}function hn(e){let{pascal:t,kebab:n}=e;return`/**
1800
- * ${t} Domain Service
1801
- *
1802
- * Domain layer — contains business rules that don't belong to a single entity.
1803
- * Use this for cross-entity logic, validation rules, and domain invariants.
1804
- * Keep it free of HTTP/framework concerns.
1805
- */
1806
- import { Service, Inject, HttpException } from '@forinda/kickjs'
1807
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../repositories/${n}.repository'
1808
-
1809
- @Service()
1810
- export class ${t}DomainService {
1811
- constructor(
1812
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
1813
- ) {}
1814
-
1815
- async ensureExists(id: string): Promise<void> {
1816
- const entity = await this.repo.findById(id)
1817
- if (!entity) {
1818
- throw HttpException.notFound('${t} not found')
1819
- }
1820
- }
1821
- }
1822
- `}function gn(e){let{pascal:t,kebab:n}=e;return`/**
1823
- * ${t} Entity
1824
- *
1825
- * Domain layer — the core business object.
1826
- * Uses a private constructor with static factory methods (create, reconstitute)
1827
- * to enforce invariants. Properties are accessed via getters to maintain encapsulation.
1828
- *
1829
- * Patterns used:
1830
- * - Private constructor: prevents direct instantiation
1831
- * - create(): factory for new entities (generates ID, sets timestamps)
1832
- * - reconstitute(): factory for rebuilding from persistence (no side effects)
1833
- * - changeName(): mutation method that enforces business rules
1834
- */
1835
- import { ${t}Id } from '../value-objects/${n}-id.vo'
1836
-
1837
- interface ${t}Props {
1838
- id: ${t}Id
1839
- name: string
1840
- createdAt: Date
1841
- updatedAt: Date
1842
- }
1843
-
1844
- export class ${t} {
1845
- private constructor(private props: ${t}Props) {}
1846
-
1847
- static create(params: { name: string }): ${t} {
1848
- const now = new Date()
1849
- return new ${t}({
1850
- id: ${t}Id.create(),
1851
- name: params.name,
1852
- createdAt: now,
1853
- updatedAt: now,
1854
- })
1855
- }
1856
-
1857
- static reconstitute(props: ${t}Props): ${t} {
1858
- return new ${t}(props)
1859
- }
1860
-
1861
- get id(): ${t}Id {
1862
- return this.props.id
1863
- }
1864
- get name(): string {
1865
- return this.props.name
1866
- }
1867
- get createdAt(): Date {
1868
- return this.props.createdAt
1869
- }
1870
- get updatedAt(): Date {
1871
- return this.props.updatedAt
1872
- }
1873
-
1874
- changeName(name: string): void {
1875
- if (!name || name.trim().length === 0) {
1876
- throw new Error('Name cannot be empty')
1877
- }
1878
- this.props.name = name.trim()
1879
- this.props.updatedAt = new Date()
1880
- }
1881
-
1882
- toJSON() {
1883
- return {
1884
- id: this.props.id.toString(),
1885
- name: this.props.name,
1886
- createdAt: this.props.createdAt.toISOString(),
1887
- updatedAt: this.props.updatedAt.toISOString(),
1888
- }
1889
- }
1890
- }
1891
- `}function _n(e){let{pascal:t}=e;return`/**
1892
- * ${t} ID Value Object
1893
- *
1894
- * Domain layer — wraps a primitive ID with type safety and validation.
1895
- * Value objects are immutable and compared by value, not reference.
1896
- *
1897
- * ${t}Id.create() — generate a new UUID
1898
- * ${t}Id.from(id) — wrap an existing ID string (validates non-empty)
1899
- * id.equals(other) — compare two IDs by value
1900
- */
1901
- import { randomUUID } from 'node:crypto'
1902
-
1903
- export class ${t}Id {
1904
- private constructor(private readonly value: string) {}
1905
-
1906
- static create(): ${t}Id {
1907
- return new ${t}Id(randomUUID())
1908
- }
1909
-
1910
- static from(id: string): ${t}Id {
1911
- if (!id || id.trim().length === 0) {
1912
- throw new Error('${t}Id cannot be empty')
1913
- }
1914
- return new ${t}Id(id)
1915
- }
1916
-
1917
- toString(): string {
1918
- return this.value
1919
- }
1920
-
1921
- equals(other: ${t}Id): boolean {
1922
- return this.value === other.value
1923
- }
1924
- }
1925
- `}function vn(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
1926
- import { Container } from '@forinda/kickjs'
1927
-
1928
- describe('${t}Controller', () => {
1929
- beforeEach(() => {
1930
- Container.reset()
1931
- })
1932
-
1933
- it('should be defined', () => {
1934
- expect(true).toBe(true)
1935
- })
1936
-
1937
- describe('POST /${r}', () => {
1938
- it('should create a new ${n}', async () => {
1939
- // TODO: Set up test module, call create endpoint, assert 201
1940
- expect(true).toBe(true)
1941
- })
1942
- })
1943
-
1944
- describe('GET /${r}', () => {
1945
- it('should return paginated ${r}', async () => {
1946
- // TODO: Set up test module, call list endpoint, assert { data, meta }
1947
- expect(true).toBe(true)
1948
- })
1949
- })
1950
-
1951
- describe('GET /${r}/:id', () => {
1952
- it('should return a ${n} by id', async () => {
1953
- // TODO: Create a ${n}, then fetch by id, assert match
1954
- expect(true).toBe(true)
1955
- })
1956
-
1957
- it('should return 404 for non-existent ${n}', async () => {
1958
- // TODO: Fetch non-existent id, assert 404
1959
- expect(true).toBe(true)
1960
- })
1961
- })
1962
-
1963
- describe('PUT /${r}/:id', () => {
1964
- it('should update an existing ${n}', async () => {
1965
- // TODO: Create, update, assert changes
1966
- expect(true).toBe(true)
1967
- })
1968
- })
1969
-
1970
- describe('DELETE /${r}/:id', () => {
1971
- it('should delete a ${n}', async () => {
1972
- // TODO: Create, delete, assert gone
1973
- expect(true).toBe(true)
1974
- })
1975
- })
1976
- })
1977
- `}function yn(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../infrastructure/repositories/in-memory-${n}.repository`}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
1978
- import { InMemory${t}Repository } from '${i}'
1979
-
1980
- describe('InMemory${t}Repository', () => {
1981
- let repo: InMemory${t}Repository
1982
-
1983
- beforeEach(() => {
1984
- repo = new InMemory${t}Repository()
1985
- })
1986
-
1987
- it('should create and retrieve a ${n}', async () => {
1988
- const created = await repo.create({ name: 'Test ${t}' })
1989
- expect(created).toBeDefined()
1990
- expect(created.name).toBe('Test ${t}')
1991
- expect(created.id).toBeDefined()
1992
-
1993
- const found = await repo.findById(created.id)
1994
- expect(found).toEqual(created)
1995
- })
1996
-
1997
- it('should return null for non-existent id', async () => {
1998
- const found = await repo.findById('non-existent')
1999
- expect(found).toBeNull()
2000
- })
2001
-
2002
- it('should list all ${r}', async () => {
2003
- await repo.create({ name: '${t} 1' })
2004
- await repo.create({ name: '${t} 2' })
2005
-
2006
- const all = await repo.findAll()
2007
- expect(all).toHaveLength(2)
2008
- })
2009
-
2010
- it('should return paginated results', async () => {
2011
- await repo.create({ name: '${t} 1' })
2012
- await repo.create({ name: '${t} 2' })
2013
- await repo.create({ name: '${t} 3' })
2014
-
2015
- const result = await repo.findPaginated({
2016
- filters: [],
2017
- sort: [],
2018
- search: '',
2019
- pagination: { page: 1, limit: 2, offset: 0 },
2020
- })
2021
-
2022
- expect(result.data).toHaveLength(2)
2023
- expect(result.total).toBe(3)
2024
- })
2025
-
2026
- it('should update a ${n}', async () => {
2027
- const created = await repo.create({ name: 'Original' })
2028
- const updated = await repo.update(created.id, { name: 'Updated' })
2029
- expect(updated.name).toBe('Updated')
2030
- })
2031
-
2032
- it('should delete a ${n}', async () => {
2033
- const created = await repo.create({ name: 'To Delete' })
2034
- await repo.delete(created.id)
2035
- const found = await repo.findById(created.id)
2036
- expect(found).toBeNull()
2037
- })
2038
- })
2039
- `}function bn(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
2040
- import type { ParsedQuery } from '@forinda/kickjs'
2041
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
2042
- import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
2043
- import type { Create${t}DTO } from './dtos/create-${n}.dto'
2044
- import type { Update${t}DTO } from './dtos/update-${n}.dto'
2045
-
2046
- @Service()
2047
- export class ${t}Service {
2048
- constructor(
2049
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2050
- ) {}
2051
-
2052
- async findById(id: string): Promise<${t}ResponseDTO | null> {
2053
- return this.repo.findById(id)
2054
- }
2055
-
2056
- async findAll(): Promise<${t}ResponseDTO[]> {
2057
- return this.repo.findAll()
2058
- }
2059
-
2060
- async findPaginated(parsed: ParsedQuery) {
2061
- return this.repo.findPaginated(parsed)
2062
- }
2063
-
2064
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2065
- return this.repo.create(dto)
2066
- }
2067
-
2068
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2069
- return this.repo.update(id, dto)
2070
- }
2071
-
2072
- async delete(id: string): Promise<void> {
2073
- await this.repo.delete(id)
2074
- }
2075
- }
2076
- `}function xn(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
2077
-
2078
- export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
2079
- filterable: ['name'],
2080
- sortable: ['name', 'createdAt'],
2081
- searchable: ['name'],
2082
- }
2083
- `}function Sn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o={inmemory:`InMemory${t}Repository`,drizzle:`Drizzle${t}Repository`,prisma:`Prisma${t}Repository`},s={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},c=o[i]??o.inmemory,l=s[i]??s.inmemory,u=a??`define`,d=`/**
2084
- * ${t} Module — CQRS Pattern
2085
- *
2086
- * Separates read (queries) and write (commands) operations.
2087
- * Events are emitted after state changes and can be handled via
2088
- * WebSocket broadcasts, queue jobs, or ETL pipelines.
2089
- *
2090
- * Structure:
2091
- * commands/ — Write operations (create, update, delete)
2092
- * queries/ — Read operations (get, list)
2093
- * events/ — Domain events + handlers (WS broadcast, queue dispatch)
2094
- * dtos/ — Request/response schemas
2095
- */`,f=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
2096
- import { ${c} } from './${l}.repository'
2097
- import { ${t}Controller } from './${n}.controller'
2098
-
2099
- // Eagerly load decorated classes
2100
- import.meta.glob(
2101
- [
2102
- './commands/**/*.ts',
2103
- './queries/**/*.ts',
2104
- './events/**/*.ts',
2105
- '!./**/*.test.ts',
2106
- ],
2107
- { eager: true },
2108
- )`,p=` /**
2109
- * Declare HTTP routes for this CQRS module. Return value shape:
2110
- *
2111
- * - \`path\` — URL prefix for this route set.
2112
- * - \`controller\` — Controller class (also drives OpenAPI).
2113
- * - \`version\` — Optional. Overrides the app-wide API version.
2114
- *
2115
- * Return an array to mount multiple route sets:
2116
- *
2117
- * return [
2118
- * { path: '/${r}', version: 1, controller: ${t}V1Controller },
2119
- * { path: '/${r}', version: 2, controller: ${t}V2Controller },
2120
- * ]
2121
- */`;return u===`class`?`${d}
2122
- import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
2123
- ${f}
2124
-
2125
- export class ${t}Module implements AppModule {
2126
- register(container: Container): void {
2127
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
2128
- container.resolve(${c}),
2129
- )
2130
- }
2131
-
2132
- ${p.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
2133
- routes(): ModuleRoutes {
2134
- return {
2135
- path: '/${r}',
2136
- controller: ${t}Controller,
2137
- }
2138
- }
2139
- }
2140
- `:`${d}
2141
- import { defineModule } from '@forinda/kickjs'
2142
- ${f}
2143
-
2144
- export const ${t}Module = defineModule({
2145
- name: '${t}Module',
2146
- build: () => ({
2147
- register(container) {
2148
- container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
2149
- container.resolve(${c}),
2150
- )
2151
- },
2152
-
2153
- ${p}
2154
- routes() {
2155
- return {
2156
- path: '/${r}',
2157
- controller: ${t}Controller,
2158
- }
2159
- },
2160
- }),
2161
- })
2162
- `}function Cn(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
2163
- import { ApiTags } from '@forinda/kickjs-swagger'
2164
- import { Create${t}Command } from './commands/create-${n}.command'
2165
- import { Update${t}Command } from './commands/update-${n}.command'
2166
- import { Delete${t}Command } from './commands/delete-${n}.command'
2167
- import { Get${t}Query } from './queries/get-${n}.query'
2168
- import { List${i}Query } from './queries/list-${r}.query'
2169
- import { create${t}Schema } from './dtos/create-${n}.dto'
2170
- import { update${t}Schema } from './dtos/update-${n}.dto'
2171
- import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
2172
-
2173
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
2174
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
2175
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
2176
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
2177
-
2178
- @Controller()
2179
- export class ${t}Controller {
2180
- @Autowired() private readonly create${t}Command!: Create${t}Command
2181
- @Autowired() private readonly update${t}Command!: Update${t}Command
2182
- @Autowired() private readonly delete${t}Command!: Delete${t}Command
2183
- @Autowired() private readonly get${t}Query!: Get${t}Query
2184
- @Autowired() private readonly list${i}Query!: List${i}Query
2185
-
2186
- @Get('/')
2187
- @ApiTags('${t}')
2188
- @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
2189
- async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
2190
- return ctx.paginate(
2191
- (parsed) => this.list${i}Query.execute(parsed),
2192
- ${t.toUpperCase()}_QUERY_CONFIG,
2193
- )
2194
- }
2195
-
2196
- @Get('/:id')
2197
- @ApiTags('${t}')
2198
- async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
2199
- const result = await this.get${t}Query.execute(ctx.params.id)
2200
- if (!result) return ctx.notFound('${t} not found')
2201
- ctx.json(result)
2202
- }
2203
-
2204
- @Post('/', { body: create${t}Schema, name: 'Create${t}' })
2205
- @ApiTags('${t}')
2206
- async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
2207
- const result = await this.create${t}Command.execute(ctx.body)
2208
- ctx.created(result)
2209
- }
2210
-
2211
- @Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
2212
- @ApiTags('${t}')
2213
- async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
2214
- const result = await this.update${t}Command.execute(ctx.params.id, ctx.body)
2215
- ctx.json(result)
2216
- }
2217
-
2218
- @Delete('/:id')
2219
- @ApiTags('${t}')
2220
- async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
2221
- await this.delete${t}Command.execute(ctx.params.id)
2222
- ctx.noContent()
2223
- }
2224
- }
2225
- `}function wn(e){let{pascal:t,kebab:n}=e;return[{file:`create-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2226
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2227
- import type { Create${t}DTO } from '../dtos/create-${n}.dto'
2228
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2229
- import { ${t}Events } from '../events/${n}.events'
2230
-
2231
- @Service()
2232
- export class Create${t}Command {
2233
- constructor(
2234
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2235
- @Inject(${t}Events) private readonly events: ${t}Events,
2236
- ) {}
2237
-
2238
- async execute(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2239
- const result = await this.repo.create(dto)
2240
- this.events.emit('${n}.created', result)
2241
- return result
2242
- }
2243
- }
2244
- `},{file:`update-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2245
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2246
- import type { Update${t}DTO } from '../dtos/update-${n}.dto'
2247
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2248
- import { ${t}Events } from '../events/${n}.events'
2249
-
2250
- @Service()
2251
- export class Update${t}Command {
2252
- constructor(
2253
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2254
- @Inject(${t}Events) private readonly events: ${t}Events,
2255
- ) {}
2256
-
2257
- async execute(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2258
- const result = await this.repo.update(id, dto)
2259
- this.events.emit('${n}.updated', result)
2260
- return result
2261
- }
2262
- }
2263
- `},{file:`delete-${n}.command.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2264
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2265
- import { ${t}Events } from '../events/${n}.events'
2266
-
2267
- @Service()
2268
- export class Delete${t}Command {
2269
- constructor(
2270
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2271
- @Inject(${t}Events) private readonly events: ${t}Events,
2272
- ) {}
2273
-
2274
- async execute(id: string): Promise<void> {
2275
- await this.repo.delete(id)
2276
- this.events.emit('${n}.deleted', { id })
2277
- }
2278
- }
2279
- `}]}function Tn(e){let{pascal:t,kebab:n,plural:r=``,pluralPascal:i=``}=e;return[{file:`get-${n}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2280
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2281
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2282
-
2283
- @Service()
2284
- export class Get${t}Query {
2285
- constructor(
2286
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2287
- ) {}
2288
-
2289
- async execute(id: string): Promise<${t}ResponseDTO | null> {
2290
- return this.repo.findById(id)
2291
- }
2292
- }
2293
- `},{file:`list-${r}.query.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
2294
- import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from '../${n}.repository'
2295
- import type { ParsedQuery } from '@forinda/kickjs'
2296
-
2297
- @Service()
2298
- export class List${i}Query {
2299
- constructor(
2300
- @Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
2301
- ) {}
2302
-
2303
- async execute(parsed: ParsedQuery) {
2304
- return this.repo.findPaginated(parsed)
2305
- }
2306
- }
2307
- `}]}function En(e){let{pascal:t,kebab:n}=e;return[{file:`${n}.events.ts`,content:`import { Service } from '@forinda/kickjs'
2308
- import { EventEmitter } from 'node:events'
2309
- import type { ${t}ResponseDTO } from '../dtos/${n}-response.dto'
2310
-
2311
- /**
2312
- * ${t} domain event types.
2313
- *
2314
- * These events are emitted by commands after state changes.
2315
- * Subscribe to them in event handlers for side effects:
2316
- * - WebSocket broadcasts (real-time UI updates)
2317
- * - Queue jobs (async processing, ETL pipelines)
2318
- * - Audit logging
2319
- * - Cache invalidation
2320
- */
2321
- export interface ${t}EventMap {
2322
- '${n}.created': ${t}ResponseDTO
2323
- '${n}.updated': ${t}ResponseDTO
2324
- '${n}.deleted': { id: string }
2325
- }
2326
-
2327
- @Service()
2328
- export class ${t}Events {
2329
- private emitter = new EventEmitter()
2330
-
2331
- emit<K extends keyof ${t}EventMap>(event: K, data: ${t}EventMap[K]): void {
2332
- this.emitter.emit(event, data)
2333
- }
2334
-
2335
- on<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
2336
- this.emitter.on(event, handler)
2337
- }
2338
-
2339
- off<K extends keyof ${t}EventMap>(event: K, handler: (data: ${t}EventMap[K]) => void): void {
2340
- this.emitter.off(event, handler)
2341
- }
2342
- }
2343
- `},{file:`on-${n}-change.handler.ts`,content:`import { Service, Autowired } from '@forinda/kickjs'
2344
- import { ${t}Events } from './${n}.events'
2345
-
2346
- /**
2347
- * ${t} Change Event Handler
2348
- *
2349
- * Reacts to domain events emitted by commands.
2350
- * Wire up side effects here:
2351
- *
2352
- * 1. WebSocket broadcast — notify connected clients in real-time
2353
- * import { WsGateway } from '@forinda/kickjs-ws'
2354
- * this.ws.broadcast('${n}-channel', { event, data })
2355
- *
2356
- * 2. Queue dispatch — offload heavy processing to background workers
2357
- * import { QueueService } from '@forinda/kickjs-queue'
2358
- * this.queue.add('${n}-etl', { action: event, payload: data })
2359
- *
2360
- * 3. ETL pipeline — transform and load data to external systems
2361
- * await this.etlPipeline.process(data)
2362
- */
2363
- @Service()
2364
- export class On${t}ChangeHandler {
2365
- @Autowired() private events!: ${t}Events
2366
-
2367
- // Uncomment to inject WebSocket and Queue services:
2368
- // @Autowired() private ws!: WsGateway
2369
- // @Autowired() private queue!: QueueService
2370
-
2371
- onInit(): void {
2372
- this.events.on('${n}.created', (data) => {
2373
- console.log('[${t}] Created:', data.id)
2374
- // TODO: Broadcast via WebSocket
2375
- // this.ws.broadcast('${n}-channel', { event: '${n}.created', data })
2376
- // TODO: Dispatch to queue for async processing / ETL
2377
- // this.queue.add('${n}-etl', { action: 'create', payload: data })
2378
- })
2379
-
2380
- this.events.on('${n}.updated', (data) => {
2381
- console.log('[${t}] Updated:', data.id)
2382
- // TODO: Broadcast via WebSocket
2383
- // this.ws.broadcast('${n}-channel', { event: '${n}.updated', data })
2384
- })
2385
-
2386
- this.events.on('${n}.deleted', (data) => {
2387
- console.log('[${t}] Deleted:', data.id)
2388
- // TODO: Broadcast via WebSocket
2389
- // this.ws.broadcast('${n}-channel', { event: '${n}.deleted', data })
2390
- })
2391
- }
2392
- }
2393
- `}]}function Dn(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
2394
- * Drizzle ${t} Repository
2395
- *
2396
- * Implements the repository interface using Drizzle ORM.
2397
- * Uses buildFromColumns() with Column objects for type-safe query building.
2398
- *
2399
- * TODO: Update the schema import to match your Drizzle schema file.
2400
- * TODO: Replace DRIZZLE_DB injection token with your actual database token.
2401
- *
2402
- * @Repository() registers this class in the DI container as a singleton.
2403
- */
2404
- import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
2405
- import { Repository, HttpException, Inject } from '@forinda/kickjs'
2406
- import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
2407
- import type { ParsedQuery } from '@forinda/kickjs'
2408
- import type { I${t}Repository } from '${r}/${n}.repository'
2409
- import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
2410
- import type { Create${t}DTO } from '${i}/create-${n}.dto'
2411
- import type { Update${t}DTO } from '${i}/update-${n}.dto'
2412
- import { ${t.toUpperCase()}_QUERY_CONFIG } from '../../constants'
2413
-
2414
- // TODO: Import your Drizzle schema table — e.g.:
2415
- // import { ${n}s } from '@/db/schema'
2416
-
2417
- const queryAdapter = new DrizzleQueryAdapter({
2418
- eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
2419
- })
2420
-
2421
- @Repository()
2422
- export class Drizzle${t}Repository implements I${t}Repository {
2423
- constructor(@Inject(DRIZZLE_DB) private db: any) {}
2424
-
2425
- async findById(id: string): Promise<${t}ResponseDTO | null> {
2426
- // TODO: Implement with Drizzle
2427
- // const row = this.db.select().from(${n}s).where(eq(${n}s.id, id)).get()
2428
- // return row ?? null
2429
- throw new Error('Drizzle ${t} repository not yet implemented — update schema imports and queries')
2430
- }
2431
-
2432
- async findAll(): Promise<${t}ResponseDTO[]> {
2433
- // TODO: Implement with Drizzle
2434
- // return this.db.select().from(${n}s).all()
2435
- throw new Error('Drizzle ${t} repository not yet implemented')
2436
- }
2437
-
2438
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
2439
- // TODO: Use buildFromColumns() with your query config for type-safe filtering
2440
- // const query = queryAdapter.buildFromColumns(parsed, ${t.toUpperCase()}_QUERY_CONFIG)
2441
- //
2442
- // const data = this.db
2443
- // .select().from(${n}s).$dynamic()
2444
- // .where(query.where).orderBy(...query.orderBy)
2445
- // .limit(query.limit).offset(query.offset).all()
2446
- //
2447
- // const totalResult = this.db
2448
- // .select({ count: count() }).from(${n}s)
2449
- // .$dynamic().where(query.where).get()
2450
- //
2451
- // return { data, total: totalResult?.count ?? 0 }
2452
- throw new Error('Drizzle ${t} repository not yet implemented')
2453
- }
2454
-
2455
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2456
- // TODO: Implement with Drizzle
2457
- // return this.db.insert(${n}s).values(dto).returning().get()
2458
- throw new Error('Drizzle ${t} repository not yet implemented')
2459
- }
2460
-
2461
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2462
- // TODO: Implement with Drizzle
2463
- // const row = this.db.update(${n}s).set(dto).where(eq(${n}s.id, id)).returning().get()
2464
- // if (!row) throw HttpException.notFound('${t} not found')
2465
- // return row
2466
- throw new Error('Drizzle ${t} repository not yet implemented')
2467
- }
2468
-
2469
- async delete(id: string): Promise<void> {
2470
- // TODO: Implement with Drizzle
2471
- // this.db.delete(${n}s).where(eq(${n}s.id, id)).run()
2472
- throw new Error('Drizzle ${t} repository not yet implemented')
2473
- }
2474
- }
2475
- `}function On(e){let{pascal:t,kebab:n}=e;return`import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
2476
- // TODO: Import your schema table and reference actual columns for type safety
2477
- // import { ${n}s } from '@/db/schema'
2478
-
2479
- export const ${t.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
2480
- columns: {
2481
- // Replace with actual Drizzle Column references for type-safe filtering:
2482
- // name: ${n}s.name,
2483
- // status: ${n}s.status,
2484
- },
2485
- sortable: {
2486
- // name: ${n}s.name,
2487
- // createdAt: ${n}s.createdAt,
2488
- },
2489
- searchColumns: [
2490
- // ${n}s.name,
2491
- ],
2492
- }
2493
- `}function kn(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e,a=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return`/**
2494
- * Prisma ${t} Repository
2495
- *
2496
- * Implements the repository interface using Prisma Client.
2497
- * Requires a PrismaClient instance injected via the DI container.
2498
- *
2499
- * Ensure your Prisma schema has a '${t}' model defined.
2500
- *
2501
- * For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
2502
- * @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
2503
- *
2504
- * @Repository() registers this class in the DI container as a singleton.
2505
- */
2506
- import { Repository, HttpException, Inject } from '@forinda/kickjs'
2507
- import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
2508
- import type { ParsedQuery } from '@forinda/kickjs'
2509
- import type { I${t}Repository } from '${r}/${n}.repository'
2510
- import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
2511
- import type { Create${t}DTO } from '${i}/create-${n}.dto'
2512
- import type { Update${t}DTO } from '${i}/update-${n}.dto'
2513
-
2514
- @Repository()
2515
- export class Prisma${t}Repository implements I${t}Repository {
2516
- @Inject(PRISMA_CLIENT) private prisma!: { ${a}: PrismaModelDelegate }
2517
-
2518
- async findById(id: string): Promise<${t}ResponseDTO | null> {
2519
- return this.prisma.${a}.findUnique({ where: { id } }) as Promise<${t}ResponseDTO | null>
2520
- }
2521
-
2522
- async findAll(): Promise<${t}ResponseDTO[]> {
2523
- return this.prisma.${a}.findMany() as Promise<${t}ResponseDTO[]>
2524
- }
2525
-
2526
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
2527
- const [data, total] = await Promise.all([
2528
- this.prisma.${a}.findMany({
2529
- skip: parsed.pagination.offset,
2530
- take: parsed.pagination.limit,
2531
- }) as Promise<${t}ResponseDTO[]>,
2532
- this.prisma.${a}.count(),
2533
- ])
2534
- return { data, total }
2535
- }
2536
-
2537
- async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
2538
- return this.prisma.${a}.create({ data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
2539
- }
2540
-
2541
- async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
2542
- const existing = await this.prisma.${a}.findUnique({ where: { id } })
2543
- if (!existing) throw HttpException.notFound('${t} not found')
2544
- return this.prisma.${a}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${t}ResponseDTO>
2545
- }
2546
-
2547
- async delete(id: string): Promise<void> {
2548
- await this.prisma.${a}.deleteMany({ where: { id } })
2549
- }
2550
- }
2551
- `}async function An(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,an({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
2552
-
2553
- // \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
2554
- // \`kick typegen\` (auto-run on \`kick dev\`).
2555
-
2556
- @Controller()
2557
- export class ${t}Controller {
2558
- @Get('/')
2559
- async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
2560
- ctx.json({ message: '${t} list' })
2561
- }
2562
- }
2563
- `)}async function jn(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,rn({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,xn({pascal:t,kebab:n})),await u(`${n}.controller.ts`,sn({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`${n}.service.ts`,bn({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,ln({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,un({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,dn({pascal:t,kebab:n})),await u(`${n}.repository.ts`,pn({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let d={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},f={inmemory:()=>U({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>Dn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>kn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},p=d[a]??`${B(a)}-${n}`,m=f[a]??(()=>mn({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${p}.repository.ts`,m()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,U({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,vn({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,yn({pascal:t,kebab:n,plural:r,repoPrefix:`../${d.inmemory??`in-memory-${n}`}.repository`})))}async function Mn(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,prismaClientPath:s,tokenScope:c,style:l,write:u}=e;await u(`${n}.module.ts`,Sn({pascal:t,kebab:n,plural:r,repo:a,style:l})),await u(`${n}.constants.ts`,xn({pascal:t,kebab:n})),await u(`${n}.controller.ts`,Cn({pascal:t,kebab:n,plural:r,pluralPascal:i})),await u(`dtos/create-${n}.dto.ts`,ln({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,un({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,dn({pascal:t,kebab:n}));let d=wn({pascal:t,kebab:n});for(let e of d)await u(`commands/${e.file}`,e.content);let f=Tn({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await u(`queries/${e.file}`,e.content);let p=En({pascal:t,kebab:n});for(let e of p)await u(`events/${e.file}`,e.content);await u(`${n}.repository.ts`,pn({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:c}));let m={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},h={inmemory:()=>U({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),drizzle:()=>Dn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}),prisma:()=>kn({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`,prismaClientPath:s})},g=m[a]??`${B(a)}-${n}`,_=h[a]??(()=>mn({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`}));await u(`${g}.repository.ts`,_()),o||(a!==`inmemory`&&await u(`in-memory-${n}.repository.ts`,U({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await u(`__tests__/${n}.controller.test.ts`,vn({pascal:t,kebab:n,plural:r})),await u(`__tests__/${n}.repository.test.ts`,yn({pascal:t,kebab:n,plural:r,repoPrefix:`../${m.inmemory??`in-memory-${n}`}.repository`})))}async function Nn(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noEntity:o,noTests:s,prismaClientPath:c,tokenScope:l,style:u,write:d}=e;await d(`${n}.module.ts`,nn({pascal:t,kebab:n,plural:r,repo:a,style:u})),await d(`constants.ts`,a===`drizzle`?On({pascal:t,kebab:n}):cn({pascal:t,kebab:n})),await d(`presentation/${n}.controller.ts`,on({pascal:t,kebab:n,plural:r,pluralPascal:i})),await d(`application/dtos/create-${n}.dto.ts`,ln({pascal:t,kebab:n})),await d(`application/dtos/update-${n}.dto.ts`,un({pascal:t,kebab:n})),await d(`application/dtos/${n}-response.dto.ts`,dn({pascal:t,kebab:n}));let f=fn({pascal:t,kebab:n,plural:r,pluralPascal:i});for(let e of f)await d(`application/use-cases/${e.file}`,e.content);await d(`domain/repositories/${n}.repository.ts`,pn({pascal:t,kebab:n,tokenScope:l})),await d(`domain/services/${n}-domain.service.ts`,hn({pascal:t,kebab:n}));let p={inmemory:`in-memory-${n}`,drizzle:`drizzle-${n}`,prisma:`prisma-${n}`},m={inmemory:()=>U({pascal:t,kebab:n}),drizzle:()=>Dn({pascal:t,kebab:n}),prisma:()=>kn({pascal:t,kebab:n,prismaClientPath:c})},h=p[a]??`${B(a)}-${n}`,g=m[a]??(()=>mn({pascal:t,kebab:n,repoType:a}));await d(`infrastructure/repositories/${h}.repository.ts`,g()),o||(await d(`domain/entities/${n}.entity.ts`,gn({pascal:t,kebab:n})),await d(`domain/value-objects/${n}-id.vo.ts`,_n({pascal:t,kebab:n}))),s||(a!==`inmemory`&&await d(`infrastructure/repositories/in-memory-${n}.repository.ts`,U({pascal:t,kebab:n})),await d(`__tests__/${n}.controller.test.ts`,vn({pascal:t,kebab:n,plural:r})),await d(`__tests__/${n}.repository.test.ts`,yn({pascal:t,kebab:n,plural:r})))}function Pn(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Fn(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`ddd`;e.minimal&&(l=`minimal`);let u=B(t),d=R(t),f=c?V(u):u,p=c?It(d):d,m=S(n,f),h=[],g=o??!1,_={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,style:e.style??`define`,write:async(e,t)=>{let n=S(m,e);if(s){h.push(n);return}if(!g&&await Be(n)&&!await F({message:`File exists: ${A.dim(e)}. Overwrite?`,initialValue:!1})){I.warn(`Skipped: ${e}`);return}await M(n,t),h.push(n)},files:h};switch(l){case`minimal`:await An(_);break;case`rest`:await jn(_);break;case`cqrs`:await Mn(_);break;default:await Nn(_);break}return s||await In(n,d,f,u,_.style),h}async function In(e,t,n,r,i=`define`){let a=S(e,`index.ts`),o=await Be(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await M(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
2564
- import { ${t}Module } from '${s}'
2565
-
2566
- export const modules: AppModuleEntry[] = [${c}]
2567
- `:`import { defineModules } from '@forinda/kickjs'
2568
- import { ${t}Module } from '${s}'
2569
-
2570
- export const modules = defineModules().mount(${c})
2571
- `);return}let l=await D(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=H(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${H(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
2572
- `,e);l=l.slice(0,t+1)+u+`
2573
- `+l.slice(t+1)}else l=u+`
2574
- `+l}let f=Rn(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${H(t)}Module\\b`).test(e)||(l=Ln(l,c))}else l=Ln(l,c);await O(a,l,`utf-8`)}function Ln(e,t){let n=Rn(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function Rn(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=Vn(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=zn(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function zn(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Hn(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Hn(e,t);if(n===-1)break;i=n+1}return i}function Bn(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
2575
- `;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&!(e[t]===`*`&&e[t+1]===`/`);)t++;return t+2}return t}function Vn(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Bn(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Hn(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Bn(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}async function Un(e){let{name:t,outDir:n}=e,r=B(t),i=R(t),a=[],o=S(n,`${r}.adapter.ts`);return await M(o,`import {
2576
- defineAdapter,
2577
- type AdapterContext,
2578
- type AdapterMiddleware,
2579
- type ContributorRegistrations,
2580
- type Constructor,
2581
- } from '@forinda/kickjs'
2582
-
2583
- /**
2584
- * Configuration for the ${i} adapter.
2585
- *
2586
- * Adapters typically take a small config object so callers can tune
2587
- * behaviour at bootstrap time. Keep the shape narrow — anything
2588
- * derived from the environment should be read inside the build
2589
- * function via getEnv(), not forced onto the caller.
2590
- */
2591
- export interface ${i}AdapterConfig {
2592
- // Add your adapter configuration here, e.g.:
2593
- // enabled?: boolean
2594
- // apiKey?: string
2595
- }
2596
-
2597
- /**
2598
- * ${i} adapter — built via \`defineAdapter()\` so callers get the
2599
- * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
2600
- *
2601
- * Hooks into the Application lifecycle to add middleware, routes,
2602
- * Context Contributors, or external service connections.
2603
- *
2604
- * Every lifecycle hook below is OPTIONAL. The scaffold emits all of
2605
- * them so adopters can browse what's available and delete what they
2606
- * don't need — \`build()\` returning \`{}\` is also valid for an adapter
2607
- * that only contributes config defaults.
2608
- *
2609
- * @example
2610
- * \`\`\`ts
2611
- * import { bootstrap } from '@forinda/kickjs'
2612
- * import { ${i}Adapter } from './adapters/${r}.adapter'
2613
- *
2614
- * bootstrap({
2615
- * modules,
2616
- * adapters: [${i}Adapter({ /* config overrides *\\/ })],
2617
- * })
2618
- * \`\`\`
2619
- */
2620
- export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
2621
- name: '${i}Adapter',
2622
- defaults: {
2623
- // Default config values go here. The adopter's overrides shallow-merge
2624
- // on top of these before \`build()\` runs.
2625
- },
2626
- build: (_config, { name: _name }) => {
2627
- // Closures inside \`build()\` are how each adapter instance owns its
2628
- // own state (database client, Map, timer handle, …). The same
2629
- // \`_config\` is visible to every hook below.
2630
-
2631
- return {
2632
- /**
2633
- * Express middleware entries the Application mounts at named phases.
2634
- *
2635
- * \`phase\` controls where each handler sits in the pipeline:
2636
- * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
2637
- *
2638
- * \`path\` (optional) scopes the entry to a path prefix.
2639
- *
2640
- * Delete this hook entirely if you don't add middleware.
2641
- */
2642
- middleware(): AdapterMiddleware[] {
2643
- return [
2644
- // Example: add a custom header to all responses
2645
- // {
2646
- // phase: 'beforeGlobal',
2647
- // handler: (_req, res, next) => {
2648
- // res.setHeader('X-${i}', 'true')
2649
- // next()
2650
- // },
2651
- // },
2652
- // Example: scope a rate limiter to one path prefix
2653
- // {
2654
- // phase: 'beforeRoutes',
2655
- // path: '/api/v1/auth',
2656
- // handler: rateLimit({ max: 10 }),
2657
- // },
2658
- ]
2659
- },
2660
-
2661
- /**
2662
- * Runs BEFORE global middleware. Mount routes that should bypass the
2663
- * middleware stack — health checks, docs UI, static assets, OAuth
2664
- * callbacks. Anything you want reachable even if a global middleware
2665
- * later in the chain rejects requests.
2666
- *
2667
- * Delete this hook if you have no early routes.
2668
- */
2669
- beforeMount(_ctx: AdapterContext): void {
2670
- // Example:
2671
- // _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
2672
- },
2673
-
2674
- /**
2675
- * Fires once per controller class as the router mounts. Use this to
2676
- * collect route metadata for OpenAPI specs, dependency graphs, route
2677
- * inventories, devtools dashboards.
2678
- *
2679
- * Delete this hook unless your adapter introspects the route registry.
2680
- */
2681
- onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
2682
- // Example (Swagger-style): collect routes for the spec.
2683
- // openApiSpec.addController(_controllerClass, _mountPath)
2684
- },
2685
-
2686
- /**
2687
- * Runs AFTER modules + routes are wired, BEFORE the server starts.
2688
- * Right place for late-stage DI registrations or final config validation.
2689
- *
2690
- * Delete this hook if there's nothing to wire post-modules.
2691
- */
2692
- beforeStart(_ctx: AdapterContext): void {
2693
- // Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
2694
- },
2695
-
2696
- /**
2697
- * Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
2698
- * available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
2699
- * gRPC, GraphQL subscriptions), warm caches, log a banner.
2700
- *
2701
- * Delete this hook if you don't need the running server reference.
2702
- */
2703
- afterStart(_ctx: AdapterContext): void {
2704
- // Example: const io = new Server(_ctx.server)
2705
- },
2706
-
2707
- /**
2708
- * Returns Context Contributors to merge into every route's pipeline
2709
- * at the \`'adapter'\` precedence level. Per-route handlers can
2710
- * override the value at the method / class / module level.
2711
- *
2712
- * Delete this hook unless your adapter ships typed per-request values
2713
- * (auth user, tenant, locale, feature flags, geo, etc).
2714
- */
2715
- contributors(): ContributorRegistrations {
2716
- return [
2717
- // Example:
2718
- // import { defineHttpContextDecorator } from '@forinda/kickjs'
2719
- // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
2720
- // const Load${i} = defineHttpContextDecorator({
2721
- // key: '${r}',
2722
- // resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
2723
- // })
2724
- // return [Load${i}.registration]
2725
- ]
2726
- },
2727
-
2728
- /**
2729
- * Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
2730
- * resources the adapter owns: close connections, flush buffers,
2731
- * cancel timers. The framework runs every adapter's \`shutdown\`
2732
- * concurrently via \`Promise.allSettled\` — one failure won't block
2733
- * sibling adapters.
2734
- *
2735
- * Delete this hook if your adapter holds no resources.
2736
- */
2737
- async shutdown(): Promise<void> {
2738
- // Example: await this.pool.end()
2739
- // Example: clearInterval(this.heartbeatTimer)
2740
- },
2741
- }
2742
- },
2743
- })
2744
- `),a.push(o),a}async function Wn(e){let{name:t,outDir:n}=e,r=B(t),i=R(t),a=[],o=S(n,`${r}.plugin.ts`);return await M(o,`import {
2745
- definePlugin,
2746
- type AppAdapter,
2747
- type AppModuleEntry,
2748
- type Container,
2749
- type ContributorRegistrations,
2750
- } from '@forinda/kickjs'
2751
-
2752
- /**
2753
- * Configuration for the ${i} plugin.
2754
- *
2755
- * Plugins typically take a small config object so callers can tune
2756
- * behaviour at bootstrap time. Keep the shape narrow — anything
2757
- * derived from the environment should be read inside the build
2758
- * function via getEnv(), not forced onto the caller.
2759
- */
2760
- export interface ${i}PluginConfig {
2761
- // Add your plugin config here, e.g.:
2762
- // enabled?: boolean
2763
- // apiKey?: string
2764
- }
2765
-
2766
- /**
2767
- * ${i} plugin — built via \`definePlugin()\` so callers get the
2768
- * factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
2769
- *
2770
- * A plugin bundles DI bindings, modules, adapters, and middleware
2771
- * into one object that can be added to \`bootstrap({ plugins })\`.
2772
- *
2773
- * Lifecycle order (each hook is optional — delete the ones you don't
2774
- * need and keep only the surface your plugin actually uses):
2775
- *
2776
- * 1. \`register(container)\` — runs before user modules load. Use
2777
- * it to bind services that modules depend on.
2778
- * 2. \`modules()\` — plugin modules load before user modules.
2779
- * 3. \`adapters()\` — plugin adapters mount before user adapters.
2780
- * 4. \`middleware()\` — plugin middleware runs before user middleware.
2781
- * 5. \`contributors()\` — Context Contributors merged into every route.
2782
- * 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
2783
- * 7. \`shutdown()\` — runs on graceful shutdown.
2784
- *
2785
- * @example
2786
- * \`\`\`ts
2787
- * import { bootstrap } from '@forinda/kickjs'
2788
- * import { ${i}Plugin } from './plugins/${r}.plugin'
2789
- *
2790
- * export const app = await bootstrap({
2791
- * modules,
2792
- * plugins: [${i}Plugin({ /* config overrides *\\/ })],
2793
- * })
2794
- * \`\`\`
2795
- */
2796
- export const ${i}Plugin = definePlugin<${i}PluginConfig>({
2797
- name: '${i}Plugin',
2798
- defaults: {
2799
- // Default config values go here
2800
- },
2801
- build: (_config, { name: _name }) => ({
2802
- /**
2803
- * Register DI bindings before modules load.
2804
- * Use \`container.registerInstance(TOKEN, value)\` for singletons
2805
- * and \`container.registerFactory(TOKEN, () => ...)\` for lazy
2806
- * constructions.
2807
- */
2808
- register(_container: Container): void {
2809
- // Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
2810
- },
2811
-
2812
- /**
2813
- * Return modules this plugin contributes to the app. These load
2814
- * before user modules, so plugin controllers and services are
2815
- * available for user code to \`@Autowired\`.
2816
- *
2817
- * Accepts both \`defineModule\`-style instances (call the factory:
2818
- * \`ExampleModule()\`) and legacy \`class … implements AppModule\`
2819
- * constructors.
2820
- */
2821
- modules(): AppModuleEntry[] {
2822
- return [
2823
- // ExampleModule(),
2824
- ]
2825
- },
2826
-
2827
- /**
2828
- * Return adapter instances to be added to the application.
2829
- * Plugin adapters mount before user adapters.
2830
- */
2831
- adapters(): AppAdapter[] {
2832
- return [
2833
- // MyAdapter({ ... }),
2834
- ]
2835
- },
2836
-
2837
- /**
2838
- * Return Express middleware entries to be added to the global
2839
- * pipeline. Plugin middleware runs before user-defined middleware.
2840
- */
2841
- middleware(): unknown[] {
2842
- return [
2843
- // helmet(),
2844
- // myCustomMiddleware(_config),
2845
- ]
2846
- },
2847
-
2848
- /**
2849
- * Return Context Contributors to merge into every route's pipeline.
2850
- * Plugins contribute at the same \`'adapter'\` precedence level as
2851
- * adapters — overrideable per-route at the method / class / module
2852
- * level. See https://forinda.github.io/kick-js/guide/context-decorators
2853
- *
2854
- * Delete this hook if your plugin doesn't ship typed per-request values.
2855
- */
2856
- contributors(): ContributorRegistrations {
2857
- return [
2858
- // Example:
2859
- // import { defineHttpContextDecorator } from '@forinda/kickjs'
2860
- // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
2861
- // const Load${i} = defineHttpContextDecorator({
2862
- // key: '${r}',
2863
- // resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
2864
- // })
2865
- // return [Load${i}.registration]
2866
- ]
2867
- },
2868
-
2869
- /**
2870
- * Called after the application has fully bootstrapped. Use this
2871
- * for post-startup work like logging, health checks, or warming
2872
- * a cache. Runs once per process.
2873
- */
2874
- async onReady(_container: Container): Promise<void> {
2875
- // const log = _container.resolve(Logger)
2876
- // log.info('${i} plugin ready')
2877
- },
2878
-
2879
- /**
2880
- * Called during graceful shutdown. Clean up any long-lived
2881
- * resources this plugin owns (connections, timers, subscriptions).
2882
- */
2883
- async shutdown(): Promise<void> {
2884
- // Example: await this.connection?.close()
2885
- },
2886
- }),
2887
- })
2888
- `),a.push(o),a}const Gn={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},Kn={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},qn={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function W(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,pattern:o=`ddd`,shouldPluralize:s=!0}=e;if(n)return w(n);if(r){let e=o===`ddd`?Gn:o===`cqrs`?qn:Kn,n=B(r),a=s?V(n):n,c=e[t]??``,l=S(i,a);return w(c?S(l,c):l)}return w(a)}async function Jn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=z(t),c=[],l=S(a,`${o}.middleware.ts`);return await M(l,`import type { Request, Response, NextFunction } from 'express'
2889
-
2890
- export interface ${R(t)}Options {
2891
- // Add configuration options here
2892
- }
2893
-
2894
- /**
2895
- * ${R(t)} middleware.
2896
- *
2897
- * Usage in bootstrap:
2898
- * middleware: [${s}()]
2899
- *
2900
- * Usage with adapter:
2901
- * middleware() { return [{ handler: ${s}(), phase: 'afterGlobal' }] }
2902
- *
2903
- * Usage with @Middleware decorator:
2904
- * @Middleware(${s}())
2905
- */
2906
- export function ${s}(options: ${R(t)}Options = {}) {
2907
- return (req: Request, res: Response, next: NextFunction) => {
2908
- // Implement your middleware logic here
2909
- next()
2910
- }
2911
- }
2912
- `),c.push(l),c}async function Yn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=z(t),c=R(t),l=[],u=S(a,`${o}.guard.ts`);return await M(u,`import { Container, HttpException } from '@forinda/kickjs'
2913
- import type { RequestContext } from '@forinda/kickjs'
2914
-
2915
- /**
2916
- * ${c} guard.
2917
- *
2918
- * Guards protect routes by checking conditions before the handler runs.
2919
- * Return early with an error response to block access.
2920
- *
2921
- * Usage:
2922
- * @Middleware(${s}Guard)
2923
- * @Get('/protected')
2924
- * async handler(ctx: RequestContext) { ... }
2925
- */
2926
- export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<void> {
2927
- // Example: check for an authorization header
2928
- const header = ctx.headers.authorization
2929
- if (!header?.startsWith('Bearer ')) {
2930
- ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
2931
- return
2932
- }
2933
-
2934
- const token = header.slice(7)
2935
-
2936
- try {
2937
- // Verify the token using a service from the DI container
2938
- // const container = Container.getInstance()
2939
- // const authService = container.resolve(AuthService)
2940
- // const payload = authService.verifyToken(token)
2941
- // ctx.set('auth', payload)
2942
-
2943
- next()
2944
- } catch {
2945
- ctx.res.status(401).json({ message: 'Invalid or expired token' })
2946
- }
2947
- }
2948
- `),l.push(u),l}async function Xn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=[],l=S(a,`${o}.service.ts`);return await M(l,`import { Service } from '@forinda/kickjs'
2949
-
2950
- @Service()
2951
- export class ${s}Service {
2952
- // Inject dependencies via constructor
2953
- // constructor(
2954
- // @Inject(MY_REPO) private readonly repo: IMyRepository,
2955
- // ) {}
2956
- }
2957
- `),c.push(l),c}async function Zn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=[],l=S(a,`${o}.controller.ts`);return await M(l,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
2958
-
2959
- // \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
2960
- // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
2961
- // will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
2962
- // See https://forinda.github.io/kick-js/guide/typegen for details.
2963
-
2964
- @Controller()
2965
- export class ${s}Controller {
2966
- // @Autowired() private readonly myService!: MyService
2967
-
2968
- @Get('/')
2969
- async list(ctx: Ctx<KickRoutes.${s}Controller['list']>) {
2970
- ctx.json({ message: '${s} list' })
2971
- }
2972
-
2973
- @Post('/')
2974
- async create(ctx: Ctx<KickRoutes.${s}Controller['create']>) {
2975
- ctx.created({ message: '${s} created', data: ctx.body })
2976
- }
2977
- }
2978
- `),c.push(l),c}async function Qn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=W({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=z(t),l=[],u=S(a,`${o}.dto.ts`);return await M(u,`import { z } from 'zod'
2979
-
2980
- export const ${c}Schema = z.object({
2981
- // Define your schema fields here
2982
- name: z.string().min(1).max(200),
2983
- })
2984
-
2985
- export type ${s}DTO = z.infer<typeof ${c}Schema>
2986
- `),l.push(u),l}async function $n(e){let t=S(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return g(t)&&!e.force&&!await F({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
2987
- Skipped — existing kick.config.ts preserved.`),[]):(await M(t,`import { defineConfig } from '@forinda/kickjs-cli'
2988
-
2989
- export default defineConfig({
2990
- modules: {
2991
- dir: '${n}',
2992
- repo: '${r}',
2993
- pluralize: true,
2994
- },
2995
-
2996
- typegen: {
2997
- schemaValidator: 'zod',
2998
- },
2999
-
3000
- commands: [
3001
- {
3002
- name: 'test',
3003
- description: 'Run tests with Vitest',
3004
- steps: 'npx vitest run',
3005
- },
3006
- {
3007
- name: 'format',
3008
- description: 'Format code with Prettier',
3009
- steps: 'npx prettier --write src/',
3010
- },
3011
- {
3012
- name: 'format:check',
3013
- description: 'Check formatting without writing',
3014
- steps: 'npx prettier --check src/',
3015
- },
3016
- {
3017
- name: 'ci:check',
3018
- description: 'Run typecheck + format check',
3019
- steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
3020
- aliases: ['verify'],
3021
- },
3022
- ],
3023
- })
3024
- `),[t])}const er=new Set([`rest`,`ddd`,`cqrs`,`minimal`]);function tr(e,t){if(t)return t;try{let t=JSON.parse(v(S(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function nr(e,t){if(t)return t;try{let t=JSON.parse(v(S(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function rr(e,t){if(t)return t;try{let t=(await r(e))?.pattern;if(t&&er.has(t))return t}catch{}return`ddd`}async function ir(e){let t=e.only??`all`,n=tr(e.outDir,e.name),r=nr(e.outDir,e.pm),i=await rr(e.outDir,e.template),a=t===`agents`||t===`both`||t===`all`,o=t===`claude`||t===`both`||t===`all`,s=t===`skills`||t===`all`,c=[];a&&c.push({file:S(e.outDir,`AGENTS.md`),render:()=>ct(n,i,r)}),o&&c.push({file:S(e.outDir,`CLAUDE.md`),render:()=>st(n,i,r)}),s&&c.push({file:S(e.outDir,`kickjs-skills.md`),render:()=>lt(n,i,r)});let l=[];for(let{file:t,render:n}of c){if(g(t)&&!e.force&&!await F({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await M(t,n()),l.push(t)}return l}function ar(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function G(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=ar(e,r);return i===-1?null:e.slice(r+1,i)}function K(e,t,n){let r=` `.repeat(n);return e.split(`
3025
- `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`);return r+e.replace(n,``)}).join(`
3026
- `)}function or(e){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,t)=>{let n=t.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`Container`&&e!==`type Container`&&e!==`type AppModule`&&e!==`AppModule`&&e!==`type ModuleRoutes`&&e!==`ModuleRoutes`);return n.includes(`defineModule`)||n.push(`defineModule`),`import { ${n.join(`, `)} } from '@forinda/kickjs'`})}function sr(e,t){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,n)=>{let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`defineModule`);return t.container&&!r.includes(`Container`)&&r.push(`Container`),t.appModule&&!r.some(e=>e===`AppModule`||e===`type AppModule`)&&r.push(`type AppModule`),t.moduleRoutes&&!r.some(e=>e===`ModuleRoutes`||e===`type ModuleRoutes`)&&r.push(`type ModuleRoutes`),t.contributorRegistrations&&!r.some(e=>e===`ContributorRegistrations`||e===`type ContributorRegistrations`)&&r.push(`type ContributorRegistrations`),`import { ${r.join(`, `)} } from '@forinda/kickjs'`})}function cr(e){if(/\bdefineModule\s*\(/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+class\s+(\w+Module)\s+implements\s+AppModule\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no class form detected`};if(t.length>1)return{migrated:null,reason:`multiple module classes in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=ar(e,i);if(a===-1)return{migrated:null,reason:`unbalanced class braces`};let o=e.slice(i+1,a),s=e.slice(0,n.index),c=e.slice(a+1),l=G(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=G(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=G(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=or(s),p=``;return l&&(p+=` register(container) {${K(l,4,6)} },\n\n`),u&&(p+=` contributors() {${K(u,4,6)} },\n\n`),p+=` routes() {${K(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
3027
- name: '${r}',
3028
- build: () => ({
3029
- ${p}
3030
- }),
3031
- })`}${c}`}}function lr(e){if(/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+const\s+(\w+Module)\s*=\s*defineModule\s*\(\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no defineModule form detected`};if(t.length>1)return{migrated:null,reason:`multiple defineModule blocks in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=ar(e,i);if(a===-1)return{migrated:null,reason:`unbalanced defineModule braces`};let o=e.indexOf(`)`,a);if(o===-1)return{migrated:null,reason:`unbalanced defineModule call parens`};let s=e.slice(i+1,a),c=e.slice(0,n.index),l=o+1;for(;l<e.length&&(e[l]===`
3032
- `||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=ar(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=G(m,/register\s*\(([^)]*)\)\s*\{/),g=G(m,/contributors\s*\(\s*\)\s*\{/),_=G(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=sr(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${K(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${K(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${K(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
3033
- ${y}
3034
- }
3035
- `}${u}`}}function ur(e,t){return t===`class`?lr(e):cr(e)}function dr(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function fr(e){let t=[];return await n(w(e),0),t;async function n(e,r){let i;try{i=await he(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=S(e,a),o;try{o=await _e(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function pr(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await he(e)}catch{return}await me(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=S(e,a),o=S(t,a),s;try{s=await _e(i)}catch{continue}s.isDirectory()?await r(i,o):(await pe(i,o),n++)}}}function mr(e){return S(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function hr(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await fr(e),s=await D(S(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=mr(r),await pr(e,c));let l=[];for(let e of o){let t=ur(await D(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await O(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=S(e,`index.ts`),d=null;try{d=await D(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=dr(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await O(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function gr(e,t){let n=await fr(e),r=[],i=t===`define`?/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/:/export\s+const\s+\w+Module\s*=\s*defineModule\s*\(/;for(let e of n){let t=await D(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function _r(e={}){let t=e.strategy??`jwt`,n=e.outDir??`src/modules/auth`,r=S(n,`dto`),i=[],a=S(n,`auth.module.ts`);await M(a,`import { Module } from '@forinda/kickjs'
3036
- import { AuthController } from './auth.controller'
3037
- import { AuthService } from './auth.service'
3038
-
3039
- @Module({
3040
- controllers: [AuthController],
3041
- services: [AuthService],
3042
- })
3043
- export class AuthModule {}
3044
- `),i.push(a);let o=S(n,`auth.controller.ts`);await M(o,t===`jwt`?vr():br()),i.push(o);let s=S(n,`auth.service.ts`);await M(s,t===`jwt`?yr():xr()),i.push(s);let c=S(r,`register.dto.ts`);await M(c,`import { z } from 'zod'
3045
-
3046
- export const RegisterDto = z.object({
3047
- email: z.string().email(),
3048
- password: z.string().min(8),
3049
- name: z.string().min(1).optional(),
3050
- })
3051
-
3052
- export type RegisterInput = z.infer<typeof RegisterDto>
3053
- `),i.push(c);let l=S(r,`login.dto.ts`);await M(l,`import { z } from 'zod'
3054
-
3055
- export const LoginDto = z.object({
3056
- email: z.string().email(),
3057
- password: z.string().min(1),
3058
- })
3059
-
3060
- export type LoginInput = z.infer<typeof LoginDto>
3061
- `),i.push(l);let u=S(n,`auth.test.ts`);if(await M(u,`import { describe, it, expect } from 'vitest'
3062
-
3063
- describe('Auth Module', () => {
3064
- it.todo('POST /register — creates a new user')
3065
- it.todo('POST /login — returns token for valid credentials')
3066
- it.todo('POST /login — rejects invalid credentials')
3067
- it.todo('POST /logout — invalidates session/token')
3068
- it.todo('GET /me — returns authenticated user')
3069
- })
3070
- `),i.push(u),e.roleGuards!==!1){let e=S(n,`auth.guard.ts`);await M(e,`import { Roles } from '@forinda/kickjs-auth'
3071
-
3072
- /**
3073
- * Role-based access guard.
3074
- * Usage: @Roles('admin') on a controller method.
3075
- *
3076
- * The AuthAdapter extracts the user's roles from the JWT/session
3077
- * and the framework checks them automatically.
3078
- */
3079
- export const AdminOnly = Roles('admin')
3080
- export const ManagerOnly = Roles('manager')
3081
- `),i.push(e)}return i}function vr(){return`import { Controller, Post, Get } from '@forinda/kickjs'
3082
- import { Authenticated, Public } from '@forinda/kickjs-auth'
3083
- import type { RequestContext } from '@forinda/kickjs'
3084
- import { Autowired } from '@forinda/kickjs'
3085
- import { AuthService } from './auth.service'
3086
-
3087
- @Controller()
3088
- @Authenticated()
3089
- export class AuthController {
3090
- @Autowired() private authService!: AuthService
3091
-
3092
- @Post('/register')
3093
- @Public()
3094
- async register(ctx: RequestContext) {
3095
- const result = await this.authService.register(ctx.body)
3096
- return ctx.created(result)
3097
- }
3098
-
3099
- @Post('/login')
3100
- @Public()
3101
- async login(ctx: RequestContext) {
3102
- const result = await this.authService.login(ctx.body)
3103
- if (!result) return ctx.badRequest('Invalid credentials')
3104
- return ctx.json(result)
3105
- }
3106
-
3107
- @Post('/logout')
3108
- async logout(ctx: RequestContext) {
3109
- return ctx.json({ message: 'Logged out' })
3110
- }
3111
-
3112
- @Get('/me')
3113
- async me(ctx: RequestContext) {
3114
- return ctx.json({ user: ctx.user })
3115
- }
3116
- }
3117
- `}function yr(){return`import { Service, Autowired } from '@forinda/kickjs'
3118
- import { PasswordService } from '@forinda/kickjs-auth'
3119
- import type { RegisterInput } from './dto/register.dto'
3120
- import type { LoginInput } from './dto/login.dto'
3121
-
3122
- // TODO: Replace with your User repository
3123
- const users = new Map<string, { id: string; email: string; name?: string; passwordHash: string }>()
3124
-
3125
- @Service()
3126
- export class AuthService {
3127
- @Autowired() private password!: PasswordService
3128
-
3129
- async register(input: RegisterInput) {
3130
- const { email, password, name } = input
3131
-
3132
- if (users.has(email)) {
3133
- throw new Error('User already exists')
3134
- }
3135
-
3136
- const passwordHash = await this.password.hash(password)
3137
- const id = crypto.randomUUID()
3138
- users.set(email, { id, email, name, passwordHash })
3139
-
3140
- return { id, email, name }
3141
- }
3142
-
3143
- async login(input: LoginInput) {
3144
- const { email, password } = input
3145
- const user = users.get(email)
3146
- if (!user) return null
3147
-
3148
- const valid = await this.password.verify(user.passwordHash, password)
3149
- if (!valid) return null
3150
-
3151
- // TODO: Generate JWT token here
3152
- // const token = jwt.sign({ sub: user.id, email: user.email }, process.env.JWT_SECRET!)
3153
- return { user: { id: user.id, email: user.email, name: user.name } }
3154
- }
3155
- }
3156
- `}function br(){return`import { Controller, Post, Get } from '@forinda/kickjs'
3157
- import { Authenticated, Public } from '@forinda/kickjs-auth'
3158
- import { sessionLogin, sessionLogout } from '@forinda/kickjs-auth'
3159
- import type { RequestContext } from '@forinda/kickjs'
3160
- import { Autowired } from '@forinda/kickjs'
3161
- import { AuthService } from './auth.service'
3162
-
3163
- @Controller()
3164
- @Authenticated()
3165
- export class AuthController {
3166
- @Autowired() private authService!: AuthService
3167
-
3168
- @Post('/register')
3169
- @Public()
3170
- async register(ctx: RequestContext) {
3171
- const result = await this.authService.register(ctx.body)
3172
- return ctx.created(result)
3173
- }
3174
-
3175
- @Post('/login')
3176
- @Public()
3177
- async login(ctx: RequestContext) {
3178
- const user = await this.authService.login(ctx.body)
3179
- if (!user) return ctx.badRequest('Invalid credentials')
3180
- await sessionLogin(ctx.session, user)
3181
- return ctx.json({ message: 'Logged in', user })
3182
- }
3183
-
3184
- @Post('/logout')
3185
- async logout(ctx: RequestContext) {
3186
- await sessionLogout(ctx.session)
3187
- return ctx.json({ message: 'Logged out' })
3188
- }
3189
-
3190
- @Get('/me')
3191
- async me(ctx: RequestContext) {
3192
- return ctx.json({ user: ctx.user })
3193
- }
3194
- }
3195
- `}function xr(){return`import { Service, Autowired } from '@forinda/kickjs'
3196
- import { PasswordService } from '@forinda/kickjs-auth'
3197
- import type { RegisterInput } from './dto/register.dto'
3198
- import type { LoginInput } from './dto/login.dto'
3199
-
3200
- // TODO: Replace with your User repository
3201
- const users = new Map<string, { id: string; email: string; name?: string; passwordHash: string }>()
3202
-
3203
- @Service()
3204
- export class AuthService {
3205
- @Autowired() private password!: PasswordService
3206
-
3207
- async register(input: RegisterInput) {
3208
- const { email, password, name } = input
3209
-
3210
- if (users.has(email)) {
3211
- throw new Error('User already exists')
3212
- }
3213
-
3214
- const passwordHash = await this.password.hash(password)
3215
- const id = crypto.randomUUID()
3216
- users.set(email, { id, email, name, passwordHash })
3217
-
3218
- return { id, email, name }
3219
- }
3220
-
3221
- async login(input: LoginInput) {
3222
- const { email, password } = input
3223
- const user = users.get(email)
3224
- if (!user) return null
3225
-
3226
- const valid = await this.password.verify(user.passwordHash, password)
3227
- if (!valid) return null
3228
-
3229
- return { id: user.id, email: user.email, name: user.name }
3230
- }
3231
- }
3232
- `}async function Sr(e){let{name:t,outDir:n}=e,r=R(t),i=B(t),a=z(t),o=e.queue??`${i}-queue`,s=[];return await(async(e,t)=>{let r=S(n,e);await M(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
3233
- import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
3234
-
3235
- /**
3236
- * ${r} Job Processor
3237
- *
3238
- * Decorators:
3239
- * @Job(queueName) — marks this class as a job processor for a queue
3240
- * @Process(jobName?) — marks a method as the handler for a specific job type
3241
- * - Without a name: handles all jobs in the queue
3242
- * - With a name: handles only jobs matching that name
3243
- *
3244
- * To add jobs to this queue from a service or controller:
3245
- * @Inject(QUEUE_MANAGER) private queue: QueueService
3246
- * await this.queue.add('${o}', '${a}', { ... })
3247
- */
3248
- @Job('${o}')
3249
- export class ${r}Job {
3250
- @Process()
3251
- async handle(job: { name: string; data: any; id?: string }) {
3252
- console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
3253
-
3254
- // TODO: Implement job logic here
3255
- // Example:
3256
- // await this.emailService.send(job.data.to, job.data.subject, job.data.body)
3257
- }
3258
-
3259
- @Process('${a}.priority')
3260
- async handlePriority(job: { name: string; data: any; id?: string }) {
3261
- console.log(\`Priority job: \${job.name}\`, job.data)
3262
- // Handle high-priority variant of this job
3263
- }
3264
- }
3265
- `),s}const Cr={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.string().datetime()`},email:{ts:`string`,zod:`z.string().email()`},url:{ts:`string`,zod:`z.string().url()`},uuid:{ts:`string`,zod:`z.string().uuid()`},json:{ts:`any`,zod:`z.any()`}};function wr(e){return e.map(e=>{let t=e.indexOf(`:`);if(t===-1)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let n=e.slice(0,t),r=e.slice(t+1);if(!n||!r)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let i=!1;r.endsWith(`:optional`)&&(r=r.slice(0,-9),i=!0),n.endsWith(`?`)&&(n=n.slice(0,-1),i=!0),r.endsWith(`?`)&&(r=r.slice(0,-1),i=!0);let a=r;if(a.startsWith(`enum:`)){let e=a.slice(5).split(`,`);return{name:n,type:`enum`,tsType:e.map(e=>`'${e}'`).join(` | `),zodType:`z.enum([${e.map(e=>`'${e}'`).join(`, `)}])`,optional:i}}let o=Cr[a];if(!o){let e=[...Object.keys(Cr),`enum:a,b,c`].join(`, `);throw Error(`Unknown field type: "${a}". Valid types: ${e}`)}return{name:n,type:a,tsType:o.ts,zodType:o.zod,optional:i}})}async function Tr(e){let{name:t,fields:n,modulesDir:r,noEntity:i,noTests:a,repo:o=`inmemory`,tokenScope:s=`app`,style:c=`define`}=e,l=e.pluralize!==!1,u=B(t),d=R(t);z(t);let f=l?V(u):u,p=l?It(d):d,m=S(r,f),h=[],g=async(e,t)=>{let n=S(m,e);await M(n,t),h.push(n)};await g(`${u}.module.ts`,Nr(d,u,f,c)),await g(`constants.ts`,kr(d,n)),await g(`presentation/${u}.controller.ts`,Pr(d,u,f,p)),await g(`application/dtos/create-${u}.dto.ts`,Er(d,n)),await g(`application/dtos/update-${u}.dto.ts`,Dr(d,n)),await g(`application/dtos/${u}-response.dto.ts`,Or(d,n));let _=Lr(d,u,f,p);for(let e of _)await g(`application/use-cases/${e.file}`,e.content);return await g(`domain/repositories/${u}.repository.ts`,Fr(d,u,s)),await g(`domain/services/${u}-domain.service.ts`,Ir(d,u)),o===`inmemory`&&await g(`infrastructure/repositories/in-memory-${u}.repository.ts`,Ar(d,u,n)),i||(await g(`domain/entities/${u}.entity.ts`,jr(d,u,n)),await g(`domain/value-objects/${u}-id.vo.ts`,Mr(d))),await In(r,d,f,u,c),h}function Er(e,t){return`import { z } from 'zod'
3266
-
3267
- export const create${e}Schema = z.object({
3268
- ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
3269
- `)}
3270
- })
3271
-
3272
- export type Create${e}DTO = z.infer<typeof create${e}Schema>
3273
- `}function Dr(e,t){return`import { z } from 'zod'
3274
-
3275
- export const update${e}Schema = z.object({
3276
- ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
3277
- `)}
3278
- })
3279
-
3280
- export type Update${e}DTO = z.infer<typeof update${e}Schema>
3281
- `}function Or(e,t){return`export interface ${e}ResponseDTO {
3282
- id: string
3283
- ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
3284
- `)}
3285
- createdAt: string
3286
- updatedAt: string
3287
- }
3288
- `}function kr(e,t){let n=t.filter(e=>e.tsType===`string`).map(e=>`'${e.name}'`);t.filter(e=>e.tsType===`number`).map(e=>`'${e.name}'`);let r=t.map(e=>`'${e.name}'`),i=[...r].join(`, `),a=[...r,`'createdAt'`,`'updatedAt'`].join(`, `),o=n.length>0?n.join(`, `):`'name'`;return`import type { ApiQueryParamsConfig } from '@forinda/kickjs'
3289
-
3290
- export const ${e.toUpperCase()}_QUERY_CONFIG: ApiQueryParamsConfig = {
3291
- filterable: [${i}],
3292
- sortable: [${a}],
3293
- searchable: [${o}],
3294
- }
3295
- `}function Ar(e,t,n){return`import { randomUUID } from 'node:crypto'
3296
- import { Repository, HttpException } from '@forinda/kickjs'
3297
- import type { ParsedQuery } from '@forinda/kickjs'
3298
- import type { I${e}Repository } from '../../domain/repositories/${t}.repository'
3299
- import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
3300
- import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
3301
- import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
3302
-
3303
- @Repository()
3304
- export class InMemory${e}Repository implements I${e}Repository {
3305
- private store = new Map<string, ${e}ResponseDTO>()
3306
-
3307
- async findById(id: string): Promise<${e}ResponseDTO | null> {
3308
- return this.store.get(id) ?? null
3309
- }
3310
-
3311
- async findAll(): Promise<${e}ResponseDTO[]> {
3312
- return Array.from(this.store.values())
3313
- }
3314
-
3315
- async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
3316
- const all = Array.from(this.store.values())
3317
- const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
3318
- return { data, total: all.length }
3319
- }
3320
-
3321
- async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
3322
- const now = new Date().toISOString()
3323
- const entity: ${e}ResponseDTO = {
3324
- id: randomUUID(),
3325
- ${n.map(e=>` ${e.name}: dto.${e.name},`).join(`
3326
- `)}
3327
- createdAt: now,
3328
- updatedAt: now,
3329
- }
3330
- this.store.set(entity.id, entity)
3331
- return entity
3332
- }
3333
-
3334
- async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
3335
- const existing = this.store.get(id)
3336
- if (!existing) throw HttpException.notFound('${e} not found')
3337
- const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
3338
- this.store.set(id, updated)
3339
- return updated
3340
- }
3341
-
3342
- async delete(id: string): Promise<void> {
3343
- if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
3344
- this.store.delete(id)
3345
- }
3346
- }
3347
- `}function jr(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
3348
-
3349
- interface ${e}Props {
3350
- id: ${e}Id
3351
- ${n.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
3352
- `)}
3353
- createdAt: Date
3354
- updatedAt: Date
3355
- }
3356
-
3357
- export class ${e} {
3358
- private constructor(private props: ${e}Props) {}
3359
-
3360
- static create(params: { ${n.filter(e=>!e.optional).map(e=>`${e.name}: ${e.tsType}`).join(`; `)} }): ${e} {
3361
- const now = new Date()
3362
- return new ${e}({
3363
- id: ${e}Id.create(),
3364
- ${n.filter(e=>!e.optional).map(e=>` ${e.name}: params.${e.name},`).join(`
3365
- `)}
3366
- createdAt: now,
3367
- updatedAt: now,
3368
- })
3369
- }
3370
-
3371
- static reconstitute(props: ${e}Props): ${e} {
3372
- return new ${e}(props)
3373
- }
3374
-
3375
- get id(): ${e}Id { return this.props.id }
3376
- ${n.map(e=>` get ${e.name}(): ${e.tsType}${e.optional?` | undefined`:``} {
3377
- return this.props.${e.name}
3378
- }`).join(`
3379
- `)}
3380
- get createdAt(): Date { return this.props.createdAt }
3381
- get updatedAt(): Date { return this.props.updatedAt }
3382
-
3383
- toJSON() {
3384
- return {
3385
- id: this.props.id.toString(),
3386
- ${n.map(e=>` ${e.name}: this.props.${e.name},`).join(`
3387
- `)}
3388
- createdAt: this.props.createdAt.toISOString(),
3389
- updatedAt: this.props.updatedAt.toISOString(),
3390
- }
3391
- }
3392
- }
3393
- `}function Mr(e){return`import { randomUUID } from 'node:crypto'
3394
-
3395
- export class ${e}Id {
3396
- private constructor(private readonly value: string) {}
3397
-
3398
- static create(): ${e}Id { return new ${e}Id(randomUUID()) }
3399
-
3400
- static from(id: string): ${e}Id {
3401
- if (!id || id.trim().length === 0) throw new Error('${e}Id cannot be empty')
3402
- return new ${e}Id(id)
3403
- }
3404
-
3405
- toString(): string { return this.value }
3406
- equals(other: ${e}Id): boolean { return this.value === other.value }
3407
- }
3408
- `}function Nr(e,t,n,r=`define`){let i=`import { ${e}Controller } from './presentation/${t}.controller'
3409
- import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
3410
- import { InMemory${e}Repository } from './infrastructure/repositories/in-memory-${t}.repository'
3411
-
3412
- // Eagerly load decorated classes so @Service()/@Repository() decorators
3413
- // register in the DI container before the application bootstraps.
3414
- import.meta.glob(
3415
- ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
3416
- { eager: true },
3417
- )`,a=` /**
3418
- * Declare HTTP routes for this module. Return value shape:
3419
- *
3420
- * - \`path\` — URL prefix for this route set.
3421
- * - \`controller\` — Controller class (also drives OpenAPI).
3422
- * - \`version\` — Optional. Overrides the app-wide API version.
3423
- *
3424
- * Return an array to mount multiple route sets:
3425
- *
3426
- * return [
3427
- * { path: '/${n}', version: 1, controller: ${e}V1Controller },
3428
- * { path: '/${n}', version: 2, controller: ${e}V2Controller },
3429
- * ]
3430
- */`;return r===`class`?`import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
3431
- ${i}
3432
-
3433
- export class ${e}Module implements AppModule {
3434
- /**
3435
- * Bind the repository token to its concrete implementation.
3436
- * Decorator-managed classes (@Service, @Controller, @Repository) are
3437
- * registered automatically — only token-to-impl bindings need to live here.
3438
- */
3439
- register(container: Container): void {
3440
- container.registerFactory(
3441
- ${e.toUpperCase()}_REPOSITORY,
3442
- () => container.resolve(InMemory${e}Repository),
3443
- )
3444
- }
3445
-
3446
- ${a.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
3447
- routes(): ModuleRoutes {
3448
- return {
3449
- path: '/${n}',
3450
- controller: ${e}Controller,
3451
- }
3452
- }
3453
- }
3454
- `:`import { defineModule } from '@forinda/kickjs'
3455
- ${i}
3456
-
3457
- export const ${e}Module = defineModule({
3458
- name: '${e}Module',
3459
- build: () => ({
3460
- /**
3461
- * Bind the repository token to its concrete implementation.
3462
- * Decorator-managed classes (@Service, @Controller, @Repository) are
3463
- * registered automatically — only token-to-impl bindings need to live here.
3464
- */
3465
- register(container) {
3466
- container.registerFactory(
3467
- ${e.toUpperCase()}_REPOSITORY,
3468
- () => container.resolve(InMemory${e}Repository),
3469
- )
3470
- },
3471
-
3472
- ${a}
3473
- routes() {
3474
- return {
3475
- path: '/${n}',
3476
- controller: ${e}Controller,
3477
- }
3478
- },
3479
- }),
3480
- })
3481
- `}function Pr(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
3482
- import { ApiTags } from '@forinda/kickjs-swagger'
3483
- import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
3484
- import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
3485
- import { List${r}UseCase } from '../application/use-cases/list-${n}.use-case'
3486
- import { Update${e}UseCase } from '../application/use-cases/update-${t}.use-case'
3487
- import { Delete${e}UseCase } from '../application/use-cases/delete-${t}.use-case'
3488
- import { create${e}Schema } from '../application/dtos/create-${t}.dto'
3489
- import { update${e}Schema } from '../application/dtos/update-${t}.dto'
3490
- import { ${e.toUpperCase()}_QUERY_CONFIG } from '../constants'
3491
-
3492
- // Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${e}Controller['<method>']>\`
3493
- // so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
3494
- // The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
3495
- // \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
3496
-
3497
- @Controller()
3498
- export class ${e}Controller {
3499
- @Autowired() private readonly create${e}UseCase!: Create${e}UseCase
3500
- @Autowired() private readonly get${e}UseCase!: Get${e}UseCase
3501
- @Autowired() private readonly list${r}UseCase!: List${r}UseCase
3502
- @Autowired() private readonly update${e}UseCase!: Update${e}UseCase
3503
- @Autowired() private readonly delete${e}UseCase!: Delete${e}UseCase
3504
-
3505
- @Get('/')
3506
- @ApiTags('${e}')
3507
- @ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
3508
- async list(ctx: Ctx<KickRoutes.${e}Controller['list']>) {
3509
- return ctx.paginate(
3510
- (parsed) => this.list${r}UseCase.execute(parsed),
3511
- ${e.toUpperCase()}_QUERY_CONFIG,
3512
- )
3513
- }
3514
-
3515
- @Get('/:id')
3516
- @ApiTags('${e}')
3517
- async getById(ctx: Ctx<KickRoutes.${e}Controller['getById']>) {
3518
- const result = await this.get${e}UseCase.execute(ctx.params.id)
3519
- if (!result) return ctx.notFound('${e} not found')
3520
- ctx.json(result)
3521
- }
3522
-
3523
- @Post('/', { body: create${e}Schema, name: 'Create${e}' })
3524
- @ApiTags('${e}')
3525
- async create(ctx: Ctx<KickRoutes.${e}Controller['create']>) {
3526
- const result = await this.create${e}UseCase.execute(ctx.body)
3527
- ctx.created(result)
3528
- }
3529
-
3530
- @Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
3531
- @ApiTags('${e}')
3532
- async update(ctx: Ctx<KickRoutes.${e}Controller['update']>) {
3533
- const result = await this.update${e}UseCase.execute(ctx.params.id, ctx.body)
3534
- ctx.json(result)
3535
- }
3536
-
3537
- @Delete('/:id')
3538
- @ApiTags('${e}')
3539
- async remove(ctx: Ctx<KickRoutes.${e}Controller['remove']>) {
3540
- await this.delete${e}UseCase.execute(ctx.params.id)
3541
- ctx.noContent()
3542
- }
3543
- }
3544
- `}function Fr(e,t,n){return`import { createToken } from '@forinda/kickjs'
3545
- import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
3546
- import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
3547
- import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
3548
- import type { ParsedQuery } from '@forinda/kickjs'
3549
-
3550
- export interface I${e}Repository {
3551
- findById(id: string): Promise<${e}ResponseDTO | null>
3552
- findAll(): Promise<${e}ResponseDTO[]>
3553
- findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }>
3554
- create(dto: Create${e}DTO): Promise<${e}ResponseDTO>
3555
- update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO>
3556
- delete(id: string): Promise<void>
3557
- }
3558
-
3559
- /**
3560
- * Collision-safe DI token bound to \`I${e}Repository\`.
3561
- * \`container.resolve(${e.toUpperCase()}_REPOSITORY)\` and
3562
- * \`@Inject(${e.toUpperCase()}_REPOSITORY)\` both return the typed
3563
- * interface — no manual generic, no \`any\` cast.
3564
- *
3565
- * The \`'${n}/'\` prefix matches the project scope so
3566
- * \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
3567
- * adopters must NOT use the reserved \`'kick/'\` namespace.
3568
- */
3569
- export const ${e.toUpperCase()}_REPOSITORY = createToken<I${e}Repository>('${n}/${e}/repository')
3570
- `}function Ir(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
3571
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
3572
-
3573
- @Service()
3574
- export class ${e}DomainService {
3575
- constructor(
3576
- @Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
3577
- ) {}
3578
-
3579
- async ensureExists(id: string): Promise<void> {
3580
- const entity = await this.repo.findById(id)
3581
- if (!entity) throw HttpException.notFound('${e} not found')
3582
- }
3583
- }
3584
- `}function Lr(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3585
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3586
- import type { Create${e}DTO } from '../dtos/create-${t}.dto'
3587
-
3588
- @Service()
3589
- export class Create${e}UseCase {
3590
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3591
- async execute(dto: Create${e}DTO) { return this.repo.create(dto) }
3592
- }
3593
- `},{file:`get-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3594
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3595
-
3596
- @Service()
3597
- export class Get${e}UseCase {
3598
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3599
- async execute(id: string) { return this.repo.findById(id) }
3600
- }
3601
- `},{file:`list-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3602
- import type { ParsedQuery } from '@forinda/kickjs'
3603
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3604
-
3605
- @Service()
3606
- export class List${r}UseCase {
3607
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3608
- async execute(parsed: ParsedQuery) { return this.repo.findPaginated(parsed) }
3609
- }
3610
- `},{file:`update-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3611
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3612
- import type { Update${e}DTO } from '../dtos/update-${t}.dto'
3613
-
3614
- @Service()
3615
- export class Update${e}UseCase {
3616
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3617
- async execute(id: string, dto: Update${e}DTO) { return this.repo.update(id, dto) }
3618
- }
3619
- `},{file:`delete-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
3620
- import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
3621
-
3622
- @Service()
3623
- export class Delete${e}UseCase {
3624
- constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
3625
- async execute(id: string) { return this.repo.delete(id) }
3626
- }
3627
- `}]}async function Rr(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=B(t),o=R(t),s=[],c;if(e.outDir)c=w(e.outDir);else if(n){let e=B(n),t=i?V(e):e;c=w(S(r??`src/modules`,t,`__tests__`))}else c=w(`src/__tests__`);let l=S(c,`${a}.test.ts`);return await M(l,`import { describe, it, expect, beforeEach } from 'vitest'
3628
- import { Container } from '@forinda/kickjs'
3629
-
3630
- describe('${o}', () => {
3631
- beforeEach(() => {
3632
- Container.reset()
3633
- })
3634
-
3635
- it('should be defined', () => {
3636
- // TODO: Import and test your class/function here
3637
- expect(true).toBe(true)
3638
- })
3639
-
3640
- it('should handle the happy path', async () => {
3641
- // TODO: Set up test data and assertions
3642
- expect(true).toBe(true)
3643
- })
3644
-
3645
- it('should handle edge cases', async () => {
3646
- // TODO: Test error handling, empty inputs, etc.
3647
- expect(true).toBe(true)
3648
- })
3649
- })
3650
- `),s.push(l),s}const zr=[`agents`,`claude`,`skills`,`both`,`all`];function q(e){return e.parent?.opts()?.dryRun??!1}function J(e,t=!1){let n=process.cwd();console.log(`\n ${t?`Would generate`:`Generated`} ${e.length} file${e.length===1?``:`s`}:`);for(let t of e)console.log(` ${t.replace(n+`/`,``)}`);t&&console.log(`
3651
- (dry run — no files were written)`),console.log()}async function Br(e){if(!e)try{let e=await r(process.cwd());await p({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const Vr=[{name:`module <name>`,description:`Full DDD module (controller, DTOs, use-cases, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`job <name>`,description:`Queue @Job processor`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}];async function Hr(){console.log(`
3652
- Built-in generators:
3653
- `);let e=Math.max(...Vr.map(e=>e.name.length));for(let t of Vr)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await r(process.cwd()),n=a(t?.plugins??[],t?.commands??[]),i=await qt(process.cwd(),n.generators);if(i.generators.length>0){console.log(`
3654
- Plugin generators:
3655
- `);let e=Math.max(...i.generators.map(e=>`${e.spec.name} <name>`.length));for(let{source:t,spec:n}of i.generators){let r=`${n.name} <name>`;console.log(` kick g ${r.padEnd(e+2)} ${n.description} [${t}]`)}}if(i.failed.length>0){console.log(`
3656
- Failed to load:
3657
- `);for(let{source:e,reason:t}of i.failed)console.log(` ${e} — ${t}`)}console.log()}async function Ur(e,i,a){let o=await r(process.cwd()),s=n(o),c=i.modulesDir??s.dir??`src/modules`,l=i.repo??Pn(s.repo),u=i.pattern??o?.pattern??`ddd`,d=i.pluralize===!1?!1:s.pluralize??!0,f=t(o,process.cwd()),p=s.style??`define`;if(!a&&p===`define`){let e=await gr(w(c),`define`);if(e.length>0){console.error(`\n ${A.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${A.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${A.bold(`Files needing migration:`)}`);for(let t of e.slice(0,5))console.error(` - ${t}`);e.length>5&&console.error(` … and ${e.length-5} more`),console.error(`\n ${A.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${A.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${A.dim(`// kick.config.ts`)}\n ${A.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let m=[];for(let t of e){let e=await Fn({name:t,modulesDir:w(c),noEntity:i.entity===!1,noTests:i.tests===!1,repo:l,minimal:i.minimal,force:i.force,pattern:u,dryRun:a,pluralize:d,prismaClientPath:s.prismaClientPath,tokenScope:f,style:s.style});m.push(...e)}J(m,a),await Br(a)}function Wr(e){let i=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{if(t.list){await Hr();return}if(!e||e.length===0){i.help();return}let o=q(n);if(j(o),e.length>=2){let[n,i,...s]=e,c=await r(process.cwd()),l=a(c?.plugins??[],c?.commands??[]),u=await Kt({generatorName:n,itemName:i,args:s,flags:t,cwd:process.cwd()},l.generators);if(u){J(u.files,o);return}}await Ur(e,t,o)});i.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=q(n);j(r),await Ur(e,{...n.optsWithGlobals(),...t},r)}),i.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=q(n);j(r),J(await Un({name:e,outDir:w(t.out)}),r)}),i.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=q(n);j(r),J(await Wn({name:e,outDir:w(t.out)}),r)}),i.command(`middleware <name>`).description(`Generate an Express middleware function
3658
- Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=q(i);j(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;J(await Jn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
3659
- Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=q(i);j(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;J(await Yn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`service <name>`).description(`Generate a @Service() class
3660
- Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=q(i);j(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;J(await Xn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
3661
- Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=q(i);j(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;J(await Zn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a),await Br(a)}),i.command(`dto <name>`).description(`Generate a Zod DTO schema
3662
- Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,i)=>{let a=q(i);j(a);let o=await r(process.cwd()),s=n(o),c=s.dir??`src/modules`;J(await Qn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),a)}),i.command(`test <name>`).description(`Generate a Vitest test scaffold
3663
- Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,i)=>{let a=q(i);j(a);let o=n(await r(process.cwd())),s=o.dir??`src/modules`;J(await Rr({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pluralize:o.pluralize??!0}),a)}),i.command(`job <name>`).description(`Generate a @Job queue processor with @Process handlers`).option(`-o, --out <dir>`,`Output directory`,`src/jobs`).option(`-q, --queue <name>`,`Queue name (default: <name>-queue)`).action(async(e,t,n)=>{let r=q(n);j(r),J(await Sr({name:e,outDir:w(t.out),queue:t.queue}),r)}),i.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
3664
- Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
3665
- Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
3666
- Optional: append :optional (shell-safe): description:text:optional
3667
- or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,i,a,o)=>{let s=q(o);j(s),i.length===0&&(console.error(`
3668
- Error: At least one field is required.
3669
- Usage: kick g scaffold <name> <field:type> [field:type...]
3670
- Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
3671
- Optional: append :optional (shell-safe, no quoting needed)
3672
- `),process.exit(1));let c=await r(process.cwd()),l=n(c),u=a.modulesDir??l.dir??`src/modules`,d=wr(i),f=t(c,process.cwd()),p=c?.pattern??`ddd`;p!==`ddd`&&(console.error(`\n Error: 'kick g scaffold' currently only supports the DDD pattern.\n Detected project pattern: '${p}'.\n Workarounds:\n - Run 'kick g module ${e}' for the ${p} layout (no fields), then add fields manually.\n - Override the pattern for this scaffold by setting kick.config.ts pattern: 'ddd'.\n`),process.exit(1));let m=await Tr({name:e,fields:d,modulesDir:w(u),noEntity:a.entity===!1,noTests:a.tests===!1,pluralize:a.pluralize===!1?!1:l.pluralize??!0,tokenScope:f,style:l.style});console.log(`\n Scaffolded ${e} with ${d.length} field(s):`);for(let e of d)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);J(m,s),await Br(s)}),i.command(`auth-scaffold`).description(`Generate a complete auth module (register, login, logout, password hashing)
3673
- Includes controller, service, DTOs, and test stubs.`).option(`-s, --strategy <type>`,`Auth strategy: jwt | session`).option(`--role-guards`,`Generate role-based guards (default: true)`).option(`--no-role-guards`,`Skip role-based guard generation`).option(`-o, --out <dir>`,`Output directory`,`src/modules/auth`).action(async(e,t)=>{let n=q(t);j(n);let r=e.strategy;r||=await Ct({message:`Auth strategy`,options:[{value:`jwt`,label:`JWT`,hint:`stateless token-based auth`},{value:`session`,label:`Session`,hint:`server-side session with cookies`}]});let i=e.roleGuards;i===void 0&&(i=await F({message:`Generate role-based guards?`,initialValue:!0})),J(await _r({strategy:r,outDir:e.out,roleGuards:i}),n)}),i.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Default repository type: inmemory | drizzle | prisma`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=q(t);j(n),J(await $n({outDir:w(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),i.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | ddd | cqrs | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=q(t);j(n);let r=e.only??`all`;if(!zr.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${zr.join(` | `)}`),process.exitCode=1;return}J(await ir({outDir:w(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)})}async function Gr(e){let t=b.resolve(e.cwd,`.kickjs/types`);await me(t,{recursive:!0});let n=new Map,r=e.scan??c,i={cwd:e.cwd,config:e.config,async importTs(e){return await import(T(e).href)},async writeFile(t,n){let r=b.resolve(e.cwd,t);await me(b.dirname(r),{recursive:!0}),await O(r,n,`utf8`)},getScanResult:e=>{let t=Kr(e),i=n.get(t);return i||(i=r(e),n.set(t,i)),i},log:console},a=[];for(let n of e.plugins){let r=await n.generate(i);if(r===null){a.push({id:n.id,status:`skipped`});continue}let o=n.outExtension??`.d.ts`,s=b.join(t,`${n.id.replace(/\//g,`__`)}${o}`),c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+r+`
3674
- `,l=``;if(g(s)&&(l=await D(s,`utf8`)),l===c){a.push({id:n.id,status:`unchanged`,outFile:s});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${s})`);await O(s,c,`utf8`),a.push({id:n.id,status:`written`,outFile:s})}return a}function Kr(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function qr(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var Jr=e({applyDisableFilter:()=>qr,runAllPluginTypegens:()=>Yr});async function Yr(e){let{enabled:t,skipped:n,unknown:r}=qr(a([...Ma,...e.config?.plugins??[]],e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&n.length>0)for(let e of n)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&r.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${r.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),t.length===0)return[];try{let n=await Gr({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check});if(!e.silent)for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}async function Xr(e,t){let{cwd:n,silent:r=!1}=t,i=t.distDir??e?.build?.outDir??`dist`,a=e?.assetMap;if(!a||Object.keys(a).length===0)return null;let o=r?()=>{}:console.log,s=w(n,i);_(s,{recursive:!0});let c=[],l={};for(let[e,t]of Object.entries(a)){let r=await Zr(e,t,n,s);c.push(r.entrySummary),Object.assign(l,r.manifestSlice),o(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let u={version:1,entries:l},d=S(s,`.kickjs-assets.json`);return ne(d,JSON.stringify(u,null,2)+`
3675
- `,`utf-8`),o(` ✓ wrote manifest → ${C(n,d)} (${Object.keys(l).length} entries)`),{manifestPath:d,entries:c,manifest:u}}async function Zr(e,t,n,r){let i=w(n,t.src),a=t.dest?w(n,t.dest):S(r,e);if($r(a,n))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:C(n,a),filesCopied:0},manifestSlice:{}};if(!g(i)||!ei(i))return{entrySummary:{namespace:e,src:t.src,dest:C(n,a),filesCopied:0},manifestSlice:{}};let o=await ye(t.glob??`**/*`,{cwd:i,nodir:!0,dot:!1,posix:!0});_(a,{recursive:!0});let s={},{pairs:c,collisionGroupsResolved:l}=be(e,[...o].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of c){let n=S(i,e),o=S(a,e);_(x(o),{recursive:!0}),h(n,o),s[t]=Qr(r,o)}return l>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${l} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:C(n,a),filesCopied:o.length},manifestSlice:s}}function Qr(e,t){return C(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function $r(e,t){let n=C(t,e);return n===``?!1:n.startsWith(`..`)||ae(n)}function ei(e){try{return te(e).isDirectory()}catch{return!1}}function ti(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function ni(e,t,n={}){t&&(process.env.PORT=t);let i=ti(n.polling),a=process.cwd(),o=await r(a),s=o?.typegen?.schemaValidator??`zod`,c=o?.typegen?.envFile;try{await p({cwd:a,allowDuplicates:!0,schemaValidator:s,envFile:c,srcDir:o?.typegen?.srcDir,outDir:o?.typegen?.outDir,assetMap:o?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}await Yr({cwd:a,config:o});let{createRequire:l}=await import(`node:module`),{createServer:u}=await import(T(l(w(`package.json`)).resolve(`vite`)).href),d=await u({configFile:w(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...i?{watch:{usePolling:!0,interval:100}}:{}}}),f=o?.assetMap?Object.values(o.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>w(a,e)):[],m=e=>f.some(t=>e===t||e.startsWith(`${t}/`)),h=null,g=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=m(e);!t&&!n||(h&&clearTimeout(h),h=setTimeout(()=>{p({cwd:a,silent:!0,allowDuplicates:!0,schemaValidator:s,envFile:c,srcDir:o?.typegen?.srcDir,outDir:o?.typegen?.outDir,assetMap:o?.assetMap,runPlugins:!1}).catch(()=>{}),Yr({cwd:a,config:o,silent:!0}).catch(()=>{})},100))};d.watcher.on(`add`,g),d.watcher.on(`unlink`,g),d.watcher.on(`change`,g),f.length>0&&d.watcher.add(f),await d.listen(),d.printUrls(),console.log(`
3676
- KickJS dev server running (Vite + @forinda/kickjs-vite)
3677
- `);let _=async()=>{h&&clearTimeout(h),await d.close(),process.exit(0)};process.on(`SIGINT`,_),process.on(`SIGTERM`,_)}function ri(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).action(async e=>{try{await ni(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
3678
- Error: vite is not installed.
3679
- Run: pnpm add -D vite unplugin-swc
3680
- `):console.error(`
3681
- Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
3682
- Building for production...
3683
- `);let{createRequire:e}=await import(`node:module`),{build:t}=await import(T(e(w(`package.json`)).resolve(`vite`)).href);await t({configFile:w(`vite.config.ts`)});let n=await r(process.cwd()),i=n?.copyDirs??[];if(i.length>0){console.log(`
3684
- Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?S(`dist`,e):e.dest??S(`dist`,t),r=w(t),i=w(n);if(!g(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}_(i,{recursive:!0}),h(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
3685
- Building asset map...`);try{await Xr(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
3686
- Build complete.
3687
- `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await r(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
3688
- Building asset map...`);try{await Xr(e,{cwd:process.cwd()}),console.log(`
3689
- Asset build complete.
3690
- `)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),Pe(e.entry,t)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await ni(e.entry,e.port)}catch(e){console.error(`
3691
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function ii(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
3692
- KickJS CLI
3693
-
3694
- System:
3695
- OS: ${Se()} ${Ce()} (${xe()})
3696
- Node: ${process.version}
3697
-
3698
- Packages:
3699
- @forinda/kickjs workspace
3700
- @forinda/kickjs-vite workspace
3701
- @forinda/kickjs-cli workspace
3702
- `)})}const{bold:Y,dim:X,green:ai,red:oi,yellow:si,blue:ci}=A;function li(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,a=[];return t&&a.push(`${t}d`),n&&a.push(`${n}h`),r&&a.push(`${r}m`),a.push(`${i}s`),a.join(` `)}async function ui(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function di(e,t){try{return await ui(`${e}${t}`)}catch{return null}}async function fi(e){let[t,n,r,i,a]=await Promise.all([di(e,`/health`),di(e,`/metrics`),di(e,`/routes`),di(e,`/container`),di(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function pi(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=X(`─`.repeat(60));if(console.log(),console.log(Y(` KickJS Inspector`)+X(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?ai(`● healthy`):oi(`● `+n.status);console.log(` ${Y(`Health:`)} ${e}`)}else console.log(` ${Y(`Health:`)} ${oi(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?oi:r.errorRate>0?si:ai;console.log(` ${Y(`Uptime:`)} ${li(r.uptimeSeconds)}`),console.log(` ${Y(`Requests:`)} ${r.requests}`),console.log(` ${Y(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${X(`(`)}${t(e+`%`)}${X(`)`)}`)}if(a&&console.log(` ${Y(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${Y(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(Y(` Routes`)),console.log(s),console.log(` ${X(`METHOD`)} ${X(`PATH`.padEnd(36))} ${X(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${_t(e.method)} ${t} ${ci(e.controller)}.${X(e.handler)}`)}}console.log(s),console.log()}function mi(e){e.command(`inspect [url]`).description(`Connect to a running KickJS app and display debug info`).option(`-p, --port <port>`,`Override port`).option(`-w, --watch`,`Poll every 5 seconds`).option(`-j, --json`,`Output raw JSON`).action(async(e,t)=>{let n=e??`http://localhost:3000`;if(t.port)try{let e=new URL(n);e.port=t.port,n=e.origin}catch{n=`http://localhost:${t.port}`}let r=`${n.replace(/\/$/,``)}/_debug`,i=async()=>{try{let e=await fi(r);t.json?console.log(JSON.stringify(e,null,2)):pi(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(oi(` ✖ Could not connect to ${n}`)),console.error(X(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function hi(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Z(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const gi=[{match(e,t){let n=hi(e,[`config`,`get`])&&Z(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Z(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
3703
- registers the env schema with kickjs at module-load time. Without it,
3704
- ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
3705
- and every user-defined key reads as undefined. @Value() may *appear* to
3706
- work via a raw process.env fallback, but Zod coercion and schema defaults
3707
- are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
3708
- import { bootstrap } from '@forinda/kickjs'
3709
- import { modules } from './modules'
3710
- `,codeAfter:`import 'reflect-metadata'
3711
- import './config' // ← add this — registers env schema
3712
- import { bootstrap } from '@forinda/kickjs'
3713
- import { modules } from './modules'
3714
- `,docs:`https://forinda.github.io/kick-js/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Z(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return Z(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
3715
- When vitest re-imports your modules across tests, the same class can be
3716
- registered twice and the container throws. The fix is to wipe the
3717
- container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
3718
- import { Container } from '@forinda/kickjs'
3719
-
3720
- describe('UserController', () => {
3721
- beforeEach(() => Container.reset())
3722
-
3723
- it('does the thing', async () => { /* ... */ })
3724
- })`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||hi(e,[`Module`,`is not a function`])||hi(e,[`Module`,`no exported member`])?{confidence:80,diagnosis:{id:`module-decorator-not-found`,title:`KickJS does not have a @Module decorator (different pattern from NestJS)`,explanation:`NestJS uses @Module({ controllers, providers }). KickJS uses an interface
3725
- pattern instead: a class implements AppModule and exposes routes() that
3726
- returns the controller wiring. This was a deliberate choice — modules
3727
- become explicit values rather than metadata, which makes them easier to
3728
- compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
3729
- import { UserController } from './user.controller'
3730
-
3731
- @Module({
3732
- controllers: [UserController],
3733
- })
3734
- export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
3735
- import { UserController } from './user.controller'
3736
-
3737
- export class UserModule implements AppModule {
3738
- routes(): ModuleRoutes {
3739
- return {
3740
- path: '/users',
3741
- router: buildRoutes(UserController),
3742
- controller: UserController,
3743
- }
3744
- }
3745
- }`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}},{match(e,t){return/KickRoutes\s*\[\s*['"](GET|POST|PUT|PATCH|DELETE)/i.test(e)?{confidence:95,diagnosis:{id:`legacy-kick-routes-bracket-syntax`,title:`KickRoutes['POST /users'] is the legacy v1 syntax`,explanation:`KickJS v2 changed the typegen output from a flat string-keyed map to a
3746
- namespaced shape: KickRoutes.UserController["create"] instead of
3747
- KickRoutes["POST /users"]. The new form is per-controller, per-method,
3748
- and matches the actual class names so refactors propagate via
3749
- rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
3750
- create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
3751
- create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://forinda.github.io/kick-js/guide/typegen.html`}}:null}},{match(e,t){let n=Z(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Z(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
3752
- cluster: { workers: N }, the framework forks N workers, each of which
3753
- spins up its own Vite instance on a separate port. The fix landed in
3754
- v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
3755
- silently skips cluster, with a warning. If you see this on an older
3756
- version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
3757
- modules,
3758
- cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
3759
- })`,docs:`https://forinda.github.io/kick-js/guide/cluster.html`}}}},{match(e,t){return Z(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
3760
- reflect-metadata polyfill. The polyfill must be imported once,
3761
- before any decorator runs. Most projects do this at the top of
3762
- src/index.ts; missing the import causes obscure "design:paramtypes"
3763
- or "Reflect.getMetadata is not a function" errors at runtime.`,fix:`Add the import at the very top of src/index.ts:`,codeAfter:`import 'reflect-metadata' // ← must be the FIRST import
3764
- import './config'
3765
- import { bootstrap } from '@forinda/kickjs'
3766
- import { modules } from './modules'
3767
-
3768
- export const app = await bootstrap({ modules })`,docs:`https://forinda.github.io/kick-js/guide/dependency-injection.html`}}:null}},{match(e,t){return Z(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
3769
- generated a module via \`kick g module foo\` but the routes don't appear,
3770
- the most likely cause is that the module is missing from the exported
3771
- array. The CLI usually wires this automatically, but a hand-edit can
3772
- drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleEntry } from '@forinda/kickjs'
3773
- import { UserModule } from './users/user.module'
3774
- import { TaskModule } from './tasks/task.module' // ← was this missing?
3775
-
3776
- export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function _i(e,t){let n=null;for(let r of gi){let i=null;try{i=r.match(e,t)}catch{continue}!i||i.confidence<40||(!n||i.confidence>n.confidence)&&(n=i)}return n}async function vi(e){let t=e.provider??`openai`,n=process.env.OPENAI_API_KEY;if(t===`openai`&&!n)return{kind:`unavailable`,reason:`OPENAI_API_KEY environment variable is not set`,suggestion:`Set OPENAI_API_KEY in your shell, e.g.
3777
- export OPENAI_API_KEY="sk-..."
3778
-
3779
- Then re-run \`kick explain --ai "<your error>"\`.`};let r;try{r=await import(`@forinda/kickjs-ai`)}catch{return{kind:`unavailable`,reason:`@forinda/kickjs-ai is not installed`,suggestion:`Install the AI package to enable the LLM fallback:
3780
- kick add ai
3781
-
3782
- Or manually:
3783
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=yi(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=bi((await a.chat({messages:[{role:`system`,content:o},{role:`user`,content:s}]})).content);return e?{kind:`ok`,diagnosis:e}:{kind:`error`,message:`The LLM responded but the payload was not valid JSON in the expected shape. Try again, or file an issue with the error text.`}}catch(e){return{kind:`error`,message:`LLM request failed: ${e instanceof Error?e.message:String(e)}`}}}function yi(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
3784
- `)}function bi(e){let t=[e,xi(e),Si(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Ci(t))return t}catch{continue}return null}function xi(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Si(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(i){i=!1;continue}if(o===`\\`&&r){i=!0;continue}if(o===`"`){r=!r;continue}if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Ci(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.title==`string`&&typeof t.explanation==`string`&&typeof t.fix==`string`}function wi(e){e.command(`explain [message]`).description(`Explain a KickJS error and suggest a fix`).option(`-m, --message <text>`,`Error message to explain (alternative to positional arg)`).option(`--ai`,`Fall back to LLM if no known-issue matches (requires @forinda/kickjs-ai)`).option(`--model <name>`,`Model name for the --ai fallback`,`gpt-4o-mini`).option(`--json`,`Output the diagnosis as JSON for tooling integration`).action(async(e,t)=>{let n=await Di(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
3785
-
3786
- Pass a message as a positional arg, --message flag, or pipe via stdin:
3787
- kick explain "config.get returned undefined"
3788
- pnpm test 2>&1 | kick explain
3789
- `),process.exit(1));let r=ki(),i=_i(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
3790
- `);return}if(i){Ai(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
3791
- `),process.exit(2)),ji(n,!1),process.exit(2));let a=await vi({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Ti(a),null,2)+`
3792
- `),process.exit(a.kind===`ok`?0:2)),Ei(n,a),process.exit(a.kind===`ok`?0:2)})}function Ti(e){return e.kind===`ok`?{matched:!0,source:`ai`,diagnosis:e.diagnosis}:e.kind===`unavailable`?{matched:!1,aiUnavailable:!0,reason:e.reason}:{matched:!1,aiError:!0,error:e.message}}function Ei(e,t){if(t.kind===`ok`){Ai(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Ni(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Mi(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Ni(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Di(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Oi()}function Oi(){return new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n)),process.stdin.on(`error`,t)})}function ki(){let e=process.cwd();return{cwd:e,hasFile:t=>g(w(e,t))}}function Ai(e,t,n,r=!1){let i=Ni(e.trim(),200),a=r?`AI-generated — verify before applying`:Pi(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${Mi(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Mi(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Mi(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Mi(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
3793
- `)}function ji(e,t){let n=Ni(e.trim(),200);process.stdout.write(`\n Explaining: ${n}\n\n`),t?process.stdout.write(` No known-issue matched, and --ai fallback is not yet wired.
3794
- When @forinda/kickjs-ai ships its provider implementations,
3795
- this command will call the configured LLM with the error +
3796
- project context and return a structured fix.
3797
-
3798
- `):process.stdout.write(` No known-issue matched. Things you can try:
3799
-
3800
- 1. Check the framework docs for the error keywords:
3801
- https://forinda.github.io/kick-js/
3802
-
3803
- 2. Re-run with --ai to fall back to an LLM (requires
3804
- @forinda/kickjs-ai with a configured provider):
3805
- kick explain --ai "<your error>"
3806
-
3807
- 3. File an issue with the error text:
3808
- https://github.com/forinda/kick-js/issues/new
3809
-
3810
- `)}function Mi(e,t){return e.split(`
3811
- `).map(e=>`${t}${e}`).join(`
3812
- `)}function Ni(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Pi(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Fi(e){let t=e.command(`mcp`).description(`Model Context Protocol commands (start | init)`);t.command(`start`,{isDefault:!0}).description(`Run the built application as an MCP server over stdio`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`--node-arg <arg...>`,`Extra arguments to pass to node`).action(Ii),t.command(`init`).description(`Generate .mcp.json for Claude Code / Cursor / Zed`).option(`-n, --name <name>`,`Server name (defaults to package.json name)`).option(`-o, --out <file>`,`Output file`,`.mcp.json`).option(`-f, --force`,`Overwrite an existing entry without prompting`).option(`--global`,`Write to ~/.mcp.json instead of the project root`).action(Li)}function Ii(e){let t=w(e.entry);g(t)||(process.stderr.write(`Error: entry file not found: ${t}\n\nBuild the app first with \`kick build\`, or pass a custom entry:\n kick mcp -e dist/server.js\n`),process.exit(1));let n=[...e.nodeArg??[],t],r=ue(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});r.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),r.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Li(e){let t=process.cwd(),n=Ri(t)??re(t),r=e.name??n,i=e.global?w(process.env.HOME??`.`,`.mcp.json`):w(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(g(i))try{let e=v(i,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(o={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${i} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}o.mcpServers[r]&&!e.force&&(process.stderr.write(`Error: an entry for "${r}" already exists in ${i}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),o.mcpServers[r]=a,ne(i,JSON.stringify(o,null,2)+`
3813
- `,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${r}" to ${i}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function Ri(e){let t=w(e,`package.json`);if(!g(t))return null;try{let e=v(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function zi(e){e.command(`tinker`).description(`Interactive REPL with DI container and services loaded`).option(`-e, --entry <file>`,`Entry file to load`,`src/index.ts`).action(async e=>{let t=process.cwd(),n=w(t,e.entry);g(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Vi(t,`tsx`);r||(console.error(`
3814
- Error: tsx not found. Install it: pnpm add -D tsx
3815
- `),process.exit(1));let i=Bi(n,e.entry),a=S(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=le(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Bi(e,t){return`
3816
- import 'reflect-metadata'
3817
-
3818
- // Prevent bootstrap() from starting the HTTP server
3819
- process.env.KICK_TINKER = '1'
3820
-
3821
- console.log('\\n 🔧 KickJS Tinker')
3822
- console.log(' Loading: ${t}\\n')
3823
-
3824
- // Load core
3825
- let Container, Logger, HttpException, HttpStatus
3826
- try {
3827
- const core = await import('@forinda/kickjs')
3828
- Container = core.Container
3829
- Logger = core.Logger
3830
- HttpException = core.HttpException
3831
- HttpStatus = core.HttpStatus
3832
- } catch {
3833
- console.error(' Error: @forinda/kickjs not found.')
3834
- console.error(' Install it: pnpm add @forinda/kickjs\\n')
3835
- process.exit(1)
3836
- }
3837
-
3838
- // Load entry to trigger decorator registration
3839
- try {
3840
- await import('${T(e).href}')
3841
- } catch (err) {
3842
- console.warn(' Warning: ' + err.message)
3843
- console.warn(' Container may be partially initialized.\\n')
3844
- }
3845
-
3846
- const container = Container.getInstance()
3847
-
3848
- // Start REPL
3849
- const repl = await import('node:repl')
3850
- const server = repl.start({ prompt: 'kick> ', useGlobal: true })
3851
-
3852
- server.context.container = container
3853
- server.context.Container = Container
3854
- server.context.resolve = (token) => container.resolve(token)
3855
- server.context.Logger = Logger
3856
- server.context.HttpException = HttpException
3857
- server.context.HttpStatus = HttpStatus
3858
-
3859
- console.log(' Available globals:')
3860
- console.log(' container — DI container instance')
3861
- console.log(' resolve(T) — shorthand for container.resolve(T)')
3862
- console.log(' Container, Logger, HttpException, HttpStatus')
3863
- console.log()
3864
-
3865
- server.on('exit', () => {
3866
- console.log('\\n Goodbye!\\n')
3867
- process.exit(0)
3868
- })
3869
- `}function Vi(e,t){let n=e;for(;;){let e=S(n,`node_modules`,`.bin`,t);if(g(e))return e;let r=w(n,`..`);if(r===n)break;n=r}return null}function Hi(e,t){let n=RegExp(`^\\s*${H(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
3870
- `;)s++;else{for(s+=2;s+1<a.length&&!(a[s]===`*`&&a[s+1]===`/`);)s++;s+=2}continue}let t=a[s]??``;if(t===`'`||t===`"`||t==="`"){let e=t;for(s++;s<a.length&&a[s]!==e;)a[s]===`\\`&&s++,s++}else if(t===`(`)o++;else if(t===`)`&&(o--,o===0))break;s++}if(o!==0)break;let c=a.slice(t,s);if(n.test(c)){let t=e;for(;t>0&&(a[t-1]===` `||a[t-1]===` `||a[t-1]===`
3871
- `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Ui(e,t){let n=Rn(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Hi(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${H(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function Wi(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=B(t),o=R(t),s=i?V(a):a,c=S(n,s);if(!await Be(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await F({message:A.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
3872
- Cancelled.
3873
- `);return}await ge(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=S(n,`index.ts`);if(await Be(l)){let e=await D(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${H(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${H(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Ui(e,o),e=e.replace(/\n{3,}/g,`
3874
-
3875
- `),e!==t&&(await O(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Gi(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let i=n(await r(process.cwd())),a=t.modulesDir??i.dir??`src/modules`,o=t.pluralize===!1?!1:i.pluralize??!0;for(let n of e)await Wi({name:n,modulesDir:w(a),force:t.force,pluralize:o})})}function Ki(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;console.warn(` kick typegen: unknown --schema-validator '${e}' (only 'zod' and 'false' are supported). Falling back to project config.`)}}function qi(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Ji(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=process.cwd(),n=await r(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-DZZsizSI.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>ja),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
3876
- Registered typegen plugins:
3877
- `);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let i=Ki(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,a=qi(e.envFile)??n?.typegen?.envFile,o={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:i,envFile:a,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await l(o);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{let{result:r}=await p(o),i=await Yr({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&i.some(e=>e.status===`written`)&&process.exit(1),e.check||await u(w(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r.written,i,e.silent??!1)}}catch(e){e instanceof f?console.error(`
3878
- `+e.message+`
3879
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Yi(e){let t=[];if(!g(e))return t;let n=y(e,{withFileTypes:!0});for(let r of n){let n=S(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Yi(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Xi(e){try{return v(e,`utf-8`)}catch{return``}}const Zi=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Qi(e,t){let n=Xi(S(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Zi.has(t.toLowerCase())||t.length<32)return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value or too short (< 32 chars) — change it`}}}for(let e of t)for(let t of[/JWT_SECRET['"]?\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i,/secret\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i])if(t.test(e))return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value in source code — use an environment variable`};return null}function $i(e){for(let t of e)if(/cors\s*\(/.test(t)&&/origin\s*:\s*['"]\*['"]/.test(t))return{severity:`CRITICAL`,message:`CORS origin is '*' — restrict to your domains`};return null}function ea(e){for(let t of e)if(/rateLimit/i.test(t)||/@RateLimit/i.test(t))return null;return{severity:`WARNING`,message:`No rate limiting detected — add rateLimit() middleware or @RateLimit decorator`}}function ta(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function na(e){let t=!1,n=!1;for(let r of e)/tokenStore/i.test(r)&&(t=!0),/MemoryTokenStore/i.test(r)&&(n=!0);return n?{severity:`WARNING`,message:`MemoryTokenStore detected — use a persistent store (Redis, DB) for production deployments`}:t?null:{severity:`WARNING`,message:`No token revocation store detected — consider adding one for auth token management`}}function ra(e){for(let t of e)if(/helmet\s*\(/.test(t))return/security\s*\.\s*helmet\s*.*false/.test(t)?{severity:`WARNING`,message:`Helmet security headers are disabled — enable them for production`}:{severity:`INFO`,message:`Helmet security headers active`};return{severity:`WARNING`,message:`Helmet not detected — add helmet() middleware for security headers`}}function ia(e){for(let t of e)if(/AuthAdapter/i.test(t))return{severity:`INFO`,message:`AuthAdapter configured`};return{severity:`INFO`,message:`No AuthAdapter detected — add one if your app requires authentication`}}function aa(e){let t=Yi(S(e,`src`)).map(e=>Xi(e)),n=[],r=Qi(e,t);r&&n.push(r);let i=$i(t);i&&n.push(i);let a=ea(t);a&&n.push(a);let o=ta();o&&n.push(o);let s=na(t);return s&&n.push(s),n.push(ra(t)),n.push(ia(t)),n}function oa(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
3880
- Usage: kick check --deploy
3881
-
3882
- Available checks:
3883
- --deploy Audit for production readiness (security, config, best practices)
3884
- `);return}let t=process.cwd();yt(`KickJS Deploy Check`);let n=Tt();n.start(`Scanning project...`);let r=aa(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)I.message(`${vt(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?A.red(`${a} critical`):`${a} critical`,o>0?A.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(bt(A.red(`${l} — fix critical issues before deploying`)),process.exit(1)):bt(A.green(`${l} — looking good!`))})}async function Q(e){return Me({configPath:b.resolve(process.cwd(),e.config)})}async function $(e){if(e.adapter){let t=await e.adapter();return{adapter:t,cleanup:async()=>t.close()}}if(!e.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL) in kick.config.ts, or supply db.adapter() factory`);let t=e.dialect??`postgres`;if(t!==`postgres`)throw Error(`kickjs-db: built-in CLI adapter only supports postgres in M1 (dialect=${t}); use db.adapter() factory for other dialects`);let[{pgAdapter:n},r]=await Promise.all([import(`@forinda/kickjs-db-pg`),import(`pg`)]),i=new r.default.Pool({connectionString:e.connectionString}),a=n({pool:i});return{adapter:a,cleanup:async()=>{await a.close(),await i.end()}}}async function sa(e){if(e.adapter||(e.dialect??`postgres`)!==`postgres`||!e.connectionString)return null;let t=new(await(import(`pg`))).default.Pool({connectionString:e.connectionString});return{runner:t,cleanup:async()=>{await t.end()}}}function ca(e){if(e.length===0){console.log(`No migrations.`);return}console.table(e.map(e=>({id:e.id,state:e.state,batch:e.batch??`-`,reviewed:e.reviewed,applied:e.appliedAt??`-`})))}function la(e){let t=e.command(`db`).description(`Database commands (kickjs-db)`);t.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(e,t)=>{let n=process.cwd(),r=await Q(t),i=await sa(r),a=i?e=>we(i.runner,e):void 0;try{let i=await Te({name:e,config:r,cwd:n,empty:t.empty,detectCompositeRefs:a});if(i.status===`no-changes`){console.log(`No schema changes detected.`);return}if(i.empty){console.log(`Created empty migration ${i.migrationDir} (author up.sql + down.sql).`);return}let o=i.changeCount===1?``:`s`;console.log(`Created migration ${i.migrationDir} (${i.changeCount} change${o}).`)}finally{await i?.cleanup()}});let n=t.command(`migrate`).description(`Migration runner subcommands`);n.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await De({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await r()}}),n.command(`up`).description(`Apply the next single pending migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await Ae({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await r()}}),n.command(`down`).description(`Reverse the most recent applied migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ee({adapter:n,migrationsDir:t.migrationsDir});e.reversed?console.log(`Reversed ${e.reversed}.`):console.log(`Nothing to reverse.`)}finally{await r()}}),n.command(`rollback`).description(`Reverse the entire last batch as a single unit`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Oe({adapter:n,migrationsDir:t.migrationsDir});e.reversed.length===0?console.log(`Nothing to roll back.`):console.log(`Rolled back batch ${e.batch}: ${e.reversed.join(`, `)}`)}finally{await r()}}),n.command(`status`).description(`Print applied + pending migrations`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{ca(await ke({adapter:n,migrationsDir:t.migrationsDir}))}finally{await r()}}),t.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await n.introspect();if(e.json){console.log(JSON.stringify(r,null,2));return}let i=e.out??t.schemaPath;await O(i,je(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}function ua(e){return e.optsWithGlobals().dryRun??!1}function da(e){e.command(`codemod`).description(`Codebase migration commands (AST-style rewrites — distinct from db migrate)`).command(`modules`).description(`Rewrite module declarations between class form and the defineModule factory.
3885
- Direction defaults to \`modules.style\` from kick.config (or "define").
3886
- --target define|class Override the migration direction.
3887
- --apply Apply the changes (default: dry-run preview).
3888
- --experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let i=ua(t)||!e.apply;j(i),e.experimental||(console.error(`
3889
- `+A.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
3890
- The regex-based rewrite handles the shapes our templates produce.
3891
- Hand-rolled modules with non-standard structures may be skipped.
3892
- Always commit before running with --apply.
3893
- `),process.exit(1));let a=n(await r(process.cwd())),o=w(e.modulesDir??a.dir??`src/modules`),s;e.target===`define`||e.target===`class`?s=e.target:e.target===void 0?s=a.style??`define`:(console.error(`\n ${A.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let c=A.dim(`→ ${s}`),l=i?A.dim(`(dry-run)`):A.bold(`(applying)`);console.log(`\n ${A.bold(`kick codemod modules`)} ${c} ${l}`),console.log(` modulesDir: ${A.dim(o)}\n`);let u=e.backup!==!1&&!i,d=await hr(o,{dryRun:i,target:s,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${A.green(`✓`)} backup: ${A.dim(e)}\n ${A.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else !i&&e.backup===!1&&console.log(` ${A.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,p=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${A.green(`✓`)} ${e.path}`);else{p++;let t=A.dim(`(${e.reason??`skipped`})`);console.log(` ${A.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${A.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=A.dim(`(${d.indexReason??`skipped`})`);console.log(` ${A.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${A.dim(`-`)} ${d.indexPath} ${A.dim(`(not found)`)}`);let m=i?A.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${A.bold(String(f))} migrated, ${A.bold(String(p))} skipped${m}\n`)})}const fa=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],pa=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=ma(e.cwd);if(!t)return null;let n=b.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${ha(b.relative(n,t)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
3894
- `)}});function ma(e){for(let t of fa){let n=b.resolve(e,t);if(t.endsWith(`.ts`)){if(g(n))return n}else{let e=b.join(n,`index.ts`);if(g(e))return e}}return null}function ha(e){return e.replace(/\\/g,`/`)}const ga=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!g(b.resolve(e.cwd,`kick.config.ts`)))return null;let t=await r(e.cwd);if(!t?.assetMap)return null;let n=s(t.assetMap,e.cwd);return n.count===0?null:d(n)}}),_a="/* eslint-disable */\n// AUTO-GENERATED by `kick typegen`. DO NOT EDIT.\n// Re-run with `kick typegen` or rely on `kick dev` to refresh.\n";function va(e,t,n){if(e.length===0)return`${_a}
3895
- // (no routes discovered yet — annotate a controller method with
3896
- // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
3897
- declare global {
3898
- // eslint-disable-next-line @typescript-eslint/no-namespace
3899
- namespace KickRoutes {}
3900
- }
3901
-
3902
- export {}
3903
- `;let r=new Map;for(let t of e){let e=r.get(t.controller)??[];e.push(t),r.set(t.controller,e)}let i=new Map,a=(e,r)=>{let a=xa(e,r,t,n,i);return a?`import('zod').infer<typeof ${a}>`:null},o=[];for(let[e,t]of r){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=a(e.bodySchema,e.filePath),i=a(e.querySchema,e.filePath),o=a(e.paramsSchema,e.filePath)??t,s=r??`unknown`,c=i??ya(e),l=ba(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${o}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),o.push(n.join(`
3904
- `))}return`${_a}${Sa(i)}
3905
- declare global {
3906
- // eslint-disable-next-line @typescript-eslint/no-namespace
3907
- namespace KickRoutes {
3908
- ${o.join(`
3909
- `)}
3910
- }
3911
- }
3912
-
3913
- export {}
3914
- `}function ya(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function ba(e){let t=[];return e.queryFilterable&&e.queryFilterable.length>0&&t.push(`Filterable: ${e.queryFilterable.join(`, `)}`),e.querySortable&&e.querySortable.length>0&&t.push(`Sortable: ${e.querySortable.join(`, `)}`),e.querySearchable&&e.querySearchable.length>0&&t.push(`Searchable: ${e.querySearchable.join(`, `)}`),t}function xa(e,t,n,r,i){if(!e||r!==`zod`||e.source===null)return null;let a=Ca(e.source,t,n);if(a===`unknown`)return null;let o=`${a}::${e.identifier}`,s=i.get(o)?.specifier;return s?s=i.get(o).specifier:(s=`_S${i.size}`,i.set(o,{identifier:e.identifier,specifier:s})),s}function Sa(e){if(e.size===0)return``;let t=[];for(let[n,r]of e){let[e]=n.split(`::`);t.push(`import type { ${r.identifier} as ${r.specifier} } from '${e}'`)}return t.join(`
3915
- `)+`
3916
- `}function Ca(e,t,n){if(e===null)return`unknown`;let r=x(n);if(e===``){let e=C(r,t).split(oe).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=C(r,w(x(t),e)).split(oe).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const wa=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Ta(e),cwd:e.cwd,envFile:Ea(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=b.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return va(t.routes,r,n)}});function Ta(e){return b.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ea(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Da(e,t){if(!e)return null;let n=C(x(t),e.filePath).split(oe).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),`/* eslint-disable */
3917
- // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
3918
- // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
3919
-
3920
- // Importing the schema as a type lets us infer its shape without
3921
- // pulling in any runtime code. \`Awaited<>\` strips an accidental
3922
- // Promise wrap on dynamic-imported defaults.
3923
- import type _envSchema from '${n}'
3924
-
3925
- // Local type alias — interfaces can only \`extend\` an identifier,
3926
- // not an inline import expression, so we resolve the schema's
3927
- // inferred shape into a named type first.
3928
- type _KickEnvShape = import('zod').infer<typeof _envSchema>
3929
-
3930
- declare global {
3931
- /**
3932
- * Typed environment registry. Augmented from \`${e.relativePath}\`
3933
- * so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
3934
- * all type-safe and autocomplete.
3935
- */
3936
- interface KickEnv extends _KickEnvShape {}
3937
-
3938
- // eslint-disable-next-line @typescript-eslint/no-namespace
3939
- namespace NodeJS {
3940
- /**
3941
- * Narrow \`process.env\` so known keys exist as \`string\` (the raw
3942
- * pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
3943
- * the schema's transforms internally; access \`process.env\` directly
3944
- * only when you need the raw string. Unknown keys still resolve to
3945
- * \`string | undefined\` via the base @types/node declaration.
3946
- */
3947
- interface ProcessEnv extends Record<keyof KickEnv, string> {}
3948
- }
3949
- }
3950
-
3951
- export {}
3952
- `}const Oa=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Aa(e);if(t===!1)return null;let n=await e.getScanResult({root:ka(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=b.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Da(n.env,r)}});function ka(e){return b.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Aa(e){return e.config?.typegen?.envFile}var ja=e({builtinCliPlugins:()=>Ma});const Ma=[o({name:`kick/init`,register:Ft}),o({name:`kick/generate`,register:Wr}),o({name:`kick/run`,register:ri}),o({name:`kick/info`,register:ii}),o({name:`kick/inspect`,register:mi}),o({name:`kick/add`,register:Nt}),o({name:`kick/list`,register:Mt}),o({name:`kick/explain`,register:wi}),o({name:`kick/mcp`,register:Fi}),o({name:`kick/tinker`,register:zi}),o({name:`kick/remove`,register:Gi}),o({name:`kick/typegen`,register:Ji}),o({name:`kick/check`,register:oa}),o({name:`kick/db`,register:la,typegens:[pa()]}),o({name:`kick/codemod`,register:da}),o({name:`kick/assets`,typegens:[ga()]}),o({name:`kick/routes`,typegens:[wa()]}),o({name:`kick/env`,typegens:[Oa()]})];export{Ne as i,ja as n,Jr as r,Ma as t};