@forinda/kickjs-cli 8.10.2 → 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-As_KjQBC.mjs → agent-docs-CuD2-X3w.mjs} +30 -26
- package/dist/{agent-docs-ZgfnGL-j.mjs → agent-docs-ykxoPqXX.mjs} +23 -19
- package/dist/agent-docs-ykxoPqXX.mjs.map +1 -0
- package/dist/{build-BfC9Kkt-.mjs → build-C-AsmCh1.mjs} +2 -2
- package/dist/{build-BuBCsnzr.mjs → build-DQnV0GCD.mjs} +3 -3
- package/dist/{build-BuBCsnzr.mjs.map → build-DQnV0GCD.mjs.map} +1 -1
- package/dist/{builtins-DXASTS7y.mjs → builtins-BsYCQU80.mjs} +2 -2
- package/dist/{builtins-397XZB9_.mjs → builtins-Cjp9FT1m.mjs} +392 -185
- 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-DGWvBOvj.mjs → doctor-rEbeoAoO.mjs} +282 -75
- package/dist/doctor-rEbeoAoO.mjs.map +1 -0
- package/dist/{fullstack-x16HfCRz.mjs → fullstack-DdSScENL.mjs} +7 -7
- package/dist/{fullstack-BqYdhTDI.mjs → fullstack-XhuwRQEb.mjs} +8 -8
- package/dist/{fullstack-BqYdhTDI.mjs.map → fullstack-XhuwRQEb.mjs.map} +1 -1
- package/dist/index.d.mts +29 -7
- 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-HazJu53p.mjs → plugin--9hxxgsD.mjs} +2 -2
- package/dist/{plugin-Dh0LYWl5.mjs → plugin-CvlUt9NG.mjs} +2 -2
- package/dist/project-BN1DnrN3.mjs +134 -0
- package/dist/project-BN1DnrN3.mjs.map +1 -0
- package/dist/project-DBmrFgdd.mjs +133 -0
- package/dist/{project-root-DGKTJDH3.mjs → project-root-BXmtd-te.mjs} +2 -2
- package/dist/{project-root-DlgCWwc_.mjs → project-root-FMt83NHV.mjs} +3 -3
- package/dist/{project-root-DlgCWwc_.mjs.map → project-root-FMt83NHV.mjs.map} +1 -1
- package/dist/{prompts-D4nwf5mP.mjs → prompts-DJBDNwHt.mjs} +2 -2
- package/dist/{prompts-D4nwf5mP.mjs.map → prompts-DJBDNwHt.mjs.map} +1 -1
- package/dist/{rolldown-runtime-7c5UUG6D.mjs → rolldown-runtime-C4d34LEE.mjs} +1 -1
- package/dist/{run-plugins-Dx-QENlm.mjs → run-plugins-9tjbMqS6.mjs} +87 -87
- package/dist/run-plugins-9tjbMqS6.mjs.map +1 -0
- package/dist/typegen-AGdhxyRc.mjs +107 -0
- package/dist/typegen-AGdhxyRc.mjs.map +1 -0
- package/dist/typegen-Lf0UPhdl.mjs +106 -0
- package/dist/{types-CtrnAiNl.mjs → types-B5dY2mTz.mjs} +1 -1
- package/package.json +3 -3
- package/templates/base/files/README.md +2 -2
- package/templates/base/files/kick.config.ts +1 -1
- package/templates/base/files/src/modules/hello/hello.controller.ts +0 -5
- package/templates/base/files/src/modules/hello/hello.service.ts +0 -4
- package/templates/base/files/tsconfig.json +3 -1
- package/templates/feature-devtools/feature.json +2 -6
- package/templates/feature-devtools/files/src/devtools.d.ts +3 -0
- package/templates/feature-queue/feature.json +39 -3
- package/templates/feature-queue/files/_dot_env.example.append +4 -2
- package/templates/feature-queue/files/src/adapters/queue.ts +16 -0
- package/templates/feature-storage/feature.json +1 -1
- package/templates/schema-valibot/files/src/config/index.ts +5 -2
- package/templates/schema-yup/files/src/config/index.ts +5 -2
- package/templates/schema-zod/files/src/config/index.ts +5 -2
- package/templates/template-inertia/feature.json +9 -1
- package/templates/template-inertia/files/_dot_env.append +2 -0
- package/templates/template-inertia/files/_dot_env.example.append +6 -2
- package/templates/template-inertia/files/_dot_env.test.append +1 -0
- package/templates/template-inertia/files/_dot_env.test.example.append +1 -0
- package/templates/template-inertia/files/src/client/Layout.tsx +2 -0
- package/templates/template-inertia/files/src/client/Seo.tsx +35 -0
- package/templates/template-inertia/files/src/index.ts +11 -5
- package/templates/template-inertia/files/src/modules/index.ts +2 -1
- package/templates/template-inertia/files/src/modules/pages/pages.controller.ts +18 -6
- package/templates/template-inertia/files/src/modules/pages/pages.test.ts +34 -0
- package/templates/template-inertia/files/src/modules/seo/seo.controller.ts +19 -0
- package/templates/template-inertia/files/src/modules/seo/seo.module.ts +12 -0
- package/templates/template-inertia/files/tsconfig.json +3 -1
- package/templates/template-inertia/files/vite.config.ts +3 -2
- package/templates/web-kick/files/web/_dot_oxfmtrc.json +9 -0
- package/templates/web-kick/files/web/src/App.tsx +1 -7
- package/dist/agent-docs-ZgfnGL-j.mjs.map +0 -1
- package/dist/config-Ck9aQVpE.mjs +0 -12
- package/dist/config-CsOfUFfq.mjs +0 -13
- package/dist/config-CsOfUFfq.mjs.map +0 -1
- package/dist/doctor-DGWvBOvj.mjs.map +0 -1
- package/dist/package-manager--IUl91nq.mjs +0 -11
- package/dist/package-manager-DBmD5nSr.mjs +0 -12
- package/dist/package-manager-DBmD5nSr.mjs.map +0 -1
- package/dist/project-C98JovY4.mjs +0 -115
- package/dist/project-C98JovY4.mjs.map +0 -1
- package/dist/project-TbTVQCnh.mjs +0 -114
- package/dist/run-plugins-Dx-QENlm.mjs.map +0 -1
- package/dist/typegen-DJQ6WBwr.mjs +0 -106
- package/dist/typegen-DSaawXaQ.mjs +0 -107
- package/dist/typegen-DSaawXaQ.mjs.map +0 -1
- package/templates/feature-queue/files/_dot_env.append +0 -2
- package/templates/template-inertia/files/public/robots.txt +0 -4
- /package/templates/feature-storage/files/src/{storage.ts → adapters/storage.ts} +0 -0
|
@@ -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-7c5UUG6D.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-TbTVQCnh.mjs";import{a as c,c as l,d as u,i as d,l as f,o as p,s as m,u as h}from"./config-Ck9aQVpE.mjs";import{n as g,r as _}from"./plugin-Dh0LYWl5.mjs";import{a as v,i as y,n as ee,o as b,t as x}from"./package-manager--IUl91nq.mjs";import{a as S,c as C,d as te,f as w,i as ne,l as re,n as ie,o as ae,p as oe,r as se,s as T,u as ce}from"./agent-docs-As_KjQBC.mjs";import{t as E}from"./project-root-DGKTJDH3.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 D,y as Ae}from"./typegen-DJQ6WBwr.mjs";import{t as je}from"./build-BfC9Kkt-.mjs";import{createRequire as Me}from"node:module";import{cpSync as Ne,existsSync as O,mkdirSync as Pe,readFileSync as k,readdirSync as A,rmSync as Fe,statSync as Ie,writeFileSync as j}from"node:fs";import M,{basename as Le,dirname as N,join as P,relative as F,resolve as I,sep as L}from"node:path";import{fileURLToPath as Re,pathToFileURL as R}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 z,readdir as We,rm as Ge,stat as Ke,writeFile as B}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import{createHash as qe}from"node:crypto";import{parseSync as Je}from"oxc-parser";import Ye from"pluralize";import{arch as Xe,platform as Ze,release as Qe}from"node:os";const $e=[{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 et(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)=>{ne(`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=I(`.`),e=Le(r)):r=I(t.directory||e),O(r)){let i=A(r);if(i.length>0){if(t.force)S.warn(`Clearing existing files in ${r}`);else if(n){S.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),T(`Aborted.`);return}else{S.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)S.message(` - ${e}`);if(i.length>5&&S.message(` ... and ${i.length-5} more`),!await se({message:w.red(`Remove all existing files and proceed?`),initialValue:!1})){T(`Aborted.`);return}}for(let e of i)Fe(I(r,e),{recursive:!0,force:!0})}}let i=t.template;i||=n?`minimal`:await C({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 C({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 C({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`}),u(c);let l=t.schema;i===`inertia`&&(l&&l!==`zod`&&S.warn(`The inertia template uses zod — ignoring --schema ${l}.`),l=`zod`),l||=n?`zod`:await C({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)||(S.warn(`Unknown --schema "${l}", falling back to zod.`),l=`zod`);let d;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();d=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else d=n?[]:await ae({message:`Select packages to include`,options:[...$e],required:!1});let f;f=t.git===void 0?n?!0:await se({message:`Initialize git repository?`,initialValue:!0}):t.git;let p;if(p=t.install===void 0?n?!0:await se({message:`Install dependencies?`,initialValue:!0}):t.install,t.frontend!==void 0&&t.frontend!==`kick`&&t.frontend!==`vite`){S.error(`Unknown --frontend '${String(t.frontend)}'. Use 'kick' (wired React app) or 'vite' (create-vite).`),T(`Aborted.`);return}let{VITE_TEMPLATES:m,DEFAULT_VITE_TEMPLATE:g}=await import(`./fullstack-x16HfCRz.mjs`);if(t.viteTemplate!==void 0&&!m.some(e=>e.value===t.viteTemplate)){S.error(`Unknown --vite-template '${String(t.viteTemplate)}'. TypeScript templates only: ${m.map(e=>e.value).join(`, `)}.`),T(`Aborted.`);return}let _=t.frontend===`vite`?`vite`:`kick`,v=t.viteTemplate??g;if(i===`fullstack`&&!t.frontend&&!n&&(_=await C({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 C({message:`create-vite template`,options:m.map(e=>({value:e.value,label:e.label})),initialValue:g})),i===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-x16HfCRz.mjs`);await t({name:e,directory:r,packageManager:o,initGit:f,installDeps:p,schemaLib:l,runtime:a,packages:d,frontend:_,viteTemplate:v}),T(`Done! Next steps: ${w.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:d,schemaLib:l,runtime:a}),T(`Done! Next steps: ${w.cyan(`cd ${e} && ${h(o,`dev`)}`)}`)})}function V(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function H(e){let t=V(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 Ye.plural(e)}function tt(e){return Ye.plural(e)}function nt(e){return U(e).replace(/-/g,`_`)}function rt(e){let t=e.cwd??process.cwd(),n=e.projectRoot??E(t),r=e.pluralize??!0,i=V(e.name),a=H(e.name),o=U(e.name),s=nt(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=V(e),c.pluralCamel=H(e)}return c}function it(e,t){return I(e.cwd,t)}async function at(e){return import(R(e).href)}const ot=/* @__PURE__ */ new Map;async function st(e){let t=ot.get(e);if(t)return t;let n=ct(e);return ot.set(e,n),n}async function ct(e){let t=I(e,`package.json`);if(!O(t))return{generators:[],loaded:[],failed:[]};let n=lt(JSON.parse(await z(t,`utf-8`))),r=Me(I(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 z(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=I(N(t),s);if(!O(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await at(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)ut(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 lt(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 ut(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function dt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return mt(r.spec,r.source,e,n);let i=pt(await st(n),e.generatorName);return i?mt(i.spec,i.source,e,n):null}async function ft(e,t=[]){let n=await st(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 pt(e,t){return e.generators.find(e=>e.spec.name===t)}async function mt(e,t,n,r){let i=rt({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=it(i,e.path);await b(t,e.content),o.push(t)}return{files:o,source:t}}function G(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const ht={inmemory:`in-memory`,drizzle:`Drizzle`,prisma:`Prisma`};function gt(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function _t(e){return ht[e]??gt(e)}function vt(e){return`create${e}Repository`}function yt(e){return e??`define`}function bt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,o=vt(t),s=yt(a),c=`/**
|
|
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.
|
|
@@ -21,10 +21,10 @@ import{t as e}from"./rolldown-runtime-7c5UUG6D.mjs";import{c as t,g as n,i as r,
|
|
|
21
21
|
* dtos/ — Request/response schemas
|
|
22
22
|
*
|
|
23
23
|
* The repository is backed by an in-memory Map so this module works as
|
|
24
|
-
* generated. Swap in ${i===`inmemory`?`a database`:
|
|
24
|
+
* generated. Swap in ${i===`inmemory`?`a database`:yt(i)} by replacing the factory body in
|
|
25
25
|
* ${n}.repository.ts — the contract is whatever that factory returns, so
|
|
26
26
|
* nothing else has to change.
|
|
27
|
-
*/`,
|
|
27
|
+
*/`,u=`import { ${t.toUpperCase()}_REPOSITORY, ${s} } from './${n}.repository'
|
|
28
28
|
import { ${t}Controller } from './${n}.controller'
|
|
29
29
|
|
|
30
30
|
// Eagerly load every module file so decorators (@Controller / @Service /
|
|
@@ -33,7 +33,7 @@ import { ${t}Controller } from './${n}.controller'
|
|
|
33
33
|
// to emit, so a hand-written \`*.usecase.ts\` or \`*.policy.ts\` silently never
|
|
34
34
|
// registered and failed later as \`No provider for X\` (#609). Recursive (./**/)
|
|
35
35
|
// so nesting keeps working.
|
|
36
|
-
import.meta.glob(['./**/*.ts', '!./**/*.test.ts', '!./**/*.d.ts'], { eager: true })`,
|
|
36
|
+
import.meta.glob(['./**/*.ts', '!./**/*.test.ts', '!./**/*.d.ts'], { eager: true })`,d=` /**
|
|
37
37
|
* Declare HTTP routes for this module. Return value shape:
|
|
38
38
|
*
|
|
39
39
|
* - \`path\` — URL prefix for this route set.
|
|
@@ -44,49 +44,49 @@ import.meta.glob(['./**/*.ts', '!./**/*.test.ts', '!./**/*.d.ts'], { eager: true
|
|
|
44
44
|
* surfaces, side-by-side v1 + v2 controllers, etc:
|
|
45
45
|
*
|
|
46
46
|
* return [
|
|
47
|
-
* { path: '/${
|
|
48
|
-
* { path: '/${
|
|
47
|
+
* { path: '/${o}', version: 1, controller: ${t}V1Controller },
|
|
48
|
+
* { path: '/${o}', version: 2, controller: ${t}V2Controller },
|
|
49
49
|
* ]
|
|
50
|
-
*/`;return
|
|
50
|
+
*/`;return c===`class`?`${l}
|
|
51
51
|
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
52
|
-
${
|
|
52
|
+
${u}
|
|
53
53
|
|
|
54
54
|
export class ${t}Module implements AppModule {
|
|
55
55
|
register(container: Container): void {
|
|
56
|
-
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () => ${
|
|
56
|
+
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () => ${s}())
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
${
|
|
59
|
+
${d.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
60
60
|
routes(): ModuleRoutes {
|
|
61
61
|
return {
|
|
62
|
-
path: '/${
|
|
62
|
+
path: '/${o}',
|
|
63
63
|
controller: ${t}Controller,
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
-
`:`${
|
|
67
|
+
`:`${l}
|
|
68
68
|
import { defineModule } from '@forinda/kickjs'
|
|
69
|
-
${
|
|
69
|
+
${u}
|
|
70
70
|
|
|
71
71
|
export const ${t}Module = defineModule({
|
|
72
72
|
name: '${t}Module',
|
|
73
73
|
build: () => ({
|
|
74
74
|
register(container) {
|
|
75
75
|
container.registerFactory(${t.toUpperCase()}_REPOSITORY, () =>
|
|
76
|
-
${
|
|
76
|
+
${s}(),
|
|
77
77
|
)
|
|
78
78
|
},
|
|
79
79
|
|
|
80
|
-
${
|
|
80
|
+
${d}
|
|
81
81
|
routes() {
|
|
82
82
|
return {
|
|
83
|
-
path: '/${
|
|
83
|
+
path: '/${o}',
|
|
84
84
|
controller: ${t}Controller,
|
|
85
85
|
}
|
|
86
86
|
},
|
|
87
87
|
}),
|
|
88
88
|
})
|
|
89
|
-
`}function
|
|
89
|
+
`}function Ct(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=e.routePath??r,o=xt(i),s=` /**
|
|
90
90
|
* Declare HTTP routes. Return value shape:
|
|
91
91
|
*
|
|
92
92
|
* - \`path\` — URL prefix for this route set.
|
|
@@ -96,17 +96,17 @@ ${u}
|
|
|
96
96
|
* Return an array to mount multiple route sets:
|
|
97
97
|
*
|
|
98
98
|
* return [
|
|
99
|
-
* { path: '/${
|
|
100
|
-
* { path: '/${
|
|
99
|
+
* { path: '/${a}', version: 1, controller: ${t}V1Controller },
|
|
100
|
+
* { path: '/${a}', version: 2, controller: ${t}V2Controller },
|
|
101
101
|
* ]
|
|
102
|
-
*/`;return
|
|
102
|
+
*/`;return o===`class`?`import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
103
103
|
import { ${t}Controller } from './${n}.controller'
|
|
104
104
|
|
|
105
105
|
export class ${t}Module implements AppModule {
|
|
106
|
-
${
|
|
106
|
+
${s.replace(/^ {4}/gm,` `).replace(/^ {6}/gm,` `)}
|
|
107
107
|
routes(): ModuleRoutes {
|
|
108
108
|
return {
|
|
109
|
-
path: '/${
|
|
109
|
+
path: '/${a}',
|
|
110
110
|
controller: ${t}Controller,
|
|
111
111
|
}
|
|
112
112
|
}
|
|
@@ -117,21 +117,21 @@ import { ${t}Controller } from './${n}.controller'
|
|
|
117
117
|
export const ${t}Module = defineModule({
|
|
118
118
|
name: '${t}Module',
|
|
119
119
|
build: () => ({
|
|
120
|
-
${
|
|
120
|
+
${s}
|
|
121
121
|
routes() {
|
|
122
122
|
return {
|
|
123
|
-
path: '/${
|
|
123
|
+
path: '/${a}',
|
|
124
124
|
controller: ${t}Controller,
|
|
125
125
|
}
|
|
126
126
|
},
|
|
127
127
|
}),
|
|
128
128
|
})
|
|
129
|
-
`}function
|
|
129
|
+
`}function wt(e){let{pascal:t,kebab:n}=e,r=e.swagger?`import { ApiTags } from '@forinda/kickjs-swagger'
|
|
130
130
|
`:``,i=e.swagger?` @ApiTags('${e.pascal}')\n`:``,a=t.charAt(0).toLowerCase()+t.slice(1);return`import {
|
|
131
131
|
Controller,
|
|
132
132
|
Get,
|
|
133
133
|
Post,
|
|
134
|
-
|
|
134
|
+
Patch,
|
|
135
135
|
Delete,
|
|
136
136
|
Autowired,
|
|
137
137
|
ApiQueryParams,
|
|
@@ -157,10 +157,18 @@ import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
|
157
157
|
// \`ctx.problem.*\` for error branches — those send immediately and return
|
|
158
158
|
// nothing, so they stay out of the success type.
|
|
159
159
|
|
|
160
|
+
// Require a signed-in user for these routes: https://kickjs.app/guide/authentication
|
|
160
161
|
@Controller()
|
|
161
162
|
export class ${t}Controller {
|
|
162
163
|
@Autowired() private readonly ${a}Service!: ${t}Service
|
|
163
164
|
|
|
165
|
+
// Offset pages (?page=&limit=). For keyset pages (?cursor=&limit=) — stable
|
|
166
|
+
// under concurrent inserts, no deep OFFSET scans — swap the body for:
|
|
167
|
+
// return ctx.paginateCursor(
|
|
168
|
+
// (q) => this.${a}Service.findAfter({ ...q, limit: q.limit + 1 }),
|
|
169
|
+
// ${t.toUpperCase()}_QUERY_CONFIG,
|
|
170
|
+
// )
|
|
171
|
+
// https://kickjs.app/guide/query-parsing#cursor-pagination
|
|
164
172
|
@Get('/')
|
|
165
173
|
${i} @ApiQueryParams(${t.toUpperCase()}_QUERY_CONFIG)
|
|
166
174
|
async list(ctx: Ctx<KickRoutes.${t}Controller['list']>) {
|
|
@@ -184,10 +192,14 @@ ${i} async getById(ctx: Ctx<KickRoutes.${t}Controller['getById']>) {
|
|
|
184
192
|
|
|
185
193
|
@Post('/', { body: create${t}Schema, name: 'Create${t}' })
|
|
186
194
|
${i} async create(ctx: Ctx<KickRoutes.${t}Controller['create']>) {
|
|
187
|
-
|
|
195
|
+
const created = await this.${a}Service.create(ctx.body)
|
|
196
|
+
// 201 + Location: where the new ${n} lives, built from the getById route.
|
|
197
|
+
return reply.created(created, {
|
|
198
|
+
location: ctx.urlFor('${t}Controller.getById', { id: created.id }),
|
|
199
|
+
})
|
|
188
200
|
}
|
|
189
201
|
|
|
190
|
-
@
|
|
202
|
+
@Patch('/:id', { body: update${t}Schema, name: 'Update${t}' })
|
|
191
203
|
${i} async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
192
204
|
return this.${a}Service.update(ctx.params.id, ctx.body)
|
|
193
205
|
}
|
|
@@ -198,10 +210,10 @@ ${i} async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
|
198
210
|
return reply.noContent()
|
|
199
211
|
}
|
|
200
212
|
}
|
|
201
|
-
`}const
|
|
213
|
+
`}const Tt={zod:{import:`import { z } from 'zod'`,required:`z.string().min(1, { error: 'Name is required' }).max(200)`,optional:`z.string().min(1).max(200).optional()`,infer:e=>`z.infer<typeof ${e}>`,hint:[` * z.string(), z.number(), z.boolean(), z.enum([...]),`,` * z.array(), z.object(), .optional(), .default(), .transform()`].join(`
|
|
202
214
|
`)},valibot:{import:`import * as v from 'valibot'`,required:`v.pipe(v.string(), v.minLength(1, 'Name is required'), v.maxLength(200))`,optional:`v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(200)))`,infer:e=>`v.InferOutput<typeof ${e}>`,hint:[` * v.string(), v.number(), v.boolean(), v.picklist([...]),`,` * v.array(), v.object(), v.optional(), and v.pipe(...) to chain checks`].join(`
|
|
203
215
|
`)},yup:{import:`import * as yup from 'yup'`,required:`yup.string().required('Name is required').min(1).max(200)`,optional:`yup.string().min(1).max(200).optional()`,infer:e=>`yup.InferType<typeof ${e}>`,hint:[` * yup.string(), yup.number(), yup.boolean(), .oneOf([...]),`,` * yup.array(), yup.object(), .required(), .optional(), .default()`].join(`
|
|
204
|
-
`)}};function
|
|
216
|
+
`)}};function Et(e,t){return`${e===`zod`?`z.object`:e===`valibot`?`v.object`:`yup.object`}({\n ${t},\n})`}function Dt(e){let{pascal:t}=e,n=e.schemaLib??`zod`,r=Tt[n],i=`create${t}Schema`,a=n===`zod`?`Zod`:n===`valibot`?`Valibot`:`Yup`;return`${r.import}
|
|
205
217
|
|
|
206
218
|
/**
|
|
207
219
|
* Create ${t} DTO — ${a} schema for validating POST request bodies.
|
|
@@ -211,21 +223,37 @@ ${i} async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
|
211
223
|
* Add more fields as needed. Supported ${a} types:
|
|
212
224
|
${r.hint}
|
|
213
225
|
*/
|
|
214
|
-
export const ${i} = ${
|
|
226
|
+
export const ${i} = ${Et(n,`name: ${r.required}`)}
|
|
215
227
|
|
|
216
228
|
export type Create${t}DTO = ${r.infer(i)}
|
|
217
|
-
`}function
|
|
229
|
+
`}function Ot(e){let{pascal:t}=e,n=e.schemaLib??`zod`,r=Tt[n],i=`update${t}Schema`;return`${r.import}
|
|
218
230
|
|
|
219
|
-
export const ${i} = ${
|
|
231
|
+
export const ${i} = ${Et(n,`name: ${r.optional}`)}
|
|
220
232
|
|
|
221
233
|
export type Update${t}DTO = ${r.infer(i)}
|
|
222
|
-
`}function
|
|
234
|
+
`}function kt(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
223
235
|
id: string
|
|
224
236
|
name: string
|
|
225
237
|
createdAt: string
|
|
226
238
|
updatedAt: string
|
|
227
239
|
}
|
|
228
|
-
`}function
|
|
240
|
+
`}function At(e){let{pascal:t,kebab:n,repoType:r,dtoPrefix:i=`./dtos`,tokenScope:a=`app`}=e,o=r&&r!==`inmemory`?r:``,s=`create${t}Repository`,c=` const store = new Map<string, ${t}ResponseDTO>()
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Filtered, searched and sorted. \`byId\` breaks sort-key ties by id — what a
|
|
244
|
+
* cursor needs; without it ties (and an unsorted list) keep insertion order.
|
|
245
|
+
*/
|
|
246
|
+
function select(parsed: Omit<ParsedQuery, 'pagination'>, byId = false): ${t}ResponseDTO[] {
|
|
247
|
+
// The parser already limited fields to ${t.toUpperCase()}_QUERY_CONFIG.
|
|
248
|
+
const q = parsed.search.toLowerCase()
|
|
249
|
+
return [...store.values()]
|
|
250
|
+
.filter(
|
|
251
|
+
(row) =>
|
|
252
|
+
parsed.filters.every((f) => matches(field(row, f.field), f)) &&
|
|
253
|
+
(!q || SEARCHABLE.some((name) => String(field(row, name) ?? '').toLowerCase().includes(q))),
|
|
254
|
+
)
|
|
255
|
+
.sort((a, b) => order(a, b, parsed.sort, byId))
|
|
256
|
+
}
|
|
229
257
|
|
|
230
258
|
return {
|
|
231
259
|
async findById(id: string): Promise<${t}ResponseDTO | null> {
|
|
@@ -239,9 +267,28 @@ export type Update${t}DTO = ${r.infer(i)}
|
|
|
239
267
|
async findPaginated(
|
|
240
268
|
parsed: ParsedQuery,
|
|
241
269
|
): Promise<{ data: ${t}ResponseDTO[]; total: number }> {
|
|
242
|
-
const
|
|
270
|
+
const rows = select(parsed)
|
|
243
271
|
const { offset, limit } = parsed.pagination
|
|
244
|
-
return { data:
|
|
272
|
+
return { data: rows.slice(offset, offset + limit), total: rows.length }
|
|
273
|
+
},
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Keyset page for \`ctx.paginateCursor\`: the rows strictly after
|
|
277
|
+
* \`cursor\` in sort order (id breaks ties), at most \`limit\` of them —
|
|
278
|
+
* the caller asks for one more than it shows, to learn whether a next
|
|
279
|
+
* page exists. A database does the same with
|
|
280
|
+
* \`WHERE (sortField, id) > (cursor.sortField, cursor.id)\`.
|
|
281
|
+
*/
|
|
282
|
+
async findAfter(
|
|
283
|
+
query: Omit<ParsedQuery, 'pagination'> & {
|
|
284
|
+
cursor: Readonly<Record<string, unknown>> | null
|
|
285
|
+
limit: number
|
|
286
|
+
},
|
|
287
|
+
): Promise<${t}ResponseDTO[]> {
|
|
288
|
+
const { cursor, limit, sort } = query
|
|
289
|
+
const rows = select(query, true)
|
|
290
|
+
const after = cursor ? rows.filter((row) => order(row, cursor, sort, true) > 0) : rows
|
|
291
|
+
return after.slice(0, limit)
|
|
245
292
|
},
|
|
246
293
|
|
|
247
294
|
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
@@ -277,11 +324,71 @@ export type Update${t}DTO = ${r.infer(i)}
|
|
|
277
324
|
*/
|
|
278
325
|
import { randomUUID } from 'node:crypto'
|
|
279
326
|
import { createToken, HttpException } from '@forinda/kickjs'
|
|
280
|
-
import type { ParsedQuery } from '@forinda/kickjs'
|
|
327
|
+
import type { FilterItem, ParsedQuery, SortItem } from '@forinda/kickjs'
|
|
328
|
+
import { ${t.toUpperCase()}_QUERY_CONFIG } from './${n}.constants'
|
|
281
329
|
import type { ${t}ResponseDTO } from '${i}/${n}-response.dto'
|
|
282
330
|
import type { Create${t}DTO } from '${i}/create-${n}.dto'
|
|
283
331
|
import type { Update${t}DTO } from '${i}/update-${n}.dto'
|
|
284
332
|
|
|
333
|
+
const SEARCHABLE = (${t.toUpperCase()}_QUERY_CONFIG.searchable ?? []) as string[]
|
|
334
|
+
|
|
335
|
+
function field(row: object, name: string): unknown {
|
|
336
|
+
return (row as Record<string, unknown>)[name]
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* A stored number compares by value (the query's value is text); everything
|
|
341
|
+
* else, ISO dates included, as text — so a string field keeps '001' ≠ '1'.
|
|
342
|
+
*/
|
|
343
|
+
function compare(stored: unknown, other: unknown): number {
|
|
344
|
+
if (typeof stored === 'number') return stored - Number(other)
|
|
345
|
+
return String(stored ?? '').localeCompare(String(other ?? ''))
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Sort order of two rows (or a row and a cursor position): each sort field in
|
|
350
|
+
* turn, then — with \`byId\` — id, in the direction of the last sort field.
|
|
351
|
+
*/
|
|
352
|
+
function order(a: object, b: object, sort: readonly SortItem[], byId: boolean): number {
|
|
353
|
+
for (const { field: name, direction } of sort) {
|
|
354
|
+
const result = compare(field(a, name), field(b, name))
|
|
355
|
+
if (result) return direction === 'desc' ? -result : result
|
|
356
|
+
}
|
|
357
|
+
if (!byId) return 0
|
|
358
|
+
const result = compare(field(a, 'id'), field(b, 'id'))
|
|
359
|
+
return sort.at(-1)?.direction === 'desc' ? -result : result
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** One \`?filter=field:op:value\` — \`in\` and \`between\` take comma-separated values. */
|
|
363
|
+
function matches(value: unknown, { operator, value: raw }: FilterItem): boolean {
|
|
364
|
+
const text = String(value ?? '').toLowerCase()
|
|
365
|
+
const list = raw.split(',')
|
|
366
|
+
switch (operator) {
|
|
367
|
+
case 'eq':
|
|
368
|
+
return compare(value, raw) === 0
|
|
369
|
+
case 'neq':
|
|
370
|
+
return compare(value, raw) !== 0
|
|
371
|
+
case 'gt':
|
|
372
|
+
return compare(value, raw) > 0
|
|
373
|
+
case 'gte':
|
|
374
|
+
return compare(value, raw) >= 0
|
|
375
|
+
case 'lt':
|
|
376
|
+
return compare(value, raw) < 0
|
|
377
|
+
case 'lte':
|
|
378
|
+
return compare(value, raw) <= 0
|
|
379
|
+
case 'between':
|
|
380
|
+
return compare(value, list[0]) >= 0 && compare(value, list[1]) <= 0
|
|
381
|
+
case 'in':
|
|
382
|
+
return list.some((v) => compare(value, v) === 0)
|
|
383
|
+
case 'contains':
|
|
384
|
+
return text.includes(raw.toLowerCase())
|
|
385
|
+
case 'starts':
|
|
386
|
+
return text.startsWith(raw.toLowerCase())
|
|
387
|
+
case 'ends':
|
|
388
|
+
return text.endsWith(raw.toLowerCase())
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
285
392
|
export function ${s}() {
|
|
286
393
|
${c}
|
|
287
394
|
}
|
|
@@ -300,7 +407,7 @@ export type ${t}Repository = ReturnType<typeof ${s}>
|
|
|
300
407
|
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
301
408
|
*/
|
|
302
409
|
export const ${t.toUpperCase()}_REPOSITORY = createToken<${t}Repository>('${a}/${t}/repository')
|
|
303
|
-
`}function
|
|
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}'
|
|
304
411
|
import request from 'supertest'
|
|
305
412
|
import { Container } from '@forinda/kickjs'
|
|
306
413
|
import { createTestApp } from '@forinda/kickjs-testing'
|
|
@@ -316,11 +423,11 @@ import { ${t}Module } from '../${n}.module'
|
|
|
316
423
|
* pass the same values in \`boot()\` below and update this to match, so the test
|
|
317
424
|
* exercises the paths production actually serves:
|
|
318
425
|
*
|
|
319
|
-
* defaultVersion: false → '/api/${
|
|
320
|
-
* apiPrefix: '/v1' → '/v1/v1/${
|
|
426
|
+
* defaultVersion: false → '/api/${s}'
|
|
427
|
+
* apiPrefix: '/v1' → '/v1/v1/${s}'
|
|
321
428
|
*/
|
|
322
|
-
const BASE = '/api/v1/${
|
|
323
|
-
`:`import { describe, it, beforeEach } from '
|
|
429
|
+
const BASE = '/api/v1/${s}'
|
|
430
|
+
`:`import { describe, it, beforeEach } from '${o}'
|
|
324
431
|
import { Container } from '@forinda/kickjs'
|
|
325
432
|
|
|
326
433
|
// Install \`@forinda/kickjs-testing\` and \`supertest\` to boot this module in a
|
|
@@ -342,7 +449,7 @@ ${a?` /**
|
|
|
342
449
|
*/
|
|
343
450
|
async function boot() {
|
|
344
451
|
const { app, container } = await createTestApp({
|
|
345
|
-
modules: [${
|
|
452
|
+
modules: [${c}],
|
|
346
453
|
// Mirror your bootstrap() here if it overrides either, and update BASE:
|
|
347
454
|
// apiPrefix: '/api',
|
|
348
455
|
// defaultVersion: 1,
|
|
@@ -350,7 +457,7 @@ ${a?` /**
|
|
|
350
457
|
return { app, container, agent: request(app.handle.bind(app)) }
|
|
351
458
|
}
|
|
352
459
|
|
|
353
|
-
describe('GET /${
|
|
460
|
+
describe('GET /${s}', () => {
|
|
354
461
|
it('returns an empty page before anything is created', async () => {
|
|
355
462
|
const { agent } = await boot()
|
|
356
463
|
const res = await agent.get(BASE)
|
|
@@ -359,8 +466,18 @@ ${a?` /**
|
|
|
359
466
|
expect(res.body).toMatchObject({ data: [], meta: { page: 1 } })
|
|
360
467
|
})
|
|
361
468
|
|
|
469
|
+
it('filters and sorts through the query string', async () => {
|
|
470
|
+
const { agent } = await boot()
|
|
471
|
+
for (const name of ['Alpha', 'Beta', 'Gamma']) await agent.post(BASE).send({ name })
|
|
472
|
+
const res = await agent.get(\`\${BASE}?filter=name:neq:Beta&sort=name:desc\`)
|
|
473
|
+
|
|
474
|
+
expect(res.status).toBe(200)
|
|
475
|
+
expect(res.body.data.map((row: { name: string }) => row.name)).toEqual(['Gamma', 'Alpha'])
|
|
476
|
+
expect(res.body.meta.total).toBe(2)
|
|
477
|
+
})
|
|
478
|
+
|
|
362
479
|
it.todo('returns created ${r}, paginated')
|
|
363
|
-
})`:` describe('GET /${
|
|
480
|
+
})`:` describe('GET /${s}', () => {
|
|
364
481
|
// Boot the module with createTestApp and assert { data, meta }.
|
|
365
482
|
it.todo('returns an empty page before anything is created')
|
|
366
483
|
it.todo('returns created ${r}, paginated')
|
|
@@ -370,38 +487,45 @@ ${a?` /**
|
|
|
370
487
|
// reporter lists it as outstanding instead of counting it as a pass. Replace
|
|
371
488
|
// the todo with a real test as you implement each endpoint.
|
|
372
489
|
|
|
373
|
-
describe('POST /${
|
|
374
|
-
|
|
375
|
-
|
|
490
|
+
describe('POST /${s}', () => {
|
|
491
|
+
${a?` it('creates a ${n} and points Location at it', async () => {
|
|
492
|
+
const { agent } = await boot()
|
|
493
|
+
const res = await agent.post(BASE).send({ name: 'Test ${t}' })
|
|
494
|
+
|
|
495
|
+
expect(res.status).toBe(201)
|
|
496
|
+
expect(res.body).toMatchObject({ name: 'Test ${t}' })
|
|
497
|
+
expect(res.headers.location).toBe(\`\${BASE}/\${res.body.id}\`)
|
|
498
|
+
})`:` // Post a valid body, assert 201, the created ${n}, and its Location header.
|
|
499
|
+
it.todo('creates a ${n}')`}
|
|
376
500
|
// Post an invalid body, assert 422 and the validation detail.
|
|
377
501
|
it.todo('rejects an invalid body')
|
|
378
502
|
})
|
|
379
503
|
|
|
380
|
-
describe('GET /${
|
|
504
|
+
describe('GET /${s}/:id', () => {
|
|
381
505
|
// Create one, fetch it by id, assert the payload matches.
|
|
382
506
|
it.todo('returns a ${n} by id')
|
|
383
507
|
// Fetch an id that does not exist, assert 404.
|
|
384
508
|
it.todo('returns 404 for an unknown id')
|
|
385
509
|
})
|
|
386
510
|
|
|
387
|
-
describe('
|
|
511
|
+
describe('PATCH /${s}/:id', () => {
|
|
388
512
|
// Create, update, assert the change is reflected on a subsequent read.
|
|
389
513
|
it.todo('updates an existing ${n}')
|
|
390
514
|
})
|
|
391
515
|
|
|
392
|
-
describe('DELETE /${
|
|
516
|
+
describe('DELETE /${s}/:id', () => {
|
|
393
517
|
// Create, delete, assert a subsequent read is 404.
|
|
394
518
|
it.todo('deletes a ${n}')
|
|
395
519
|
})
|
|
396
520
|
})
|
|
397
|
-
`}function
|
|
398
|
-
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}'
|
|
399
523
|
|
|
400
524
|
describe('${t} repository', () => {
|
|
401
525
|
let repo: ${t}Repository
|
|
402
526
|
|
|
403
527
|
beforeEach(() => {
|
|
404
|
-
repo = ${
|
|
528
|
+
repo = ${o}()
|
|
405
529
|
})
|
|
406
530
|
|
|
407
531
|
it('should create and retrieve a ${n}', async () => {
|
|
@@ -443,6 +567,83 @@ describe('${t} repository', () => {
|
|
|
443
567
|
expect(result.total).toBe(3)
|
|
444
568
|
})
|
|
445
569
|
|
|
570
|
+
it('should filter, search and sort before paginating', async () => {
|
|
571
|
+
await repo.create({ name: 'Banana' })
|
|
572
|
+
await repo.create({ name: 'apple' })
|
|
573
|
+
await repo.create({ name: 'Cherry' })
|
|
574
|
+
const pagination = { page: 1, limit: 10, offset: 0 }
|
|
575
|
+
|
|
576
|
+
const sorted = await repo.findPaginated({
|
|
577
|
+
filters: [],
|
|
578
|
+
sort: [{ field: 'name', direction: 'desc' }],
|
|
579
|
+
search: '',
|
|
580
|
+
pagination,
|
|
581
|
+
})
|
|
582
|
+
expect(sorted.data.map((row) => row.name)).toEqual(['Cherry', 'Banana', 'apple'])
|
|
583
|
+
|
|
584
|
+
const filtered = await repo.findPaginated({
|
|
585
|
+
filters: [{ field: 'name', operator: 'neq', value: 'apple' }],
|
|
586
|
+
sort: [],
|
|
587
|
+
search: '',
|
|
588
|
+
pagination: { page: 1, limit: 1, offset: 0 },
|
|
589
|
+
})
|
|
590
|
+
expect(filtered.data).toHaveLength(1)
|
|
591
|
+
expect(filtered.total).toBe(2)
|
|
592
|
+
|
|
593
|
+
const searched = await repo.findPaginated({ filters: [], sort: [], search: 'AN', pagination })
|
|
594
|
+
expect(searched.data.map((row) => row.name)).toEqual(['Banana'])
|
|
595
|
+
})
|
|
596
|
+
|
|
597
|
+
it('compares a text field as text, not as a number', async () => {
|
|
598
|
+
await repo.create({ name: '001' })
|
|
599
|
+
await repo.create({ name: '10' })
|
|
600
|
+
await repo.create({ name: '9' })
|
|
601
|
+
const pagination = { page: 1, limit: 10, offset: 0 }
|
|
602
|
+
|
|
603
|
+
const exact = await repo.findPaginated({
|
|
604
|
+
filters: [{ field: 'name', operator: 'eq', value: '1' }],
|
|
605
|
+
sort: [],
|
|
606
|
+
search: '',
|
|
607
|
+
pagination,
|
|
608
|
+
})
|
|
609
|
+
expect(exact.total).toBe(0)
|
|
610
|
+
|
|
611
|
+
const sorted = await repo.findPaginated({
|
|
612
|
+
filters: [],
|
|
613
|
+
sort: [{ field: 'name', direction: 'asc' }],
|
|
614
|
+
search: '',
|
|
615
|
+
pagination,
|
|
616
|
+
})
|
|
617
|
+
expect(sorted.data.map((row) => row.name)).toEqual(['001', '10', '9'])
|
|
618
|
+
})
|
|
619
|
+
|
|
620
|
+
it('pages through rows with findAfter, stable when sort keys tie', async () => {
|
|
621
|
+
// Three rows share 'a', so a page boundary falls inside the tie: only the
|
|
622
|
+
// id tie-breaker keeps the third 'a' from being skipped or repeated.
|
|
623
|
+
for (const name of ['b', 'a', 'b', 'a', 'a']) await repo.create({ name })
|
|
624
|
+
const query = { filters: [], sort: [{ field: 'name', direction: 'asc' as const }], search: '' }
|
|
625
|
+
const limit = 2
|
|
626
|
+
|
|
627
|
+
const pages: string[][] = []
|
|
628
|
+
const ids: string[] = []
|
|
629
|
+
let cursor: Record<string, unknown> | null = null
|
|
630
|
+
let hasNext = true
|
|
631
|
+
while (hasNext) {
|
|
632
|
+
// Ask for one more than a page, as ctx.paginateCursor's fetcher does.
|
|
633
|
+
const rows = await repo.findAfter({ ...query, cursor, limit: limit + 1 })
|
|
634
|
+
hasNext = rows.length > limit
|
|
635
|
+
const page = rows.slice(0, limit)
|
|
636
|
+
pages.push(page.map((row) => row.name))
|
|
637
|
+
ids.push(...page.map((row) => row.id))
|
|
638
|
+
const last = page.at(-1)
|
|
639
|
+
cursor = last ? { name: last.name, id: last.id } : null
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
expect(pages.map((page) => page.length)).toEqual([2, 2, 1])
|
|
643
|
+
expect(pages.flat()).toEqual(['a', 'a', 'a', 'b', 'b'])
|
|
644
|
+
expect(new Set(ids).size).toBe(5)
|
|
645
|
+
})
|
|
646
|
+
|
|
446
647
|
it('should update a ${n}', async () => {
|
|
447
648
|
const created = await repo.create({ name: 'Original' })
|
|
448
649
|
const updated = await repo.update(created.id, { name: 'Updated' })
|
|
@@ -456,7 +657,7 @@ describe('${t} repository', () => {
|
|
|
456
657
|
expect(found).toBeNull()
|
|
457
658
|
})
|
|
458
659
|
})
|
|
459
|
-
`}function
|
|
660
|
+
`}function Nt(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject } from '@forinda/kickjs'
|
|
460
661
|
import type { ParsedQuery } from '@forinda/kickjs'
|
|
461
662
|
import { ${t.toUpperCase()}_REPOSITORY, type ${t}Repository } from './${n}.repository'
|
|
462
663
|
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
@@ -481,6 +682,10 @@ export class ${t}Service {
|
|
|
481
682
|
return this.repo.findPaginated(parsed)
|
|
482
683
|
}
|
|
483
684
|
|
|
685
|
+
async findAfter(query: Parameters<${t}Repository['findAfter']>[0]) {
|
|
686
|
+
return this.repo.findAfter(query)
|
|
687
|
+
}
|
|
688
|
+
|
|
484
689
|
async create(dto: Create${t}DTO): Promise<${t}ResponseDTO> {
|
|
485
690
|
return this.repo.create(dto)
|
|
486
691
|
}
|
|
@@ -493,14 +698,14 @@ export class ${t}Service {
|
|
|
493
698
|
await this.repo.delete(id)
|
|
494
699
|
}
|
|
495
700
|
}
|
|
496
|
-
`}function
|
|
701
|
+
`}const Pt=/* @__PURE__ */ new Set([`string`,`text`,`email`,`url`]),Ft=/* @__PURE__ */ new Set([`json`]);function It(e){let{pascal:t,fields:n=[{name:`name`,type:`string`}]}=e,r=n.filter(e=>!Ft.has(e.type)).map(e=>e.name),i=n.filter(e=>Pt.has(e.type)).map(e=>e.name),a=e=>`[${e.map(e=>`'${e}'`).join(`, `)}]`;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
497
702
|
|
|
498
703
|
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
499
|
-
filterable:
|
|
500
|
-
sortable: [
|
|
501
|
-
searchable:
|
|
704
|
+
filterable: ${a(r)},
|
|
705
|
+
sortable: ${a([...r.filter(e=>e!==`createdAt`),`createdAt`])},
|
|
706
|
+
searchable: ${a(i)},
|
|
502
707
|
}
|
|
503
|
-
`}async function
|
|
708
|
+
`}async function Lt(e){let{pascal:t,kebab:n,plural:r,routePath:i,style:a,write:o}=e;await o(`${n}.module.ts`,Ct({pascal:t,kebab:n,plural:r,routePath:i,style:a})),await o(`${n}.controller.ts`,`import { Controller, Get, Post, Patch, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
504
709
|
|
|
505
710
|
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
506
711
|
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
@@ -513,6 +718,7 @@ export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
|
513
718
|
// "Minimal" is about the file count, not the route surface — you get the whole
|
|
514
719
|
// CRUD shape here in one file.
|
|
515
720
|
|
|
721
|
+
// Require a signed-in user for these routes: https://kickjs.app/guide/authentication
|
|
516
722
|
@Controller()
|
|
517
723
|
export class ${t}Controller {
|
|
518
724
|
@Get('/')
|
|
@@ -530,7 +736,7 @@ export class ${t}Controller {
|
|
|
530
736
|
return reply.created({ data: ctx.body })
|
|
531
737
|
}
|
|
532
738
|
|
|
533
|
-
@
|
|
739
|
+
@Patch('/:id')
|
|
534
740
|
async update(ctx: Ctx<KickRoutes.${t}Controller['update']>) {
|
|
535
741
|
return { id: ctx.params.id, data: ctx.body }
|
|
536
742
|
}
|
|
@@ -540,7 +746,7 @@ export class ${t}Controller {
|
|
|
540
746
|
return reply.noContent()
|
|
541
747
|
}
|
|
542
748
|
}
|
|
543
|
-
`)}async function
|
|
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'
|
|
544
750
|
import { ${t}Module } from '${s}'
|
|
545
751
|
|
|
546
752
|
export const modules: AppModuleEntry[] = [${c}]
|
|
@@ -548,11 +754,11 @@ export const modules: AppModuleEntry[] = [${c}]
|
|
|
548
754
|
import { ${t}Module } from '${s}'
|
|
549
755
|
|
|
550
756
|
export const modules = defineModules().mount(${c})
|
|
551
|
-
`;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(`
|
|
552
758
|
`,e);l=l.slice(0,t+1)+u+`
|
|
553
759
|
`+l.slice(t+1)}else l=u+`
|
|
554
|
-
`+l}let f=
|
|
555
|
-
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function
|
|
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
|
+
`;)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`/**
|
|
556
762
|
* Snapshot for the DevTools topology view (\`/_debug\`).
|
|
557
763
|
*
|
|
558
764
|
* Must be CHEAP — the topology endpoint polls on a short interval, so
|
|
@@ -592,7 +798,7 @@ export const modules = defineModules().mount(${c})
|
|
|
592
798
|
// ]
|
|
593
799
|
// },`.split(`
|
|
594
800
|
`).map(e=>r+e).join(`
|
|
595
|
-
`)}async function
|
|
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 {
|
|
596
802
|
defineAdapter,
|
|
597
803
|
type AdapterContext,
|
|
598
804
|
type AdapterMiddleware,
|
|
@@ -797,11 +1003,11 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
|
797
1003
|
return { name: '${r}', status: 'up' }
|
|
798
1004
|
},
|
|
799
1005
|
|
|
800
|
-
${
|
|
1006
|
+
${Jt(r,i,`adapter`,` `)}
|
|
801
1007
|
}
|
|
802
1008
|
},
|
|
803
1009
|
})
|
|
804
|
-
`),a.push(o),a}async function
|
|
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 {
|
|
805
1011
|
definePlugin,
|
|
806
1012
|
type AppAdapter,
|
|
807
1013
|
type AppModuleEntry,
|
|
@@ -958,13 +1164,13 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
|
958
1164
|
// Example: await this.connection?.close()
|
|
959
1165
|
},
|
|
960
1166
|
|
|
961
|
-
${
|
|
1167
|
+
${Jt(r,i,`plugin`,` `)}
|
|
962
1168
|
}),
|
|
963
1169
|
})
|
|
964
|
-
`),a.push(o),a}const
|
|
965
|
-
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=
|
|
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'`}
|
|
966
1172
|
|
|
967
|
-
export interface ${
|
|
1173
|
+
export interface ${U(t)}Options {
|
|
968
1174
|
// Add configuration options here. The factory below closes over the
|
|
969
1175
|
// resolved options object; pass them at the call site —
|
|
970
1176
|
// \`${l}({ foo: 'bar' })\` — and the closure preserves them across
|
|
@@ -972,7 +1178,7 @@ export interface ${V(t)}Options {
|
|
|
972
1178
|
}
|
|
973
1179
|
|
|
974
1180
|
/**
|
|
975
|
-
* ${
|
|
1181
|
+
* ${U(t)} middleware.
|
|
976
1182
|
*
|
|
977
1183
|
* Usage in bootstrap (fires on every request):
|
|
978
1184
|
* middlewares: [${l}()]
|
|
@@ -1008,7 +1214,7 @@ export interface ${V(t)}Options {
|
|
|
1008
1214
|
* first \`next()\` throws \`TypeError: next is not a function\`. Generate a
|
|
1009
1215
|
* guard instead (\`kick g guard\`) for the per-route, ctx-style shape.
|
|
1010
1216
|
*/
|
|
1011
|
-
export function ${l}(options: ${
|
|
1217
|
+
export function ${l}(options: ${U(t)}Options = {}) {
|
|
1012
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
|
|
1013
1219
|
// on every engine, but ${o} dependency to import types from. Under Fastify the handler
|
|
1014
1220
|
// receives \`request.raw\` / a reply driver, and under h3 the node objects, so
|
|
@@ -1021,7 +1227,7 @@ ${a?" // Typed from `express` because that is this project's runtime\n // (`ru
|
|
|
1021
1227
|
next()
|
|
1022
1228
|
}
|
|
1023
1229
|
}
|
|
1024
|
-
`),u.push(d),u}async function
|
|
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'
|
|
1025
1231
|
import type { RequestContext } from '@forinda/kickjs'
|
|
1026
1232
|
|
|
1027
1233
|
/**
|
|
@@ -1061,7 +1267,7 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
|
|
|
1061
1267
|
ctx.problem.unauthorized({ detail: 'Invalid or expired token' })
|
|
1062
1268
|
}
|
|
1063
1269
|
}
|
|
1064
|
-
`),l.push(u),l}function
|
|
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(`
|
|
1065
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.
|
|
1066
1272
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
1067
1273
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
@@ -1112,7 +1318,7 @@ ${_}
|
|
|
1112
1318
|
throw new Error("${s} contributor: resolve() not implemented")
|
|
1113
1319
|
},
|
|
1114
1320
|
})
|
|
1115
|
-
`,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'
|
|
1116
1322
|
|
|
1117
1323
|
@Service()
|
|
1118
1324
|
export class ${s}Service {
|
|
@@ -1121,7 +1327,7 @@ export class ${s}Service {
|
|
|
1121
1327
|
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1122
1328
|
// ) {}
|
|
1123
1329
|
}
|
|
1124
|
-
`),c.push(l),c}async function
|
|
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'
|
|
1125
1331
|
|
|
1126
1332
|
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1127
1333
|
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
@@ -1134,6 +1340,7 @@ export class ${s}Service {
|
|
|
1134
1340
|
//
|
|
1135
1341
|
// The bodies below are placeholders: wire them to a service or repository.
|
|
1136
1342
|
|
|
1343
|
+
// Require a signed-in user for these routes: https://kickjs.app/guide/authentication
|
|
1137
1344
|
@Controller()
|
|
1138
1345
|
export class ${s}Controller {
|
|
1139
1346
|
// @Autowired() private readonly myService!: MyService
|
|
@@ -1153,7 +1360,7 @@ export class ${s}Controller {
|
|
|
1153
1360
|
return reply.created({ data: ctx.body })
|
|
1154
1361
|
}
|
|
1155
1362
|
|
|
1156
|
-
@
|
|
1363
|
+
@Patch('/:id')
|
|
1157
1364
|
async update(ctx: Ctx<KickRoutes.${s}Controller['update']>) {
|
|
1158
1365
|
return { id: ctx.params.id, data: ctx.body }
|
|
1159
1366
|
}
|
|
@@ -1163,19 +1370,19 @@ export class ${s}Controller {
|
|
|
1163
1370
|
return reply.noContent()
|
|
1164
1371
|
}
|
|
1165
1372
|
}
|
|
1166
|
-
`),c.push(l),c}async function
|
|
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}
|
|
1167
1374
|
|
|
1168
|
-
export const ${c}Schema = ${
|
|
1375
|
+
export const ${c}Schema = ${Et(l,`// Define your schema fields here\n name: ${u.required}`)}
|
|
1169
1376
|
|
|
1170
1377
|
export type ${s}DTO = ${u.infer(`${c}Schema`)}
|
|
1171
|
-
`),d.push(f),d}async function
|
|
1172
|
-
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'
|
|
1173
1380
|
|
|
1174
1381
|
export default defineConfig({
|
|
1175
1382
|
modules: {
|
|
1176
1383
|
dir: '${n}',
|
|
1177
1384
|
repo: '${r}',
|
|
1178
|
-
pluralize:
|
|
1385
|
+
pluralize: false,
|
|
1179
1386
|
},
|
|
1180
1387
|
|
|
1181
1388
|
typegen: {
|
|
@@ -1212,18 +1419,18 @@ export default defineConfig({
|
|
|
1212
1419
|
},
|
|
1213
1420
|
],
|
|
1214
1421
|
})
|
|
1215
|
-
`),[t])}function
|
|
1422
|
+
`),[t])}function cn(e,t){if(e[t]!==`{`)return-1;let n=1;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`{`)n++;else if(t===`}`&&(n--,n===0))return r}return-1}function ln(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=cn(e,r);return i===-1?null:e.slice(r+1,i)}function un(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
1216
1423
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
1217
|
-
`)}function
|
|
1424
|
+
`)}function dn(e){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,t)=>{let n=t.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`Container`&&e!==`type Container`&&e!==`type AppModule`&&e!==`AppModule`&&e!==`type ModuleRoutes`&&e!==`ModuleRoutes`);return n.includes(`defineModule`)||n.push(`defineModule`),`import { ${n.join(`, `)} } from '@forinda/kickjs'`})}function fn(e,t){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,n)=>{let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`defineModule`);return t.container&&!r.includes(`Container`)&&r.push(`Container`),t.appModule&&!r.some(e=>e===`AppModule`||e===`type AppModule`)&&r.push(`type AppModule`),t.moduleRoutes&&!r.some(e=>e===`ModuleRoutes`||e===`type ModuleRoutes`)&&r.push(`type ModuleRoutes`),t.contributorRegistrations&&!r.some(e=>e===`ContributorRegistrations`||e===`type ContributorRegistrations`)&&r.push(`type ContributorRegistrations`),`import { ${r.join(`, `)} } from '@forinda/kickjs'`})}function pn(e){if(/\bdefineModule\s*\(/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+class\s+(\w+Module)\s+implements\s+AppModule\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no class form detected`};if(t.length>1)return{migrated:null,reason:`multiple module classes in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=cn(e,i);if(a===-1)return{migrated:null,reason:`unbalanced class braces`};let o=e.slice(i+1,a),s=e.slice(0,n.index),c=e.slice(a+1),l=ln(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=ln(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=ln(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=dn(s),p=``;return l&&(p+=` register(container) {${un(l,4,6)} },\n\n`),u&&(p+=` contributors() {${un(u,4,6)} },\n\n`),p+=` routes() {${un(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
1218
1425
|
name: '${r}',
|
|
1219
1426
|
build: () => ({
|
|
1220
1427
|
${p}
|
|
1221
1428
|
}),
|
|
1222
|
-
})`}${c}`}}function
|
|
1223
|
-
`||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=
|
|
1429
|
+
})`}${c}`}}function mn(e){if(/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+const\s+(\w+Module)\s*=\s*defineModule\s*\(\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no defineModule form detected`};if(t.length>1)return{migrated:null,reason:`multiple defineModule blocks in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=cn(e,i);if(a===-1)return{migrated:null,reason:`unbalanced defineModule braces`};let o=e.indexOf(`)`,a);if(o===-1)return{migrated:null,reason:`unbalanced defineModule call parens`};let s=e.slice(i+1,a),c=e.slice(0,n.index),l=o+1;for(;l<e.length&&(e[l]===`
|
|
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 {
|
|
1224
1431
|
${y}
|
|
1225
1432
|
}
|
|
1226
|
-
`}${u}`}}function
|
|
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'
|
|
1227
1434
|
|
|
1228
1435
|
export const create${e}Schema = z.object({
|
|
1229
1436
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -1231,7 +1438,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
|
|
|
1231
1438
|
})
|
|
1232
1439
|
|
|
1233
1440
|
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
1234
|
-
`}function
|
|
1441
|
+
`}function En(e,t){return`import { z } from 'zod'
|
|
1235
1442
|
|
|
1236
1443
|
export const update${e}Schema = z.object({
|
|
1237
1444
|
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
@@ -1239,17 +1446,17 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
|
1239
1446
|
})
|
|
1240
1447
|
|
|
1241
1448
|
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
1242
|
-
`}function
|
|
1449
|
+
`}function Dn(e,t){return`export interface ${e}ResponseDTO {
|
|
1243
1450
|
id: string
|
|
1244
1451
|
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
1245
1452
|
`)}
|
|
1246
1453
|
createdAt: string
|
|
1247
1454
|
updatedAt: string
|
|
1248
1455
|
}
|
|
1249
|
-
`}async function
|
|
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}'
|
|
1250
1457
|
import { Container } from '@forinda/kickjs'
|
|
1251
1458
|
|
|
1252
|
-
describe('${
|
|
1459
|
+
describe('${s}', () => {
|
|
1253
1460
|
beforeEach(() => {
|
|
1254
1461
|
Container.reset()
|
|
1255
1462
|
})
|
|
@@ -1269,53 +1476,53 @@ describe('${o}', () => {
|
|
|
1269
1476
|
expect(true).toBe(true)
|
|
1270
1477
|
})
|
|
1271
1478
|
})
|
|
1272
|
-
`),
|
|
1273
|
-
`);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
|
|
1274
|
-
(dry run — no files were written)`),console.log()}async function
|
|
1275
|
-
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),
|
|
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
|
+
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(`
|
|
1276
1483
|
Built-in generators:
|
|
1277
|
-
`);let e=Math.max(...
|
|
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(`
|
|
1278
1485
|
Plugin generators:
|
|
1279
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(`
|
|
1280
1487
|
Failed to load:
|
|
1281
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}function
|
|
1282
|
-
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=
|
|
1283
|
-
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)
|
|
1284
1491
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1285
1492
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
1286
|
-
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=
|
|
1287
|
-
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=
|
|
1288
|
-
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=
|
|
1289
|
-
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=
|
|
1290
|
-
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
|
|
1291
1498
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1292
1499
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
1293
1500
|
Optional: append :optional (shell-safe): description:text:optional
|
|
1294
|
-
or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use
|
|
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(`
|
|
1295
1502
|
Error: At least one field is required.
|
|
1296
1503
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1297
1504
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1298
1505
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
1299
|
-
`),process.exit(1));let o=await
|
|
1300
|
-
`,u=``;
|
|
1301
|
-
`)){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(`
|
|
1302
1509
|
`):`${n.slice(0,t).join(`
|
|
1303
|
-
`)}\n… ${n.length-t} more line(s)`}function
|
|
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(`
|
|
1304
1511
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
1305
|
-
`),
|
|
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(`
|
|
1306
1513
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1307
1514
|
Building for production...
|
|
1308
|
-
`);let{createRequire:e}=await import(`node:module`),t=e(
|
|
1309
|
-
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(`
|
|
1310
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(`
|
|
1311
1518
|
Build complete.
|
|
1312
|
-
`)}),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(`
|
|
1313
1520
|
Building asset map...`);try{await je(e,{cwd:process.cwd()}),console.log(`
|
|
1314
1521
|
Asset build complete.
|
|
1315
|
-
`)}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=
|
|
1316
|
-
No type-checker found. Install one in this project:\n ${
|
|
1317
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function
|
|
1318
|
-
`))})}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
|
|
1319
1526
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
1320
1527
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
1321
1528
|
directly — so that import does not run and ConfigService falls back to
|
|
@@ -1339,7 +1546,7 @@ import { modules } from './modules'
|
|
|
1339
1546
|
import './config' // ← add this — registers env schema
|
|
1340
1547
|
import { bootstrap } from '@forinda/kickjs'
|
|
1341
1548
|
import { modules } from './modules'
|
|
1342
|
-
`,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.
|
|
1343
1550
|
When vitest re-imports your modules across tests, the same class can be
|
|
1344
1551
|
registered twice and the container throws. The fix is to wipe the
|
|
1345
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'
|
|
@@ -1349,7 +1556,7 @@ describe('UserController', () => {
|
|
|
1349
1556
|
beforeEach(() => Container.reset())
|
|
1350
1557
|
|
|
1351
1558
|
it('does the thing', async () => { /* ... */ })
|
|
1352
|
-
})`,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
|
|
1353
1560
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
1354
1561
|
returns the controller wiring. This was a deliberate choice — modules
|
|
1355
1562
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -1376,7 +1583,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
|
1376
1583
|
and matches the actual class names so refactors propagate via
|
|
1377
1584
|
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
1378
1585
|
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
1379
|
-
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
|
|
1380
1587
|
cluster: { workers: N }, the framework forks N workers, each of which
|
|
1381
1588
|
spins up its own Vite instance on a separate port. The fix landed in
|
|
1382
1589
|
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
@@ -1384,7 +1591,7 @@ silently skips cluster, with a warning. If you see this on an older
|
|
|
1384
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({
|
|
1385
1592
|
modules,
|
|
1386
1593
|
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
1387
|
-
})`,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
|
|
1388
1595
|
reflect-metadata polyfill. The polyfill must be imported once,
|
|
1389
1596
|
before any decorator runs. Most projects do this at the top of
|
|
1390
1597
|
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
@@ -1393,7 +1600,7 @@ import './config'
|
|
|
1393
1600
|
import { bootstrap } from '@forinda/kickjs'
|
|
1394
1601
|
import { modules } from './modules'
|
|
1395
1602
|
|
|
1396
|
-
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
|
|
1397
1604
|
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
1398
1605
|
the most likely cause is that the module is missing from the exported
|
|
1399
1606
|
array. The CLI usually wires this automatically, but a hand-edit can
|
|
@@ -1401,7 +1608,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
1401
1608
|
import { UserModule } from './users/user.module'
|
|
1402
1609
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
1403
1610
|
|
|
1404
|
-
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\`.
|
|
1405
1612
|
That protects the vars your test runner pinned — but every var it did NOT
|
|
1406
1613
|
pin is silently backfilled from your \`.env\`. So a suite can pin its database
|
|
1407
1614
|
URL and still reach live development services through the vars it forgot,
|
|
@@ -1435,7 +1642,7 @@ beforeAll(() => {
|
|
|
1435
1642
|
vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
|
|
1436
1643
|
resetEnvCache()
|
|
1437
1644
|
loadEnv(envSchema)
|
|
1438
|
-
})`,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
|
|
1439
1646
|
the first time the container resolves it. A REQUEST-scoped binding is the
|
|
1440
1647
|
opposite — one instance per request, discarded when the response ends.
|
|
1441
1648
|
|
|
@@ -1456,7 +1663,7 @@ and the singleton never captures one.
|
|
|
1456
1663
|
|
|
1457
1664
|
If the dependency did not need request scope in the first place, the
|
|
1458
1665
|
other direction also works — make it SINGLETON and pass the per-request
|
|
1459
|
-
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
|
|
1460
1667
|
is requested while it is already being resolved further up the stack, the
|
|
1461
1668
|
graph has a cycle and there is no order that satisfies both ends.
|
|
1462
1669
|
|
|
@@ -1488,7 +1695,7 @@ export class OrderService {
|
|
|
1488
1695
|
@Service()
|
|
1489
1696
|
export class BillingService {
|
|
1490
1697
|
@Autowired() private readonly orders!: OrderService // ← resolved after construction
|
|
1491
|
-
}`,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 —
|
|
1492
1699
|
and a class is only loaded if something imports it. A module that is not
|
|
1493
1700
|
in the bootstrap array is never imported, so none of its @Service /
|
|
1494
1701
|
@Repository / @Controller classes ever register, and the first thing that
|
|
@@ -1514,7 +1721,7 @@ export const TenantModule = defineModule({
|
|
|
1514
1721
|
},
|
|
1515
1722
|
routes: () => null,
|
|
1516
1723
|
}),
|
|
1517
|
-
})`,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
|
|
1518
1725
|
and reads \`app\` off it, then hands each request to that instance.
|
|
1519
1726
|
|
|
1520
1727
|
When the entry runs \`await bootstrap(...)\` without assigning the result to
|
|
@@ -1530,23 +1737,23 @@ import { bootstrap } from '@forinda/kickjs'
|
|
|
1530
1737
|
await bootstrap({ modules }) // ← nothing for the dev server to read`,codeAfter:`import './env'
|
|
1531
1738
|
import { bootstrap } from '@forinda/kickjs'
|
|
1532
1739
|
|
|
1533
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function
|
|
1740
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/project-structure.html`}}}}];function wr(e,t){let n=null;for(let r of Cr){let i=null;try{i=r.match(e,t)}catch{continue}!i||i.confidence<40||(!n||i.confidence>n.confidence)&&(n=i)}return n}async function Tr(e){let t=e.provider??`openai`,n=process.env.OPENAI_API_KEY;if(t===`openai`&&!n)return{kind:`unavailable`,reason:`OPENAI_API_KEY environment variable is not set`,suggestion:`Set OPENAI_API_KEY in your shell, e.g.
|
|
1534
1741
|
export OPENAI_API_KEY="sk-..."
|
|
1535
1742
|
|
|
1536
1743
|
Then re-run \`kick explain --ai "<your error>"\`.`};let r;try{r=await import(`@forinda/kickjs-ai`)}catch{return{kind:`unavailable`,reason:`@forinda/kickjs-ai is not installed`,suggestion:`Install the AI package to enable the LLM fallback:
|
|
1537
1744
|
kick add ai
|
|
1538
1745
|
|
|
1539
1746
|
Or manually:
|
|
1540
|
-
${
|
|
1541
|
-
`)}function
|
|
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
|
+
`)}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.
|
|
1542
1749
|
|
|
1543
1750
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
1544
1751
|
kick explain "config.get returned undefined"
|
|
1545
|
-
${
|
|
1546
|
-
`);return}if(i){
|
|
1547
|
-
`),process.exit(2)),
|
|
1548
|
-
`),process.exit(a.kind===`ok`?0:2)),
|
|
1549
|
-
`)}function
|
|
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
|
+
`);return}if(i){Lr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
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=>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
|
+
`)}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:
|
|
1550
1757
|
|
|
1551
1758
|
1. Check the framework docs for the error keywords:
|
|
1552
1759
|
https://kickjs.app/
|
|
@@ -1558,10 +1765,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1558
1765
|
3. File an issue with the error text:
|
|
1559
1766
|
https://github.com/forinda/kick-js/issues/new
|
|
1560
1767
|
|
|
1561
|
-
`)}function
|
|
1768
|
+
`)}function zr(e,t){return e.split(`
|
|
1562
1769
|
`).map(e=>`${t}${e}`).join(`
|
|
1563
|
-
`)}function
|
|
1564
|
-
`,`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
|
|
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`
|
|
1565
1772
|
import 'reflect-metadata'
|
|
1566
1773
|
|
|
1567
1774
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -1586,7 +1793,7 @@ try {
|
|
|
1586
1793
|
|
|
1587
1794
|
// Load entry to trigger decorator registration
|
|
1588
1795
|
try {
|
|
1589
|
-
await import('${
|
|
1796
|
+
await import('${V(e).href}')
|
|
1590
1797
|
} catch (err) {
|
|
1591
1798
|
console.warn(' Warning: ' + err.message)
|
|
1592
1799
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -1615,56 +1822,56 @@ server.on('exit', () => {
|
|
|
1615
1822
|
console.log('\\n Goodbye!\\n')
|
|
1616
1823
|
process.exit(0)
|
|
1617
1824
|
})
|
|
1618
|
-
`}function
|
|
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]!==`
|
|
1619
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]===`
|
|
1620
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t}else i=s+1}return{content:a,changed:r}}function
|
|
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(`
|
|
1621
1828
|
Cancelled.
|
|
1622
|
-
`);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,`
|
|
1623
1830
|
|
|
1624
|
-
`),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(`
|
|
1625
1832
|
Registered typegen plugins:
|
|
1626
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(`
|
|
1627
1834
|
Disable one in kick.config.ts:
|
|
1628
1835
|
`),console.log(` typegen: { disable: ['`+(r.typegens[0]?.id??`kick/x`)+`'] }
|
|
1629
|
-
`);return}let r
|
|
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(`
|
|
1630
1837
|
`+e.message+`
|
|
1631
|
-
`):e instanceof
|
|
1838
|
+
`):e instanceof An?console.error(`
|
|
1632
1839
|
`+e.message+`
|
|
1633
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}const
|
|
1634
|
-
`).length:1}function
|
|
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`&&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(`
|
|
1635
1842
|
Usage: kick check [--deploy] [--di]
|
|
1636
1843
|
|
|
1637
1844
|
Available checks:
|
|
1638
1845
|
--deploy Audit for production readiness (security, config, best practices)
|
|
1639
1846
|
--di Find REQUEST-scoped dependencies injected into singleton constructors
|
|
1640
|
-
`);return}let t=process.cwd();
|
|
1641
|
-
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function
|
|
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
|
|
1642
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
|
|
1643
1850
|
development env — including DATABASE_URL and any third-party credentials.
|
|
1644
1851
|
|
|
1645
1852
|
Create .env.test (cp .env.test.example .env.test, if the project has one)
|
|
1646
1853
|
holding the whole environment the suite should run against
|
|
1647
1854
|
(a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
|
|
1648
|
-
and supply env from the test runner.`}}const
|
|
1649
|
-
`).map(e=>` ${
|
|
1650
|
-
`)}function
|
|
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
|
|
1651
1858
|
# sections. Re-run it after changing them; \`kick env example --check\` fails when stale.
|
|
1652
1859
|
#
|
|
1653
1860
|
# Uncommented variables are required. Commented ones are optional; the value shown
|
|
1654
|
-
# is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...
|
|
1655
|
-
`));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...
|
|
1861
|
+
# is the default. Any variable can come from a file instead: NAME_FILE=/run/secrets/name`];e.env.length>0&&t.push([`# ── App env schema ──`,...aa(e.env)].join(`
|
|
1862
|
+
`));for(let n of e.sections)t.push([`# ── ${n.prefix} settings (declared by ${n.declaredBy}) ──`,...aa(n.vars)].join(`
|
|
1656
1863
|
`));return`${t.join(`
|
|
1657
1864
|
|
|
1658
|
-
`)}\n`}async function
|
|
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.
|
|
1659
1866
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
1660
1867
|
--target define|class Override the migration direction.
|
|
1661
1868
|
--apply Apply the changes (default: dry-run preview).
|
|
1662
|
-
--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=
|
|
1663
|
-
`+
|
|
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.
|
|
1664
1871
|
The regex-based rewrite handles the shapes our templates produce.
|
|
1665
1872
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
1666
1873
|
Always commit before running with --apply.
|
|
1667
|
-
`),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'
|
|
1668
1875
|
import { handler } from '${e}'
|
|
1669
1876
|
|
|
1670
1877
|
// Where the app's build files were packaged; the platform starts this
|
|
@@ -1678,7 +1885,7 @@ export const config = {
|
|
|
1678
1885
|
${r.join(`
|
|
1679
1886
|
`)}
|
|
1680
1887
|
}
|
|
1681
|
-
`}function
|
|
1888
|
+
`}function ha(){return`import { fileURLToPath } from 'node:url'
|
|
1682
1889
|
import { handler } from './server.mjs'
|
|
1683
1890
|
|
|
1684
1891
|
// The app's build files are copied into this function at their project
|
|
@@ -1688,11 +1895,11 @@ process.env.KICK_APP_ROOT ??= fileURLToPath(new URL('./', import.meta.url))
|
|
|
1688
1895
|
const requestContext = () => globalThis[Symbol.for('@vercel/request-context')]?.get?.()
|
|
1689
1896
|
|
|
1690
1897
|
export default (req, res) => handler.node(req, res, requestContext())
|
|
1691
|
-
`}function
|
|
1692
|
-
`).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
|
|
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=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(`
|
|
1693
1900
|
`)?`
|
|
1694
1901
|
`:``}${i.join(`
|
|
1695
|
-
`)}\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}
|
|
1696
1903
|
// (no routes discovered yet — annotate a controller method with
|
|
1697
1904
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1698
1905
|
declare global {
|
|
@@ -1709,19 +1916,19 @@ declare global {
|
|
|
1709
1916
|
|
|
1710
1917
|
/** Empty until the first route exists — see kick typegen. */
|
|
1711
1918
|
export const kickRpc = {} as const
|
|
1712
|
-
`;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=
|
|
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(`
|
|
1713
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(`
|
|
1714
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(`
|
|
1715
|
-
`));let h=[],g=/* @__PURE__ */ new Set;for(let[e,t]of i){let n=
|
|
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(`
|
|
1716
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(`
|
|
1717
|
-
`),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=
|
|
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(`
|
|
1718
1925
|
`)+`
|
|
1719
|
-
`:``,
|
|
1720
|
-
`);return`${
|
|
1926
|
+
`:``,x=za(a)+b,S=l.join(`
|
|
1927
|
+
`);return`${Na}${x}
|
|
1721
1928
|
declare global {
|
|
1722
1929
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
1723
1930
|
namespace KickRoutes {
|
|
1724
|
-
${
|
|
1931
|
+
${S}
|
|
1725
1932
|
}
|
|
1726
1933
|
|
|
1727
1934
|
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
@@ -1729,18 +1936,18 @@ ${x}
|
|
|
1729
1936
|
}
|
|
1730
1937
|
|
|
1731
1938
|
${_}
|
|
1732
|
-
`}function
|
|
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(`
|
|
1733
1940
|
`)+`
|
|
1734
|
-
`}function
|
|
1735
|
-
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 '${
|
|
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=`
|
|
1736
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===`
|
|
1737
1944
|
`?`
|
|
1738
|
-
`: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
|
|
1739
|
-
`));for(let n of
|
|
1740
|
-
`);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
|
|
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=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
|
+
`);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(`
|
|
1741
1948
|
`)+`
|
|
1742
|
-
`}function
|
|
1743
|
-
`))}},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:[...
|
|
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 */
|
|
1744
1951
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1745
1952
|
//
|
|
1746
1953
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
@@ -1754,7 +1961,7 @@ ${_}
|
|
|
1754
1961
|
//
|
|
1755
1962
|
// Written when \`kick dev\` starts, not on save — resolving these types builds a
|
|
1756
1963
|
// full TypeScript program over the server. Re-run \`kick typegen\`.
|
|
1757
|
-
`;function
|
|
1964
|
+
`;function fo(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${uo}
|
|
1758
1965
|
// (no routes discovered yet — annotate a controller method with
|
|
1759
1966
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1760
1967
|
interface Api {}
|
|
@@ -1771,7 +1978,7 @@ export type { Api }
|
|
|
1771
1978
|
|
|
1772
1979
|
`)+`
|
|
1773
1980
|
|
|
1774
|
-
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${
|
|
1981
|
+
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${uo}
|
|
1775
1982
|
${r}interface Api {
|
|
1776
1983
|
${i.join(`
|
|
1777
1984
|
`)}
|
|
@@ -1785,7 +1992,7 @@ declare global {
|
|
|
1785
1992
|
}
|
|
1786
1993
|
|
|
1787
1994
|
export type { Api }
|
|
1788
|
-
`}const
|
|
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 */
|
|
1789
1996
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1790
1997
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1791
1998
|
|
|
@@ -1823,5 +2030,5 @@ declare global {
|
|
|
1823
2030
|
}
|
|
1824
2031
|
|
|
1825
2032
|
export {}
|
|
1826
|
-
`}const
|
|
1827
|
-
`)}});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};
|