@forinda/kickjs-cli 8.1.3 → 8.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{agent-docs-C6feHEIe.mjs → agent-docs-BK33p0Pw.mjs} +2 -2
  2. package/dist/{agent-docs-CksX-ROg.mjs → agent-docs-DzaWoZc7.mjs} +3 -3
  3. package/dist/{agent-docs-CksX-ROg.mjs.map → agent-docs-DzaWoZc7.mjs.map} +1 -1
  4. package/dist/{build-nf_1TqZ-.mjs → build-DBT23vXN.mjs} +3 -3
  5. package/dist/{build-nf_1TqZ-.mjs.map → build-DBT23vXN.mjs.map} +1 -1
  6. package/dist/{build-BDwasfWP.mjs → build-clh7HpZV.mjs} +2 -2
  7. package/dist/{builtins-XSYvrFb3.mjs → builtins-B6Dc2coA.mjs} +163 -146
  8. package/dist/{builtins-CXyb3PC1.mjs → builtins-HdwKAx0s.mjs} +2 -2
  9. package/dist/cli.mjs +2 -2
  10. package/dist/config-CzL24fBQ.mjs +12 -0
  11. package/dist/config-D06pHD-Y.mjs +13 -0
  12. package/dist/{config-DNf67j-M.mjs.map → config-D06pHD-Y.mjs.map} +1 -1
  13. package/dist/{doctor-C_Nwy9pB.mjs → doctor-Bi_jVzha.mjs} +59 -54
  14. package/dist/doctor-Bi_jVzha.mjs.map +1 -0
  15. package/dist/{fullstack-0pA-ni3E.mjs → fullstack-CdAbknb3.mjs} +4 -4
  16. package/dist/{fullstack-0pA-ni3E.mjs.map → fullstack-CdAbknb3.mjs.map} +1 -1
  17. package/dist/{fullstack-BLs3Q93Y.mjs → fullstack-DAEEITND.mjs} +3 -3
  18. package/dist/index.d.mts +11 -0
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +2 -2
  21. package/dist/{plugin-D5BaucQm.mjs → plugin-BSNGbECd.mjs} +2 -2
  22. package/dist/{plugin-DgYOUNLo.mjs → plugin-CD9WjquV.mjs} +3 -3
  23. package/dist/{plugin-DgYOUNLo.mjs.map → plugin-CD9WjquV.mjs.map} +1 -1
  24. package/dist/{project-ChvYcc9t.mjs → project-DfBzpCeE.mjs} +5 -5
  25. package/dist/{project-docs-BgHHE2Y-.mjs → project-docs-BCwWphge.mjs} +3 -3
  26. package/dist/{project-docs-BgHHE2Y-.mjs.map → project-docs-BCwWphge.mjs.map} +1 -1
  27. package/dist/{project-docs-Bj8TOOks.mjs → project-docs-DRLN1EDX.mjs} +2 -2
  28. package/dist/{project-BwghMh67.mjs → project-indmSdfC.mjs} +6 -6
  29. package/dist/project-indmSdfC.mjs.map +1 -0
  30. package/dist/{project-root-Bakzso9Y.mjs → project-root-BsyQhlS5.mjs} +2 -2
  31. package/dist/{project-root-C-NAF0bl.mjs → project-root-CQCNCAvv.mjs} +3 -3
  32. package/dist/{project-root-C-NAF0bl.mjs.map → project-root-CQCNCAvv.mjs.map} +1 -1
  33. package/dist/{prompts-B1P3iwUU.mjs → prompts-Ba0PO3Rn.mjs} +2 -2
  34. package/dist/{prompts-B1P3iwUU.mjs.map → prompts-Ba0PO3Rn.mjs.map} +1 -1
  35. package/dist/{rolldown-runtime-C7LUc-Oa.mjs → rolldown-runtime-DmTqmRjS.mjs} +1 -1
  36. package/dist/{run-plugins-CTbRE_nh.mjs → run-plugins-BKWupYoJ.mjs} +94 -82
  37. package/dist/run-plugins-BKWupYoJ.mjs.map +1 -0
  38. package/dist/{typegen-D1esvePN.mjs → typegen-B6vIx4Qd.mjs} +4 -4
  39. package/dist/{typegen-CgN9aE8p.mjs → typegen-CnsfSSpH.mjs} +5 -5
  40. package/dist/{typegen-CgN9aE8p.mjs.map → typegen-CnsfSSpH.mjs.map} +1 -1
  41. package/dist/{types-Cloqgm4i.mjs → types-B6yNws8R.mjs} +1 -1
  42. package/package.json +4 -4
  43. package/dist/config-B78h-btI.mjs +0 -12
  44. package/dist/config-DNf67j-M.mjs +0 -13
  45. package/dist/doctor-C_Nwy9pB.mjs.map +0 -1
  46. package/dist/project-BwghMh67.mjs.map +0 -1
  47. package/dist/run-plugins-CTbRE_nh.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.1.3
