@forinda/kickjs-cli 6.15.0 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-docs-RzUq1w3g.mjs → agent-docs-CskjGFT3.mjs} +2 -2
- package/dist/{agent-docs-UjZY8eIH.mjs → agent-docs-ziibOmI4.mjs} +3 -3
- package/dist/{agent-docs-UjZY8eIH.mjs.map → agent-docs-ziibOmI4.mjs.map} +1 -1
- package/dist/{build-D5YferX_.mjs → build-Bq2FP8WN.mjs} +2 -2
- package/dist/{build-BFVauqjB.mjs → build-DZXFg_64.mjs} +3 -3
- package/dist/{build-BFVauqjB.mjs.map → build-DZXFg_64.mjs.map} +1 -1
- package/dist/{builtins-BcVTwsM2.mjs → builtins-Cs2-TWwj.mjs} +163 -170
- package/dist/{builtins-DmHWitfb.mjs → builtins-eX32WH9F.mjs} +2 -2
- package/dist/cli.mjs +2 -2
- package/dist/config-Cq-quG7q.mjs +13 -0
- package/dist/config-Cq-quG7q.mjs.map +1 -0
- package/dist/config-o2ganxLo.mjs +12 -0
- package/dist/{doctor-SbR1xW8I.mjs → doctor-DOcvYGMG.mjs} +24 -29
- package/dist/doctor-DOcvYGMG.mjs.map +1 -0
- package/dist/fullstack-5paK85Qh.mjs +190 -0
- package/dist/fullstack-5paK85Qh.mjs.map +1 -0
- package/dist/fullstack-DccMBr2Y.mjs +189 -0
- package/dist/index.d.mts +36 -22
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-BsRrj_kY.mjs → plugin-BXf1bhiA.mjs} +2 -2
- package/dist/{plugin-DTQnluc3.mjs → plugin-CyiOvPC4.mjs} +3 -3
- package/dist/{plugin-DTQnluc3.mjs.map → plugin-CyiOvPC4.mjs.map} +1 -1
- package/dist/{project-CcOnvi2Z.mjs → project-RMuxqw1k.mjs} +24 -15
- package/dist/project-RMuxqw1k.mjs.map +1 -0
- package/dist/{project-GekbCLn_.mjs → project-ZXTSFnxa.mjs} +22 -13
- package/dist/{project-docs-CwjrMj8x.mjs → project-docs-C64R8KF2.mjs} +6 -6
- package/dist/project-docs-C64R8KF2.mjs.map +1 -0
- package/dist/{project-docs-DT-rkK_c.mjs → project-docs-OH_dzRY0.mjs} +5 -5
- package/dist/{project-root-Cl_W-7A_.mjs → project-root-BMn6XJ0F.mjs} +2 -2
- package/dist/{project-root-D_srTNIh.mjs → project-root-D8FOMFdT.mjs} +3 -3
- package/dist/{project-root-D_srTNIh.mjs.map → project-root-D8FOMFdT.mjs.map} +1 -1
- package/dist/{prompts-B7kUC0iX.mjs → prompts-CW0Y_P2D.mjs} +2 -2
- package/dist/{prompts-B7kUC0iX.mjs.map → prompts-CW0Y_P2D.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DJDWk3oJ.mjs → rolldown-runtime-BaQcsmMo.mjs} +1 -1
- package/dist/{run-plugins-BQPBSfB7.mjs → run-plugins-w_jNdZ-F.mjs} +127 -129
- package/dist/run-plugins-w_jNdZ-F.mjs.map +1 -0
- package/dist/{typegen-oYhFwjVU.mjs → typegen-ID6CHFZr.mjs} +5 -5
- package/dist/{typegen-oYhFwjVU.mjs.map → typegen-ID6CHFZr.mjs.map} +1 -1
- package/dist/{typegen-D0790Kwg.mjs → typegen-_JlS_scO.mjs} +4 -4
- package/dist/{types-B2U2Sfj5.mjs → types-DYDvLhqy.mjs} +1 -1
- package/package.json +1 -1
- package/dist/config-BR-SjJdX.mjs +0 -13
- package/dist/config-BR-SjJdX.mjs.map +0 -1
- package/dist/config-CHhcvsYA.mjs +0 -12
- package/dist/doctor-SbR1xW8I.mjs.map +0 -1
- package/dist/fullstack-C9MW0tvI.mjs +0 -137
- package/dist/fullstack-dCjwUVC7.mjs +0 -138
- package/dist/fullstack-dCjwUVC7.mjs.map +0 -1
- package/dist/project-CcOnvi2Z.mjs.map +0 -1
- package/dist/project-docs-CwjrMj8x.mjs.map +0 -1
- package/dist/run-plugins-BQPBSfB7.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli
|
|
2
|
+
* @forinda/kickjs-cli v7.0.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{c as e,l as t,s as n}from"./project-docs-
|
|
11
|
+
import{c as e,l as t,s as n}from"./project-docs-C64R8KF2.mjs";import{a as r,c as i,d as a,i as o,l as s,n as c,o as l,r as u,s as d,t as f,u as p}from"./prompts-CW0Y_P2D.mjs";import{A as m,C as h,D as g,E as _,F as v,I as y,M as b,N as ee,O as te,P as x,S,T as ne,_ as re,a as C,b as ie,c as ae,f as oe,g as se,h as ce,i as le,j as w,k as ue,l as de,m as fe,p as pe,r as me,u as he,v as ge,w as _e,x as ve,y as ye}from"./doctor-DOcvYGMG.mjs";import{a as be,c as xe,o as Se,r as Ce,t as we,u as Te}from"./project-RMuxqw1k.mjs";import{a as T,c as Ee,i as De,o as E,s as Oe}from"./config-Cq-quG7q.mjs";import{t as ke}from"./project-root-D8FOMFdT.mjs";import{n as D}from"./types-DYDvLhqy.mjs";import{t as Ae}from"./build-DZXFg_64.mjs";import{n as je}from"./agent-docs-ziibOmI4.mjs";import{n as Me}from"./plugin-CyiOvPC4.mjs";import{a as Ne,c as Pe,d as Fe,f as Ie,g as Le,h as Re,i as ze,l as Be,m as Ve,o as He,p as Ue,r as We,s as Ge,t as Ke,u as qe}from"./typegen-ID6CHFZr.mjs";import{createRequire as Je}from"node:module";import O,{basename as Ye,dirname as k,join as A,relative as Xe,resolve as j,sep as Ze}from"node:path";import{cpSync as Qe,existsSync as M,mkdirSync as $e,readFileSync as N,readdirSync as P,rmSync as et,writeFileSync as tt}from"node:fs";import{copyFile as nt,mkdir as F,readFile as I,readdir as rt,rm as it,stat as at,writeFile as L}from"node:fs/promises";import{fork as ot,spawn as st,spawnSync as ct}from"node:child_process";import{fileURLToPath as lt,pathToFileURL as R}from"node:url";import{arch as ut,platform as dt,release as ft}from"node:os";const pt=[{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 mt(e){e.command(`new [name]`).alias(`init`).description(`Create a new KickJS project (use "." for current directory)`).option(`-d, --directory <dir>`,`Target directory (defaults to project name)`).option(`--pm <manager>`,`Package manager: pnpm | npm | yarn | bun`).option(`--git`,`Initialize git repository`).option(`--no-git`,`Skip git initialization`).option(`--install`,`Install dependencies after scaffolding`).option(`--no-install`,`Skip dependency installation`).option(`-f, --force`,`Remove existing files without prompting`).option(`-t, --template <type>`,`Project template: rest | minimal | fullstack`).option(`--runtime <engine>`,`HTTP runtime: express | fastify | h3`).option(`-r, --repo <type>`,`Repository name (inmemory, or any DB name e.g. postgres)`).option(`-s, --schema <lib>`,`Schema library for env / DTOs: zod | valibot | yup (default: zod)`).option(`--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,t)=>{c(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await i({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let a;if(e===`.`?(a=j(`.`),e=Ye(a)):a=j(t.directory||e),M(a)){let i=P(a);if(i.length>0){if(t.force)u.warn(`Clearing existing files in ${a}`);else if(n){u.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),r(`Aborted.`);return}else{u.warn(`Directory "${e}" is not empty:`);let t=i.slice(0,5);for(let e of t)u.message(` - ${e}`);if(i.length>5&&u.message(` ... and ${i.length-5} more`),!await f({message:p.red(`Remove all existing files and proceed?`),initialValue:!1})){r(`Aborted.`);return}}for(let e of i)et(j(a,e),{recursive:!0,force:!0})}}let s=t.template;s||=n?`minimal`:await l({message:`Project template`,options:[{value:`rest`,label:`REST API`,hint:`Express + Swagger`},{value:`minimal`,label:`Minimal`,hint:`bare Express`},{value:`fullstack`,label:`Fullstack`,hint:`server + Vite React web, typed client`}]});let d=t.runtime;d||=n?`express`:await l({message:`HTTP runtime`,options:[{value:`express`,label:`Express`,hint:`default, zero-config`},{value:`fastify`,label:`Fastify`,hint:`fastify + @fastify/middie`},{value:`h3`,label:`h3`,hint:`Nitro / Nuxt engine`}]});let m=t.pm;m||=n?await xe(void 0):await l({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let h=t.repo;h||=n?`inmemory`:await i({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Ee(h);let g=t.schema;g||=n?`zod`:await l({message:`Schema library (env + DTO validation)`,options:[{value:`zod`,label:`Zod`,hint:`default — broad ecosystem`},{value:`valibot`,label:`Valibot`,hint:`smaller bundle`},{value:`yup`,label:`Yup`,hint:`classic API`}]}),[`zod`,`valibot`,`yup`].includes(g)||(u.warn(`Unknown --schema "${g}", falling back to zod.`),g=`zod`);let _;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();_=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else _=n?[]:await o({message:`Select packages to include`,options:[...pt],required:!1});let v;v=t.git===void 0?n?!0:await f({message:`Initialize git repository?`,initialValue:!0}):t.git;let y;if(y=t.install===void 0?n?!0:await f({message:`Install dependencies?`,initialValue:!0}):t.install,s===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-5paK85Qh.mjs`);await t({name:e,directory:a,packageManager:m,initGit:v,installDeps:y,schemaLib:g,runtime:d}),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${m}${m===`pnpm`?` dev`:` run dev:server`}`)}`);return}await we({name:e,directory:a,packageManager:m,initGit:v,installDeps:y,template:s,defaultRepo:h,packages:_,schemaLib:g,runtime:d}),r(`Done! Next steps: ${p.cyan(`cd ${e} && ${m} dev`)}`)})}async function ht(e){let{name:n,outDir:r}=e,i=v(n),a=y(n),o=[],s=A(r,`${i}.plugin.ts`);return await t(s,`import {
|
|
12
12
|
definePlugin,
|
|
13
13
|
type AppAdapter,
|
|
14
14
|
type AppModuleEntry,
|
|
@@ -154,11 +154,11 @@ export const ${a}Plugin = definePlugin<${a}PluginConfig>({
|
|
|
154
154
|
},
|
|
155
155
|
}),
|
|
156
156
|
})
|
|
157
|
-
`),o.push(s),o}function
|
|
157
|
+
`),o.push(s),o}function gt(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>{let[t,n]=e.split(`:`).map(e=>e.trim());return{name:t,type:n||`string`}}).filter(e=>e.name.length>0):[]}async function _t(e){let{name:n,moduleName:r,modulesDir:i,pattern:a}=e,o=e.type??`http`,s=v(n),c=y(n),l=e.key??x(n),u=Array.isArray(e.params)?e.params:gt(e.params),d=ge({type:`contributor`,outDir:e.outDir,moduleName:r,modulesDir:i,defaultDir:`src/contributors`,pattern:a,shouldPluralize:e.pluralize??!0}),f=o===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,p=o===`http`?`RequestContext`:`ExecutionContext`,m=u.length>0?`\nexport type ${c}Params = {\n${u.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
158
158
|
`)}\n}\n`:``,h=u.length>0?`${f}.withParams<${c}Params>()({`:`${f}({`,g=u.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
159
159
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
160
160
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
161
|
-
requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,
|
|
161
|
+
requiredParams: [${u.map(e=>`'${e.name}'`).join(`, `)}],\n`:``,_=u.length>0?`(ctx, _deps, params)`:`(ctx)`,b=u.length>0?` // \`params\` is typed as ${c}Params (call-site params merged onto any paramDefaults).`:` // \`ctx\` is a ${p} — read ctx.req / ctx.headers / ctx.params (http) or ctx.get (bare).`,ee=`import { ${f} } from '@forinda/kickjs'
|
|
162
162
|
import type { ${p} } from '@forinda/kickjs'
|
|
163
163
|
|
|
164
164
|
/**
|
|
@@ -200,12 +200,12 @@ ${m}
|
|
|
200
200
|
export const ${c} = ${h}
|
|
201
201
|
key: '${l}',
|
|
202
202
|
${g} resolve: ${_} => {
|
|
203
|
-
${
|
|
203
|
+
${b}
|
|
204
204
|
// TODO: compute and return the value written to ctx.set('${l}', …)
|
|
205
205
|
throw new Error("${c} contributor: resolve() not implemented")
|
|
206
206
|
},
|
|
207
207
|
})
|
|
208
|
-
`,
|
|
208
|
+
`,te=A(d,`${s}.contributor.ts`);return await t(te,ee),[te]}async function vt(e){let n=A(e.outDir,`kick.config.ts`),r=e.modulesDir??`src/modules`,i=e.defaultRepo??`inmemory`;return M(n)&&!e.force&&!await f({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
209
209
|
Skipped — existing kick.config.ts preserved.`),[]):(await t(n,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
210
210
|
|
|
211
211
|
export default defineConfig({
|
|
@@ -223,71 +223,43 @@ export default defineConfig({
|
|
|
223
223
|
{
|
|
224
224
|
name: 'test',
|
|
225
225
|
description: 'Run tests with Vitest',
|
|
226
|
-
steps: '
|
|
226
|
+
steps: 'vitest run',
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
name: 'lint',
|
|
230
|
+
description: 'Lint with oxlint',
|
|
231
|
+
steps: 'oxlint src/',
|
|
227
232
|
},
|
|
228
233
|
{
|
|
229
234
|
name: 'format',
|
|
230
|
-
description: 'Format code with
|
|
231
|
-
steps: '
|
|
235
|
+
description: 'Format code with oxfmt',
|
|
236
|
+
steps: 'oxfmt src/',
|
|
232
237
|
},
|
|
233
238
|
{
|
|
234
239
|
name: 'format:check',
|
|
235
240
|
description: 'Check formatting without writing',
|
|
236
|
-
steps: '
|
|
241
|
+
steps: 'oxfmt --check src/',
|
|
237
242
|
},
|
|
238
243
|
{
|
|
239
244
|
name: 'ci:check',
|
|
240
|
-
description: 'Run typecheck + format check',
|
|
241
|
-
steps: ['
|
|
245
|
+
description: 'Run typecheck + lint + format check',
|
|
246
|
+
steps: ['kick typecheck', 'oxlint src/', 'oxfmt --check src/'],
|
|
242
247
|
aliases: ['verify'],
|
|
243
248
|
},
|
|
244
249
|
],
|
|
245
250
|
})
|
|
246
|
-
`),[n])}function
|
|
251
|
+
`),[n])}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(`
|
|
247
252
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
248
|
-
`)}function
|
|
253
|
+
`)}function yt(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 bt(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 xt(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=yt(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({
|
|
249
254
|
name: '${r}',
|
|
250
255
|
build: () => ({
|
|
251
256
|
${p}
|
|
252
257
|
}),
|
|
253
|
-
})`}${c}`}}function
|
|
254
|
-
`||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=
|
|
258
|
+
})`}${c}`}}function St(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]===`
|
|
259
|
+
`||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=bt(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 {
|
|
255
260
|
${y}
|
|
256
261
|
}
|
|
257
|
-
`}${u}`}}function
|
|
258
|
-
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
259
|
-
|
|
260
|
-
/**
|
|
261
|
-
* ${i} Job Processor
|
|
262
|
-
*
|
|
263
|
-
* Decorators:
|
|
264
|
-
* @Job(queueName) — marks this class as a job processor for a queue
|
|
265
|
-
* @Process(jobName?) — marks a method as the handler for a specific job type
|
|
266
|
-
* - Without a name: handles all jobs in the queue
|
|
267
|
-
* - With a name: handles only jobs matching that name
|
|
268
|
-
*
|
|
269
|
-
* To add jobs to this queue from a service or controller:
|
|
270
|
-
* @Inject(QUEUE_MANAGER) private queue: QueueService
|
|
271
|
-
* await this.queue.add('${s}', '${o}', { ... })
|
|
272
|
-
*/
|
|
273
|
-
@Job('${s}')
|
|
274
|
-
export class ${i}Job {
|
|
275
|
-
@Process()
|
|
276
|
-
async handle(job: { name: string; data: any; id?: string }) {
|
|
277
|
-
console.log(\`Processing \${job.name} (id: \${job.id})\`, job.data)
|
|
278
|
-
|
|
279
|
-
// TODO: Implement job logic here
|
|
280
|
-
// Example:
|
|
281
|
-
// await this.emailService.send(job.data.to, job.data.subject, job.data.body)
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
@Process('${o}.priority')
|
|
285
|
-
async handlePriority(job: { name: string; data: any; id?: string }) {
|
|
286
|
-
console.log(\`Priority job: \${job.name}\`, job.data)
|
|
287
|
-
// Handle high-priority variant of this job
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
`),c}const Dt={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 Ot(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=Dt[a];if(!o){let e=[...Object.keys(Dt),`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 kt(e){let{name:n,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=x(n),u=v(n),d=c?w(l):l,f=c?y(u):u,p=M(i,d),m=[],b=async(e,n)=>{let r=M(p,e);await t(r,n),m.push(r)};await b(`${l}.module.ts`,le({pascal:u,kebab:l,plural:d,repo:a,style:s})),await b(`${l}.constants.ts`,h({pascal:u,kebab:l})),await b(`${l}.controller.ts`,ee({pascal:u,kebab:l,plural:d,pluralPascal:f})),await b(`${l}.service.ts`,ge({pascal:u,kebab:l})),await b(`dtos/create-${l}.dto.ts`,At(u,r)),await b(`dtos/update-${l}.dto.ts`,jt(u,r)),await b(`dtos/${l}-response.dto.ts`,Mt(u,r)),await b(`${l}.repository.ts`,g({pascal:u,kebab:l,dtoPrefix:`./dtos`,tokenScope:o}));let S=a===`inmemory`,ne=S?`in-memory-${l}`:`${x(a)}-${l}`,C=S?_({pascal:u,kebab:l,repoPrefix:`.`,dtoPrefix:`./dtos`}):te({pascal:u,kebab:l,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`});return await b(`${ne}.repository.ts`,C),await ve(i,u,d,l,s),m}function At(e,t){return`import { z } from 'zod'
|
|
262
|
+
`}${u}`}}function Ct(e,t){return t===`class`?St(e):xt(e)}function wt(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 Tt(e){let t=[];return await n(j(e),0),t;async function n(e,r){let i;try{i=await rt(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o;try{o=await at(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Et(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await rt(e)}catch{return}await F(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=A(e,a),o=A(t,a),s;try{s=await at(i)}catch{continue}s.isDirectory()?await r(i,o):(await nt(i,o),n++)}}}function Dt(e){return A(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function Ot(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await Tt(e),s=await I(A(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Dt(r),await Et(e,c));let l=[];for(let e of o){let t=Ct(await I(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await L(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=A(e,`index.ts`),d=null;try{d=await I(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=wt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await L(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function kt(e,t){let n=await Tt(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 I(e,`utf-8`);i.test(t)&&r.push(e)}return r}const At={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 jt(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=At[a];if(!o){let e=[...Object.keys(At),`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 Mt(e){let{name:n,fields:r,modulesDir:i,repo:a=`inmemory`,tokenScope:o=`app`,style:s=`define`}=e,c=e.pluralize!==!1,l=v(n),u=y(n),d=c?b(l):l,f=c?ee(u):u,p=A(i,d),h=[],x=async(e,n)=>{let r=A(p,e);await t(r,n),h.push(r)};await x(`${l}.module.ts`,m({pascal:u,kebab:l,plural:d,repo:a,style:s})),await x(`${l}.constants.ts`,_e({pascal:u,kebab:l})),await x(`${l}.controller.ts`,ue({pascal:u,kebab:l,plural:d,pluralPascal:f,swagger:e.swagger??!1})),await x(`${l}.service.ts`,ne({pascal:u,kebab:l})),await x(`dtos/create-${l}.dto.ts`,Nt(u,r)),await x(`dtos/update-${l}.dto.ts`,Pt(u,r)),await x(`dtos/${l}-response.dto.ts`,Ft(u,r)),await x(`${l}.repository.ts`,te({pascal:u,kebab:l,dtoPrefix:`./dtos`,tokenScope:o}));let S=a===`inmemory`,re=S?`in-memory-${l}`:`${v(a)}-${l}`,C=S?g({pascal:u,kebab:l,repoPrefix:`.`,dtoPrefix:`./dtos`}):_({pascal:u,kebab:l,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`});return await x(`${re}.repository.ts`,C),await ie(i,u,d,l,s),h}function Nt(e,t){return`import { z } from 'zod'
|
|
291
263
|
|
|
292
264
|
export const create${e}Schema = z.object({
|
|
293
265
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -295,7 +267,7 @@ ${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:`
|
|
|
295
267
|
})
|
|
296
268
|
|
|
297
269
|
export type Create${e}DTO = z.infer<typeof create${e}Schema>
|
|
298
|
-
`}function
|
|
270
|
+
`}function Pt(e,t){return`import { z } from 'zod'
|
|
299
271
|
|
|
300
272
|
export const update${e}Schema = z.object({
|
|
301
273
|
${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
@@ -303,14 +275,14 @@ ${t.map(e=>` ${e.name}: ${e.zodType}.optional(),`).join(`
|
|
|
303
275
|
})
|
|
304
276
|
|
|
305
277
|
export type Update${e}DTO = z.infer<typeof update${e}Schema>
|
|
306
|
-
`}function
|
|
278
|
+
`}function Ft(e,t){return`export interface ${e}ResponseDTO {
|
|
307
279
|
id: string
|
|
308
280
|
${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
309
281
|
`)}
|
|
310
282
|
createdAt: string
|
|
311
283
|
updatedAt: string
|
|
312
284
|
}
|
|
313
|
-
`}async function
|
|
285
|
+
`}async function It(e){let{name:n,moduleName:r,modulesDir:i}=e,a=e.pluralize??!0,o=v(n),s=y(n),c=[],l;if(e.outDir)l=j(e.outDir);else if(r){let e=v(r),t=a?b(e):e;l=j(A(i??`src/modules`,t,`__tests__`))}else l=j(`src/__tests__`);let u=A(l,`${o}.test.ts`);return await t(u,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
314
286
|
import { Container } from '@forinda/kickjs'
|
|
315
287
|
|
|
316
288
|
describe('${s}', () => {
|
|
@@ -333,52 +305,57 @@ describe('${s}', () => {
|
|
|
333
305
|
expect(true).toBe(true)
|
|
334
306
|
})
|
|
335
307
|
})
|
|
336
|
-
`),c.push(u),c}const
|
|
337
|
-
(dry run — no files were written)`),console.log()}async function
|
|
308
|
+
`),c.push(u),c}const Lt=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`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(`
|
|
309
|
+
(dry run — no files were written)`),console.log()}async function Rt(e){if(!e)try{let e=await T(process.cwd());await Ke({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 zt=[{name:`module <name>`,description:`REST module (controller, service, DTOs, repo)`},{name:`scaffold <name> <fields...>`,description:`CRUD module from field definitions`},{name:`controller <name>`,description:`@Controller() class [-m module]`},{name:`service <name>`,description:`@Service() singleton [-m module]`},{name:`middleware <name>`,description:`Express middleware function [-m module]`},{name:`guard <name>`,description:`Route guard (auth, roles, etc.) [-m module]`},{name:`contributor <name>`,description:`Context contributor [--type http|bare] [--params a:string] [-m]`},{name:`dto <name>`,description:`Zod DTO schema [-m module]`},{name:`adapter <name>`,description:`AppAdapter with lifecycle hooks (app-level only)`},{name:`test <name>`,description:`Vitest test scaffold [-m module]`},{name:`config`,description:`Generate kick.config.ts`},{name:`agents`,description:`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md from upstream templates`}],Bt=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
|
|
310
|
+
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),Vt=new Set([...zt.map(e=>e.name.split(` `)[0]),...Bt.keys()]);async function Ht(){console.log(`
|
|
338
311
|
Built-in generators:
|
|
339
|
-
`);let e=Math.max(...
|
|
312
|
+
`);let e=Math.max(...zt.map(e=>e.name.length));for(let t of zt)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await T(process.cwd()),n=Me(t?.plugins??[],t?.commands??[]),r=await le(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
340
313
|
Plugin generators:
|
|
341
314
|
`);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(`
|
|
342
315
|
Failed to load:
|
|
343
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function
|
|
344
|
-
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(t,n,r)=>{let i=
|
|
345
|
-
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(t,n,r)=>{let i=
|
|
316
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function Ut(e,t,n){let r=await T(process.cwd()),i=E(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??h(i.repo);t.repo&&Ee(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,l=Oe(r,process.cwd()),u=De(ke()),d=i.style??`define`;if(!n&&d===`define`){let e=await kt(j(a),`define`);if(e.length>0){console.error(`\n ${p.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${p.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${p.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 ${p.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${p.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${p.dim(`// kick.config.ts`)}\n ${p.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let f=[];for(let r of e){let e=await S({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,tokenScope:l,swagger:u,style:i.style});f.push(...e)}U(f,n),await Rt(n)}function Wt(t,n){let r=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 name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(t,i,a)=>{if(i.list){await Ht();return}if(!t||t.length===0){r.help();return}let o=H(a);e(o);let[s,c,...l]=t;if(s){let e=await T(process.cwd()),t=Me(e?.plugins??[],e?.commands??[]),r=await C({generatorName:s,itemName:c??``,args:l,flags:i,cwd:process.cwd(),projectRoot:n?.projectRoot},t.generators);if(r){U(r.files,o);return}if(s!==`module`&&Vt.has(s)){let e=Bt.get(s);e?(console.error(`\n 'kick g ${s}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${s}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${s} ${c??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${s}' generator — upgrade it.\n`)),process.exitCode=1;return}}await Ut(t,i,o)});r.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(t,n,r)=>{let i=H(r);e(i),await Ut(t,{...r.optsWithGlobals(),...n},i)}),r.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(t,n,r)=>{let i=H(r);e(i),U(await ye({name:t,outDir:j(n.out)}),i)}),r.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(t,n,r)=>{let i=H(r);e(i),U(await ht({name:t,outDir:j(n.out)}),i)}),r.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
|
|
317
|
+
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(t,n,r)=>{let i=H(r);e(i);let a=await T(process.cwd()),o=E(a),s=o.dir??`src/modules`;U(await re({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0,runtime:a?.runtime}),i)}),r.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
318
|
+
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(t,n,r)=>{let i=H(r);e(i);let a=await T(process.cwd()),o=E(a),s=o.dir??`src/modules`;U(await se({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
346
319
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
347
320
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
348
|
-
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(t,n,r)=>{let i=
|
|
349
|
-
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(t,n,r)=>{let i=
|
|
350
|
-
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(t,n,r)=>{let i=
|
|
351
|
-
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(t,n,r)=>{let i=
|
|
352
|
-
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(t,n,r)=>{let i=
|
|
321
|
+
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(t,n,r)=>{let i=H(r);e(i);let a=(n.type??`http`).toLowerCase();a!==`http`&&a!==`bare`&&(console.warn(` kick g contributor: unknown --type '${n.type}', using 'http'.`),a=`http`);let o=await T(process.cwd()),s=E(o),c=s.dir??`src/modules`;U(await _t({name:t,type:a,key:n.key,params:n.params,outDir:n.out,moduleName:n.module,modulesDir:c,pattern:o?.pattern,pluralize:s.pluralize??!0}),i)}),r.command(`service <name>`).description(`Generate a @Service() class
|
|
322
|
+
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(t,n,r)=>{let i=H(r);e(i);let a=await T(process.cwd()),o=E(a),s=o.dir??`src/modules`;U(await ce({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
323
|
+
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(t,n,r)=>{let i=H(r);e(i);let a=await T(process.cwd()),o=E(a),s=o.dir??`src/modules`;U(await fe({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i),await Rt(i)}),r.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
324
|
+
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(t,n,r)=>{let i=H(r);e(i);let a=await T(process.cwd()),o=E(a),s=o.dir??`src/modules`;U(await pe({name:t,outDir:n.out,moduleName:n.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),i)}),r.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
325
|
+
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(t,n,r)=>{let i=H(r);e(i);let a=E(await T(process.cwd())),o=a.dir??`src/modules`;U(await It({name:t,outDir:n.out,moduleName:n.module,modulesDir:o,pluralize:a.pluralize??!0}),i)}),r.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
353
326
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
354
327
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
355
328
|
Optional: append :optional (shell-safe): description:text:optional
|
|
356
|
-
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(t,n,r,i)=>{let a=
|
|
329
|
+
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(t,n,r,i)=>{let a=H(i);e(a),n.length===0&&(console.error(`
|
|
357
330
|
Error: At least one field is required.
|
|
358
331
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
359
332
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
360
333
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
361
|
-
`),process.exit(1));let o=await
|
|
362
|
-
`,u=``;if(
|
|
334
|
+
`),process.exit(1));let o=await T(process.cwd()),s=E(o),c=r.modulesDir??s.dir??`src/modules`,l=jt(n),u=Oe(o,process.cwd()),d=De(ke()),f=await Mt({name:t,fields:l,modulesDir:j(c),noEntity:r.entity===!1,noTests:r.tests===!1,pluralize:r.pluralize===!1?!1:s.pluralize??!0,tokenScope:u,swagger:d,style:s.style});console.log(`\n Scaffolded ${t} with ${l.length} field(s):`);for(let e of l)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);U(f,a),await Rt(a)}),r.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(t,n)=>{let r=H(n);e(r),U(await vt({outDir:j(`.`),modulesDir:t.modulesDir,defaultRepo:t.repo,force:t.force}),r)}),r.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 | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(t,n)=>{let r=H(n);e(r);let i=t.only??`all`;if(!Lt.includes(i)){console.error(` Invalid --only value: ${i}. Expected: ${Lt.join(` | `)}`),process.exitCode=1;return}U(await je({outDir:j(`.`),only:i,name:t.name,pm:t.pm,template:t.template,force:t.force}),r)});for(let e of n?.generators??[])Gt(r,e,n?.projectRoot)}function Gt(t,n,r){let{source:i,spec:a}=n,o=a.args?.[0],s=o?.name??`itemName`,c=o?.required?`<${s}>`:`[${s}]`,l=`${a.name} ${c} [extraArgs...]`,u=t.command(l).description(`${a.description} [${i}]`);for(let e of a.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;u.option(n,e.description??``)}u.action(async(t,i,o,s)=>{let c=H(s);e(c);let l=await C({generatorName:a.name,itemName:t??``,args:i??[],flags:o,cwd:process.cwd(),projectRoot:r},[n]);l&&U(l.files,c)})}async function Kt(e){let t=O.resolve(e.cwd,`.kickjs/types`);e.check||await F(t,{recursive:!0});let n=new Map,r=e.scan??Re,i=O.resolve(e.cwd,`.kickjs`,`cache`),a=e.scan?void 0:e.changedFiles,o={cwd:e.cwd,config:e.config,async importTs(e){return await import(R(e).href)},async writeFile(t,n){let r=O.resolve(e.cwd,t);await F(O.dirname(r),{recursive:!0}),await L(r,n,`utf8`)},getScanResult:e=>{let t=qt(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?Le(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=O.join(t,`${n.id.replace(/\//g,`__`)}${r}`),a;try{a=await n.generate(o)}catch(t){let r=t instanceof Error?t.message:String(t);if(e.check)throw Error(`kick typegen --check: ${n.id} failed to generate (${r})`,{cause:t});o.log.error(` ${n.id}: typegen failed (${r}) — keeping previous output`),s.push({id:n.id,status:`error`,outFile:i});continue}if(a===null){s.push({id:n.id,status:`skipped`});continue}let l=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+a+`
|
|
335
|
+
`,u=``;if(M(i)&&(u=await I(i,`utf8`)),u===l){s.push({id:n.id,status:`unchanged`,outFile:i});continue}if(e.check){c.push({id:n.id,outFile:i}),s.push({id:n.id,status:`drifted`,outFile:i});continue}await L(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new he(c);return s}function qt(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 Jt(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 Yt(e){let{enabled:t,skipped:n,unknown:r}=Jt(Me([...Qr,...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 Kt({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&oe())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof he||e.check)throw t;if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}function Xt(e){let t=A(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`vue-tsc`,`tsgo`,`tsc`]){let r=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let i of r){let r=A(t,i);if(M(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function Zt(e){let t=e.spawnFn??st,n=null,r=0,i=!1;return{schedule(){if(i)return;let a=++r;n&&=(n.kill(),null);let o=Date.now(),s=t(e.bin.cmd,e.bin.args,{cwd:e.cwd,shell:e.bin.shell,stdio:[`ignore`,`pipe`,`pipe`]});n=s;let c=``;s.stdout?.on(`data`,e=>{c+=e.toString()}),s.stderr?.on(`data`,e=>{c+=e.toString()}),s.on(`error`,()=>{a===r&&(n=null)}),s.on(`close`,t=>{i||a!==r||(n=null,e.onResult({ok:t===0,output:c,durationMs:Date.now()-o,kind:e.bin.kind}))})},dispose(){i=!0,n&&=(n.kill(),null)}}}function Qt(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
363
336
|
`):`${n.slice(0,t).join(`
|
|
364
|
-
`)}\n… ${n.length-t} more line(s)`}function
|
|
337
|
+
`)}\n… ${n.length-t} more line(s)`}function $t(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function en(e,t=`127.0.0.1`){let n=await import(`node:inspector`);n.open(e,t,!1);let r=n.url();if(!r)throw Error(`inspector.open() reported no URL`);return r}async function tn(e,t,n={}){t&&(process.env.PORT=t);let r=$t(n.polling),i=process.cwd(),a=await T(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await Ke({cwd:i,allowDuplicates:!0,schemaValidator:o,envFile:s,srcDir:a?.typegen?.srcDir,outDir:a?.typegen?.outDir,assetMap:a?.assetMap,runPlugins:!1})}catch(e){console.warn(` kick typegen: skipped (${e?.message??e})`)}let c=j(i,a?.typegen?.outDir??`.kickjs/types`);try{await ze(c,await Yt({cwd:i,config:a}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),{createServer:u}=await import(R(l(j(`package.json`)).resolve(`vite`)).href);globalThis[ae]=`kick-dev`;let d=await u({configFile:j(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),f=n.typecheck??a?.dev?.typecheck??!1,p=null,m=!0;if(f){let e=Xt(i);e?p=Zt({cwd:i,bin:e,onResult:e=>{d.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?m||(m=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(m=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(Qt(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let h=de({cwd:i,config:a,emitWarning:e=>{console.warn(e),d.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>p?.schedule()});d.watcher.on(`add`,e=>h.handleWatchEvent(`add`,e)),d.watcher.on(`unlink`,e=>h.handleWatchEvent(`unlink`,e)),d.watcher.on(`change`,e=>h.handleWatchEvent(`change`,e)),d.watcher.on(`unlinkDir`,e=>h.handleWatchEvent(`unlinkDir`,e)),h.assetSrcRoots.length>0&&d.watcher.add([...h.assetSrcRoots]),await d.listen(),d.printUrls(),console.log(`
|
|
365
338
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
366
|
-
`),p?.schedule();let g=!1,_=async()=>{if(!g){g=!0,h.dispose(),p?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await d.close(),process.exit(0)}};process.on(`SIGINT`,_),process.on(`SIGTERM`,_),process.on(`SIGBREAK`,_)}function
|
|
339
|
+
`),p?.schedule();let g=!1,_=async()=>{if(!g){g=!0,h.dispose(),p?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await d.close(),process.exit(0)}};process.on(`SIGINT`,_),process.on(`SIGTERM`,_),process.on(`SIGBREAK`,_)}function nn(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await tn(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
367
340
|
Error: vite is not installed.
|
|
368
341
|
Run: pnpm add -D vite unplugin-swc
|
|
369
342
|
`):console.error(`
|
|
370
343
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
371
344
|
Building for production...
|
|
372
|
-
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(
|
|
373
|
-
Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
374
|
-
Building asset map...`);try{await
|
|
345
|
+
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(R(e(j(`package.json`)).resolve(`vite`)).href);await t({configFile:j(`vite.config.ts`)});let n=await T(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
|
|
346
|
+
Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?A(`dist`,e):e.dest??A(`dist`,t),r=j(t),i=j(n);if(!M(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}$e(i,{recursive:!0}),Qe(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
|
|
347
|
+
Building asset map...`);try{await Ae(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
375
348
|
Build complete.
|
|
376
|
-
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await
|
|
377
|
-
Building asset map...`);try{await
|
|
349
|
+
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await T(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
350
|
+
Building asset map...`);try{await Ae(e,{cwd:process.cwd()}),console.log(`
|
|
378
351
|
Asset build complete.
|
|
379
|
-
`)}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)),
|
|
380
|
-
|
|
381
|
-
|
|
352
|
+
`)}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)),Te(e.entry,t)}),e.command(`typecheck`).description(`Type-check the project with its own tsgo/tsc`).option(`--cwd <dir>`,`Directory to type-check`,`.`).action(e=>{let t=j(process.cwd(),e.cwd??`.`),n=Xt(t);if(!n){console.error(`
|
|
353
|
+
No type-checker found. Install one in this project:
|
|
354
|
+
pnpm add -D typescript (tsc)
|
|
355
|
+
pnpm add -D @typescript/native-preview (tsgo, faster)
|
|
356
|
+
`),process.exit(1);return}let r=ct(n.cmd,n.args,{stdio:`inherit`,shell:n.shell,cwd:t});process.exit(r.status??1)}),e.command(`dev:debug`).description(`Start dev server with Node.js inspector attached`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--inspect-port <port>`,`Inspector port`,`9229`).option(`--inspect-host <host>`,`Inspector bind address (use 0.0.0.0 to reach it from outside a container)`,`127.0.0.1`).action(async e=>{let t=Number(e.inspectPort??`9229`),n=e.inspectHost??`127.0.0.1`;[`127.0.0.1`,`localhost`,`::1`].includes(n)||console.warn(` WARNING: the debugger is bound to ${n}, not loopback. Anyone who can\n reach port ${t} can run code in this process. Use it on a trusted\n network only, and prefer publishing the port from your container instead.`);let r;try{r=await en(t,n)}catch(e){console.error(`\n Could not open the inspector on ${t}: ${e.message??e}\n Another process may already hold it — try --inspect-port <port>.`),process.exit(1);return}console.log(` Debugger: ${r}`);try{await tn(e.entry,e.port)}catch(e){console.error(`
|
|
357
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function rn(){try{let e=k(lt(import.meta.url));return JSON.parse(N(A(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const an=new Set(Object.values(Ce).filter(e=>e.deprecated).map(e=>e.pkg));function on(e){let t=A(e,`package.json`);if(!M(t))return[];let n;try{n=JSON.parse(N(t,`utf-8`))}catch{return[]}let r={...n.dependencies,...n.devDependencies};return Object.keys(r).filter(e=>e===`@forinda/kickjs`||e.startsWith(`@forinda/kickjs-`)).toSorted().map(t=>{let n=null,i=A(e,`node_modules`,...t.split(`/`),`package.json`);if(M(i))try{n=JSON.parse(N(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:an.has(t)}})}function sn(e){let t=e;for(;;){if(M(A(t,`package.json`)))return t;let e=k(t);if(e===t)return null;t=e}}function cn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${rn()}`,``,` System:`,` OS: ${dt()} ${ft()} (${ut()})`,` Node: ${process.version}`],t=sn(process.cwd()),n=t?on(t):[];if(!t)e.push(``,` Packages: (not inside a project — no package.json found)`);else if(n.length===0)e.push(``,` Packages: (no @forinda/kickjs* dependencies in ${t})`);else{e.push(``,` Packages:`);let t=Math.max(...n.map(e=>e.name.length));for(let r of n){let n=r.installed??`${r.declared??`?`} (declared — not installed)`,i=r.deprecated?" [DEPRECATED — see `kick add --list --all`]":``;e.push(` ${r.name.padEnd(t+2)} ${n}${i}`)}}e.push(``),console.log(e.join(`
|
|
358
|
+
`))})}const{bold:W,dim:G,green:ln,red:K,yellow:un,blue:dn}=p;function fn(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60),i=e%60,a=[];return t&&a.push(`${t}d`),n&&a.push(`${n}h`),r&&a.push(`${r}m`),a.push(`${i}s`),a.join(` `)}async function pn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function q(e,t){try{return await pn(`${e}${t}`)}catch{return null}}async function mn(e){let[t,n,r,i,a]=await Promise.all([q(e,`/health`),q(e,`/metrics`),q(e,`/routes`),q(e,`/container`),q(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function hn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,c=G(`─`.repeat(60));if(console.log(),console.log(W(` KickJS Inspector`)+G(` → ${e}`)),console.log(c),n){let e=n.status===`healthy`?ln(`● healthy`):K(`● `+n.status);console.log(` ${W(`Health:`)} ${e}`)}else console.log(` ${W(`Health:`)} ${K(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?K:r.errorRate>0?un:ln;console.log(` ${W(`Uptime:`)} ${fn(r.uptimeSeconds)}`),console.log(` ${W(`Requests:`)} ${r.requests}`),console.log(` ${W(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${G(`(`)}${t(e+`%`)}${G(`)`)}`)}if(a&&console.log(` ${W(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${W(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(W(` Routes`)),console.log(c),console.log(` ${G(`METHOD`)} ${G(`PATH`.padEnd(36))} ${G(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${s(e.method)} ${t} ${dn(e.controller)}.${G(e.handler)}`)}}console.log(c),console.log()}function gn(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 mn(r);t.json?console.log(JSON.stringify(e,null,2)):hn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(K(` ✖ Could not connect to ${n}`)),console.error(G(` ${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 _n(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function J(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const vn=[{match(e,t){let n=_n(e,[`config`,`get`])&&J(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&J(e,[`undefined`,`is not defined`]);return!n&&!r?null:J(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`])?{confidence:85,diagnosis:{id:`env-schema-not-registered-in-test`,title:`ConfigService.get() returns undefined inside a test`,explanation:`The env schema is registered by a module-load side effect in
|
|
382
359
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
383
360
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
384
361
|
directly — so that import does not run and ConfigService falls back to
|
|
@@ -402,7 +379,7 @@ import { modules } from './modules'
|
|
|
402
379
|
import './config' // ← add this — registers env schema
|
|
403
380
|
import { bootstrap } from '@forinda/kickjs'
|
|
404
381
|
import { modules } from './modules'
|
|
405
|
-
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=
|
|
382
|
+
`,docs:`https://kickjs.app/guide/configuration.html#wiring-the-schema-at-startup`}}}},{match(e,t){let n=J(e,[`vitest`,`createTestApp`,`__tests__`,`.test.`,`.spec.`]);return J(e,[`already registered`,`already exists`,`duplicate`,`has been registered`])?{confidence:n?85:60,diagnosis:{id:`container-not-reset-in-tests`,title:`DI container leaks between test cases`,explanation:`KickJS decorators register classes on the global Container at import time.
|
|
406
383
|
When vitest re-imports your modules across tests, the same class can be
|
|
407
384
|
registered twice and the container throws. The fix is to wipe the
|
|
408
385
|
container between tests so each case starts fresh.`,fix:`Add Container.reset() to a beforeEach hook in the failing test file:`,codeAfter:`import { describe, it, beforeEach } from 'vitest'
|
|
@@ -412,7 +389,7 @@ describe('UserController', () => {
|
|
|
412
389
|
beforeEach(() => Container.reset())
|
|
413
390
|
|
|
414
391
|
it('does the thing', async () => { /* ... */ })
|
|
415
|
-
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||
|
|
392
|
+
})`,docs:`https://kickjs.app/guide/testing.html`}}:null}},{match(e,t){return e.includes(`@Module`)||_n(e,[`Module`,`is not a function`])||_n(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
|
|
416
393
|
pattern instead: a class implements AppModule and exposes routes() that
|
|
417
394
|
returns the controller wiring. This was a deliberate choice — modules
|
|
418
395
|
become explicit values rather than metadata, which makes them easier to
|
|
@@ -439,7 +416,7 @@ KickRoutes["POST /users"]. The new form is per-controller, per-method,
|
|
|
439
416
|
and matches the actual class names so refactors propagate via
|
|
440
417
|
rename-symbol instead of grep.`,fix:`Update the Ctx<...> type parameter to use the namespace form:`,codeBefore:`@Post('/', { body: createUserSchema })
|
|
441
418
|
create(ctx: Ctx<KickRoutes['POST /users']>) { /* ... */ }`,codeAfter:`@Post('/', { body: createUserSchema, name: 'CreateUser' })
|
|
442
|
-
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=
|
|
419
|
+
create(ctx: Ctx<KickRoutes.UserController['create']>) { /* ... */ }`,docs:`https://kickjs.app/guide/typegen.html`}}:null}},{match(e,t){let n=J(e,[`cluster`,`workers`,`two ports`,`duplicate server`]),r=J(e,[`kick dev`,`vite`,`eaddrinuse`,`5173`,`5174`,`two servers`]);return!n||!r?null:{confidence:85,diagnosis:{id:`cluster-in-vite-dev`,title:"Cluster mode is incompatible with `kick dev` (Vite owns the server)",explanation:`In dev mode, Vite owns the HTTP server. If your bootstrap passes
|
|
443
420
|
cluster: { workers: N }, the framework forks N workers, each of which
|
|
444
421
|
spins up its own Vite instance on a separate port. The fix landed in
|
|
445
422
|
v2.2.5: McpAdapter (and bootstrap()) now detects Vite dev mode and
|
|
@@ -447,7 +424,7 @@ silently skips cluster, with a warning. If you see this on an older
|
|
|
447
424
|
version, upgrade or guard the cluster option behind NODE_ENV.`,fix:`Either upgrade to v2.2.5+ or gate cluster mode on production:`,codeAfter:`export const app = await bootstrap({
|
|
448
425
|
modules,
|
|
449
426
|
cluster: process.env.NODE_ENV === 'production' ? { workers: 4 } : false,
|
|
450
|
-
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return
|
|
427
|
+
})`,docs:`https://kickjs.app/guide/cluster.html`}}}},{match(e,t){return J(e,[`reflect-metadata`,`Reflect.getMetadata is not a function`,`Reflect.defineMetadata`,`design:type`,`design:paramtypes`])?{confidence:90,diagnosis:{id:`reflect-metadata-missing`,title:`reflect-metadata is not loaded — DI cannot read decorator types`,explanation:`The DI container reads constructor parameter types via the
|
|
451
428
|
reflect-metadata polyfill. The polyfill must be imported once,
|
|
452
429
|
before any decorator runs. Most projects do this at the top of
|
|
453
430
|
src/index.ts; missing the import causes obscure "design:paramtypes"
|
|
@@ -456,7 +433,7 @@ import './config'
|
|
|
456
433
|
import { bootstrap } from '@forinda/kickjs'
|
|
457
434
|
import { modules } from './modules'
|
|
458
435
|
|
|
459
|
-
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return
|
|
436
|
+
export const app = await bootstrap({ modules })`,docs:`https://kickjs.app/guide/dependency-injection.html`}}:null}},{match(e,t){return J(e,[`404`,`cannot get`,`cannot post`,`no route`])?{confidence:50,diagnosis:{id:`module-not-registered`,title:`A 404 may indicate a module is not in the modules array`,explanation:`KickJS only mounts modules listed in \`src/modules/index.ts\`. If you
|
|
460
437
|
generated a module via \`kick g module foo\` but the routes don't appear,
|
|
461
438
|
the most likely cause is that the module is missing from the exported
|
|
462
439
|
array. The CLI usually wires this automatically, but a hand-edit can
|
|
@@ -464,7 +441,7 @@ drop the entry.`,fix:`Open src/modules/index.ts and verify the module is in the
|
|
|
464
441
|
import { UserModule } from './users/user.module'
|
|
465
442
|
import { TaskModule } from './tasks/task.module' // ← was this missing?
|
|
466
443
|
|
|
467
|
-
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!
|
|
444
|
+
export const modules: AppModuleEntry[] = [UserModule(), TaskModule()]`,docs:`https://kickjs.app/guide/project-structure.html`}}:null}},{match(e,t){if(!J(e,[`vitest`,`test`,`spec`,`__tests__`,`.test.`,`jest`]))return null;let n=J(e,[`wrong database`,`dev database`,`development database`,`production database`,`wrong db`,`dev db`,`connected to the wrong`,`wiped`,`truncated`,`deleted rows`,`sent a real email`,`real email`,`live api`]),r=J(e,[`stubenv`,`process.env`,`setupfiles`,`test.env`,`env override`])&&J(e,[`no effect`,`not applied`,`ignored`,`still`,`undefined`,`does nothing`,`doesn't work`,`not working`]);if(!n&&!r)return null;let i=t?.hasFile?.(`.env`)===!0||t?.hasFile?.(`.env.local`)===!0,a=t?.hasFile?.(`.env.test`)===!0||t?.hasFile?.(`.env.test.local`)===!0,o=i&&!a,s=n&&r?85:n?75:65;return o&&(s=Math.min(95,s+10)),{confidence:s,diagnosis:{id:`test-env-leaked-from-dotenv`,title:`Test run inherited env vars from your development .env`,explanation:`KickJS loads dotenv as an import-time side effect, with \`override: false\`.
|
|
468
445
|
That protects the vars your test runner pinned — but every var it did NOT
|
|
469
446
|
pin is silently backfilled from your \`.env\`. So a suite can pin its database
|
|
470
447
|
URL and still reach live development services through the vars it forgot,
|
|
@@ -498,24 +475,24 @@ beforeAll(() => {
|
|
|
498
475
|
vi.stubEnv('JWT_SECRET', 'x'.repeat(32))
|
|
499
476
|
resetEnvCache()
|
|
500
477
|
loadEnv(envSchema)
|
|
501
|
-
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}}];function
|
|
478
|
+
})`,docs:`https://kickjs.app/guide/testing.html#environment-isolation`}}}}];function yn(e,t){let n=null;for(let r of vn){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 bn(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.
|
|
502
479
|
export OPENAI_API_KEY="sk-..."
|
|
503
480
|
|
|
504
481
|
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:
|
|
505
482
|
kick add ai
|
|
506
483
|
|
|
507
484
|
Or manually:
|
|
508
|
-
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=
|
|
509
|
-
`)}function
|
|
485
|
+
pnpm add @forinda/kickjs-ai`}}let{OpenAIProvider:i}=r,a=new i({apiKey:n,defaultChatModel:e.model??`gpt-4o-mini`}),o=xn(e.cwd),s=`Error or stack trace:\n\n${e.input.trim()}`;try{let e=Sn((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 xn(e){return[`You are a diagnostic assistant for KickJS, a decorator-driven Node.js`,`framework built on Express 5 and TypeScript. KickJS projects use:`,` - @Controller, @Get, @Post, @Autowired, @Service, @Value decorators`,` - An AppModule interface with a routes() method (NOT a @Module decorator)`,` - Zod schemas as both runtime validators and OpenAPI sources`,` - Ctx<KickRoutes.ControllerName['method']> for typed request context`,` - src/config/index.ts with defineEnv/loadEnv for env schema`,' - A side-effect `import "./config"` in src/index.ts to register the schema',` - Container.reset() in beforeEach for DI test isolation`,``,`When the user gives you an error message or stack trace, produce a`,`structured diagnosis that helps them fix the bug. You MUST respond`,`with a single JSON object (no surrounding prose, no markdown fences)`,`matching this shape:`,``,`{`,` "id": "<kebab-case-identifier>",`,` "title": "<one-line problem summary>",`,` "explanation": "<multi-line explanation of what is wrong>",`,` "fix": "<multi-line instructions for fixing the problem>",`,` "codeBefore": "<optional: broken code snippet>",`,` "codeAfter": "<optional: corrected code snippet>",`,` "docs": "<optional: KickJS doc URL that discusses this topic>"`,`}`,``,`The KickJS docs live at https://kickjs.app/ — prefer`,`that domain for any doc links you suggest.`,e?`The project is located at ${e}.`:``].filter(e=>e.length>0).join(`
|
|
486
|
+
`)}function Sn(e){let t=[e,Cn(e),wn(e)].filter(e=>e!==null);for(let e of t)try{let t=JSON.parse(e);if(Tn(t))return t}catch{continue}return null}function Cn(e){let t=e.match(/```(?:json)?\s*\n([\s\S]*?)```/);return t?t[1]?.trim()??null:null}function wn(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 Tn(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 En(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 kn(e,t.message);(!n||n.trim().length===0)&&(process.stderr.write(`Error: no input provided.
|
|
510
487
|
|
|
511
488
|
Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
512
489
|
kick explain "config.get returned undefined"
|
|
513
490
|
pnpm test 2>&1 | kick explain
|
|
514
|
-
`),process.exit(1));let r=
|
|
515
|
-
`);return}if(i){
|
|
516
|
-
`),process.exit(2)),
|
|
517
|
-
`),process.exit(a.kind===`ok`?0:2)),
|
|
518
|
-
`)}function
|
|
491
|
+
`),process.exit(1));let r=jn(),i=yn(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
492
|
+
`);return}if(i){Mn(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
493
|
+
`),process.exit(2)),Nn(n,!1),process.exit(2));let a=await bn({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(Dn(a),null,2)+`
|
|
494
|
+
`),process.exit(a.kind===`ok`?0:2)),On(n,a),process.exit(a.kind===`ok`?0:2)})}function Dn(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 On(e,t){if(t.kind===`ok`){Mn(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${X(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Y(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${X(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function kn(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:An()}function An(){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 jn(){let e=process.cwd();return{cwd:e,hasFile:t=>M(j(e,t))}}function Mn(e,t,n,r=!1){let i=X(e.trim(),200),a=r?`AI-generated — verify before applying`:Pn(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${Y(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Y(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Y(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Y(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
495
|
+
`)}function Nn(e,t){let n=X(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.
|
|
519
496
|
When @forinda/kickjs-ai ships its provider implementations,
|
|
520
497
|
this command will call the configured LLM with the error +
|
|
521
498
|
project context and return a structured fix.
|
|
@@ -532,12 +509,12 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
532
509
|
3. File an issue with the error text:
|
|
533
510
|
https://github.com/forinda/kick-js/issues/new
|
|
534
511
|
|
|
535
|
-
`)}function
|
|
512
|
+
`)}function Y(e,t){return e.split(`
|
|
536
513
|
`).map(e=>`${t}${e}`).join(`
|
|
537
|
-
`)}function
|
|
538
|
-
`,`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
|
|
514
|
+
`)}function X(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Pn(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Fn(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(In),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(Ln)}function In(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=st(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 Ln(e){let t=process.cwd(),n=Rn(t)??Ye(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=N(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,tt(i,JSON.stringify(o,null,2)+`
|
|
515
|
+
`,`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 Rn(e){let t=j(e,`package.json`);if(!M(t))return null;try{let e=N(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function zn(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=Vn(t,`tsx`);r||(console.error(`
|
|
539
516
|
Error: tsx not found. Install it: pnpm add -D tsx
|
|
540
|
-
`),process.exit(1));let i=
|
|
517
|
+
`),process.exit(1));let i=Bn(n,e.entry),a=A(t,`.kick-tinker.mjs`),{writeFileSync:o,unlinkSync:s}=await import(`node:fs`);o(a,i,`utf-8`);try{let e=ot(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function Bn(e,t){return`
|
|
541
518
|
import 'reflect-metadata'
|
|
542
519
|
|
|
543
520
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -562,7 +539,7 @@ try {
|
|
|
562
539
|
|
|
563
540
|
// Load entry to trigger decorator registration
|
|
564
541
|
try {
|
|
565
|
-
await import('${
|
|
542
|
+
await import('${R(e).href}')
|
|
566
543
|
} catch (err) {
|
|
567
544
|
console.warn(' Warning: ' + err.message)
|
|
568
545
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -591,33 +568,33 @@ server.on('exit', () => {
|
|
|
591
568
|
console.log('\\n Goodbye!\\n')
|
|
592
569
|
process.exit(0)
|
|
593
570
|
})
|
|
594
|
-
`}function
|
|
571
|
+
`}function Vn(e,t){let n=e;for(;;){let e=A(n,`node_modules`,`.bin`,t);if(M(e))return e;let r=j(n,`..`);if(r===n)break;n=r}return null}function Hn(e,t){let n=RegExp(`^\\s*${w(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]!==`
|
|
595
572
|
`;)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]===`
|
|
596
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function
|
|
573
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function Un(e,t){let n=ve(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Hn(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${w(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 Wn(e){let{name:t,modulesDir:r,force:i}=e,a=e.pluralize!==!1,o=v(t),s=y(t),c=a?b(o):o,l=A(r,c);if(!await n(l)){console.log(`\n Module not found: ${l}\n`);return}if(!i&&!await f({message:p.red(`Delete module '${c}' at ${l}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
597
574
|
Cancelled.
|
|
598
|
-
`);return}await
|
|
575
|
+
`);return}await it(l,{recursive:!0,force:!0}),console.log(` Deleted: ${l}`);let u=A(r,`index.ts`);if(await n(u)){let e=await I(u,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${w(s)}Module\\s*\\}\\s*from\\s*['"][^'"]*${w(c)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=Un(e,s),e=e.replace(/\n{3,}/g,`
|
|
599
576
|
|
|
600
|
-
`),e!==t&&(await
|
|
577
|
+
`),e!==t&&(await L(u,e,`utf-8`),console.log(` Unregistered: ${s}Module from ${u}`))}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=E(await T(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`;if(e===`kickjs-schema`||e===`schema`)return`kickjs-schema`;console.warn(` kick typegen: unknown --schema-validator '${e}' (supported: 'zod', 'kickjs-schema', 'false'). Falling back to project config.`)}}function 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: exit non-zero if any generated file in .kickjs/types/ is out of date (routes, env, db, assets, adopter plugins) instead of writing it`).option(`--fix`,`Patch module import.meta.glob() calls to cover decorated classes that aren't loaded by any glob (orphans)`).option(`--list`,"List every registered typegen plugin id (use to populate `typegen.disable`)").option(`--no-cache`,`Disable the persistent scan cache; re-read + re-extract every file from cold`).action(async e=>{let t=ke(process.cwd()),n=await T(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-CyiOvPC4.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await import(`./builtins-eX32WH9F.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(`
|
|
601
578
|
Registered typegen plugins:
|
|
602
|
-
`);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=
|
|
579
|
+
`);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,fix:e.fix,allowDuplicates:e.allowDuplicates,noCache:e.cache===!1,schemaValidator:r,envFile:i,assetMap:n?.assetMap,runPlugins:!1};try{if(e.watch){let t=await We(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await Ke(a);let r=await Yt({cwd:t,config:n??null,silent:e.silent,check:e.check});e.check&&r.some(e=>e.status===`written`)&&process.exit(1),e.check||await ze(j(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof Ge?console.error(`
|
|
603
580
|
`+e.message+`
|
|
604
|
-
`):e instanceof
|
|
581
|
+
`):e instanceof he?console.error(`
|
|
605
582
|
`+e.message+`
|
|
606
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function
|
|
583
|
+
`):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=P(e,{withFileTypes:!0});for(let r of n){let n=A(e,r.name);if(r.isDirectory()){if([`node_modules`,`dist`,`.kickjs`,`.git`].includes(r.name))continue;t.push(...Yn(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function Xn(e){try{return N(e,`utf-8`)}catch{return``}}const Zn=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Qn(e,t){let n=Xn(A(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(A(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(`
|
|
607
584
|
Usage: kick check --deploy
|
|
608
585
|
|
|
609
586
|
Available checks:
|
|
610
587
|
--deploy Audit for production readiness (security, config, best practices)
|
|
611
|
-
`);return}let t=process.cwd();c(`KickJS Deploy Check`);let n=d();n.start(`Scanning project...`);let i=
|
|
588
|
+
`);return}let t=process.cwd();c(`KickJS Deploy Check`);let n=d();n.start(`Scanning project...`);let i=ar(t);n.stop(`Scan complete`);let o={CRITICAL:0,WARNING:1,INFO:2};i.sort((e,t)=>o[e.severity]-o[t.severity]);for(let e of i)u.message(`${a(e.severity)} ${e.message}`);let s=i.filter(e=>e.severity===`CRITICAL`).length,l=i.filter(e=>e.severity===`WARNING`).length,f=i.filter(e=>e.severity===`INFO`).length,m=l===1?`warning`:`warnings`,h=[s>0?p.red(`${s} critical`):`${s} critical`,l>0?p.yellow(`${l} ${m}`):`${l} ${m}`,`${f} info`].join(`, `);s>0?(r(p.red(`${h} — fix critical issues before deploying`)),process.exit(1)):r(p.green(`${h} — looking good!`))})}function sr(e){return e.optsWithGlobals().dryRun??!1}function cr(t){t.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.
|
|
612
589
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
613
590
|
--target define|class Override the migration direction.
|
|
614
591
|
--apply Apply the changes (default: dry-run preview).
|
|
615
|
-
--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(t,n)=>{let r=
|
|
592
|
+
--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(t,n)=>{let r=sr(n)||!t.apply;e(r),t.experimental||(console.error(`
|
|
616
593
|
`+p.red(`Error:`)+` kick codemod modules is experimental — pass --experimental to acknowledge.
|
|
617
594
|
The regex-based rewrite handles the shapes our templates produce.
|
|
618
595
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
619
596
|
Always commit before running with --apply.
|
|
620
|
-
`),process.exit(1));let i=
|
|
597
|
+
`),process.exit(1));let i=E(await T(process.cwd())),a=j(t.modulesDir??i.dir??`src/modules`),o;t.target===`define`||t.target===`class`?o=t.target:t.target===void 0?o=i.style??`define`:(console.error(`\n ${p.red(`Error:`)} --target must be 'define' or 'class' (got '${t.target}').\n`),process.exit(1));let s=p.dim(`→ ${o}`),c=r?p.dim(`(dry-run)`):p.bold(`(applying)`);console.log(`\n ${p.bold(`kick codemod modules`)} ${s} ${c}`),console.log(` modulesDir: ${p.dim(a)}\n`);let l=t.backup!==!1&&!r,u=await Ot(a,{dryRun:r,target:o,backup:l});if(u.backupDir){let e=u.backupDir;console.log(` ${p.green(`✓`)} backup: ${p.dim(e)}\n ${p.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!r&&t.backup===!1&&console.log(` ${p.dim(`(--no-backup — skipping snapshot)`)}\n`);let d=0,f=0;for(let e of u.files)if(e.status===`migrated`)d++,console.log(` ${p.green(`✓`)} ${e.path}`);else{f++;let t=p.dim(`(${e.reason??`skipped`})`);console.log(` ${p.dim(`-`)} ${e.path} ${t}`)}if(console.log(),u.indexStatus===`migrated`)console.log(` ${p.green(`✓`)} ${u.indexPath}`);else if(u.indexStatus===`skipped`){let e=p.dim(`(${u.indexReason??`skipped`})`);console.log(` ${p.dim(`-`)} ${u.indexPath} ${e}`)}else console.log(` ${p.dim(`-`)} ${u.indexPath} ${p.dim(`(not found)`)}`);let m=r?p.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${p.bold(String(d))} migrated, ${p.bold(String(f))} skipped${m}\n`)})}const lr=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!M(O.resolve(e.cwd,`kick.config.ts`)))return null;let t=await T(e.cwd);if(!t?.assetMap)return null;let n=Ne(t.assetMap,e.cwd);return n.count===0?null:He(n)}}),ur="/* 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 dr(e,t,n,r={}){if(e.length===0)return`${ur}
|
|
621
598
|
// (no routes discovered yet — annotate a controller method with
|
|
622
599
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
623
600
|
declare global {
|
|
@@ -634,14 +611,14 @@ declare global {
|
|
|
634
611
|
|
|
635
612
|
/** Empty until the first route exists — see kick typegen. */
|
|
636
613
|
export const kickRpc = {} as const
|
|
637
|
-
`;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=
|
|
614
|
+
`;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=hr(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??pr(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=mr(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` contextKeys: ${fr(e)}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
638
615
|
`))}let u=[],d=new Set,f=new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;if(d.has(t)){r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`);continue}d.add(t),f.add(`${e}.${n.method}`),u.push(` '${t}': ${e}['${n.method}']`)}let p=[` interface Api {`,...u,` }`].join(`
|
|
639
|
-
`);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=
|
|
616
|
+
`);l.push(p);let m=[],h=new Set;for(let[e,t]of i){let n=vr(e);if(h.has(n)){r.onWarn?.(`RPC manifest: controller key '${n}' (from ${e}) collides with another controller — keeping the first; rename one class for distinct RPC namespaces.`);continue}h.add(n);let i=[];for(let n of t){if(!f.has(`${e}.${n.method}`))continue;let t=`${n.httpMethod} ${n.mountedPath??n.path}`;i.push(` ${n.method}: '${t}',`)}i.length>0&&m.push(` ${n}: {\n${i.join(`
|
|
640
617
|
`)}\n },`)}let g=[`/**`,` * Runtime route manifest for the tRPC-style sugar:`," * `createRpc(api, kickRpc)` from @forinda/kickjs-client.",` */`,`export const kickRpc = {`,...m,`} as const`].join(`
|
|
641
|
-
`),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=
|
|
618
|
+
`),_=[],v=new Map;for(let t of e)v.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=v.get(e),i=_r(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;_.push(`import type { ${a} } from '${i}'`)}let y=_.length>0?_.join(`
|
|
642
619
|
`)+`
|
|
643
|
-
`:``,b=
|
|
644
|
-
`);return`${
|
|
620
|
+
`:``,b=gr(a)+y,ee=l.join(`
|
|
621
|
+
`);return`${ur}${b}
|
|
645
622
|
declare global {
|
|
646
623
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
647
624
|
namespace KickRoutes {
|
|
@@ -653,41 +630,62 @@ ${ee}
|
|
|
653
630
|
}
|
|
654
631
|
|
|
655
632
|
${g}
|
|
656
|
-
`}function
|
|
633
|
+
`}function fr(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function pr(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 mr(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 hr(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=_r(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 gr(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(`
|
|
657
634
|
`)+`
|
|
658
|
-
`}function
|
|
659
|
-
TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${
|
|
660
|
-
`){let i=[];for(let r of this.checker.getIndexInfosOfType(e)){let e=this.checker.typeToString(r.keyType);i.push(`${n}[key: ${e}]: ${this.render(r.type,t+1)}`)}for(let r of this.checker.getPropertiesOfType(e)){let e=
|
|
635
|
+
`}function _r(e,t,n){if(e===null)return`unknown`;let r=k(n);if(e===``){let e=Xe(r,t).split(Ze).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=Xe(r,j(k(t),e)).split(Ze).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function vr(e){let t=e.endsWith(`Controller`)?e.slice(0,-10):e,n=t.length>0?t:e;return n.charAt(0).toLowerCase()+n.slice(1)}const yr=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:br(e),cwd:e.cwd,envFile:xr(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return dr(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function br(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function xr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Z=`@typescript/typescript6`;function Sr(e){return typeof e?.createProgram==`function`}function Cr(e){if(Sr(e.typescript))return{api:e.typescript,source:`typescript`};if(Sr(e.ts6))return{api:e.ts6,source:Z};let t=`Install it in the project:\n pnpm add -D ${Z}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
|
|
636
|
+
TypeScript 7 does not ship a compiler API, so the compatibility package is required.\n ${t}`):Error(`kick typegen: the client route map needs a TypeScript compiler API, and neither 'typescript' nor '${Z}' resolved from this project.\n ${t}`)}async function wr(e){let t=Je(A(e,`package.json`)),n=async e=>{try{return await import(R(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Z)]);return Cr({typescript:Tr(r),ts6:Tr(i)}).api}function Tr(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}var Er=class{ts;checker;program;opts;hoistedByType=new Map;blocks=[];maxDepth;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12}hoisted(){return this.blocks}expand(e){return this.render(e,0)}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth)return this.opts.onWarn?.(`type nesting exceeded ${this.maxDepth} levels — emitting 'unknown'. Declare a response schema on the route for an exact type.`),`unknown`;if(e.flags&(n.String|n.Number|n.Boolean|n.BigInt|n.ESSymbol)||e.flags&(n.Any|n.Unknown|n.Never|n.Void|n.Undefined|n.Null)||e.isLiteral()||e.flags&n.BooleanLiteral)return this.checker.typeToString(e);if(e.isUnion())return e.types.map(e=>this.render(e,t+1)).join(` | `);if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let r=this.arrayElement(e);if(r){let e=this.render(r.element,t+1),n=/[|&]/.test(e)?`(${e})[]`:`${e}[]`;return r.readonly?`readonly ${n}`:n}return this.isLibType(e)?this.renderLibType(e,t):e.flags&n.Object?this.renderObject(e,t):(this.opts.onWarn?.(`could not expand type '${this.checker.typeToString(e)}' — emitting 'unknown'`),`unknown`)}renderObject(e,t){let n=this.hoistedByType.get(e);if(n)return n;if(this.isNamed(e)){let t=`__T${this.hoistedByType.size}`;this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.members(e,t,``,`; `);return r.length>0?`{ ${r} }`:`{}`}members(e,t,n,r=`
|
|
637
|
+
`){let i=[];for(let r of this.checker.getIndexInfosOfType(e)){let e=this.checker.typeToString(r.keyType);i.push(`${n}[key: ${e}]: ${this.render(r.type,t+1)}`)}for(let r of this.checker.getPropertiesOfType(e)){let e=this.typeOfProperty(r),a=(r.flags&this.ts.SymbolFlags.Optional)!==0,o=this.renderPropertyType(e,a,r,t+1),s=this.isReadonlyProp(r)?`readonly `:``;i.push(`${n}${s}${this.propName(r.getName())}${a?`?`:``}: ${o}`)}return i.join(r===`
|
|
661
638
|
`?`
|
|
662
|
-
`:r)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};async function
|
|
663
|
-
`);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function
|
|
639
|
+
`:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};async function Dr(e){let t=await wr(e.compilerFrom??e.projectDir),n=A(k(e.routesFile),`__kick_client_probe__.ts`),r=Ar(e.routesFile,e.keys),i=Nr(t,e.projectDir,n,r),a=i.getTypeChecker(),o=i.getSourceFile(n);if(!o)throw Error(`kick/client: could not add the resolution probe to the program. Check that ${e.routesFile} exists — run \`kick typegen\` first.`);Or(t,i,e.routesFile);let s=jr(t,i,o,e.keys),c=null,l=new Er(t,a,i,{onWarn:t=>e.onWarn?.(c?`route '${c}': ${t}`:t)}),u=new Map;for(let[n,r]of e.keys.entries()){if(s.has(r)){e.onWarn?.(`route '${r}' is not present in KickRoutes.Api — skipped. Re-run \`kick typegen\` so the two maps agree.`);continue}let i=o.statements.find(e=>t.isTypeAliasDeclaration(e)&&e.name.text===kr(n));if(!i){e.onWarn?.(`route '${r}' could not be resolved — skipped.`);continue}let d=a.getTypeAtLocation(i.type);if(d.flags&t.TypeFlags.Any){e.onWarn?.(`route '${r}' resolved to 'any' — skipped rather than emitted, since an 'any' entry silently accepts every call. Check that the server type-checks.`);continue}c=r,u.set(r,l.expand(d)),c=null}return{entries:u,hoisted:l.hoisted()}}function Or(e,t,n){let r=t.getSourceFile(n);if(!r)throw Error(`kick/client: ${n} is not in the TypeScript program. Run \`kick typegen\` first, and check that tsconfig.json includes .kickjs.`);let i=t.getSemanticDiagnostics(r);if(i.length===0)return;let a=i.slice(0,3).map(t=>` ${e.flattenDiagnosticMessageText(t.messageText,` `)}`).join(`
|
|
640
|
+
`);throw Error(`${n} has ${i.length} type error(s), so its route types cannot be resolved — every entry would come out as 'any'.\n${a}\n Usually this means dependencies are not installed or the server does not type-check.`)}function kr(e){return`_K${e}`}function Ar(e,t){let n=`./`+Ye(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${kr(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
|
|
664
641
|
`)+`
|
|
665
|
-
`}function
|
|
666
|
-
`))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...o.fileNames,n],options:o.options,host:s})}const
|
|
642
|
+
`}function jr(e,t,n,r){let i=new Set,a=new Map;for(let t of n.statements)e.isTypeAliasDeclaration(t)&&a.set(t.name.text,t);for(let e of t.getSemanticDiagnostics(n))if(e.start!==void 0)for(let[t,o]of r.entries()){let r=a.get(kr(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function Mr(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=P(t).filter(e=>e.endsWith(`.ts`)).map(e=>A(t,e))}catch{}return[...new Set([...n,...r])]}function Nr(e,t,n,r){let i=A(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
|
|
643
|
+
`))}},o=e.getParsedCommandLineOfConfigFile(i,{},a);if(!o)throw Error(`kick/client: could not read ${i}`);let s=e.createCompilerHost(o.options,!0),c=s.readFile.bind(s),l=s.getSourceFile.bind(s),u=s.fileExists.bind(s);return s.readFile=e=>e===n?r:c(e),s.fileExists=e=>e===n||u(e),s.getSourceFile=(t,i,a,o)=>t===n?e.createSourceFile(t,r,i,!0):l(t,i,a,o),e.createProgram({rootNames:[...Mr(o.fileNames,k(n)),n],options:o.options,host:s})}const Pr=`/* eslint-disable */
|
|
667
644
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
668
645
|
//
|
|
669
646
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
670
647
|
// compiling the server, its decorators, or its path aliases.
|
|
671
648
|
//
|
|
672
|
-
//
|
|
673
|
-
// export const api = createClient<
|
|
649
|
+
// // Ambient — add this file to the frontend's tsconfig "include", then:
|
|
650
|
+
// export const api = createClient<KickClientApi.Api>({ baseUrl: '/api/v1' })
|
|
651
|
+
//
|
|
652
|
+
// // Or import it explicitly, if you prefer no globals:
|
|
653
|
+
// import type { Api } from './path/to/kick__client'
|
|
674
654
|
//
|
|
675
655
|
// Not refreshed by \`kick dev\` — resolving these types builds a full
|
|
676
656
|
// TypeScript program over the server. Re-run \`kick typegen\`.
|
|
677
|
-
`;function
|
|
657
|
+
`;function Fr(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${Pr}
|
|
678
658
|
// (no routes discovered yet — annotate a controller method with
|
|
679
659
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
680
|
-
|
|
660
|
+
interface Api {}
|
|
661
|
+
|
|
662
|
+
declare global {
|
|
663
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
664
|
+
namespace KickClientApi {
|
|
665
|
+
export { Api }
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
export type { Api }
|
|
681
670
|
`;let r=e.hoisted.length>0?e.hoisted.join(`
|
|
682
671
|
|
|
683
672
|
`)+`
|
|
684
673
|
|
|
685
|
-
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${
|
|
686
|
-
${r}
|
|
674
|
+
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${Pr}
|
|
675
|
+
${r}interface Api {
|
|
687
676
|
${i.join(`
|
|
688
677
|
`)}
|
|
689
678
|
}
|
|
690
|
-
|
|
679
|
+
|
|
680
|
+
declare global {
|
|
681
|
+
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
682
|
+
namespace KickClientApi {
|
|
683
|
+
export { Api }
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
export type { Api }
|
|
688
|
+
`}const Q=`.kickjs/types/kick__client.d.ts`;async function Ir(e){let t=O.resolve(e.cwd,Q);if(!M(t))return!1;try{await it(t,{force:!0})}catch(t){return e.log.warn(` kick/client: could not remove the stale ${Q} — treat it as out of date (${t instanceof Error?t.message:String(t)})`),!0}return e.log.warn(` kick/client: removed the previously generated ${Q} rather than leave a stale one — re-run \`kick typegen\` once the cause above is fixed.`),!0}function Lr(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:(M(O.resolve(e.cwd,Q))&&e.log.warn(` kick/client: ${Q} exists but typegen.client is not set, so it is NOT being refreshed.\n Add \`typegen: { client: true }\` to kick.config.ts to keep it current, or delete the file if nothing reads it.`),!1)}const Rr=()=>({id:`kick/client`,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!Lr(e))return null;if(e.watch)return e.log.info?.(" kick/client: skipped under watch (builds a full TypeScript program). Run `kick typegen` to refresh the client route map."),null;let t=await e.getScanResult({root:O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`),cwd:e.cwd}),n=[],r=new Set;for(let e of t.routes){let t=`${e.httpMethod} ${e.mountedPath??e.path}`;r.has(t)||(r.add(t),n.push(t))}try{return Fr(await Dr({projectDir:e.cwd,routesFile:O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,onWarn:t=>e.log.warn(t)}),n)}catch(t){let n=M(O.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):oe()&&e.log.info?.(r),n&&await Ir(e),null}}});function zr(e,t,n=`zod`){if(!e)return null;let r=Xe(k(t),e.filePath).split(Ze).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
|
|
691
689
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
692
690
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
693
691
|
|
|
@@ -725,6 +723,6 @@ declare global {
|
|
|
725
723
|
}
|
|
726
724
|
|
|
727
725
|
export {}
|
|
728
|
-
`}const
|
|
729
|
-
`)}}]})];export{
|
|
730
|
-
//# sourceMappingURL=run-plugins-
|
|
726
|
+
`}const Br=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=Hr(e);if(t===!1)return null;let n=await e.getScanResult({root:Vr(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=O.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return zr(n.env,i,r)}});function Vr(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Hr(e){return e.config?.typegen?.envFile}function Ur(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Wr(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:Ur(e),cwd:e.cwd,envFile:Wr(e)}}const Gr=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=O.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return Ue(t.classes,n,r)}}),Kr=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e)),n=new Set(t.collisions.map(e=>e.className));return Ve(`ServiceToken`,Be(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),qr=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return Ve(`ModuleToken`,Pe((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Jr=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return Ie((await e.getScanResult($(e))).pluginsAndAdapters)}}),Yr=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return qe((await e.getScanResult($(e))).augmentations)}}),Xr=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:Fe(t.contextKeys)}}),Zr={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Qr=[D({name:`kick/init`,register:mt}),D({name:`kick/generate`,register:Wt}),D({name:`kick/run`,register:nn}),D({name:`kick/info`,register:cn}),D({name:`kick/inspect`,register:gn}),D({name:`kick/add`,register:be}),D({name:`kick/list`,register:Se}),D({name:`kick/explain`,register:En}),D({name:`kick/mcp`,register:Fn}),D({name:`kick/tinker`,register:zn}),D({name:`kick/remove`,register:Gn}),D({name:`kick/typegen`,register:Jn}),D({name:`kick/check`,register:or}),D({name:`kick/doctor`,register:me}),D({name:`kick/codemod`,register:cr}),D({name:`kick/registry`,typegens:[Gr()]}),D({name:`kick/services`,typegens:[Kr()]}),D({name:`kick/modules`,typegens:[qr()]}),D({name:`kick/plugins`,typegens:[Jr()]}),D({name:`kick/augmentations`,typegens:[Yr()]}),D({name:`kick/context`,typegens:[Xr()]}),D({name:`kick/assets`,typegens:[lr()]}),D({name:`kick/routes`,typegens:[yr()]}),D({name:`kick/client`,typegens:[Rr()]}),D({name:`kick/env`,typegens:[Br()]}),D({name:`kick/runtime`,typegens:[{id:`kick/runtime`,outExtension:`.ts`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`],async generate(e){let t=e.config?.runtime;if(t!==`fastify`&&t!==`h3`)return null;let{subpath:n,typeName:r}=Zr[t];return[`// Runtime escape-hatch types for the '${t}' engine (kick.config runtime).`,`declare module '@forinda/kickjs' {`,` interface KickRuntimeRegister {`,` runtime: import('${n}').${r}`,` }`,`}`,``,`export {}`,``].join(`
|
|
727
|
+
`)}}]})];export{Jt as applyDisableFilter,Yt as runAllPluginTypegens,Qr as t};
|
|
728
|
+
//# sourceMappingURL=run-plugins-w_jNdZ-F.mjs.map
|