@forinda/kickjs-cli 6.9.1 → 6.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-docs-B91ALPZR.mjs → agent-docs-BnGa_odb.mjs} +2 -2
- package/dist/{agent-docs-DvLtd3g5.mjs → agent-docs-CLs1wTpl.mjs} +3 -3
- package/dist/{agent-docs-DvLtd3g5.mjs.map → agent-docs-CLs1wTpl.mjs.map} +1 -1
- package/dist/{build-Dghtk24W.mjs → build-BQUDhMVD.mjs} +3 -3
- package/dist/{build-Dghtk24W.mjs.map → build-BQUDhMVD.mjs.map} +1 -1
- package/dist/{build-D-7xvnpW.mjs → build-BX7-8d5h.mjs} +2 -2
- package/dist/{builtins-CPF14ODX.mjs → builtins-DWngUnQ8.mjs} +2 -2
- package/dist/{builtins-BjcrVIsO.mjs → builtins-DfzsCxQu.mjs} +202 -131
- package/dist/cli.mjs +2 -2
- package/dist/{config-DzcY7KDb.mjs → config-DHHqXYVF.mjs} +2 -2
- package/dist/{config-CFAZrUmi.mjs → config-DYS_-oZ_.mjs} +3 -3
- package/dist/{config-CFAZrUmi.mjs.map → config-DYS_-oZ_.mjs.map} +1 -1
- package/dist/{doctor-BRs6lrbi.mjs → doctor-CC8eWifc.mjs} +88 -17
- package/dist/doctor-CC8eWifc.mjs.map +1 -0
- package/dist/{fullstack-BlETTj51.mjs → fullstack-1y-ENahw.mjs} +12 -12
- package/dist/{fullstack-3TAOhXfk.mjs → fullstack-BWopEQFU.mjs} +13 -13
- package/dist/fullstack-BWopEQFU.mjs.map +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-DSCSpumh.mjs → plugin-CrbgblqR.mjs} +2 -2
- package/dist/{plugin-qwSg0kwT.mjs → plugin-Dgdp1o7e.mjs} +3 -3
- package/dist/{plugin-qwSg0kwT.mjs.map → plugin-Dgdp1o7e.mjs.map} +1 -1
- package/dist/{project-BD_l6pkS.mjs → project-BFhosVpo.mjs} +20 -20
- package/dist/{project-BSSB5kBG.mjs → project-DPQJNbUr.mjs} +21 -21
- package/dist/project-DPQJNbUr.mjs.map +1 -0
- package/dist/{project-docs-Dlq_ipnh.mjs → project-docs-BEnHASsn.mjs} +3 -3
- package/dist/{project-docs-Dlq_ipnh.mjs.map → project-docs-BEnHASsn.mjs.map} +1 -1
- package/dist/{project-docs-DG-aI5f_.mjs → project-docs-BlYdtsfz.mjs} +2 -2
- package/dist/{project-root-BNYhLr1o.mjs → project-root-74p4iEbS.mjs} +3 -3
- package/dist/{project-root-BNYhLr1o.mjs.map → project-root-74p4iEbS.mjs.map} +1 -1
- package/dist/{project-root-Dv1HfN0o.mjs → project-root-CSfkrbTB.mjs} +2 -2
- package/dist/{prompts-D82t3FiY.mjs → prompts-kKPsD4J5.mjs} +2 -2
- package/dist/{prompts-D82t3FiY.mjs.map → prompts-kKPsD4J5.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DnEcvn06.mjs → rolldown-runtime-Wu10E8Jp.mjs} +1 -1
- package/dist/{run-plugins-B49z_ywO.mjs → run-plugins-BPLz855M.mjs} +46 -46
- package/dist/run-plugins-BPLz855M.mjs.map +1 -0
- package/dist/{typegen-BZKiGXjW.mjs → typegen-ByZnBYdj.mjs} +4 -4
- package/dist/{typegen-CdS37QWi.mjs → typegen-ngGYyfaY.mjs} +5 -5
- package/dist/{typegen-CdS37QWi.mjs.map → typegen-ngGYyfaY.mjs.map} +1 -1
- package/dist/{types-Dfg3zods.mjs → types-BYbOAJ_d.mjs} +1 -1
- package/package.json +3 -3
- package/dist/doctor-BRs6lrbi.mjs.map +0 -1
- package/dist/fullstack-3TAOhXfk.mjs.map +0 -1
- package/dist/project-BSSB5kBG.mjs.map +0 -1
- package/dist/run-plugins-B49z_ywO.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v6.
|
|
2
|
+
* @forinda/kickjs-cli v6.10.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as e}from"./rolldown-runtime-
|
|
11
|
+
import{t as e}from"./rolldown-runtime-Wu10E8Jp.mjs";import{a as t,c as n,i as r,o as i,r as a,s as o,t as s,u as c}from"./project-BFhosVpo.mjs";import{a as l,i as u,o as d,r as f}from"./config-DHHqXYVF.mjs";import{n as p,r as m}from"./plugin-CrbgblqR.mjs";import{c as h,l as g,s as _}from"./project-docs-BlYdtsfz.mjs";import{a as v,c as y,d as b,f as x,i as ee,l as te,n as ne,o as re,p as ie,r as S,s as C,u as ae}from"./agent-docs-BnGa_odb.mjs";import{t as oe}from"./project-root-CSfkrbTB.mjs";import{a as se,c as ce,d as le,f as ue,g as de,h as fe,i as pe,l as me,m as he,o as ge,p as _e,r as ve,s as ye,t as be,u as xe}from"./typegen-ByZnBYdj.mjs";import{t as Se}from"./build-BX7-8d5h.mjs";import{createRequire as Ce}from"node:module";import{cpSync as we,existsSync as w,mkdirSync as Te,readFileSync as T,readdirSync as E,rmSync as Ee,statSync as De,writeFileSync as Oe}from"node:fs";import D,{basename as ke,dirname as O,join as k,relative as A,resolve as j,sep as Ae}from"node:path";import{fileURLToPath as je,pathToFileURL as M}from"node:url";import{fork as Me,spawn as Ne}from"node:child_process";import{copyFile as Pe,mkdir as Fe,readFile as N,readdir as Ie,rm as Le,stat as Re,writeFile as P}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import ze from"pluralize";import{arch as Be,platform as Ve,release as He}from"node:os";const Ue=[{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 We(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 | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{ee(`KickJS — Create a new project`);let r=!!(t.yes||t.nonInteractive);e||=r?`my-api`:await ae({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=j(`.`),e=ke(i)):i=j(t.directory||e),w(i)){let n=E(i);if(n.length>0){if(t.force)v.warn(`Clearing existing files in ${i}`);else if(r){v.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),C(`Aborted.`);return}else{v.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)v.message(` - ${e}`);if(n.length>5&&v.message(` ... and ${n.length-5} more`),!await S({message:x.red(`Remove all existing files and proceed?`),initialValue:!1})){C(`Aborted.`);return}}for(let e of n)Ee(j(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=r?`minimal`:await y({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let o=t.runtime;o||=r?`express`:await y({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let c=t.pm;c||=r?await n(void 0):await y({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||=r?`inmemory`:await ae({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),d(l);let u=t.schema;u||=r?`zod`:await y({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(u)||(v.warn(`Unknown --schema "${u}", falling back to zod.`),u=`zod`);let f;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();f=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else f=r?[]:await re({message:`Select packages to include`,options:[...Ue],required:!1});let p;p=t.git===void 0?r?!0:await S({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?r?!0:await S({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-1y-ENahw.mjs`);await t({name:e,directory:i,packageManager:c,initGit:p,installDeps:m,schemaLib:u,runtime:o}),C(`Done! Next steps: ${x.cyan(`cd ${e} && ${c}${c===`pnpm`?` dev`:` run dev:server`}`)}`);return}await s({name:e,directory:i,packageManager:c,initGit:p,installDeps:m,template:a,defaultRepo:l,packages:f,schemaLib:u,runtime:o}),C(`Done! Next steps: ${x.cyan(`cd ${e} && ${c} dev`)}`)})}function F(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function I(e){let t=F(e);return t.charAt(0).toLowerCase()+t.slice(1)}function L(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function R(e){return ze.plural(e)}function Ge(e){return ze.plural(e)}function Ke(e){return L(e).replace(/-/g,`_`)}function qe(e){let t=e.cwd??process.cwd(),n=e.projectRoot??oe(t),r=e.pluralize??!0,i=F(e.name),a=I(e.name),o=L(e.name),s=Ke(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=R(o);c.pluralKebab=e,c.pluralPascal=F(e),c.pluralCamel=I(e)}return c}function Je(e,t){return j(e.cwd,t)}async function Ye(e){return import(M(e).href)}const Xe=new Map;async function Ze(e){let t=Xe.get(e);if(t)return t;let n=Qe(e);return Xe.set(e,n),n}async function Qe(e){let t=j(e,`package.json`);if(!w(t))return{generators:[],loaded:[],failed:[]};let n=$e(JSON.parse(await N(t,`utf-8`))),r=Ce(j(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await N(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=j(O(t),s);if(!w(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await Ye(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u)){o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of u){if(!et(t)){o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}i.push({source:e,spec:t})}a.push(e)}return{generators:i,loaded:a,failed:o}}function $e(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function et(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function tt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return it(r.spec,r.source,e,n);let i=rt(await Ze(n),e.generatorName);return i?it(i.spec,i.source,e,n):null}async function nt(e,t=[]){let n=await Ze(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function rt(e,t){return e.generators.find(e=>e.spec.name===t)}async function it(e,t,n,r){let i=qe({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=Je(i,e.path);await g(t,e.content),o.push(t)}return{files:o,source:t}}function z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function at(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ot(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function st(e,t,n){let r={inmemory:`InMemory${e}Repository`,drizzle:`Drizzle${e}Repository`,prisma:`Prisma${e}Repository`},i={inmemory:`in-memory-${t}`,drizzle:`drizzle-${t}`,prisma:`prisma-${t}`};return{repoClass:r[n]??`${at(n)}${e}Repository`,repoFile:i[n]??`${ot(n)}-${t}`}}function ct(e){return e??`define`}function lt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=st(t,n,i),c=ct(a),l=`/**
|
|
12
12
|
* ${t} Module
|
|
13
13
|
*
|
|
14
14
|
* REST module with a flat folder structure.
|
|
@@ -85,7 +85,7 @@ ${d}
|
|
|
85
85
|
},
|
|
86
86
|
}),
|
|
87
87
|
})
|
|
88
|
-
`}function
|
|
88
|
+
`}function ut(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=ct(i),o=` /**
|
|
89
89
|
* Declare HTTP routes. Return value shape:
|
|
90
90
|
*
|
|
91
91
|
* - \`path\` — URL prefix for this route set.
|
|
@@ -125,7 +125,17 @@ ${o}
|
|
|
125
125
|
},
|
|
126
126
|
}),
|
|
127
127
|
})
|
|
128
|
-
`}function
|
|
128
|
+
`}function dt(e){let{pascal:t,kebab:n}=e,r=t.charAt(0).toLowerCase()+t.slice(1);return`import {
|
|
129
|
+
Controller,
|
|
130
|
+
Get,
|
|
131
|
+
Post,
|
|
132
|
+
Put,
|
|
133
|
+
Delete,
|
|
134
|
+
Autowired,
|
|
135
|
+
ApiQueryParams,
|
|
136
|
+
reply,
|
|
137
|
+
type Ctx,
|
|
138
|
+
} from '@forinda/kickjs'
|
|
129
139
|
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
130
140
|
import { ${t}Service } from './${n}.service'
|
|
131
141
|
import { create${t}Schema } from './dtos/create-${n}.dto'
|
|
@@ -136,6 +146,15 @@ import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
|
136
146
|
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
137
147
|
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
138
148
|
// \`kick dev\`) — see https://kickjs.app/guide/typegen.
|
|
149
|
+
//
|
|
150
|
+
// Handlers RETURN their payload rather than calling \`ctx.json()\`: the runtime
|
|
151
|
+
// auto-sends it, and \`kick typegen\` reads the return type to fill in
|
|
152
|
+
// \`KickRoutes[...].response\` — which is what makes the typed client know what
|
|
153
|
+
// each route gives back. A handler that writes via \`ctx.json()\` and returns
|
|
154
|
+
// nothing infers as \`unknown\`. Use \`reply(status, body)\` (or the
|
|
155
|
+
// \`reply.created\` / \`reply.noContent\` sugars) when the status isn't 200, and
|
|
156
|
+
// \`ctx.problem.*\` for error branches — those send immediately and return
|
|
157
|
+
// nothing, so they stay out of the success type.
|
|
139
158
|
|
|
140
159
|
@Controller()
|
|
141
160
|
export class ${t}Controller {
|
|
@@ -155,32 +174,35 @@ export class ${t}Controller {
|
|
|
155
174
|
@ApiTags('${t}')
|
|
156
175
|
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
157
176
|
const result = await this.${r}Service.findById(ctx.params.id)
|
|
158
|
-
if (!result)
|
|
159
|
-
|
|
177
|
+
if (!result) {
|
|
178
|
+
// Sends RFC 9457 problem+json now; returning nothing keeps the 404 out
|
|
179
|
+
// of this route's inferred response type.
|
|
180
|
+
ctx.problem.notFound({ detail: \`${t} \${ctx.params.id} not found\` })
|
|
181
|
+
return
|
|
182
|
+
}
|
|
183
|
+
return result
|
|
160
184
|
}
|
|
161
185
|
|
|
162
186
|
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
163
187
|
@ApiTags('${t}')
|
|
164
188
|
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
165
|
-
|
|
166
|
-
ctx.created(result)
|
|
189
|
+
return reply.created(await this.${r}Service.create(ctx.body))
|
|
167
190
|
}
|
|
168
191
|
|
|
169
192
|
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
170
193
|
@ApiTags('${t}')
|
|
171
194
|
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
172
|
-
|
|
173
|
-
ctx.json(result)
|
|
195
|
+
return this.${r}Service.update(ctx.params.id, ctx.body)
|
|
174
196
|
}
|
|
175
197
|
|
|
176
198
|
@Delete('/:id')
|
|
177
199
|
@ApiTags('${t}')
|
|
178
200
|
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
179
201
|
await this.${r}Service.delete(ctx.params.id)
|
|
180
|
-
|
|
202
|
+
return reply.noContent()
|
|
181
203
|
}
|
|
182
204
|
}
|
|
183
|
-
`}function
|
|
205
|
+
`}function ft(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
184
206
|
|
|
185
207
|
/**
|
|
186
208
|
* Create ${t} DTO — Zod schema for validating POST request bodies.
|
|
@@ -196,20 +218,20 @@ export const create${t}Schema = z.object({
|
|
|
196
218
|
})
|
|
197
219
|
|
|
198
220
|
export type Create${t}DTO = z.infer<typeof create${t}Schema>
|
|
199
|
-
`}function
|
|
221
|
+
`}function pt(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
200
222
|
|
|
201
223
|
export const update${t}Schema = z.object({
|
|
202
224
|
name: z.string().min(1).max(200).optional(),
|
|
203
225
|
})
|
|
204
226
|
|
|
205
227
|
export type Update${t}DTO = z.infer<typeof update${t}Schema>
|
|
206
|
-
`}function
|
|
228
|
+
`}function mt(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
207
229
|
id: string
|
|
208
230
|
name: string
|
|
209
231
|
createdAt: string
|
|
210
232
|
updatedAt: string
|
|
211
233
|
}
|
|
212
|
-
`}function
|
|
234
|
+
`}function ht(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
|
|
213
235
|
* ${t} Repository Interface
|
|
214
236
|
*
|
|
215
237
|
* Defines the contract for data access.
|
|
@@ -244,7 +266,7 @@ export interface I${t}Repository {
|
|
|
244
266
|
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
245
267
|
*/
|
|
246
268
|
export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
|
|
247
|
-
`}function
|
|
269
|
+
`}function gt(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
248
270
|
* In-Memory ${t} Repository
|
|
249
271
|
*
|
|
250
272
|
* Implements the repository interface using a Map.
|
|
@@ -304,7 +326,7 @@ export class InMemory${t}Repository implements I${t}Repository {
|
|
|
304
326
|
this.store.delete(id)
|
|
305
327
|
}
|
|
306
328
|
}
|
|
307
|
-
`}function
|
|
329
|
+
`}function _t(e){let{pascal:t,kebab:n,repoType:r=``,repoPrefix:i=`../../domain/repositories`,dtoPrefix:a=`../../application/dtos`}=e,o=r.charAt(0).toUpperCase()+r.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return`/**
|
|
308
330
|
* ${o} ${t} Repository
|
|
309
331
|
*
|
|
310
332
|
* Stub implementation for a custom '${r}' repository.
|
|
@@ -373,7 +395,7 @@ export class ${o}${t}Repository implements I${t}Repository {
|
|
|
373
395
|
this.store.delete(id)
|
|
374
396
|
}
|
|
375
397
|
}
|
|
376
|
-
`}function
|
|
398
|
+
`}function vt(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
377
399
|
import { Container } from '@forinda/kickjs'
|
|
378
400
|
|
|
379
401
|
describe('${t}Controller', () => {
|
|
@@ -425,7 +447,7 @@ describe('${t}Controller', () => {
|
|
|
425
447
|
})
|
|
426
448
|
})
|
|
427
449
|
})
|
|
428
|
-
`}function
|
|
450
|
+
`}function yt(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../infrastructure/repositories/in-memory-${n}.repository`}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
429
451
|
import { InMemory${t}Repository } from '${i}'
|
|
430
452
|
|
|
431
453
|
describe('InMemory${t}Repository', () => {
|
|
@@ -487,7 +509,7 @@ describe('InMemory${t}Repository', () => {
|
|
|
487
509
|
expect(found).toBeNull()
|
|
488
510
|
})
|
|
489
511
|
})
|
|
490
|
-
`}function
|
|
512
|
+
`}function bt(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
491
513
|
import type { ParsedQuery } from '@forinda/kickjs'
|
|
492
514
|
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
|
|
493
515
|
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
@@ -524,38 +546,66 @@ export class ${t}Service {
|
|
|
524
546
|
await this.repo.delete(id)
|
|
525
547
|
}
|
|
526
548
|
}
|
|
527
|
-
`}function
|
|
549
|
+
`}function xt(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
528
550
|
|
|
529
551
|
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
530
552
|
filterable: ['name'],
|
|
531
553
|
sortable: ['name', 'createdAt'],
|
|
532
554
|
searchable: ['name'],
|
|
533
555
|
}
|
|
534
|
-
`}async function
|
|
556
|
+
`}async function St(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,ut({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
535
557
|
|
|
536
558
|
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
537
559
|
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
560
|
+
//
|
|
561
|
+
// Return the payload instead of calling \`ctx.json()\` — the runtime sends it,
|
|
562
|
+
// and typegen reads the return type to fill in \`KickRoutes[...].response\`.
|
|
563
|
+
// \`reply(status, body)\` carries a non-200 status without losing that type.
|
|
564
|
+
//
|
|
565
|
+
// The bodies below are placeholders: wire them to a service or repository.
|
|
566
|
+
// "Minimal" is about the file count, not the route surface — you get the whole
|
|
567
|
+
// CRUD shape here in one file.
|
|
538
568
|
|
|
539
569
|
@Controller()
|
|
540
570
|
export class ${t}Controller {
|
|
541
571
|
@Get('/')
|
|
542
572
|
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
543
|
-
|
|
573
|
+
return { items: [], total: 0 }
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
@Get('/:id')
|
|
577
|
+
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
578
|
+
return { id: ctx.params.id }
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
@Post('/')
|
|
582
|
+
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
583
|
+
return reply.created({ data: ctx.body })
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
@Put('/:id')
|
|
587
|
+
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
588
|
+
return { id: ctx.params.id, data: ctx.body }
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
@Delete('/:id')
|
|
592
|
+
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
593
|
+
return reply.noContent()
|
|
544
594
|
}
|
|
545
595
|
}
|
|
546
|
-
`)}async function
|
|
596
|
+
`)}async function Ct(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,tokenScope:s,style:c,write:l}=e;await l(`${n}.module.ts`,lt({pascal:t,kebab:n,plural:r,repo:a,style:c})),await l(`${n}.constants.ts`,xt({pascal:t,kebab:n})),await l(`${n}.controller.ts`,dt({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`${n}.service.ts`,bt({pascal:t,kebab:n})),await l(`dtos/create-${n}.dto.ts`,ft({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,pt({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,mt({pascal:t,kebab:n})),await l(`${n}.repository.ts`,ht({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:s}));let u=a===`inmemory`,d=u?`in-memory-${n}`:`${L(a)}-${n}`,f=u?gt({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}):_t({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`});await l(`${d}.repository.ts`,f),o||(a!==`inmemory`&&await l(`in-memory-${n}.repository.ts`,gt({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,vt({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,yt({pascal:t,kebab:n,plural:r,repoPrefix:`../in-memory-${n}.repository`})))}function wt(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Tt(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`rest`;e.minimal&&(l=`minimal`);let u=L(t),d=F(t),f=c?R(u):u,p=c?Ge(d):d,m=k(n,f),h=[],y=o??!1,b={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,prismaClientPath:e.prismaClientPath??`@prisma/client`,tokenScope:e.tokenScope??`app`,style:e.style??`define`,write:async(e,t)=>{let n=k(m,e);if(s){h.push(n);return}if(!y&&await _(n)&&!await S({message:`File exists: ${x.dim(e)}. Overwrite?`,initialValue:!1})){v.warn(`Skipped: ${e}`);return}await g(n,t),h.push(n)},files:h};switch(l){case`minimal`:await St(b);break;default:await Ct(b);break}return s||await Et(n,d,f,u,b.style),h}async function Et(e,t,n,r,i=`define`){let a=k(e,`index.ts`),o=await _(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await g(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
547
597
|
import { ${t}Module } from '${s}'
|
|
548
598
|
|
|
549
|
-
export const modules: AppModuleEntry[] = [${
|
|
599
|
+
export const modules: AppModuleEntry[] = [${c}]
|
|
550
600
|
`:`import { defineModules } from '@forinda/kickjs'
|
|
551
601
|
import { ${t}Module } from '${s}'
|
|
552
602
|
|
|
553
|
-
export const modules = defineModules().mount(${
|
|
554
|
-
`);return}let
|
|
555
|
-
`,e);
|
|
556
|
-
`+
|
|
557
|
-
`+
|
|
558
|
-
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function
|
|
603
|
+
export const modules = defineModules().mount(${c})
|
|
604
|
+
`);return}let l=await N(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=z(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${z(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
|
|
605
|
+
`,e);l=l.slice(0,t+1)+u+`
|
|
606
|
+
`+l.slice(t+1)}else l=u+`
|
|
607
|
+
`+l}let f=Ot(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${z(t)}Module\\b`).test(e)||(l=Dt(l,c))}else l=Dt(l,c);await P(a,l,`utf-8`)}function Dt(e,t){let n=Ot(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function Ot(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=jt(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=kt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function kt(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Mt(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Mt(e,t);if(n===-1)break;i=n+1}return i}function At(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
608
|
+
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function jt(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=At(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Mt(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=At(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}async function Nt(e){let{name:t,outDir:n}=e,r=L(t),i=F(t),a=[],o=k(n,`${r}.adapter.ts`);return await g(o,`import {
|
|
559
609
|
defineAdapter,
|
|
560
610
|
type AdapterContext,
|
|
561
611
|
type AdapterMiddleware,
|
|
@@ -724,7 +774,7 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
|
724
774
|
}
|
|
725
775
|
},
|
|
726
776
|
})
|
|
727
|
-
`),a.push(o),a}async function
|
|
777
|
+
`),a.push(o),a}async function Pt(e){let{name:t,outDir:n}=e,r=L(t),i=F(t),a=[],o=k(n,`${r}.plugin.ts`);return await g(o,`import {
|
|
728
778
|
definePlugin,
|
|
729
779
|
type AppAdapter,
|
|
730
780
|
type AppModuleEntry,
|
|
@@ -868,7 +918,7 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
|
868
918
|
},
|
|
869
919
|
}),
|
|
870
920
|
})
|
|
871
|
-
`),a.push(o),a}const
|
|
921
|
+
`),a.push(o),a}const Ft={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function B(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return j(n);if(r){let e=Ft,n=L(r),a=o?R(n):n,s=e[t]??``,c=k(i,a);return j(s?k(c,s):c)}return j(a)}async function It(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=B({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),o=L(t),s=I(t),c=[],l=k(a,`${o}.middleware.ts`);return await g(l,`import type { Request, Response, NextFunction } from 'express'
|
|
872
922
|
|
|
873
923
|
export interface ${F(t)}Options {
|
|
874
924
|
// Add configuration options here. The factory below closes over the
|
|
@@ -918,11 +968,11 @@ export function ${s}(options: ${F(t)}Options = {}) {
|
|
|
918
968
|
next()
|
|
919
969
|
}
|
|
920
970
|
}
|
|
921
|
-
`),
|
|
971
|
+
`),c.push(l),c}async function Lt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=B({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=L(t),s=I(t),c=F(t),l=[],u=k(a,`${o}.guard.ts`);return await g(u,`import { Container, HttpException } from '@forinda/kickjs'
|
|
922
972
|
import type { RequestContext } from '@forinda/kickjs'
|
|
923
973
|
|
|
924
974
|
/**
|
|
925
|
-
* ${
|
|
975
|
+
* ${c} guard.
|
|
926
976
|
*
|
|
927
977
|
* Guards protect routes by checking conditions before the handler runs.
|
|
928
978
|
* Return early with an error response to block access.
|
|
@@ -954,58 +1004,58 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
|
|
|
954
1004
|
ctx.res.status(401).json({ message: 'Invalid or expired token' })
|
|
955
1005
|
}
|
|
956
1006
|
}
|
|
957
|
-
`),
|
|
958
|
-
`)}\n}\n`:``,
|
|
1007
|
+
`),l.push(u),l}function Rt(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function zt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=L(t),s=F(t),c=e.key??I(t),l=Array.isArray(e.params)?e.params:Rt(e.params),u=B({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
1008
|
+
`)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,h=l.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
959
1009
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
960
1010
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
961
|
-
requiredParams: [${
|
|
962
|
-
import type { ${
|
|
1011
|
+
requiredParams: [${l.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=l.length>0?`(ctx, _deps, params)`:`(ctx)`,v=l.length>0?` // \`params\` is typed as ${s}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${f} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,y=`import { ${d} } from '@forinda/kickjs'
|
|
1012
|
+
import type { ${f} } from '@forinda/kickjs'
|
|
963
1013
|
|
|
964
1014
|
/**
|
|
965
1015
|
* ${s} context contributor (${a}).
|
|
966
1016
|
*
|
|
967
|
-
* Computes a value and writes it to \`ctx.set('${
|
|
1017
|
+
* Computes a value and writes it to \`ctx.set('${c}', …)\` before a
|
|
968
1018
|
* matched handler runs — the typed, ordered alternative to
|
|
969
1019
|
* \`@Middleware()\` when the only job is to populate \`ctx\`.
|
|
970
1020
|
*
|
|
971
1021
|
* Apply per method/class:
|
|
972
1022
|
*
|
|
973
|
-
${a===`http`?` * @${s}${
|
|
1023
|
+
${a===`http`?` * @${s}${l.length>0?`({ ${l[0]?.name}: … })`:``}
|
|
974
1024
|
* @Get('/')
|
|
975
|
-
* handler(ctx: ${
|
|
976
|
-
* return ctx.
|
|
1025
|
+
* handler(ctx: ${f}) {
|
|
1026
|
+
* return ctx.require('${c}')
|
|
977
1027
|
* }`:` * // Any transport whose handler receives an ExecutionContext
|
|
978
1028
|
* // (WebSocket, queue, cron). Attach via that transport's decorator,
|
|
979
1029
|
* // or register the contributor at a module / bootstrap site below.
|
|
980
|
-
* handler(ctx: ${
|
|
981
|
-
* const value = ctx.require('${
|
|
1030
|
+
* handler(ctx: ${f}) {
|
|
1031
|
+
* const value = ctx.require('${c}')
|
|
982
1032
|
* }`}
|
|
983
1033
|
*
|
|
984
1034
|
* Or register at a module / adapter / bootstrap site — those take a
|
|
985
1035
|
* \`ContributorRegistration\`, not the decorator itself:
|
|
986
1036
|
*
|
|
987
|
-
* bootstrap({ contributors: [${s}${
|
|
1037
|
+
* bootstrap({ contributors: [${s}${l.length>0?`.with({ ${l[0]?.name}: … })`:``}.registration] })
|
|
988
1038
|
*/
|
|
989
1039
|
|
|
990
|
-
// Register '${
|
|
1040
|
+
// Register '${c}' so \`ctx.require('${c}')\` is typed and \`dependsOn: ['${c}']\`
|
|
991
1041
|
// is checked. Replace \`unknown\` with the resolved value's real type.
|
|
992
1042
|
// (For a key you only depend on — no value type needed — declare it in
|
|
993
1043
|
// \`interface ContextKeys\` instead.)
|
|
994
1044
|
declare module '@forinda/kickjs' {
|
|
995
1045
|
interface ContextMeta {
|
|
996
|
-
'${
|
|
1046
|
+
'${c}': unknown
|
|
997
1047
|
}
|
|
998
1048
|
}
|
|
999
|
-
${
|
|
1000
|
-
export const ${s} = ${
|
|
1001
|
-
key: '${
|
|
1002
|
-
${
|
|
1049
|
+
${p}
|
|
1050
|
+
export const ${s} = ${m}
|
|
1051
|
+
key: '${c}',
|
|
1052
|
+
${h} resolve: ${_} => {
|
|
1003
1053
|
${v}
|
|
1004
|
-
// TODO: compute and return the value written to ctx.set('${
|
|
1054
|
+
// TODO: compute and return the value written to ctx.set('${c}', …)
|
|
1005
1055
|
throw new Error("${s} contributor: resolve() not implemented")
|
|
1006
1056
|
},
|
|
1007
1057
|
})
|
|
1008
|
-
`,b=k(
|
|
1058
|
+
`,b=k(u,`${o}.contributor.ts`);return await g(b,y),[b]}async function Bt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=B({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=L(t),s=F(t),c=[],l=k(a,`${o}.service.ts`);return await g(l,`import { Service } from '@forinda/kickjs'
|
|
1009
1059
|
|
|
1010
1060
|
@Service()
|
|
1011
1061
|
export class ${s}Service {
|
|
@@ -1014,12 +1064,18 @@ export class ${s}Service {
|
|
|
1014
1064
|
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1015
1065
|
// ) {}
|
|
1016
1066
|
}
|
|
1017
|
-
`),
|
|
1067
|
+
`),c.push(l),c}async function Vt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=B({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=L(t),s=F(t),c=[],l=k(a,`${o}.controller.ts`);return await g(l,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
1018
1068
|
|
|
1019
1069
|
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1020
1070
|
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
1021
1071
|
// will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
|
|
1022
1072
|
// See https://kickjs.app/guide/typegen for details.
|
|
1073
|
+
//
|
|
1074
|
+
// Return the payload instead of calling \`ctx.json()\` — the runtime sends it,
|
|
1075
|
+
// and typegen reads the return type to fill in \`KickRoutes[...].response\`.
|
|
1076
|
+
// \`reply(status, body)\` carries a non-200 status without losing that type.
|
|
1077
|
+
//
|
|
1078
|
+
// The bodies below are placeholders: wire them to a service or repository.
|
|
1023
1079
|
|
|
1024
1080
|
@Controller()
|
|
1025
1081
|
export class ${s}Controller {
|
|
@@ -1027,24 +1083,39 @@ export class ${s}Controller {
|
|
|
1027
1083
|
|
|
1028
1084
|
@Get('/')
|
|
1029
1085
|
async list(ctx: Ctx<KickRoutes.${s}Controller['list']>) {
|
|
1030
|
-
|
|
1086
|
+
return { items: [], total: 0 }
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
@Get('/:id')
|
|
1090
|
+
async getById(ctx: Ctx<KickRoutes.${s}Controller['getById']>) {
|
|
1091
|
+
return { id: ctx.params.id }
|
|
1031
1092
|
}
|
|
1032
1093
|
|
|
1033
1094
|
@Post('/')
|
|
1034
1095
|
async create(ctx: Ctx<KickRoutes.${s}Controller['create']>) {
|
|
1035
|
-
|
|
1096
|
+
return reply.created({ data: ctx.body })
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
@Put('/:id')
|
|
1100
|
+
async update(ctx: Ctx<KickRoutes.${s}Controller['update']>) {
|
|
1101
|
+
return { id: ctx.params.id, data: ctx.body }
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
@Delete('/:id')
|
|
1105
|
+
async remove(ctx: Ctx<KickRoutes.${s}Controller['remove']>) {
|
|
1106
|
+
return reply.noContent()
|
|
1036
1107
|
}
|
|
1037
1108
|
}
|
|
1038
|
-
`),
|
|
1109
|
+
`),c.push(l),c}async function Ht(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=B({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=L(t),s=F(t),c=I(t),l=[],u=k(a,`${o}.dto.ts`);return await g(u,`import { z } from 'zod'
|
|
1039
1110
|
|
|
1040
|
-
export const ${
|
|
1111
|
+
export const ${c}Schema = z.object({
|
|
1041
1112
|
// Define your schema fields here
|
|
1042
1113
|
name: z.string().min(1).max(200),
|
|
1043
1114
|
})
|
|
1044
1115
|
|
|
1045
|
-
export type ${s}DTO = z.infer<typeof ${
|
|
1046
|
-
`),
|
|
1047
|
-
Skipped — existing kick.config.ts preserved.`),[]):(await
|
|
1116
|
+
export type ${s}DTO = z.infer<typeof ${c}Schema>
|
|
1117
|
+
`),l.push(u),l}async function Ut(e){let t=k(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return w(t)&&!e.force&&!await S({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
1118
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await g(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1048
1119
|
|
|
1049
1120
|
export default defineConfig({
|
|
1050
1121
|
modules: {
|
|
@@ -1083,16 +1154,16 @@ export default defineConfig({
|
|
|
1083
1154
|
})
|
|
1084
1155
|
`),[t])}function V(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function H(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=V(e,r);return i===-1?null:e.slice(r+1,i)}function U(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
1085
1156
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
1086
|
-
`)}function
|
|
1157
|
+
`)}function Wt(e){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,t)=>{let n=t.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`Container`&&e!==`type Container`&&e!==`type AppModule`&&e!==`AppModule`&&e!==`type ModuleRoutes`&&e!==`ModuleRoutes`);return n.includes(`defineModule`)||n.push(`defineModule`),`import { ${n.join(`, `)} } from '@forinda/kickjs'`})}function Gt(e,t){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,n)=>{let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`defineModule`);return t.container&&!r.includes(`Container`)&&r.push(`Container`),t.appModule&&!r.some(e=>e===`AppModule`||e===`type AppModule`)&&r.push(`type AppModule`),t.moduleRoutes&&!r.some(e=>e===`ModuleRoutes`||e===`type ModuleRoutes`)&&r.push(`type ModuleRoutes`),t.contributorRegistrations&&!r.some(e=>e===`ContributorRegistrations`||e===`type ContributorRegistrations`)&&r.push(`type ContributorRegistrations`),`import { ${r.join(`, `)} } from '@forinda/kickjs'`})}function Kt(e){if(/\bdefineModule\s*\(/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+class\s+(\w+Module)\s+implements\s+AppModule\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no class form detected`};if(t.length>1)return{migrated:null,reason:`multiple module classes in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=V(e,i);if(a===-1)return{migrated:null,reason:`unbalanced class braces`};let o=e.slice(i+1,a),s=e.slice(0,n.index),c=e.slice(a+1),l=H(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=H(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=H(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Wt(s),p=``;return l&&(p+=` register(container) {${U(l,4,6)} },\n\n`),u&&(p+=` contributors() {${U(u,4,6)} },\n\n`),p+=` routes() {${U(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
1087
1158
|
name: '${r}',
|
|
1088
1159
|
build: () => ({
|
|
1089
1160
|
${p}
|
|
1090
1161
|
}),
|
|
1091
|
-
})`}${c}`}}function
|
|
1092
|
-
`||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=V(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=H(m,/register\s*\(([^)]*)\)\s*\{/),g=H(m,/contributors\s*\(\s*\)\s*\{/),_=H(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=
|
|
1162
|
+
})`}${c}`}}function qt(e){if(/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+const\s+(\w+Module)\s*=\s*defineModule\s*\(\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no defineModule form detected`};if(t.length>1)return{migrated:null,reason:`multiple defineModule blocks in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=V(e,i);if(a===-1)return{migrated:null,reason:`unbalanced defineModule braces`};let o=e.indexOf(`)`,a);if(o===-1)return{migrated:null,reason:`unbalanced defineModule call parens`};let s=e.slice(i+1,a),c=e.slice(0,n.index),l=o+1;for(;l<e.length&&(e[l]===`
|
|
1163
|
+
`||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=V(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=H(m,/register\s*\(([^)]*)\)\s*\{/),g=H(m,/contributors\s*\(\s*\)\s*\{/),_=H(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Gt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${U(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${U(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${U(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
1093
1164
|
${y}
|
|
1094
1165
|
}
|
|
1095
|
-
`}${u}`}}function
|
|
1166
|
+
`}${u}`}}function Jt(e,t){return t===`class`?qt(e):Kt(e)}function Yt(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function Xt(e){let t=[];return await n(j(e),0),t;async function n(e,r){let i;try{i=await Ie(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o;try{o=await Re(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Zt(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Ie(e)}catch{return}await Fe(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o=k(t,a),s;try{s=await Re(i)}catch{continue}s.isDirectory()?await r(i,o):(await Pe(i,o),n++)}}}function Qt(e){return k(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function $t(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Xt(e),s=await N(k(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Qt(r),await Zt(e,c));let l=[];for(let e of o){let t=Jt(await N(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await P(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=k(e,`index.ts`),d=null;try{d=await N(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Yt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await P(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function en(e,t){let n=await Xt(e),r=[],i=t===`define`?/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/:/export\s+const\s+\w+Module\s*=\s*defineModule\s*\(/;for(let e of n){let t=await N(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function tn(e){let{name:t,outDir:n}=e,r=F(t),i=L(t),a=I(t),o=e.queue??`${i}-queue`,s=[];return await(async(e,t)=>{let r=k(n,e);await g(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
|
|
1096
1167
|
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
1097
1168
|
|
|
1098
1169
|
/**
|
|
@@ -1125,7 +1196,7 @@ export class ${r}Job {
|
|
|
1125
1196
|
// Handle high-priority variant of this job
|
|
1126
1197
|
}
|
|
1127
1198
|
}
|
|
1128
|
-
`),s}const
|
|
1199
|
+
`),s}const nn={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 rn(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=nn[a];if(!o){let e=[...Object.keys(nn),`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 an(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=L(t),l=F(t),u=s?R(c):c,d=s?Ge(l):l,f=k(r,u),p=[],m=async(e,t)=>{let n=k(f,e);await g(n,t),p.push(n)};await m(`${c}.module.ts`,lt({pascal:l,kebab:c,plural:u,repo:i,style:o})),await m(`${c}.constants.ts`,xt({pascal:l,kebab:c})),await m(`${c}.controller.ts`,dt({pascal:l,kebab:c,plural:u,pluralPascal:d})),await m(`${c}.service.ts`,bt({pascal:l,kebab:c})),await m(`dtos/create-${c}.dto.ts`,on(l,n)),await m(`dtos/update-${c}.dto.ts`,sn(l,n)),await m(`dtos/${c}-response.dto.ts`,cn(l,n)),await m(`${c}.repository.ts`,ht({pascal:l,kebab:c,dtoPrefix:`./dtos`,tokenScope:a}));let h=i===`inmemory`,_=h?`in-memory-${c}`:`${L(i)}-${c}`,v=h?gt({pascal:l,kebab:c,repoPrefix:`.`,dtoPrefix:`./dtos`}):_t({pascal:l,kebab:c,repoType:i,repoPrefix:`.`,dtoPrefix:`./dtos`});return await m(`${_}.repository.ts`,v),await Et(r,l,u,c,o),p}function on(e,t){return`import { z } from 'zod'
|
|
1129
1200
|
|
|
1130
1201
|
export const create${e}Schema = z.object({
|
|
1131
1202
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -1133,7 +1204,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
|
|
|
1133
1204
|
})
|
|
1134
1205
|
|
|
1135
1206
|
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
1136
|
-
`}function
|
|
1207
|
+
`}function sn(e,t){return`import { z } from 'zod'
|
|
1137
1208
|
|
|
1138
1209
|
export const update${e}Schema = z.object({
|
|
1139
1210
|
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
@@ -1141,14 +1212,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
|
1141
1212
|
})
|
|
1142
1213
|
|
|
1143
1214
|
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
1144
|
-
`}function
|
|
1215
|
+
`}function cn(e,t){return`export interface ${e}ResponseDTO {
|
|
1145
1216
|
id: string
|
|
1146
1217
|
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
1147
1218
|
`)}
|
|
1148
1219
|
createdAt: string
|
|
1149
1220
|
updatedAt: string
|
|
1150
1221
|
}
|
|
1151
|
-
`}async function
|
|
1222
|
+
`}async function ln(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=L(t),o=F(t),s=[],c;if(e.outDir)c=j(e.outDir);else if(n){let e=L(n),t=i?R(e):e;c=j(k(r??`src/modules`,t,`__tests__`))}else c=j(`src/__tests__`);let l=k(c,`${a}.test.ts`);return await g(l,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
1152
1223
|
import { Container } from '@forinda/kickjs'
|
|
1153
1224
|
|
|
1154
1225
|
describe('${o}', () => {
|
|
@@ -1171,53 +1242,53 @@ describe('${o}', () => {
|
|
|
1171
1242
|
expect(true).toBe(true)
|
|
1172
1243
|
})
|
|
1173
1244
|
})
|
|
1174
|
-
`),s.push(
|
|
1175
|
-
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const
|
|
1176
|
-
(dry run — no files were written)`),console.log()}async function
|
|
1245
|
+
`),s.push(l),s}var un=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
|
|
1246
|
+
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const dn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function W(e){return e.parent?.opts()?.dryRun??!1}function G(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(`
|
|
1247
|
+
(dry run — no files were written)`),console.log()}async function fn(e){if(!e)try{let e=await f(process.cwd());await be({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 pn=[{name:`module <name>`,description:`REST module (controller, service, DTOs, 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:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{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`}],mn=new Set(pn.map(e=>e.name.split(` `)[0]));async function hn(){console.log(`
|
|
1177
1248
|
Built-in generators:
|
|
1178
|
-
`);let e=Math.max(...
|
|
1249
|
+
`);let e=Math.max(...pn.map(e=>e.name.length));for(let t of pn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await f(process.cwd()),n=p(t?.plugins??[],t?.commands??[]),r=await nt(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
1179
1250
|
Plugin generators:
|
|
1180
1251
|
`);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(`
|
|
1181
1252
|
Failed to load:
|
|
1182
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function
|
|
1183
|
-
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,
|
|
1184
|
-
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,
|
|
1253
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function gn(e,t,n){let r=await f(process.cwd()),i=u(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??wt(i.repo);t.repo&&d(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,p=l(r,process.cwd()),m=i.style??`define`;if(!n&&m===`define`){let e=await en(j(a),`define`);if(e.length>0){console.error(`\n ${x.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${x.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${x.bold(`Files needing migration:`)}`);for(let t of e.slice(0,5))console.error(` - ${t}`);e.length>5&&console.error(` … and ${e.length-5} more`),console.error(`\n ${x.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${x.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${x.dim(`// kick.config.ts`)}\n ${x.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let h=[];for(let r of e){let e=await Tt({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:p,style:i.style});h.push(...e)}G(h,n),await fn(n)}function _n(e,t){let n=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 name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | 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,r,i)=>{if(r.list){await hn();return}if(!e||e.length===0){n.help();return}let a=W(i);h(a);let[o,s,...c]=e;if(o){let e=await f(process.cwd()),n=p(e?.plugins??[],e?.commands??[]),i=await tt({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){G(i.files,a);return}if(o!==`module`&&mn.has(o)){console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`),process.exitCode=1;return}}await gn(e,r,a)});n.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 name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | 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=W(n);h(r),await gn(e,{...n.optsWithGlobals(),...t},r)}),n.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=W(n);h(r),G(await Nt({name:e,outDir:j(t.out)}),r)}),n.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=W(n);h(r),G(await Pt({name:e,outDir:j(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate an Express middleware function
|
|
1254
|
+
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=W(n);h(r);let i=await f(process.cwd()),a=u(i),o=a.dir??`src/modules`;G(await It({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
1255
|
+
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=W(n);h(r);let i=await f(process.cwd()),a=u(i),o=a.dir??`src/modules`;G(await Lt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
1185
1256
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1186
1257
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
1187
|
-
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,
|
|
1188
|
-
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,
|
|
1189
|
-
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,
|
|
1190
|
-
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,
|
|
1191
|
-
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,
|
|
1258
|
+
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=W(n);h(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await f(process.cwd()),o=u(a),s=o.dir??`src/modules`;G(await zt({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
1259
|
+
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=W(n);h(r);let i=await f(process.cwd()),a=u(i),o=a.dir??`src/modules`;G(await Bt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
1260
|
+
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=W(n);h(r);let i=await f(process.cwd()),a=u(i),o=a.dir??`src/modules`;G(await Vt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await fn(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
1261
|
+
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=W(n);h(r);let i=await f(process.cwd()),a=u(i),o=a.dir??`src/modules`;G(await Ht({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
1262
|
+
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=W(n);h(r);let i=u(await f(process.cwd())),a=i.dir??`src/modules`;G(await ln({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.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=W(n);h(r),G(await tn({name:e,outDir:j(t.out),queue:t.queue}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
1192
1263
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1193
1264
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
1194
1265
|
Optional: append :optional (shell-safe): description:text:optional
|
|
1195
|
-
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,
|
|
1266
|
+
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=W(r);h(i),t.length===0&&(console.error(`
|
|
1196
1267
|
Error: At least one field is required.
|
|
1197
1268
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1198
1269
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1199
1270
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
1200
|
-
`),process.exit(1));let
|
|
1201
|
-
`,u=``;if(w(i)&&(u=await N(i,`utf8`)),u===l){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check){c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i});continue}await P(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new
|
|
1271
|
+
`),process.exit(1));let a=await f(process.cwd()),o=u(a),s=n.modulesDir??o.dir??`src/modules`,c=rn(t),d=l(a,process.cwd()),p=await an({name:e,fields:c,modulesDir:j(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:d,style:o.style});console.log(`\n Scaffolded ${e} with ${c.length} field(s):`);for(let e of c)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);G(p,i),await fn(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=W(t);h(n),G(await Ut({outDir:j(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.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 | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=W(t);h(n);let r=e.only??`all`;if(!dn.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${dn.join(` | `)}`),process.exitCode=1;return}G(await ne({outDir:j(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])vn(n,e,t?.projectRoot)}function vn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=W(o);h(s);let c=await tt({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&G(c.files,s)})}async function yn(e){let t=D.resolve(e.cwd,`.kickjs/types`);e.check||await Fe(t,{recursive:!0});let n=new Map,r=e.scan??fe,i=D.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(M(e).href)},async writeFile(t,n){let r=D.resolve(e.cwd,t);await Fe(D.dirname(r),{recursive:!0}),await P(r,n,`utf8`)},getScanResult:e=>{let t=bn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?de(s,a):r(s),n.set(t,o)}return o},log:console},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=D.join(t,`${n.id.replace(/\//g,`__`)}${r}`),a;try{a=await n.generate(o)}catch(t){let r=t instanceof Error?t.message:String(t);if(e.check)throw Error(`kick typegen --check: ${n.id} failed to generate (${r})`,{cause:t});o.log.error(` ${n.id}: typegen failed (${r}) — keeping previous output`),s.push({id:n.id,status:`error`,outFile:i});continue}if(a===null){s.push({id:n.id,status:`skipped`});continue}let l=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+a+`
|
|
1272
|
+
`,u=``;if(w(i)&&(u=await N(i,`utf8`)),u===l){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check){c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i});continue}await P(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new un(c);return s}function bn(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 xn(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var Sn=e({applyDisableFilter:()=>xn,runAllPluginTypegens:()=>wn});function Cn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}async function wn(e){let{enabled:t,skipped:n,unknown:r}=xn(p([...Vi,...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 yn({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Cn())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof un||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function Tn(e){let t=new Map;return{report(n,r){let i=r instanceof Error?r.message:String(r);t.get(n)!==i&&(t.set(n,i),e(` kick typegen: ${n} pass failed (${i}) — types in .kickjs/types may be stale`))},clear(e){t.delete(e)}}}function En(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-ByZnBYdj.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Sn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-ByZnBYdj.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-BX7-8d5h.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=D.resolve(t,n?.typegen?.outDir??`.kickjs/types`),c=n?.assetMap?Object.values(n.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>D.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,u=e=>e.replaceAll(`\\`,`/`),d=c.map(u),f=e=>{let t=u(e);return d.some(e=>t===e||t.startsWith(`${e}/`))},p=Tn(e.emitWarning),m=null,h=!1,g=new Set,_=new Set,v=!1,y=!1;function b(r,c){i.runTypegen({cwd:t,silent:!0,allowDuplicates:!0,schemaValidator:a,envFile:o,srcDir:n?.typegen?.srcDir,outDir:n?.typegen?.outDir,assetMap:n?.assetMap,changedFiles:r,runPlugins:!1}).then(()=>p.clear(`scan`)).catch(e=>p.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>p.clear(`plugins`)).catch(e=>p.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function x(){let e=v?void 0:{changed:[...g],removed:[..._]},t=y;g.clear(),_.clear(),v=!1,y=!1,b(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!h&&!u(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)v=!0,l&&(y=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=f(t);if(!n&&!r)return;r&&l&&(y=!0),n&&(e===`unlink`?(_.add(t),g.delete(t)):(g.add(t),_.delete(t)))}m&&clearTimeout(m),m=setTimeout(x,r)}},runOnce(){h||b(void 0,l)},dispose(){h=!0,m&&clearTimeout(m),m=null}}}function Dn(e){let t=k(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=k(t,i);if(w(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function On(e){let t=e.spawnFn??Ne,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function kn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
1202
1273
|
`):`${n.slice(0,t).join(`
|
|
1203
|
-
`)}\n… ${n.length-t} more line(s)`}function
|
|
1274
|
+
`)}\n… ${n.length-t} more line(s)`}function An(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function jn(e,t,n={}){t&&(process.env.PORT=t);let r=An(n.polling),i=process.cwd(),a=await f(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await be({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})`)}let c=j(i,a?.typegen?.outDir??`.kickjs/types`);try{await pe(c,await wn({cwd:i,config:a}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),{createServer:u}=await import(M(l(j(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let d=await u({configFile:j(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??a?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=Dn(i);e?m=On({cwd:i,bin:e,onResult:e=>{d.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?h||(h=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(h=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(kn(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let g=En({cwd:i,config:a,emitWarning:e=>{console.warn(e),d.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>m?.schedule()});d.watcher.on(`add`,e=>g.handleWatchEvent(`add`,e)),d.watcher.on(`unlink`,e=>g.handleWatchEvent(`unlink`,e)),d.watcher.on(`change`,e=>g.handleWatchEvent(`change`,e)),d.watcher.on(`unlinkDir`,e=>g.handleWatchEvent(`unlinkDir`,e)),g.assetSrcRoots.length>0&&d.watcher.add([...g.assetSrcRoots]),await d.listen(),d.printUrls(),console.log(`
|
|
1204
1275
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
1205
|
-
`),m?.schedule();let _=!1,v=async()=>{if(!_){_=!0,g.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await
|
|
1276
|
+
`),m?.schedule();let _=!1,v=async()=>{if(!_){_=!0,g.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await d.close(),process.exit(0)}};process.on(`SIGINT`,v),process.on(`SIGTERM`,v),process.on(`SIGBREAK`,v)}function Mn(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)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await jn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
1206
1277
|
Error: vite is not installed.
|
|
1207
1278
|
Run: pnpm add -D vite unplugin-swc
|
|
1208
1279
|
`):console.error(`
|
|
1209
1280
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1210
1281
|
Building for production...
|
|
1211
|
-
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(M(e(j(`package.json`)).resolve(`vite`)).href);await t({configFile:j(`vite.config.ts`)});let n=await
|
|
1212
|
-
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(!w(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}
|
|
1213
|
-
Building asset map...`);try{await
|
|
1282
|
+
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(M(e(j(`package.json`)).resolve(`vite`)).href);await t({configFile:j(`vite.config.ts`)});let n=await f(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
|
|
1283
|
+
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(!w(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}Te(i,{recursive:!0}),we(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
|
|
1284
|
+
Building asset map...`);try{await Se(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
1214
1285
|
Build complete.
|
|
1215
|
-
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await
|
|
1216
|
-
Building asset map...`);try{await
|
|
1286
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await f(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
1287
|
+
Building asset map...`);try{await Se(e,{cwd:process.cwd()}),console.log(`
|
|
1217
1288
|
Asset build complete.
|
|
1218
|
-
`)}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)),
|
|
1219
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function
|
|
1220
|
-
`))})}const{bold:K,dim:q,green:
|
|
1289
|
+
`)}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)),c(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 jn(e.entry,e.port)}catch(e){console.error(`
|
|
1290
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Nn(){try{let e=O(je(import.meta.url));return JSON.parse(T(k(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Pn=new Set(Object.values(a).filter(e=>e.deprecated).map(e=>e.pkg));function Fn(e){let t=k(e,`package.json`);if(!w(t))return[];let n;try{n=JSON.parse(T(t,`utf-8`))}catch{return[]}let r={...n.dependencies,...n.devDependencies};return Object.keys(r).filter(e=>e===`@forinda/kickjs`||e.startsWith(`@forinda/kickjs-`)).toSorted().map(t=>{let n=null,i=k(e,`node_modules`,...t.split(`/`),`package.json`);if(w(i))try{n=JSON.parse(T(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Pn.has(t)}})}function In(e){let t=e;for(;;){if(w(k(t,`package.json`)))return t;let e=O(t);if(e===t)return null;t=e}}function Ln(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Nn()}`,``,` System:`,` OS: ${Ve()} ${He()} (${Be()})`,` Node: ${process.version}`],t=In(process.cwd()),n=t?Fn(t):[];if(!t)e.push(``,` Packages: (not inside a project — no package.json found)`);else if(n.length===0)e.push(``,` Packages: (no @forinda/kickjs* dependencies in ${t})`);else{e.push(``,` Packages:`);let t=Math.max(...n.map(e=>e.name.length));for(let r of n){let n=r.installed??`${r.declared??`?`} (declared — not installed)`,i=r.deprecated?" [DEPRECATED — see `kick add --list --all`]":``;e.push(` ${r.name.padEnd(t+2)} ${n}${i}`)}}e.push(``),console.log(e.join(`
|
|
1291
|
+
`))})}const{bold:K,dim:q,green:Rn,red:J,yellow:zn,blue:Bn}=x;function Vn(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 Hn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Y(e,t){try{return await Hn(`${e}${t}`)}catch{return null}}async function Un(e){let[t,n,r,i,a]=await Promise.all([Y(e,`/health`),Y(e,`/metrics`),Y(e,`/routes`),Y(e,`/container`),Y(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function Wn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Rn(`● healthy`):J(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${J(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?J:r.errorRate>0?zn:Rn;console.log(` ${K(`Uptime:`)} ${Vn(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${K(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(s),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${b(e.method)} ${t} ${Bn(e.controller)}.${q(e.handler)}`)}}console.log(s),console.log()}function Gn(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 Un(r);t.json?console.log(JSON.stringify(e,null,2)):Wn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(J(` ✖ Could not connect to ${n}`)),console.error(q(` ${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 Kn(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function X(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const qn=[{match(e,t){let n=Kn(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(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
|
|
1221
1292
|
registers the env schema with kickjs at module-load time. Without it,
|
|
1222
1293
|
ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
|
|
1223
1294
|
and every user-defined key reads as undefined. @Value() may *appear* to
|
|
@@ -1239,7 +1310,7 @@ describe('UserController', () => {
|
|
|
1239
1310
|
beforeEach(() => Container.reset())
|
|
1240
1311
|
|
|
1241
1312
|
it('does the thing', async () => { /* ... */ })
|
|
1242
|
-
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
1313
|
+
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Kn(e,[`Module`,`is not a function`])||Kn(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
|
|
1243
1314
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
1244
1315
|
returns the controller wiring. This was a deliberate choice — modules
|
|
1245
1316
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -1291,24 +1362,24 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
1291
1362
|
import { UserModule } from './users/user.module'
|
|
1292
1363
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
1293
1364
|
|
|
1294
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}}];function
|
|
1365
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}}];function Jn(e,t){let n=null;for(let r of qn){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 Yn(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.
|
|
1295
1366
|
export OPENAI_API_KEY="sk-..."
|
|
1296
1367
|
|
|
1297
1368
|
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:
|
|
1298
1369
|
kick add ai
|
|
1299
1370
|
|
|
1300
1371
|
Or manually:
|
|
1301
|
-
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o
|
|
1302
|
-
`)}function
|
|
1372
|
+
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Xn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Zn((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 Xn(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://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
1373
|
+
`)}function Zn(e){let t=[e,Qn(e),$n(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(er(t))return t}catch{continue}return null}function Qn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function $n(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 er(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 tr(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 ir(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
1303
1374
|
|
|
1304
1375
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
1305
1376
|
kick explain "config.get returned undefined"
|
|
1306
1377
|
pnpm test 2>&1 | kick explain
|
|
1307
|
-
`),process.exit(1));let r=
|
|
1308
|
-
`);return}if(i){
|
|
1309
|
-
`),process.exit(2)),
|
|
1310
|
-
`),process.exit(a.kind===`ok`?0:2)),
|
|
1311
|
-
`)}function
|
|
1378
|
+
`),process.exit(1));let r=or(),i=Jn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
1379
|
+
`);return}if(i){sr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
1380
|
+
`),process.exit(2)),cr(n,!1),process.exit(2));let a=await Yn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(nr(a),null,2)+`
|
|
1381
|
+
`),process.exit(a.kind===`ok`?0:2)),rr(n,a),process.exit(a.kind===`ok`?0:2)})}function nr(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 rr(e,t){if(t.kind===`ok`){sr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Q(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Z(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Q(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function ir(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:ar()}function ar(){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 or(){let e=process.cwd();return{cwd:e,hasFile:t=>w(j(e,t))}}function sr(e,t,n,r=!1){let i=Q(e.trim(),200),a=r?`AI-generated — verify before applying`:lr(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${Z(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Z(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Z(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Z(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
1382
|
+
`)}function cr(e,t){let n=Q(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.
|
|
1312
1383
|
When @forinda/kickjs-ai ships its provider implementations,
|
|
1313
1384
|
this command will call the configured LLM with the error +
|
|
1314
1385
|
project context and return a structured fix.
|
|
@@ -1327,10 +1398,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1327
1398
|
|
|
1328
1399
|
`)}function Z(e,t){return e.split(`
|
|
1329
1400
|
`).map(e=>`${t}${e}`).join(`
|
|
1330
|
-
`)}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function
|
|
1331
|
-
`,`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
|
|
1401
|
+
`)}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function lr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function ur(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(dr),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(fr)}function dr(e){let t=j(e.entry);w(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=Ne(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 fr(e){let t=process.cwd(),n=pr(t)??ke(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(w(i))try{let e=T(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,Oe(i,JSON.stringify(o,null,2)+`
|
|
1402
|
+
`,`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 pr(e){let t=j(e,`package.json`);if(!w(t))return null;try{let e=T(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function mr(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);w(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=gr(t,`tsx`);r||(console.error(`
|
|
1332
1403
|
Error: tsx not found. Install it: pnpm add -D tsx
|
|
1333
|
-
`),process.exit(1));let i=
|
|
1404
|
+
`),process.exit(1));let i=hr(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=Me(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function hr(e,t){return`
|
|
1334
1405
|
import 'reflect-metadata'
|
|
1335
1406
|
|
|
1336
1407
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -1384,41 +1455,41 @@ server.on('exit', () => {
|
|
|
1384
1455
|
console.log('\\n Goodbye!\\n')
|
|
1385
1456
|
process.exit(0)
|
|
1386
1457
|
})
|
|
1387
|
-
`}function
|
|
1458
|
+
`}function gr(e,t){let n=e;for(;;){let e=k(n,`node_modules`,`.bin`,t);if(w(e))return e;let r=j(n,`..`);if(r===n)break;n=r}return null}function _r(e,t){let n=RegExp(`^\\s*${z(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
|
|
1388
1459
|
`;)s++;else{for(s+=2;s+1<a.length&&(a[s]!==`*`||a[s+1]!==`/`);)s++;s+=2}continue}let t=a[s]??``;if(t===`'`||t===`"`||t==="`"){let e=t;for(s++;s<a.length&&a[s]!==e;)a[s]===`\\`&&s++,s++}else if(t===`(`)o++;else if(t===`)`&&(o--,o===0))break;s++}if(o!==0)break;let c=a.slice(t,s);if(n.test(c)){let t=e;for(;t>0&&(a[t-1]===` `||a[t-1]===` `||a[t-1]===`
|
|
1389
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function
|
|
1460
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function vr(e,t){let n=Ot(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=_r(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${z(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function yr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=L(t),o=F(t),s=i?R(a):a,c=k(n,s);if(!await _(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await S({message:x.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
1390
1461
|
Cancelled.
|
|
1391
|
-
`);return}await
|
|
1462
|
+
`);return}await Le(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=k(n,`index.ts`);if(await _(l)){let e=await N(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${z(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${z(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=vr(e,o),e=e.replace(/\n{3,}/g,`
|
|
1392
1463
|
|
|
1393
|
-
`),e!==t&&(await P(
|
|
1464
|
+
`),e!==t&&(await P(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function br(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=u(await f(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await yr({name:n,modulesDir:j(r),force:t.force,pluralize:i})})}function xr(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;if(e===`kickjs-schema`||e===`schema`)return`kickjs-schema`;console.warn(` kick typegen: unknown --schema-validator '${e}' (supported: 'zod', 'kickjs-schema', 'false'). Falling back to project config.`)}}function Sr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Cr(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: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=oe(process.cwd()),n=await f(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-CrbgblqR.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Bi),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(`
|
|
1394
1465
|
Registered typegen plugins:
|
|
1395
|
-
`);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=
|
|
1466
|
+
`);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=xr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Sr(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ve(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 be(a);let r=await wn({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&r.some(e=>e.status===`written`)&&process.exit(1),e.check||await pe(j(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof ye?console.error(`
|
|
1396
1467
|
`+e.message+`
|
|
1397
|
-
`):e instanceof
|
|
1468
|
+
`):e instanceof un?console.error(`
|
|
1398
1469
|
`+e.message+`
|
|
1399
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function
|
|
1470
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function wr(e){let t=[];if(!w(e))return t;let n=E(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(...wr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Tr(e){try{return T(e,`utf-8`)}catch{return``}}const Er=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Dr(e,t){let n=Tr(k(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Er.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 Or(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 kr(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 Ar(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function jr(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 Mr(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 Nr(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 Pr(e){let t=wr(k(e,`src`)).map(e=>Tr(e)),n=[],r=Dr(e,t);r&&n.push(r);let i=Or(t);i&&n.push(i);let a=kr(t);a&&n.push(a);let o=Ar();o&&n.push(o);let s=jr(t);return s&&n.push(s),n.push(Mr(t)),n.push(Nr(t)),n}function Fr(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
|
|
1400
1471
|
Usage: kick check --deploy
|
|
1401
1472
|
|
|
1402
1473
|
Available checks:
|
|
1403
1474
|
--deploy Audit for production readiness (security, config, best practices)
|
|
1404
|
-
`);return}let t=process.cwd();
|
|
1405
|
-
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function
|
|
1475
|
+
`);return}let t=process.cwd();ee(`KickJS Deploy Check`);let n=te();n.start(`Scanning project...`);let r=Pr(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)v.message(`${ie(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?x.red(`${a} critical`):`${a} critical`,o>0?x.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(C(x.red(`${l} — fix critical issues before deploying`)),process.exit(1)):C(x.green(`${l} — looking good!`))})}function Ir(e){try{return JSON.parse(T(e,`utf-8`))}catch{return null}}function Lr(e){try{return T(e,`utf-8`)}catch{return null}}function Rr(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function zr(e){let t=k(e,`tsconfig.json`);if(w(t))return Br(t,new Set)}function Br(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Lr(e);if(n===null)return null;let r=Rr(n);if(typeof r!=`object`||!r)return null;let i=Array.isArray(r.extends)?r.extends:typeof r.extends==`string`?[r.extends]:[],a={};for(let n of i){if(typeof n!=`string`)continue;let r=Vr(O(e),n);if(!r)continue;let i=Br(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Vr(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return Hr(j(e,t));let n=e;for(;;){let e=Hr(k(n,`node_modules`,t));if(e)return e;let r=O(n);if(r===n)break;n=r}return null}function Hr(e){if(w(e)){try{if(De(e).isDirectory()){let t=k(e,`tsconfig.json`);return w(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return w(t)?t:null}function Ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Wr(){let e=process.version,t=Number.parseInt(e.replace(/^v/,``).split(`.`)[0],10);return Number.isNaN(t)||t<20?{name:`Node version`,status:`fail`,message:e,fix:`KickJS requires Node 20 or newer.
|
|
1476
|
+
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Gr(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function Kr(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:"`@forinda/kickjs` declares `express` as a required peer dependency, but your package.json does not include it. Install: pnpm add express"}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const qr={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function Jr(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=qr[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: pnpm add ${n.join(` `)}`}:{name:r,status:`pass`}}function Yr(e){if(!e.pkg||!Zr(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const Xr=2e3;function Zr(e){let t=k(e,`src`);if(!w(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<Xr;){let e=r.pop(),t;try{t=E(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=Xr)break;let t=k(e,a.name);if(a.isDirectory()){a.name!==`node_modules`&&r.push(t);continue}if(/\.(ts|tsx|mts|cts)$/.test(a.name)&&(i++,n.test(Lr(t)??``)))return!0}}return!1}function Qr(e){if(!e.pkg)return{name:`reflect-metadata installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies};return t[`reflect-metadata`]?{name:`reflect-metadata installed`,status:`pass`,message:t[`reflect-metadata`]}:{name:`reflect-metadata installed`,status:`fail`,fix:`KickJS decorators require the reflect-metadata polyfill.
|
|
1406
1477
|
Install it: pnpm add reflect-metadata
|
|
1407
1478
|
Then import it at the top of src/index.ts:
|
|
1408
1479
|
|
|
1409
1480
|
import 'reflect-metadata'
|
|
1410
|
-
// ... rest of bootstrap`}}function
|
|
1411
|
-
`).map(e=>` ${
|
|
1412
|
-
`)}function
|
|
1481
|
+
// ... rest of bootstrap`}}function $r(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function ei(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>k(e.cwd,t)).filter(e=>w(e)).filter(e=>/\bloadEnv\s*\(/.test(Lr(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>k(e.cwd,t)).find(e=>w(e));if(!n)return{name:`env wiring`,status:`warn`,message:`env-init file exists but no src/index.ts or src/main.ts found`};let r=Lr(n)??``,i=O(n),a=[];for(let e of t){let t=A(i,e).replace(/\\/g,`/`).replace(/\.ts$/,``),n=t.startsWith(`.`)?t:`./`+t,r=n.replace(/\/index$/,``);a.push(n,r);let o=e.replace(/\\/g,`/`).match(/\/src\/(.+?)(?:\.ts)?$/);if(o){let e=`@/`+o[1],t=e.replace(/\/index$/,``);a.push(e,t)}}let o=-1;for(let e of new Set(a)){let t=RegExp(`^import\\s+(?:.*?from\\s+)?['"]${Ur(e)}['"]`,`m`),n=r.match(t);n&&n.index!==void 0&&(o===-1||n.index<o)&&(o=n.index)}let s=r.search(/\bbootstrap\s*\(/),c=t.map(t=>A(e.cwd,t).replace(/\\/g,`/`)).join(`, `);return o===-1?{name:`env wiring`,status:`fail`,message:c,fix:`An env-init file (${c}) calls \`loadEnv(...)\` but \`${A(e.cwd,n).replace(/\\/g,`/`)}\` doesn't import it.\nWithout this, ConfigService.get('X') returns undefined while @Value('X') works via process.env fallback — a half-broken config you won't notice until something is missing.\n\nFix: add a side-effect import at the top of ${A(e.cwd,n).replace(/\\/g,`/`)} (above bootstrap()), pointing at one of the detected files. For example:\n\n import './env'\n // or\n import './config'\n // or, with the @/ alias:\n import '@/config/env'`}:s!==-1&&o>s?{name:`env wiring`,status:`warn`,message:`env-init imported AFTER bootstrap() — should be before`,fix:`Move the env import above the bootstrap() call so the schema runs before any service reads from ConfigService.`}:{name:`env wiring`,status:`pass`}}function ti(e,t=ni){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=E(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=k(e,o.name);if(o.isDirectory()){i.push(a);continue}try{let e=De(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const ni=2e3;function ri(e){let t=k(e.cwd,`.kickjs`,`types`);if(!w(t))return null;let n=ti(t);if(n===0)return null;let r=Date.now()-n,i=Math.floor(r/6e4);return i>60?{name:`typegen freshness`,status:`warn`,message:`last updated ${i} minutes ago`,fix:"Re-run `kick typegen` (or `kick dev`, which runs it on every reload) so generated types match the current code."}:{name:`typegen freshness`,status:`pass`,message:i===0?`just now`:`${i}m ago`}}const ii=[()=>Wr(),Gr,Kr,Jr,Yr,Qr,$r,ei,ri];async function ai(e,t={}){let n={cwd:e,pkg:Ir(k(e,`package.json`)),tsconfig:zr(e),runtime:t.runtime??`express`},r=[...ii,...t.extraChecks??[]],i=[];for(let e of r){let t;try{t=await e(n)}catch(t){i.push({name:e.name||`doctor check`,status:`fail`,message:t instanceof Error?t.message:String(t)});continue}t!=null&&(Array.isArray(t)?i.push(...t):i.push(t))}return i}function oi(e){switch(e){case`pass`:return x.green(`✔`);case`warn`:return x.yellow(`⚠`);case`fail`:return x.red(`✖`)}}function si(e){let t=oi(e.status),n=e.message?` ${x.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function ci(e){return e.split(`
|
|
1482
|
+
`).map(e=>` ${x.dim(`→`)} ${e}`).join(`
|
|
1483
|
+
`)}function li(e){return e?.doctor?.checks??[]}function ui(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=li(await f(e)),n=await o(e);ee(`KickJS Doctor`);let r=await ai(e,{extraChecks:t,runtime:n});for(let e of r)v.message(si(e)),e.fix&&e.status!==`pass`&&v.message(ci(e.fix));let i=r.filter(e=>e.status===`pass`).length,a=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[x.green(`${i} passed`),a>0?x.yellow(`${a} warning${a===1?``:`s`}`):`${a} warnings`,s>0?x.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(C(`${c} — fix the errors above before running the app`),process.exit(1)):C(a>0?`${c} — review the warnings`:x.green(`${c} — your environment looks good`))})}function di(e){return e.optsWithGlobals().dryRun??!1}function fi(e){e.command(`codemod`).description(`Codebase migration commands (AST-style rewrites — distinct from db migrate)`).command(`modules`).description(`Rewrite module declarations between class form and the defineModule factory.
|
|
1413
1484
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
1414
1485
|
--target define|class Override the migration direction.
|
|
1415
1486
|
--apply Apply the changes (default: dry-run preview).
|
|
1416
|
-
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let
|
|
1417
|
-
`+
|
|
1487
|
+
--experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=di(t)||!e.apply;h(n),e.experimental||(console.error(`
|
|
1488
|
+
`+x.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
1418
1489
|
The regex-based rewrite handles the shapes our templates produce.
|
|
1419
1490
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
1420
1491
|
Always commit before running with --apply.
|
|
1421
|
-
`),process.exit(1));let
|
|
1492
|
+
`),process.exit(1));let r=u(await f(process.cwd())),i=j(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${x.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=x.dim(`→ ${a}`),s=n?x.dim(`(dry-run)`):x.bold(`(applying)`);console.log(`\n ${x.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${x.dim(i)}\n`);let c=e.backup!==!1&&!n,l=await $t(i,{dryRun:n,target:a,backup:c});if(l.backupDir){let e=l.backupDir;console.log(` ${x.green(`✓`)} backup: ${x.dim(e)}\n ${x.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${x.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,p=0;for(let e of l.files)if(e.status===`migrated`)d++,console.log(` ${x.green(`✓`)} ${e.path}`);else{p++;let t=x.dim(`(${e.reason??`skipped`})`);console.log(` ${x.dim(`-`)} ${e.path} ${t}`)}if(console.log(),l.indexStatus===`migrated`)console.log(` ${x.green(`✓`)} ${l.indexPath}`);else if(l.indexStatus===`skipped`){let e=x.dim(`(${l.indexReason??`skipped`})`);console.log(` ${x.dim(`-`)} ${l.indexPath} ${e}`)}else console.log(` ${x.dim(`-`)} ${l.indexPath} ${x.dim(`(not found)`)}`);let m=n?x.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${x.bold(String(d))} migrated, ${x.bold(String(p))} skipped${m}\n`)})}const pi=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!w(D.resolve(e.cwd,`kick.config.ts`)))return null;let t=await f(e.cwd);if(!t?.assetMap)return null;let n=se(t.assetMap,e.cwd);return n.count===0?null:ge(n)}}),mi="/* 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 hi(e,t,n,r={}){if(e.length===0)return`${mi}
|
|
1422
1493
|
// (no routes discovered yet — annotate a controller method with
|
|
1423
1494
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1424
1495
|
declare global {
|
|
@@ -1435,14 +1506,14 @@ declare global {
|
|
|
1435
1506
|
|
|
1436
1507
|
/** Empty until the first route exists — see kick typegen. */
|
|
1437
1508
|
export const kickRpc = {} as const
|
|
1438
|
-
`;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=
|
|
1509
|
+
`;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=yi(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??_i(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=vi(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${gi(e)}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
1439
1510
|
`))}let u=[],d=new Set,f=new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;if(d.has(t)){r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`);continue}d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`)}let p=[` interface Api {`,...u,` }`].join(`
|
|
1440
|
-
`);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=
|
|
1511
|
+
`);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=Si(e);if(h.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}h.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&m.push(` ${n}: {\n${i.join(`
|
|
1441
1512
|
`)}\n },`)}let g=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...m,`} as const`].join(`
|
|
1442
|
-
`),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=
|
|
1513
|
+
`),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=xi(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
|
|
1443
1514
|
`)+`
|
|
1444
|
-
`:``,b=
|
|
1445
|
-
`);return`${
|
|
1515
|
+
`:``,b=bi(a)+y,x=l.join(`
|
|
1516
|
+
`);return`${mi}${b}
|
|
1446
1517
|
declare global {
|
|
1447
1518
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1448
1519
|
namespace KickRoutes {
|
|
@@ -1454,9 +1525,9 @@ ${x}
|
|
|
1454
1525
|
}
|
|
1455
1526
|
|
|
1456
1527
|
${g}
|
|
1457
|
-
`}function
|
|
1528
|
+
`}function gi(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function _i(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 vi(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 yi(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=xi(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 bi(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(`
|
|
1458
1529
|
`)+`
|
|
1459
|
-
`}function
|
|
1530
|
+
`}function xi(e,t,n){if(e===null)return`unknown`;let r=O(n);if(e===``){let e=A(r,t).split(Ae).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(Ae).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function Si(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const Ci=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:wi(e),cwd:e.cwd,envFile:Ti(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return hi(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function wi(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ti(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Ei(e,t,n=`zod`){if(!e)return null;let r=A(O(t),e.filePath).split(Ae).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
|
|
1460
1531
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1461
1532
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1462
1533
|
|
|
@@ -1494,5 +1565,5 @@ declare global {
|
|
|
1494
1565
|
}
|
|
1495
1566
|
|
|
1496
1567
|
export {}
|
|
1497
|
-
`}const
|
|
1498
|
-
`)}});var
|
|
1568
|
+
`}const Di=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=ki(e);if(t===!1)return null;let n=await e.getScanResult({root:Oi(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=D.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Ei(n.env,i,r)}});function Oi(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ki(e){return e.config?.typegen?.envFile}function Ai(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ji(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ai(e),cwd:e.cwd,envFile:ji(e)}}const Mi=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=D.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return _e(t.classes,n,r)}}),Ni=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className));return he(`ServiceToken`,me(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Pi=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return he(`ModuleToken`,ce((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Fi=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return ue((await e.getScanResult($(e))).pluginsAndAdapters)}}),Ii=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return xe((await e.getScanResult($(e))).augmentations)}}),Li=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:le(t.contextKeys)}}),Ri={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},zi=()=>({id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=Ri[t];return[`// Runtime escape-hatch types for the '${t}' engine (kick.config runtime).`,`declare module '@forinda/kickjs' {`,` interface KickRuntimeRegister {`,` runtime: import('${n}').${r}`,` }`,`}`,``,`export {}`,``].join(`
|
|
1569
|
+
`)}});var Bi=e({builtinCliPlugins:()=>Vi});const Vi=[m({name:`kick/init`,register:We}),m({name:`kick/generate`,register:_n}),m({name:`kick/run`,register:Mn}),m({name:`kick/info`,register:Ln}),m({name:`kick/inspect`,register:Gn}),m({name:`kick/add`,register:t}),m({name:`kick/list`,register:i}),m({name:`kick/explain`,register:tr}),m({name:`kick/mcp`,register:ur}),m({name:`kick/tinker`,register:mr}),m({name:`kick/remove`,register:br}),m({name:`kick/typegen`,register:Cr}),m({name:`kick/check`,register:Fr}),m({name:`kick/doctor`,register:ui}),m({name:`kick/codemod`,register:fi}),m({name:`kick/registry`,typegens:[Mi()]}),m({name:`kick/services`,typegens:[Ni()]}),m({name:`kick/modules`,typegens:[Pi()]}),m({name:`kick/plugins`,typegens:[Fi()]}),m({name:`kick/augmentations`,typegens:[Ii()]}),m({name:`kick/context`,typegens:[Li()]}),m({name:`kick/assets`,typegens:[pi()]}),m({name:`kick/routes`,typegens:[Ci()]}),m({name:`kick/env`,typegens:[Di()]}),m({name:`kick/runtime`,typegens:[zi()]})];export{Sn as n,Vi as t};
|