@forinda/kickjs-cli 8.11.0 → 8.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-docs-DUxCvCBc.mjs → agent-docs-CuD2-X3w.mjs} +2 -2
- package/dist/{agent-docs-DGE_9641.mjs → agent-docs-ykxoPqXX.mjs} +3 -3
- package/dist/{agent-docs-DGE_9641.mjs.map → agent-docs-ykxoPqXX.mjs.map} +1 -1
- package/dist/{build-BUFgk6Ss.mjs → build-C-AsmCh1.mjs} +2 -2
- package/dist/{build-BQiF63pu.mjs → build-DQnV0GCD.mjs} +3 -3
- package/dist/{build-BQiF63pu.mjs.map → build-DQnV0GCD.mjs.map} +1 -1
- package/dist/{builtins-CaOnJmm8.mjs → builtins-BsYCQU80.mjs} +2 -2
- package/dist/{builtins-d9YrHyb1.mjs → builtins-Cjp9FT1m.mjs} +107 -107
- package/dist/cli.mjs +2 -2
- package/dist/config-DMFwBdWg.mjs +12 -0
- package/dist/config-DbnBakh8.mjs +13 -0
- package/dist/config-DbnBakh8.mjs.map +1 -0
- package/dist/{doctor-CYnItgYt.mjs → doctor-rEbeoAoO.mjs} +21 -21
- package/dist/doctor-rEbeoAoO.mjs.map +1 -0
- package/dist/{fullstack-D6ikgPKw.mjs → fullstack-DdSScENL.mjs} +3 -3
- package/dist/{fullstack--utMEADY.mjs → fullstack-XhuwRQEb.mjs} +4 -4
- package/dist/{fullstack--utMEADY.mjs.map → fullstack-XhuwRQEb.mjs.map} +1 -1
- package/dist/index.d.mts +8 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/package-manager-C8ekNwsa.mjs +11 -0
- package/dist/package-manager-DvXi-NGm.mjs +12 -0
- package/dist/package-manager-DvXi-NGm.mjs.map +1 -0
- package/dist/{plugin-C7ybMh21.mjs → plugin--9hxxgsD.mjs} +2 -2
- package/dist/{plugin-DS5g6A5U.mjs → plugin-CvlUt9NG.mjs} +2 -2
- package/dist/{project-CGCAZsQV.mjs → project-BN1DnrN3.mjs} +5 -5
- package/dist/{project-CGCAZsQV.mjs.map → project-BN1DnrN3.mjs.map} +1 -1
- package/dist/{project-CDUJMeIr.mjs → project-DBmrFgdd.mjs} +4 -4
- package/dist/{project-root-Da2aMneY.mjs → project-root-BXmtd-te.mjs} +2 -2
- package/dist/{project-root-ThZdP1t_.mjs → project-root-FMt83NHV.mjs} +3 -3
- package/dist/{project-root-ThZdP1t_.mjs.map → project-root-FMt83NHV.mjs.map} +1 -1
- package/dist/{prompts-Pzk_Seut.mjs → prompts-DJBDNwHt.mjs} +2 -2
- package/dist/{prompts-Pzk_Seut.mjs.map → prompts-DJBDNwHt.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DAPeToCs.mjs → rolldown-runtime-C4d34LEE.mjs} +1 -1
- package/dist/{run-plugins-Du6FlB7_.mjs → run-plugins-9tjbMqS6.mjs} +80 -80
- package/dist/run-plugins-9tjbMqS6.mjs.map +1 -0
- package/dist/{typegen-9tepCLIZ.mjs → typegen-AGdhxyRc.mjs} +5 -5
- package/dist/{typegen-9tepCLIZ.mjs.map → typegen-AGdhxyRc.mjs.map} +1 -1
- package/dist/{typegen-BkpCnSQ3.mjs → typegen-Lf0UPhdl.mjs} +4 -4
- package/dist/{types-DJXxhn43.mjs → types-B5dY2mTz.mjs} +1 -1
- package/package.json +3 -3
- package/templates/base/files/tsconfig.json +3 -1
- package/templates/template-inertia/feature.json +1 -1
- package/templates/template-inertia/files/tsconfig.json +3 -1
- package/templates/template-inertia/files/vite.config.ts +3 -2
- package/dist/config-CcsYA02N.mjs +0 -13
- package/dist/config-CcsYA02N.mjs.map +0 -1
- package/dist/config-DhzyaY1S.mjs +0 -12
- package/dist/doctor-CYnItgYt.mjs.map +0 -1
- package/dist/package-manager-BaXE6gY_.mjs +0 -12
- package/dist/package-manager-BaXE6gY_.mjs.map +0 -1
- package/dist/package-manager-Ogog_AHE.mjs +0 -11
- package/dist/run-plugins-Du6FlB7_.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v8.
|
|
2
|
+
* @forinda/kickjs-cli v8.12.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as e}from"./rolldown-runtime-DAPeToCs.mjs";import{c as t,g as n,i as r,o as i,r as a,s as o,t as s}from"./project-CDUJMeIr.mjs";import{a as c,c as l,d as u,f as d,i as f,l as p,o as m,p as h,s as g,u as _}from"./config-DhzyaY1S.mjs";import{n as v,r as y}from"./plugin-DS5g6A5U.mjs";import{a as b,i as x,n as ee,o as S,t as C}from"./package-manager-Ogog_AHE.mjs";import{a as w,c as te,d as ne,f as T,i as re,l as ie,n as ae,o as oe,p as se,r as E,s as D,u as ce}from"./agent-docs-DUxCvCBc.mjs";import{t as O}from"./project-root-Da2aMneY.mjs";import{C as le,S as ue,_ as de,a as fe,b as pe,c as me,d as he,f as ge,g as _e,h as ve,i as ye,l as be,m as xe,o as Se,p as Ce,r as we,s as Te,t as Ee,u as De,v as Oe,w as ke,x as k,y as Ae}from"./typegen-BkpCnSQ3.mjs";import{t as je}from"./build-BUFgk6Ss.mjs";import{createRequire as Me}from"node:module";import{cpSync as Ne,existsSync as A,mkdirSync as Pe,readFileSync as j,readdirSync as M,rmSync as Fe,statSync as Ie,writeFileSync as N}from"node:fs";import P,{basename as Le,dirname as F,join as I,relative as L,resolve as R,sep as z}from"node:path";import{fileURLToPath as Re,pathToFileURL as B}from"node:url";import{fork as ze,spawn as Be,spawnSync as Ve}from"node:child_process";import{copyFile as He,mkdir as Ue,readFile as V,readdir as We,rm as Ge,stat as Ke,writeFile as qe}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as Je}from"node:crypto";import{parseSync as Ye}from"oxc-parser";import Xe from"pluralize";import{arch as Ze,platform as Qe,release as $e}from"node:os";const et=[{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`},{value:`storage`,label:`Storage`,hint:`disk, S3 / R2 / MinIO`}];function tt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack | inertia`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{re(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await ce({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=R(`.`),e=Le(r)):r=R(t.directory||e),A(r)){let i=M(r);if(i.length>0){if(t.force)w.warn(`Clearing existing files in ${r}`);else if(n){w.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),D(`Aborted.`);return}else{w.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)w.message(` - ${e}`);if(i.length>5&&w.message(` ... and ${i.length-5} more`),!await E({message:T.red(`Remove all existing files and proceed?`),initialValue:!1})){D(`Aborted.`);return}}for(let e of i)Fe(R(r,e),{recursive:!0,force:!0})}}let i=t.template;i||=n?`minimal`:await te({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 a=t.runtime;a||=n?`express`:await te({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 o=t.pm;o||=n?await ee(void 0):await te({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let c=t.repo;c||=n?`inmemory`:await ce({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),h(c);let l=t.schema;i===`inertia`&&(l&&l!==`zod`&&w.warn(`The inertia template uses zod — ignoring --schema ${l}.`),l=`zod`),l||=n?`zod`:await te({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(l)||(w.warn(`Unknown --schema "${l}", falling back to zod.`),l=`zod`);let u;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();u=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else u=n?[]:await oe({message:`Select packages to include`,options:[...et],required:!1});let f;f=t.git===void 0?n?!0:await E({message:`Initialize git repository?`,initialValue:!0}):t.git;let p;if(p=t.install===void 0?n?!0:await E({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){w.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),D(`Aborted.`);return}let{VITE_TEMPLATES:m,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-D6ikgPKw.mjs`);if(t.viteTemplate!==void 0&&!m.some(e=>e.value===t.viteTemplate)){w.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${m.map(e=>e.value).join(`, `)}.`),D(`Aborted.`);return}let _=t.frontend===`vite`?`vite`:`kick`,v=t.viteTemplate??g;if(i===`fullstack`&&!t.frontend&&!n&&(_=await te({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)`}]})),_===`vite`&&!t.viteTemplate&&!n&&(v=await te({message:`create-vite template`,options:m.map(e=>({value:e.value,label:e.label})),initialValue:g})),i===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-D6ikgPKw.mjs`);await t({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,schemaLib:l,runtime:a,packages:u,frontend:_,viteTemplate:v}),D(`Done! Next steps: ${T.cyan(`cd ${e} && ${o}${o===`pnpm`?` dev`:` run dev:server`}`)}`)}else await s({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,template:i,defaultRepo:c,packages:u,schemaLib:l,runtime:a}),D(`Done! Next steps: ${T.cyan(`cd ${e} && ${d(o,`dev`)}`)}`)})}Xe.addUncountableRule(`auth`);function H(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function nt(e){let t=H(e);return t.charAt(0).toLowerCase()+t.slice(1)}function U(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function W(e){return Xe.plural(e)}function rt(e){return Xe.plural(e)}function it(e){return U(e).replace(/-/g,`_`)}function at(e){let t=e.cwd??process.cwd(),n=e.projectRoot??O(t),r=e.pluralize??!1,i=H(e.name),a=nt(e.name),o=U(e.name),s=it(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=W(o);c.pluralKebab=e,c.pluralPascal=H(e),c.pluralCamel=nt(e)}return c}function ot(e,t){return R(e.cwd,t)}async function st(e){return import(B(e).href)}const ct=/* @__PURE__ */ new Map;async function lt(e){let t=ct.get(e);if(t)return t;let n=ut(e);return ct.set(e,n),n}async function ut(e){let t=R(e,`package.json`);if(!A(t))return{generators:[],loaded:[],failed:[]};let n=dt(JSON.parse(await V(t,`utf-8`))),r=Me(R(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 V(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=R(F(t),s);if(!A(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await st(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)ft(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 dt(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 ft(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function pt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return gt(r.spec,r.source,e,n);let i=ht(await lt(n),e.generatorName);return i?gt(i.spec,i.source,e,n):null}async function mt(e,t=[]){let n=await lt(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 ht(e,t){return e.generators.find(e=>e.spec.name===t)}async function gt(e,t,n,r){let i=at({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=ot(i,e.path);await S(t,e.content),o.push(t)}return{files:o,source:t}}function G(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const _t={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function vt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yt(e){return _t[e]??vt(e)}function bt(e){return`create${e}Repository`}function xt(e){return e??`define`}function St(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=e.routePath??r,s=bt(t),c=xt(a),l=`/**
|
|
11
|
+
import{t as e}from"./rolldown-runtime-C4d34LEE.mjs";import{c as t,g as n,i as r,o as i,r as a,s as o,t as s}from"./project-DBmrFgdd.mjs";import{a as c,c as l,d as u,f as d,i as f,l as p,m,o as h,p as g,s as _,u as v}from"./config-DMFwBdWg.mjs";import{n as y,r as b}from"./plugin-CvlUt9NG.mjs";import{a as x,i as S,n as ee,o as C,t as w}from"./package-manager-C8ekNwsa.mjs";import{a as T,c as te,d as ne,f as E,i as re,l as ie,n as ae,o as oe,p as se,r as D,s as O,u as ce}from"./agent-docs-CuD2-X3w.mjs";import{t as k}from"./project-root-BXmtd-te.mjs";import{C as le,S as ue,_ as de,a as fe,b as pe,c as me,d as he,f as ge,g as _e,h as ve,i as ye,l as be,m as xe,o as Se,p as Ce,r as we,s as Te,t as Ee,u as De,v as Oe,w as ke,x as A,y as Ae}from"./typegen-Lf0UPhdl.mjs";import{t as je}from"./build-C-AsmCh1.mjs";import{createRequire as Me}from"node:module";import{cpSync as Ne,existsSync as j,mkdirSync as Pe,readFileSync as M,readdirSync as N,rmSync as Fe,statSync as Ie,writeFileSync as P}from"node:fs";import F,{basename as Le,dirname as I,join as L,relative as R,resolve as z,sep as B}from"node:path";import{fileURLToPath as Re,pathToFileURL as V}from"node:url";import{fork as ze,spawn as Be,spawnSync as Ve}from"node:child_process";import{copyFile as He,mkdir as Ue,readFile as H,readdir as We,rm as Ge,stat as Ke,writeFile as qe}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as Je}from"node:crypto";import{parseSync as Ye}from"oxc-parser";import Xe from"pluralize";import{arch as Ze,platform as Qe,release as $e}from"node:os";const et=[{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`},{value:`storage`,label:`Storage`,hint:`disk, S3 / R2 / MinIO`}];function tt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack | inertia`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--frontend <kind>`,`Fullstack web/ scaffold: 'kick' (wired React app) or 'vite' (create-vite, unwired)`).option(`--vite-template <name>`,`create-vite TypeScript template for --frontend vite (default 'react-ts')`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. swagger,ws,queue,devtools)`).option(`-y, --yes`,`Pick safe defaults for every prompt (template=minimal, repo=inmemory, no extras, git+install on)`).option(`--non-interactive`,`alias for --yes`).action(async(e,t)=>{re(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await ce({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let r;if(e===`.`?(r=z(`.`),e=Le(r)):r=z(t.directory||e),j(r)){let i=N(r);if(i.length>0){if(t.force)T.warn(`Clearing existing files in ${r}`);else if(n){T.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),O(`Aborted.`);return}else{T.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)T.message(` - ${e}`);if(i.length>5&&T.message(` ... and ${i.length-5} more`),!await D({message:E.red(`Remove all existing files and proceed?`),initialValue:!1})){O(`Aborted.`);return}}for(let e of i)Fe(z(r,e),{recursive:!0,force:!0})}}let i=t.template;i||=n?`minimal`:await te({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 a=t.runtime;a||=n?`express`:await te({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 o=t.pm;o||=n?await ee(void 0):await te({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let c=t.repo;c||=n?`inmemory`:await ce({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),m(c);let l=t.schema;i===`inertia`&&(l&&l!==`zod`&&T.warn(`The inertia template uses zod — ignoring --schema ${l}.`),l=`zod`),l||=n?`zod`:await te({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(l)||(T.warn(`Unknown --schema "${l}", falling back to zod.`),l=`zod`);let u;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();u=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else u=n?[]:await oe({message:`Select packages to include`,options:[...et],required:!1});let f;f=t.git===void 0?n?!0:await D({message:`Initialize git repository?`,initialValue:!0}):t.git;let p;if(p=t.install===void 0?n?!0:await D({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){T.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),O(`Aborted.`);return}let{VITE_TEMPLATES:h,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-DdSScENL.mjs`);if(t.viteTemplate!==void 0&&!h.some(e=>e.value===t.viteTemplate)){T.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${h.map(e=>e.value).join(`, `)}.`),O(`Aborted.`);return}let _=t.frontend===`vite`?`vite`:`kick`,v=t.viteTemplate??g;if(i===`fullstack`&&!t.frontend&&!n&&(_=await te({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)`}]})),_===`vite`&&!t.viteTemplate&&!n&&(v=await te({message:`create-vite template`,options:h.map(e=>({value:e.value,label:e.label})),initialValue:g})),i===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-DdSScENL.mjs`);await t({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,schemaLib:l,runtime:a,packages:u,frontend:_,viteTemplate:v}),O(`Done! Next steps: ${E.cyan(`cd ${e} && ${o}${o===`pnpm`?` dev`:` run dev:server`}`)}`)}else await s({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,template:i,defaultRepo:c,packages:u,schemaLib:l,runtime:a}),O(`Done! Next steps: ${E.cyan(`cd ${e} && ${d(o,`dev`)}`)}`)})}Xe.addUncountableRule(`auth`);function U(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function nt(e){let t=U(e);return t.charAt(0).toLowerCase()+t.slice(1)}function W(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function G(e){return Xe.plural(e)}function rt(e){return Xe.plural(e)}function it(e){return W(e).replace(/-/g,`_`)}function at(e){let t=e.cwd??process.cwd(),n=e.projectRoot??k(t),r=e.pluralize??!1,i=U(e.name),a=nt(e.name),o=W(e.name),s=it(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=G(o);c.pluralKebab=e,c.pluralPascal=U(e),c.pluralCamel=nt(e)}return c}function ot(e,t){return z(e.cwd,t)}async function st(e){return import(V(e).href)}const ct=/* @__PURE__ */ new Map;async function lt(e){let t=ct.get(e);if(t)return t;let n=ut(e);return ct.set(e,n),n}async function ut(e){let t=z(e,`package.json`);if(!j(t))return{generators:[],loaded:[],failed:[]};let n=dt(JSON.parse(await H(t,`utf-8`))),r=Me(z(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 H(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=z(I(t),s);if(!j(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await st(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)ft(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 dt(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 ft(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function pt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return gt(r.spec,r.source,e,n);let i=ht(await lt(n),e.generatorName);return i?gt(i.spec,i.source,e,n):null}async function mt(e,t=[]){let n=await lt(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 ht(e,t){return e.generators.find(e=>e.spec.name===t)}async function gt(e,t,n,r){let i=at({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=ot(i,e.path);await C(t,e.content),o.push(t)}return{files:o,source:t}}function K(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const _t={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function vt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yt(e){return _t[e]??vt(e)}function bt(e){return`create${e}Repository`}function xt(e){return e??`define`}function St(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=e.routePath??r,s=bt(t),c=xt(a),l=`/**
|
|
12
12
|
* ${t} Module
|
|
13
13
|
*
|
|
14
14
|
* REST module with a flat folder structure.
|
|
@@ -407,7 +407,7 @@ export type ${t}Repository = ReturnType<typeof ${s}>
|
|
|
407
407
|
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
408
408
|
*/
|
|
409
409
|
export const ${t.toUpperCase()}_REPOSITORY = createToken<${t}Repository>('${a}/${t}/repository')
|
|
410
|
-
`}function jt(e){let{pascal:t,kebab:n,plural:r=``,style:i=`define`,testHarness:a=!1}=e,
|
|
410
|
+
`}function jt(e){let{pascal:t,kebab:n,plural:r=``,style:i=`define`,testHarness:a=!1,testImport:o=`vitest`}=e,s=e.routePath??r,c=i===`define`?`${t}Module()`:`${t}Module`;return`${a?`import { describe, it, expect, beforeEach } from '${o}'
|
|
411
411
|
import request from 'supertest'
|
|
412
412
|
import { Container } from '@forinda/kickjs'
|
|
413
413
|
import { createTestApp } from '@forinda/kickjs-testing'
|
|
@@ -423,11 +423,11 @@ import { ${t}Module } from '../${n}.module'
|
|
|
423
423
|
* pass the same values in \`boot()\` below and update this to match, so the test
|
|
424
424
|
* exercises the paths production actually serves:
|
|
425
425
|
*
|
|
426
|
-
* defaultVersion: false → '/api/${
|
|
427
|
-
* apiPrefix: '/v1' → '/v1/v1/${
|
|
426
|
+
* defaultVersion: false → '/api/${s}'
|
|
427
|
+
* apiPrefix: '/v1' → '/v1/v1/${s}'
|
|
428
428
|
*/
|
|
429
|
-
const BASE = '/api/v1/${
|
|
430
|
-
`:`import { describe, it, beforeEach } from '
|
|
429
|
+
const BASE = '/api/v1/${s}'
|
|
430
|
+
`:`import { describe, it, beforeEach } from '${o}'
|
|
431
431
|
import { Container } from '@forinda/kickjs'
|
|
432
432
|
|
|
433
433
|
// Install \`@forinda/kickjs-testing\` and \`supertest\` to boot this module in a
|
|
@@ -449,7 +449,7 @@ ${a?` /**
|
|
|
449
449
|
*/
|
|
450
450
|
async function boot() {
|
|
451
451
|
const { app, container } = await createTestApp({
|
|
452
|
-
modules: [${
|
|
452
|
+
modules: [${c}],
|
|
453
453
|
// Mirror your bootstrap() here if it overrides either, and update BASE:
|
|
454
454
|
// apiPrefix: '/api',
|
|
455
455
|
// defaultVersion: 1,
|
|
@@ -457,7 +457,7 @@ ${a?` /**
|
|
|
457
457
|
return { app, container, agent: request(app.handle.bind(app)) }
|
|
458
458
|
}
|
|
459
459
|
|
|
460
|
-
describe('GET /${
|
|
460
|
+
describe('GET /${s}', () => {
|
|
461
461
|
it('returns an empty page before anything is created', async () => {
|
|
462
462
|
const { agent } = await boot()
|
|
463
463
|
const res = await agent.get(BASE)
|
|
@@ -477,7 +477,7 @@ ${a?` /**
|
|
|
477
477
|
})
|
|
478
478
|
|
|
479
479
|
it.todo('returns created ${r}, paginated')
|
|
480
|
-
})`:` describe('GET /${
|
|
480
|
+
})`:` describe('GET /${s}', () => {
|
|
481
481
|
// Boot the module with createTestApp and assert { data, meta }.
|
|
482
482
|
it.todo('returns an empty page before anything is created')
|
|
483
483
|
it.todo('returns created ${r}, paginated')
|
|
@@ -487,7 +487,7 @@ ${a?` /**
|
|
|
487
487
|
// reporter lists it as outstanding instead of counting it as a pass. Replace
|
|
488
488
|
// the todo with a real test as you implement each endpoint.
|
|
489
489
|
|
|
490
|
-
describe('POST /${
|
|
490
|
+
describe('POST /${s}', () => {
|
|
491
491
|
${a?` it('creates a ${n} and points Location at it', async () => {
|
|
492
492
|
const { agent } = await boot()
|
|
493
493
|
const res = await agent.post(BASE).send({ name: 'Test ${t}' })
|
|
@@ -501,31 +501,31 @@ ${a?` it('creates a ${n} and points Location at it', async () => {
|
|
|
501
501
|
it.todo('rejects an invalid body')
|
|
502
502
|
})
|
|
503
503
|
|
|
504
|
-
describe('GET /${
|
|
504
|
+
describe('GET /${s}/:id', () => {
|
|
505
505
|
// Create one, fetch it by id, assert the payload matches.
|
|
506
506
|
it.todo('returns a ${n} by id')
|
|
507
507
|
// Fetch an id that does not exist, assert 404.
|
|
508
508
|
it.todo('returns 404 for an unknown id')
|
|
509
509
|
})
|
|
510
510
|
|
|
511
|
-
describe('PATCH /${
|
|
511
|
+
describe('PATCH /${s}/:id', () => {
|
|
512
512
|
// Create, update, assert the change is reflected on a subsequent read.
|
|
513
513
|
it.todo('updates an existing ${n}')
|
|
514
514
|
})
|
|
515
515
|
|
|
516
|
-
describe('DELETE /${
|
|
516
|
+
describe('DELETE /${s}/:id', () => {
|
|
517
517
|
// Create, delete, assert a subsequent read is 404.
|
|
518
518
|
it.todo('deletes a ${n}')
|
|
519
519
|
})
|
|
520
520
|
})
|
|
521
|
-
`}function Mt(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../${n}.repository`}=e,
|
|
522
|
-
import { ${
|
|
521
|
+
`}function Mt(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../${n}.repository`,testImport:a=`vitest`}=e,o=`create${t}Repository`;return`import { describe, it, expect, beforeEach } from '${a}'
|
|
522
|
+
import { ${o}, type ${t}Repository } from '${i}'
|
|
523
523
|
|
|
524
524
|
describe('${t} repository', () => {
|
|
525
525
|
let repo: ${t}Repository
|
|
526
526
|
|
|
527
527
|
beforeEach(() => {
|
|
528
|
-
repo = ${
|
|
528
|
+
repo = ${o}()
|
|
529
529
|
})
|
|
530
530
|
|
|
531
531
|
it('should create and retrieve a ${n}', async () => {
|
|
@@ -657,7 +657,7 @@ describe('${t} repository', () => {
|
|
|
657
657
|
expect(found).toBeNull()
|
|
658
658
|
})
|
|
659
659
|
})
|
|
660
|
-
`}function Nt(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject
|
|
660
|
+
`}function Nt(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject } from '@forinda/kickjs'
|
|
661
661
|
import type { ParsedQuery } from '@forinda/kickjs'
|
|
662
662
|
import { ${t.toUpperCase()}_REPOSITORY, type ${t}Repository } from './${n}.repository'
|
|
663
663
|
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
@@ -746,7 +746,7 @@ export class ${t}Controller {
|
|
|
746
746
|
return reply.noContent()
|
|
747
747
|
}
|
|
748
748
|
}
|
|
749
|
-
`)}async function Rt(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,routePath:a,repo:o,noTests:s,tokenScope:c,style:l,testHarness:u,write:
|
|
749
|
+
`)}async function Rt(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,routePath:a,repo:o,noTests:s,tokenScope:c,style:l,testHarness:u,testImport:d,write:f}=e,p=e.swagger??!1,m=e.schemaLib??`zod`;await f(`${n}.module.ts`,St({pascal:t,kebab:n,plural:r,routePath:a,repo:o,style:l})),await f(`${n}.constants.ts`,It({pascal:t,kebab:n})),await f(`${n}.controller.ts`,wt({pascal:t,kebab:n,plural:r,pluralPascal:i,swagger:p})),await f(`${n}.service.ts`,Nt({pascal:t,kebab:n})),await f(`dtos/create-${n}.dto.ts`,Dt({pascal:t,kebab:n,schemaLib:m})),await f(`dtos/update-${n}.dto.ts`,Ot({pascal:t,kebab:n,schemaLib:m})),await f(`dtos/${n}-response.dto.ts`,kt({pascal:t,kebab:n})),await f(`${n}.repository.ts`,At({pascal:t,kebab:n,repoType:o,dtoPrefix:`./dtos`,tokenScope:c})),s||(await f(`__tests__/${n}.controller.test.ts`,jt({pascal:t,kebab:n,plural:r,routePath:a,style:l,testHarness:u,testImport:d})),await f(`__tests__/${n}.repository.test.ts`,Mt({pascal:t,kebab:n,plural:r,repoPrefix:`../${n}.repository`,testImport:d})))}function zt(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Bt(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize===!0,l=e.pattern??`rest`;e.minimal&&(l=`minimal`);let u=W(t),d=U(t),f=c?G(u):u,p=c?rt(d):d,m=e.pluralizeRoutes===!1?u:G(u),h=L(n,f),g=[],_=o??!1,v={kebab:u,pascal:d,plural:f,pluralPascal:p,routePath:m,moduleDir:h,repo:a,noEntity:r??!1,noTests:i??!1,tokenScope:e.tokenScope??`app`,swagger:e.swagger??!1,schemaLib:e.schemaLib??`zod`,testHarness:e.testHarness??!1,testImport:e.testImport,style:e.style??`define`,write:async(e,t)=>{let n=L(h,e);s?g.push(n):!_&&await S(n)&&!await D({message:`File exists: ${E.dim(e)}. Overwrite?`,initialValue:!1})?T.warn(`Skipped: ${e}`):(await C(n,t),g.push(n))},files:g};switch(l){case`minimal`:await Lt(v);break;default:await Rt(v)}return s||await Vt(n,d,f,u,v.style),g}async function Vt(e,t,n,r,i=`define`){let a=L(e,`index.ts`),o=await S(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){let e=i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
750
750
|
import { ${t}Module } from '${s}'
|
|
751
751
|
|
|
752
752
|
export const modules: AppModuleEntry[] = [${c}]
|
|
@@ -754,10 +754,10 @@ export const modules: AppModuleEntry[] = [${c}]
|
|
|
754
754
|
import { ${t}Module } from '${s}'
|
|
755
755
|
|
|
756
756
|
export const modules = defineModules().mount(${c})
|
|
757
|
-
`;await
|
|
757
|
+
`;await C(a,e);return}let l=await H(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=K(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${K(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
|
|
758
758
|
`,e);l=l.slice(0,t+1)+u+`
|
|
759
759
|
`+l.slice(t+1)}else l=u+`
|
|
760
|
-
`+l}let f=Ut(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${
|
|
760
|
+
`+l}let f=Ut(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${K(t)}Module\\b`).test(e)||(l=Ht(l,c))}else l=Ht(l,c);await C(a,l)}function Ht(e,t){let n=Ut(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function Ut(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=Kt(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=Wt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function Wt(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=qt(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=qt(e,t);if(n===-1)break;i=n+1}return i}function Gt(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
761
761
|
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function Kt(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Gt(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++}else{if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}}return-1}function qt(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Gt(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++}else{if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}}return-1}function Jt(e,t,n,r){return`/**
|
|
762
762
|
* Snapshot for the DevTools topology view (\`/_debug\`).
|
|
763
763
|
*
|
|
@@ -798,7 +798,7 @@ export const modules = defineModules().mount(${c})
|
|
|
798
798
|
// ]
|
|
799
799
|
// },`.split(`
|
|
800
800
|
`).map(e=>r+e).join(`
|
|
801
|
-
`)}async function Yt(e){let{name:t,outDir:n}=e,r=
|
|
801
|
+
`)}async function Yt(e){let{name:t,outDir:n}=e,r=W(t),i=U(t),a=[],o=L(n,`${r}.adapter.ts`);return await C(o,`import {
|
|
802
802
|
defineAdapter,
|
|
803
803
|
type AdapterContext,
|
|
804
804
|
type AdapterMiddleware,
|
|
@@ -1007,7 +1007,7 @@ ${Jt(r,i,`adapter`,` `)}
|
|
|
1007
1007
|
}
|
|
1008
1008
|
},
|
|
1009
1009
|
})
|
|
1010
|
-
`),a.push(o),a}async function Xt(e){let{name:t,outDir:n}=e,r=
|
|
1010
|
+
`),a.push(o),a}async function Xt(e){let{name:t,outDir:n}=e,r=W(t),i=U(t),a=[],o=L(n,`${r}.plugin.ts`);return await C(o,`import {
|
|
1011
1011
|
definePlugin,
|
|
1012
1012
|
type AppAdapter,
|
|
1013
1013
|
type AppModuleEntry,
|
|
@@ -1167,10 +1167,10 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
|
1167
1167
|
${Jt(r,i,`plugin`,` `)}
|
|
1168
1168
|
}),
|
|
1169
1169
|
})
|
|
1170
|
-
`),a.push(o),a}const Zt={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function Qt(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!1}=e;if(n)return
|
|
1171
|
-
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=Qt({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!1}),c=
|
|
1170
|
+
`),a.push(o),a}const Zt={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function Qt(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!1}=e;if(n)return z(n);if(r){let e=Zt,n=W(r),a=o?G(n):n,s=e[t]??``,c=L(i,a);return z(s?L(c,s):c)}return z(a)}async function $t(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.runtime===`express`,o=e.runtime?`this project runs on ${e.runtime} and has no
|
|
1171
|
+
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=Qt({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!1}),c=W(t),l=nt(t),u=[],d=L(s,`${c}.middleware.ts`);return await C(d,`${a?`import type { Request, Response, NextFunction } from 'express'`:`import type { IncomingMessage, ServerResponse } from 'node:http'`}
|
|
1172
1172
|
|
|
1173
|
-
export interface ${
|
|
1173
|
+
export interface ${U(t)}Options {
|
|
1174
1174
|
// Add configuration options here. The factory below closes over the
|
|
1175
1175
|
// resolved options object; pass them at the call site —
|
|
1176
1176
|
// \`${l}({ foo: 'bar' })\` — and the closure preserves them across
|
|
@@ -1178,7 +1178,7 @@ export interface ${H(t)}Options {
|
|
|
1178
1178
|
}
|
|
1179
1179
|
|
|
1180
1180
|
/**
|
|
1181
|
-
* ${
|
|
1181
|
+
* ${U(t)} middleware.
|
|
1182
1182
|
*
|
|
1183
1183
|
* Usage in bootstrap (fires on every request):
|
|
1184
1184
|
* middlewares: [${l}()]
|
|
@@ -1214,7 +1214,7 @@ export interface ${H(t)}Options {
|
|
|
1214
1214
|
* first \`next()\` throws \`TypeError: next is not a function\`. Generate a
|
|
1215
1215
|
* guard instead (\`kick g guard\`) for the per-route, ctx-style shape.
|
|
1216
1216
|
*/
|
|
1217
|
-
export function ${l}(options: ${
|
|
1217
|
+
export function ${l}(options: ${U(t)}Options = {}) {
|
|
1218
1218
|
${a?" // Typed from `express` because that is this project's runtime\n // (`runtime: 'express'` in kick.config.ts). Global middleware is\n // connect-style on every engine, but only Express hands the handler its own\n // request / response objects — so `req.originalUrl`, `req.query` and\n // `res.json()` are all available here. Switching `runtime` later means\n // re-typing this signature from `node:http`.\n return (req: Request, res: Response, next: NextFunction) => {":` // Typed from \`node:http\`, not \`express\`. Global middleware is connect-style
|
|
1219
1219
|
// on every engine, but ${o} dependency to import types from. Under Fastify the handler
|
|
1220
1220
|
// receives \`request.raw\` / a reply driver, and under h3 the node objects, so
|
|
@@ -1227,7 +1227,7 @@ ${a?" // Typed from `express` because that is this project's runtime\n // (`ru
|
|
|
1227
1227
|
next()
|
|
1228
1228
|
}
|
|
1229
1229
|
}
|
|
1230
|
-
`),u.push(d),u}async function en(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!1}),o=
|
|
1230
|
+
`),u.push(d),u}async function en(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!1}),o=W(t),s=nt(t),c=U(t),l=[],u=L(a,`${o}.guard.ts`);return await C(u,`import { Container, HttpException } from '@forinda/kickjs'
|
|
1231
1231
|
import type { RequestContext } from '@forinda/kickjs'
|
|
1232
1232
|
|
|
1233
1233
|
/**
|
|
@@ -1267,7 +1267,7 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
|
|
|
1267
1267
|
ctx.problem.unauthorized({ detail: 'Invalid or expired token' })
|
|
1268
1268
|
}
|
|
1269
1269
|
}
|
|
1270
|
-
`),l.push(u),l}function tn(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function nn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=
|
|
1270
|
+
`),l.push(u),l}function tn(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function nn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=W(t),s=U(t),c=e.key??nt(t),l=Array.isArray(e.params)?e.params:tn(e.params),u=Qt({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!1}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
1271
1271
|
`)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,h=l.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
1272
1272
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
1273
1273
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
@@ -1318,7 +1318,7 @@ ${_}
|
|
|
1318
1318
|
throw new Error("${s} contributor: resolve() not implemented")
|
|
1319
1319
|
},
|
|
1320
1320
|
})
|
|
1321
|
-
`,y=
|
|
1321
|
+
`,y=L(u,`${o}.contributor.ts`);return await C(y,v),[y]}async function rn(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!1}),o=W(t),s=U(t),c=[],l=L(a,`${o}.service.ts`);return await C(l,`import { Service } from '@forinda/kickjs'
|
|
1322
1322
|
|
|
1323
1323
|
@Service()
|
|
1324
1324
|
export class ${s}Service {
|
|
@@ -1327,7 +1327,7 @@ export class ${s}Service {
|
|
|
1327
1327
|
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1328
1328
|
// ) {}
|
|
1329
1329
|
}
|
|
1330
|
-
`),c.push(l),c}async function an(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!1}),o=
|
|
1330
|
+
`),c.push(l),c}async function an(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!1}),o=W(t),s=U(t),c=[],l=L(a,`${o}.controller.ts`);return await C(l,`import { Controller, Get, Post, Patch, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
1331
1331
|
|
|
1332
1332
|
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1333
1333
|
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
@@ -1370,13 +1370,13 @@ export class ${s}Controller {
|
|
|
1370
1370
|
return reply.noContent()
|
|
1371
1371
|
}
|
|
1372
1372
|
}
|
|
1373
|
-
`),c.push(l),c}async function on(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!1}),o=
|
|
1373
|
+
`),c.push(l),c}async function on(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=Qt({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!1}),o=W(t),s=U(t),c=nt(t),l=e.schemaLib??`zod`,u=Tt[l],d=[],f=L(a,`${o}.dto.ts`);return await C(f,`${u.import}
|
|
1374
1374
|
|
|
1375
1375
|
export const ${c}Schema = ${Et(l,`// Define your schema fields here\n name: ${u.required}`)}
|
|
1376
1376
|
|
|
1377
1377
|
export type ${s}DTO = ${u.infer(`${c}Schema`)}
|
|
1378
|
-
`),d.push(f),d}async function sn(e){let t=
|
|
1379
|
-
Skipped — existing kick.config.ts preserved.`),[]):(await
|
|
1378
|
+
`),d.push(f),d}async function sn(e){let t=L(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return j(t)&&!e.force&&!await D({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
1379
|
+
Skipped — existing kick.config.ts preserved.`),[]):(await C(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1380
1380
|
|
|
1381
1381
|
export default defineConfig({
|
|
1382
1382
|
modules: {
|
|
@@ -1430,7 +1430,7 @@ ${p}
|
|
|
1430
1430
|
`||e[l]===`\r`);)l++;let u=e.slice(l),d=/build\s*:\s*\([^)]*\)\s*=>\s*\(\s*\{/g.exec(s);if(!d)return{migrated:null,reason:`build: () => ({...}) not found in defineModule`};let f=d.index+d[0].length-1,p=cn(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=ln(m,/register\s*\(([^)]*)\)\s*\{/),g=ln(m,/contributors\s*\(\s*\)\s*\{/),_=ln(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=fn(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${un(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${un(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${un(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
1431
1431
|
${y}
|
|
1432
1432
|
}
|
|
1433
|
-
`}${u}`}}function hn(e,t){return t===`class`?mn(e):pn(e)}function gn(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function _n(e){let t=[];return await n(
|
|
1433
|
+
`}${u}`}}function hn(e,t){return t===`class`?mn(e):pn(e)}function gn(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function _n(e){let t=[];return await n(z(e),0),t;async function n(e,r){let i;try{i=await We(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=L(e,a),o;try{o=await Ke(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function vn(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await We(e)}catch{return}await Ue(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=L(e,a),o=L(t,a),s;try{s=await Ke(i)}catch{continue}s.isDirectory()?await r(i,o):(await He(i,o),n++)}}}function yn(e){let t=(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`);return L(e,`.kickjs`,`codemod-backups`,`${t}-modules`)}async function bn(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await _n(e),s=await H(L(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=yn(r),await vn(e,c));let l=[];for(let e of o){let t=hn(await H(e,`utf-8`),i);t.migrated==null?l.push({path:e,status:`skipped`,reason:t.reason}):(n||await qe(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`}))}let u=L(e,`index.ts`),d=null;try{d=await H(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=gn(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await qe(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function xn(e,t){let n=await _n(e),r=[],i=t===`define`?/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/:/export\s+const\s+\w+Module\s*=\s*defineModule\s*\(/;for(let e of n){let t=await H(e,`utf-8`);i.test(t)&&r.push(e)}return r}const Sn={string:{ts:`string`,zod:`z.string().min(1).max(200)`},text:{ts:`string`,zod:`z.string().min(1)`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.iso.datetime()`},email:{ts:`string`,zod:`z.email()`},url:{ts:`string`,zod:`z.url()`},uuid:{ts:`string`,zod:`z.uuid()`},json:{ts:`any`,zod:`z.any()`}};function Cn(e){let t=e.map(e=>{let t=e.indexOf(`:`);if(t===-1)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let n=e.slice(0,t),r=e.slice(t+1);if(!n||!r)throw Error(`Invalid field: "${e}". Use format: name:type (e.g. title:string)`);let i=!1;r.endsWith(`:optional`)&&(r=r.slice(0,-9),i=!0),n.endsWith(`?`)&&(n=n.slice(0,-1),i=!0),r.endsWith(`?`)&&(r=r.slice(0,-1),i=!0);let a=r;if(a.startsWith(`enum:`)){let e=a.slice(5).split(`,`);return{name:n,type:`enum`,tsType:e.map(e=>`'${e}'`).join(` | `),zodType:`z.enum([${e.map(e=>`'${e}'`).join(`, `)}])`,optional:i}}let o=Sn[a];if(!o){let e=[...Object.keys(Sn),`enum:a,b,c`].join(`, `);throw Error(`Unknown field type: "${a}". Valid types: ${e}`)}return{name:n,type:a,tsType:o.ts,zodType:o.zod,optional:i}}),n=/* @__PURE__ */ new Set;for(let{name:e}of t){if(n.has(e))throw Error(`Duplicate field: "${e}". Each field name may appear once.`);n.add(e)}return t}async function wn(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize===!0,c=W(t),l=U(t),u=s?G(c):c,d=s?rt(l):l,f=e.pluralizeRoutes===!1?c:G(c),p=L(r,u),m=[],h=async(e,t)=>{let n=L(p,e);await C(n,t),m.push(n)};return await h(`${c}.module.ts`,St({pascal:l,kebab:c,plural:u,routePath:f,repo:i,style:o})),await h(`${c}.constants.ts`,It({pascal:l,kebab:c,fields:n})),await h(`${c}.controller.ts`,wt({pascal:l,kebab:c,plural:u,pluralPascal:d,swagger:e.swagger??!1})),await h(`${c}.service.ts`,Nt({pascal:l,kebab:c})),await h(`dtos/create-${c}.dto.ts`,Tn(l,n)),await h(`dtos/update-${c}.dto.ts`,En(l,n)),await h(`dtos/${c}-response.dto.ts`,Dn(l,n)),await h(`${c}.repository.ts`,At({pascal:l,kebab:c,repoType:i,dtoPrefix:`./dtos`,tokenScope:a})),await Vt(r,l,u,c,o),m}function Tn(e,t){return`import { z } from 'zod'
|
|
1434
1434
|
|
|
1435
1435
|
export const create${e}Schema = z.object({
|
|
1436
1436
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -1453,10 +1453,10 @@ ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
|
1453
1453
|
createdAt: string
|
|
1454
1454
|
updatedAt: string
|
|
1455
1455
|
}
|
|
1456
|
-
`}async function On(e){let{name:t,moduleName:n,modulesDir:r}=e,
|
|
1456
|
+
`}async function On(e){let{name:t,moduleName:n,modulesDir:r,testImport:i=`vitest`}=e,a=e.pluralize??!1,o=W(t),s=U(t),c=[],l;if(e.outDir)l=z(e.outDir);else if(n){let e=W(n),t=a?G(e):e;l=z(L(r??`src/modules`,t,`__tests__`))}else l=z(`src/__tests__`);let u=L(l,`${o}.test.ts`);return await C(u,`import { describe, it, expect, beforeEach } from '${i}'
|
|
1457
1457
|
import { Container } from '@forinda/kickjs'
|
|
1458
1458
|
|
|
1459
|
-
describe('${
|
|
1459
|
+
describe('${s}', () => {
|
|
1460
1460
|
beforeEach(() => {
|
|
1461
1461
|
Container.reset()
|
|
1462
1462
|
})
|
|
@@ -1476,53 +1476,53 @@ describe('${o}', () => {
|
|
|
1476
1476
|
expect(true).toBe(true)
|
|
1477
1477
|
})
|
|
1478
1478
|
})
|
|
1479
|
-
`),
|
|
1480
|
-
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const jn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function
|
|
1481
|
-
(dry run — no files were written)`),console.log()}async function Mn(e){if(!e)try{let e=await
|
|
1479
|
+
`),c.push(u),c}function kn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}var An=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
|
|
1480
|
+
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const jn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function q(e){return e.parent?.opts()?.dryRun??!1}function J(e,t=!1){let n=process.cwd();console.log(`\n ${t?`Would generate`:`Generated`} ${e.length} file${e.length===1?``:`s`}:`);for(let t of e)console.log(` ${t.replace(n+`/`,``)}`);t&&console.log(`
|
|
1481
|
+
(dry run — no files were written)`),console.log()}async function Mn(e){if(!e)try{let e=await h(process.cwd());await Ee({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const Nn=[{name:`module <name>`,description:`REST module (controller, service, DTOs, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate .agents/* + root CLAUDE.md from upstream templates`}],Pn=/* @__PURE__ */ new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
|
|
1482
1482
|
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),Fn=/* @__PURE__ */ new Set([...Nn.map(e=>e.name.split(` `)[0]),...Pn.keys()]);async function In(){console.log(`
|
|
1483
1483
|
Built-in generators:
|
|
1484
|
-
`);let e=Math.max(...Nn.map(e=>e.name.length));for(let t of Nn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await
|
|
1484
|
+
`);let e=Math.max(...Nn.map(e=>e.name.length));for(let t of Nn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await h(process.cwd()),n=y(t?.plugins??[],t?.commands??[]),r=await mt(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
1485
1485
|
Plugin generators:
|
|
1486
1486
|
`);let e=Math.max(...r.generators.map(e=>`${e.spec.name} <name>`.length));for(let{source:t,spec:n}of r.generators){let r=`${n.name} <name>`;console.log(` kick g ${r.padEnd(e+2)} ${n.description} [${t}]`)}}if(r.failed.length>0){console.log(`
|
|
1487
1487
|
Failed to load:
|
|
1488
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function Ln(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`])n[e]===!1&&(r[e]=!1);for(let e of[`pluralize`,`pluralizeRoutes`])r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return r}async function Rn(e,t,n){let r=await
|
|
1489
|
-
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
1490
|
-
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
1488
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function Ln(e,t){let n=e.parent?.opts()??{},r={...e.optsWithGlobals(),...t};for(let e of[`entity`,`tests`])n[e]===!1&&(r[e]=!1);for(let e of[`pluralize`,`pluralizeRoutes`])r[e]===void 0&&n[e]!==void 0&&(r[e]=n[e]);return r}async function Rn(e,t,n){let r=await h(process.cwd()),i=_(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??zt(i.repo);t.repo&&m(t.repo);let s=t.pattern??r?.pattern??`rest`,d=l(t.pluralize,i),y=p(t.pluralizeRoutes,i),b=u(r,process.cwd()),x=c(k()),S=v(k()),ee=k(),C=f(ee,`@forinda/kickjs-testing`,`any`)&&f(ee,`supertest`,`any`),w=i.style??`define`;if(!n&&w===`define`){let e=await xn(z(a),`define`);if(e.length>0){console.error(`\n ${E.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${E.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${E.bold(`Files needing migration:`)}`);for(let t of e.slice(0,5))console.error(` - ${t}`);e.length>5&&console.error(` … and ${e.length-5} more`),console.error(`\n ${E.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${E.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${E.dim(`// kick.config.ts`)}\n ${E.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let T=[];for(let r of e){let e=await Bt({name:r,modulesDir:z(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,testHarness:C,testImport:g(ee),dryRun:n,pluralize:d,pluralizeRoutes:y,tokenScope:b,swagger:x,schemaLib:S,style:i.style});T.push(...e)}J(T,n),await Mn(n)}function zn(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await In();return}if(!e||e.length===0){n.help();return}let a=q(i);x(a);let[o,s,...c]=e;if(o){let e=await h(process.cwd()),n=y(e?.plugins??[],e?.commands??[]),i=await pt({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){J(i.files,a);return}if(o!==`module`&&Fn.has(o)){let e=Pn.get(o);e?(console.error(`\n 'kick g ${o}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`)),process.exitCode=1;return}}await Rn(e,r,a)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=q(n);x(r),await Rn(e,Ln(n,t),r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=q(n);x(r),J(await Yt({name:e,outDir:z(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=q(n);x(r),J(await Xt({name:e,outDir:z(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
|
|
1489
|
+
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);x(r);let i=await h(process.cwd()),a=_(i),o=a.dir??`src/modules`;J(await $t({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:l(void 0,a),runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
1490
|
+
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);x(r);let i=await h(process.cwd()),a=_(i),o=a.dir??`src/modules`;J(await en({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:l(void 0,a)}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
1491
1491
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1492
1492
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
1493
|
-
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=
|
|
1494
|
-
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
1495
|
-
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
1496
|
-
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=
|
|
1497
|
-
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=
|
|
1493
|
+
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=q(n);x(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await h(process.cwd()),o=_(a),s=o.dir??`src/modules`;J(await nn({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:l(void 0,o)}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
1494
|
+
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);x(r);let i=await h(process.cwd()),a=_(i),o=a.dir??`src/modules`;J(await rn({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:l(void 0,a)}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
1495
|
+
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);x(r);let i=await h(process.cwd()),a=_(i),o=a.dir??`src/modules`;J(await an({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:l(void 0,a)}),r),await Mn(r)}),n.command(`dto <name>`).description(`Generate a DTO schema for the project’s validation library
|
|
1496
|
+
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=q(n);x(r);let i=await h(process.cwd()),a=_(i),o=a.dir??`src/modules`;J(await on({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:l(void 0,a),schemaLib:v(k())}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
1497
|
+
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=q(n);x(r);let i=await h(process.cwd()),a=_(i),o=a.dir??`src/modules`;J(await On({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pluralize:l(void 0,a),testImport:g(k())}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
1498
1498
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1499
1499
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
1500
1500
|
Optional: append :optional (shell-safe): description:text:optional
|
|
1501
|
-
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=Ln(r,n),a=
|
|
1501
|
+
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--pluralize`,`Pluralize module folders and names (users/ for user)`).option(`--no-pluralize`,`Use names as typed (the default)`).option(`--pluralize-routes`,`Mount at the plural of the name (/users for user, the default)`).option(`--no-pluralize-routes`,`Mount at the name as typed (/user)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=Ln(r,n),a=q(r);x(a),t.length===0&&(console.error(`
|
|
1502
1502
|
Error: At least one field is required.
|
|
1503
1503
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1504
1504
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1505
1505
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
1506
|
-
`),process.exit(1));let o=await
|
|
1507
|
-
`,u=``;
|
|
1508
|
-
`)){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(
|
|
1506
|
+
`),process.exit(1));let o=await h(process.cwd()),s=_(o),d=i.modulesDir??s.dir??`src/modules`,f=Cn(t),m=u(o,process.cwd()),g=c(k()),v=await wn({name:e,fields:f,modulesDir:z(d),noEntity:i.entity===!1,noTests:i.tests===!1,pluralize:l(i.pluralize,s),pluralizeRoutes:p(i.pluralizeRoutes,s),tokenScope:m,swagger:g,style:s.style});console.log(`\n Scaffolded ${e} with ${f.length} field(s):`);for(let e of f)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);J(v,a),await Mn(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=q(t);x(n),J(await sn({outDir:z(`.`),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=q(t);x(n);let r=e.only??`all`;jn.includes(r)?J(await ae({outDir:z(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n):(console.error(` Invalid --only value: ${r}. Expected: ${jn.join(` | `)}`),process.exitCode=1)});for(let e of t?.generators??[])Bn(n,e,t?.projectRoot)}function Bn(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=q(o);x(s);let c=await pt({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&J(c.files,s)})}const Vn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function Hn(e){let t=F.resolve(e.cwd,`.kickjs/types`);e.check||await Ue(t,{recursive:!0});let n=/* @__PURE__ */ new Map,r=e.scan??ve,i=F.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(V(e).href)},async writeFile(t,n){let r=F.resolve(e.cwd,t);await Ue(F.dirname(r),{recursive:!0}),await qe(r,n,`utf8`)},getScanResult:e=>{let t=Un(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?_e(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=F.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=`${Vn}${n.id} */\n\n`+a+`
|
|
1507
|
+
`,u=``;j(i)&&(u=await H(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 qe(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i}))}if(c.length>0)throw new An(c);return s}function Un(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function Wn(e,t){let n=new Set(t),r=[],i=[],a=/* @__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 Gn=/* @__PURE__ */ e({applyDisableFilter:()=>Wn,runAllPluginTypegens:()=>Kn});async function Kn(e){let t=[...zo,...e.config?.plugins??[]],{enabled:n,skipped:r,unknown:i}=Wn(y(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 Hn({cwd:e.cwd,config:e.config??{},plugins:n,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&kn())for(let e of t)console.log(` ${e.id}: ${e.status}`);return t}catch(t){if(t instanceof An||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 qn(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 Jn=`__kickjs_typegen_owner`;function Yn(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-Lf0UPhdl.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Gn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-Lf0UPhdl.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-C-AsmCh1.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=F.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=>F.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=qn(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 Xn(e){let t=process.platform===`win32`;for(let n of Zn(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=L(n,i);if(j(r))return{cmd:r,args:[`--noEmit`],shell:t,kind:e}}}return null}function Zn(e){let t=z(e),n=Qn(t);return(n?[t,n]:[t]).map(e=>L(e,`node_modules`,`.bin`))}function Qn(e){for(let t=I(e);t!==I(t);t=I(t)){let n=L(t,`pnpm-workspace.yaml`),r=L(t,`package.json`);if(j(n)||j(r))return $n(n,r).some(n=>er(n,R(t,e)))?t:void 0}}function $n(e,t){try{if(j(e)){let t=M(e,`utf-8`).split(/^packages:\s*$/m)[1]??``,n=[];for(let e of t.split(`
|
|
1508
|
+
`)){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(M(t,`utf-8`)),r=Array.isArray(n)?n:n?.packages;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}catch{return[]}}function er(e,t){let n=e.replace(/^\.\//,``).replace(/\/+$/,``).split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${n}$`).test(t.split(B).join(`/`))}function tr(e){let t=e.spawnFn??Be,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 nr(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
1509
1509
|
`):`${n.slice(0,t).join(`
|
|
1510
|
-
`)}\n… ${n.length-t} more line(s)`}function rr(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function ir(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 ar(e,t,n={}){t&&(process.env.PORT=t);let r=rr(n.polling),i=process.cwd(),a=await
|
|
1510
|
+
`)}\n… ${n.length-t} more line(s)`}function rr(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function ir(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 ar(e,t,n={}){t&&(process.env.PORT=t);let r=rr(n.polling),i=process.cwd(),a=await h(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await Ee({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=z(i,a?.typegen?.outDir??`.kickjs/types`);try{let e=await Kn({cwd:i,config:a});await ye(c,e,!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),u=l(z(`package.json`)).resolve(`vite`),{createServer:d}=await import(V(u).href);globalThis[Jn]=`kick-dev`;let f=await d({configFile:z(`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,g=!0;if(p){let e=Xn(i);e?m=tr({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?g||(g=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(g=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(nr(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 _=Yn({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=>_.handleWatchEvent(`add`,e)),f.watcher.on(`unlink`,e=>_.handleWatchEvent(`unlink`,e)),f.watcher.on(`change`,e=>_.handleWatchEvent(`change`,e)),f.watcher.on(`unlinkDir`,e=>_.handleWatchEvent(`unlinkDir`,e)),_.assetSrcRoots.length>0&&f.watcher.add([..._.assetSrcRoots]),await f.listen(),f.printUrls(),console.log(`
|
|
1511
1511
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
1512
|
-
`),
|
|
1512
|
+
`),m?.schedule();let v=!1,y=async()=>{if(!v){v=!0,_.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await f.close(),process.exit(0)}};process.on(`SIGINT`,y),process.on(`SIGTERM`,y),process.on(`SIGBREAK`,y)}async function or(e){let t=await h(e);try{await Ee({cwd:e,allowDuplicates:!0,schemaValidator:t?.typegen?.schemaValidator??`zod`,envFile:t?.typegen?.envFile,srcDir:t?.typegen?.srcDir,outDir:t?.typegen?.outDir,assetMap:t?.assetMap,runPlugins:!1});let n=z(e,t?.typegen?.outDir??`.kickjs/types`),r=await Kn({cwd:e,config:t});await ye(n,r,!1)}catch(e){console.warn(` kick typegen: skipped before typecheck (${e?.message??e}).\n Generated types may be stale — errors inside .kickjs/types are likely from that.`)}}function sr(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await ar(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`\n Error: vite is not installed.\n Run: ${w()} add -D vite unplugin-swc\n`):console.error(`
|
|
1513
1513
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1514
1514
|
Building for production...
|
|
1515
|
-
`);let{createRequire:e}=await import(`node:module`),t=e(
|
|
1516
|
-
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
1515
|
+
`);let{createRequire:e}=await import(`node:module`),t=e(z(`package.json`)).resolve(`vite`),{build:n}=await import(V(t).href);await n({configFile:z(`vite.config.ts`)});let r=await h(process.cwd()),i=r?.copyDirs??[];if(i.length>0){console.log(`
|
|
1516
|
+
Copying directories to dist...`);for(let e of i){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?L(`dist`,e):e.dest??L(`dist`,t),r=z(t),i=z(n);j(r)?(Pe(i,{recursive:!0}),Ne(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)):console.log(` ⚠ Skipped ${t} (not found)`)}}if(r?.assetMap&&Object.keys(r.assetMap).length>0){console.log(`
|
|
1517
1517
|
Building asset map...`);try{await je(r,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
1518
1518
|
Build complete.
|
|
1519
|
-
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await
|
|
1519
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await h(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0)console.log(` No assetMap entries — nothing to build.`);else{console.log(`
|
|
1520
1520
|
Building asset map...`);try{await je(e,{cwd:process.cwd()}),console.log(`
|
|
1521
1521
|
Asset build complete.
|
|
1522
|
-
`)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),n(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=
|
|
1523
|
-
No type-checker found. Install one in this project:\n ${
|
|
1524
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function cr(){try{let e=
|
|
1525
|
-
`))})}const{bold:
|
|
1522
|
+
`)}catch(e){console.error(` ✗ ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}}),e.command(`start`).description(`Start production server`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`-p, --port <port>`,`Port number`).action(e=>{let t={NODE_ENV:`production`};e.port&&(t.PORT=String(e.port)),n(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).option(`--no-typegen`,`Skip refreshing .kickjs/types first`).action(async e=>{let t=z(process.cwd(),e.cwd??`.`);e.typegen!==!1&&await or(t);let n=Xn(t);if(!n){console.error(`
|
|
1523
|
+
No type-checker found. Install one in this project:\n ${w(t)} add -D typescript (tsc)\n ${w(t)} add -D @typescript/native-preview (tsgo, faster)\n`),process.exit(1);return}let r=Ve(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await ir(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await ar(e.entry,e.port)}catch(e){console.error(`
|
|
1524
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function cr(){try{let e=I(Re(import.meta.url));return JSON.parse(M(L(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const lr=new Set(Object.values(a).filter(e=>e.deprecated).map(e=>e.pkg));function ur(e){let t=L(e,`package.json`);if(!j(t))return[];let n;try{n=JSON.parse(M(t,`utf-8`))}catch{return[]}let r={...n.dependencies,...n.devDependencies};return Object.keys(r).filter(e=>e===`@forinda/kickjs`||e.startsWith(`@forinda/kickjs-`)).toSorted().map(t=>{let n=null,i=L(e,`node_modules`,...t.split(`/`),`package.json`);if(j(i))try{n=JSON.parse(M(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:lr.has(t)}})}function dr(e){let t=e;for(;;){if(j(L(t,`package.json`)))return t;let e=I(t);if(e===t)return null;t=e}}function fr(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${cr()}`,``,` System:`,` OS: ${Qe()} ${$e()} (${Ze()})`,` Node: ${process.version}`],t=dr(process.cwd()),n=t?ur(t):[];if(!t)e.push(``,` Packages: (not inside a project — no package.json found)`);else if(n.length===0)e.push(``,` Packages: (no @forinda/kickjs* dependencies in ${t})`);else{e.push(``,` Packages:`);let t=Math.max(...n.map(e=>e.name.length));for(let r of n){let n=r.installed??`${r.declared??`?`} (declared — not installed)`,i=r.deprecated?" [DEPRECATED — see `kick add --list --all`]":``;e.push(` ${r.name.padEnd(t+2)} ${n}${i}`)}}e.push(``),console.log(e.join(`
|
|
1525
|
+
`))})}const{bold:Y,dim:X,green:pr,red:mr,yellow:hr,blue:gr}=E;function _r(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,a=[];return t&&a.push(`${t}d`),n&&a.push(`${n}h`),r&&a.push(`${r}m`),a.push(`${i}s`),a.join(` `)}async function vr(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function yr(e,t){try{return await vr(`${e}${t}`)}catch{return null}}async function br(e){let[t,n,r,i,a]=await Promise.all([yr(e,`/health`),yr(e,`/metrics`),yr(e,`/routes`),yr(e,`/container`),yr(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function xr(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=X(`─`.repeat(60));if(console.log(),console.log(Y(` KickJS Inspector`)+X(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?pr(`● healthy`):mr(`● `+n.status);console.log(` ${Y(`Health:`)} ${e}`)}else console.log(` ${Y(`Health:`)} ${mr(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?mr:r.errorRate>0?hr:pr;console.log(` ${Y(`Uptime:`)} ${_r(r.uptimeSeconds)}`),console.log(` ${Y(`Requests:`)} ${r.requests}`),console.log(` ${Y(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${X(`(`)}${t(e+`%`)}${X(`)`)}`)}if(a&&console.log(` ${Y(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${Y(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(Y(` Routes`)),console.log(s),console.log(` ${X(`METHOD`)} ${X(`PATH`.padEnd(36))} ${X(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${ne(e.method)} ${t} ${gr(e.controller)}.${X(e.handler)}`)}}console.log(s),console.log()}function Sr(e){e.command(`inspect [url]`).description(`Connect to a running KickJS app and display debug info`).option(`-p, --port <port>`,`Override port`).option(`-w, --watch`,`Poll every 5 seconds`).option(`-j, --json`,`Output raw JSON`).action(async(e,t)=>{let n=e??`http://localhost:3000`;if(t.port)try{let e=new URL(n);e.port=t.port,n=e.origin}catch{n=`http://localhost:${t.port}`}let r=`${n.replace(/\/$/,``)}/_debug`,i=async()=>{try{let e=await br(r);t.json?console.log(JSON.stringify(e,null,2)):xr(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(mr(` ✖ Could not connect to ${n}`)),console.error(X(` ${e instanceof Error?e.message:String(e)}`))),t.watch||(process.exitCode=1)}};if(t.watch){let e=async()=>{process.stdout.write(`\x1B[2J\x1B[H`),await i()};await e(),setInterval(e,5e3)}else await i()})}function Z(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Q(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Cr=[{match(e,t){let n=Z(e,[`config`,`get`])&&Q(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Q(e,[`undefined`,`is not defined`]);return!n&&!r?null:Q(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
|
|
1526
1526
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
1527
1527
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
1528
1528
|
directly — so that import does not run and ConfigService falls back to
|
|
@@ -1546,7 +1546,7 @@ import { modules } from './modules'
|
|
|
1546
1546
|
import './config' // ← add this — registers env schema
|
|
1547
1547
|
import { bootstrap } from '@forinda/kickjs'
|
|
1548
1548
|
import { modules } from './modules'
|
|
1549
|
-
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=
|
|
1549
|
+
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=Q(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);return Q(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
|
|
1550
1550
|
When vitest re-imports your modules across tests, the same class can be
|
|
1551
1551
|
registered twice and the container throws. The fix is to wipe the
|
|
1552
1552
|
container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
|
|
@@ -1556,7 +1556,7 @@ describe('UserController', () => {
|
|
|
1556
1556
|
beforeEach(() => Container.reset())
|
|
1557
1557
|
|
|
1558
1558
|
it('does the thing', async () => { /* ... */ })
|
|
1559
|
-
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
1559
|
+
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Z(e,[`Module`,`is not a function`])||Z(e,[`Module`,`no exported member`])?{confidence:80,diagnosis:{id:`module-decorator-not-found`,title:`KickJS does not have a @Module decorator (different pattern from NestJS)`,explanation:`NestJS uses @Module({ controllers, providers }). KickJS uses an interface
|
|
1560
1560
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
1561
1561
|
returns the controller wiring. This was a deliberate choice — modules
|
|
1562
1562
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -1583,7 +1583,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
|
1583
1583
|
and matches the actual class names so refactors propagate via
|
|
1584
1584
|
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
1585
1585
|
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
1586
|
-
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=
|
|
1586
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=Q(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=Q(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
|
|
1587
1587
|
cluster: { workers: N }, the framework forks N workers, each of which
|
|
1588
1588
|
spins up its own Vite instance on a separate port. The fix landed in
|
|
1589
1589
|
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
@@ -1591,7 +1591,7 @@ silently skips cluster, with a warning. If you see this on an older
|
|
|
1591
1591
|
version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
|
|
1592
1592
|
modules,
|
|
1593
1593
|
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
1594
|
-
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return
|
|
1594
|
+
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return Q(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
|
|
1595
1595
|
reflect-metadata polyfill. The polyfill must be imported once,
|
|
1596
1596
|
before any decorator runs. Most projects do this at the top of
|
|
1597
1597
|
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
@@ -1600,7 +1600,7 @@ import './config'
|
|
|
1600
1600
|
import { bootstrap } from '@forinda/kickjs'
|
|
1601
1601
|
import { modules } from './modules'
|
|
1602
1602
|
|
|
1603
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return
|
|
1603
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return Q(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
|
|
1604
1604
|
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
1605
1605
|
the most likely cause is that the module is missing from the exported
|
|
1606
1606
|
array. The CLI usually wires this automatically, but a hand-edit can
|
|
@@ -1608,7 +1608,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
1608
1608
|
import { UserModule } from './users/user.module'
|
|
1609
1609
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
1610
1610
|
|
|
1611
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!
|
|
1611
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!Q(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=Q(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=Q(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&Q(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
|
|
1612
1612
|
That protects the vars your test runner pinned — but every var it did NOT
|
|
1613
1613
|
pin is silently backfilled from your \`.env\`. So a suite can pin its database
|
|
1614
1614
|
URL and still reach live development services through the vars it forgot,
|
|
@@ -1642,7 +1642,7 @@ beforeAll(() => {
|
|
|
1642
1642
|
vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
|
|
1643
1643
|
resetEnvCache()
|
|
1644
1644
|
loadEnv(envSchema)
|
|
1645
|
-
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=
|
|
1645
|
+
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}},{match(e,t){let n=Z(e,[`cannot inject`,`request-scoped`,`singleton`]),r=Z(e,[`request-scoped`,`singleton`]);return!n&&!r?null:{confidence:n?100:70,diagnosis:{id:`di-request-scope-into-singleton`,title:`A SINGLETON cannot hold a REQUEST-scoped dependency`,explanation:`Controllers are SINGLETON by default: one instance for the process, built
|
|
1646
1646
|
the first time the container resolves it. A REQUEST-scoped binding is the
|
|
1647
1647
|
opposite — one instance per request, discarded when the response ends.
|
|
1648
1648
|
|
|
@@ -1663,7 +1663,7 @@ and the singleton never captures one.
|
|
|
1663
1663
|
|
|
1664
1664
|
If the dependency did not need request scope in the first place, the
|
|
1665
1665
|
other direction also works — make it SINGLETON and pass the per-request
|
|
1666
|
-
values in as method arguments.`,docs:`https://kickjs.app/guide/dependency-injection.html#scopes`}}}},{match(e,t){let n=e.toLowerCase().includes(`circular dependency detected`),r=
|
|
1666
|
+
values in as method arguments.`,docs:`https://kickjs.app/guide/dependency-injection.html#scopes`}}}},{match(e,t){let n=e.toLowerCase().includes(`circular dependency detected`),r=Z(e,[`circular`,`dependency`]);return!n&&!r?null:{confidence:n?100:65,diagnosis:{id:`di-circular-dependency`,title:`Two services depend on each other, directly or through a chain`,explanation:`The container resolves constructor dependencies depth-first. When a token
|
|
1667
1667
|
is requested while it is already being resolved further up the stack, the
|
|
1668
1668
|
graph has a cycle and there is no order that satisfies both ends.
|
|
1669
1669
|
|
|
@@ -1695,7 +1695,7 @@ export class OrderService {
|
|
|
1695
1695
|
@Service()
|
|
1696
1696
|
export class BillingService {
|
|
1697
1697
|
@Autowired() private readonly orders!: OrderService // ← resolved after construction
|
|
1698
|
-
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=
|
|
1698
|
+
}`,docs:`https://kickjs.app/guide/dependency-injection.html#circular-dependency-detection`}}}},{match(e,t){let n=e.includes(`KICK001`),r=Q(e,[`no provider for`,`no provider found for`,`no binding is registered`]);return!n&&!r?null:{confidence:n?100:85,diagnosis:{id:`di-no-provider-for-token`,title:`A token was requested but nothing registers it`,explanation:`Decorators register bindings as a side effect of the class being LOADED —
|
|
1699
1699
|
and a class is only loaded if something imports it. A module that is not
|
|
1700
1700
|
in the bootstrap array is never imported, so none of its @Service /
|
|
1701
1701
|
@Repository / @Controller classes ever register, and the first thing that
|
|
@@ -1721,7 +1721,7 @@ export const TenantModule = defineModule({
|
|
|
1721
1721
|
},
|
|
1722
1722
|
routes: () => null,
|
|
1723
1723
|
}),
|
|
1724
|
-
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!
|
|
1724
|
+
})`,docs:`https://kickjs.app/guide/dependency-injection.html#registering-services`}}}},{match(e,t){if(!Q(e,[`vite`,`kick dev`,`dev server`,`localhost:5173`,`:5173`])||!Q(e,[`404`,`not found`,`cannot get`,`cannot post`,`no route`]))return null;let n=Z(e,[`app`,`export`]),r=Q(e,[`every route`,`all routes`,`every endpoint`,`all endpoints`,`none of the routes`]);return!n&&!r?null:{confidence:n&&r?85:n?80:70,diagnosis:{id:`vite-dev-app-not-exported`,title:"Every route 404s in dev because the entry file exports no `app`",explanation:`The Vite plugin does not start your server. It imports the entry module
|
|
1725
1725
|
and reads \`app\` off it, then hands each request to that instance.
|
|
1726
1726
|
|
|
1727
1727
|
When the entry runs \`await bootstrap(...)\` without assigning the result to
|
|
@@ -1744,15 +1744,15 @@ Then re-run \`kick explain --ai "<your error>"\`.`};let r;try{r=await import(`@f
|
|
|
1744
1744
|
kick add ai
|
|
1745
1745
|
|
|
1746
1746
|
Or manually:
|
|
1747
|
-
${
|
|
1747
|
+
${w()} add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Er(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Dr((await a.chat({messages:[{role:`system`,content:o},{role:`user`,content:s}]})).content);return e?{kind:`ok`,diagnosis:e}:{kind:`error`,message:`The LLM responded but the payload was not valid JSON in the expected shape. Try again, or file an issue with the error text.`}}catch(e){return{kind:`error`,message:`LLM request failed: ${e instanceof Error?e.message:String(e)}`}}}function Er(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
1748
1748
|
`)}function Dr(e){let t=[e,Or(e),kr(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Ar(t))return t}catch{continue}return null}function Or(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function kr(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(i)i=!1;else if(o===`\\`&&r)i=!0;else if(o===`"`)r=!r;else if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Ar(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.title==`string`&&typeof t.explanation==`string`&&typeof t.fix==`string`}function jr(e){e.command(`explain [message]`).description(`Explain a KickJS error and suggest a fix`).option(`-m, --message <text>`,`Error message to explain (alternative to positional arg)`).option(`--ai`,`Fall back to LLM if no known-issue matches (requires @forinda/kickjs-ai)`).option(`--model <name>`,`Model name for the --ai fallback`,`gpt-4o-mini`).option(`--json`,`Output the diagnosis as JSON for tooling integration`).action(async(e,t)=>{let n=await Pr(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
1749
1749
|
|
|
1750
1750
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
1751
1751
|
kick explain "config.get returned undefined"
|
|
1752
|
-
${d(
|
|
1752
|
+
${d(w(),`test`)} 2>&1 | kick explain\n`),process.exit(1));let r=Ir(),i=wr(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
1753
1753
|
`);return}if(i){Lr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
1754
1754
|
`),process.exit(2)),Rr(n),process.exit(2));let a=await Tr({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Mr(a),null,2)+`
|
|
1755
|
-
`),process.exit(a.kind===`ok`?0:2)),Nr(n,a),process.exit(a.kind===`ok`?0:2)})}function Mr(e){return e.kind===`ok`?{matched:!0,source:`ai`,diagnosis:e.diagnosis}:e.kind===`unavailable`?{matched:!1,aiUnavailable:!0,reason:e.reason}:{matched:!1,aiError:!0,error:e.message}}function Nr(e,t){t.kind===`ok`?Lr(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${Br(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${zr(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${Br(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function Pr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Fr()}function Fr(){return new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n)),process.stdin.on(`error`,t)})}function Ir(){let e=process.cwd();return{cwd:e,hasFile:t=>
|
|
1755
|
+
`),process.exit(a.kind===`ok`?0:2)),Nr(n,a),process.exit(a.kind===`ok`?0:2)})}function Mr(e){return e.kind===`ok`?{matched:!0,source:`ai`,diagnosis:e.diagnosis}:e.kind===`unavailable`?{matched:!1,aiUnavailable:!0,reason:e.reason}:{matched:!1,aiError:!0,error:e.message}}function Nr(e,t){t.kind===`ok`?Lr(e,t.diagnosis,-1,!0):t.kind===`unavailable`?(process.stdout.write(`\n Explaining: ${Br(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${zr(t.suggestion,` `)}\n\n`)):(process.stdout.write(`\n Explaining: ${Br(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`))}async function Pr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Fr()}function Fr(){return new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n)),process.stdin.on(`error`,t)})}function Ir(){let e=process.cwd();return{cwd:e,hasFile:t=>j(z(e,t))}}function Lr(e,t,n,r=!1){let i=Br(e.trim(),200),a=r?`AI-generated — verify before applying`:Vr(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${zr(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${zr(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${zr(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${zr(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
1756
1756
|
`)}function Rr(e){let t=Br(e.trim(),200);process.stdout.write(`\n Explaining: ${t}\n\n`),process.stdout.write(` No known-issue matched. Things you can try:
|
|
1757
1757
|
|
|
1758
1758
|
1. Check the framework docs for the error keywords:
|
|
@@ -1767,8 +1767,8 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1767
1767
|
|
|
1768
1768
|
`)}function zr(e,t){return e.split(`
|
|
1769
1769
|
`).map(e=>`${t}${e}`).join(`
|
|
1770
|
-
`)}function Br(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Vr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Hr(e){let t=e.command(`mcp`).description(`Model Context Protocol commands (start | init)`);t.command(`start`,{isDefault:!0}).description(`Run the built application as an MCP server over stdio`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`--node-arg <arg...>`,`Extra arguments to pass to node`).action(Ur),t.command(`init`).description(`Generate .mcp.json for Claude Code / Cursor / Zed`).option(`-n, --name <name>`,`Server name (defaults to package.json name)`).option(`-o, --out <file>`,`Output file`,`.mcp.json`).option(`-f, --force`,`Overwrite an existing entry without prompting`).option(`--global`,`Write to ~/.mcp.json instead of the project root`).action(Wr)}function Ur(e){let t=
|
|
1771
|
-
`,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${r}" to ${i}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function Gr(e){let t=
|
|
1770
|
+
`)}function Br(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Vr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Hr(e){let t=e.command(`mcp`).description(`Model Context Protocol commands (start | init)`);t.command(`start`,{isDefault:!0}).description(`Run the built application as an MCP server over stdio`).option(`-e, --entry <file>`,`Entry file`,`dist/index.js`).option(`--node-arg <arg...>`,`Extra arguments to pass to node`).action(Ur),t.command(`init`).description(`Generate .mcp.json for Claude Code / Cursor / Zed`).option(`-n, --name <name>`,`Server name (defaults to package.json name)`).option(`-o, --out <file>`,`Output file`,`.mcp.json`).option(`-f, --force`,`Overwrite an existing entry without prompting`).option(`--global`,`Write to ~/.mcp.json instead of the project root`).action(Wr)}function Ur(e){let t=z(e.entry);j(t)||(process.stderr.write(`Error: entry file not found: ${t}\n\nBuild the app first with \`kick build\`, or pass a custom entry:\n kick mcp -e dist/server.js\n`),process.exit(1));let n=[...e.nodeArg??[],t],r=Be(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});r.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),r.on(`exit`,(e,t)=>{t?process.kill(process.pid,t):process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Wr(e){let t=process.cwd(),n=Gr(t)??Le(t),r=e.name??n,i=e.global?z(process.env.HOME??`.`,`.mcp.json`):z(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(j(i))try{let e=M(i,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(o={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${i} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}o.mcpServers[r]&&!e.force&&(process.stderr.write(`Error: an entry for "${r}" already exists in ${i}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),o.mcpServers[r]=a,P(i,JSON.stringify(o,null,2)+`
|
|
1771
|
+
`,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${r}" to ${i}\n\n To activate it:\n 1. Build your app: kick build\n 2. Restart your MCP client (Claude Code, Cursor, Zed)\n 3. The server should appear in the client's tool picker\n\n`)}function Gr(e){let t=z(e,`package.json`);if(!j(t))return null;try{let e=M(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Kr(e){e.command(`tinker`).description(`Interactive REPL with DI container and services loaded`).option(`-e, --entry <file>`,`Entry file to load`,`src/index.ts`).action(async e=>{let t=process.cwd(),n=z(t,e.entry);j(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Jr(t,`tsx`);r||(console.error(`\n Error: tsx not found. Install it: ${w(t)} add -D tsx\n`),process.exit(1));let i=qr(n,e.entry),a=L(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=ze(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function qr(e,t){return`
|
|
1772
1772
|
import 'reflect-metadata'
|
|
1773
1773
|
|
|
1774
1774
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -1793,7 +1793,7 @@ try {
|
|
|
1793
1793
|
|
|
1794
1794
|
// Load entry to trigger decorator registration
|
|
1795
1795
|
try {
|
|
1796
|
-
await import('${
|
|
1796
|
+
await import('${V(e).href}')
|
|
1797
1797
|
} catch (err) {
|
|
1798
1798
|
console.warn(' Warning: ' + err.message)
|
|
1799
1799
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -1822,39 +1822,39 @@ server.on('exit', () => {
|
|
|
1822
1822
|
console.log('\\n Goodbye!\\n')
|
|
1823
1823
|
process.exit(0)
|
|
1824
1824
|
})
|
|
1825
|
-
`}function Jr(e,t){for(let n of Zn(e)){let e=
|
|
1825
|
+
`}function Jr(e,t){for(let n of Zn(e)){let e=L(n,t);if(j(e))return e}return null}function Yr(e,t){let n=RegExp(`^\\s*${K(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
|
|
1826
1826
|
`;)s++;else{for(s+=2;s+1<a.length&&(a[s]!==`*`||a[s+1]!==`/`);)s++;s+=2}continue}let t=a[s]??``;if(t===`'`||t===`"`||t==="`"){let e=t;for(s++;s<a.length&&a[s]!==e;)a[s]===`\\`&&s++,s++}else if(t===`(`)o++;else if(t===`)`&&(o--,o===0))break;s++}if(o!==0)break;let c=a.slice(t,s);if(n.test(c)){let t=e;for(;t>0&&(a[t-1]===` `||a[t-1]===` `||a[t-1]===`
|
|
1827
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function Xr(e,t){let n=Ut(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Yr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${
|
|
1827
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function Xr(e,t){let n=Ut(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Yr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${K(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function Zr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize===!0,a=W(t),o=U(t),s=i?G(a):a;s!==a&&!await S(L(n,s))&&await S(L(n,a))&&(s=a);let c=L(n,s);if(!await S(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await D({message:E.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
1828
1828
|
Cancelled.
|
|
1829
|
-
`);return}await Ge(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=
|
|
1829
|
+
`);return}await Ge(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=L(n,`index.ts`);if(await S(l)){let e=await H(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${K(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${K(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Xr(e,o),e=e.replace(/\n{3,}/g,`
|
|
1830
1830
|
|
|
1831
|
-
`),e!==t&&(await
|
|
1831
|
+
`),e!==t&&(await C(l,e),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Qr(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--pluralize`,`The module folder is pluralized (users/ for user)`).option(`--no-pluralize`,`The module folder is the name as typed (the default)`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=await h(process.cwd()),r=_(n),i=t.modulesDir??r.dir??`src/modules`,a=l(t.pluralize,r);for(let n of e)await Zr({name:n,modulesDir:z(i),force:t.force,pluralize:a})})}function $r(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;if(e===`kickjs-schema`||e===`schema`)return`kickjs-schema`;console.warn(` kick typegen: unknown --schema-validator '${e}' (supported: 'zod', 'kickjs-schema', 'false'). Falling back to project config.`)}}function ei(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function ti(e){e.command(`typegen`).description(`Generate type-safe DI registry and module types into .kickjs/types/`).option(`-w, --watch`,`Watch source files and regenerate on change`).option(`-s, --src <dir>`,`Source directory to scan`,`src`).option(`-o, --out <dir>`,`Output directory`,`.kickjs/types`).option(`--silent`,`Suppress output`).option(`--allow-duplicates`,`Auto-namespace duplicate class names instead of failing (use with caution)`).option(`--schema-validator <name>`,`Schema validator for body/query/params typing (currently 'zod' or 'false')`).option(`--env-file <path>`,`Path to env schema file for KickEnv typing (default 'src/env.ts'; pass 'false' to disable)`).option(`--check`,`CI gate: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=k(process.cwd()),n=await h(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-CvlUt9NG.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Ro),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(`
|
|
1832
1832
|
Registered typegen plugins:
|
|
1833
1833
|
`);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(`
|
|
1834
1834
|
Disable one in kick.config.ts:
|
|
1835
1835
|
`),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
|
|
1836
|
-
`);return}let r=$r(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=ei(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await we(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await Ee(a);let r=await Kn({cwd:t,config:n??null,silent:e.silent,check:e.check});if(e.check&&r.some(e=>e.status===`written`)&&process.exit(1),!e.check){let i=
|
|
1836
|
+
`);return}let r=$r(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=ei(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await we(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await Ee(a);let r=await Kn({cwd:t,config:n??null,silent:e.silent,check:e.check});if(e.check&&r.some(e=>e.status===`written`)&&process.exit(1),!e.check){let i=z(t,e.out??n?.typegen?.outDir??`.kickjs/types`);await ye(i,r,e.silent??!1)}}}catch(e){e instanceof Te?console.error(`
|
|
1837
1837
|
`+e.message+`
|
|
1838
1838
|
`):e instanceof An?console.error(`
|
|
1839
1839
|
`+e.message+`
|
|
1840
1840
|
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const ni=/* @__PURE__ */ new Set([`Service`,`Injectable`,`Component`,`Repository`]);function ri(e,t){return typeof t==`number`?e.slice(0,t).split(`
|
|
1841
|
-
`).length:1}function ii(e){let t=le(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(ue(e)&&e.type===`MemberExpression`&&
|
|
1841
|
+
`).length:1}function ii(e){let t=le(e);if(t===`singleton`||t===`transient`||t===`request`)return t;if(ue(e)&&e.type===`MemberExpression`&&A(e.object)===`Scope`){let t=A(e.property);if(t===`SINGLETON`)return`singleton`;if(t===`TRANSIENT`)return`transient`;if(t===`REQUEST`)return`request`}return`unknown`}function ai(e){let t=A(e);if(t)return{key:`id:${t}`,label:t};let n=le(e);return n===null?null:{key:`lit:${n}`,label:`'${n}'`}}function oi(e,t){let n=(e.body?.body??[]).find(e=>e.type===`MethodDefinition`&&e.kind===`constructor`)?.value?.params??[],r=[];for(let e of n){let n=e.type===`TSParameterProperty`?e.parameter:e,i=Oe(e).map(de).find(e=>e?.name===`Inject`),a=null;if(i)a=ai(i.call.arguments?.[0]);else{let e=n?.typeAnnotation?.typeAnnotation??null;e?.type===`TSTypeReference`&&(a=ai(e.typeName))}a&&r.push({...a,line:ri(t,e.start)})}return r}function si(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=[],i=(e,n)=>{t.has(e)||t.set(e,/* @__PURE__ */ new Set),t.get(e).add(n)},a=(e,t)=>{e&&(n.has(e)||n.set(e,/* @__PURE__ */ new Set),n.get(e).add(t))};for(let{path:t,source:n}of e){let e;try{let r=Ye(t,n);if(r.errors.length>0)continue;e=r.program}catch{continue}for(let n of e.body??[]){let e=(n.type===`ExportNamedDeclaration`||n.type===`ExportDefaultDeclaration`)&&ue(n.declaration)?n.declaration:n;if(e.type===`ClassDeclaration`&&a(A(e.id),t),e.type===`VariableDeclaration`)for(let n of e.declarations??[])a(A(n.id),t)}ke(e,e=>{if(e.type===`ClassDeclaration`){let a=A(e.id);if(!a)return;for(let o of Oe(e)){let s=de(o);if(s){if(s.name===`Controller`){i(`id:${a}`,`singleton`),r.push({name:a,kind:`controller`,file:t,params:oi(e,n)});return}if(ni.has(s.name)){let o=pe(Ae(s.call),`scope`),c=o?ii(o):`singleton`;i(`id:${a}`,c),r.push({name:a,kind:`other`,file:t,params:oi(e,n)});return}}}return}if(e.type!==`CallExpression`)return;let a=e.callee;if(!ue(a)||a.type!==`MemberExpression`)return;let o=A(a.property);if(o!==`register`&&o!==`registerFactory`)return;let s=e.arguments??[];if(s.length<2)return;let c=ai(s[0]);c&&i(c.key,s.length>=3?ii(s[2]):`singleton`)})}let o=e=>(n.get(e)?.size??0)<=1,s=(e,n)=>{let r=t.get(e);return r?.size===1&&r.has(n)},c=[];for(let e of r)if(o(e.name)&&s(`id:${e.name}`,`singleton`))for(let t of e.params){if(t.key.startsWith(`id:`)&&!o(t.label)||!s(t.key,`request`))continue;let n=e.kind===`controller`?`@Controller() is always SINGLETON, so inject ${t.label} with @Autowired() instead of the constructor.`:`Give ${e.name} TRANSIENT or REQUEST scope, or inject ${t.label} with @Autowired() instead of the constructor.`;c.push({file:e.file,line:t.line,parent:e.name,dependency:t.label,message:`${e.name} (SINGLETON) injects REQUEST-scoped ${t.label} through its constructor — the first request that resolves it answers 500. ${n}`})}return c}function ci(e){let t=[];if(!j(e))return t;let n=N(e,{withFileTypes:!0});for(let r of n){let n=L(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...ci(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function li(e){try{return M(e,`utf-8`)}catch{return``}}const ui=/* @__PURE__ */ new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function di(e,t){let n=li(L(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(ui.has(t.toLowerCase())||t.length<32)return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value or too short (< 32 chars) — change it`}}}for(let e of t)for(let t of[/JWT_SECRET['"]?\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i,/secret\s*[:=]\s*['"]?(secret|changeme|password|test|default)['"]?/i])if(t.test(e))return{severity:`CRITICAL`,message:`JWT_SECRET appears to be a default value in source code — use an environment variable`};return null}function fi(e){for(let t of e)if(/cors\s*\(/.test(t)&&/origin\s*:\s*['"]\*['"]/.test(t))return{severity:`CRITICAL`,message:`CORS origin is '*' — restrict to your domains`};return null}function pi(e){for(let t of e)if(/rateLimit/i.test(t)||/@RateLimit/i.test(t))return null;return{severity:`WARNING`,message:`No rate limiting detected — add rateLimit() middleware or @RateLimit decorator`}}function mi(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function hi(e){let t=!1,n=!1;for(let r of e)/tokenStore/i.test(r)&&(t=!0),/MemoryTokenStore/i.test(r)&&(n=!0);return n?{severity:`WARNING`,message:`MemoryTokenStore detected — use a persistent store (Redis, DB) for production deployments`}:t?null:{severity:`WARNING`,message:`No token revocation store detected — consider adding one for auth token management`}}function gi(e){for(let t of e)if(/helmet\s*\(/.test(t))return/security\s*\.\s*helmet\s*.*false/.test(t)?{severity:`WARNING`,message:`Helmet security headers are disabled — enable them for production`}:{severity:`INFO`,message:`Helmet security headers active`};return{severity:`WARNING`,message:`Helmet not detected — add helmet() middleware for security headers`}}function _i(e){for(let t of e)if(/AuthAdapter/i.test(t))return{severity:`INFO`,message:`AuthAdapter configured`};return{severity:`INFO`,message:`No AuthAdapter detected — add one if your app requires authentication`}}function vi(e){let t=ci(L(e,`src`)).map(e=>li(e)),n=[],r=di(e,t);r&&n.push(r);let i=fi(t);i&&n.push(i);let a=pi(t);a&&n.push(a);let o=mi();o&&n.push(o);let s=hi(t);return s&&n.push(s),n.push(gi(t)),n.push(_i(t)),n}function yi(e){let t=si(ci(L(e,`src`)).filter(e=>!/\.(test|spec)\.tsx?$/.test(e)).map(t=>({path:R(e,t).split(`\\`).join(`/`),source:li(t)})));return t.length===0?[{severity:`INFO`,message:`No REQUEST-scoped dependency injected into a singleton`}]:t.map(e=>({severity:`CRITICAL`,message:`${e.file}:${e.line} ${e.message}`}))}function bi(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).option(`--di`,`Find REQUEST-scoped dependencies injected into singletons`).action(e=>{if(!e.deploy&&!e.di){console.log(`
|
|
1842
1842
|
Usage: kick check [--deploy] [--di]
|
|
1843
1843
|
|
|
1844
1844
|
Available checks:
|
|
1845
1845
|
--deploy Audit for production readiness (security, config, best practices)
|
|
1846
1846
|
--di Find REQUEST-scoped dependencies injected into singleton constructors
|
|
1847
|
-
`);return}let t=process.cwd();re(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=ie();n.start(`Scanning project...`);let r=[...e.deploy?vi(t):[],...e.di?yi(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)
|
|
1848
|
-
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Ai(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 ji(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: ${
|
|
1847
|
+
`);return}let t=process.cwd();re(e.deploy?`KickJS Deploy Check`:`KickJS DI Check`);let n=ie();n.start(`Scanning project...`);let r=[...e.deploy?vi(t):[],...e.di?yi(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)T.message(`${se(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?E.red(`${a} critical`):`${a} critical`,o>0?E.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(O(E.red(`${l} — fix critical issues before deploying`)),process.exit(1)):O(E.green(`${l} — looking good!`))})}function xi(e){try{return JSON.parse(M(e,`utf-8`))}catch{return null}}function Si(e){try{return M(e,`utf-8`)}catch{return null}}function Ci(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function wi(e){let t=L(e,`tsconfig.json`);if(j(t))return Ti(t,/* @__PURE__ */ new Set)}function Ti(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Si(e);if(n===null)return null;let r=Ci(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=Ei(I(e),n);if(!r)continue;let i=Ti(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function Ei(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return Di(z(e,t));let n=e;for(;;){let e=Di(L(n,`node_modules`,t));if(e)return e;let r=I(n);if(r===n)break;n=r}return null}function Di(e){if(j(e)){try{if(Ie(e).isDirectory()){let t=L(e,`tsconfig.json`);return j(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return j(t)?t:null}function Oi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ki(){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.
|
|
1848
|
+
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Ai(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 ji(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: ${w(e.cwd)} add express`}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const Mi={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function Ni(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=Mi[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: ${w(e.cwd)} add ${n.join(` `)}`}:e.runtime===`h3`&&Pi(e.cwd,t.h3)===1?{name:r,status:`fail`,message:`h3 v1`,fix:`This version of @forinda/kickjs runs on h3 v2 only. Upgrade: ${w(e.cwd)} add h3@^2 — no code change for apps that only use KickJS APIs.`}:{name:r,status:`pass`}}function Pi(e,t){let n=t;for(let t=z(e);;t=I(t)){try{n=JSON.parse(M(L(t,`node_modules`,`h3`,`package.json`),`utf8`)).version;break}catch{}if(I(t)===t)break}let r=/(\d+)/.exec(n)?.[1];return r===void 0?void 0:Number(r)}function Fi(e){if(!e.pkg||!Li(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or ${w(e.cwd)} add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const Ii=2e3;function Li(e){let t=L(e,`src`);if(!j(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<Ii;){let e=r.pop(),t;try{t=N(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=Ii)break;let t=L(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(Si(t)??``)))return!0}}return!1}function Ri(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: ${w(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 zi(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 Bi(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>L(e.cwd,t)).filter(e=>j(e)).filter(e=>/\bloadEnv\s*\(/.test(Si(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>L(e.cwd,t)).find(e=>j(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=Si(n)??``,i=I(n),a=[];for(let e of t){let t=R(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+)?['"]${Oi(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=>R(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 \`${R(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 ${R(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 Vi(e,t=Hi){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=N(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=L(e,o.name);if(o.isDirectory())i.push(a);else try{let e=Ie(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const Hi=2e3;function Ui(e){let t=L(e.cwd,`.kickjs`,`types`);if(!j(t))return null;let n=Vi(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 Wi=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],Gi=[`.env.test`,`.env.test.local`],Ki=[`.env`,`.env.local`];function qi(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 Ji(e){if(!Wi.some(t=>j(L(e.cwd,t))))return null;let t=Ki.filter(t=>j(L(e.cwd,t)));if(t.length===0)return null;let n=Gi.filter(t=>j(L(e.cwd,t)));if(n.length>0){let t=qi(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
|
|
1849
1849
|
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
|
|
1850
1850
|
development env — including DATABASE_URL and any third-party credentials.
|
|
1851
1851
|
|
|
1852
1852
|
Create .env.test (cp .env.test.example .env.test, if the project has one)
|
|
1853
1853
|
holding the whole environment the suite should run against
|
|
1854
1854
|
(a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
|
|
1855
|
-
and supply env from the test runner.`}}const Yi=[()=>ki(),Ai,ji,Ni,Fi,Ri,zi,Bi,Ji,Ui];async function Xi(e,t={}){let n={cwd:e,pkg:xi(
|
|
1856
|
-
`).map(e=>` ${
|
|
1857
|
-
`)}function ea(e){return e?.doctor?.checks??[]}function ta(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),n=ea(await
|
|
1855
|
+
and supply env from the test runner.`}}const Yi=[()=>ki(),Ai,ji,Ni,Fi,Ri,zi,Bi,Ji,Ui];async function Xi(e,t={}){let n={cwd:e,pkg:xi(L(e,`package.json`)),tsconfig:wi(e),runtime:t.runtime??`express`},r=[...Yi,...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 Zi(e){switch(e){case`pass`:return E.green(`✔`);case`warn`:return E.yellow(`⚠`);case`fail`:return E.red(`✖`)}}function Qi(e){let t=Zi(e.status),n=e.message?` ${E.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function $i(e){return e.split(`
|
|
1856
|
+
`).map(e=>` ${E.dim(`→`)} ${e}`).join(`
|
|
1857
|
+
`)}function ea(e){return e?.doctor?.checks??[]}function ta(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),n=ea(await h(e)),r=await t(e);re(`KickJS Doctor`);let i=await Xi(e,{extraChecks:n,runtime:r});for(let e of i)T.message(Qi(e)),e.fix&&e.status!==`pass`&&T.message($i(e.fix));let a=i.filter(e=>e.status===`pass`).length,o=i.filter(e=>e.status===`warn`).length,s=i.filter(e=>e.status===`fail`).length,c=[E.green(`${a} passed`),o>0?E.yellow(`${o} warning${o===1?``:`s`}`):`${o} warnings`,s>0?E.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(O(`${c} — fix the errors above before running the app`),process.exit(1)):O(o>0?`${c} — review the warnings`:E.green(`${c} — your environment looks good`))})}const na=Symbol.for(`kickjs.handler.entryCapture`),ra=Symbol.for(`kickjs.config.describe`);function ia(e){return Array.isArray(e)?e.join(`,`):typeof e==`object`&&e||typeof e==`string`&&/[\r\n]/.test(e)?JSON.stringify(e):String(e)}function aa(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?``:ia(n.default)}`)}return t}function oa(e){let t=[`# Generated by \`kick env example\` from the env schema and the declared settings
|
|
1858
1858
|
# sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
|
|
1859
1859
|
#
|
|
1860
1860
|
# Uncommented variables are required. Commented ones are optional; the value shown
|
|
@@ -1862,16 +1862,16 @@ and supply env from the test runner.`}}const Yi=[()=>ki(),Ai,ji,Ni,Fi,Ri,zi,Bi,J
|
|
|
1862
1862
|
`));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...aa(n.vars)].join(`
|
|
1863
1863
|
`));return`${t.join(`
|
|
1864
1864
|
|
|
1865
|
-
`)}\n`}async function sa(e,t){let n=
|
|
1865
|
+
`)}\n`}async function sa(e,t){let n=z(e,t);if(!j(n))throw Error(`${t} not found`);let r=z(e,`vite.config.ts`);if(!j(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(z(e,`package.json`)),{createServer:o}=await import(V(a.resolve(`vite`)).href),s=globalThis,c;s[na]=e=>{c??=e},s[ra]=!0,s[Jn]=`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[na],delete s[ra],delete s[Jn],await l.close()}if(!c)throw Error(`${t} finished loading without calling bootstrap()`);return c.describeConfig()}function ca(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=z(t,e.out),r;try{r=oa(await sa(t,e.entry))}catch(e){console.error(`\n kick env example: ${e.message}\n`),process.exit(1)}e.check?((j(n)?M(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.`)):(P(n,r),console.log(` Wrote ${e.out}`))})}function la(e){return e.optsWithGlobals().dryRun??!1}function ua(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.
|
|
1866
1866
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
1867
1867
|
--target define|class Override the migration direction.
|
|
1868
1868
|
--apply Apply the changes (default: dry-run preview).
|
|
1869
|
-
--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=la(t)||!e.apply;
|
|
1870
|
-
`+
|
|
1869
|
+
--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=la(t)||!e.apply;x(n),e.experimental||(console.error(`
|
|
1870
|
+
`+E.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
1871
1871
|
The regex-based rewrite handles the shapes our templates produce.
|
|
1872
1872
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
1873
1873
|
Always commit before running with --apply.
|
|
1874
|
-
`),process.exit(1));let r=await
|
|
1874
|
+
`),process.exit(1));let r=await h(process.cwd()),i=_(r),a=z(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 ${E.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=E.dim(`→ ${o}`),c=n?E.dim(`(dry-run)`):E.bold(`(applying)`);console.log(`\n ${E.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${E.dim(a)}\n`);let l=e.backup!==!1&&!n,u=await bn(a,{dryRun:n,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${E.green(`✓`)} backup: ${E.dim(e)}\n ${E.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${E.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${E.green(`✓`)} ${e.path}`);else{f++;let t=E.dim(`(${e.reason??`skipped`})`);console.log(` ${E.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${E.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=E.dim(`(${u.indexReason??`skipped`})`);console.log(` ${E.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${E.dim(`-`)} ${u.indexPath} ${E.dim(`(not found)`)}`);let p=n?E.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${E.bold(String(d))} migrated, ${E.bold(String(f))} skipped${p}\n`)})}function da(e){try{let t=JSON.parse(M(z(e,`package.json`),`utf-8`));return{...t.dependencies,...t.devDependencies}}catch{return{}}}function fa(e,t=j,n=da(e)){if(n[`@forinda/kickjs-inertia`])return{staticDir:`dist/client`,siteRoot:`.`,apiPath:``,include:[`dist/client/.vite/manifest.json`,`dist/ssr`]};let r=I(e);return(t(z(r,`pnpm-workspace.yaml`))||t(z(r,`package.json`)))&&t(z(r,`web`,`package.json`))?{staticDir:`../web/dist`,siteRoot:`..`,apiPath:`/api`}:{siteRoot:`.`,apiPath:``}}function pa(e,t,n,r){let i=fa(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 ma(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'
|
|
1875
1875
|
import { handler } from '${e}'
|
|
1876
1876
|
|
|
1877
1877
|
// Where the app's build files were packaged; the platform starts this
|
|
@@ -1896,10 +1896,10 @@ const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.
|
|
|
1896
1896
|
|
|
1897
1897
|
export default (req, res) => handler.node(req, res, requestContext())
|
|
1898
1898
|
`}function ga(e){return/^\s*publish\s*=\s*["']([^"']+)["']/m.exec(e)?.[1]?.replace(/^\.\//,``).replace(/\/+$/,``)}function _a(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 va(e,t){let n;try{n=Ye(t,e).program}catch{return[]}let r=[],i=t=>e.slice(0,t).split(`
|
|
1899
|
-
`).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 ya(e){let t=
|
|
1899
|
+
`).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 ya(e){let t=z(e,`src`);return j(t)?N(t,{recursive:!0,encoding:`utf-8`}).filter(e=>/\.m?ts$/.test(e)&&!/\.(test|spec|d)\.m?ts$/.test(e)).flatMap(e=>{let n=M(z(t,e),`utf-8`);return n.includes(`@Cron`)?va(n,`src/${e}`):[]}):[]}function ba(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 xa(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(ba(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 Sa(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 Ca(e,t){let{createRequire:n}=await import(`node:module`),r=n(z(e,`package.json`)),i;try{i=r.resolve(`${t}/package.json`)}catch{i=z(e,`node_modules`,t,`package.json`)}if(!j(i))throw Error(`${t} is not installed in this project. Run: ${w(e)} add -D vite unplugin-swc @forinda/kickjs-vite`);let a=Sa(JSON.parse(M(i,`utf-8`)));if(!a)throw Error(`${t} has no importable entry point`);return import(V(z(I(i),a)).href)}async function wa(e,t,n){let r=z(e,t.entry);if(!j(r))throw Error(`${t.entry} not found. The serverless entry exports \`handler = createHandler({ modules })\` — see the Serverless guide.`);let{build:i}=await Ca(e,`vite`),{default:a}=await Ca(e,`unplugin-swc`),{devtoolsFlagPlugin:o,devtoolsStripPlugin:s}=await Ca(e,`@forinda/kickjs-vite`);await i({configFile:!1,root:e,logLevel:`warn`,oxc:!1,plugins:[a.vite(),o(),s()],resolve:{alias:{"@":z(e,`src`)}},ssr:{noExternal:!0,target:`node`},build:{ssr:!0,target:`node20`,outDir:z(e,t.outDir),emptyOutDir:!0,minify:!1,rollupOptions:{input:r,external:(n,r)=>Ea(n,r?I(r):e)||t.external.includes(n)&&Ea(n,e),output:{format:`esm`,entryFileNames:`server.mjs`,codeSplitting:!1}}}});let c=z(e,t.outDir,`server.mjs`);return n(`bundled ${R(process.cwd(),c)}`),c}function Ta(e){return/^((?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*)(?:\/|$)/i.exec(e)?.[1]}function Ea(e,t,n=j){let r=Ta(e);if(!r)return!1;for(let e=t;;e=I(e)){if(n(z(e,`node_modules`,r,`package.json`)))return!1;if(I(e)===e)return!0}}function Da(e,t){let n=R(e,t).split(B)[0];return n!==void 0&&n.startsWith(`.`)}function Oa(e){return e.flatMap(e=>[`/${e} /404 404!`,`/${e}/* /404 404!`])}function ka(e){try{return Ie(e)}catch{return}}function Aa(e,t){let n=t.filter(t=>!j(z(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 (\`${d(w(e),`build`)}\`), or fix \`deploy.include\`.`)}function ja(e,t){let n=t.projectRoot,r=()=>pa(t.config?.deploy,n);e.command(`build:netlify`).description(`Bundle the serverless entry and write the Netlify function`).action(async()=>{let e=r();Aa(n,e.include);let i=await wa(n,e,t.log),a=z(n,e.siteRoot),o=ya(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=z(a,`.netlify/v1/functions`);Pe(s,{recursive:!0});let c=R(s,i).split(B).join(`/`),l=e=>e.split(B).join(`/`);P(z(s,`api.mjs`),ma(c,e.apiPath,{projectDir:l(R(s,n)),preferStatic:e.apiPath===``&&!!e.staticDir,includedFiles:e.include.flatMap(e=>{let t=l(R(s,z(n,e)));return ka(z(n,e))?.isDirectory()?[`${t}/**`]:[t]})})),t.log(`wrote ${R(process.cwd(),z(s,`api.mjs`))}`);let u=e.staticDir??e.publishDir;if(!e.staticDir)Pe(z(n,u),{recursive:!0}),t.log(`publish directory ready at ${R(process.cwd(),z(n,u))}`);else if(j(z(n,u))){let e=N(z(n,u)).filter(e=>e.startsWith(`.`));if(e.length>0){let t=z(n,u,`_redirects`),r=j(t)?M(t,`utf-8`):``,i=Oa(e).filter(e=>!r.includes(e));i.length>0&&P(t,`${r}${r&&!r.endsWith(`
|
|
1900
1900
|
`)?`
|
|
1901
1901
|
`:``}${i.join(`
|
|
1902
|
-
`)}\n`)}}let d=
|
|
1902
|
+
`)}\n`)}}let d=z(a,`netlify.toml`);if(j(d)){let e=ga(M(d,`utf-8`)),r=R(a,z(n,u)).split(B).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();Aa(n,e.include);let i=await wa(n,e,t.log),a=z(n,e.siteRoot),o=e.staticDir?z(n,e.staticDir):void 0,s=z(a,`.vercel/output`),c=z(s,`functions/api.func`);Fe(s,{recursive:!0,force:!0}),Pe(c,{recursive:!0}),Ne(i,z(c,`server.mjs`)),P(z(c,`index.mjs`),ha());for(let t of e.include)Ne(z(n,t),z(c,t),{recursive:!0});if(P(z(c,`.vc-config.json`),`${JSON.stringify({runtime:e.vercelRuntime,handler:`index.mjs`,launcherType:`Nodejs`,supportsResponseStreaming:!0},null,2)}\n`),o){if(!j(o))throw Error(`build:vercel: ${e.staticDir} does not exist — build the frontend first`);Ne(o,z(s,`static`),{recursive:!0,filter:e=>!Da(o,e)})}let{crons:l,warnings:u}=xa(ya(n));for(let e of u)t.log(`warning: ${e}`);let d={version:3,routes:_a(e.apiPath,!!o,l.length>0),...l.length>0?{crons:l}:{}};P(z(s,`config.json`),`${JSON.stringify(d,null,2)}\n`),t.log(`wrote ${R(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 Ma=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){let t=F.resolve(e.cwd,`kick.config.ts`);if(!j(t))return null;let n=await h(e.cwd);if(!n?.assetMap)return null;let r=fe(n.assetMap,e.cwd);return r.count===0?null:Se(r)}}),Na="/* 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 Pa(e,t,n,r={}){if(e.length===0)return`${Na}
|
|
1903
1903
|
// (no routes discovered yet — annotate a controller method with
|
|
1904
1904
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1905
1905
|
declare global {
|
|
@@ -1916,19 +1916,19 @@ declare global {
|
|
|
1916
1916
|
|
|
1917
1917
|
/** Empty until the first route exists — see kick typegen. */
|
|
1918
1918
|
export const kickRpc = {} as const
|
|
1919
|
-
`;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=Ra(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${
|
|
1919
|
+
`;let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=Ra(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`,n=`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path})`;r.onWarn?.(e.unexported?`${n}: ${o} schema '${e.identifier}' is declared in ${R(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??Ia(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=La(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${Fa(e)}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
1920
1920
|
`))}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(`
|
|
1921
1921
|
`);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(`
|
|
1922
1922
|
`));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=Va(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(`
|
|
1923
1923
|
`)}\n },`)}let _=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...h,`} as const`].join(`
|
|
1924
1924
|
`),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=Ba(``,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(`
|
|
1925
1925
|
`)+`
|
|
1926
|
-
`:``,x=za(a)+b,
|
|
1926
|
+
`:``,x=za(a)+b,S=l.join(`
|
|
1927
1927
|
`);return`${Na}${x}
|
|
1928
1928
|
declare global {
|
|
1929
1929
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1930
1930
|
namespace KickRoutes {
|
|
1931
|
-
${
|
|
1931
|
+
${S}
|
|
1932
1932
|
}
|
|
1933
1933
|
|
|
1934
1934
|
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
@@ -1938,16 +1938,16 @@ ${ee}
|
|
|
1938
1938
|
${_}
|
|
1939
1939
|
`}function Fa(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Ia(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 La(e){let t=[];return e.queryFilterable&&e.queryFilterable.length>0&&t.push(`Filterable: ${e.queryFilterable.join(`, `)}`),e.querySortable&&e.querySortable.length>0&&t.push(`Sortable: ${e.querySortable.join(`, `)}`),e.querySearchable&&e.querySearchable.length>0&&t.push(`Searchable: ${e.querySearchable.join(`, `)}`),t}function Ra(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Ba(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 za(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(`
|
|
1940
1940
|
`)+`
|
|
1941
|
-
`}function Ba(e,t,n){if(e===null)return`unknown`;let r=
|
|
1942
|
-
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 '${Ga}' resolved from this project.\n ${t}`)}async function Ja(e){let t=Me(
|
|
1941
|
+
`}function Ba(e,t,n){if(e===null)return`unknown`;let r=I(n);if(e===``){let e=R(r,t).split(B).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=I(t),a=z(i,e),o=R(r,a).split(B).join(`/`);return o=o.replace(/\.(ts|tsx|mts|cts)$/i,``),o.startsWith(`.`)||(o=`./`+o),o}function Va(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 Ha=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Ua(e),cwd:e.cwd,envFile:Wa(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=F.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Pa(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Ua(e){return F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Wa(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Ga=`@typescript/typescript6`;function Ka(e){return typeof e?.createProgram==`function`}function qa(e){if(Ka(e.typescript))return{api:e.typescript,source:`typescript`};if(Ka(e.ts6))return{api:e.ts6,source:Ga};let t=`Install it in the project:\n ${w()} add -D ${Ga}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
|
|
1942
|
+
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 '${Ga}' resolved from this project.\n ${t}`)}async function Ja(e){let t=Me(L(e,`package.json`)),n=async e=>{try{return await import(V(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Ga)]);return qa({typescript:Ya(r),ts6:Ya(i)}).api}function Ya(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Xa=Symbol(`kick/client: expansion budget exhausted`);var Za=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!==Xa)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 Xa;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=`
|
|
1943
1943
|
`){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===`
|
|
1944
1944
|
`?`
|
|
1945
1945
|
`: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 Qa=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],$a=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function eo(e){return Je(`sha1`).update(e).digest(`hex`)}function to(e){let t=Je(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
|
|
1946
|
-
`));for(let n of Qa){let r=
|
|
1946
|
+
`));for(let n of Qa){let r=L(e.projectDir,n);if(j(r))try{t.update(M(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!$a.test(n)){t.update(n);try{t.update(M(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function no(e){try{let t=await Ja(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(L(e.projectDir,`tsconfig.json`),{},n);return r?to({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 Ja(e.compilerFrom??e.projectDir),n=L(I(e.routesFile),`__kick_client_probe__.ts`),r=oo(e.routesFile,e.keys),i=lo(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.`);io(t,i,e.routesFile);let s=so(t,i,o,e.keys),c=null,l=new Za(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===ao(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 io(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(`
|
|
1947
1947
|
`);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 ao(e){return`_K${e}`}function oo(e,t){let n=`./`+Le(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${ao(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
|
|
1948
1948
|
`)+`
|
|
1949
|
-
`}function so(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(ao(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function co(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=
|
|
1950
|
-
`))}},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:[...co(o.fileNames,
|
|
1949
|
+
`}function so(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(ao(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function co(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=N(t).filter(e=>e.endsWith(`.ts`)).map(e=>L(t,e))}catch{}return[.../* @__PURE__ */ new Set([...n,...r])]}function lo(e,t,n,r){let i=L(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
|
|
1950
|
+
`))}},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:[...co(o.fileNames,I(n)),n],options:o.options,host:s})}const uo=`/* eslint-disable */
|
|
1951
1951
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1952
1952
|
//
|
|
1953
1953
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
@@ -1992,7 +1992,7 @@ declare global {
|
|
|
1992
1992
|
}
|
|
1993
1993
|
|
|
1994
1994
|
export type { Api }
|
|
1995
|
-
`}const po=`kick/client
|
|
1995
|
+
`}const po=`kick/client`,$=`.kickjs/types/kick__client.d.ts`,mo=`.kickjs/cache/client-map.sha1`,ho=(()=>{try{return Me(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function go(e){try{if(!j(e))return null;let[t,n]=M(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function _o(e){return`${Vn}${po} */\n\n${e}\n`}function vo(e){try{return j(e)?M(e,`utf-8`):null}catch{return null}}async function yo(e){let t=F.resolve(e.cwd,$);if(!j(t))return!1;try{await Ge(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 bo(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function xo(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(j(F.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 So=()=>({id:po,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!xo(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:F.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=bo(e.config),a=await no({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:ho}),o=go(F.resolve(e.cwd,mo)),s=vo(F.resolve(e.cwd,$));if(a&&o&&s!==null&&o.inputs===a&&o.output===eo(s))return kn()&&e.log.info?.(` kick/client: unchanged, keeping ${$}`),null;try{let t=fo(await ro({projectDir:e.cwd,routesFile:F.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(mo,`${a} ${eo(_o(t))}`),t}catch(t){let n=j(F.resolve(e.cwd,$)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):kn()&&e.log.info?.(r),n&&await yo(e),null}}});function Co(e,t,n=`zod`){if(!e)return null;let r=I(t),i=R(r,e.filePath).split(B).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),`/* eslint-disable */
|
|
1996
1996
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1997
1997
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1998
1998
|
|
|
@@ -2030,5 +2030,5 @@ declare global {
|
|
|
2030
2030
|
}
|
|
2031
2031
|
|
|
2032
2032
|
export {}
|
|
2033
|
-
`}const wo=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Eo(e);if(t===!1)return null;let n=await e.getScanResult({root:To(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=
|
|
2034
|
-
`)}});var
|
|
2033
|
+
`}const wo=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Eo(e);if(t===!1)return null;let n=await e.getScanResult({root:To(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=F.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Co(n.env,i,r)}});function To(e){return F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Eo(e){return e.config?.typegen?.envFile}function Do(e){return F.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Oo(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function ko(e){return{root:Do(e),cwd:e.cwd,envFile:Oo(e)}}const Ao=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ko(e)),n=F.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return ge(t.classes,n,r)}}),jo=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ko(e)),n=new Set(t.collisions.map(e=>e.className)),r=be(t.classes,t.tokens,t.injects,n);return xe(`ServiceToken`,r,"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Mo=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ko(e));return xe(`ModuleToken`,me(t.classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),No=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ko(e));return he(t.pluginsAndAdapters)}}),Po=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ko(e));return t.contextKeys.length===0?null:De(t.contextKeys)}}),Fo=()=>({id:`kick/route-flags`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(ko(e));return Ce(t.routeFlags)}}),Io={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Lo=()=>({id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=Io[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(`
|
|
2034
|
+
`)}});var Ro=/* @__PURE__ */ e({builtinCliPlugins:()=>zo});const zo=[b({name:`kick/init`,register:tt}),b({name:`kick/generate`,register:zn}),b({name:`kick/run`,register:sr}),b({name:`kick/info`,register:fr}),b({name:`kick/inspect`,register:Sr}),b({name:`kick/add`,register:i}),b({name:`kick/list`,register:o}),b({name:`kick/explain`,register:jr}),b({name:`kick/mcp`,register:Hr}),b({name:`kick/tinker`,register:Kr}),b({name:`kick/remove`,register:Qr}),b({name:`kick/typegen`,register:ti}),b({name:`kick/check`,register:bi}),b({name:`kick/doctor`,register:ta}),b({name:`kick/env-command`,register:ca}),b({name:`kick/codemod`,register:ua}),b({name:`kick/deploy`,register:ja}),b({name:`kick/registry`,typegens:[Ao()]}),b({name:`kick/services`,typegens:[jo()]}),b({name:`kick/modules`,typegens:[Mo()]}),b({name:`kick/plugins`,typegens:[No()]}),b({name:`kick/context`,typegens:[Po()]}),b({name:`kick/route-flags`,typegens:[Fo()]}),b({name:`kick/assets`,typegens:[Ma()]}),b({name:`kick/routes`,typegens:[Ha()]}),b({name:`kick/client`,typegens:[So()]}),b({name:`kick/env`,typegens:[wo()]}),b({name:`kick/runtime`,typegens:[Lo()]})];export{Gn as n,zo as t};
|