2
+ * @forinda/kickjs-cli v8.1.5
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as e}from"./rolldown-runtime-C7LUc-Oa.mjs";import{a as t,c as n,i as r,o as i,r as a,s as o,t as s,u as c}from"./project-ChvYcc9t.mjs";import{a as l,c as u,i as d,o as f,r as p,s as m}from"./config-B78h-btI.mjs";import{n as h,r as g}from"./plugin-D5BaucQm.mjs";import{c as _,l as v,s as y}from"./project-docs-Bj8TOOks.mjs";import{a as b,c as x,d as ee,f as S,i as te,l as ne,n as re,o as ie,p as ae,r as C,s as w,u as oe}from"./agent-docs-C6feHEIe.mjs";import{t as T}from"./project-root-Bakzso9Y.mjs";import{_ as se,a as ce,c as le,d as ue,f as de,g as fe,h as pe,i as me,l as he,m as ge,o as _e,p as ve,r as ye,s as be,t as xe,u as Se}from"./typegen-D1esvePN.mjs";import{t as Ce}from"./build-BDwasfWP.mjs";import{createRequire as we}from"node:module";import{cpSync as Te,existsSync as E,mkdirSync as Ee,readFileSync as D,readdirSync as O,rmSync as De,statSync as Oe,writeFileSync as ke}from"node:fs";import k,{basename as Ae,dirname as A,join as j,relative as M,resolve as N,sep as je}from"node:path";import{fileURLToPath as Me,pathToFileURL as P}from"node:url";import{fork as Ne,spawn as Pe,spawnSync as Fe}from"node:child_process";import{copyFile as Ie,mkdir as Le,readFile as F,readdir as Re,rm as ze,stat as Be,writeFile as I}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import Ve from"pluralize";import{arch as He,platform as Ue,release as We}from"node:os";import{createHash as Ge}from"node:crypto";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. swagger,ws,queue,devtools)`).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)=>{te(`KickJS — Create a new project`);let r=!!(t.yes||t.nonInteractive);e||=r?`my-api`:await oe({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=N(`.`),e=Ae(i)):i=N(t.directory||e),E(i)){let n=O(i);if(n.length>0){if(t.force)b.warn(`Clearing existing files in ${i}`);else if(r){b.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),w(`Aborted.`);return}else{b.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)b.message(` - ${e}`);if(n.length>5&&b.message(` ... and ${n.length-5} more`),!await C({message:S.red(`Remove all existing files and proceed?`),initialValue:!1})){w(`Aborted.`);return}}for(let e of n)De(N(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=r?`minimal`:await x({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let o=t.runtime;o||=r?`express`:await x({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let c=t.pm;c||=r?await n(void 0):await x({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||=r?`inmemory`:await oe({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),u(l);let d=t.schema;d||=r?`zod`:await x({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(d)||(b.warn(`Unknown --schema "${d}", falling back to zod.`),d=`zod`);let f;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();f=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else f=r?[]:await ie({message:`Select packages to include`,options:[...Ke],required:!1});let p;p=t.git===void 0?r?!0:await C({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?r?!0:await C({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-BLs3Q93Y.mjs`);await t({name:e,directory:i,packageManager:c,initGit:p,installDeps:m,schemaLib:d,runtime:o}),w(`Done! Next steps: ${S.cyan(`cd ${e} && ${c}${c===`pnpm`?` dev`:` run dev:server`}`)}`);return}await s({name:e,directory:i,packageManager:c,initGit:p,installDeps:m,template:a,defaultRepo:l,packages:f,schemaLib:d,runtime:o}),w(`Done! Next steps: ${S.cyan(`cd ${e} && ${c} dev`)}`)})}function L(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function R(e){let t=L(e);return t.charAt(0).toLowerCase()+t.slice(1)}function z(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function B(e){return Ve.plural(e)}function Je(e){return Ve.plural(e)}function Ye(e){return z(e).replace(/-/g,`_`)}function Xe(e){let t=e.cwd??process.cwd(),n=e.projectRoot??T(t),r=e.pluralize??!0,i=L(e.name),a=R(e.name),o=z(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=B(o);c.pluralKebab=e,c.pluralPascal=L(e),c.pluralCamel=R(e)}return c}function Ze(e,t){return N(e.cwd,t)}async function Qe(e){return import(P(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=N(e,`package.json`);if(!E(t))return{generators:[],loaded:[],failed:[]};let n=nt(JSON.parse(await F(t,`utf-8`))),r=we(N(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 F(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=N(A(t),s);if(!E(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 v(t,e.content),o.push(t)}return{files:o,source:t}}function V(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const ct={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function lt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ut(e){return ct[e]??lt(e)}function dt(e){return`create${e}Repository`}function ft(e){return e??`define`}function pt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=dt(t),s=ft(a),c=`/**
11
+ import{t as e}from"./rolldown-runtime-DmTqmRjS.mjs";import{a as t,c as n,i as r,o as i,r as a,s as o,t as s,u as c}from"./project-DfBzpCeE.mjs";import{a as l,c as u,i as d,l as f,o as p,r as m,s as h}from"./config-CzL24fBQ.mjs";import{n as g,r as _}from"./plugin-BSNGbECd.mjs";import{c as v,l as y,s as b}from"./project-docs-DRLN1EDX.mjs";import{a as x,c as S,d as ee,f as C,i as te,l as ne,n as re,o as ie,p as ae,r as w,s as T,u as oe}from"./agent-docs-BK33p0Pw.mjs";import{t as E}from"./project-root-BsyQhlS5.mjs";import{_ as se,a as ce,c as le,d as ue,f as de,g as fe,h as pe,i as me,l as he,m as ge,o as _e,p as ve,r as ye,s as be,t as xe,u as Se}from"./typegen-B6vIx4Qd.mjs";import{t as Ce}from"./build-clh7HpZV.mjs";import{createRequire as we}from"node:module";import{cpSync as Te,existsSync as D,mkdirSync as Ee,readFileSync as O,readdirSync as k,rmSync as De,statSync as Oe,writeFileSync as ke}from"node:fs";import A,{basename as Ae,dirname as j,join as M,relative as N,resolve as P,sep as je}from"node:path";import{fileURLToPath as Me,pathToFileURL as F}from"node:url";import{fork as Ne,spawn as Pe,spawnSync as Fe}from"node:child_process";import{copyFile as Ie,mkdir as Le,readFile as I,readdir as Re,rm as ze,stat as Be,writeFile as L}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import Ve from"pluralize";import{arch as He,platform as Ue,release as We}from"node:os";import{createHash as Ge}from"node:crypto";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. swagger,ws,queue,devtools)`).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)=>{te(`KickJS — Create a new project`);let r=!!(t.yes||t.nonInteractive);e||=r?`my-api`:await oe({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=P(`.`),e=Ae(i)):i=P(t.directory||e),D(i)){let n=k(i);if(n.length>0){if(t.force)x.warn(`Clearing existing files in ${i}`);else if(r){x.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),T(`Aborted.`);return}else{x.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)x.message(` - ${e}`);if(n.length>5&&x.message(` ... and ${n.length-5} more`),!await w({message:C.red(`Remove all existing files and proceed?`),initialValue:!1})){T(`Aborted.`);return}}for(let e of n)De(P(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=r?`minimal`:await S({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let o=t.runtime;o||=r?`express`:await S({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let c=t.pm;c||=r?await n(void 0):await S({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||=r?`inmemory`:await oe({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),f(l);let u=t.schema;u||=r?`zod`:await S({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(u)||(x.warn(`Unknown --schema "${u}", falling back to zod.`),u=`zod`);let d;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();d=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else d=r?[]:await ie({message:`Select packages to include`,options:[...Ke],required:!1});let p;p=t.git===void 0?r?!0:await w({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?r?!0:await w({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DAEEITND.mjs`);await t({name:e,directory:i,packageManager:c,initGit:p,installDeps:m,schemaLib:u,runtime:o}),T(`Done! Next steps: ${C.cyan(`cd ${e} && ${c}${c===`pnpm`?` dev`:` run dev:server`}`)}`);return}await s({name:e,directory:i,packageManager:c,initGit:p,installDeps:m,template:a,defaultRepo:l,packages:d,schemaLib:u,runtime:o}),T(`Done! Next steps: ${C.cyan(`cd ${e} && ${c} dev`)}`)})}function R(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function z(e){let t=R(e);return t.charAt(0).toLowerCase()+t.slice(1)}function B(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function V(e){return Ve.plural(e)}function Je(e){return Ve.plural(e)}function Ye(e){return B(e).replace(/-/g,`_`)}function Xe(e){let t=e.cwd??process.cwd(),n=e.projectRoot??E(t),r=e.pluralize??!0,i=R(e.name),a=z(e.name),o=B(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=V(o);c.pluralKebab=e,c.pluralPascal=R(e),c.pluralCamel=z(e)}return c}function Ze(e,t){return P(e.cwd,t)}async function Qe(e){return import(F(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=P(e,`package.json`);if(!D(t))return{generators:[],loaded:[],failed:[]};let n=nt(JSON.parse(await I(t,`utf-8`))),r=we(P(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 I(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=P(j(t),s);if(!D(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 y(t,e.content),o.push(t)}return{files:o,source:t}}function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const ct={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function lt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ut(e){return ct[e]??lt(e)}function dt(e){return`create${e}Repository`}function ft(e){return e??`define`}function pt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=dt(t),s=ft(a),c=`/**
12
12
  * ${t} Module
13
13
  *
14
14
  * REST module with a flat folder structure.
@@ -198,36 +198,34 @@ ${i} async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
198
198
  return reply.noContent()
199
199
  }
200
200
  }
201
- `}function gt(e){let{pascal:t}=e;return`import { z } from 'zod'
201
+ `}const gt={zod:{import:`import { z } from 'zod'`,required:`z.string().min(1, 'Name is required').max(200)`,optional:`z.string().min(1).max(200).optional()`,infer:e=>`z.infer<typeof ${e}>`,hint:[` * z.string(), z.number(), z.boolean(), z.enum([...]),`,` * z.array(), z.object(), .optional(), .default(), .transform()`].join(`
202
+ `)},valibot:{import:`import * as v from 'valibot'`,required:`v.pipe(v.string(), v.minLength(1, 'Name is required'), v.maxLength(200))`,optional:`v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200)))`,infer:e=>`v.InferOutput<typeof ${e}>`,hint:[` * v.string(), v.number(), v.boolean(), v.picklist([...]),`,` * v.array(), v.object(), v.optional(), and v.pipe(...) to chain checks`].join(`
203
+ `)},yup:{import:`import * as yup from 'yup'`,required:`yup.string().required('Name is required').min(1).max(200)`,optional:`yup.string().min(1).max(200).optional()`,infer:e=>`yup.InferType<typeof ${e}>`,hint:[` * yup.string(), yup.number(), yup.boolean(), .oneOf([...]),`,` * yup.array(), yup.object(), .required(), .optional(), .default()`].join(`
204
+ `)}};function _t(e,t){return`${e===`zod`?`z.object`:e===`valibot`?`v.object`:`yup.object`}({\n ${t},\n})`}function vt(e){let{pascal:t}=e,n=e.schemaLib??`zod`,r=gt[n],i=`create${t}Schema`,a=n===`zod`?`Zod`:n===`valibot`?`Valibot`:`Yup`;return`${r.import}
202
205
 
203
206
  /**
204
- * Create ${t} DTO — Zod schema for validating POST request bodies.
205
- * This schema is passed to @Post('/', { body: create${t}Schema }) for automatic validation.
207
+ * Create ${t} DTO — ${a} schema for validating POST request bodies.
208
+ * This schema is passed to @Post('/', { body: ${i} }) for automatic validation.
206
209
  * It also generates OpenAPI request body docs when SwaggerAdapter is used.
207
210
  *
208
- * Add more fields as needed. Supported Zod types:
209
- * z.string(), z.number(), z.boolean(), z.enum([...]),
210
- * z.array(), z.object(), .optional(), .default(), .transform()
211
+ * Add more fields as needed. Supported ${a} types:
212
+ ${r.hint}
211
213
  */
212
- export const create${t}Schema = z.object({
213
- name: z.string().min(1, 'Name is required').max(200),
214
- })
214
+ export const ${i} = ${_t(n,`name: ${r.required}`)}
215
215
 
216
- export type Create${t}DTO = z.infer<typeof create${t}Schema>
217
- `}function _t(e){let{pascal:t}=e;return`import { z } from 'zod'
216
+ export type Create${t}DTO = ${r.infer(i)}
217
+ `}function yt(e){let{pascal:t}=e,n=e.schemaLib??`zod`,r=gt[n],i=`update${t}Schema`;return`${r.import}
218
218
 
219
- export const update${t}Schema = z.object({
220
- name: z.string().min(1).max(200).optional(),
221
- })
219
+ export const ${i} = ${_t(n,`name: ${r.optional}`)}
222
220
 
223
- export type Update${t}DTO = z.infer<typeof update${t}Schema>
224
- `}function vt(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
221
+ export type Update${t}DTO = ${r.infer(i)}
222
+ `}function bt(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
225
223
  id: string
226
224
  name: string
227
225
  createdAt: string
228
226
  updatedAt: string
229
227
  }
230
- `}function yt(e){let{pascal:t,kebab:n,repoType:r,dtoPrefix:i=`./dtos`,tokenScope:a=`app`}=e,o=r&&r!==`inmemory`?r:``,s=`create${t}Repository`,c=` const store = new Map<string, ${t}ResponseDTO>()
228
+ `}function xt(e){let{pascal:t,kebab:n,repoType:r,dtoPrefix:i=`./dtos`,tokenScope:a=`app`}=e,o=r&&r!==`inmemory`?r:``,s=`create${t}Repository`,c=` const store = new Map<string, ${t}ResponseDTO>()
231
229
 
232
230
  return {
233
231
  async findById(id: string): Promise<${t}ResponseDTO | null> {
@@ -302,7 +300,7 @@ export type ${t}Repository = ReturnType<typeof ${s}>
302
300
  * adopters must NOT use the reserved \`'kick/'\` namespace.
303
301
  */
304
302
  export const ${t.toUpperCase()}_REPOSITORY = createToken<${t}Repository>('${a}/${t}/repository')
305
- `}function bt(e){let{pascal:t,kebab:n,plural:r=``,style:i=`define`,testHarness:a=!1}=e,o=i===`define`?`${t}Module()`:`${t}Module`;return`${a?`import { describe, it, expect, beforeEach } from 'vitest'
303
+ `}function St(e){let{pascal:t,kebab:n,plural:r=``,style:i=`define`,testHarness:a=!1}=e,o=i===`define`?`${t}Module()`:`${t}Module`;return`${a?`import { describe, it, expect, beforeEach } from 'vitest'
306
304
  import request from 'supertest'
307
305
  import { Container } from '@forinda/kickjs'
308
306
  import { createTestApp } from '@forinda/kickjs-testing'
@@ -396,7 +394,7 @@ ${a?` /**
396
394
  it.todo('deletes a ${n}')
397
395
  })
398
396
  })
399
- `}function xt(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../${n}.repository`}=e,a=`create${t}Repository`;return`import { describe, it, expect, beforeEach } from 'vitest'
397
+ `}function Ct(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../${n}.repository`}=e,a=`create${t}Repository`;return`import { describe, it, expect, beforeEach } from 'vitest'
400
398
  import { ${a}, type ${t}Repository } from '${i}'
401
399
 
402
400
  describe('${t} repository', () => {
@@ -458,7 +456,7 @@ describe('${t} repository', () => {
458
456
  expect(found).toBeNull()
459
457
  })
460
458
  })
461
- `}function St(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
459
+ `}function wt(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
462
460
  import type { ParsedQuery } from '@forinda/kickjs'
463
461
  import { ${t.toUpperCase()}_REPOSITORY, type ${t}Repository } from './${n}.repository'
464
462
  import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
@@ -495,14 +493,14 @@ export class ${t}Service {
495
493
  await this.repo.delete(id)
496
494
  }
497
495
  }
498
- `}function Ct(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
496
+ `}function Tt(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
499
497
 
500
498
  export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
501
499
  filterable: ['name'],
502
500
  sortable: ['name', 'createdAt'],
503
501
  searchable: ['name'],
504
502
  }
505
- `}async function wt(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,mt({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
503
+ `}async function Et(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,mt({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
506
504
 
507
505
  // \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
508
506
  // \`kick typegen\` (auto-run on \`kick dev\`).
@@ -542,7 +540,7 @@ export class ${t}Controller {
542
540
  return reply.noContent()
543
541
  }
544
542
  }
545
- `)}async function Tt(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,tokenScope:s,style:c,testHarness:l,write:u}=e,d=e.swagger??!1;await u(`${n}.module.ts`,pt({pascal:t,kebab:n,plural:r,repo:a,style:c})),await u(`${n}.constants.ts`,Ct({pascal:t,kebab:n})),await u(`${n}.controller.ts`,ht({pascal:t,kebab:n,plural:r,pluralPascal:i,swagger:d})),await u(`${n}.service.ts`,St({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,gt({pascal:t,kebab:n})),await u(`dtos/update-${n}.dto.ts`,_t({pascal:t,kebab:n})),await u(`dtos/${n}-response.dto.ts`,vt({pascal:t,kebab:n})),await u(`${n}.repository.ts`,yt({pascal:t,kebab:n,repoType:a,dtoPrefix:`./dtos`,tokenScope:s})),o||(await u(`__tests__/${n}.controller.test.ts`,bt({pascal:t,kebab:n,plural:r,style:c,testHarness:l})),await u(`__tests__/${n}.repository.test.ts`,xt({pascal:t,kebab:n,plural:r,repoPrefix:`../${n}.repository`})))}function Et(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Dt(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`rest`;e.minimal&&(l=`minimal`);let u=z(t),d=L(t),f=c?B(u):u,p=c?Je(d):d,m=j(n,f),h=[],g=o??!1,_={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,tokenScope:e.tokenScope??`app`,swagger:e.swagger??!1,testHarness:e.testHarness??!1,style:e.style??`define`,write:async(e,t)=>{let n=j(m,e);if(s){h.push(n);return}if(!g&&await y(n)&&!await C({message:`File exists: ${S.dim(e)}. Overwrite?`,initialValue:!1})){b.warn(`Skipped: ${e}`);return}await v(n,t),h.push(n)},files:h};switch(l){case`minimal`:await wt(_);break;default:await Tt(_);break}return s||await Ot(n,d,f,u,_.style),h}async function Ot(e,t,n,r,i=`define`){let a=j(e,`index.ts`),o=await y(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await v(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
543
+ `)}async function Dt(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,tokenScope:s,style:c,testHarness:l,write:u}=e,d=e.swagger??!1,f=e.schemaLib??`zod`;await u(`${n}.module.ts`,pt({pascal:t,kebab:n,plural:r,repo:a,style:c})),await u(`${n}.constants.ts`,Tt({pascal:t,kebab:n})),await u(`${n}.controller.ts`,ht({pascal:t,kebab:n,plural:r,pluralPascal:i,swagger:d})),await u(`${n}.service.ts`,wt({pascal:t,kebab:n})),await u(`dtos/create-${n}.dto.ts`,vt({pascal:t,kebab:n,schemaLib:f})),await u(`dtos/update-${n}.dto.ts`,yt({pascal:t,kebab:n,schemaLib:f})),await u(`dtos/${n}-response.dto.ts`,bt({pascal:t,kebab:n})),await u(`${n}.repository.ts`,xt({pascal:t,kebab:n,repoType:a,dtoPrefix:`./dtos`,tokenScope:s})),o||(await u(`__tests__/${n}.controller.test.ts`,St({pascal:t,kebab:n,plural:r,style:c,testHarness:l})),await u(`__tests__/${n}.repository.test.ts`,Ct({pascal:t,kebab:n,plural:r,repoPrefix:`../${n}.repository`})))}function Ot(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function kt(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`rest`;e.minimal&&(l=`minimal`);let u=B(t),d=R(t),f=c?V(u):u,p=c?Je(d):d,m=M(n,f),h=[],g=o??!1,_={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,tokenScope:e.tokenScope??`app`,swagger:e.swagger??!1,schemaLib:e.schemaLib??`zod`,testHarness:e.testHarness??!1,style:e.style??`define`,write:async(e,t)=>{let n=M(m,e);if(s){h.push(n);return}if(!g&&await b(n)&&!await w({message:`File exists: ${C.dim(e)}. Overwrite?`,initialValue:!1})){x.warn(`Skipped: ${e}`);return}await y(n,t),h.push(n)},files:h};switch(l){case`minimal`:await Et(_);break;default:await Dt(_);break}return s||await At(n,d,f,u,_.style),h}async function At(e,t,n,r,i=`define`){let a=M(e,`index.ts`),o=await b(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await y(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
546
544
  import { ${t}Module } from '${s}'
547
545
 
548
546
  export const modules: AppModuleEntry[] = [${c}]
@@ -550,11 +548,11 @@ export const modules: AppModuleEntry[] = [${c}]
550
548
  import { ${t}Module } from '${s}'
551
549
 
552
550
  export const modules = defineModules().mount(${c})
553
- `);return}let l=await F(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=V(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${V(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
551
+ `);return}let l=await I(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=H(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${H(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
554
552
  `,e);l=l.slice(0,t+1)+u+`
555
553
  `+l.slice(t+1)}else l=u+`
556
- `+l}let f=At(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${V(t)}Module\\b`).test(e)||(l=kt(l,c))}else l=kt(l,c);await I(a,l,`utf-8`)}function kt(e,t){let n=At(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 At(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=Nt(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=jt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function jt(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=Pt(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=Pt(e,t);if(n===-1)break;i=n+1}return i}function Mt(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
557
- `;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function Nt(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=Mt(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 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=Mt(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 Ft(e){let{name:t,outDir:n}=e,r=z(t),i=L(t),a=[],o=j(n,`${r}.adapter.ts`);return await v(o,`import {
554
+ `+l}let f=Mt(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${H(t)}Module\\b`).test(e)||(l=jt(l,c))}else l=jt(l,c);await L(a,l,`utf-8`)}function jt(e,t){let n=Mt(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 Mt(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=Ft(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=Nt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function Nt(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=It(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=It(e,t);if(n===-1)break;i=n+1}return i}function Pt(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
555
+ `;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}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=Pt(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 It(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=Pt(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 Lt(e){let{name:t,outDir:n}=e,r=B(t),i=R(t),a=[],o=M(n,`${r}.adapter.ts`);return await y(o,`import {
558
556
  defineAdapter,
559
557
  type AdapterContext,
560
558
  type AdapterMiddleware,
@@ -619,7 +617,8 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
619
617
  * \`phase\` controls where each handler sits in the pipeline:
620
618
  * 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
621
619
  *
622
- * \`path\` (optional) scopes the entry to a path prefix.
620
+ * \`path\` (optional) scopes the entry — a string prefix, a RegExp,
621
+ * or an array mixing both. See \`MiddlewarePath\`.
623
622
  *
624
623
  * Delete this hook entirely if you don't add middleware.
625
624
  */
@@ -651,8 +650,13 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
651
650
  * Delete this hook if you have no early routes.
652
651
  */
653
652
  beforeMount(_ctx: AdapterContext): void {
654
- // Example:
655
- // _ctx.app.get('/${r}/status', (_req, res) => res.json({ status: 'ok' }))
653
+ // Example — \`ctx.http\` is the engine-neutral seam, so this route
654
+ // works under Express, Fastify and h3 alike:
655
+ // _ctx.http.route('GET', '/${r}/status', (ctx) => ctx.json({ status: 'ok' }))
656
+ //
657
+ // \`ctx.app\` is the engine-native instance (an Express app only under
658
+ // the default runtime). Reach for it when what you're wiring is
659
+ // genuinely engine-specific, and accept the lock-in.
656
660
  },
657
661
 
658
662
  /**
@@ -793,7 +797,7 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
793
797
  }
794
798
  },
795
799
  })
796
- `),a.push(o),a}async function It(e){let{name:t,outDir:n}=e,r=z(t),i=L(t),a=[],o=j(n,`${r}.plugin.ts`);return await v(o,`import {
800
+ `),a.push(o),a}async function Rt(e){let{name:t,outDir:n}=e,r=B(t),i=R(t),a=[],o=M(n,`${r}.plugin.ts`);return await y(o,`import {
797
801
  definePlugin,
798
802
  type AppAdapter,
799
803
  type AppModuleEntry,
@@ -822,18 +826,27 @@ export interface ${i}PluginConfig {
822
826
  * A plugin bundles DI bindings, modules, adapters, and middleware
823
827
  * into one object that can be added to \`bootstrap({ plugins })\`.
824
828
  *
825
- * Lifecycle order (each hook is optional — delete the ones you don't
826
- * need and keep only the surface your plugin actually uses):
829
+ * Call order (each hook is optional — delete the ones you don't need and
830
+ * keep only the surface your plugin actually uses). This is the order the
831
+ * hooks are INVOKED in, which is not the order they read in below:
827
832
  *
828
- * 1. \`register(container)\` — runs before user modules load. Use
829
- * it to bind services that modules depend on.
830
- * 2. \`modules()\` — plugin modules load before user modules.
831
- * 3. \`adapters()\` — plugin adapters mount before user adapters.
832
- * 4. \`middleware()\` — plugin middleware runs before user middleware.
833
+ * 1. \`adapters()\` — read first, while the app is still being
834
+ * constructed; the returned adapters mount before user adapters.
835
+ * 2. \`register(container)\` — runs before user modules load. Use it to
836
+ * bind services that modules depend on.
837
+ * 3. \`middleware()\` — mounts BEFORE \`modules()\` is read, so a
838
+ * handler here cannot resolve anything a plugin module registers.
839
+ * 4. \`modules()\` / \`setup(registry)\` — plugin modules load before user
840
+ * modules.
833
841
  * 5. \`contributors()\` — Context Contributors merged into every route.
834
842
  * 6. \`onReady(container)\` — runs after the app has fully bootstrapped.
835
843
  * 7. \`shutdown()\` — on shutdown AND every HMR reload.
836
844
  *
845
+ * \`.async()\` resolves its config inside \`onReady\`, which is past every
846
+ * contribution point above: only \`register()\`, \`onReady()\` and
847
+ * \`shutdown()\` still run. Use the bare or \`.scoped()\` form when the plugin
848
+ * ships modules, adapters, middleware, or contributors.
849
+ *
837
850
  * @example
838
851
  * \`\`\`ts
839
852
  * import { bootstrap } from '@forinda/kickjs'
@@ -887,8 +900,11 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
887
900
  },
888
901
 
889
902
  /**
890
- * Return Express middleware entries to be added to the global
891
- * pipeline. Plugin middleware runs before user-defined middleware.
903
+ * Return connect-style handlers — \`(req, res, next)\` — for the global
904
+ * pipeline. Every runtime accepts them: each one is mounted through the
905
+ * engine's \`useConnect\` seam, so this is NOT Express-only. Plugin
906
+ * middleware runs before user-defined middleware, and takes no
907
+ * \`phase\` / \`path\` — use an adapter's \`middleware()\` for those.
892
908
  */
893
909
  middleware(): unknown[] {
894
910
  return [
@@ -939,10 +955,10 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
939
955
  },
940
956
  }),
941
957
  })
942
- `),a.push(o),a}const Lt={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function H(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return N(n);if(r){let e=Lt,n=z(r),a=o?B(n):n,s=e[t]??``,c=j(i,a);return N(s?j(c,s):c)}return N(a)}async function Rt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.runtime===`express`,o=e.runtime?`this project runs on ${e.runtime} and has no
943
- // \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=H({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),c=z(t),l=R(t),u=[],d=j(s,`${c}.middleware.ts`);return await v(d,`${a?`import type { Request, Response, NextFunction } from 'express'`:`import type { IncomingMessage, ServerResponse } from 'node:http'`}
958
+ `),a.push(o),a}const zt={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function U(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return P(n);if(r){let e=zt,n=B(r),a=o?V(n):n,s=e[t]??``,c=M(i,a);return P(s?M(c,s):c)}return P(a)}async function Bt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.runtime===`express`,o=e.runtime?`this project runs on ${e.runtime} and has no
959
+ // \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=U({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),c=B(t),l=z(t),u=[],d=M(s,`${c}.middleware.ts`);return await y(d,`${a?`import type { Request, Response, NextFunction } from 'express'`:`import type { IncomingMessage, ServerResponse } from 'node:http'`}
944
960
 
945
- export interface ${L(t)}Options {
961
+ export interface ${R(t)}Options {
946
962
  // Add configuration options here. The factory below closes over the
947
963
  // resolved options object; pass them at the call site —
948
964
  // \`${l}({ foo: 'bar' })\` — and the closure preserves them across
@@ -950,7 +966,7 @@ export interface ${L(t)}Options {
950
966
  }
951
967
 
952
968
  /**
953
- * ${L(t)} middleware.
969
+ * ${R(t)} middleware.
954
970
  *
955
971
  * Usage in bootstrap (fires on every request):
956
972
  * middlewares: [${l}()]
@@ -979,10 +995,14 @@ export interface ${L(t)}Options {
979
995
  * }]
980
996
  * }
981
997
  *
982
- * Usage with @Middleware decorator:
983
- * @Middleware(${l}())
998
+ * NOT for \`@Middleware()\`. That decorator takes a ctx-style handler —
999
+ * \`(ctx, next)\`, see \`MiddlewareHandler\` — and the runtime calls it with
1000
+ * exactly two arguments. Passing this connect-style factory there binds
1001
+ * \`next\` to the response slot and passes no third argument at all, so the
1002
+ * first \`next()\` throws \`TypeError: next is not a function\`. Generate a
1003
+ * guard instead (\`kick g guard\`) for the per-route, ctx-style shape.
984
1004
  */
985
- export function ${l}(options: ${L(t)}Options = {}) {
1005
+ export function ${l}(options: ${R(t)}Options = {}) {
986
1006
  ${a?" // Typed from `express` because that is this project's runtime\n // (`runtime: 'express'` in kick.config.ts). Global middleware is\n // connect-style on every engine, but only Express hands the handler its own\n // request / response objects — so `req.originalUrl`, `req.query` and\n // `res.json()` are all available here. Switching `runtime` later means\n // re-typing this signature from `node:http`.\n return (req: Request, res: Response, next: NextFunction) => {":` // Typed from \`node:http\`, not \`express\`. Global middleware is connect-style
987
1007
  // on every engine, but ${o} dependency to import types from. Under Fastify the handler
988
1008
  // receives \`request.raw\` / a reply driver, and under h3 the node objects, so
@@ -995,7 +1015,7 @@ ${a?" // Typed from `express` because that is this project's runtime\n // (`ru
995
1015
  next()
996
1016
  }
997
1017
  }
998
- `),u.push(d),u}async function zt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=H({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=R(t),c=L(t),l=[],u=j(a,`${o}.guard.ts`);return await v(u,`import { Container, HttpException } from '@forinda/kickjs'
1018
+ `),u.push(d),u}async function Vt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=z(t),c=R(t),l=[],u=M(a,`${o}.guard.ts`);return await y(u,`import { Container, HttpException } from '@forinda/kickjs'
999
1019
  import type { RequestContext } from '@forinda/kickjs'
1000
1020
 
1001
1021
  /**
@@ -1035,11 +1055,11 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
1035
1055
  ctx.problem.unauthorized({ detail: 'Invalid or expired token' })
1036
1056
  }
1037
1057
  }
1038
- `),l.push(u),l}function Bt(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 Vt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=z(t),s=L(t),c=e.key??R(t),l=Array.isArray(e.params)?e.params:Bt(e.params),u=H({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
1058
+ `),l.push(u),l}function Ht(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 Ut(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=B(t),s=R(t),c=e.key??z(t),l=Array.isArray(e.params)?e.params:Ht(e.params),u=U({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
1039
1059
  `)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,h=l.length>0?` // Every call site must supply these — no placeholder defaults.
1040
1060
  // Add \`paramDefaults: { … }\` for any field whose default is
1041
1061
  // genuinely correct for an undecorated route, and drop it from here.
1042
- requiredParams: [${l.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,g=l.length>0?`(ctx, _deps, params)`:`(ctx)`,_=l.length>0?` // \`params\` is typed as ${s}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${f} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,y=`import { ${d} } from '@forinda/kickjs'
1062
+ requiredParams: [${l.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,g=l.length>0?`(ctx, _deps, params)`:`(ctx)`,_=l.length>0?` // \`params\` is typed as ${s}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${f} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,v=`import { ${d} } from '@forinda/kickjs'
1043
1063
  import type { ${f} } from '@forinda/kickjs'
1044
1064
 
1045
1065
  /**
@@ -1086,7 +1106,7 @@ ${_}
1086
1106
  throw new Error("${s} contributor: resolve() not implemented")
1087
1107
  },
1088
1108
  })
1089
- `,b=j(u,`${o}.contributor.ts`);return await v(b,y),[b]}async function Ht(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=H({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=L(t),c=[],l=j(a,`${o}.service.ts`);return await v(l,`import { Service } from '@forinda/kickjs'
1109
+ `,b=M(u,`${o}.contributor.ts`);return await y(b,v),[b]}async function Wt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=[],l=M(a,`${o}.service.ts`);return await y(l,`import { Service } from '@forinda/kickjs'
1090
1110
 
1091
1111
  @Service()
1092
1112
  export class ${s}Service {
@@ -1095,7 +1115,7 @@ export class ${s}Service {
1095
1115
  // @Inject(MY_REPO) private readonly repo: IMyRepository,
1096
1116
  // ) {}
1097
1117
  }
1098
- `),c.push(l),c}async function Ut(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=H({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=L(t),c=[],l=j(a,`${o}.controller.ts`);return await v(l,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
1118
+ `),c.push(l),c}async function Gt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=[],l=M(a,`${o}.controller.ts`);return await y(l,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
1099
1119
 
1100
1120
  // \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
1101
1121
  // \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
@@ -1137,16 +1157,13 @@ export class ${s}Controller {
1137
1157
  return reply.noContent()
1138
1158
  }
1139
1159
  }
1140
- `),c.push(l),c}async function Wt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=H({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=z(t),s=L(t),c=R(t),l=[],u=j(a,`${o}.dto.ts`);return await v(u,`import { z } from 'zod'
1160
+ `),c.push(l),c}async function Kt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=U({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=B(t),s=R(t),c=z(t),l=e.schemaLib??`zod`,u=gt[l],d=[],f=M(a,`${o}.dto.ts`);return await y(f,`${u.import}
1141
1161
 
1142
- export const ${c}Schema = z.object({
1143
- // Define your schema fields here
1144
- name: z.string().min(1).max(200),
1145
- })
1162
+ export const ${c}Schema = ${_t(l,`// Define your schema fields here\n name: ${u.required}`)}
1146
1163
 
1147
- export type ${s}DTO = z.infer<typeof ${c}Schema>
1148
- `),l.push(u),l}async function Gt(e){let t=j(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return E(t)&&!e.force&&!await C({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
1149
- Skipped — existing kick.config.ts preserved.`),[]):(await v(t,`import { defineConfig } from '@forinda/kickjs-cli'
1164
+ export type ${s}DTO = ${u.infer(`${c}Schema`)}
1165
+ `),d.push(f),d}async function qt(e){let t=M(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return D(t)&&!e.force&&!await w({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
1166
+ Skipped — existing kick.config.ts preserved.`),[]):(await y(t,`import { defineConfig } from '@forinda/kickjs-cli'
1150
1167
 
1151
1168
  export default defineConfig({
1152
1169
  modules: {
@@ -1188,18 +1205,18 @@ export default defineConfig({
1188
1205
  },
1189
1206
  ],
1190
1207
  })
1191
- `),[t])}function Kt(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 U(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=Kt(e,r);return i===-1?null:e.slice(r+1,i)}function W(e,t,n){let r=` `.repeat(n);return e.split(`
1208
+ `),[t])}function Jt(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 W(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=Jt(e,r);return i===-1?null:e.slice(r+1,i)}function G(e,t,n){let r=` `.repeat(n);return e.split(`
1192
1209
  `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
1193
- `)}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=Kt(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=U(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=U(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=U(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) {${W(l,4,6)} },\n\n`),u&&(p+=` contributors() {${W(u,4,6)} },\n\n`),p+=` routes() {${W(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
1210
+ `)}function Yt(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 Xt(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 Zt(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=Jt(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=W(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=W(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=W(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Yt(s),p=``;return l&&(p+=` register(container) {${G(l,4,6)} },\n\n`),u&&(p+=` contributors() {${G(u,4,6)} },\n\n`),p+=` routes() {${G(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
1194
1211
  name: '${r}',
1195
1212
  build: () => ({
1196
1213
  ${p}
1197
1214
  }),
1198
- })`}${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=Kt(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]===`
1199
- `||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=Kt(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=U(m,/register\s*\(([^)]*)\)\s*\{/),g=U(m,/contributors\s*\(\s*\)\s*\{/),_=U(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 {${W(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${W(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${W(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
1215
+ })`}${c}`}}function Qt(e){if(/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+const\s+(\w+Module)\s*=\s*defineModule\s*\(\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no defineModule form detected`};if(t.length>1)return{migrated:null,reason:`multiple defineModule blocks in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=Jt(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]===`
1216
+ `||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=Jt(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=W(m,/register\s*\(([^)]*)\)\s*\{/),g=W(m,/contributors\s*\(\s*\)\s*\{/),_=W(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Xt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${G(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${G(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${G(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
1200
1217
  ${y}
1201
1218
  }
1202
- `}${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(N(e),0),t;async function n(e,r){let i;try{i=await Re(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=j(e,a),o;try{o=await Be(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 Re(e)}catch{return}await Le(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=j(e,a),o=j(t,a),s;try{s=await Be(i)}catch{continue}s.isDirectory()?await r(i,o):(await Ie(i,o),n++)}}}function tn(e){return j(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 F(j(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 F(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await I(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=j(e,`index.ts`),d=null;try{d=await F(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 I(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 F(e,`utf-8`);i.test(t)&&r.push(e)}return r}const an={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 on(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=an[a];if(!o){let e=[...Object.keys(an),`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 sn(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=z(t),l=L(t),u=s?B(c):c,d=s?Je(l):l,f=j(r,u),p=[],m=async(e,t)=>{let n=j(f,e);await v(n,t),p.push(n)};return await m(`${c}.module.ts`,pt({pascal:l,kebab:c,plural:u,repo:i,style:o})),await m(`${c}.constants.ts`,Ct({pascal:l,kebab:c})),await m(`${c}.controller.ts`,ht({pascal:l,kebab:c,plural:u,pluralPascal:d,swagger:e.swagger??!1})),await m(`${c}.service.ts`,St({pascal:l,kebab:c})),await m(`dtos/create-${c}.dto.ts`,cn(l,n)),await m(`dtos/update-${c}.dto.ts`,ln(l,n)),await m(`dtos/${c}-response.dto.ts`,un(l,n)),await m(`${c}.repository.ts`,yt({pascal:l,kebab:c,repoType:i,dtoPrefix:`./dtos`,tokenScope:a})),await Ot(r,l,u,c,o),p}function cn(e,t){return`import { z } from 'zod'
1219
+ `}${u}`}}function $t(e,t){return t===`class`?Qt(e):Zt(e)}function en(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 tn(e){let t=[];return await n(P(e),0),t;async function n(e,r){let i;try{i=await Re(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=M(e,a),o;try{o=await Be(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function nn(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Re(e)}catch{return}await Le(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=M(e,a),o=M(t,a),s;try{s=await Be(i)}catch{continue}s.isDirectory()?await r(i,o):(await Ie(i,o),n++)}}}function rn(e){return M(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function an(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await tn(e),s=await I(M(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=rn(r),await nn(e,c));let l=[];for(let e of o){let t=$t(await I(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await L(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=M(e,`index.ts`),d=null;try{d=await I(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=en(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await L(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function on(e,t){let n=await tn(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 I(e,`utf-8`);i.test(t)&&r.push(e)}return r}const sn={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 cn(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=sn[a];if(!o){let e=[...Object.keys(sn),`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 ln(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=B(t),l=R(t),u=s?V(c):c,d=s?Je(l):l,f=M(r,u),p=[],m=async(e,t)=>{let n=M(f,e);await y(n,t),p.push(n)};return await m(`${c}.module.ts`,pt({pascal:l,kebab:c,plural:u,repo:i,style:o})),await m(`${c}.constants.ts`,Tt({pascal:l,kebab:c})),await m(`${c}.controller.ts`,ht({pascal:l,kebab:c,plural:u,pluralPascal:d,swagger:e.swagger??!1})),await m(`${c}.service.ts`,wt({pascal:l,kebab:c})),await m(`dtos/create-${c}.dto.ts`,un(l,n)),await m(`dtos/update-${c}.dto.ts`,dn(l,n)),await m(`dtos/${c}-response.dto.ts`,fn(l,n)),await m(`${c}.repository.ts`,xt({pascal:l,kebab:c,repoType:i,dtoPrefix:`./dtos`,tokenScope:a})),await At(r,l,u,c,o),p}function un(e,t){return`import { z } from 'zod'
1203
1220
 
1204
1221
  export const create${e}Schema = z.object({
1205
1222
  ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
@@ -1207,7 +1224,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
1207
1224
  })
1208
1225
 
1209
1226
  export type Create${e}DTO = z.infer<typeof create${e}Schema>
1210
- `}function ln(e,t){return`import { z } from 'zod'
1227
+ `}function dn(e,t){return`import { z } from 'zod'
1211
1228
 
1212
1229
  export const update${e}Schema = z.object({
1213
1230
  ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
@@ -1215,14 +1232,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
1215
1232
  })
1216
1233
 
1217
1234
  export type Update${e}DTO = z.infer<typeof update${e}Schema>
1218
- `}function un(e,t){return`export interface ${e}ResponseDTO {
1235
+ `}function fn(e,t){return`export interface ${e}ResponseDTO {
1219
1236
  id: string
1220
1237
  ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
1221
1238
  `)}
1222
1239
  createdAt: string
1223
1240
  updatedAt: string
1224
1241
  }
1225
- `}async function dn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=z(t),o=L(t),s=[],c;if(e.outDir)c=N(e.outDir);else if(n){let e=z(n),t=i?B(e):e;c=N(j(r??`src/modules`,t,`__tests__`))}else c=N(`src/__tests__`);let l=j(c,`${a}.test.ts`);return await v(l,`import { describe, it, expect, beforeEach } from 'vitest'
1242
+ `}async function pn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=B(t),o=R(t),s=[],c;if(e.outDir)c=P(e.outDir);else if(n){let e=B(n),t=i?V(e):e;c=P(M(r??`src/modules`,t,`__tests__`))}else c=P(`src/__tests__`);let l=M(c,`${a}.test.ts`);return await y(l,`import { describe, it, expect, beforeEach } from 'vitest'
1226
1243
  import { Container } from '@forinda/kickjs'
1227
1244
 
1228
1245
  describe('${o}', () => {
@@ -1245,58 +1262,58 @@ describe('${o}', () => {
1245
1262
  expect(true).toBe(true)
1246
1263
  })
1247
1264
  })
1248
- `),s.push(l),s}function fn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}var pn=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
1249
- `);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 G(e){return e.parent?.opts()?.dryRun??!1}function K(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(`
1250
- (dry run — no files were written)`),console.log()}async function hn(e){if(!e)try{let e=await l(process.cwd());await xe({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:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate .agents/* + root CLAUDE.md from upstream templates`}],_n=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
1251
- Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),vn=new Set([...gn.map(e=>e.name.split(` `)[0]),..._n.keys()]);async function yn(){console.log(`
1265
+ `),s.push(l),s}function mn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}var hn=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
1266
+ `);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 gn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function K(e){return e.parent?.opts()?.dryRun??!1}function q(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(`
1267
+ (dry run — no files were written)`),console.log()}async function _n(e){if(!e)try{let e=await l(process.cwd());await xe({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 vn=[{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:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate .agents/* + root CLAUDE.md from upstream templates`}],yn=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
1268
+ Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),bn=new Set([...vn.map(e=>e.name.split(` `)[0]),...yn.keys()]);async function xn(){console.log(`
1252
1269
  Built-in generators:
1253
- `);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 l(process.cwd()),n=h(t?.plugins??[],t?.commands??[]),r=await at(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
1270
+ `);let e=Math.max(...vn.map(e=>e.name.length));for(let t of vn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await l(process.cwd()),n=g(t?.plugins??[],t?.commands??[]),r=await at(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
1254
1271
  Plugin generators:
1255
1272
  `);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(`
1256
1273
  Failed to load:
1257
- `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function bn(e,t,n){let r=await l(process.cwd()),i=f(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Et(i.repo);t.repo&&u(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,h=m(r,process.cwd()),g=d(T()),_=T(),v=p(_,`@forinda/kickjs-testing`,`any`)&&p(_,`supertest`,`any`),y=i.style??`define`;if(!n&&y===`define`){let e=await rn(N(a),`define`);if(e.length>0){console.error(`\n ${S.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${S.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${S.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 ${S.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${S.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${S.dim(`// kick.config.ts`)}\n ${S.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let b=[];for(let r of e){let e=await Dt({name:r,modulesDir:N(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:v,dryRun:n,pluralize:c,tokenScope:h,swagger:g,style:i.style});b.push(...e)}K(b,n),await hn(n)}function xn(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await yn();return}if(!e||e.length===0){n.help();return}let a=G(i);_(a);let[o,s,...c]=e;if(o){let e=await l(process.cwd()),n=h(e?.plugins??[],e?.commands??[]),i=await it({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){K(i.files,a);return}if(o!==`module`&&vn.has(o)){let e=_n.get(o);e?(console.error(`\n 'kick g ${o}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`)),process.exitCode=1;return}}await bn(e,r,a)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=G(n);_(r),await bn(e,{...n.optsWithGlobals(),...t},r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=G(n);_(r),K(await Ft({name:e,outDir:N(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=G(n);_(r),K(await It({name:e,outDir:N(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
1258
- Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=G(n);_(r);let i=await l(process.cwd()),a=f(i),o=a.dir??`src/modules`;K(await Rt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
1259
- Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=G(n);_(r);let i=await l(process.cwd()),a=f(i),o=a.dir??`src/modules`;K(await zt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
1274
+ `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Sn(e,t,n){let r=await l(process.cwd()),i=p(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Ot(i.repo);t.repo&&f(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,g=u(r,process.cwd()),_=d(E()),v=h(E()),y=E(),b=m(y,`@forinda/kickjs-testing`,`any`)&&m(y,`supertest`,`any`),x=i.style??`define`;if(!n&&x===`define`){let e=await on(P(a),`define`);if(e.length>0){console.error(`\n ${C.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${C.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${C.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 ${C.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${C.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${C.dim(`// kick.config.ts`)}\n ${C.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let S=[];for(let r of e){let e=await kt({name:r,modulesDir:P(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:b,dryRun:n,pluralize:c,tokenScope:g,swagger:_,schemaLib:v,style:i.style});S.push(...e)}q(S,n),await _n(n)}function Cn(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await xn();return}if(!e||e.length===0){n.help();return}let a=K(i);v(a);let[o,s,...c]=e;if(o){let e=await l(process.cwd()),n=g(e?.plugins??[],e?.commands??[]),i=await it({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){q(i.files,a);return}if(o!==`module`&&bn.has(o)){let e=yn.get(o);e?(console.error(`\n 'kick g ${o}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`)),process.exitCode=1;return}}await Sn(e,r,a)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=K(n);v(r),await Sn(e,{...n.optsWithGlobals(),...t},r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=K(n);v(r),q(await Lt({name:e,outDir:P(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=K(n);v(r),q(await Rt({name:e,outDir:P(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
1275
+ Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=K(n);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;q(await Bt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
1276
+ Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=K(n);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;q(await Vt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
1260
1277
  --type http (default, RequestContext) | bare (ExecutionContext)
1261
1278
  --params "source:string,region:number" → emits the withParams<T>() form
1262
- Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=G(n);_(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await l(process.cwd()),o=f(a),s=o.dir??`src/modules`;K(await Vt({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
1263
- Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=G(n);_(r);let i=await l(process.cwd()),a=f(i),o=a.dir??`src/modules`;K(await Ht({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
1264
- Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=G(n);_(r);let i=await l(process.cwd()),a=f(i),o=a.dir??`src/modules`;K(await Ut({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await hn(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
1265
- Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=G(n);_(r);let i=await l(process.cwd()),a=f(i),o=a.dir??`src/modules`;K(await Wt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
1266
- Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=G(n);_(r);let i=f(await l(process.cwd())),a=i.dir??`src/modules`;K(await dn({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
1279
+ Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=K(n);v(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await l(process.cwd()),o=p(a),s=o.dir??`src/modules`;q(await Ut({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
1280
+ Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=K(n);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;q(await Wt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
1281
+ Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=K(n);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;q(await Gt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await _n(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
1282
+ Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=K(n);v(r);let i=await l(process.cwd()),a=p(i),o=a.dir??`src/modules`;q(await Kt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,schemaLib:h(E())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
1283
+ Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=K(n);v(r);let i=p(await l(process.cwd())),a=i.dir??`src/modules`;q(await pn({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
1267
1284
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
1268
1285
  Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
1269
1286
  Optional: append :optional (shell-safe): description:text:optional
1270
- or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=G(r);_(i),t.length===0&&(console.error(`
1287
+ or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=K(r);v(i),t.length===0&&(console.error(`
1271
1288
  Error: At least one field is required.
1272
1289
  Usage: kick g scaffold <name> <field:type> [field:type...]
1273
1290
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
1274
1291
  Optional: append :optional (shell-safe, no quoting needed)
1275
- `),process.exit(1));let a=await l(process.cwd()),o=f(a),s=n.modulesDir??o.dir??`src/modules`,c=on(t),u=m(a,process.cwd()),p=d(T()),h=await sn({name:e,fields:c,modulesDir:N(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:u,swagger:p,style:o.style});console.log(`\n Scaffolded ${e} with ${c.length} field(s):`);for(let e of c)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);K(h,i),await hn(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=G(t);_(n),K(await Gt({outDir:N(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | 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 | fullstack`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=G(t);_(n);let r=e.only??`all`;if(!mn.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${mn.join(` | `)}`),process.exitCode=1;return}K(await re({outDir:N(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])Sn(n,e,t?.projectRoot)}function Sn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=G(o);_(s);let c=await it({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&K(c.files,s)})}const Cn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function wn(e){let t=k.resolve(e.cwd,`.kickjs/types`);e.check||await Le(t,{recursive:!0});let n=new Map,r=e.scan??fe,i=k.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(P(e).href)},async writeFile(t,n){let r=k.resolve(e.cwd,t);await Le(k.dirname(r),{recursive:!0}),await I(r,n,`utf8`)},getScanResult:e=>{let t=Tn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?se(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=k.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=`${Cn}${n.id} */\n\n`+a+`
1276
- `,u=``;if(E(i)&&(u=await F(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 I(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new pn(c);return s}function Tn(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 En(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 Dn=e({applyDisableFilter:()=>En,runAllPluginTypegens:()=>On});async function On(e){let{enabled:t,skipped:n,unknown:r}=En(h([...Ma,...e.config?.plugins??[]],e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&n.length>0)for(let e of n)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&r.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${r.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),t.length===0)return[];try{let n=await wn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&fn())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 kn(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 An(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-D1esvePN.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Dn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-D1esvePN.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-BDwasfWP.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=k.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=>k.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=kn(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,watch:!0}).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 jn(e){let t=j(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=j(t,i);if(E(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function Mn(e){let t=e.spawnFn??Pe,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 Nn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
1292
+ `),process.exit(1));let a=await l(process.cwd()),o=p(a),s=n.modulesDir??o.dir??`src/modules`,c=cn(t),f=u(a,process.cwd()),m=d(E()),h=await ln({name:e,fields:c,modulesDir:P(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:f,swagger:m,style:o.style});console.log(`\n Scaffolded ${e} with ${c.length} field(s):`);for(let e of c)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);q(h,i),await _n(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=K(t);v(n),q(await qt({outDir:P(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | 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 | fullstack`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=K(t);v(n);let r=e.only??`all`;if(!gn.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${gn.join(` | `)}`),process.exitCode=1;return}q(await re({outDir:P(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])wn(n,e,t?.projectRoot)}function wn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=K(o);v(s);let c=await it({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&q(c.files,s)})}const Tn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function En(e){let t=A.resolve(e.cwd,`.kickjs/types`);e.check||await Le(t,{recursive:!0});let n=new Map,r=e.scan??fe,i=A.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(F(e).href)},async writeFile(t,n){let r=A.resolve(e.cwd,t);await Le(A.dirname(r),{recursive:!0}),await L(r,n,`utf8`)},getScanResult:e=>{let t=Dn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?se(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=A.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=`${Tn}${n.id} */\n\n`+a+`
1293
+ `,u=``;if(D(i)&&(u=await I(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 L(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new hn(c);return s}function Dn(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 On(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 kn=e({applyDisableFilter:()=>On,runAllPluginTypegens:()=>An});async function An(e){let{enabled:t,skipped:n,unknown:r}=On(g([...Fa,...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 En({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&mn())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof hn||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 jn(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 Mn(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-B6vIx4Qd.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>kn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-B6vIx4Qd.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-clh7HpZV.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=A.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=>A.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=jn(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,watch:!0}).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 Nn(e){let t=M(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=M(t,i);if(D(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function Pn(e){let t=e.spawnFn??Pe,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 Fn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
1277
1294
  `):`${n.slice(0,t).join(`
1278
- `)}\n… ${n.length-t} more line(s)`}function Pn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Fn(e,t=`127.0.0.1`){let n=await import(`node:inspector`);n.open(e,t,!1);let r=n.url();if(!r)throw Error(`inspector.open() reported no URL`);return r}async function In(e,t,n={}){t&&(process.env.PORT=t);let r=Pn(n.polling),i=process.cwd(),a=await l(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await xe({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}let c=N(i,a?.typegen?.outDir??`.kickjs/types`);try{await me(c,await On({cwd:i,config:a}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:u}=await import(`node:module`),{createServer:d}=await import(P(u(N(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let f=await d({configFile:N(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??a?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=jn(i);e?m=Mn({cwd:i,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(Nn(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=An({cwd:i,config:a,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(`
1295
+ `)}\n… ${n.length-t} more line(s)`}function In(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Ln(e,t=`127.0.0.1`){let n=await import(`node:inspector`);n.open(e,t,!1);let r=n.url();if(!r)throw Error(`inspector.open() reported no URL`);return r}async function Rn(e,t,n={}){t&&(process.env.PORT=t);let r=In(n.polling),i=process.cwd(),a=await l(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await xe({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}let c=P(i,a?.typegen?.outDir??`.kickjs/types`);try{await me(c,await An({cwd:i,config:a}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:u}=await import(`node:module`),{createServer:d}=await import(F(u(P(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let f=await d({configFile:P(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??a?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=Nn(i);e?m=Pn({cwd:i,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(Fn(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=Mn({cwd:i,config:a,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(`
1279
1296
  KickJS dev server running (Vite + @forinda/kickjs-vite)
1280
- `),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)}async function Ln(e){let t=await l(e);try{await xe({cwd:e,allowDuplicates:!0,schemaValidator:t?.typegen?.schemaValidator??`zod`,envFile:t?.typegen?.envFile,srcDir:t?.typegen?.srcDir,outDir:t?.typegen?.outDir,assetMap:t?.assetMap,runPlugins:!1}),await me(N(e,t?.typegen?.outDir??`.kickjs/types`),await On({cwd:e,config:t}),!1)}catch(e){console.warn(` kick typegen: skipped before typecheck (${e?.message??e}).\n Generated types may be stale — errors inside .kickjs/types are likely from that.`)}}function Rn(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 In(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
1297
+ `),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)}async function zn(e){let t=await l(e);try{await xe({cwd:e,allowDuplicates:!0,schemaValidator:t?.typegen?.schemaValidator??`zod`,envFile:t?.typegen?.envFile,srcDir:t?.typegen?.srcDir,outDir:t?.typegen?.outDir,assetMap:t?.assetMap,runPlugins:!1}),await me(P(e,t?.typegen?.outDir??`.kickjs/types`),await An({cwd:e,config:t}),!1)}catch(e){console.warn(` kick typegen: skipped before typecheck (${e?.message??e}).\n Generated types may be stale — errors inside .kickjs/types are likely from that.`)}}function Bn(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 Rn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
1281
1298
  Error: vite is not installed.
1282
1299
  Run: pnpm add -D vite unplugin-swc
1283
1300
  `):console.error(`
1284
1301
  Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
1285
1302
  Building for production...
1286
- `);let{createRequire:e}=await import(`node:module`),{build:t}=await import(P(e(N(`package.json`)).resolve(`vite`)).href);await t({configFile:N(`vite.config.ts`)});let n=await l(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
1287
- Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?j(`dist`,e):e.dest??j(`dist`,t),r=N(t),i=N(n);if(!E(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}Ee(i,{recursive:!0}),Te(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
1303
+ `);let{createRequire:e}=await import(`node:module`),{build:t}=await import(F(e(P(`package.json`)).resolve(`vite`)).href);await t({configFile:P(`vite.config.ts`)});let n=await l(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
1304
+ Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?M(`dist`,e):e.dest??M(`dist`,t),r=P(t),i=P(n);if(!D(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}Ee(i,{recursive:!0}),Te(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
1288
1305
  Building asset map...`);try{await Ce(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
1289
1306
  Build complete.
1290
1307
  `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await l(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
1291
1308
  Building asset map...`);try{await Ce(e,{cwd:process.cwd()}),console.log(`
1292
1309
  Asset build complete.
1293
- `)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),c(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=N(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await Ln(t);let n=jn(t);if(!n){console.error(`
1310
+ `)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),c(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=P(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await zn(t);let n=Nn(t);if(!n){console.error(`
1294
1311
  No type-checker found. Install one in this project:
1295
1312
  pnpm add -D typescript (tsc)
1296
1313
  pnpm add -D @typescript/native-preview (tsgo, faster)
1297
- `),process.exit(1);return}let r=Fe(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),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`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await Fn(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await In(e.entry,e.port)}catch(e){console.error(`
1298
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function zn(){try{let e=A(Me(import.meta.url));return JSON.parse(D(j(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Bn=new Set(Object.values(a).filter(e=>e.deprecated).map(e=>e.pkg));function Vn(e){let t=j(e,`package.json`);if(!E(t))return[];let n;try{n=JSON.parse(D(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=j(e,`node_modules`,...t.split(`/`),`package.json`);if(E(i))try{n=JSON.parse(D(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Bn.has(t)}})}function Hn(e){let t=e;for(;;){if(E(j(t,`package.json`)))return t;let e=A(t);if(e===t)return null;t=e}}function Un(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${zn()}`,``,` System:`,` OS: ${Ue()} ${We()} (${He()})`,` Node: ${process.version}`],t=Hn(process.cwd()),n=t?Vn(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(`
1299
- `))})}const{bold:q,dim:J,green:Wn,red:Gn,yellow:Kn,blue:qn}=S;function Jn(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 Yn(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 Yn(`${e}${t}`)}catch{return null}}async function Xn(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 Zn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=J(`─`.repeat(60));if(console.log(),console.log(q(` KickJS Inspector`)+J(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Wn(`● healthy`):Gn(`● `+n.status);console.log(` ${q(`Health:`)} ${e}`)}else console.log(` ${q(`Health:`)} ${Gn(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Gn:r.errorRate>0?Kn:Wn;console.log(` ${q(`Uptime:`)} ${Jn(r.uptimeSeconds)}`),console.log(` ${q(`Requests:`)} ${r.requests}`),console.log(` ${q(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${J(`(`)}${t(e+`%`)}${J(`)`)}`)}if(a&&console.log(` ${q(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${q(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(q(` Routes`)),console.log(s),console.log(` ${J(`METHOD`)} ${J(`PATH`.padEnd(36))} ${J(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${ee(e.method)} ${t} ${qn(e.controller)}.${J(e.handler)}`)}}console.log(s),console.log()}function Qn(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 Xn(r);t.json?console.log(JSON.stringify(e,null,2)):Zn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Gn(` ✖ Could not connect to ${n}`)),console.error(J(` ${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 $n(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 er=[{match(e,t){let n=$n(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:X(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
1314
+ `),process.exit(1);return}let r=Fe(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),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`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await Ln(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await Rn(e.entry,e.port)}catch(e){console.error(`
1315
+ Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Vn(){try{let e=j(Me(import.meta.url));return JSON.parse(O(M(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Hn=new Set(Object.values(a).filter(e=>e.deprecated).map(e=>e.pkg));function Un(e){let t=M(e,`package.json`);if(!D(t))return[];let n;try{n=JSON.parse(O(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=M(e,`node_modules`,...t.split(`/`),`package.json`);if(D(i))try{n=JSON.parse(O(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Hn.has(t)}})}function Wn(e){let t=e;for(;;){if(D(M(t,`package.json`)))return t;let e=j(t);if(e===t)return null;t=e}}function Gn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Vn()}`,``,` System:`,` OS: ${Ue()} ${We()} (${He()})`,` Node: ${process.version}`],t=Wn(process.cwd()),n=t?Un(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(`
1316
+ `))})}const{bold:J,dim:Y,green:Kn,red:qn,yellow:Jn,blue:Yn}=C;function Xn(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 Zn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function X(e,t){try{return await Zn(`${e}${t}`)}catch{return null}}async function Qn(e){let[t,n,r,i,a]=await Promise.all([X(e,`/health`),X(e,`/metrics`),X(e,`/routes`),X(e,`/container`),X(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function $n(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=Y(`─`.repeat(60));if(console.log(),console.log(J(` KickJS Inspector`)+Y(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Kn(`● healthy`):qn(`● `+n.status);console.log(` ${J(`Health:`)} ${e}`)}else console.log(` ${J(`Health:`)} ${qn(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?qn:r.errorRate>0?Jn:Kn;console.log(` ${J(`Uptime:`)} ${Xn(r.uptimeSeconds)}`),console.log(` ${J(`Requests:`)} ${r.requests}`),console.log(` ${J(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${Y(`(`)}${t(e+`%`)}${Y(`)`)}`)}if(a&&console.log(` ${J(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${J(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(J(` Routes`)),console.log(s),console.log(` ${Y(`METHOD`)} ${Y(`PATH`.padEnd(36))} ${Y(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${ee(e.method)} ${t} ${Yn(e.controller)}.${Y(e.handler)}`)}}console.log(s),console.log()}function er(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 Qn(r);t.json?console.log(JSON.stringify(e,null,2)):$n(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(qn(` ✖ Could not connect to ${n}`)),console.error(Y(` ${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 tr(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Z(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const nr=[{match(e,t){let n=tr(e,[`config`,`get`])&&Z(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Z(e,[`undefined`,`is not defined`]);return!n&&!r?null:Z(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
1300
1317
  src/config/index.ts, and src/index.ts imports it before bootstrap().
1301
1318
  Tests never load src/index.ts — \`createTestApp\` builds the app
1302
1319
  directly — so that import does not run and ConfigService falls back to
@@ -1320,7 +1337,7 @@ import { modules } from './modules'
1320
1337
  import './config' // ← add this — registers env schema
1321
1338
  import { bootstrap } from '@forinda/kickjs'
1322
1339
  import { modules } from './modules'
1323
- `,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=X(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);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.
1340
+ `,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Z(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);return Z(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
1324
1341
  When vitest re-imports your modules across tests, the same class can be
1325
1342
  registered twice and the container throws. The fix is to wipe the
1326
1343
  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'
@@ -1330,7 +1347,7 @@ describe('UserController', () => {
1330
1347
  beforeEach(() => Container.reset())
1331
1348
 
1332
1349
  it('does the thing', async () => { /* ... */ })
1333
- })`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||$n(e,[`Module`,`is not a function`])||$n(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
1350
+ })`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||tr(e,[`Module`,`is not a function`])||tr(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
1334
1351
  pattern instead: a class implements AppModule and exposes routes() that
1335
1352
  returns the controller wiring. This was a deliberate choice — modules
1336
1353
  become explicit values rather than metadata, which makes them easier to
@@ -1357,7 +1374,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
1357
1374
  and matches the actual class names so refactors propagate via
1358
1375
  rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
1359
1376
  create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
1360
- 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
1377
+ create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=Z(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Z(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
1361
1378
  cluster: { workers: N }, the framework forks N workers, each of which
1362
1379
  spins up its own Vite instance on a separate port. The fix landed in
1363
1380
  v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
@@ -1365,7 +1382,7 @@ silently skips cluster, with a warning. If you see this on an older
1365
1382
  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({
1366
1383
  modules,
1367
1384
  cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
1368
- })`,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
1385
+ })`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return Z(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
1369
1386
  reflect-metadata polyfill. The polyfill must be imported once,
1370
1387
  before any decorator runs. Most projects do this at the top of
1371
1388
  src/index.ts; missing the import causes obscure "design:paramtypes"
@@ -1374,7 +1391,7 @@ import './config'
1374
1391
  import { bootstrap } from '@forinda/kickjs'
1375
1392
  import { modules } from './modules'
1376
1393
 
1377
- 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
1394
+ export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return Z(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
1378
1395
  generated a module via \`kick g module foo\` but the routes don't appear,
1379
1396
  the most likely cause is that the module is missing from the exported
1380
1397
  array. The CLI usually wires this automatically, but a hand-edit can
@@ -1382,7 +1399,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
1382
1399
  import { UserModule } from './users/user.module'
1383
1400
  import { TaskModule } from './tasks/task.module' // ← was this missing?
1384
1401
 
1385
- export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!X(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=X(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=X(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&X(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
1402
+ export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!Z(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=Z(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=Z(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&Z(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
1386
1403
  That protects the vars your test runner pinned — but every var it did NOT
1387
1404
  pin is silently backfilled from your \`.env\`. So a suite can pin its database
1388
1405
  URL and still reach live development services through the vars it forgot,
@@ -1416,24 +1433,24 @@ beforeAll(() => {
1416
1433
  vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
1417
1434
  resetEnvCache()
1418
1435
  loadEnv(envSchema)
1419
- })`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}}];function tr(e,t){let n=null;for(let r of er){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 nr(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.
1436
+ })`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}}];function rr(e,t){let n=null;for(let r of nr){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 ir(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.
1420
1437
  export OPENAI_API_KEY="sk-..."
1421
1438
 
1422
1439
  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:
1423
1440
  kick add ai
1424
1441
 
1425
1442
  Or manually:
1426
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=rr(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=ir((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 rr(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(`
1427
- `)}function ir(e){let t=[e,ar(e),or(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(sr(t))return t}catch{continue}return null}function ar(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function or(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 sr(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 cr(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 dr(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
1443
+ pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=ar(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=or((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 ar(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(`
1444
+ `)}function or(e){let t=[e,sr(e),cr(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(lr(t))return t}catch{continue}return null}function sr(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function cr(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 lr(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 ur(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 pr(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
1428
1445
 
1429
1446
  Pass a message as a positional arg, --message flag, or pipe via stdin:
1430
1447
  kick explain "config.get returned undefined"
1431
1448
  pnpm test 2>&1 | kick explain
1432
- `),process.exit(1));let r=pr(),i=tr(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
1433
- `);return}if(i){mr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
1434
- `),process.exit(2)),hr(n,!1),process.exit(2));let a=await nr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(lr(a),null,2)+`
1435
- `),process.exit(a.kind===`ok`?0:2)),ur(n,a),process.exit(a.kind===`ok`?0:2)})}function lr(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 ur(e,t){if(t.kind===`ok`){mr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${gr(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: ${gr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function dr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:fr()}function fr(){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 pr(){let e=process.cwd();return{cwd:e,hasFile:t=>E(N(e,t))}}function mr(e,t,n,r=!1){let i=gr(e.trim(),200),a=r?`AI-generated — verify before applying`:_r(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(`
1436
- `)}function hr(e,t){let n=gr(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.
1449
+ `),process.exit(1));let r=hr(),i=rr(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
1450
+ `);return}if(i){gr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
1451
+ `),process.exit(2)),_r(n,!1),process.exit(2));let a=await ir({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(dr(a),null,2)+`
1452
+ `),process.exit(a.kind===`ok`?0:2)),fr(n,a),process.exit(a.kind===`ok`?0:2)})}function dr(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 fr(e,t){if(t.kind===`ok`){gr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${yr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${vr(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${yr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function pr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:mr()}function mr(){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 hr(){let e=process.cwd();return{cwd:e,hasFile:t=>D(P(e,t))}}function gr(e,t,n,r=!1){let i=yr(e.trim(),200),a=r?`AI-generated — verify before applying`:br(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${vr(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${vr(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${vr(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${vr(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
1453
+ `)}function _r(e,t){let n=yr(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.
1437
1454
  When @forinda/kickjs-ai ships its provider implementations,
1438
1455
  this command will call the configured LLM with the error +
1439
1456
  project context and return a structured fix.
@@ -1450,12 +1467,12 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
1450
1467
  3. File an issue with the error text:
1451
1468
  https://github.com/forinda/kick-js/issues/new
1452
1469
 
1453
- `)}function Z(e,t){return e.split(`
1470
+ `)}function vr(e,t){return e.split(`
1454
1471
  `).map(e=>`${t}${e}`).join(`
1455
- `)}function gr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function _r(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function vr(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(yr),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(br)}function yr(e){let t=N(e.entry);E(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=Pe(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 br(e){let t=process.cwd(),n=xr(t)??Ae(t),r=e.name??n,i=e.global?N(process.env.HOME??`.`,`.mcp.json`):N(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(E(i))try{let e=D(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,ke(i,JSON.stringify(o,null,2)+`
1456
- `,`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 xr(e){let t=N(e,`package.json`);if(!E(t))return null;try{let e=D(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Sr(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=N(t,e.entry);E(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=wr(t,`tsx`);r||(console.error(`
1472
+ `)}function yr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function br(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function xr(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(Sr),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(Cr)}function Sr(e){let t=P(e.entry);D(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=Pe(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 Cr(e){let t=process.cwd(),n=wr(t)??Ae(t),r=e.name??n,i=e.global?P(process.env.HOME??`.`,`.mcp.json`):P(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(D(i))try{let e=O(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,ke(i,JSON.stringify(o,null,2)+`
1473
+ `,`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 wr(e){let t=P(e,`package.json`);if(!D(t))return null;try{let e=O(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Tr(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=P(t,e.entry);D(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Dr(t,`tsx`);r||(console.error(`
1457
1474
  Error: tsx not found. Install it: pnpm add -D tsx
1458
- `),process.exit(1));let i=Cr(n,e.entry),a=j(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Ne(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Cr(e,t){return`
1475
+ `),process.exit(1));let i=Er(n,e.entry),a=M(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Ne(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Er(e,t){return`
1459
1476
  import 'reflect-metadata'
1460
1477
 
1461
1478
  // Prevent bootstrap() from starting the HTTP server
@@ -1480,7 +1497,7 @@ try {
1480
1497
 
1481
1498
  // Load entry to trigger decorator registration
1482
1499
  try {
1483
- await import('${P(e).href}')
1500
+ await import('${F(e).href}')
1484
1501
  } catch (err) {
1485
1502
  console.warn(' Warning: ' + err.message)
1486
1503
  console.warn(' Container may be partially initialized.\\n')
@@ -1509,50 +1526,50 @@ server.on('exit', () => {
1509
1526
  console.log('\\n Goodbye!\\n')
1510
1527
  process.exit(0)
1511
1528
  })
1512
- `}function wr(e,t){let n=e;for(;;){let e=j(n,`node_modules`,`.bin`,t);if(E(e))return e;let r=N(n,`..`);if(r===n)break;n=r}return null}function Tr(e,t){let n=RegExp(`^\\s*${V(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]!==`
1529
+ `}function Dr(e,t){let n=e;for(;;){let e=M(n,`node_modules`,`.bin`,t);if(D(e))return e;let r=P(n,`..`);if(r===n)break;n=r}return null}function Or(e,t){let n=RegExp(`^\\s*${H(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
1513
1530
  `;)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]===`
1514
- `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Er(e,t){let n=At(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Tr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${V(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 Dr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=z(t),o=L(t),s=i?B(a):a,c=j(n,s);if(!await y(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await C({message:S.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
1531
+ `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function kr(e,t){let n=Mt(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Or(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${H(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function Ar(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=B(t),o=R(t),s=i?V(a):a,c=M(n,s);if(!await b(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await w({message:C.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
1515
1532
  Cancelled.
1516
- `);return}await ze(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=j(n,`index.ts`);if(await y(l)){let e=await F(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${V(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${V(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Er(e,o),e=e.replace(/\n{3,}/g,`
1533
+ `);return}await ze(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=M(n,`index.ts`);if(await b(l)){let e=await I(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${H(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${H(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=kr(e,o),e=e.replace(/\n{3,}/g,`
1517
1534
 
1518
- `),e!==t&&(await I(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Or(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=f(await l(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Dr({name:n,modulesDir:N(r),force:t.force,pluralize:i})})}function kr(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 Ar(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function jr(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=T(process.cwd()),n=await l(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-D5BaucQm.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>ja),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
1535
+ `),e!==t&&(await L(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function jr(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=p(await l(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Ar({name:n,modulesDir:P(r),force:t.force,pluralize:i})})}function Mr(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 Nr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Pr(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=E(process.cwd()),n=await l(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-BSNGbECd.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Pa),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(`
1519
1536
  Registered typegen plugins:
1520
1537
  `);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``,n=`${e.id.replace(/\//g,`__`)}${e.outExtension??`.d.ts`}`;console.log(` ${e.id.padEnd(a+2)}→ .kickjs/types/${n}${t}`),console.log(` ${` `.repeat(a+2)} watches: ${e.inputs.join(`, `)||`(none)`}`)}console.log(`
1521
1538
  Disable one in kick.config.ts:
1522
1539
  `),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
1523
- `);return}let r=kr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Ar(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ye(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await xe(a);let r=await On({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 me(N(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof be?console.error(`
1540
+ `);return}let r=Mr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Nr(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ye(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await xe(a);let r=await An({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 me(P(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof be?console.error(`
1524
1541
  `+e.message+`
1525
- `):e instanceof pn?console.error(`
1542
+ `):e instanceof hn?console.error(`
1526
1543
  `+e.message+`
1527
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Mr(e){let t=[];if(!E(e))return t;let n=O(e,{withFileTypes:!0});for(let r of n){let n=j(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Mr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Nr(e){try{return D(e,`utf-8`)}catch{return``}}const Pr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Fr(e,t){let n=Nr(j(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Pr.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 Ir(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 Lr(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 Rr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function zr(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 Br(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 Vr(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 Hr(e){let t=Mr(j(e,`src`)).map(e=>Nr(e)),n=[],r=Fr(e,t);r&&n.push(r);let i=Ir(t);i&&n.push(i);let a=Lr(t);a&&n.push(a);let o=Rr();o&&n.push(o);let s=zr(t);return s&&n.push(s),n.push(Br(t)),n.push(Vr(t)),n}function Ur(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
1544
+ `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Fr(e){let t=[];if(!D(e))return t;let n=k(e,{withFileTypes:!0});for(let r of n){let n=M(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Fr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Ir(e){try{return O(e,`utf-8`)}catch{return``}}const Lr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Rr(e,t){let n=Ir(M(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Lr.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 zr(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 Br(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 Vr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Hr(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 Ur(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 Wr(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 Gr(e){let t=Fr(M(e,`src`)).map(e=>Ir(e)),n=[],r=Rr(e,t);r&&n.push(r);let i=zr(t);i&&n.push(i);let a=Br(t);a&&n.push(a);let o=Vr();o&&n.push(o);let s=Hr(t);return s&&n.push(s),n.push(Ur(t)),n.push(Wr(t)),n}function Kr(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
1528
1545
  Usage: kick check --deploy
1529
1546
 
1530
1547
  Available checks:
1531
1548
  --deploy Audit for production readiness (security, config, best practices)
1532
- `);return}let t=process.cwd();te(`KickJS Deploy Check`);let n=ne();n.start(`Scanning project...`);let r=Hr(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)b.message(`${ae(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?S.red(`${a} critical`):`${a} critical`,o>0?S.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(w(S.red(`${l} — fix critical issues before deploying`)),process.exit(1)):w(S.green(`${l} — looking good!`))})}function Wr(e){try{return JSON.parse(D(e,`utf-8`))}catch{return null}}function Gr(e){try{return D(e,`utf-8`)}catch{return null}}function Kr(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function qr(e){let t=j(e,`tsconfig.json`);if(E(t))return Jr(t,new Set)}function Jr(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Gr(e);if(n===null)return null;let r=Kr(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=Yr(A(e),n);if(!r)continue;let i=Jr(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Yr(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return Xr(N(e,t));let n=e;for(;;){let e=Xr(j(n,`node_modules`,t));if(e)return e;let r=A(n);if(r===n)break;n=r}return null}function Xr(e){if(E(e)){try{if(Oe(e).isDirectory()){let t=j(e,`tsconfig.json`);return E(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return E(t)?t:null}function Zr(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.
1533
- Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function $r(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 ei(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 ti={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function ni(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=ti[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 ri(e){if(!e.pkg||!ai(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const ii=2e3;function ai(e){let t=j(e,`src`);if(!E(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<ii;){let e=r.pop(),t;try{t=O(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=ii)break;let t=j(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(Gr(t)??``)))return!0}}return!1}function oi(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.
1549
+ `);return}let t=process.cwd();te(`KickJS Deploy Check`);let n=ne();n.start(`Scanning project...`);let r=Gr(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)x.message(`${ae(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?C.red(`${a} critical`):`${a} critical`,o>0?C.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(T(C.red(`${l} — fix critical issues before deploying`)),process.exit(1)):T(C.green(`${l} — looking good!`))})}function qr(e){try{return JSON.parse(O(e,`utf-8`))}catch{return null}}function Jr(e){try{return O(e,`utf-8`)}catch{return null}}function Yr(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function Xr(e){let t=M(e,`tsconfig.json`);if(D(t))return Zr(t,new Set)}function Zr(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Jr(e);if(n===null)return null;let r=Yr(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=Qr(j(e),n);if(!r)continue;let i=Zr(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Qr(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return $r(P(e,t));let n=e;for(;;){let e=$r(M(n,`node_modules`,t));if(e)return e;let r=j(n);if(r===n)break;n=r}return null}function $r(e){if(D(e)){try{if(Oe(e).isDirectory()){let t=M(e,`tsconfig.json`);return D(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return D(t)?t:null}function ei(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ti(){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.
1550
+ Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function ni(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 ri(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 ii={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function ai(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=ii[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 oi(e){if(!e.pkg||!ci(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const si=2e3;function ci(e){let t=M(e,`src`);if(!D(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<si;){let e=r.pop(),t;try{t=k(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=si)break;let t=M(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(Jr(t)??``)))return!0}}return!1}function li(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.
1534
1551
  Install it: pnpm add reflect-metadata
1535
1552
  Then import it at the top of src/index.ts:
1536
1553
 
1537
1554
  import 'reflect-metadata'
1538
- // ... rest of bootstrap`}}function si(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 ci(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>j(e.cwd,t)).filter(e=>E(e)).filter(e=>/\bloadEnv\s*\(/.test(Gr(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>j(e.cwd,t)).find(e=>E(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=Gr(n)??``,i=A(n),a=[];for(let e of t){let t=M(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+)?['"]${Zr(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=>M(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 \`${M(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 ${M(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 li(e,t=ui){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=O(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=j(e,o.name);if(o.isDirectory()){i.push(a);continue}try{let e=Oe(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const ui=2e3;function di(e){let t=j(e.cwd,`.kickjs`,`types`);if(!E(t))return null;let n=li(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 fi=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],pi=[`.env.test`,`.env.test.local`],mi=[`.env`,`.env.local`];function hi(e){let t=e.pkg?.scripts;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(!e.startsWith(`test`)||typeof n!=`string`)continue;let t=/KICKJS_ENV_FILE=(\S+)/.exec(n);if(t?.[1])return t[1]}return process.env.KICKJS_ENV_FILE??null}function gi(e){if(!fi.some(t=>E(j(e.cwd,t))))return null;let t=mi.filter(t=>E(j(e.cwd,t)));if(t.length===0)return null;let n=pi.filter(t=>E(j(e.cwd,t)));if(n.length>0){let t=hi(e);return t&&t!==`off`&&t!==`none`?{name:`test env isolation`,status:`warn`,message:`${n.join(`, `)} present, but KICKJS_ENV_FILE=${t} overrides it`,fix:`KICKJS_ENV_FILE is checked before test-mode isolation, so ${n[0]} is\nignored and "${t}" is read instead. Drop the override to use the\ntest files, or set KICKJS_ENV_FILE=off if env comes from the runner.`}:{name:`test env isolation`,status:`pass`,message:`${n.join(`, `)} present`}}return{name:`test env isolation`,status:`warn`,message:`${t.join(`, `)} present, no .env.test`,fix:`Under NODE_ENV=test (or vitest's VITEST) KickJS reads .env.test / .env.test.local
1555
+ // ... rest of bootstrap`}}function ui(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 di(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>M(e.cwd,t)).filter(e=>D(e)).filter(e=>/\bloadEnv\s*\(/.test(Jr(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>M(e.cwd,t)).find(e=>D(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=Jr(n)??``,i=j(n),a=[];for(let e of t){let t=N(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+)?['"]${ei(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=>N(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 \`${N(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 ${N(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 fi(e,t=pi){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=k(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=M(e,o.name);if(o.isDirectory()){i.push(a);continue}try{let e=Oe(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const pi=2e3;function mi(e){let t=M(e.cwd,`.kickjs`,`types`);if(!D(t))return null;let n=fi(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 hi=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],gi=[`.env.test`,`.env.test.local`],_i=[`.env`,`.env.local`];function vi(e){let t=e.pkg?.scripts;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(!e.startsWith(`test`)||typeof n!=`string`)continue;let t=/KICKJS_ENV_FILE=(\S+)/.exec(n);if(t?.[1])return t[1]}return process.env.KICKJS_ENV_FILE??null}function yi(e){if(!hi.some(t=>D(M(e.cwd,t))))return null;let t=_i.filter(t=>D(M(e.cwd,t)));if(t.length===0)return null;let n=gi.filter(t=>D(M(e.cwd,t)));if(n.length>0){let t=vi(e);return t&&t!==`off`&&t!==`none`?{name:`test env isolation`,status:`warn`,message:`${n.join(`, `)} present, but KICKJS_ENV_FILE=${t} overrides it`,fix:`KICKJS_ENV_FILE is checked before test-mode isolation, so ${n[0]} is\nignored and "${t}" is read instead. Drop the override to use the\ntest files, or set KICKJS_ENV_FILE=off if env comes from the runner.`}:{name:`test env isolation`,status:`pass`,message:`${n.join(`, `)} present`}}return{name:`test env isolation`,status:`warn`,message:`${t.join(`, `)} present, no .env.test`,fix:`Under NODE_ENV=test (or vitest's VITEST) KickJS reads .env.test / .env.test.local
1539
1556
  INSTEAD of ${t.join(` and `)} — no layering, no fallback. Without one of\nthose files, every var your test config does not pin resolves from your
1540
1557
  development env — including DATABASE_URL and any third-party credentials.
1541
1558
 
1542
1559
  Create .env.test holding the whole environment the suite should run against
1543
1560
  (a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
1544
- and supply env from the test runner.`}}const _i=[()=>Qr(),$r,ei,ni,ri,oi,si,ci,gi,di];async function vi(e,t={}){let n={cwd:e,pkg:Wr(j(e,`package.json`)),tsconfig:qr(e),runtime:t.runtime??`express`},r=[..._i,...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 yi(e){switch(e){case`pass`:return S.green(`✔`);case`warn`:return S.yellow(`⚠`);case`fail`:return S.red(`✖`)}}function bi(e){let t=yi(e.status),n=e.message?` ${S.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function xi(e){return e.split(`
1545
- `).map(e=>` ${S.dim(`→`)} ${e}`).join(`
1546
- `)}function Si(e){return e?.doctor?.checks??[]}function Ci(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=Si(await l(e)),n=await o(e);te(`KickJS Doctor`);let r=await vi(e,{extraChecks:t,runtime:n});for(let e of r)b.message(bi(e)),e.fix&&e.status!==`pass`&&b.message(xi(e.fix));let i=r.filter(e=>e.status===`pass`).length,a=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[S.green(`${i} passed`),a>0?S.yellow(`${a} warning${a===1?``:`s`}`):`${a} warnings`,s>0?S.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(w(`${c} — fix the errors above before running the app`),process.exit(1)):w(a>0?`${c} — review the warnings`:S.green(`${c} — your environment looks good`))})}function wi(e){return e.optsWithGlobals().dryRun??!1}function Ti(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.
1561
+ and supply env from the test runner.`}}const bi=[()=>ti(),ni,ri,ai,oi,li,ui,di,yi,mi];async function xi(e,t={}){let n={cwd:e,pkg:qr(M(e,`package.json`)),tsconfig:Xr(e),runtime:t.runtime??`express`},r=[...bi,...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 Si(e){switch(e){case`pass`:return C.green(`✔`);case`warn`:return C.yellow(`⚠`);case`fail`:return C.red(`✖`)}}function Ci(e){let t=Si(e.status),n=e.message?` ${C.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function wi(e){return e.split(`
1562
+ `).map(e=>` ${C.dim(`→`)} ${e}`).join(`
1563
+ `)}function Ti(e){return e?.doctor?.checks??[]}function Ei(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=Ti(await l(e)),n=await o(e);te(`KickJS Doctor`);let r=await xi(e,{extraChecks:t,runtime:n});for(let e of r)x.message(Ci(e)),e.fix&&e.status!==`pass`&&x.message(wi(e.fix));let i=r.filter(e=>e.status===`pass`).length,a=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[C.green(`${i} passed`),a>0?C.yellow(`${a} warning${a===1?``:`s`}`):`${a} warnings`,s>0?C.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(T(`${c} — fix the errors above before running the app`),process.exit(1)):T(a>0?`${c} — review the warnings`:C.green(`${c} — your environment looks good`))})}function Di(e){return e.optsWithGlobals().dryRun??!1}function Oi(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.
1547
1564
  Direction defaults to \`modules.style\` from kick.config (or "define").
1548
1565
  --target define|class Override the migration direction.
1549
1566
  --apply Apply the changes (default: dry-run preview).
1550
- --experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=wi(t)||!e.apply;_(n),e.experimental||(console.error(`
1551
- `+S.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
1567
+ --experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=Di(t)||!e.apply;v(n),e.experimental||(console.error(`
1568
+ `+C.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
1552
1569
  The regex-based rewrite handles the shapes our templates produce.
1553
1570
  Hand-rolled modules with non-standard structures may be skipped.
1554
1571
  Always commit before running with --apply.
1555
- `),process.exit(1));let r=f(await l(process.cwd())),i=N(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${S.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=S.dim(`→ ${a}`),s=n?S.dim(`(dry-run)`):S.bold(`(applying)`);console.log(`\n ${S.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${S.dim(i)}\n`);let c=e.backup!==!1&&!n,u=await nn(i,{dryRun:n,target:a,backup:c});if(u.backupDir){let e=u.backupDir;console.log(` ${S.green(`✓`)} backup: ${S.dim(e)}\n ${S.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${S.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,p=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${S.green(`✓`)} ${e.path}`);else{p++;let t=S.dim(`(${e.reason??`skipped`})`);console.log(` ${S.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${S.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=S.dim(`(${u.indexReason??`skipped`})`);console.log(` ${S.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${S.dim(`-`)} ${u.indexPath} ${S.dim(`(not found)`)}`);let m=n?S.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${S.bold(String(d))} migrated, ${S.bold(String(p))} skipped${m}\n`)})}const Ei=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!E(k.resolve(e.cwd,`kick.config.ts`)))return null;let t=await l(e.cwd);if(!t?.assetMap)return null;let n=ce(t.assetMap,e.cwd);return n.count===0?null:_e(n)}}),Di="/* 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 Oi(e,t,n,r={}){if(e.length===0)return`${Di}
1572
+ `),process.exit(1));let r=p(await l(process.cwd())),i=P(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${C.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=C.dim(`→ ${a}`),s=n?C.dim(`(dry-run)`):C.bold(`(applying)`);console.log(`\n ${C.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${C.dim(i)}\n`);let c=e.backup!==!1&&!n,u=await an(i,{dryRun:n,target:a,backup:c});if(u.backupDir){let e=u.backupDir;console.log(` ${C.green(`✓`)} backup: ${C.dim(e)}\n ${C.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${C.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${C.green(`✓`)} ${e.path}`);else{f++;let t=C.dim(`(${e.reason??`skipped`})`);console.log(` ${C.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${C.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=C.dim(`(${u.indexReason??`skipped`})`);console.log(` ${C.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${C.dim(`-`)} ${u.indexPath} ${C.dim(`(not found)`)}`);let m=n?C.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${C.bold(String(d))} migrated, ${C.bold(String(f))} skipped${m}\n`)})}const ki=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!D(A.resolve(e.cwd,`kick.config.ts`)))return null;let t=await l(e.cwd);if(!t?.assetMap)return null;let n=ce(t.assetMap,e.cwd);return n.count===0?null:_e(n)}}),Ai="/* 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 ji(e,t,n,r={}){if(e.length===0)return`${Ai}
1556
1573
  // (no routes discovered yet — annotate a controller method with
1557
1574
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
1558
1575
  declare global {
@@ -1569,14 +1586,14 @@ declare global {
1569
1586
 
1570
1587
  /** Empty until the first route exists — see kick typegen. */
1571
1588
  export const kickRpc = {} as const
1572
- `;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=Mi(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??Ai(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=ji(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${ki(e)}`,` }`)}n.push(` }`),l.push(n.join(`
1589
+ `;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=Fi(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??Ni(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=Pi(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${Mi(e)}`,` }`)}n.push(` }`),l.push(n.join(`
1573
1590
  `))}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(`
1574
- `);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=Fi(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(`
1591
+ `);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=Ri(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(`
1575
1592
  `)}\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(`
1576
- `),_=[],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=Pi(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
1593
+ `),_=[],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=Li(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
1577
1594
  `)+`
1578
- `:``,b=Ni(a)+y,x=l.join(`
1579
- `);return`${Di}${b}
1595
+ `:``,b=Ii(a)+y,x=l.join(`
1596
+ `);return`${Ai}${b}
1580
1597
  declare global {
1581
1598
  // eslint-disable-next-line @typescript-eslint/no-namespace
1582
1599
  namespace KickRoutes {
@@ -1588,18 +1605,18 @@ ${x}
1588
1605
  }
1589
1606
 
1590
1607
  ${g}
1591
- `}function ki(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Ai(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 ji(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 Mi(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Pi(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 Ni(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(`
1608
+ `}function Mi(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Ni(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 Pi(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 Fi(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Li(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 Ii(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(`
1592
1609
  `)+`
1593
- `}function Pi(e,t,n){if(e===null)return`unknown`;let r=A(n);if(e===``){let e=M(r,t).split(je).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=M(r,N(A(t),e)).split(je).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function Fi(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 Ii=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Li(e),cwd:e.cwd,envFile:Ri(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=k.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Oi(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Li(e){return k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ri(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const zi=`@typescript/typescript6`;function Bi(e){return typeof e?.createProgram==`function`}function Vi(e){if(Bi(e.typescript))return{api:e.typescript,source:`typescript`};if(Bi(e.ts6))return{api:e.ts6,source:zi};let t=`Install it in the project:\n pnpm add -D ${zi}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
1594
- TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${zi}' resolved from this project.\n ${t}`)}async function Hi(e){let t=we(j(e,`package.json`)),n=async e=>{try{return await import(P(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(zi)]);return Vi({typescript:Ui(r),ts6:Ui(i)}).api}function Ui(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Wi=Symbol(`kick/client: expansion budget exhausted`);var Gi=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=new Map;inProgress=new Map;jsonInProgress=new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;try{return this.render(e,0)}catch(e){if(e!==Wi)throw e;return this.opts.onWarn?.(`expansion abandoned after ${this.budget} truncations — emitting 'unknown'. This usually means a recursive type. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth){if(++this.truncations>this.budget)throw Wi;return this.opts.onWarn?.(`type nesting exceeded ${this.maxDepth} levels — emitting 'unknown'. Declare a response schema on the route for an exact type.`),`unknown`}if(e.flags&(n.String|n.Number|n.Boolean|n.BigInt|n.ESSymbol)||e.flags&(n.Any|n.Unknown|n.Never|n.Void|n.Undefined|n.Null)||e.isLiteral()||e.flags&n.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let r=this.arrayElement(e);if(r){let e=this.render(r.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return r.readonly?`readonly ${n}`:n}let i=this.toJsonType(e);if(i){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(i,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&n.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
1610
+ `}function Li(e,t,n){if(e===null)return`unknown`;let r=j(n);if(e===``){let e=N(r,t).split(je).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=N(r,P(j(t),e)).split(je).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function Ri(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 zi=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Bi(e),cwd:e.cwd,envFile:Vi(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=A.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return ji(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Bi(e){return A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Vi(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Hi=`@typescript/typescript6`;function Ui(e){return typeof e?.createProgram==`function`}function Wi(e){if(Ui(e.typescript))return{api:e.typescript,source:`typescript`};if(Ui(e.ts6))return{api:e.ts6,source:Hi};let t=`Install it in the project:\n pnpm add -D ${Hi}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
1611
+ TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${Hi}' resolved from this project.\n ${t}`)}async function Gi(e){let t=we(M(e,`package.json`)),n=async e=>{try{return await import(F(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Hi)]);return Wi({typescript:Ki(r),ts6:Ki(i)}).api}function Ki(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const qi=Symbol(`kick/client: expansion budget exhausted`);var Ji=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=new Map;inProgress=new Map;jsonInProgress=new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;try{return this.render(e,0)}catch(e){if(e!==qi)throw e;return this.opts.onWarn?.(`expansion abandoned after ${this.budget} truncations — emitting 'unknown'. This usually means a recursive type. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth){if(++this.truncations>this.budget)throw qi;return this.opts.onWarn?.(`type nesting exceeded ${this.maxDepth} levels — emitting 'unknown'. Declare a response schema on the route for an exact type.`),`unknown`}if(e.flags&(n.String|n.Number|n.Boolean|n.BigInt|n.ESSymbol)||e.flags&(n.Any|n.Unknown|n.Never|n.Void|n.Undefined|n.Null)||e.isLiteral()||e.flags&n.BooleanLiteral)return this.checker.typeToString(e,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let r=this.arrayElement(e);if(r){let e=this.render(r.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return r.readonly?`readonly ${n}`:n}let i=this.toJsonType(e);if(i){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(i,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&n.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
1595
1612
  `){let i=[];for(let r of this.checker.getIndexInfosOfType(e)){let e=this.checker.typeToString(r.keyType,void 0,this.printFlags);i.push(`${n}[key: ${e}]: ${this.render(r.type,t+1)}`)}for(let r of this.checker.getPropertiesOfType(e)){let e=this.typeOfProperty(r);if(this.isCallable(e)||r.getName().startsWith(`__@`))continue;let a=(r.flags&this.ts.SymbolFlags.Optional)!==0,o=this.renderPropertyType(e,a,r,t+1),s=this.isReadonlyProp(r)?`readonly `:``;i.push(`${n}${s}${this.propName(r.getName())}${a?`?`:``}: ${o}`)}return i.join(r===`
1596
1613
  `?`
1597
- `:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const Ki=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],qi=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Ji(e){return Ge(`sha1`).update(e).digest(`hex`)}function Yi(e){let t=Ge(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
1598
- `));for(let n of Ki){let r=j(e.projectDir,n);if(E(r))try{t.update(D(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!qi.test(n)){t.update(n);try{t.update(D(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Xi(e){try{let t=await Hi(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(j(e.projectDir,`tsconfig.json`),{},n);return r?Yi({projectDir:e.projectDir,fileNames:r.fileNames,keys:e.keys,options:{...r.options,__kickMaxDepth:e.maxDepth??null},cliVersion:e.cliVersion}):null}catch{return null}}async function Zi(e){let t=await Hi(e.compilerFrom??e.projectDir),n=j(A(e.routesFile),`__kick_client_probe__.ts`),r=ea(e.routesFile,e.keys),i=ra(t,e.projectDir,n,r),a=i.getTypeChecker(),o=i.getSourceFile(n);if(!o)throw Error(`kick/client: could not add the resolution probe to the program. Check that ${e.routesFile} exists — run \`kick typegen\` first.`);Qi(t,i,e.routesFile);let s=ta(t,i,o,e.keys),c=null,l=new Gi(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===$i(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);if(d.flags&t.TypeFlags.Any){e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`);continue}c=r,u.set(r,l.expand(d)),c=null}return{entries:u,hoisted:l.hoisted()}}function Qi(e,t,n){let r=t.getSourceFile(n);if(!r)throw Error(`kick/client: ${n} is not in the TypeScript program. Run \`kick typegen\` first, and check that tsconfig.json includes .kickjs.`);let i=t.getSemanticDiagnostics(r);if(i.length===0)return;let a=i.slice(0,3).map(t=>` ${e.flattenDiagnosticMessageText(t.messageText,` `)}`).join(`
1599
- `);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function $i(e){return`_K${e}`}function ea(e,t){let n=`./`+Ae(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${$i(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
1614
+ `:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const Yi=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Xi=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Zi(e){return Ge(`sha1`).update(e).digest(`hex`)}function Qi(e){let t=Ge(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
1615
+ `));for(let n of Yi){let r=M(e.projectDir,n);if(D(r))try{t.update(O(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Xi.test(n)){t.update(n);try{t.update(O(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function $i(e){try{let t=await Gi(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(M(e.projectDir,`tsconfig.json`),{},n);return r?Qi({projectDir:e.projectDir,fileNames:r.fileNames,keys:e.keys,options:{...r.options,__kickMaxDepth:e.maxDepth??null},cliVersion:e.cliVersion}):null}catch{return null}}async function ea(e){let t=await Gi(e.compilerFrom??e.projectDir),n=M(j(e.routesFile),`__kick_client_probe__.ts`),r=ra(e.routesFile,e.keys),i=oa(t,e.projectDir,n,r),a=i.getTypeChecker(),o=i.getSourceFile(n);if(!o)throw Error(`kick/client: could not add the resolution probe to the program. Check that ${e.routesFile} exists — run \`kick typegen\` first.`);ta(t,i,e.routesFile);let s=ia(t,i,o,e.keys),c=null,l=new Ji(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===na(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);if(d.flags&t.TypeFlags.Any){e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`);continue}c=r,u.set(r,l.expand(d)),c=null}return{entries:u,hoisted:l.hoisted()}}function ta(e,t,n){let r=t.getSourceFile(n);if(!r)throw Error(`kick/client: ${n} is not in the TypeScript program. Run \`kick typegen\` first, and check that tsconfig.json includes .kickjs.`);let i=t.getSemanticDiagnostics(r);if(i.length===0)return;let a=i.slice(0,3).map(t=>` ${e.flattenDiagnosticMessageText(t.messageText,` `)}`).join(`
1616
+ `);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function na(e){return`_K${e}`}function ra(e,t){let n=`./`+Ae(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${na(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
1600
1617
  `)+`
1601
- `}function ta(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get($i(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function na(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=O(t).filter(e=>e.endsWith(`.ts`)).map(e=>j(t,e))}catch{}return[...new Set([...n,...r])]}function ra(e,t,n,r){let i=j(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
1602
- `))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...na(o.fileNames,A(n)),n],options:o.options,host:s})}const ia=`/* eslint-disable */
1618
+ `}function ia(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(na(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function aa(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=k(t).filter(e=>e.endsWith(`.ts`)).map(e=>M(t,e))}catch{}return[...new Set([...n,...r])]}function oa(e,t,n,r){let i=M(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
1619
+ `))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...aa(o.fileNames,j(n)),n],options:o.options,host:s})}const sa=`/* eslint-disable */
1603
1620
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
1604
1621
  //
1605
1622
  // Self-contained: this file has no imports, so a frontend consumes it without
@@ -1613,7 +1630,7 @@ ${g}
1613
1630
  //
1614
1631
  // Not refreshed by \`kick dev\` — resolving these types builds a full
1615
1632
  // TypeScript program over the server. Re-run \`kick typegen\`.
1616
- `;function aa(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${ia}
1633
+ `;function ca(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${sa}
1617
1634
  // (no routes discovered yet — annotate a controller method with
1618
1635
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
1619
1636
  interface Api {}
@@ -1630,7 +1647,7 @@ export type { Api }
1630
1647
 
1631
1648
  `)+`
1632
1649
 
1633
- `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${ia}
1650
+ `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${sa}
1634
1651
  ${r}interface Api {
1635
1652
  ${i.join(`
1636
1653
  `)}
@@ -1644,7 +1661,7 @@ declare global {
1644
1661
  }
1645
1662
 
1646
1663
  export type { Api }
1647
- `}const oa=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,sa=`.kickjs/cache/client-map.sha1`,ca=(()=>{try{return we(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function la(e){try{if(!E(e))return null;let[t,n]=D(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function ua(e){return`${Cn}${oa} */\n\n${e}\n`}function da(e){try{return E(e)?D(e,`utf-8`):null}catch{return null}}async function fa(e){let t=k.resolve(e.cwd,Q);if(!E(t))return!1;try{await ze(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${Q} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${Q} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function pa(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function ma(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(E(k.resolve(e.cwd,Q))&&e.log.warn(` kick/client: ${Q} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const ha=()=>({id:oa,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!ma(e))return null;if(e.watch)return e.log.info?.(" kick/client: skipped under watch (builds a full TypeScript program). Run `kick typegen` to refresh the client route map."),null;let t=await e.getScanResult({root:k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=pa(e.config),a=await Xi({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:ca}),o=la(k.resolve(e.cwd,sa)),s=da(k.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Ji(s))return fn()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=aa(await Zi({projectDir:e.cwd,routesFile:k.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,maxDepth:i,onWarn:t=>e.log.warn(t)}),n);return a&&!e.check&&await e.writeFile(sa,`${a} ${Ji(ua(t))}`),t}catch(t){let n=E(k.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):fn()&&e.log.info?.(r),n&&await fa(e),null}}});function ga(e,t,n=`zod`){if(!e)return null;let r=M(A(t),e.filePath).split(je).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
1664
+ `}const la=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,ua=`.kickjs/cache/client-map.sha1`,da=(()=>{try{return we(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function fa(e){try{if(!D(e))return null;let[t,n]=O(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function pa(e){return`${Tn}${la} */\n\n${e}\n`}function ma(e){try{return D(e)?O(e,`utf-8`):null}catch{return null}}async function ha(e){let t=A.resolve(e.cwd,Q);if(!D(t))return!1;try{await ze(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${Q} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${Q} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function ga(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function _a(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(D(A.resolve(e.cwd,Q))&&e.log.warn(` kick/client: ${Q} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const va=()=>({id:la,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!_a(e))return null;if(e.watch)return e.log.info?.(" kick/client: skipped under watch (builds a full TypeScript program). Run `kick typegen` to refresh the client route map."),null;let t=await e.getScanResult({root:A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}let i=ga(e.config),a=await $i({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:da}),o=fa(A.resolve(e.cwd,ua)),s=ma(A.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Zi(s))return mn()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=ca(await ea({projectDir:e.cwd,routesFile:A.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,maxDepth:i,onWarn:t=>e.log.warn(t)}),n);return a&&!e.check&&await e.writeFile(ua,`${a} ${Zi(pa(t))}`),t}catch(t){let n=D(A.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):mn()&&e.log.info?.(r),n&&await ha(e),null}}});function ya(e,t,n=`zod`){if(!e)return null;let r=N(j(t),e.filePath).split(je).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
1648
1665
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
1649
1666
  // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
1650
1667
 
@@ -1682,5 +1699,5 @@ declare global {
1682
1699
  }
1683
1700
 
1684
1701
  export {}
1685
- `}const _a=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=ya(e);if(t===!1)return null;let n=await e.getScanResult({root:va(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=k.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return ga(n.env,i,r)}});function va(e){return k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ya(e){return e.config?.typegen?.envFile}function ba(e){return k.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function xa(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:ba(e),cwd:e.cwd,envFile:xa(e)}}const Sa=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=k.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return ve(t.classes,n,r)}}),Ca=()=>({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 pe(`ServiceToken`,he(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),wa=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return pe(`ModuleToken`,le((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Ta=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return de((await e.getScanResult($(e))).pluginsAndAdapters)}}),Ea=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return Se((await e.getScanResult($(e))).augmentations)}}),Da=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:ue(t.contextKeys)}}),Oa=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){return ge((await e.getScanResult($(e))).routeFlags)}}),ka={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Aa=()=>({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}=ka[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(`
1686
- `)}});var ja=e({builtinCliPlugins:()=>Ma});const Ma=[g({name:`kick/init`,register:qe}),g({name:`kick/generate`,register:xn}),g({name:`kick/run`,register:Rn}),g({name:`kick/info`,register:Un}),g({name:`kick/inspect`,register:Qn}),g({name:`kick/add`,register:t}),g({name:`kick/list`,register:i}),g({name:`kick/explain`,register:cr}),g({name:`kick/mcp`,register:vr}),g({name:`kick/tinker`,register:Sr}),g({name:`kick/remove`,register:Or}),g({name:`kick/typegen`,register:jr}),g({name:`kick/check`,register:Ur}),g({name:`kick/doctor`,register:Ci}),g({name:`kick/codemod`,register:Ti}),g({name:`kick/registry`,typegens:[Sa()]}),g({name:`kick/services`,typegens:[Ca()]}),g({name:`kick/modules`,typegens:[wa()]}),g({name:`kick/plugins`,typegens:[Ta()]}),g({name:`kick/augmentations`,typegens:[Ea()]}),g({name:`kick/context`,typegens:[Da()]}),g({name:`kick/route-flags`,typegens:[Oa()]}),g({name:`kick/assets`,typegens:[Ei()]}),g({name:`kick/routes`,typegens:[Ii()]}),g({name:`kick/client`,typegens:[ha()]}),g({name:`kick/env`,typegens:[_a()]}),g({name:`kick/runtime`,typegens:[Aa()]})];export{Dn as n,Ma as t};
1702
+ `}const ba=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Sa(e);if(t===!1)return null;let n=await e.getScanResult({root:xa(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=A.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return ya(n.env,i,r)}});function xa(e){return A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Sa(e){return e.config?.typegen?.envFile}function Ca(e){return A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function wa(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ca(e),cwd:e.cwd,envFile:wa(e)}}const Ta=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=A.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return ve(t.classes,n,r)}}),Ea=()=>({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 pe(`ServiceToken`,he(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Da=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return pe(`ModuleToken`,le((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Oa=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return de((await e.getScanResult($(e))).pluginsAndAdapters)}}),ka=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return Se((await e.getScanResult($(e))).augmentations)}}),Aa=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:ue(t.contextKeys)}}),ja=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){return ge((await e.getScanResult($(e))).routeFlags)}}),Ma={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Na=()=>({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}=Ma[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(`
1703
+ `)}});var Pa=e({builtinCliPlugins:()=>Fa});const Fa=[_({name:`kick/init`,register:qe}),_({name:`kick/generate`,register:Cn}),_({name:`kick/run`,register:Bn}),_({name:`kick/info`,register:Gn}),_({name:`kick/inspect`,register:er}),_({name:`kick/add`,register:t}),_({name:`kick/list`,register:i}),_({name:`kick/explain`,register:ur}),_({name:`kick/mcp`,register:xr}),_({name:`kick/tinker`,register:Tr}),_({name:`kick/remove`,register:jr}),_({name:`kick/typegen`,register:Pr}),_({name:`kick/check`,register:Kr}),_({name:`kick/doctor`,register:Ei}),_({name:`kick/codemod`,register:Oi}),_({name:`kick/registry`,typegens:[Ta()]}),_({name:`kick/services`,typegens:[Ea()]}),_({name:`kick/modules`,typegens:[Da()]}),_({name:`kick/plugins`,typegens:[Oa()]}),_({name:`kick/augmentations`,typegens:[ka()]}),_({name:`kick/context`,typegens:[Aa()]}),_({name:`kick/route-flags`,typegens:[ja()]}),_({name:`kick/assets`,typegens:[ki()]}),_({name:`kick/routes`,typegens:[zi()]}),_({name:`kick/client`,typegens:[va()]}),_({name:`kick/env`,typegens:[ba()]}),_({name:`kick/runtime`,typegens:[Na()]})];export{kn as n,Fa as t};