@forinda/kickjs-cli 5.4.0 → 5.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/{builtins-K-nRJcJG.mjs → builtins-CB0cpCRy.mjs} +207 -190
  2. package/dist/{builtins-DBzZkJey.mjs → builtins-DNnIUbGs.mjs} +101 -99
  3. package/dist/builtins-DNnIUbGs.mjs.map +1 -0
  4. package/dist/cli.mjs +2 -2
  5. package/dist/{config-CCNnXhar.mjs → config-CAjDTnMg.mjs} +2 -2
  6. package/dist/{config-CQZ6Hppr.mjs → config-f_GHcOYT.mjs} +3 -3
  7. package/dist/{config-CQZ6Hppr.mjs.map → config-f_GHcOYT.mjs.map} +1 -1
  8. package/dist/{generator-extension-Bn2aH7kY.mjs → generator-extension-Ds2fzYZS.mjs} +99 -84
  9. package/dist/generator-extension-Ds2fzYZS.mjs.map +1 -0
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +2 -2
  12. package/dist/{plugin-DasN_2Zr.mjs → plugin-CiWyeMpX.mjs} +3 -3
  13. package/dist/{plugin-DasN_2Zr.mjs.map → plugin-CiWyeMpX.mjs.map} +1 -1
  14. package/dist/{plugin-D0C4ISZA.mjs → plugin-Dz0Yu4Ow.mjs} +2 -2
  15. package/dist/{rolldown-runtime-BTpMa50s.mjs → rolldown-runtime-iJll81ez.mjs} +1 -1
  16. package/dist/{run-plugins-Dk7KBKON.mjs → run-plugins-DBOc1G96.mjs} +2 -2
  17. package/dist/typegen-COBqEd4w.mjs +116 -0
  18. package/dist/typegen-DzmDwZvN.mjs +117 -0
  19. package/dist/typegen-DzmDwZvN.mjs.map +1 -0
  20. package/dist/{types-kAfWJgh0.mjs → types-DucsCMzP.mjs} +2 -2
  21. package/dist/{types-kAfWJgh0.mjs.map → types-DucsCMzP.mjs.map} +1 -1
  22. package/package.json +1 -1
  23. package/dist/builtins-DBzZkJey.mjs.map +0 -1
  24. package/dist/generator-extension-Bn2aH7kY.mjs.map +0 -1
  25. package/dist/typegen-Bl9kUVNL.mjs +0 -115
  26. package/dist/typegen-Bl9kUVNL.mjs.map +0 -1
  27. package/dist/typegen-DDQJNnUl.mjs +0 -114
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v5.4.0
2
+ * @forinda/kickjs-cli v5.4.2
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,14 +8,14 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{A as e,C as t,D as n,E as r,F as i,M as a,N as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,h as v,j as y,k as b,l as ee,m as te,n as ne,o as re,p as ie,s as ae,t as oe,u as se,v as ce,w as x,x as S,y as le}from"./generator-extension-Bn2aH7kY.mjs";import{a as C,i as w,o as ue,t as de}from"./config-CQZ6Hppr.mjs";import{n as T}from"./types-kAfWJgh0.mjs";import{n as fe}from"./plugin-DasN_2Zr.mjs";import{a as pe,i as me,o as he,r as ge,s as _e,t as E}from"./typegen-Bl9kUVNL.mjs";import D,{basename as ve,dirname as O,isAbsolute as ye,join as k,relative as A,resolve as j,sep as be}from"node:path";import{cpSync as xe,existsSync as M,mkdirSync as N,readFileSync as P,readdirSync as Se,rmSync as Ce,statSync as we,writeFileSync as Te}from"node:fs";import{copyFile as Ee,mkdir as De,readFile as F,readdir as Oe,rm as ke,stat as Ae,writeFile as I}from"node:fs/promises";import{execSync as je,fork as Me,spawn as Ne,spawnSync as Pe}from"node:child_process";import{pathToFileURL as L}from"node:url";import{glob as Fe}from"glob";import{groupAssetKeys as Ie}from"@forinda/kickjs";import{arch as Le,platform as Re,release as ze}from"node:os";import{generate as Be,migrateDown as Ve,migrateLatest as He,migrateRollback as Ue,migrateStatus as We,migrateUp as Ge,renderSchemaSource as Ke,resolveDbConfig as qe}from"@forinda/kickjs-db";const Je={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},"db-pg":{pkg:`@forinda/kickjs-db-pg`,peers:[`pg`],description:`kick/db PostgreSQL dialect + adapter (pgDialect, pgAdapter)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},auth:{pkg:`@forinda/kickjs-auth`,peers:[`jsonwebtoken`],description:`Authentication — JWT, API key, and custom strategies`},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},mcp:{pkg:`@forinda/kickjs-mcp`,peers:[`@modelcontextprotocol/sdk`],description:`Model Context Protocol server — expose @Controller endpoints as AI tools`},testing:{pkg:`@forinda/kickjs-testing`,peers:[],description:`Test utilities and TestModule builder`,dev:!0}};function R(e,t=process.cwd()){let n=t;for(;;){if(M(j(n,e)))return n;let t=O(n);if(t===n)return null;n=t}}function Ye(){return R(`pnpm-lock.yaml`)?`pnpm`:R(`yarn.lock`)?`yarn`:R(`bun.lockb`)||R(`bun.lock`)?`bun`:R(`package-lock.json`)?`npm`:null}function Xe(){let e=process.cwd();for(;e;){let t=j(e,`package.json`);if(M(t))try{let e=JSON.parse(P(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(de.includes(t))return t}}catch{}let n=O(e);if(n===e)return null;e=n}return null}async function Ze(e){if(e&&de.includes(e))return{pm:e,source:`flag`};let t=await w(process.cwd());if(t?.packageManager&&de.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=Xe();if(n)return{pm:n,source:`package.json`};let r=Ye();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function Qe(e){let{pm:t}=await Ze(e);return t}function $e(e=!1){let t=Object.entries(Je),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``;return` ${r} ${t.description}${i}`};console.log(`
11
+ import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as ee,f as v,g as y,h as te,j as ne,k as b,l as re,m as ie,n as ae,o as oe,p as se,s as ce,t as le,u as ue,v as de,w as x,x as fe,y as S}from"./generator-extension-Ds2fzYZS.mjs";import{a as C,i as w,o as pe,t as me}from"./config-f_GHcOYT.mjs";import{n as T}from"./types-DucsCMzP.mjs";import{n as he}from"./plugin-CiWyeMpX.mjs";import{a as ge,c as _e,i as ve,n as ye,o as be,s as xe,t as E}from"./typegen-DzmDwZvN.mjs";import D,{basename as Se,dirname as O,isAbsolute as Ce,join as k,relative as A,resolve as j,sep as we}from"node:path";import{cpSync as Te,existsSync as M,mkdirSync as N,readFileSync as P,readdirSync as Ee,rmSync as De,statSync as Oe,writeFileSync as ke}from"node:fs";import{copyFile as Ae,mkdir as je,readFile as F,readdir as Me,rm as Ne,stat as Pe,writeFile as I}from"node:fs/promises";import{execSync as Fe,fork as Ie,spawn as Le,spawnSync as Re}from"node:child_process";import{pathToFileURL as L}from"node:url";import{glob as ze}from"glob";import{groupAssetKeys as Be}from"@forinda/kickjs";import{arch as Ve,platform as He,release as Ue}from"node:os";import{generate as We,migrateDown as Ge,migrateLatest as Ke,migrateRollback as qe,migrateStatus as Je,migrateUp as Ye,renderSchemaSource as Xe,resolveDbConfig as Ze}from"@forinda/kickjs-db";const Qe={kickjs:{pkg:`@forinda/kickjs`,peers:[`express`],description:`Unified framework: DI, decorators, routing, middleware`,core:!0},vite:{pkg:`@forinda/kickjs-vite`,peers:[`vite`],description:`Vite plugin: dev server, HMR, module discovery`,dev:!0,core:!0},cli:{pkg:`@forinda/kickjs-cli`,peers:[],description:`CLI tool and code generators`,dev:!0,core:!0},swagger:{pkg:`@forinda/kickjs-swagger`,peers:[],description:`OpenAPI spec + Swagger UI + ReDoc`},db:{pkg:`@forinda/kickjs-db`,peers:[],description:`kick/db core — schema DSL, migrations, KickDbClient, customType`},"db-pg":{pkg:`@forinda/kickjs-db-pg`,peers:[`pg`],description:`kick/db PostgreSQL dialect + adapter (pgDialect, pgAdapter)`},drizzle:{pkg:`@forinda/kickjs-drizzle`,peers:[`drizzle-orm`],description:`Drizzle ORM adapter + query builder`},prisma:{pkg:`@forinda/kickjs-prisma`,peers:[`@prisma/client`],description:`Prisma adapter + query builder`},ws:{pkg:`@forinda/kickjs-ws`,peers:[`socket.io`],description:`WebSocket with @WsController decorators`},devtools:{pkg:`@forinda/kickjs-devtools`,peers:[],description:`Development dashboard — routes, DI, metrics, health`,dev:!0},auth:{pkg:`@forinda/kickjs-auth`,peers:[`jsonwebtoken`],description:`Authentication — JWT, API key, and custom strategies`},queue:{pkg:`@forinda/kickjs-queue`,peers:[],description:`Queue adapter (BullMQ/RabbitMQ/Kafka)`},"queue:bullmq":{pkg:`@forinda/kickjs-queue`,peers:[`bullmq`,`ioredis`],description:`Queue with BullMQ + Redis`},"queue:rabbitmq":{pkg:`@forinda/kickjs-queue`,peers:[`amqplib`],description:`Queue with RabbitMQ`},"queue:kafka":{pkg:`@forinda/kickjs-queue`,peers:[`kafkajs`],description:`Queue with Kafka`},mcp:{pkg:`@forinda/kickjs-mcp`,peers:[`@modelcontextprotocol/sdk`],description:`Model Context Protocol server — expose @Controller endpoints as AI tools`},testing:{pkg:`@forinda/kickjs-testing`,peers:[],description:`Test utilities and TestModule builder`,dev:!0}};function R(e,t=process.cwd()){let n=t;for(;;){if(M(j(n,e)))return n;let t=O(n);if(t===n)return null;n=t}}function $e(){return R(`pnpm-lock.yaml`)?`pnpm`:R(`yarn.lock`)?`yarn`:R(`bun.lockb`)||R(`bun.lock`)?`bun`:R(`package-lock.json`)?`npm`:null}function et(){let e=process.cwd();for(;e;){let t=j(e,`package.json`);if(M(t))try{let e=JSON.parse(P(t,`utf-8`)).packageManager;if(typeof e==`string`){let t=e.split(`@`)[0];if(me.includes(t))return t}}catch{}let n=O(e);if(n===e)return null;e=n}return null}async function tt(e){if(e&&me.includes(e))return{pm:e,source:`flag`};let t=await w(process.cwd());if(t?.packageManager&&me.includes(t.packageManager))return{pm:t.packageManager,source:`config`};let n=et();if(n)return{pm:n,source:`package.json`};let r=$e();return r?{pm:r,source:`lockfile`}:{pm:`npm`,source:`default`}}async function nt(e){let{pm:t}=await tt(e);return t}function rt(e=!1){let t=Object.entries(Qe),n=Math.max(...t.map(([e])=>e.length)),r=t.filter(([,e])=>e.core),i=t.filter(([,e])=>!e.core),a=([e,t])=>{let r=e.padEnd(n+2),i=t.peers.length?` (+ ${t.peers.join(`, `)})`:``;return` ${r} ${t.description}${i}`};console.log(`
12
12
  Core packages (always installed by \`kick new\`):
13
13
  `);for(let e of r)console.log(a(e));if(e){console.log(`
14
14
  Optional packages (add as needed):
15
15
  `);for(let e of i)console.log(a(e))}else console.log(`\n Plus ${i.length} optional packages (auth, swagger, db, queue, …).`),console.log(" Run `kick add --list --all` for the full catalog.");console.log(`
16
- Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function et(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{$e(!!e.all)})}function tt(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){$e(!!t.all);return}let{pm:n,source:r}=await Ze(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=t.dev,a=new Set,o=new Set,s=[];for(let t of e){let e=Je[t];if(!e){s.push(t);continue}let n=i||e.dev?o:a;n.add(e.pkg);for(let t of e.peers)n.add(t)}if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
17
- `),a.size===0&&o.size===0))){if(a.size>0){let e=Array.from(a),t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{je(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.size>0){let e=Array.from(o),t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{je(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
18
- `)}})}const nt=[{value:`auth`,label:`Auth`,hint:`JWT, OAuth, API keys`},{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function rt(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 | ddd | cqrs | minimal`).option(`-r, --repo <type>`,`Default repository: prisma | drizzle | inmemory | custom`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).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,i)=>{t(`KickJS — Create a new project`);let a=!!(i.yes||i.nonInteractive);e||=a?`my-api`:await b({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let o;if(e===`.`?(o=j(`.`),e=ve(o)):o=j(i.directory||e),M(o)){let t=Se(o);if(t.length>0){if(i.force)x.warn(`Clearing existing files in ${o}`);else if(a){x.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{x.warn(`Directory "${e}" is not empty:`);let n=t.slice(0,5);for(let e of n)x.message(` - ${e}`);if(t.length>5&&x.message(` ... and ${t.length-5} more`),!await l({message:y.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of t)Ce(j(o,e),{recursive:!0,force:!0})}}let s=i.template;s||=a?`minimal`:await n({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`ddd`,label:`DDD`,hint:`Domain-Driven Design modules`},{value:`cqrs`,label:`CQRS`,hint:`Commands, Queries, Events + WS/Queue`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let c=i.pm;c||=a?await Qe(void 0):await n({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let d=i.repo;d||(a?d=`inmemory`:(d=await n({message:`Default repository/ORM`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle`},{value:`inmemory`,label:`In-Memory`},{value:`custom`,label:`Custom`,hint:`specify later`}]}),d===`custom`&&(d=await b({message:`Custom repository name`,defaultValue:`custom`}))));let p;if(i.packages!==void 0){let e=i.packages.trim().toLowerCase();p=e===``||e===`none`||e===`false`?[]:i.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else p=a?[]:await u({message:`Select packages to include`,options:[...nt],required:!1});let m;m=i.git===void 0?a?!0:await l({message:`Initialize git repository?`,initialValue:!0}):i.git;let h;h=i.install===void 0?a?!0:await l({message:`Install dependencies?`,initialValue:!0}):i.install,await f({name:e,directory:o,packageManager:c,initGit:m,installDeps:h,template:s,defaultRepo:d,packages:p}),r(`Done! Next steps: ${y.cyan(`cd ${e} && ${c} dev`)}`)})}async function it(e){let{name:t,outDir:n}=e,r=p(t),a=S(t),o=[],s=k(n,`${r}.plugin.ts`);return await i(s,`import {
16
+ Usage: kick add auth drizzle swagger`),console.log(` kick add queue:bullmq`),console.log()}function it(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{rt(!!e.all)})}function at(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){rt(!!t.all);return}let{pm:n,source:r}=await tt(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=t.dev,a=new Set,o=new Set,s=[];for(let t of e){let e=Qe[t];if(!e){s.push(t);continue}let n=i||e.dev?o:a;n.add(e.pkg);for(let t of e.peers)n.add(t)}if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
17
+ `),a.size===0&&o.size===0))){if(a.size>0){let e=Array.from(a),t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{Fe(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.size>0){let e=Array.from(o),t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{Fe(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
18
+ `)}})}const ot=[{value:`auth`,label:`Auth`,hint:`JWT, OAuth, API keys`},{value:`swagger`,label:`Swagger`,hint:`OpenAPI docs`},{value:`ws`,label:`WebSocket`,hint:`rooms, heartbeat`},{value:`queue`,label:`Queue`,hint:`BullMQ/RabbitMQ/Kafka`},{value:`devtools`,label:`DevTools`,hint:`debug dashboard`}];function st(t){t.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 | ddd | cqrs | minimal`).option(`-r, --repo <type>`,`Default repository: prisma | drizzle | inmemory | custom`).option(`--packages <packages>`,`Comma-separated packages to include (e.g. auth,swagger,ws,queue)`).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(t,i)=>{r(`KickJS — Create a new project`);let a=!!(i.yes||i.nonInteractive);t||=a?`my-api`:await s({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let o;if(t===`.`?(o=j(`.`),t=Se(o)):o=j(i.directory||t),M(o)){let e=Ee(o);if(e.length>0){if(i.force)n.warn(`Clearing existing files in ${o}`);else if(a){n.warn(`Directory "${t}" is not empty. Pass --force to clear it.`),b(`Aborted.`);return}else{n.warn(`Directory "${t}" is not empty:`);let r=e.slice(0,5);for(let e of r)n.message(` - ${e}`);if(e.length>5&&n.message(` ... and ${e.length-5} more`),!await p({message:u.red(`Remove all existing files and proceed?`),initialValue:!1})){b(`Aborted.`);return}}for(let t of e)De(j(o,t),{recursive:!0,force:!0})}}let c=i.template;c||=a?`minimal`:await e({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`ddd`,label:`DDD`,hint:`Domain-Driven Design modules`},{value:`cqrs`,label:`CQRS`,hint:`Commands, Queries, Events + WS/Queue`},{value:`minimal`,label:`Minimal`,hint:`bare Express`}]});let d=i.pm;d||=a?await nt(void 0):await e({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let f=i.repo;f||(a?f=`inmemory`:(f=await e({message:`Default repository/ORM`,options:[{value:`prisma`,label:`Prisma`},{value:`drizzle`,label:`Drizzle`},{value:`inmemory`,label:`In-Memory`},{value:`custom`,label:`Custom`,hint:`specify later`}]}),f===`custom`&&(f=await s({message:`Custom repository name`,defaultValue:`custom`}))));let m;if(i.packages!==void 0){let e=i.packages.trim().toLowerCase();m=e===``||e===`none`||e===`false`?[]:i.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else m=a?[]:await l({message:`Select packages to include`,options:[...ot],required:!1});let g;g=i.git===void 0?a?!0:await p({message:`Initialize git repository?`,initialValue:!0}):i.git;let _;_=i.install===void 0?a?!0:await p({message:`Install dependencies?`,initialValue:!0}):i.install,await h({name:t,directory:o,packageManager:d,initGit:g,installDeps:_,template:c,defaultRepo:f,packages:m}),b(`Done! Next steps: ${u.cyan(`cd ${t} && ${d} dev`)}`)})}async function ct(e){let{name:n,outDir:r}=e,i=t(n),a=x(n),o=[],s=k(r,`${i}.plugin.ts`);return await d(s,`import {
19
19
  definePlugin,
20
20
  type AppAdapter,
21
21
  type AppModuleEntry,
@@ -59,7 +59,7 @@ export interface ${a}PluginConfig {
59
59
  * @example
60
60
  * \`\`\`ts
61
61
  * import { bootstrap } from '@forinda/kickjs'
62
- * import { ${a}Plugin } from './plugins/${r}.plugin'
62
+ * import { ${a}Plugin } from './plugins/${i}.plugin'
63
63
  *
64
64
  * export const app = await bootstrap({
65
65
  * modules,
@@ -131,10 +131,10 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
131
131
  return [
132
132
  // Example:
133
133
  // import { defineHttpContextDecorator } from '@forinda/kickjs'
134
- // declare module '@forinda/kickjs' { interface ContextMeta { ${r}: { foo: string } } }
134
+ // declare module '@forinda/kickjs' { interface ContextMeta { ${i}: { foo: string } } }
135
135
  // const Load${a} = defineHttpContextDecorator({
136
- // key: '${r}',
137
- // resolve: (ctx) => ({ foo: ctx.req.headers['x-${r}'] as string }),
136
+ // key: '${i}',
137
+ // resolve: (ctx) => ({ foo: ctx.req.headers['x-${i}'] as string }),
138
138
  // })
139
139
  // return [Load${a}.registration]
140
140
  ]
@@ -159,8 +159,8 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
159
159
  },
160
160
  }),
161
161
  })
162
- `),o.push(s),o}async function at(e){let t=k(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return M(t)&&!e.force&&!await l({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
163
- Skipped — existing kick.config.ts preserved.`),[]):(await i(t,`import { defineConfig } from '@forinda/kickjs-cli'
162
+ `),o.push(s),o}async function lt(e){let t=k(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return M(t)&&!e.force&&!await p({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
163
+ Skipped — existing kick.config.ts preserved.`),[]):(await d(t,`import { defineConfig } from '@forinda/kickjs-cli'
164
164
 
165
165
  export default defineConfig({
166
166
  modules: {
@@ -197,18 +197,18 @@ export default defineConfig({
197
197
  },
198
198
  ],
199
199
  })
200
- `),[t])}const ot=new Set([`rest`,`ddd`,`cqrs`,`minimal`]);function st(e,t){if(t)return t;try{let t=JSON.parse(P(k(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function ct(e,t){if(t)return t;try{let t=JSON.parse(P(k(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function lt(e,t){if(t)return t;try{let t=(await w(e))?.pattern;if(t&&ot.has(t))return t}catch{}return`ddd`}async function ut(e){let t=e.only??`all`,n=st(e.outDir,e.name),r=ct(e.outDir,e.pm),a=await lt(e.outDir,e.template),o=t===`agents`||t===`both`||t===`all`,s=t===`claude`||t===`both`||t===`all`,c=t===`skills`||t===`all`,u=[];o&&u.push({file:k(e.outDir,`AGENTS.md`),render:()=>re(n,a,r)}),s&&u.push({file:k(e.outDir,`CLAUDE.md`),render:()=>ae(n,a,r)}),c&&u.push({file:k(e.outDir,`kickjs-skills.md`),render:()=>m(n,a,r)});let d=[];for(let{file:t,render:n}of u){if(M(t)&&!e.force&&!await l({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await i(t,n()),d.push(t)}return d}function z(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 B(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=z(e,r);return i===-1?null:e.slice(r+1,i)}function V(e,t,n){let r=` `.repeat(n);return e.split(`
200
+ `),[t])}const ut=new Set([`rest`,`ddd`,`cqrs`,`minimal`]);function dt(e,t){if(t)return t;try{let t=JSON.parse(P(k(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function ft(e,t){if(t)return t;try{let t=JSON.parse(P(k(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function pt(e,t){if(t)return t;try{let t=(await w(e))?.pattern;if(t&&ut.has(t))return t}catch{}return`ddd`}async function mt(e){let t=e.only??`all`,n=dt(e.outDir,e.name),r=ft(e.outDir,e.pm),i=await pt(e.outDir,e.template),a=t===`agents`||t===`both`||t===`all`,o=t===`claude`||t===`both`||t===`all`,s=t===`skills`||t===`all`,c=[];a&&c.push({file:k(e.outDir,`AGENTS.md`),render:()=>oe(n,i,r)}),o&&c.push({file:k(e.outDir,`CLAUDE.md`),render:()=>ce(n,i,r)}),s&&c.push({file:k(e.outDir,`kickjs-skills.md`),render:()=>_(n,i,r)});let l=[];for(let{file:t,render:n}of c){if(M(t)&&!e.force&&!await p({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await d(t,n()),l.push(t)}return l}function z(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 B(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=z(e,r);return i===-1?null:e.slice(r+1,i)}function V(e,t,n){let r=` `.repeat(n);return e.split(`
201
201
  `).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`);return r+e.replace(n,``)}).join(`
202
- `)}function dt(e){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,t)=>{let n=t.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`Container`&&e!==`type Container`&&e!==`type AppModule`&&e!==`AppModule`&&e!==`type ModuleRoutes`&&e!==`ModuleRoutes`);return n.includes(`defineModule`)||n.push(`defineModule`),`import { ${n.join(`, `)} } from '@forinda/kickjs'`})}function ft(e,t){return e.replaceAll(/import\s*\{\s*([^}]+)\s*\}\s*from\s*'@forinda\/kickjs'/g,(e,n)=>{let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&e!==`defineModule`);return t.container&&!r.includes(`Container`)&&r.push(`Container`),t.appModule&&!r.some(e=>e===`AppModule`||e===`type AppModule`)&&r.push(`type AppModule`),t.moduleRoutes&&!r.some(e=>e===`ModuleRoutes`||e===`type ModuleRoutes`)&&r.push(`type ModuleRoutes`),t.contributorRegistrations&&!r.some(e=>e===`ContributorRegistrations`||e===`type ContributorRegistrations`)&&r.push(`type ContributorRegistrations`),`import { ${r.join(`, `)} } from '@forinda/kickjs'`})}function pt(e){if(/\bdefineModule\s*\(/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+class\s+(\w+Module)\s+implements\s+AppModule\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no class form detected`};if(t.length>1)return{migrated:null,reason:`multiple module classes in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=z(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=B(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=B(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=B(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=dt(s),p=``;return l&&(p+=` register(container) {${V(l,4,6)} },\n\n`),u&&(p+=` contributors() {${V(u,4,6)} },\n\n`),p+=` routes() {${V(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
202
+ `)}function ht(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 gt(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 _t(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=z(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=B(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=B(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=B(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=ht(s),p=``;return l&&(p+=` register(container) {${V(l,4,6)} },\n\n`),u&&(p+=` contributors() {${V(u,4,6)} },\n\n`),p+=` routes() {${V(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
203
203
  name: '${r}',
204
204
  build: () => ({
205
205
  ${p}
206
206
  }),
207
- })`}${c}`}}function mt(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=z(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]===`
208
- `||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=z(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=B(m,/register\s*\(([^)]*)\)\s*\{/),g=B(m,/contributors\s*\(\s*\)\s*\{/),_=B(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=ft(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${V(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${V(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${V(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
209
- ${y}
207
+ })`}${c}`}}function vt(e){if(/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/.test(e))return{migrated:null,reason:`already in target form`};let t=[...e.matchAll(/export\s+const\s+(\w+Module)\s*=\s*defineModule\s*\(\s*\{/g)];if(t.length===0)return{migrated:null,reason:`no defineModule form detected`};if(t.length>1)return{migrated:null,reason:`multiple defineModule blocks in one file — migrate manually`};let n=t[0],r=n[1],i=n.index+n[0].length-1,a=z(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]===`
208
+ `||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=z(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=B(m,/register\s*\(([^)]*)\)\s*\{/),g=B(m,/contributors\s*\(\s*\)\s*\{/),_=B(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let ee=gt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),v=``;return h!==null&&(v+=` register(container: Container): void {${V(h,6,4)} }\n\n`),g!==null&&(v+=` contributors(): ContributorRegistrations {${V(g,6,4)} }\n\n`),v+=` routes(): ModuleRoutes {${V(_,6,4)} }`,{migrated:`${ee}${`export class ${r} implements AppModule {
209
+ ${v}
210
210
  }
211
- `}${u}`}}function ht(e,t){return t===`class`?mt(e):pt(e)}function gt(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 _t(e){let t=[];return await n(j(e),0),t;async function n(e,r){let i;try{i=await Oe(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o;try{o=await Ae(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function vt(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Oe(e)}catch{return}await De(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o=k(t,a),s;try{s=await Ae(i)}catch{continue}s.isDirectory()?await r(i,o):(await Ee(i,o),n++)}}}function yt(e){return k(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function bt(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await _t(e),s=await F(k(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=yt(r),await vt(e,c));let l=[];for(let e of o){let t=ht(await F(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await I(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=k(e,`index.ts`),d=null;try{d=await F(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=gt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await I(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function xt(e,t){let n=await _t(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 F(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function St(e={}){let t=e.strategy??`jwt`,n=e.outDir??`src/modules/auth`,r=k(n,`dto`),a=[],o=k(n,`auth.module.ts`);await i(o,`import { Module } from '@forinda/kickjs'
211
+ `}${u}`}}function yt(e,t){return t===`class`?vt(e):_t(e)}function bt(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 xt(e){let t=[];return await n(j(e),0),t;async function n(e,r){let i;try{i=await Me(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o;try{o=await Pe(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function St(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Me(e)}catch{return}await je(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=k(e,a),o=k(t,a),s;try{s=await Pe(i)}catch{continue}s.isDirectory()?await r(i,o):(await Ae(i,o),n++)}}}function Ct(e){return k(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function wt(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await xt(e),s=await F(k(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Ct(r),await St(e,c));let l=[];for(let e of o){let t=yt(await F(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await I(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=k(e,`index.ts`),d=null;try{d=await F(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=bt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await I(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Tt(e,t){let n=await xt(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 F(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function Et(e={}){let t=e.strategy??`jwt`,n=e.outDir??`src/modules/auth`,r=k(n,`dto`),i=[],a=k(n,`auth.module.ts`);await d(a,`import { Module } from '@forinda/kickjs'
212
212
  import { AuthController } from './auth.controller'
213
213
  import { AuthService } from './auth.service'
214
214
 
@@ -217,7 +217,7 @@ import { AuthService } from './auth.service'
217
217
  services: [AuthService],
218
218
  })
219
219
  export class AuthModule {}
220
- `),a.push(o);let s=k(n,`auth.controller.ts`);await i(s,t===`jwt`?Ct():Tt()),a.push(s);let c=k(n,`auth.service.ts`);await i(c,t===`jwt`?wt():Et()),a.push(c);let l=k(r,`register.dto.ts`);await i(l,`import { z } from 'zod'
220
+ `),i.push(a);let o=k(n,`auth.controller.ts`);await d(o,t===`jwt`?Dt():kt()),i.push(o);let s=k(n,`auth.service.ts`);await d(s,t===`jwt`?Ot():At()),i.push(s);let c=k(r,`register.dto.ts`);await d(c,`import { z } from 'zod'
221
221
 
222
222
  export const RegisterDto = z.object({
223
223
  email: z.string().email(),
@@ -226,7 +226,7 @@ export const RegisterDto = z.object({
226
226
  })
227
227
 
228
228
  export type RegisterInput = z.infer<typeof RegisterDto>
229
- `),a.push(l);let u=k(r,`login.dto.ts`);await i(u,`import { z } from 'zod'
229
+ `),i.push(c);let l=k(r,`login.dto.ts`);await d(l,`import { z } from 'zod'
230
230
 
231
231
  export const LoginDto = z.object({
232
232
  email: z.string().email(),
@@ -234,7 +234,7 @@ export const LoginDto = z.object({
234
234
  })
235
235
 
236
236
  export type LoginInput = z.infer<typeof LoginDto>
237
- `),a.push(u);let d=k(n,`auth.test.ts`);if(await i(d,`import { describe, it, expect } from 'vitest'
237
+ `),i.push(l);let u=k(n,`auth.test.ts`);if(await d(u,`import { describe, it, expect } from 'vitest'
238
238
 
239
239
  describe('Auth Module', () => {
240
240
  it.todo('POST /register — creates a new user')
@@ -243,7 +243,7 @@ describe('Auth Module', () => {
243
243
  it.todo('POST /logout — invalidates session/token')
244
244
  it.todo('GET /me — returns authenticated user')
245
245
  })
246
- `),a.push(d),e.roleGuards!==!1){let e=k(n,`auth.guard.ts`);await i(e,`import { Roles } from '@forinda/kickjs-auth'
246
+ `),i.push(u),e.roleGuards!==!1){let e=k(n,`auth.guard.ts`);await d(e,`import { Roles } from '@forinda/kickjs-auth'
247
247
 
248
248
  /**
249
249
  * Role-based access guard.
@@ -254,7 +254,7 @@ describe('Auth Module', () => {
254
254
  */
255
255
  export const AdminOnly = Roles('admin')
256
256
  export const ManagerOnly = Roles('manager')
257
- `),a.push(e)}return a}function Ct(){return`import { Controller, Post, Get } from '@forinda/kickjs'
257
+ `),i.push(e)}return i}function Dt(){return`import { Controller, Post, Get } from '@forinda/kickjs'
258
258
  import { Authenticated, Public } from '@forinda/kickjs-auth'
259
259
  import type { RequestContext } from '@forinda/kickjs'
260
260
  import { Autowired } from '@forinda/kickjs'
@@ -290,7 +290,7 @@ export class AuthController {
290
290
  return ctx.json({ user: ctx.user })
291
291
  }
292
292
  }
293
- `}function wt(){return`import { Service, Autowired } from '@forinda/kickjs'
293
+ `}function Ot(){return`import { Service, Autowired } from '@forinda/kickjs'
294
294
  import { PasswordService } from '@forinda/kickjs-auth'
295
295
  import type { RegisterInput } from './dto/register.dto'
296
296
  import type { LoginInput } from './dto/login.dto'
@@ -329,7 +329,7 @@ export class AuthService {
329
329
  return { user: { id: user.id, email: user.email, name: user.name } }
330
330
  }
331
331
  }
332
- `}function Tt(){return`import { Controller, Post, Get } from '@forinda/kickjs'
332
+ `}function kt(){return`import { Controller, Post, Get } from '@forinda/kickjs'
333
333
  import { Authenticated, Public } from '@forinda/kickjs-auth'
334
334
  import { sessionLogin, sessionLogout } from '@forinda/kickjs-auth'
335
335
  import type { RequestContext } from '@forinda/kickjs'
@@ -368,7 +368,7 @@ export class AuthController {
368
368
  return ctx.json({ user: ctx.user })
369
369
  }
370
370
  }
371
- `}function Et(){return`import { Service, Autowired } from '@forinda/kickjs'
371
+ `}function At(){return`import { Service, Autowired } from '@forinda/kickjs'
372
372
  import { PasswordService } from '@forinda/kickjs-auth'
373
373
  import type { RegisterInput } from './dto/register.dto'
374
374
  import type { LoginInput } from './dto/login.dto'
@@ -405,11 +405,11 @@ export class AuthService {
405
405
  return { id: user.id, email: user.email, name: user.name }
406
406
  }
407
407
  }
408
- `}async function Dt(e){let{name:t,outDir:n}=e,r=S(t),a=p(t),o=le(t),s=e.queue??`${a}-queue`,c=[];return await(async(e,t)=>{let r=k(n,e);await i(r,t),c.push(r)})(`${a}.job.ts`,`import { Inject } from '@forinda/kickjs'
408
+ `}async function jt(e){let{name:n,outDir:r}=e,i=x(n),a=t(n),o=f(n),s=e.queue??`${a}-queue`,c=[];return await(async(e,t)=>{let n=k(r,e);await d(n,t),c.push(n)})(`${a}.job.ts`,`import { Inject } from '@forinda/kickjs'
409
409
  import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
410
410
 
411
411
  /**
412
- * ${r} Job Processor
412
+ * ${i} Job Processor
413
413
  *
414
414
  * Decorators:
415
415
  * @Job(queueName) — marks this class as a job processor for a queue
@@ -422,7 +422,7 @@ import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-
422
422
  * await this.queue.add('${s}', '${o}', { ... })
423
423
  */
424
424
  @Job('${s}')
425
- export class ${r}Job {
425
+ export class ${i}Job {
426
426
  @Process()
427
427
  async handle(job: { name: string; data: any; id?: string }) {
428
428
  console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
@@ -438,7 +438,7 @@ export class ${r}Job {
438
438
  // Handle high-priority variant of this job
439
439
  }
440
440
  }
441
- `),c}const Ot={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.string().datetime()`},email:{ts:`string`,zod:`z.string().email()`},url:{ts:`string`,zod:`z.string().url()`},uuid:{ts:`string`,zod:`z.string().uuid()`},json:{ts:`any`,zod:`z.any()`}};function kt(e){return 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=Ot[a];if(!o){let e=[...Object.keys(Ot),`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}})}async function At(e){let{name:t,fields:n,modulesDir:r,noEntity:a,noTests:o,repo:s=`inmemory`,tokenScope:c=`app`,style:l=`define`}=e,u=e.pluralize!==!1,f=p(t),m=S(t);le(t);let h=u?d(f):f,g=u?ce(m):m,_=k(r,h),v=[],y=async(e,t)=>{let n=k(_,e);await i(n,t),v.push(n)};await y(`${f}.module.ts`,Rt(m,f,h,l)),await y(`constants.ts`,Pt(m,n)),await y(`presentation/${f}.controller.ts`,zt(m,f,h,g)),await y(`application/dtos/create-${f}.dto.ts`,jt(m,n)),await y(`application/dtos/update-${f}.dto.ts`,Mt(m,n)),await y(`application/dtos/${f}-response.dto.ts`,Nt(m,n));let b=Ht(m,f,h,g);for(let e of b)await y(`application/use-cases/${e.file}`,e.content);return await y(`domain/repositories/${f}.repository.ts`,Bt(m,f,c)),await y(`domain/services/${f}-domain.service.ts`,Vt(m,f)),s===`inmemory`&&await y(`infrastructure/repositories/in-memory-${f}.repository.ts`,Ft(m,f,n)),a||(await y(`domain/entities/${f}.entity.ts`,It(m,f,n)),await y(`domain/value-objects/${f}-id.vo.ts`,Lt(m))),await Ut(r,m,h,f,l),v}function jt(e,t){return`import { z } from 'zod'
441
+ `),c}const Mt={string:{ts:`string`,zod:`z.string()`},text:{ts:`string`,zod:`z.string()`},number:{ts:`number`,zod:`z.number()`},int:{ts:`number`,zod:`z.number().int()`},float:{ts:`number`,zod:`z.number()`},boolean:{ts:`boolean`,zod:`z.boolean()`},date:{ts:`string`,zod:`z.string().datetime()`},email:{ts:`string`,zod:`z.string().email()`},url:{ts:`string`,zod:`z.string().url()`},uuid:{ts:`string`,zod:`z.string().uuid()`},json:{ts:`any`,zod:`z.any()`}};function Nt(e){return 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=Mt[a];if(!o){let e=[...Object.keys(Mt),`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}})}async function Pt(e){let{name:n,fields:r,modulesDir:i,noEntity:a,noTests:o,repo:s=`inmemory`,tokenScope:c=`app`,style:l=`define`}=e,u=e.pluralize!==!1,p=t(n),m=x(n);f(n);let h=u?g(p):p,_=u?fe(m):m,ee=k(i,h),v=[],y=async(e,t)=>{let n=k(ee,e);await d(n,t),v.push(n)};await y(`${p}.module.ts`,Ht(m,p,h,l)),await y(`constants.ts`,Rt(m,r)),await y(`presentation/${p}.controller.ts`,Ut(m,p,h,_)),await y(`application/dtos/create-${p}.dto.ts`,Ft(m,r)),await y(`application/dtos/update-${p}.dto.ts`,It(m,r)),await y(`application/dtos/${p}-response.dto.ts`,Lt(m,r));let ne=Kt(m,p,h,_);for(let e of ne)await y(`application/use-cases/${e.file}`,e.content);return await y(`domain/repositories/${p}.repository.ts`,Wt(m,p,c)),await y(`domain/services/${p}-domain.service.ts`,Gt(m,p)),s===`inmemory`&&await y(`infrastructure/repositories/in-memory-${p}.repository.ts`,zt(m,p,r)),a||(await y(`domain/entities/${p}.entity.ts`,Bt(m,p,r)),await y(`domain/value-objects/${p}-id.vo.ts`,Vt(m))),await te(i,m,h,p,l),v}function Ft(e,t){return`import { z } from 'zod'
442
442
 
443
443
  export const create${e}Schema = z.object({
444
444
  ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
@@ -446,7 +446,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
446
446
  })
447
447
 
448
448
  export type Create${e}DTO = z.infer<typeof create${e}Schema>
449
- `}function Mt(e,t){return`import { z } from 'zod'
449
+ `}function It(e,t){return`import { z } from 'zod'
450
450
 
451
451
  export const update${e}Schema = z.object({
452
452
  ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
@@ -454,21 +454,21 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
454
454
  })
455
455
 
456
456
  export type Update${e}DTO = z.infer<typeof update${e}Schema>
457
- `}function Nt(e,t){return`export interface ${e}ResponseDTO {
457
+ `}function Lt(e,t){return`export interface ${e}ResponseDTO {
458
458
  id: string
459
459
  ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
460
460
  `)}
461
461
  createdAt: string
462
462
  updatedAt: string
463
463
  }
464
- `}function Pt(e,t){let n=t.filter(e=>e.tsType===`string`).map(e=>`'${e.name}'`);t.filter(e=>e.tsType===`number`).map(e=>`'${e.name}'`);let r=t.map(e=>`'${e.name}'`),i=[...r].join(`, `),a=[...r,`'createdAt'`,`'updatedAt'`].join(`, `),o=n.length>0?n.join(`, `):`'name'`;return`import type { ApiQueryParamsConfig } from '@forinda/kickjs'
464
+ `}function Rt(e,t){let n=t.filter(e=>e.tsType===`string`).map(e=>`'${e.name}'`);t.filter(e=>e.tsType===`number`).map(e=>`'${e.name}'`);let r=t.map(e=>`'${e.name}'`),i=[...r].join(`, `),a=[...r,`'createdAt'`,`'updatedAt'`].join(`, `),o=n.length>0?n.join(`, `):`'name'`;return`import type { ApiQueryParamsConfig } from '@forinda/kickjs'
465
465
 
466
466
  export const ${e.toUpperCase()}_QUERY_CONFIG: ApiQueryParamsConfig = {
467
467
  filterable: [${i}],
468
468
  sortable: [${a}],
469
469
  searchable: [${o}],
470
470
  }
471
- `}function Ft(e,t,n){return`import { randomUUID } from 'node:crypto'
471
+ `}function zt(e,t,n){return`import { randomUUID } from 'node:crypto'
472
472
  import { Repository, HttpException } from '@forinda/kickjs'
473
473
  import type { ParsedQuery } from '@forinda/kickjs'
474
474
  import type { I${e}Repository } from '../../domain/repositories/${t}.repository'
@@ -520,7 +520,7 @@ ${n.map(e=>` ${e.name}: dto.${e.name},`).join(`
520
520
  this.store.delete(id)
521
521
  }
522
522
  }
523
- `}function It(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
523
+ `}function Bt(e,t,n){return`import { ${e}Id } from '../value-objects/${t}-id.vo'
524
524
 
525
525
  interface ${e}Props {
526
526
  id: ${e}Id
@@ -566,7 +566,7 @@ ${n.map(e=>` ${e.name}: this.props.${e.name},`).join(`
566
566
  }
567
567
  }
568
568
  }
569
- `}function Lt(e){return`import { randomUUID } from 'node:crypto'
569
+ `}function Vt(e){return`import { randomUUID } from 'node:crypto'
570
570
 
571
571
  export class ${e}Id {
572
572
  private constructor(private readonly value: string) {}
@@ -581,7 +581,7 @@ export class ${e}Id {
581
581
  toString(): string { return this.value }
582
582
  equals(other: ${e}Id): boolean { return this.value === other.value }
583
583
  }
584
- `}function Rt(e,t,n,r=`define`){let i=`import { ${e}Controller } from './presentation/${t}.controller'
584
+ `}function Ht(e,t,n,r=`define`){let i=`import { ${e}Controller } from './presentation/${t}.controller'
585
585
  import { ${e.toUpperCase()}_REPOSITORY } from './domain/repositories/${t}.repository'
586
586
  import { InMemory${e}Repository } from './infrastructure/repositories/in-memory-${t}.repository'
587
587
 
@@ -591,10 +591,13 @@ import.meta.glob(
591
591
  ['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
592
592
  { eager: true },
593
593
  )`,a=` /**
594
- * Declare HTTP routes. Pass \`controller\` and the framework
595
- * derives the Express Router via \`buildRoutes()\`. Return an array
596
- * to mount multiple route sets each entry can override the API
597
- * version with a \`version\` field:
594
+ * Declare HTTP routes for this module. Return value shape:
595
+ *
596
+ * - \`path\` URL prefix for this route set.
597
+ * - \`controller\` — Controller class (also drives OpenAPI).
598
+ * - \`version\` — Optional. Overrides the app-wide API version.
599
+ *
600
+ * Return an array to mount multiple route sets:
598
601
  *
599
602
  * return [
600
603
  * { path: '/${n}', version: 1, controller: ${e}V1Controller },
@@ -651,7 +654,7 @@ ${a}
651
654
  },
652
655
  }),
653
656
  })
654
- `}function zt(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
657
+ `}function Ut(e,t,n,r){return`import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
655
658
  import { ApiTags } from '@forinda/kickjs-swagger'
656
659
  import { Create${e}UseCase } from '../application/use-cases/create-${t}.use-case'
657
660
  import { Get${e}UseCase } from '../application/use-cases/get-${t}.use-case'
@@ -714,7 +717,7 @@ export class ${e}Controller {
714
717
  ctx.noContent()
715
718
  }
716
719
  }
717
- `}function Bt(e,t,n){return`import { createToken } from '@forinda/kickjs'
720
+ `}function Wt(e,t,n){return`import { createToken } from '@forinda/kickjs'
718
721
  import type { ${e}ResponseDTO } from '../../application/dtos/${t}-response.dto'
719
722
  import type { Create${e}DTO } from '../../application/dtos/create-${t}.dto'
720
723
  import type { Update${e}DTO } from '../../application/dtos/update-${t}.dto'
@@ -740,7 +743,7 @@ export interface I${e}Repository {
740
743
  * adopters must NOT use the reserved \`'kick/'\` namespace.
741
744
  */
742
745
  export const ${e.toUpperCase()}_REPOSITORY = createToken<I${e}Repository>('${n}/${e}/repository')
743
- `}function Vt(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
746
+ `}function Gt(e,t){return`import { Service, Inject, HttpException } from '@forinda/kickjs'
744
747
  import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../repositories/${t}.repository'
745
748
 
746
749
  @Service()
@@ -754,7 +757,7 @@ export class ${e}DomainService {
754
757
  if (!entity) throw HttpException.notFound('${e} not found')
755
758
  }
756
759
  }
757
- `}function Ht(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
760
+ `}function Kt(e,t,n,r){return[{file:`create-${t}.use-case.ts`,content:`import { Service, Inject } from '@forinda/kickjs'
758
761
  import { ${e.toUpperCase()}_REPOSITORY, type I${e}Repository } from '../../domain/repositories/${t}.repository'
759
762
  import type { Create${e}DTO } from '../dtos/create-${t}.dto'
760
763
 
@@ -797,10 +800,7 @@ export class Delete${e}UseCase {
797
800
  constructor(@Inject(${e.toUpperCase()}_REPOSITORY) private repo: I${e}Repository) {}
798
801
  async execute(id: string) { return this.repo.delete(id) }
799
802
  }
800
- `}]}async function Ut(e,t,n,r,a=`define`){let s=k(e,`index.ts`),c=await o(s),l=`./${n}/${r}.module`,u=a===`class`?`${t}Module`:`${t}Module()`;if(!c){await i(s,`import type { AppModuleEntry } from '@forinda/kickjs'\nimport { ${t}Module } from '${l}'\n\nexport const modules: AppModuleEntry[] = [${u}]\n`);return}let d=await F(s,`utf-8`),f=`import { ${t}Module } from '${l}'`;if(!d.includes(`${t}Module`)){let e=d.lastIndexOf(`import `);if(e!==-1){let t=d.indexOf(`
801
- `,e);d=d.slice(0,t+1)+f+`
802
- `+d.slice(t+1)}else d=f+`
803
- `+d;d=d.replace(/(=\s*\[)([\s\S]*?)(])/,(e,t,n,r)=>{let i=n.trim();if(!i)return`${t}${u}${r}`;let a=i.endsWith(`,`)?``:`,`;return`${t}${n.trimEnd()}${a} ${u}${r}`})}await I(s,d,`utf-8`)}async function Wt(e){let{name:t,moduleName:n,modulesDir:r}=e,a=e.pluralize??!0,o=p(t),s=S(t),c=[],l;if(e.outDir)l=j(e.outDir);else if(n){let e=p(n),t=a?d(e):e;l=j(k(r??`src/modules`,t,`__tests__`))}else l=j(`src/__tests__`);let u=k(l,`${o}.test.ts`);return await i(u,`import { describe, it, expect, beforeEach } from 'vitest'
803
+ `}]}async function qt(e){let{name:n,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=t(n),s=x(n),c=[],l;if(e.outDir)l=j(e.outDir);else if(r){let e=t(r),n=a?g(e):e;l=j(k(i??`src/modules`,n,`__tests__`))}else l=j(`src/__tests__`);let u=k(l,`${o}.test.ts`);return await d(u,`import { describe, it, expect, beforeEach } from 'vitest'
804
804
  import { Container } from '@forinda/kickjs'
805
805
 
806
806
  describe('${s}', () => {
@@ -823,59 +823,59 @@ describe('${s}', () => {
823
823
  expect(true).toBe(true)
824
824
  })
825
825
  })
826
- `),c.push(u),c}const Gt=[`agents`,`claude`,`skills`,`both`,`all`];function H(e){return e.parent?.opts()?.dryRun??!1}function U(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(`
827
- (dry run — no files were written)`),console.log()}async function Kt(e){if(!e)try{let e=await w(process.cwd());await E({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const qt=[{name:`module <name>`,description:`Full DDD module (controller, DTOs, use-cases, 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:`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:`job <name>`,description:`Queue @Job processor`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}];async function Jt(){console.log(`
826
+ `),c.push(u),c}const Jt=[`agents`,`claude`,`skills`,`both`,`all`];function H(e){return e.parent?.opts()?.dryRun??!1}function U(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(`
827
+ (dry run — no files were written)`),console.log()}async function Yt(e){if(!e)try{let e=await w(process.cwd());await E({cwd:process.cwd(),allowDuplicates:!0,silent:!0,schemaValidator:e?.typegen?.schemaValidator??`zod`,envFile:e?.typegen?.envFile,srcDir:e?.typegen?.srcDir,outDir:e?.typegen?.outDir})}catch{}}const Xt=[{name:`module <name>`,description:`Full DDD module (controller, DTOs, use-cases, 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:`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:`job <name>`,description:`Queue @Job processor`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}];async function Zt(){console.log(`
828
828
  Built-in generators:
829
- `);let e=Math.max(...qt.map(e=>e.name.length));for(let t of qt)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await w(process.cwd()),n=fe(t?.plugins??[],t?.commands??[]),r=await oe(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
829
+ `);let e=Math.max(...Xt.map(e=>e.name.length));for(let t of Xt)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await w(process.cwd()),n=he(t?.plugins??[],t?.commands??[]),r=await le(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
830
830
  Plugin generators:
831
831
  `);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(`
832
832
  Failed to load:
833
- `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Yt(e,t,n){let r=await w(process.cwd()),i=C(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??_(i.repo),s=t.pattern??r?.pattern??`ddd`,c=t.pluralize===!1?!1:i.pluralize??!0,l=ue(r,process.cwd()),u=i.style??`define`;if(!n&&u===`define`){let e=await xt(j(a),`define`);if(e.length>0){console.error(`\n ${y.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${y.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${y.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 ${y.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${y.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${y.dim(`// kick.config.ts`)}\n ${y.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let d=[];for(let r of e){let e=await v({name:r,modulesDir:j(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,dryRun:n,pluralize:c,prismaClientPath:i.prismaClientPath,tokenScope:l,style:i.style});d.push(...e)}U(d,n),await Kt(n)}function Xt(e){let t=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 implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,n,r)=>{if(n.list){await Jt();return}if(!e||e.length===0){t.help();return}let i=H(r);if(c(i),e.length>=2){let[t,r,...a]=e,o=await w(process.cwd()),s=fe(o?.plugins??[],o?.commands??[]),c=await ne({generatorName:t,itemName:r,args:a,flags:n,cwd:process.cwd()},s.generators);if(c){U(c.files,i);return}}await Yt(e,n,i)});t.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 implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=H(n);c(r),await Yt(e,t,r)}),t.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=H(n);c(r),U(await te({name:e,outDir:j(t.out)}),r)}),t.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=H(n);c(r),U(await it({name:e,outDir:j(t.out)}),r)}),t.command(`middleware <name>`).description(`Generate an Express middleware function
834
- 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=H(n);c(r);let i=await w(process.cwd()),a=C(i),o=a.dir??`src/modules`;U(await ie({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
835
- 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=H(n);c(r);let i=await w(process.cwd()),a=C(i),o=a.dir??`src/modules`;U(await g({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`service <name>`).description(`Generate a @Service() class
836
- 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=H(n);c(r);let i=await w(process.cwd()),a=C(i),o=a.dir??`src/modules`;U(await h({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
837
- 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=H(n);c(r);let i=await w(process.cwd()),a=C(i),o=a.dir??`src/modules`;U(await se({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await Kt(r)}),t.command(`dto <name>`).description(`Generate a Zod DTO schema
838
- 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=H(n);c(r);let i=await w(process.cwd()),a=C(i),o=a.dir??`src/modules`;U(await ee({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),t.command(`test <name>`).description(`Generate a Vitest test scaffold
839
- 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=H(n);c(r);let i=C(await w(process.cwd())),a=i.dir??`src/modules`;U(await Wt({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),t.command(`job <name>`).description(`Generate a @Job queue processor with @Process handlers`).option(`-o, --out <dir>`,`Output directory`,`src/jobs`).option(`-q, --queue <name>`,`Queue name (default: <name>-queue)`).action(async(e,t,n)=>{let r=H(n);c(r),U(await Dt({name:e,outDir:j(t.out),queue:t.queue}),r)}),t.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
833
+ `);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Qt(e,t,n){let r=await w(process.cwd()),i=C(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??de(i.repo),s=t.pattern??r?.pattern??`ddd`,c=t.pluralize===!1?!1:i.pluralize??!0,l=pe(r,process.cwd()),d=i.style??`define`;if(!n&&d===`define`){let e=await Tt(j(a),`define`);if(e.length>0){console.error(`\n ${u.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${u.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${u.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 ${u.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${u.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${u.dim(`// kick.config.ts`)}\n ${u.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let f=[];for(let r of e){let e=await m({name:r,modulesDir:j(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,dryRun:n,pluralize:c,prismaClientPath:i.prismaClientPath,tokenScope:l,style:i.style});f.push(...e)}U(f,n),await Yt(n)}function $t(t){let n=t.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 implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,r)=>{if(t.list){await Zt();return}if(!e||e.length===0){n.help();return}let i=H(r);if(o(i),e.length>=2){let[n,r,...a]=e,o=await w(process.cwd()),s=he(o?.plugins??[],o?.commands??[]),c=await ae({generatorName:n,itemName:r,args:a,flags:t,cwd:process.cwd()},s.generators);if(c){U(c.files,i);return}}await Qt(e,t,i)});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 implementation: inmemory | drizzle | prisma`).option(`--pattern <pattern>`,`Override project pattern: rest | ddd | cqrs | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=H(n);o(r),await Qt(e,{...n.optsWithGlobals(),...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=H(n);o(r),U(await ie({name:e,outDir:j(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=H(n);o(r),U(await ct({name:e,outDir:j(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate an Express middleware function
834
+ 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=H(n);o(r);let i=await w(process.cwd()),a=C(i),s=a.dir??`src/modules`;U(await se({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
835
+ 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=H(n);o(r);let i=await w(process.cwd()),a=C(i),s=a.dir??`src/modules`;U(await v({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
836
+ 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=H(n);o(r);let i=await w(process.cwd()),a=C(i),s=a.dir??`src/modules`;U(await ee({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
837
+ 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=H(n);o(r);let i=await w(process.cwd()),a=C(i),s=a.dir??`src/modules`;U(await ue({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await Yt(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
838
+ 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=H(n);o(r);let i=await w(process.cwd()),a=C(i),s=a.dir??`src/modules`;U(await re({name:e,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
839
+ 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=H(n);o(r);let i=C(await w(process.cwd())),a=i.dir??`src/modules`;U(await qt({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.command(`job <name>`).description(`Generate a @Job queue processor with @Process handlers`).option(`-o, --out <dir>`,`Output directory`,`src/jobs`).option(`-q, --queue <name>`,`Queue name (default: <name>-queue)`).action(async(e,t,n)=>{let r=H(n);o(r),U(await jt({name:e,outDir:j(t.out),queue:t.queue}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
840
840
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
841
841
  Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
842
842
  Optional: append :optional (shell-safe): description:text:optional
843
- or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=H(r);c(i),t.length===0&&(console.error(`
843
+ or use ? with quoting: "description:text?" or "description?:text"`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`--modules-dir <dir>`,`Modules directory`).action(async(e,t,n,r)=>{let i=H(r);o(i),t.length===0&&(console.error(`
844
844
  Error: At least one field is required.
845
845
  Usage: kick g scaffold <name> <field:type> [field:type...]
846
846
  Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
847
847
  Optional: append :optional (shell-safe, no quoting needed)
848
- `),process.exit(1));let a=await w(process.cwd()),o=C(a),s=n.modulesDir??o.dir??`src/modules`,l=kt(t),u=ue(a,process.cwd()),d=a?.pattern??`ddd`;d!==`ddd`&&(console.error(`\n Error: 'kick g scaffold' currently only supports the DDD pattern.\n Detected project pattern: '${d}'.\n Workarounds:\n - Run 'kick g module ${e}' for the ${d} layout (no fields), then add fields manually.\n - Override the pattern for this scaffold by setting kick.config.ts pattern: 'ddd'.\n`),process.exit(1));let f=await At({name:e,fields:l,modulesDir:j(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:u,style:o.style});console.log(`\n Scaffolded ${e} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);U(f,i),await Kt(i)}),t.command(`auth-scaffold`).description(`Generate a complete auth module (register, login, logout, password hashing)
849
- Includes controller, service, DTOs, and test stubs.`).option(`-s, --strategy <type>`,`Auth strategy: jwt | session`).option(`--role-guards`,`Generate role-based guards (default: true)`).option(`--no-role-guards`,`Skip role-based guard generation`).option(`-o, --out <dir>`,`Output directory`,`src/modules/auth`).action(async(e,t)=>{let r=H(t);c(r);let i=e.strategy;i||=await n({message:`Auth strategy`,options:[{value:`jwt`,label:`JWT`,hint:`stateless token-based auth`},{value:`session`,label:`Session`,hint:`server-side session with cookies`}]});let a=e.roleGuards;a===void 0&&(a=await l({message:`Generate role-based guards?`,initialValue:!0})),U(await St({strategy:i,outDir:e.out,roleGuards:a}),r)}),t.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Default repository type: inmemory | drizzle | prisma`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=H(t);c(n),U(await at({outDir:j(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),t.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | ddd | cqrs | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=H(t);c(n);let r=e.only??`all`;if(!Gt.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${Gt.join(` | `)}`),process.exitCode=1;return}U(await ut({outDir:j(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)})}function Zt(e,t,n){let r=Pe(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}async function Qt(e){let t=D.resolve(e.cwd,`.kickjs/types`);await De(t,{recursive:!0});let n=new Map,r=e.scan??_e,i={cwd:e.cwd,config:e.config,async importTs(e){return await import(L(e).href)},async writeFile(t,n){let r=D.resolve(e.cwd,t);await De(D.dirname(r),{recursive:!0}),await I(r,n,`utf8`)},getScanResult:e=>{let t=$t(e),i=n.get(t);return i||(i=r(e),n.set(t,i)),i},log:console},a=[];for(let n of e.plugins){let r=await n.generate(i);if(r===null){a.push({id:n.id,status:`skipped`});continue}let o=n.outExtension??`.d.ts`,s=D.join(t,`${n.id.replace(/\//g,`__`)}${o}`),c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+r+`
850
- `,l=``;if(M(s)&&(l=await F(s,`utf8`)),l===c){a.push({id:n.id,status:`unchanged`,outFile:s});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${s})`);await I(s,c,`utf8`),a.push({id:n.id,status:`written`,outFile:s})}return a}function $t(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 en(e,t){let n=new Set(t),r=[],i=[],a=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))}}async function W(e){let{enabled:t,skipped:n,unknown:r}=en(fe([...Ar,...e.config?.plugins??[]],e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&n.length>0)for(let e of n)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&r.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${r.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),t.length===0)return[];try{let n=await Qt({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check});if(!e.silent)for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}async function tn(e,t){let{cwd:n,silent:r=!1}=t,i=t.distDir??e?.build?.outDir??`dist`,a=e?.assetMap;if(!a||Object.keys(a).length===0)return null;let o=r?()=>{}:console.log,s=j(n,i);N(s,{recursive:!0});let c=[],l={};for(let[e,t]of Object.entries(a)){let r=await nn(e,t,n,s);c.push(r.entrySummary),Object.assign(l,r.manifestSlice),o(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let u={version:1,entries:l},d=k(s,`.kickjs-assets.json`);return Te(d,JSON.stringify(u,null,2)+`
851
- `,`utf-8`),o(` ✓ wrote manifest → ${A(n,d)} (${Object.keys(l).length} entries)`),{manifestPath:d,entries:c,manifest:u}}async function nn(e,t,n,r){let i=j(n,t.src),a=t.dest?j(n,t.dest):k(r,e);if(an(a,n))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:0},manifestSlice:{}};if(!M(i)||!on(i))return{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:0},manifestSlice:{}};let o=await Fe(t.glob??`**/*`,{cwd:i,nodir:!0,dot:!1,posix:!0});N(a,{recursive:!0});let s={},{pairs:c,collisionGroupsResolved:l}=Ie(e,[...o].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of c){let n=k(i,e),o=k(a,e);N(O(o),{recursive:!0}),xe(n,o),s[t]=rn(r,o)}return l>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${l} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:o.length},manifestSlice:s}}function rn(e,t){return A(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function an(e,t){let n=A(t,e);return n===``?!1:n.startsWith(`..`)||ye(n)}function on(e){try{return we(e).isDirectory()}catch{return!1}}function sn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function cn(e,t,n={}){t&&(process.env.PORT=t);let r=sn(n.polling),i=process.cwd(),a=await w(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await E({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}await W({cwd:i,config:a});let{createRequire:c}=await import(`node:module`),{createServer:l}=await import(L(c(j(`package.json`)).resolve(`vite`)).href),u=await l({configFile:j(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),d=a?.assetMap?Object.values(a.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>j(i,e)):[],f=e=>d.some(t=>e===t||e.startsWith(`${t}/`)),p=null,m=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=f(e);!t&&!n||(p&&clearTimeout(p),p=setTimeout(()=>{E({cwd:i,silent:!0,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1}).catch(()=>{}),W({cwd:i,config:a,silent:!0}).catch(()=>{})},100))};u.watcher.on(`add`,m),u.watcher.on(`unlink`,m),u.watcher.on(`change`,m),d.length>0&&u.watcher.add(d),await u.listen(),u.printUrls(),console.log(`
848
+ `),process.exit(1));let a=await w(process.cwd()),s=C(a),c=n.modulesDir??s.dir??`src/modules`,l=Nt(t),u=pe(a,process.cwd()),d=a?.pattern??`ddd`;d!==`ddd`&&(console.error(`\n Error: 'kick g scaffold' currently only supports the DDD pattern.\n Detected project pattern: '${d}'.\n Workarounds:\n - Run 'kick g module ${e}' for the ${d} layout (no fields), then add fields manually.\n - Override the pattern for this scaffold by setting kick.config.ts pattern: 'ddd'.\n`),process.exit(1));let f=await Pt({name:e,fields:l,modulesDir:j(c),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:s.pluralize??!0,tokenScope:u,style:s.style});console.log(`\n Scaffolded ${e} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);U(f,i),await Yt(i)}),n.command(`auth-scaffold`).description(`Generate a complete auth module (register, login, logout, password hashing)
849
+ Includes controller, service, DTOs, and test stubs.`).option(`-s, --strategy <type>`,`Auth strategy: jwt | session`).option(`--role-guards`,`Generate role-based guards (default: true)`).option(`--no-role-guards`,`Skip role-based guard generation`).option(`-o, --out <dir>`,`Output directory`,`src/modules/auth`).action(async(t,n)=>{let r=H(n);o(r);let i=t.strategy;i||=await e({message:`Auth strategy`,options:[{value:`jwt`,label:`JWT`,hint:`stateless token-based auth`},{value:`session`,label:`Session`,hint:`server-side session with cookies`}]});let a=t.roleGuards;a===void 0&&(a=await p({message:`Generate role-based guards?`,initialValue:!0})),U(await Et({strategy:i,outDir:t.out,roleGuards:a}),r)}),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>`,`Default repository type: inmemory | drizzle | prisma`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=H(t);o(n),U(await lt({outDir:j(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | ddd | cqrs | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=H(t);o(n);let r=e.only??`all`;if(!Jt.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${Jt.join(` | `)}`),process.exitCode=1;return}U(await mt({outDir:j(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)})}function en(e,t,n){let r=Re(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}async function tn(e){let t=D.resolve(e.cwd,`.kickjs/types`);await je(t,{recursive:!0});let n=new Map,r=e.scan??_e,i={cwd:e.cwd,config:e.config,async importTs(e){return await import(L(e).href)},async writeFile(t,n){let r=D.resolve(e.cwd,t);await je(D.dirname(r),{recursive:!0}),await I(r,n,`utf8`)},getScanResult:e=>{let t=nn(e),i=n.get(t);return i||(i=r(e),n.set(t,i)),i},log:console},a=[];for(let n of e.plugins){let r=await n.generate(i);if(r===null){a.push({id:n.id,status:`skipped`});continue}let o=n.outExtension??`.d.ts`,s=D.join(t,`${n.id.replace(/\//g,`__`)}${o}`),c=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+r+`
850
+ `,l=``;if(M(s)&&(l=await F(s,`utf8`)),l===c){a.push({id:n.id,status:`unchanged`,outFile:s});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${s})`);await I(s,c,`utf8`),a.push({id:n.id,status:`written`,outFile:s})}return a}function nn(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 rn(e,t){let n=new Set(t),r=[],i=[],a=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))}}async function W(e){let{enabled:t,skipped:n,unknown:r}=rn(he([...Fr,...e.config?.plugins??[]],e.config?.commands??[]).typegens,e.config?.typegen?.disable??[]);if(!e.silent&&n.length>0)for(let e of n)console.log(` ${e.id}: disabled (typegen.disable)`);if(!e.silent&&r.length>0&&console.warn(` kick typegen: disable list references unknown id(s): ${r.map(e=>`'${e}'`).join(`, `)}. Run \`kick typegen --list\` to see registered ids.`),t.length===0)return[];try{let n=await tn({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check});if(!e.silent)for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}async function an(e,t){let{cwd:n,silent:r=!1}=t,i=t.distDir??e?.build?.outDir??`dist`,a=e?.assetMap;if(!a||Object.keys(a).length===0)return null;let o=r?()=>{}:console.log,s=j(n,i);N(s,{recursive:!0});let c=[],l={};for(let[e,t]of Object.entries(a)){let r=await on(e,t,n,s);c.push(r.entrySummary),Object.assign(l,r.manifestSlice),o(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let u={version:1,entries:l},d=k(s,`.kickjs-assets.json`);return ke(d,JSON.stringify(u,null,2)+`
851
+ `,`utf-8`),o(` ✓ wrote manifest → ${A(n,d)} (${Object.keys(l).length} entries)`),{manifestPath:d,entries:c,manifest:u}}async function on(e,t,n,r){let i=j(n,t.src),a=t.dest?j(n,t.dest):k(r,e);if(cn(a,n))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:0},manifestSlice:{}};if(!M(i)||!ln(i))return{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:0},manifestSlice:{}};let o=await ze(t.glob??`**/*`,{cwd:i,nodir:!0,dot:!1,posix:!0});N(a,{recursive:!0});let s={},{pairs:c,collisionGroupsResolved:l}=Be(e,[...o].toSorted(),{strategy:t.keys??`auto`});for(let{rel:e,key:t}of c){let n=k(i,e),o=k(a,e);N(O(o),{recursive:!0}),Te(n,o),s[t]=sn(r,o)}return l>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${l} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:A(n,a),filesCopied:o.length},manifestSlice:s}}function sn(e,t){return A(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function cn(e,t){let n=A(t,e);return n===``?!1:n.startsWith(`..`)||Ce(n)}function ln(e){try{return Oe(e).isDirectory()}catch{return!1}}function un(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function dn(e,t,n={}){t&&(process.env.PORT=t);let r=un(n.polling),i=process.cwd(),a=await w(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await E({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}await W({cwd:i,config:a});let{createRequire:c}=await import(`node:module`),{createServer:l}=await import(L(c(j(`package.json`)).resolve(`vite`)).href),u=await l({configFile:j(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),d=a?.assetMap?Object.values(a.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>j(i,e)):[],f=e=>d.some(t=>e===t||e.startsWith(`${t}/`)),p=null,m=e=>{if(e.includes(`.kickjs`)||e.endsWith(`.d.ts`))return;let t=/\.(ts|tsx|mts|cts)$/.test(e),n=f(e);!t&&!n||(p&&clearTimeout(p),p=setTimeout(()=>{E({cwd:i,silent:!0,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1}).catch(()=>{}),W({cwd:i,config:a,silent:!0}).catch(()=>{})},100))};u.watcher.on(`add`,m),u.watcher.on(`unlink`,m),u.watcher.on(`change`,m),d.length>0&&u.watcher.add(d),await u.listen(),u.printUrls(),console.log(`
852
852
  KickJS dev server running (Vite + @forinda/kickjs-vite)
853
- `);let h=async()=>{p&&clearTimeout(p),await u.close(),process.exit(0)};process.on(`SIGINT`,h),process.on(`SIGTERM`,h)}function ln(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)`).action(async e=>{try{await cn(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
853
+ `);let h=async()=>{p&&clearTimeout(p),await u.close(),process.exit(0)};process.on(`SIGINT`,h),process.on(`SIGTERM`,h)}function fn(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)`).action(async e=>{try{await dn(e.entry,e.port,{polling:e.polling})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
854
854
  Error: vite is not installed.
855
855
  Run: pnpm add -D vite unplugin-swc
856
856
  `):console.error(`
857
857
  Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
858
858
  Building for production...
859
859
  `);let{createRequire:e}=await import(`node:module`),{build:t}=await import(L(e(j(`package.json`)).resolve(`vite`)).href);await t({configFile:j(`vite.config.ts`)});let n=await w(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
860
- Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?k(`dist`,e):e.dest??k(`dist`,t),r=j(t),i=j(n);if(!M(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}N(i,{recursive:!0}),xe(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
861
- Building asset map...`);try{await tn(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
860
+ Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?k(`dist`,e):e.dest??k(`dist`,t),r=j(t),i=j(n);if(!M(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}N(i,{recursive:!0}),Te(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
861
+ Building asset map...`);try{await an(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
862
862
  Build complete.
863
863
  `)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await w(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
864
- Building asset map...`);try{await tn(e,{cwd:process.cwd()}),console.log(`
864
+ Building asset map...`);try{await an(e,{cwd:process.cwd()}),console.log(`
865
865
  Asset build complete.
866
- `)}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)),Zt(e.entry,t)}),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`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await cn(e.entry,e.port)}catch(e){console.error(`
867
- Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function un(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
866
+ `)}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)),en(e.entry,t)}),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`).action(async e=>{let t=e.inspectPort??`9229`;process.env.NODE_OPTIONS=`--inspect=0.0.0.0:${t}`,console.log(` Debugger: ws://0.0.0.0:${t}`);try{await dn(e.entry,e.port)}catch(e){console.error(`
867
+ Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function pn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{console.log(`
868
868
  KickJS CLI
869
869
 
870
870
  System:
871
- OS: ${Re()} ${ze()} (${Le()})
871
+ OS: ${He()} ${Ue()} (${Ve()})
872
872
  Node: ${process.version}
873
873
 
874
874
  Packages:
875
875
  @forinda/kickjs workspace
876
876
  @forinda/kickjs-vite workspace
877
877
  @forinda/kickjs-cli workspace
878
- `)})}const{bold:G,dim:K,green:dn,red:q,yellow:fn,blue:pn}=y;function mn(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 hn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function J(e,t){try{return await hn(`${e}${t}`)}catch{return null}}async function gn(e){let[t,n,r,i,a]=await Promise.all([J(e,`/health`),J(e,`/metrics`),J(e,`/routes`),J(e,`/container`),J(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function _n(t,n){let{health:r,metrics:i,routes:a,container:o,ws:s}=n,c=K(`─`.repeat(60));if(console.log(),console.log(G(` KickJS Inspector`)+K(` → ${t}`)),console.log(c),r){let e=r.status===`healthy`?dn(`● healthy`):q(`● `+r.status);console.log(` ${G(`Health:`)} ${e}`)}else console.log(` ${G(`Health:`)} ${q(`● unreachable`)}`);if(i){let e=((i.errorRate??0)*100).toFixed(1),t=i.errorRate>.1?q:i.errorRate>0?fn:dn;console.log(` ${G(`Uptime:`)} ${mn(i.uptimeSeconds)}`),console.log(` ${G(`Requests:`)} ${i.requests}`),console.log(` ${G(`Errors:`)} ${i.serverErrors} server, ${i.clientErrors??0} client ${K(`(`)}${t(e+`%`)}${K(`)`)}`)}if(o&&console.log(` ${G(`DI:`)} ${o.count} bindings`),s&&s.enabled&&console.log(` ${G(`WS:`)} ${s.connections??0} connections, ${s.namespaces??0} namespaces`),a?.routes?.length){console.log(),console.log(G(` Routes`)),console.log(c),console.log(` ${K(`METHOD`)} ${K(`PATH`.padEnd(36))} ${K(`CONTROLLER`)}`);for(let t of a.routes){let n=t.path.length>36?t.path.slice(0,33)+`...`:t.path.padEnd(36);console.log(` ${e(t.method)} ${n} ${pn(t.controller)}.${K(t.handler)}`)}}console.log(c),console.log()}function vn(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 gn(r);t.json?console.log(JSON.stringify(e,null,2)):_n(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(q(` ✖ Could not connect to ${n}`)),console.error(K(` ${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 yn(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Y(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const bn=[{match(e,t){let n=yn(e,[`config`,`get`])&&Y(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Y(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
878
+ `)})}const{bold:G,dim:K,green:mn,red:q,yellow:hn,blue:gn}=u;function _n(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 vn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function J(e,t){try{return await vn(`${e}${t}`)}catch{return null}}async function yn(e){let[t,n,r,i,a]=await Promise.all([J(e,`/health`),J(e,`/metrics`),J(e,`/routes`),J(e,`/container`),J(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function bn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=K(`─`.repeat(60));if(console.log(),console.log(G(` KickJS Inspector`)+K(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?mn(`● healthy`):q(`● `+n.status);console.log(` ${G(`Health:`)} ${e}`)}else console.log(` ${G(`Health:`)} ${q(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?q:r.errorRate>0?hn:mn;console.log(` ${G(`Uptime:`)} ${_n(r.uptimeSeconds)}`),console.log(` ${G(`Requests:`)} ${r.requests}`),console.log(` ${G(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${K(`(`)}${t(e+`%`)}${K(`)`)}`)}if(a&&console.log(` ${G(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${G(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(G(` Routes`)),console.log(s),console.log(` ${K(`METHOD`)} ${K(`PATH`.padEnd(36))} ${K(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${c(e.method)} ${t} ${gn(e.controller)}.${K(e.handler)}`)}}console.log(s),console.log()}function xn(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 yn(r);t.json?console.log(JSON.stringify(e,null,2)):bn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(q(` ✖ Could not connect to ${n}`)),console.error(K(` ${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 Sn(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function Y(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Cn=[{match(e,t){let n=Sn(e,[`config`,`get`])&&Y(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&Y(e,[`undefined`,`is not defined`]);return!n&&!r?null:{confidence:n&&r?90:75,diagnosis:{id:`env-schema-not-registered`,title:`ConfigService.get() returns undefined for user-defined keys`,explanation:`Your src/index.ts is missing \`import "./config"\`. That side-effect import
879
879
  registers the env schema with kickjs at module-load time. Without it,
880
880
  ConfigService falls back to the base schema (PORT/NODE_ENV/LOG_LEVEL only)
881
881
  and every user-defined key reads as undefined. @Value() may *appear* to
@@ -897,7 +897,7 @@ describe('UserController', () => {
897
897
  beforeEach(() => Container.reset())
898
898
 
899
899
  it('does the thing', async () => { /* ... */ })
900
- })`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||yn(e,[`Module`,`is not a function`])||yn(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
900
+ })`,docs:`https://forinda.github.io/kick-js/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||Sn(e,[`Module`,`is not a function`])||Sn(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
901
901
  pattern instead: a class implements AppModule and exposes routes() that
902
902
  returns the controller wiring. This was a deliberate choice — modules
903
903
  become explicit values rather than metadata, which makes them easier to
@@ -949,24 +949,24 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
949
949
  import { UserModule } from './users/user.module'
950
950
  import { TaskModule } from './tasks/task.module' // ← was this missing?
951
951
 
952
- export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function xn(e,t){let n=null;for(let r of bn){let i=null;try{i=r.match(e,t)}catch{continue}!i||i.confidence<40||(!n||i.confidence>n.confidence)&&(n=i)}return n}async function Sn(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.
952
+ export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://forinda.github.io/kick-js/guide/project-structure.html`}}:null}}];function wn(e,t){let n=null;for(let r of Cn){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 Tn(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.
953
953
  export OPENAI_API_KEY="sk-..."
954
954
 
955
955
  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:
956
956
  kick add ai
957
957
 
958
958
  Or manually:
959
- pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=Cn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=wn((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 Cn(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://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
960
- `)}function wn(e){let t=[e,Tn(e),En(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Dn(t))return t}catch{continue}return null}function Tn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function En(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;continue}if(o===`\\`&&r){i=!0;continue}if(o===`"`){r=!r;continue}if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function Dn(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 On(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 jn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
959
+ pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=En(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Dn((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 En(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://forinda.github.io/kick-js/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
960
+ `)}function Dn(e){let t=[e,On(e),kn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(An(t))return t}catch{continue}return null}function On(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function kn(e){let t=e.indexOf(`{`);if(t===-1)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a++){let o=e[a];if(i){i=!1;continue}if(o===`\\`&&r){i=!0;continue}if(o===`"`){r=!r;continue}if(!r&&(o===`{`&&n++,o===`}`&&(n--,n===0)))return e.slice(t,a+1)}return null}function An(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&typeof t.title==`string`&&typeof t.explanation==`string`&&typeof t.fix==`string`}function jn(e){e.command(`explain [message]`).description(`Explain a KickJS error and suggest a fix`).option(`-m, --message <text>`,`Error message to explain (alternative to positional arg)`).option(`--ai`,`Fall back to LLM if no known-issue matches (requires @forinda/kickjs-ai)`).option(`--model <name>`,`Model name for the --ai fallback`,`gpt-4o-mini`).option(`--json`,`Output the diagnosis as JSON for tooling integration`).action(async(e,t)=>{let n=await Pn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
961
961
 
962
962
  Pass a message as a positional arg, --message flag, or pipe via stdin:
963
963
  kick explain "config.get returned undefined"
964
964
  pnpm test 2>&1 | kick explain
965
- `),process.exit(1));let r=Nn(),i=xn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
966
- `);return}if(i){Pn(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
967
- `),process.exit(2)),Fn(n,!1),process.exit(2));let a=await Sn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(kn(a),null,2)+`
968
- `),process.exit(a.kind===`ok`?0:2)),An(n,a),process.exit(a.kind===`ok`?0:2)})}function kn(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 An(e,t){if(t.kind===`ok`){Pn(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${X(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function jn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Mn()}function Mn(){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 Nn(){let e=process.cwd();return{cwd:e,hasFile:t=>M(j(e,t))}}function Pn(e,t,n,r=!1){let i=Z(e.trim(),200),a=r?`AI-generated — verify before applying`:In(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${X(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${X(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${X(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${X(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
969
- `)}function Fn(e,t){let n=Z(e.trim(),200);process.stdout.write(`\n Explaining: ${n}\n\n`),t?process.stdout.write(` No known-issue matched, and --ai fallback is not yet wired.
965
+ `),process.exit(1));let r=In(),i=wn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
966
+ `);return}if(i){Ln(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
967
+ `),process.exit(2)),Rn(n,!1),process.exit(2));let a=await Tn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Mn(a),null,2)+`
968
+ `),process.exit(a.kind===`ok`?0:2)),Nn(n,a),process.exit(a.kind===`ok`?0:2)})}function Mn(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 Nn(e,t){if(t.kind===`ok`){Ln(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${X(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${Z(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function Pn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:Fn()}function Fn(){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 In(){let e=process.cwd();return{cwd:e,hasFile:t=>M(j(e,t))}}function Ln(e,t,n,r=!1){let i=Z(e.trim(),200),a=r?`AI-generated — verify before applying`:zn(n);process.stdout.write(`\n Explaining: ${i}\n`),process.stdout.write(`\n Match: ${t.id} (${a})\n`),process.stdout.write(` Title: ${t.title}\n`),process.stdout.write(`\n Diagnosis:\n${X(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${X(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${X(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${X(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
969
+ `)}function Rn(e,t){let n=Z(e.trim(),200);process.stdout.write(`\n Explaining: ${n}\n\n`),t?process.stdout.write(` No known-issue matched, and --ai fallback is not yet wired.
970
970
  When @forinda/kickjs-ai ships its provider implementations,
971
971
  this command will call the configured LLM with the error +
972
972
  project context and return a structured fix.
@@ -985,10 +985,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
985
985
 
986
986
  `)}function X(e,t){return e.split(`
987
987
  `).map(e=>`${t}${e}`).join(`
988
- `)}function Z(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function In(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Ln(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(Rn),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(zn)}function Rn(e){let t=j(e.entry);M(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=Ne(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)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function zn(e){let t=process.cwd(),n=Bn(t)??ve(t),r=e.name??n,i=e.global?j(process.env.HOME??`.`,`.mcp.json`):j(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(M(i))try{let e=P(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,Te(i,JSON.stringify(o,null,2)+`
989
- `,`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 Bn(e){let t=j(e,`package.json`);if(!M(t))return null;try{let e=P(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Vn(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=j(t,e.entry);M(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Un(t,`tsx`);r||(console.error(`
988
+ `)}function Z(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function zn(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Bn(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(Vn),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(Hn)}function Vn(e){let t=j(e.entry);M(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=Le(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)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function Hn(e){let t=process.cwd(),n=Un(t)??Se(t),r=e.name??n,i=e.global?j(process.env.HOME??`.`,`.mcp.json`):j(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(M(i))try{let e=P(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,ke(i,JSON.stringify(o,null,2)+`
989
+ `,`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 Un(e){let t=j(e,`package.json`);if(!M(t))return null;try{let e=P(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function Wn(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=j(t,e.entry);M(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Kn(t,`tsx`);r||(console.error(`
990
990
  Error: tsx not found. Install it: pnpm add -D tsx
991
- `),process.exit(1));let i=Hn(n,e.entry),a=k(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Me(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Hn(e,t){return`
991
+ `),process.exit(1));let i=Gn(n,e.entry),a=k(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=Ie(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Gn(e,t){return`
992
992
  import 'reflect-metadata'
993
993
 
994
994
  // Prevent bootstrap() from starting the HTTP server
@@ -1042,30 +1042,32 @@ server.on('exit', () => {
1042
1042
  console.log('\\n Goodbye!\\n')
1043
1043
  process.exit(0)
1044
1044
  })
1045
- `}function Un(e,t){let n=e;for(;;){let e=k(n,`node_modules`,`.bin`,t);if(M(e))return e;let r=j(n,`..`);if(r===n)break;n=r}return null}async function Wn(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=p(t),s=S(t),c=i?d(a):a,u=k(n,c);if(!await o(u)){console.log(`\n Module not found: ${u}\n`);return}if(!r&&!await l({message:y.red(`Delete module '${c}' at ${u}? This cannot be undone.`),initialValue:!1})){console.log(`
1045
+ `}function Kn(e,t){let n=e;for(;;){let e=k(n,`node_modules`,`.bin`,t);if(M(e))return e;let r=j(n,`..`);if(r===n)break;n=r}return null}function qn(e,t){let n=RegExp(`^\\s*${S(t)}Module\\b`),r=!1,i=0,a=e;for(;;){let e=a.indexOf(`.mount(`,i);if(e===-1)break;let t=e+7,o=1,s=t;for(;s<a.length&&o>0;){let e=a.slice(s,s+2);if(e===`//`||e===`/*`){if(e===`//`)for(s+=2;s<a.length&&a[s]!==`
1046
+ `;)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]===`
1047
+ `);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Jn(e,t){let n=y(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=qn(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${S(t)}Module\\b(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),a=a.replace(/,(\s*])/,`$1`),e.slice(0,r)+a+e.slice(i)}async function Yn(e){let{name:n,modulesDir:r,force:i}=e,o=e.pluralize!==!1,s=t(n),c=x(n),l=o?g(s):s,d=k(r,l);if(!await a(d)){console.log(`\n Module not found: ${d}\n`);return}if(!i&&!await p({message:u.red(`Delete module '${l}' at ${d}? This cannot be undone.`),initialValue:!1})){console.log(`
1046
1048
  Cancelled.
1047
- `);return}await ke(u,{recursive:!0,force:!0}),console.log(` Deleted: ${u}`);let f=k(n,`index.ts`);if(await o(f)){let e=await F(f,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${s}Module\\s*\\}\\s*from\\s*['"][^'"]*${c}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=e.replace(RegExp(`\\s*,?\\s*${s}Module(?:\\s*\\(\\s*\\))?\\s*,?`,`g`),e=>{let t=e.trimStart().startsWith(`,`),n=e.trimEnd().endsWith(`,`);return t&&n?`,`:``}),e=e.replace(/,(\s*])/,`$1`),e=e.replace(/\n{3,}/g,`
1049
+ `);return}await Ne(d,{recursive:!0,force:!0}),console.log(` Deleted: ${d}`);let f=k(r,`index.ts`);if(await a(f)){let e=await F(f,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${S(c)}Module\\s*\\}\\s*from\\s*['"][^'"]*${S(l)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Jn(e,c),e=e.replace(/\n{3,}/g,`
1048
1050
 
1049
- `),e!==t&&(await I(f,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${f}`))}console.log(`\n Module '${c}' removed.\n`)}function Gn(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=C(await w(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Wn({name:n,modulesDir:j(r),force:t.force,pluralize:i})})}function Kn(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;console.warn(` kick typegen: unknown --schema-validator '${e}' (only 'zod' and 'false' are supported). Falling back to project config.`)}}function qn(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function Jn(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: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=process.cwd(),n=await w(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-DasN_2Zr.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-DBzZkJey.mjs`),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
1051
+ `),e!==t&&(await I(f,e,`utf-8`),console.log(` Unregistered: ${c}Module from ${f}`))}console.log(`\n Module '${l}' removed.\n`)}function Xn(e){e.command(`remove`).alias(`rm`).description(`Remove generated code`).command(`module <names...>`).description(`Remove one or more modules (e.g. kick rm module user task)`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular module name`).option(`-f, --force`,`Skip confirmation prompt`).action(async(e,t)=>{let n=C(await w(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Yn({name:n,modulesDir:j(r),force:t.force,pluralize:i})})}function Zn(e){if(e!==void 0){if(e===`false`||e===`off`||e===`none`)return!1;if(e===`zod`)return`zod`;console.warn(` kick typegen: unknown --schema-validator '${e}' (only 'zod' and 'false' are supported). Falling back to project config.`)}}function Qn(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function $n(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: fail on plugin-typegen drift instead of writing`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").action(async e=>{let t=process.cwd(),n=await w(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-CiWyeMpX.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-DNnIUbGs.mjs`),r=e([...t,...n?.plugins??[]],n?.commands??[]),i=new Set(n?.typegen?.disable??[]);if(r.typegens.length===0){console.log(` No typegen plugins registered.`);return}let a=Math.max(...r.typegens.map(e=>e.id.length));console.log(`
1050
1052
  Registered typegen plugins:
1051
- `);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let r=Kn(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=qn(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ge(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await E(a);let r=await W({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&r.some(e=>e.status===`written`)&&process.exit(1)}}catch(e){e instanceof me?console.error(`
1053
+ `);for(let e of r.typegens){let t=i.has(e.id)?` (disabled)`:``;console.log(` ${e.id.padEnd(a+2)}inputs: ${e.inputs.join(`, `)||`(none)`}${t}`)}console.log();return}let r=Zn(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Qn(e.envFile)??n?.typegen?.envFile,a={cwd:t,srcDir:e.src??n?.typegen?.srcDir,outDir:e.out??n?.typegen?.outDir,silent:e.silent,allowDuplicates:e.allowDuplicates,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await ve(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{let{result:r}=await E(a),i=await W({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&i.some(e=>e.status===`written`)&&process.exit(1),e.check||await ye(j(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r.written,i,e.silent??!1)}}catch(e){e instanceof xe?console.error(`
1052
1054
  `+e.message+`
1053
- `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Yn(e){let t=[];if(!M(e))return t;let n=Se(e,{withFileTypes:!0});for(let r of n){let n=k(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Yn(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Xn(e){try{return P(e,`utf-8`)}catch{return``}}const Zn=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Qn(e,t){let n=Xn(k(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Zn.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 $n(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 er(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 tr(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function nr(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 rr(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 ir(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 ar(e){let t=Yn(k(e,`src`)).map(e=>Xn(e)),n=[],r=Qn(e,t);r&&n.push(r);let i=$n(t);i&&n.push(i);let a=er(t);a&&n.push(a);let o=tr();o&&n.push(o);let s=nr(t);return s&&n.push(s),n.push(rr(t)),n.push(ir(t)),n}function or(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
1055
+ `):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function er(e){let t=[];if(!M(e))return t;let n=Ee(e,{withFileTypes:!0});for(let r of n){let n=k(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...er(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function tr(e){try{return P(e,`utf-8`)}catch{return``}}const nr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function rr(e,t){let n=tr(k(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(nr.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 ir(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 ar(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 or(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function sr(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 cr(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 lr(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 ur(e){let t=er(k(e,`src`)).map(e=>tr(e)),n=[],r=rr(e,t);r&&n.push(r);let i=ir(t);i&&n.push(i);let a=ar(t);a&&n.push(a);let o=or();o&&n.push(o);let s=sr(t);return s&&n.push(s),n.push(cr(t)),n.push(lr(t)),n}function dr(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
1054
1056
  Usage: kick check --deploy
1055
1057
 
1056
1058
  Available checks:
1057
1059
  --deploy Audit for production readiness (security, config, best practices)
1058
- `);return}let n=process.cwd();t(`KickJS Deploy Check`);let i=s();i.start(`Scanning project...`);let o=ar(n);i.stop(`Scan complete`);let c={CRITICAL:0,WARNING:1,INFO:2};o.sort((e,t)=>c[e.severity]-c[t.severity]);for(let e of o)x.message(`${a(e.severity)} ${e.message}`);let l=o.filter(e=>e.severity===`CRITICAL`).length,u=o.filter(e=>e.severity===`WARNING`).length,d=o.filter(e=>e.severity===`INFO`).length,f=u===1?`warning`:`warnings`,p=[l>0?y.red(`${l} critical`):`${l} critical`,u>0?y.yellow(`${u} ${f}`):`${u} ${f}`,`${d} info`].join(`, `);l>0?(r(y.red(`${p} — fix critical issues before deploying`)),process.exit(1)):r(y.green(`${p} — looking good!`))})}async function Q(e){return qe({configPath:D.resolve(process.cwd(),e.config)})}async function $(e){if(e.adapter){let t=await e.adapter();return{adapter:t,cleanup:async()=>t.close()}}if(!e.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL) in kick.config.ts, or supply db.adapter() factory`);let t=e.dialect??`postgres`;if(t!==`postgres`)throw Error(`kickjs-db: built-in CLI adapter only supports postgres in M1 (dialect=${t}); use db.adapter() factory for other dialects`);let[{pgAdapter:n},r]=await Promise.all([import(`@forinda/kickjs-db-pg`),import(`pg`)]),i=new r.default.Pool({connectionString:e.connectionString}),a=n({pool:i});return{adapter:a,cleanup:async()=>{await a.close(),await i.end()}}}function sr(e){if(e.length===0){console.log(`No migrations.`);return}console.table(e.map(e=>({id:e.id,state:e.state,batch:e.batch??`-`,reviewed:e.reviewed,applied:e.appliedAt??`-`})))}function cr(e){let t=e.command(`db`).description(`Database commands (kickjs-db)`);t.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(e,t)=>{let n=process.cwd(),r=await Be({name:e,config:await Q(t),cwd:n,empty:t.empty});if(r.status===`no-changes`){console.log(`No schema changes detected.`);return}if(r.empty){console.log(`Created empty migration ${r.migrationDir} (author up.sql + down.sql).`);return}let i=r.changeCount===1?``:`s`;console.log(`Created migration ${r.migrationDir} (${r.changeCount} change${i}).`)});let n=t.command(`migrate`).description(`Migration runner subcommands`);n.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await He({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await r()}}),n.command(`up`).description(`Apply the next single pending migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await Ge({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await r()}}),n.command(`down`).description(`Reverse the most recent applied migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ve({adapter:n,migrationsDir:t.migrationsDir});e.reversed?console.log(`Reversed ${e.reversed}.`):console.log(`Nothing to reverse.`)}finally{await r()}}),n.command(`rollback`).description(`Reverse the entire last batch as a single unit`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ue({adapter:n,migrationsDir:t.migrationsDir});e.reversed.length===0?console.log(`Nothing to roll back.`):console.log(`Rolled back batch ${e.batch}: ${e.reversed.join(`, `)}`)}finally{await r()}}),n.command(`status`).description(`Print applied + pending migrations`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{sr(await We({adapter:n,migrationsDir:t.migrationsDir}))}finally{await r()}}),t.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await n.introspect();if(e.json){console.log(JSON.stringify(r,null,2));return}let i=e.out??t.schemaPath;await I(i,Ke(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}function lr(e){return e.optsWithGlobals().dryRun??!1}function ur(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.
1060
+ `);return}let t=process.cwd();r(`KickJS Deploy Check`);let a=ne();a.start(`Scanning project...`);let o=ur(t);a.stop(`Scan complete`);let s={CRITICAL:0,WARNING:1,INFO:2};o.sort((e,t)=>s[e.severity]-s[t.severity]);for(let e of o)n.message(`${i(e.severity)} ${e.message}`);let c=o.filter(e=>e.severity===`CRITICAL`).length,l=o.filter(e=>e.severity===`WARNING`).length,d=o.filter(e=>e.severity===`INFO`).length,f=l===1?`warning`:`warnings`,p=[c>0?u.red(`${c} critical`):`${c} critical`,l>0?u.yellow(`${l} ${f}`):`${l} ${f}`,`${d} info`].join(`, `);c>0?(b(u.red(`${p} — fix critical issues before deploying`)),process.exit(1)):b(u.green(`${p} — looking good!`))})}async function Q(e){return Ze({configPath:D.resolve(process.cwd(),e.config)})}async function $(e){if(e.adapter){let t=await e.adapter();return{adapter:t,cleanup:async()=>t.close()}}if(!e.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL) in kick.config.ts, or supply db.adapter() factory`);let t=e.dialect??`postgres`;if(t!==`postgres`)throw Error(`kickjs-db: built-in CLI adapter only supports postgres in M1 (dialect=${t}); use db.adapter() factory for other dialects`);let[{pgAdapter:n},r]=await Promise.all([import(`@forinda/kickjs-db-pg`),import(`pg`)]),i=new r.default.Pool({connectionString:e.connectionString}),a=n({pool:i});return{adapter:a,cleanup:async()=>{await a.close(),await i.end()}}}function fr(e){if(e.length===0){console.log(`No migrations.`);return}console.table(e.map(e=>({id:e.id,state:e.state,batch:e.batch??`-`,reviewed:e.reviewed,applied:e.appliedAt??`-`})))}function pr(e){let t=e.command(`db`).description(`Database commands (kickjs-db)`);t.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(e,t)=>{let n=process.cwd(),r=await We({name:e,config:await Q(t),cwd:n,empty:t.empty});if(r.status===`no-changes`){console.log(`No schema changes detected.`);return}if(r.empty){console.log(`Created empty migration ${r.migrationDir} (author up.sql + down.sql).`);return}let i=r.changeCount===1?``:`s`;console.log(`Created migration ${r.migrationDir} (${r.changeCount} change${i}).`)});let n=t.command(`migrate`).description(`Migration runner subcommands`);n.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await Ke({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await r()}}),n.command(`up`).description(`Apply the next single pending migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await Ye({adapter:n,migrationsDir:t.migrationsDir,confirmEnumDrop:e.confirmEnumDrop});r.applied.length===0?console.log(`No pending migrations.`):console.log(`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await r()}}),n.command(`down`).description(`Reverse the most recent applied migration`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await Ge({adapter:n,migrationsDir:t.migrationsDir});e.reversed?console.log(`Reversed ${e.reversed}.`):console.log(`Nothing to reverse.`)}finally{await r()}}),n.command(`rollback`).description(`Reverse the entire last batch as a single unit`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let e=await qe({adapter:n,migrationsDir:t.migrationsDir});e.reversed.length===0?console.log(`Nothing to roll back.`):console.log(`Rolled back batch ${e.batch}: ${e.reversed.join(`, `)}`)}finally{await r()}}),n.command(`status`).description(`Print applied + pending migrations`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{fr(await Je({adapter:n,migrationsDir:t.migrationsDir}))}finally{await r()}}),t.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`-c, --config <path>`,`Path to kick.config.ts`,`kick.config.ts`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async e=>{let t=await Q(e),{adapter:n,cleanup:r}=await $(t);try{let r=await n.introspect();if(e.json){console.log(JSON.stringify(r,null,2));return}let i=e.out??t.schemaPath;await I(i,Xe(r),`utf8`);let a=Object.keys(r.tables).length;console.log(`Wrote ${i} (${a} table${a===1?``:`s`}).`)}finally{await r()}})}function mr(e){return e.optsWithGlobals().dryRun??!1}function hr(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.
1059
1061
  Direction defaults to \`modules.style\` from kick.config (or "define").
1060
1062
  --target define|class Override the migration direction.
1061
1063
  --apply Apply the changes (default: dry-run preview).
1062
- --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=lr(t)||!e.apply;c(n),e.experimental||(console.error(`
1063
- `+y.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
1064
+ --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=mr(t)||!e.apply;o(n),e.experimental||(console.error(`
1065
+ `+u.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
1064
1066
  The regex-based rewrite handles the shapes our templates produce.
1065
1067
  Hand-rolled modules with non-standard structures may be skipped.
1066
1068
  Always commit before running with --apply.
1067
- `),process.exit(1));let r=C(await w(process.cwd())),i=j(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${y.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=y.dim(`→ ${a}`),s=n?y.dim(`(dry-run)`):y.bold(`(applying)`);console.log(`\n ${y.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${y.dim(i)}\n`);let l=e.backup!==!1&&!n,u=await bt(i,{dryRun:n,target:a,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${y.green(`✓`)} backup: ${y.dim(e)}\n ${y.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else !n&&e.backup===!1&&console.log(` ${y.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${y.green(`✓`)} ${e.path}`);else{f++;let t=y.dim(`(${e.reason??`skipped`})`);console.log(` ${y.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${y.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=y.dim(`(${u.indexReason??`skipped`})`);console.log(` ${y.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${y.dim(`-`)} ${u.indexPath} ${y.dim(`(not found)`)}`);let p=n?y.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${y.bold(String(d))} migrated, ${y.bold(String(f))} skipped${p}\n`)})}const dr=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],fr=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=pr(e.cwd);if(!t)return null;let n=D.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${mr(D.relative(n,t)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
1068
- `)}});function pr(e){for(let t of dr){let n=D.resolve(e,t);if(t.endsWith(`.ts`)){if(M(n))return n}else{let e=D.join(n,`index.ts`);if(M(e))return e}}return null}function mr(e){return e.replace(/\\/g,`/`)}const hr=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!M(D.resolve(e.cwd,`kick.config.ts`)))return null;let t=await w(e.cwd);if(!t?.assetMap)return null;let n=pe(t.assetMap,e.cwd);return n.count===0?null:he(n)}}),gr="/* 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 _r(e,t,n){if(e.length===0)return`${gr}
1069
+ `),process.exit(1));let r=C(await w(process.cwd())),i=j(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${u.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let s=u.dim(`→ ${a}`),c=n?u.dim(`(dry-run)`):u.bold(`(applying)`);console.log(`\n ${u.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${u.dim(i)}\n`);let l=e.backup!==!1&&!n,d=await wt(i,{dryRun:n,target:a,backup:l});if(d.backupDir){let e=d.backupDir;console.log(` ${u.green(`✓`)} backup: ${u.dim(e)}\n ${u.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else !n&&e.backup===!1&&console.log(` ${u.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,p=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${u.green(`✓`)} ${e.path}`);else{p++;let t=u.dim(`(${e.reason??`skipped`})`);console.log(` ${u.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${u.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=u.dim(`(${d.indexReason??`skipped`})`);console.log(` ${u.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${u.dim(`-`)} ${d.indexPath} ${u.dim(`(not found)`)}`);let m=n?u.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${u.bold(String(f))} migrated, ${u.bold(String(p))} skipped${m}\n`)})}const gr=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],_r=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(e){let t=vr(e.cwd);if(!t)return null;let n=D.resolve(e.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${yr(D.relative(n,t)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
1070
+ `)}});function vr(e){for(let t of gr){let n=D.resolve(e,t);if(t.endsWith(`.ts`)){if(M(n))return n}else{let e=D.join(n,`index.ts`);if(M(e))return e}}return null}function yr(e){return e.replace(/\\/g,`/`)}const br=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!M(D.resolve(e.cwd,`kick.config.ts`)))return null;let t=await w(e.cwd);if(!t?.assetMap)return null;let n=ge(t.assetMap,e.cwd);return n.count===0?null:be(n)}}),xr="/* 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 Sr(e,t,n){if(e.length===0)return`${xr}
1069
1071
  // (no routes discovered yet — annotate a controller method with
1070
1072
  // @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
1071
1073
  declare global {
@@ -1074,8 +1076,8 @@ declare global {
1074
1076
  }
1075
1077
 
1076
1078
  export {}
1077
- `;let r=new Map;for(let t of e){let e=r.get(t.controller)??[];e.push(t),r.set(t.controller,e)}let i=new Map,a=(e,r)=>{let a=br(e,r,t,n,i);return a?`import('zod').infer<typeof ${a}>`:null},o=[];for(let[e,t]of r){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=a(e.bodySchema,e.filePath),i=a(e.querySchema,e.filePath),o=a(e.paramsSchema,e.filePath)??t,s=r??`unknown`,c=i??vr(e),l=yr(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${o}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),o.push(n.join(`
1078
- `))}return`${gr}${xr(i)}
1079
+ `;let r=new Map;for(let t of e){let e=r.get(t.controller)??[];e.push(t),r.set(t.controller,e)}let i=new Map,a=(e,r)=>{let a=Tr(e,r,t,n,i);return a?`import('zod').infer<typeof ${a}>`:null},o=[];for(let[e,t]of r){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=a(e.bodySchema,e.filePath),i=a(e.querySchema,e.filePath),o=a(e.paramsSchema,e.filePath)??t,s=r??`unknown`,c=i??Cr(e),l=wr(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...l.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${o}`,` body: ${s}`,` query: ${c}`,` response: unknown`,` }`)}n.push(` }`),o.push(n.join(`
1080
+ `))}return`${xr}${Er(i)}
1079
1081
  declare global {
1080
1082
  // eslint-disable-next-line @typescript-eslint/no-namespace
1081
1083
  namespace KickRoutes {
@@ -1085,9 +1087,9 @@ ${o.join(`
1085
1087
  }
1086
1088
 
1087
1089
  export {}
1088
- `}function vr(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function yr(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 br(e,t,n,r,i){if(!e||r!==`zod`||e.source===null)return null;let a=Sr(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 xr(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(`
1090
+ `}function Cr(e){if(e.queryFilterable===null)return`unknown`;let t=e.querySortable??[];return`{ filter?: string | string[]; sort?: ${t.length>0?t.flatMap(e=>[`'${e}'`,`'-${e}'`]).join(` | `):`string`}; q?: string; page?: string; limit?: string }`}function wr(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 Tr(e,t,n,r,i){if(!e||r!==`zod`||e.source===null)return null;let a=Dr(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 Er(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(`
1089
1091
  `)+`
1090
- `}function Sr(e,t,n){if(e===null)return`unknown`;let r=O(n);if(e===``){let e=A(r,t).split(be).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=A(r,j(O(t),e)).split(be).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const Cr=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:wr(e),cwd:e.cwd,envFile:Tr(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return _r(t.routes,r,n)}});function wr(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Tr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function Er(e,t){if(!e)return null;let n=A(O(t),e.filePath).split(be).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),`/* eslint-disable */
1092
+ `}function Dr(e,t,n){if(e===null)return`unknown`;let r=O(n);if(e===``){let e=A(r,t).split(we).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=A(r,j(O(t),e)).split(we).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}const Or=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:kr(e),cwd:e.cwd,envFile:Ar(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=D.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Sr(t.routes,r,n)}});function kr(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ar(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function jr(e,t){if(!e)return null;let n=A(O(t),e.filePath).split(we).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),`/* eslint-disable */
1091
1093
  // AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
1092
1094
  // Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
1093
1095
 
@@ -1123,5 +1125,5 @@ declare global {
1123
1125
  }
1124
1126
 
1125
1127
  export {}
1126
- `}const Dr=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=kr(e);if(t===!1)return null;let n=await e.getScanResult({root:Or(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=D.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return Er(n.env,r)}});function Or(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function kr(e){return e.config?.typegen?.envFile}const Ar=[T({name:`kick/init`,register:rt}),T({name:`kick/generate`,register:Xt}),T({name:`kick/run`,register:ln}),T({name:`kick/info`,register:un}),T({name:`kick/inspect`,register:vn}),T({name:`kick/add`,register:tt}),T({name:`kick/list`,register:et}),T({name:`kick/explain`,register:On}),T({name:`kick/mcp`,register:Ln}),T({name:`kick/tinker`,register:Vn}),T({name:`kick/remove`,register:Gn}),T({name:`kick/typegen`,register:Jn}),T({name:`kick/check`,register:or}),T({name:`kick/db`,register:cr,typegens:[fr()]}),T({name:`kick/codemod`,register:ur}),T({name:`kick/assets`,typegens:[hr()]}),T({name:`kick/routes`,typegens:[Cr()]}),T({name:`kick/env`,typegens:[Dr()]})];export{Ar as builtinCliPlugins,en as n,W as t};
1127
- //# sourceMappingURL=builtins-DBzZkJey.mjs.map
1128
+ `}const Mr=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Pr(e);if(t===!1)return null;let n=await e.getScanResult({root:Nr(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=D.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return jr(n.env,r)}});function Nr(e){return D.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Pr(e){return e.config?.typegen?.envFile}const Fr=[T({name:`kick/init`,register:st}),T({name:`kick/generate`,register:$t}),T({name:`kick/run`,register:fn}),T({name:`kick/info`,register:pn}),T({name:`kick/inspect`,register:xn}),T({name:`kick/add`,register:at}),T({name:`kick/list`,register:it}),T({name:`kick/explain`,register:jn}),T({name:`kick/mcp`,register:Bn}),T({name:`kick/tinker`,register:Wn}),T({name:`kick/remove`,register:Xn}),T({name:`kick/typegen`,register:$n}),T({name:`kick/check`,register:dr}),T({name:`kick/db`,register:pr,typegens:[_r()]}),T({name:`kick/codemod`,register:hr}),T({name:`kick/assets`,typegens:[br()]}),T({name:`kick/routes`,typegens:[Or()]}),T({name:`kick/env`,typegens:[Mr()]})];export{Fr as builtinCliPlugins,rn as n,W as t};
1129
+ //# sourceMappingURL=builtins-DNnIUbGs.mjs.map