@forinda/kickjs-cli 6.7.0 → 6.9.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-BEaN-yVq.mjs +11 -0
- package/dist/{agent-docs-tlau7tZv.mjs → agent-docs-NyyqHAxw.mjs} +3 -3
- package/dist/{agent-docs-tlau7tZv.mjs.map → agent-docs-NyyqHAxw.mjs.map} +1 -1
- package/dist/{build-CDi72mKz.mjs → build-CNy9rla8.mjs} +3 -3
- package/dist/{build-CDi72mKz.mjs.map → build-CNy9rla8.mjs.map} +1 -1
- package/dist/build-DBdGEMiZ.mjs +12 -0
- package/dist/builtins-DR3wYkm4.mjs +1498 -0
- package/dist/{builtins-BiTg6p4D.mjs → builtins-epL6Z9Me.mjs} +2 -2
- package/dist/cli.mjs +2 -2838
- package/dist/config-BQy8iVib.mjs +12 -0
- package/dist/{config-D6C74vFp.mjs → config-BnGHE669.mjs} +3 -3
- package/dist/{config-D6C74vFp.mjs.map → config-BnGHE669.mjs.map} +1 -1
- package/dist/{doctor-BHnei8KS.mjs → doctor-26f-Bu4P.mjs} +29 -28
- package/dist/doctor-26f-Bu4P.mjs.map +1 -0
- package/dist/{fullstack-Cmedpn8G.mjs → fullstack-CeSmhGE2.mjs} +4 -4
- package/dist/{fullstack-Cmedpn8G.mjs.map → fullstack-CeSmhGE2.mjs.map} +1 -1
- package/dist/{fullstack-e-wuEMD0.mjs → fullstack-DUPLtANA.mjs} +3 -3
- package/dist/index.d.mts +48 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -3
- package/dist/plugin-C3PeTJQb.mjs +11 -0
- package/dist/{plugin-BlWy4Nbd.mjs → plugin-RBStrEDQ.mjs} +3 -3
- package/dist/{plugin-BlWy4Nbd.mjs.map → plugin-RBStrEDQ.mjs.map} +1 -1
- package/dist/{project-CnU7KcYI.mjs → project-DxcX4ryE.mjs} +6 -6
- package/dist/{project-CnU7KcYI.mjs.map → project-DxcX4ryE.mjs.map} +1 -1
- package/dist/project-Op2Qt1bv.mjs +389 -0
- package/dist/{project-docs-BV-h5EmP.mjs → project-docs-BQ022LVW.mjs} +47 -11
- package/dist/project-docs-BQ022LVW.mjs.map +1 -0
- package/dist/project-docs-uEIleRls.mjs +928 -0
- package/dist/{project-root-CdqXle6R.mjs → project-root-BifjB5PL.mjs} +3 -3
- package/dist/{project-root-CdqXle6R.mjs.map → project-root-BifjB5PL.mjs.map} +1 -1
- package/dist/project-root-CtnL9FBb.mjs +11 -0
- package/dist/{prompts-D7bKHNce.mjs → prompts-j1nmMgAf.mjs} +2 -2
- package/dist/{prompts-D7bKHNce.mjs.map → prompts-j1nmMgAf.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DiP_G7eI.mjs → rolldown-runtime-DOk7ha8c.mjs} +1 -1
- package/dist/{run-plugins-C5kGYAsD.mjs → run-plugins-BouWvZvo.mjs} +79 -66
- package/dist/run-plugins-BouWvZvo.mjs.map +1 -0
- package/dist/typegen-DRSOapGb.mjs +114 -0
- package/dist/typegen-DRSOapGb.mjs.map +1 -0
- package/dist/typegen-b-Siu3FR.mjs +113 -0
- package/dist/{types-BNOSmSFj.mjs → types-DSOcCoe_.mjs} +1 -1
- package/package.json +5 -5
- package/dist/doctor-BHnei8KS.mjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/project-docs-BV-h5EmP.mjs.map +0 -1
- package/dist/run-plugins-C5kGYAsD.mjs.map +0 -1
- package/dist/typegen-qeQ5co2C.mjs +0 -114
- package/dist/typegen-qeQ5co2C.mjs.map +0 -1
|
@@ -0,0 +1,1498 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-cli v6.9.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{t as e}from"./rolldown-runtime-DOk7ha8c.mjs";import{a as t,i as n,o as r,r as i}from"./config-BQy8iVib.mjs";import{n as a,r as o}from"./plugin-C3PeTJQb.mjs";import{c as s,l as c,s as l}from"./project-docs-uEIleRls.mjs";import{a as u,c as d,i as f,o as p,r as m,s as h,t as g}from"./project-Op2Qt1bv.mjs";import{a as _,c as v,d as y,f as b,i as x,l as ee,n as te,o as ne,p as re,r as S,s as C,u as ie}from"./agent-docs-BEaN-yVq.mjs";import{t as ae}from"./project-root-CtnL9FBb.mjs";import{a as oe,c as se,d as ce,f as le,g as ue,h as de,i as fe,l as pe,m as me,o as he,p as ge,r as _e,s as ve,t as ye,u as be}from"./typegen-b-Siu3FR.mjs";import{t as xe}from"./build-DBdGEMiZ.mjs";import{createRequire as Se}from"node:module";import{cpSync as Ce,existsSync as w,mkdirSync as we,readFileSync as T,readdirSync as E,rmSync as Te,statSync as Ee,writeFileSync as De}from"node:fs";import D,{basename as Oe,dirname as O,join as k,relative as A,resolve as j,sep as ke}from"node:path";import{fileURLToPath as Ae,pathToFileURL as M}from"node:url";import{execSync as je,fork as Me,spawn as Ne,spawnSync as Pe}from"node:child_process";import{copyFile as Fe,mkdir as Ie,readFile as N,readdir as Le,rm as Re,stat as ze,writeFile as P}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import Be from"pluralize";import{arch as Ve,platform as He,release as Ue}from"node:os";function We(e,t,n){je(e,{cwd:t,stdio:`inherit`,env:n?{...process.env,...n}:process.env})}function Ge(e,t,n){let r=Pe(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}const Ke=[{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 qe(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)=>{x(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await ie({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=j(`.`),e=Oe(i)):i=j(t.directory||e),w(i)){let r=E(i);if(r.length>0){if(t.force)_.warn(`Clearing existing files in ${i}`);else if(n){_.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),C(`Aborted.`);return}else{_.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)_.message(` - ${e}`);if(r.length>5&&_.message(` ... and ${r.length-5} more`),!await S({message:b.red(`Remove all existing files and proceed?`),initialValue:!1})){C(`Aborted.`);return}}for(let e of r)Te(j(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await v({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||=n?`express`:await v({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 s=t.pm;s||=n?await d(void 0):await v({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let c=t.repo;c||=n?`inmemory`:await ie({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),r(c);let l=t.schema;l||=n?`zod`:await v({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(l)||(_.warn(`Unknown --schema "${l}", falling back to zod.`),l=`zod`);let u;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();u=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else u=n?[]:await ne({message:`Select packages to include`,options:[...Ke],required:!1});let f;f=t.git===void 0?n?!0:await S({message:`Initialize git repository?`,initialValue:!0}):t.git;let p;if(p=t.install===void 0?n?!0:await S({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DUPLtANA.mjs`);await t({name:e,directory:i,packageManager:s,initGit:f,installDeps:p,schemaLib:l,runtime:o}),C(`Done! Next steps: ${b.cyan(`cd ${e} && ${s}${s===`pnpm`?` dev`:` run dev:server`}`)}`);return}await g({name:e,directory:i,packageManager:s,initGit:f,installDeps:p,template:a,defaultRepo:c,packages:u,schemaLib:l,runtime:o}),C(`Done! Next steps: ${b.cyan(`cd ${e} && ${s} 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 Be.plural(e)}function Je(e){return Be.plural(e)}function Ye(e){return L(e).replace(/-/g,`_`)}function Xe(e){let t=e.cwd??process.cwd(),n=e.projectRoot??ae(t),r=e.pluralize??!0,i=F(e.name),a=I(e.name),o=L(e.name),s=Ye(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 Ze(e,t){return j(e.cwd,t)}async function Qe(e){return import(M(e).href)}const $e=new Map;async function et(e){let t=$e.get(e);if(t)return t;let n=tt(e);return $e.set(e,n),n}async function tt(e){let t=j(e,`package.json`);if(!w(t))return{generators:[],loaded:[],failed:[]};let n=nt(JSON.parse(await N(t,`utf-8`))),r=Se(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 Qe(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(!rt(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 nt(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 rt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function it(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return st(r.spec,r.source,e,n);let i=ot(await et(n),e.generatorName);return i?st(i.spec,i.source,e,n):null}async function at(e,t=[]){let n=await et(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 ot(e,t){return e.generators.find(e=>e.spec.name===t)}async function st(e,t,n,r){let i=Xe({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=Ze(i,e.path);await c(t,e.content),o.push(t)}return{files:o,source:t}}function z(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ct(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function lt(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function ut(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]??`${ct(n)}${e}Repository`,repoFile:i[n]??`${lt(n)}-${t}`}}function dt(e){return e??`define`}function ft(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=ut(t,n,i),c=dt(a),l=`/**
|
|
12
|
+
* ${t} Module
|
|
13
|
+
*
|
|
14
|
+
* REST module with a flat folder structure.
|
|
15
|
+
* Controller delegates to service, service wraps the repository.
|
|
16
|
+
*
|
|
17
|
+
* Structure:
|
|
18
|
+
* ${n}.controller.ts — HTTP routes (CRUD)
|
|
19
|
+
* ${n}.service.ts — Business logic
|
|
20
|
+
* ${n}.repository.ts — Repository interface
|
|
21
|
+
* ${s}.repository.ts — Repository implementation
|
|
22
|
+
* dtos/ — Request/response schemas
|
|
23
|
+
*/`,u=`import { ${t.toUpperCase()}_REPOSITORY } from './${n}.repository'
|
|
24
|
+
import { ${o} } from './${s}.repository'
|
|
25
|
+
import { ${t}Controller } from './${n}.controller'
|
|
26
|
+
|
|
27
|
+
// Eagerly load decorated classes so @Controller()/@Service()/@Repository() decorators
|
|
28
|
+
// register in the DI container. Recursive globs (./**/) so the module keeps working
|
|
29
|
+
// however you nest files (e.g. moving controllers into a controllers/ sub-folder).
|
|
30
|
+
import.meta.glob(
|
|
31
|
+
['./**/*.controller.ts', './**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'],
|
|
32
|
+
{ eager: true },
|
|
33
|
+
)`,d=` /**
|
|
34
|
+
* Declare HTTP routes for this module. Return value shape:
|
|
35
|
+
*
|
|
36
|
+
* - \`path\` — URL prefix for this route set.
|
|
37
|
+
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
38
|
+
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
39
|
+
*
|
|
40
|
+
* Return an **array** to mount multiple route sets — admin
|
|
41
|
+
* surfaces, side-by-side v1 + v2 controllers, etc:
|
|
42
|
+
*
|
|
43
|
+
* return [
|
|
44
|
+
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
45
|
+
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
46
|
+
* ]
|
|
47
|
+
*/`;return c===`class`?`${l}
|
|
48
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
49
|
+
${u}
|
|
50
|
+
|
|
51
|
+
export class ${t}Module implements AppModule {
|
|
52
|
+
register(container: Container): void {
|
|
53
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
54
|
+
container.resolve(${o}),
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
59
|
+
routes(): ModuleRoutes {
|
|
60
|
+
return {
|
|
61
|
+
path: '/${r}',
|
|
62
|
+
controller: ${t}Controller,
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
`:`${l}
|
|
67
|
+
import { defineModule } from '@forinda/kickjs'
|
|
68
|
+
${u}
|
|
69
|
+
|
|
70
|
+
export const ${t}Module = defineModule({
|
|
71
|
+
name: '${t}Module',
|
|
72
|
+
build: () => ({
|
|
73
|
+
register(container) {
|
|
74
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
75
|
+
container.resolve(${o}),
|
|
76
|
+
)
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
${d}
|
|
80
|
+
routes() {
|
|
81
|
+
return {
|
|
82
|
+
path: '/${r}',
|
|
83
|
+
controller: ${t}Controller,
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
}),
|
|
87
|
+
})
|
|
88
|
+
`}function pt(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=dt(i),o=` /**
|
|
89
|
+
* Declare HTTP routes. Return value shape:
|
|
90
|
+
*
|
|
91
|
+
* - \`path\` — URL prefix for this route set.
|
|
92
|
+
* - \`controller\` — Controller class (also drives OpenAPI).
|
|
93
|
+
* - \`version\` — Optional. Overrides the app-wide API version.
|
|
94
|
+
*
|
|
95
|
+
* Return an array to mount multiple route sets:
|
|
96
|
+
*
|
|
97
|
+
* return [
|
|
98
|
+
* { path: '/${r}', version: 1, controller: ${t}V1Controller },
|
|
99
|
+
* { path: '/${r}', version: 2, controller: ${t}V2Controller },
|
|
100
|
+
* ]
|
|
101
|
+
*/`;return a===`class`?`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
102
|
+
import { ${t}Controller } from './${n}.controller'
|
|
103
|
+
|
|
104
|
+
export class ${t}Module implements AppModule {
|
|
105
|
+
${o.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
106
|
+
routes(): ModuleRoutes {
|
|
107
|
+
return {
|
|
108
|
+
path: '/${r}',
|
|
109
|
+
controller: ${t}Controller,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
`:`import { defineModule } from '@forinda/kickjs'
|
|
114
|
+
import { ${t}Controller } from './${n}.controller'
|
|
115
|
+
|
|
116
|
+
export const ${t}Module = defineModule({
|
|
117
|
+
name: '${t}Module',
|
|
118
|
+
build: () => ({
|
|
119
|
+
${o}
|
|
120
|
+
routes() {
|
|
121
|
+
return {
|
|
122
|
+
path: '/${r}',
|
|
123
|
+
controller: ${t}Controller,
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
}),
|
|
127
|
+
})
|
|
128
|
+
`}function mt(e){let{pascal:t,kebab:n}=e,r=t.charAt(0).toLowerCase()+t.slice(1);return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
129
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
130
|
+
import { ${t}Service } from './${n}.service'
|
|
131
|
+
import { create${t}Schema } from './dtos/create-${n}.dto'
|
|
132
|
+
import { update${t}Schema } from './dtos/update-${n}.dto'
|
|
133
|
+
import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
134
|
+
|
|
135
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${t}Controller['<method>']>\`
|
|
136
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
137
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
138
|
+
// \`kick dev\`) — see https://kickjs.app/guide/typegen.
|
|
139
|
+
|
|
140
|
+
@Controller()
|
|
141
|
+
export class ${t}Controller {
|
|
142
|
+
@Autowired() private readonly ${r}Service!: ${t}Service
|
|
143
|
+
|
|
144
|
+
@Get('/')
|
|
145
|
+
@ApiTags('${t}')
|
|
146
|
+
@ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
147
|
+
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
148
|
+
return ctx.paginate(
|
|
149
|
+
(parsed) => this.${r}Service.findPaginated(parsed),
|
|
150
|
+
${t.toUpperCase()}_QUERY_CONFIG,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
@Get('/:id')
|
|
155
|
+
@ApiTags('${t}')
|
|
156
|
+
async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
157
|
+
const result = await this.${r}Service.findById(ctx.params.id)
|
|
158
|
+
if (!result) return ctx.notFound('${t} not found')
|
|
159
|
+
ctx.json(result)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
163
|
+
@ApiTags('${t}')
|
|
164
|
+
async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
165
|
+
const result = await this.${r}Service.create(ctx.body)
|
|
166
|
+
ctx.created(result)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
@Put('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
170
|
+
@ApiTags('${t}')
|
|
171
|
+
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
172
|
+
const result = await this.${r}Service.update(ctx.params.id, ctx.body)
|
|
173
|
+
ctx.json(result)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
@Delete('/:id')
|
|
177
|
+
@ApiTags('${t}')
|
|
178
|
+
async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
179
|
+
await this.${r}Service.delete(ctx.params.id)
|
|
180
|
+
ctx.noContent()
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
`}function ht(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Create ${t} DTO — Zod schema for validating POST request bodies.
|
|
187
|
+
* This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
|
|
188
|
+
* It also generates OpenAPI request body docs when SwaggerAdapter is used.
|
|
189
|
+
*
|
|
190
|
+
* Add more fields as needed. Supported Zod types:
|
|
191
|
+
* z.string(), z.number(), z.boolean(), z.enum([...]),
|
|
192
|
+
* z.array(), z.object(), .optional(), .default(), .transform()
|
|
193
|
+
*/
|
|
194
|
+
export const create${t}Schema = z.object({
|
|
195
|
+
name: z.string().min(1, 'Name is required').max(200),
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
export type Create${t}DTO = z.infer<typeof create${t}Schema>
|
|
199
|
+
`}function gt(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
200
|
+
|
|
201
|
+
export const update${t}Schema = z.object({
|
|
202
|
+
name: z.string().min(1).max(200).optional(),
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
export type Update${t}DTO = z.infer<typeof update${t}Schema>
|
|
206
|
+
`}function _t(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
207
|
+
id: string
|
|
208
|
+
name: string
|
|
209
|
+
createdAt: string
|
|
210
|
+
updatedAt: string
|
|
211
|
+
}
|
|
212
|
+
`}function vt(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
|
|
213
|
+
* ${t} Repository Interface
|
|
214
|
+
*
|
|
215
|
+
* Defines the contract for data access.
|
|
216
|
+
* The interface declares what operations are available;
|
|
217
|
+
* implementations (in-memory, Drizzle, Prisma) fulfill the contract.
|
|
218
|
+
*
|
|
219
|
+
* To swap implementations, change the factory in the module's register() method.
|
|
220
|
+
*/
|
|
221
|
+
import { createToken } from '@forinda/kickjs'
|
|
222
|
+
import type { ${t}ResponseDTO } from '${r}/${n}-response.dto'
|
|
223
|
+
import type { Create${t}DTO } from '${r}/create-${n}.dto'
|
|
224
|
+
import type { Update${t}DTO } from '${r}/update-${n}.dto'
|
|
225
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
226
|
+
|
|
227
|
+
export interface I${t}Repository {
|
|
228
|
+
findById(id: string): Promise<${t}ResponseDTO | null>
|
|
229
|
+
findAll(): Promise<${t}ResponseDTO[]>
|
|
230
|
+
findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }>
|
|
231
|
+
create(dto: Create${t}DTO): Promise<${t}ResponseDTO>
|
|
232
|
+
update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO>
|
|
233
|
+
delete(id: string): Promise<void>
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Collision-safe DI token bound to \`I${t}Repository\`.
|
|
238
|
+
* \`container.resolve(${t.toUpperCase()}_REPOSITORY)\` and
|
|
239
|
+
* \`@Inject(${t.toUpperCase()}_REPOSITORY)\` both return the typed
|
|
240
|
+
* interface — no manual generic, no \`any\` cast.
|
|
241
|
+
*
|
|
242
|
+
* The \`'${i}/'\` prefix matches the project scope so
|
|
243
|
+
* \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
|
|
244
|
+
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
245
|
+
*/
|
|
246
|
+
export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
|
|
247
|
+
`}function yt(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
248
|
+
* In-Memory ${t} Repository
|
|
249
|
+
*
|
|
250
|
+
* Implements the repository interface using a Map.
|
|
251
|
+
* Useful for prototyping and testing. Replace with a database implementation
|
|
252
|
+
* (Drizzle, Prisma, etc.) for production use.
|
|
253
|
+
*
|
|
254
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
255
|
+
*/
|
|
256
|
+
import { randomUUID } from 'node:crypto'
|
|
257
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
258
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
259
|
+
import type { I${t}Repository } from '${r}/${n}.repository'
|
|
260
|
+
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
261
|
+
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
262
|
+
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
263
|
+
|
|
264
|
+
@Repository()
|
|
265
|
+
export class InMemory${t}Repository implements I${t}Repository {
|
|
266
|
+
private store = new Map<string, ${t}ResponseDTO>()
|
|
267
|
+
|
|
268
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
269
|
+
return this.store.get(id) ?? null
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
273
|
+
return Array.from(this.store.values())
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
277
|
+
const all = Array.from(this.store.values())
|
|
278
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
279
|
+
return { data, total: all.length }
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
283
|
+
const now = new Date().toISOString()
|
|
284
|
+
const entity: ${t}ResponseDTO = {
|
|
285
|
+
id: randomUUID(),
|
|
286
|
+
...dto,
|
|
287
|
+
createdAt: now,
|
|
288
|
+
updatedAt: now,
|
|
289
|
+
}
|
|
290
|
+
this.store.set(entity.id, entity)
|
|
291
|
+
return entity
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
295
|
+
const existing = this.store.get(id)
|
|
296
|
+
if (!existing) throw HttpException.notFound('${t} not found')
|
|
297
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
298
|
+
this.store.set(id, updated)
|
|
299
|
+
return updated
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async delete(id: string): Promise<void> {
|
|
303
|
+
if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
|
|
304
|
+
this.store.delete(id)
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
`}function bt(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
|
+
* ${o} ${t} Repository
|
|
309
|
+
*
|
|
310
|
+
* Stub implementation for a custom '${r}' repository.
|
|
311
|
+
* Implements the repository interface using an in-memory Map as a placeholder.
|
|
312
|
+
*
|
|
313
|
+
* TODO: Replace the in-memory Map with your ${r} data-access logic.
|
|
314
|
+
* See I${t}Repository for the interface contract.
|
|
315
|
+
*
|
|
316
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
317
|
+
*/
|
|
318
|
+
import { randomUUID } from 'node:crypto'
|
|
319
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
320
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
321
|
+
import type { I${t}Repository } from '${i}/${n}.repository'
|
|
322
|
+
import type { ${t}ResponseDTO } from '${a}/${n}-response.dto'
|
|
323
|
+
import type { Create${t}DTO } from '${a}/create-${n}.dto'
|
|
324
|
+
import type { Update${t}DTO } from '${a}/update-${n}.dto'
|
|
325
|
+
|
|
326
|
+
@Repository()
|
|
327
|
+
export class ${o}${t}Repository implements I${t}Repository {
|
|
328
|
+
// TODO: Replace with your ${r} client/connection
|
|
329
|
+
private store = new Map<string, ${t}ResponseDTO>()
|
|
330
|
+
|
|
331
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
332
|
+
// TODO: Implement with ${r}
|
|
333
|
+
return this.store.get(id) ?? null
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
337
|
+
// TODO: Implement with ${r}
|
|
338
|
+
return Array.from(this.store.values())
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
342
|
+
// TODO: Implement with ${r}
|
|
343
|
+
const all = Array.from(this.store.values())
|
|
344
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
345
|
+
return { data, total: all.length }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
349
|
+
// TODO: Implement with ${r}
|
|
350
|
+
const now = new Date().toISOString()
|
|
351
|
+
const entity: ${t}ResponseDTO = {
|
|
352
|
+
id: randomUUID(),
|
|
353
|
+
...dto,
|
|
354
|
+
createdAt: now,
|
|
355
|
+
updatedAt: now,
|
|
356
|
+
}
|
|
357
|
+
this.store.set(entity.id, entity)
|
|
358
|
+
return entity
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
362
|
+
// TODO: Implement with ${r}
|
|
363
|
+
const existing = this.store.get(id)
|
|
364
|
+
if (!existing) throw HttpException.notFound('${t} not found')
|
|
365
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
366
|
+
this.store.set(id, updated)
|
|
367
|
+
return updated
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async delete(id: string): Promise<void> {
|
|
371
|
+
// TODO: Implement with ${r}
|
|
372
|
+
if (!this.store.has(id)) throw HttpException.notFound('${t} not found')
|
|
373
|
+
this.store.delete(id)
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
`}function xt(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
377
|
+
import { Container } from '@forinda/kickjs'
|
|
378
|
+
|
|
379
|
+
describe('${t}Controller', () => {
|
|
380
|
+
beforeEach(() => {
|
|
381
|
+
Container.reset()
|
|
382
|
+
})
|
|
383
|
+
|
|
384
|
+
it('should be defined', () => {
|
|
385
|
+
expect(true).toBe(true)
|
|
386
|
+
})
|
|
387
|
+
|
|
388
|
+
describe('POST /${r}', () => {
|
|
389
|
+
it('should create a new ${n}', async () => {
|
|
390
|
+
// TODO: Set up test module, call create endpoint, assert 201
|
|
391
|
+
expect(true).toBe(true)
|
|
392
|
+
})
|
|
393
|
+
})
|
|
394
|
+
|
|
395
|
+
describe('GET /${r}', () => {
|
|
396
|
+
it('should return paginated ${r}', async () => {
|
|
397
|
+
// TODO: Set up test module, call list endpoint, assert { data, meta }
|
|
398
|
+
expect(true).toBe(true)
|
|
399
|
+
})
|
|
400
|
+
})
|
|
401
|
+
|
|
402
|
+
describe('GET /${r}/:id', () => {
|
|
403
|
+
it('should return a ${n} by id', async () => {
|
|
404
|
+
// TODO: Create a ${n}, then fetch by id, assert match
|
|
405
|
+
expect(true).toBe(true)
|
|
406
|
+
})
|
|
407
|
+
|
|
408
|
+
it('should return 404 for non-existent ${n}', async () => {
|
|
409
|
+
// TODO: Fetch non-existent id, assert 404
|
|
410
|
+
expect(true).toBe(true)
|
|
411
|
+
})
|
|
412
|
+
})
|
|
413
|
+
|
|
414
|
+
describe('PUT /${r}/:id', () => {
|
|
415
|
+
it('should update an existing ${n}', async () => {
|
|
416
|
+
// TODO: Create, update, assert changes
|
|
417
|
+
expect(true).toBe(true)
|
|
418
|
+
})
|
|
419
|
+
})
|
|
420
|
+
|
|
421
|
+
describe('DELETE /${r}/:id', () => {
|
|
422
|
+
it('should delete a ${n}', async () => {
|
|
423
|
+
// TODO: Create, delete, assert gone
|
|
424
|
+
expect(true).toBe(true)
|
|
425
|
+
})
|
|
426
|
+
})
|
|
427
|
+
})
|
|
428
|
+
`}function St(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
|
+
import { InMemory${t}Repository } from '${i}'
|
|
430
|
+
|
|
431
|
+
describe('InMemory${t}Repository', () => {
|
|
432
|
+
let repo: InMemory${t}Repository
|
|
433
|
+
|
|
434
|
+
beforeEach(() => {
|
|
435
|
+
repo = new InMemory${t}Repository()
|
|
436
|
+
})
|
|
437
|
+
|
|
438
|
+
it('should create and retrieve a ${n}', async () => {
|
|
439
|
+
const created = await repo.create({ name: 'Test ${t}' })
|
|
440
|
+
expect(created).toBeDefined()
|
|
441
|
+
expect(created.name).toBe('Test ${t}')
|
|
442
|
+
expect(created.id).toBeDefined()
|
|
443
|
+
|
|
444
|
+
const found = await repo.findById(created.id)
|
|
445
|
+
expect(found).toEqual(created)
|
|
446
|
+
})
|
|
447
|
+
|
|
448
|
+
it('should return null for non-existent id', async () => {
|
|
449
|
+
const found = await repo.findById('non-existent')
|
|
450
|
+
expect(found).toBeNull()
|
|
451
|
+
})
|
|
452
|
+
|
|
453
|
+
it('should list all ${r}', async () => {
|
|
454
|
+
await repo.create({ name: '${t} 1' })
|
|
455
|
+
await repo.create({ name: '${t} 2' })
|
|
456
|
+
|
|
457
|
+
const all = await repo.findAll()
|
|
458
|
+
expect(all).toHaveLength(2)
|
|
459
|
+
})
|
|
460
|
+
|
|
461
|
+
it('should return paginated results', async () => {
|
|
462
|
+
await repo.create({ name: '${t} 1' })
|
|
463
|
+
await repo.create({ name: '${t} 2' })
|
|
464
|
+
await repo.create({ name: '${t} 3' })
|
|
465
|
+
|
|
466
|
+
const result = await repo.findPaginated({
|
|
467
|
+
filters: [],
|
|
468
|
+
sort: [],
|
|
469
|
+
search: '',
|
|
470
|
+
pagination: { page: 1, limit: 2, offset: 0 },
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
expect(result.data).toHaveLength(2)
|
|
474
|
+
expect(result.total).toBe(3)
|
|
475
|
+
})
|
|
476
|
+
|
|
477
|
+
it('should update a ${n}', async () => {
|
|
478
|
+
const created = await repo.create({ name: 'Original' })
|
|
479
|
+
const updated = await repo.update(created.id, { name: 'Updated' })
|
|
480
|
+
expect(updated.name).toBe('Updated')
|
|
481
|
+
})
|
|
482
|
+
|
|
483
|
+
it('should delete a ${n}', async () => {
|
|
484
|
+
const created = await repo.create({ name: 'To Delete' })
|
|
485
|
+
await repo.delete(created.id)
|
|
486
|
+
const found = await repo.findById(created.id)
|
|
487
|
+
expect(found).toBeNull()
|
|
488
|
+
})
|
|
489
|
+
})
|
|
490
|
+
`}function Ct(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
491
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
492
|
+
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
|
|
493
|
+
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
494
|
+
import type { Create${t}DTO } from './dtos/create-${n}.dto'
|
|
495
|
+
import type { Update${t}DTO } from './dtos/update-${n}.dto'
|
|
496
|
+
|
|
497
|
+
@Service()
|
|
498
|
+
export class ${t}Service {
|
|
499
|
+
constructor(
|
|
500
|
+
@Inject(${t.toUpperCase()}_REPOSITORY) private readonly repo: I${t}Repository,
|
|
501
|
+
) {}
|
|
502
|
+
|
|
503
|
+
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
504
|
+
return this.repo.findById(id)
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
async findAll(): Promise<${t}ResponseDTO[]> {
|
|
508
|
+
return this.repo.findAll()
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async findPaginated(parsed: ParsedQuery) {
|
|
512
|
+
return this.repo.findPaginated(parsed)
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
516
|
+
return this.repo.create(dto)
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async update(id: string, dto: Update${t}DTO): Promise<${t}ResponseDTO> {
|
|
520
|
+
return this.repo.update(id, dto)
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async delete(id: string): Promise<void> {
|
|
524
|
+
await this.repo.delete(id)
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
`}function wt(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
528
|
+
|
|
529
|
+
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
530
|
+
filterable: ['name'],
|
|
531
|
+
sortable: ['name', 'createdAt'],
|
|
532
|
+
searchable: ['name'],
|
|
533
|
+
}
|
|
534
|
+
`}async function Tt(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,pt({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, type Ctx } from '@forinda/kickjs'
|
|
535
|
+
|
|
536
|
+
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
537
|
+
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
538
|
+
|
|
539
|
+
@Controller()
|
|
540
|
+
export class ${t}Controller {
|
|
541
|
+
@Get('/')
|
|
542
|
+
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
543
|
+
ctx.json({ message: '${t} list' })
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
`)}async function Et(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`,ft({pascal:t,kebab:n,plural:r,repo:a,style:c})),await l(`${n}.constants.ts`,wt({pascal:t,kebab:n})),await l(`${n}.controller.ts`,mt({pascal:t,kebab:n,plural:r,pluralPascal:i})),await l(`${n}.service.ts`,Ct({pascal:t,kebab:n})),await l(`dtos/create-${n}.dto.ts`,ht({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,gt({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,_t({pascal:t,kebab:n})),await l(`${n}.repository.ts`,vt({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:s}));let u=a===`inmemory`,d=u?`in-memory-${n}`:`${L(a)}-${n}`,f=u?yt({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}):bt({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`,yt({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,xt({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,St({pascal:t,kebab:n,plural:r,repoPrefix:`../in-memory-${n}.repository`})))}function Dt(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Ot(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,u=e.pluralize!==!1,d=e.pattern??`rest`;e.minimal&&(d=`minimal`);let f=L(t),p=F(t),m=u?R(f):f,h=u?Je(p):p,g=k(n,m),v=[],y=o??!1,x={kebab:f,pascal:p,plural:m,pluralPascal:h,moduleDir:g,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(g,e);if(s){v.push(n);return}if(!y&&await l(n)&&!await S({message:`File exists: ${b.dim(e)}. Overwrite?`,initialValue:!1})){_.warn(`Skipped: ${e}`);return}await c(n,t),v.push(n)},files:v};switch(d){case`minimal`:await Tt(x);break;default:await Et(x);break}return s||await kt(n,p,m,f,x.style),v}async function kt(e,t,n,r,i=`define`){let a=k(e,`index.ts`),o=await l(a),s=`./${n}/${r}.module`,u=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await c(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
547
|
+
import { ${t}Module } from '${s}'
|
|
548
|
+
|
|
549
|
+
export const modules: AppModuleEntry[] = [${u}]
|
|
550
|
+
`:`import { defineModules } from '@forinda/kickjs'
|
|
551
|
+
import { ${t}Module } from '${s}'
|
|
552
|
+
|
|
553
|
+
export const modules = defineModules().mount(${u})
|
|
554
|
+
`);return}let d=await N(a,`utf-8`),f=`import { ${t}Module } from '${s}'`,p=z(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${z(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${p}['"]`,`m`).test(d)){let e=d.lastIndexOf(`import `);if(e!==-1){let t=d.indexOf(`
|
|
555
|
+
`,e);d=d.slice(0,t+1)+f+`
|
|
556
|
+
`+d.slice(t+1)}else d=f+`
|
|
557
|
+
`+d}let m=jt(d);if(m){let e=d.slice(m.rhsStart,m.rhsEnd+1);RegExp(`\\b${z(t)}Module\\b`).test(e)||(d=At(d,u))}else d=At(d,u);await P(a,d,`utf-8`)}function At(e,t){let n=jt(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 jt(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=Pt(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=Mt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function Mt(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=Ft(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=Ft(e,t);if(n===-1)break;i=n+1}return i}function Nt(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
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 Pt(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=Nt(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 Ft(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=Nt(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 It(e){let{name:t,outDir:n}=e,r=L(t),i=F(t),a=[],o=k(n,`${r}.adapter.ts`);return await c(o,`import {
|
|
559
|
+
defineAdapter,
|
|
560
|
+
type AdapterContext,
|
|
561
|
+
type AdapterMiddleware,
|
|
562
|
+
type ContributorRegistrations,
|
|
563
|
+
type Constructor,
|
|
564
|
+
} from '@forinda/kickjs'
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Configuration for the ${i} adapter.
|
|
568
|
+
*
|
|
569
|
+
* Adapters typically take a small config object so callers can tune
|
|
570
|
+
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
571
|
+
* derived from the environment should be read inside the build
|
|
572
|
+
* function via getEnv(), not forced onto the caller.
|
|
573
|
+
*/
|
|
574
|
+
export interface ${i}AdapterConfig {
|
|
575
|
+
// Add your adapter configuration here, e.g.:
|
|
576
|
+
// enabled?: boolean
|
|
577
|
+
// apiKey?: string
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* ${i} adapter — built via \`defineAdapter()\` so callers get the
|
|
582
|
+
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
583
|
+
*
|
|
584
|
+
* Hooks into the Application lifecycle to add middleware, routes,
|
|
585
|
+
* Context Contributors, or external service connections.
|
|
586
|
+
*
|
|
587
|
+
* Every lifecycle hook below is OPTIONAL. The scaffold emits all of
|
|
588
|
+
* them so adopters can browse what's available and delete what they
|
|
589
|
+
* don't need — \`build()\` returning \`{}\` is also valid for an adapter
|
|
590
|
+
* that only contributes config defaults.
|
|
591
|
+
*
|
|
592
|
+
* @example
|
|
593
|
+
* \`\`\`ts
|
|
594
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
595
|
+
* import { ${i}Adapter } from './adapters/${r}.adapter'
|
|
596
|
+
*
|
|
597
|
+
* bootstrap({
|
|
598
|
+
* modules,
|
|
599
|
+
* adapters: [${i}Adapter({ /* config overrides *\\/ })],
|
|
600
|
+
* })
|
|
601
|
+
* \`\`\`
|
|
602
|
+
*/
|
|
603
|
+
export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
604
|
+
name: '${i}Adapter',
|
|
605
|
+
defaults: {
|
|
606
|
+
// Default config values go here. The adopter's overrides shallow-merge
|
|
607
|
+
// on top of these before \`build()\` runs.
|
|
608
|
+
},
|
|
609
|
+
build: (_config, { name: _name }) => {
|
|
610
|
+
// Closures inside \`build()\` are how each adapter instance owns its
|
|
611
|
+
// own state (database client, Map, timer handle, …). The same
|
|
612
|
+
// \`_config\` is visible to every hook below.
|
|
613
|
+
|
|
614
|
+
return {
|
|
615
|
+
/**
|
|
616
|
+
* Express middleware entries the Application mounts at named phases.
|
|
617
|
+
*
|
|
618
|
+
* \`phase\` controls where each handler sits in the pipeline:
|
|
619
|
+
* 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
|
|
620
|
+
*
|
|
621
|
+
* \`path\` (optional) scopes the entry to a path prefix.
|
|
622
|
+
*
|
|
623
|
+
* Delete this hook entirely if you don't add middleware.
|
|
624
|
+
*/
|
|
625
|
+
middleware(): AdapterMiddleware[] {
|
|
626
|
+
return [
|
|
627
|
+
// Example: add a custom header to all responses
|
|
628
|
+
// {
|
|
629
|
+
// phase: 'beforeGlobal',
|
|
630
|
+
// handler: (_req, res, next) => {
|
|
631
|
+
// res.setHeader('X-${i}', 'true')
|
|
632
|
+
// next()
|
|
633
|
+
// },
|
|
634
|
+
// },
|
|
635
|
+
// Example: scope a rate limiter to one path prefix
|
|
636
|
+
// {
|
|
637
|
+
// phase: 'beforeRoutes',
|
|
638
|
+
// path: '/api/v1/auth',
|
|
639
|
+
// handler: rateLimit({ max: 10 }),
|
|
640
|
+
// },
|
|
641
|
+
]
|
|
642
|
+
},
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Runs BEFORE global middleware. Mount routes that should bypass the
|
|
646
|
+
* middleware stack — health checks, docs UI, static assets, OAuth
|
|
647
|
+
* callbacks. Anything you want reachable even if a global middleware
|
|
648
|
+
* later in the chain rejects requests.
|
|
649
|
+
*
|
|
650
|
+
* Delete this hook if you have no early routes.
|
|
651
|
+
*/
|
|
652
|
+
beforeMount(_ctx: AdapterContext): void {
|
|
653
|
+
// Example:
|
|
654
|
+
// _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
|
|
655
|
+
},
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Fires once per controller class as the router mounts. Use this to
|
|
659
|
+
* collect route metadata for OpenAPI specs, dependency graphs, route
|
|
660
|
+
* inventories, devtools dashboards.
|
|
661
|
+
*
|
|
662
|
+
* Delete this hook unless your adapter introspects the route registry.
|
|
663
|
+
*/
|
|
664
|
+
onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
|
|
665
|
+
// Example (Swagger-style): collect routes for the spec.
|
|
666
|
+
// openApiSpec.addController(_controllerClass, _mountPath)
|
|
667
|
+
},
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Runs AFTER modules + routes are wired, BEFORE the server starts.
|
|
671
|
+
* Right place for late-stage DI registrations or final config validation.
|
|
672
|
+
*
|
|
673
|
+
* Delete this hook if there's nothing to wire post-modules.
|
|
674
|
+
*/
|
|
675
|
+
beforeStart(_ctx: AdapterContext): void {
|
|
676
|
+
// Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
677
|
+
},
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
|
|
681
|
+
* available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
|
|
682
|
+
* gRPC, GraphQL subscriptions), warm caches, log a banner.
|
|
683
|
+
*
|
|
684
|
+
* Delete this hook if you don't need the running server reference.
|
|
685
|
+
*/
|
|
686
|
+
afterStart(_ctx: AdapterContext): void {
|
|
687
|
+
// Example: const io = new Server(_ctx.server)
|
|
688
|
+
},
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Returns Context Contributors to merge into every route's pipeline
|
|
692
|
+
* at the \`'adapter'\` precedence level. Per-route handlers can
|
|
693
|
+
* override the value at the method / class / module level.
|
|
694
|
+
*
|
|
695
|
+
* Delete this hook unless your adapter ships typed per-request values
|
|
696
|
+
* (auth user, tenant, locale, feature flags, geo, etc).
|
|
697
|
+
*/
|
|
698
|
+
contributors(): ContributorRegistrations {
|
|
699
|
+
return [
|
|
700
|
+
// Example:
|
|
701
|
+
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
702
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { id: string } } }
|
|
703
|
+
// const Load${i} = defineHttpContextDecorator({
|
|
704
|
+
// key: '${r}',
|
|
705
|
+
// resolve: (ctx) => ({ id: ctx.req.headers['x-${r}-id'] as string }),
|
|
706
|
+
// })
|
|
707
|
+
// return [Load${i}.registration]
|
|
708
|
+
]
|
|
709
|
+
},
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
|
|
713
|
+
* resources the adapter owns: close connections, flush buffers,
|
|
714
|
+
* cancel timers. The framework runs every adapter's \`shutdown\`
|
|
715
|
+
* concurrently via \`Promise.allSettled\` — one failure won't block
|
|
716
|
+
* sibling adapters.
|
|
717
|
+
*
|
|
718
|
+
* Delete this hook if your adapter holds no resources.
|
|
719
|
+
*/
|
|
720
|
+
async shutdown(): Promise<void> {
|
|
721
|
+
// Example: await this.pool.end()
|
|
722
|
+
// Example: clearInterval(this.heartbeatTimer)
|
|
723
|
+
},
|
|
724
|
+
}
|
|
725
|
+
},
|
|
726
|
+
})
|
|
727
|
+
`),a.push(o),a}async function Lt(e){let{name:t,outDir:n}=e,r=L(t),i=F(t),a=[],o=k(n,`${r}.plugin.ts`);return await c(o,`import {
|
|
728
|
+
definePlugin,
|
|
729
|
+
type AppAdapter,
|
|
730
|
+
type AppModuleEntry,
|
|
731
|
+
type Container,
|
|
732
|
+
type ContributorRegistrations,
|
|
733
|
+
} from '@forinda/kickjs'
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* Configuration for the ${i} plugin.
|
|
737
|
+
*
|
|
738
|
+
* Plugins typically take a small config object so callers can tune
|
|
739
|
+
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
740
|
+
* derived from the environment should be read inside the build
|
|
741
|
+
* function via getEnv(), not forced onto the caller.
|
|
742
|
+
*/
|
|
743
|
+
export interface ${i}PluginConfig {
|
|
744
|
+
// Add your plugin config here, e.g.:
|
|
745
|
+
// enabled?: boolean
|
|
746
|
+
// apiKey?: string
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* ${i} plugin — built via \`definePlugin()\` so callers get the
|
|
751
|
+
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
752
|
+
*
|
|
753
|
+
* A plugin bundles DI bindings, modules, adapters, and middleware
|
|
754
|
+
* into one object that can be added to \`bootstrap({ plugins })\`.
|
|
755
|
+
*
|
|
756
|
+
* Lifecycle order (each hook is optional — delete the ones you don't
|
|
757
|
+
* need and keep only the surface your plugin actually uses):
|
|
758
|
+
*
|
|
759
|
+
* 1. \`register(container)\` — runs before user modules load. Use
|
|
760
|
+
* it to bind services that modules depend on.
|
|
761
|
+
* 2. \`modules()\` — plugin modules load before user modules.
|
|
762
|
+
* 3. \`adapters()\` — plugin adapters mount before user adapters.
|
|
763
|
+
* 4. \`middleware()\` — plugin middleware runs before user middleware.
|
|
764
|
+
* 5. \`contributors()\` — Context Contributors merged into every route.
|
|
765
|
+
* 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
|
|
766
|
+
* 7. \`shutdown()\` — runs on graceful shutdown.
|
|
767
|
+
*
|
|
768
|
+
* @example
|
|
769
|
+
* \`\`\`ts
|
|
770
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
771
|
+
* import { ${i}Plugin } from './plugins/${r}.plugin'
|
|
772
|
+
*
|
|
773
|
+
* export const app = await bootstrap({
|
|
774
|
+
* modules,
|
|
775
|
+
* plugins: [${i}Plugin({ /* config overrides *\\/ })],
|
|
776
|
+
* })
|
|
777
|
+
* \`\`\`
|
|
778
|
+
*/
|
|
779
|
+
export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
780
|
+
name: '${i}Plugin',
|
|
781
|
+
defaults: {
|
|
782
|
+
// Default config values go here
|
|
783
|
+
},
|
|
784
|
+
build: (_config, { name: _name }) => ({
|
|
785
|
+
/**
|
|
786
|
+
* Register DI bindings before modules load.
|
|
787
|
+
* Use \`container.registerInstance(TOKEN, value)\` for singletons
|
|
788
|
+
* and \`container.registerFactory(TOKEN, () => ...)\` for lazy
|
|
789
|
+
* constructions.
|
|
790
|
+
*/
|
|
791
|
+
register(_container: Container): void {
|
|
792
|
+
// Example: _container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
793
|
+
},
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Return modules this plugin contributes to the app. These load
|
|
797
|
+
* before user modules, so plugin controllers and services are
|
|
798
|
+
* available for user code to \`@Autowired\`.
|
|
799
|
+
*
|
|
800
|
+
* Accepts both \`defineModule\`-style instances (call the factory:
|
|
801
|
+
* \`ExampleModule()\`) and legacy \`class … implements AppModule\`
|
|
802
|
+
* constructors.
|
|
803
|
+
*/
|
|
804
|
+
modules(): AppModuleEntry[] {
|
|
805
|
+
return [
|
|
806
|
+
// ExampleModule(),
|
|
807
|
+
]
|
|
808
|
+
},
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Return adapter instances to be added to the application.
|
|
812
|
+
* Plugin adapters mount before user adapters.
|
|
813
|
+
*/
|
|
814
|
+
adapters(): AppAdapter[] {
|
|
815
|
+
return [
|
|
816
|
+
// MyAdapter({ ... }),
|
|
817
|
+
]
|
|
818
|
+
},
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Return Express middleware entries to be added to the global
|
|
822
|
+
* pipeline. Plugin middleware runs before user-defined middleware.
|
|
823
|
+
*/
|
|
824
|
+
middleware(): unknown[] {
|
|
825
|
+
return [
|
|
826
|
+
// helmet(),
|
|
827
|
+
// myCustomMiddleware(_config),
|
|
828
|
+
]
|
|
829
|
+
},
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* Return Context Contributors to merge into every route's pipeline.
|
|
833
|
+
* Plugins contribute at the same \`'adapter'\` precedence level as
|
|
834
|
+
* adapters — overrideable per-route at the method / class / module
|
|
835
|
+
* level. See https://kickjs.app/guide/context-decorators
|
|
836
|
+
*
|
|
837
|
+
* Delete this hook if your plugin doesn't ship typed per-request values.
|
|
838
|
+
*/
|
|
839
|
+
contributors(): ContributorRegistrations {
|
|
840
|
+
return [
|
|
841
|
+
// Example:
|
|
842
|
+
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
843
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
|
|
844
|
+
// const Load${i} = defineHttpContextDecorator({
|
|
845
|
+
// key: '${r}',
|
|
846
|
+
// resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
|
|
847
|
+
// })
|
|
848
|
+
// return [Load${i}.registration]
|
|
849
|
+
]
|
|
850
|
+
},
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* Called after the application has fully bootstrapped. Use this
|
|
854
|
+
* for post-startup work like logging, health checks, or warming
|
|
855
|
+
* a cache. Runs once per process.
|
|
856
|
+
*/
|
|
857
|
+
async onReady(_container: Container): Promise<void> {
|
|
858
|
+
// const log = _container.resolve(Logger)
|
|
859
|
+
// log.info('${i} plugin ready')
|
|
860
|
+
},
|
|
861
|
+
|
|
862
|
+
/**
|
|
863
|
+
* Called during graceful shutdown. Clean up any long-lived
|
|
864
|
+
* resources this plugin owns (connections, timers, subscriptions).
|
|
865
|
+
*/
|
|
866
|
+
async shutdown(): Promise<void> {
|
|
867
|
+
// Example: await this.connection?.close()
|
|
868
|
+
},
|
|
869
|
+
}),
|
|
870
|
+
})
|
|
871
|
+
`),a.push(o),a}const Rt={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=Rt,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 zt(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),l=[],u=k(a,`${o}.middleware.ts`);return await c(u,`import type { Request, Response, NextFunction } from 'express'
|
|
872
|
+
|
|
873
|
+
export interface ${F(t)}Options {
|
|
874
|
+
// Add configuration options here. The factory below closes over the
|
|
875
|
+
// resolved options object; pass them at the call site —
|
|
876
|
+
// \`${s}({ foo: 'bar' })\` — and the closure preserves them across
|
|
877
|
+
// every request.
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* ${F(t)} middleware.
|
|
882
|
+
*
|
|
883
|
+
* Usage in bootstrap (fires on every request):
|
|
884
|
+
* middleware: [${s}()]
|
|
885
|
+
*
|
|
886
|
+
* Usage with adapter — phase controls *when* the handler runs:
|
|
887
|
+
*
|
|
888
|
+
* middleware() {
|
|
889
|
+
* return [{ handler: ${s}(), phase: 'afterGlobal' }]
|
|
890
|
+
* }
|
|
891
|
+
*
|
|
892
|
+
* Phase semantics (see \`MiddlewarePhase\` JSDoc for the full contract):
|
|
893
|
+
* - 'beforeGlobal' / 'afterGlobal' / 'beforeRoutes' — fire on every
|
|
894
|
+
* request, before module routes run.
|
|
895
|
+
* - 'afterRoutes' — fires ONLY when no route matched (404 fall-through)
|
|
896
|
+
* OR a route handler called \`next()\` without ending the response.
|
|
897
|
+
* Controllers that call \`ctx.json(…)\` end the chain and skip this
|
|
898
|
+
* phase. For per-response work (logging, metrics) attach to
|
|
899
|
+
* \`res.on('finish', …)\` from an earlier-phase middleware instead.
|
|
900
|
+
*
|
|
901
|
+
* Optional path scope — string, RegExp, or array of either:
|
|
902
|
+
* middleware() {
|
|
903
|
+
* return [{
|
|
904
|
+
* handler: ${s}({ region: 'eu' }),
|
|
905
|
+
* phase: 'afterGlobal',
|
|
906
|
+
* path: ['/api', /^\\/admin/],
|
|
907
|
+
* }]
|
|
908
|
+
* }
|
|
909
|
+
*
|
|
910
|
+
* Usage with @Middleware decorator:
|
|
911
|
+
* @Middleware(${s}())
|
|
912
|
+
*/
|
|
913
|
+
export function ${s}(options: ${F(t)}Options = {}) {
|
|
914
|
+
return (req: Request, res: Response, next: NextFunction) => {
|
|
915
|
+
// Implement your middleware logic here. \`options\` is captured by
|
|
916
|
+
// closure — log or read it anywhere in this handler body.
|
|
917
|
+
void options
|
|
918
|
+
next()
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
`),l.push(u),l}async function Bt(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),l=F(t),u=[],d=k(a,`${o}.guard.ts`);return await c(d,`import { Container, HttpException } from '@forinda/kickjs'
|
|
922
|
+
import type { RequestContext } from '@forinda/kickjs'
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* ${l} guard.
|
|
926
|
+
*
|
|
927
|
+
* Guards protect routes by checking conditions before the handler runs.
|
|
928
|
+
* Return early with an error response to block access.
|
|
929
|
+
*
|
|
930
|
+
* Usage:
|
|
931
|
+
* @Middleware(${s}Guard)
|
|
932
|
+
* @Get('/protected')
|
|
933
|
+
* async handler(ctx: RequestContext) { ... }
|
|
934
|
+
*/
|
|
935
|
+
export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<void> {
|
|
936
|
+
// Example: check for an authorization header
|
|
937
|
+
const header = ctx.headers.authorization
|
|
938
|
+
if (!header?.startsWith('Bearer ')) {
|
|
939
|
+
ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
|
|
940
|
+
return
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
const token = header.slice(7)
|
|
944
|
+
|
|
945
|
+
try {
|
|
946
|
+
// Verify the token using a service from the DI container
|
|
947
|
+
// const container = Container.getInstance()
|
|
948
|
+
// const authService = container.resolve(AuthService)
|
|
949
|
+
// const payload = authService.verifyToken(token)
|
|
950
|
+
// ctx.set('auth', payload)
|
|
951
|
+
|
|
952
|
+
next()
|
|
953
|
+
} catch {
|
|
954
|
+
ctx.res.status(401).json({ message: 'Invalid or expired token' })
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
`),u.push(d),u}function Vt(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 Ht(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=L(t),s=F(t),l=e.key??I(t),u=Array.isArray(e.params)?e.params:Vt(e.params),d=B({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),f=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,p=a===`http`?`RequestContext`:`ExecutionContext`,m=u.length>0?`\nexport type ${s}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
958
|
+
`)}\n}\n`:``,h=u.length>0?`${f}.withParams<${s}Params>()({`:`${f}({`,g=u.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
959
|
+
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
960
|
+
// genuinely correct for an undecorated route, and drop it from here.
|
|
961
|
+
requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,v=u.length>0?` // \`params\` is typed as ${s}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,y=`import { ${f} } from '@forinda/kickjs'
|
|
962
|
+
import type { ${p} } from '@forinda/kickjs'
|
|
963
|
+
|
|
964
|
+
/**
|
|
965
|
+
* ${s} context contributor (${a}).
|
|
966
|
+
*
|
|
967
|
+
* Computes a value and writes it to \`ctx.set('${l}', …)\` before a
|
|
968
|
+
* matched handler runs — the typed, ordered alternative to
|
|
969
|
+
* \`@Middleware()\` when the only job is to populate \`ctx\`.
|
|
970
|
+
*
|
|
971
|
+
* Apply per method/class:
|
|
972
|
+
*
|
|
973
|
+
${a===`http`?` * @${s}${u.length>0?`({ ${u[0]?.name}: … })`:``}
|
|
974
|
+
* @Get('/')
|
|
975
|
+
* handler(ctx: ${p}) {
|
|
976
|
+
* return ctx.json(ctx.require('${l}'))
|
|
977
|
+
* }`:` * // Any transport whose handler receives an ExecutionContext
|
|
978
|
+
* // (WebSocket, queue, cron). Attach via that transport's decorator,
|
|
979
|
+
* // or register the contributor at a module / bootstrap site below.
|
|
980
|
+
* handler(ctx: ${p}) {
|
|
981
|
+
* const value = ctx.require('${l}')
|
|
982
|
+
* }`}
|
|
983
|
+
*
|
|
984
|
+
* Or register at a module / adapter / bootstrap site — those take a
|
|
985
|
+
* \`ContributorRegistration\`, not the decorator itself:
|
|
986
|
+
*
|
|
987
|
+
* bootstrap({ contributors: [${s}${u.length>0?`.with({ ${u[0]?.name}: … })`:``}.registration] })
|
|
988
|
+
*/
|
|
989
|
+
|
|
990
|
+
// Register '${l}' so \`ctx.require('${l}')\` is typed and \`dependsOn: ['${l}']\`
|
|
991
|
+
// is checked. Replace \`unknown\` with the resolved value's real type.
|
|
992
|
+
// (For a key you only depend on — no value type needed — declare it in
|
|
993
|
+
// \`interface ContextKeys\` instead.)
|
|
994
|
+
declare module '@forinda/kickjs' {
|
|
995
|
+
interface ContextMeta {
|
|
996
|
+
'${l}': unknown
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
${m}
|
|
1000
|
+
export const ${s} = ${h}
|
|
1001
|
+
key: '${l}',
|
|
1002
|
+
${g} resolve: ${_} => {
|
|
1003
|
+
${v}
|
|
1004
|
+
// TODO: compute and return the value written to ctx.set('${l}', …)
|
|
1005
|
+
throw new Error("${s} contributor: resolve() not implemented")
|
|
1006
|
+
},
|
|
1007
|
+
})
|
|
1008
|
+
`,b=k(d,`${o}.contributor.ts`);return await c(b,y),[b]}async function Ut(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),l=[],u=k(a,`${o}.service.ts`);return await c(u,`import { Service } from '@forinda/kickjs'
|
|
1009
|
+
|
|
1010
|
+
@Service()
|
|
1011
|
+
export class ${s}Service {
|
|
1012
|
+
// Inject dependencies via constructor
|
|
1013
|
+
// constructor(
|
|
1014
|
+
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1015
|
+
// ) {}
|
|
1016
|
+
}
|
|
1017
|
+
`),l.push(u),l}async function Wt(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),l=[],u=k(a,`${o}.controller.ts`);return await c(u,`import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
|
|
1018
|
+
|
|
1019
|
+
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1020
|
+
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
1021
|
+
// will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
|
|
1022
|
+
// See https://kickjs.app/guide/typegen for details.
|
|
1023
|
+
|
|
1024
|
+
@Controller()
|
|
1025
|
+
export class ${s}Controller {
|
|
1026
|
+
// @Autowired() private readonly myService!: MyService
|
|
1027
|
+
|
|
1028
|
+
@Get('/')
|
|
1029
|
+
async list(ctx: Ctx<KickRoutes.${s}Controller['list']>) {
|
|
1030
|
+
ctx.json({ message: '${s} list' })
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
@Post('/')
|
|
1034
|
+
async create(ctx: Ctx<KickRoutes.${s}Controller['create']>) {
|
|
1035
|
+
ctx.created({ message: '${s} created', data: ctx.body })
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
`),l.push(u),l}async function Gt(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),l=I(t),u=[],d=k(a,`${o}.dto.ts`);return await c(d,`import { z } from 'zod'
|
|
1039
|
+
|
|
1040
|
+
export const ${l}Schema = z.object({
|
|
1041
|
+
// Define your schema fields here
|
|
1042
|
+
name: z.string().min(1).max(200),
|
|
1043
|
+
})
|
|
1044
|
+
|
|
1045
|
+
export type ${s}DTO = z.infer<typeof ${l}Schema>
|
|
1046
|
+
`),u.push(d),u}async function Kt(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(`
|
|
1047
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await c(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1048
|
+
|
|
1049
|
+
export default defineConfig({
|
|
1050
|
+
modules: {
|
|
1051
|
+
dir: '${n}',
|
|
1052
|
+
repo: '${r}',
|
|
1053
|
+
pluralize: true,
|
|
1054
|
+
},
|
|
1055
|
+
|
|
1056
|
+
typegen: {
|
|
1057
|
+
schemaValidator: 'zod',
|
|
1058
|
+
},
|
|
1059
|
+
|
|
1060
|
+
commands: [
|
|
1061
|
+
{
|
|
1062
|
+
name: 'test',
|
|
1063
|
+
description: 'Run tests with Vitest',
|
|
1064
|
+
steps: 'npx vitest run',
|
|
1065
|
+
},
|
|
1066
|
+
{
|
|
1067
|
+
name: 'format',
|
|
1068
|
+
description: 'Format code with Prettier',
|
|
1069
|
+
steps: 'npx prettier --write src/',
|
|
1070
|
+
},
|
|
1071
|
+
{
|
|
1072
|
+
name: 'format:check',
|
|
1073
|
+
description: 'Check formatting without writing',
|
|
1074
|
+
steps: 'npx prettier --check src/',
|
|
1075
|
+
},
|
|
1076
|
+
{
|
|
1077
|
+
name: 'ci:check',
|
|
1078
|
+
description: 'Run typecheck + format check',
|
|
1079
|
+
steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
|
|
1080
|
+
aliases: ['verify'],
|
|
1081
|
+
},
|
|
1082
|
+
],
|
|
1083
|
+
})
|
|
1084
|
+
`),[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
|
+
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
1086
|
+
`)}function qt(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 Jt(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 Yt(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=qt(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
|
+
name: '${r}',
|
|
1088
|
+
build: () => ({
|
|
1089
|
+
${p}
|
|
1090
|
+
}),
|
|
1091
|
+
})`}${c}`}}function Xt(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]===`
|
|
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=Jt(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
|
+
${y}
|
|
1094
|
+
}
|
|
1095
|
+
`}${u}`}}function Zt(e,t){return t===`class`?Xt(e):Yt(e)}function Qt(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 $t(e){let t=[];return await n(j(e),0),t;async function n(e,r){let i;try{i=await Le(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 ze(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function en(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Le(e)}catch{return}await Ie(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 ze(i)}catch{continue}s.isDirectory()?await r(i,o):(await Fe(i,o),n++)}}}function tn(e){return k(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function nn(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await $t(e),s=await N(k(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=tn(r),await en(e,c));let l=[];for(let e of o){let t=Zt(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=Qt(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 rn(e,t){let n=await $t(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 an(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 c(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
|
|
1096
|
+
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* ${r} Job Processor
|
|
1100
|
+
*
|
|
1101
|
+
* Decorators:
|
|
1102
|
+
* @Job(queueName) — marks this class as a job processor for a queue
|
|
1103
|
+
* @Process(jobName?) — marks a method as the handler for a specific job type
|
|
1104
|
+
* - Without a name: handles all jobs in the queue
|
|
1105
|
+
* - With a name: handles only jobs matching that name
|
|
1106
|
+
*
|
|
1107
|
+
* To add jobs to this queue from a service or controller:
|
|
1108
|
+
* @Inject(QUEUE_MANAGER) private queue: QueueService
|
|
1109
|
+
* await this.queue.add('${o}', '${a}', { ... })
|
|
1110
|
+
*/
|
|
1111
|
+
@Job('${o}')
|
|
1112
|
+
export class ${r}Job {
|
|
1113
|
+
@Process()
|
|
1114
|
+
async handle(job: { name: string; data: any; id?: string }) {
|
|
1115
|
+
console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
|
|
1116
|
+
|
|
1117
|
+
// TODO: Implement job logic here
|
|
1118
|
+
// Example:
|
|
1119
|
+
// await this.emailService.send(job.data.to, job.data.subject, job.data.body)
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
@Process('${a}.priority')
|
|
1123
|
+
async handlePriority(job: { name: string; data: any; id?: string }) {
|
|
1124
|
+
console.log(\`Priority job: \${job.name}\`, job.data)
|
|
1125
|
+
// Handle high-priority variant of this job
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
`),s}const on={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 sn(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=on[a];if(!o){let e=[...Object.keys(on),`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 cn(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,l=L(t),u=F(t),d=s?R(l):l,f=s?Je(u):u,p=k(r,d),m=[],h=async(e,t)=>{let n=k(p,e);await c(n,t),m.push(n)};await h(`${l}.module.ts`,ft({pascal:u,kebab:l,plural:d,repo:i,style:o})),await h(`${l}.constants.ts`,wt({pascal:u,kebab:l})),await h(`${l}.controller.ts`,mt({pascal:u,kebab:l,plural:d,pluralPascal:f})),await h(`${l}.service.ts`,Ct({pascal:u,kebab:l})),await h(`dtos/create-${l}.dto.ts`,ln(u,n)),await h(`dtos/update-${l}.dto.ts`,un(u,n)),await h(`dtos/${l}-response.dto.ts`,dn(u,n)),await h(`${l}.repository.ts`,vt({pascal:u,kebab:l,dtoPrefix:`./dtos`,tokenScope:a}));let g=i===`inmemory`,_=g?`in-memory-${l}`:`${L(i)}-${l}`,v=g?yt({pascal:u,kebab:l,repoPrefix:`.`,dtoPrefix:`./dtos`}):bt({pascal:u,kebab:l,repoType:i,repoPrefix:`.`,dtoPrefix:`./dtos`});return await h(`${_}.repository.ts`,v),await kt(r,u,d,l,o),m}function ln(e,t){return`import { z } from 'zod'
|
|
1129
|
+
|
|
1130
|
+
export const create${e}Schema = z.object({
|
|
1131
|
+
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
1132
|
+
`)}
|
|
1133
|
+
})
|
|
1134
|
+
|
|
1135
|
+
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
1136
|
+
`}function un(e,t){return`import { z } from 'zod'
|
|
1137
|
+
|
|
1138
|
+
export const update${e}Schema = z.object({
|
|
1139
|
+
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
1140
|
+
`)}
|
|
1141
|
+
})
|
|
1142
|
+
|
|
1143
|
+
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
1144
|
+
`}function dn(e,t){return`export interface ${e}ResponseDTO {
|
|
1145
|
+
id: string
|
|
1146
|
+
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
1147
|
+
`)}
|
|
1148
|
+
createdAt: string
|
|
1149
|
+
updatedAt: string
|
|
1150
|
+
}
|
|
1151
|
+
`}async function fn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=L(t),o=F(t),s=[],l;if(e.outDir)l=j(e.outDir);else if(n){let e=L(n),t=i?R(e):e;l=j(k(r??`src/modules`,t,`__tests__`))}else l=j(`src/__tests__`);let u=k(l,`${a}.test.ts`);return await c(u,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
1152
|
+
import { Container } from '@forinda/kickjs'
|
|
1153
|
+
|
|
1154
|
+
describe('${o}', () => {
|
|
1155
|
+
beforeEach(() => {
|
|
1156
|
+
Container.reset()
|
|
1157
|
+
})
|
|
1158
|
+
|
|
1159
|
+
it('should be defined', () => {
|
|
1160
|
+
// TODO: Import and test your class/function here
|
|
1161
|
+
expect(true).toBe(true)
|
|
1162
|
+
})
|
|
1163
|
+
|
|
1164
|
+
it('should handle the happy path', async () => {
|
|
1165
|
+
// TODO: Set up test data and assertions
|
|
1166
|
+
expect(true).toBe(true)
|
|
1167
|
+
})
|
|
1168
|
+
|
|
1169
|
+
it('should handle edge cases', async () => {
|
|
1170
|
+
// TODO: Test error handling, empty inputs, etc.
|
|
1171
|
+
expect(true).toBe(true)
|
|
1172
|
+
})
|
|
1173
|
+
})
|
|
1174
|
+
`),s.push(u),s}var pn=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
|
|
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 mn=[`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(`
|
|
1176
|
+
(dry run — no files were written)`),console.log()}async function hn(e){if(!e)try{let e=await i(process.cwd());await ye({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 gn=[{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`}],_n=new Set(gn.map(e=>e.name.split(` `)[0]));async function vn(){console.log(`
|
|
1177
|
+
Built-in generators:
|
|
1178
|
+
`);let e=Math.max(...gn.map(e=>e.name.length));for(let t of gn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await i(process.cwd()),n=a(t?.plugins??[],t?.commands??[]),r=await at(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
1179
|
+
Plugin generators:
|
|
1180
|
+
`);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
|
+
Failed to load:
|
|
1182
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function yn(e,a,o){let s=await i(process.cwd()),c=n(s),l=a.modulesDir??c.dir??`src/modules`,u=a.repo??Dt(c.repo);a.repo&&r(a.repo);let d=a.pattern??s?.pattern??`rest`,f=a.pluralize===!1?!1:c.pluralize??!0,p=t(s,process.cwd()),m=c.style??`define`;if(!o&&m===`define`){let e=await rn(j(l),`define`);if(e.length>0){console.error(`\n ${b.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${b.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${b.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 ${b.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${b.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${b.dim(`// kick.config.ts`)}\n ${b.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let h=[];for(let t of e){let e=await Ot({name:t,modulesDir:j(l),noEntity:a.entity===!1,noTests:a.tests===!1,repo:u,minimal:a.minimal,force:a.force,pattern:d,dryRun:o,pluralize:f,prismaClientPath:c.prismaClientPath,tokenScope:p,style:c.style});h.push(...e)}G(h,o),await hn(o)}function bn(e,r){let o=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,t,n)=>{if(t.list){await vn();return}if(!e||e.length===0){o.help();return}let c=W(n);s(c);let[l,u,...d]=e;if(l){let e=await i(process.cwd()),n=a(e?.plugins??[],e?.commands??[]),o=await it({generatorName:l,itemName:u??``,args:d,flags:t,cwd:process.cwd(),projectRoot:r?.projectRoot},n.generators);if(o){G(o.files,c);return}if(l!==`module`&&_n.has(l)){console.error(`\n '${l}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${l} ${u??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${l}' generator — upgrade it.\n`),process.exitCode=1;return}}await yn(e,t,c)});o.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);s(r),await yn(e,{...n.optsWithGlobals(),...t},r)}),o.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);s(r),G(await It({name:e,outDir:j(t.out)}),r)}),o.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);s(r),G(await Lt({name:e,outDir:j(t.out)}),r)}),o.command(`middleware <name>`).description(`Generate an Express middleware 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,r)=>{let a=W(r);s(a);let o=await i(process.cwd()),c=n(o),l=c.dir??`src/modules`;G(await zt({name:e,outDir:t.out,moduleName:t.module,modulesDir:l,pattern:o?.pattern,pluralize:c.pluralize??!0}),a)}),o.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
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,r)=>{let a=W(r);s(a);let o=await i(process.cwd()),c=n(o),l=c.dir??`src/modules`;G(await Bt({name:e,outDir:t.out,moduleName:t.module,modulesDir:l,pattern:o?.pattern,pluralize:c.pluralize??!0}),a)}),o.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
1185
|
+
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1186
|
+
--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,r)=>{let a=W(r);s(a);let o=(t.type??`http`).toLowerCase();o!==`http`&&o!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),o=`http`);let c=await i(process.cwd()),l=n(c),u=l.dir??`src/modules`;G(await Ht({name:e,type:o,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:u,pattern:c?.pattern,pluralize:l.pluralize??!0}),a)}),o.command(`service <name>`).description(`Generate a @Service() class
|
|
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,r)=>{let a=W(r);s(a);let o=await i(process.cwd()),c=n(o),l=c.dir??`src/modules`;G(await Ut({name:e,outDir:t.out,moduleName:t.module,modulesDir:l,pattern:o?.pattern,pluralize:c.pluralize??!0}),a)}),o.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
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,r)=>{let a=W(r);s(a);let o=await i(process.cwd()),c=n(o),l=c.dir??`src/modules`;G(await Wt({name:e,outDir:t.out,moduleName:t.module,modulesDir:l,pattern:o?.pattern,pluralize:c.pluralize??!0}),a),await hn(a)}),o.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
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,r)=>{let a=W(r);s(a);let o=await i(process.cwd()),c=n(o),l=c.dir??`src/modules`;G(await Gt({name:e,outDir:t.out,moduleName:t.module,modulesDir:l,pattern:o?.pattern,pluralize:c.pluralize??!0}),a)}),o.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
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,r)=>{let a=W(r);s(a);let o=n(await i(process.cwd())),c=o.dir??`src/modules`;G(await fn({name:e,outDir:t.out,moduleName:t.module,modulesDir:c,pluralize:o.pluralize??!0}),a)}),o.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);s(r),G(await an({name:e,outDir:j(t.out),queue:t.queue}),r)}),o.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
1192
|
+
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1193
|
+
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
1194
|
+
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,r,a,o)=>{let c=W(o);s(c),r.length===0&&(console.error(`
|
|
1196
|
+
Error: At least one field is required.
|
|
1197
|
+
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1198
|
+
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1199
|
+
Optional: append :optional (shell-safe, no quoting needed)
|
|
1200
|
+
`),process.exit(1));let l=await i(process.cwd()),u=n(l),d=a.modulesDir??u.dir??`src/modules`,f=sn(r),p=t(l,process.cwd()),m=await cn({name:e,fields:f,modulesDir:j(d),noEntity:a.entity===!1,noTests:a.tests===!1,pluralize:a.pluralize===!1?!1:u.pluralize??!0,tokenScope:p,style:u.style});console.log(`\n Scaffolded ${e} with ${f.length} field(s):`);for(let e of f)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);G(m,c),await hn(c)}),o.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);s(n),G(await Kt({outDir:j(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),o.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);s(n);let r=e.only??`all`;if(!mn.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${mn.join(` | `)}`),process.exitCode=1;return}G(await te({outDir:j(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of r?.generators??[])xn(o,e,r?.projectRoot)}function xn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,c=a?.required?`<${o}>`:`[${o}]`,l=`${i.name} ${c} [extraArgs...]`,u=e.command(l).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;u.option(n,e.description??``)}u.action(async(e,r,a,o)=>{let c=W(o);s(c);let l=await it({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);l&&G(l.files,c)})}async function Sn(e){let t=D.resolve(e.cwd,`.kickjs/types`);e.check||await Ie(t,{recursive:!0});let n=new Map,r=e.scan??de,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 Ie(D.dirname(r),{recursive:!0}),await P(r,n,`utf8`)},getScanResult:e=>{let t=Cn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?ue(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+`
|
|
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 pn(c);return s}function Cn(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 wn(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 Tn=e({applyDisableFilter:()=>wn,runAllPluginTypegens:()=>Dn});function En(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}async function Dn(e){let{enabled:t,skipped:n,unknown:r}=wn(a([...Wi,...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 Sn({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&En())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof pn||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 On(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 kn(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-b-Siu3FR.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Tn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-b-Siu3FR.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-DBdGEMiZ.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=On(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 An(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 jn(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 Mn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
1202
|
+
`):`${n.slice(0,t).join(`
|
|
1203
|
+
`)}\n… ${n.length-t} more line(s)`}function Nn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Pn(e,t,n={}){t&&(process.env.PORT=t);let r=Nn(n.polling),a=process.cwd(),o=await i(a),s=o?.typegen?.schemaValidator??`zod`,c=o?.typegen?.envFile;try{await ye({cwd:a,allowDuplicates:!0,schemaValidator:s,envFile:c,srcDir:o?.typegen?.srcDir,outDir:o?.typegen?.outDir,assetMap:o?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}let l=j(a,o?.typegen?.outDir??`.kickjs/types`);try{await fe(l,await Dn({cwd:a,config:o}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:u}=await import(`node:module`),{createServer:d}=await import(M(u(j(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let f=await d({configFile:j(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??o?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=An(a);e?m=jn({cwd:a,bin:e,onResult:e=>{f.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(Mn(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=kn({cwd:a,config:o,emitWarning:e=>{console.warn(e),f.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>m?.schedule()});f.watcher.on(`add`,e=>g.handleWatchEvent(`add`,e)),f.watcher.on(`unlink`,e=>g.handleWatchEvent(`unlink`,e)),f.watcher.on(`change`,e=>g.handleWatchEvent(`change`,e)),f.watcher.on(`unlinkDir`,e=>g.handleWatchEvent(`unlinkDir`,e)),g.assetSrcRoots.length>0&&f.watcher.add([...g.assetSrcRoots]),await f.listen(),f.printUrls(),console.log(`
|
|
1204
|
+
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 f.close(),process.exit(0)}};process.on(`SIGINT`,v),process.on(`SIGTERM`,v),process.on(`SIGBREAK`,v)}function Fn(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 Pn(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
|
+
Error: vite is not installed.
|
|
1207
|
+
Run: pnpm add -D vite unplugin-swc
|
|
1208
|
+
`):console.error(`
|
|
1209
|
+
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1210
|
+
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 i(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
|
|
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}we(i,{recursive:!0}),Ce(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
|
|
1213
|
+
Building asset map...`);try{await xe(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
1214
|
+
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 i(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
1216
|
+
Building asset map...`);try{await xe(e,{cwd:process.cwd()}),console.log(`
|
|
1217
|
+
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)),Ge(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 Pn(e.entry,e.port)}catch(e){console.error(`
|
|
1219
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function In(){try{let e=O(Ae(import.meta.url));return JSON.parse(T(k(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Ln=new Set(Object.values(m).filter(e=>e.deprecated).map(e=>e.pkg));function Rn(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:Ln.has(t)}})}function zn(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 Bn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${In()}`,``,` System:`,` OS: ${He()} ${Ue()} (${Ve()})`,` Node: ${process.version}`],t=zn(process.cwd()),n=t?Rn(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(`
|
|
1220
|
+
`))})}const{bold:K,dim:q,green:Vn,red:J,yellow:Hn,blue:Un}=b;function Wn(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 Gn(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 Gn(`${e}${t}`)}catch{return null}}async function Kn(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 qn(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`?Vn(`● 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?Hn:Vn;console.log(` ${K(`Uptime:`)} ${Wn(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(` ${y(e.method)} ${t} ${Un(e.controller)}.${q(e.handler)}`)}}console.log(s),console.log()}function Jn(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 Kn(r);t.json?console.log(JSON.stringify(e,null,2)):qn(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 Yn(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 Xn=[{match(e,t){let n=Yn(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
|
+
registers the env schema with kickjs at module-load time. Without it,
|
|
1222
|
+
ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
|
|
1223
|
+
and every user-defined key reads as undefined. @Value() may *appear* to
|
|
1224
|
+
work via a raw process.env fallback, but Zod coercion and schema defaults
|
|
1225
|
+
are silently skipped.`,fix:`Add this line to src/index.ts near the top, before bootstrap() runs:`,codeBefore:`import 'reflect-metadata'
|
|
1226
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1227
|
+
import { modules } from './modules'
|
|
1228
|
+
`,codeAfter:`import 'reflect-metadata'
|
|
1229
|
+
import './config' // ← add this — registers env schema
|
|
1230
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1231
|
+
import { modules } from './modules'
|
|
1232
|
+
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=X(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`]);return X(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
|
|
1233
|
+
When vitest re-imports your modules across tests, the same class can be
|
|
1234
|
+
registered twice and the container throws. The fix is to wipe the
|
|
1235
|
+
container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
|
|
1236
|
+
import { Container } from '@forinda/kickjs'
|
|
1237
|
+
|
|
1238
|
+
describe('UserController', () => {
|
|
1239
|
+
beforeEach(() => Container.reset())
|
|
1240
|
+
|
|
1241
|
+
it('does the thing', async () => { /* ... */ })
|
|
1242
|
+
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Yn(e,[`Module`,`is not a function`])||Yn(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
|
+
pattern instead: a class implements AppModule and exposes routes() that
|
|
1244
|
+
returns the controller wiring. This was a deliberate choice — modules
|
|
1245
|
+
become explicit values rather than metadata, which makes them easier to
|
|
1246
|
+
compose, test, and serialize.`,fix:`Replace the @Module decorator with an AppModule class:`,codeBefore:`import { Module } from '@forinda/kickjs' // ← does not exist
|
|
1247
|
+
import { UserController } from './user.controller'
|
|
1248
|
+
|
|
1249
|
+
@Module({
|
|
1250
|
+
controllers: [UserController],
|
|
1251
|
+
})
|
|
1252
|
+
export class UserModule {}`,codeAfter:`import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
|
|
1253
|
+
import { UserController } from './user.controller'
|
|
1254
|
+
|
|
1255
|
+
export class UserModule implements AppModule {
|
|
1256
|
+
routes(): ModuleRoutes {
|
|
1257
|
+
return {
|
|
1258
|
+
path: '/users',
|
|
1259
|
+
router: buildRoutes(UserController),
|
|
1260
|
+
controller: UserController,
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){return/KickRoutes\s*\[\s*['"](GET|POST|PUT|PATCH|DELETE)/i.test(e)?{confidence:95,diagnosis:{id:`legacy-kick-routes-bracket-syntax`,title:`KickRoutes['POST /users'] is the legacy v1 syntax`,explanation:`KickJS v2 changed the typegen output from a flat string-keyed map to a
|
|
1264
|
+
namespaced shape: KickRoutes.UserController["create"] instead of
|
|
1265
|
+
KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
1266
|
+
and matches the actual class names so refactors propagate via
|
|
1267
|
+
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
1268
|
+
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
1269
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=X(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=X(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
|
|
1270
|
+
cluster: { workers: N }, the framework forks N workers, each of which
|
|
1271
|
+
spins up its own Vite instance on a separate port. The fix landed in
|
|
1272
|
+
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
1273
|
+
silently skips cluster, with a warning. If you see this on an older
|
|
1274
|
+
version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
|
|
1275
|
+
modules,
|
|
1276
|
+
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
1277
|
+
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return X(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
|
|
1278
|
+
reflect-metadata polyfill. The polyfill must be imported once,
|
|
1279
|
+
before any decorator runs. Most projects do this at the top of
|
|
1280
|
+
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
1281
|
+
or "Reflect.getMetadata is not a function" errors at runtime.`,fix:`Add the import at the very top of src/index.ts:`,codeAfter:`import 'reflect-metadata' // ← must be the FIRST import
|
|
1282
|
+
import './config'
|
|
1283
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1284
|
+
import { modules } from './modules'
|
|
1285
|
+
|
|
1286
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return X(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
|
|
1287
|
+
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
1288
|
+
the most likely cause is that the module is missing from the exported
|
|
1289
|
+
array. The CLI usually wires this automatically, but a hand-edit can
|
|
1290
|
+
drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the array:`,codeAfter:`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
1291
|
+
import { UserModule } from './users/user.module'
|
|
1292
|
+
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
1293
|
+
|
|
1294
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}}];function Zn(e,t){let n=null;for(let r of Xn){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 Qn(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
|
+
export OPENAI_API_KEY="sk-..."
|
|
1296
|
+
|
|
1297
|
+
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
|
+
kick add ai
|
|
1299
|
+
|
|
1300
|
+
Or manually:
|
|
1301
|
+
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=$n(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=er((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 $n(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(`
|
|
1302
|
+
`)}function er(e){let t=[e,tr(e),nr(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(rr(t))return t}catch{continue}return null}function tr(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function nr(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 rr(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 ir(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 sr(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
1303
|
+
|
|
1304
|
+
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
1305
|
+
kick explain "config.get returned undefined"
|
|
1306
|
+
pnpm test 2>&1 | kick explain
|
|
1307
|
+
`),process.exit(1));let r=lr(),i=Zn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
1308
|
+
`);return}if(i){ur(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
1309
|
+
`),process.exit(2)),dr(n,!1),process.exit(2));let a=await Qn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(ar(a),null,2)+`
|
|
1310
|
+
`),process.exit(a.kind===`ok`?0:2)),or(n,a),process.exit(a.kind===`ok`?0:2)})}function ar(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 or(e,t){if(t.kind===`ok`){ur(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 sr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:cr()}function cr(){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 lr(){let e=process.cwd();return{cwd:e,hasFile:t=>w(j(e,t))}}function ur(e,t,n,r=!1){let i=Q(e.trim(),200),a=r?`AI-generated — verify before applying`:fr(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(`
|
|
1311
|
+
`)}function dr(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
|
+
When @forinda/kickjs-ai ships its provider implementations,
|
|
1313
|
+
this command will call the configured LLM with the error +
|
|
1314
|
+
project context and return a structured fix.
|
|
1315
|
+
|
|
1316
|
+
`):process.stdout.write(` No known-issue matched. Things you can try:
|
|
1317
|
+
|
|
1318
|
+
1. Check the framework docs for the error keywords:
|
|
1319
|
+
https://kickjs.app/
|
|
1320
|
+
|
|
1321
|
+
2. Re-run with --ai to fall back to an LLM (requires
|
|
1322
|
+
@forinda/kickjs-ai with a configured provider):
|
|
1323
|
+
kick explain --ai "<your error>"
|
|
1324
|
+
|
|
1325
|
+
3. File an issue with the error text:
|
|
1326
|
+
https://github.com/forinda/kick-js/issues/new
|
|
1327
|
+
|
|
1328
|
+
`)}function Z(e,t){return e.split(`
|
|
1329
|
+
`).map(e=>`${t}${e}`).join(`
|
|
1330
|
+
`)}function Q(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function fr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function pr(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(mr),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(hr)}function mr(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 hr(e){let t=process.cwd(),n=gr(t)??Oe(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,De(i,JSON.stringify(o,null,2)+`
|
|
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 gr(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 _r(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=yr(t,`tsx`);r||(console.error(`
|
|
1332
|
+
Error: tsx not found. Install it: pnpm add -D tsx
|
|
1333
|
+
`),process.exit(1));let i=vr(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 vr(e,t){return`
|
|
1334
|
+
import 'reflect-metadata'
|
|
1335
|
+
|
|
1336
|
+
// Prevent bootstrap() from starting the HTTP server
|
|
1337
|
+
process.env.KICK_TINKER = '1'
|
|
1338
|
+
|
|
1339
|
+
console.log('\\n 🔧 KickJS Tinker')
|
|
1340
|
+
console.log(' Loading: ${t}\\n')
|
|
1341
|
+
|
|
1342
|
+
// Load core
|
|
1343
|
+
let Container, Logger, HttpException, HttpStatus
|
|
1344
|
+
try {
|
|
1345
|
+
const core = await import('@forinda/kickjs')
|
|
1346
|
+
Container = core.Container
|
|
1347
|
+
Logger = core.Logger
|
|
1348
|
+
HttpException = core.HttpException
|
|
1349
|
+
HttpStatus = core.HttpStatus
|
|
1350
|
+
} catch {
|
|
1351
|
+
console.error(' Error: @forinda/kickjs not found.')
|
|
1352
|
+
console.error(' Install it: pnpm add @forinda/kickjs\\n')
|
|
1353
|
+
process.exit(1)
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
// Load entry to trigger decorator registration
|
|
1357
|
+
try {
|
|
1358
|
+
await import('${M(e).href}')
|
|
1359
|
+
} catch (err) {
|
|
1360
|
+
console.warn(' Warning: ' + err.message)
|
|
1361
|
+
console.warn(' Container may be partially initialized.\\n')
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
const container = Container.getInstance()
|
|
1365
|
+
|
|
1366
|
+
// Start REPL
|
|
1367
|
+
const repl = await import('node:repl')
|
|
1368
|
+
const server = repl.start({ prompt: 'kick> ', useGlobal: true })
|
|
1369
|
+
|
|
1370
|
+
server.context.container = container
|
|
1371
|
+
server.context.Container = Container
|
|
1372
|
+
server.context.resolve = (token) => container.resolve(token)
|
|
1373
|
+
server.context.Logger = Logger
|
|
1374
|
+
server.context.HttpException = HttpException
|
|
1375
|
+
server.context.HttpStatus = HttpStatus
|
|
1376
|
+
|
|
1377
|
+
console.log(' Available globals:')
|
|
1378
|
+
console.log(' container — DI container instance')
|
|
1379
|
+
console.log(' resolve(T) — shorthand for container.resolve(T)')
|
|
1380
|
+
console.log(' Container, Logger, HttpException, HttpStatus')
|
|
1381
|
+
console.log()
|
|
1382
|
+
|
|
1383
|
+
server.on('exit', () => {
|
|
1384
|
+
console.log('\\n Goodbye!\\n')
|
|
1385
|
+
process.exit(0)
|
|
1386
|
+
})
|
|
1387
|
+
`}function yr(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 br(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
|
+
`;)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 xr(e,t){let n=jt(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=br(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 Sr(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 l(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await S({message:b.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
1390
|
+
Cancelled.
|
|
1391
|
+
`);return}await Re(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let u=k(n,`index.ts`);if(await l(u)){let e=await N(u,`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=xr(e,o),e=e.replace(/\n{3,}/g,`
|
|
1392
|
+
|
|
1393
|
+
`),e!==t&&(await P(u,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${u}`))}console.log(`\n Module '${s}' removed.\n`)}function Cr(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 r=n(await i(process.cwd())),a=t.modulesDir??r.dir??`src/modules`,o=t.pluralize===!1?!1:r.pluralize??!0;for(let n of e)await Sr({name:n,modulesDir:j(a),force:t.force,pluralize:o})})}function wr(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 Tr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Er(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=ae(process.cwd()),n=await i(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-C3PeTJQb.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Ui),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
|
+
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=wr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,a=Tr(e.envFile)??n?.typegen?.envFile,o={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:a,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await _e(o);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await ye(o);let r=await Dn({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 fe(j(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof ve?console.error(`
|
|
1396
|
+
`+e.message+`
|
|
1397
|
+
`):e instanceof pn?console.error(`
|
|
1398
|
+
`+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 Dr(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(...Dr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Or(e){try{return T(e,`utf-8`)}catch{return``}}const kr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Ar(e,t){let n=Or(k(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(kr.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 jr(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 Mr(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 Nr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Pr(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 Fr(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 Ir(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 Lr(e){let t=Dr(k(e,`src`)).map(e=>Or(e)),n=[],r=Ar(e,t);r&&n.push(r);let i=jr(t);i&&n.push(i);let a=Mr(t);a&&n.push(a);let o=Nr();o&&n.push(o);let s=Pr(t);return s&&n.push(s),n.push(Fr(t)),n.push(Ir(t)),n}function Rr(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
|
|
1400
|
+
Usage: kick check --deploy
|
|
1401
|
+
|
|
1402
|
+
Available checks:
|
|
1403
|
+
--deploy Audit for production readiness (security, config, best practices)
|
|
1404
|
+
`);return}let t=process.cwd();x(`KickJS Deploy Check`);let n=ee();n.start(`Scanning project...`);let r=Lr(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)_.message(`${re(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?b.red(`${a} critical`):`${a} critical`,o>0?b.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(C(b.red(`${l} — fix critical issues before deploying`)),process.exit(1)):C(b.green(`${l} — looking good!`))})}function zr(e){try{return JSON.parse(T(e,`utf-8`))}catch{return null}}function Br(e){try{return T(e,`utf-8`)}catch{return null}}function Vr(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function Hr(e){let t=k(e,`tsconfig.json`);if(w(t))return Ur(t,new Set)}function Ur(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Br(e);if(n===null)return null;let r=Vr(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=Wr(O(e),n);if(!r)continue;let i=Ur(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Wr(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return Gr(j(e,t));let n=e;for(;;){let e=Gr(k(n,`node_modules`,t));if(e)return e;let r=O(n);if(r===n)break;n=r}return null}function Gr(e){if(w(e)){try{if(Ee(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 Kr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function qr(){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.
|
|
1405
|
+
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Jr(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 Yr(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 Xr={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function Zr(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=Xr[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 Qr(e){if(!e.pkg||!ei(e.cwd))return null;let t=f[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 $r=2e3;function ei(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<$r;){let e=r.pop(),t;try{t=E(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=$r)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(Br(t)??``)))return!0}}return!1}function ti(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
|
+
Install it: pnpm add reflect-metadata
|
|
1407
|
+
Then import it at the top of src/index.ts:
|
|
1408
|
+
|
|
1409
|
+
import 'reflect-metadata'
|
|
1410
|
+
// ... rest of bootstrap`}}function ni(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 ri(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(Br(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=Br(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+)?['"]${Kr(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 ii(e,t=ai){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=Ee(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const ai=2e3;function oi(e){let t=k(e.cwd,`.kickjs`,`types`);if(!w(t))return null;let n=ii(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 si=[()=>qr(),Jr,Yr,Zr,Qr,ti,ni,ri,oi];async function ci(e,t={}){let n={cwd:e,pkg:zr(k(e,`package.json`)),tsconfig:Hr(e),runtime:t.runtime??`express`},r=[...si,...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 li(e){switch(e){case`pass`:return b.green(`✔`);case`warn`:return b.yellow(`⚠`);case`fail`:return b.red(`✖`)}}function ui(e){let t=li(e.status),n=e.message?` ${b.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function di(e){return e.split(`
|
|
1411
|
+
`).map(e=>` ${b.dim(`→`)} ${e}`).join(`
|
|
1412
|
+
`)}function fi(e){return e?.doctor?.checks??[]}function pi(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=fi(await i(e)),n=await h(e);x(`KickJS Doctor`);let r=await ci(e,{extraChecks:t,runtime:n});for(let e of r)_.message(ui(e)),e.fix&&e.status!==`pass`&&_.message(di(e.fix));let a=r.filter(e=>e.status===`pass`).length,o=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[b.green(`${a} passed`),o>0?b.yellow(`${o} warning${o===1?``:`s`}`):`${o} warnings`,s>0?b.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(o>0?`${c} — review the warnings`:b.green(`${c} — your environment looks good`))})}function mi(e){return e.optsWithGlobals().dryRun??!1}function hi(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
|
+
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
1414
|
+
--target define|class Override the migration direction.
|
|
1415
|
+
--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 r=mi(t)||!e.apply;s(r),e.experimental||(console.error(`
|
|
1417
|
+
`+b.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
1418
|
+
The regex-based rewrite handles the shapes our templates produce.
|
|
1419
|
+
Hand-rolled modules with non-standard structures may be skipped.
|
|
1420
|
+
Always commit before running with --apply.
|
|
1421
|
+
`),process.exit(1));let a=n(await i(process.cwd())),o=j(e.modulesDir??a.dir??`src/modules`),c;e.target===`define`||e.target===`class`?c=e.target:e.target===void 0?c=a.style??`define`:(console.error(`\n ${b.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let l=b.dim(`→ ${c}`),u=r?b.dim(`(dry-run)`):b.bold(`(applying)`);console.log(`\n ${b.bold(`kick codemod modules`)} ${l} ${u}`),console.log(` modulesDir: ${b.dim(o)}\n`);let d=e.backup!==!1&&!r,f=await nn(o,{dryRun:r,target:c,backup:d});if(f.backupDir){let e=f.backupDir;console.log(` ${b.green(`✓`)} backup: ${b.dim(e)}\n ${b.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!r&&e.backup===!1&&console.log(` ${b.dim(`(--no-backup — skipping snapshot)`)}\n`);let p=0,m=0;for(let e of f.files)if(e.status===`migrated`)p++,console.log(` ${b.green(`✓`)} ${e.path}`);else{m++;let t=b.dim(`(${e.reason??`skipped`})`);console.log(` ${b.dim(`-`)} ${e.path} ${t}`)}if(console.log(),f.indexStatus===`migrated`)console.log(` ${b.green(`✓`)} ${f.indexPath}`);else if(f.indexStatus===`skipped`){let e=b.dim(`(${f.indexReason??`skipped`})`);console.log(` ${b.dim(`-`)} ${f.indexPath} ${e}`)}else console.log(` ${b.dim(`-`)} ${f.indexPath} ${b.dim(`(not found)`)}`);let h=r?b.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${b.bold(String(p))} migrated, ${b.bold(String(m))} skipped${h}\n`)})}const gi=()=>({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 i(e.cwd);if(!t?.assetMap)return null;let n=oe(t.assetMap,e.cwd);return n.count===0?null:he(n)}}),_i="/* 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 vi(e,t,n,r={}){if(e.length===0)return`${_i}
|
|
1422
|
+
// (no routes discovered yet — annotate a controller method with
|
|
1423
|
+
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1424
|
+
declare global {
|
|
1425
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1426
|
+
namespace KickRoutes {
|
|
1427
|
+
// Always present so \`createClient<KickRoutes.Api>\` compiles before the
|
|
1428
|
+
// first route exists (fresh project / pre-controller typegen runs).
|
|
1429
|
+
interface Api {}
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
1433
|
+
type KickApi = KickRoutes.Api
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
/** Empty until the first route exists — see kick typegen. */
|
|
1437
|
+
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=Si(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??bi(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=xi(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${yi(e)}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
1439
|
+
`))}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=Ti(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
|
+
`)}\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=wi(``,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
|
+
`)+`
|
|
1444
|
+
`:``,b=Ci(a)+y,x=l.join(`
|
|
1445
|
+
`);return`${_i}${b}
|
|
1446
|
+
declare global {
|
|
1447
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1448
|
+
namespace KickRoutes {
|
|
1449
|
+
${x}
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
1453
|
+
type KickApi = KickRoutes.Api
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
${g}
|
|
1457
|
+
`}function yi(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function bi(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 xi(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 Si(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=wi(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 Ci(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
|
+
`)+`
|
|
1459
|
+
`}function wi(e,t,n){if(e===null)return`unknown`;let r=O(n);if(e===``){let e=A(r,t).split(ke).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(ke).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function Ti(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 Ei=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Di(e),cwd:e.cwd,envFile:Oi(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return vi(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Di(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Oi(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function ki(e,t,n=`zod`){if(!e)return null;let r=A(O(t),e.filePath).split(ke).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
|
|
1460
|
+
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1461
|
+
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1462
|
+
|
|
1463
|
+
// Importing the schema as a type lets us infer its shape without
|
|
1464
|
+
// pulling in any runtime code. \`Awaited<>\` strips an accidental
|
|
1465
|
+
// Promise wrap on dynamic-imported defaults.
|
|
1466
|
+
import type _envSchema from '${r}'
|
|
1467
|
+
|
|
1468
|
+
${n===`kickjs-schema`?`type _Raw = import('@forinda/kickjs-schema').InferSchemaOutput<typeof _envSchema>
|
|
1469
|
+
type _Resolved = { [K in keyof _Raw]: _Raw[K] }
|
|
1470
|
+
`:``}// Local type alias — interfaces can only \`extend\` an identifier,
|
|
1471
|
+
// not an inline import expression, so we resolve the schema's
|
|
1472
|
+
// inferred shape into a named type first.
|
|
1473
|
+
type _KickEnvShape = ${n===`kickjs-schema`?`_Resolved`:`import('zod').infer<typeof _envSchema>`}
|
|
1474
|
+
|
|
1475
|
+
declare global {
|
|
1476
|
+
/**
|
|
1477
|
+
* Typed environment registry. Augmented from \`${e.relativePath}\`
|
|
1478
|
+
* so \`@Value('PORT')\`, \`Env<'PORT'>\`, and \`process.env.PORT\` are
|
|
1479
|
+
* all type-safe and autocomplete.
|
|
1480
|
+
*/
|
|
1481
|
+
interface KickEnv extends _KickEnvShape {}
|
|
1482
|
+
|
|
1483
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1484
|
+
namespace NodeJS {
|
|
1485
|
+
/**
|
|
1486
|
+
* Narrow \`process.env\` so known keys exist as \`string\` (the raw
|
|
1487
|
+
* pre-Zod-coercion form). \`@Value\` and the \`ConfigService\` apply
|
|
1488
|
+
* the schema's transforms internally; access \`process.env\` directly
|
|
1489
|
+
* only when you need the raw string. Unknown keys still resolve to
|
|
1490
|
+
* \`string | undefined\` via the base @types/node declaration.
|
|
1491
|
+
*/
|
|
1492
|
+
interface ProcessEnv extends Record<keyof KickEnv, string> {}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
export {}
|
|
1497
|
+
`}const Ai=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Mi(e);if(t===!1)return null;let n=await e.getScanResult({root:ji(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 ki(n.env,i,r)}});function ji(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Mi(e){return e.config?.typegen?.envFile}function Ni(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Pi(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ni(e),cwd:e.cwd,envFile:Pi(e)}}const Fi=()=>({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 ge(t.classes,n,r)}}),Ii=()=>({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 me(`ServiceToken`,pe(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Li=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return me(`ModuleToken`,se((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Ri=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return le((await e.getScanResult($(e))).pluginsAndAdapters)}}),zi=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return be((await e.getScanResult($(e))).augmentations)}}),Bi=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:ce(t.contextKeys)}}),Vi={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Hi=()=>({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}=Vi[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(`
|
|
1498
|
+
`)}});var Ui=e({builtinCliPlugins:()=>Wi});const Wi=[o({name:`kick/init`,register:qe}),o({name:`kick/generate`,register:bn}),o({name:`kick/run`,register:Fn}),o({name:`kick/info`,register:Bn}),o({name:`kick/inspect`,register:Jn}),o({name:`kick/add`,register:u}),o({name:`kick/list`,register:p}),o({name:`kick/explain`,register:ir}),o({name:`kick/mcp`,register:pr}),o({name:`kick/tinker`,register:_r}),o({name:`kick/remove`,register:Cr}),o({name:`kick/typegen`,register:Er}),o({name:`kick/check`,register:Rr}),o({name:`kick/doctor`,register:pi}),o({name:`kick/codemod`,register:hi}),o({name:`kick/registry`,typegens:[Fi()]}),o({name:`kick/services`,typegens:[Ii()]}),o({name:`kick/modules`,typegens:[Li()]}),o({name:`kick/plugins`,typegens:[Ri()]}),o({name:`kick/augmentations`,typegens:[zi()]}),o({name:`kick/context`,typegens:[Bi()]}),o({name:`kick/assets`,typegens:[gi()]}),o({name:`kick/routes`,typegens:[Ei()]}),o({name:`kick/env`,typegens:[Ai()]}),o({name:`kick/runtime`,typegens:[Hi()]})];export{Tn as n,We as r,Wi as t};
|