@forinda/kickjs-cli 8.14.1 → 8.14.3

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 (38) hide show
  1. package/dist/{agent-docs-DA1ICOUV.mjs → agent-docs-brHNoyLK.mjs} +2 -2
  2. package/dist/{agent-docs-ClLUdXi9.mjs → agent-docs-tr9_AJYU.mjs} +3 -3
  3. package/dist/{agent-docs-ClLUdXi9.mjs.map → agent-docs-tr9_AJYU.mjs.map} +1 -1
  4. package/dist/{build-B1SVlQMj.mjs → build-CI56pcUZ.mjs} +3 -3
  5. package/dist/{build-B1SVlQMj.mjs.map → build-CI56pcUZ.mjs.map} +1 -1
  6. package/dist/{build-BNarDoas.mjs → build-DRfjqnqV.mjs} +2 -2
  7. package/dist/{builtins-DIdRQfIZ.mjs → builtins-C9MmvIBs.mjs} +37 -35
  8. package/dist/{builtins-C8CUXR7y.mjs → builtins-CfuSe-qw.mjs} +2 -2
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-BZ_DgqAb.mjs → config-DmEDJwvJ.mjs} +2 -2
  11. package/dist/{config-D3vAudYh.mjs → config-sixJ2517.mjs} +3 -3
  12. package/dist/{config-D3vAudYh.mjs.map → config-sixJ2517.mjs.map} +1 -1
  13. package/dist/{doctor-BYvatDDh.mjs → doctor-Bkhf8Adv.mjs} +24 -22
  14. package/dist/doctor-Bkhf8Adv.mjs.map +1 -0
  15. package/dist/{fullstack-NAgRR7Dj.mjs → fullstack-DAU0nTaN.mjs} +3 -3
  16. package/dist/{fullstack-BqwHqBWK.mjs → fullstack-srmNRn5h.mjs} +4 -4
  17. package/dist/{fullstack-BqwHqBWK.mjs.map → fullstack-srmNRn5h.mjs.map} +1 -1
  18. package/dist/index.mjs +2 -2
  19. package/dist/{package-manager-BIKlWb_z.mjs → package-manager-L8IEB6v4.mjs} +3 -3
  20. package/dist/{package-manager-BIKlWb_z.mjs.map → package-manager-L8IEB6v4.mjs.map} +1 -1
  21. package/dist/{package-manager-vtILOPAv.mjs → package-manager-n73HlY1T.mjs} +2 -2
  22. package/dist/{plugin-DkhJMphG.mjs → plugin-Cccp0Rzz.mjs} +2 -2
  23. package/dist/{plugin-BOpVRMKa.mjs → plugin-T3Aes85q.mjs} +2 -2
  24. package/dist/{project-BMojPey-.mjs → project-DVOYSwrb.mjs} +5 -5
  25. package/dist/{project-BMojPey-.mjs.map → project-DVOYSwrb.mjs.map} +1 -1
  26. package/dist/{project-BGfW_cup.mjs → project-mWxqd_g2.mjs} +4 -4
  27. package/dist/{project-root-DvXJgSgx.mjs → project-root-CVGTdH_N.mjs} +2 -2
  28. package/dist/{project-root-BQKspC3k.mjs → project-root-u6rwcIHh.mjs} +3 -3
  29. package/dist/{project-root-BQKspC3k.mjs.map → project-root-u6rwcIHh.mjs.map} +1 -1
  30. package/dist/{rolldown-runtime-C_ICmTLf.mjs → rolldown-runtime-DB9qXK5A.mjs} +1 -1
  31. package/dist/{run-plugins-PuTINHKr.mjs → run-plugins-DXxLu7EH.mjs} +4 -4
  32. package/dist/{run-plugins-PuTINHKr.mjs.map → run-plugins-DXxLu7EH.mjs.map} +1 -1
  33. package/dist/{typegen-DCJ5718N.mjs → typegen-Bdo4S6uC.mjs} +5 -5
  34. package/dist/{typegen-DCJ5718N.mjs.map → typegen-Bdo4S6uC.mjs.map} +1 -1
  35. package/dist/{typegen-BDdaN5Se.mjs → typegen-DaeXT-vU.mjs} +4 -4
  36. package/dist/{types-DOfGMqCL.mjs → types-COk7vdvT.mjs} +1 -1
  37. package/package.json +5 -5
  38. package/dist/doctor-BYvatDDh.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.14.1
