@forinda/kickjs-cli 5.2.0 → 5.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtins-BdvmVAJ1.mjs +3740 -0
- package/dist/builtins-Du70nybS.mjs +1066 -0
- package/dist/builtins-Du70nybS.mjs.map +1 -0
- package/dist/cli.mjs +2 -120
- package/dist/config-Dzw8Ws4d.mjs +11 -0
- package/dist/config-lCKbrRnt.mjs +12 -0
- package/dist/{config-DDrgs-I3.mjs.map → config-lCKbrRnt.mjs.map} +1 -1
- package/dist/generator-extension-Cp5FUUAw.mjs +2687 -0
- package/dist/generator-extension-Cp5FUUAw.mjs.map +1 -0
- package/dist/index.mjs +2 -5
- package/dist/plugin-Dv2gKsuC.mjs +11 -0
- package/dist/plugin-VPl_QQGb.mjs +12 -0
- package/dist/{plugin-6_YlK-JG.mjs.map → plugin-VPl_QQGb.mjs.map} +1 -1
- package/dist/rolldown-runtime-B6QC8dMY.mjs +11 -0
- package/dist/{run-plugins-B1R0HG0g.mjs → run-plugins-CM1Af-4B.mjs} +2 -3
- package/dist/typegen-C6ZfoYTC.mjs +114 -0
- package/dist/typegen-CBI7dNXr.mjs +115 -0
- package/dist/{typegen-DugZmi-0.mjs.map → typegen-CBI7dNXr.mjs.map} +1 -1
- package/dist/types-n4LRUF_c.mjs +12 -0
- package/dist/{types-CGB8BiQh.mjs.map → types-n4LRUF_c.mjs.map} +1 -1
- package/package.json +5 -5
- package/dist/builtins-BW3g09hP.mjs +0 -8538
- package/dist/builtins-C_VfEGdg.mjs +0 -4182
- package/dist/builtins-C_VfEGdg.mjs.map +0 -1
- package/dist/config-DDrgs-I3.mjs +0 -171
- package/dist/config-DsQe2yzy.mjs +0 -169
- package/dist/generator-extension-DRNQpoZP.mjs +0 -4380
- package/dist/generator-extension-DRNQpoZP.mjs.map +0 -1
- package/dist/plugin-6_YlK-JG.mjs +0 -71
- package/dist/plugin-CQ0yYXyr.mjs +0 -80
- package/dist/rolldown-runtime-CYBbkZNy.mjs +0 -24
- package/dist/typegen-CYCsmCRF.mjs +0 -1351
- package/dist/typegen-DugZmi-0.mjs +0 -1353
- package/dist/types-CGB8BiQh.mjs +0 -25
|
@@ -0,0 +1,1066 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-cli v5.2.3
|
|
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{A as e,C as t,D as n,E as r,F as i,M as a,N as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as ee,g,h as _,j as v,k as te,l as ne,m as re,n as ie,o as ae,p as oe,s as se,t as ce,u as le,v as ue,w as y,x as b,y as de}from"./generator-extension-Cp5FUUAw.mjs";import{a as x,i as S,o as fe,t as C}from"./config-lCKbrRnt.mjs";import{n as w}from"./types-n4LRUF_c.mjs";import{n as T}from"./plugin-VPl_QQGb.mjs";import{a as pe,i as me,o as he,r as ge,s as _e,t as E}from"./typegen-CBI7dNXr.mjs";import D,{basename as ve,dirname as O,isAbsolute as ye,join as k,relative as A,resolve as j,sep as M}from"node:path";import{cpSync as be,existsSync as N,mkdirSync as P,readFileSync as F,readdirSync as xe,rmSync as Se,statSync as Ce,writeFileSync as we}from"node:fs";import{mkdir as Te,readFile as I,rm as Ee,writeFile as L}from"node:fs/promises";import{execSync as De,fork as Oe,spawn as ke,spawnSync as Ae}from"node:child_process";import{pathToFileURL as R}from"node:url";import{glob as je}from"glob";import{groupAssetKeys as Me}from"@forinda/kickjs";import{arch as Ne,platform as Pe,release as Fe}from"node:os";import{generate as Ie,migrateDown as Le,migrateLatest as Re,migrateRollback as ze,migrateStatus as Be,migrateUp as Ve,renderSchemaSource as He,resolveDbConfig as Ue}from"@forinda/kickjs-db";const We={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 z(e,t=process.cwd()){let n=t;for(;;){if(N(j(n,e)))return n;let t=O(n);if(t===n)return null;n=t}}function Ge(){return z(`pnpm-lock.yaml`)?`pnpm`:z(`yarn.lock`)?`yarn`:z(`bun.lockb`)||z(`bun.lock`)?`bun`:z(`package-lock.json`)?`npm`:null}function Ke(){let e=process.cwd();for(;e;){let t=j(e,`package.json`);if(N(t))try{let e=JSON.parse(F(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(C.includes(t))return t}}catch{}let n=O(e);if(n===e)return null;e=n}return null}async function qe(e){if(e&&C.includes(e))return{pm:e,source:`flag`};let t=await S(process.cwd());if(t?.packageManager&&C.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=Ke();if(n)return{pm:n,source:`package.json`};let r=Ge();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function Je(e){let{pm:t}=await qe(e);return t}function Ye(e=!1){let t=Object.entries(We),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(`
|
|
12
|
+
Core packages (always installed by \`kick new\`):
|
|
13
|
+
`);for(let e of r)console.log(a(e));if(e){console.log(`
|
|
14
|
+
Optional packages (add as needed):
|
|
15
|
+
`);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(`
|
|
16
|
+
Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function Xe(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=>{Ye(!!e.all)})}function Ze(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){Ye(!!t.all);return}let{pm:n,source:r}=await qe(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=We[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.
|
|
17
|
+
`),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{De(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{De(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
|
|
18
|
+
`)}})}const Qe=[{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 $e(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,i)=>{t(`KickJS — Create a new project`);let a=!!(i.yes||i.nonInteractive);e||=a?`my-api`:await te({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let o;if(e===`.`?(o=j(`.`),e=ve(o)):o=j(i.directory||e),N(o)){let t=xe(o);if(t.length>0){if(i.force)y.warn(`Clearing existing files in ${o}`);else if(a){y.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{y.warn(`Directory "${e}" is not empty:`);let n=t.slice(0,5);for(let e of n)y.message(` - ${e}`);if(t.length>5&&y.message(` ... and ${t.length-5} more`),!await l({message:v.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of t)Se(j(o,e),{recursive:!0,force:!0})}}let s=i.template;s||=a?`minimal`:await n({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 c=i.pm;c||=a?await Je(void 0):await n({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let d=i.repo;d||(a?d=`inmemory`:(d=await n({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`}]}),d===`custom`&&(d=await te({message:`Custom repository name`,defaultValue:`custom`}))));let p;if(i.packages!==void 0){let e=i.packages.trim().toLowerCase();p=e===``||e===`none`||e===`false`?[]:i.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else p=a?[]:await u({message:`Select packages to include`,options:[...Qe],required:!1});let m;m=i.git===void 0?a?!0:await l({message:`Initialize git repository?`,initialValue:!0}):i.git;let h;h=i.install===void 0?a?!0:await l({message:`Install dependencies?`,initialValue:!0}):i.install,await f({name:e,directory:o,packageManager:c,initGit:m,installDeps:h,template:s,defaultRepo:d,packages:p}),r(`Done! Next steps: ${v.cyan(`cd ${e} && ${c} dev`)}`)})}async function et(e){let{name:t,outDir:n}=e,r=p(t),a=b(t),o=[],s=k(n,`${r}.plugin.ts`);return await i(s,`import {
|
|
19
|
+
definePlugin,
|
|
20
|
+
type AppAdapter,
|
|
21
|
+
type AppModuleClass,
|
|
22
|
+
type Container,
|
|
23
|
+
type ContributorRegistrations,
|
|
24
|
+
} from '@forinda/kickjs'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Configuration for the ${a} plugin.
|
|
28
|
+
*
|
|
29
|
+
* Plugins typically take a small config object so callers can tune
|
|
30
|
+
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
31
|
+
* derived from the environment should be read inside the build
|
|
32
|
+
* function via getEnv(), not forced onto the caller.
|
|
33
|
+
*/
|
|
34
|
+
export interface ${a}PluginConfig {
|
|
35
|
+
// Add your plugin config here, e.g.:
|
|
36
|
+
// enabled?: boolean
|
|
37
|
+
// apiKey?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* ${a} plugin — built via \`definePlugin()\` so callers get the
|
|
42
|
+
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
43
|
+
*
|
|
44
|
+
* A plugin bundles DI bindings, modules, adapters, and middleware
|
|
45
|
+
* into one object that can be added to \`bootstrap({ plugins })\`.
|
|
46
|
+
*
|
|
47
|
+
* Lifecycle order (each hook is optional — delete the ones you don't
|
|
48
|
+
* need and keep only the surface your plugin actually uses):
|
|
49
|
+
*
|
|
50
|
+
* 1. \`register(container)\` — runs before user modules load. Use
|
|
51
|
+
* it to bind services that modules depend on.
|
|
52
|
+
* 2. \`modules()\` — plugin modules load before user modules.
|
|
53
|
+
* 3. \`adapters()\` — plugin adapters mount before user adapters.
|
|
54
|
+
* 4. \`middleware()\` — plugin middleware runs before user middleware.
|
|
55
|
+
* 5. \`contributors()\` — Context Contributors merged into every route.
|
|
56
|
+
* 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
|
|
57
|
+
* 7. \`shutdown()\` — runs on graceful shutdown.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* \`\`\`ts
|
|
61
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
62
|
+
* import { ${a}Plugin } from './plugins/${r}.plugin'
|
|
63
|
+
*
|
|
64
|
+
* export const app = await bootstrap({
|
|
65
|
+
* modules,
|
|
66
|
+
* plugins: [${a}Plugin({ /* config overrides *\\/ })],
|
|
67
|
+
* })
|
|
68
|
+
* \`\`\`
|
|
69
|
+
*/
|
|
70
|
+
export const ${a}Plugin = definePlugin<${a}PluginConfig>({
|
|
71
|
+
name: '${a}Plugin',
|
|
72
|
+
defaults: {
|
|
73
|
+
// Default config values go here
|
|
74
|
+
},
|
|
75
|
+
build: (_config, { name: _name }) => ({
|
|
76
|
+
/**
|
|
77
|
+
* Register DI bindings before modules load.
|
|
78
|
+
* Use \`container.registerInstance(TOKEN, value)\` for singletons
|
|
79
|
+
* and \`container.registerFactory(TOKEN, () => ...)\` for lazy
|
|
80
|
+
* constructions.
|
|
81
|
+
*/
|
|
82
|
+
register(_container: Container): void {
|
|
83
|
+
// Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Return module classes this plugin contributes to the app.
|
|
88
|
+
* These load before user modules, so plugin controllers and
|
|
89
|
+
* services are available for user code to \`@Autowired\`.
|
|
90
|
+
*/
|
|
91
|
+
modules(): AppModuleClass[] {
|
|
92
|
+
return [
|
|
93
|
+
// ExampleModule,
|
|
94
|
+
]
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Return adapter instances to be added to the application.
|
|
99
|
+
* Plugin adapters mount before user adapters.
|
|
100
|
+
*/
|
|
101
|
+
adapters(): AppAdapter[] {
|
|
102
|
+
return [
|
|
103
|
+
// MyAdapter({ ... }),
|
|
104
|
+
]
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Return Express middleware entries to be added to the global
|
|
109
|
+
* pipeline. Plugin middleware runs before user-defined middleware.
|
|
110
|
+
*/
|
|
111
|
+
middleware(): unknown[] {
|
|
112
|
+
return [
|
|
113
|
+
// helmet(),
|
|
114
|
+
// myCustomMiddleware(_config),
|
|
115
|
+
]
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Return Context Contributors to merge into every route's pipeline.
|
|
120
|
+
* Plugins contribute at the same \`'adapter'\` precedence level as
|
|
121
|
+
* adapters — overrideable per-route at the method / class / module
|
|
122
|
+
* level. See https://forinda.github.io/kick-js/guide/context-decorators
|
|
123
|
+
*
|
|
124
|
+
* Delete this hook if your plugin doesn't ship typed per-request values.
|
|
125
|
+
*/
|
|
126
|
+
contributors(): ContributorRegistrations {
|
|
127
|
+
return [
|
|
128
|
+
// Example:
|
|
129
|
+
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
130
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
|
|
131
|
+
// const Load${a} = defineHttpContextDecorator({
|
|
132
|
+
// key: '${r}',
|
|
133
|
+
// resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
|
|
134
|
+
// })
|
|
135
|
+
// return [Load${a}.registration]
|
|
136
|
+
]
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Called after the application has fully bootstrapped. Use this
|
|
141
|
+
* for post-startup work like logging, health checks, or warming
|
|
142
|
+
* a cache. Runs once per process.
|
|
143
|
+
*/
|
|
144
|
+
async onReady(_container: Container): Promise<void> {
|
|
145
|
+
// const log = _container.resolve(Logger)
|
|
146
|
+
// log.info('${a} plugin ready')
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Called during graceful shutdown. Clean up any long-lived
|
|
151
|
+
* resources this plugin owns (connections, timers, subscriptions).
|
|
152
|
+
*/
|
|
153
|
+
async shutdown(): Promise<void> {
|
|
154
|
+
// Example: await this.connection?.close()
|
|
155
|
+
},
|
|
156
|
+
}),
|
|
157
|
+
})
|
|
158
|
+
`),o.push(s),o}async function tt(e){let t=k(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return N(t)&&!e.force&&!await l({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
159
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await i(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
160
|
+
|
|
161
|
+
export default defineConfig({
|
|
162
|
+
modules: {
|
|
163
|
+
dir: '${n}',
|
|
164
|
+
repo: '${r}',
|
|
165
|
+
pluralize: true,
|
|
166
|
+
},
|
|
167
|
+
|
|
168
|
+
typegen: {
|
|
169
|
+
schemaValidator: 'zod',
|
|
170
|
+
},
|
|
171
|
+
|
|
172
|
+
commands: [
|
|
173
|
+
{
|
|
174
|
+
name: 'test',
|
|
175
|
+
description: 'Run tests with Vitest',
|
|
176
|
+
steps: 'npx vitest run',
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: 'format',
|
|
180
|
+
description: 'Format code with Prettier',
|
|
181
|
+
steps: 'npx prettier --write src/',
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
name: 'format:check',
|
|
185
|
+
description: 'Check formatting without writing',
|
|
186
|
+
steps: 'npx prettier --check src/',
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
name: 'ci:check',
|
|
190
|
+
description: 'Run typecheck + format check',
|
|
191
|
+
steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
|
|
192
|
+
aliases: ['verify'],
|
|
193
|
+
},
|
|
194
|
+
],
|
|
195
|
+
})
|
|
196
|
+
`),[t])}const nt=new Set([`rest`,`ddd`,`cqrs`,`minimal`]);function rt(e,t){if(t)return t;try{let t=JSON.parse(F(k(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function it(e,t){if(t)return t;try{let t=JSON.parse(F(k(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function at(e,t){if(t)return t;try{let t=(await S(e))?.pattern;if(t&&nt.has(t))return t}catch{}return`ddd`}async function ot(e){let t=e.only??`all`,n=rt(e.outDir,e.name),r=it(e.outDir,e.pm),a=await at(e.outDir,e.template),o=t===`agents`||t===`both`||t===`all`,s=t===`claude`||t===`both`||t===`all`,c=t===`skills`||t===`all`,u=[];o&&u.push({file:k(e.outDir,`AGENTS.md`),render:()=>ae(n,a,r)}),s&&u.push({file:k(e.outDir,`CLAUDE.md`),render:()=>se(n,a,r)}),c&&u.push({file:k(e.outDir,`kickjs-skills.md`),render:()=>m(n,a,r)});let d=[];for(let{file:t,render:n}of u){if(N(t)&&!e.force&&!await l({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await i(t,n()),d.push(t)}return d}async function st(e={}){let t=e.strategy??`jwt`,n=e.outDir??`src/modules/auth`,r=k(n,`dto`),a=[],o=k(n,`auth.module.ts`);await i(o,`import { Module } from '@forinda/kickjs'
|
|
197
|
+
import { AuthController } from './auth.controller'
|
|
198
|
+
import { AuthService } from './auth.service'
|
|
199
|
+
|
|
200
|
+
@Module({
|
|
201
|
+
controllers: [AuthController],
|
|
202
|
+
services: [AuthService],
|
|
203
|
+
})
|
|
204
|
+
export class AuthModule {}
|
|
205
|
+
`),a.push(o);let s=k(n,`auth.controller.ts`);await i(s,t===`jwt`?ct():ut()),a.push(s);let c=k(n,`auth.service.ts`);await i(c,t===`jwt`?lt():dt()),a.push(c);let l=k(r,`register.dto.ts`);await i(l,`import { z } from 'zod'
|
|
206
|
+
|
|
207
|
+
export const RegisterDto = z.object({
|
|
208
|
+
email: z.string().email(),
|
|
209
|
+
password: z.string().min(8),
|
|
210
|
+
name: z.string().min(1).optional(),
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
export type RegisterInput = z.infer<typeof RegisterDto>
|
|
214
|
+
`),a.push(l);let u=k(r,`login.dto.ts`);await i(u,`import { z } from 'zod'
|
|
215
|
+
|
|
216
|
+
export const LoginDto = z.object({
|
|
217
|
+
email: z.string().email(),
|
|
218
|
+
password: z.string().min(1),
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
export type LoginInput = z.infer<typeof LoginDto>
|
|
222
|
+
`),a.push(u);let d=k(n,`auth.test.ts`);if(await i(d,`import { describe, it, expect } from 'vitest'
|
|
223
|
+
|
|
224
|
+
describe('Auth Module', () => {
|
|
225
|
+
it.todo('POST /register — creates a new user')
|
|
226
|
+
it.todo('POST /login — returns token for valid credentials')
|
|
227
|
+
it.todo('POST /login — rejects invalid credentials')
|
|
228
|
+
it.todo('POST /logout — invalidates session/token')
|
|
229
|
+
it.todo('GET /me — returns authenticated user')
|
|
230
|
+
})
|
|
231
|
+
`),a.push(d),e.roleGuards!==!1){let e=k(n,`auth.guard.ts`);await i(e,`import { Roles } from '@forinda/kickjs-auth'
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Role-based access guard.
|
|
235
|
+
* Usage: @Roles('admin') on a controller method.
|
|
236
|
+
*
|
|
237
|
+
* The AuthAdapter extracts the user's roles from the JWT/session
|
|
238
|
+
* and the framework checks them automatically.
|
|
239
|
+
*/
|
|
240
|
+
export const AdminOnly = Roles('admin')
|
|
241
|
+
export const ManagerOnly = Roles('manager')
|
|
242
|
+
`),a.push(e)}return a}function ct(){return`import { Controller, Post, Get } from '@forinda/kickjs'
|
|
243
|
+
import { Authenticated, Public } from '@forinda/kickjs-auth'
|
|
244
|
+
import type { RequestContext } from '@forinda/kickjs'
|
|
245
|
+
import { Autowired } from '@forinda/kickjs'
|
|
246
|
+
import { AuthService } from './auth.service'
|
|
247
|
+
|
|
248
|
+
@Controller()
|
|
249
|
+
@Authenticated()
|
|
250
|
+
export class AuthController {
|
|
251
|
+
@Autowired() private authService!: AuthService
|
|
252
|
+
|
|
253
|
+
@Post('/register')
|
|
254
|
+
@Public()
|
|
255
|
+
async register(ctx: RequestContext) {
|
|
256
|
+
const result = await this.authService.register(ctx.body)
|
|
257
|
+
return ctx.created(result)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
@Post('/login')
|
|
261
|
+
@Public()
|
|
262
|
+
async login(ctx: RequestContext) {
|
|
263
|
+
const result = await this.authService.login(ctx.body)
|
|
264
|
+
if (!result) return ctx.badRequest('Invalid credentials')
|
|
265
|
+
return ctx.json(result)
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
@Post('/logout')
|
|
269
|
+
async logout(ctx: RequestContext) {
|
|
270
|
+
return ctx.json({ message: 'Logged out' })
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
@Get('/me')
|
|
274
|
+
async me(ctx: RequestContext) {
|
|
275
|
+
return ctx.json({ user: ctx.user })
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
`}function lt(){return`import { Service, Autowired } from '@forinda/kickjs'
|
|
279
|
+
import { PasswordService } from '@forinda/kickjs-auth'
|
|
280
|
+
import type { RegisterInput } from './dto/register.dto'
|
|
281
|
+
import type { LoginInput } from './dto/login.dto'
|
|
282
|
+
|
|
283
|
+
// TODO: Replace with your User repository
|
|
284
|
+
const users = new Map<string, { id: string; email: string; name?: string; passwordHash: string }>()
|
|
285
|
+
|
|
286
|
+
@Service()
|
|
287
|
+
export class AuthService {
|
|
288
|
+
@Autowired() private password!: PasswordService
|
|
289
|
+
|
|
290
|
+
async register(input: RegisterInput) {
|
|
291
|
+
const { email, password, name } = input
|
|
292
|
+
|
|
293
|
+
if (users.has(email)) {
|
|
294
|
+
throw new Error('User already exists')
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const passwordHash = await this.password.hash(password)
|
|
298
|
+
const id = crypto.randomUUID()
|
|
299
|
+
users.set(email, { id, email, name, passwordHash })
|
|
300
|
+
|
|
301
|
+
return { id, email, name }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async login(input: LoginInput) {
|
|
305
|
+
const { email, password } = input
|
|
306
|
+
const user = users.get(email)
|
|
307
|
+
if (!user) return null
|
|
308
|
+
|
|
309
|
+
const valid = await this.password.verify(user.passwordHash, password)
|
|
310
|
+
if (!valid) return null
|
|
311
|
+
|
|
312
|
+
// TODO: Generate JWT token here
|
|
313
|
+
// const token = jwt.sign({ sub: user.id, email: user.email }, process.env.JWT_SECRET!)
|
|
314
|
+
return { user: { id: user.id, email: user.email, name: user.name } }
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
`}function ut(){return`import { Controller, Post, Get } from '@forinda/kickjs'
|
|
318
|
+
import { Authenticated, Public } from '@forinda/kickjs-auth'
|
|
319
|
+
import { sessionLogin, sessionLogout } from '@forinda/kickjs-auth'
|
|
320
|
+
import type { RequestContext } from '@forinda/kickjs'
|
|
321
|
+
import { Autowired } from '@forinda/kickjs'
|
|
322
|
+
import { AuthService } from './auth.service'
|
|
323
|
+
|
|
324
|
+
@Controller()
|
|
325
|
+
@Authenticated()
|
|
326
|
+
export class AuthController {
|
|
327
|
+
@Autowired() private authService!: AuthService
|
|
328
|
+
|
|
329
|
+
@Post('/register')
|
|
330
|
+
@Public()
|
|
331
|
+
async register(ctx: RequestContext) {
|
|
332
|
+
const result = await this.authService.register(ctx.body)
|
|
333
|
+
return ctx.created(result)
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
@Post('/login')
|
|
337
|
+
@Public()
|
|
338
|
+
async login(ctx: RequestContext) {
|
|
339
|
+
const user = await this.authService.login(ctx.body)
|
|
340
|
+
if (!user) return ctx.badRequest('Invalid credentials')
|
|
341
|
+
await sessionLogin(ctx.session, user)
|
|
342
|
+
return ctx.json({ message: 'Logged in', user })
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
@Post('/logout')
|
|
346
|
+
async logout(ctx: RequestContext) {
|
|
347
|
+
await sessionLogout(ctx.session)
|
|
348
|
+
return ctx.json({ message: 'Logged out' })
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
@Get('/me')
|
|
352
|
+
async me(ctx: RequestContext) {
|
|
353
|
+
return ctx.json({ user: ctx.user })
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
`}function dt(){return`import { Service, Autowired } from '@forinda/kickjs'
|
|
357
|
+
import { PasswordService } from '@forinda/kickjs-auth'
|
|
358
|
+
import type { RegisterInput } from './dto/register.dto'
|
|
359
|
+
import type { LoginInput } from './dto/login.dto'
|
|
360
|
+
|
|
361
|
+
// TODO: Replace with your User repository
|
|
362
|
+
const users = new Map<string, { id: string; email: string; name?: string; passwordHash: string }>()
|
|
363
|
+
|
|
364
|
+
@Service()
|
|
365
|
+
export class AuthService {
|
|
366
|
+
@Autowired() private password!: PasswordService
|
|
367
|
+
|
|
368
|
+
async register(input: RegisterInput) {
|
|
369
|
+
const { email, password, name } = input
|
|
370
|
+
|
|
371
|
+
if (users.has(email)) {
|
|
372
|
+
throw new Error('User already exists')
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const passwordHash = await this.password.hash(password)
|
|
376
|
+
const id = crypto.randomUUID()
|
|
377
|
+
users.set(email, { id, email, name, passwordHash })
|
|
378
|
+
|
|
379
|
+
return { id, email, name }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async login(input: LoginInput) {
|
|
383
|
+
const { email, password } = input
|
|
384
|
+
const user = users.get(email)
|
|
385
|
+
if (!user) return null
|
|
386
|
+
|
|
387
|
+
const valid = await this.password.verify(user.passwordHash, password)
|
|
388
|
+
if (!valid) return null
|
|
389
|
+
|
|
390
|
+
return { id: user.id, email: user.email, name: user.name }
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
`}async function ft(e){let{name:t,outDir:n}=e,r=b(t),a=p(t),o=de(t),s=e.queue??`${a}-queue`,c=[];return await(async(e,t)=>{let r=k(n,e);await i(r,t),c.push(r)})(`${a}.job.ts`,`import { Inject } from '@forinda/kickjs'
|
|
394
|
+
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* ${r} Job Processor
|
|
398
|
+
*
|
|
399
|
+
* Decorators:
|
|
400
|
+
* @Job(queueName) — marks this class as a job processor for a queue
|
|
401
|
+
* @Process(jobName?) — marks a method as the handler for a specific job type
|
|
402
|
+
* - Without a name: handles all jobs in the queue
|
|
403
|
+
* - With a name: handles only jobs matching that name
|
|
404
|
+
*
|
|
405
|
+
* To add jobs to this queue from a service or controller:
|
|
406
|
+
* @Inject(QUEUE_MANAGER) private queue: QueueService
|
|
407
|
+
* await this.queue.add('${s}', '${o}', { ... })
|
|
408
|
+
*/
|
|
409
|
+
@Job('${s}')
|
|
410
|
+
export class ${r}Job {
|
|
411
|
+
@Process()
|
|
412
|
+
async handle(job: { name: string; data: any; id?: string }) {
|
|
413
|
+
console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
|
|
414
|
+
|
|
415
|
+
// TODO: Implement job logic here
|
|
416
|
+
// Example:
|
|
417
|
+
// await this.emailService.send(job.data.to, job.data.subject, job.data.body)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
@Process('${o}.priority')
|
|
421
|
+
async handlePriority(job: { name: string; data: any; id?: string }) {
|
|
422
|
+
console.log(\`Priority job: \${job.name}\`, job.data)
|
|
423
|
+
// Handle high-priority variant of this job
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
`),c}const pt={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 mt(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=pt[a];if(!o){let e=[...Object.keys(pt),`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 ht(e){let{name:t,fields:n,modulesDir:r,noEntity:a,noTests:o,repo:s=`inmemory`,tokenScope:c=`app`}=e,l=e.pluralize!==!1,u=p(t),f=b(t);de(t);let m=l?d(u):u,h=l?ue(f):f,ee=k(r,m),g=[],_=async(e,t)=>{let n=k(ee,e);await i(n,t),g.push(n)};await _(`${u}.module.ts`,Ct(f,u,m)),await _(`constants.ts`,yt(f,n)),await _(`presentation/${u}.controller.ts`,wt(f,u,m,h)),await _(`application/dtos/create-${u}.dto.ts`,gt(f,n)),await _(`application/dtos/update-${u}.dto.ts`,_t(f,n)),await _(`application/dtos/${u}-response.dto.ts`,vt(f,n));let v=Dt(f,u,m,h);for(let e of v)await _(`application/use-cases/${e.file}`,e.content);return await _(`domain/repositories/${u}.repository.ts`,Tt(f,u,c)),await _(`domain/services/${u}-domain.service.ts`,Et(f,u)),s===`inmemory`&&await _(`infrastructure/repositories/in-memory-${u}.repository.ts`,bt(f,u,n)),a||(await _(`domain/entities/${u}.entity.ts`,xt(f,u,n)),await _(`domain/value-objects/${u}-id.vo.ts`,St(f))),await Ot(r,f,m,u),g}function gt(e,t){return`import { z } from 'zod'
|
|
427
|
+
|
|
428
|
+
export const create${e}Schema = z.object({
|
|
429
|
+
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
430
|
+
`)}
|
|
431
|
+
})
|
|
432
|
+
|
|
433
|
+
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
434
|
+
`}function _t(e,t){return`import { z } from 'zod'
|
|
435
|
+
|
|
436
|
+
export const update${e}Schema = z.object({
|
|
437
|
+
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
438
|
+
`)}
|
|
439
|
+
})
|
|
440
|
+
|
|
441
|
+
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
442
|
+
`}function vt(e,t){return`export interface ${e}ResponseDTO {
|
|
443
|
+
id: string
|
|
444
|
+
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
445
|
+
`)}
|
|
446
|
+
createdAt: string
|
|
447
|
+
updatedAt: string
|
|
448
|
+
}
|
|
449
|
+
`}function yt(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'
|
|
450
|
+
|
|
451
|
+
export const ${e.toUpperCase()}_QUERY_CONFIG: ApiQueryParamsConfig = {
|
|
452
|
+
filterable: [${i}],
|
|
453
|
+
sortable: [${a}],
|
|
454
|
+
searchable: [${o}],
|
|
455
|
+
}
|
|
456
|
+
`}function bt(e,t,n){return`import { randomUUID } from 'node:crypto'
|
|
457
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
458
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
459
|
+
import type { I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
460
|
+
import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
|
|
461
|
+
import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
|
|
462
|
+
import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
|
|
463
|
+
|
|
464
|
+
@Repository()
|
|
465
|
+
export class InMemory${e}Repository implements I${e}Repository {
|
|
466
|
+
private store = new Map<string, ${e}ResponseDTO>()
|
|
467
|
+
|
|
468
|
+
async findById(id: string): Promise<${e}ResponseDTO | null> {
|
|
469
|
+
return this.store.get(id) ?? null
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async findAll(): Promise<${e}ResponseDTO[]> {
|
|
473
|
+
return Array.from(this.store.values())
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }> {
|
|
477
|
+
const all = Array.from(this.store.values())
|
|
478
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
479
|
+
return { data, total: all.length }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async create(dto: Create${e}DTO): Promise<${e}ResponseDTO> {
|
|
483
|
+
const now = new Date().toISOString()
|
|
484
|
+
const entity: ${e}ResponseDTO = {
|
|
485
|
+
id: randomUUID(),
|
|
486
|
+
${n.map(e=>` ${e.name}: dto.${e.name},`).join(`
|
|
487
|
+
`)}
|
|
488
|
+
createdAt: now,
|
|
489
|
+
updatedAt: now,
|
|
490
|
+
}
|
|
491
|
+
this.store.set(entity.id, entity)
|
|
492
|
+
return entity
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO> {
|
|
496
|
+
const existing = this.store.get(id)
|
|
497
|
+
if (!existing) throw HttpException.notFound('${e} not found')
|
|
498
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
499
|
+
this.store.set(id, updated)
|
|
500
|
+
return updated
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async delete(id: string): Promise<void> {
|
|
504
|
+
if (!this.store.has(id)) throw HttpException.notFound('${e} not found')
|
|
505
|
+
this.store.delete(id)
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
`}function xt(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
|
|
509
|
+
|
|
510
|
+
interface ${e}Props {
|
|
511
|
+
id: ${e}Id
|
|
512
|
+
${n.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
513
|
+
`)}
|
|
514
|
+
createdAt: Date
|
|
515
|
+
updatedAt: Date
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export class ${e} {
|
|
519
|
+
private constructor(private props: ${e}Props) {}
|
|
520
|
+
|
|
521
|
+
static create(params: { ${n.filter(e=>!e.optional).map(e=>`${e.name}: ${e.tsType}`).join(`; `)} }): ${e} {
|
|
522
|
+
const now = new Date()
|
|
523
|
+
return new ${e}({
|
|
524
|
+
id: ${e}Id.create(),
|
|
525
|
+
${n.filter(e=>!e.optional).map(e=>` ${e.name}: params.${e.name},`).join(`
|
|
526
|
+
`)}
|
|
527
|
+
createdAt: now,
|
|
528
|
+
updatedAt: now,
|
|
529
|
+
})
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
static reconstitute(props: ${e}Props): ${e} {
|
|
533
|
+
return new ${e}(props)
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
get id(): ${e}Id { return this.props.id }
|
|
537
|
+
${n.map(e=>` get ${e.name}(): ${e.tsType}${e.optional?` | undefined`:``} {
|
|
538
|
+
return this.props.${e.name}
|
|
539
|
+
}`).join(`
|
|
540
|
+
`)}
|
|
541
|
+
get createdAt(): Date { return this.props.createdAt }
|
|
542
|
+
get updatedAt(): Date { return this.props.updatedAt }
|
|
543
|
+
|
|
544
|
+
toJSON() {
|
|
545
|
+
return {
|
|
546
|
+
id: this.props.id.toString(),
|
|
547
|
+
${n.map(e=>` ${e.name}: this.props.${e.name},`).join(`
|
|
548
|
+
`)}
|
|
549
|
+
createdAt: this.props.createdAt.toISOString(),
|
|
550
|
+
updatedAt: this.props.updatedAt.toISOString(),
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
`}function St(e){return`import { randomUUID } from 'node:crypto'
|
|
555
|
+
|
|
556
|
+
export class ${e}Id {
|
|
557
|
+
private constructor(private readonly value: string) {}
|
|
558
|
+
|
|
559
|
+
static create(): ${e}Id { return new ${e}Id(randomUUID()) }
|
|
560
|
+
|
|
561
|
+
static from(id: string): ${e}Id {
|
|
562
|
+
if (!id || id.trim().length === 0) throw new Error('${e}Id cannot be empty')
|
|
563
|
+
return new ${e}Id(id)
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
toString(): string { return this.value }
|
|
567
|
+
equals(other: ${e}Id): boolean { return this.value === other.value }
|
|
568
|
+
}
|
|
569
|
+
`}function Ct(e,t,n){return`import { type AppModule, type ModuleRoutes, Container, buildRoutes } from '@forinda/kickjs'
|
|
570
|
+
import { ${e}Controller } from './presentation/${t}.controller'
|
|
571
|
+
import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
|
|
572
|
+
import { InMemory${e}Repository } from './infrastructure/repositories/in-memory-${t}.repository'
|
|
573
|
+
|
|
574
|
+
// Eagerly load decorated classes so @Service()/@Repository() decorators
|
|
575
|
+
// register in the DI container before the application bootstraps.
|
|
576
|
+
import.meta.glob(
|
|
577
|
+
['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
|
|
578
|
+
{ eager: true },
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
export class ${e}Module implements AppModule {
|
|
582
|
+
/**
|
|
583
|
+
* Bind the repository token to its concrete implementation.
|
|
584
|
+
* Decorator-managed classes (@Service, @Controller, @Repository) are
|
|
585
|
+
* registered automatically — only token-to-impl bindings need to live here.
|
|
586
|
+
*/
|
|
587
|
+
register(container: Container): void {
|
|
588
|
+
container.registerFactory(
|
|
589
|
+
${e.toUpperCase()}_REPOSITORY,
|
|
590
|
+
() => container.resolve(InMemory${e}Repository),
|
|
591
|
+
)
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
routes(): ModuleRoutes {
|
|
595
|
+
return {
|
|
596
|
+
path: '/${n}',
|
|
597
|
+
router: buildRoutes(${e}Controller),
|
|
598
|
+
controller: ${e}Controller,
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
`}function wt(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
603
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
604
|
+
import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
|
|
605
|
+
import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
|
|
606
|
+
import { List${r}UseCase } from '../application/use-cases/list-${n}.use-case'
|
|
607
|
+
import { Update${e}UseCase } from '../application/use-cases/update-${t}.use-case'
|
|
608
|
+
import { Delete${e}UseCase } from '../application/use-cases/delete-${t}.use-case'
|
|
609
|
+
import { create${e}Schema } from '../application/dtos/create-${t}.dto'
|
|
610
|
+
import { update${e}Schema } from '../application/dtos/update-${t}.dto'
|
|
611
|
+
import { ${e.toUpperCase()}_QUERY_CONFIG } from '../constants'
|
|
612
|
+
|
|
613
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${e}Controller['<method>']>\`
|
|
614
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
615
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
616
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
617
|
+
|
|
618
|
+
@Controller()
|
|
619
|
+
export class ${e}Controller {
|
|
620
|
+
@Autowired() private readonly create${e}UseCase!: Create${e}UseCase
|
|
621
|
+
@Autowired() private readonly get${e}UseCase!: Get${e}UseCase
|
|
622
|
+
@Autowired() private readonly list${r}UseCase!: List${r}UseCase
|
|
623
|
+
@Autowired() private readonly update${e}UseCase!: Update${e}UseCase
|
|
624
|
+
@Autowired() private readonly delete${e}UseCase!: Delete${e}UseCase
|
|
625
|
+
|
|
626
|
+
@Get('/')
|
|
627
|
+
@ApiTags('${e}')
|
|
628
|
+
@ApiQueryParams(${e.toUpperCase()}_QUERY_CONFIG)
|
|
629
|
+
async list(ctx: Ctx<KickRoutes.${e}Controller['list']>) {
|
|
630
|
+
return ctx.paginate(
|
|
631
|
+
(parsed) => this.list${r}UseCase.execute(parsed),
|
|
632
|
+
${e.toUpperCase()}_QUERY_CONFIG,
|
|
633
|
+
)
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
@Get('/:id')
|
|
637
|
+
@ApiTags('${e}')
|
|
638
|
+
async getById(ctx: Ctx<KickRoutes.${e}Controller['getById']>) {
|
|
639
|
+
const result = await this.get${e}UseCase.execute(ctx.params.id)
|
|
640
|
+
if (!result) return ctx.notFound('${e} not found')
|
|
641
|
+
ctx.json(result)
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
@Post('/', { body: create${e}Schema, name: 'Create${e}' })
|
|
645
|
+
@ApiTags('${e}')
|
|
646
|
+
async create(ctx: Ctx<KickRoutes.${e}Controller['create']>) {
|
|
647
|
+
const result = await this.create${e}UseCase.execute(ctx.body)
|
|
648
|
+
ctx.created(result)
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
@Put('/:id', { body: update${e}Schema, name: 'Update${e}' })
|
|
652
|
+
@ApiTags('${e}')
|
|
653
|
+
async update(ctx: Ctx<KickRoutes.${e}Controller['update']>) {
|
|
654
|
+
const result = await this.update${e}UseCase.execute(ctx.params.id, ctx.body)
|
|
655
|
+
ctx.json(result)
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
@Delete('/:id')
|
|
659
|
+
@ApiTags('${e}')
|
|
660
|
+
async remove(ctx: Ctx<KickRoutes.${e}Controller['remove']>) {
|
|
661
|
+
await this.delete${e}UseCase.execute(ctx.params.id)
|
|
662
|
+
ctx.noContent()
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
`}function Tt(e,t,n){return`import { createToken } from '@forinda/kickjs'
|
|
666
|
+
import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
|
|
667
|
+
import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
|
|
668
|
+
import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
|
|
669
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
670
|
+
|
|
671
|
+
export interface I${e}Repository {
|
|
672
|
+
findById(id: string): Promise<${e}ResponseDTO | null>
|
|
673
|
+
findAll(): Promise<${e}ResponseDTO[]>
|
|
674
|
+
findPaginated(parsed: ParsedQuery): Promise<{ data: ${e}ResponseDTO[]; total: number }>
|
|
675
|
+
create(dto: Create${e}DTO): Promise<${e}ResponseDTO>
|
|
676
|
+
update(id: string, dto: Update${e}DTO): Promise<${e}ResponseDTO>
|
|
677
|
+
delete(id: string): Promise<void>
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Collision-safe DI token bound to \`I${e}Repository\`.
|
|
682
|
+
* \`container.resolve(${e.toUpperCase()}_REPOSITORY)\` and
|
|
683
|
+
* \`@Inject(${e.toUpperCase()}_REPOSITORY)\` both return the typed
|
|
684
|
+
* interface — no manual generic, no \`any\` cast.
|
|
685
|
+
*
|
|
686
|
+
* The \`'${n}/'\` prefix matches the project scope so
|
|
687
|
+
* \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
|
|
688
|
+
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
689
|
+
*/
|
|
690
|
+
export const ${e.toUpperCase()}_REPOSITORY = createToken<I${e}Repository>('${n}/${e}/repository')
|
|
691
|
+
`}function Et(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
692
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
|
|
693
|
+
|
|
694
|
+
@Service()
|
|
695
|
+
export class ${e}DomainService {
|
|
696
|
+
constructor(
|
|
697
|
+
@Inject(${e.toUpperCase()}_REPOSITORY) private readonly repo: I${e}Repository,
|
|
698
|
+
) {}
|
|
699
|
+
|
|
700
|
+
async ensureExists(id: string): Promise<void> {
|
|
701
|
+
const entity = await this.repo.findById(id)
|
|
702
|
+
if (!entity) throw HttpException.notFound('${e} not found')
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
`}function Dt(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
706
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
707
|
+
import type { Create${e}DTO } from '../dtos/create-${t}.dto'
|
|
708
|
+
|
|
709
|
+
@Service()
|
|
710
|
+
export class Create${e}UseCase {
|
|
711
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
712
|
+
async execute(dto: Create${e}DTO) { return this.repo.create(dto) }
|
|
713
|
+
}
|
|
714
|
+
`},{file:`get-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
715
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
716
|
+
|
|
717
|
+
@Service()
|
|
718
|
+
export class Get${e}UseCase {
|
|
719
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
720
|
+
async execute(id: string) { return this.repo.findById(id) }
|
|
721
|
+
}
|
|
722
|
+
`},{file:`list-${n}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
723
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
724
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
725
|
+
|
|
726
|
+
@Service()
|
|
727
|
+
export class List${r}UseCase {
|
|
728
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
729
|
+
async execute(parsed: ParsedQuery) { return this.repo.findPaginated(parsed) }
|
|
730
|
+
}
|
|
731
|
+
`},{file:`update-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
732
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
733
|
+
import type { Update${e}DTO } from '../dtos/update-${t}.dto'
|
|
734
|
+
|
|
735
|
+
@Service()
|
|
736
|
+
export class Update${e}UseCase {
|
|
737
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
738
|
+
async execute(id: string, dto: Update${e}DTO) { return this.repo.update(id, dto) }
|
|
739
|
+
}
|
|
740
|
+
`},{file:`delete-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
|
|
741
|
+
import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
|
|
742
|
+
|
|
743
|
+
@Service()
|
|
744
|
+
export class Delete${e}UseCase {
|
|
745
|
+
constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
|
|
746
|
+
async execute(id: string) { return this.repo.delete(id) }
|
|
747
|
+
}
|
|
748
|
+
`}]}async function Ot(e,t,n,r){let a=k(e,`index.ts`),s=await o(a),c=`./${n}/${r}.module`;if(!s){await i(a,`import type { AppModuleClass } from '@forinda/kickjs'\nimport { ${t}Module } from '${c}'\n\nexport const modules: AppModuleClass[] = [${t}Module]\n`);return}let l=await I(a,`utf-8`),u=`import { ${t}Module } from '${c}'`;if(!l.includes(`${t}Module`)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
|
|
749
|
+
`,e);l=l.slice(0,t+1)+u+`
|
|
750
|
+
`+l.slice(t+1)}else l=u+`
|
|
751
|
+
`+l;l=l.replace(/(=\s*\[)([\s\S]*?)(])/,(e,n,r,i)=>{let a=r.trim();if(!a)return`${n}${t}Module${i}`;let o=a.endsWith(`,`)?``:`,`;return`${n}${r.trimEnd()}${o} ${t}Module${i}`})}await L(a,l,`utf-8`)}async function kt(e){let{name:t,moduleName:n,modulesDir:r}=e,a=e.pluralize??!0,o=p(t),s=b(t),c=[],l;if(e.outDir)l=j(e.outDir);else if(n){let e=p(n),t=a?d(e):e;l=j(k(r??`src/modules`,t,`__tests__`))}else l=j(`src/__tests__`);let u=k(l,`${o}.test.ts`);return await i(u,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
752
|
+
import { Container } from '@forinda/kickjs'
|
|
753
|
+
|
|
754
|
+
describe('${s}', () => {
|
|
755
|
+
beforeEach(() => {
|
|
756
|
+
Container.reset()
|
|
757
|
+
})
|
|
758
|
+
|
|
759
|
+
it('should be defined', () => {
|
|
760
|
+
// TODO: Import and test your class/function here
|
|
761
|
+
expect(true).toBe(true)
|
|
762
|
+
})
|
|
763
|
+
|
|
764
|
+
it('should handle the happy path', async () => {
|
|
765
|
+
// TODO: Set up test data and assertions
|
|
766
|
+
expect(true).toBe(true)
|
|
767
|
+
})
|
|
768
|
+
|
|
769
|
+
it('should handle edge cases', async () => {
|
|
770
|
+
// TODO: Test error handling, empty inputs, etc.
|
|
771
|
+
expect(true).toBe(true)
|
|
772
|
+
})
|
|
773
|
+
})
|
|
774
|
+
`),c.push(u),c}const At=[`agents`,`claude`,`skills`,`both`,`all`];function B(e){return e.parent?.opts()?.dryRun??!1}function V(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(`
|
|
775
|
+
(dry run — no files were written)`),console.log()}async function H(e){if(!e)try{let e=await S(process.cwd());await E({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 jt=[{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 Mt(){console.log(`
|
|
776
|
+
Built-in generators:
|
|
777
|
+
`);let e=Math.max(...jt.map(e=>e.name.length));for(let t of jt)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await S(process.cwd()),n=T(t?.plugins??[],t?.commands??[]),r=await ce(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
778
|
+
Plugin generators:
|
|
779
|
+
`);let e=Math.max(...r.generators.map(e=>`${e.spec.name} <name>`.length));for(let{source:t,spec:n}of r.generators){let r=`${n.name} <name>`;console.log(` kick g ${r.padEnd(e+2)} ${n.description} [${t}]`)}}if(r.failed.length>0){console.log(`
|
|
780
|
+
Failed to load:
|
|
781
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Nt(e,t,n){let r=await S(process.cwd()),i=x(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??g(i.repo),s=t.pattern??r?.pattern??`ddd`,c=t.pluralize===!1?!1:i.pluralize??!0,l=fe(r,process.cwd()),u=[];for(let r of e){let e=await _({name:r,modulesDir:j(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,dryRun:n,pluralize:c,prismaClientPath:i.prismaClientPath,tokenScope:l});u.push(...e)}V(u,n),await H(n)}function Pt(e){let t=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,n,r)=>{if(n.list){await Mt();return}if(!e||e.length===0){t.help();return}let i=B(r);if(c(i),e.length>=2){let[t,r,...a]=e,o=await S(process.cwd()),s=T(o?.plugins??[],o?.commands??[]),c=await ie({generatorName:t,itemName:r,args:a,flags:n,cwd:process.cwd()},s.generators);if(c){V(c.files,i);return}}await Nt(e,n,i)});t.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=B(n);c(r),await Nt(e,t,r)}),t.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=B(n);c(r),V(await re({name:e,outDir:j(t.out)}),r)}),t.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=B(n);c(r),V(await et({name:e,outDir:j(t.out)}),r)}),t.command(`middleware <name>`).description(`Generate an Express middleware function
|
|
782
|
+
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,n)=>{let r=B(n);c(r);let i=await S(process.cwd()),a=x(i),o=a.dir??`src/modules`;V(await oe({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
783
|
+
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,n)=>{let r=B(n);c(r);let i=await S(process.cwd()),a=x(i),o=a.dir??`src/modules`;V(await ee({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`service <name>`).description(`Generate a @Service() class
|
|
784
|
+
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,n)=>{let r=B(n);c(r);let i=await S(process.cwd()),a=x(i),o=a.dir??`src/modules`;V(await h({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
785
|
+
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,n)=>{let r=B(n);c(r);let i=await S(process.cwd()),a=x(i),o=a.dir??`src/modules`;V(await le({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await H(r)}),t.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
786
|
+
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,n)=>{let r=B(n);c(r);let i=await S(process.cwd()),a=x(i),o=a.dir??`src/modules`;V(await ne({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
787
|
+
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,n)=>{let r=B(n);c(r);let i=x(await S(process.cwd())),a=i.dir??`src/modules`;V(await kt({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),t.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=B(n);c(r),V(await ft({name:e,outDir:j(t.out),queue:t.queue}),r)}),t.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
788
|
+
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
789
|
+
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
790
|
+
Optional: append :optional (shell-safe): description:text:optional
|
|
791
|
+
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,t,n,r)=>{let i=B(r);c(i),t.length===0&&(console.error(`
|
|
792
|
+
Error: At least one field is required.
|
|
793
|
+
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
794
|
+
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
795
|
+
Optional: append :optional (shell-safe, no quoting needed)
|
|
796
|
+
`),process.exit(1));let a=await S(process.cwd()),o=x(a),s=n.modulesDir??o.dir??`src/modules`,l=mt(t),u=fe(a,process.cwd()),d=await ht({name:e,fields:l,modulesDir:j(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:u});console.log(`\n Scaffolded ${e} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);V(d,i),await H(i)}),t.command(`auth-scaffold`).description(`Generate a complete auth module (register, login, logout, password hashing)
|
|
797
|
+
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 r=B(t);c(r);let i=e.strategy;i||=await n({message:`Auth strategy`,options:[{value:`jwt`,label:`JWT`,hint:`stateless token-based auth`},{value:`session`,label:`Session`,hint:`server-side session with cookies`}]});let a=e.roleGuards;a===void 0&&(a=await l({message:`Generate role-based guards?`,initialValue:!0})),V(await st({strategy:i,outDir:e.out,roleGuards:a}),r)}),t.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=B(t);c(n),V(await tt({outDir:j(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),t.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=B(t);c(n);let r=e.only??`all`;if(!At.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${At.join(` | `)}`),process.exitCode=1;return}V(await ot({outDir:j(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)})}function Ft(e,t,n){let r=Ae(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}async function It(e){let t=D.resolve(e.cwd,`.kickjs/types`);await Te(t,{recursive:!0});let n=new Map,r=e.scan??_e,i={cwd:e.cwd,config:e.config,async importTs(e){return await import(R(e).href)},async writeFile(t,n){let r=D.resolve(e.cwd,t);await Te(D.dirname(r),{recursive:!0}),await L(r,n,`utf8`)},getScanResult:e=>{let t=Lt(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=D.join(t,`${n.id.replace(/\//g,`__`)}${o}`),c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+r+`
|
|
798
|
+
`,l=``;if(N(s)&&(l=await I(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 L(s,c,`utf8`),a.push({id:n.id,status:`written`,outFile:s})}return a}function Lt(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 Rt(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))}}async function U(e){let{enabled:t,skipped:n,unknown:r}=Rt(T([...dr,...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 It({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 zt(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=j(n,i);P(s,{recursive:!0});let c=[],l={};for(let[e,t]of Object.entries(a)){let r=await Bt(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=k(s,`.kickjs-assets.json`);return we(d,JSON.stringify(u,null,2)+`
|
|
799
|
+
`,`utf-8`),o(` ✓ wrote manifest → ${A(n,d)} (${Object.keys(l).length} entries)`),{manifestPath:d,entries:c,manifest:u}}async function Bt(e,t,n,r){let i=j(n,t.src),a=t.dest?j(n,t.dest):k(r,e);if(Ht(a,n))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:0},manifestSlice:{}};if(!N(i)||!Ut(i))return{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:0},manifestSlice:{}};let o=await je(t.glob??`**/*`,{cwd:i,nodir:!0,dot:!1,posix:!0});P(a,{recursive:!0});let s={},{pairs:c,collisionGroupsResolved:l}=Me(e,[...o].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of c){let n=k(i,e),o=k(a,e);P(O(o),{recursive:!0}),be(n,o),s[t]=Vt(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:A(n,a),filesCopied:o.length},manifestSlice:s}}function Vt(e,t){return A(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function Ht(e,t){let n=A(t,e);return n===``?!1:n.startsWith(`..`)||ye(n)}function Ut(e){try{return Ce(e).isDirectory()}catch{return!1}}function Wt(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Gt(e,t,n={}){t&&(process.env.PORT=t);let r=Wt(n.polling),i=process.cwd(),a=await S(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await E({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}await U({cwd:i,config:a});let{createRequire:c}=await import(`node:module`),{createServer:l}=await import(R(c(j(`package.json`)).resolve(`vite`)).href),u=await l({configFile:j(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),d=a?.assetMap?Object.values(a.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>j(i,e)):[],f=e=>d.some(t=>e===t||e.startsWith(`${t}/`)),p=null,m=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=f(e);!t&&!n||(p&&clearTimeout(p),p=setTimeout(()=>{E({cwd:i,silent:!0,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1}).catch(()=>{}),U({cwd:i,config:a,silent:!0}).catch(()=>{})},100))};u.watcher.on(`add`,m),u.watcher.on(`unlink`,m),u.watcher.on(`change`,m),d.length>0&&u.watcher.add(d),await u.listen(),u.printUrls(),console.log(`
|
|
800
|
+
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
801
|
+
`);let h=async()=>{p&&clearTimeout(p),await u.close(),process.exit(0)};process.on(`SIGINT`,h),process.on(`SIGTERM`,h)}function Kt(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 Gt(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
802
|
+
Error: vite is not installed.
|
|
803
|
+
Run: pnpm add -D vite unplugin-swc
|
|
804
|
+
`):console.error(`
|
|
805
|
+
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
806
|
+
Building for production...
|
|
807
|
+
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(R(e(j(`package.json`)).resolve(`vite`)).href);await t({configFile:j(`vite.config.ts`)});let n=await S(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
|
|
808
|
+
Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?k(`dist`,e):e.dest??k(`dist`,t),r=j(t),i=j(n);if(!N(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}P(i,{recursive:!0}),be(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
|
|
809
|
+
Building asset map...`);try{await zt(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
810
|
+
Build complete.
|
|
811
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await S(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
812
|
+
Building asset map...`);try{await zt(e,{cwd:process.cwd()}),console.log(`
|
|
813
|
+
Asset build complete.
|
|
814
|
+
`)}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)),Ft(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 Gt(e.entry,e.port)}catch(e){console.error(`
|
|
815
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function qt(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
|
|
816
|
+
KickJS CLI
|
|
817
|
+
|
|
818
|
+
System:
|
|
819
|
+
OS: ${Pe()} ${Fe()} (${Ne()})
|
|
820
|
+
Node: ${process.version}
|
|
821
|
+
|
|
822
|
+
Packages:
|
|
823
|
+
@forinda/kickjs workspace
|
|
824
|
+
@forinda/kickjs-vite workspace
|
|
825
|
+
@forinda/kickjs-cli workspace
|
|
826
|
+
`)})}const{bold:W,dim:G,green:Jt,red:K,yellow:Yt,blue:Xt}=v;function Zt(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 Qt(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function q(e,t){try{return await Qt(`${e}${t}`)}catch{return null}}async function $t(e){let[t,n,r,i,a]=await Promise.all([q(e,`/health`),q(e,`/metrics`),q(e,`/routes`),q(e,`/container`),q(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function en(t,n){let{health:r,metrics:i,routes:a,container:o,ws:s}=n,c=G(`─`.repeat(60));if(console.log(),console.log(W(` KickJS Inspector`)+G(` → ${t}`)),console.log(c),r){let e=r.status===`healthy`?Jt(`● healthy`):K(`● `+r.status);console.log(` ${W(`Health:`)} ${e}`)}else console.log(` ${W(`Health:`)} ${K(`● unreachable`)}`);if(i){let e=((i.errorRate??0)*100).toFixed(1),t=i.errorRate>.1?K:i.errorRate>0?Yt:Jt;console.log(` ${W(`Uptime:`)} ${Zt(i.uptimeSeconds)}`),console.log(` ${W(`Requests:`)} ${i.requests}`),console.log(` ${W(`Errors:`)} ${i.serverErrors} server, ${i.clientErrors??0} client ${G(`(`)}${t(e+`%`)}${G(`)`)}`)}if(o&&console.log(` ${W(`DI:`)} ${o.count} bindings`),s&&s.enabled&&console.log(` ${W(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),a?.routes?.length){console.log(),console.log(W(` Routes`)),console.log(c),console.log(` ${G(`METHOD`)} ${G(`PATH`.padEnd(36))} ${G(`CONTROLLER`)}`);for(let t of a.routes){let n=t.path.length>36?t.path.slice(0,33)+`...`:t.path.padEnd(36);console.log(` ${e(t.method)} ${n} ${Xt(t.controller)}.${G(t.handler)}`)}}console.log(c),console.log()}function tn(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 $t(r);t.json?console.log(JSON.stringify(e,null,2)):en(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(K(` ✖ Could not connect to ${n}`)),console.error(G(` ${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 J(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Y(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const nn=[{match(e,t){let n=J(e,[`config`,`get`])&&Y(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Y(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
|
|
827
|
+
registers the env schema with kickjs at module-load time. Without it,
|
|
828
|
+
ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
|
|
829
|
+
and every user-defined key reads as undefined. @Value() may *appear* to
|
|
830
|
+
work via a raw process.env fallback, but Zod coercion and schema defaults
|
|
831
|
+
are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
|
|
832
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
833
|
+
import { modules } from './modules'
|
|
834
|
+
`,codeAfter:`import 'reflect-metadata'
|
|
835
|
+
import './config' // ← add this — registers env schema
|
|
836
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
837
|
+
import { modules } from './modules'
|
|
838
|
+
`,docs:`https://forinda.github.io/kick-js/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Y(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return Y(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.
|
|
839
|
+
When vitest re-imports your modules across tests, the same class can be
|
|
840
|
+
registered twice and the container throws. The fix is to wipe the
|
|
841
|
+
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'
|
|
842
|
+
import { Container } from '@forinda/kickjs'
|
|
843
|
+
|
|
844
|
+
describe('UserController', () => {
|
|
845
|
+
beforeEach(() => Container.reset())
|
|
846
|
+
|
|
847
|
+
it('does the thing', async () => { /* ... */ })
|
|
848
|
+
})`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||J(e,[`Module`,`is not a function`])||J(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
|
|
849
|
+
pattern instead: a class implements AppModule and exposes routes() that
|
|
850
|
+
returns the controller wiring. This was a deliberate choice — modules
|
|
851
|
+
become explicit values rather than metadata, which makes them easier to
|
|
852
|
+
compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
|
|
853
|
+
import { UserController } from './user.controller'
|
|
854
|
+
|
|
855
|
+
@Module({
|
|
856
|
+
controllers: [UserController],
|
|
857
|
+
})
|
|
858
|
+
export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
|
|
859
|
+
import { UserController } from './user.controller'
|
|
860
|
+
|
|
861
|
+
export class UserModule implements AppModule {
|
|
862
|
+
routes(): ModuleRoutes {
|
|
863
|
+
return {
|
|
864
|
+
path: '/users',
|
|
865
|
+
router: buildRoutes(UserController),
|
|
866
|
+
controller: UserController,
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}`,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
|
|
870
|
+
namespaced shape: KickRoutes.UserController["create"] instead of
|
|
871
|
+
KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
872
|
+
and matches the actual class names so refactors propagate via
|
|
873
|
+
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
874
|
+
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
875
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://forinda.github.io/kick-js/guide/typegen.html`}}:null}},{match(e,t){let n=Y(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Y(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
|
|
876
|
+
cluster: { workers: N }, the framework forks N workers, each of which
|
|
877
|
+
spins up its own Vite instance on a separate port. The fix landed in
|
|
878
|
+
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
879
|
+
silently skips cluster, with a warning. If you see this on an older
|
|
880
|
+
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({
|
|
881
|
+
modules,
|
|
882
|
+
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
883
|
+
})`,docs:`https://forinda.github.io/kick-js/guide/cluster.html`}}}},{match(e,t){return Y(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
|
|
884
|
+
reflect-metadata polyfill. The polyfill must be imported once,
|
|
885
|
+
before any decorator runs. Most projects do this at the top of
|
|
886
|
+
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
887
|
+
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
|
|
888
|
+
import './config'
|
|
889
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
890
|
+
import { modules } from './modules'
|
|
891
|
+
|
|
892
|
+
export const app = await bootstrap({ modules })`,docs:`https://forinda.github.io/kick-js/guide/dependency-injection.html`}}:null}},{match(e,t){return Y(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
|
|
893
|
+
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
894
|
+
the most likely cause is that the module is missing from the exported
|
|
895
|
+
array. The CLI usually wires this automatically, but a hand-edit can
|
|
896
|
+
drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleClass } from '@forinda/kickjs'
|
|
897
|
+
import { UserModule } from './users/user.module'
|
|
898
|
+
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
899
|
+
|
|
900
|
+
export const modules: AppModuleClass[] = [UserModule, TaskModule]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function rn(e,t){let n=null;for(let r of nn){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 an(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.
|
|
901
|
+
export OPENAI_API_KEY="sk-..."
|
|
902
|
+
|
|
903
|
+
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:
|
|
904
|
+
kick add ai
|
|
905
|
+
|
|
906
|
+
Or manually:
|
|
907
|
+
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=on(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=sn((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 on(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(`
|
|
908
|
+
`)}function sn(e){let t=[e,cn(e),ln(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(un(t))return t}catch{continue}return null}function cn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function ln(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 un(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 dn(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 mn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
909
|
+
|
|
910
|
+
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
911
|
+
kick explain "config.get returned undefined"
|
|
912
|
+
pnpm test 2>&1 | kick explain
|
|
913
|
+
`),process.exit(1));let r=gn(),i=rn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
914
|
+
`);return}if(i){_n(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
915
|
+
`),process.exit(2)),vn(n,!1),process.exit(2));let a=await an({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(fn(a),null,2)+`
|
|
916
|
+
`),process.exit(a.kind===`ok`?0:2)),pn(n,a),process.exit(a.kind===`ok`?0:2)})}function fn(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 pn(e,t){if(t.kind===`ok`){_n(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${X(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function mn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:hn()}function hn(){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 gn(){let e=process.cwd();return{cwd:e,hasFile:t=>N(j(e,t))}}function _n(e,t,n,r=!1){let i=Z(e.trim(),200),a=r?`AI-generated — verify before applying`:yn(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${X(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${X(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${X(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${X(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
917
|
+
`)}function vn(e,t){let n=Z(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.
|
|
918
|
+
When @forinda/kickjs-ai ships its provider implementations,
|
|
919
|
+
this command will call the configured LLM with the error +
|
|
920
|
+
project context and return a structured fix.
|
|
921
|
+
|
|
922
|
+
`):process.stdout.write(` No known-issue matched. Things you can try:
|
|
923
|
+
|
|
924
|
+
1. Check the framework docs for the error keywords:
|
|
925
|
+
https://forinda.github.io/kick-js/
|
|
926
|
+
|
|
927
|
+
2. Re-run with --ai to fall back to an LLM (requires
|
|
928
|
+
@forinda/kickjs-ai with a configured provider):
|
|
929
|
+
kick explain --ai "<your error>"
|
|
930
|
+
|
|
931
|
+
3. File an issue with the error text:
|
|
932
|
+
https://github.com/forinda/kick-js/issues/new
|
|
933
|
+
|
|
934
|
+
`)}function X(e,t){return e.split(`
|
|
935
|
+
`).map(e=>`${t}${e}`).join(`
|
|
936
|
+
`)}function Z(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function yn(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function bn(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(xn),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(Sn)}function xn(e){let t=j(e.entry);N(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=ke(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 Sn(e){let t=process.cwd(),n=Cn(t)??ve(t),r=e.name??n,i=e.global?j(process.env.HOME??`.`,`.mcp.json`):j(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(N(i))try{let e=F(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,we(i,JSON.stringify(o,null,2)+`
|
|
937
|
+
`,`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 Cn(e){let t=j(e,`package.json`);if(!N(t))return null;try{let e=F(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function wn(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=j(t,e.entry);N(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=En(t,`tsx`);r||(console.error(`
|
|
938
|
+
Error: tsx not found. Install it: pnpm add -D tsx
|
|
939
|
+
`),process.exit(1));let i=Tn(n,e.entry),a=k(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Oe(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Tn(e,t){return`
|
|
940
|
+
import 'reflect-metadata'
|
|
941
|
+
|
|
942
|
+
// Prevent bootstrap() from starting the HTTP server
|
|
943
|
+
process.env.KICK_TINKER = '1'
|
|
944
|
+
|
|
945
|
+
console.log('\\n 🔧 KickJS Tinker')
|
|
946
|
+
console.log(' Loading: ${t}\\n')
|
|
947
|
+
|
|
948
|
+
// Load core
|
|
949
|
+
let Container, Logger, HttpException, HttpStatus
|
|
950
|
+
try {
|
|
951
|
+
const core = await import('@forinda/kickjs')
|
|
952
|
+
Container = core.Container
|
|
953
|
+
Logger = core.Logger
|
|
954
|
+
HttpException = core.HttpException
|
|
955
|
+
HttpStatus = core.HttpStatus
|
|
956
|
+
} catch {
|
|
957
|
+
console.error(' Error: @forinda/kickjs not found.')
|
|
958
|
+
console.error(' Install it: pnpm add @forinda/kickjs\\n')
|
|
959
|
+
process.exit(1)
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
// Load entry to trigger decorator registration
|
|
963
|
+
try {
|
|
964
|
+
await import('${R(e).href}')
|
|
965
|
+
} catch (err) {
|
|
966
|
+
console.warn(' Warning: ' + err.message)
|
|
967
|
+
console.warn(' Container may be partially initialized.\\n')
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
const container = Container.getInstance()
|
|
971
|
+
|
|
972
|
+
// Start REPL
|
|
973
|
+
const repl = await import('node:repl')
|
|
974
|
+
const server = repl.start({ prompt: 'kick> ', useGlobal: true })
|
|
975
|
+
|
|
976
|
+
server.context.container = container
|
|
977
|
+
server.context.Container = Container
|
|
978
|
+
server.context.resolve = (token) => container.resolve(token)
|
|
979
|
+
server.context.Logger = Logger
|
|
980
|
+
server.context.HttpException = HttpException
|
|
981
|
+
server.context.HttpStatus = HttpStatus
|
|
982
|
+
|
|
983
|
+
console.log(' Available globals:')
|
|
984
|
+
console.log(' container — DI container instance')
|
|
985
|
+
console.log(' resolve(T) — shorthand for container.resolve(T)')
|
|
986
|
+
console.log(' Container, Logger, HttpException, HttpStatus')
|
|
987
|
+
console.log()
|
|
988
|
+
|
|
989
|
+
server.on('exit', () => {
|
|
990
|
+
console.log('\\n Goodbye!\\n')
|
|
991
|
+
process.exit(0)
|
|
992
|
+
})
|
|
993
|
+
`}function En(e,t){let n=e;for(;;){let e=k(n,`node_modules`,`.bin`,t);if(N(e))return e;let r=j(n,`..`);if(r===n)break;n=r}return null}async function Dn(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=p(t),s=b(t),c=i?d(a):a,u=k(n,c);if(!await o(u)){console.log(`\n Module not found: ${u}\n`);return}if(!r&&!await l({message:v.red(`Delete module '${c}' at ${u}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
994
|
+
Cancelled.
|
|
995
|
+
`);return}await Ee(u,{recursive:!0,force:!0}),console.log(` Deleted: ${u}`);let f=k(n,`index.ts`);if(await o(f)){let e=await I(f,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${s}Module\\s*\\}\\s*from\\s*['"][^'"]*${c}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=e.replace(RegExp(`\\s*,?\\s*${s}Module\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),e=e.replace(/,(\s*])/,`$1`),e=e.replace(/\n{3,}/g,`
|
|
996
|
+
|
|
997
|
+
`),e!==t&&(await L(f,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${f}`))}console.log(`\n Module '${c}' removed.\n`)}function On(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 n=x(await S(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Dn({name:n,modulesDir:j(r),force:t.force,pluralize:i})})}function kn(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 An(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function jn(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 S(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-VPl_QQGb.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-Du70nybS.mjs`),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(`
|
|
998
|
+
Registered typegen plugins:
|
|
999
|
+
`);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 r=kn(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=An(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ge(a);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{await E(a);let r=await U({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&r.some(e=>e.status===`written`)&&process.exit(1)}}catch(e){e instanceof me?console.error(`
|
|
1000
|
+
`+e.message+`
|
|
1001
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Mn(e){let t=[];if(!N(e))return t;let n=xe(e,{withFileTypes:!0});for(let r of n){let n=k(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Mn(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Nn(e){try{return F(e,`utf-8`)}catch{return``}}const Pn=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Fn(e,t){let n=Nn(k(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Pn.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 In(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 Ln(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 Rn(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function zn(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 Bn(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 Vn(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 Hn(e){let t=Mn(k(e,`src`)).map(e=>Nn(e)),n=[],r=Fn(e,t);r&&n.push(r);let i=In(t);i&&n.push(i);let a=Ln(t);a&&n.push(a);let o=Rn();o&&n.push(o);let s=zn(t);return s&&n.push(s),n.push(Bn(t)),n.push(Vn(t)),n}function Un(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
|
|
1002
|
+
Usage: kick check --deploy
|
|
1003
|
+
|
|
1004
|
+
Available checks:
|
|
1005
|
+
--deploy Audit for production readiness (security, config, best practices)
|
|
1006
|
+
`);return}let n=process.cwd();t(`KickJS Deploy Check`);let i=s();i.start(`Scanning project...`);let o=Hn(n);i.stop(`Scan complete`);let c={CRITICAL:0,WARNING:1,INFO:2};o.sort((e,t)=>c[e.severity]-c[t.severity]);for(let e of o)y.message(`${a(e.severity)} ${e.message}`);let l=o.filter(e=>e.severity===`CRITICAL`).length,u=o.filter(e=>e.severity===`WARNING`).length,d=o.filter(e=>e.severity===`INFO`).length,f=u===1?`warning`:`warnings`,p=[l>0?v.red(`${l} critical`):`${l} critical`,u>0?v.yellow(`${u} ${f}`):`${u} ${f}`,`${d} info`].join(`, `);l>0?(r(v.red(`${p} — fix critical issues before deploying`)),process.exit(1)):r(v.green(`${p} — looking good!`))})}async function Q(e){return Ue({configPath:D.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()}}}function Wn(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 Gn(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 Ie({name:e,config:await Q(t),cwd:n,empty:t.empty});if(r.status===`no-changes`){console.log(`No schema changes detected.`);return}if(r.empty){console.log(`Created empty migration ${r.migrationDir} (author up.sql + down.sql).`);return}let i=r.changeCount===1?``:`s`;console.log(`Created migration ${r.migrationDir} (${r.changeCount} change${i}).`)});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`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Re({adapter:n,migrationsDir:t.migrationsDir});e.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${e.batch}: ${e.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`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ve({adapter:n,migrationsDir:t.migrationsDir});e.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${e.applied[0]} (batch ${e.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 Le({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 ze({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{Wn(await Be({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 L(i,He(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}const Kn=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],qn=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=Jn(e.cwd);if(!t)return null;let n=D.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${Yn(D.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>`,` }`,`}`].join(`
|
|
1007
|
+
`)}});function Jn(e){for(let t of Kn){let n=D.resolve(e,t);if(t.endsWith(`.ts`)){if(N(n))return n}else{let e=D.join(n,`index.ts`);if(N(e))return e}}return null}function Yn(e){return e.replace(/\\/g,`/`)}const Xn=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!N(D.resolve(e.cwd,`kick.config.ts`)))return null;let t=await S(e.cwd);if(!t?.assetMap)return null;let n=pe(t.assetMap,e.cwd);return n.count===0?null:he(n)}}),Zn="/* 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 Qn(e,t,n){if(e.length===0)return`${Zn}
|
|
1008
|
+
// (no routes discovered yet — annotate a controller method with
|
|
1009
|
+
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1010
|
+
declare global {
|
|
1011
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1012
|
+
namespace KickRoutes {}
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
export {}
|
|
1016
|
+
`;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=tr(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??$n(e),l=er(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(`
|
|
1017
|
+
`))}return`${Zn}${nr(i)}
|
|
1018
|
+
declare global {
|
|
1019
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1020
|
+
namespace KickRoutes {
|
|
1021
|
+
${o.join(`
|
|
1022
|
+
`)}
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
export {}
|
|
1027
|
+
`}function $n(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 er(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 tr(e,t,n,r,i){if(!e||r!==`zod`||e.source===null)return null;let a=rr(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 nr(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(`
|
|
1028
|
+
`)+`
|
|
1029
|
+
`}function rr(e,t,n){if(e===null)return`unknown`;let r=O(n);if(e===``){let e=A(r,t).split(M).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=A(r,j(O(t),e)).split(M).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const ir=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:ar(e),cwd:e.cwd,envFile:or(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Qn(t.routes,r,n)}});function ar(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function or(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function sr(e,t){if(!e)return null;let n=A(O(t),e.filePath).split(M).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),`/* eslint-disable */
|
|
1030
|
+
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1031
|
+
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1032
|
+
|
|
1033
|
+
// Importing the schema as a type lets us infer its shape without
|
|
1034
|
+
// pulling in any runtime code. \`Awaited<>\` strips an accidental
|
|
1035
|
+
// Promise wrap on dynamic-imported defaults.
|
|
1036
|
+
import type _envSchema from '${n}'
|
|
1037
|
+
|
|
1038
|
+
// Local type alias — interfaces can only \`extend\` an identifier,
|
|
1039
|
+
// not an inline import expression, so we resolve the schema's
|
|
1040
|
+
// inferred shape into a named type first.
|
|
1041
|
+
type _KickEnvShape = import('zod').infer<typeof _envSchema>
|
|
1042
|
+
|
|
1043
|
+
declare global {
|
|
1044
|
+
/**
|
|
1045
|
+
* Typed environment registry. Augmented from \`${e.relativePath}\`
|
|
1046
|
+
* so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
|
|
1047
|
+
* all type-safe and autocomplete.
|
|
1048
|
+
*/
|
|
1049
|
+
interface KickEnv extends _KickEnvShape {}
|
|
1050
|
+
|
|
1051
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1052
|
+
namespace NodeJS {
|
|
1053
|
+
/**
|
|
1054
|
+
* Narrow \`process.env\` so known keys exist as \`string\` (the raw
|
|
1055
|
+
* pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
|
|
1056
|
+
* the schema's transforms internally; access \`process.env\` directly
|
|
1057
|
+
* only when you need the raw string. Unknown keys still resolve to
|
|
1058
|
+
* \`string | undefined\` via the base @types/node declaration.
|
|
1059
|
+
*/
|
|
1060
|
+
interface ProcessEnv extends Record<keyof KickEnv, string> {}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
export {}
|
|
1065
|
+
`}const cr=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=ur(e);if(t===!1)return null;let n=await e.getScanResult({root:lr(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=D.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return sr(n.env,r)}});function lr(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ur(e){return e.config?.typegen?.envFile}const dr=[w({name:`kick/init`,register:$e}),w({name:`kick/generate`,register:Pt}),w({name:`kick/run`,register:Kt}),w({name:`kick/info`,register:qt}),w({name:`kick/inspect`,register:tn}),w({name:`kick/add`,register:Ze}),w({name:`kick/list`,register:Xe}),w({name:`kick/explain`,register:dn}),w({name:`kick/mcp`,register:bn}),w({name:`kick/tinker`,register:wn}),w({name:`kick/remove`,register:On}),w({name:`kick/typegen`,register:jn}),w({name:`kick/check`,register:Un}),w({name:`kick/db`,register:Gn,typegens:[qn()]}),w({name:`kick/assets`,typegens:[Xn()]}),w({name:`kick/routes`,typegens:[ir()]}),w({name:`kick/env`,typegens:[cr()]})];export{dr as builtinCliPlugins,Rt as n,U as t};
|
|
1066
|
+
//# sourceMappingURL=builtins-Du70nybS.mjs.map
|