@forinda/kickjs-cli 7.0.1 → 7.1.1
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-ByLNah3Q.mjs → agent-docs-Bxp34Ss6.mjs} +2 -2
- package/dist/{agent-docs-DpnGe5eB.mjs → agent-docs-CMj7Zyj4.mjs} +3 -3
- package/dist/{agent-docs-DpnGe5eB.mjs.map → agent-docs-CMj7Zyj4.mjs.map} +1 -1
- package/dist/{build-kAS8vTgJ.mjs → build-1OHeIhGr.mjs} +2 -2
- package/dist/{build-BhHgwfnn.mjs → build-BJd10HpG.mjs} +3 -3
- package/dist/{build-BhHgwfnn.mjs.map → build-BJd10HpG.mjs.map} +1 -1
- package/dist/{builtins-C1AUhwra.mjs → builtins-BJ1fZBKi.mjs} +2 -2
- package/dist/{builtins-OqcjV5Ah.mjs → builtins-CK8nnKx3.mjs} +85 -85
- package/dist/cli.mjs +2 -2
- package/dist/{config-BpuK2U4H.mjs → config-B26M-H3G.mjs} +3 -3
- package/dist/config-B26M-H3G.mjs.map +1 -0
- package/dist/{config-CAMuUYHB.mjs → config-CcRRKBhg.mjs} +2 -2
- package/dist/{doctor-CaxYeesL.mjs → doctor-bVCuDQuM.mjs} +4 -4
- package/dist/{doctor-CaxYeesL.mjs.map → doctor-bVCuDQuM.mjs.map} +1 -1
- package/dist/{fullstack-CFb-_pLC.mjs → fullstack-BfgB5r1W.mjs} +3 -3
- package/dist/{fullstack-D6NhL_2E.mjs → fullstack-Bhe_l1v6.mjs} +4 -4
- package/dist/{fullstack-D6NhL_2E.mjs.map → fullstack-Bhe_l1v6.mjs.map} +1 -1
- package/dist/index.d.mts +27 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-DLmjmJ0w.mjs → plugin-LY_08MMA.mjs} +2 -2
- package/dist/{plugin-B5cTyUvL.mjs → plugin-_eznyEJd.mjs} +3 -3
- package/dist/{plugin-B5cTyUvL.mjs.map → plugin-_eznyEJd.mjs.map} +1 -1
- package/dist/{project-y3fadrjc.mjs → project-BRcVX0aF.mjs} +5 -5
- package/dist/{project-y3fadrjc.mjs.map → project-BRcVX0aF.mjs.map} +1 -1
- package/dist/{project-DYUMUXFZ.mjs → project-C7RF1-Gb.mjs} +4 -4
- package/dist/{project-docs-BVwzaWxS.mjs → project-docs-BJSgVODJ.mjs} +2 -2
- package/dist/{project-docs-BVwzaWxS.mjs.map → project-docs-BJSgVODJ.mjs.map} +1 -1
- package/dist/{project-docs-BCQIwKnL.mjs → project-docs-YvI9sWW2.mjs} +1 -1
- package/dist/{project-root-DxxK-sLA.mjs → project-root-Cd1GKxvd.mjs} +2 -2
- package/dist/{project-root-De_nJub0.mjs → project-root-DpJw0zEd.mjs} +3 -3
- package/dist/{project-root-De_nJub0.mjs.map → project-root-DpJw0zEd.mjs.map} +1 -1
- package/dist/{prompts-BMOJYPvM.mjs → prompts-CE8oxMS2.mjs} +2 -2
- package/dist/{prompts-BMOJYPvM.mjs.map → prompts-CE8oxMS2.mjs.map} +1 -1
- package/dist/{rolldown-runtime-qj3ktXfH.mjs → rolldown-runtime-D-Y-59yJ.mjs} +1 -1
- package/dist/{run-plugins-UrVjs36R.mjs → run-plugins-CHv-_CI_.mjs} +17 -17
- package/dist/{run-plugins-UrVjs36R.mjs.map → run-plugins-CHv-_CI_.mjs.map} +1 -1
- package/dist/{typegen-C2eQNnoa.mjs → typegen-BDYmZKFF.mjs} +5 -5
- package/dist/{typegen-C2eQNnoa.mjs.map → typegen-BDYmZKFF.mjs.map} +1 -1
- package/dist/{typegen-C0-zbJ7C.mjs → typegen-DiD6n0_q.mjs} +4 -4
- package/dist/{types-8TVtHOJr.mjs → types-BvRcbnr7.mjs} +1 -1
- package/package.json +4 -4
- package/dist/config-BpuK2U4H.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v7.
|
|
2
|
+
* @forinda/kickjs-cli v7.1.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{t as e}from"./rolldown-runtime-
|
|
11
|
+
import{t as e}from"./rolldown-runtime-D-Y-59yJ.mjs";import{a as t,c as n,i as r,o as i,r as a,s as o,t as s,u as c}from"./project-C7RF1-Gb.mjs";import{a as l,i as u,o as d,r as f,s as p}from"./config-CcRRKBhg.mjs";import{n as m,r as h}from"./plugin-LY_08MMA.mjs";import{c as g,l as _,s as v}from"./project-docs-YvI9sWW2.mjs";import{a as y,c as b,d as ee,f as x,i as te,l as ne,n as re,o as ie,p as ae,r as S,s as C,u as oe}from"./agent-docs-Bxp34Ss6.mjs";import{t as w}from"./project-root-Cd1GKxvd.mjs";import{a as se,c as ce,d as le,f as ue,g as de,h as fe,i as pe,l as me,m as he,o as ge,p as _e,r as ve,s as ye,t as be,u as xe}from"./typegen-DiD6n0_q.mjs";import{t as Se}from"./build-1OHeIhGr.mjs";import{createRequire as Ce}from"node:module";import{cpSync as we,existsSync as T,mkdirSync as Te,readFileSync as E,readdirSync as D,rmSync as Ee,statSync as De,writeFileSync as Oe}from"node:fs";import O,{basename as ke,dirname as k,join as A,relative as j,resolve as M,sep as Ae}from"node:path";import{fileURLToPath as je,pathToFileURL as N}from"node:url";import{fork as Me,spawn as Ne,spawnSync as Pe}from"node:child_process";import{copyFile as Fe,mkdir as Ie,readFile as P,readdir as Le,rm as Re,stat as ze,writeFile as F}from"node:fs/promises";import"@forinda/kickjs-cli-kit";import Be from"pluralize";import{arch as Ve,platform as He,release as Ue}from"node:os";import{createHash as We}from"node:crypto";const Ge=[{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 Ke(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)=>{te(`KickJS — Create a new project`);let r=!!(t.yes||t.nonInteractive);e||=r?`my-api`:await oe({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=M(`.`),e=ke(i)):i=M(t.directory||e),T(i)){let n=D(i);if(n.length>0){if(t.force)y.warn(`Clearing existing files in ${i}`);else if(r){y.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),C(`Aborted.`);return}else{y.warn(`Directory "${e}" is not empty:`);let t=n.slice(0,5);for(let e of t)y.message(` - ${e}`);if(n.length>5&&y.message(` ... and ${n.length-5} more`),!await S({message:x.red(`Remove all existing files and proceed?`),initialValue:!1})){C(`Aborted.`);return}}for(let e of n)Ee(M(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=r?`minimal`:await b({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 o=t.runtime;o||=r?`express`:await b({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 c=t.pm;c||=r?await n(void 0):await b({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let l=t.repo;l||=r?`inmemory`:await oe({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),p(l);let u=t.schema;u||=r?`zod`:await b({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(u)||(y.warn(`Unknown --schema "${u}", falling back to zod.`),u=`zod`);let d;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();d=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else d=r?[]:await ie({message:`Select packages to include`,options:[...Ge],required:!1});let f;f=t.git===void 0?r?!0:await S({message:`Initialize git repository?`,initialValue:!0}):t.git;let m;if(m=t.install===void 0?r?!0:await S({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-BfgB5r1W.mjs`);await t({name:e,directory:i,packageManager:c,initGit:f,installDeps:m,schemaLib:u,runtime:o}),C(`Done! Next steps: ${x.cyan(`cd ${e} && ${c}${c===`pnpm`?` dev`:` run dev:server`}`)}`);return}await s({name:e,directory:i,packageManager:c,initGit:f,installDeps:m,template:a,defaultRepo:l,packages:d,schemaLib:u,runtime:o}),C(`Done! Next steps: ${x.cyan(`cd ${e} && ${c} dev`)}`)})}function I(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function L(e){let t=I(e);return t.charAt(0).toLowerCase()+t.slice(1)}function R(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function z(e){return Be.plural(e)}function qe(e){return Be.plural(e)}function Je(e){return R(e).replace(/-/g,`_`)}function Ye(e){let t=e.cwd??process.cwd(),n=e.projectRoot??w(t),r=e.pluralize??!0,i=I(e.name),a=L(e.name),o=R(e.name),s=Je(e.name),c={name:e.name,pascal:i,camel:a,kebab:o,snake:s,modulesDir:e.modulesDir??`src/modules`,cwd:t,projectRoot:n,args:e.args??[],flags:e.flags??{}};if(r){let e=z(o);c.pluralKebab=e,c.pluralPascal=I(e),c.pluralCamel=L(e)}return c}function Xe(e,t){return M(e.cwd,t)}async function Ze(e){return import(N(e).href)}const Qe=new Map;async function $e(e){let t=Qe.get(e);if(t)return t;let n=et(e);return Qe.set(e,n),n}async function et(e){let t=M(e,`package.json`);if(!T(t))return{generators:[],loaded:[],failed:[]};let n=tt(JSON.parse(await P(t,`utf-8`))),r=Ce(M(e,`package.json`)),i=[],a=[],o=[];for(let e of n){let t;try{t=r.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await P(t,`utf-8`))}catch(t){o.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let s=n.kickjs.generators,c=M(k(t),s);if(!T(c)){o.push({source:e,reason:`kickjs.generators points to missing file: ${s}`});continue}let l;try{l=await Ze(c)}catch(t){o.push({source:e,reason:`failed to import manifest: ${t}`});continue}let u=l.default;if(!Array.isArray(u)){o.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of u){if(!nt(t)){o.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}i.push({source:e,spec:t})}a.push(e)}return{generators:i,loaded:a,failed:o}}function tt(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function nt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function rt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return ot(r.spec,r.source,e,n);let i=at(await $e(n),e.generatorName);return i?ot(i.spec,i.source,e,n):null}async function it(e,t=[]){let n=await $e(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function at(e,t){return e.generators.find(e=>e.spec.name===t)}async function ot(e,t,n,r){let i=Ye({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r,projectRoot:n.projectRoot}),a=await e.files(i),o=[];for(let e of a){let t=Xe(i,e.path);await _(t,e.content),o.push(t)}return{files:o,source:t}}function B(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function st(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ct(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function lt(e,t,n){let r={inmemory:`InMemory${e}Repository`,drizzle:`Drizzle${e}Repository`,prisma:`Prisma${e}Repository`},i={inmemory:`in-memory-${t}`,drizzle:`drizzle-${t}`,prisma:`prisma-${t}`};return{repoClass:r[n]??`${st(n)}${e}Repository`,repoFile:i[n]??`${ct(n)}-${t}`}}function ut(e){return e??`define`}function dt(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=lt(t,n,i),c=ut(a),l=`/**
|
|
12
12
|
* ${t} Module
|
|
13
13
|
*
|
|
14
14
|
* REST module with a flat folder structure.
|
|
@@ -85,7 +85,7 @@ ${d}
|
|
|
85
85
|
},
|
|
86
86
|
}),
|
|
87
87
|
})
|
|
88
|
-
`}function
|
|
88
|
+
`}function ft(e){let{pascal:t,kebab:n,plural:r=``,style:i}=e,a=ut(i),o=` /**
|
|
89
89
|
* Declare HTTP routes. Return value shape:
|
|
90
90
|
*
|
|
91
91
|
* - \`path\` — URL prefix for this route set.
|
|
@@ -125,7 +125,7 @@ ${o}
|
|
|
125
125
|
},
|
|
126
126
|
}),
|
|
127
127
|
})
|
|
128
|
-
`}function
|
|
128
|
+
`}function pt(e){let{pascal:t,kebab:n}=e,r=e.swagger?`import { ApiTags } from '@forinda/kickjs-swagger'
|
|
129
129
|
`:``,i=e.swagger?` @ApiTags('${e.pascal}')\n`:``,a=t.charAt(0).toLowerCase()+t.slice(1);return`import {
|
|
130
130
|
Controller,
|
|
131
131
|
Get,
|
|
@@ -197,7 +197,7 @@ ${i} async remove(ctx: Ctx<KickRoutes.${t}Controller['remove']>) {
|
|
|
197
197
|
return reply.noContent()
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
|
-
`}function
|
|
200
|
+
`}function mt(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
201
201
|
|
|
202
202
|
/**
|
|
203
203
|
* Create ${t} DTO — Zod schema for validating POST request bodies.
|
|
@@ -213,20 +213,20 @@ export const create${t}Schema = z.object({
|
|
|
213
213
|
})
|
|
214
214
|
|
|
215
215
|
export type Create${t}DTO = z.infer<typeof create${t}Schema>
|
|
216
|
-
`}function
|
|
216
|
+
`}function ht(e){let{pascal:t}=e;return`import { z } from 'zod'
|
|
217
217
|
|
|
218
218
|
export const update${t}Schema = z.object({
|
|
219
219
|
name: z.string().min(1).max(200).optional(),
|
|
220
220
|
})
|
|
221
221
|
|
|
222
222
|
export type Update${t}DTO = z.infer<typeof update${t}Schema>
|
|
223
|
-
`}function
|
|
223
|
+
`}function gt(e){let{pascal:t}=e;return`export interface ${t}ResponseDTO {
|
|
224
224
|
id: string
|
|
225
225
|
name: string
|
|
226
226
|
createdAt: string
|
|
227
227
|
updatedAt: string
|
|
228
228
|
}
|
|
229
|
-
`}function
|
|
229
|
+
`}function _t(e){let{pascal:t,kebab:n,dtoPrefix:r=`../../application/dtos`,tokenScope:i=`app`}=e;return`/**
|
|
230
230
|
* ${t} Repository Interface
|
|
231
231
|
*
|
|
232
232
|
* Defines the contract for data access.
|
|
@@ -261,7 +261,7 @@ export interface I${t}Repository {
|
|
|
261
261
|
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
262
262
|
*/
|
|
263
263
|
export const ${t.toUpperCase()}_REPOSITORY = createToken<I${t}Repository>('${i}/${t}/repository')
|
|
264
|
-
`}function
|
|
264
|
+
`}function vt(e){let{pascal:t,kebab:n,repoPrefix:r=`../../domain/repositories`,dtoPrefix:i=`../../application/dtos`}=e;return`/**
|
|
265
265
|
* In-Memory ${t} Repository
|
|
266
266
|
*
|
|
267
267
|
* Implements the repository interface using a Map.
|
|
@@ -321,7 +321,7 @@ export class InMemory${t}Repository implements I${t}Repository {
|
|
|
321
321
|
this.store.delete(id)
|
|
322
322
|
}
|
|
323
323
|
}
|
|
324
|
-
`}function
|
|
324
|
+
`}function yt(e){let{pascal:t,kebab:n,repoType:r=``,repoPrefix:i=`../../domain/repositories`,dtoPrefix:a=`../../application/dtos`}=e,o=r.charAt(0).toUpperCase()+r.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return`/**
|
|
325
325
|
* ${o} ${t} Repository
|
|
326
326
|
*
|
|
327
327
|
* Stub implementation for a custom '${r}' repository.
|
|
@@ -390,7 +390,7 @@ export class ${o}${t}Repository implements I${t}Repository {
|
|
|
390
390
|
this.store.delete(id)
|
|
391
391
|
}
|
|
392
392
|
}
|
|
393
|
-
`}function
|
|
393
|
+
`}function bt(e){let{pascal:t,kebab:n,plural:r=``}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
394
394
|
import { Container } from '@forinda/kickjs'
|
|
395
395
|
|
|
396
396
|
describe('${t}Controller', () => {
|
|
@@ -442,7 +442,7 @@ describe('${t}Controller', () => {
|
|
|
442
442
|
})
|
|
443
443
|
})
|
|
444
444
|
})
|
|
445
|
-
`}function
|
|
445
|
+
`}function xt(e){let{pascal:t,kebab:n,plural:r=``,repoPrefix:i=`../infrastructure/repositories/in-memory-${n}.repository`}=e;return`import { describe, it, expect, beforeEach } from 'vitest'
|
|
446
446
|
import { InMemory${t}Repository } from '${i}'
|
|
447
447
|
|
|
448
448
|
describe('InMemory${t}Repository', () => {
|
|
@@ -504,7 +504,7 @@ describe('InMemory${t}Repository', () => {
|
|
|
504
504
|
expect(found).toBeNull()
|
|
505
505
|
})
|
|
506
506
|
})
|
|
507
|
-
`}function
|
|
507
|
+
`}function St(e){let{pascal:t,kebab:n}=e;return`import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
508
508
|
import type { ParsedQuery } from '@forinda/kickjs'
|
|
509
509
|
import { ${t.toUpperCase()}_REPOSITORY, type I${t}Repository } from './${n}.repository'
|
|
510
510
|
import type { ${t}ResponseDTO } from './dtos/${n}-response.dto'
|
|
@@ -541,14 +541,14 @@ export class ${t}Service {
|
|
|
541
541
|
await this.repo.delete(id)
|
|
542
542
|
}
|
|
543
543
|
}
|
|
544
|
-
`}function
|
|
544
|
+
`}function Ct(e){let{pascal:t}=e;return`import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
545
545
|
|
|
546
546
|
export const ${t.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
547
547
|
filterable: ['name'],
|
|
548
548
|
sortable: ['name', 'createdAt'],
|
|
549
549
|
searchable: ['name'],
|
|
550
550
|
}
|
|
551
|
-
`}async function
|
|
551
|
+
`}async function wt(e){let{pascal:t,kebab:n,plural:r,style:i,write:a}=e;await a(`${n}.module.ts`,ft({pascal:t,kebab:n,plural:r,style:i})),await a(`${n}.controller.ts`,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
552
552
|
|
|
553
553
|
// \`Ctx<KickRoutes.${t}Controller['<method>']>\` is generated by
|
|
554
554
|
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
@@ -588,7 +588,7 @@ export class ${t}Controller {
|
|
|
588
588
|
return reply.noContent()
|
|
589
589
|
}
|
|
590
590
|
}
|
|
591
|
-
`)}async function
|
|
591
|
+
`)}async function Tt(e){let{pascal:t,kebab:n,plural:r,pluralPascal:i,repo:a,noTests:o,tokenScope:s,style:c,write:l}=e,u=e.swagger??!1;await l(`${n}.module.ts`,dt({pascal:t,kebab:n,plural:r,repo:a,style:c})),await l(`${n}.constants.ts`,Ct({pascal:t,kebab:n})),await l(`${n}.controller.ts`,pt({pascal:t,kebab:n,plural:r,pluralPascal:i,swagger:u})),await l(`${n}.service.ts`,St({pascal:t,kebab:n})),await l(`dtos/create-${n}.dto.ts`,mt({pascal:t,kebab:n})),await l(`dtos/update-${n}.dto.ts`,ht({pascal:t,kebab:n})),await l(`dtos/${n}-response.dto.ts`,gt({pascal:t,kebab:n})),await l(`${n}.repository.ts`,_t({pascal:t,kebab:n,dtoPrefix:`./dtos`,tokenScope:s}));let d=a===`inmemory`,f=d?`in-memory-${n}`:`${R(a)}-${n}`,p=d?vt({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`}):yt({pascal:t,kebab:n,repoType:a,repoPrefix:`.`,dtoPrefix:`./dtos`});await l(`${f}.repository.ts`,p),o||(a!==`inmemory`&&await l(`in-memory-${n}.repository.ts`,vt({pascal:t,kebab:n,repoPrefix:`.`,dtoPrefix:`./dtos`})),await l(`__tests__/${n}.controller.test.ts`,bt({pascal:t,kebab:n,plural:r})),await l(`__tests__/${n}.repository.test.ts`,xt({pascal:t,kebab:n,plural:r,repoPrefix:`../in-memory-${n}.repository`})))}function Et(e){return e?typeof e==`string`?e:e.name:`inmemory`}async function Dt(e){let{name:t,modulesDir:n,noEntity:r,noTests:i,repo:a=`inmemory`,force:o,dryRun:s}=e,c=e.pluralize!==!1,l=e.pattern??`rest`;e.minimal&&(l=`minimal`);let u=R(t),d=I(t),f=c?z(u):u,p=c?qe(d):d,m=A(n,f),h=[],g=o??!1,b={kebab:u,pascal:d,plural:f,pluralPascal:p,moduleDir:m,repo:a,noEntity:r??!1,noTests:i??!1,tokenScope:e.tokenScope??`app`,swagger:e.swagger??!1,style:e.style??`define`,write:async(e,t)=>{let n=A(m,e);if(s){h.push(n);return}if(!g&&await v(n)&&!await S({message:`File exists: ${x.dim(e)}. Overwrite?`,initialValue:!1})){y.warn(`Skipped: ${e}`);return}await _(n,t),h.push(n)},files:h};switch(l){case`minimal`:await wt(b);break;default:await Tt(b);break}return s||await Ot(n,d,f,u,b.style),h}async function Ot(e,t,n,r,i=`define`){let a=A(e,`index.ts`),o=await v(a),s=`./${n}/${r}.module`,c=i===`class`?`${t}Module`:`${t}Module()`;if(!o){await _(a,i===`class`?`import type { AppModuleEntry } from '@forinda/kickjs'
|
|
592
592
|
import { ${t}Module } from '${s}'
|
|
593
593
|
|
|
594
594
|
export const modules: AppModuleEntry[] = [${c}]
|
|
@@ -596,11 +596,11 @@ export const modules: AppModuleEntry[] = [${c}]
|
|
|
596
596
|
import { ${t}Module } from '${s}'
|
|
597
597
|
|
|
598
598
|
export const modules = defineModules().mount(${c})
|
|
599
|
-
`);return}let l=await
|
|
599
|
+
`);return}let l=await P(a,`utf-8`),u=`import { ${t}Module } from '${s}'`,d=B(s);if(!RegExp(`^import\\s*\\{[^}]*\\b${B(t)}Module\\b[^}]*\\}\\s*from\\s*['"]${d}['"]`,`m`).test(l)){let e=l.lastIndexOf(`import `);if(e!==-1){let t=l.indexOf(`
|
|
600
600
|
`,e);l=l.slice(0,t+1)+u+`
|
|
601
601
|
`+l.slice(t+1)}else l=u+`
|
|
602
|
-
`+l}let f=
|
|
603
|
-
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function
|
|
602
|
+
`+l}let f=At(l);if(f){let e=l.slice(f.rhsStart,f.rhsEnd+1);RegExp(`\\b${B(t)}Module\\b`).test(e)||(l=kt(l,c))}else l=kt(l,c);await F(a,l,`utf-8`)}function kt(e,t){let n=At(e);if(!n)return e;if(n.shape===`array`){let r=e.slice(n.rhsStart+1,n.rhsEnd),i=r.trim(),a;if(!i)a=`[${t}]`;else{let e=i.endsWith(`,`)?``:`,`;a=`[${r.trimEnd()}${e} ${t}]`}return e.slice(0,n.rhsStart)+a+e.slice(n.rhsEnd+1)}return`${e.slice(0,n.chainEnd)}\n .mount(${t})${e.slice(n.chainEnd)}`}function At(e){let t=/export\s+const\s+modules\b[^=]*=/.exec(e);if(!t)return null;let n=t.index+t[0].length;for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]===`[`){let t=Nt(e,n);return t===-1?null:{shape:`array`,rhsStart:n,rhsEnd:t}}if(e.slice(n,n+13)===`defineModules`){let t=jt(e,n);return t===-1?null:{shape:`chain`,rhsStart:n,rhsEnd:t-1,chainEnd:t}}return null}function jt(e,t=0){let n=/defineModules\s*\(/g;n.lastIndex=t;let r=n.exec(e);if(!r)return-1;let i=r.index+r[0].length-1;if(e[i]!==`(`||(i=Pt(e,i),i===-1))return-1;for(i++;;){let t=i;for(;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`.`||e.slice(t,t+6)!==`.mount`)break;for(t+=6;t<e.length&&/\s/.test(e[t]??``);)t++;if(e[t]!==`(`)break;let n=Pt(e,t);if(n===-1)break;i=n+1}return i}function Mt(e,t){let n=e.slice(t,t+2);if(n===`//`){for(t+=2;t<e.length&&e[t]!==`
|
|
603
|
+
`;)t++;return t}if(n===`/*`){for(t+=2;t+1<e.length&&(e[t]!==`*`||e[t+1]!==`/`);)t++;return t+2}return t}function Nt(e,t){if(e[t]!==`[`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Mt(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`[`)n++;else if(i===`]`&&(n--,n===0))return r;r++}return-1}function Pt(e,t){if(e[t]!==`(`)return-1;let n=1,r=t+1;for(;r<e.length;){let t=e.slice(r,r+2);if(t===`//`||t===`/*`){r=Mt(e,r);continue}let i=e[r]??``;if(i===`'`||i===`"`||i==="`"){let t=i;for(r++;r<e.length&&e[r]!==t;)e[r]===`\\`&&r++,r++;r<e.length&&r++;continue}if(i===`(`)n++;else if(i===`)`&&(n--,n===0))return r;r++}return-1}async function Ft(e){let{name:t,outDir:n}=e,r=R(t),i=I(t),a=[],o=A(n,`${r}.adapter.ts`);return await _(o,`import {
|
|
604
604
|
defineAdapter,
|
|
605
605
|
type AdapterContext,
|
|
606
606
|
type AdapterMiddleware,
|
|
@@ -776,7 +776,7 @@ export const ${i}Adapter = defineAdapter<${i}AdapterConfig>({
|
|
|
776
776
|
}
|
|
777
777
|
},
|
|
778
778
|
})
|
|
779
|
-
`),a.push(o),a}async function
|
|
779
|
+
`),a.push(o),a}async function It(e){let{name:t,outDir:n}=e,r=R(t),i=I(t),a=[],o=A(n,`${r}.plugin.ts`);return await _(o,`import {
|
|
780
780
|
definePlugin,
|
|
781
781
|
type AppAdapter,
|
|
782
782
|
type AppModuleEntry,
|
|
@@ -922,10 +922,10 @@ export const ${i}Plugin = definePlugin<${i}PluginConfig>({
|
|
|
922
922
|
},
|
|
923
923
|
}),
|
|
924
924
|
})
|
|
925
|
-
`),a.push(o),a}const
|
|
926
|
-
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=
|
|
925
|
+
`),a.push(o),a}const Lt={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,contributor:`contributors`};function V(e){let{type:t,outDir:n,moduleName:r,modulesDir:i=`src/modules`,defaultDir:a,shouldPluralize:o=!0}=e;if(n)return M(n);if(r){let e=Lt,n=R(r),a=o?z(n):n,s=e[t]??``,c=A(i,a);return M(s?A(c,s):c)}return M(a)}async function Rt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.runtime===`express`,o=e.runtime?`this project runs on ${e.runtime} and has no
|
|
926
|
+
// \`express\``:"this project declares no `runtime` in kick.config.ts, so it\n // may have no `express`",s=V({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/middleware`,pattern:i,shouldPluralize:e.pluralize??!0}),c=R(t),l=L(t),u=[],d=A(s,`${c}.middleware.ts`);return await _(d,`${a?`import type { Request, Response, NextFunction } from 'express'`:`import type { IncomingMessage, ServerResponse } from 'node:http'`}
|
|
927
927
|
|
|
928
|
-
export interface ${
|
|
928
|
+
export interface ${I(t)}Options {
|
|
929
929
|
// Add configuration options here. The factory below closes over the
|
|
930
930
|
// resolved options object; pass them at the call site —
|
|
931
931
|
// \`${l}({ foo: 'bar' })\` — and the closure preserves them across
|
|
@@ -933,7 +933,7 @@ export interface ${F(t)}Options {
|
|
|
933
933
|
}
|
|
934
934
|
|
|
935
935
|
/**
|
|
936
|
-
* ${
|
|
936
|
+
* ${I(t)} middleware.
|
|
937
937
|
*
|
|
938
938
|
* Usage in bootstrap (fires on every request):
|
|
939
939
|
* middleware: [${l}()]
|
|
@@ -965,7 +965,7 @@ export interface ${F(t)}Options {
|
|
|
965
965
|
* Usage with @Middleware decorator:
|
|
966
966
|
* @Middleware(${l}())
|
|
967
967
|
*/
|
|
968
|
-
export function ${l}(options: ${
|
|
968
|
+
export function ${l}(options: ${I(t)}Options = {}) {
|
|
969
969
|
${a?" // Typed from `express` because that is this project's runtime\n // (`runtime: 'express'` in kick.config.ts). Global middleware is\n // connect-style on every engine, but only Express hands the handler its own\n // request / response objects — so `req.originalUrl`, `req.query` and\n // `res.json()` are all available here. Switching `runtime` later means\n // re-typing this signature from `node:http`.\n return (req: Request, res: Response, next: NextFunction) => {":` // Typed from \`node:http\`, not \`express\`. Global middleware is connect-style
|
|
970
970
|
// on every engine, but ${o} dependency to import types from. Under Fastify the handler
|
|
971
971
|
// receives \`request.raw\` / a reply driver, and under h3 the node objects, so
|
|
@@ -978,7 +978,7 @@ ${a?" // Typed from `express` because that is this project's runtime\n // (`ru
|
|
|
978
978
|
next()
|
|
979
979
|
}
|
|
980
980
|
}
|
|
981
|
-
`),u.push(d),u}async function
|
|
981
|
+
`),u.push(d),u}async function zt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=V({type:`guard`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/guards`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=L(t),c=I(t),l=[],u=A(a,`${o}.guard.ts`);return await _(u,`import { Container, HttpException } from '@forinda/kickjs'
|
|
982
982
|
import type { RequestContext } from '@forinda/kickjs'
|
|
983
983
|
|
|
984
984
|
/**
|
|
@@ -1018,7 +1018,7 @@ export async function ${s}Guard(ctx: RequestContext, next: () => void): Promise<
|
|
|
1018
1018
|
ctx.problem.unauthorized({ detail: 'Invalid or expired token' })
|
|
1019
1019
|
}
|
|
1020
1020
|
}
|
|
1021
|
-
`),l.push(u),l}function
|
|
1021
|
+
`),l.push(u),l}function Bt(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 Vt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=e.type??`http`,o=R(t),s=I(t),c=e.key??L(t),l=Array.isArray(e.params)?e.params:Bt(e.params),u=V({type:`contributor`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/contributors`,pattern:i,shouldPluralize:e.pluralize??!0}),d=a===`http`?`defineHttpContextDecorator`:`defineContextDecorator`,f=a===`http`?`RequestContext`:`ExecutionContext`,p=l.length>0?`\nexport type ${s}Params = {\n${l.map(e=>` ${e.name}: ${e.type}`).join(`
|
|
1022
1022
|
`)}\n}\n`:``,m=l.length>0?`${d}.withParams<${s}Params>()({`:`${d}({`,h=l.length>0?` // Every call site must supply these — no placeholder defaults.
|
|
1023
1023
|
// Add \`paramDefaults: { … }\` for any field whose default is
|
|
1024
1024
|
// genuinely correct for an undecorated route, and drop it from here.
|
|
@@ -1069,7 +1069,7 @@ ${v}
|
|
|
1069
1069
|
throw new Error("${s} contributor: resolve() not implemented")
|
|
1070
1070
|
},
|
|
1071
1071
|
})
|
|
1072
|
-
`,b=
|
|
1072
|
+
`,b=A(u,`${o}.contributor.ts`);return await _(b,y),[b]}async function Ht(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=V({type:`service`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/services`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=I(t),c=[],l=A(a,`${o}.service.ts`);return await _(l,`import { Service } from '@forinda/kickjs'
|
|
1073
1073
|
|
|
1074
1074
|
@Service()
|
|
1075
1075
|
export class ${s}Service {
|
|
@@ -1078,7 +1078,7 @@ export class ${s}Service {
|
|
|
1078
1078
|
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
1079
1079
|
// ) {}
|
|
1080
1080
|
}
|
|
1081
|
-
`),c.push(l),c}async function
|
|
1081
|
+
`),c.push(l),c}async function Ut(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=V({type:`controller`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/controllers`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=I(t),c=[],l=A(a,`${o}.controller.ts`);return await _(l,`import { Controller, Get, Post, Put, Delete, reply, type Ctx } from '@forinda/kickjs'
|
|
1082
1082
|
|
|
1083
1083
|
// \`Ctx<KickRoutes.${s}Controller['<method>']>\` is generated by
|
|
1084
1084
|
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
@@ -1120,7 +1120,7 @@ export class ${s}Controller {
|
|
|
1120
1120
|
return reply.noContent()
|
|
1121
1121
|
}
|
|
1122
1122
|
}
|
|
1123
|
-
`),c.push(l),c}async function
|
|
1123
|
+
`),c.push(l),c}async function Wt(e){let{name:t,moduleName:n,modulesDir:r,pattern:i}=e,a=V({type:`dto`,outDir:e.outDir,moduleName:n,modulesDir:r,defaultDir:`src/dtos`,pattern:i,shouldPluralize:e.pluralize??!0}),o=R(t),s=I(t),c=L(t),l=[],u=A(a,`${o}.dto.ts`);return await _(u,`import { z } from 'zod'
|
|
1124
1124
|
|
|
1125
1125
|
export const ${c}Schema = z.object({
|
|
1126
1126
|
// Define your schema fields here
|
|
@@ -1128,7 +1128,7 @@ export const ${c}Schema = z.object({
|
|
|
1128
1128
|
})
|
|
1129
1129
|
|
|
1130
1130
|
export type ${s}DTO = z.infer<typeof ${c}Schema>
|
|
1131
|
-
`),l.push(u),l}async function
|
|
1131
|
+
`),l.push(u),l}async function Gt(e){let t=A(e.outDir,`kick.config.ts`),n=e.modulesDir??`src/modules`,r=e.defaultRepo??`inmemory`;return T(t)&&!e.force&&!await S({message:`kick.config.ts already exists. Overwrite?`,initialValue:!1})?(console.log(`
|
|
1132
1132
|
Skipped — existing kick.config.ts preserved.`),[]):(await _(t,`import { defineConfig } from '@forinda/kickjs-cli'
|
|
1133
1133
|
|
|
1134
1134
|
export default defineConfig({
|
|
@@ -1171,18 +1171,18 @@ export default defineConfig({
|
|
|
1171
1171
|
},
|
|
1172
1172
|
],
|
|
1173
1173
|
})
|
|
1174
|
-
`),[t])}function
|
|
1174
|
+
`),[t])}function Kt(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 H(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=Kt(e,r);return i===-1?null:e.slice(r+1,i)}function U(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
1175
1175
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
1176
|
-
`)}function qt(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 Jt(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 Yt(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=
|
|
1176
|
+
`)}function qt(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 Jt(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 Yt(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=Kt(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=H(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=H(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=H(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=qt(s),p=``;return l&&(p+=` register(container) {${U(l,4,6)} },\n\n`),u&&(p+=` contributors() {${U(u,4,6)} },\n\n`),p+=` routes() {${U(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
1177
1177
|
name: '${r}',
|
|
1178
1178
|
build: () => ({
|
|
1179
1179
|
${p}
|
|
1180
1180
|
}),
|
|
1181
|
-
})`}${c}`}}function Xt(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=
|
|
1182
|
-
`||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=
|
|
1181
|
+
})`}${c}`}}function Xt(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=Kt(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]===`
|
|
1182
|
+
`||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=Kt(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=H(m,/register\s*\(([^)]*)\)\s*\{/),g=H(m,/contributors\s*\(\s*\)\s*\{/),_=H(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=Jt(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${U(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${U(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${U(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
1183
1183
|
${y}
|
|
1184
1184
|
}
|
|
1185
|
-
`}${u}`}}function Zt(e,t){return t===`class`?Xt(e):Yt(e)}function Qt(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function $t(e){let t=[];return await n(
|
|
1185
|
+
`}${u}`}}function Zt(e,t){return t===`class`?Xt(e):Yt(e)}function Qt(e,t){let n=e,r=!1;if(t===`define`){/\bAppModuleClass\b/.test(n)&&(n=n.replaceAll(/\bAppModuleClass\b/g,`AppModuleEntry`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)(?![(.])/g,`$1()`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}else{/\bAppModuleEntry\b/.test(n)&&(n=n.replaceAll(/\bAppModuleEntry\b/g,`AppModuleClass`),r=!0);let e=/(=\s*\[)([\s\S]*?)(])/,t=e.exec(n);if(t){let i=t[1],a=t[3],o=t[2],s=o.replaceAll(/(\b\w+Module)\s*\(\s*\)/g,`$1`);s!==o&&(n=n.replace(e,`${i}${s}${a}`),r=!0)}}return r?{migrated:n}:{migrated:null,reason:`no changes needed`}}async function $t(e){let t=[];return await n(M(e),0),t;async function n(e,r){let i;try{i=await Le(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 ze(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function en(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await Le(e)}catch{return}await Ie(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 ze(i)}catch{continue}s.isDirectory()?await r(i,o):(await Fe(i,o),n++)}}}function tn(e){return A(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function nn(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await $t(e),s=await P(A(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=tn(r),await en(e,c));let l=[];for(let e of o){let t=Zt(await P(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await F(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=A(e,`index.ts`),d=null;try{d=await P(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=Qt(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await F(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function rn(e,t){let n=await $t(e),r=[],i=t===`define`?/export\s+class\s+\w+Module\s+implements\s+AppModule\s*\{/:/export\s+const\s+\w+Module\s*=\s*defineModule\s*\(/;for(let e of n){let t=await P(e,`utf-8`);i.test(t)&&r.push(e)}return r}const an={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 on(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=an[a];if(!o){let e=[...Object.keys(an),`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 sn(e){let{name:t,fields:n,modulesDir:r,repo:i=`inmemory`,tokenScope:a=`app`,style:o=`define`}=e,s=e.pluralize!==!1,c=R(t),l=I(t),u=s?z(c):c,d=s?qe(l):l,f=A(r,u),p=[],m=async(e,t)=>{let n=A(f,e);await _(n,t),p.push(n)};await m(`${c}.module.ts`,dt({pascal:l,kebab:c,plural:u,repo:i,style:o})),await m(`${c}.constants.ts`,Ct({pascal:l,kebab:c})),await m(`${c}.controller.ts`,pt({pascal:l,kebab:c,plural:u,pluralPascal:d,swagger:e.swagger??!1})),await m(`${c}.service.ts`,St({pascal:l,kebab:c})),await m(`dtos/create-${c}.dto.ts`,cn(l,n)),await m(`dtos/update-${c}.dto.ts`,ln(l,n)),await m(`dtos/${c}-response.dto.ts`,un(l,n)),await m(`${c}.repository.ts`,_t({pascal:l,kebab:c,dtoPrefix:`./dtos`,tokenScope:a}));let h=i===`inmemory`,g=h?`in-memory-${c}`:`${R(i)}-${c}`,v=h?vt({pascal:l,kebab:c,repoPrefix:`.`,dtoPrefix:`./dtos`}):yt({pascal:l,kebab:c,repoType:i,repoPrefix:`.`,dtoPrefix:`./dtos`});return await m(`${g}.repository.ts`,v),await Ot(r,l,u,c,o),p}function cn(e,t){return`import { z } from 'zod'
|
|
1186
1186
|
|
|
1187
1187
|
export const create${e}Schema = z.object({
|
|
1188
1188
|
${t.map(e=>{let t=e.zodType;return` ${e.name}: ${t}${e.optional?`.optional()`:``},`}).join(`
|
|
@@ -1205,7 +1205,7 @@ ${t.map(e=>` ${e.name}${e.optional?`?`:``}: ${e.tsType}`).join(`
|
|
|
1205
1205
|
createdAt: string
|
|
1206
1206
|
updatedAt: string
|
|
1207
1207
|
}
|
|
1208
|
-
`}async function dn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=
|
|
1208
|
+
`}async function dn(e){let{name:t,moduleName:n,modulesDir:r}=e,i=e.pluralize??!0,a=R(t),o=I(t),s=[],c;if(e.outDir)c=M(e.outDir);else if(n){let e=R(n),t=i?z(e):e;c=M(A(r??`src/modules`,t,`__tests__`))}else c=M(`src/__tests__`);let l=A(c,`${a}.test.ts`);return await _(l,`import { describe, it, expect, beforeEach } from 'vitest'
|
|
1209
1209
|
import { Container } from '@forinda/kickjs'
|
|
1210
1210
|
|
|
1211
1211
|
describe('${o}', () => {
|
|
@@ -1230,22 +1230,22 @@ describe('${o}', () => {
|
|
|
1230
1230
|
})
|
|
1231
1231
|
`),s.push(l),s}function fn(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}var pn=class extends Error{drifted;constructor(e){let t=e.map(e=>` ${e.id} → ${e.outFile}`).join(`
|
|
1232
1232
|
`);super(`kick typegen --check: ${e.length} generated file(s) are out of date:\n${t}\n Run \`kick typegen\` and commit the result.`),this.name=`TypegenDriftError`,this.drifted=e}};const mn=[`agents`,`claude`,`skills`,`gemini`,`copilot`,`both`,`all`];function W(e){return e.parent?.opts()?.dryRun??!1}function G(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(`
|
|
1233
|
-
(dry run — no files were written)`),console.log()}async function hn(e){if(!e)try{let e=await u(process.cwd());await
|
|
1233
|
+
(dry run — no files were written)`),console.log()}async function hn(e){if(!e)try{let e=await u(process.cwd());await be({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 gn=[{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`}],_n=new Map([[`job`,`Queue processors are no longer built in — their shape belongs to whichever queue you run.
|
|
1234
1234
|
Add your own in kick.config.ts: https://kickjs.app/guide/plugin-generators.html`]]),vn=new Set([...gn.map(e=>e.name.split(` `)[0]),..._n.keys()]);async function yn(){console.log(`
|
|
1235
1235
|
Built-in generators:
|
|
1236
|
-
`);let e=Math.max(...gn.map(e=>e.name.length));for(let t of gn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await u(process.cwd()),n=m(t?.plugins??[],t?.commands??[]),r=await
|
|
1236
|
+
`);let e=Math.max(...gn.map(e=>e.name.length));for(let t of gn)console.log(` kick g ${t.name.padEnd(e+2)} ${t.description}`);let t=await u(process.cwd()),n=m(t?.plugins??[],t?.commands??[]),r=await it(process.cwd(),n.generators);if(r.generators.length>0){console.log(`
|
|
1237
1237
|
Plugin generators:
|
|
1238
1238
|
`);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(`
|
|
1239
1239
|
Failed to load:
|
|
1240
|
-
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function bn(e,t,n){let r=await u(process.cwd()),i=l(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??
|
|
1241
|
-
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await
|
|
1242
|
-
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await
|
|
1240
|
+
`);for(let{source:e,reason:t}of r.failed)console.log(` ${e} — ${t}`)}console.log()}async function bn(e,t,n){let r=await u(process.cwd()),i=l(r),a=t.modulesDir??i.dir??`src/modules`,o=t.repo??Et(i.repo);t.repo&&p(t.repo);let s=t.pattern??r?.pattern??`rest`,c=t.pluralize===!1?!1:i.pluralize??!0,m=d(r,process.cwd()),h=f(w()),g=i.style??`define`;if(!n&&g===`define`){let e=await rn(M(a),`define`);if(e.length>0){console.error(`\n ${x.red(`Error:`)} ${e.length} module file(s) still use the legacy \`class … implements AppModule\` shape.\n ${x.dim(`Project setting:`)} modules.style: 'define' (default)\n\n ${x.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 ${x.bold(`Pick one:`)}\n 1. Migrate everything to defineModule:\n ${x.dim(`$`)} kick codemod modules --experimental --apply\n 2. Keep the class form — pin it in kick.config.ts:\n ${x.dim(`// kick.config.ts`)}\n ${x.dim(`export default defineConfig({ modules: { style: 'class' } })`)}\n`),process.exit(1)}}let _=[];for(let r of e){let e=await Dt({name:r,modulesDir:M(a),noEntity:t.entity===!1,noTests:t.tests===!1,repo:o,minimal:t.minimal,force:t.force,pattern:s,dryRun:n,pluralize:c,tokenScope:m,swagger:h,style:i.style});_.push(...e)}G(_,n),await hn(n)}function xn(e,t){let n=e.command(`generate [names...]`).alias(`g`).description("Generate code scaffolds — bare form `kick g <name>` is shorthand for `kick g module <name>`").option(`--list`,`List all available generators`).option(`--dry-run`,`Preview files that would be generated without writing them`).option(`--no-entity`,`Skip entity and value object generation (module shortcut)`).option(`--no-tests`,`Skip test file generation (module shortcut)`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,r,i)=>{if(r.list){await yn();return}if(!e||e.length===0){n.help();return}let a=W(i);g(a);let[o,s,...c]=e;if(o){let e=await u(process.cwd()),n=m(e?.plugins??[],e?.commands??[]),i=await rt({generatorName:o,itemName:s??``,args:c,flags:r,cwd:process.cwd(),projectRoot:t?.projectRoot},n.generators);if(i){G(i.files,a);return}if(o!==`module`&&vn.has(o)){let e=_n.get(o);e?(console.error(`\n 'kick g ${o}' has been removed.`),console.error(` ${e}\n`)):(console.error(`\n '${o}' is a generator, not a module name.`),console.error(` Did you mean: kick g ${o} ${s??`<name>`}`),console.error(` If that errors, your @forinda/kickjs-cli is older than the '${o}' generator — upgrade it.\n`)),process.exitCode=1;return}}await bn(e,r,a)});n.command(`module <names...>`).description(`Generate one or more modules (e.g. kick g module user task project)`).option(`--no-entity`,`Skip entity and value object generation`).option(`--no-tests`,`Skip test file generation`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name (e.g. postgres)`).option(`--pattern <pattern>`,`Override project pattern: rest | minimal`).option(`--minimal`,`Shorthand for --pattern minimal`).option(`--modules-dir <dir>`,`Modules directory`).option(`--no-pluralize`,`Use singular names (skip auto-pluralization)`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t,n)=>{let r=W(n);g(r),await bn(e,{...n.optsWithGlobals(),...t},r)}),n.command(`adapter <name>`).description(`Generate an AppAdapter with lifecycle hooks and middleware support`).option(`-o, --out <dir>`,`Output directory`,`src/adapters`).action(async(e,t,n)=>{let r=W(n);g(r),G(await Ft({name:e,outDir:M(t.out)}),r)}),n.command(`plugin <name>`).description(`Generate a KickPlugin with DI, modules, adapters, middleware, and lifecycle hooks`).option(`-o, --out <dir>`,`Output directory`,`src/plugins`).action(async(e,t,n)=>{let r=W(n);g(r),G(await It({name:e,outDir:M(t.out)}),r)}),n.command(`middleware <name>`).description(`Generate a global middleware function, typed for the configured runtime
|
|
1241
|
+
Use -m to scope it to a module: kick g middleware auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await Rt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0,runtime:i?.runtime}),r)}),n.command(`guard <name>`).description(`Generate a route guard (auth, roles, etc.)
|
|
1242
|
+
Use -m to scope it to a module: kick g guard admin -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await zt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`contributor <name>`).description(`Generate a Context Contributor (typed alternative to @Middleware for ctx.set)
|
|
1243
1243
|
--type http (default, RequestContext) | bare (ExecutionContext)
|
|
1244
1244
|
--params "source:string,region:number" → emits the withParams<T>() form
|
|
1245
|
-
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=W(n);g(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await u(process.cwd()),o=l(a),s=o.dir??`src/modules`;G(await
|
|
1246
|
-
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await
|
|
1247
|
-
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await
|
|
1248
|
-
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await
|
|
1245
|
+
Use -m to scope it to a module: kick g contributor tenant -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).option(`-t, --type <type>`,`Contributor flavour: http | bare`,`http`).option(`-k, --key <key>`,`Context key it writes (defaults to camelCase of name)`).option(`--params <fields>`,`Per-call params, e.g. "source:string,region:number"`).action(async(e,t,n)=>{let r=W(n);g(r);let i=(t.type??`http`).toLowerCase();i!==`http`&&i!==`bare`&&(console.warn(` kick g contributor: unknown --type '${t.type}', using 'http'.`),i=`http`);let a=await u(process.cwd()),o=l(a),s=o.dir??`src/modules`;G(await Vt({name:e,type:i,key:t.key,params:t.params,outDir:t.out,moduleName:t.module,modulesDir:s,pattern:a?.pattern,pluralize:o.pluralize??!0}),r)}),n.command(`service <name>`).description(`Generate a @Service() class
|
|
1246
|
+
Use -m to scope it to a module: kick g service payment -m orders`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await Ht({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`controller <name>`).description(`Generate a @Controller() class with basic routes
|
|
1247
|
+
Use -m to scope it to a module: kick g controller auth -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await Ut({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r),await hn(r)}),n.command(`dto <name>`).description(`Generate a Zod DTO schema
|
|
1248
|
+
Use -m to scope it to a module: kick g dto create-user -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=await u(process.cwd()),a=l(i),o=a.dir??`src/modules`;G(await Wt({name:e,outDir:t.out,moduleName:t.module,modulesDir:o,pattern:i?.pattern,pluralize:a.pluralize??!0}),r)}),n.command(`test <name>`).description(`Generate a Vitest test scaffold
|
|
1249
1249
|
Use -m to scope it to a module: kick g test user-service -m users`).option(`-o, --out <dir>`,`Output directory (overrides --module)`).option(`-m, --module <module>`,`Place inside a module's __tests__/ folder`).action(async(e,t,n)=>{let r=W(n);g(r);let i=l(await u(process.cwd())),a=i.dir??`src/modules`;G(await dn({name:e,outDir:t.out,moduleName:t.module,modulesDir:a,pluralize:i.pluralize??!0}),r)}),n.command(`scaffold <name> [fields...]`).description(`Generate a full CRUD module from field definitions
|
|
1250
1250
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1251
1251
|
Types: string, text, number, int, float, boolean, date, email, url, uuid, json, enum:a,b,c
|
|
@@ -1255,10 +1255,10 @@ describe('${o}', () => {
|
|
|
1255
1255
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
1256
1256
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
1257
1257
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
1258
|
-
`),process.exit(1));let a=await u(process.cwd()),o=l(a),s=n.modulesDir??o.dir??`src/modules`,c=on(t),p=d(a,process.cwd()),m=f(
|
|
1259
|
-
`,u=``;if(
|
|
1258
|
+
`),process.exit(1));let a=await u(process.cwd()),o=l(a),s=n.modulesDir??o.dir??`src/modules`,c=on(t),p=d(a,process.cwd()),m=f(w()),h=await sn({name:e,fields:c,modulesDir:M(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:p,swagger:m,style:o.style});console.log(`\n Scaffolded ${e} with ${c.length} field(s):`);for(let e of c)console.log(` ${e.name}: ${e.type}${e.optional?` (optional)`:``}`);G(h,i),await hn(i)}),n.command(`config`).description(`Generate a kick.config.ts at the project root`).option(`--modules-dir <dir>`,`Modules directory path`,`src/modules`).option(`--repo <type>`,`Repository name: inmemory (default) or any DB name`,`inmemory`).option(`-f, --force`,`Overwrite existing kick.config.ts without prompting`).action(async(e,t)=>{let n=W(t);g(n),G(await Gt({outDir:M(`.`),modulesDir:e.modulesDir,defaultRepo:e.repo,force:e.force}),n)}),n.command(`agents`).alias(`agent-docs`).alias(`ai-docs`).description(`Regenerate AGENTS.md + CLAUDE.md + kickjs-skills.md (sync after framework upgrades)`).option(`--only <which>`,`Limit scope: agents | claude | skills | both (agents+claude) | all (default: all)`,`all`).option(`--name <name>`,`Project name (defaults to package.json name)`).option(`--pm <pm>`,`Package manager (defaults to package.json packageManager)`).option(`--template <template>`,`Template: rest | minimal`).option(`-f, --force`,`Overwrite existing files without prompting`).action(async(e,t)=>{let n=W(t);g(n);let r=e.only??`all`;if(!mn.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${mn.join(` | `)}`),process.exitCode=1;return}G(await re({outDir:M(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])Sn(n,e,t?.projectRoot)}function Sn(e,t,n){let{source:r,spec:i}=t,a=i.args?.[0],o=a?.name??`itemName`,s=a?.required?`<${o}>`:`[${o}]`,c=`${i.name} ${s} [extraArgs...]`,l=e.command(c).description(`${i.description} [${r}]`);for(let e of i.flags??[]){let t=e.takesValue?`--${e.name} <value>`:`--${e.name}`,n=e.alias?`-${e.alias}, ${t}`:t;l.option(n,e.description??``)}l.action(async(e,r,a,o)=>{let s=W(o);g(s);let c=await rt({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&G(c.files,s)})}const Cn=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: `;async function wn(e){let t=O.resolve(e.cwd,`.kickjs/types`);e.check||await Ie(t,{recursive:!0});let n=new Map,r=e.scan??fe,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(N(e).href)},async writeFile(t,n){let r=O.resolve(e.cwd,t);await Ie(O.dirname(r),{recursive:!0}),await F(r,n,`utf8`)},getScanResult:e=>{let t=Tn(e),o=n.get(t);if(!o){let s={cacheDir:i,...e};o=a?de(s,a):r(s),n.set(t,o)}return o},log:console,watch:e.watch,check:e.check},s=[],c=[];for(let n of e.plugins){let r=n.outExtension??`.d.ts`,i=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=`${Cn}${n.id} */\n\n`+a+`
|
|
1259
|
+
`,u=``;if(T(i)&&(u=await P(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 F(i,l,`utf8`),s.push({id:n.id,status:`written`,outFile:i})}if(c.length>0)throw new pn(c);return s}function Tn(e){let t=(e.extensions??[]).slice().toSorted().join(`,`),n=(e.exclude??[]).slice().toSorted().join(`,`);return[`root=${e.root}`,`cwd=${e.cwd}`,`extensions=${t}`,`exclude=${n}`,`envFile=${e.envFile??``}`].join(`|`)}function En(e,t){let n=new Set(t),r=[],i=[],a=new Set;for(let t of e)n.has(t.id)?(i.push(t),a.add(t.id)):r.push(t);return{enabled:r,skipped:i,unknown:[...n].filter(e=>!a.has(e))}}var Dn=e({applyDisableFilter:()=>En,runAllPluginTypegens:()=>On});async function On(e){let{enabled:t,skipped:n,unknown:r}=En(m([...ka,...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 wn({cwd:e.cwd,config:e.config??{},plugins:t,watch:e.watch,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&fn())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(t instanceof pn||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 kn(e){let t=new Map;return{report(n,r){let i=r instanceof Error?r.message:String(r);t.get(n)!==i&&(t.set(n,i),e(` kick typegen: ${n} pass failed (${i}) — types in .kickjs/types may be stale`))},clear(e){t.delete(e)}}}function An(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await import(`./typegen-DiD6n0_q.mjs`).then(e=>e.n)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Dn)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await import(`./typegen-DiD6n0_q.mjs`).then(e=>e.n)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await import(`./build-1OHeIhGr.mjs`).then(e=>e.n)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=O.resolve(t,n?.typegen?.outDir??`.kickjs/types`),c=n?.assetMap?Object.values(n.assetMap).map(e=>e?.src).filter(e=>typeof e==`string`&&e.length>0).map(e=>O.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,u=e=>e.replaceAll(`\\`,`/`),d=c.map(u),f=e=>{let t=u(e);return d.some(e=>t===e||t.startsWith(`${e}/`))},p=kn(e.emitWarning),m=null,h=!1,g=new Set,_=new Set,v=!1,y=!1;function b(r,c){i.runTypegen({cwd:t,silent:!0,allowDuplicates:!0,schemaValidator:a,envFile:o,srcDir:n?.typegen?.srcDir,outDir:n?.typegen?.outDir,assetMap:n?.assetMap,changedFiles:r,runPlugins:!1}).then(()=>p.clear(`scan`)).catch(e=>p.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r,watch:!0}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>p.clear(`plugins`)).catch(e=>p.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function ee(){let e=v?void 0:{changed:[...g],removed:[..._]},t=y;g.clear(),_.clear(),v=!1,y=!1,b(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!h&&!u(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)v=!0,l&&(y=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=f(t);if(!n&&!r)return;r&&l&&(y=!0),n&&(e===`unlink`?(_.add(t),g.delete(t)):(g.add(t),_.delete(t)))}m&&clearTimeout(m),m=setTimeout(ee,r)}},runOnce(){h||b(void 0,l)},dispose(){h=!0,m&&clearTimeout(m),m=null}}}function jn(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(T(r))return{cmd:r,args:[`--noEmit`],shell:n,kind:e}}}return null}function Mn(e){let t=e.spawnFn??Ne,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 Nn(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
1260
1260
|
`):`${n.slice(0,t).join(`
|
|
1261
|
-
`)}\n… ${n.length-t} more line(s)`}function Pn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Fn(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 In(e,t,n={}){t&&(process.env.PORT=t);let r=Pn(n.polling),i=process.cwd(),a=await u(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await
|
|
1261
|
+
`)}\n… ${n.length-t} more line(s)`}function Pn(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function Fn(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 In(e,t,n={}){t&&(process.env.PORT=t);let r=Pn(n.polling),i=process.cwd(),a=await u(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await be({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=M(i,a?.typegen?.outDir??`.kickjs/types`);try{await pe(c,await On({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:d}=await import(N(l(M(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let f=await d({configFile:M(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),p=n.typecheck??a?.dev?.typecheck??!1,m=null,h=!0;if(p){let e=jn(i);e?m=Mn({cwd:i,bin:e,onResult:e=>{f.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?h||(h=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(h=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(Nn(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let g=An({cwd:i,config:a,emitWarning:e=>{console.warn(e),f.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>m?.schedule()});f.watcher.on(`add`,e=>g.handleWatchEvent(`add`,e)),f.watcher.on(`unlink`,e=>g.handleWatchEvent(`unlink`,e)),f.watcher.on(`change`,e=>g.handleWatchEvent(`change`,e)),f.watcher.on(`unlinkDir`,e=>g.handleWatchEvent(`unlinkDir`,e)),g.assetSrcRoots.length>0&&f.watcher.add([...g.assetSrcRoots]),await f.listen(),f.printUrls(),console.log(`
|
|
1262
1262
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
1263
1263
|
`),m?.schedule();let _=!1,v=async()=>{if(!_){_=!0,g.dispose(),m?.dispose();try{await globalThis.__kickjs_app_shutdown?.()}catch(e){console.error(` app shutdown hook failed: ${e?.message??e}`)}await f.close(),process.exit(0)}};process.on(`SIGINT`,v),process.on(`SIGTERM`,v),process.on(`SIGBREAK`,v)}function Ln(e){e.command(`dev`).description(`Start development server with Vite HMR (zero-downtime reload)`).option(`-e, --entry <file>`,`Entry file`,`src/index.ts`).option(`-p, --port <port>`,`Port number`).option(`--polling`,`Force chokidar to poll for file changes (Docker / WSL / NFS / older kernels)`).option(`--typecheck`,`Run the project TypeScript checker (tsgo/tsc --noEmit) after each change and report diagnostics`).action(async e=>{try{await In(e.entry,e.port,{polling:e.polling,typecheck:e.typecheck})}catch(e){e.code===`ERR_MODULE_NOT_FOUND`&&e.message?.includes(`vite`)?console.error(`
|
|
1264
1264
|
Error: vite is not installed.
|
|
@@ -1266,19 +1266,19 @@ describe('${o}', () => {
|
|
|
1266
1266
|
`):console.error(`
|
|
1267
1267
|
Dev server failed:`,e.message??e),process.exit(1)}}),e.command(`build`).description(`Build for production via Vite`).action(async()=>{console.log(`
|
|
1268
1268
|
Building for production...
|
|
1269
|
-
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(
|
|
1270
|
-
Copying directories to dist...`);for(let e of r){let t=typeof e==`string`?e:e.src,n=typeof e==`string`?
|
|
1271
|
-
Building asset map...`);try{await
|
|
1269
|
+
`);let{createRequire:e}=await import(`node:module`),{build:t}=await import(N(e(M(`package.json`)).resolve(`vite`)).href);await t({configFile:M(`vite.config.ts`)});let n=await u(process.cwd()),r=n?.copyDirs??[];if(r.length>0){console.log(`
|
|
1270
|
+
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=M(t),i=M(n);if(!T(r)){console.log(` ⚠ Skipped ${t} (not found)`);continue}Te(i,{recursive:!0}),we(r,i,{recursive:!0}),console.log(` ✓ ${t} → ${n}`)}}if(n?.assetMap&&Object.keys(n.assetMap).length>0){console.log(`
|
|
1271
|
+
Building asset map...`);try{await Se(n,{cwd:process.cwd()})}catch(e){console.error(` ✗ asset build failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}console.log(`
|
|
1272
1272
|
Build complete.
|
|
1273
1273
|
`)}),e.command(`build:assets`).description(`Rebuild the .kickjs-assets.json manifest under the configured outDir (no JS rebuild)`).action(async()=>{let e=await u(process.cwd());if(!e?.assetMap||Object.keys(e.assetMap).length===0){console.log(` No assetMap entries — nothing to build.`);return}console.log(`
|
|
1274
|
-
Building asset map...`);try{await
|
|
1274
|
+
Building asset map...`);try{await Se(e,{cwd:process.cwd()}),console.log(`
|
|
1275
1275
|
Asset build complete.
|
|
1276
|
-
`)}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)),c(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=
|
|
1276
|
+
`)}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)),c(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=M(process.cwd(),e.cwd??`.`),n=jn(t);if(!n){console.error(`
|
|
1277
1277
|
No type-checker found. Install one in this project:
|
|
1278
1278
|
pnpm add -D typescript (tsc)
|
|
1279
1279
|
pnpm add -D @typescript/native-preview (tsgo, faster)
|
|
1280
|
-
`),process.exit(1);return}let r=
|
|
1281
|
-
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Rn(){try{let e=
|
|
1280
|
+
`),process.exit(1);return}let r=Pe(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 Fn(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 In(e.entry,e.port)}catch(e){console.error(`
|
|
1281
|
+
Dev server (debug) failed:`,e.message??e),process.exit(1)}})}function Rn(){try{let e=k(je(import.meta.url));return JSON.parse(E(A(e,`..`,`package.json`),`utf-8`)).version??`unknown`}catch{return`unknown`}}const zn=new Set(Object.values(a).filter(e=>e.deprecated).map(e=>e.pkg));function Bn(e){let t=A(e,`package.json`);if(!T(t))return[];let n;try{n=JSON.parse(E(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(T(i))try{n=JSON.parse(E(i,`utf-8`)).version??null}catch{}return{name:t,installed:n,declared:r[t]??null,deprecated:zn.has(t)}})}function Vn(e){let t=e;for(;;){if(T(A(t,`package.json`)))return t;let e=k(t);if(e===t)return null;t=e}}function Hn(e){e.command(`info`).description(`Print system and framework info`).action(()=>{let e=[``,` KickJS CLI v${Rn()}`,``,` System:`,` OS: ${He()} ${Ue()} (${Ve()})`,` Node: ${process.version}`],t=Vn(process.cwd()),n=t?Bn(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(`
|
|
1282
1282
|
`))})}const{bold:K,dim:q,green:Un,red:J,yellow:Wn,blue:Gn}=x;function Kn(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 qn(e){let t=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`${t.status} ${t.statusText}`);return t.json()}async function Y(e,t){try{return await qn(`${e}${t}`)}catch{return null}}async function Jn(e){let[t,n,r,i,a]=await Promise.all([Y(e,`/health`),Y(e,`/metrics`),Y(e,`/routes`),Y(e,`/container`),Y(e,`/ws`)]);return{health:t,metrics:n,routes:r,container:i,ws:a}}function Yn(e,t){let{health:n,metrics:r,routes:i,container:a,ws:o}=t,s=q(`─`.repeat(60));if(console.log(),console.log(K(` KickJS Inspector`)+q(` → ${e}`)),console.log(s),n){let e=n.status===`healthy`?Un(`● healthy`):J(`● `+n.status);console.log(` ${K(`Health:`)} ${e}`)}else console.log(` ${K(`Health:`)} ${J(`● unreachable`)}`);if(r){let e=((r.errorRate??0)*100).toFixed(1),t=r.errorRate>.1?J:r.errorRate>0?Wn:Un;console.log(` ${K(`Uptime:`)} ${Kn(r.uptimeSeconds)}`),console.log(` ${K(`Requests:`)} ${r.requests}`),console.log(` ${K(`Errors:`)} ${r.serverErrors} server, ${r.clientErrors??0} client ${q(`(`)}${t(e+`%`)}${q(`)`)}`)}if(a&&console.log(` ${K(`DI:`)} ${a.count} bindings`),o&&o.enabled&&console.log(` ${K(`WS:`)} ${o.connections??0} connections, ${o.namespaces??0} namespaces`),i?.routes?.length){console.log(),console.log(K(` Routes`)),console.log(s),console.log(` ${q(`METHOD`)} ${q(`PATH`.padEnd(36))} ${q(`CONTROLLER`)}`);for(let e of i.routes){let t=e.path.length>36?e.path.slice(0,33)+`...`:e.path.padEnd(36);console.log(` ${ee(e.method)} ${t} ${Gn(e.controller)}.${q(e.handler)}`)}}console.log(s),console.log()}function Xn(e){e.command(`inspect [url]`).description(`Connect to a running KickJS app and display debug info`).option(`-p, --port <port>`,`Override port`).option(`-w, --watch`,`Poll every 5 seconds`).option(`-j, --json`,`Output raw JSON`).action(async(e,t)=>{let n=e??`http://localhost:3000`;if(t.port)try{let e=new URL(n);e.port=t.port,n=e.origin}catch{n=`http://localhost:${t.port}`}let r=`${n.replace(/\/$/,``)}/_debug`,i=async()=>{try{let e=await Jn(r);t.json?console.log(JSON.stringify(e,null,2)):Yn(n,e)}catch(e){t.json?console.log(JSON.stringify({error:String(e)})):(console.error(J(` ✖ Could not connect to ${n}`)),console.error(q(` ${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 Zn(e,t){let n=e.toLowerCase();return t.every(e=>n.includes(e.toLowerCase()))}function X(e,t){let n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}const Qn=[{match(e,t){let n=Zn(e,[`config`,`get`])&&X(e,[`undefined`,`null`]),r=e.includes(`@Value`)&&X(e,[`undefined`,`is not defined`]);return!n&&!r?null:X(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
|
|
1283
1283
|
src/config/index.ts, and src/index.ts imports it before bootstrap().
|
|
1284
1284
|
Tests never load src/index.ts — \`createTestApp\` builds the app
|
|
@@ -1415,7 +1415,7 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1415
1415
|
`),process.exit(1));let r=dr(),i=$n(n,r);if(t.json&&i){process.stdout.write(JSON.stringify({matched:!0,...i},null,2)+`
|
|
1416
1416
|
`);return}if(i){fr(n,i.diagnosis,i.confidence);return}t.ai||(t.json&&(process.stdout.write(JSON.stringify({matched:!1},null,2)+`
|
|
1417
1417
|
`),process.exit(2)),pr(n,!1),process.exit(2));let a=await er({input:n,model:t.model,cwd:r.cwd});t.json&&(process.stdout.write(JSON.stringify(sr(a),null,2)+`
|
|
1418
|
-
`),process.exit(a.kind===`ok`?0:2)),cr(n,a),process.exit(a.kind===`ok`?0:2)})}function sr(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 cr(e,t){if(t.kind===`ok`){fr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${mr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Z(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${mr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function lr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:ur()}function ur(){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 dr(){let e=process.cwd();return{cwd:e,hasFile:t=>
|
|
1418
|
+
`),process.exit(a.kind===`ok`?0:2)),cr(n,a),process.exit(a.kind===`ok`?0:2)})}function sr(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 cr(e,t){if(t.kind===`ok`){fr(e,t.diagnosis,-1,!0);return}if(t.kind===`unavailable`){process.stdout.write(`\n Explaining: ${mr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback unavailable: ${t.reason}\n\n`),process.stdout.write(`${Z(t.suggestion,` `)}\n\n`);return}process.stdout.write(`\n Explaining: ${mr(e.trim(),200)}\n\n`),process.stdout.write(` AI fallback error: ${t.message}\n\n`)}async function lr(e,t){return e&&e.trim().length>0?e:t&&t.trim().length>0?t:process.stdin.isTTY?``:ur()}function ur(){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 dr(){let e=process.cwd();return{cwd:e,hasFile:t=>T(M(e,t))}}function fr(e,t,n,r=!1){let i=mr(e.trim(),200),a=r?`AI-generated — verify before applying`:hr(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${Z(t.explanation,` `)}\n`),process.stdout.write(`\n Fix:\n${Z(t.fix,` `)}\n`),t.codeBefore&&process.stdout.write(`\n Before:\n${Z(t.codeBefore,` `)}\n`),t.codeAfter&&process.stdout.write(`\n After:\n${Z(t.codeAfter,` `)}\n`),t.docs&&process.stdout.write(`\n Docs: ${t.docs}\n`),process.stdout.write(`
|
|
1419
1419
|
`)}function pr(e,t){let n=mr(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.
|
|
1420
1420
|
When @forinda/kickjs-ai ships its provider implementations,
|
|
1421
1421
|
this command will call the configured LLM with the error +
|
|
@@ -1435,10 +1435,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
1435
1435
|
|
|
1436
1436
|
`)}function Z(e,t){return e.split(`
|
|
1437
1437
|
`).map(e=>`${t}${e}`).join(`
|
|
1438
|
-
`)}function mr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function hr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function gr(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(_r),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(vr)}function _r(e){let t=
|
|
1439
|
-
`,`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 yr(e){let t=
|
|
1438
|
+
`)}function mr(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function hr(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function gr(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(_r),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(vr)}function _r(e){let t=M(e.entry);T(t)||(process.stderr.write(`Error: entry file not found: ${t}\n\nBuild the app first with \`kick build\`, or pass a custom entry:\n kick mcp -e dist/server.js\n`),process.exit(1));let n=[...e.nodeArg??[],t],r=Ne(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});r.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),r.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let i=e=>{r.killed||r.kill(e)};process.on(`SIGINT`,()=>i(`SIGINT`)),process.on(`SIGTERM`,()=>i(`SIGTERM`))}function vr(e){let t=process.cwd(),n=yr(t)??ke(t),r=e.name??n,i=e.global?M(process.env.HOME??`.`,`.mcp.json`):M(t,e.out),a={command:`kick`,args:[`mcp`],cwd:t},o={mcpServers:{}};if(T(i))try{let e=E(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,Oe(i,JSON.stringify(o,null,2)+`
|
|
1439
|
+
`,`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 yr(e){let t=M(e,`package.json`);if(!T(t))return null;try{let e=E(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function br(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=M(t,e.entry);T(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let r=Sr(t,`tsx`);r||(console.error(`
|
|
1440
1440
|
Error: tsx not found. Install it: pnpm add -D tsx
|
|
1441
|
-
`),process.exit(1));let i=xr(n,e.entry),a=
|
|
1441
|
+
`),process.exit(1));let i=xr(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=Me(a,[],{cwd:t,execPath:r,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{s(a)}catch{}}})}function xr(e,t){return`
|
|
1442
1442
|
import 'reflect-metadata'
|
|
1443
1443
|
|
|
1444
1444
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -1463,7 +1463,7 @@ try {
|
|
|
1463
1463
|
|
|
1464
1464
|
// Load entry to trigger decorator registration
|
|
1465
1465
|
try {
|
|
1466
|
-
await import('${
|
|
1466
|
+
await import('${N(e).href}')
|
|
1467
1467
|
} catch (err) {
|
|
1468
1468
|
console.warn(' Warning: ' + err.message)
|
|
1469
1469
|
console.warn(' Container may be partially initialized.\\n')
|
|
@@ -1492,36 +1492,36 @@ server.on('exit', () => {
|
|
|
1492
1492
|
console.log('\\n Goodbye!\\n')
|
|
1493
1493
|
process.exit(0)
|
|
1494
1494
|
})
|
|
1495
|
-
`}function Sr(e,t){let n=e;for(;;){let e=
|
|
1495
|
+
`}function Sr(e,t){let n=e;for(;;){let e=A(n,`node_modules`,`.bin`,t);if(T(e))return e;let r=M(n,`..`);if(r===n)break;n=r}return null}function Cr(e,t){let n=RegExp(`^\\s*${B(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]!==`
|
|
1496
1496
|
`;)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]===`
|
|
1497
|
-
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function wr(e,t){let n=
|
|
1497
|
+
`);)t--;a=a.slice(0,t)+a.slice(s+1),r=!0,i=t;continue}i=s+1}return{content:a,changed:r}}function wr(e,t){let n=At(e);if(!n)return e;let r=n.rhsStart,i=n.rhsEnd+1,a=e.slice(r,i);return a=Cr(a,t).content,a=a.replace(RegExp(`\\s*,?\\s*${B(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 Tr(e){let{name:t,modulesDir:n,force:r}=e,i=e.pluralize!==!1,a=R(t),o=I(t),s=i?z(a):a,c=A(n,s);if(!await v(c)){console.log(`\n Module not found: ${c}\n`);return}if(!r&&!await S({message:x.red(`Delete module '${s}' at ${c}? This cannot be undone.`),initialValue:!1})){console.log(`
|
|
1498
1498
|
Cancelled.
|
|
1499
|
-
`);return}await
|
|
1499
|
+
`);return}await Re(c,{recursive:!0,force:!0}),console.log(` Deleted: ${c}`);let l=A(n,`index.ts`);if(await v(l)){let e=await P(l,`utf-8`),t=e,n=RegExp(`^import\\s*\\{\\s*${B(o)}Module\\s*\\}\\s*from\\s*['"][^'"]*${B(s)}(?:/[^'"]*)?['"].*\\n?`,`gm`);e=e.replace(n,``),e=wr(e,o),e=e.replace(/\n{3,}/g,`
|
|
1500
1500
|
|
|
1501
|
-
`),e!==t&&(await
|
|
1501
|
+
`),e!==t&&(await F(l,e,`utf-8`),console.log(` Unregistered: ${o}Module from ${l}`))}console.log(`\n Module '${s}' removed.\n`)}function Er(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=l(await u(process.cwd())),r=t.modulesDir??n.dir??`src/modules`,i=t.pluralize===!1?!1:n.pluralize??!0;for(let n of e)await Tr({name:n,modulesDir:M(r),force:t.force,pluralize:i})})}function Dr(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 Or(e){if(e!==void 0)return e===`false`||e===`off`||e===`none`?!1:e}function kr(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=w(process.cwd()),n=await u(t);if(e.list){let{mergeCliPlugins:e}=await import(`./plugin-LY_08MMA.mjs`).then(e=>e.t),{builtinCliPlugins:t}=await Promise.resolve().then(()=>Oa),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(`
|
|
1502
1502
|
Registered typegen plugins:
|
|
1503
|
-
`);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=Dr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Or(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
|
|
1503
|
+
`);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=Dr(e.schemaValidator)??n?.typegen?.schemaValidator??`zod`,i=Or(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 ve(a);e.silent||console.log(` kick typegen: watching for changes (Ctrl-C to exit)`);let n=()=>{t(),process.exit(0)};process.on(`SIGINT`,n),process.on(`SIGTERM`,n),await new Promise(()=>{})}else{await be(a);let r=await On({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 pe(M(t,e.out??n?.typegen?.outDir??`.kickjs/types`),r,e.silent??!1)}}catch(e){e instanceof ye?console.error(`
|
|
1504
1504
|
`+e.message+`
|
|
1505
1505
|
`):e instanceof pn?console.error(`
|
|
1506
1506
|
`+e.message+`
|
|
1507
|
-
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Ar(e){let t=[];if(!
|
|
1507
|
+
`):e instanceof Error?console.error(`\n kick typegen failed: ${e.message}`):console.error(`\n kick typegen failed: ${JSON.stringify(e)}`),process.exit(1)}})}function Ar(e){let t=[];if(!T(e))return t;let n=D(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(...Ar(n))}else r.isFile()&&/\.tsx?$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(n)}return t}function jr(e){try{return E(e,`utf-8`)}catch{return``}}const Mr=new Set([`secret`,`changeme`,`password`,`test`,`default`,``]);function Nr(e,t){let n=jr(A(e,`.env`));if(n){let e=n.match(/^JWT_SECRET\s*=\s*['"]?([^'"\n]*)['"]?/m);if(e){let t=e[1].trim();if(Mr.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 Pr(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 Fr(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 Ir(){return process.env.NODE_ENV===`production`?null:{severity:`WARNING`,message:`NODE_ENV is '${process.env.NODE_ENV??`undefined`}', not 'production'`}}function Lr(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 zr(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 Br(e){let t=Ar(A(e,`src`)).map(e=>jr(e)),n=[],r=Nr(e,t);r&&n.push(r);let i=Pr(t);i&&n.push(i);let a=Fr(t);a&&n.push(a);let o=Ir();o&&n.push(o);let s=Lr(t);return s&&n.push(s),n.push(Rr(t)),n.push(zr(t)),n}function Vr(e){e.command(`check`).description(`Audit project for common issues`).option(`--deploy`,`Run production readiness checks`).action(e=>{if(!e.deploy){console.log(`
|
|
1508
1508
|
Usage: kick check --deploy
|
|
1509
1509
|
|
|
1510
1510
|
Available checks:
|
|
1511
1511
|
--deploy Audit for production readiness (security, config, best practices)
|
|
1512
|
-
`);return}let t=process.cwd();te(`KickJS Deploy Check`);let n=ne();n.start(`Scanning project...`);let r=Br(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)y.message(`${ae(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?x.red(`${a} critical`):`${a} critical`,o>0?x.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(C(x.red(`${l} — fix critical issues before deploying`)),process.exit(1)):C(x.green(`${l} — looking good!`))})}function Hr(e){try{return JSON.parse(
|
|
1513
|
-
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Zr(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function Qr(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:"`@forinda/kickjs` declares `express` as a required peer dependency, but your package.json does not include it. Install: pnpm add express"}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const $r={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function ei(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=$r[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: pnpm add ${n.join(` `)}`}:{name:r,status:`pass`}}function ti(e){if(!e.pkg||!ri(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const ni=2e3;function ri(e){let t=
|
|
1512
|
+
`);return}let t=process.cwd();te(`KickJS Deploy Check`);let n=ne();n.start(`Scanning project...`);let r=Br(t);n.stop(`Scan complete`);let i={CRITICAL:0,WARNING:1,INFO:2};r.sort((e,t)=>i[e.severity]-i[t.severity]);for(let e of r)y.message(`${ae(e.severity)} ${e.message}`);let a=r.filter(e=>e.severity===`CRITICAL`).length,o=r.filter(e=>e.severity===`WARNING`).length,s=r.filter(e=>e.severity===`INFO`).length,c=o===1?`warning`:`warnings`,l=[a>0?x.red(`${a} critical`):`${a} critical`,o>0?x.yellow(`${o} ${c}`):`${o} ${c}`,`${s} info`].join(`, `);a>0?(C(x.red(`${l} — fix critical issues before deploying`)),process.exit(1)):C(x.green(`${l} — looking good!`))})}function Hr(e){try{return JSON.parse(E(e,`utf-8`))}catch{return null}}function Ur(e){try{return E(e,`utf-8`)}catch{return null}}function Wr(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,``).replace(/(^|[^:"'\\])\/\/.*$/gm,`$1`).replace(/,(\s*[}\]])/g,`$1`);try{return JSON.parse(t)}catch{return null}}function Gr(e){let t=A(e,`tsconfig.json`);if(T(t))return Kr(t,new Set)}function Kr(e,t){if(t.has(e)||t.size>=16)return null;t.add(e);let n=Ur(e);if(n===null)return null;let r=Wr(n);if(typeof r!=`object`||!r)return null;let i=Array.isArray(r.extends)?r.extends:typeof r.extends==`string`?[r.extends]:[],a={};for(let n of i){if(typeof n!=`string`)continue;let r=qr(k(e),n);if(!r)continue;let i=Kr(r,t);i&&Object.assign(a,i.compilerOptions)}return r.compilerOptions={...a,...r.compilerOptions},r}function qr(e,t){if(t.startsWith(`.`)||t.startsWith(`/`))return Jr(M(e,t));let n=e;for(;;){let e=Jr(A(n,`node_modules`,t));if(e)return e;let r=k(n);if(r===n)break;n=r}return null}function Jr(e){if(T(e)){try{if(De(e).isDirectory()){let t=A(e,`tsconfig.json`);return T(t)?t:null}}catch{return null}return e}let t=`${e}.json`;return T(t)?t:null}function Yr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Xr(){let e=process.version,t=Number.parseInt(e.replace(/^v/,``).split(`.`)[0],10);return Number.isNaN(t)||t<20?{name:`Node version`,status:`fail`,message:e,fix:`KickJS requires Node 20 or newer.
|
|
1513
|
+
Install a supported version via nvm / fnm / volta.`}:{name:`Node version`,status:`pass`,message:e}}function Zr(e){if(!e.pkg)return{name:`@forinda/kickjs installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]?{name:`@forinda/kickjs installed`,status:`pass`,message:t[`@forinda/kickjs`]}:{name:`@forinda/kickjs installed`,status:`fail`,fix:"This directory does not look like a KickJS project — `@forinda/kickjs` is not in your package.json. Run `kick doctor` from the project root, or scaffold a fresh project with `kick new <name>`."}}function Qr(e){if(!e.pkg)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies};return t[`@forinda/kickjs`]&&!t.express?{name:`express installed`,status:`fail`,fix:"`@forinda/kickjs` declares `express` as a required peer dependency, but your package.json does not include it. Install: pnpm add express"}:t.express?{name:`express installed`,status:`pass`,message:t.express}:null}const $r={express:[],fastify:[`fastify`,`@fastify/middie`],h3:[`h3`]};function ei(e){if(!e.pkg||e.runtime===`express`)return null;let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies},n=$r[e.runtime].filter(e=>!t[e]),r=`runtime engine (${e.runtime})`;return n.length>0?{name:r,status:`fail`,fix:`Resolved runtime '${e.runtime}' is missing engine peer(s): ${n.join(`, `)}.\nInstall: pnpm add ${n.join(` `)}`}:{name:r,status:`pass`}}function ti(e){if(!e.pkg||!ri(e.cwd))return null;let t=r[e.runtime],n=`upload driver (${e.runtime})`;return t.prod?{...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies}[t.prod]?{name:n,status:`pass`,message:t.prod}:{name:n,status:`fail`,fix:`This project uses file uploads on the '${e.runtime}' runtime, which needs '${t.prod}'.\nInstall it: kick add upload (or pnpm add ${t.prod})`}:{name:n,status:`pass`,message:`native multipart`}}const ni=2e3;function ri(e){let t=A(e,`src`);if(!T(t))return!1;let n=/@FileUpload\b|\bupload\.(single|array|none)\s*\(/,r=[t],i=0;for(;r.length>0&&i<ni;){let e=r.pop(),t;try{t=D(e,{withFileTypes:!0})}catch{continue}for(let a of t){if(i>=ni)break;let t=A(e,a.name);if(a.isDirectory()){a.name!==`node_modules`&&r.push(t);continue}if(/\.(ts|tsx|mts|cts)$/.test(a.name)&&(i++,n.test(Ur(t)??``)))return!0}}return!1}function ii(e){if(!e.pkg)return{name:`reflect-metadata installed`,status:`warn`,message:`no package.json`};let t={...e.pkg.dependencies,...e.pkg.peerDependencies,...e.pkg.devDependencies};return t[`reflect-metadata`]?{name:`reflect-metadata installed`,status:`pass`,message:t[`reflect-metadata`]}:{name:`reflect-metadata installed`,status:`fail`,fix:`KickJS decorators require the reflect-metadata polyfill.
|
|
1514
1514
|
Install it: pnpm add reflect-metadata
|
|
1515
1515
|
Then import it at the top of src/index.ts:
|
|
1516
1516
|
|
|
1517
1517
|
import 'reflect-metadata'
|
|
1518
|
-
// ... rest of bootstrap`}}function ai(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function oi(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>
|
|
1518
|
+
// ... rest of bootstrap`}}function ai(e){if(e.tsconfig===void 0)return[{name:`tsconfig.json present`,status:`fail`,fix:"Create a tsconfig.json with `experimentalDecorators: true` and `emitDecoratorMetadata: true`. `kick new` scaffolds one automatically."}];if(e.tsconfig===null)return[{name:`tsconfig.json readable`,status:`warn`,message:`could not parse tsconfig.json (or a config it extends)`,fix:"Check tsconfig.json for a syntax error, and that every path in its `extends` chain resolves. Decorator options could not be verified."}];let t=e.tsconfig.compilerOptions??{},n=[];return n.push(t.experimentalDecorators===!0?{name:`tsconfig: experimentalDecorators`,status:`pass`}:{name:`tsconfig: experimentalDecorators`,status:`fail`,fix:'Add `"experimentalDecorators": true` to compilerOptions in tsconfig.json. Without it, @Service / @Controller / @Get etc. don\'t register any metadata at compile time.'}),n.push(t.emitDecoratorMetadata===!0?{name:`tsconfig: emitDecoratorMetadata`,status:`pass`}:{name:`tsconfig: emitDecoratorMetadata`,status:`fail`,fix:'Add `"emitDecoratorMetadata": true` to compilerOptions in tsconfig.json. The DI container uses this metadata for constructor-parameter injection.'}),n}function oi(e){let t=[`src/env.ts`,`src/env/index.ts`,`src/config/env.ts`,`src/config/index.ts`].map(t=>A(e.cwd,t)).filter(e=>T(e)).filter(e=>/\bloadEnv\s*\(/.test(Ur(e)??``));if(t.length===0)return null;let n=[`src/index.ts`,`src/main.ts`].map(t=>A(e.cwd,t)).find(e=>T(e));if(!n)return{name:`env wiring`,status:`warn`,message:`env-init file exists but no src/index.ts or src/main.ts found`};let r=Ur(n)??``,i=k(n),a=[];for(let e of t){let t=j(i,e).replace(/\\/g,`/`).replace(/\.ts$/,``),n=t.startsWith(`.`)?t:`./`+t,r=n.replace(/\/index$/,``);a.push(n,r);let o=e.replace(/\\/g,`/`).match(/\/src\/(.+?)(?:\.ts)?$/);if(o){let e=`@/`+o[1],t=e.replace(/\/index$/,``);a.push(e,t)}}let o=-1;for(let e of new Set(a)){let t=RegExp(`^import\\s+(?:.*?from\\s+)?['"]${Yr(e)}['"]`,`m`),n=r.match(t);n&&n.index!==void 0&&(o===-1||n.index<o)&&(o=n.index)}let s=r.search(/\bbootstrap\s*\(/),c=t.map(t=>j(e.cwd,t).replace(/\\/g,`/`)).join(`, `);return o===-1?{name:`env wiring`,status:`fail`,message:c,fix:`An env-init file (${c}) calls \`loadEnv(...)\` but \`${j(e.cwd,n).replace(/\\/g,`/`)}\` doesn't import it.\nWithout this, ConfigService.get('X') returns undefined while @Value('X') works via process.env fallback — a half-broken config you won't notice until something is missing.\n\nFix: add a side-effect import at the top of ${j(e.cwd,n).replace(/\\/g,`/`)} (above bootstrap()), pointing at one of the detected files. For example:\n\n import './env'\n // or\n import './config'\n // or, with the @/ alias:\n import '@/config/env'`}:s!==-1&&o>s?{name:`env wiring`,status:`warn`,message:`env-init imported AFTER bootstrap() — should be before`,fix:`Move the env import above the bootstrap() call so the schema runs before any service reads from ConfigService.`}:{name:`env wiring`,status:`pass`}}function si(e,t=ci){let n=0,r=0,i=[e];for(;i.length>0&&r<t;){let e=i.pop(),a;try{a=D(e,{withFileTypes:!0})}catch{continue}for(let o of a){if(r>=t)break;r++;let a=A(e,o.name);if(o.isDirectory()){i.push(a);continue}try{let e=De(a).mtimeMs;e>n&&(n=e)}catch{}}}return n}const ci=2e3;function li(e){let t=A(e.cwd,`.kickjs`,`types`);if(!T(t))return null;let n=si(t);if(n===0)return null;let r=Date.now()-n,i=Math.floor(r/6e4);return i>60?{name:`typegen freshness`,status:`warn`,message:`last updated ${i} minutes ago`,fix:"Re-run `kick typegen` (or `kick dev`, which runs it on every reload) so generated types match the current code."}:{name:`typegen freshness`,status:`pass`,message:i===0?`just now`:`${i}m ago`}}const ui=[`vitest.config.ts`,`vitest.config.js`,`vitest.config.mts`,`vite.config.ts`,`jest.config.ts`,`jest.config.js`],di=[`.env.test`,`.env.test.local`],fi=[`.env`,`.env.local`];function pi(e){let t=e.pkg?.scripts;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){if(!e.startsWith(`test`)||typeof n!=`string`)continue;let t=/KICKJS_ENV_FILE=(\S+)/.exec(n);if(t?.[1])return t[1]}return process.env.KICKJS_ENV_FILE??null}function mi(e){if(!ui.some(t=>T(A(e.cwd,t))))return null;let t=fi.filter(t=>T(A(e.cwd,t)));if(t.length===0)return null;let n=di.filter(t=>T(A(e.cwd,t)));if(n.length>0){let t=pi(e);return t&&t!==`off`&&t!==`none`?{name:`test env isolation`,status:`warn`,message:`${n.join(`, `)} present, but KICKJS_ENV_FILE=${t} overrides it`,fix:`KICKJS_ENV_FILE is checked before test-mode isolation, so ${n[0]} is\nignored and "${t}" is read instead. Drop the override to use the\ntest files, or set KICKJS_ENV_FILE=off if env comes from the runner.`}:{name:`test env isolation`,status:`pass`,message:`${n.join(`, `)} present`}}return{name:`test env isolation`,status:`warn`,message:`${t.join(`, `)} present, no .env.test`,fix:`Under NODE_ENV=test (or vitest's VITEST) KickJS reads .env.test / .env.test.local
|
|
1519
1519
|
INSTEAD of ${t.join(` and `)} — no layering, no fallback. Without one of\nthose files, every var your test config does not pin resolves from your
|
|
1520
1520
|
development env — including DATABASE_URL and any third-party credentials.
|
|
1521
1521
|
|
|
1522
1522
|
Create .env.test holding the whole environment the suite should run against
|
|
1523
1523
|
(a var you leave out is then missing, not inherited), or set KICKJS_ENV_FILE=off
|
|
1524
|
-
and supply env from the test runner.`}}const hi=[()=>Xr(),Zr,Qr,ei,ti,ii,ai,oi,mi,li];async function gi(e,t={}){let n={cwd:e,pkg:Hr(
|
|
1524
|
+
and supply env from the test runner.`}}const hi=[()=>Xr(),Zr,Qr,ei,ti,ii,ai,oi,mi,li];async function gi(e,t={}){let n={cwd:e,pkg:Hr(A(e,`package.json`)),tsconfig:Gr(e),runtime:t.runtime??`express`},r=[...hi,...t.extraChecks??[]],i=[];for(let e of r){let t;try{t=await e(n)}catch(t){i.push({name:e.name||`doctor check`,status:`fail`,message:t instanceof Error?t.message:String(t)});continue}t!=null&&(Array.isArray(t)?i.push(...t):i.push(t))}return i}function _i(e){switch(e){case`pass`:return x.green(`✔`);case`warn`:return x.yellow(`⚠`);case`fail`:return x.red(`✖`)}}function vi(e){let t=_i(e.status),n=e.message?` ${x.dim(`(${e.message})`)}`:``;return`${t} ${e.name}${n}`}function yi(e){return e.split(`
|
|
1525
1525
|
`).map(e=>` ${x.dim(`→`)} ${e}`).join(`
|
|
1526
1526
|
`)}function bi(e){return e?.doctor?.checks??[]}function xi(e){e.command(`doctor`).description(`Pre-flight checks for your KickJS project (dev environment health)`).action(async()=>{let e=process.cwd(),t=bi(await u(e)),n=await o(e);te(`KickJS Doctor`);let r=await gi(e,{extraChecks:t,runtime:n});for(let e of r)y.message(vi(e)),e.fix&&e.status!==`pass`&&y.message(yi(e.fix));let i=r.filter(e=>e.status===`pass`).length,a=r.filter(e=>e.status===`warn`).length,s=r.filter(e=>e.status===`fail`).length,c=[x.green(`${i} passed`),a>0?x.yellow(`${a} warning${a===1?``:`s`}`):`${a} warnings`,s>0?x.red(`${s} error${s===1?``:`s`}`):`${s} errors`].join(`, `);s>0?(C(`${c} — fix the errors above before running the app`),process.exit(1)):C(a>0?`${c} — review the warnings`:x.green(`${c} — your environment looks good`))})}function Si(e){return e.optsWithGlobals().dryRun??!1}function Ci(e){e.command(`codemod`).description(`Codebase migration commands (AST-style rewrites — distinct from db migrate)`).command(`modules`).description(`Rewrite module declarations between class form and the defineModule factory.
|
|
1527
1527
|
Direction defaults to \`modules.style\` from kick.config (or "define").
|
|
@@ -1532,7 +1532,7 @@ and supply env from the test runner.`}}const hi=[()=>Xr(),Zr,Qr,ei,ti,ii,ai,oi,m
|
|
|
1532
1532
|
The regex-based rewrite handles the shapes our templates produce.
|
|
1533
1533
|
Hand-rolled modules with non-standard structures may be skipped.
|
|
1534
1534
|
Always commit before running with --apply.
|
|
1535
|
-
`),process.exit(1));let r=l(await u(process.cwd())),i=
|
|
1535
|
+
`),process.exit(1));let r=l(await u(process.cwd())),i=M(e.modulesDir??r.dir??`src/modules`),a;e.target===`define`||e.target===`class`?a=e.target:e.target===void 0?a=r.style??`define`:(console.error(`\n ${x.red(`Error:`)} --target must be 'define' or 'class' (got '${e.target}').\n`),process.exit(1));let o=x.dim(`→ ${a}`),s=n?x.dim(`(dry-run)`):x.bold(`(applying)`);console.log(`\n ${x.bold(`kick codemod modules`)} ${o} ${s}`),console.log(` modulesDir: ${x.dim(i)}\n`);let c=e.backup!==!1&&!n,d=await nn(i,{dryRun:n,target:a,backup:c});if(d.backupDir){let e=d.backupDir;console.log(` ${x.green(`✓`)} backup: ${x.dim(e)}\n ${x.dim(`(restore: rm -rf <modulesDir> && mv "<backup>" <modulesDir>)`)}\n`)}else!n&&e.backup===!1&&console.log(` ${x.dim(`(--no-backup — skipping snapshot)`)}\n`);let f=0,p=0;for(let e of d.files)if(e.status===`migrated`)f++,console.log(` ${x.green(`✓`)} ${e.path}`);else{p++;let t=x.dim(`(${e.reason??`skipped`})`);console.log(` ${x.dim(`-`)} ${e.path} ${t}`)}if(console.log(),d.indexStatus===`migrated`)console.log(` ${x.green(`✓`)} ${d.indexPath}`);else if(d.indexStatus===`skipped`){let e=x.dim(`(${d.indexReason??`skipped`})`);console.log(` ${x.dim(`-`)} ${d.indexPath} ${e}`)}else console.log(` ${x.dim(`-`)} ${d.indexPath} ${x.dim(`(not found)`)}`);let m=n?x.dim(` (dry-run — pass --apply to write)`):``;console.log(`\n ${x.bold(String(f))} migrated, ${x.bold(String(p))} skipped${m}\n`)})}const wi=()=>({id:`kick/assets`,inputs:[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`],async generate(e){if(!T(O.resolve(e.cwd,`kick.config.ts`)))return null;let t=await u(e.cwd);if(!t?.assetMap)return null;let n=se(t.assetMap,e.cwd);return n.count===0?null:ge(n)}}),Ti="/* 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 Ei(e,t,n,r={}){if(e.length===0)return`${Ti}
|
|
1536
1536
|
// (no routes discovered yet — annotate a controller method with
|
|
1537
1537
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1538
1538
|
declare global {
|
|
@@ -1570,16 +1570,16 @@ ${ee}
|
|
|
1570
1570
|
${g}
|
|
1571
1571
|
`}function Di(e){let t=e.contextKeys;return t==null?`string`:t.length===0?`never`:t.map(e=>JSON.stringify(e)).join(` | `)}function Oi(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 ki(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 Ai(e,t,n,r,i){if(!e||r===!1||e.source===null)return null;let a=Mi(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 ji(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(`
|
|
1572
1572
|
`)+`
|
|
1573
|
-
`}function Mi(e,t,n){if(e===null)return`unknown`;let r=
|
|
1574
|
-
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 '${Li}' resolved from this project.\n ${t}`)}async function Bi(e){let t=
|
|
1575
|
-
`){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)
|
|
1573
|
+
`}function Mi(e,t,n){if(e===null)return`unknown`;let r=k(n);if(e===``){let e=j(r,t).split(Ae).join(`/`);return e=e.replace(/\.(ts|tsx|mts|cts)$/i,``),e.startsWith(`.`)||(e=`./`+e),e}if(!e.startsWith(`.`)&&!e.startsWith(`/`))return e;let i=j(r,M(k(t),e)).split(Ae).join(`/`);return i=i.replace(/\.(ts|tsx|mts|cts)$/i,``),i.startsWith(`.`)||(i=`./`+i),i}function Ni(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 Pi=()=>({id:`kick/routes`,outExtension:`.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){let t=await e.getScanResult({root:Fi(e),cwd:e.cwd,envFile:Ii(e)}),n=e.config?.typegen?.schemaValidator??`zod`,r=O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`);return Ei(t.routes,r,n,{onWarn:t=>e.log.warn(t)})}});function Fi(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function Ii(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}const Li=`@typescript/typescript6`;function Ri(e){return typeof e?.createProgram==`function`}function zi(e){if(Ri(e.typescript))return{api:e.typescript,source:`typescript`};if(Ri(e.ts6))return{api:e.ts6,source:Li};let t=`Install it in the project:\n pnpm add -D ${Li}`;throw e.typescript?Error(`kick typegen: the client route map needs a TypeScript compiler API.
|
|
1574
|
+
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 '${Li}' resolved from this project.\n ${t}`)}async function Bi(e){let t=Ce(A(e,`package.json`)),n=async e=>{try{return await import(N(t.resolve(e)).href)}catch{return null}},[r,i]=await Promise.all([n(`typescript`),n(Li)]);return zi({typescript:Vi(r),ts6:Vi(i)}).api}function Vi(e){let t=e;return t?.default&&typeof t.default==`object`?t.default:e}const Hi=Symbol(`kick/client: expansion budget exhausted`);var Ui=class{ts;checker;program;opts;get printFlags(){return this.ts.TypeFormatFlags.NoTruncation}hoistedByType=new Map;inProgress=new Map;jsonInProgress=new Set;nextName=0;blocks=[];maxDepth;truncations=0;budget;constructor(e,t,n,r={}){this.ts=e,this.checker=t,this.program=n,this.opts=r,this.maxDepth=r.maxDepth??12,this.budget=r.truncationBudget??1e3}hoisted(){return this.blocks}expand(e){this.truncations=0;try{return this.render(e,0)}catch(e){if(e!==Hi)throw e;return this.opts.onWarn?.(`expansion abandoned after ${this.budget} truncations — emitting 'unknown'. This usually means a recursive type. Declare a response schema on the route for an exact type.`),`unknown`}}render(e,t){let n=this.ts.TypeFlags;if(t>this.maxDepth){if(++this.truncations>this.budget)throw Hi;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,void 0,this.printFlags);if(e.isUnion()){let n=e.types.filter(e=>!this.isCallable(e));return(n.length>0?n:e.types).map(e=>this.render(e,t+1)).join(` | `)}if(e.isIntersection())return e.types.map(e=>this.render(e,t+1)).join(` & `);if(this.isTuple(e))return this.renderTuple(e,t);let 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}let i=this.toJsonType(e);if(i){if(this.jsonInProgress.has(e))return this.opts.onWarn?.(`'${this.checker.typeToString(e,void 0,this.printFlags)}' has a cyclic toJSON() — emitting 'unknown', since it has no serializable form.`),`unknown`;this.jsonInProgress.add(e);try{return this.render(i,t)}finally{this.jsonInProgress.delete(e)}}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=this.allocName();this.hoistedByType.set(e,t);let n=this.blocks.length;return this.blocks.push(``),this.blocks[n]=`interface ${t} {\n${this.members(e,0,` `)}\n}`,t}let r=this.inProgress.get(e);if(r)return r.name??=this.allocName();let i={name:null};this.inProgress.set(e,i);let a;try{a=this.members(e,t,``,`; `)}finally{this.inProgress.delete(e)}if(i.name){this.hoistedByType.set(e,i.name);let t=this.blocks.length;return this.blocks.push(``),this.blocks[t]=`interface ${i.name} {\n${this.members(e,0,` `)}\n}`,i.name}return a.length>0?`{ ${a} }`:`{}`}allocName(){return`__T${this.nextName++}`}members(e,t,n,r=`
|
|
1575
|
+
`){let i=[];for(let r of this.checker.getIndexInfosOfType(e)){let e=this.checker.typeToString(r.keyType,void 0,this.printFlags);i.push(`${n}[key: ${e}]: ${this.render(r.type,t+1)}`)}for(let r of this.checker.getPropertiesOfType(e)){let e=this.typeOfProperty(r);if(this.isCallable(e)||r.getName().startsWith(`__@`))continue;let a=(r.flags&this.ts.SymbolFlags.Optional)!==0,o=this.renderPropertyType(e,a,r,t+1),s=this.isReadonlyProp(r)?`readonly `:``;i.push(`${n}${s}${this.propName(r.getName())}${a?`?`:``}: ${o}`)}return i.join(r===`
|
|
1576
1576
|
`?`
|
|
1577
|
-
`: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}};const
|
|
1578
|
-
`));for(let n of
|
|
1579
|
-
`);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
|
|
1577
|
+
`:r)}typeOfProperty(e){let t=this.checker;if(typeof t.getTypeOfSymbol==`function`)return t.getTypeOfSymbol(e);let n=e.valueDeclaration??e.declarations?.[0];return n?this.checker.getTypeOfSymbolAtLocation(e,n):this.checker.getDeclaredTypeOfSymbol(e)}renderPropertyType(e,t,n,r){if(!t||!e.isUnion()||this.declaresUndefined(n))return this.render(e,r);let i=e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined));return i.length===0?`undefined`:i.map(e=>this.render(e,r)).join(` | `)}isReadonlyProp(e){let t=e.valueDeclaration??e.declarations?.[0];return t?(this.ts.getCombinedModifierFlags(t)&this.ts.ModifierFlags.Readonly)!==0:!1}declaresUndefined(e){let t=e.valueDeclaration??e.declarations?.[0];if(!t||!(this.ts.isPropertySignature(t)||this.ts.isPropertyDeclaration(t))||!t.type)return!1;let n=this.checker.getTypeFromTypeNode(t.type);return(n.isUnion()?n.types:[n]).some(e=>(e.flags&this.ts.TypeFlags.Undefined)!==0)}renderTuple(e,t){let n=this.ts.ElementFlags,r=this.checker.getTypeArguments(e),i=e.target,a=i.elementFlags??[],o=r.map((e,r)=>{let i=a[r]??n.Required;return i&n.Optional?`${(e.isUnion()?e.types.filter(e=>!(e.flags&this.ts.TypeFlags.Undefined)):[e]).map(e=>this.render(e,t+1)).join(` | `)}?`:i&n.Rest?`...${this.render(e,t+1)}[]`:i&n.Variadic?`...${this.render(e,t+1)}`:this.render(e,t+1)});return`${i.readonly?`readonly `:``}[${o.join(`, `)}]`}propName(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}isLibType(e){let t=e.aliasSymbol?.declarations??e.getSymbol()?.declarations;return!t||t.length===0?!1:t.every(e=>this.program.isSourceFileDefaultLibrary(e.getSourceFile()))}renderLibType(e,t){let n=(e.aliasSymbol??e.getSymbol())?.getName(),r=e.aliasTypeArguments??this.typeArguments(e);return!n||r.length===0?this.checker.typeToString(e,void 0,this.printFlags):`${n}<${r.map(e=>this.render(e,t+1)).join(`, `)}>`}typeArguments(e){return!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&this.ts.ObjectFlags.Reference)?[]:this.checker.getTypeArguments(e)}toJsonType(e){if(!(e.flags&this.ts.TypeFlags.Object))return null;let t=this.checker.getPropertyOfType(e,`toJSON`);if(!t)return null;let[n]=this.checker.getSignaturesOfType(this.typeOfProperty(t),this.ts.SignatureKind.Call);if(!n)return null;let r=this.checker.getReturnTypeOfSignature(n);return r===e?null:r}isCallable(e){if(e.isUnion()){let t=e.types.filter(e=>!(e.flags&(this.ts.TypeFlags.Undefined|this.ts.TypeFlags.Null)));return t.length>0&&t.every(e=>this.isCallable(e))}return this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Call).length>0||this.checker.getSignaturesOfType(e,this.ts.SignatureKind.Construct).length>0}isNamed(e){let t=e.getSymbol();if(!t)return!1;let n=t.getName();return n!==`__type`&&n!==`__object`&&n.length>0}isTuple(e){let t=this.ts.ObjectFlags;if(!(e.flags&this.ts.TypeFlags.Object)||!(e.objectFlags&t.Reference))return!1;let n=e.target;return!!(n&&n.objectFlags&t.Tuple)}arrayElement(e){let t=e.getSymbol()?.getName();if(t!==`Array`&&t!==`ReadonlyArray`)return null;let n=this.checker.getTypeArguments(e);return n.length===1?{element:n[0],readonly:t===`ReadonlyArray`}:null}};const Wi=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],Gi=/(?:^|[\\/])(?:node_modules|\.kickjs)(?:[\\/]|$)/;function Ki(e){return We(`sha1`).update(e).digest(`hex`)}function qi(e){let t=We(`sha1`);t.update(e.cliVersion),t.update(JSON.stringify(e.options??{})),t.update(e.keys.join(`
|
|
1578
|
+
`));for(let n of Wi){let r=A(e.projectDir,n);if(T(r))try{t.update(E(r))}catch(e){throw Error(`kick/client: cannot read lockfile ${r}`,{cause:e})}}for(let n of e.fileNames.toSorted())if(!Gi.test(n)){t.update(n);try{t.update(E(n))}catch(e){throw Error(`kick/client: cannot read project file ${n}`,{cause:e})}}return t.digest(`hex`)}async function Ji(e){try{let t=await Bi(e.compilerFrom??e.projectDir),n={...t.sys,onUnRecoverableConfigFileDiagnostic:()=>{}},r=t.getParsedCommandLineOfConfigFile(A(e.projectDir,`tsconfig.json`),{},n);return r?qi({projectDir:e.projectDir,fileNames:r.fileNames,keys:e.keys,options:{...r.options,__kickMaxDepth:e.maxDepth??null},cliVersion:e.cliVersion}):null}catch{return null}}async function Yi(e){let t=await Bi(e.compilerFrom??e.projectDir),n=A(k(e.routesFile),`__kick_client_probe__.ts`),r=Qi(e.routesFile,e.keys),i=ta(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.`);Xi(t,i,e.routesFile);let s=$i(t,i,o,e.keys),c=null,l=new Ui(t,a,i,{maxDepth:e.maxDepth,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===Zi(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 Xi(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(`
|
|
1579
|
+
`);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 Zi(e){return`_K${e}`}function Qi(e,t){let n=`./`+ke(e).replace(/\.tsx?$/,``),r=t.map((e,t)=>`type ${Zi(t)} = KickRoutes.Api[${JSON.stringify(e)}]`);return[`import ${JSON.stringify(n)}`,...r].join(`
|
|
1580
1580
|
`)+`
|
|
1581
|
-
`}function
|
|
1582
|
-
`))}},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:[
|
|
1581
|
+
`}function $i(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(Zi(t));r&&e.start>=r.getStart(n)&&e.start<r.getEnd()&&i.add(o)}return i}function ea(e,t){let n=e.filter(e=>/\.d\.(ts|mts|cts)$/.test(e)),r=[];try{r=D(t).filter(e=>e.endsWith(`.ts`)).map(e=>A(t,e))}catch{}return[...new Set([...n,...r])]}function ta(e,t,n,r){let i=A(t,`tsconfig.json`),a={...e.sys,onUnRecoverableConfigFileDiagnostic:t=>{throw Error(e.flattenDiagnosticMessageText(t.messageText,`
|
|
1582
|
+
`))}},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:[...ea(o.fileNames,k(n)),n],options:o.options,host:s})}const na=`/* eslint-disable */
|
|
1583
1583
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1584
1584
|
//
|
|
1585
1585
|
// Self-contained: this file has no imports, so a frontend consumes it without
|
|
@@ -1593,7 +1593,7 @@ ${g}
|
|
|
1593
1593
|
//
|
|
1594
1594
|
// Not refreshed by \`kick dev\` — resolving these types builds a full
|
|
1595
1595
|
// TypeScript program over the server. Re-run \`kick typegen\`.
|
|
1596
|
-
`;function
|
|
1596
|
+
`;function ra(e,t){let n=t.filter(t=>e.entries.has(t));if(n.length===0)return`${na}
|
|
1597
1597
|
// (no routes discovered yet — annotate a controller method with
|
|
1598
1598
|
// @Get/@Post/@Put/@Delete/@Patch and re-run \`kick typegen\`)
|
|
1599
1599
|
interface Api {}
|
|
@@ -1610,7 +1610,7 @@ export type { Api }
|
|
|
1610
1610
|
|
|
1611
1611
|
`)+`
|
|
1612
1612
|
|
|
1613
|
-
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${
|
|
1613
|
+
`:``,i=n.map(t=>` ${JSON.stringify(t)}: ${e.entries.get(t)}`);return`${na}
|
|
1614
1614
|
${r}interface Api {
|
|
1615
1615
|
${i.join(`
|
|
1616
1616
|
`)}
|
|
@@ -1624,7 +1624,7 @@ declare global {
|
|
|
1624
1624
|
}
|
|
1625
1625
|
|
|
1626
1626
|
export type { Api }
|
|
1627
|
-
`}const
|
|
1627
|
+
`}const ia=`kick/client`,Q=`.kickjs/types/kick__client.d.ts`,aa=`.kickjs/cache/client-map.sha1`,oa=(()=>{try{return Ce(import.meta.url)(`../../../package.json`).version??`0.0.0`}catch{return`0.0.0`}})();function sa(e){try{if(!T(e))return null;let[t,n]=E(e,`utf-8`).trim().split(/\s+/);return t&&n?{inputs:t,output:n}:null}catch{return null}}function ca(e){return`${Cn}${ia} */\n\n${e}\n`}function la(e){try{return T(e)?E(e,`utf-8`):null}catch{return null}}async function ua(e){let t=O.resolve(e.cwd,Q);if(!T(t))return!1;try{await Re(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 da(e){let t=e?.typegen?.client;return typeof t==`object`?t.maxDepth:void 0}function fa(e){let t=e.config?.typegen?.client;return typeof t==`boolean`?t:t&&typeof t==`object`?t.enabled!==!1:(T(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 pa=()=>({id:ia,outExtension:`.d.ts`,inputs:[`src/**/*.controller.ts`,`src/**/*.module.ts`],async generate(e){if(!fa(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))}let i=da(e.config),a=await Ji({projectDir:e.cwd,keys:n,maxDepth:i,cliVersion:oa}),o=sa(O.resolve(e.cwd,aa)),s=la(O.resolve(e.cwd,Q));if(a&&o&&s!==null&&o.inputs===a&&o.output===Ki(s))return fn()&&e.log.info?.(` kick/client: unchanged, keeping ${Q}`),null;try{let t=ra(await Yi({projectDir:e.cwd,routesFile:O.resolve(e.cwd,`.kickjs/types/kick__routes.ts`),keys:n,maxDepth:i,onWarn:t=>e.log.warn(t)}),n);return a&&!e.check&&await e.writeFile(aa,`${a} ${Ki(ca(t))}`),t}catch(t){let n=T(O.resolve(e.cwd,Q)),r=` kick/client: skipped — ${t instanceof Error?t.message:String(t)}`;return n?e.log.warn(r):fn()&&e.log.info?.(r),n&&await ua(e),null}}});function ma(e,t,n=`zod`){if(!e)return null;let r=j(k(t),e.filePath).split(Ae).join(`/`);return r=r.replace(/\.(ts|tsx|mts|cts)$/i,``),r.startsWith(`.`)||(r=`./`+r),`/* eslint-disable */
|
|
1628
1628
|
// AUTO-GENERATED by \`kick typegen\`. DO NOT EDIT.
|
|
1629
1629
|
// Re-run with \`kick typegen\` or rely on \`kick dev\` to refresh.
|
|
1630
1630
|
|
|
@@ -1662,5 +1662,5 @@ declare global {
|
|
|
1662
1662
|
}
|
|
1663
1663
|
|
|
1664
1664
|
export {}
|
|
1665
|
-
`}const
|
|
1666
|
-
`)}});var
|
|
1665
|
+
`}const ha=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=_a(e);if(t===!1)return null;let n=await e.getScanResult({root:ga(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 ma(n.env,i,r)}});function ga(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function _a(e){return e.config?.typegen?.envFile}function va(e){return O.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function ya(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function $(e){return{root:va(e),cwd:e.cwd,envFile:ya(e)}}const ba=()=>({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 _e(t.classes,n,r)}}),xa=()=>({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 he(`ServiceToken`,me(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),Sa=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return he(`ModuleToken`,ce((await e.getScanResult($(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),Ca=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return ue((await e.getScanResult($(e))).pluginsAndAdapters)}}),wa=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return xe((await e.getScanResult($(e))).augmentations)}}),Ta=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult($(e));return t.contextKeys.length===0?null:le(t.contextKeys)}}),Ea={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},Da=()=>({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}=Ea[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(`
|
|
1666
|
+
`)}});var Oa=e({builtinCliPlugins:()=>ka});const ka=[h({name:`kick/init`,register:Ke}),h({name:`kick/generate`,register:xn}),h({name:`kick/run`,register:Ln}),h({name:`kick/info`,register:Hn}),h({name:`kick/inspect`,register:Xn}),h({name:`kick/add`,register:t}),h({name:`kick/list`,register:i}),h({name:`kick/explain`,register:or}),h({name:`kick/mcp`,register:gr}),h({name:`kick/tinker`,register:br}),h({name:`kick/remove`,register:Er}),h({name:`kick/typegen`,register:kr}),h({name:`kick/check`,register:Vr}),h({name:`kick/doctor`,register:xi}),h({name:`kick/codemod`,register:Ci}),h({name:`kick/registry`,typegens:[ba()]}),h({name:`kick/services`,typegens:[xa()]}),h({name:`kick/modules`,typegens:[Sa()]}),h({name:`kick/plugins`,typegens:[Ca()]}),h({name:`kick/augmentations`,typegens:[wa()]}),h({name:`kick/context`,typegens:[Ta()]}),h({name:`kick/assets`,typegens:[wi()]}),h({name:`kick/routes`,typegens:[Pi()]}),h({name:`kick/client`,typegens:[pa()]}),h({name:`kick/env`,typegens:[ha()]}),h({name:`kick/runtime`,typegens:[Da()]})];export{Dn as n,ka as t};
|