2
+ * @forinda/kickjs-cli v8.14.3
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-C_ICmTLf.mjs";import{T as t,_ as n,a as r,d as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,w as v,y}from"./project-BGfW_cup.mjs";import{a as b,c as x,d as S,f as ee,i as te,l as ne,m as re,o as C,p as ie,s as w,u as ae}from"./config-BZ_DgqAb.mjs";import{n as oe,r as T}from"./plugin-BOpVRMKa.mjs";import{_ as E,a as se,c as D,d as ce,f as le,g as O,h as ue,i as de,l as fe,m as pe,n as me,o as k,p as A,r as he,s as ge,t as j,u as _e}from"./package-manager-vtILOPAv.mjs";import{t as M}from"./project-root-DvXJgSgx.mjs";import{n as ve}from"./agent-docs-DA1ICOUV.mjs";import{C as ye,S as be,_ as xe,a as Se,b as Ce,c as we,d as Te,f as Ee,g as De,h as Oe,i as ke,l as Ae,m as je,o as Me,p as Ne,r as Pe,s as Fe,t as Ie,u as Le,v as Re,w as ze,x as Be,y as Ve}from"./typegen-BDdaN5Se.mjs";import{t as He}from"./build-BNarDoas.mjs";import{createRequire as Ue}from"node:module";import{cpSync as We,existsSync as N,mkdirSync as Ge,readFileSync as P,readdirSync as F,rmSync as Ke,statSync as qe,writeFileSync as I}from"node:fs";import L,{basename as Je,dirname as R,join as z,relative as B,resolve as V,sep as H}from"node:path";import{fileURLToPath as Ye,pathToFileURL as U}from"node:url";import{fork as Xe,spawn as Ze,spawnSync as Qe}from"node:child_process";import{copyFile as $e,mkdir as et,readFile as W,readdir as tt,rm as nt,stat as rt,writeFile as it}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as at}from"node:crypto";import{parseSync as ot}from"oxc-parser";import st from"pluralize";import{arch as ct,platform as lt,release as ut}from"node:os";const dt=[{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 ft(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack | inertia`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`--deploy <targets>`,`Comma-separated deploy targets to write files for: netlify, vercel, docker (later: kick g deploy)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{se(`KickJS — Create a new project`);let n=p(),r=e=>{e&&k.warn(`kick ${h} is behind the latest release, ${e} — templates and options added since are missing. Upgrade: npm i -g @forinda/kickjs-cli@latest`)},i=[];try{i=t.deploy?y(t.deploy):[]}catch(e){k.error(e.message),D(`Aborted.`),process.exitCode=1;return}let a=!!(t.yes||t.nonInteractive);e||=a?`my-api`:await ce({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let o;if(e===`.`?(o=V(`.`),e=Je(o)):o=V(t.directory||e),N(o)){let n=F(o);if(n.length>0){if(t.force)k.warn(`Clearing existing files in ${o}`);else if(a){k.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),D(`Aborted.`);return}else{k.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)k.message(` - ${e}`);if(n.length>5&&k.message(` ... and ${n.length-5} more`),!await de({message:A.red(`Remove all existing files and proceed?`),initialValue:!1})){D(`Aborted.`);return}}for(let e of n)Ke(V(o,e),{recursive:!0,force:!0})}}a||r(await Promise.race([n,new Promise(e=>setTimeout(e,3e3,null).unref())]));let s=t.template;s||=a?`minimal`:await fe({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||=a?`express`:await fe({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 l=t.pm;l||=a?await me(void 0):await fe({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let d=t.repo;d||=a?`inmemory`:await ce({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),re(d);let f=t.schema;s===`inertia`&&(f&&f!==`zod`&&k.warn(`The inertia template uses zod — ignoring --schema ${f}.`),f=`zod`),f||=a?`zod`:await fe({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(f)||(k.warn(`Unknown --schema "${f}", falling back to zod.`),f=`zod`);let m;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();m=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else m=a?[]:await ge({message:`Select packages to include`,options:[...dt],required:!1});let g;g=t.git===void 0?a?!0:await de({message:`Initialize git repository?`,initialValue:!0}):t.git;let _;if(_=t.install===void 0?a?!0:await de({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){k.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),D(`Aborted.`);return}let{VITE_TEMPLATES:v,DEFAULT_VITE_TEMPLATE:b}=await import(`./fullstack-NAgRR7Dj.mjs`);if(t.viteTemplate!==void 0&&!v.some(e=>e.value===t.viteTemplate)){k.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${v.map(e=>e.value).join(`, `)}.`),D(`Aborted.`);return}let x=t.frontend===`vite`?`vite`:`kick`,S=t.viteTemplate??b;if(s===`fullstack`&&!t.frontend&&!a&&(x=await fe({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&&!a&&(S=await fe({message:`create-vite template`,options:v.map(e=>({value:e.value,label:e.label})),initialValue:b})),s===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-NAgRR7Dj.mjs`);await t({name:e,directory:o,packageManager:l,initGit:g,installDeps:_,schemaLib:f,runtime:c,packages:m,frontend:x,viteTemplate:S,deploy:i}),a&&r(await n),D(`Done! Next steps: ${A.cyan(`cd ${e} && ${l}${l===`pnpm`?` dev`:` run dev:server`}`)}`)}else await u({name:e,directory:o,packageManager:l,initGit:g,installDeps:_,template:s,defaultRepo:d,packages:m,schemaLib:f,runtime:c,deploy:i}),a&&r(await n),D(`Done! Next steps: ${A.cyan(`cd ${e} && ${ee(l,`dev`)}`)}`)})}st.addUncountableRule(`auth`);function G(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function pt(e){let t=G(e);return t.charAt(0).toLowerCase()+t.slice(1)}function K(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function q(e){return st.plural(e)}function mt(e){return st.plural(e)}function ht(e){return K(e).replace(/-/g,`_`)}function gt(e){let t=e.cwd??process.cwd(),n=e.projectRoot??M(t),r=e.pluralize??!1,i=G(e.name),a=pt(e.name),o=K(e.name),s=ht(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=q(o);c.pluralKebab=e,c.pluralPascal=G(e),c.pluralCamel=pt(e)}return c}function _t(e,t){return V(e.cwd,t)}async function vt(e){return import(U(e).href)}const yt=/* @__PURE__ */ new Map;async function bt(e){let t=yt.get(e);if(t)return t;let n=xt(e);return yt.set(e,n),n}async function xt(e){let t=V(e,`package.json`);if(!N(t))return{generators:[],loaded:[],failed:[]};let n=St(JSON.parse(await W(t,`utf-8`))),r=Ue(V(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await W(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=V(R(t),s);if(!N(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await vt(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u))o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});else{for(let t of u)Ct(t)?i.push({source:e,spec:t}):o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});a.push(e)}}return{generators:i,loaded:a,failed:o}}function St(e){let t=/* @__PURE__ */ new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function Ct(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function wt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Dt(r.spec,r.source,e,n);let i=Et(await bt(n),e.generatorName);return i?Dt(i.spec,i.source,e,n):null}async function Tt(e,t=[]){let n=await bt(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function Et(e,t){return e.generators.find(e=>e.spec.name===t)}async function Dt(e,t,n,r){let i=gt({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=_t(i,e.path);await E(t,e.content),o.push(t)}return{files:o,source:t}}function Ot(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const kt={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function At(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function jt(e){return kt[e]??At(e)}function Mt(e){return`create${e}Repository`}function Nt(e){return e??`define`}function Pt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=e.routePath??r,s=Mt(t),c=Nt(a),l=`/**
11
+ import{t as e}from"./rolldown-runtime-DB9qXK5A.mjs";import{T as t,_ as n,a as r,d as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,u as g,v as _,w as v,y}from"./project-mWxqd_g2.mjs";import{a as b,c as x,d as S,f as ee,i as te,l as ne,m as re,o as C,p as ie,s as w,u as ae}from"./config-DmEDJwvJ.mjs";import{n as oe,r as T}from"./plugin-T3Aes85q.mjs";import{_ as E,a as se,c as D,d as ce,f as le,g as O,h as ue,i as de,l as fe,m as pe,n as me,o as k,p as A,r as he,s as ge,t as j,u as _e}from"./package-manager-n73HlY1T.mjs";import{t as M}from"./project-root-CVGTdH_N.mjs";import{n as ve}from"./agent-docs-brHNoyLK.mjs";import{C as ye,S as be,_ as xe,a as Se,b as Ce,c as we,d as Te,f as Ee,g as De,h as Oe,i as ke,l as Ae,m as je,o as Me,p as Ne,r as Pe,s as Fe,t as Ie,u as Le,v as Re,w as ze,x as Be,y as Ve}from"./typegen-DaeXT-vU.mjs";import{t as He}from"./build-DRfjqnqV.mjs";import{createRequire as Ue}from"node:module";import{cpSync as We,existsSync as N,mkdirSync as Ge,readFileSync as P,readdirSync as F,rmSync as Ke,statSync as qe,writeFileSync as I}from"node:fs";import L,{basename as Je,dirname as R,join as z,relative as B,resolve as V,sep as H}from"node:path";import{fileURLToPath as Ye,pathToFileURL as U}from"node:url";import{fork as Xe,spawn as Ze,spawnSync as Qe}from"node:child_process";import{copyFile as $e,mkdir as et,readFile as W,readdir as tt,rm as nt,stat as rt,writeFile as it}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as at}from"node:crypto";import{parseSync as ot}from"oxc-parser";import st from"pluralize";import{arch as ct,platform as lt,release as ut}from"node:os";const dt=[{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 ft(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack | inertia`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`--deploy <targets>`,`Comma-separated deploy targets to write files for: netlify, vercel, docker (later: kick g deploy)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{se(`KickJS — Create a new project`);let n=p(),r=e=>{e&&k.warn(`kick ${h} is behind the latest release, ${e} — templates and options added since are missing. Upgrade: npm i -g @forinda/kickjs-cli@latest`)},i=[];try{i=t.deploy?y(t.deploy):[]}catch(e){k.error(e.message),D(`Aborted.`),process.exitCode=1;return}let a=!!(t.yes||t.nonInteractive);e||=a?`my-api`:await ce({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let o;if(e===`.`?(o=V(`.`),e=Je(o)):o=V(t.directory||e),N(o)){let n=F(o);if(n.length>0){if(t.force)k.warn(`Clearing existing files in ${o}`);else if(a){k.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),D(`Aborted.`);return}else{k.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)k.message(` - ${e}`);if(n.length>5&&k.message(` ... and ${n.length-5} more`),!await de({message:A.red(`Remove all existing files and proceed?`),initialValue:!1})){D(`Aborted.`);return}}for(let e of n)Ke(V(o,e),{recursive:!0,force:!0})}}a||r(await Promise.race([n,new Promise(e=>setTimeout(e,3e3,null).unref())]));let s=t.template;s||=a?`minimal`:await fe({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||=a?`express`:await fe({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 l=t.pm;l||=a?await me(void 0):await fe({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let d=t.repo;d||=a?`inmemory`:await ce({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),re(d);let f=t.schema;s===`inertia`&&(f&&f!==`zod`&&k.warn(`The inertia template uses zod — ignoring --schema ${f}.`),f=`zod`),f||=a?`zod`:await fe({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(f)||(k.warn(`Unknown --schema "${f}", falling back to zod.`),f=`zod`);let m;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();m=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else m=a?[]:await ge({message:`Select packages to include`,options:[...dt],required:!1});let g;g=t.git===void 0?a?!0:await de({message:`Initialize git repository?`,initialValue:!0}):t.git;let _;if(_=t.install===void 0?a?!0:await de({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){k.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),D(`Aborted.`);return}let{VITE_TEMPLATES:v,DEFAULT_VITE_TEMPLATE:b}=await import(`./fullstack-DAU0nTaN.mjs`);if(t.viteTemplate!==void 0&&!v.some(e=>e.value===t.viteTemplate)){k.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${v.map(e=>e.value).join(`, `)}.`),D(`Aborted.`);return}let x=t.frontend===`vite`?`vite`:`kick`,S=t.viteTemplate??b;if(s===`fullstack`&&!t.frontend&&!a&&(x=await fe({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&&!a&&(S=await fe({message:`create-vite template`,options:v.map(e=>({value:e.value,label:e.label})),initialValue:b})),s===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DAU0nTaN.mjs`);await t({name:e,directory:o,packageManager:l,initGit:g,installDeps:_,schemaLib:f,runtime:c,packages:m,frontend:x,viteTemplate:S,deploy:i}),a&&r(await n),D(`Done! Next steps: ${A.cyan(`cd ${e} && ${l}${l===`pnpm`?` dev`:` run dev:server`}`)}`)}else await u({name:e,directory:o,packageManager:l,initGit:g,installDeps:_,template:s,defaultRepo:d,packages:m,schemaLib:f,runtime:c,deploy:i}),a&&r(await n),D(`Done! Next steps: ${A.cyan(`cd ${e} && ${ee(l,`dev`)}`)}`)})}st.addUncountableRule(`auth`);function G(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function pt(e){let t=G(e);return t.charAt(0).toLowerCase()+t.slice(1)}function K(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function q(e){return st.plural(e)}function mt(e){return st.plural(e)}function ht(e){return K(e).replace(/-/g,`_`)}function gt(e){let t=e.cwd??process.cwd(),n=e.projectRoot??M(t),r=e.pluralize??!1,i=G(e.name),a=pt(e.name),o=K(e.name),s=ht(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=q(o);c.pluralKebab=e,c.pluralPascal=G(e),c.pluralCamel=pt(e)}return c}function _t(e,t){return V(e.cwd,t)}async function vt(e){return import(U(e).href)}const yt=/* @__PURE__ */ new Map;async function bt(e){let t=yt.get(e);if(t)return t;let n=xt(e);return yt.set(e,n),n}async function xt(e){let t=V(e,`package.json`);if(!N(t))return{generators:[],loaded:[],failed:[]};let n=St(JSON.parse(await W(t,`utf-8`))),r=Ue(V(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await W(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=V(R(t),s);if(!N(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await vt(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u))o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});else{for(let t of u)Ct(t)?i.push({source:e,spec:t}):o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});a.push(e)}}return{generators:i,loaded:a,failed:o}}function St(e){let t=/* @__PURE__ */ new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function Ct(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function wt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Dt(r.spec,r.source,e,n);let i=Et(await bt(n),e.generatorName);return i?Dt(i.spec,i.source,e,n):null}async function Tt(e,t=[]){let n=await bt(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function Et(e,t){return e.generators.find(e=>e.spec.name===t)}async function Dt(e,t,n,r){let i=gt({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=_t(i,e.path);await E(t,e.content),o.push(t)}return{files:o,source:t}}function Ot(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const kt={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function At(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function jt(e){return kt[e]??At(e)}function Mt(e){return`create${e}Repository`}function Nt(e){return e??`define`}function Pt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=e.routePath??r,s=Mt(t),c=Nt(a),l=`/**
12
12
  * ${t} Module
13
13
  *
14
14
  * REST module with a flat folder structure.
@@ -1515,7 +1515,7 @@ describe('${s}', () => {
1515
1515
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
1516
1516
  Optional: append :optional (shell-safe, no quoting needed)
1517
1517
  `),process.exit(1));let o=await C(process.cwd()),s=w(o),c=i.modulesDir??s.dir??`src/modules`,l=Fn(t),u=S(o,process.cwd()),d=b(M()),f=await In({name:e,fields:l,modulesDir:V(c),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:x(i.pluralize,s),pluralizeRoutes:ne(i.pluralizeRoutes,s),tokenScope:u,swagger:d,style:s.style});console.log(`\n Scaffolded ${e} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);Y(f,a),await Wn(a)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=J(t);O(n),Y(await yn({outDir:V(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate .agents/* + root CLAUDE.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | gemini | copilot | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (default: detected from kick.config, packageManager, or the lockfile)`).option(`--template <template>`,`Template: rest | minimal | fullstack | inertia`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=J(t);O(n);let r=e.only??`all`;Un.includes(r)?Y(await ve({outDir:V(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n):(console.error(` Invalid --only value: ${r}. Expected: ${Un.join(` | `)}`),process.exitCode=1)}),n.command(`deploy <targets...>`).description(`Add deploy files: netlify | vercel | docker (config, serverless entry, build script)`).option(`--pm <pm>`,`Package manager (default: detected)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=J(n);O(r);let i;try{i=y(e.flatMap(e=>e.split(`,`))),Y(await _({dir:V(`.`),targets:i,pm:t.pm,force:t.force}),r)}catch(e){console.error(` ${e.message}`),process.exitCode=1}});for(let e of t?.generators??[])Qn(n,e,t?.projectRoot)}function Qn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=J(o);O(s);let c=await wt({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&Y(c.files,s)})}const $n=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function er(e){let t=L.resolve(e.cwd,`.kickjs/types`);e.check||await et(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??Oe,i=L.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(U(e).href)},async writeFile(t,n){let r=L.resolve(e.cwd,t);await et(L.dirname(r),{recursive:!0}),await it(r,n,`utf8`)},getScanResult:e=>{let t=tr(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?De(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=L.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=`${$n}${n.id} */\n\n`+a+`
1518
- `,u=``;N(i)&&(u=await W(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 it(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new Hn(c);return s}function tr(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 nr(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 rr=/* @__PURE__ */ e({applyDisableFilter:()=>nr,runAllPluginTypegens:()=>ir});async function ir(e){let t=[...ys,...e.config?.plugins??[]],{enabled:n,skipped:r,unknown:i}=nr(oe(t,e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&r.length>0)for(let e of r)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&i.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${i.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),n.length===0)return[];try{let t=await er({cwd:e.cwd,config:e.config??{},plugins:n,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Vn())for(let e of t)console.log(` ${e.id}: ${e.status}`);return t}catch(t){if(t instanceof Hn||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function ar(e){let t=/* @__PURE__ */ new Map;return{report(n,r){let i=r instanceof Error?r.message:String(r);t.get(n)!==i&&(t.set(n,i),e(` kick typegen: ${n} pass failed (${i}) — types in .kickjs/types may be stale`))},clear(e){t.delete(e)}}}const or=`__kickjs_typegen_owner`;function sr(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-BDdaN5Se.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>rr)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-BDdaN5Se.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-BNarDoas.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=L.resolve(t,n?.typegen?.outDir??`.kickjs/types`),c=n?.assetMap?Object.values(n.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>L.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,u=e=>e.replaceAll(`\\`,`/`),d=c.map(u),f=e=>{let t=u(e);return d.some(e=>t===e||t.startsWith(`${e}/`))},p=ar(e.emitWarning),m=null,h=!1,g=/* @__PURE__ */ new Set,_=/* @__PURE__ */ new Set,v=!1,y=!1;function b(r,c){i.runTypegen({cwd:t,silent:!0,allowDuplicates:!0,schemaValidator:a,envFile:o,srcDir:n?.typegen?.srcDir,outDir:n?.typegen?.outDir,assetMap:n?.assetMap,changedFiles:r,runPlugins:!1}).then(()=>p.clear(`scan`)).catch(e=>p.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r,watch:!0}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>p.clear(`plugins`)).catch(e=>p.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function x(){let e=v?void 0:{changed:[...g],removed:[..._]},t=y;g.clear(),_.clear(),v=!1,y=!1,b(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!h&&!u(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)v=!0,l&&(y=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=f(t);if(!n&&!r)return;r&&l&&(y=!0),n&&(e===`unlink`?(_.add(t),g.delete(t)):(g.add(t),_.delete(t)))}m&&clearTimeout(m),m=setTimeout(x,r)}},runOnce(){h||b(void 0,l)},dispose(){h=!0,m&&clearTimeout(m),m=null}}}function cr(e){let t=process.platform===`win32`;for(let n of lr(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=z(n,i);if(N(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function lr(e){let t=V(e),n=ur(t);return(n?[t,n]:[t]).map(e=>z(e,`node_modules`,`.bin`))}function ur(e){for(let t=R(e);t!==R(t);t=R(t)){let n=z(t,`pnpm-workspace.yaml`),r=z(t,`package.json`);if(N(n)||N(r))return dr(n,r).some(n=>fr(n,B(t,e)))?t:void 0}}function dr(e,t){try{if(N(e)){let t=P(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
1518
+ `,u=``;N(i)&&(u=await W(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 it(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new Hn(c);return s}function tr(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 nr(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 rr=/* @__PURE__ */ e({applyDisableFilter:()=>nr,runAllPluginTypegens:()=>ir});async function ir(e){let t=[...Ss,...e.config?.plugins??[]],{enabled:n,skipped:r,unknown:i}=nr(oe(t,e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&r.length>0)for(let e of r)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&i.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${i.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),n.length===0)return[];try{let t=await er({cwd:e.cwd,config:e.config??{},plugins:n,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Vn())for(let e of t)console.log(` ${e.id}: ${e.status}`);return t}catch(t){if(t instanceof Hn||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function ar(e){let t=/* @__PURE__ */ new Map;return{report(n,r){let i=r instanceof Error?r.message:String(r);t.get(n)!==i&&(t.set(n,i),e(` kick typegen: ${n} pass failed (${i}) — types in .kickjs/types may be stale`))},clear(e){t.delete(e)}}}const or=`__kickjs_typegen_owner`;function sr(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-DaeXT-vU.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>rr)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-DaeXT-vU.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-DRfjqnqV.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=L.resolve(t,n?.typegen?.outDir??`.kickjs/types`),c=n?.assetMap?Object.values(n.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>L.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,u=e=>e.replaceAll(`\\`,`/`),d=c.map(u),f=e=>{let t=u(e);return d.some(e=>t===e||t.startsWith(`${e}/`))},p=ar(e.emitWarning),m=null,h=!1,g=/* @__PURE__ */ new Set,_=/* @__PURE__ */ new Set,v=!1,y=!1;function b(r,c){i.runTypegen({cwd:t,silent:!0,allowDuplicates:!0,schemaValidator:a,envFile:o,srcDir:n?.typegen?.srcDir,outDir:n?.typegen?.outDir,assetMap:n?.assetMap,changedFiles:r,runPlugins:!1}).then(()=>p.clear(`scan`)).catch(e=>p.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r,watch:!0}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>p.clear(`plugins`)).catch(e=>p.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function x(){let e=v?void 0:{changed:[...g],removed:[..._]},t=y;g.clear(),_.clear(),v=!1,y=!1,b(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!h&&!u(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)v=!0,l&&(y=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=f(t);if(!n&&!r)return;r&&l&&(y=!0),n&&(e===`unlink`?(_.add(t),g.delete(t)):(g.add(t),_.delete(t)))}m&&clearTimeout(m),m=setTimeout(x,r)}},runOnce(){h||b(void 0,l)},dispose(){h=!0,m&&clearTimeout(m),m=null}}}function cr(e){let t=process.platform===`win32`;for(let n of lr(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=z(n,i);if(N(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function lr(e){let t=V(e),n=ur(t);return(n?[t,n]:[t]).map(e=>z(e,`node_modules`,`.bin`))}function ur(e){for(let t=R(e);t!==R(t);t=R(t)){let n=z(t,`pnpm-workspace.yaml`),r=z(t,`package.json`);if(N(n)||N(r))return dr(n,r).some(n=>fr(n,B(t,e)))?t:void 0}}function dr(e,t){try{if(N(e)){let t=P(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
1519
1519
  `)){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(P(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function fr(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(H).join(`/`))}function pr(e){let t=e.spawnFn??Ze,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 mr(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
1520
1520
  `):`${n.slice(0,t).join(`
1521
1521
  `)}\n… ${n.length-t} more line(s)`}function hr(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function gr(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 _r(e,t,n={}){t&&(process.env.PORT=t);let r=hr(n.polling),i=process.cwd(),a=await C(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await Ie({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=V(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await ir({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(V(`package.json`)).resolve(`vite`),{createServer:d}=await import(U(u).href);globalThis[or]=`kick-dev`;let f=await d({configFile:V(`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=cr(i);e?m=pr({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(mr(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=sr({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(`
@@ -1850,7 +1850,7 @@ server.on('exit', () => {
1850
1850
  Cancelled.
1851
1851
  `);return}await nt(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=z(n,`index.ts`);if(await ue(l)){let e=await W(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${Ot(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${Ot(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Ai(e,o),e=e.replace(/\n{3,}/g,`
1852
1852
 
1853
- `),e!==t&&(await E(l,e),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Mi(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--pluralize`,`The module folder is pluralized (users/ for user)`).option(`--no-pluralize`,`The module folder is the name as typed (the default)`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await C(process.cwd()),r=w(n),i=t.modulesDir??r.dir??`src/modules`,a=x(t.pluralize,r);for(let n of e)await ji({name:n,modulesDir:V(i),force:t.force,pluralize:a})})}function Ni(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 Pi(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Fi(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=M(process.cwd()),n=await C(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-BOpVRMKa.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>vs),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(`
1853
+ `),e!==t&&(await E(l,e),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Mi(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--pluralize`,`The module folder is pluralized (users/ for user)`).option(`--no-pluralize`,`The module folder is the name as typed (the default)`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await C(process.cwd()),r=w(n),i=t.modulesDir??r.dir??`src/modules`,a=x(t.pluralize,r);for(let n of e)await ji({name:n,modulesDir:V(i),force:t.force,pluralize:a})})}function Ni(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 Pi(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Fi(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=M(process.cwd()),n=await C(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-T3Aes85q.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>xs),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(`
1854
1854
  Registered typegen plugins:
1855
1855
  `);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(`
1856
1856
  Disable one in kick.config.ts:
@@ -1866,34 +1866,36 @@ server.on('exit', () => {
1866
1866
  Available checks:
1867
1867
  --deploy Audit for production readiness (security, config, best practices)
1868
1868
  --di Find REQUEST-scoped dependencies injected into singleton constructors
1869
- `);return}let t=process.cwd();se(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=_e();n.start(`Scanning project...`);let r=[...e.deploy?Qi(t):[],...e.di?$i(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)k.message(`${pe(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?A.red(`${a} critical`):`${a} critical`,o>0?A.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(D(A.red(`${l} — fix critical issues before deploying`)),process.exit(1)):D(A.green(`${l} — looking good!`))})}function ta(e){try{return JSON.parse(P(e,`utf-8`))}catch{return null}}function na(e){try{return P(e,`utf-8`)}catch{return null}}function ra(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function ia(e){let t=z(e,`tsconfig.json`);if(N(t))return aa(t,/* @__PURE__ */ new Set)}function aa(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=na(e);if(n===null)return null;let r=ra(n);if(typeof r!=`object`||!r)return null;let i=Array.isArray(r.extends)?r.extends:typeof r.extends==`string`?[r.extends]:[],a={};for(let n of i){if(typeof n!=`string`)continue;let r=oa(R(e),n);if(!r)continue;let i=aa(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function oa(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return sa(V(e,t));let n=e;for(;;){let e=sa(z(n,`node_modules`,t));if(e)return e;let r=R(n);if(r===n)break;n=r}return null}function sa(e){if(N(e)){try{if(qe(e).isDirectory()){let t=z(e,`tsconfig.json`);return N(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return N(t)?t:null}function ca(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function la(){let e=process.version,t=Number.parseInt(e.replace(/^v/,``).split(`.`)[0],10);return Number.isNaN(t)||t<20?{name:`Node version`,status:`fail`,message:e,fix:`KickJS requires Node 20 or newer.
1870
- Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function ua(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function da(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:`\`@forinda/kickjs\` declares \`express\` as a required peer dependency, but your package.json does not include it. Install: ${j(e.cwd)} add express`}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const fa={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function pa(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=fa[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: ${j(e.cwd)} add ${n.join(` `)}`}:e.runtime===`h3`&&ma(e.cwd,t.h3)===1?{name:r,status:`fail`,message:`h3 v1`,fix:`This version of @forinda/kickjs runs on h3 v2 only. Upgrade: ${j(e.cwd)} add h3@^2 — no code change for apps that only use KickJS APIs.`}:{name:r,status:`pass`}}function ma(e,t){let n=t;for(let t=V(e);;t=R(t)){try{n=JSON.parse(P(z(t,`node_modules`,`h3`,`package.json`),`utf8`)).version;break}catch{}if(R(t)===t)break}let r=/(\d+)/.exec(n)?.[1];return r===void 0?void 0:Number(r)}function ha(e){if(!e.pkg||!_a(e.cwd))return null;let t=m[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or ${j(e.cwd)} add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const ga=2e3;function _a(e){let t=z(e,`src`);if(!N(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<ga;){let e=r.pop(),t;try{t=F(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=ga)break;let t=z(e,a.name);if(a.isDirectory())a.name!==`node_modules`&&r.push(t);else if(/\.(ts|tsx|mts|cts)$/.test(a.name)&&(i++,n.test(na(t)??``)))return!0}}return!1}function va(e){if(!e.pkg)return{name:`reflect-metadata installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies};return t[`reflect-metadata`]?{name:`reflect-metadata installed`,status:`pass`,message:t[`reflect-metadata`]}:{name:`reflect-metadata installed`,status:`fail`,fix:`KickJS decorators require the reflect-metadata polyfill.\nInstall it: ${j(e.cwd)} add reflect-metadata\nThen import it at the top of src/index.ts:\n\n import 'reflect-metadata'\n // ... rest of bootstrap`}}function ya(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function ba(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>z(e.cwd,t)).filter(e=>N(e)).filter(e=>/\bloadEnv\s*\(/.test(na(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>z(e.cwd,t)).find(e=>N(e));if(!n)return{name:`env wiring`,status:`warn`,message:`env-init file exists but no src/index.ts or src/main.ts found`};let r=na(n)??``,i=R(n),a=[];for(let e of t){let t=B(i,e).replace(/\\/g,`/`).replace(/\.ts$/,``),n=t.startsWith(`.`)?t:`./`+t,r=n.replace(/\/index$/,``);a.push(n,r);let o=e.replace(/\\/g,`/`).match(/\/src\/(.+?)(?:\.ts)?$/);if(o){let e=`@/`+o[1],t=e.replace(/\/index$/,``);a.push(e,t)}}let o=-1;for(let e of new Set(a)){let t=RegExp(`^import\\s+(?:.*?from\\s+)?['"]${ca(e)}['"]`,`m`),n=r.match(t);n&&n.index!==void 0&&(o===-1||n.index<o)&&(o=n.index)}let s=r.search(/\bbootstrap\s*\(/),c=t.map(t=>B(e.cwd,t).replace(/\\/g,`/`)).join(`, `);return o===-1?{name:`env wiring`,status:`fail`,message:c,fix:`An env-init file (${c}) calls \`loadEnv(...)\` but \`${B(e.cwd,n).replace(/\\/g,`/`)}\` doesn't import it.\nWithout this, ConfigService.get('X') returns undefined while @Value('X') works via process.env fallback — a half-broken config you won't notice until something is missing.\n\nFix: add a side-effect import at the top of ${B(e.cwd,n).replace(/\\/g,`/`)} (above bootstrap()), pointing at one of the detected files. For example:\n\n import './env'\n // or\n import './config'\n // or, with the @/ alias:\n import '@/config/env'`}:s!==-1&&o>s?{name:`env wiring`,status:`warn`,message:`env-init imported AFTER bootstrap() — should be before`,fix:`Move the env import above the bootstrap() call so the schema runs before any service reads from ConfigService.`}:{name:`env wiring`,status:`pass`}}function xa(e,t=Sa){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=F(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=z(e,o.name);if(o.isDirectory())i.push(a);else try{let e=qe(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const Sa=2e3;function Ca(e){let t=z(e.cwd,`.kickjs`,`types`);if(!N(t))return null;let n=xa(t);if(n===0)return null;let r=Date.now()-n,i=Math.floor(r/6e4);return i>60?{name:`typegen freshness`,status:`warn`,message:`last updated ${i} minutes ago`,fix:"Re-run `kick typegen` (or `kick dev`, which runs it on every reload) so generated types match the current code."}:{name:`typegen freshness`,status:`pass`,message:i===0?`just now`:`${i}m ago`}}const wa=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],Ta=[`.env.test`,`.env.test.local`],Ea=[`.env`,`.env.local`];function Da(e){let t=e.pkg?.scripts;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(!e.startsWith(`test`)||typeof n!=`string`)continue;let t=/KICKJS_ENV_FILE=(\S+)/.exec(n);if(t?.[1])return t[1]}return process.env.KICKJS_ENV_FILE??null}function Oa(e){if(!wa.some(t=>N(z(e.cwd,t))))return null;let t=Ea.filter(t=>N(z(e.cwd,t)));if(t.length===0)return null;let n=Ta.filter(t=>N(z(e.cwd,t)));if(n.length>0){let t=Da(e);return t&&t!==`off`&&t!==`none`?{name:`test env isolation`,status:`warn`,message:`${n.join(`, `)} present, but KICKJS_ENV_FILE=${t} overrides it`,fix:`KICKJS_ENV_FILE is checked before test-mode isolation, so ${n[0]} is\nignored and "${t}" is read instead. Drop the override to use the\ntest files, or set KICKJS_ENV_FILE=off if env comes from the runner.`}:{name:`test env isolation`,status:`pass`,message:`${n.join(`, `)} present`}}return{name:`test env isolation`,status:`warn`,message:`${t.join(`, `)} present, no .env.test`,fix:`Under NODE_ENV=test (or vitest's VITEST) KickJS reads .env.test / .env.test.local
1869
+ `);return}let t=process.cwd();se(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=_e();n.start(`Scanning project...`);let r=[...e.deploy?Qi(t):[],...e.di?$i(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)k.message(`${pe(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?A.red(`${a} critical`):`${a} critical`,o>0?A.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(D(A.red(`${l} — fix critical issues before deploying`)),process.exit(1)):D(A.green(`${l} — looking good!`))})}function ta(e){try{return JSON.parse(P(e,`utf-8`))}catch{return null}}function na(e){try{return P(e,`utf-8`)}catch{return null}}const ra=[`include`,`exclude`];function ia(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`"`){let r=n;for(n++;n<e.length&&e[n]!==`"`;n++)e[n]===`\\`&&n++;t+=e.slice(r,n+1)}else if(r===`/`&&e[n+1]===`/`){for(;n<e.length&&e[n]!==`
1870
+ `;)n++;t+=`
1871
+ `}else if(r===`/`&&e[n+1]===`*`){let t=e.indexOf(`*/`,n+2);n=t===-1?e.length:t+1}else t+=r}try{return JSON.parse(t.replace(/,(\s*[}\]])/g,`$1`))}catch{return null}}function aa(e){let t=z(e,`tsconfig.json`);if(N(t))return oa(t,/* @__PURE__ */ new Set)}function oa(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=na(e);if(n===null)return null;let r=ia(n);if(typeof r!=`object`||!r)return null;let i=Array.isArray(r.extends)?r.extends:typeof r.extends==`string`?[r.extends]:[],a={},o={};for(let t of ra)r[t]!==void 0&&(r[`${t}Base`]=R(e));for(let n of i){if(typeof n!=`string`)continue;let r=sa(R(e),n);if(!r)continue;let i=oa(r,t);if(i){Object.assign(a,i.compilerOptions);for(let e of ra)i[e]!==void 0&&(o[e]=i[e],o[`${e}Base`]=i[`${e}Base`])}}r.compilerOptions={...a,...r.compilerOptions};for(let e of ra)r[e]===void 0&&o[e]!==void 0&&(r[e]=o[e],r[`${e}Base`]=o[`${e}Base`]);return r}function sa(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return ca(V(e,t));let n=e;for(;;){let e=ca(z(n,`node_modules`,t));if(e)return e;let r=R(n);if(r===n)break;n=r}return null}function ca(e){if(N(e)){try{if(qe(e).isDirectory()){let t=z(e,`tsconfig.json`);return N(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return N(t)?t:null}function la(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ua(){let e=process.version,t=Number.parseInt(e.replace(/^v/,``).split(`.`)[0],10);return Number.isNaN(t)||t<20?{name:`Node version`,status:`fail`,message:e,fix:`KickJS requires Node 20 or newer.
1872
+ Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function da(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function fa(e){if(!e.pkg||e.runtime!==`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:`This app runs on the Express runtime, but package.json does not include \`express\`. Install: ${j(e.cwd)} add express`}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const pa={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function ma(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=pa[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: ${j(e.cwd)} add ${n.join(` `)}`}:e.runtime===`h3`&&ha(e.cwd,t.h3)===1?{name:r,status:`fail`,message:`h3 v1`,fix:`This version of @forinda/kickjs runs on h3 v2 only. Upgrade: ${j(e.cwd)} add h3@^2 — no code change for apps that only use KickJS APIs.`}:{name:r,status:`pass`}}function ha(e,t){let n=t;for(let t=V(e);;t=R(t)){try{n=JSON.parse(P(z(t,`node_modules`,`h3`,`package.json`),`utf8`)).version;break}catch{}if(R(t)===t)break}let r=/(\d+)/.exec(n)?.[1];return r===void 0?void 0:Number(r)}function ga(e){if(!e.pkg||!va(e.cwd))return null;let t=m[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or ${j(e.cwd)} add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const _a=2e3;function va(e){let t=z(e,`src`);if(!N(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<_a;){let e=r.pop(),t;try{t=F(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=_a)break;let t=z(e,a.name);if(a.isDirectory())a.name!==`node_modules`&&r.push(t);else if(/\.(ts|tsx|mts|cts)$/.test(a.name)&&(i++,n.test(na(t)??``)))return!0}}return!1}function ya(e){if(!e.pkg)return{name:`reflect-metadata installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies};return t[`reflect-metadata`]?{name:`reflect-metadata installed`,status:`pass`,message:t[`reflect-metadata`]}:{name:`reflect-metadata installed`,status:`fail`,fix:`KickJS decorators require the reflect-metadata polyfill.\nInstall it: ${j(e.cwd)} add reflect-metadata\nThen import it at the top of src/index.ts:\n\n import 'reflect-metadata'\n // ... rest of bootstrap`}}function ba(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function xa(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>z(e.cwd,t)).filter(e=>N(e)).filter(e=>/\bloadEnv(?:FromSchema)?\s*\(/.test(na(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>z(e.cwd,t)).find(e=>N(e));if(!n)return{name:`env wiring`,status:`warn`,message:`env-init file exists but no src/index.ts or src/main.ts found`};let r=na(n)??``,i=R(n),a=[];for(let e of t){let t=B(i,e).replace(/\\/g,`/`).replace(/\.ts$/,``),n=t.startsWith(`.`)?t:`./`+t,r=n.replace(/\/index$/,``);a.push(n,r);let o=e.replace(/\\/g,`/`).match(/\/src\/(.+?)(?:\.ts)?$/);if(o){let e=`@/`+o[1],t=e.replace(/\/index$/,``);a.push(e,t)}}let o=-1;for(let e of new Set(a)){let t=RegExp(`^import\\s+(?:.*?from\\s+)?['"]${la(e)}['"]`,`m`),n=r.match(t);n&&n.index!==void 0&&(o===-1||n.index<o)&&(o=n.index)}let s=r.search(/\bbootstrap\s*\(/),c=t.map(t=>B(e.cwd,t).replace(/\\/g,`/`)).join(`, `);return o===-1?{name:`env wiring`,status:`fail`,message:c,fix:`An env-init file (${c}) calls \`loadEnv(...)\` but \`${B(e.cwd,n).replace(/\\/g,`/`)}\` doesn't import it.\nWithout this, ConfigService.get('X') returns undefined while @Value('X') works via process.env fallback — a half-broken config you won't notice until something is missing.\n\nFix: add a side-effect import at the top of ${B(e.cwd,n).replace(/\\/g,`/`)} (above bootstrap()), pointing at one of the detected files. For example:\n\n import './env'\n // or\n import './config'\n // or, with the @/ alias:\n import '@/config/env'`}:s!==-1&&o>s?{name:`env wiring`,status:`warn`,message:`env-init imported AFTER bootstrap() — should be before`,fix:`Move the env import above the bootstrap() call so the schema runs before any service reads from ConfigService.`}:{name:`env wiring`,status:`pass`}}function Sa(e,t=Ca){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=F(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=z(e,o.name);if(o.isDirectory())i.push(a);else try{let e=qe(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const Ca=2e3;function wa(e){let t=z(e.cwd,`.kickjs`,`types`);if(!N(t))return null;let n=Sa(t);if(n===0)return null;let r=Date.now()-n,i=Math.floor(r/6e4);return i>60?{name:`typegen freshness`,status:`warn`,message:`last updated ${i} minutes ago`,fix:"Re-run `kick typegen` (or `kick dev`, which runs it on every reload) so generated types match the current code."}:{name:`typegen freshness`,status:`pass`,message:i===0?`just now`:`${i}m ago`}}const Ta=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],Ea=[`.env.test`,`.env.test.local`],Da=[`.env`,`.env.local`];function Oa(e){let t=e.pkg?.scripts;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(!e.startsWith(`test`)||typeof n!=`string`)continue;let t=/KICKJS_ENV_FILE=(\S+)/.exec(n);if(t?.[1])return t[1]}return process.env.KICKJS_ENV_FILE??null}function ka(e){if(!Ta.some(t=>N(z(e.cwd,t))))return null;let t=Da.filter(t=>N(z(e.cwd,t)));if(t.length===0)return null;let n=Ea.filter(t=>N(z(e.cwd,t)));if(n.length>0){let t=Oa(e);return t&&t!==`off`&&t!==`none`?{name:`test env isolation`,status:`warn`,message:`${n.join(`, `)} present, but KICKJS_ENV_FILE=${t} overrides it`,fix:`KICKJS_ENV_FILE is checked before test-mode isolation, so ${n[0]} is\nignored and "${t}" is read instead. Drop the override to use the\ntest files, or set KICKJS_ENV_FILE=off if env comes from the runner.`}:{name:`test env isolation`,status:`pass`,message:`${n.join(`, `)} present`}}return{name:`test env isolation`,status:`warn`,message:`${t.join(`, `)} present, no .env.test`,fix:`Under NODE_ENV=test (or vitest's VITEST) KickJS reads .env.test / .env.test.local
1871
1873
  INSTEAD of ${t.join(` and `)} — no layering, no fallback. Without one of\nthose files, every var your test config does not pin resolves from your
1872
1874
  development env — including DATABASE_URL and any third-party credentials.
1873
1875
 
1874
1876
  Create .env.test (cp .env.test.example .env.test, if the project has one)
1875
1877
  holding the whole environment the suite should run against
1876
1878
  (a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
1877
- and supply env from the test runner.`}}const ka=[()=>la(),ua,da,pa,ha,va,ya,ba,Oa,Ca];async function Aa(e,t={}){let n={cwd:e,pkg:ta(z(e,`package.json`)),tsconfig:ia(e),runtime:t.runtime??`express`},r=[...ka,...t.extraChecks??[]],i=[];for(let e of r){let t;try{t=await e(n)}catch(t){i.push({name:e.name||`doctor check`,status:`fail`,message:t instanceof Error?t.message:String(t)});continue}t!=null&&(Array.isArray(t)?i.push(...t):i.push(t))}return i}function ja(e){switch(e){case`pass`:return A.green(`✔`);case`warn`:return A.yellow(`⚠`);case`fail`:return A.red(`✖`)}}function Ma(e){let t=ja(e.status),n=e.message?` ${A.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function Na(e){return e.split(`
1879
+ and supply env from the test runner.`}}function Aa(e){let t={...e.pkg?.dependencies,...e.pkg?.devDependencies};if(!t[`@forinda/kickjs`]||!t[`@forinda/kickjs-di`])return null;let n=`one DI container`,r=t=>ta(z(e.cwd,`node_modules`,t,`package.json`)),i=r(`@forinda/kickjs`)?.dependencies?.[`@forinda/kickjs-di`],a=r(`@forinda/kickjs-di`)?.version,o=`Remove it and import from @forinda/kickjs, which re-exports it: ${j(e.cwd)} remove @forinda/kickjs-di`;return i&&a&&i!==a?{name:n,status:`fail`,message:`@forinda/kickjs-di ${a}, @forinda/kickjs uses ${i}`,fix:`Two copies of the DI container are installed, each with its own registrations — a class decorated against one is missing from the other.\n${o}`}:{name:n,status:`warn`,message:`@forinda/kickjs-di is listed in package.json`,fix:`@forinda/kickjs already depends on the exact version it needs; listing it too invites a second copy on the next upgrade.\n${o}`}}function ja(e){if(!e.tsconfig||!N(z(e.cwd,`.kickjs`,`types`)))return null;let t=`tsconfig includes typegen output`,n=t=>{let n=e.tsconfig[t],r=e.tsconfig[`${t}Base`]??e.cwd;return Array.isArray(n)?n.filter(e=>typeof e==`string`).map(t=>B(e.cwd,V(r,t)).replace(/\\/g,`/`)):[]},r=e=>/^\.kickjs\/(types(\/|$)|\*\*)/.test(e),i=e=>/^(\*\*\/)?\.kickjs(\/types)?(\/\*\*(\/\*)?|\/\*)?$/.test(e),a=n(`include`).filter(r),o=n(`exclude`).find(i),s=`Add ".kickjs/types/**/*.d.ts" and ".kickjs/types/**/*.ts" to "include" in tsconfig.json.`;return a.length===0?{name:t,status:`warn`,message:`.kickjs/types is not in include`,fix:`${s} Without them, the route, env and DI types from \`kick typegen\` don't apply.`}:o?{name:t,status:`warn`,message:`excluded by "${o}"`,fix:`Remove "${o}" from "exclude" in tsconfig.json — it drops the types \`kick typegen\` writes.`}:a.every(e=>e.endsWith(`.d.ts`))?{name:t,status:`warn`,message:`only the .d.ts files of .kickjs/types are included`,fix:`${s} The route types are a .ts file.`}:String(e.tsconfig.compilerOptions?.rootDir??``).replace(/^\.\//,``).replace(/\/$/,``)===`src`?{name:t,status:`warn`,message:`rootDir: 'src'`,fix:"Remove `rootDir` from tsconfig.json — the generated types live outside src/, and tsc refuses files outside rootDir."}:{name:t,status:`pass`}}const Ma=[()=>ua(),da,fa,ma,ga,Aa,ya,ba,ja,xa,ka,wa];async function Na(e,t={}){let n={cwd:e,pkg:ta(z(e,`package.json`)),tsconfig:aa(e),runtime:t.runtime??`express`},r=[...Ma,...t.extraChecks??[]],i=[];for(let e of r){let t;try{t=await e(n)}catch(t){i.push({name:e.name||`doctor check`,status:`fail`,message:t instanceof Error?t.message:String(t)});continue}t!=null&&(Array.isArray(t)?i.push(...t):i.push(t))}return i}function Pa(e){switch(e){case`pass`:return A.green(`✔`);case`warn`:return A.yellow(`⚠`);case`fail`:return A.red(`✖`)}}function Fa(e){let t=Pa(e.status),n=e.message?` ${A.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function Ia(e){return e.split(`
1878
1880
  `).map(e=>` ${A.dim(`→`)} ${e}`).join(`
1879
- `)}function Pa(e){return e?.doctor?.checks??[]}function Fa(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=Pa(await C(e)),n=await a(e);se(`KickJS Doctor`);let r=await Aa(e,{extraChecks:t,runtime:n});for(let e of r)k.message(Ma(e)),e.fix&&e.status!==`pass`&&k.message(Na(e.fix));let i=r.filter(e=>e.status===`pass`).length,o=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[A.green(`${i} passed`),o>0?A.yellow(`${o} warning${o===1?``:`s`}`):`${o} warnings`,s>0?A.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(D(`${c} — fix the errors above before running the app`),process.exit(1)):D(o>0?`${c} — review the warnings`:A.green(`${c} — your environment looks good`))})}const Ia=Symbol.for(`kickjs.handler.entryCapture`),La=Symbol.for(`kickjs.config.describe`);function Ra(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function za(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?``:Ra(n.default)}`)}return t}function Ba(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
1881
+ `)}function La(e){return e?.doctor?.checks??[]}function Ra(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=La(await C(e)),n=await a(e);se(`KickJS Doctor`);let r=await Na(e,{extraChecks:t,runtime:n});for(let e of r)k.message(Fa(e)),e.fix&&e.status!==`pass`&&k.message(Ia(e.fix));let i=r.filter(e=>e.status===`pass`).length,o=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[A.green(`${i} passed`),o>0?A.yellow(`${o} warning${o===1?``:`s`}`):`${o} warnings`,s>0?A.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(D(`${c} — fix the errors above before running the app`),process.exit(1)):D(o>0?`${c} — review the warnings`:A.green(`${c} — your environment looks good`))})}const za=Symbol.for(`kickjs.handler.entryCapture`),Ba=Symbol.for(`kickjs.config.describe`);function Va(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function Ha(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?``:Va(n.default)}`)}return t}function Ua(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
1880
1882
  # sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
1881
1883
  #
1882
1884
  # Uncommented variables are required. Commented ones are optional; the value shown
1883
- # 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 ──`,...za(e.env)].join(`
1884
- `));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...za(n.vars)].join(`
1885
+ # 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 ──`,...Ha(e.env)].join(`
1886
+ `));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...Ha(n.vars)].join(`
1885
1887
  `));return`${t.join(`
1886
1888
 
1887
- `)}\n`}async function Va(e,t){let n=V(e,t);if(!N(n))throw Error(`${t} not found`);let r=V(e,`vite.config.ts`);if(!N(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(V(e,`package.json`)),{createServer:o}=await import(U(a.resolve(`vite`)).href),s=globalThis,c;s[Ia]=e=>{c??=e},s[La]=!0,s[or]=`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[Ia],delete s[La],delete s[or],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function Ha(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=V(t,e.out),r;try{r=Ba(await Va(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((N(n)?P(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.`)):(I(n,r),console.log(` Wrote ${e.out}`))})}function Ua(e){return e.optsWithGlobals().dryRun??!1}function Wa(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.
1889
+ `)}\n`}async function Wa(e,t){let n=V(e,t);if(!N(n))throw Error(`${t} not found`);let r=V(e,`vite.config.ts`);if(!N(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(V(e,`package.json`)),{createServer:o}=await import(U(a.resolve(`vite`)).href),s=globalThis,c;s[za]=e=>{c??=e},s[Ba]=!0,s[or]=`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[za],delete s[Ba],delete s[or],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function Ga(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=V(t,e.out),r;try{r=Ua(await Wa(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((N(n)?P(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.`)):(I(n,r),console.log(` Wrote ${e.out}`))})}function Ka(e){return e.optsWithGlobals().dryRun??!1}function qa(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.
1888
1890
  Direction defaults to \`modules.style\` from kick.config (or "define").
1889
1891
  --target define|class Override the migration direction.
1890
1892
  --apply Apply the changes (default: dry-run preview).
1891
- --experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=Ua(t)||!e.apply;O(n),e.experimental||(console.error(`
1893
+ --experimental Acknowledge that AST migration is experimental.`).option(`--modules-dir <dir>`,`Modules directory (default: src/modules from kick.config)`).option(`--apply`,`Apply the migration to disk (default: dry-run)`).option(`--experimental`,`Acknowledge that this command is experimental`).option(`--target <style>`,`Migration direction — 'define' or 'class'`).option(`--no-backup`,`Skip the .kickjs/codemod-backups/ snapshot (default: backup on)`).action(async(e,t)=>{let n=Ka(t)||!e.apply;O(n),e.experimental||(console.error(`
1892
1894
  `+A.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
1893
1895
  The regex-based rewrite handles the shapes our templates produce.
1894
1896
  Hand-rolled modules with non-standard structures may be skipped.
1895
1897
  Always commit before running with --apply.
1896
- `),process.exit(1));let r=await C(process.cwd()),i=w(r),a=V(e.modulesDir??i.dir??`src/modules`),o;e.target===`define`||e.target===`class`?o=e.target:e.target===void 0?o=i.style??`define`:(console.error(`\n ${A.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=A.dim(`→ ${o}`),c=n?A.dim(`(dry-run)`):A.bold(`(applying)`);console.log(`\n ${A.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${A.dim(a)}\n`);let l=e.backup!==!1&&!n,u=await Mn(a,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${A.green(`✓`)} backup: ${A.dim(e)}\n ${A.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${A.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${A.green(`✓`)} ${e.path}`);else{f++;let t=A.dim(`(${e.reason??`skipped`})`);console.log(` ${A.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${A.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=A.dim(`(${u.indexReason??`skipped`})`);console.log(` ${A.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${A.dim(`-`)} ${u.indexPath} ${A.dim(`(not found)`)}`);let p=n?A.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${A.bold(String(d))} migrated, ${A.bold(String(f))} skipped${p}\n`)})}function Ga(e){try{let t=JSON.parse(P(V(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function Ka(e,t=N,n=Ga(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=R(e);return(t(V(r,`pnpm-workspace.yaml`))||t(V(r,`package.json`)))&&t(V(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function qa(e,t,n,r){let i=Ka(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 Ja(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'
1898
+ `),process.exit(1));let r=await C(process.cwd()),i=w(r),a=V(e.modulesDir??i.dir??`src/modules`),o;e.target===`define`||e.target===`class`?o=e.target:e.target===void 0?o=i.style??`define`:(console.error(`\n ${A.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=A.dim(`→ ${o}`),c=n?A.dim(`(dry-run)`):A.bold(`(applying)`);console.log(`\n ${A.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${A.dim(a)}\n`);let l=e.backup!==!1&&!n,u=await Mn(a,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${A.green(`✓`)} backup: ${A.dim(e)}\n ${A.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${A.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${A.green(`✓`)} ${e.path}`);else{f++;let t=A.dim(`(${e.reason??`skipped`})`);console.log(` ${A.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${A.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=A.dim(`(${u.indexReason??`skipped`})`);console.log(` ${A.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${A.dim(`-`)} ${u.indexPath} ${A.dim(`(not found)`)}`);let p=n?A.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${A.bold(String(d))} migrated, ${A.bold(String(f))} skipped${p}\n`)})}function Ja(e){try{let t=JSON.parse(P(V(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function Ya(e,t=N,n=Ja(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=R(e);return(t(V(r,`pnpm-workspace.yaml`))||t(V(r,`package.json`)))&&t(V(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function Xa(e,t,n,r){let i=Ya(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 Za(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'
1897
1899
  import { handler } from '${e}'
1898
1900
 
1899
1901
  // Where the app's build files were packaged; the platform starts this
@@ -1907,7 +1909,7 @@ export const config = {
1907
1909
  ${r.join(`
1908
1910
  `)}
1909
1911
  }
1910
- `}function Ya(){return`import { fileURLToPath } from 'node:url'
1912
+ `}function Qa(){return`import { fileURLToPath } from 'node:url'
1911
1913
  import { handler } from './server.mjs'
1912
1914
 
1913
1915
  // The app's build files are copied into this function at their project
@@ -1917,11 +1919,11 @@ process.env.KICK_APP_ROOT ??= fileURLToPath(new URL('./', import.meta.url))
1917
1919
  const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
1918
1920
 
1919
1921
  export default (req, res) => handler.node(req, res, requestContext())
1920
- `}function Xa(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function Za(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 Qa(e,t){let n;try{n=ot(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
1921
- `).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 $a(e){let t=V(e,`src`);return N(t)?F(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=P(V(t,e),`utf-8`);return n.includes(`@Cron`)?Qa(n,`src/${e}`):[]}):[]}function eo(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 to(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(eo(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 no(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 ro(e,t){let{createRequire:n}=await import(`node:module`),r=n(V(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=V(e,`node_modules`,t,`package.json`)}if(!N(i))throw Error(`${t} is not installed in this project. Run: ${j(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=no(JSON.parse(P(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(U(V(R(i),a)).href)}async function io(e,t,n){let r=V(e,t.entry);if(!N(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await ro(e,`vite`),{default:a}=await ro(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await ro(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":V(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:V(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>oo(n,r?R(r):e)||t.external.includes(n)&&oo(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=V(e,t.outDir,`server.mjs`);return n(`bundled ${B(process.cwd(),c)}`),c}function ao(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function oo(e,t,n=N){let r=ao(e);if(!r)return!1;for(let e=t;;e=R(e)){if(n(V(e,`node_modules`,r,`package.json`)))return!1;if(R(e)===e)return!0}}function so(e,t){let n=B(e,t).split(H)[0];return n!==void 0&&n.startsWith(`.`)}function co(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function lo(e){try{return qe(e)}catch{return}}function uo(e,t){let n=t.filter(t=>!N(V(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 (\`${ee(j(e),`build`)}\`), or fix \`deploy.include\`.`)}function fo(e,t){let n=t.projectRoot,r=()=>qa(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();uo(n,e.include);let i=await io(n,e,t.log),a=V(n,e.siteRoot),o=$a(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=V(a,`.netlify/v1/functions`);Ge(s,{recursive:!0});let c=B(s,i).split(H).join(`/`),l=e=>e.split(H).join(`/`);I(V(s,`api.mjs`),Ja(c,e.apiPath,{projectDir:l(B(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(B(s,V(n,e)));return lo(V(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${B(process.cwd(),V(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)Ge(V(n,u),{recursive:!0}),t.log(`publish directory ready at ${B(process.cwd(),V(n,u))}`);else if(N(V(n,u))){let e=F(V(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=V(n,u,`_redirects`),r=N(t)?P(t,`utf-8`):``,i=co(e).filter(e=>!r.includes(e));i.length>0&&I(t,`${r}${r&&!r.endsWith(`
1922
+ `}function $a(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function eo(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 to(e,t){let n;try{n=ot(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
1923
+ `).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 no(e){let t=V(e,`src`);return N(t)?F(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=P(V(t,e),`utf-8`);return n.includes(`@Cron`)?to(n,`src/${e}`):[]}):[]}function ro(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 io(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(ro(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 ao(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 oo(e,t){let{createRequire:n}=await import(`node:module`),r=n(V(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=V(e,`node_modules`,t,`package.json`)}if(!N(i))throw Error(`${t} is not installed in this project. Run: ${j(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=ao(JSON.parse(P(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(U(V(R(i),a)).href)}async function so(e,t,n){let r=V(e,t.entry);if(!N(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await oo(e,`vite`),{default:a}=await oo(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await oo(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":V(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:V(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>lo(n,r?R(r):e)||t.external.includes(n)&&lo(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=V(e,t.outDir,`server.mjs`);return n(`bundled ${B(process.cwd(),c)}`),c}function co(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function lo(e,t,n=N){let r=co(e);if(!r)return!1;for(let e=t;;e=R(e)){if(n(V(e,`node_modules`,r,`package.json`)))return!1;if(R(e)===e)return!0}}function uo(e,t){let n=B(e,t).split(H)[0];return n!==void 0&&n.startsWith(`.`)}function fo(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function po(e){try{return qe(e)}catch{return}}function mo(e,t){let n=t.filter(t=>!N(V(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 (\`${ee(j(e),`build`)}\`), or fix \`deploy.include\`.`)}function ho(e,t){let n=t.projectRoot,r=()=>Xa(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();mo(n,e.include);let i=await so(n,e,t.log),a=V(n,e.siteRoot),o=no(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=V(a,`.netlify/v1/functions`);Ge(s,{recursive:!0});let c=B(s,i).split(H).join(`/`),l=e=>e.split(H).join(`/`);I(V(s,`api.mjs`),Za(c,e.apiPath,{projectDir:l(B(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(B(s,V(n,e)));return po(V(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${B(process.cwd(),V(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)Ge(V(n,u),{recursive:!0}),t.log(`publish directory ready at ${B(process.cwd(),V(n,u))}`);else if(N(V(n,u))){let e=F(V(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=V(n,u,`_redirects`),r=N(t)?P(t,`utf-8`):``,i=fo(e).filter(e=>!r.includes(e));i.length>0&&I(t,`${r}${r&&!r.endsWith(`
1922
1924
  `)?`
1923
1925
  `:``}${i.join(`
1924
- `)}\n`)}}let d=V(a,`netlify.toml`);if(N(d)){let e=Xa(P(d,`utf-8`)),r=B(a,V(n,u)).split(H).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();uo(n,e.include);let i=await io(n,e,t.log),a=V(n,e.siteRoot),o=e.staticDir?V(n,e.staticDir):void 0,s=V(a,`.vercel/output`),c=V(s,`functions/api.func`);Ke(s,{recursive:!0,force:!0}),Ge(c,{recursive:!0}),We(i,V(c,`server.mjs`)),I(V(c,`index.mjs`),Ya());for(let t of e.include)We(V(n,t),V(c,t),{recursive:!0});if(I(V(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!N(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);We(o,V(s,`static`),{recursive:!0,filter:e=>!so(o,e)})}let{crons:l,warnings:u}=to($a(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:Za(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};I(V(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${B(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 po=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=L.resolve(e.cwd,`kick.config.ts`);if(!N(t))return null;let n=await C(e.cwd);if(!n?.assetMap)return null;let r=Se(n.assetMap,e.cwd);return r.count===0?null:Me(r)}}),mo="/* 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 ho(e,t,n,r={}){if(e.length===0)return`${mo}
1926
+ `)}\n`)}}let d=V(a,`netlify.toml`);if(N(d)){let e=$a(P(d,`utf-8`)),r=B(a,V(n,u)).split(H).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();mo(n,e.include);let i=await so(n,e,t.log),a=V(n,e.siteRoot),o=e.staticDir?V(n,e.staticDir):void 0,s=V(a,`.vercel/output`),c=V(s,`functions/api.func`);Ke(s,{recursive:!0,force:!0}),Ge(c,{recursive:!0}),We(i,V(c,`server.mjs`)),I(V(c,`index.mjs`),Qa());for(let t of e.include)We(V(n,t),V(c,t),{recursive:!0});if(I(V(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!N(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);We(o,V(s,`static`),{recursive:!0,filter:e=>!uo(o,e)})}let{crons:l,warnings:u}=io(no(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:eo(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};I(V(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${B(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 go=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=L.resolve(e.cwd,`kick.config.ts`);if(!N(t))return null;let n=await C(e.cwd);if(!n?.assetMap)return null;let r=Se(n.assetMap,e.cwd);return r.count===0?null:Me(r)}}),_o="/* 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 vo(e,t,n,r={}){if(e.length===0)return`${_o}
1925
1927
  // (no routes discovered yet — annotate a controller method with
1926
1928
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
1927
1929
  declare global {
@@ -1938,15 +1940,15 @@ declare global {
1938
1940
 
1939
1941
  /** Empty until the first route exists — see kick typegen. */
1940
1942
  export const kickRpc = {} as const
1941
- `;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=yo(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${B(process.cwd(),i.filePath)} but not exported, so the generated types can't import it — ${o} is typed as ${t}. Export it (\`export const ${e.identifier} = ...\`) to type ctx.${o}.`:`${n}: ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??_o(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=vo(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${go(e)}`,` }`)}n.push(` }`),l.push(n.join(`
1943
+ `;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=So(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${B(process.cwd(),i.filePath)} but not exported, so the generated types can't import it — ${o} is typed as ${t}. Export it (\`export const ${e.identifier} = ...\`) to type ctx.${o}.`:`${n}: ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??bo(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=xo(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${yo(e)}`,` }`)}n.push(` }`),l.push(n.join(`
1942
1944
  `))}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(`
1943
1945
  `);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(`
1944
- `));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=So(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(`
1946
+ `));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=To(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(`
1945
1947
  `)}\n },`)}let _=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...h,`} as const`].join(`
1946
- `),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=xo(``,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(`
1948
+ `),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=wo(``,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(`
1947
1949
  `)+`
1948
- `:``,x=bo(a)+b,S=l.join(`
1949
- `);return`${mo}${x}
1950
+ `:``,x=Co(a)+b,S=l.join(`
1951
+ `);return`${_o}${x}
1950
1952
  declare global {
1951
1953
  // eslint-disable-next-line @typescript-eslint/no-namespace
1952
1954
  namespace KickRoutes {
@@ -1958,18 +1960,18 @@ ${S}
1958
1960
  }
1959
1961
 
1960
1962
  ${_}
1961
- `}function go(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function _o(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string; cursor?: string }`}function vo(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 yo(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=xo(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 bo(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(`
1963
+ `}function yo(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function bo(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string; cursor?: string }`}function xo(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 So(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=wo(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 Co(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(`
1962
1964
  `)+`
1963
- `}function xo(e,t,n){if(e===null)return`unknown`;let r=R(n);if(e===``){let e=B(r,t).split(H).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=R(t),a=V(i,e),o=B(r,a).split(H).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function So(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 Co=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:wo(e),cwd:e.cwd,envFile:To(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=L.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return ho(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function wo(e){return L.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function To(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Eo=`@typescript/typescript6`;function Do(e){return typeof e?.createProgram==`function`}function Oo(e){if(Do(e.typescript))return{api:e.typescript,source:`typescript`};if(Do(e.ts6))return{api:e.ts6,source:Eo};let t=`Install it in the project:\n ${j()} add -D ${Eo}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
1964
- 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 '${Eo}' resolved from this project.\n ${t}`)}async function ko(e){let t=Ue(z(e,`package.json`)),n=async e=>{try{return await import(U(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Eo)]);return Oo({typescript:Ao(r),ts6:Ao(i)}).api}function Ao(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const jo=Symbol(`kick/client: expansion budget exhausted`);var Mo=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!==jo)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 jo;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=`
1965
+ `}function wo(e,t,n){if(e===null)return`unknown`;let r=R(n);if(e===``){let e=B(r,t).split(H).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=R(t),a=V(i,e),o=B(r,a).split(H).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function To(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 Eo=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Do(e),cwd:e.cwd,envFile:Oo(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=L.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return vo(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Do(e){return L.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Oo(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const ko=`@typescript/typescript6`;function Ao(e){return typeof e?.createProgram==`function`}function jo(e){if(Ao(e.typescript))return{api:e.typescript,source:`typescript`};if(Ao(e.ts6))return{api:e.ts6,source:ko};let t=`Install it in the project:\n ${j()} add -D ${ko}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
1966
+ 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 '${ko}' resolved from this project.\n ${t}`)}async function Mo(e){let t=Ue(z(e,`package.json`)),n=async e=>{try{return await import(U(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(ko)]);return jo({typescript:No(r),ts6:No(i)}).api}function No(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Po=Symbol(`kick/client: expansion budget exhausted`);var Fo=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!==Po)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 Po;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=`
1965
1967
  `){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===`
1966
1968
  `?`
1967
- `: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 No=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Po=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Fo(e){return at(`sha1`).update(e).digest(`hex`)}function Io(e){let t=at(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
1968
- `));for(let n of No){let r=z(e.projectDir,n);if(N(r))try{t.update(P(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Po.test(n)){t.update(n);try{t.update(P(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Lo(e){try{let t=await ko(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(z(e.projectDir,`tsconfig.json`),{},n);return r?Io({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 Ro(e){let t=await ko(e.compilerFrom??e.projectDir),n=z(R(e.routesFile),`__kick_client_probe__.ts`),r=Vo(e.routesFile,e.keys),i=Wo(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.`);zo(t,i,e.routesFile);let s=Ho(t,i,o,e.keys),c=null,l=new Mo(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===Bo(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 zo(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(`
1969
- `);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 Bo(e){return`_K${e}`}function Vo(e,t){let n=`./`+Je(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Bo(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
1969
+ `: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 Io=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Lo=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Ro(e){return at(`sha1`).update(e).digest(`hex`)}function zo(e){let t=at(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
1970
+ `));for(let n of Io){let r=z(e.projectDir,n);if(N(r))try{t.update(P(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Lo.test(n)){t.update(n);try{t.update(P(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Bo(e){try{let t=await Mo(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(z(e.projectDir,`tsconfig.json`),{},n);return r?zo({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 Vo(e){let t=await Mo(e.compilerFrom??e.projectDir),n=z(R(e.routesFile),`__kick_client_probe__.ts`),r=Wo(e.routesFile,e.keys),i=qo(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.`);Ho(t,i,e.routesFile);let s=Go(t,i,o,e.keys),c=null,l=new Fo(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===Uo(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 Ho(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(`
1971
+ `);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 Uo(e){return`_K${e}`}function Wo(e,t){let n=`./`+Je(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Uo(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
1970
1972
  `)+`
1971
- `}function Ho(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(Bo(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Uo(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=F(t).filter(e=>e.endsWith(`.ts`)).map(e=>z(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function Wo(e,t,n,r){let i=z(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
1972
- `))}},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:[...Uo(o.fileNames,R(n)),n],options:o.options,host:s})}const Go=`/* eslint-disable */
1973
+ `}function Go(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(Uo(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Ko(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=F(t).filter(e=>e.endsWith(`.ts`)).map(e=>z(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function qo(e,t,n,r){let i=z(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
1974
+ `))}},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:[...Ko(o.fileNames,R(n)),n],options:o.options,host:s})}const Jo=`/* eslint-disable */
1973
1975
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
1974
1976
  //
1975
1977
  // Self-contained: this file has no imports, so a frontend consumes it without
@@ -1983,7 +1985,7 @@ ${_}
1983
1985
  //
1984
1986
  // Written when \`kick dev\` starts, not on save — resolving these types builds a
1985
1987
  // full TypeScript program over the server. Re-run \`kick typegen\`.
1986
- `;function Ko(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Go}
1988
+ `;function Yo(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Jo}
1987
1989
  // (no routes discovered yet — annotate a controller method with
1988
1990
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
1989
1991
  interface Api {}
@@ -2000,7 +2002,7 @@ export type { Api }
2000
2002
 
2001
2003
  `)+`
2002
2004
 
2003
- `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Go}
2005
+ `:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Jo}
2004
2006
  ${r}interface Api {
2005
2007
  ${i.join(`
2006
2008
  `)}
@@ -2014,7 +2016,7 @@ declare global {
2014
2016
  }
2015
2017
 
2016
2018
  export type { Api }
2017
- `}const qo=`kick/client`,$=`.kickjs/types/kick__client.d.ts`,Jo=`.kickjs/cache/client-map.sha1`,Yo=(()=>{try{return Ue(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function Xo(e){try{if(!N(e))return null;let[t,n]=P(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function Zo(e){return`${$n}${qo} */\n\n${e}\n`}function Qo(e){try{return N(e)?P(e,`utf-8`):null}catch{return null}}async function $o(e){let t=L.resolve(e.cwd,$);if(!N(t))return!1;try{await nt(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${$} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${$} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function es(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function ts(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(N(L.resolve(e.cwd,$))&&e.log.warn(` kick/client: ${$} 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 ns=()=>({id:qo,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!ts(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:L.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=es(e.config),a=await Lo({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Yo}),o=Xo(L.resolve(e.cwd,Jo)),s=Qo(L.resolve(e.cwd,$));if(a&&o&&s!==null&&o.inputs===a&&o.output===Fo(s))return Vn()&&e.log.info?.(` kick/client: unchanged, keeping ${$}`),null;try{let t=Ko(await Ro({projectDir:e.cwd,routesFile:L.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(Jo,`${a} ${Fo(Zo(t))}`),t}catch(t){let n=N(L.resolve(e.cwd,$)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):Vn()&&e.log.info?.(r),n&&await $o(e),null}}});function rs(e,t,n=`zod`){if(!e)return null;let r=R(t),i=B(r,e.filePath).split(H).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
2019
+ `}const Xo=`kick/client`,$=`.kickjs/types/kick__client.d.ts`,Zo=`.kickjs/cache/client-map.sha1`,Qo=(()=>{try{return Ue(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function $o(e){try{if(!N(e))return null;let[t,n]=P(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function es(e){return`${$n}${Xo} */\n\n${e}\n`}function ts(e){try{return N(e)?P(e,`utf-8`):null}catch{return null}}async function ns(e){let t=L.resolve(e.cwd,$);if(!N(t))return!1;try{await nt(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${$} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${$} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function rs(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function is(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(N(L.resolve(e.cwd,$))&&e.log.warn(` kick/client: ${$} 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 as=()=>({id:Xo,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!is(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:L.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=rs(e.config),a=await Bo({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:Qo}),o=$o(L.resolve(e.cwd,Zo)),s=ts(L.resolve(e.cwd,$));if(a&&o&&s!==null&&o.inputs===a&&o.output===Ro(s))return Vn()&&e.log.info?.(` kick/client: unchanged, keeping ${$}`),null;try{let t=Yo(await Vo({projectDir:e.cwd,routesFile:L.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(Zo,`${a} ${Ro(es(t))}`),t}catch(t){let n=N(L.resolve(e.cwd,$)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):Vn()&&e.log.info?.(r),n&&await ns(e),null}}});function os(e,t,n=`zod`){if(!e)return null;let r=R(t),i=B(r,e.filePath).split(H).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
2018
2020
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
2019
2021
  // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
2020
2022
 
@@ -2052,5 +2054,5 @@ declare global {
2052
2054
  }
2053
2055
 
2054
2056
  export {}
2055
- `}const is=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=os(e);if(t===!1)return null;let n=await e.getScanResult({root:as(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=L.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return rs(n.env,i,r)}});function as(e){return L.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function os(e){return e.config?.typegen?.envFile}function ss(e){return L.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function cs(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function ls(e){return{root:ss(e),cwd:e.cwd,envFile:cs(e)}}const us=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ls(e)),n=L.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ee(t.classes,n,r)}}),ds=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ls(e)),n=new Set(t.collisions.map(e=>e.className)),r=Ae(t.classes,t.tokens,t.injects,n);return je(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),fs=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ls(e));return je(`ModuleToken`,we(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),ps=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ls(e));return Te(t.pluginsAndAdapters)}}),ms=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ls(e));return t.contextKeys.length===0?null:Le(t.contextKeys)}}),hs=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ls(e));return Ne(t.routeFlags)}}),gs={express:{subpath:`@forinda/kickjs/express`,typeName:`ExpressRuntimeTypes`},fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},_s=()=>({id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime??`express`;if(t!==`express`&&t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=gs[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(`
2056
- `)}});var vs=/* @__PURE__ */ e({builtinCliPlugins:()=>ys});const ys=[T({name:`kick/init`,register:ft}),T({name:`kick/generate`,register:Zn}),T({name:`kick/run`,register:yr}),T({name:`kick/info`,register:wr}),T({name:`kick/inspect`,register:Pr}),T({name:`kick/add`,register:g}),T({name:`kick/runtime-swap`,register:Zr}),T({name:`kick/list`,register:i}),T({name:`kick/explain`,register:di}),T({name:`kick/mcp`,register:Si}),T({name:`kick/tinker`,register:Ei}),T({name:`kick/remove`,register:Mi}),T({name:`kick/typegen`,register:Fi}),T({name:`kick/check`,register:ea}),T({name:`kick/doctor`,register:Fa}),T({name:`kick/env-command`,register:Ha}),T({name:`kick/codemod`,register:Wa}),T({name:`kick/deploy`,register:fo}),T({name:`kick/registry`,typegens:[us()]}),T({name:`kick/services`,typegens:[ds()]}),T({name:`kick/modules`,typegens:[fs()]}),T({name:`kick/plugins`,typegens:[ps()]}),T({name:`kick/context`,typegens:[ms()]}),T({name:`kick/route-flags`,typegens:[hs()]}),T({name:`kick/assets`,typegens:[po()]}),T({name:`kick/routes`,typegens:[Co()]}),T({name:`kick/client`,typegens:[ns()]}),T({name:`kick/env`,typegens:[is()]}),T({name:`kick/runtime`,typegens:[_s()]})];export{rr as n,ys as t};
2057
+ `}const ss=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=ls(e);if(t===!1)return null;let n=await e.getScanResult({root:cs(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=L.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return os(n.env,i,r)}});function cs(e){return L.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ls(e){return e.config?.typegen?.envFile}function us(e){return L.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ds(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function fs(e){return{root:us(e),cwd:e.cwd,envFile:ds(e)}}const ps=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(fs(e)),n=L.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ee(t.classes,n,r)}}),ms=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(fs(e)),n=new Set(t.collisions.map(e=>e.className)),r=Ae(t.classes,t.tokens,t.injects,n);return je(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),hs=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(fs(e));return je(`ModuleToken`,we(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),gs=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(fs(e));return Te(t.pluginsAndAdapters)}}),_s=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(fs(e));return t.contextKeys.length===0?null:Le(t.contextKeys)}}),vs=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(fs(e));return Ne(t.routeFlags)}}),ys={express:{subpath:`@forinda/kickjs/express`,typeName:`ExpressRuntimeTypes`},fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},bs=()=>({id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime??`express`;if(t!==`express`&&t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=ys[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(`
2058
+ `)}});var xs=/* @__PURE__ */ e({builtinCliPlugins:()=>Ss});const Ss=[T({name:`kick/init`,register:ft}),T({name:`kick/generate`,register:Zn}),T({name:`kick/run`,register:yr}),T({name:`kick/info`,register:wr}),T({name:`kick/inspect`,register:Pr}),T({name:`kick/add`,register:g}),T({name:`kick/runtime-swap`,register:Zr}),T({name:`kick/list`,register:i}),T({name:`kick/explain`,register:di}),T({name:`kick/mcp`,register:Si}),T({name:`kick/tinker`,register:Ei}),T({name:`kick/remove`,register:Mi}),T({name:`kick/typegen`,register:Fi}),T({name:`kick/check`,register:ea}),T({name:`kick/doctor`,register:Ra}),T({name:`kick/env-command`,register:Ga}),T({name:`kick/codemod`,register:qa}),T({name:`kick/deploy`,register:ho}),T({name:`kick/registry`,typegens:[ps()]}),T({name:`kick/services`,typegens:[ms()]}),T({name:`kick/modules`,typegens:[hs()]}),T({name:`kick/plugins`,typegens:[gs()]}),T({name:`kick/context`,typegens:[_s()]}),T({name:`kick/route-flags`,typegens:[vs()]}),T({name:`kick/assets`,typegens:[go()]}),T({name:`kick/routes`,typegens:[Eo()]}),T({name:`kick/client`,typegens:[as()]}),T({name:`kick/env`,typegens:[ss()]}),T({name:`kick/runtime`,typegens:[bs()]})];export{rr as n,Ss as t};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.14.1
2
+ * @forinda/kickjs-cli v8.14.3
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as builtinCliPlugins}from"./run-plugins-PuTINHKr.mjs";
11
+ export{t as builtinCliPlugins}from"./run-plugins-DXxLu7EH.mjs";
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.14.1
2
+ * @forinda/kickjs-cli v8.14.3
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{E as e}from"./project-BGfW_cup.mjs";import{o as t}from"./config-BZ_DgqAb.mjs";import{n}from"./plugin-BOpVRMKa.mjs";import{t as r}from"./builtins-DIdRQfIZ.mjs";import{t as i}from"./project-root-DvXJgSgx.mjs";import{Command as a}from"commander";import{readFileSync as o}from"node:fs";import{delimiter as s,dirname as c,join as l}from"node:path";import{fileURLToPath as u}from"node:url";function d(e,t){if(!t?.commands?.length)return;let n=new Set(e.commands.map(e=>e.name()));for(let r of t.commands)n.has(r.name)?console.warn(` Warning: custom command '${r.name}' skipped — conflicts with a built-in command`):f(e,r)}function f(t,n){let r=t.command(n.name).description(n.description);if(n.aliases)for(let e of n.aliases)r.alias(e);r.allowUnknownOption(!0),r.argument(`[args...]`,`Additional arguments passed to the command`);function i(){return{PATH:`${l(process.cwd(),`node_modules`,`.bin`)}${s}${process.env.PATH??``}`}}r.action(t=>{let r=t.join(` `),a=Array.isArray(n.steps)?n.steps:[n.steps];for(let t of a){let a=r?`${t} ${r}`:t;console.log(` $ ${a}`);try{e(a,void 0,i())}catch{console.error(` Command failed: ${n.name}`),process.exitCode=1;return}}})}const p=c(u(import.meta.url)),m=JSON.parse(o(l(p,`..`,`package.json`),`utf-8`));async function h(){let e=new a;e.name(`kick`).description(`KickJS — A production-grade, decorator-driven Node.js framework`).version(m.version);let o=i(process.cwd()),s=o,c=await t(s)??{},l=[...r,...c.plugins??[]],u=n(l,c.commands??[]);await u.register(e,{cwd:s,projectRoot:o,config:c,log:e=>console.log(e)}),d(e,{...c,commands:u.commands}),e.showHelpAfterError();let f=process.argv.map(e=>e===`-v`?`--version`:e);await e.parseAsync(f)}h().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{};
11
+ import{E as e}from"./project-mWxqd_g2.mjs";import{o as t}from"./config-DmEDJwvJ.mjs";import{n}from"./plugin-T3Aes85q.mjs";import{t as r}from"./builtins-C9MmvIBs.mjs";import{t as i}from"./project-root-CVGTdH_N.mjs";import{Command as a}from"commander";import{readFileSync as o}from"node:fs";import{delimiter as s,dirname as c,join as l}from"node:path";import{fileURLToPath as u}from"node:url";function d(e,t){if(!t?.commands?.length)return;let n=new Set(e.commands.map(e=>e.name()));for(let r of t.commands)n.has(r.name)?console.warn(` Warning: custom command '${r.name}' skipped — conflicts with a built-in command`):f(e,r)}function f(t,n){let r=t.command(n.name).description(n.description);if(n.aliases)for(let e of n.aliases)r.alias(e);r.allowUnknownOption(!0),r.argument(`[args...]`,`Additional arguments passed to the command`);function i(){return{PATH:`${l(process.cwd(),`node_modules`,`.bin`)}${s}${process.env.PATH??``}`}}r.action(t=>{let r=t.join(` `),a=Array.isArray(n.steps)?n.steps:[n.steps];for(let t of a){let a=r?`${t} ${r}`:t;console.log(` $ ${a}`);try{e(a,void 0,i())}catch{console.error(` Command failed: ${n.name}`),process.exitCode=1;return}}})}const p=c(u(import.meta.url)),m=JSON.parse(o(l(p,`..`,`package.json`),`utf-8`));async function h(){let e=new a;e.name(`kick`).description(`KickJS — A production-grade, decorator-driven Node.js framework`).version(m.version);let o=i(process.cwd()),s=o,c=await t(s)??{},l=[...r,...c.plugins??[]],u=n(l,c.commands??[]);await u.register(e,{cwd:s,projectRoot:o,config:c,log:e=>console.log(e)}),d(e,{...c,commands:u.commands}),e.showHelpAfterError();let f=process.argv.map(e=>e===`-v`?`--version`:e);await e.parseAsync(f)}h().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v8.14.1
2
+ * @forinda/kickjs-cli v8.14.3
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as e}from"./rolldown-runtime-C_ICmTLf.mjs";import{existsSync as t,mkdirSync as n,readFileSync as r,writeFileSync as i}from"node:fs";import{dirname as a,isAbsolute as o,join as s,relative as c,resolve as l}from"node:path";import{fileURLToPath as u}from"node:url";import{access as d,readFile as f}from"node:fs/promises";var p=/* @__PURE__ */ e({BUILTIN_REPO_TYPES:()=>_,DEPRECATED_REPO_TYPES:()=>v,PACKAGE_MANAGERS:()=>m,PLURALIZE_DEFAULT:()=>!1,defineConfig:()=>b,execBin:()=>g,hasDependency:()=>x,hasSwagger:()=>C,loadKickConfig:()=>M,resolveModuleConfig:()=>k,resolvePluralize:()=>D,resolvePluralizeRoutes:()=>O,resolveSchemaLib:()=>w,resolveTokenScope:()=>T,runScript:()=>h,testImportSource:()=>S,validateAssetMap:()=>P,warnIfDeprecatedRepo:()=>y,writeAssetConfigSnapshot:()=>N});const m=[`pnpm`,`npm`,`yarn`,`bun`];function h(e,t){return e===`npm`||e===`bun`?`${e} run ${t}`:`${e} ${t}`}function g(e,t){return{npm:`npx ${t}`,pnpm:`pnpm exec ${t}`,yarn:`yarn ${t}`,bun:`bunx ${t}`}[e]}const _=[`inmemory`],v=[`prisma`,`drizzle`];function y(e){return v.includes(e)?(console.warn(` Note: '${e}' is no longer a built-in repository preset — a repository shaped to it is that library's interface, not KickJS's.\n Scaffolding a generic custom-repository stub instead; wire it to ${e} yourself.`),!0):!1}function b(e){return e}function x(e,n,i=`runtime`){try{let a=s(e,`package.json`);if(!t(a))return!1;let o=JSON.parse(r(a,`utf-8`));return o.dependencies?.[n]?!0:i===`any`&&!!o.devDependencies?.[n]}catch{return!1}}function S(e){return x(e,`vite-plus`,`any`)&&!x(e,`vitest`,`any`)?`vite-plus/test`:`vitest`}function C(e){return x(e,`@forinda/kickjs-swagger`,`runtime`)}function w(e){return x(e,`valibot`,`runtime`)?`valibot`:x(e,`yup`,`runtime`)?`yup`:`zod`}function T(e,n){if(e?.tokenScope&&typeof e.tokenScope==`string`&&e.tokenScope.length>0){let t=E(e.tokenScope);if(t.length>0)return t}try{let e=s(n,`package.json`);if(t(e)){let t=JSON.parse(r(e,`utf-8`));if(typeof t.name==`string`&&t.name.length>0){let e=t.name.match(/^@([^/]+)\//),n=E(e?e[1]:t.name);if(n.length>0)return n}}}catch{}return`app`}function E(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/^-+|-+$/g,``).replace(/-{2,}/g,`-`)}function D(e,t){return e??t?.pluralize??!1}function O(e,t){return e??t?.pluralizeRoutes??!0}function k(e){if(!e)return{};let t={dir:e.modules?.dir,repo:e.modules?.repo,schemaDir:e.modules?.schemaDir,pluralize:e.modules?.pluralize,pluralizeRoutes:e.modules?.pluralizeRoutes,style:e.modules?.style};return t.style!==void 0&&t.style!==`define`&&t.style!==`class`&&(console.warn(` Warning: modules.style '${t.style}' is not a valid value (expected 'define' or 'class'). Falling back to 'define'.`),t.style=`define`),t.repo&&typeof t.repo==`string`&&!_.includes(t.repo)&&(y(t.repo)||console.warn(` Warning: modules.repo '${t.repo}' is not a built-in type (${_.join(`, `)}). It will generate a stub repository. Use { name: '${t.repo}' } to silence this warning.`)),t}const A=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function j(e){for(let n=e;;n=a(n)){if(t(s(n,`node_modules`,`@forinda`,`kickjs-cli`,`package.json`)))return{};if(a(n)===n)break}let n=s(a(u(import.meta.url)),`..`),r=[s(n,`dist`,`index.mjs`),s(n,`src`,`index.ts`)].find(t);return r?{"@forinda/kickjs-cli":r}:{}}async function M(e){let{findProjectRoot:t}=await import(`./project-root-DvXJgSgx.mjs`).then(e=>e.n),n=t(e);for(let e of A){let t=s(n,e);try{await d(t)}catch{continue}if(e.endsWith(`.json`)){let e=await f(t,`utf-8`);return JSON.parse(e)}if(e.endsWith(`.ts`)){let r;try{r=await import(`jiti`)}catch(t){let n=t instanceof Error?t.message:String(t);n.includes(`Cannot find package 'jiti'`)||n.includes(`ERR_MODULE_NOT_FOUND`)?console.warn(`Warning: Failed to load ${e} — 'jiti' is required for TypeScript configs. Install jiti as a dev dependency, or rename the file to kick.config.js / kick.config.mjs / kick.config.json.`):console.warn(`Warning: Failed to initialize jiti for ${e}: ${n}`);continue}try{let e=await r.createJiti(n,{interopDefault:!0,fsCache:!1,alias:j(n),tsconfigPaths:!0}).import(t,{default:!0}),i=P(e,n);for(let e of i)console.warn(` Warning: ${e}`);return N(n,e),e}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}try{let{pathToFileURL:e}=await import(`node:url`),r=await import(e(t).href),i=r.default??r,a=P(i,n);for(let e of a)console.warn(` Warning: ${e}`);return N(n,i),i}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}return null}function N(e,t){if(t?.assetMap&&Object.keys(t.assetMap).length!==0)try{let r=s(e,`.kickjs`);n(r,{recursive:!0});let a={version:1,assetMap:t.assetMap,...t.build?.outDir?{build:{outDir:t.build.outDir}}:{}};i(s(r,`kick.config.json`),JSON.stringify(a,null,2)+`
11
+ import{t as e}from"./rolldown-runtime-DB9qXK5A.mjs";import{existsSync as t,mkdirSync as n,readFileSync as r,writeFileSync as i}from"node:fs";import{dirname as a,isAbsolute as o,join as s,relative as c,resolve as l}from"node:path";import{fileURLToPath as u}from"node:url";import{access as d,readFile as f}from"node:fs/promises";var p=/* @__PURE__ */ e({BUILTIN_REPO_TYPES:()=>_,DEPRECATED_REPO_TYPES:()=>v,PACKAGE_MANAGERS:()=>m,PLURALIZE_DEFAULT:()=>!1,defineConfig:()=>b,execBin:()=>g,hasDependency:()=>x,hasSwagger:()=>C,loadKickConfig:()=>M,resolveModuleConfig:()=>k,resolvePluralize:()=>D,resolvePluralizeRoutes:()=>O,resolveSchemaLib:()=>w,resolveTokenScope:()=>T,runScript:()=>h,testImportSource:()=>S,validateAssetMap:()=>P,warnIfDeprecatedRepo:()=>y,writeAssetConfigSnapshot:()=>N});const m=[`pnpm`,`npm`,`yarn`,`bun`];function h(e,t){return e===`npm`||e===`bun`?`${e} run ${t}`:`${e} ${t}`}function g(e,t){return{npm:`npx ${t}`,pnpm:`pnpm exec ${t}`,yarn:`yarn ${t}`,bun:`bunx ${t}`}[e]}const _=[`inmemory`],v=[`prisma`,`drizzle`];function y(e){return v.includes(e)?(console.warn(` Note: '${e}' is no longer a built-in repository preset — a repository shaped to it is that library's interface, not KickJS's.\n Scaffolding a generic custom-repository stub instead; wire it to ${e} yourself.`),!0):!1}function b(e){return e}function x(e,n,i=`runtime`){try{let a=s(e,`package.json`);if(!t(a))return!1;let o=JSON.parse(r(a,`utf-8`));return o.dependencies?.[n]?!0:i===`any`&&!!o.devDependencies?.[n]}catch{return!1}}function S(e){return x(e,`vite-plus`,`any`)&&!x(e,`vitest`,`any`)?`vite-plus/test`:`vitest`}function C(e){return x(e,`@forinda/kickjs-swagger`,`runtime`)}function w(e){return x(e,`valibot`,`runtime`)?`valibot`:x(e,`yup`,`runtime`)?`yup`:`zod`}function T(e,n){if(e?.tokenScope&&typeof e.tokenScope==`string`&&e.tokenScope.length>0){let t=E(e.tokenScope);if(t.length>0)return t}try{let e=s(n,`package.json`);if(t(e)){let t=JSON.parse(r(e,`utf-8`));if(typeof t.name==`string`&&t.name.length>0){let e=t.name.match(/^@([^/]+)\//),n=E(e?e[1]:t.name);if(n.length>0)return n}}}catch{}return`app`}function E(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/^-+|-+$/g,``).replace(/-{2,}/g,`-`)}function D(e,t){return e??t?.pluralize??!1}function O(e,t){return e??t?.pluralizeRoutes??!0}function k(e){if(!e)return{};let t={dir:e.modules?.dir,repo:e.modules?.repo,schemaDir:e.modules?.schemaDir,pluralize:e.modules?.pluralize,pluralizeRoutes:e.modules?.pluralizeRoutes,style:e.modules?.style};return t.style!==void 0&&t.style!==`define`&&t.style!==`class`&&(console.warn(` Warning: modules.style '${t.style}' is not a valid value (expected 'define' or 'class'). Falling back to 'define'.`),t.style=`define`),t.repo&&typeof t.repo==`string`&&!_.includes(t.repo)&&(y(t.repo)||console.warn(` Warning: modules.repo '${t.repo}' is not a built-in type (${_.join(`, `)}). It will generate a stub repository. Use { name: '${t.repo}' } to silence this warning.`)),t}const A=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function j(e){for(let n=e;;n=a(n)){if(t(s(n,`node_modules`,`@forinda`,`kickjs-cli`,`package.json`)))return{};if(a(n)===n)break}let n=s(a(u(import.meta.url)),`..`),r=[s(n,`dist`,`index.mjs`),s(n,`src`,`index.ts`)].find(t);return r?{"@forinda/kickjs-cli":r}:{}}async function M(e){let{findProjectRoot:t}=await import(`./project-root-CVGTdH_N.mjs`).then(e=>e.n),n=t(e);for(let e of A){let t=s(n,e);try{await d(t)}catch{continue}if(e.endsWith(`.json`)){let e=await f(t,`utf-8`);return JSON.parse(e)}if(e.endsWith(`.ts`)){let r;try{r=await import(`jiti`)}catch(t){let n=t instanceof Error?t.message:String(t);n.includes(`Cannot find package 'jiti'`)||n.includes(`ERR_MODULE_NOT_FOUND`)?console.warn(`Warning: Failed to load ${e} — 'jiti' is required for TypeScript configs. Install jiti as a dev dependency, or rename the file to kick.config.js / kick.config.mjs / kick.config.json.`):console.warn(`Warning: Failed to initialize jiti for ${e}: ${n}`);continue}try{let e=await r.createJiti(n,{interopDefault:!0,fsCache:!1,alias:j(n),tsconfigPaths:!0}).import(t,{default:!0}),i=P(e,n);for(let e of i)console.warn(` Warning: ${e}`);return N(n,e),e}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}try{let{pathToFileURL:e}=await import(`node:url`),r=await import(e(t).href),i=r.default??r,a=P(i,n);for(let e of a)console.warn(` Warning: ${e}`);return N(n,i),i}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}return null}function N(e,t){if(t?.assetMap&&Object.keys(t.assetMap).length!==0)try{let r=s(e,`.kickjs`);n(r,{recursive:!0});let a={version:1,assetMap:t.assetMap,...t.build?.outDir?{build:{outDir:t.build.outDir}}:{}};i(s(r,`kick.config.json`),JSON.stringify(a,null,2)+`
12
12
  `,`utf-8`)}catch{}}function P(e,n){let r=[];if(!e?.assetMap)return r;let i=l(n);for(let[a,o]of Object.entries(e.assetMap)){if(!a||a.includes(`/`)){r.push(`assetMap key '${a}' is invalid — must be a non-empty string without '/'`);continue}if(typeof o?.src!=`string`||o.src.length===0){r.push(`assetMap.${a} is missing a non-empty 'src' field`);continue}let e=l(n,o.src);t(e)||r.push(`assetMap.${a}.src ('${o.src}') does not exist — typegen + build will fail`),o.dest&&F(l(n,o.dest),i)&&r.push(`assetMap.${a}.dest ('${o.dest}') resolves outside the project root — refusing to copy`)}return r}function F(e,t){let n=c(t,e);return n===``?!1:n.startsWith(`..`)||o(n)}export{C as a,D as c,T as d,h as f,x as i,O as l,y as m,p as n,M as o,S as p,g as r,k as s,m as t,w as u};