@forinda/kickjs-cli 8.9.0 → 8.10.1

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 (64) hide show
  1. package/README.md +2 -0
  2. package/dist/{agent-docs-DUB-1Z6Q.mjs → agent-docs-TdQs75ND.mjs} +70 -21
  3. package/dist/agent-docs-TdQs75ND.mjs.map +1 -0
  4. package/dist/{agent-docs-bVMPt2m5.mjs → agent-docs-uEhHT_Tq.mjs} +72 -23
  5. package/dist/{build-C30mBgw6.mjs → build-D90mecBH.mjs} +3 -3
  6. package/dist/{build-C30mBgw6.mjs.map → build-D90mecBH.mjs.map} +1 -1
  7. package/dist/{build-xQXbdDpw.mjs → build-xfLqm9dd.mjs} +2 -2
  8. package/dist/{builtins-CtpLZ4FY.mjs → builtins-C3BQ79nW.mjs} +2 -2
  9. package/dist/{builtins-DiWfXc-D.mjs → builtins-CNJXXYW-.mjs} +149 -153
  10. package/dist/cli.mjs +2 -2
  11. package/dist/config-BV6rXylg.mjs +13 -0
  12. package/dist/config-BV6rXylg.mjs.map +1 -0
  13. package/dist/config-CVuSVUvw.mjs +12 -0
  14. package/dist/{doctor-CnsnRW7T.mjs → doctor-a-UkOZYd.mjs} +35 -40
  15. package/dist/doctor-a-UkOZYd.mjs.map +1 -0
  16. package/dist/fullstack-BlNhq-tI.mjs +100 -0
  17. package/dist/fullstack-BlNhq-tI.mjs.map +1 -0
  18. package/dist/fullstack-Zk31eUT1.mjs +99 -0
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +2 -2
  21. package/dist/package-manager-BUDLqU4F.mjs +12 -0
  22. package/dist/package-manager-BUDLqU4F.mjs.map +1 -0
  23. package/dist/package-manager-Bk2uiXkV.mjs +11 -0
  24. package/dist/{plugin-Bs0soxrU.mjs → plugin-DDENlsHw.mjs} +2 -2
  25. package/dist/{plugin-BfdvW6_r.mjs → plugin-FOqPjQ0u.mjs} +2 -2
  26. package/dist/project-BBiJ64ya.mjs +114 -0
  27. package/dist/project-fa9FRWXx.mjs +115 -0
  28. package/dist/project-fa9FRWXx.mjs.map +1 -0
  29. package/dist/{project-root-LYOxQHXp.mjs → project-root-BMpUTIbO.mjs} +2 -2
  30. package/dist/{project-root-B9BrO1na.mjs → project-root-BZ1wVwrr.mjs} +3 -3
  31. package/dist/{project-root-B9BrO1na.mjs.map → project-root-BZ1wVwrr.mjs.map} +1 -1
  32. package/dist/{prompts-BEAqcbPT.mjs → prompts-C4g1xbsv.mjs} +2 -2
  33. package/dist/{prompts-BEAqcbPT.mjs.map → prompts-C4g1xbsv.mjs.map} +1 -1
  34. package/dist/{rolldown-runtime-Da-NDvKz.mjs → rolldown-runtime-D8pytGn4.mjs} +1 -1
  35. package/dist/{run-plugins-0AfIgIsZ.mjs → run-plugins-CeZS2Opt.mjs} +107 -106
  36. package/dist/run-plugins-CeZS2Opt.mjs.map +1 -0
  37. package/dist/{typegen-BzgWveE_.mjs → typegen-Cj5lp0gl.mjs} +5 -5
  38. package/dist/{typegen-BzgWveE_.mjs.map → typegen-Cj5lp0gl.mjs.map} +1 -1
  39. package/dist/{typegen-up-UkaNc.mjs → typegen-D9opCn2d.mjs} +4 -4
  40. package/dist/{types-ChFFRT8E.mjs → types-BqvSIAQz.mjs} +1 -1
  41. package/package.json +6 -6
  42. package/templates/base/files/README.md +17 -15
  43. package/templates/base/files/kick.config.ts +1 -1
  44. package/templates/feature-storage/feature.json +13 -0
  45. package/templates/feature-storage/files/_dot_env.example.append +6 -0
  46. package/templates/feature-storage/files/_dot_gitignore.append +2 -0
  47. package/templates/feature-storage/files/src/storage.ts +16 -0
  48. package/templates/template-inertia/files/src/client/app.css +1 -1
  49. package/templates/template-inertia/files/vite.client.config.ts +1 -1
  50. package/dist/agent-docs-DUB-1Z6Q.mjs.map +0 -1
  51. package/dist/config-YvIngROH.mjs +0 -12
  52. package/dist/config-ZHuFjsKI.mjs +0 -13
  53. package/dist/config-ZHuFjsKI.mjs.map +0 -1
  54. package/dist/doctor-CnsnRW7T.mjs.map +0 -1
  55. package/dist/fs-Bm2St4gk.mjs +0 -11
  56. package/dist/fs-BvGbbHY0.mjs +0 -12
  57. package/dist/fs-BvGbbHY0.mjs.map +0 -1
  58. package/dist/fullstack-B0g06sSQ.mjs +0 -96
  59. package/dist/fullstack-B0g06sSQ.mjs.map +0 -1
  60. package/dist/fullstack-CZ9XQYk-.mjs +0 -95
  61. package/dist/project-B_qDdkYQ.mjs +0 -113
  62. package/dist/project-B_qDdkYQ.mjs.map +0 -1
  63. package/dist/project-Bp-KfBNb.mjs +0 -112
  64. package/dist/run-plugins-0AfIgIsZ.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.9.0
