@forinda/kickjs-cli 8.13.0 → 8.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{agent-docs-D0qgHBA8.mjs → agent-docs-BBIVix8s.mjs} +2 -2
  2. package/dist/{agent-docs-DD0hT2pE.mjs → agent-docs-DR1PRHV4.mjs} +3 -3
  3. package/dist/{agent-docs-DD0hT2pE.mjs.map → agent-docs-DR1PRHV4.mjs.map} +1 -1
  4. package/dist/{build-C1ZgYqj7.mjs → build-CA0uDYP4.mjs} +2 -2
  5. package/dist/{build-DEdLI54B.mjs → build-DvcK_Feg.mjs} +3 -3
  6. package/dist/{build-DEdLI54B.mjs.map → build-DvcK_Feg.mjs.map} +1 -1
  7. package/dist/{builtins-BWtf5CEP.mjs → builtins-DWzysfuk.mjs} +2 -2
  8. package/dist/{builtins-DZ-kQSyt.mjs → builtins-QqgoF4jk.mjs} +142 -131
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-CQGH0FTE.mjs → config-ChYZE_ER.mjs} +2 -2
  11. package/dist/{config-CHRM7WLZ.mjs → config-Cz2-AJbR.mjs} +3 -3
  12. package/dist/{config-CHRM7WLZ.mjs.map → config-Cz2-AJbR.mjs.map} +1 -1
  13. package/dist/{doctor-D0uazKD7.mjs → doctor-CNra8Yf_.mjs} +4 -4
  14. package/dist/{doctor-D0uazKD7.mjs.map → doctor-CNra8Yf_.mjs.map} +1 -1
  15. package/dist/{fullstack-Cr5tath7.mjs → fullstack-B6QDnu27.mjs} +5 -5
  16. package/dist/{fullstack-Cr5tath7.mjs.map → fullstack-B6QDnu27.mjs.map} +1 -1
  17. package/dist/{fullstack-C8k03oM8.mjs → fullstack-en-ECevz.mjs} +4 -4
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +2 -2
  20. package/dist/{package-manager-mqxVziQ9.mjs → package-manager-D8W1-xh-.mjs} +3 -3
  21. package/dist/{package-manager-mqxVziQ9.mjs.map → package-manager-D8W1-xh-.mjs.map} +1 -1
  22. package/dist/{package-manager-B-BW1RBj.mjs → package-manager-vl66Np0J.mjs} +2 -2
  23. package/dist/{plugin-MPu_4sWN.mjs → plugin-C22PThnC.mjs} +2 -2
  24. package/dist/{plugin-DSgKyJSD.mjs → plugin-C4ZvjEuo.mjs} +2 -2
  25. package/dist/project-BO5joAFY.mjs +134 -0
  26. package/dist/project-BO5joAFY.mjs.map +1 -0
  27. package/dist/project-BxGXkPHR.mjs +133 -0
  28. package/dist/{project-root-BsIxM6Gj.mjs → project-root-CH1Dy_HW.mjs} +2 -2
  29. package/dist/{project-root-C4lAZePJ.mjs → project-root-DVa7AoaZ.mjs} +3 -3
  30. package/dist/{project-root-C4lAZePJ.mjs.map → project-root-DVa7AoaZ.mjs.map} +1 -1
  31. package/dist/{rolldown-runtime-BVrPnwAV.mjs → rolldown-runtime-V3xbKk8u.mjs} +1 -1
  32. package/dist/{run-plugins-cqNounm7.mjs → run-plugins-9IDaa4U7.mjs} +99 -88
  33. package/dist/run-plugins-9IDaa4U7.mjs.map +1 -0
  34. package/dist/{typegen-BfFiyGeh.mjs → typegen-BKa7OeBf.mjs} +4 -4
  35. package/dist/{typegen-Ctafx65M.mjs → typegen-CiKLo3iV.mjs} +5 -5
  36. package/dist/{typegen-Ctafx65M.mjs.map → typegen-CiKLo3iV.mjs.map} +1 -1
  37. package/dist/{types-CH5itn9u.mjs → types-Zu0gh9vO.mjs} +1 -1
  38. package/package.json +2 -2
  39. package/templates/feature-devtools/feature.json +1 -1
  40. package/dist/project--T8NPgfc.mjs +0 -133
  41. package/dist/project-w-OcvS26.mjs +0 -134
  42. package/dist/project-w-OcvS26.mjs.map +0 -1
  43. package/dist/run-plugins-cqNounm7.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.13.0