2
+ * @forinda/kickjs-cli v8.10.1
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-Da-NDvKz.mjs";import{n as t,r as n,t as r}from"./fs-BvGbbHY0.mjs";import{a as i,c as a,d as o,i as s,l as c,n as l,o as u,r as d,s as f,t as p,u as m}from"./prompts-BEAqcbPT.mjs";import{A as h,C as g,D as _,E as v,F as y,M as b,N as ee,O as x,P as S,S as te,T as ne,_ as re,a as ie,b as ae,c as oe,f as se,g as ce,h as le,i as ue,j as de,k as fe,l as pe,m as me,p as he,r as ge,u as _e,v as ve,w as ye,x as be,y as xe}from"./doctor-CnsnRW7T.mjs";import{f as Se,l as Ce,o as we,r as Te,s as Ee,t as De}from"./project-B_qDdkYQ.mjs";import{a as Oe,c as ke,i as Ae,l as je,o as C,s as w,u as Me}from"./config-ZHuFjsKI.mjs";import{t as T}from"./project-root-B9BrO1na.mjs";import{n as E,t as Ne}from"./types-ChFFRT8E.mjs";import{t as Pe}from"./build-C30mBgw6.mjs";import{n as Fe}from"./agent-docs-DUB-1Z6Q.mjs";import{C as Ie,S as Le,_ as Re,a as ze,b as Be,c as Ve,d as He,f as Ue,g as We,h as Ge,i as Ke,l as qe,m as Je,o as Ye,p as Xe,r as Ze,s as Qe,t as $e,u as et,v as tt,w as nt,x as D,y as rt}from"./typegen-BzgWveE_.mjs";import{createRequire as it}from"node:module";import O,{basename as at,dirname as k,join as A,relative as j,resolve as M,sep as N}from"node:path";import{cpSync as ot,existsSync as P,mkdirSync as st,readFileSync as F,readdirSync as I,rmSync as ct,statSync as lt,writeFileSync as L}from"node:fs";import{copyFile as ut,mkdir as dt,readFile as R,readdir as ft,rm as pt,stat as mt,writeFile as z}from"node:fs/promises";import{fork as ht,spawn as gt,spawnSync as _t}from"node:child_process";import{createHash as vt}from"node:crypto";import{fileURLToPath as yt,pathToFileURL as B}from"node:url";import{parseSync as bt}from"oxc-parser";import{arch as xt,platform as St,release as Ct}from"node:os";const wt=[{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function Tt(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(`-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)=>{l(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await a({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=M(`.`),e=at(r)):r=M(t.directory||e),P(r)){let a=I(r);if(a.length>0){if(t.force)d.warn(`Clearing existing files in ${r}`);else if(n){d.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),i(`Aborted.`);return}else{d.warn(`Directory "${e}" is not empty:`);let t=a.slice(0,5);for(let e of t)d.message(` - ${e}`);if(a.length>5&&d.message(` ... and ${a.length-5} more`),!await p({message:m.red(`Remove all existing files and proceed?`),initialValue:!1})){i(`Aborted.`);return}}for(let e of a)ct(M(r,e),{recursive:!0,force:!0})}}let o=t.template;o||=n?`minimal`:await u({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 c=t.runtime;c||=n?`express`:await u({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 f=t.pm;f||=n?await Ce(void 0):await u({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let h=t.repo;h||=n?`inmemory`:await a({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Me(h);let g=t.schema;o===`inertia`&&(g&&g!==`zod`&&d.warn(`The inertia template uses zod — ignoring --schema ${g}.`),g=`zod`),g||=n?`zod`:await u({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(g)||(d.warn(`Unknown --schema "${g}", falling back to zod.`),g=`zod`);let _;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();_=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else _=n?[]:await s({message:`Select packages to include`,options:[...wt],required:!1});let v;v=t.git===void 0?n?!0:await p({message:`Initialize git repository?`,initialValue:!0}):t.git;let y;if(y=t.install===void 0?n?!0:await p({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){d.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),i(`Aborted.`);return}let{VITE_TEMPLATES:b,DEFAULT_VITE_TEMPLATE:ee}=await import(`./fullstack-B0g06sSQ.mjs`);if(t.viteTemplate!==void 0&&!b.some(e=>e.value===t.viteTemplate)){d.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${b.map(e=>e.value).join(`, `)}.`),i(`Aborted.`);return}let x=t.frontend===`vite`?`vite`:`kick`,S=t.viteTemplate??ee;if(o===`fullstack`&&!t.frontend&&!n&&(x=await u({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)`}]})),x===`vite`&&!t.viteTemplate&&!n&&(S=await u({message:`create-vite template`,options:b.map(e=>({value:e.value,label:e.label})),initialValue:ee})),o===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-B0g06sSQ.mjs`);await t({name:e,directory:r,packageManager:f,initGit:v,installDeps:y,schemaLib:g,runtime:c,packages:_,frontend:x,viteTemplate:S}),i(`Done! Next steps: ${m.cyan(`cd ${e} && ${f}${f===`pnpm`?` dev`:` run dev:server`}`)}`)}else await De({name:e,directory:r,packageManager:f,initGit:v,installDeps:y,template:o,defaultRepo:h,packages:_,schemaLib:g,runtime:c}),i(`Done! Next steps: ${m.cyan(`cd ${e} && ${f} dev`)}`)})}function Et(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 Ne(`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 Ne(`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 Ne(`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 Ne(`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-B9BrO1na.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 Dt(e){let{name:t,outDir:r}=e,i=S(t),a=y(t),o=[],s=A(r,`${i}.plugin.ts`);return await n(s,`import {
11
+ import{t as e}from"./rolldown-runtime-D8pytGn4.mjs";import{a as t,i as n,n as r,o as i,t as a}from"./package-manager-BUDLqU4F.mjs";import{a as o,c as s,d as c,i as l,l as u,n as d,o as f,r as p,s as m,t as h,u as g}from"./prompts-C4g1xbsv.mjs";import{A as _,C as v,D as y,E as b,F as x,M as ee,N as te,O as ne,P as S,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-a-UkOZYd.mjs";import{a as we,c as C,d as Te,f as Ee,l as De,o as Oe,s as w,u as ke}from"./config-BV6rXylg.mjs";import{o as Ae,r as je,s as Me,t as Ne,u as Pe}from"./project-fa9FRWXx.mjs";import{t as T}from"./project-root-BZ1wVwrr.mjs";import{n as E,t as Fe}from"./types-BqvSIAQz.mjs";import{t as Ie}from"./build-D90mecBH.mjs";import{n as Le}from"./agent-docs-TdQs75ND.mjs";import{C as Re,S as ze,_ as Be,a as Ve,b as He,c as Ue,d as We,f as Ge,g as Ke,h as qe,i as Je,l as Ye,m as Xe,o as Ze,p as Qe,r as $e,s as et,t as tt,u as nt,v as rt,w as it,x as D,y as at}from"./typegen-Cj5lp0gl.mjs";import{createRequire as ot}from"node:module";import O,{basename as st,dirname as k,join as A,relative as j,resolve as M,sep as N}from"node:path";import{cpSync as ct,existsSync as P,mkdirSync as lt,readFileSync as F,readdirSync as I,rmSync as ut,statSync as dt,writeFileSync as L}from"node:fs";import{copyFile as ft,mkdir as pt,readFile as R,readdir as mt,rm as ht,stat as gt,writeFile as z}from"node:fs/promises";import{fork as _t,spawn as vt,spawnSync as yt}from"node:child_process";import{createHash as bt}from"node:crypto";import{fileURLToPath as xt,pathToFileURL as B}from"node:url";import{parseSync as St}from"oxc-parser";import{arch as Ct,platform as wt,release as Tt}from"node:os";const Et=[{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 Dt(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(`-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)=>{d(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await s({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=M(`.`),e=st(i)):i=M(t.directory||e),P(i)){let r=I(i);if(r.length>0){if(t.force)p.warn(`Clearing existing files in ${i}`);else if(n){p.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),o(`Aborted.`);return}else{p.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)p.message(` - ${e}`);if(r.length>5&&p.message(` ... and ${r.length-5} more`),!await h({message:g.red(`Remove all existing files and proceed?`),initialValue:!1})){o(`Aborted.`);return}}for(let e of r)ut(M(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await f({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 c=t.runtime;c||=n?`express`:await f({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 u=t.pm;u||=n?await r(void 0):await f({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let m=t.repo;m||=n?`inmemory`:await s({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Ee(m);let _=t.schema;a===`inertia`&&(_&&_!==`zod`&&p.warn(`The inertia template uses zod — ignoring --schema ${_}.`),_=`zod`),_||=n?`zod`:await f({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(_)||(p.warn(`Unknown --schema "${_}", falling back to zod.`),_=`zod`);let v;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();v=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else v=n?[]:await l({message:`Select packages to include`,options:[...Et],required:!1});let y;y=t.git===void 0?n?!0:await h({message:`Initialize git repository?`,initialValue:!0}):t.git;let b;if(b=t.install===void 0?n?!0:await h({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){p.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),o(`Aborted.`);return}let{VITE_TEMPLATES:x,DEFAULT_VITE_TEMPLATE:ee}=await import(`./fullstack-BlNhq-tI.mjs`);if(t.viteTemplate!==void 0&&!x.some(e=>e.value===t.viteTemplate)){p.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${x.map(e=>e.value).join(`, `)}.`),o(`Aborted.`);return}let te=t.frontend===`vite`?`vite`:`kick`,ne=t.viteTemplate??ee;if(a===`fullstack`&&!t.frontend&&!n&&(te=await f({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&&!n&&(ne=await f({message:`create-vite template`,options:x.map(e=>({value:e.value,label:e.label})),initialValue:ee})),a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-BlNhq-tI.mjs`);await t({name:e,directory:i,packageManager:u,initGit:y,installDeps:b,schemaLib:_,runtime:c,packages:v,frontend:te,viteTemplate:ne}),o(`Done! Next steps: ${g.cyan(`cd ${e} && ${u}${u===`pnpm`?` dev`:` run dev:server`}`)}`)}else await Ne({name:e,directory:i,packageManager:u,initGit:y,installDeps:b,template:a,defaultRepo:m,packages:v,schemaLib:_,runtime:c}),o(`Done! Next steps: ${g.cyan(`cd ${e} && ${Te(u,`dev`)}`)}`)})}function Ot(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 Fe(`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 Fe(`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 Fe(`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 Fe(`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-BZ1wVwrr.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 kt(e){let{name:t,outDir:n}=e,r=S(t),a=x(t),o=[],s=A(n,`${r}.plugin.ts`);return await i(s,`import {
12
12
  definePlugin,
13
13
  type AppAdapter,
14
14
  type AppModuleEntry,
@@ -61,7 +61,7 @@ export interface ${a}PluginConfig {
61
61
  * @example
62
62
  * \`\`\`ts
63
63
  * import { bootstrap } from '@forinda/kickjs'
64
- * import { ${a}Plugin } from './plugins/${i}.plugin'
64
+ * import { ${a}Plugin } from './plugins/${r}.plugin'
65
65
  *
66
66
  * export const app = await bootstrap({
67
67
  * modules,
@@ -136,10 +136,10 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
136
136
  return [
137
137
  // Example:
138
138
  // import { defineHttpContextDecorator } from '@forinda/kickjs'
139
- // declare module '@forinda/kickjs' { interface ContextMeta { ${i}: { foo: string } } }
139
+ // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
140
140
  // const Load${a} = defineHttpContextDecorator({
141
- // key: '${i}',
142
- // resolve: (ctx) => ({ foo: ctx.req.headers['x-${i}'] as string }),
141
+ // key: '${r}',
142
+ // resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
143
143
  // })
144
144
  // return [Load${a}.registration]
145
145
  ]
@@ -165,14 +165,14 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
165
165
  // Example: await this.connection?.close()
166
166
  },
167
167
 
168
- ${ae(i,a,`plugin`,` `)}
168
+ ${se(r,a,`plugin`,` `)}
169
169
  }),
170
170
  })
171
- `),o.push(s),o}function Ot(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:t,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=S(t),c=y(t),l=e.key??ee(t),u=Array.isArray(e.params)?e.params:Ot(e.params),d=ve({type:`contributor`,outDir:e.outDir,moduleName:r,modulesDir:i,defaultDir:`src/contributors`,pattern:a,shouldPluralize:e.pluralize??!0}),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 At(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 jt(e){let{name:t,moduleName:n,modulesDir:r,pattern:a}=e,o=e.type??`http`,s=S(t),c=x(t),l=e.key??te(t),u=Array.isArray(e.params)?e.params:At(e.params),d=be({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:a,shouldPluralize:e.pluralize??!0}),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.
175
- requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,v=u.length>0?` // \`params\` is typed as ${c}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,b=`import { ${f} } from '@forinda/kickjs'
175
+ requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,v=u.length>0?` // \`params\` is typed as ${c}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,y=`import { ${f} } from '@forinda/kickjs'
176
176
  import type { ${p} } from '@forinda/kickjs'
177
177
 
178
178
  /**
@@ -219,13 +219,13 @@ ${v}
219
219
  throw new Error("${c} contributor: resolve() not implemented")
220
220
  },
221
221
  })
222
- `,x=A(d,`${s}.contributor.ts`);return await n(x,b),[x]}async function At(e){let t=A(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return P(t)&&!e.force&&!await p({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
223
- Skipped — existing kick.config.ts preserved.`),[]):(await n(t,`import { defineConfig } from '@forinda/kickjs-cli'
222
+ `,b=A(d,`${s}.contributor.ts`);return await i(b,y),[b]}async function Mt(e){let t=A(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return P(t)&&!e.force&&!await h({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
223
+ Skipped — existing kick.config.ts preserved.`),[]):(await i(t,`import { defineConfig } from '@forinda/kickjs-cli'
224
224
 
225
225
  export default defineConfig({
226
226
  modules: {
227
- dir: '${r}',
228
- repo: '${i}',
227
+ dir: '${n}',
228
+ repo: '${r}',
229
229
  pluralize: true,
230
230
  },
231
231
 
@@ -238,7 +238,7 @@ export default defineConfig({
238
238
  {
239
239
  name: 'test',
240
240
  description: 'Run tests with Vitest',
241
- steps: 'vitest run',
241
+ steps: 'vitest run --passWithNoTests',
242
242
  },
243
243
  {
244
244
  name: 'lint',
@@ -263,18 +263,18 @@ export default defineConfig({
263
263
  },
264
264
  ],
265
265
  })
266
- `),[t])}function jt(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function V(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 H(e,t,n){let r=` `.repeat(n);return e.split(`
266
+ `),[t])}function Nt(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 V(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=Nt(e,r);return i===-1?null:e.slice(r+1,i)}function H(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 Mt(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 Nt(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 Pt(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=V(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=V(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=V(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Mt(s),p=``;return l&&(p+=` register(container) {${H(l,4,6)} },\n\n`),u&&(p+=` contributors() {${H(u,4,6)} },\n\n`),p+=` routes() {${H(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
268
+ `)}function Pt(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 Ft(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 It(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=Nt(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=V(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=V(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=V(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=Pt(s),p=``;return l&&(p+=` register(container) {${H(l,4,6)} },\n\n`),u&&(p+=` contributors() {${H(u,4,6)} },\n\n`),p+=` routes() {${H(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
269
269
  name: '${r}',
270
270
  build: () => ({
271
271
  ${p}
272
272
  }),
273
- })`}${c}`}}function Ft(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=V(m,/register\s*\(([^)]*)\)\s*\{/),g=V(m,/contributors\s*\(\s*\)\s*\{/),_=V(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Nt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${H(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${H(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${H(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
273
+ })`}${c}`}}function Lt(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=Nt(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=Nt(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=V(m,/register\s*\(([^)]*)\)\s*\{/),g=V(m,/contributors\s*\(\s*\)\s*\{/),_=V(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Ft(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${H(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${H(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${H(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
275
275
  ${y}
276
276
  }
277
- `}${u}`}}function It(e,t){return t===`class`?Ft(e):Pt(e)}function Lt(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 Rt(e){let t=[];return await n(M(e),0),t;async function n(e,r){let i;try{i=await ft(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o;try{o=await mt(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function zt(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await ft(e)}catch{return}await dt(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o=A(t,a),s;try{s=await mt(i)}catch{continue}s.isDirectory()?await r(i,o):(await ut(i,o),n++)}}}function Bt(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return A(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function Vt(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Rt(e),s=await R(A(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Bt(r),await zt(e,c));let l=[];for(let e of o){let t=It(await R(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await z(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=A(e,`index.ts`),d=null;try{d=await R(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Lt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await z(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Ht(e,t){let n=await Rt(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 R(e,`utf-8`);i.test(t)&&r.push(e)}return r}const Ut={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.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 Wt(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=Ut[a];if(!o){let e=[...Object.keys(Ut),`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 Gt(e){let{name:t,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=S(t),u=y(t),d=c?de(l):l,f=c?b(u):u,p=A(i,d),m=[],h=async(e,t)=>{let r=A(p,e);await n(r,t),m.push(r)};return await h(`${l}.module.ts`,fe({pascal:u,kebab:l,plural:d,repo:a,style:s})),await h(`${l}.constants.ts`,ne({pascal:u,kebab:l})),await h(`${l}.controller.ts`,x({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await h(`${l}.service.ts`,v({pascal:u,kebab:l})),await h(`dtos/create-${l}.dto.ts`,Kt(u,r)),await h(`dtos/update-${l}.dto.ts`,qt(u,r)),await h(`dtos/${l}-response.dto.ts`,Jt(u,r)),await h(`${l}.repository.ts`,_({pascal:u,kebab:l,repoType:a,dtoPrefix:`./dtos`,tokenScope:o})),await be(i,u,d,l,s),m}function Kt(e,t){return`import { z } from 'zod'
277
+ `}${u}`}}function Rt(e,t){return t===`class`?Lt(e):It(e)}function zt(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 Bt(e){let t=[];return await n(M(e),0),t;async function n(e,r){let i;try{i=await mt(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o;try{o=await gt(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Vt(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await mt(e)}catch{return}await pt(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o=A(t,a),s;try{s=await gt(i)}catch{continue}s.isDirectory()?await r(i,o):(await ft(i,o),n++)}}}function Ht(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return A(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function Ut(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Bt(e),s=await R(A(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Ht(r),await Vt(e,c));let l=[];for(let e of o){let t=Rt(await R(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await z(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=A(e,`index.ts`),d=null;try{d=await R(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=zt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await z(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Wt(e,t){let n=await Bt(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 R(e,`utf-8`);i.test(t)&&r.push(e)}return r}const Gt={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.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 Kt(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=Gt[a];if(!o){let e=[...Object.keys(Gt),`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 qt(e){let{name:t,fields:n,modulesDir:r,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=S(t),u=x(t),d=c?pe(l):l,f=c?ee(u):u,p=A(r,d),m=[],h=async(e,t)=>{let n=A(p,e);await i(n,t),m.push(n)};return await h(`${l}.module.ts`,me({pascal:u,kebab:l,plural:d,repo:a,style:s})),await h(`${l}.constants.ts`,ie({pascal:u,kebab:l})),await h(`${l}.controller.ts`,ne({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await h(`${l}.service.ts`,b({pascal:u,kebab:l})),await h(`dtos/create-${l}.dto.ts`,Jt(u,n)),await h(`dtos/update-${l}.dto.ts`,Yt(u,n)),await h(`dtos/${l}-response.dto.ts`,Xt(u,n)),await h(`${l}.repository.ts`,y({pascal:u,kebab:l,repoType:a,dtoPrefix:`./dtos`,tokenScope:o})),await Se(r,u,d,l,s),m}function Jt(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 qt(e,t){return`import { z } from 'zod'
285
+ `}function Yt(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 Jt(e,t){return`export interface ${e}ResponseDTO {
293
+ `}function Xt(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 Yt(e){let{name:t,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=S(t),s=y(t),c=[],l;if(e.outDir)l=M(e.outDir);else if(r){let e=S(r),t=a?de(e):e;l=M(A(i??`src/modules`,t,`__tests__`))}else l=M(`src/__tests__`);let u=A(l,`${o}.test.ts`);return await n(u,`import { describe, it, expect, beforeEach } from 'vitest'
300
+ `}async function Zt(e){let{name:t,moduleName:n,modulesDir:r}=e,a=e.pluralize??!0,o=S(t),s=x(t),c=[],l;if(e.outDir)l=M(e.outDir);else if(n){let e=S(n),t=a?pe(e):e;l=M(A(r??`src/modules`,t,`__tests__`))}else l=M(`src/__tests__`);let u=A(l,`${o}.test.ts`);return await i(u,`import { describe, it, expect, beforeEach } from 'vitest'
301
301
  import { Container } from '@forinda/kickjs'
302
302
 
303
303
  describe('${s}', () => {
@@ -320,57 +320,52 @@ describe('${s}', () => {
320
320
  expect(true).toBe(true)
321
321
  })
322
322
  })
323
- `),c.push(u),c}const Xt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function U(e){return e.parent?.opts()?.dryRun??!1}function W(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 Zt(e){if(!e)try{let e=await C(process.cwd());await $e({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const Qt=[{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`}],$t=/* @__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`]]),en=/* @__PURE__ */ new Set([...Qt.map(e=>e.name.split(` `)[0]),...$t.keys()]);async function tn(){console.log(`
323
+ `),c.push(u),c}const Qt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function U(e){return e.parent?.opts()?.dryRun??!1}function W(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 $t(e){if(!e)try{let e=await w(process.cwd());await tt({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 en=[{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`}],tn=/* @__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`]]),nn=/* @__PURE__ */ new Set([...en.map(e=>e.name.split(` `)[0]),...tn.keys()]);async function rn(){console.log(`
326
326
  Built-in generators:
327
- `);let e=Math.max(...Qt.map(e=>e.name.length));for(let t of Qt)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await C(process.cwd()),n=Et(t?.plugins??[],t?.commands??[]),r=await ue(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
327
+ `);let e=Math.max(...en.map(e=>e.name.length));for(let t of en)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await w(process.cwd()),n=Ot(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 nn(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`,`pluralize`])n[e]===!1&&(r[e]=!1);return r}async function rn(e,t,n){let r=await C(process.cwd()),i=w(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??ye(i.repo);t.repo&&Me(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,l=je(r,process.cwd()),u=Oe(T()),d=ke(T()),f=T(),p=Ae(f,`@forinda/kickjs-testing`,`any`)&&Ae(f,`supertest`,`any`),h=i.style??`define`;if(!n&&h===`define`){let e=await Ht(M(a),`define`);if(e.length>0){console.error(`\n ${m.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${m.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${m.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 ${m.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${m.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${m.dim(`// kick.config.ts`)}\n ${m.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let _=[];for(let r of e){let e=await g({name:r,modulesDir:M(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:p,dryRun:n,pluralize:c,tokenScope:l,swagger:u,schemaLib:d,style:i.style});_.push(...e)}W(_,n),await Zt(n)}function an(e,n){let r=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,i,a)=>{if(i.list){await tn();return}if(!e||e.length===0){r.help();return}let o=U(a);t(o);let[s,c,...l]=e;if(s){let e=await C(process.cwd()),t=Et(e?.plugins??[],e?.commands??[]),r=await ie({generatorName:s,itemName:c??``,args:l,flags:i,cwd:process.cwd(),projectRoot:n?.projectRoot},t.generators);if(r){W(r.files,o);return}if(s!==`module`&&en.has(s)){let e=$t.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 rn(e,i,o)});r.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,n,r)=>{let i=U(r);t(i),await rn(e,nn(r,n),i)}),r.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,n,r)=>{let i=U(r);t(i),W(await xe({name:e,outDir:M(n.out)}),i)}),r.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,n,r)=>{let i=U(r);t(i),W(await Dt({name:e,outDir:M(n.out)}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await C(process.cwd()),o=w(a),s=o.dir??`src/modules`;W(await re({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,runtime:a?.runtime}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await C(process.cwd()),o=w(a),s=o.dir??`src/modules`;W(await ce({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.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 an(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`,`pluralize`])n[e]===!1&&(r[e]=!1);return r}async function on(e,t,n){let r=await w(process.cwd()),i=C(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??xe(i.repo);t.repo&&Ee(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,l=ke(r,process.cwd()),u=Oe(T()),d=De(T()),f=T(),p=we(f,`@forinda/kickjs-testing`,`any`)&&we(f,`supertest`,`any`),m=i.style??`define`;if(!n&&m===`define`){let e=await Wt(M(a),`define`);if(e.length>0){console.error(`\n ${g.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${g.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${g.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 ${g.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${g.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${g.dim(`// kick.config.ts`)}\n ${g.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let h=[];for(let r of e){let e=await v({name:r,modulesDir:M(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:p,dryRun:n,pluralize:c,tokenScope:l,swagger:u,schemaLib:d,style:i.style});h.push(...e)}W(h,n),await $t(n)}function sn(e,n){let r=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,i,a)=>{if(i.list){await rn();return}if(!e||e.length===0){r.help();return}let o=U(a);t(o);let[s,c,...l]=e;if(s){let e=await w(process.cwd()),t=Ot(e?.plugins??[],e?.commands??[]),r=await oe({generatorName:s,itemName:c??``,args:l,flags:i,cwd:process.cwd(),projectRoot:n?.projectRoot},t.generators);if(r){W(r.files,o);return}if(s!==`module`&&nn.has(s)){let e=tn.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 on(e,i,o)});r.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,n,r)=>{let i=U(r);t(i),await on(e,an(r,n),i)}),r.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,n,r)=>{let i=U(r);t(i),W(await Ce({name:e,outDir:M(n.out)}),i)}),r.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,n,r)=>{let i=U(r);t(i),W(await kt({name:e,outDir:M(n.out)}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await w(process.cwd()),o=C(a),s=o.dir??`src/modules`;W(await ae({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,runtime:a?.runtime}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await w(process.cwd()),o=C(a),s=o.dir??`src/modules`;W(await ue({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=(n.type??`http`).toLowerCase();a!==`http`&&a!==`bare`&&(console.warn(` kick g contributor: unknown --type '${n.type}', using 'http'.`),a=`http`);let o=await C(process.cwd()),s=w(o),c=s.dir??`src/modules`;W(await kt({name:e,type:a,key:n.key,params:n.params,outDir:n.out,moduleName:n.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await C(process.cwd()),o=w(a),s=o.dir??`src/modules`;W(await le({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await C(process.cwd()),o=w(a),s=o.dir??`src/modules`;W(await me({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i),await Zt(i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await C(process.cwd()),o=w(a),s=o.dir??`src/modules`;W(await he({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,schemaLib:ke(T())}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await C(process.cwd()),o=w(a),s=o.dir??`src/modules`;W(await Yt({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pluralize:o.pluralize??!0}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=(n.type??`http`).toLowerCase();a!==`http`&&a!==`bare`&&(console.warn(` kick g contributor: unknown --type '${n.type}', using 'http'.`),a=`http`);let o=await w(process.cwd()),s=C(o),c=s.dir??`src/modules`;W(await jt({name:e,type:a,key:n.key,params:n.params,outDir:n.out,moduleName:n.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await w(process.cwd()),o=C(a),s=o.dir??`src/modules`;W(await de({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await w(process.cwd()),o=C(a),s=o.dir??`src/modules`;W(await ge({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i),await $t(i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await w(process.cwd()),o=C(a),s=o.dir??`src/modules`;W(await _e({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,schemaLib:De(T())}),i)}),r.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,n,r)=>{let i=U(r);t(i);let a=await w(process.cwd()),o=C(a),s=o.dir??`src/modules`;W(await Zt({name:e,outDir:n.out,moduleName:n.module,modulesDir:s,pluralize:o.pluralize??!0}),i)}),r.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(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,n,r,i)=>{let a=nn(i,r),o=U(i);t(o),n.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(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,n,r,i)=>{let a=an(i,r),o=U(i);t(o),n.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 C(process.cwd()),c=w(s),l=a.modulesDir??c.dir??`src/modules`,u=Wt(n),d=je(s,process.cwd()),f=Oe(T()),p=await Gt({name:e,fields:u,modulesDir:M(l),noEntity:a.entity===!1,noTests:a.tests===!1,pluralize:a.pluralize===!1?!1:c.pluralize??!0,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)`:``}`);W(p,o),await Zt(o)}),r.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,n)=>{let r=U(n);t(r),W(await At({outDir:M(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),r)}),r.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | minimal | fullstack | inertia`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,n)=>{let r=U(n);t(r);let i=e.only??`all`;Xt.includes(i)?W(await Fe({outDir:M(`.`),only:i,name:e.name,pm:e.pm,template:e.template,force:e.force}),r):(console.error(` Invalid --only value: ${i}. Expected: ${Xt.join(` | `)}`),process.exitCode=1)});for(let e of n?.generators??[])on(r,e,n?.projectRoot)}function on(e,n,r){let{source:i,spec:a}=n,o=a.args?.[0],s=o?.name??`itemName`,c=o?.required?`<${s}>`:`[${s}]`,l=`${a.name} ${c} [extraArgs...]`,u=e.command(l).description(`${a.description} [${i}]`);for(let e of a.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,i,o,s)=>{let c=U(s);t(c);let l=await ie({generatorName:a.name,itemName:e??``,args:i??[],flags:o,cwd:process.cwd(),projectRoot:r},[n]);l&&W(l.files,c)})}const sn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function cn(e){let t=O.resolve(e.cwd,`.kickjs/types`);e.check||await dt(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??Ge,i=O.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(B(e).href)},async writeFile(t,n){let r=O.resolve(e.cwd,t);await dt(O.dirname(r),{recursive:!0}),await z(r,n,`utf8`)},getScanResult:e=>{let t=ln(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?We(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=O.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=`${sn}${n.id} */\n\n`+a+`
350
- `,u=``;P(i)&&(u=await R(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 z(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new _e(c);return s}function ln(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 un(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 dn=/* @__PURE__ */ e({applyDisableFilter:()=>un,runAllPluginTypegens:()=>G});async function G(e){let{enabled:t,skipped:n,unknown:r}=un(Et([...ra,...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 cn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&se())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof _e||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 fn(e){let t=A(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=A(t,i);if(P(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function pn(e){let t=e.spawnFn??gt,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function mn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
349
+ `),process.exit(1));let s=await w(process.cwd()),c=C(s),l=a.modulesDir??c.dir??`src/modules`,u=Kt(n),d=ke(s,process.cwd()),f=Oe(T()),p=await qt({name:e,fields:u,modulesDir:M(l),noEntity:a.entity===!1,noTests:a.tests===!1,pluralize:a.pluralize===!1?!1:c.pluralize??!0,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)`:``}`);W(p,o),await $t(o)}),r.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,n)=>{let r=U(n);t(r),W(await Mt({outDir:M(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),r)}),r.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,n)=>{let r=U(n);t(r);let i=e.only??`all`;Qt.includes(i)?W(await Le({outDir:M(`.`),only:i,name:e.name,pm:e.pm,template:e.template,force:e.force}),r):(console.error(` Invalid --only value: ${i}. Expected: ${Qt.join(` | `)}`),process.exitCode=1)});for(let e of n?.generators??[])cn(r,e,n?.projectRoot)}function cn(e,n,r){let{source:i,spec:a}=n,o=a.args?.[0],s=o?.name??`itemName`,c=o?.required?`<${s}>`:`[${s}]`,l=`${a.name} ${c} [extraArgs...]`,u=e.command(l).description(`${a.description} [${i}]`);for(let e of a.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,i,o,s)=>{let c=U(s);t(c);let l=await oe({generatorName:a.name,itemName:e??``,args:i??[],flags:o,cwd:process.cwd(),projectRoot:r},[n]);l&&W(l.files,c)})}const ln=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function un(e){let t=O.resolve(e.cwd,`.kickjs/types`);e.check||await pt(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??qe,i=O.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(B(e).href)},async writeFile(t,n){let r=O.resolve(e.cwd,t);await pt(O.dirname(r),{recursive:!0}),await z(r,n,`utf8`)},getScanResult:e=>{let t=dn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?Ke(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=O.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=`${ln}${n.id} */\n\n`+a+`
350
+ `,u=``;P(i)&&(u=await R(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 z(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new ye(c);return s}function dn(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function fn(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 pn=/* @__PURE__ */ e({applyDisableFilter:()=>fn,runAllPluginTypegens:()=>G});async function G(e){let{enabled:t,skipped:n,unknown:r}=fn(Ot([...ga,...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 un({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 mn(e){let t=process.platform===`win32`;for(let n of hn(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=A(n,i);if(P(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function hn(e){let t=M(e),n=gn(t);return(n?[t,n]:[t]).map(e=>A(e,`node_modules`,`.bin`))}function gn(e){for(let t=k(e);t!==k(t);t=k(t)){let n=A(t,`pnpm-workspace.yaml`),r=A(t,`package.json`);if(P(n)||P(r))return _n(n,r).some(n=>vn(n,j(t,e)))?t:void 0}}function _n(e,t){try{if(P(e)){let t=F(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(F(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function vn(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(N).join(`/`))}function yn(e){let t=e.spawnFn??vt,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 bn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
351
352
  `):`${n.slice(0,t).join(`
352
- `)}\n… ${n.length-t} more line(s)`}function hn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function gn(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 _n(e,t,n={}){t&&(process.env.PORT=t);let r=hn(n.polling),i=process.cwd(),a=await C(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await $e({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}let c=M(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await G({cwd:i,config:a});await Ke(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(M(`package.json`)).resolve(`vite`),{createServer:d}=await import(B(u).href);globalThis[oe]=`kick-dev`;let f=await d({configFile:M(`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=fn(i);e?m=pn({cwd:i,bin:e,onResult:e=>{f.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?h||(h=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(h=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(mn(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let g=pe({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 xn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Sn(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 Cn(e,t,n={}){t&&(process.env.PORT=t);let r=xn(n.polling),i=process.cwd(),a=await w(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await tt({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=M(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await G({cwd:i,config:a});await Je(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(M(`package.json`)).resolve(`vite`),{createServer:d}=await import(B(u).href);globalThis[ce]=`kick-dev`;let f=await d({configFile:M(`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=mn(i);e?m=yn({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(bn(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(`
353
354
  KickJS dev server running (Vite + @forinda/kickjs-vite)
354
- `),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 vn(e){let t=await C(e);try{await $e({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=M(e,t?.typegen?.outDir??`.kickjs/types`),r=await G({cwd:e,config:t});await Ke(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 yn(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 _n(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
355
- Error: vite is not installed.
356
- Run: pnpm add -D vite unplugin-swc
357
- `):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 wn(e){let t=await w(e);try{await tt({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=M(e,t?.typegen?.outDir??`.kickjs/types`),r=await G({cwd:e,config:t});await Je(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 Tn(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 Cn(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: ${a()} add -D vite unplugin-swc\n`):console.error(`
358
356
  Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
359
357
  Building for production...
360
- `);let{createRequire:e}=await import(`node:module`),t=e(M(`package.json`)).resolve(`vite`),{build:n}=await import(B(t).href);await n({configFile:M(`vite.config.ts`)});let r=await C(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
361
- Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?A(`dist`,e):e.dest??A(`dist`,t),r=M(t),i=M(n);P(r)?(st(i,{recursive:!0}),ot(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(`
362
- Building asset map...`);try{await Pe(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(M(`package.json`)).resolve(`vite`),{build:n}=await import(B(t).href);await n({configFile:M(`vite.config.ts`)});let r=await w(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`?A(`dist`,e):e.dest??A(`dist`,t),r=M(t),i=M(n);P(r)?(lt(i,{recursive:!0}),ct(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 Ie(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
363
361
  Build complete.
364
- `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await C(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0)console.log(` No assetMap entries — nothing to build.`);else{console.log(`
365
- Building asset map...`);try{await Pe(e,{cwd:process.cwd()}),console.log(`
362
+ `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await w(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 Ie(e,{cwd:process.cwd()}),console.log(`
366
364
  Asset build complete.
367
- `)}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)),Se(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=M(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await vn(t);let n=fn(t);if(!n){console.error(`
368
- No type-checker found. Install one in this project:
369
- pnpm add -D typescript (tsc)
370
- pnpm add -D @typescript/native-preview (tsgo, faster)
371
- `),process.exit(1);return}let r=_t(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 gn(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 _n(e.entry,e.port)}catch(e){console.error(`
372
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function bn(){try{let e=k(yt(import.meta.url));return JSON.parse(F(A(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const xn=new Set(Object.values(Te).filter(e=>e.deprecated).map(e=>e.pkg));function Sn(e){let t=A(e,`package.json`);if(!P(t))return[];let n;try{n=JSON.parse(F(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=A(e,`node_modules`,...t.split(`/`),`package.json`);if(P(i))try{n=JSON.parse(F(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:xn.has(t)}})}function Cn(e){let t=e;for(;;){if(P(A(t,`package.json`)))return t;let e=k(t);if(e===t)return null;t=e}}function wn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${bn()}`,``,` System:`,` OS: ${St()} ${Ct()} (${xt()})`,` Node: ${process.version}`],t=Cn(process.cwd()),n=t?Sn(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(`
373
- `))})}const{bold:K,dim:q,green:Tn,red:En,yellow:Dn,blue:On}=m;function kn(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 An(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function J(e,t){try{return await An(`${e}${t}`)}catch{return null}}async function jn(e){let[t,n,r,i,a]=await Promise.all([J(e,`/health`),J(e,`/metrics`),J(e,`/routes`),J(e,`/container`),J(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function Mn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Tn(`● healthy`):En(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${En(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?En:r.errorRate>0?Dn:Tn;console.log(` ${K(`Uptime:`)} ${kn(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${K(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(s),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${c(e.method)} ${t} ${On(e.controller)}.${q(e.handler)}`)}}console.log(s),console.log()}function Nn(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 jn(r);t.json?console.log(JSON.stringify(e,null,2)):Mn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(En(` ✖ Could not connect to ${n}`)),console.error(q(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function Y(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function X(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Pn=[{match(e,t){let n=Y(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:X(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
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)),Pe(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=M(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await wn(t);let n=mn(t);if(!n){console.error(`
366
+ No type-checker found. Install one in this project:\n ${a(t)} add -D typescript (tsc)\n ${a(t)} add -D @typescript/native-preview (tsgo, faster)\n`),process.exit(1);return}let r=yt(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 Sn(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 Cn(e.entry,e.port)}catch(e){console.error(`
367
+ Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function En(){try{let e=k(xt(import.meta.url));return JSON.parse(F(A(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const Dn=new Set(Object.values(je).filter(e=>e.deprecated).map(e=>e.pkg));function On(e){let t=A(e,`package.json`);if(!P(t))return[];let n;try{n=JSON.parse(F(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=A(e,`node_modules`,...t.split(`/`),`package.json`);if(P(i))try{n=JSON.parse(F(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:Dn.has(t)}})}function kn(e){let t=e;for(;;){if(P(A(t,`package.json`)))return t;let e=k(t);if(e===t)return null;t=e}}function An(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${En()}`,``,` System:`,` OS: ${wt()} ${Tt()} (${Ct()})`,` Node: ${process.version}`],t=kn(process.cwd()),n=t?On(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:K,dim:q,green:jn,red:Mn,yellow:Nn,blue:Pn}=g;function Fn(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 In(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function J(e,t){try{return await In(`${e}${t}`)}catch{return null}}async function Ln(e){let[t,n,r,i,a]=await Promise.all([J(e,`/health`),J(e,`/metrics`),J(e,`/routes`),J(e,`/container`),J(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function Rn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?jn(`● healthy`):Mn(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${Mn(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?Mn:r.errorRate>0?Nn:jn;console.log(` ${K(`Uptime:`)} ${Fn(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${K(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(s),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${u(e.method)} ${t} ${Pn(e.controller)}.${q(e.handler)}`)}}console.log(s),console.log()}function zn(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 Ln(r);t.json?console.log(JSON.stringify(e,null,2)):Rn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(Mn(` ✖ Could not connect to ${n}`)),console.error(q(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function Y(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function X(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Bn=[{match(e,t){let n=Y(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:X(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
374
369
  src/config/index.ts, and src/index.ts imports it before bootstrap().
375
370
  Tests never load src/index.ts — \`createTestApp\` builds the app
376
371
  directly — so that import does not run and ConfigService falls back to
@@ -585,24 +580,23 @@ import { bootstrap } from '@forinda/kickjs'
585
580
  await bootstrap({ modules }) // ← nothing for the dev server to read`,codeAfter:`import './env'
586
581
  import { bootstrap } from '@forinda/kickjs'
587
582
 
588
- export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function Fn(e,t){let n=null;for(let r of Pn){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 In(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.
583
+ export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function Vn(e,t){let n=null;for(let r of Bn){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 Hn(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.
589
584
  export OPENAI_API_KEY="sk-..."
590
585
 
591
586
  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:
592
587
  kick add ai
593
588
 
594
589
  Or manually:
595
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Ln(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Rn((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 Ln(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(`
596
- `)}function Rn(e){let t=[e,zn(e),Bn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Vn(t))return t}catch{continue}return null}function zn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Bn(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 Vn(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 Hn(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 Gn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
590
+ ${a()} add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,o=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),s=Un(e.cwd),c=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Wn((await o.chat({messages:[{role:`system`,content:s},{role:`user`,content:c}]})).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 Un(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 Wn(e){let t=[e,Gn(e),Kn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(qn(t))return t}catch{continue}return null}function Gn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function Kn(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 qn(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 Jn(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 Zn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
597
592
 
598
593
  Pass a message as a positional arg, --message flag, or pipe via stdin:
599
594
  kick explain "config.get returned undefined"
600
- pnpm test 2>&1 | kick explain
601
- `),process.exit(1));let r=qn(),i=Fn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
602
- `);return}if(i){Jn(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
603
- `),process.exit(2)),Yn(n),process.exit(2));let a=await In({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Un(a),null,2)+`
604
- `),process.exit(a.kind===`ok`?0:2)),Wn(n,a),process.exit(a.kind===`ok`?0:2)})}function Un(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 Wn(e,t){t.kind===`ok`?Jn(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${Xn(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Z(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${Xn(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function Gn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Kn()}function Kn(){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 qn(){let e=process.cwd();return{cwd:e,hasFile:t=>P(M(e,t))}}function Jn(e,t,n,r=!1){let i=Xn(e.trim(),200),a=r?`AI-generated — verify before applying`:Zn(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${Z(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Z(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Z(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Z(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
605
- `)}function Yn(e){let t=Xn(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
595
+ ${Te(a(),`test`)} 2>&1 | kick explain\n`),process.exit(1));let r=$n(),i=Vn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
596
+ `);return}if(i){er(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
597
+ `),process.exit(2)),tr(n),process.exit(2));let o=await Hn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Yn(o),null,2)+`
598
+ `),process.exit(o.kind===`ok`?0:2)),Xn(n,o),process.exit(o.kind===`ok`?0:2)})}function Yn(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 Xn(e,t){t.kind===`ok`?er(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${nr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Z(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${nr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function Zn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Qn()}function Qn(){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 $n(){let e=process.cwd();return{cwd:e,hasFile:t=>P(M(e,t))}}function er(e,t,n,r=!1){let i=nr(e.trim(),200),a=r?`AI-generated — verify before applying`:rr(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${Z(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Z(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Z(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Z(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
599
+ `)}function tr(e){let t=nr(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
606
600
 
607
601
  1. Check the framework docs for the error keywords:
608
602
  https://kickjs.app/
@@ -616,10 +610,8 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
616
610
 
617
611
  `)}function Z(e,t){return e.split(`
618
612
  `).map(e=>`${t}${e}`).join(`
619
- `)}function Xn(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Zn(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Qn(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($n),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(er)}function $n(e){let t=M(e.entry);P(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=gt(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 er(e){let t=process.cwd(),n=tr(t)??at(t),r=e.name??n,i=e.global?M(process.env.HOME??`.`,`.mcp.json`):M(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(P(i))try{let e=F(i,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(o={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${i} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}o.mcpServers[r]&&!e.force&&(process.stderr.write(`Error: an entry for "${r}" already exists in ${i}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),o.mcpServers[r]=a,L(i,JSON.stringify(o,null,2)+`
620
- `,`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 tr(e){let t=M(e,`package.json`);if(!P(t))return null;try{let e=F(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function nr(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=M(t,e.entry);P(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=ir(t,`tsx`);r||(console.error(`
621
- Error: tsx not found. Install it: pnpm add -D tsx
622
- `),process.exit(1));let i=rr(n,e.entry),a=A(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=ht(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function rr(e,t){return`
613
+ `)}function nr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function rr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function ir(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(ar),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(or)}function ar(e){let t=M(e.entry);P(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=vt(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 or(e){let t=process.cwd(),n=sr(t)??st(t),r=e.name??n,i=e.global?M(process.env.HOME??`.`,`.mcp.json`):M(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(P(i))try{let e=F(i,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(o={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${i} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}o.mcpServers[r]&&!e.force&&(process.stderr.write(`Error: an entry for "${r}" already exists in ${i}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),o.mcpServers[r]=a,L(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 sr(e){let t=M(e,`package.json`);if(!P(t))return null;try{let e=F(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function cr(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=M(t,e.entry);P(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=ur(t,`tsx`);r||(console.error(`\n Error: tsx not found. Install it: ${a(t)} add -D tsx\n`),process.exit(1));let i=lr(n,e.entry),o=A(t,`.kick-tinker.mjs`),{writeFileSync:s,unlinkSync:c}=await import(`node:fs`);s(o,i,`utf-8`);try{let e=_t(o,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{c(o)}catch{}}})}function lr(e,t){return`
623
615
  import 'reflect-metadata'
624
616
 
625
617
  // Prevent bootstrap() from starting the HTTP server
@@ -638,7 +630,7 @@ try {
638
630
  HttpStatus = core.HttpStatus
639
631
  } catch {
640
632
  console.error(' Error: @forinda/kickjs not found.')
641
- console.error(' Install it: pnpm add @forinda/kickjs\\n')
633
+ console.error(' Install @forinda/kickjs in this project.\\n')
642
634
  process.exit(1)
643
635
  }
644
636
 
@@ -673,38 +665,46 @@ server.on('exit', () => {
673
665
  console.log('\\n Goodbye!\\n')
674
666
  process.exit(0)
675
667
  })
676
- `}function ir(e,t){let n=e;for(;;){let e=A(n,`node_modules`,`.bin`,t);if(P(e))return e;let r=M(n,`..`);if(r===n)break;n=r}return null}function ar(e,t){let n=RegExp(`^\\s*${h(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
668
+ `}function ur(e,t){for(let n of hn(e)){let e=A(n,t);if(P(e))return e}return null}function dr(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]!==`
677
669
  `;)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]===`
678
- `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function or(e,t){let n=te(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=ar(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${h(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function sr(e){let{name:t,modulesDir:n,force:i}=e,a=e.pluralize!==!1,o=S(t),s=y(t),c=a?de(o):o;c!==o&&!await r(A(n,c))&&await r(A(n,o))&&(c=o);let l=A(n,c);if(!await r(l)){console.log(`\n Module not found: ${l}\n`);return}if(!i&&!await p({message:m.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
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 fr(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=dr(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 pr(e){let{name:t,modulesDir:r,force:i}=e,a=e.pluralize!==!1,o=S(t),s=x(t),c=a?pe(o):o;c!==o&&!await n(A(r,c))&&await n(A(r,o))&&(c=o);let l=A(r,c);if(!await n(l)){console.log(`\n Module not found: ${l}\n`);return}if(!i&&!await h({message:g.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
679
671
  Cancelled.
680
- `);return}await pt(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let u=A(n,`index.ts`);if(await r(u)){let e=await R(u,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${h(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${h(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=or(e,s),e=e.replace(/\n{3,}/g,`
672
+ `);return}await ht(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let u=A(r,`index.ts`);if(await n(u)){let e=await R(u,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${_(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${_(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=fr(e,s),e=e.replace(/\n{3,}/g,`
681
673
 
682
- `),e!==t&&(await z(u,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${u}`))}console.log(`\n Module '${c}' removed.\n`)}function cr(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await C(process.cwd()),r=w(n),i=t.modulesDir??r.dir??`src/modules`,a=t.pluralize===!1?!1:r.pluralize??!0;for(let n of e)await sr({name:n,modulesDir:M(i),force:t.force,pluralize:a})})}function lr(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 ur(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function dr(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=T(process.cwd()),n=await C(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-Bs0soxrU.mjs`),{builtinCliPlugins:t}=await import(`./builtins-CtpLZ4FY.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(`
674
+ `),e!==t&&(await z(u,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${u}`))}console.log(`\n Module '${c}' removed.\n`)}function mr(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await w(process.cwd()),r=C(n),i=t.modulesDir??r.dir??`src/modules`,a=t.pluralize===!1?!1:r.pluralize??!0;for(let n of e)await pr({name:n,modulesDir:M(i),force:t.force,pluralize:a})})}function hr(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 gr(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function _r(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=T(process.cwd()),n=await w(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-DDENlsHw.mjs`),{builtinCliPlugins:t}=await import(`./builtins-C3BQ79nW.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(`
683
675
  Registered typegen plugins:
684
676
  `);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(`
685
677
  Disable one in kick.config.ts:
686
678
  `),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
687
- `);return}let r=lr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=ur(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 Ze(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await $e(a);let r=await G({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=M(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await Ke(i,r,e.silent??!1)}}}catch(e){e instanceof Qe?console.error(`
679
+ `);return}let r=hr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=gr(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 $e(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 tt(a);let r=await G({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=M(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await Je(i,r,e.silent??!1)}}}catch(e){e instanceof et?console.error(`
688
680
  `+e.message+`
689
- `):e instanceof _e?console.error(`
681
+ `):e instanceof ye?console.error(`
690
682
  `+e.message+`
691
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const fr=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function pr(e,t){return typeof t==`number`?e.slice(0,t).split(`
692
- `).length:1}function mr(e){let t=Ie(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(Le(e)&&e.type===`MemberExpression`&&D(e.object)===`Scope`){let t=D(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function hr(e){let t=D(e);if(t)return{key:`id:${t}`,label:t};let n=Ie(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function gr(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=tt(e).map(Re).find(e=>e?.name===`Inject`),a=null;if(i)a=hr(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=hr(e.typeName))}a&&r.push({...a,line:pr(t,e.start)})}return r}function _r(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=bt(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`)&&Le(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(D(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(D(n.id),t)}nt(e,e=>{if(e.type===`ClassDeclaration`){let a=D(e.id);if(!a)return;for(let o of tt(e)){let s=Re(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:gr(e,n)});return}if(fr.has(s.name)){let o=Be(rt(s.call),`scope`),c=o?mr(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:gr(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!Le(a)||a.type!==`MemberExpression`)return;let o=D(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=hr(s[0]);c&&i(c.key,s.length>=3?mr(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 vr(e){let t=[];if(!P(e))return t;let n=I(e,{withFileTypes:!0});for(let r of n){let n=A(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...vr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function yr(e){try{return F(e,`utf-8`)}catch{return``}}const br=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function xr(e,t){let n=yr(A(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(br.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 Sr(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 Cr(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 wr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Tr(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 Er(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 Dr(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 Or(e){let t=vr(A(e,`src`)).map(e=>yr(e)),n=[],r=xr(e,t);r&&n.push(r);let i=Sr(t);i&&n.push(i);let a=Cr(t);a&&n.push(a);let o=wr();o&&n.push(o);let s=Tr(t);return s&&n.push(s),n.push(Er(t)),n.push(Dr(t)),n}function kr(e){let t=_r(vr(A(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:j(e,t).split(`\\`).join(`/`),source:yr(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 Ar(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(`
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 vr=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function yr(e,t){return typeof t==`number`?e.slice(0,t).split(`
684
+ `).length:1}function br(e){let t=Re(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(ze(e)&&e.type===`MemberExpression`&&D(e.object)===`Scope`){let t=D(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function xr(e){let t=D(e);if(t)return{key:`id:${t}`,label:t};let n=Re(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function Sr(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=rt(e).map(Be).find(e=>e?.name===`Inject`),a=null;if(i)a=xr(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=xr(e.typeName))}a&&r.push({...a,line:yr(t,e.start)})}return r}function Cr(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=St(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`)&&ze(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(D(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(D(n.id),t)}it(e,e=>{if(e.type===`ClassDeclaration`){let a=D(e.id);if(!a)return;for(let o of rt(e)){let s=Be(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:Sr(e,n)});return}if(vr.has(s.name)){let o=He(at(s.call),`scope`),c=o?br(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:Sr(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!ze(a)||a.type!==`MemberExpression`)return;let o=D(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=xr(s[0]);c&&i(c.key,s.length>=3?br(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 wr(e){let t=[];if(!P(e))return t;let n=I(e,{withFileTypes:!0});for(let r of n){let n=A(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...wr(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Tr(e){try{return F(e,`utf-8`)}catch{return``}}const Er=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Dr(e,t){let n=Tr(A(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Er.has(t.toLowerCase())||t.length<32)return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value or too short (< 32 chars) — change it`}}}for(let e of t)for(let t of[/JWT_SECRET['"]?\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i,/secret\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i])if(t.test(e))return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value in source code — use an environment variable`};return null}function Or(e){for(let t of e)if(/cors\s*\(/.test(t)&&/origin\s*:\s*['"]\*['"]/.test(t))return{severity:`CRITICAL`,message:`CORS origin is '*' — restrict to your domains`};return null}function kr(e){for(let t of e)if(/rateLimit/i.test(t)||/@RateLimit/i.test(t))return null;return{severity:`WARNING`,message:`No rate limiting detected — add rateLimit() middleware or @RateLimit decorator`}}function Ar(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function jr(e){let t=!1,n=!1;for(let r of e)/tokenStore/i.test(r)&&(t=!0),/MemoryTokenStore/i.test(r)&&(n=!0);return n?{severity:`WARNING`,message:`MemoryTokenStore detected — use a persistent store (Redis, DB) for production deployments`}:t?null:{severity:`WARNING`,message:`No token revocation store detected — consider adding one for auth token management`}}function Mr(e){for(let t of e)if(/helmet\s*\(/.test(t))return/security\s*\.\s*helmet\s*.*false/.test(t)?{severity:`WARNING`,message:`Helmet security headers are disabled — enable them for production`}:{severity:`INFO`,message:`Helmet security headers active`};return{severity:`WARNING`,message:`Helmet not detected — add helmet() middleware for security headers`}}function Nr(e){for(let t of e)if(/AuthAdapter/i.test(t))return{severity:`INFO`,message:`AuthAdapter configured`};return{severity:`INFO`,message:`No AuthAdapter detected — add one if your app requires authentication`}}function Pr(e){let t=wr(A(e,`src`)).map(e=>Tr(e)),n=[],r=Dr(e,t);r&&n.push(r);let i=Or(t);i&&n.push(i);let a=kr(t);a&&n.push(a);let o=Ar();o&&n.push(o);let s=jr(t);return s&&n.push(s),n.push(Mr(t)),n.push(Nr(t)),n}function Fr(e){let t=Cr(wr(A(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:j(e,t).split(`\\`).join(`/`),source:Tr(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 Ir(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(`
693
685
  Usage: kick check [--deploy] [--di]
694
686
 
695
687
  Available checks:
696
688
  --deploy Audit for production readiness (security, config, best practices)
697
689
  --di Find REQUEST-scoped dependencies injected into singleton constructors
698
- `);return}let t=process.cwd();l(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=f();n.start(`Scanning project...`);let r=[...e.deploy?Or(t):[],...e.di?kr(t):[]];n.stop(`Scan complete`);let a={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>a[e.severity]-a[t.severity]);for(let e of r)d.message(`${o(e.severity)} ${e.message}`);let s=r.filter(e=>e.severity===`CRITICAL`).length,c=r.filter(e=>e.severity===`WARNING`).length,u=r.filter(e=>e.severity===`INFO`).length,p=c===1?`warning`:`warnings`,h=[s>0?m.red(`${s} critical`):`${s} critical`,c>0?m.yellow(`${c} ${p}`):`${c} ${p}`,`${u} info`].join(`, `);s>0?(i(m.red(`${h} — fix critical issues before deploying`)),process.exit(1)):i(m.green(`${h} — looking good!`))})}function jr(e){return e.optsWithGlobals().dryRun??!1}function Mr(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.
690
+ `);return}let t=process.cwd();d(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=m();n.start(`Scanning project...`);let r=[...e.deploy?Pr(t):[],...e.di?Fr(t):[]];n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)p.message(`${c(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,s=r.filter(e=>e.severity===`WARNING`).length,l=r.filter(e=>e.severity===`INFO`).length,u=s===1?`warning`:`warnings`,f=[a>0?g.red(`${a} critical`):`${a} critical`,s>0?g.yellow(`${s} ${u}`):`${s} ${u}`,`${l} info`].join(`, `);a>0?(o(g.red(`${f} — fix critical issues before deploying`)),process.exit(1)):o(g.green(`${f} — looking good!`))})}const Lr=Symbol.for(`kickjs.handler.entryCapture`),Rr=Symbol.for(`kickjs.config.describe`);function zr(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function Br(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?``:zr(n.default)}`)}return t}function Vr(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
691
+ # sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
692
+ #
693
+ # 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 ──`,...Br(e.env)].join(`
695
+ `));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...Br(n.vars)].join(`
696
+ `));return`${t.join(`
697
+
698
+ `)}\n`}async function Hr(e,t){let n=M(e,t);if(!P(n))throw Error(`${t} not found`);let r=M(e,`vite.config.ts`);if(!P(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(M(e,`package.json`)),{createServer:o}=await import(B(a.resolve(`vite`)).href),s=globalThis,c;s[Lr]=e=>{c??=e},s[Rr]=!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[Lr],delete s[Rr],delete s[ce],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function Ur(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=M(t,e.out),r;try{r=Vr(await Hr(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((P(n)?F(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.`)):(L(n,r),console.log(` Wrote ${e.out}`))})}function Wr(e){return e.optsWithGlobals().dryRun??!1}function Gr(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
699
  Direction defaults to \`modules.style\` from kick.config (or "define").
700
700
  --target define|class Override the migration direction.
701
701
  --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,n)=>{let r=jr(n)||!e.apply;t(r),e.experimental||(console.error(`
703
- `+m.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
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,n)=>{let r=Wr(n)||!e.apply;t(r),e.experimental||(console.error(`
703
+ `+g.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
704
704
  The regex-based rewrite handles the shapes our templates produce.
705
705
  Hand-rolled modules with non-standard structures may be skipped.
706
706
  Always commit before running with --apply.
707
- `),process.exit(1));let i=await C(process.cwd()),a=w(i),o=M(e.modulesDir??a.dir??`src/modules`),s;e.target===`define`||e.target===`class`?s=e.target:e.target===void 0?s=a.style??`define`:(console.error(`\n ${m.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let c=m.dim(`→ ${s}`),l=r?m.dim(`(dry-run)`):m.bold(`(applying)`);console.log(`\n ${m.bold(`kick codemod modules`)} ${c} ${l}`),console.log(` modulesDir: ${m.dim(o)}\n`);let u=e.backup!==!1&&!r,d=await Vt(o,{dryRun:r,target:s,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${m.green(`✓`)} backup: ${m.dim(e)}\n ${m.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!r&&e.backup===!1&&console.log(` ${m.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,p=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${m.green(`✓`)} ${e.path}`);else{p++;let t=m.dim(`(${e.reason??`skipped`})`);console.log(` ${m.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${m.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=m.dim(`(${d.indexReason??`skipped`})`);console.log(` ${m.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${m.dim(`-`)} ${d.indexPath} ${m.dim(`(not found)`)}`);let h=r?m.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${m.bold(String(f))} migrated, ${m.bold(String(p))} skipped${h}\n`)})}function Nr(e){try{let t=JSON.parse(F(M(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function Pr(e,t=P,n=Nr(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=k(e);return(t(M(r,`pnpm-workspace.yaml`))||t(M(r,`package.json`)))&&t(M(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function Fr(e,t,n,r){let i=Pr(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 Ir(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'
707
+ `),process.exit(1));let i=await w(process.cwd()),a=C(i),o=M(e.modulesDir??a.dir??`src/modules`),s;e.target===`define`||e.target===`class`?s=e.target:e.target===void 0?s=a.style??`define`:(console.error(`\n ${g.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let c=g.dim(`→ ${s}`),l=r?g.dim(`(dry-run)`):g.bold(`(applying)`);console.log(`\n ${g.bold(`kick codemod modules`)} ${c} ${l}`),console.log(` modulesDir: ${g.dim(o)}\n`);let u=e.backup!==!1&&!r,d=await Ut(o,{dryRun:r,target:s,backup:u});if(d.backupDir){let e=d.backupDir;console.log(` ${g.green(`✓`)} backup: ${g.dim(e)}\n ${g.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!r&&e.backup===!1&&console.log(` ${g.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,p=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${g.green(`✓`)} ${e.path}`);else{p++;let t=g.dim(`(${e.reason??`skipped`})`);console.log(` ${g.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${g.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=g.dim(`(${d.indexReason??`skipped`})`);console.log(` ${g.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${g.dim(`-`)} ${d.indexPath} ${g.dim(`(not found)`)}`);let m=r?g.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${g.bold(String(f))} migrated, ${g.bold(String(p))} skipped${m}\n`)})}function Kr(e){try{let t=JSON.parse(F(M(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function qr(e,t=P,n=Kr(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=k(e);return(t(M(r,`pnpm-workspace.yaml`))||t(M(r,`package.json`)))&&t(M(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function Jr(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 Yr(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
708
  import { handler } from '${e}'
709
709
 
710
710
  // Where the app's build files were packaged; the platform starts this
@@ -718,7 +718,7 @@ export const config = {
718
718
  ${r.join(`
719
719
  `)}
720
720
  }
721
- `}function Lr(){return`import { fileURLToPath } from 'node:url'
721
+ `}function Xr(){return`import { fileURLToPath } from 'node:url'
722
722
  import { handler } from './server.mjs'
723
723
 
724
724
  // The app's build files are copied into this function at their project
@@ -728,11 +728,11 @@ process.env.KICK_APP_ROOT ??= fileURLToPath(new URL('./', import.meta.url))
728
728
  const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
729
729
 
730
730
  export default (req, res) => handler.node(req, res, requestContext())
731
- `}function Rr(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function zr(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 Br(e,t){let n;try{n=bt(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 Vr(e){let t=M(e,`src`);return P(t)?I(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=F(M(t,e),`utf-8`);return n.includes(`@Cron`)?Br(n,`src/${e}`):[]}):[]}function Hr(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 Ur(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(Hr(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 Wr(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 Gr(e,t){let{createRequire:n}=await import(`node:module`),r=n(M(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=M(e,`node_modules`,t,`package.json`)}if(!P(i))throw Error(`${t} is not installed in this project. Run: pnpm add -D vite unplugin-swc @forinda/kickjs-vite`);let a=Wr(JSON.parse(F(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(B(M(k(i),a)).href)}async function Kr(e,t,n){let r=M(e,t.entry);if(!P(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await Gr(e,`vite`),{default:a}=await Gr(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await Gr(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":M(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:M(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>Jr(n,r?k(r):e)||t.external.includes(n)&&!P(M(e,`node_modules`,n)),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=M(e,t.outDir,`server.mjs`);return n(`bundled ${j(process.cwd(),c)}`),c}function qr(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function Jr(e,t,n=P){let r=qr(e);if(!r)return!1;for(let e=t;;e=k(e)){if(n(M(e,`node_modules`,r,`package.json`)))return!1;if(k(e)===e)return!0}}function Yr(e,t){let n=j(e,t).split(N)[0];return n!==void 0&&n.startsWith(`.`)}function Xr(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function Zr(e){try{return lt(e)}catch{return}}function Qr(e,t){let n=t.filter(t=>!P(M(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 (\`pnpm build\`), or fix \`deploy.include\`.`)}function $r(e,t){let n=t.projectRoot,r=()=>Fr(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();Qr(n,e.include);let i=await Kr(n,e,t.log),a=M(n,e.siteRoot),o=Vr(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=M(a,`.netlify/v1/functions`);st(s,{recursive:!0});let c=j(s,i).split(N).join(`/`),l=e=>e.split(N).join(`/`);L(M(s,`api.mjs`),Ir(c,e.apiPath,{projectDir:l(j(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(j(s,M(n,e)));return Zr(M(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${j(process.cwd(),M(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)st(M(n,u),{recursive:!0}),t.log(`publish directory ready at ${j(process.cwd(),M(n,u))}`);else if(P(M(n,u))){let e=I(M(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=M(n,u,`_redirects`),r=P(t)?F(t,`utf-8`):``,i=Xr(e).filter(e=>!r.includes(e));i.length>0&&L(t,`${r}${r&&!r.endsWith(`
731
+ `}function Zr(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function Qr(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 $r(e,t){let n;try{n=St(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 ei(e){let t=M(e,`src`);return P(t)?I(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=F(M(t,e),`utf-8`);return n.includes(`@Cron`)?$r(n,`src/${e}`):[]}):[]}function ti(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 ni(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(ti(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 ri(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 ii(e,t){let{createRequire:n}=await import(`node:module`),r=n(M(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=M(e,`node_modules`,t,`package.json`)}if(!P(i))throw Error(`${t} is not installed in this project. Run: ${a(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let o=ri(JSON.parse(F(i,`utf-8`)));if(!o)throw Error(`${t} has no importable entry point`);return import(B(M(k(i),o)).href)}async function ai(e,t,n){let r=M(e,t.entry);if(!P(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await ii(e,`vite`),{default:a}=await ii(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await ii(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":M(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:M(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>si(n,r?k(r):e)||t.external.includes(n)&&si(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=M(e,t.outDir,`server.mjs`);return n(`bundled ${j(process.cwd(),c)}`),c}function oi(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function si(e,t,n=P){let r=oi(e);if(!r)return!1;for(let e=t;;e=k(e)){if(n(M(e,`node_modules`,r,`package.json`)))return!1;if(k(e)===e)return!0}}function ci(e,t){let n=j(e,t).split(N)[0];return n!==void 0&&n.startsWith(`.`)}function li(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function ui(e){try{return dt(e)}catch{return}}function di(e,t){let n=t.filter(t=>!P(M(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 (\`${Te(a(e),`build`)}\`), or fix \`deploy.include\`.`)}function fi(e,t){let n=t.projectRoot,r=()=>Jr(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();di(n,e.include);let i=await ai(n,e,t.log),a=M(n,e.siteRoot),o=ei(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=M(a,`.netlify/v1/functions`);lt(s,{recursive:!0});let c=j(s,i).split(N).join(`/`),l=e=>e.split(N).join(`/`);L(M(s,`api.mjs`),Yr(c,e.apiPath,{projectDir:l(j(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(j(s,M(n,e)));return ui(M(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${j(process.cwd(),M(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)lt(M(n,u),{recursive:!0}),t.log(`publish directory ready at ${j(process.cwd(),M(n,u))}`);else if(P(M(n,u))){let e=I(M(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=M(n,u,`_redirects`),r=P(t)?F(t,`utf-8`):``,i=li(e).filter(e=>!r.includes(e));i.length>0&&L(t,`${r}${r&&!r.endsWith(`
733
733
  `)?`
734
734
  `:``}${i.join(`
735
- `)}\n`)}}let d=M(a,`netlify.toml`);if(P(d)){let e=Rr(F(d,`utf-8`)),r=j(a,M(n,u)).split(N).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();Qr(n,e.include);let i=await Kr(n,e,t.log),a=M(n,e.siteRoot),o=e.staticDir?M(n,e.staticDir):void 0,s=M(a,`.vercel/output`),c=M(s,`functions/api.func`);ct(s,{recursive:!0,force:!0}),st(c,{recursive:!0}),ot(i,M(c,`server.mjs`)),L(M(c,`index.mjs`),Lr());for(let t of e.include)ot(M(n,t),M(c,t),{recursive:!0});if(L(M(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!P(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);ot(o,M(s,`static`),{recursive:!0,filter:e=>!Yr(o,e)})}let{crons:l,warnings:u}=Ur(Vr(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:zr(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};L(M(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${j(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 ei=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=O.resolve(e.cwd,`kick.config.ts`);if(!P(t))return null;let n=await C(e.cwd);if(!n?.assetMap)return null;let r=ze(n.assetMap,e.cwd);return r.count===0?null:Ye(r)}}),ti="/* 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 ni(e,t,n,r={}){if(e.length===0)return`${ti}
735
+ `)}\n`)}}let d=M(a,`netlify.toml`);if(P(d)){let e=Zr(F(d,`utf-8`)),r=j(a,M(n,u)).split(N).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();di(n,e.include);let i=await ai(n,e,t.log),a=M(n,e.siteRoot),o=e.staticDir?M(n,e.staticDir):void 0,s=M(a,`.vercel/output`),c=M(s,`functions/api.func`);ut(s,{recursive:!0,force:!0}),lt(c,{recursive:!0}),ct(i,M(c,`server.mjs`)),L(M(c,`index.mjs`),Xr());for(let t of e.include)ct(M(n,t),M(c,t),{recursive:!0});if(L(M(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!P(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);ct(o,M(s,`static`),{recursive:!0,filter:e=>!ci(o,e)})}let{crons:l,warnings:u}=ni(ei(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:Qr(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};L(M(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${j(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 pi=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=O.resolve(e.cwd,`kick.config.ts`);if(!P(t))return null;let n=await w(e.cwd);if(!n?.assetMap)return null;let r=Ve(n.assetMap,e.cwd);return r.count===0?null:Ze(r)}}),mi="/* eslint-disable */\n// AUTO-GENERATED by `kick typegen`. DO NOT EDIT.\n// Re-run with `kick typegen` or rely on `kick dev` to refresh.\n";function hi(e,t,n,r={}){if(e.length===0)return`${mi}
736
736
  // (no routes discovered yet — annotate a controller method with
737
737
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
738
738
  declare global {
@@ -749,14 +749,15 @@ declare global {
749
749
 
750
750
  /** Empty until the first route exists — see kick typegen. */
751
751
  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=oi(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??ii(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=ai(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${ri(e)}`,` }`)}n.push(` }`),l.push(n.join(`
753
- `))}let u=[],d=/* @__PURE__ */ new Set,f=/* @__PURE__ */ new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;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
- `);l.push(p);let m=[],h=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=li(e);if(h.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}h.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&m.push(` ${n}: {\n${i.join(`
755
- `)}\n },`)}let g=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...m,`} as const`].join(`
756
- `),_=[],v=/* @__PURE__ */ new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=ci(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
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=yi(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??_i(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=vi(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${gi(e)}`,` }`)}n.push(` }`),l.push(n.join(`
753
+ `))}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
+ `);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=Si(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
+ `)}\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=xi(``,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(`
757
758
  `)+`
758
- `:``,b=si(a)+y,ee=l.join(`
759
- `);return`${ti}${b}
759
+ `:``,x=bi(a)+b,ee=l.join(`
760
+ `);return`${mi}${x}
760
761
  declare global {
761
762
  // eslint-disable-next-line @typescript-eslint/no-namespace
762
763
  namespace KickRoutes {
@@ -767,19 +768,19 @@ ${ee}
767
768
  type KickApi = KickRoutes.Api
768
769
  }
769
770
 
770
- ${g}
771
- `}function ri(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function ii(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function ai(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 oi(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=ci(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 si(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(`
771
+ ${_}
772
+ `}function gi(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function _i(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function vi(e){let t=[];return e.queryFilterable&&e.queryFilterable.length>0&&t.push(`Filterable: ${e.queryFilterable.join(`, `)}`),e.querySortable&&e.querySortable.length>0&&t.push(`Sortable: ${e.querySortable.join(`, `)}`),e.querySearchable&&e.querySearchable.length>0&&t.push(`Searchable: ${e.querySearchable.join(`, `)}`),t}function yi(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=xi(e.source,t,n);if(a===`unknown`)return null;let o=`${a}::${e.identifier}`,s=i.get(o)?.specifier;return s?s=i.get(o).specifier:(s=`_S${i.size}`,i.set(o,{identifier:e.identifier,specifier:s})),s}function bi(e){if(e.size===0)return``;let t=[];for(let[n,r]of e){let[e]=n.split(`::`);t.push(`import type { ${r.identifier} as ${r.specifier} } from '${e}'`)}return t.join(`
772
773
  `)+`
773
- `}function ci(e,t,n){if(e===null)return`unknown`;let r=k(n);if(e===``){let e=j(r,t).split(N).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=k(t),a=M(i,e),o=j(r,a).split(N).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function li(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 ui=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:di(e),cwd:e.cwd,envFile:fi(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return ni(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function di(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function fi(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const pi=`@typescript/typescript6`;function mi(e){return typeof e?.createProgram==`function`}function hi(e){if(mi(e.typescript))return{api:e.typescript,source:`typescript`};if(mi(e.ts6))return{api:e.ts6,source:pi};let t=`Install it in the project:\n pnpm add -D ${pi}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
774
- 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 '${pi}' resolved from this project.\n ${t}`)}async function gi(e){let t=it(A(e,`package.json`)),n=async e=>{try{return await import(B(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(pi)]);return hi({typescript:_i(r),ts6:_i(i)}).api}function _i(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const vi=Symbol(`kick/client: expansion budget exhausted`);var yi=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!==vi)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 vi;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=`
774
+ `}function xi(e,t,n){if(e===null)return`unknown`;let r=k(n);if(e===``){let e=j(r,t).split(N).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=k(t),a=M(i,e),o=j(r,a).split(N).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function Si(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const Ci=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:wi(e),cwd:e.cwd,envFile:Ti(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return hi(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function wi(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ti(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Ei=`@typescript/typescript6`;function Di(e){return typeof e?.createProgram==`function`}function Oi(e){if(Di(e.typescript))return{api:e.typescript,source:`typescript`};if(Di(e.ts6))return{api:e.ts6,source:Ei};let t=`Install it in the project:\n ${a()} add -D ${Ei}`;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 '${Ei}' resolved from this project.\n ${t}`)}async function ki(e){let t=ot(A(e,`package.json`)),n=async e=>{try{return await import(B(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Ei)]);return Oi({typescript:Ai(r),ts6:Ai(i)}).api}function Ai(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const ji=Symbol(`kick/client: expansion budget exhausted`);var Mi=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!==ji)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 ji;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=`
775
776
  `){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===`
776
777
  `?`
777
- `: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 bi=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],xi=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Si(e){return vt(`sha1`).update(e).digest(`hex`)}function Ci(e){let t=vt(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
778
- `));for(let n of bi){let r=A(e.projectDir,n);if(P(r))try{t.update(F(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!xi.test(n)){t.update(n);try{t.update(F(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function wi(e){try{let t=await gi(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(A(e.projectDir,`tsconfig.json`),{},n);return r?Ci({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 Ti(e){let t=await gi(e.compilerFrom??e.projectDir),n=A(k(e.routesFile),`__kick_client_probe__.ts`),r=Oi(e.routesFile,e.keys),i=ji(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.`);Ei(t,i,e.routesFile);let s=ki(t,i,o,e.keys),c=null,l=new yi(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===Di(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 Ei(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(`
779
- `);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 Di(e){return`_K${e}`}function Oi(e,t){let n=`./`+at(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Di(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
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 Ni=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Pi=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Fi(e){return bt(`sha1`).update(e).digest(`hex`)}function Ii(e){let t=bt(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
779
+ `));for(let n of Ni){let r=A(e.projectDir,n);if(P(r))try{t.update(F(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Pi.test(n)){t.update(n);try{t.update(F(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Li(e){try{let t=await ki(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(A(e.projectDir,`tsconfig.json`),{},n);return r?Ii({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 Ri(e){let t=await ki(e.compilerFrom??e.projectDir),n=A(k(e.routesFile),`__kick_client_probe__.ts`),r=Vi(e.routesFile,e.keys),i=Wi(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.`);zi(t,i,e.routesFile);let s=Hi(t,i,o,e.keys),c=null,l=new Mi(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===Bi(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 zi(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 Bi(e){return`_K${e}`}function Vi(e,t){let n=`./`+st(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Bi(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
780
781
  `)+`
781
- `}function ki(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(Di(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Ai(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=I(t).filter(e=>e.endsWith(`.ts`)).map(e=>A(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function ji(e,t,n,r){let i=A(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
782
- `))}},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:[...Ai(o.fileNames,k(n)),n],options:o.options,host:s})}const Mi=`/* eslint-disable */
782
+ `}function Hi(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(Bi(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Ui(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=I(t).filter(e=>e.endsWith(`.ts`)).map(e=>A(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function Wi(e,t,n,r){let i=A(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:[...Ui(o.fileNames,k(n)),n],options:o.options,host:s})}const Gi=`/* eslint-disable */
783
784
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
784
785
  //
785
786
  // Self-contained: this file has no imports, so a frontend consumes it without
@@ -793,7 +794,7 @@ ${g}
793
794
  //
794
795
  // Written when \`kick dev\` starts, not on save — resolving these types builds a
795
796
  // full TypeScript program over the server. Re-run \`kick typegen\`.
796
- `;function Ni(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Mi}
797
+ `;function Ki(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Gi}
797
798
  // (no routes discovered yet — annotate a controller method with
798
799
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
799
800
  interface Api {}
@@ -810,7 +811,7 @@ export type { Api }
810
811
 
811
812
  `)+`
812
813
 
813
- `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Mi}
814
+ `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Gi}
814
815
  ${r}interface Api {
815
816
  ${i.join(`
816
817
  `)}
@@ -824,7 +825,7 @@ declare global {
824
825
  }
825
826
 
826
827
  export type { Api }
827
- `}const Pi=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,Fi=`.kickjs/cache/client-map.sha1`,Ii=(()=>{try{return it(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function Li(e){try{if(!P(e))return null;let[t,n]=F(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Ri(e){return`${sn}${Pi} */\n\n${e}\n`}function zi(e){try{return P(e)?F(e,`utf-8`):null}catch{return null}}async function Bi(e){let t=O.resolve(e.cwd,Q);if(!P(t))return!1;try{await pt(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 Vi(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function Hi(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(P(O.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 Ui=()=>({id:Pi,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!Hi(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:O.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=Vi(e.config),a=await wi({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Ii}),o=Li(O.resolve(e.cwd,Fi)),s=zi(O.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Si(s))return se()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=Ni(await Ti({projectDir:e.cwd,routesFile:O.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(Fi,`${a} ${Si(Ri(t))}`),t}catch(t){let n=P(O.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):se()&&e.log.info?.(r),n&&await Bi(e),null}}});function Wi(e,t,n=`zod`){if(!e)return null;let r=k(t),i=j(r,e.filePath).split(N).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
828
+ `}const qi=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,Ji=`.kickjs/cache/client-map.sha1`,Yi=(()=>{try{return ot(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function Xi(e){try{if(!P(e))return null;let[t,n]=F(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Zi(e){return`${ln}${qi} */\n\n${e}\n`}function Qi(e){try{return P(e)?F(e,`utf-8`):null}catch{return null}}async function $i(e){let t=O.resolve(e.cwd,Q);if(!P(t))return!1;try{await ht(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 ea(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function ta(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(P(O.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 na=()=>({id:qi,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!ta(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:O.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=ea(e.config),a=await Li({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Yi}),o=Xi(O.resolve(e.cwd,Ji)),s=Qi(O.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Fi(s))return le()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=Ki(await Ri({projectDir:e.cwd,routesFile:O.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(Ji,`${a} ${Fi(Zi(t))}`),t}catch(t){let n=P(O.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 $i(e),null}}});function ra(e,t,n=`zod`){if(!e)return null;let r=k(t),i=j(r,e.filePath).split(N).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
828
829
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
829
830
  // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
830
831
 
@@ -862,6 +863,6 @@ declare global {
862
863
  }
863
864
 
864
865
  export {}
865
- `}const Gi=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=qi(e);if(t===!1)return null;let n=await e.getScanResult({root:Ki(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=O.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Wi(n.env,i,r)}});function Ki(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function qi(e){return e.config?.typegen?.envFile}function Ji(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Yi(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ji(e),cwd:e.cwd,envFile:Yi(e)}}const Xi=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=O.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ue(t.classes,n,r)}}),Zi=()=>({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 Je(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Qi=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return Je(`ModuleToken`,Ve(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),$i=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return He(t.pluginsAndAdapters)}}),ea=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:et(t.contextKeys)}}),ta=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return Xe(t.routeFlags)}}),na={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},ra=[E({name:`kick/init`,register:Tt}),E({name:`kick/generate`,register:an}),E({name:`kick/run`,register:yn}),E({name:`kick/info`,register:wn}),E({name:`kick/inspect`,register:Nn}),E({name:`kick/add`,register:we}),E({name:`kick/list`,register:Ee}),E({name:`kick/explain`,register:Hn}),E({name:`kick/mcp`,register:Qn}),E({name:`kick/tinker`,register:nr}),E({name:`kick/remove`,register:cr}),E({name:`kick/typegen`,register:dr}),E({name:`kick/check`,register:Ar}),E({name:`kick/doctor`,register:ge}),E({name:`kick/codemod`,register:Mr}),E({name:`kick/deploy`,register:$r}),E({name:`kick/registry`,typegens:[Xi()]}),E({name:`kick/services`,typegens:[Zi()]}),E({name:`kick/modules`,typegens:[Qi()]}),E({name:`kick/plugins`,typegens:[$i()]}),E({name:`kick/context`,typegens:[ea()]}),E({name:`kick/route-flags`,typegens:[ta()]}),E({name:`kick/assets`,typegens:[ei()]}),E({name:`kick/routes`,typegens:[ui()]}),E({name:`kick/client`,typegens:[Ui()]}),E({name:`kick/env`,typegens:[Gi()]}),E({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;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=na[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(`
866
- `)}}]})];export{un as applyDisableFilter,dn as n,Et as r,G as runAllPluginTypegens,ra as t};
867
- //# sourceMappingURL=run-plugins-0AfIgIsZ.mjs.map
866
+ `}const ia=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=oa(e);if(t===!1)return null;let n=await e.getScanResult({root:aa(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=O.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return ra(n.env,i,r)}});function aa(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function oa(e){return e.config?.typegen?.envFile}function sa(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ca(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:sa(e),cwd:e.cwd,envFile:ca(e)}}const la=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=O.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ge(t.classes,n,r)}}),ua=()=>({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=Ye(t.classes,t.tokens,t.injects,n);return Xe(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),da=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return Xe(`ModuleToken`,Ue(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),fa=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return We(t.pluginsAndAdapters)}}),pa=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:nt(t.contextKeys)}}),ma=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return Qe(t.routeFlags)}}),ha={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},ga=[E({name:`kick/init`,register:Dt}),E({name:`kick/generate`,register:sn}),E({name:`kick/run`,register:Tn}),E({name:`kick/info`,register:An}),E({name:`kick/inspect`,register:zn}),E({name:`kick/add`,register:Ae}),E({name:`kick/list`,register:Me}),E({name:`kick/explain`,register:Jn}),E({name:`kick/mcp`,register:ir}),E({name:`kick/tinker`,register:cr}),E({name:`kick/remove`,register:mr}),E({name:`kick/typegen`,register:_r}),E({name:`kick/check`,register:Ir}),E({name:`kick/doctor`,register:ve}),E({name:`kick/env-command`,register:Ur}),E({name:`kick/codemod`,register:Gr}),E({name:`kick/deploy`,register:fi}),E({name:`kick/registry`,typegens:[la()]}),E({name:`kick/services`,typegens:[ua()]}),E({name:`kick/modules`,typegens:[da()]}),E({name:`kick/plugins`,typegens:[fa()]}),E({name:`kick/context`,typegens:[pa()]}),E({name:`kick/route-flags`,typegens:[ma()]}),E({name:`kick/assets`,typegens:[pi()]}),E({name:`kick/routes`,typegens:[Ci()]}),E({name:`kick/client`,typegens:[na()]}),E({name:`kick/env`,typegens:[ia()]}),E({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;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=ha[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{fn as applyDisableFilter,pn as n,Ot as r,G as runAllPluginTypegens,ga as t};
868
+ //# sourceMappingURL=run-plugins-CeZS2Opt.mjs.map