2
+ * @forinda/kickjs-cli v8.14.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as e}from"./rolldown-runtime-BVrPnwAV.mjs";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,s as m,t as h,u as g}from"./package-manager-mqxVziQ9.mjs";import{A as _,C as v,D as y,E as b,F as x,M as S,N as ee,O as te,P as C,S as ne,T as re,_ as ie,a as ae,b as oe,c as se,f as ce,g as le,h as ue,i as de,j as fe,k as pe,l as me,m as he,p as ge,r as _e,u as ve,v as ye,w as be,x as xe,y as Se}from"./doctor-D0uazKD7.mjs";import{a as Ce,c as w,d as we,f as Te,h as Ee,l as T,m as De,o as Oe,p as ke,s as E,u as Ae}from"./config-CHRM7WLZ.mjs";import{d as je,f as Me,o as Ne,r as Pe,s as Fe,t as Ie,u as Le}from"./project-w-OcvS26.mjs";import{t as D}from"./project-root-C4lAZePJ.mjs";import{n as O,t as Re}from"./types-CH5itn9u.mjs";import{t as ze}from"./build-DEdLI54B.mjs";import{n as Be}from"./agent-docs-DD0hT2pE.mjs";import{C as Ve,S as He,_ as Ue,a as We,b as Ge,c as Ke,d as qe,f as Je,g as Ye,h as Xe,i as Ze,l as Qe,m as $e,o as et,p as tt,r as nt,s as rt,t as it,u as at,v as ot,w as st,x as k,y as ct}from"./typegen-Ctafx65M.mjs";import{createRequire as lt}from"node:module";import A,{basename as ut,dirname as j,join as M,relative as N,resolve as P,sep as F}from"node:path";import{cpSync as dt,existsSync as I,mkdirSync as ft,readFileSync as L,readdirSync as R,rmSync as pt,statSync as mt,writeFileSync as z}from"node:fs";import{copyFile as ht,mkdir as gt,readFile as B,readdir as _t,rm as vt,stat as yt,writeFile as bt}from"node:fs/promises";import{fork as xt,spawn as St,spawnSync as Ct}from"node:child_process";import{createHash as wt}from"node:crypto";import{fileURLToPath as Tt,pathToFileURL as V}from"node:url";import{parseSync as Et}from"oxc-parser";import{arch as Dt,platform as Ot,release as kt}from"node:os";const At=[{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`},{value:`storage`,label:`Storage`,hint:`disk, S3 / R2 / MinIO`}];function jt(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 | inertia`).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(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`--deploy <targets>`,`Comma-separated deploy targets to write files for: netlify, vercel, docker (later: kick g deploy)`).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)=>{n(`KickJS — Create a new project`);let a=[];try{a=t.deploy?Me(t.deploy):[]}catch(e){f.error(e.message),r(`Aborted.`),process.exitCode=1;return}let o=!!(t.yes||t.nonInteractive);e||=o?`my-api`:await i({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let s;if(e===`.`?(s=P(`.`),e=ut(s)):s=P(t.directory||e),I(s)){let n=R(s);if(n.length>0){if(t.force)f.warn(`Clearing existing files in ${s}`);else if(o){f.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{f.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)f.message(` - ${e}`);if(n.length>5&&f.message(` ... and ${n.length-5} more`),!await c({message:p.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of n)pt(P(s,e),{recursive:!0,force:!0})}}let u=t.template;u||=o?`minimal`:await l({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`},{value:`inertia`,label:`Inertia`,hint:`server-driven React pages, one app, SSR`}]});let h=t.runtime;h||=o?`express`:await l({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 g=t.pm;g||=o?await d(void 0):await l({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let _=t.repo;_||=o?`inmemory`:await i({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Ee(_);let v=t.schema;u===`inertia`&&(v&&v!==`zod`&&f.warn(`The inertia template uses zod — ignoring --schema ${v}.`),v=`zod`),v||=o?`zod`:await l({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(v)||(f.warn(`Unknown --schema "${v}", falling back to zod.`),v=`zod`);let y;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();y=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else y=o?[]:await m({message:`Select packages to include`,options:[...At],required:!1});let b;b=t.git===void 0?o?!0:await c({message:`Initialize git repository?`,initialValue:!0}):t.git;let x;if(x=t.install===void 0?o?!0:await c({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){f.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),r(`Aborted.`);return}let{VITE_TEMPLATES:S,DEFAULT_VITE_TEMPLATE:ee}=await import(`./fullstack-Cr5tath7.mjs`);if(t.viteTemplate!==void 0&&!S.some(e=>e.value===t.viteTemplate)){f.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${S.map(e=>e.value).join(`, `)}.`),r(`Aborted.`);return}let te=t.frontend===`vite`?`vite`:`kick`,C=t.viteTemplate??ee;if(u===`fullstack`&&!t.frontend&&!o&&(te=await l({message:`Frontend for web/`,options:[{value:`kick`,label:`KickJS React app`,hint:`typed client, /api proxy, route types — wired`},{value:`vite`,label:`Delegate to create-vite`,hint:`pick any framework; wiring is manual (guide printed after)`}]})),te===`vite`&&!t.viteTemplate&&!o&&(C=await l({message:`create-vite template`,options:S.map(e=>({value:e.value,label:e.label})),initialValue:ee})),u===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-Cr5tath7.mjs`);await t({name:e,directory:s,packageManager:g,initGit:b,installDeps:x,schemaLib:v,runtime:h,packages:y,frontend:te,viteTemplate:C,deploy:a}),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${g}${g===`pnpm`?` dev`:` run dev:server`}`)}`)}else await Ie({name:e,directory:s,packageManager:g,initGit:b,installDeps:x,template:u,defaultRepo:_,packages:y,schemaLib:v,runtime:h,deploy:a}),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${ke(g,`dev`)}`)}`)})}function Mt(e,t=[]){let n=/* @__PURE__ */ new Map;for(let t of e){let e=(n.get(t.name)??0)+1;if(n.set(t.name,e),e===2)throw new Re(`plugin`,t.name,[t.name,t.name])}let r=/* @__PURE__ */ new Map,i=[];for(let t of e)for(let e of t.commands??[]){let n=r.get(e.name);if(n)throw new Re(`command`,e.name,[n,t.name]);r.set(e.name,t.name),i.push(e)}let a=new Set(t.map(e=>e.name)),o=[...i.filter(e=>!a.has(e.name)),...t],s=/* @__PURE__ */ new Map,c=[];for(let t of e)for(let e of t.typegens??[]){let n=s.get(e.id);if(n)throw new Re(`typegen`,e.id,[n,t.name]);s.set(e.id,t.name),c.push(e)}let l=/* @__PURE__ */ new Map,u=[];for(let t of e)for(let e of t.generators??[]){let n=l.get(e.name);if(n)throw new Re(`generator`,e.name,[n,t.name]);l.set(e.name,t.name),u.push({source:t.name,spec:e})}return{commands:o,typegens:c,generators:u,register:async(t,n)=>{let r;if(n)r={generators:u,...n};else{let{findProjectRoot:e}=await import(`./project-root-C4lAZePJ.mjs`).then(e=>e.n),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:u}}for(let n of e)n.register&&await n.register(t,r)}}}async function Nt(e){let{name:n,outDir:r}=e,i=C(n),a=x(n),o=[],s=M(r,`${i}.plugin.ts`);return await t(s,`import {
11
+ import{t as e}from"./rolldown-runtime-V3xbKk8u.mjs";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _}from"./package-manager-D8W1-xh-.mjs";import{A as v,C as y,D as b,E as x,F as S,M as ee,N as te,O as ne,P as C,S as re,T as ie,_ as ae,a as oe,b as se,c as ce,f as le,g as ue,h as de,i as fe,j as pe,k as me,l as he,m as ge,p as _e,r as ve,u as ye,v as be,w as xe,x as Se,y as Ce}from"./doctor-CNra8Yf_.mjs";import{a as we,c as w,d as Te,f as Ee,h as De,l as T,m as Oe,o as ke,p as Ae,s as E,u as je}from"./config-Cz2-AJbR.mjs";import{_ as Me,a as Ne,b as Pe,d as Fe,g as Ie,h as Le,l as Re,m as ze,n as Be,o as Ve,p as He,r as Ue,s as D,t as We,u as Ge,v as Ke,x as qe,y as Je}from"./project-BO5joAFY.mjs";import{t as O}from"./project-root-DVa7AoaZ.mjs";import{n as k,t as Ye}from"./types-Zu0gh9vO.mjs";import{t as Xe}from"./build-DvcK_Feg.mjs";import{n as Ze}from"./agent-docs-DR1PRHV4.mjs";import{C as Qe,S as $e,_ as et,a as tt,b as nt,c as rt,d as it,f as at,g as ot,h as st,i as ct,l as lt,m as ut,o as dt,p as ft,r as pt,s as mt,t as ht,u as gt,v as _t,w as vt,x as A,y as yt}from"./typegen-CiKLo3iV.mjs";import{createRequire as bt}from"node:module";import j,{basename as xt,dirname as M,join as N,relative as P,resolve as F,sep as I}from"node:path";import{cpSync as St,existsSync as L,mkdirSync as Ct,readFileSync as R,readdirSync as z,rmSync as wt,statSync as Tt,writeFileSync as B}from"node:fs";import{copyFile as Et,mkdir as Dt,readFile as V,readdir as Ot,rm as kt,stat as At,writeFile as jt}from"node:fs/promises";import{fork as Mt,spawn as Nt,spawnSync as Pt}from"node:child_process";import{createHash as Ft}from"node:crypto";import{fileURLToPath as It,pathToFileURL as H}from"node:url";import{parseSync as Lt}from"oxc-parser";import{arch as Rt,platform as zt,release as Bt}from"node:os";const Vt=[{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`},{value:`storage`,label:`Storage`,hint:`disk, S3 / R2 / MinIO`}];function Ht(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 | inertia`).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(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`--deploy <targets>`,`Comma-separated deploy targets to write files for: netlify, vercel, docker (later: kick g deploy)`).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)=>{n(`KickJS — Create a new project`);let a=Ue(),o=e=>{e&&f.warn(`kick ${We} is behind the latest release, ${e} — templates and options added since are missing. Upgrade: npm i -g @forinda/kickjs-cli@latest`)},s=[];try{s=t.deploy?qe(t.deploy):[]}catch(e){f.error(e.message),r(`Aborted.`),process.exitCode=1;return}let u=!!(t.yes||t.nonInteractive);e||=u?`my-api`:await i({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let m;if(e===`.`?(m=F(`.`),e=xt(m)):m=F(t.directory||e),L(m)){let n=z(m);if(n.length>0){if(t.force)f.warn(`Clearing existing files in ${m}`);else if(u){f.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{f.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)f.message(` - ${e}`);if(n.length>5&&f.message(` ... and ${n.length-5} more`),!await c({message:p.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of n)wt(F(m,e),{recursive:!0,force:!0})}}u||o(await Promise.race([a,new Promise(e=>setTimeout(e,3e3,null).unref())]));let g=t.template;g||=u?`minimal`:await l({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`},{value:`inertia`,label:`Inertia`,hint:`server-driven React pages, one app, SSR`}]});let _=t.runtime;_||=u?`express`:await l({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 v=t.pm;v||=u?await d(void 0):await l({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let y=t.repo;y||=u?`inmemory`:await i({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),De(y);let b=t.schema;g===`inertia`&&(b&&b!==`zod`&&f.warn(`The inertia template uses zod — ignoring --schema ${b}.`),b=`zod`),b||=u?`zod`:await l({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(b)||(f.warn(`Unknown --schema "${b}", falling back to zod.`),b=`zod`);let x;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();x=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else x=u?[]:await h({message:`Select packages to include`,options:[...Vt],required:!1});let S;S=t.git===void 0?u?!0:await c({message:`Initialize git repository?`,initialValue:!0}):t.git;let ee;if(ee=t.install===void 0?u?!0:await c({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){f.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),r(`Aborted.`);return}let{VITE_TEMPLATES:te,DEFAULT_VITE_TEMPLATE:ne}=await import(`./fullstack-B6QDnu27.mjs`);if(t.viteTemplate!==void 0&&!te.some(e=>e.value===t.viteTemplate)){f.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${te.map(e=>e.value).join(`, `)}.`),r(`Aborted.`);return}let C=t.frontend===`vite`?`vite`:`kick`,re=t.viteTemplate??ne;if(g===`fullstack`&&!t.frontend&&!u&&(C=await l({message:`Frontend for web/`,options:[{value:`kick`,label:`KickJS React app`,hint:`typed client, /api proxy, route types — wired`},{value:`vite`,label:`Delegate to create-vite`,hint:`pick any framework; wiring is manual (guide printed after)`}]})),C===`vite`&&!t.viteTemplate&&!u&&(re=await l({message:`create-vite template`,options:te.map(e=>({value:e.value,label:e.label})),initialValue:ne})),g===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-B6QDnu27.mjs`);await t({name:e,directory:m,packageManager:v,initGit:S,installDeps:ee,schemaLib:b,runtime:_,packages:x,frontend:C,viteTemplate:re,deploy:s}),u&&o(await a),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${v}${v===`pnpm`?` dev`:` run dev:server`}`)}`)}else await Be({name:e,directory:m,packageManager:v,initGit:S,installDeps:ee,template:g,defaultRepo:y,packages:x,schemaLib:b,runtime:_,deploy:s}),u&&o(await a),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${Ae(v,`dev`)}`)}`)})}function Ut(e,t=[]){let n=/* @__PURE__ */ new Map;for(let t of e){let e=(n.get(t.name)??0)+1;if(n.set(t.name,e),e===2)throw new Ye(`plugin`,t.name,[t.name,t.name])}let r=/* @__PURE__ */ new Map,i=[];for(let t of e)for(let e of t.commands??[]){let n=r.get(e.name);if(n)throw new Ye(`command`,e.name,[n,t.name]);r.set(e.name,t.name),i.push(e)}let a=new Set(t.map(e=>e.name)),o=[...i.filter(e=>!a.has(e.name)),...t],s=/* @__PURE__ */ new Map,c=[];for(let t of e)for(let e of t.typegens??[]){let n=s.get(e.id);if(n)throw new Ye(`typegen`,e.id,[n,t.name]);s.set(e.id,t.name),c.push(e)}let l=/* @__PURE__ */ new Map,u=[];for(let t of e)for(let e of t.generators??[]){let n=l.get(e.name);if(n)throw new Ye(`generator`,e.name,[n,t.name]);l.set(e.name,t.name),u.push({source:t.name,spec:e})}return{commands:o,typegens:c,generators:u,register:async(t,n)=>{let r;if(n)r={generators:u,...n};else{let{findProjectRoot:e}=await import(`./project-root-DVa7AoaZ.mjs`).then(e=>e.n),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:u}}for(let n of e)n.register&&await n.register(t,r)}}}async function Wt(e){let{name:n,outDir:r}=e,i=C(n),a=S(n),o=[],s=N(r,`${i}.plugin.ts`);return await t(s,`import {
12
12
  definePlugin,
13
13
  type AppAdapter,
14
14
  type AppModuleEntry,
@@ -165,10 +165,10 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
165
165
  // Example: await this.connection?.close()
166
166
  },
167
167
 
168
- ${oe(i,a,`plugin`,` `)}
168
+ ${se(i,a,`plugin`,` `)}
169
169
  }),
170
170
  })
171
- `),o.push(s),o}function Pt(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 Ft(e){let{name:n,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=C(n),c=x(n),l=e.key??ee(n),u=Array.isArray(e.params)?e.params:Pt(e.params),d=ye({type:`contributor`,outDir:e.outDir,moduleName:r,modulesDir:i,defaultDir:`src/contributors`,pattern:a,shouldPluralize:e.pluralize??!1}),f=o===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,p=o===`http`?`RequestContext`:`ExecutionContext`,m=u.length>0?`\nexport type ${c}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
171
+ `),o.push(s),o}function Gt(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 Kt(e){let{name:n,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=C(n),c=S(n),l=e.key??te(n),u=Array.isArray(e.params)?e.params:Gt(e.params),d=be({type:`contributor`,outDir:e.outDir,moduleName:r,modulesDir:i,defaultDir:`src/contributors`,pattern:a,shouldPluralize:e.pluralize??!1}),f=o===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,p=o===`http`?`RequestContext`:`ExecutionContext`,m=u.length>0?`\nexport type ${c}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
172
172
  `)}\n}\n`:``,h=u.length>0?`${f}.withParams<${c}Params>()({`:`${f}({`,g=u.length>0?` // Every call site must supply these — no placeholder defaults.
173
173
  // Add \`paramDefaults: { … }\` for any field whose default is
174
174
  // genuinely correct for an undecorated route, and drop it from here.
@@ -219,7 +219,7 @@ ${v}
219
219
  throw new Error("${c} contributor: resolve() not implemented")
220
220
  },
221
221
  })
222
- `,b=M(d,`${s}.contributor.ts`);return await t(b,y),[b]}async function It(e){let n=M(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return I(n)&&!e.force&&!await c({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
222
+ `,b=N(d,`${s}.contributor.ts`);return await t(b,y),[b]}async function qt(e){let n=N(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return L(n)&&!e.force&&!await c({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
223
223
  Skipped — existing kick.config.ts preserved.`),[]):(await t(n,`import { defineConfig } from '@forinda/kickjs-cli'
224
224
 
225
225
  export default defineConfig({
@@ -263,18 +263,18 @@ export default defineConfig({
263
263
  },
264
264
  ],
265
265
  })
266
- `),[n])}function Lt(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function H(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=Lt(e,r);return i===-1?null:e.slice(r+1,i)}function U(e,t,n){let r=` `.repeat(n);return e.split(`
266
+ `),[n])}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 U(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 W(e,t,n){let r=` `.repeat(n);return e.split(`
267
267
  `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
268
- `)}function Rt(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 zt(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 Bt(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=Lt(e,i);if(a===-1)return{migrated:null,reason:`unbalanced class braces`};let o=e.slice(i+1,a),s=e.slice(0,n.index),c=e.slice(a+1),l=H(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=H(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=H(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Rt(s),p=``;return l&&(p+=` register(container) {${U(l,4,6)} },\n\n`),u&&(p+=` contributors() {${U(u,4,6)} },\n\n`),p+=` routes() {${U(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
268
+ `)}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=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=Yt(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({
269
269
  name: '${r}',
270
270
  build: () => ({
271
271
  ${p}
272
272
  }),
273
- })`}${c}`}}function Vt(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=Lt(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]===`
274
- `||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=Lt(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=H(m,/register\s*\(([^)]*)\)\s*\{/),g=H(m,/contributors\s*\(\s*\)\s*\{/),_=H(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=zt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${U(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${U(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${U(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
273
+ })`}${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]===`
274
+ `||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=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=Xt(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 {
275
275
  ${y}
276
276
  }
277
- `}${u}`}}function Ht(e,t){return t===`class`?Vt(e):Bt(e)}function Ut(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 Wt(e){let t=[];return await n(P(e),0),t;async function n(e,r){let i;try{i=await _t(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 yt(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Gt(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await _t(e)}catch{return}await gt(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 yt(i)}catch{continue}s.isDirectory()?await r(i,o):(await ht(i,o),n++)}}}function Kt(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return M(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function qt(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Wt(e),s=await B(M(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Kt(r),await Gt(e,c));let l=[];for(let e of o){let t=Ht(await B(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await bt(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=M(e,`index.ts`),d=null;try{d=await B(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Ut(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await bt(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Jt(e,t){let n=await Wt(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 B(e,`utf-8`);i.test(t)&&r.push(e)}return r}const Yt={string:{ts:`string`,zod:`z.string().min(1).max(200)`},text:{ts:`string`,zod:`z.string().min(1)`},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.iso.datetime()`},email:{ts:`string`,zod:`z.email()`},url:{ts:`string`,zod:`z.url()`},uuid:{ts:`string`,zod:`z.uuid()`},json:{ts:`any`,zod:`z.any()`}};function Xt(e){let t=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=Yt[a];if(!o){let e=[...Object.keys(Yt),`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}}),n=/* @__PURE__ */ new Set;for(let{name:e}of t){if(n.has(e))throw Error(`Duplicate field: "${e}". Each field name may appear once.`);n.add(e)}return t}async function Zt(e){let{name:n,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize===!0,l=C(n),u=x(n),d=c?fe(l):l,f=c?S(u):u,p=e.pluralizeRoutes===!1?l:fe(l),m=M(i,d),h=[],g=async(e,n)=>{let r=M(m,e);await t(r,n),h.push(r)};return await g(`${l}.module.ts`,pe({pascal:u,kebab:l,plural:d,routePath:p,repo:a,style:s})),await g(`${l}.constants.ts`,re({pascal:u,kebab:l,fields:r})),await g(`${l}.controller.ts`,te({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await g(`${l}.service.ts`,b({pascal:u,kebab:l})),await g(`dtos/create-${l}.dto.ts`,Qt(u,r)),await g(`dtos/update-${l}.dto.ts`,$t(u,r)),await g(`dtos/${l}-response.dto.ts`,en(u,r)),await g(`${l}.repository.ts`,y({pascal:u,kebab:l,repoType:a,dtoPrefix:`./dtos`,tokenScope:o})),await xe(i,u,d,l,s),h}function Qt(e,t){return`import { z } from 'zod'
277
+ `}${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(F(e),0),t;async function n(e,r){let i;try{i=await Ot(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=N(e,a),o;try{o=await At(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 Ot(e)}catch{return}await Dt(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=N(e,a),o=N(t,a),s;try{s=await At(i)}catch{continue}s.isDirectory()?await r(i,o):(await Et(i,o),n++)}}}function rn(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return N(e,`.kickjs`,`codemod-backups`,`${t}-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 V(N(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 V(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await jt(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=N(e,`index.ts`),d=null;try{d=await V(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 jt(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 V(e,`utf-8`);i.test(t)&&r.push(e)}return r}const sn={string:{ts:`string`,zod:`z.string().min(1).max(200)`},text:{ts:`string`,zod:`z.string().min(1)`},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.iso.datetime()`},email:{ts:`string`,zod:`z.email()`},url:{ts:`string`,zod:`z.url()`},uuid:{ts:`string`,zod:`z.uuid()`},json:{ts:`any`,zod:`z.any()`}};function cn(e){let t=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}}),n=/* @__PURE__ */ new Set;for(let{name:e}of t){if(n.has(e))throw Error(`Duplicate field: "${e}". Each field name may appear once.`);n.add(e)}return t}async function ln(e){let{name:n,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize===!0,l=C(n),u=S(n),d=c?pe(l):l,f=c?ee(u):u,p=e.pluralizeRoutes===!1?l:pe(l),m=N(i,d),h=[],g=async(e,n)=>{let r=N(m,e);await t(r,n),h.push(r)};return await g(`${l}.module.ts`,me({pascal:u,kebab:l,plural:d,routePath:p,repo:a,style:s})),await g(`${l}.constants.ts`,ie({pascal:u,kebab:l,fields:r})),await g(`${l}.controller.ts`,ne({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await g(`${l}.service.ts`,x({pascal:u,kebab:l})),await g(`dtos/create-${l}.dto.ts`,un(u,r)),await g(`dtos/update-${l}.dto.ts`,dn(u,r)),await g(`dtos/${l}-response.dto.ts`,fn(u,r)),await g(`${l}.repository.ts`,b({pascal:u,kebab:l,repoType:a,dtoPrefix:`./dtos`,tokenScope:o})),await Se(i,u,d,l,s),h}function un(e,t){return`import { z } from 'zod'
278
278
 
279
279
  export const create${e}Schema = z.object({
280
280
  ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
@@ -282,7 +282,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
282
282
  })
283
283
 
284
284
  export type Create${e}DTO = z.infer<typeof create${e}Schema>
285
- `}function $t(e,t){return`import { z } from 'zod'
285
+ `}function dn(e,t){return`import { z } from 'zod'
286
286
 
287
287
  export const update${e}Schema = z.object({
288
288
  ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
@@ -290,14 +290,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
290
290
  })
291
291
 
292
292
  export type Update${e}DTO = z.infer<typeof update${e}Schema>
293
- `}function en(e,t){return`export interface ${e}ResponseDTO {
293
+ `}function fn(e,t){return`export interface ${e}ResponseDTO {
294
294
  id: string
295
295
  ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
296
296
  `)}
297
297
  createdAt: string
298
298
  updatedAt: string
299
299
  }
300
- `}async function tn(e){let{name:n,moduleName:r,modulesDir:i,testImport:a=`vitest`}=e,o=e.pluralize??!1,s=C(n),c=x(n),l=[],u;if(e.outDir)u=P(e.outDir);else if(r){let e=C(r),t=o?fe(e):e;u=P(M(i??`src/modules`,t,`__tests__`))}else u=P(`src/__tests__`);let d=M(u,`${s}.test.ts`);return await t(d,`import { describe, it, expect, beforeEach } from '${a}'
300
+ `}async function pn(e){let{name:n,moduleName:r,modulesDir:i,testImport:a=`vitest`}=e,o=e.pluralize??!1,s=C(n),c=S(n),l=[],u;if(e.outDir)u=F(e.outDir);else if(r){let e=C(r),t=o?pe(e):e;u=F(N(i??`src/modules`,t,`__tests__`))}else u=F(`src/__tests__`);let d=N(u,`${s}.test.ts`);return await t(d,`import { describe, it, expect, beforeEach } from '${a}'
301
301
  import { Container } from '@forinda/kickjs'
302
302
 
303
303
  describe('${c}', () => {
@@ -320,52 +320,63 @@ describe('${c}', () => {
320
320
  expect(true).toBe(true)
321
321
  })
322
322
  })
323
- `),l.push(d),l}const nn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function W(e){return e.parent?.opts()?.dryRun??!1}function G(e,t=!1){let n=process.cwd();console.log(`\n ${t?`Would generate`:`Generated`} ${e.length} file${e.length===1?``:`s`}:`);for(let t of e)console.log(` ${t.replace(n+`/`,``)}`);t&&console.log(`
324
- (dry run — no files were written)`),console.log()}async function rn(e){if(!e)try{let e=await E(process.cwd());await it({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 an=[{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`},{name:`deploy <targets...>`,description:`Deploy files: netlify | vercel | docker (config, entry, build script)`}],on=/* @__PURE__ */ new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
325
- Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),sn=/* @__PURE__ */ new Set([...an.map(e=>e.name.split(` `)[0]),...on.keys()]);async function cn(){console.log(`
323
+ `),l.push(d),l}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(`
324
+ (dry run — no files were written)`),console.log()}async function hn(e){if(!e)try{let e=await E(process.cwd());await ht({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`},{name:`deploy <targets...>`,description:`Deploy files: netlify | vercel | docker (config, entry, build script)`}],_n=/* @__PURE__ */ new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
325
+ Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),vn=/* @__PURE__ */ new Set([...gn.map(e=>e.name.split(` `)[0]),..._n.keys()]);async function yn(){console.log(`
326
326
  Built-in generators:
327
- `);let e=Math.max(...an.map(e=>e.name.length));for(let t of an)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await E(process.cwd()),n=Mt(t?.plugins??[],t?.commands??[]),r=await de(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
327
+ `);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 E(process.cwd()),n=Ut(t?.plugins??[],t?.commands??[]),r=await fe(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
328
328
  Plugin generators:
329
329
  `);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(`
330
330
  Failed to load:
331
- `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function ln(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`])n[e]===!1&&(r[e]=!1);for(let e of[`pluralize`,`pluralizeRoutes`])r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return r}async function un(e,t,n){let r=await E(process.cwd()),i=w(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??be(i.repo);t.repo&&Ee(t.repo);let s=t.pattern??r?.pattern??`rest`,c=T(t.pluralize,i),l=Ae(t.pluralizeRoutes,i),u=Te(r,process.cwd()),d=Oe(D()),f=we(D()),m=D(),h=Ce(m,`@forinda/kickjs-testing`,`any`)&&Ce(m,`supertest`,`any`),g=i.style??`define`;if(!n&&g===`define`){let e=await Jt(P(a),`define`);if(e.length>0){console.error(`\n ${p.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${p.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${p.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 ${p.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${p.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${p.dim(`// kick.config.ts`)}\n ${p.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let _=[];for(let r of e){let e=await v({name:r,modulesDir:P(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:h,testImport:De(m),dryRun:n,pluralize:c,pluralizeRoutes:l,tokenScope:u,swagger:d,schemaLib:f,style:i.style});_.push(...e)}G(_,n),await rn(n)}function dn(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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await cn();return}if(!e||e.length===0){n.help();return}let a=W(i);o(a);let[s,c,...l]=e;if(s){let e=await E(process.cwd()),n=Mt(e?.plugins??[],e?.commands??[]),i=await ae({generatorName:s,itemName:c??``,args:l,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){G(i.files,a);return}if(s!==`module`&&sn.has(s)){let e=on.get(s);e?(console.error(`\n 'kick g ${s}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${s}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${s} ${c??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${s}' generator — upgrade it.\n`)),process.exitCode=1;return}}await un(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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=W(n);o(r),await un(e,ln(n,t),r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=W(n);o(r),G(await Se({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=W(n);o(r),G(await Nt({name:e,outDir:P(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
332
- Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;G(await ie({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a),runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
333
- Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;G(await le({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a)}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
331
+ `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function bn(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`])n[e]===!1&&(r[e]=!1);for(let e of[`pluralize`,`pluralizeRoutes`])r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return r}async function xn(e,t,n){let r=await E(process.cwd()),i=w(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??xe(i.repo);t.repo&&De(t.repo);let s=t.pattern??r?.pattern??`rest`,c=T(t.pluralize,i),l=je(t.pluralizeRoutes,i),u=Ee(r,process.cwd()),d=ke(O()),f=Te(O()),m=O(),h=we(m,`@forinda/kickjs-testing`,`any`)&&we(m,`supertest`,`any`),g=i.style??`define`;if(!n&&g===`define`){let e=await on(F(a),`define`);if(e.length>0){console.error(`\n ${p.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${p.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${p.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 ${p.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${p.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${p.dim(`// kick.config.ts`)}\n ${p.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let _=[];for(let r of e){let e=await y({name:r,modulesDir:F(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:h,testImport:Oe(m),dryRun:n,pluralize:c,pluralizeRoutes:l,tokenScope:u,swagger:d,schemaLib:f,style:i.style});_.push(...e)}K(_,n),await hn(n)}function Sn(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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).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);o(a);let[s,c,...l]=e;if(s){let e=await E(process.cwd()),n=Ut(e?.plugins??[],e?.commands??[]),i=await oe({generatorName:s,itemName:c??``,args:l,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){K(i.files,a);return}if(s!==`module`&&vn.has(s)){let e=_n.get(s);e?(console.error(`\n 'kick g ${s}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${s}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${s} ${c??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${s}' generator — upgrade it.\n`)),process.exitCode=1;return}}await xn(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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=G(n);o(r),await xn(e,bn(n,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);o(r),K(await Ce({name:e,outDir:F(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);o(r),K(await Wt({name:e,outDir:F(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
332
+ 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);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;K(await ae({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a),runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
333
+ 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);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;K(await ue({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a)}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
334
334
  --type http (default, RequestContext) | bare (ExecutionContext)
335
335
  --params "source:string,region:number" → emits the withParams<T>() form
336
- Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=W(n);o(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 E(process.cwd()),s=w(a),c=s.dir??`src/modules`;G(await Ft({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:a?.pattern,pluralize:T(void 0,s)}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
337
- Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;G(await ue({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a)}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
338
- Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;G(await he({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a)}),r),await rn(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
339
- Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;G(await ge({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a),schemaLib:we(D())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
340
- Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=W(n);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;G(await tn({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pluralize:T(void 0,a),testImport:De(D())}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
336
+ 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);o(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 E(process.cwd()),s=w(a),c=s.dir??`src/modules`;K(await Kt({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:c,pattern:a?.pattern,pluralize:T(void 0,s)}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
337
+ 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);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;K(await de({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a)}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
338
+ 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);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;K(await ge({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a)}),r),await hn(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
339
+ 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);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;K(await _e({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:T(void 0,a),schemaLib:Te(O())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
340
+ 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);o(r);let i=await E(process.cwd()),a=w(i),s=a.dir??`src/modules`;K(await pn({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pluralize:T(void 0,a),testImport:Oe(O())}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
341
341
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
342
342
  Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
343
343
  Optional: append :optional (shell-safe): description:text:optional
344
- 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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=ln(r,n),a=W(r);o(a),t.length===0&&(console.error(`
344
+ 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(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=bn(r,n),a=G(r);o(a),t.length===0&&(console.error(`
345
345
  Error: At least one field is required.
346
346
  Usage: kick g scaffold <name> <field:type> [field:type...]
347
347
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
348
348
  Optional: append :optional (shell-safe, no quoting needed)
349
- `),process.exit(1));let s=await E(process.cwd()),c=w(s),l=i.modulesDir??c.dir??`src/modules`,u=Xt(t),d=Te(s,process.cwd()),f=Oe(D()),p=await Zt({name:e,fields:u,modulesDir:P(l),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:T(i.pluralize,c),pluralizeRoutes:Ae(i.pluralizeRoutes,c),tokenScope:d,swagger:f,style:c.style});console.log(`\n Scaffolded ${e} with ${u.length} field(s):`);for(let e of u)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);G(p,a),await rn(a)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=W(t);o(n),G(await It({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 (default: detected from kick.config, packageManager, or the lockfile)`).option(`--template <template>`,`Template: rest | minimal | fullstack | inertia`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=W(t);o(n);let r=e.only??`all`;nn.includes(r)?G(await Be({outDir:P(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n):(console.error(` Invalid --only value: ${r}. Expected: ${nn.join(` | `)}`),process.exitCode=1)}),n.command(`deploy <targets...>`).description(`Add deploy files: netlify | vercel | docker (config, serverless entry, build script)`).option(`--pm <pm>`,`Package manager (default: detected)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=W(n);o(r);let i;try{i=Me(e.flatMap(e=>e.split(`,`))),G(await je({dir:P(`.`),targets:i,pm:t.pm,force:t.force}),r)}catch(e){console.error(` ${e.message}`),process.exitCode=1}});for(let e of t?.generators??[])fn(n,e,t?.projectRoot)}function fn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],s=a?.name??`itemName`,c=a?.required?`<${s}>`:`[${s}]`,l=`${i.name} ${c} [extraArgs...]`,u=e.command(l).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;u.option(n,e.description??``)}u.action(async(e,r,a,s)=>{let c=W(s);o(c);let l=await ae({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);l&&G(l.files,c)})}const pn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function mn(e){let t=A.resolve(e.cwd,`.kickjs/types`);e.check||await gt(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??Xe,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(V(e).href)},async writeFile(t,n){let r=A.resolve(e.cwd,t);await gt(A.dirname(r),{recursive:!0}),await bt(r,n,`utf8`)},getScanResult:e=>{let t=hn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?Ye(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=`${pn}${n.id} */\n\n`+a+`
350
- `,u=``;I(i)&&(u=await B(i,`utf8`)),u===l?s.push({id:n.id,status:`unchanged`,outFile:i}):e.check?(c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i})):(await bt(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new ve(c);return s}function hn(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 gn(e,t){let n=new Set(t),r=[],i=[],a=/* @__PURE__ */ 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 _n=/* @__PURE__ */ e({applyDisableFilter:()=>gn,runAllPluginTypegens:()=>K});async function K(e){let{enabled:t,skipped:n,unknown:r}=gn(Mt([...xa,...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 mn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&ce())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof ve||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 vn(e){let t=process.platform===`win32`;for(let n of yn(e))for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=t?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=M(n,i);if(I(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function yn(e){let t=P(e),n=bn(t);return(n?[t,n]:[t]).map(e=>M(e,`node_modules`,`.bin`))}function bn(e){for(let t=j(e);t!==j(t);t=j(t)){let n=M(t,`pnpm-workspace.yaml`),r=M(t,`package.json`);if(I(n)||I(r))return xn(n,r).some(n=>Sn(n,N(t,e)))?t:void 0}}function xn(e,t){try{if(I(e)){let t=L(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
351
- `)){if(!e.trim()||e.trim().startsWith(`#`))continue;let t=/^\s+-\s*['"]?([^'"#]+?)['"]?\s*$/.exec(e);if(!t)break;n.push(t[1])}return n}let{workspaces:n}=JSON.parse(L(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function Sn(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(F).join(`/`))}function Cn(e){let t=e.spawnFn??St,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 wn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
349
+ `),process.exit(1));let s=await E(process.cwd()),c=w(s),l=i.modulesDir??c.dir??`src/modules`,u=cn(t),d=Ee(s,process.cwd()),f=ke(O()),p=await ln({name:e,fields:u,modulesDir:F(l),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:T(i.pluralize,c),pluralizeRoutes:je(i.pluralizeRoutes,c),tokenScope:d,swagger:f,style:c.style});console.log(`\n Scaffolded ${e} with ${u.length} field(s):`);for(let e of u)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);K(p,a),await hn(a)}),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);o(n),K(await qt({outDir:F(`.`),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 (default: detected from kick.config, packageManager, or the lockfile)`).option(`--template <template>`,`Template: rest | minimal | fullstack | inertia`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=G(t);o(n);let r=e.only??`all`;mn.includes(r)?K(await Ze({outDir:F(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n):(console.error(` Invalid --only value: ${r}. Expected: ${mn.join(` | `)}`),process.exitCode=1)}),n.command(`deploy <targets...>`).description(`Add deploy files: netlify | vercel | docker (config, serverless entry, build script)`).option(`--pm <pm>`,`Package manager (default: detected)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=G(n);o(r);let i;try{i=qe(e.flatMap(e=>e.split(`,`))),K(await Pe({dir:F(`.`),targets:i,pm:t.pm,force:t.force}),r)}catch(e){console.error(` ${e.message}`),process.exitCode=1}});for(let e of t?.generators??[])Cn(n,e,t?.projectRoot)}function Cn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],s=a?.name??`itemName`,c=a?.required?`<${s}>`:`[${s}]`,l=`${i.name} ${c} [extraArgs...]`,u=e.command(l).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;u.option(n,e.description??``)}u.action(async(e,r,a,s)=>{let c=G(s);o(c);let l=await oe({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);l&&K(l.files,c)})}const wn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function Tn(e){let t=j.resolve(e.cwd,`.kickjs/types`);e.check||await Dt(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??st,i=j.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(H(e).href)},async writeFile(t,n){let r=j.resolve(e.cwd,t);await Dt(j.dirname(r),{recursive:!0}),await jt(r,n,`utf8`)},getScanResult:e=>{let t=En(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?ot(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=j.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=`${wn}${n.id} */\n\n`+a+`
350
+ `,u=``;L(i)&&(u=await V(i,`utf8`)),u===l?s.push({id:n.id,status:`unchanged`,outFile:i}):e.check?(c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i})):(await jt(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new ye(c);return s}function En(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 Dn(e,t){let n=new Set(t),r=[],i=[],a=/* @__PURE__ */ 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 On=/* @__PURE__ */ e({applyDisableFilter:()=>Dn,runAllPluginTypegens:()=>kn});async function kn(e){let{enabled:t,skipped:n,unknown:r}=Dn(Ut([...eo,...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 Tn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&le())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof ye||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 An(e){let t=process.platform===`win32`;for(let n of jn(e))for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=t?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=N(n,i);if(L(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function jn(e){let t=F(e),n=Mn(t);return(n?[t,n]:[t]).map(e=>N(e,`node_modules`,`.bin`))}function Mn(e){for(let t=M(e);t!==M(t);t=M(t)){let n=N(t,`pnpm-workspace.yaml`),r=N(t,`package.json`);if(L(n)||L(r))return Nn(n,r).some(n=>Pn(n,P(t,e)))?t:void 0}}function Nn(e,t){try{if(L(e)){let t=R(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
351
+ `)){if(!e.trim()||e.trim().startsWith(`#`))continue;let t=/^\s+-\s*['"]?([^'"#]+?)['"]?\s*$/.exec(e);if(!t)break;n.push(t[1])}return n}let{workspaces:n}=JSON.parse(R(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function Pn(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(I).join(`/`))}function Fn(e){let t=e.spawnFn??Nt,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 In(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
352
352
  `):`${n.slice(0,t).join(`
353
- `)}\n… ${n.length-t} more line(s)`}function Tn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function En(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 Dn(e,t,n={}){t&&(process.env.PORT=t);let r=Tn(n.polling),i=process.cwd(),a=await E(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await it({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{let e=await K({cwd:i,config:a});await Ze(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(P(`package.json`)).resolve(`vite`),{createServer:d}=await import(V(u).href);globalThis[se]=`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=vn(i);e?m=Cn({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(wn(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=me({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(`
353
+ `)}\n… ${n.length-t} more line(s)`}function Ln(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Rn(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 zn(e,t,n={}){t&&(process.env.PORT=t);let r=Ln(n.polling),i=process.cwd(),a=await E(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await ht({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=F(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await kn({cwd:i,config:a});await ct(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(F(`package.json`)).resolve(`vite`),{createServer:d}=await import(H(u).href);globalThis[ce]=`kick-dev`;let f=await d({configFile:F(`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=An(i);e?m=Fn({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(In(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=he({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(`
354
354
  KickJS dev server running (Vite + @forinda/kickjs-vite)
355
- `),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 On(e){let t=await E(e);try{await it({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});let n=P(e,t?.typegen?.outDir??`.kickjs/types`),r=await K({cwd:e,config:t});await Ze(n,r,!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 kn(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 Dn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`\n Error: vite is not installed.\n Run: ${h()} add -D vite unplugin-swc\n`):console.error(`
355
+ `),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 Bn(e){let t=await E(e);try{await ht({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});let n=F(e,t?.typegen?.outDir??`.kickjs/types`),r=await kn({cwd:e,config:t});await ct(n,r,!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 Vn(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 zn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`\n Error: vite is not installed.\n Run: ${g()} add -D vite unplugin-swc\n`):console.error(`
356
356
  Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
357
357
  Building for production...
358
- `);let{createRequire:e}=await import(`node:module`),t=e(P(`package.json`)).resolve(`vite`),{build:n}=await import(V(t).href);await n({configFile:P(`vite.config.ts`)});let r=await E(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
359
- Copying directories to dist...`);for(let e of i){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);I(r)?(ft(i,{recursive:!0}),dt(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)):console.log(` ⚠ Skipped ${t} (not found)`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
360
- Building asset map...`);try{await ze(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
358
+ `);let{createRequire:e}=await import(`node:module`),t=e(F(`package.json`)).resolve(`vite`),{build:n}=await import(H(t).href);await n({configFile:F(`vite.config.ts`)});let r=await E(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
359
+ Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?N(`dist`,e):e.dest??N(`dist`,t),r=F(t),i=F(n);L(r)?(Ct(i,{recursive:!0}),St(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)):console.log(` ⚠ Skipped ${t} (not found)`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
360
+ Building asset map...`);try{await Xe(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
361
361
  Build complete.
362
362
  `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await E(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0)console.log(` No assetMap entries — nothing to build.`);else{console.log(`
363
- Building asset map...`);try{await ze(e,{cwd:process.cwd()}),console.log(`
363
+ Building asset map...`);try{await Xe(e,{cwd:process.cwd()}),console.log(`
364
364
  Asset build complete.
365
- `)}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)),Le(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 On(t);let n=vn(t);if(!n){console.error(`
366
- No type-checker found. Install one in this project:\n ${h(t)} add -D typescript (tsc)\n ${h(t)} add -D @typescript/native-preview (tsgo, faster)\n`),process.exit(1);return}let r=Ct(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 En(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 Dn(e.entry,e.port)}catch(e){console.error(`
367
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function An(){try{let e=j(Tt(import.meta.url));return JSON.parse(L(M(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const jn=new Set(Object.values(Pe).filter(e=>e.deprecated).map(e=>e.pkg));function Mn(e){let t=M(e,`package.json`);if(!I(t))return[];let n;try{n=JSON.parse(L(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(I(i))try{n=JSON.parse(L(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:jn.has(t)}})}function Nn(e){let t=e;for(;;){if(I(M(t,`package.json`)))return t;let e=j(t);if(e===t)return null;t=e}}function Pn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${An()}`,``,` System:`,` OS: ${Ot()} ${kt()} (${Dt()})`,` Node: ${process.version}`],t=Nn(process.cwd()),n=t?Mn(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(`
368
- `))})}const{bold:q,dim:J,green:Fn,red:In,yellow:Ln,blue:Rn}=p;function zn(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 Bn(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 Bn(`${e}${t}`)}catch{return null}}async function Vn(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 Hn(e,t){let{health:n,metrics:r,routes:i,container:o,ws:s}=t,c=J(`─`.repeat(60));if(console.log(),console.log(q(` KickJS Inspector`)+J(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?Fn(`● healthy`):In(`● `+n.status);console.log(` ${q(`Health:`)} ${e}`)}else console.log(` ${q(`Health:`)} ${In(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?In:r.errorRate>0?Ln:Fn;console.log(` ${q(`Uptime:`)} ${zn(r.uptimeSeconds)}`),console.log(` ${q(`Requests:`)} ${r.requests}`),console.log(` ${q(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${J(`(`)}${t(e+`%`)}${J(`)`)}`)}if(o&&console.log(` ${q(`DI:`)} ${o.count} bindings`),s&&s.enabled&&console.log(` ${q(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(q(` Routes`)),console.log(c),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(` ${a(e.method)} ${t} ${Rn(e.controller)}.${J(e.handler)}`)}}console.log(c),console.log()}function Un(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 Vn(r);t.json?console.log(JSON.stringify(e,null,2)):Hn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(In(` ✖ 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 X(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 Wn=[{match(e,t){let n=X(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
365
+ `)}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)),Je(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=F(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await Bn(t);let n=An(t);if(!n){console.error(`
366
+ No type-checker found. Install one in this project:\n ${g(t)} add -D typescript (tsc)\n ${g(t)} add -D @typescript/native-preview (tsgo, faster)\n`),process.exit(1);return}let r=Pt(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 Rn(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 zn(e.entry,e.port)}catch(e){console.error(`
367
+ Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Hn(){try{let e=M(It(import.meta.url));return JSON.parse(R(N(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Un=new Set(Object.values(Ve).filter(e=>e.deprecated).map(e=>e.pkg));function Wn(e){let t=N(e,`package.json`);if(!L(t))return[];let n;try{n=JSON.parse(R(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=N(e,`node_modules`,...t.split(`/`),`package.json`);if(L(i))try{n=JSON.parse(R(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Un.has(t)}})}function Gn(e){let t=e;for(;;){if(L(N(t,`package.json`)))return t;let e=M(t);if(e===t)return null;t=e}}function Kn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Hn()}`,``,` System:`,` OS: ${zt()} ${Bt()} (${Rt()})`,` Node: ${process.version}`],t=Gn(process.cwd()),n=t?Wn(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(`
368
+ `))})}const{bold:q,dim:J,green:qn,red:Jn,yellow:Yn,blue:Xn}=p;function Zn(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 Qn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function $n(e,t){try{return await Qn(`${e}${t}`)}catch{return null}}async function er(e){let[t,n,r,i,a]=await Promise.all([$n(e,`/health`),$n(e,`/metrics`),$n(e,`/routes`),$n(e,`/container`),$n(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function tr(e,t){let{health:n,metrics:r,routes:i,container:o,ws:s}=t,c=J(`─`.repeat(60));if(console.log(),console.log(q(` KickJS Inspector`)+J(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?qn(`● healthy`):Jn(`● `+n.status);console.log(` ${q(`Health:`)} ${e}`)}else console.log(` ${q(`Health:`)} ${Jn(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Jn:r.errorRate>0?Yn:qn;console.log(` ${q(`Uptime:`)} ${Zn(r.uptimeSeconds)}`),console.log(` ${q(`Requests:`)} ${r.requests}`),console.log(` ${q(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${J(`(`)}${t(e+`%`)}${J(`)`)}`)}if(o&&console.log(` ${q(`DI:`)} ${o.count} bindings`),s&&s.enabled&&console.log(` ${q(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(q(` Routes`)),console.log(c),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(` ${a(e.method)} ${t} ${Xn(e.controller)}.${J(e.handler)}`)}}console.log(c),console.log()}function nr(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 er(r);t.json?console.log(JSON.stringify(e,null,2)):tr(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Jn(` ✖ 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()})}const rr={express:{name:`expressRuntime`,from:`@forinda/kickjs`},fastify:{name:`fastifyRuntime`,from:`@forinda/kickjs/fastify`},h3:{name:`h3Runtime`,from:`@forinda/kickjs/h3`}},ir=`// Express needs a body parser; Fastify and h3 parse bodies natively.`;function ar(e,t,n,r=`src/index.ts`){let i={source:e,changes:[],manual:[],blocked:!1},a=rr[t],o=rr[n],s=sr(Y(r,i.source));if(!s)return i.manual.push(`No bootstrap({ ... }) call in ${r}: set \`runtime: ${o.name}()\` (import { ${o.name} } from '${o.from}') yourself.`),i;let c=cr(s,`runtime`),l=`${o.name}()`;if(c){let e=c.value,s=dr(Y(r,i.source),a.from,a.name);if(c.shorthand||e.type!==`CallExpression`||e.callee?.type!==`Identifier`||s===void 0||e.callee.name!==s){let e=i.source.slice(c.start,c.end);return i.manual.push(`\`${e}\` in ${r} isn't a call to ${a.name}(): set it to ${l} (import { ${o.name} } from '${o.from}') yourself.`),i.blocked=!0,i}let u=e.arguments;if(u.length>0){let e=i.source.slice(u[0].start,u.at(-1).end);i.manual.push(`The ${t} runtime had options (${e}); ${n} takes its own — see guide/http-runtimes.`)}i.source=i.source.slice(0,e.start)+l+i.source.slice(e.end)}else i.source=lr(i.source,s,`runtime: ${l}`);if(i.changes.push(`runtime: ${l}`),i.source=Ie(i.source,{from:o.from,names:[o.name]},r),i.source=fr(i.source,a.from,a.name,r),t===`express`&&n!==`express`){let e=ur(i.source,r);e!==i.source&&(i.source=pr(e,`express`,r),i.changes.push(`removed express.json() — ${n} parses bodies itself`))}else if(n===`express`&&t!==`express`){let e=Me(i.source,[{import:{from:`express`,default:`express`},slot:`middleware`,code:`${ir}\nexpress.json()`}],void 0,r);i.source=e.source,e.added.length>0&&i.changes.push(`added express.json() to middlewares`),e.manual.length>0&&i.manual.push(`Add express.json() to bootstrap({ middlewares }) yourself.`)}return i}function or(e,t,n=`kick.config.ts`){let r=Y(n,e).body.find(e=>e.type===`ExportDefaultDeclaration`)?.declaration;for(;r&&(r.type===`TSSatisfiesExpression`||r.type===`TSAsExpression`);)r=r.expression;if(r?.type===`CallExpression`&&(r=r.arguments?.[0]),r?.type!==`ObjectExpression`)return null;let i=cr(r,`runtime`);if(!i)return lr(e,r,`runtime: '${t}'`);let a=i.value;if(a.type!==`Literal`||typeof a.value!=`string`)return null;let o=e[a.start]===`"`?`"`:`'`;return`${e.slice(0,a.start)}${o}${t}${o}${e.slice(a.end)}`}function Y(e,t){return Lt(e,t).program}function sr(e){let t,n=e=>{if(t||!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(n);let r=e;if(r.type===`CallExpression`&&r.callee?.type===`Identifier`&&r.callee.name===`bootstrap`&&r.arguments?.[0]?.type===`ObjectExpression`)t=r.arguments[0];else for(let e in r)n(r[e])};return n(e),t}function cr(e,t){return e.properties.find(e=>e.type===`Property`&&(e.key?.name??e.key?.value)===t)}function lr(e,t,n){let r=t.properties[0];if(!r)return`${e.slice(0,t.start)}{ ${n} }${e.slice(t.end)}`;let i=e.lastIndexOf(`
369
+ `,r.start)+1,a=e.slice(i,r.start);return/^\s*$/.test(a)?`${e.slice(0,r.start)}${n},\n${a}${e.slice(r.start)}`:`${e.slice(0,r.start)}${n}, ${e.slice(r.start)}`}function ur(e,t){let n=sr(Y(t,e)),r=n&&cr(n,`middlewares`);if(!r||r.value.type!==`ArrayExpression`)return e;let i=r.value.elements.find(e=>e?.type===`CallExpression`&&e.callee?.type===`MemberExpression`&&e.callee.object?.name===`express`&&e.callee.property?.name===`json`);if(!i)return e;let a=i.start,o=i.end,s=e.slice(o).match(/^\s*,/);s&&(o+=s[0].length);let c=e.lastIndexOf(`
370
+ `,a)+1;if(/^\s*$/.test(e.slice(c,a))){a=c;let t=e.lastIndexOf(`
371
+ `,a-2)+1;e.slice(t,a-1).trim()===ir&&(a=t);let n=e.indexOf(`
372
+ `,o);n!==-1&&/^\s*$/.test(e.slice(o,n))&&(o=n+1)}return e.slice(0,a)+e.slice(o)}function dr(e,t,n){for(let r of e.body)if(r.type===`ImportDeclaration`&&r.source.value===t)for(let e of r.specifiers){let t=e.imported?.name??e.imported?.value;if(e.type===`ImportSpecifier`&&t===n)return e.local.name}}function fr(e,t,n,r){let i=Y(r,e);for(let r of i.body){if(r.type!==`ImportDeclaration`||r.source.value!==t)continue;let a=r.specifiers.find(e=>e.type===`ImportSpecifier`&&(e.imported?.name??e.imported?.value)===n);if(a)return mr(i,a.local.name)?e:hr(e,r,a)}return e}function pr(e,t,n){let r=Y(n,e);for(let n of r.body){if(n.type!==`ImportDeclaration`||n.source.value!==t)continue;let i=n.specifiers.find(e=>e.type===`ImportDefaultSpecifier`);if(i)return mr(r,i.local.name)?e:hr(e,n,i)}return e}function mr(e,t){let n=!1,r=e=>{if(n||!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(r);let i=e;if(i.type!==`ImportDeclaration`){if((i.type===`Identifier`||i.type===`IdentifierReference`)&&i.name===t)n=!0;else for(let e in i)e!==`parent`&&r(i[e])}};return r(e.body),n}function hr(e,t,n){let r=t.specifiers;if(r.length===1){let n=e[t.end]===`
373
+ `?t.end+1:t.end;return e.slice(0,t.start)+e.slice(n)}let i=r.filter(e=>e.type===`ImportSpecifier`);if(n.type===`ImportSpecifier`&&i.length===1){let t=e.lastIndexOf(`,`,n.start),r=e.indexOf(`}`,n.end)+1;return e.slice(0,t)+e.slice(r)}if(n.type===`ImportDefaultSpecifier`){let t=e.indexOf(`,`,n.end)+1,r=e.slice(t).match(/^\s*/)[0].length;return e.slice(0,n.start)+e.slice(t+r)}let a=i.indexOf(n),o=a===0?n.start:i[a-1].end,s=a===0?i[1].start:n.end;return e.slice(0,o)+e.slice(s)}const gr={express:/from ['"](express|@types\/express)['"]/,fastify:/from ['"](fastify|@fastify\/[^'"]+)['"]/,h3:/from ['"]h3['"]/},_r=e=>e.replace(/(?<=.)@[^/]*$/,``);function vr(e){e.command(`runtime [engine]`).description(`Show the HTTP engine, or move the app to another: express | fastify | h3`).option(`--dry-run`,`Print what would change, and change nothing`).option(`--no-install`,`Edit the files only; leave packages to you`).option(`--pm <manager>`,`Package manager override`).option(`--entry <file>`,`Entry file (default: src/index.ts, then src/main.ts)`).option(`-f, --force`,`Edit files with uncommitted changes`).action(async(e,t)=>{let n=process.cwd(),r=await He(n);if(!e){let e=r.fromConfig?`kick.config.ts`:`guessed from package.json`;console.log(`\n HTTP runtime: ${r.runtime} (${e})`),r.ambiguous&&console.log(` Several engines are installed: ${r.candidates.join(`, `)}.`),console.log(` Move to another with: kick runtime <express|fastify|h3>
374
+ `);return}let i;try{i=Re(e)}catch{console.error(`\n Unknown engine '${e}'. Expected express, fastify or h3.\n`),process.exitCode=1;return}if(r.ambiguous&&!r.fromConfig){console.error(`\n Cannot tell which engine this app boots on now: found ${r.candidates.join(`, `)} in package.json.\n Set \`runtime: '<engine>'\` in kick.config.ts, then rerun.\n`),process.exitCode=1;return}let a=r.runtime;if(a===i){console.log(`\n Already on ${i}.\n`);return}let o=Le(n,t.entry);if(!o){console.error(`\n No entry file (${t.entry??`src/index.ts or src/main.ts`}).\n`),process.exitCode=1;return}let s=[`kick.config.ts`,`kick.config.mts`,`kick.config.js`].find(e=>L(N(n,e))),c=ze(n,[o,...s?[s]:[]]);if(c.length>0&&!t.force&&!t.dryRun){console.error(`\n ${c.join(`, `)} ${c.length===1?`has`:`have`} uncommitted changes. Commit or stage them first, so this change is its own diff, or rerun with --force.
375
+ `),process.exitCode=1;return}let l=ar(R(N(n,o),`utf-8`),a,i,o);if(l.blocked){for(let e of l.manual)console.error(`\n ${e}`);console.error(`\n Nothing changed. Fix that, then rerun kick runtime ${i}.\n`),process.exitCode=1;return}let u=s?R(N(n,s),`utf-8`):void 0,d=u===void 0?null:or(u,i,s);d===null&&l.manual.push(`Set \`runtime: '${i}'\` in ${s??`kick.config.ts`} so kick commands know the engine.`);let f=Sr(N(n,`src`)).map(e=>({file:e,text:e===N(n,o)?l.source:R(e,`utf-8`)})),p=f.some(({text:e})=>/@FileUpload\(|upload\.(single|array|none)\(/.test(e)),h=xr(n),{toAdd:g,toAddDev:_,toRemove:v,stillImported:y}=yr({from:a,to:i,installed:/* @__PURE__ */ new Set([...Object.keys(h.dependencies),...Object.keys(h.devDependencies)]),uploads:p,imported:e=>f.some(({text:t})=>RegExp(`from ['"]${e}(/[^'"]*)?['"]`).test(t))}),b=[];for(let{file:e,text:t}of f)t.split(`
376
+ `).forEach((t,r)=>{(gr[a].test(t)||/\bctx\.res\./.test(t))&&b.push(`${P(n,e)}:${r+1} ${t.trim()}`)});console.log(`\n ${a} → ${i}\n`);for(let e of l.changes)console.log(` ${o}: ${e}`);if(d&&console.log(` ${s}: runtime: '${i}'`),g.length&&console.log(` + ${g.join(`, `)}`),_.length&&console.log(` + ${_.join(`, `)} (dev)`),v.length&&console.log(` - ${v.join(`, `)}`),y.length&&console.log(` kept ${y.join(`, `)}: still imported in src/`),t.dryRun){console.log(`
377
+ Dry run: nothing changed.
378
+ `),br(l.manual,b,a);return}B(N(n,o),l.source),d!==null&&B(N(n,s),d);let x=!0;if(t.install!==!1){let{pm:e}=await m(t.pm),r=t=>{let r=[e,...t].join(` `);console.log(`\n ${r}`);try{Ke(e,t,{cwd:n})}catch{x=!1,console.log(` Failed. Run it yourself:\n ${r}`)}};g.length&&r([`add`,...g]),_.length&&r([`add`,`-D`,..._]),v.length&&r([e===`npm`?`uninstall`:`remove`,...v])}br(l.manual,b,a),console.log(x?" Done. Run `kick typegen` and your typecheck to see the rest.\n":` Files changed; the package step above did not finish.
379
+ `),x||(process.exitCode=1)})}function yr(e){let{from:t,to:n,installed:r,uploads:i,imported:a}=e,o=[...Ne[n],...i&&D[n].prod?[D[n].prod]:[]],s=[...n===`express`?[`@types/express`]:[],...i&&D[n].dev?[D[n].dev]:[]],c=new Set([...o,...s].map(_r)),l=[...Ne[t],...t===`express`?[`@types/express`]:[],...D[t].prod?[D[t].prod]:[],...D[t].dev?[D[t].dev]:[]].map(_r).filter(e=>r.has(e)&&!c.has(e)),u=l.filter(e=>a(e.replace(/^@types\//,``)));return{toAdd:o.filter(e=>!r.has(_r(e))),toAddDev:s.filter(e=>!r.has(_r(e))),toRemove:l.filter(e=>!u.includes(e)),stillImported:u}}function br(e,t,n){for(let t of e)console.log(`\n ! ${t}`);if(t.length>0){console.log(`\n Review — code that uses ${n} or the engine's response (ctx.res) directly:`);for(let e of t)console.log(` ${e}`)}console.log()}function xr(e){try{let t=JSON.parse(R(N(e,`package.json`),`utf-8`));return{dependencies:t.dependencies??{},devDependencies:t.devDependencies??{}}}catch{return{dependencies:{},devDependencies:{}}}}function Sr(e){return L(e)?z(e,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&/\.(ts|tsx|mts)$/.test(e.name)).map(e=>N(e.parentPath,e.name)):[]}function X(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 Cr=[{match(e,t){let n=X(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
369
380
  src/config/index.ts, and src/index.ts imports it before bootstrap().
370
381
  Tests never load src/index.ts — \`createTestApp\` builds the app
371
382
  directly — so that import does not run and ConfigService falls back to
@@ -580,23 +591,23 @@ import { bootstrap } from '@forinda/kickjs'
580
591
  await bootstrap({ modules }) // ← nothing for the dev server to read`,codeAfter:`import './env'
581
592
  import { bootstrap } from '@forinda/kickjs'
582
593
 
583
- export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function Gn(e,t){let n=null;for(let r of Wn){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 Kn(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.
594
+ export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function wr(e,t){let n=null;for(let r of Cr){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 Tr(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.
584
595
  export OPENAI_API_KEY="sk-..."
585
596
 
586
597
  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:
587
598
  kick add ai
588
599
 
589
600
  Or manually:
590
- ${h()} add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=qn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Jn((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 qn(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(`
591
- `)}function Jn(e){let t=[e,Yn(e),Xn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Zn(t))return t}catch{continue}return null}function Yn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Xn(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;else if(o===`\\`&&r)i=!0;else if(o===`"`)r=!r;else if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Zn(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 Qn(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 tr(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
601
+ ${g()} add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Er(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Dr((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 Er(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(`
602
+ `)}function Dr(e){let t=[e,Or(e),kr(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Ar(t))return t}catch{continue}return null}function Or(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function kr(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;else if(o===`\\`&&r)i=!0;else if(o===`"`)r=!r;else if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Ar(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 jr(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.
592
603
 
593
604
  Pass a message as a positional arg, --message flag, or pipe via stdin:
594
605
  kick explain "config.get returned undefined"
595
- ${ke(h(),`test`)} 2>&1 | kick explain\n`),process.exit(1));let r=rr(),i=Gn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
596
- `);return}if(i){ir(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
597
- `),process.exit(2)),ar(n),process.exit(2));let a=await Kn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify($n(a),null,2)+`
598
- `),process.exit(a.kind===`ok`?0:2)),er(n,a),process.exit(a.kind===`ok`?0:2)})}function $n(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 er(e,t){t.kind===`ok`?ir(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${sr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${or(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${sr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function tr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:nr()}function nr(){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 rr(){let e=process.cwd();return{cwd:e,hasFile:t=>I(P(e,t))}}function ir(e,t,n,r=!1){let i=sr(e.trim(),200),a=r?`AI-generated — verify before applying`:cr(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${or(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${or(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${or(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${or(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
599
- `)}function ar(e){let t=sr(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
606
+ ${Ae(g(),`test`)} 2>&1 | kick explain\n`),process.exit(1));let r=Ir(),i=wr(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
607
+ `);return}if(i){Lr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
608
+ `),process.exit(2)),Rr(n),process.exit(2));let a=await Tr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Mr(a),null,2)+`
609
+ `),process.exit(a.kind===`ok`?0:2)),Nr(n,a),process.exit(a.kind===`ok`?0:2)})}function Mr(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 Nr(e,t){t.kind===`ok`?Lr(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${Br(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${zr(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${Br(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?``: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 Ir(){let e=process.cwd();return{cwd:e,hasFile:t=>L(F(e,t))}}function Lr(e,t,n,r=!1){let i=Br(e.trim(),200),a=r?`AI-generated — verify before applying`:Vr(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${zr(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${zr(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${zr(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${zr(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
610
+ `)}function Rr(e){let t=Br(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
600
611
 
601
612
  1. Check the framework docs for the error keywords:
602
613
  https://kickjs.app/
@@ -608,10 +619,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
608
619
  3. File an issue with the error text:
609
620
  https://github.com/forinda/kick-js/issues/new
610
621
 
611
- `)}function or(e,t){return e.split(`
622
+ `)}function zr(e,t){return e.split(`
612
623
  `).map(e=>`${t}${e}`).join(`
613
- `)}function sr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function cr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function lr(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(ur),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(dr)}function ur(e){let t=P(e.entry);I(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=St(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)=>{t?process.kill(process.pid,t):process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function dr(e){let t=process.cwd(),n=fr(t)??ut(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(I(i))try{let e=L(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,z(i,JSON.stringify(o,null,2)+`
614
- `,`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 fr(e){let t=P(e,`package.json`);if(!I(t))return null;try{let e=L(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function pr(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);I(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=hr(t,`tsx`);r||(console.error(`\n Error: tsx not found. Install it: ${h(t)} add -D tsx\n`),process.exit(1));let i=mr(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=xt(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function mr(e,t){return`
624
+ `)}function Br(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Vr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Hr(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(Ur),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(Wr)}function Ur(e){let t=F(e.entry);L(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=Nt(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)=>{t?process.kill(process.pid,t):process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Wr(e){let t=process.cwd(),n=Gr(t)??xt(t),r=e.name??n,i=e.global?F(process.env.HOME??`.`,`.mcp.json`):F(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(L(i))try{let e=R(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,B(i,JSON.stringify(o,null,2)+`
625
+ `,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${r}" to ${i}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function Gr(e){let t=F(e,`package.json`);if(!L(t))return null;try{let e=R(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Kr(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=F(t,e.entry);L(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Jr(t,`tsx`);r||(console.error(`\n Error: tsx not found. Install it: ${g(t)} add -D tsx\n`),process.exit(1));let i=qr(n,e.entry),a=N(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Mt(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function qr(e,t){return`
615
626
  import 'reflect-metadata'
616
627
 
617
628
  // Prevent bootstrap() from starting the HTTP server
@@ -636,7 +647,7 @@ try {
636
647
 
637
648
  // Load entry to trigger decorator registration
638
649
  try {
639
- await import('${V(e).href}')
650
+ await import('${H(e).href}')
640
651
  } catch (err) {
641
652
  console.warn(' Warning: ' + err.message)
642
653
  console.warn(' Container may be partially initialized.\\n')
@@ -665,46 +676,46 @@ server.on('exit', () => {
665
676
  console.log('\\n Goodbye!\\n')
666
677
  process.exit(0)
667
678
  })
668
- `}function hr(e,t){for(let n of yn(e)){let e=M(n,t);if(I(e))return e}return null}function gr(e,t){let n=RegExp(`^\\s*${_(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]!==`
679
+ `}function Jr(e,t){for(let n of jn(e)){let e=N(n,t);if(L(e))return e}return null}function Yr(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]!==`
669
680
  `;)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]===`
670
- `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function _r(e,t){let n=ne(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=gr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${_(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 vr(e){let{name:n,modulesDir:r,force:i}=e,a=e.pluralize===!0,o=C(n),l=x(n),u=a?fe(o):o;u!==o&&!await s(M(r,u))&&await s(M(r,o))&&(u=o);let d=M(r,u);if(!await s(d)){console.log(`\n Module not found: ${d}\n`);return}if(!i&&!await c({message:p.red(`Delete module '${u}' at ${d}? This cannot be undone.`),initialValue:!1})){console.log(`
681
+ `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function Xr(e,t){let n=re(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Yr(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 Zr(e){let{name:n,modulesDir:r,force:i}=e,a=e.pluralize===!0,o=C(n),l=S(n),u=a?pe(o):o;u!==o&&!await s(N(r,u))&&await s(N(r,o))&&(u=o);let d=N(r,u);if(!await s(d)){console.log(`\n Module not found: ${d}\n`);return}if(!i&&!await c({message:p.red(`Delete module '${u}' at ${d}? This cannot be undone.`),initialValue:!1})){console.log(`
671
682
  Cancelled.
672
- `);return}await vt(d,{recursive:!0,force:!0}),console.log(` Deleted: ${d}`);let f=M(r,`index.ts`);if(await s(f)){let e=await B(f,`utf-8`),n=e,r=RegExp(`^import\\s*\\{\\s*${_(l)}Module\\s*\\}\\s*from\\s*['"][^'"]*${_(u)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(r,``),e=_r(e,l),e=e.replace(/\n{3,}/g,`
683
+ `);return}await kt(d,{recursive:!0,force:!0}),console.log(` Deleted: ${d}`);let f=N(r,`index.ts`);if(await s(f)){let e=await V(f,`utf-8`),n=e,r=RegExp(`^import\\s*\\{\\s*${v(l)}Module\\s*\\}\\s*from\\s*['"][^'"]*${v(u)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(r,``),e=Xr(e,l),e=e.replace(/\n{3,}/g,`
673
684
 
674
- `),e!==n&&(await t(f,e),console.log(` Unregistered: ${l}Module from ${f}`))}console.log(`\n Module '${u}' removed.\n`)}function yr(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(`--pluralize`,`The module folder is pluralized (users/ for user)`).option(`--no-pluralize`,`The module folder is the name as typed (the default)`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await E(process.cwd()),r=w(n),i=t.modulesDir??r.dir??`src/modules`,a=T(t.pluralize,r);for(let n of e)await vr({name:n,modulesDir:P(i),force:t.force,pluralize:a})})}function br(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 xr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Sr(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=D(process.cwd()),n=await E(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-DSgKyJSD.mjs`),{builtinCliPlugins:t}=await import(`./builtins-BWtf5CEP.mjs`),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
685
+ `),e!==n&&(await t(f,e),console.log(` Unregistered: ${l}Module from ${f}`))}console.log(`\n Module '${u}' removed.\n`)}function Qr(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(`--pluralize`,`The module folder is pluralized (users/ for user)`).option(`--no-pluralize`,`The module folder is the name as typed (the default)`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await E(process.cwd()),r=w(n),i=t.modulesDir??r.dir??`src/modules`,a=T(t.pluralize,r);for(let n of e)await Zr({name:n,modulesDir:F(i),force:t.force,pluralize:a})})}function $r(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 ei(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function ti(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=O(process.cwd()),n=await E(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-C4ZvjEuo.mjs`),{builtinCliPlugins:t}=await import(`./builtins-DWzysfuk.mjs`),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
675
686
  Registered typegen plugins:
676
687
  `);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(`
677
688
  Disable one in kick.config.ts:
678
689
  `),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
679
- `);return}let r=br(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=xr(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 nt(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 it(a);let r=await K({cwd:t,config:n??null,silent:e.silent,check:e.check});if(e.check&&r.some(e=>e.status===`written`)&&process.exit(1),!e.check){let i=P(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await Ze(i,r,e.silent??!1)}}}catch(e){e instanceof rt?console.error(`
690
+ `);return}let r=$r(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=ei(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 pt(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 ht(a);let r=await kn({cwd:t,config:n??null,silent:e.silent,check:e.check});if(e.check&&r.some(e=>e.status===`written`)&&process.exit(1),!e.check){let i=F(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await ct(i,r,e.silent??!1)}}}catch(e){e instanceof mt?console.error(`
680
691
  `+e.message+`
681
- `):e instanceof ve?console.error(`
692
+ `):e instanceof ye?console.error(`
682
693
  `+e.message+`
683
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const Cr=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function wr(e,t){return typeof t==`number`?e.slice(0,t).split(`
684
- `).length:1}function Tr(e){let t=Ve(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(He(e)&&e.type===`MemberExpression`&&k(e.object)===`Scope`){let t=k(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function Er(e){let t=k(e);if(t)return{key:`id:${t}`,label:t};let n=Ve(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function Dr(e,t){let n=(e.body?.body??[]).find(e=>e.type===`MethodDefinition`&&e.kind===`constructor`)?.value?.params??[],r=[];for(let e of n){let n=e.type===`TSParameterProperty`?e.parameter:e,i=ot(e).map(Ue).find(e=>e?.name===`Inject`),a=null;if(i)a=Er(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=Er(e.typeName))}a&&r.push({...a,line:wr(t,e.start)})}return r}function Or(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,/* @__PURE__ */ new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,/* @__PURE__ */ new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=Et(t,n);if(r.errors.length>0)continue;e=r.program}catch{continue}for(let n of e.body??[]){let e=(n.type===`ExportNamedDeclaration`||n.type===`ExportDefaultDeclaration`)&&He(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(k(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(k(n.id),t)}st(e,e=>{if(e.type===`ClassDeclaration`){let a=k(e.id);if(!a)return;for(let o of ot(e)){let s=Ue(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:Dr(e,n)});return}if(Cr.has(s.name)){let o=Ge(ct(s.call),`scope`),c=o?Tr(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:Dr(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!He(a)||a.type!==`MemberExpression`)return;let o=k(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=Er(s[0]);c&&i(c.key,s.length>=3?Tr(s[2]):`singleton`)})}let o=e=>(n.get(e)?.size??0)<=1,s=(e,n)=>{let r=t.get(e);return r?.size===1&&r.has(n)},c=[];for(let e of r)if(o(e.name)&&s(`id:${e.name}`,`singleton`))for(let t of e.params){if(t.key.startsWith(`id:`)&&!o(t.label)||!s(t.key,`request`))continue;let n=e.kind===`controller`?`@Controller() is always SINGLETON, so inject ${t.label} with @Autowired() instead of the constructor.`:`Give ${e.name} TRANSIENT or REQUEST scope, or inject ${t.label} with @Autowired() instead of the constructor.`;c.push({file:e.file,line:t.line,parent:e.name,dependency:t.label,message:`${e.name} (SINGLETON) injects REQUEST-scoped ${t.label} through its constructor — the first request that resolves it answers 500. ${n}`})}return c}function kr(e){let t=[];if(!I(e))return t;let n=R(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(...kr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Ar(e){try{return L(e,`utf-8`)}catch{return``}}const jr=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Mr(e,t){let n=Ar(M(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(jr.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 Nr(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 Pr(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 Fr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Ir(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 Lr(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 Rr(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 zr(e){let t=kr(M(e,`src`)).map(e=>Ar(e)),n=[],r=Mr(e,t);r&&n.push(r);let i=Nr(t);i&&n.push(i);let a=Pr(t);a&&n.push(a);let o=Fr();o&&n.push(o);let s=Ir(t);return s&&n.push(s),n.push(Lr(t)),n.push(Rr(t)),n}function Br(e){let t=Or(kr(M(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:N(e,t).split(`\\`).join(`/`),source:Ar(t)})));return t.length===0?[{severity:`INFO`,message:`No REQUEST-scoped dependency injected into a singleton`}]:t.map(e=>({severity:`CRITICAL`,message:`${e.file}:${e.line} ${e.message}`}))}function Vr(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).option(`--di`,`Find REQUEST-scoped dependencies injected into singletons`).action(e=>{if(!e.deploy&&!e.di){console.log(`
694
+ `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const ni=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function ri(e,t){return typeof t==`number`?e.slice(0,t).split(`
695
+ `).length:1}function ii(e){let t=Qe(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if($e(e)&&e.type===`MemberExpression`&&A(e.object)===`Scope`){let t=A(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function ai(e){let t=A(e);if(t)return{key:`id:${t}`,label:t};let n=Qe(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function oi(e,t){let n=(e.body?.body??[]).find(e=>e.type===`MethodDefinition`&&e.kind===`constructor`)?.value?.params??[],r=[];for(let e of n){let n=e.type===`TSParameterProperty`?e.parameter:e,i=_t(e).map(et).find(e=>e?.name===`Inject`),a=null;if(i)a=ai(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=ai(e.typeName))}a&&r.push({...a,line:ri(t,e.start)})}return r}function si(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,/* @__PURE__ */ new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,/* @__PURE__ */ new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=Lt(t,n);if(r.errors.length>0)continue;e=r.program}catch{continue}for(let n of e.body??[]){let e=(n.type===`ExportNamedDeclaration`||n.type===`ExportDefaultDeclaration`)&&$e(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(A(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(A(n.id),t)}vt(e,e=>{if(e.type===`ClassDeclaration`){let a=A(e.id);if(!a)return;for(let o of _t(e)){let s=et(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:oi(e,n)});return}if(ni.has(s.name)){let o=nt(yt(s.call),`scope`),c=o?ii(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:oi(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!$e(a)||a.type!==`MemberExpression`)return;let o=A(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=ai(s[0]);c&&i(c.key,s.length>=3?ii(s[2]):`singleton`)})}let o=e=>(n.get(e)?.size??0)<=1,s=(e,n)=>{let r=t.get(e);return r?.size===1&&r.has(n)},c=[];for(let e of r)if(o(e.name)&&s(`id:${e.name}`,`singleton`))for(let t of e.params){if(t.key.startsWith(`id:`)&&!o(t.label)||!s(t.key,`request`))continue;let n=e.kind===`controller`?`@Controller() is always SINGLETON, so inject ${t.label} with @Autowired() instead of the constructor.`:`Give ${e.name} TRANSIENT or REQUEST scope, or inject ${t.label} with @Autowired() instead of the constructor.`;c.push({file:e.file,line:t.line,parent:e.name,dependency:t.label,message:`${e.name} (SINGLETON) injects REQUEST-scoped ${t.label} through its constructor — the first request that resolves it answers 500. ${n}`})}return c}function ci(e){let t=[];if(!L(e))return t;let n=z(e,{withFileTypes:!0});for(let r of n){let n=N(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...ci(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function li(e){try{return R(e,`utf-8`)}catch{return``}}const ui=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function di(e,t){let n=li(N(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(ui.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 fi(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 pi(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 mi(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function hi(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 gi(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 _i(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 vi(e){let t=ci(N(e,`src`)).map(e=>li(e)),n=[],r=di(e,t);r&&n.push(r);let i=fi(t);i&&n.push(i);let a=pi(t);a&&n.push(a);let o=mi();o&&n.push(o);let s=hi(t);return s&&n.push(s),n.push(gi(t)),n.push(_i(t)),n}function yi(e){let t=si(ci(N(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:P(e,t).split(`\\`).join(`/`),source:li(t)})));return t.length===0?[{severity:`INFO`,message:`No REQUEST-scoped dependency injected into a singleton`}]:t.map(e=>({severity:`CRITICAL`,message:`${e.file}:${e.line} ${e.message}`}))}function bi(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).option(`--di`,`Find REQUEST-scoped dependencies injected into singletons`).action(e=>{if(!e.deploy&&!e.di){console.log(`
685
696
  Usage: kick check [--deploy] [--di]
686
697
 
687
698
  Available checks:
688
699
  --deploy Audit for production readiness (security, config, best practices)
689
700
  --di Find REQUEST-scoped dependencies injected into singleton constructors
690
- `);return}let t=process.cwd();n(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let i=g();i.start(`Scanning project...`);let a=[...e.deploy?zr(t):[],...e.di?Br(t):[]];i.stop(`Scan complete`);let o={CRITICAL:0,WARNING:1,INFO:2};a.sort((e,t)=>o[e.severity]-o[t.severity]);for(let e of a)f.message(`${u(e.severity)} ${e.message}`);let s=a.filter(e=>e.severity===`CRITICAL`).length,c=a.filter(e=>e.severity===`WARNING`).length,l=a.filter(e=>e.severity===`INFO`).length,d=c===1?`warning`:`warnings`,m=[s>0?p.red(`${s} critical`):`${s} critical`,c>0?p.yellow(`${c} ${d}`):`${c} ${d}`,`${l} info`].join(`, `);s>0?(r(p.red(`${m} — fix critical issues before deploying`)),process.exit(1)):r(p.green(`${m} — looking good!`))})}const Hr=Symbol.for(`kickjs.handler.entryCapture`),Ur=Symbol.for(`kickjs.config.describe`);function Wr(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function Gr(e){let t=[];for(let n of e){let e=[n.description,n.list?`comma-separated list`:void 0].filter(Boolean);for(let n of e.length>0?e.join(` — `).split(/\r?\n/):[])t.push(`# ${n}`);n.required?t.push(`${n.name}=`):t.push(`# ${n.name}=${n.default===void 0?``:Wr(n.default)}`)}return t}function Kr(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
701
+ `);return}let t=process.cwd();n(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let i=_();i.start(`Scanning project...`);let a=[...e.deploy?vi(t):[],...e.di?yi(t):[]];i.stop(`Scan complete`);let o={CRITICAL:0,WARNING:1,INFO:2};a.sort((e,t)=>o[e.severity]-o[t.severity]);for(let e of a)f.message(`${u(e.severity)} ${e.message}`);let s=a.filter(e=>e.severity===`CRITICAL`).length,c=a.filter(e=>e.severity===`WARNING`).length,l=a.filter(e=>e.severity===`INFO`).length,d=c===1?`warning`:`warnings`,m=[s>0?p.red(`${s} critical`):`${s} critical`,c>0?p.yellow(`${c} ${d}`):`${c} ${d}`,`${l} info`].join(`, `);s>0?(r(p.red(`${m} — fix critical issues before deploying`)),process.exit(1)):r(p.green(`${m} — looking good!`))})}const xi=Symbol.for(`kickjs.handler.entryCapture`),Si=Symbol.for(`kickjs.config.describe`);function Ci(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function wi(e){let t=[];for(let n of e){let e=[n.description,n.list?`comma-separated list`:void 0].filter(Boolean);for(let n of e.length>0?e.join(` — `).split(/\r?\n/):[])t.push(`# ${n}`);n.required?t.push(`${n.name}=`):t.push(`# ${n.name}=${n.default===void 0?``:Ci(n.default)}`)}return t}function Ti(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
691
702
  # sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
692
703
  #
693
704
  # Uncommented variables are required. Commented ones are optional; the value shown
694
- # is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...Gr(e.env)].join(`
695
- `));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...Gr(n.vars)].join(`
705
+ # is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...wi(e.env)].join(`
706
+ `));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...wi(n.vars)].join(`
696
707
  `));return`${t.join(`
697
708
 
698
- `)}\n`}async function qr(e,t){let n=P(e,t);if(!I(n))throw Error(`${t} not found`);let r=P(e,`vite.config.ts`);if(!I(r))throw Error(`vite.config.ts not found — kick env example loads the app through it`);let{createRequire:i}=await import(`node:module`),a=i(P(e,`package.json`)),{createServer:o}=await import(V(a.resolve(`vite`)).href),s=globalThis,c;s[Hr]=e=>{c??=e},s[Ur]=!0,s[se]=`kick-env`;let l=await o({configFile:r,root:e,logLevel:`error`,appType:`custom`,server:{middlewareMode:!0,hmr:!1,watch:null}});try{await l.ssrLoadModule(n)}finally{delete s[Hr],delete s[Ur],delete s[se],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function Jr(e){e.command(`env`).description(`Work with the environment the app reads`).command(`example`).description(`Write .env.example from the env schema and declared settings sections`).option(`-e, --entry <file>`,`App entry that calls bootstrap()`,`src/index.ts`).option(`-o, --out <file>`,`File to write`,`.env.example`).option(`--check`,`Exit 1 if the file is missing or out of date, instead of writing it`).action(async e=>{let t=process.cwd(),n=P(t,e.out),r;try{r=Kr(await qr(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((I(n)?L(n,`utf8`):void 0)!==r&&(console.error(`\n ${e.out} is out of date — run \`kick env example\`.\n`),process.exit(1)),console.log(` ${e.out} is up to date.`)):(z(n,r),console.log(` Wrote ${e.out}`))})}function Yr(e){return e.optsWithGlobals().dryRun??!1}function Xr(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.
709
+ `)}\n`}async function Ei(e,t){let n=F(e,t);if(!L(n))throw Error(`${t} not found`);let r=F(e,`vite.config.ts`);if(!L(r))throw Error(`vite.config.ts not found — kick env example loads the app through it`);let{createRequire:i}=await import(`node:module`),a=i(F(e,`package.json`)),{createServer:o}=await import(H(a.resolve(`vite`)).href),s=globalThis,c;s[xi]=e=>{c??=e},s[Si]=!0,s[ce]=`kick-env`;let l=await o({configFile:r,root:e,logLevel:`error`,appType:`custom`,server:{middlewareMode:!0,hmr:!1,watch:null}});try{await l.ssrLoadModule(n)}finally{delete s[xi],delete s[Si],delete s[ce],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function Di(e){e.command(`env`).description(`Work with the environment the app reads`).command(`example`).description(`Write .env.example from the env schema and declared settings sections`).option(`-e, --entry <file>`,`App entry that calls bootstrap()`,`src/index.ts`).option(`-o, --out <file>`,`File to write`,`.env.example`).option(`--check`,`Exit 1 if the file is missing or out of date, instead of writing it`).action(async e=>{let t=process.cwd(),n=F(t,e.out),r;try{r=Ti(await Ei(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((L(n)?R(n,`utf8`):void 0)!==r&&(console.error(`\n ${e.out} is out of date — run \`kick env example\`.\n`),process.exit(1)),console.log(` ${e.out} is up to date.`)):(B(n,r),console.log(` Wrote ${e.out}`))})}function Oi(e){return e.optsWithGlobals().dryRun??!1}function ki(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.
699
710
  Direction defaults to \`modules.style\` from kick.config (or "define").
700
711
  --target define|class Override the migration direction.
701
712
  --apply Apply the changes (default: dry-run preview).
702
- --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=Yr(t)||!e.apply;o(n),e.experimental||(console.error(`
713
+ --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=Oi(t)||!e.apply;o(n),e.experimental||(console.error(`
703
714
  `+p.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
704
715
  The regex-based rewrite handles the shapes our templates produce.
705
716
  Hand-rolled modules with non-standard structures may be skipped.
706
717
  Always commit before running with --apply.
707
- `),process.exit(1));let r=await E(process.cwd()),i=w(r),a=P(e.modulesDir??i.dir??`src/modules`),s;e.target===`define`||e.target===`class`?s=e.target:e.target===void 0?s=i.style??`define`:(console.error(`\n ${p.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let c=p.dim(`→ ${s}`),l=n?p.dim(`(dry-run)`):p.bold(`(applying)`);console.log(`\n ${p.bold(`kick codemod modules`)} ${c} ${l}`),console.log(` modulesDir: ${p.dim(a)}\n`);let u=e.backup!==!1&&!n,d=await qt(a,{dryRun:n,target:s,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${p.green(`✓`)} backup: ${p.dim(e)}\n ${p.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${p.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,m=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${p.green(`✓`)} ${e.path}`);else{m++;let t=p.dim(`(${e.reason??`skipped`})`);console.log(` ${p.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${p.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=p.dim(`(${d.indexReason??`skipped`})`);console.log(` ${p.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${p.dim(`-`)} ${d.indexPath} ${p.dim(`(not found)`)}`);let h=n?p.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${p.bold(String(f))} migrated, ${p.bold(String(m))} skipped${h}\n`)})}function Zr(e){try{let t=JSON.parse(L(P(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function Qr(e,t=I,n=Zr(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=j(e);return(t(P(r,`pnpm-workspace.yaml`))||t(P(r,`package.json`)))&&t(P(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function $r(e,t,n,r){let i=Qr(t,n,r),a=e?.staticDir===!1?void 0:e?.staticDir??i.staticDir;return{entry:e?.entry??`src/serverless.ts`,outDir:e?.outDir??`dist/serverless`,staticDir:a,siteRoot:e?.siteRoot??i.siteRoot,publishDir:e?.publishDir??`dist/public`,apiPath:e?.apiPath??i.apiPath,external:e?.external??[`valibot`,`yup`],vercelRuntime:e?.vercelRuntime??`nodejs22.x`,include:e?.include??i.include??[]}}function ei(e,t,n={projectDir:`.`}){let r=[` path: '${t}/*',`,...n.preferStatic?[` preferStatic: true,`]:[],...n.includedFiles?.length?[` includedFiles: ${JSON.stringify(n.includedFiles)},`]:[]];return`import { fileURLToPath } from 'node:url'
718
+ `),process.exit(1));let r=await E(process.cwd()),i=w(r),a=F(e.modulesDir??i.dir??`src/modules`),s;e.target===`define`||e.target===`class`?s=e.target:e.target===void 0?s=i.style??`define`:(console.error(`\n ${p.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let c=p.dim(`→ ${s}`),l=n?p.dim(`(dry-run)`):p.bold(`(applying)`);console.log(`\n ${p.bold(`kick codemod modules`)} ${c} ${l}`),console.log(` modulesDir: ${p.dim(a)}\n`);let u=e.backup!==!1&&!n,d=await an(a,{dryRun:n,target:s,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${p.green(`✓`)} backup: ${p.dim(e)}\n ${p.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${p.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,m=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${p.green(`✓`)} ${e.path}`);else{m++;let t=p.dim(`(${e.reason??`skipped`})`);console.log(` ${p.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${p.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=p.dim(`(${d.indexReason??`skipped`})`);console.log(` ${p.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${p.dim(`-`)} ${d.indexPath} ${p.dim(`(not found)`)}`);let h=n?p.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${p.bold(String(f))} migrated, ${p.bold(String(m))} skipped${h}\n`)})}function Ai(e){try{let t=JSON.parse(R(F(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function ji(e,t=L,n=Ai(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=M(e);return(t(F(r,`pnpm-workspace.yaml`))||t(F(r,`package.json`)))&&t(F(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function Mi(e,t,n,r){let i=ji(t,n,r),a=e?.staticDir===!1?void 0:e?.staticDir??i.staticDir;return{entry:e?.entry??`src/serverless.ts`,outDir:e?.outDir??`dist/serverless`,staticDir:a,siteRoot:e?.siteRoot??i.siteRoot,publishDir:e?.publishDir??`dist/public`,apiPath:e?.apiPath??i.apiPath,external:e?.external??[`valibot`,`yup`],vercelRuntime:e?.vercelRuntime??`nodejs22.x`,include:e?.include??i.include??[]}}function Ni(e,t,n={projectDir:`.`}){let r=[` path: '${t}/*',`,...n.preferStatic?[` preferStatic: true,`]:[],...n.includedFiles?.length?[` includedFiles: ${JSON.stringify(n.includedFiles)},`]:[]];return`import { fileURLToPath } from 'node:url'
708
719
  import { handler } from '${e}'
709
720
 
710
721
  // Where the app's build files were packaged; the platform starts this
@@ -718,7 +729,7 @@ export const config = {
718
729
  ${r.join(`
719
730
  `)}
720
731
  }
721
- `}function ti(){return`import { fileURLToPath } from 'node:url'
732
+ `}function Pi(){return`import { fileURLToPath } from 'node:url'
722
733
  import { handler } from './server.mjs'
723
734
 
724
735
  // The app's build files are copied into this function at their project
@@ -728,11 +739,11 @@ process.env.KICK_APP_ROOT ??= fileURLToPath(new URL('./', import.meta.url))
728
739
  const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
729
740
 
730
741
  export default (req, res) => handler.node(req, res, requestContext())
731
- `}function ni(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function ri(e,t,n=!1){let r=[{handle:`filesystem`},{src:`^${e}/(.*)$`,dest:`/api`}];return n&&e!==``&&r.push({src:`^/_kick/(.*)$`,dest:`/api`}),t&&e!==``&&r.push({src:`^/(.*)$`,dest:`/index.html`}),r}function ii(e,t){let n;try{n=Et(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
732
- `).length,a=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(a);let n=e,o=n.expression;if(n.type===`Decorator`&&o?.type===`CallExpression`&&o.callee?.type===`Identifier`&&o.callee.name===`Cron`){let[e,a]=o.arguments??[],s=e?.type===`Literal`&&typeof e.value==`string`?e.value:e?.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value?.cooked:void 0;r.push({file:t,line:i(n.start??0),expression:s,timezone:a?.type===`ObjectExpression`&&a.properties.some(e=>(e.key?.name??e.key?.value)===`timezone`)})}for(let e in n)e!==`parent`&&a(n[e])};return a(n),r}function ai(e){let t=P(e,`src`);return I(t)?R(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=L(P(t,e),`utf-8`);return n.includes(`@Cron`)?ii(n,`src/${e}`):[]}):[]}function oi(e){let t=2166136261;for(let n of e.trim().replace(/\s+/g,` `))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(36)}function si(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=`${r.file}:${r.line}`;if(r.expression===void 0){t.push(`${e}: @Cron expression is not a string literal, so it has no Vercel cron entry`);continue}r.timezone&&t.push(`${e}: Vercel crons run in UTC — the timezone option is ignored there`);let i=r.expression.trim().replace(/\s+/g,` `);i.split(` `).length===5?n.set(oi(i),i):t.push(`${e}: Vercel crons need a five-field expression, so it has no Vercel cron entry`)}return{crons:[...n].map(([e,t])=>({path:`/_kick/cron/${e}`,schedule:t})),warnings:t}}function ci(e){let t=e=>{if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return;let n=e;for(let e of[`import`,`module`,`node`,`default`]){let r=t(n[e]);if(r)return r}},n=e.exports;return t(typeof n==`string`||Array.isArray(n)?n:n?.[`.`]??n)??e.module??e.main}async function li(e,t){let{createRequire:n}=await import(`node:module`),r=n(P(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=P(e,`node_modules`,t,`package.json`)}if(!I(i))throw Error(`${t} is not installed in this project. Run: ${h(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=ci(JSON.parse(L(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(V(P(j(i),a)).href)}async function ui(e,t,n){let r=P(e,t.entry);if(!I(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await li(e,`vite`),{default:a}=await li(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await li(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":P(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:P(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>fi(n,r?j(r):e)||t.external.includes(n)&&fi(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=P(e,t.outDir,`server.mjs`);return n(`bundled ${N(process.cwd(),c)}`),c}function di(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function fi(e,t,n=I){let r=di(e);if(!r)return!1;for(let e=t;;e=j(e)){if(n(P(e,`node_modules`,r,`package.json`)))return!1;if(j(e)===e)return!0}}function pi(e,t){let n=N(e,t).split(F)[0];return n!==void 0&&n.startsWith(`.`)}function mi(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function hi(e){try{return mt(e)}catch{return}}function gi(e,t){let n=t.filter(t=>!I(P(e,t)));if(n.length>0)throw Error(`${n.join(`, `)} not found — the function reads ${n.length===1?`it`:`them`} at runtime. Run the full build first (\`${ke(h(e),`build`)}\`), or fix \`deploy.include\`.`)}function _i(e,t){let n=t.projectRoot,r=()=>$r(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();gi(n,e.include);let i=await ui(n,e,t.log),a=P(n,e.siteRoot),o=ai(n);o.length>0&&t.log(`warning: ${o.length} @Cron job(s) found — Netlify has no cron trigger for them, so they will not run. Use Netlify scheduled functions, or deploy to Vercel or Workers.`);let s=P(a,`.netlify/v1/functions`);ft(s,{recursive:!0});let c=N(s,i).split(F).join(`/`),l=e=>e.split(F).join(`/`);z(P(s,`api.mjs`),ei(c,e.apiPath,{projectDir:l(N(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(N(s,P(n,e)));return hi(P(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${N(process.cwd(),P(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)ft(P(n,u),{recursive:!0}),t.log(`publish directory ready at ${N(process.cwd(),P(n,u))}`);else if(I(P(n,u))){let e=R(P(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=P(n,u,`_redirects`),r=I(t)?L(t,`utf-8`):``,i=mi(e).filter(e=>!r.includes(e));i.length>0&&z(t,`${r}${r&&!r.endsWith(`
742
+ `}function Fi(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function Ii(e,t,n=!1){let r=[{handle:`filesystem`},{src:`^${e}/(.*)$`,dest:`/api`}];return n&&e!==``&&r.push({src:`^/_kick/(.*)$`,dest:`/api`}),t&&e!==``&&r.push({src:`^/(.*)$`,dest:`/index.html`}),r}function Li(e,t){let n;try{n=Lt(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
743
+ `).length,a=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e))return e.forEach(a);let n=e,o=n.expression;if(n.type===`Decorator`&&o?.type===`CallExpression`&&o.callee?.type===`Identifier`&&o.callee.name===`Cron`){let[e,a]=o.arguments??[],s=e?.type===`Literal`&&typeof e.value==`string`?e.value:e?.type===`TemplateLiteral`&&e.expressions.length===0?e.quasis[0]?.value?.cooked:void 0;r.push({file:t,line:i(n.start??0),expression:s,timezone:a?.type===`ObjectExpression`&&a.properties.some(e=>(e.key?.name??e.key?.value)===`timezone`)})}for(let e in n)e!==`parent`&&a(n[e])};return a(n),r}function Ri(e){let t=F(e,`src`);return L(t)?z(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=R(F(t,e),`utf-8`);return n.includes(`@Cron`)?Li(n,`src/${e}`):[]}):[]}function zi(e){let t=2166136261;for(let n of e.trim().replace(/\s+/g,` `))t^=n.codePointAt(0),t=Math.imul(t,16777619)>>>0;return t.toString(36)}function Bi(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=`${r.file}:${r.line}`;if(r.expression===void 0){t.push(`${e}: @Cron expression is not a string literal, so it has no Vercel cron entry`);continue}r.timezone&&t.push(`${e}: Vercel crons run in UTC — the timezone option is ignored there`);let i=r.expression.trim().replace(/\s+/g,` `);i.split(` `).length===5?n.set(zi(i),i):t.push(`${e}: Vercel crons need a five-field expression, so it has no Vercel cron entry`)}return{crons:[...n].map(([e,t])=>({path:`/_kick/cron/${e}`,schedule:t})),warnings:t}}function Vi(e){let t=e=>{if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return;let n=e;for(let e of[`import`,`module`,`node`,`default`]){let r=t(n[e]);if(r)return r}},n=e.exports;return t(typeof n==`string`||Array.isArray(n)?n:n?.[`.`]??n)??e.module??e.main}async function Hi(e,t){let{createRequire:n}=await import(`node:module`),r=n(F(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=F(e,`node_modules`,t,`package.json`)}if(!L(i))throw Error(`${t} is not installed in this project. Run: ${g(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=Vi(JSON.parse(R(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(H(F(M(i),a)).href)}async function Ui(e,t,n){let r=F(e,t.entry);if(!L(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await Hi(e,`vite`),{default:a}=await Hi(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await Hi(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":F(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:F(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>Gi(n,r?M(r):e)||t.external.includes(n)&&Gi(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=F(e,t.outDir,`server.mjs`);return n(`bundled ${P(process.cwd(),c)}`),c}function Wi(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function Gi(e,t,n=L){let r=Wi(e);if(!r)return!1;for(let e=t;;e=M(e)){if(n(F(e,`node_modules`,r,`package.json`)))return!1;if(M(e)===e)return!0}}function Ki(e,t){let n=P(e,t).split(I)[0];return n!==void 0&&n.startsWith(`.`)}function qi(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function Ji(e){try{return Tt(e)}catch{return}}function Yi(e,t){let n=t.filter(t=>!L(F(e,t)));if(n.length>0)throw Error(`${n.join(`, `)} not found — the function reads ${n.length===1?`it`:`them`} at runtime. Run the full build first (\`${Ae(g(e),`build`)}\`), or fix \`deploy.include\`.`)}function Xi(e,t){let n=t.projectRoot,r=()=>Mi(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();Yi(n,e.include);let i=await Ui(n,e,t.log),a=F(n,e.siteRoot),o=Ri(n);o.length>0&&t.log(`warning: ${o.length} @Cron job(s) found — Netlify has no cron trigger for them, so they will not run. Use Netlify scheduled functions, or deploy to Vercel or Workers.`);let s=F(a,`.netlify/v1/functions`);Ct(s,{recursive:!0});let c=P(s,i).split(I).join(`/`),l=e=>e.split(I).join(`/`);B(F(s,`api.mjs`),Ni(c,e.apiPath,{projectDir:l(P(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(P(s,F(n,e)));return Ji(F(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${P(process.cwd(),F(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)Ct(F(n,u),{recursive:!0}),t.log(`publish directory ready at ${P(process.cwd(),F(n,u))}`);else if(L(F(n,u))){let e=z(F(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=F(n,u,`_redirects`),r=L(t)?R(t,`utf-8`):``,i=qi(e).filter(e=>!r.includes(e));i.length>0&&B(t,`${r}${r&&!r.endsWith(`
733
744
  `)?`
734
745
  `:``}${i.join(`
735
- `)}\n`)}}let d=P(a,`netlify.toml`);if(I(d)){let e=ni(L(d,`utf-8`)),r=N(a,P(n,u)).split(F).join(`/`);e!==void 0&&e!==r&&t.log(`warning: netlify.toml publishes "${e}", but this build fills "${r}". Update netlify.toml, or set \`deploy.publishDir\` / \`deploy.staticDir\` to match.`)}}),e.command(`build:vercel`).description(`Bundle the serverless entry and write .vercel/output (Build Output API v3)`).action(async()=>{let e=r();gi(n,e.include);let i=await ui(n,e,t.log),a=P(n,e.siteRoot),o=e.staticDir?P(n,e.staticDir):void 0,s=P(a,`.vercel/output`),c=P(s,`functions/api.func`);pt(s,{recursive:!0,force:!0}),ft(c,{recursive:!0}),dt(i,P(c,`server.mjs`)),z(P(c,`index.mjs`),ti());for(let t of e.include)dt(P(n,t),P(c,t),{recursive:!0});if(z(P(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!I(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);dt(o,P(s,`static`),{recursive:!0,filter:e=>!pi(o,e)})}let{crons:l,warnings:u}=si(ai(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:ri(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};z(P(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${N(process.cwd(),s)}`),l.length>0&&t.log(`${l.length} cron schedule(s) written. Set CRON_SECRET in the Vercel project — the trigger is not mounted without it.`)})}const vi=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=A.resolve(e.cwd,`kick.config.ts`);if(!I(t))return null;let n=await E(e.cwd);if(!n?.assetMap)return null;let r=We(n.assetMap,e.cwd);return r.count===0?null:et(r)}}),yi="/* 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 bi(e,t,n,r={}){if(e.length===0)return`${yi}
746
+ `)}\n`)}}let d=F(a,`netlify.toml`);if(L(d)){let e=Fi(R(d,`utf-8`)),r=P(a,F(n,u)).split(I).join(`/`);e!==void 0&&e!==r&&t.log(`warning: netlify.toml publishes "${e}", but this build fills "${r}". Update netlify.toml, or set \`deploy.publishDir\` / \`deploy.staticDir\` to match.`)}}),e.command(`build:vercel`).description(`Bundle the serverless entry and write .vercel/output (Build Output API v3)`).action(async()=>{let e=r();Yi(n,e.include);let i=await Ui(n,e,t.log),a=F(n,e.siteRoot),o=e.staticDir?F(n,e.staticDir):void 0,s=F(a,`.vercel/output`),c=F(s,`functions/api.func`);wt(s,{recursive:!0,force:!0}),Ct(c,{recursive:!0}),St(i,F(c,`server.mjs`)),B(F(c,`index.mjs`),Pi());for(let t of e.include)St(F(n,t),F(c,t),{recursive:!0});if(B(F(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!L(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);St(o,F(s,`static`),{recursive:!0,filter:e=>!Ki(o,e)})}let{crons:l,warnings:u}=Bi(Ri(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:Ii(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};B(F(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${P(process.cwd(),s)}`),l.length>0&&t.log(`${l.length} cron schedule(s) written. Set CRON_SECRET in the Vercel project — the trigger is not mounted without it.`)})}const Zi=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=j.resolve(e.cwd,`kick.config.ts`);if(!L(t))return null;let n=await E(e.cwd);if(!n?.assetMap)return null;let r=tt(n.assetMap,e.cwd);return r.count===0?null:dt(r)}}),Qi="/* 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 $i(e,t,n,r={}){if(e.length===0)return`${Qi}
736
747
  // (no routes discovered yet — annotate a controller method with
737
748
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
738
749
  declare global {
@@ -749,15 +760,15 @@ declare global {
749
760
 
750
761
  /** Empty until the first route exists — see kick typegen. */
751
762
  export const kickRpc = {} as const
752
- `;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ 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=wi(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'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${N(process.cwd(),i.filePath)} but not exported, so the generated types can't import it — ${o} is typed as ${t}. Export it (\`export const ${e.identifier} = ...\`) to type ctx.${o}.`:`${n}: ${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??Si(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=Ci(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${xi(e)}`,` }`)}n.push(` }`),l.push(n.join(`
763
+ `;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ 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=ra(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'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${P(process.cwd(),i.filePath)} but not exported, so the generated types can't import it — ${o} is typed as ${t}. Export it (\`export const ${e.identifier} = ...\`) to type ctx.${o}.`:`${n}: ${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??ta(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=na(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${ea(e)}`,` }`)}n.push(` }`),l.push(n.join(`
753
764
  `))}let u=[],d=/* @__PURE__ */ new Set,f=/* @__PURE__ */ new Set;i.has(`Named`)&&r.onWarn?.(`controller class 'Named' collides with the reserved KickRoutes.Named route-name map — its interface declaration-merges into it. Rename the controller.`),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}`;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.`):(d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`))}let p=[` interface Api {`,...u,` }`].join(`
754
765
  `);l.push(p);let m=[];for(let[e,t]of i)for(let n of t)f.has(`${e}.${n.method}`)&&m.push(` '${e}.${n.method}': ${e}['${n.method}']`);l.push([` interface Named {`,...m,` }`].join(`
755
- `));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=Di(e);if(g.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}g.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&&h.push(` ${n}: {\n${i.join(`
766
+ `));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=oa(e);if(g.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}g.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&&h.push(` ${n}: {\n${i.join(`
756
767
  `)}\n },`)}let _=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...h,`} as const`].join(`
757
- `),v=[],y=/* @__PURE__ */ new Map;for(let t of e)y.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=y.get(e),i=Ei(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;v.push(`import type { ${a} } from '${i}'`)}let b=v.length>0?v.join(`
768
+ `),v=[],y=/* @__PURE__ */ new Map;for(let t of e)y.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=y.get(e),i=aa(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;v.push(`import type { ${a} } from '${i}'`)}let b=v.length>0?v.join(`
758
769
  `)+`
759
- `:``,x=Ti(a)+b,S=l.join(`
760
- `);return`${yi}${x}
770
+ `:``,x=ia(a)+b,S=l.join(`
771
+ `);return`${Qi}${x}
761
772
  declare global {
762
773
  // eslint-disable-next-line @typescript-eslint/no-namespace
763
774
  namespace KickRoutes {
@@ -769,18 +780,18 @@ ${S}
769
780
  }
770
781
 
771
782
  ${_}
772
- `}function xi(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Si(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; cursor?: string }`}function Ci(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 wi(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Ei(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 Ti(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(`
783
+ `}function ea(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function ta(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; cursor?: string }`}function na(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 ra(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=aa(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 ia(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(`
773
784
  `)+`
774
- `}function Ei(e,t,n){if(e===null)return`unknown`;let r=j(n);if(e===``){let e=N(r,t).split(F).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=j(t),a=P(i,e),o=N(r,a).split(F).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function Di(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 Oi=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:ki(e),cwd:e.cwd,envFile:Ai(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=A.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return bi(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function ki(e){return A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ai(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const ji=`@typescript/typescript6`;function Mi(e){return typeof e?.createProgram==`function`}function Ni(e){if(Mi(e.typescript))return{api:e.typescript,source:`typescript`};if(Mi(e.ts6))return{api:e.ts6,source:ji};let t=`Install it in the project:\n ${h()} add -D ${ji}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
775
- 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 '${ji}' resolved from this project.\n ${t}`)}async function Pi(e){let t=lt(M(e,`package.json`)),n=async e=>{try{return await import(V(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(ji)]);return Ni({typescript:Fi(r),ts6:Fi(i)}).api}function Fi(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Ii=Symbol(`kick/client: expansion budget exhausted`);var Li=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=/* @__PURE__ */ new Map;inProgress=/* @__PURE__ */ new Map;jsonInProgress=/* @__PURE__ */ 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;let t=this.blocks.length,n=this.nextName,r=new Set(this.hoistedByType.keys());try{return this.render(e,0)}catch(e){if(e!==Ii)throw e;this.blocks.length=t,this.nextName=n;for(let e of this.hoistedByType.keys())r.has(e)||this.hoistedByType.delete(e);return this.opts.onWarn?.(`expansion abandoned after ${this.budget} depth hoists — emitting 'unknown'. Either the response type never repeats (a generic that grows at every level) or it nests more distinct types than the budget allows; raising maxDepth hoists fewer of them. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t,n=!0){let r=this.ts.TypeFlags;if(n){let t=this.hoistedByType.get(e);if(t)return t}if(t>this.maxDepth&&!this.isLeaf(e))return this.hoistDeep(e);if(e.flags&(r.String|r.Number|r.Boolean|r.BigInt|r.ESSymbol)||e.flags&(r.Any|r.Unknown|r.Never|r.Void|r.Undefined|r.Null)||e.isLiteral()||e.flags&r.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 i=this.arrayElement(e);if(i){let e=this.render(i.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return i.readonly?`readonly ${n}`:n}let a=this.toJsonType(e);if(a){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(a,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&r.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}isLeaf(e){let t=this.ts.TypeFlags;return(e.flags&(t.String|t.Number|t.Boolean|t.BigInt|t.ESSymbol|t.Any|t.Unknown|t.Never|t.Void|t.Undefined|t.Null|t.BooleanLiteral))!==0||e.isLiteral()}hoistDeep(e){if(++this.truncations>this.budget)throw Ii;let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=this.isPlainObject(e)?`interface ${t} {\n${this.members(e,0,` `)}\n}`:`type ${t} = ${this.render(e,0,!1)}`,t}isPlainObject(e){return(e.flags&this.ts.TypeFlags.Object)!==0&&!e.isUnionOrIntersection()&&!this.isTuple(e)&&!this.arrayElement(e)&&!this.toJsonType(e)&&!this.isLibType(e)}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=`
785
+ `}function aa(e,t,n){if(e===null)return`unknown`;let r=M(n);if(e===``){let e=P(r,t).split(I).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(t),a=F(i,e),o=P(r,a).split(I).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function oa(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 sa=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:ca(e),cwd:e.cwd,envFile:la(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=j.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return $i(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function ca(e){return j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function la(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const ua=`@typescript/typescript6`;function da(e){return typeof e?.createProgram==`function`}function fa(e){if(da(e.typescript))return{api:e.typescript,source:`typescript`};if(da(e.ts6))return{api:e.ts6,source:ua};let t=`Install it in the project:\n ${g()} add -D ${ua}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
786
+ 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 '${ua}' resolved from this project.\n ${t}`)}async function pa(e){let t=bt(N(e,`package.json`)),n=async e=>{try{return await import(H(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(ua)]);return fa({typescript:ma(r),ts6:ma(i)}).api}function ma(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const ha=Symbol(`kick/client: expansion budget exhausted`);var ga=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=/* @__PURE__ */ new Map;inProgress=/* @__PURE__ */ new Map;jsonInProgress=/* @__PURE__ */ 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;let t=this.blocks.length,n=this.nextName,r=new Set(this.hoistedByType.keys());try{return this.render(e,0)}catch(e){if(e!==ha)throw e;this.blocks.length=t,this.nextName=n;for(let e of this.hoistedByType.keys())r.has(e)||this.hoistedByType.delete(e);return this.opts.onWarn?.(`expansion abandoned after ${this.budget} depth hoists — emitting 'unknown'. Either the response type never repeats (a generic that grows at every level) or it nests more distinct types than the budget allows; raising maxDepth hoists fewer of them. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t,n=!0){let r=this.ts.TypeFlags;if(n){let t=this.hoistedByType.get(e);if(t)return t}if(t>this.maxDepth&&!this.isLeaf(e))return this.hoistDeep(e);if(e.flags&(r.String|r.Number|r.Boolean|r.BigInt|r.ESSymbol)||e.flags&(r.Any|r.Unknown|r.Never|r.Void|r.Undefined|r.Null)||e.isLiteral()||e.flags&r.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 i=this.arrayElement(e);if(i){let e=this.render(i.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return i.readonly?`readonly ${n}`:n}let a=this.toJsonType(e);if(a){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(a,t)}finally{this.jsonInProgress.delete(e)}}return this.isLibType(e)?this.renderLibType(e,t):e.flags&r.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}isLeaf(e){let t=this.ts.TypeFlags;return(e.flags&(t.String|t.Number|t.Boolean|t.BigInt|t.ESSymbol|t.Any|t.Unknown|t.Never|t.Void|t.Undefined|t.Null|t.BooleanLiteral))!==0||e.isLiteral()}hoistDeep(e){if(++this.truncations>this.budget)throw ha;let t=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=this.isPlainObject(e)?`interface ${t} {\n${this.members(e,0,` `)}\n}`:`type ${t} = ${this.render(e,0,!1)}`,t}isPlainObject(e){return(e.flags&this.ts.TypeFlags.Object)!==0&&!e.isUnionOrIntersection()&&!this.isTuple(e)&&!this.arrayElement(e)&&!this.toJsonType(e)&&!this.isLibType(e)}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=`
776
787
  `){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===`
777
788
  `?`
778
- `: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 Ri=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],zi=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Bi(e){return wt(`sha1`).update(e).digest(`hex`)}function Vi(e){let t=wt(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
779
- `));for(let n of Ri){let r=M(e.projectDir,n);if(I(r))try{t.update(L(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!zi.test(n)){t.update(n);try{t.update(L(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Hi(e){try{let t=await Pi(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(M(e.projectDir,`tsconfig.json`),{},n);return r?Vi({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 Ui(e){let t=await Pi(e.compilerFrom??e.projectDir),n=M(j(e.routesFile),`__kick_client_probe__.ts`),r=Ki(e.routesFile,e.keys),i=Yi(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.`);Wi(t,i,e.routesFile);let s=qi(t,i,o,e.keys),c=null,l=new Li(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=/* @__PURE__ */ 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===Gi(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);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.`):(c=r,u.set(r,l.expand(d)),c=null)}return{entries:u,hoisted:l.hoisted()}}function Wi(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(`
780
- `);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 Gi(e){return`_K${e}`}function Ki(e,t){let n=`./`+ut(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Gi(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
789
+ `: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 _a=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],va=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function ya(e){return Ft(`sha1`).update(e).digest(`hex`)}function ba(e){let t=Ft(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
790
+ `));for(let n of _a){let r=N(e.projectDir,n);if(L(r))try{t.update(R(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!va.test(n)){t.update(n);try{t.update(R(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function xa(e){try{let t=await pa(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(N(e.projectDir,`tsconfig.json`),{},n);return r?ba({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 Sa(e){let t=await pa(e.compilerFrom??e.projectDir),n=N(M(e.routesFile),`__kick_client_probe__.ts`),r=Ta(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.`);Ca(t,i,e.routesFile);let s=Ea(t,i,o,e.keys),c=null,l=new ga(t,a,i,{maxDepth:e.maxDepth,onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=/* @__PURE__ */ 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===wa(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);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.`):(c=r,u.set(r,l.expand(d)),c=null)}return{entries:u,hoisted:l.hoisted()}}function Ca(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(`
791
+ `);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 wa(e){return`_K${e}`}function Ta(e,t){let n=`./`+xt(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${wa(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
781
792
  `)+`
782
- `}function qi(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ 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(Gi(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Ji(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=R(t).filter(e=>e.endsWith(`.ts`)).map(e=>M(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function Yi(e,t,n,r){let i=M(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
783
- `))}},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:[...Ji(o.fileNames,j(n)),n],options:o.options,host:s})}const Xi=`/* eslint-disable */
793
+ `}function Ea(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ 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(wa(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Da(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=z(t).filter(e=>e.endsWith(`.ts`)).map(e=>N(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function Oa(e,t,n,r){let i=N(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
794
+ `))}},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:[...Da(o.fileNames,M(n)),n],options:o.options,host:s})}const ka=`/* eslint-disable */
784
795
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
785
796
  //
786
797
  // Self-contained: this file has no imports, so a frontend consumes it without
@@ -794,7 +805,7 @@ ${_}
794
805
  //
795
806
  // Written when \`kick dev\` starts, not on save — resolving these types builds a
796
807
  // full TypeScript program over the server. Re-run \`kick typegen\`.
797
- `;function Zi(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Xi}
808
+ `;function Aa(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${ka}
798
809
  // (no routes discovered yet — annotate a controller method with
799
810
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
800
811
  interface Api {}
@@ -811,7 +822,7 @@ export type { Api }
811
822
 
812
823
  `)+`
813
824
 
814
- `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Xi}
825
+ `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${ka}
815
826
  ${r}interface Api {
816
827
  ${i.join(`
817
828
  `)}
@@ -825,7 +836,7 @@ declare global {
825
836
  }
826
837
 
827
838
  export type { Api }
828
- `}const Qi=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,$i=`.kickjs/cache/client-map.sha1`,ea=(()=>{try{return lt(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function ta(e){try{if(!I(e))return null;let[t,n]=L(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function na(e){return`${pn}${Qi} */\n\n${e}\n`}function ra(e){try{return I(e)?L(e,`utf-8`):null}catch{return null}}async function ia(e){let t=A.resolve(e.cwd,Q);if(!I(t))return!1;try{await vt(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 aa(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function oa(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(I(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 sa=()=>({id:Qi,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!oa(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=/* @__PURE__ */ 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=aa(e.config),a=await Hi({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:ea}),o=ta(A.resolve(e.cwd,$i)),s=ra(A.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Bi(s))return ce()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=Zi(await Ui({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($i,`${a} ${Bi(na(t))}`),t}catch(t){let n=I(A.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):ce()&&e.log.info?.(r),n&&await ia(e),null}}});function ca(e,t,n=`zod`){if(!e)return null;let r=j(t),i=N(r,e.filePath).split(F).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
839
+ `}const ja=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,Ma=`.kickjs/cache/client-map.sha1`,Na=(()=>{try{return bt(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function Pa(e){try{if(!L(e))return null;let[t,n]=R(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Fa(e){return`${wn}${ja} */\n\n${e}\n`}function Ia(e){try{return L(e)?R(e,`utf-8`):null}catch{return null}}async function La(e){let t=j.resolve(e.cwd,Q);if(!L(t))return!1;try{await kt(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 Ra(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function za(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(L(j.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 Ba=()=>({id:ja,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!za(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:j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=/* @__PURE__ */ 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=Ra(e.config),a=await xa({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Na}),o=Pa(j.resolve(e.cwd,Ma)),s=Ia(j.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===ya(s))return le()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=Aa(await Sa({projectDir:e.cwd,routesFile:j.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(Ma,`${a} ${ya(Fa(t))}`),t}catch(t){let n=L(j.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):le()&&e.log.info?.(r),n&&await La(e),null}}});function Va(e,t,n=`zod`){if(!e)return null;let r=M(t),i=P(r,e.filePath).split(I).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
829
840
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
830
841
  // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
831
842
 
@@ -863,6 +874,6 @@ declare global {
863
874
  }
864
875
 
865
876
  export {}
866
- `}const la=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=da(e);if(t===!1)return null;let n=await e.getScanResult({root:ua(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 ca(n.env,i,r)}});function ua(e){return A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function da(e){return e.config?.typegen?.envFile}function fa(e){return A.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function pa(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:fa(e),cwd:e.cwd,envFile:pa(e)}}const ma=()=>({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 Je(t.classes,n,r)}}),ha=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className)),r=Qe(t.classes,t.tokens,t.injects,n);return $e(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),ga=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return $e(`ModuleToken`,Ke(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),_a=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return qe(t.pluginsAndAdapters)}}),va=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:at(t.contextKeys)}}),ya=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return tt(t.routeFlags)}}),ba={express:{subpath:`@forinda/kickjs/express`,typeName:`ExpressRuntimeTypes`},fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},xa=[O({name:`kick/init`,register:jt}),O({name:`kick/generate`,register:dn}),O({name:`kick/run`,register:kn}),O({name:`kick/info`,register:Pn}),O({name:`kick/inspect`,register:Un}),O({name:`kick/add`,register:Ne}),O({name:`kick/list`,register:Fe}),O({name:`kick/explain`,register:Qn}),O({name:`kick/mcp`,register:lr}),O({name:`kick/tinker`,register:pr}),O({name:`kick/remove`,register:yr}),O({name:`kick/typegen`,register:Sr}),O({name:`kick/check`,register:Vr}),O({name:`kick/doctor`,register:_e}),O({name:`kick/env-command`,register:Jr}),O({name:`kick/codemod`,register:Xr}),O({name:`kick/deploy`,register:_i}),O({name:`kick/registry`,typegens:[ma()]}),O({name:`kick/services`,typegens:[ha()]}),O({name:`kick/modules`,typegens:[ga()]}),O({name:`kick/plugins`,typegens:[_a()]}),O({name:`kick/context`,typegens:[va()]}),O({name:`kick/route-flags`,typegens:[ya()]}),O({name:`kick/assets`,typegens:[vi()]}),O({name:`kick/routes`,typegens:[Oi()]}),O({name:`kick/client`,typegens:[sa()]}),O({name:`kick/env`,typegens:[la()]}),O({name:`kick/runtime`,typegens:[{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??`express`;if(t!==`express`&&t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=ba[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(`
867
- `)}}]})];export{gn as applyDisableFilter,_n as n,Mt as r,K as runAllPluginTypegens,xa as t};
868
- //# sourceMappingURL=run-plugins-cqNounm7.mjs.map
877
+ `}const Ha=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Wa(e);if(t===!1)return null;let n=await e.getScanResult({root:Ua(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=j.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Va(n.env,i,r)}});function Ua(e){return j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Wa(e){return e.config?.typegen?.envFile}function Ga(e){return j.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ka(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ga(e),cwd:e.cwd,envFile:Ka(e)}}const qa=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=j.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return at(t.classes,n,r)}}),Ja=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className)),r=lt(t.classes,t.tokens,t.injects,n);return ut(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Ya=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return ut(`ModuleToken`,rt(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Xa=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return it(t.pluginsAndAdapters)}}),Za=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:gt(t.contextKeys)}}),Qa=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return ft(t.routeFlags)}}),$a={express:{subpath:`@forinda/kickjs/express`,typeName:`ExpressRuntimeTypes`},fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},eo=[k({name:`kick/init`,register:Ht}),k({name:`kick/generate`,register:Sn}),k({name:`kick/run`,register:Vn}),k({name:`kick/info`,register:Kn}),k({name:`kick/inspect`,register:nr}),k({name:`kick/add`,register:Ge}),k({name:`kick/runtime-swap`,register:vr}),k({name:`kick/list`,register:Fe}),k({name:`kick/explain`,register:jr}),k({name:`kick/mcp`,register:Hr}),k({name:`kick/tinker`,register:Kr}),k({name:`kick/remove`,register:Qr}),k({name:`kick/typegen`,register:ti}),k({name:`kick/check`,register:bi}),k({name:`kick/doctor`,register:ve}),k({name:`kick/env-command`,register:Di}),k({name:`kick/codemod`,register:ki}),k({name:`kick/deploy`,register:Xi}),k({name:`kick/registry`,typegens:[qa()]}),k({name:`kick/services`,typegens:[Ja()]}),k({name:`kick/modules`,typegens:[Ya()]}),k({name:`kick/plugins`,typegens:[Xa()]}),k({name:`kick/context`,typegens:[Za()]}),k({name:`kick/route-flags`,typegens:[Qa()]}),k({name:`kick/assets`,typegens:[Zi()]}),k({name:`kick/routes`,typegens:[sa()]}),k({name:`kick/client`,typegens:[Ba()]}),k({name:`kick/env`,typegens:[Ha()]}),k({name:`kick/runtime`,typegens:[{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??`express`;if(t!==`express`&&t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=$a[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(`
878
+ `)}}]})];export{Dn as applyDisableFilter,On as n,Ut as r,kn as runAllPluginTypegens,eo as t};
879
+ //# sourceMappingURL=run-plugins-9IDaa4U7.mjs.map