@forinda/kickjs-cli 6.5.0 → 6.6.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-Du-kAfnd.mjs +12 -0
- package/dist/agent-docs-Du-kAfnd.mjs.map +1 -0
- package/dist/{build-RlkRhDyM.mjs → build-DGTo6Lbp.mjs} +3 -3
- package/dist/{build-RlkRhDyM.mjs.map → build-DGTo6Lbp.mjs.map} +1 -1
- package/dist/{builtins-Ce5uoK6s.mjs → builtins-C5YZMX7U.mjs} +2 -2
- package/dist/cli.mjs +52 -20
- package/dist/{config-xEbwXlmo.mjs → config-COL9zMB5.mjs} +3 -3
- package/dist/{config-xEbwXlmo.mjs.map → config-COL9zMB5.mjs.map} +1 -1
- package/dist/{doctor-DCFgdlJ3.mjs → doctor-BCMp4UCQ.mjs} +4 -4
- package/dist/{doctor-DCFgdlJ3.mjs.map → doctor-BCMp4UCQ.mjs.map} +1 -1
- package/dist/{fullstack-iuAdYQmC.mjs → fullstack-C8u97QC-.mjs} +5 -5
- package/dist/{fullstack-pPl60src.mjs → fullstack-Cqm_v3sf.mjs} +6 -6
- package/dist/fullstack-Cqm_v3sf.mjs.map +1 -0
- package/dist/index.d.mts +7 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-B_40AQRr.mjs → plugin-BHLfFlki.mjs} +3 -3
- package/dist/{plugin-B_40AQRr.mjs.map → plugin-BHLfFlki.mjs.map} +1 -1
- package/dist/{project-D_8okjEO.mjs → project-YM9dH4O_.mjs} +5 -5
- package/dist/{project-D_8okjEO.mjs.map → project-YM9dH4O_.mjs.map} +1 -1
- package/dist/{project-docs-MYPeTYsJ.mjs → project-docs-VwSwcfVt.mjs} +31 -5
- package/dist/project-docs-VwSwcfVt.mjs.map +1 -0
- package/dist/{project-root-CWcfpTV4.mjs → project-root-DRTGL9O5.mjs} +3 -3
- package/dist/{project-root-CWcfpTV4.mjs.map → project-root-DRTGL9O5.mjs.map} +1 -1
- package/dist/{prompts-D0mIvDKz.mjs → prompts-BJywkbEr.mjs} +2 -2
- package/dist/{prompts-D0mIvDKz.mjs.map → prompts-BJywkbEr.mjs.map} +1 -1
- package/dist/{rolldown-runtime-wP2RwkAN.mjs → rolldown-runtime-BKn_X0JJ.mjs} +1 -1
- package/dist/{run-plugins-USrmMITe.mjs → run-plugins-C1wpiuKz.mjs} +11 -5
- package/dist/{run-plugins-USrmMITe.mjs.map → run-plugins-C1wpiuKz.mjs.map} +1 -1
- package/dist/{typegen-Do1rVRd1.mjs → typegen-Dh-JBQSr.mjs} +17 -17
- package/dist/typegen-Dh-JBQSr.mjs.map +1 -0
- package/dist/{types-CjDOGs_1.mjs → types-B2DQMqCA.mjs} +1 -1
- package/package.json +2 -2
- package/dist/agent-docs-Xlt6Fk-e.mjs +0 -12
- package/dist/agent-docs-Xlt6Fk-e.mjs.map +0 -1
- package/dist/fullstack-pPl60src.mjs.map +0 -1
- package/dist/project-docs-MYPeTYsJ.mjs.map +0 -1
- package/dist/typegen-Do1rVRd1.mjs.map +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v6.
|
|
2
|
+
* @forinda/kickjs-cli v6.6.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createRequire as e}from"node:module";import{Command as t}from"commander";import{cpSync as n,existsSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,rmSync as s,statSync as c,writeFileSync as l}from"node:fs";import u,{basename as d,dirname as f,extname as p,isAbsolute as m,join as h,parse as g,relative as _,resolve as v,sep as y}from"node:path";import{fileURLToPath as b,pathToFileURL as x}from"node:url";import{execFileSync as
|
|
12
|
-
`,`utf-8`)}catch{}}function Pe(e,t){let n=[];if(!e?.assetMap)return n;let i=v(t);for(let[a,o]of Object.entries(e.assetMap)){if(!a||a.includes(`/`)){n.push(`assetMap key '${a}' is invalid — must be a non-empty string without '/'`);continue}if(typeof o?.src!=`string`||o.src.length===0){n.push(`assetMap.${a} is missing a non-empty 'src' field`);continue}r(v(t,o.src))||n.push(`assetMap.${a}.src ('${o.src}') does not exist — typegen + build will fail`),o.dest&&Fe(v(t,o.dest),i)&&n.push(`assetMap.${a}.dest ('${o.dest}') resolves outside the project root — refusing to copy`)}return n}function Fe(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function Ie(e,t=[]){let n=new Map;for(let t of e){let e=(n.get(t.name)??0)+1;if(n.set(t.name,e),e===2)throw new ue(`plugin`,t.name,[t.name,t.name])}let r=new Map,i=[];for(let t of e)for(let e of t.commands??[]){let n=r.get(e.name);if(n)throw new ue(`command`,e.name,[n,t.name]);r.set(e.name,t.name),i.push(e)}let a=new Set(t.map(e=>e.name)),o=[...i.filter(e=>!a.has(e.name)),...t],s=new Map,c=[];for(let t of e)for(let e of t.typegens??[]){let n=s.get(e.id);if(n)throw new ue(`typegen`,e.id,[n,t.name]);s.set(e.id,t.name),c.push(e)}let l=new Map,u=[];for(let t of e)for(let e of t.generators??[]){let n=l.get(e.name);if(n)throw new ue(`generator`,e.name,[n,t.name]);l.set(e.name,t.name),u.push({source:t.name,spec:e})}return{commands:o,typegens:c,generators:u,register:async(t,n)=>{let r;if(n)r={generators:u,...n};else{let{findProjectRoot:e}=await Promise.resolve().then(()=>tn),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:u}}for(let n of e)n.register&&await n.register(t,r)}}}var Le=k({mergeCliPlugins:()=>Ie});let Re=!1;function M(e){Re=e}const ze=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function N(e,t){Re||(await
|
|
11
|
+
import{createRequire as e}from"node:module";import{Command as t}from"commander";import{cpSync as n,existsSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,rmSync as s,statSync as c,writeFileSync as l}from"node:fs";import u,{basename as d,dirname as f,extname as p,isAbsolute as m,join as h,parse as g,relative as _,resolve as v,sep as y}from"node:path";import{fileURLToPath as b,pathToFileURL as x}from"node:url";import{execFileSync as S,execSync as C,fork as ee,spawn as te,spawnSync as ne}from"node:child_process";import{access as re,copyFile as ie,mkdir as ae,readFile as w,readdir as oe,rm as se,stat as ce,unlink as le,writeFile as T}from"node:fs/promises";import{KickPluginConflictError as ue,defineCliPlugin as E}from"@forinda/kickjs-cli-kit";import*as D from"@clack/prompts";import O from"picocolors";import de from"pluralize";import{parseSync as fe}from"oxc-parser";import{glob as pe,globSync as me}from"glob";import{groupAssetKeys as he}from"@forinda/kickjs";import{arch as ge,platform as _e,release as ve}from"node:os";var ye=Object.defineProperty,k=(e,t)=>{let n={};for(var r in e)ye(n,r,{get:e[r],enumerable:!0});return t||ye(n,Symbol.toStringTag,{value:`Module`}),n};function be(e,t,n){C(e,{cwd:t,stdio:`inherit`,env:n?{...process.env,...n}:process.env})}function xe(e,t,n){let r=ne(process.execPath,[e],{cwd:n,stdio:`inherit`,env:{...process.env,...t}});r.status!==0&&process.exit(r.status??1)}function Se(e,t){if(!t?.commands?.length)return;let n=new Set(e.commands.map(e=>e.name()));for(let r of t.commands){if(n.has(r.name)){console.warn(` Warning: custom command '${r.name}' skipped — conflicts with a built-in command`);continue}Ce(e,r)}}function Ce(e,t){let n=e.command(t.name).description(t.description);if(t.aliases)for(let e of t.aliases)n.alias(e);n.allowUnknownOption(!0),n.argument(`[args...]`,`Additional arguments passed to the command`),n.action(e=>{let n=e.join(` `),r=Array.isArray(t.steps)?t.steps:[t.steps];for(let e of r){let r=n?`${e} ${n}`:e;console.log(` $ ${r}`);try{be(r)}catch{console.error(` Command failed: ${t.name}`),process.exitCode=1;return}}})}var we=k({BUILTIN_REPO_TYPES:()=>Ee,DEPRECATED_REPO_TYPES:()=>De,PACKAGE_MANAGERS:()=>Te,defineConfig:()=>ke,loadKickConfig:()=>j,resolveModuleConfig:()=>A,resolveTokenScope:()=>Ae,validateAssetMap:()=>Pe,warnIfDeprecatedRepo:()=>Oe,writeAssetConfigSnapshot:()=>Ne});const Te=[`pnpm`,`npm`,`yarn`,`bun`],Ee=[`inmemory`],De=[`prisma`,`drizzle`];function Oe(e){return De.includes(e)?(console.warn(` Note: the '${e}' repository preset is deprecated. Generating a generic custom repository named '${e}' instead — wire it to your DB by hand. Pass any name via \`--repo <name>\` or \`modules.repo: { name: '<name>' }\`.`),!0):!1}function ke(e){return e}function Ae(e,t){if(e?.tokenScope&&typeof e.tokenScope==`string`&&e.tokenScope.length>0){let t=je(e.tokenScope);if(t.length>0)return t}try{let e=h(t,`package.json`);if(r(e)){let t=JSON.parse(a(e,`utf-8`));if(typeof t.name==`string`&&t.name.length>0){let e=t.name.match(/^@([^/]+)\//),n=je(e?e[1]:t.name);if(n.length>0)return n}}}catch{}return`app`}function je(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/^-+|-+$/g,``).replace(/-{2,}/g,`-`)}function A(e){if(!e)return{};let t={dir:e.modules?.dir,repo:e.modules?.repo,schemaDir:e.modules?.schemaDir,pluralize:e.modules?.pluralize,prismaClientPath:e.modules?.prismaClientPath,style:e.modules?.style};return t.style!==void 0&&t.style!==`define`&&t.style!==`class`&&(console.warn(` Warning: modules.style '${t.style}' is not a valid value (expected 'define' or 'class'). Falling back to 'define'.`),t.style=`define`),t.repo&&typeof t.repo==`string`&&!Ee.includes(t.repo)&&(Oe(t.repo)||console.warn(` Warning: modules.repo '${t.repo}' is not a built-in type (${Ee.join(`, `)}). It will generate a stub repository. Use { name: '${t.repo}' } to silence this warning.`)),t}const Me=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];async function j(e){let{findProjectRoot:t}=await Promise.resolve().then(()=>tn),n=t(e);for(let e of Me){let t=h(n,e);try{await re(t)}catch{continue}if(e.endsWith(`.json`)){let e=await w(t,`utf-8`);return JSON.parse(e)}if(e.endsWith(`.ts`)){let r;try{r=await import(`jiti`)}catch(t){let n=t instanceof Error?t.message:String(t);n.includes(`Cannot find package 'jiti'`)||n.includes(`ERR_MODULE_NOT_FOUND`)?console.warn(`Warning: Failed to load ${e} — 'jiti' is required for TypeScript configs. Run \`pnpm add -D jiti\` (or your package manager's equivalent), or rename the file to kick.config.js / kick.config.mjs / kick.config.json.`):console.warn(`Warning: Failed to initialize jiti for ${e}: ${n}`);continue}try{let e=await r.createJiti(n,{interopDefault:!0,fsCache:!1}).import(t,{default:!0}),i=Pe(e,n);for(let e of i)console.warn(` Warning: ${e}`);return Ne(n,e),e}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}try{let{pathToFileURL:e}=await import(`node:url`),r=await import(e(t).href),i=r.default??r,a=Pe(i,n);for(let e of a)console.warn(` Warning: ${e}`);return Ne(n,i),i}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Warning: Failed to load ${e}: ${n}`);continue}}return null}function Ne(e,t){if(!(!t?.assetMap||Object.keys(t.assetMap).length===0))try{let n=h(e,`.kickjs`);i(n,{recursive:!0});let r={version:1,assetMap:t.assetMap,...t.build?.outDir?{build:{outDir:t.build.outDir}}:{}};l(h(n,`kick.config.json`),JSON.stringify(r,null,2)+`
|
|
12
|
+
`,`utf-8`)}catch{}}function Pe(e,t){let n=[];if(!e?.assetMap)return n;let i=v(t);for(let[a,o]of Object.entries(e.assetMap)){if(!a||a.includes(`/`)){n.push(`assetMap key '${a}' is invalid — must be a non-empty string without '/'`);continue}if(typeof o?.src!=`string`||o.src.length===0){n.push(`assetMap.${a} is missing a non-empty 'src' field`);continue}r(v(t,o.src))||n.push(`assetMap.${a}.src ('${o.src}') does not exist — typegen + build will fail`),o.dest&&Fe(v(t,o.dest),i)&&n.push(`assetMap.${a}.dest ('${o.dest}') resolves outside the project root — refusing to copy`)}return n}function Fe(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function Ie(e,t=[]){let n=new Map;for(let t of e){let e=(n.get(t.name)??0)+1;if(n.set(t.name,e),e===2)throw new ue(`plugin`,t.name,[t.name,t.name])}let r=new Map,i=[];for(let t of e)for(let e of t.commands??[]){let n=r.get(e.name);if(n)throw new ue(`command`,e.name,[n,t.name]);r.set(e.name,t.name),i.push(e)}let a=new Set(t.map(e=>e.name)),o=[...i.filter(e=>!a.has(e.name)),...t],s=new Map,c=[];for(let t of e)for(let e of t.typegens??[]){let n=s.get(e.id);if(n)throw new ue(`typegen`,e.id,[n,t.name]);s.set(e.id,t.name),c.push(e)}let l=new Map,u=[];for(let t of e)for(let e of t.generators??[]){let n=l.get(e.name);if(n)throw new ue(`generator`,e.name,[n,t.name]);l.set(e.name,t.name),u.push({source:t.name,spec:e})}return{commands:o,typegens:c,generators:u,register:async(t,n)=>{let r;if(n)r={generators:u,...n};else{let{findProjectRoot:e}=await Promise.resolve().then(()=>tn),t=process.cwd();r={cwd:t,projectRoot:e(t),config:null,log:()=>{},generators:u}}for(let n of e)n.register&&await n.register(t,r)}}}var Le=k({mergeCliPlugins:()=>Ie});let Re=!1;function M(e){Re=e}const ze=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function N(e,t){Re||(await ae(f(e),{recursive:!0}),await T(e,t,`utf-8`),ze.has(p(e))&&await He(e,t).catch(()=>{}))}let Be;async function Ve(t){if(Be!==void 0)return Be;try{Be=await import(e(h(t,`package.json`)).resolve(`oxfmt`))}catch{Be=null}return Be}async function He(e,t){let n=await Ve(process.cwd());if(!n)return;let r=await We(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await T(e,i.code,`utf-8`)}const Ue=new Map;async function We(e){let t=f(e),n=t;if(Ue.has(n))return Ue.get(n);for(;;){let e=h(t,`.oxfmtrc.json`);if(r(e))try{let t=await w(e,`utf-8`),r=JSON.parse(t);return delete r.$schema,delete r.ignorePatterns,Ue.set(n,r),r}catch{return Ue.set(n,null),null}let i=f(t);if(i===t)return Ue.set(n,null),null;t=i}}async function Ge(e){try{return await re(e),!0}catch{return!1}}const Ke={swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`},qe={zod:{name:`zod`,range:`^4.3.6`},valibot:{name:`valibot`,range:`^1.4.1`},yup:{name:`yup`,range:`^1.7.1`}};function Je(e,t){let n=e[t];if(!n)throw Error(`generatePackageJson: missing resolved version for ${t}. Add it to SIBLING_PACKAGES in generators/project.ts.`);return n}function Ye(e,t,n,r=[],i=`zod`,a=`express`){let o=qe[i],s={"@forinda/kickjs":Je(n,`@forinda/kickjs`),"@forinda/kickjs-schema":Je(n,`@forinda/kickjs-schema`),dotenv:`^17.3.1`,"reflect-metadata":`^0.2.2`,[o.name]:o.range};a===`express`?s.express=`^5.1.0`:a===`fastify`?(s.fastify=`^5.0.0`,s[`@fastify/middie`]=`^9.0.0`,s[`serve-static`]=`^2.2.0`):a===`h3`&&(s.h3=`^1.0.0`,s[`serve-static`]=`^2.2.0`);for(let e of r){let t=Ke[e];t&&!s[t]&&(s[t]=Je(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`kick dev`,"dev:debug":`kick dev:debug`,build:`kick build`,start:`kick start`,test:`vitest run`,"test:watch":`vitest`,typecheck:`tsc --noEmit`,typegen:`kick typegen`,lint:`eslint src/`,format:`prettier --write src/`},dependencies:s,devDependencies:{"@forinda/kickjs-cli":Je(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":Je(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,...a===`express`?{"@types/express":`^5.0.6`}:{},"@types/node":`^25.0.0`,"unplugin-swc":`^1.5.9`,vite:`^8.0.3`,vitest:`^4.1.2`,typescript:`^6.0.3`,prettier:`^3.8.1`}},null,2)}function Xe(){return`import { defineConfig } from 'vite'
|
|
13
13
|
import { resolve } from 'node:path'
|
|
14
14
|
import swc from 'unplugin-swc'
|
|
15
15
|
import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
|
|
@@ -378,7 +378,7 @@ export default defineConfig({
|
|
|
378
378
|
},
|
|
379
379
|
],
|
|
380
380
|
})
|
|
381
|
-
`}function pt(e,t,n){let r={rest:`REST API`,
|
|
381
|
+
`}function pt(e,t,n){let r={rest:`REST API`,minimal:`Minimal`,fullstack:`Fullstack (KickJS API + typed web app)`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`),`# ${e}
|
|
382
382
|
|
|
383
383
|
A **${r[t]??`REST API`}** built with [KickJS](https://kickjs.app/) — a decorator-driven Node.js framework for TypeScript that runs on Express, Fastify, or h3 (swap the engine in one line).
|
|
384
384
|
|
|
@@ -526,7 +526,24 @@ add tool-specific affordances on top.
|
|
|
526
526
|
## Before You Start
|
|
527
527
|
|
|
528
528
|
1. Run \`${n} install\` to install dependencies
|
|
529
|
-
2. Run \`kick dev\` to verify the app starts
|
|
529
|
+
2. Run \`kick dev\` to verify the app starts${t===`fullstack`?`
|
|
530
|
+
|
|
531
|
+
## Fullstack workspace layout
|
|
532
|
+
|
|
533
|
+
This is a WORKSPACE root — the KickJS API lives in \`server/\`, the typed web
|
|
534
|
+
app in \`web/\`. Run both with \`${n===`pnpm`?`pnpm dev`:`${n} run dev:server + ${n} run dev:web`}\`.
|
|
535
|
+
|
|
536
|
+
The type loop (do not break it):
|
|
537
|
+
1. \`server/\` handlers RETURN their payloads → \`kick typegen\` (auto under
|
|
538
|
+
\`kick dev\`) emits \`server/.kickjs/types/kick__routes.ts\` incl. the flat
|
|
539
|
+
\`KickRoutes.Api\` map with inferred response types.
|
|
540
|
+
2. \`web/src/types/kick-routes.d.ts\` imports that file TYPE-ONLY.
|
|
541
|
+
3. \`web/src/api.ts\` = \`createClient<KickApi>({ baseUrl: '/api/v1' })\`
|
|
542
|
+
— every call site is typed from the server's handlers.
|
|
543
|
+
|
|
544
|
+
Rules: kick commands (\`kick g\`, \`kick typegen\`, \`kick dev\`) run in
|
|
545
|
+
\`server/\`; never import server runtime code into \`web/\` (the d.ts bridge is
|
|
546
|
+
type-only); prefer return-value handlers so responses stay inferable.`:``}
|
|
530
547
|
3. Read the [KickJS documentation](https://kickjs.app/) for framework details
|
|
531
548
|
|
|
532
549
|
## HTTP runtime — DON'T assume Express-only
|
|
@@ -541,6 +558,15 @@ any engine-specific code, **check which engine this project uses**:
|
|
|
541
558
|
|
|
542
559
|
Rules that keep generated code correct on **every** engine:
|
|
543
560
|
|
|
561
|
+
- **Prefer return-value handlers.** \`return payload\` sends 200 json on every
|
|
562
|
+
engine and lets \`kick typegen\` infer the response type into
|
|
563
|
+
\`KickRoutes.Api\` (consumed by the \`@forinda/kickjs-client\` typed client);
|
|
564
|
+
\`reply(status, body)\` for non-200, \`reply.noContent()\` for 204. A declared
|
|
565
|
+
\`{ response: schema }\` on the route feeds BOTH the OpenAPI success response
|
|
566
|
+
and the typegen response type. \`ctx.json(...)\` stays fully supported but
|
|
567
|
+
infers \`unknown\`.
|
|
568
|
+
- **Lifecycle hooks:** \`@PostConstruct()\` after instantiation; \`@PreDestroy()\`
|
|
569
|
+
when a REQUEST-scoped service's request closes (release transactions/handles).
|
|
544
570
|
- **Write to \`ctx\`, not the raw request/response.** \`ctx.json()\`, \`ctx.body\`,
|
|
545
571
|
\`ctx.params\`, \`ctx.query\`, \`ctx.set/get\`, \`ctx.sse()\` are engine-neutral and
|
|
546
572
|
work identically everywhere. \`ctx.req\` / \`ctx.res\` are the engine-native
|
|
@@ -1078,7 +1104,7 @@ routes() {
|
|
|
1078
1104
|
- \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
|
|
1079
1105
|
- \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
|
|
1080
1106
|
- \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
|
|
1081
|
-
- Module not registered in \`src/modules/index.ts\`.`},{slug:`add-adapter`,frontmatterName:`kickjs-add-adapter`,description:`Use when wiring a single-concern lifecycle integration (Swagger, DevTools, Sentry, Redis client).`,body:"**Steps**:\n1. `kick g adapter <name>` to scaffold the boilerplate, OR install via `kick add <package>` for first-party adapters.\n2. The generated file uses `defineAdapter()` — never `class implements AppAdapter`.\n3. Add the adapter instance (note the parens) to `src/adapters/index.ts` — don't inline in `src/index.ts`.\n4. Pick the right hook and middleware phase deliberately.\n5. Verify with `kick dev` that the adapter's lifecycle logs fire.\n\n**Canonical shape** — factory closure owns instance state:\n\n```ts\nexport const RedisAdapter = defineAdapter<RedisConfig>({\n name: 'RedisAdapter',\n defaults: { url: 'redis://localhost' },\n build: (config) => {\n const client = createClient(config.url)\n return {\n beforeStart: ({ container }) => {\n container.registerInstance(REDIS_CLIENT, client)\n },\n afterStart: () => client.connect(),\n shutdown: () => client.quit(),\n }\n },\n})\n\n// In src/adapters/index.ts:\nexport const adapters = [RedisAdapter({ url: env.REDIS_URL })] // <-- note parens\n```\n\n**Lifecycle hook decision tree**:\n- `beforeMount` — register early routes that should bypass middleware (health, docs UI).\n- `beforeStart` — DI ready, server not listening yet. **Use this for `container.registerInstance(...)` calls** so they work under `createTestApp` too.\n- `afterStart` — server has `ctx.server` available. Only use for things that need a listening server (Socket.IO upgrades, port logging). **Doesn't fire under `createTestApp`.**\n- `shutdown` — runs concurrently via `Promise.allSettled`, so one failure doesn't block siblings (but errors are swallowed — log inside).\n\n**Middleware phases** (see `MiddlewarePhase` JSDoc):\n`beforeGlobal` | `afterGlobal` (default) | `beforeRoutes` | `afterRoutes` (fires only on fall-through — matched routes that respond skip it).\n\n**Multi-instance** — `.scoped('cache', { url: ... })` makes `name` become `RedisAdapter:cache`. **Deferred config** — `.async({ inject, useFactory })` for config that depends on DI-resolved services.\n\n**Red flags**:\n- `bootstrap({ adapters: [MyAdapter] })` — passed the factory, not the instance. Call it: `MyAdapter()`.\n- Inlining the adapter list directly in `src/index.ts` — entry file should stay thin.\n- Returning a plain object instead of going through `defineAdapter()` — type inference for `config` will be wrong.\n- Using `.async()` for an adapter that returns `middleware()` / `contributors()` / `beforeMount()` / `onRouteMount()` — those hooks have already run by the time `.async()` resolves and are silently skipped.\n- Cross-adapter ordering via array position when it's load-bearing — use `dependsOn: ['OtelAdapter']`; cycles throw `MountCycleError` at boot.\n- Using an adapter when the integration ships **modules + DI bindings + middleware** together → that's a plugin. Promote to `definePlugin()` (see `add-plugin` skill).\n\n**Nuances**:\n- `AdapterContext.server` is `undefined` outside `afterStart`.\n- `shutdown` errors are swallowed by `Promise.allSettled` — wrap in try/catch and log if you care."},{slug:`add-plugin`,frontmatterName:`kickjs-add-plugin`,description:`Use when scaffolding a feature that bundles modules + DI + middleware + adapters together (auth, monitoring suite, multi-tenant scaffolding).`,body:"**When plugin > adapter**: a plugin is the right answer when the integration ships **more than one** of: a module, a DI binding, middleware, or another adapter. If you have a single hook (`beforeStart`) and no other contributions, use `defineAdapter` instead.\n\n**Canonical shape**:\n\n```ts\nimport { definePlugin } from '@forinda/kickjs'\n\nexport const AuthPlugin = definePlugin({\n name: 'AuthPlugin',\n defaults: { tokenTtl: '1h' },\n build: (config, { name }) => ({\n modules: () => [AuthModule()],\n adapters: () => [JwtAdapter({ ttl: config.tokenTtl })],\n middleware: () => [requestIdMiddleware()],\n register(container) {\n container.registerFactory(TOKEN_SIGNER, () => createSigner(config))\n },\n contributors() {\n return [LoadCurrentUser.registration]\n },\n onReady({ server }) {\n log.info(`AuthPlugin listening on port ${server.address().port}`)\n },\n }),\n})\n\n// In bootstrap:\nbootstrap({ plugins: [AuthPlugin({ tokenTtl: env.TOKEN_TTL })] }) // <-- parens\n```\n\n**Inline plugin literal** — the canonical answer for one-off DI bindings. There's no top-level `register:` on `bootstrap` itself:\n\n```ts\nbootstrap({\n plugins: [{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } }],\n})\n```\n\n**Execution order** (memorize):\nplugin `register()` → plugin `middleware()` → plugin `modules()` + user modules → plugin `adapters()` + user adapters → server listens → plugin `onReady()`.\n\n**Static vs dynamic modules**: `modules()` returning an array is introspectable (Swagger, DevTools see it). `setup(registry)` is imperative — pick the latter when the module set depends on resolved config.\n\n**Multi-instance** — `.scoped('users', { url })`; derive unique DI tokens from `ctx.name` inside `build`:\n\n```ts\nbuild: (config, { name }) => ({\n register(c) {\n c.registerInstance(createToken(`cache/${name}`), client)\n },\n})\n```\n\n**Precedence**: plugin contributors land at `'adapter'` precedence — beat global, lose to module/class/method same-key.\n\n**Red flags**:\n- `bootstrap({ plugins: [AuthPlugin] })` — passed factory. Call it: `AuthPlugin()`.\n- Reaching for a plugin when an adapter would do (no modules, no DI bindings, no contributors) — overkill; use `defineAdapter()`.\n- `.async()` plugin that depends on `modules()` / `middleware()` / `adapters()` / `contributors()` — those are dropped. `.async()` only resolves `register()` + `onReady()`.\n- Confusing CLI plugins (`defineCliPlugin` from `@forinda/kickjs-cli`) with runtime plugins (`definePlugin` from `@forinda/kickjs`) — different surfaces, different registration sites.\n- `dependsOn: ['SomePlugin']` referring to a plugin not in the boot list — throws `MissingMountDepError` at boot.\n\n**Nuances**:\n- `definition` is `Object.freeze`'d metadata; useful for version checks (`compare(AuthPlugin.definition.version, '1.2.0')`) — not mountable."},{slug:`write-controller-test`,frontmatterName:`kickjs-write-controller-test`,description:`Use when adding a Vitest test that exercises an HTTP route or DI graph.`,body:"**Template** (copy/paste, adjust):\n\n```ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\nbeforeEach(() => {\n Container.reset() // isolated DI per test\n})\n\ndescribe('UserController', () => {\n it('returns users', async () => {\n const app = await createTestApp([UserModule])\n const res = await app.get('/api/v1/users')\n expect(res.status).toBe(200)\n })\n})\n```\n\n**Typed handler signature** — pair with `kick typegen` so `ctx.body` / `params` / `query` are typed by the route's Zod schema:\n\n```ts\n@Post('/', { body: createTodoSchema })\ncreate(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route\n ctx.created(await this.service.create(ctx.body))\n}\n```\n\n**Red flags**:\n- `new Container()` — wrong; use `Container.reset()` in `beforeEach` or `Container.create()` for fully isolated graphs.\n- `Container.getInstance().reset()` — wrong; same fix.\n- Sharing a container instance across `it()` blocks — leaks registrations between tests.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.\n- Calling `getRequestValue<string>('traceId')` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.\n- Asserting on `res.body.requestId` when `requestId()` middleware isn't mounted in the test app — value will be `undefined`.\n- Using `Scope.REQUEST` services in a test without mounting `requestScopeMiddleware()` — `getRequestValue` silently returns `undefined`; `getRequestStore` throws.\n\n**Nuances**:\n- `@Inject` and `@Autowired` are interchangeable — same runtime, same types; pick by readability.\n- `@Value('MISSING_KEY')` with no default **throws on property access**, not at construction — tests that exercise the getter will surface the missing-env issue."},{slug:`env-wiring-check`,frontmatterName:`kickjs-env-wiring-check`,description:`Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.`,body:"**Diagnosis (in order)**:\n1. Open `src/index.ts`. The **first non-`reflect-metadata`** import MUST be `import './config'`.\n2. Open `src/config/index.ts`. It MUST call `loadEnv(envSchema)` as a top-level side effect — not just declare the schema:\n ```ts\n import { loadEnv, defineEnv } from '@forinda/kickjs'\n const envSchema = defineEnv((base) => base.extend({ DATABASE_URL: z.string().url() }))\n export const env = loadEnv(envSchema)\n ```\n3. The new key MUST be declared in the Zod schema. `@Value('NEW_KEY')` accepts any string at the type level and **falls back to raw `process.env`** when the schema doesn't know the key — silently skipping Zod coercion.\n4. After adding a key, re-run `kick typegen` (or restart `kick dev` if the typegen watcher missed it) so the global `KickEnv` augmentation picks it up.\n\n**Why `@Value` \"works\" but `ConfigService.get` doesn't**: `@Value` has the `process.env` fallback that masks missing-side-effect-import bugs; `ConfigService` has none. If `@Value('FOO')` returns a value but `ConfigService.get('FOO')` returns `undefined`, the side-effect import of `./config` is missing.\n\n**`reloadEnv` vs `resetEnvCache`** — distinct, frequently mixed up:\n- `reloadEnv()` — re-reads `process.env` against the **already registered** schema. Use in HMR plugins after `.env` file changes. Schema survives.\n- `resetEnvCache()` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.\n\n**Nuances**:\n- `loadEnv()` cache is **sticky**: once `loadEnv(extendedSchema)` runs anywhere, no-arg calls reuse it — but only if it actually ran. Schema downgrades silently if `src/config/index.ts` isn't imported.\n- `createConfigService(envSchema)` is deprecated; the typegen-driven `ConfigService` covers it.\n- `dotenv` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.\n- For HMR-friendly `.env` edits, add `envWatchPlugin()` to `vite.config.ts` — calls `reloadEnv()` automatically.\n\n**Fix recipe**: add the key to the schema; add `import './config'` as the first non-reflect-metadata import in `src/index.ts`; re-run `kick typegen`."},{slug:`bootstrap-export`,frontmatterName:`kickjs-bootstrap-export`,description:`Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.`,body:"**Check** `src/index.ts`'s last line:\n\n```ts\n// CORRECT — Vite plugin + createTestApp import the named `app` symbol\nexport const app = await bootstrap({ ... })\n\n// WRONG — HMR degrades to full restart, createTestApp loses the handle\nawait bootstrap({ ... })\n```\n\nThe Vite plugin imports the named `app` symbol via `virtual:kickjs/app`; testing helpers do too. Without the export, both fall back to slower paths (full restart on save, mock handle in tests) **without warning**.\n\n**Red flags**:\n- A bare `await bootstrap(...)` with no `export` — fix by adding `export const app =`.\n- Re-assigning `app` later in the file (`app = somethingElse`) — Vite imports by reference at module-load time; reassignments don't propagate.\n- Multiple files calling `bootstrap()` — only the entry should. Tests use `createTestApp` instead."},{slug:`thin-entry-file`,frontmatterName:`kickjs-thin-entry-file`,description:`Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.`,body:`**Refactor target**:
|
|
1107
|
+
- Module not registered in \`src/modules/index.ts\`.`},{slug:`add-adapter`,frontmatterName:`kickjs-add-adapter`,description:`Use when wiring a single-concern lifecycle integration (Swagger, DevTools, Sentry, Redis client).`,body:"**Steps**:\n1. `kick g adapter <name>` to scaffold the boilerplate, OR install via `kick add <package>` for first-party adapters.\n2. The generated file uses `defineAdapter()` — never `class implements AppAdapter`.\n3. Add the adapter instance (note the parens) to `src/adapters/index.ts` — don't inline in `src/index.ts`.\n4. Pick the right hook and middleware phase deliberately.\n5. Verify with `kick dev` that the adapter's lifecycle logs fire.\n\n**Canonical shape** — factory closure owns instance state:\n\n```ts\nexport const RedisAdapter = defineAdapter<RedisConfig>({\n name: 'RedisAdapter',\n defaults: { url: 'redis://localhost' },\n build: (config) => {\n const client = createClient(config.url)\n return {\n beforeStart: ({ container }) => {\n container.registerInstance(REDIS_CLIENT, client)\n },\n afterStart: () => client.connect(),\n shutdown: () => client.quit(),\n }\n },\n})\n\n// In src/adapters/index.ts:\nexport const adapters = [RedisAdapter({ url: env.REDIS_URL })] // <-- note parens\n```\n\n**Lifecycle hook decision tree**:\n- `beforeMount` — register early routes that should bypass middleware (health, docs UI).\n- `beforeStart` — DI ready, server not listening yet. **Use this for `container.registerInstance(...)` calls** so they work under `createTestApp` too.\n- `afterStart` — server has `ctx.server` available. Only use for things that need a listening server (Socket.IO upgrades, port logging). **Doesn't fire under `createTestApp`.**\n- `shutdown` — runs concurrently via `Promise.allSettled`, so one failure doesn't block siblings (but errors are swallowed — log inside).\n\n**Middleware phases** (see `MiddlewarePhase` JSDoc):\n`beforeGlobal` | `afterGlobal` (default) | `beforeRoutes` | `afterRoutes` (fires only on fall-through — matched routes that respond skip it).\n\n**Multi-instance** — `.scoped('cache', { url: ... })` makes `name` become `RedisAdapter:cache`. **Deferred config** — `.async({ inject, useFactory })` for config that depends on DI-resolved services.\n\n**Red flags**:\n- `bootstrap({ adapters: [MyAdapter] })` — passed the factory, not the instance. Call it: `MyAdapter()`.\n- Inlining the adapter list directly in `src/index.ts` — entry file should stay thin.\n- Returning a plain object instead of going through `defineAdapter()` — type inference for `config` will be wrong.\n- Using `.async()` for an adapter that returns `middleware()` / `contributors()` / `beforeMount()` / `onRouteMount()` — those hooks have already run by the time `.async()` resolves and are silently skipped.\n- Cross-adapter ordering via array position when it's load-bearing — use `dependsOn: ['OtelAdapter']`; cycles throw `MountCycleError` at boot.\n- Using an adapter when the integration ships **modules + DI bindings + middleware** together → that's a plugin. Promote to `definePlugin()` (see `add-plugin` skill).\n\n**Nuances**:\n- `AdapterContext.server` is `undefined` outside `afterStart`.\n- `shutdown` errors are swallowed by `Promise.allSettled` — wrap in try/catch and log if you care."},{slug:`add-plugin`,frontmatterName:`kickjs-add-plugin`,description:`Use when scaffolding a feature that bundles modules + DI + middleware + adapters together (auth, monitoring suite, multi-tenant scaffolding).`,body:"**When plugin > adapter**: a plugin is the right answer when the integration ships **more than one** of: a module, a DI binding, middleware, or another adapter. If you have a single hook (`beforeStart`) and no other contributions, use `defineAdapter` instead.\n\n**Canonical shape**:\n\n```ts\nimport { definePlugin } from '@forinda/kickjs'\n\nexport const AuthPlugin = definePlugin({\n name: 'AuthPlugin',\n defaults: { tokenTtl: '1h' },\n build: (config, { name }) => ({\n modules: () => [AuthModule()],\n adapters: () => [JwtAdapter({ ttl: config.tokenTtl })],\n middleware: () => [requestIdMiddleware()],\n register(container) {\n container.registerFactory(TOKEN_SIGNER, () => createSigner(config))\n },\n contributors() {\n return [LoadCurrentUser.registration]\n },\n onReady({ server }) {\n log.info(`AuthPlugin listening on port ${server.address().port}`)\n },\n }),\n})\n\n// In bootstrap:\nbootstrap({ plugins: [AuthPlugin({ tokenTtl: env.TOKEN_TTL })] }) // <-- parens\n```\n\n**Inline plugin literal** — the canonical answer for one-off DI bindings. There's no top-level `register:` on `bootstrap` itself:\n\n```ts\nbootstrap({\n plugins: [{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } }],\n})\n```\n\n**Execution order** (memorize):\nplugin `register()` → plugin `middleware()` → plugin `modules()` + user modules → plugin `adapters()` + user adapters → server listens → plugin `onReady()`.\n\n**Static vs dynamic modules**: `modules()` returning an array is introspectable (Swagger, DevTools see it). `setup(registry)` is imperative — pick the latter when the module set depends on resolved config.\n\n**Multi-instance** — `.scoped('users', { url })`; derive unique DI tokens from `ctx.name` inside `build`:\n\n```ts\nbuild: (config, { name }) => ({\n register(c) {\n c.registerInstance(createToken(`cache/${name}`), client)\n },\n})\n```\n\n**Precedence**: plugin contributors land at `'adapter'` precedence — beat global, lose to module/class/method same-key.\n\n**Red flags**:\n- `bootstrap({ plugins: [AuthPlugin] })` — passed factory. Call it: `AuthPlugin()`.\n- Reaching for a plugin when an adapter would do (no modules, no DI bindings, no contributors) — overkill; use `defineAdapter()`.\n- `.async()` plugin that depends on `modules()` / `middleware()` / `adapters()` / `contributors()` — those are dropped. `.async()` only resolves `register()` + `onReady()`.\n- Confusing CLI plugins (`defineCliPlugin` from `@forinda/kickjs-cli`) with runtime plugins (`definePlugin` from `@forinda/kickjs`) — different surfaces, different registration sites.\n- `dependsOn: ['SomePlugin']` referring to a plugin not in the boot list — throws `MissingMountDepError` at boot.\n\n**Nuances**:\n- `definition` is `Object.freeze`'d metadata; useful for version checks (`compare(AuthPlugin.definition.version, '1.2.0')`) — not mountable."},{slug:`write-controller-test`,frontmatterName:`kickjs-write-controller-test`,description:`Use when adding a Vitest test that exercises an HTTP route or DI graph.`,body:"**Template** (copy/paste, adjust):\n\n```ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\nbeforeEach(() => {\n Container.reset() // isolated DI per test\n})\n\ndescribe('UserController', () => {\n it('returns users', async () => {\n const app = await createTestApp([UserModule])\n const res = await app.get('/api/v1/users')\n expect(res.status).toBe(200)\n })\n})\n```\n\n**Typed handler signature** — pair with `kick typegen` so `ctx.body` / `params` / `query` are typed by the route's Zod schema:\n\n```ts\n@Post('/', { body: createTodoSchema })\nasync create(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route.\n // Returning (vs ctx.created) lets typegen infer the response type.\n return reply(201, await this.service.create(ctx.body))\n}\n```\n\n**Red flags**:\n- `new Container()` — wrong; use `Container.reset()` in `beforeEach` or `Container.create()` for fully isolated graphs.\n- `Container.getInstance().reset()` — wrong; same fix.\n- Sharing a container instance across `it()` blocks — leaks registrations between tests.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.\n- Calling `getRequestValue<string>('traceId')` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.\n- Asserting on `res.body.requestId` when `requestId()` middleware isn't mounted in the test app — value will be `undefined`.\n- Using `Scope.REQUEST` services in a test without mounting `requestScopeMiddleware()` — `getRequestValue` silently returns `undefined`; `getRequestStore` throws.\n\n**Nuances**:\n- `@Inject` and `@Autowired` are interchangeable — same runtime, same types; pick by readability.\n- `@Value('MISSING_KEY')` with no default **throws on property access**, not at construction — tests that exercise the getter will surface the missing-env issue."},{slug:`env-wiring-check`,frontmatterName:`kickjs-env-wiring-check`,description:`Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.`,body:"**Diagnosis (in order)**:\n1. Open `src/index.ts`. The **first non-`reflect-metadata`** import MUST be `import './config'`.\n2. Open `src/config/index.ts`. It MUST call `loadEnv(envSchema)` as a top-level side effect — not just declare the schema:\n ```ts\n import { loadEnv, defineEnv } from '@forinda/kickjs'\n const envSchema = defineEnv((base) => base.extend({ DATABASE_URL: z.string().url() }))\n export const env = loadEnv(envSchema)\n ```\n3. The new key MUST be declared in the Zod schema. `@Value('NEW_KEY')` accepts any string at the type level and **falls back to raw `process.env`** when the schema doesn't know the key — silently skipping Zod coercion.\n4. After adding a key, re-run `kick typegen` (or restart `kick dev` if the typegen watcher missed it) so the global `KickEnv` augmentation picks it up.\n\n**Why `@Value` \"works\" but `ConfigService.get` doesn't**: `@Value` has the `process.env` fallback that masks missing-side-effect-import bugs; `ConfigService` has none. If `@Value('FOO')` returns a value but `ConfigService.get('FOO')` returns `undefined`, the side-effect import of `./config` is missing.\n\n**`reloadEnv` vs `resetEnvCache`** — distinct, frequently mixed up:\n- `reloadEnv()` — re-reads `process.env` against the **already registered** schema. Use in HMR plugins after `.env` file changes. Schema survives.\n- `resetEnvCache()` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.\n\n**Nuances**:\n- `loadEnv()` cache is **sticky**: once `loadEnv(extendedSchema)` runs anywhere, no-arg calls reuse it — but only if it actually ran. Schema downgrades silently if `src/config/index.ts` isn't imported.\n- `createConfigService(envSchema)` is deprecated; the typegen-driven `ConfigService` covers it.\n- `dotenv` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.\n- For HMR-friendly `.env` edits, add `envWatchPlugin()` to `vite.config.ts` — calls `reloadEnv()` automatically.\n\n**Fix recipe**: add the key to the schema; add `import './config'` as the first non-reflect-metadata import in `src/index.ts`; re-run `kick typegen`."},{slug:`bootstrap-export`,frontmatterName:`kickjs-bootstrap-export`,description:`Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.`,body:"**Check** `src/index.ts`'s last line:\n\n```ts\n// CORRECT — Vite plugin + createTestApp import the named `app` symbol\nexport const app = await bootstrap({ ... })\n\n// WRONG — HMR degrades to full restart, createTestApp loses the handle\nawait bootstrap({ ... })\n```\n\nThe Vite plugin imports the named `app` symbol via `virtual:kickjs/app`; testing helpers do too. Without the export, both fall back to slower paths (full restart on save, mock handle in tests) **without warning**.\n\n**Red flags**:\n- A bare `await bootstrap(...)` with no `export` — fix by adding `export const app =`.\n- Re-assigning `app` later in the file (`app = somethingElse`) — Vite imports by reference at module-load time; reassignments don't propagate.\n- Multiple files calling `bootstrap()` — only the entry should. Tests use `createTestApp` instead."},{slug:`thin-entry-file`,frontmatterName:`kickjs-thin-entry-file`,description:`Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.`,body:`**Refactor target**:
|
|
1082
1108
|
|
|
1083
1109
|
\`\`\`ts
|
|
1084
1110
|
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
@@ -1239,10 +1265,10 @@ in \`.agents/COPILOT.local.md\`.
|
|
|
1239
1265
|
Optional packages (add as needed):
|
|
1240
1266
|
`);for(let e of i)console.log(a(e))}else console.log(`\n Plus ${i.length} optional packages (auth, swagger, db, queue, …).`),console.log(" Run `kick add --list --all` for the full catalog.");console.log(`
|
|
1241
1267
|
Usage: kick add ai db swagger`),console.log(` kick add queue:bullmq`),console.log(` kick add upload # installs the multipart driver for your runtime`),console.log()}function At(e,t,n=`express`){let r=new Set,i=new Set,a=[],o=[],s=[];for(let c of e){if(c===`upload`){let e=xt[n];s.push(`upload (${n}): ${e.note}`),e.prod&&(t?i:r).add(e.prod),e.dev&&i.add(e.dev);continue}let e=yt[c];if(!e){a.push(c);continue}e.deprecated&&o.push(`'${c}' (${e.pkg}) is deprecated — ${e.deprecated}`);let l=t||e.dev?i:r;l.add(e.pkg);for(let t of e.peers)l.add(t)}return{prodDeps:[...r],devDeps:[...i],unknown:a,warnings:o,notices:s}}function jt(e){e.command(`list`).alias(`ls`).description(`List KickJS packages (core only; pair with --all for the full catalog)`).option(`--all`,`Include the full optional catalog`).action(e=>{kt(!!e.all)})}function Mt(e){e.command(`add [packages...]`).description(`Add KickJS packages with their required dependencies`).option(`--pm <manager>`,`Package manager override`).option(`-D, --dev`,`Install as dev dependency`).option(`--list`,`List packages (core only by default; pair with --all)`).option(`--all`,`When listing, include the full optional catalog`).action(async(e,t)=>{if(t.list||e.length===0){kt(!!t.all);return}let{pm:n,source:r}=await Dt(t.pm);console.log(`\n Using ${n} (resolved from ${r})`);let i=await St(process.cwd()),{prodDeps:a,devDeps:o,unknown:s,warnings:c,notices:l}=At(e,!!t.dev,i);for(let e of c)console.warn(`\n WARNING: ${e}`);for(let e of l)console.log(`\n ${e}`);if(!(s.length>0&&(console.log(`\n Unknown packages: ${s.join(`, `)}`),console.log(` Run "kick add --list" to see available packages.
|
|
1242
|
-
`),a.length===0&&o.length===0))){if(a.length>0){let e=a,t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{
|
|
1243
|
-
`)}})}const Nt=f(b(import.meta.url)),Pt=JSON.parse(a(h(Nt,`..`,`package.json`),`utf-8`)),Ft=`^${Pt.version}`,It=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-schema`,`@forinda/kickjs-vite`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`,`@forinda/kickjs-client`];async function Lt(){let e=await Promise.all(It.map(async e=>{try{let t=
|
|
1244
|
-
Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await Promise.resolve().then(()=>Aa);await e({cwd:l,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{
|
|
1245
|
-
Project scaffolded successfully!`),console.log();let p=l!==process.cwd();u(`Next steps:`),p&&u(` cd ${t}`),e.installDeps||u(` ${r} install`);let m={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};u(` ${m[i]??m.rest}`),u(` kick dev`),u(``),u(`Commands:`),u(` kick dev Start dev server with Vite HMR`),u(` kick build Production build via Vite`),u(` kick start Run production build`),u(``),u(`Generators:`),u(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),u(` kick g scaffold <n> <f..> CRUD module from field definitions`),u(` kick g controller <name> Standalone controller`),u(` kick g service <name> @Service() class`),u(` kick g middleware <name> Express middleware`),u(` kick g guard <name> Route guard (auth, roles, etc.)`),u(` kick g adapter <name> AppAdapter with lifecycle hooks`),u(` kick g dto <name> Zod DTO schema`),u(` kick g config Generate kick.config.ts`),u(``),u(`Add packages:`),u(` kick add <pkg> Install a KickJS package + peers`),u(` kick add --list Show all available packages`),u(``),u(`Available: ${bt}`),u(``)}const Ut={GET:O.green,POST:O.cyan,PUT:O.yellow,PATCH:O.magenta,DELETE:O.red};function Wt(e){return(Ut[e]??O.dim)(e.padEnd(7))}function Gt(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return O.red(t);case`WARNING`:return O.yellow(t);case`INFO`:return O.blue(O.dim(t));default:return t}}O.green(`✓`),O.red(`✖`),O.yellow(`⚠`),O.blue(`ℹ`);function Kt(e){D.intro(O.bgCyan(O.black(` ${e} `)))}function P(e){D.outro(e)}function qt(e){D.isCancel(e)&&(D.cancel(`Operation cancelled.`),process.exit(0))}async function Jt(e){let t=await D.text(e);return qt(t),t}async function Yt(e){let t=await D.select(e);return qt(t),t}async function Xt(e){let t=await D.multiselect(e);return qt(t),t}async function F(e){let t=await D.confirm(e);return qt(t),t}function Zt(){return D.spinner()}const I=D.log,Qt=[{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 $t(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)=>{Kt(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await Jt({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=v(`.`),e=d(i)):i=v(t.directory||e),r(i)){let r=o(i);if(r.length>0){if(t.force)I.warn(`Clearing existing files in ${i}`);else if(n){I.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),P(`Aborted.`);return}else{I.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)I.message(` - ${e}`);if(r.length>5&&I.message(` ... and ${r.length-5} more`),!await F({message:O.red(`Remove all existing files and proceed?`),initialValue:!1})){P(`Aborted.`);return}}for(let e of r)s(v(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await Yt({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 c=t.runtime;c||=n?`express`:await Yt({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 l=t.pm;l||=n?await Ot(void 0):await Yt({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let u=t.repo;u||=n?`inmemory`:await Jt({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Oe(u);let f=t.schema;f||=n?`zod`:await Yt({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(f)||(I.warn(`Unknown --schema "${f}", falling back to zod.`),f=`zod`);let p;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();p=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else p=n?[]:await Xt({message:`Select packages to include`,options:[...Qt],required:!1});let m;m=t.git===void 0?n?!0:await F({message:`Initialize git repository?`,initialValue:!0}):t.git;let h;if(h=t.install===void 0?n?!0:await F({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-iuAdYQmC.mjs`);await t({name:e,directory:i,packageManager:l,initGit:m,installDeps:h,schemaLib:f,runtime:c}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${l}${l===`pnpm`?` dev`:` run dev:server`}`)}`);return}await Ht({name:e,directory:i,packageManager:l,initGit:m,installDeps:h,template:a,defaultRepo:u,packages:p,schemaLib:f,runtime:c}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${l} dev`)}`)})}function L(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function R(e){let t=L(e);return t.charAt(0).toLowerCase()+t.slice(1)}function z(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function B(e){return de.plural(e)}function en(e){return de.plural(e)}var tn=k({findProjectRoot:()=>rn});const nn=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function rn(e=process.cwd()){let t=v(e),{root:n}=g(t),i=null,a=t;for(;;){for(let e of nn)if(r(v(a,e)))return a;if(i===null&&r(v(a,`package.json`))&&(i=a),a===n)break;let e=f(a);if(e===a)break;a=e}return i??t}function an(e){return z(e).replace(/-/g,`_`)}function on(e){let t=e.cwd??process.cwd(),n=e.projectRoot??rn(t),r=e.pluralize??!0,i=L(e.name),a=R(e.name),o=z(e.name),s=an(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=B(o);c.pluralKebab=e,c.pluralPascal=L(e),c.pluralCamel=R(e)}return c}function sn(e,t){return v(e.cwd,t)}async function cn(e){return import(x(e).href)}const ln=new Map;async function un(e){let t=ln.get(e);if(t)return t;let n=dn(e);return ln.set(e,n),n}async function dn(t){let n=v(t,`package.json`);if(!r(n))return{generators:[],loaded:[],failed:[]};let i=fn(JSON.parse(await w(n,`utf-8`))),a=e(v(t,`package.json`)),o=[],s=[],c=[];for(let e of i){let t;try{t=a.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await w(t,`utf-8`))}catch(t){c.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let i=n.kickjs.generators,l=v(f(t),i);if(!r(l)){c.push({source:e,reason:`kickjs.generators points to missing file: ${i}`});continue}let u;try{u=await cn(l)}catch(t){c.push({source:e,reason:`failed to import manifest: ${t}`});continue}let d=u.default;if(!Array.isArray(d)){c.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of d){if(!pn(t)){c.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}o.push({source:e,spec:t})}s.push(e)}return{generators:o,loaded:s,failed:c}}function fn(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 pn(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function mn(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return _n(r.spec,r.source,e,n);let i=gn(await un(n),e.generatorName);return i?_n(i.spec,i.source,e,n):null}async function hn(e,t=[]){let n=await un(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 gn(e,t){return e.generators.find(e=>e.spec.name===t)}async function _n(e,t,n,r){let i=on({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=sn(i,e.path);await N(t,e.content),o.push(t)}return{files:o,source:t}}function V(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function vn(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yn(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function bn(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]??`${vn(n)}${e}Repository`,repoFile:i[n]??`${yn(n)}-${t}`}}function xn(e){return e??`define`}function Sn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=bn(t,n,i),c=xn(a),l=`/**
|
|
1268
|
+
`),a.length===0&&o.length===0))){if(a.length>0){let e=a,t=`${n} add ${e.join(` `)}`;console.log(`\n Installing ${e.length} dependency(ies):`);for(let t of e)console.log(` + ${t}`);console.log();try{C(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}if(o.length>0){let e=o,t=`${n} add -D ${e.join(` `)}`;console.log(`\n Installing ${e.length} dev dependency(ies):`);for(let t of e)console.log(` + ${t} (dev)`);console.log();try{C(t,{stdio:`inherit`})}catch{console.log(`\n Installation failed. Run manually:\n ${t}\n`)}}console.log(` Done!
|
|
1269
|
+
`)}})}const Nt=f(b(import.meta.url)),Pt=JSON.parse(a(h(Nt,`..`,`package.json`),`utf-8`)),Ft=`^${Pt.version}`,It=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-schema`,`@forinda/kickjs-vite`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`,`@forinda/kickjs-client`];async function Lt(){let e=await Promise.all(It.map(async e=>{try{let t=S(`npm`,[`view`,e,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(t&&/^\d+\.\d+\.\d+/.test(t))return[e,`^${t}`]}catch{}return[e,Ft]}));return Object.fromEntries(e)}function Rt(e,t){try{let n=S(`npm`,[`view`,`${e}@${t}`,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();return n&&/^\d+\.\d+\.\d+/.test(n)?n:null}catch{return null}}function zt(e){return(e??``).replace(/^[\^~>=<\s]+/,``)}function Bt(e,t){let n=e=>zt(e).split(`-`)[0].split(`.`).map(e=>Number.parseInt(e,10)||0),[r=0,i=0,a=0]=n(e),[o=0,s=0,c=0]=n(t);return r===o?i===s?a>=c:i>s:r>o}function Vt(e,t,n){try{let r=S(`npm`,[`view`,`${e}@${t}`,`exports`,`--json`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(!r)return!1;let i=JSON.parse(r);return Object.prototype.hasOwnProperty.call(i,n)}catch{return!1}}async function Ht(e){let{name:t,directory:n,packageManager:r=`pnpm`,template:i=`rest`,defaultRepo:a=`inmemory`,packages:o=[],schemaLib:s=`zod`,runtime:c=`express`}=e,l=n,u=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),u(`Resolving package versions...`);let d=await Lt();if(c!==`express`)if(Vt(`@forinda/kickjs`,`latest`,`./${c}`))u(`Using @forinda/kickjs@latest (stable ships the ${c} runtime)`);else{let e=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`],t=[],n=!1;for(let r of e){let e=Rt(r,`alpha`);e&&Bt(e,zt(d[r]))&&(d[r]=`^${e}`,t.push(`${r}@^${e}`),r===`@forinda/kickjs`&&(n=!0))}u(n?`Using the alpha channel for the ${c} runtime: ${t.join(`, `)}`:`WARNING: could not resolve @forinda/kickjs@alpha — the ${c} runtime subpath may be missing. After install, run: ${r} add @forinda/kickjs@alpha`)}await N(h(l,`package.json`),Ye(t,i,d,o,s,c)),await N(h(l,`vite.config.ts`),Xe()),await N(h(l,`tsconfig.json`),Ze()),await N(h(l,`.prettierrc`),Qe()),await N(h(l,`.editorconfig`),$e()),await N(h(l,`.gitignore`),et()),await N(h(l,`.gitattributes`),tt()),await N(h(l,`.env`),nt()),await N(h(l,`.env.example`),rt()),await N(h(l,`src/config/index.ts`),ct(s)),await N(h(l,`src/index.ts`),ot(t,i,Pt.version,o,c)),await N(h(l,`src/modules/index.ts`),st()),await N(h(l,`src/modules/hello/hello.service.ts`),lt()),await N(h(l,`src/modules/hello/hello.controller.ts`),ut()),await N(h(l,`src/modules/hello/hello.module.ts`),dt()),await N(h(l,`kick.config.ts`),ft(i,a,r,c)),await N(h(l,`vitest.config.ts`),it()),await N(h(l,`README.md`),pt(t,i,r));let{generateAgentDocs:f}=await Promise.resolve().then(()=>ar);if(await f({outDir:l,name:t,pm:r,template:i,only:`all`,force:!0}),e.installDeps){console.log(`\n Installing dependencies with ${r}...\n`);try{C(`${r} install`,{cwd:l,stdio:`inherit`}),console.log(`
|
|
1270
|
+
Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${r} install failed. Run it manually.`)}}try{let{runTypegen:e}=await Promise.resolve().then(()=>Aa);await e({cwd:l,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{C(`git init`,{cwd:l,stdio:`pipe`}),C(`git branch -M main`,{cwd:l,stdio:`pipe`}),C(`git add -A`,{cwd:l,stdio:`pipe`}),C(`git commit -m "chore: initial commit from kick new"`,{cwd:l,stdio:`pipe`}),u(`Git repository initialized`)}catch{u(`Warning: git init failed (git may not be installed)`)}console.log(`
|
|
1271
|
+
Project scaffolded successfully!`),console.log();let p=l!==process.cwd();u(`Next steps:`),p&&u(` cd ${t}`),e.installDeps||u(` ${r} install`);let m={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};u(` ${m[i]??m.rest}`),u(` kick dev`),u(``),u(`Commands:`),u(` kick dev Start dev server with Vite HMR`),u(` kick build Production build via Vite`),u(` kick start Run production build`),u(``),u(`Generators:`),u(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),u(` kick g scaffold <n> <f..> CRUD module from field definitions`),u(` kick g controller <name> Standalone controller`),u(` kick g service <name> @Service() class`),u(` kick g middleware <name> Express middleware`),u(` kick g guard <name> Route guard (auth, roles, etc.)`),u(` kick g adapter <name> AppAdapter with lifecycle hooks`),u(` kick g dto <name> Zod DTO schema`),u(` kick g config Generate kick.config.ts`),u(``),u(`Add packages:`),u(` kick add <pkg> Install a KickJS package + peers`),u(` kick add --list Show all available packages`),u(``),u(`Available: ${bt}`),u(``)}const Ut={GET:O.green,POST:O.cyan,PUT:O.yellow,PATCH:O.magenta,DELETE:O.red};function Wt(e){return(Ut[e]??O.dim)(e.padEnd(7))}function Gt(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return O.red(t);case`WARNING`:return O.yellow(t);case`INFO`:return O.blue(O.dim(t));default:return t}}O.green(`✓`),O.red(`✖`),O.yellow(`⚠`),O.blue(`ℹ`);function Kt(e){D.intro(O.bgCyan(O.black(` ${e} `)))}function P(e){D.outro(e)}function qt(e){D.isCancel(e)&&(D.cancel(`Operation cancelled.`),process.exit(0))}async function Jt(e){let t=await D.text(e);return qt(t),t}async function Yt(e){let t=await D.select(e);return qt(t),t}async function Xt(e){let t=await D.multiselect(e);return qt(t),t}async function F(e){let t=await D.confirm(e);return qt(t),t}function Zt(){return D.spinner()}const I=D.log,Qt=[{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 $t(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)=>{Kt(`KickJS — Create a new project`);let n=!!(t.yes||t.nonInteractive);e||=n?`my-api`:await Jt({message:`Project name`,placeholder:`my-api`,defaultValue:`my-api`});let i;if(e===`.`?(i=v(`.`),e=d(i)):i=v(t.directory||e),r(i)){let r=o(i);if(r.length>0){if(t.force)I.warn(`Clearing existing files in ${i}`);else if(n){I.warn(`Directory "${e}" is not empty. Pass --force to clear it.`),P(`Aborted.`);return}else{I.warn(`Directory "${e}" is not empty:`);let t=r.slice(0,5);for(let e of t)I.message(` - ${e}`);if(r.length>5&&I.message(` ... and ${r.length-5} more`),!await F({message:O.red(`Remove all existing files and proceed?`),initialValue:!1})){P(`Aborted.`);return}}for(let e of r)s(v(i,e),{recursive:!0,force:!0})}}let a=t.template;a||=n?`minimal`:await Yt({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 c=t.runtime;c||=n?`express`:await Yt({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 l=t.pm;l||=n?await Ot(void 0):await Yt({message:`Package manager`,options:[{value:`pnpm`,label:`pnpm`},{value:`npm`,label:`npm`},{value:`yarn`,label:`yarn`},{value:`bun`,label:`bun`}]});let u=t.repo;u||=n?`inmemory`:await Jt({message:`Repository name`,placeholder:`inmemory (or a DB name, e.g. postgres)`,defaultValue:`inmemory`}),Oe(u);let f=t.schema;f||=n?`zod`:await Yt({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(f)||(I.warn(`Unknown --schema "${f}", falling back to zod.`),f=`zod`);let p;if(t.packages!==void 0){let e=t.packages.trim().toLowerCase();p=e===``||e===`none`||e===`false`?[]:t.packages.split(`,`).map(e=>e.trim()).filter(Boolean)}else p=n?[]:await Xt({message:`Select packages to include`,options:[...Qt],required:!1});let m;m=t.git===void 0?n?!0:await F({message:`Initialize git repository?`,initialValue:!0}):t.git;let h;if(h=t.install===void 0?n?!0:await F({message:`Install dependencies?`,initialValue:!0}):t.install,a===`fullstack`){let{initFullstackProject:t}=await import(`./fullstack-C8u97QC-.mjs`);await t({name:e,directory:i,packageManager:l,initGit:m,installDeps:h,schemaLib:f,runtime:c}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${l}${l===`pnpm`?` dev`:` run dev:server`}`)}`);return}await Ht({name:e,directory:i,packageManager:l,initGit:m,installDeps:h,template:a,defaultRepo:u,packages:p,schemaLib:f,runtime:c}),P(`Done! Next steps: ${O.cyan(`cd ${e} && ${l} dev`)}`)})}function L(e){return e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``).replace(/^(.)/,e=>e.toUpperCase())}function R(e){let t=L(e);return t.charAt(0).toLowerCase()+t.slice(1)}function z(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function B(e){return de.plural(e)}function en(e){return de.plural(e)}var tn=k({findProjectRoot:()=>rn});const nn=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function rn(e=process.cwd()){let t=v(e),{root:n}=g(t),i=null,a=t;for(;;){for(let e of nn)if(r(v(a,e)))return a;if(i===null&&r(v(a,`package.json`))&&(i=a),a===n)break;let e=f(a);if(e===a)break;a=e}return i??t}function an(e){return z(e).replace(/-/g,`_`)}function on(e){let t=e.cwd??process.cwd(),n=e.projectRoot??rn(t),r=e.pluralize??!0,i=L(e.name),a=R(e.name),o=z(e.name),s=an(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=B(o);c.pluralKebab=e,c.pluralPascal=L(e),c.pluralCamel=R(e)}return c}function sn(e,t){return v(e.cwd,t)}async function cn(e){return import(x(e).href)}const ln=new Map;async function un(e){let t=ln.get(e);if(t)return t;let n=dn(e);return ln.set(e,n),n}async function dn(t){let n=v(t,`package.json`);if(!r(n))return{generators:[],loaded:[],failed:[]};let i=fn(JSON.parse(await w(n,`utf-8`))),a=e(v(t,`package.json`)),o=[],s=[],c=[];for(let e of i){let t;try{t=a.resolve(`${e}/package.json`)}catch{continue}let n;try{n=JSON.parse(await w(t,`utf-8`))}catch(t){c.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!n.kickjs?.generators)continue;let i=n.kickjs.generators,l=v(f(t),i);if(!r(l)){c.push({source:e,reason:`kickjs.generators points to missing file: ${i}`});continue}let u;try{u=await cn(l)}catch(t){c.push({source:e,reason:`failed to import manifest: ${t}`});continue}let d=u.default;if(!Array.isArray(d)){c.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of d){if(!pn(t)){c.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}o.push({source:e,spec:t})}s.push(e)}return{generators:o,loaded:s,failed:c}}function fn(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 pn(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function mn(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return _n(r.spec,r.source,e,n);let i=gn(await un(n),e.generatorName);return i?_n(i.spec,i.source,e,n):null}async function hn(e,t=[]){let n=await un(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 gn(e,t){return e.generators.find(e=>e.spec.name===t)}async function _n(e,t,n,r){let i=on({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=sn(i,e.path);await N(t,e.content),o.push(t)}return{files:o,source:t}}function V(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function vn(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yn(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function bn(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]??`${vn(n)}${e}Repository`,repoFile:i[n]??`${yn(n)}-${t}`}}function xn(e){return e??`define`}function Sn(e){let{pascal:t,kebab:n,plural:r=``,repo:i,style:a}=e,{repoClass:o,repoFile:s}=bn(t,n,i),c=xn(a),l=`/**
|
|
1246
1272
|
* ${t} Module
|
|
1247
1273
|
*
|
|
1248
1274
|
* REST module with a flat folder structure.
|
|
@@ -2304,7 +2330,7 @@ export default defineConfig({
|
|
|
2304
2330
|
},
|
|
2305
2331
|
],
|
|
2306
2332
|
})
|
|
2307
|
-
`),[t])}var ar=k({generateAgentDocs:()=>dr});const or=`.agents`,sr=new Set([`rest`,`minimal`]);function cr(e,t){if(t)return t;try{let t=JSON.parse(a(h(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function lr(e,t){if(t)return t;try{let t=JSON.parse(a(h(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function ur(e,t){if(t)return t;try{let t=(await j(e))?.pattern;if(t&&sr.has(t))return t}catch{}return`rest`}async function dr(e){let t=e.only??`all`,n=cr(e.outDir,e.name),i=lr(e.outDir,e.pm),a=await ur(e.outDir,e.template),o=t===`agents`||t===`both`||t===`all`,s=t===`claude`||t===`both`||t===`all`,c=t===`skills`||t===`all`,l=t===`gemini`||t===`all`,u=t===`copilot`||t===`all`,d=[];if(o&&d.push({file:h(e.outDir,or,`AGENTS.md`),render:()=>ht(n,a,i)}),s&&d.push({file:h(e.outDir,`CLAUDE.md`),render:()=>mt(n,a,i)}),c)for(let t of gt(n,a,i))d.push({file:h(e.outDir,or,`skills`,t.slug,`SKILL.md`),render:()=>t.content});l&&d.push({file:h(e.outDir,or,`GEMINI.md`),render:()=>_t(n,a,i)}),u&&d.push({file:h(e.outDir,or,`COPILOT.md`),render:()=>vt(n,a,i)});let f=[];for(let{file:t,render:n}of d){if(r(t)&&!e.force&&!await F({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await N(t,n()),f.push(t)}return f}function fr(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 pr(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=fr(e,r);return i===-1?null:e.slice(r+1,i)}function mr(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
2333
|
+
`),[t])}var ar=k({generateAgentDocs:()=>dr});const or=`.agents`,sr=new Set([`rest`,`minimal`,`fullstack`]);function cr(e,t){if(t)return t;try{let t=JSON.parse(a(h(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}function lr(e,t){if(t)return t;try{let t=JSON.parse(a(h(e,`package.json`),`utf-8`));if(t.packageManager)return t.packageManager.split(`@`)[0]}catch{}return`pnpm`}async function ur(e,t){if(t)return t;try{let t=(await j(e))?.pattern;if(t&&sr.has(t))return t}catch{}return`rest`}async function dr(e){let t=e.only??`all`,n=cr(e.outDir,e.name),i=lr(e.outDir,e.pm),a=await ur(e.outDir,e.template),o=t===`agents`||t===`both`||t===`all`,s=t===`claude`||t===`both`||t===`all`,c=t===`skills`||t===`all`,l=t===`gemini`||t===`all`,u=t===`copilot`||t===`all`,d=[];if(o&&d.push({file:h(e.outDir,or,`AGENTS.md`),render:()=>ht(n,a,i)}),s&&d.push({file:h(e.outDir,`CLAUDE.md`),render:()=>mt(n,a,i)}),c)for(let t of gt(n,a,i))d.push({file:h(e.outDir,or,`skills`,t.slug,`SKILL.md`),render:()=>t.content});l&&d.push({file:h(e.outDir,or,`GEMINI.md`),render:()=>_t(n,a,i)}),u&&d.push({file:h(e.outDir,or,`COPILOT.md`),render:()=>vt(n,a,i)});let f=[];for(let{file:t,render:n}of d){if(r(t)&&!e.force&&!await F({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})){console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`);continue}await N(t,n()),f.push(t)}return f}function fr(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 pr(e,t){let n=t.exec(e);if(!n)return null;let r=n.index+n[0].length-1,i=fr(e,r);return i===-1?null:e.slice(r+1,i)}function mr(e,t,n){let r=` `.repeat(n);return e.split(`
|
|
2308
2334
|
`).map(e=>{if(e.trim()===``)return e;let n=RegExp(`^ {0,${t}}`),i=e.replace(n,``);return r+i}).join(`
|
|
2309
2335
|
`)}function hr(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 gr(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 _r(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=fr(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=pr(o,/register\s*\(([^)]*)\)\s*:\s*void\s*\{/),u=pr(o,/contributors\s*\(\s*\)\s*:\s*ContributorRegistrations\s*\{/),d=pr(o,/routes\s*\(\s*\)\s*:\s*[A-Za-z|[\]\s]+\{/);if(!d)return{migrated:null,reason:`routes() method missing or signature unrecognized`};let f=hr(s),p=``;return l&&(p+=` register(container) {${mr(l,4,6)} },\n\n`),u&&(p+=` contributors() {${mr(u,4,6)} },\n\n`),p+=` routes() {${mr(d,4,6)} },`,{migrated:`${f}${`export const ${r} = defineModule({
|
|
2310
2336
|
name: '${r}',
|
|
@@ -2315,7 +2341,7 @@ ${p}
|
|
|
2315
2341
|
`||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=fr(s,f);if(p===-1)return{migrated:null,reason:`unbalanced build() braces`};let m=s.slice(f+1,p),h=pr(m,/register\s*\(([^)]*)\)\s*\{/),g=pr(m,/contributors\s*\(\s*\)\s*\{/),_=pr(m,/routes\s*\(\s*\)\s*\{/);if(!_)return{migrated:null,reason:`routes() method missing inside build()`};let v=gr(c,{container:h!==null,appModule:!0,moduleRoutes:!0,contributorRegistrations:g!==null}),y=``;return h!==null&&(y+=` register(container: Container): void {${mr(h,6,4)} }\n\n`),g!==null&&(y+=` contributors(): ContributorRegistrations {${mr(g,6,4)} }\n\n`),y+=` routes(): ModuleRoutes {${mr(_,6,4)} }`,{migrated:`${v}${`export class ${r} implements AppModule {
|
|
2316
2342
|
${y}
|
|
2317
2343
|
}
|
|
2318
|
-
`}${u}`}}function yr(e,t){return t===`class`?vr(e):_r(e)}function br(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 xr(e){let t=[];return await n(v(e),0),t;async function n(e,r){let i;try{i=await oe(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=h(e,a),o;try{o=await ce(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Sr(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await oe(e)}catch{return}await
|
|
2344
|
+
`}${u}`}}function yr(e,t){return t===`class`?vr(e):_r(e)}function br(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 xr(e){let t=[];return await n(v(e),0),t;async function n(e,r){let i;try{i=await oe(e)}catch{return}for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=h(e,a),o;try{o=await ce(i)}catch{continue}o.isDirectory()?await n(i,r+1):(a.endsWith(`.module.ts`)||a===`index.ts`&&r===1)&&t.push(i)}}}async function Sr(e,t){let n=0;return await r(e,t),n;async function r(e,t){let i;try{i=await oe(e)}catch{return}await ae(t,{recursive:!0});for(let a of i){if(a===`node_modules`||a===`dist`||a===`.kickjs`)continue;let i=h(e,a),o=h(t,a),s;try{s=await ce(i)}catch{continue}s.isDirectory()?await r(i,o):(await ie(i,o),n++)}}}function Cr(e){return h(e,`.kickjs`,`codemod-backups`,`${new Date().toISOString().replaceAll(/[:.]/g,`-`)}-modules`)}async function wr(e,t){let{dryRun:n=!1,cwd:r=process.cwd(),target:i}=t,a=t.backup??!n,o=await xr(e),s=await w(h(e,`index.ts`),`utf-8`).then(()=>!0,()=>!1),c=null;a&&(o.length>0||s)&&(c=Cr(r),await Sr(e,c));let l=[];for(let e of o){let t=yr(await w(e,`utf-8`),i);if(t.migrated==null){l.push({path:e,status:`skipped`,reason:t.reason});continue}n||await T(e,t.migrated,`utf-8`),l.push({path:e,status:`migrated`})}let u=h(e,`index.ts`),d=null;try{d=await w(u,`utf-8`)}catch{return{target:i,files:l,indexStatus:`not-found`,indexPath:u,backupDir:c}}let f=br(d,i);return f.migrated==null?{target:i,files:l,indexStatus:`skipped`,indexPath:u,indexReason:f.reason,backupDir:c}:(n||await T(u,f.migrated,`utf-8`),{target:i,files:l,indexStatus:`migrated`,indexPath:u,backupDir:c})}async function Tr(e,t){let n=await xr(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 w(e,`utf-8`);i.test(t)&&r.push(e)}return r}async function Er(e){let{name:t,outDir:n}=e,r=L(t),i=z(t),a=R(t),o=e.queue??`${i}-queue`,s=[];return await(async(e,t)=>{let r=h(n,e);await N(r,t),s.push(r)})(`${i}.job.ts`,`import { Inject } from '@forinda/kickjs'
|
|
2319
2345
|
import { Job, Process, QUEUE_MANAGER, type QueueService } from '@forinda/kickjs-queue'
|
|
2320
2346
|
|
|
2321
2347
|
/**
|
|
@@ -2394,7 +2420,7 @@ describe('${o}', () => {
|
|
|
2394
2420
|
expect(true).toBe(true)
|
|
2395
2421
|
})
|
|
2396
2422
|
})
|
|
2397
|
-
`),s.push(l),s}const Pr=[`classes`,`tokens`,`injects`,`pluginsAndAdapters`,`augmentations`,`contextKeys`,`routes`,`moduleMounts`,`globPatterns`];function Fr(e){if(!e||typeof e!=`object`)return!1;let t=e;return Pr.every(e=>Array.isArray(t[e]))}var Ir=class e{path;prev;next=new Map;nextSig=new Map;constructor(e,t){this.path=e,this.prev=t}static async load(t){let n=h(t,`scan.json`),r=new Map;try{let e=await w(n,`utf-8`),t=JSON.parse(e);if(t.version===2&&t.files)for(let[e,n]of Object.entries(t.files))n&&typeof n.sig==`string`&&Fr(n.extract)&&r.set(e,n)}catch{}return new e(n,r)}static async signature(e){try{let t=await ce(e);return`${t.mtimeMs}:${t.size}`}catch{return null}}get(e,t){let n=this.prev.get(e);return n&&n.sig===t?n.extract:null}set(e,t,n){this.next.set(e,n),this.nextSig.set(e,t)}cachedFiles(){return[...this.prev.keys()]}peek(e){return this.prev.get(e)?.extract??null}carry(e){let t=this.prev.get(e);return t?(this.next.set(e,t.extract),this.nextSig.set(e,t.sig),!0):!1}async save(){let e={};for(let[t,n]of this.next){let r=this.nextSig.get(t);r&&(e[t]={sig:r,extract:n})}let t={version:2,files:e};try{await C(f(this.path),{recursive:!0}),await T(this.path,JSON.stringify(t),`utf-8`)}catch{}}};let Lr=null;function Rr(){return Lr??=new Set(ei),Lr}const zr=new Set([`Get`,`Post`,`Put`,`Delete`,`Patch`]);function H(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(H(e)){t(e);for(let n of Object.keys(e)){if(n===`type`)continue;let r=e[n];typeof r==`object`&&r&&U(r,t)}}}function W(e){if(!H(e))return null;if(e.type===`Literal`&&typeof e.value==`string`)return e.value;if(e.type===`TemplateLiteral`){let t=e.quasis,n=e.expressions;if(t?.length===1&&(n?.length??0)===0){let e=t[0].value?.cooked;return typeof e==`string`?e:null}}return null}function G(e){return H(e)&&e.type===`Identifier`?e.name:null}function Br(e){return G(e.callee)}function K(e,t){if(!e||e.type!==`ObjectExpression`)return null;for(let n of e.properties??[]){if(n.type!==`Property`)continue;let e=n.key;if((G(e)??(e.type===`Literal`?String(e.value):W(e)))===t)return n.value}return null}function Vr(e){let t=e.arguments?.[0];return H(t)&&t.type===`ObjectExpression`?t:null}function Hr(e,t){let n=K(e,t);if(!H(n)||n.type!==`ArrayExpression`)return[];let r=[];for(let e of n.elements??[]){let t=W(e);t!==null&&r.push(t)}return r}function Ur(e,t){return _(t,e).split(y).join(`/`)}function Wr(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function Gr(e,t){for(let n of e.implements??[]){let e=n.expression??n;if(G(e)===t)return!0;if(e.type===`TSQualifiedName`||e.type===`MemberExpression`){let n=e.right??e.property;if(n&&G(n)===t)return!0}}return!1}function Kr(e){return e.decorators??[]}function qr(e){let t=e.expression;if(!H(t)||t.type!==`CallExpression`)return null;let n=Br(t);return n?{name:n,call:t}:null}function Jr(e){let t=new Map,n=new Set;for(let r of e.body??[]){if(r.type===`ImportDeclaration`){let e=W(r.source)??``;for(let n of r.specifiers??[]){let r=G(n.local);r&&t.set(r,{source:e})}continue}let e=r.type===`VariableDeclaration`?r:r.type===`ExportNamedDeclaration`&&H(r.declaration)?r.declaration:null;if(H(e)&&e.type===`VariableDeclaration`)for(let t of e.declarations??[]){let e=G(t.id);e&&n.add(e)}}return{imports:t,topLevelConsts:n}}function Yr(e,t){let n=t.imports.get(e);return n?{identifier:e,source:n.source}:t.topLevelConsts.has(e)?{identifier:e,source:``}:{identifier:e,source:null}}function Xr(e,t,n){let r=G(K(e,t));return r?Yr(r,n):null}function Zr(e,t){for(let n of e){let e=qr(n);if(!e||e.name!==`ApiQueryParams`)continue;let r=e.call.arguments?.[0],i=null;if(H(r)&&r.type===`ObjectExpression`)i=r;else{let e=G(r);if(e){let n=t.get(e);n&&n.type===`ObjectExpression`&&(i=n)}}return{filterable:Hr(i,`filterable`),sortable:Hr(i,`sortable`),searchable:Hr(i,`searchable`)}}return null}function Qr(e,t,n){let r;try{let n=fe(t,e);if(n.errors.length>0)return null;r=n.program}catch{return null}let i=Ur(t,n),a=Jr(r),o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m=[],h=new Set,g=new Set,_=new Set,v=new Map;for(let e of r.body??[]){let t=e.type===`VariableDeclaration`?e:e.type===`ExportNamedDeclaration`&&H(e.declaration)?e.declaration:null;if(H(t)&&t.type===`VariableDeclaration`)for(let e of t.declarations??[]){let t=G(e.id);t&&H(e.init)&&v.set(t,e.init)}}let y=[];for(let e of r.body??[])if(e.type===`ExportNamedDeclaration`&&H(e.declaration)){let t=e.declaration;t.type===`ClassDeclaration`&&y.push({cls:t,isDefault:!1})}else if(e.type===`ExportDefaultDeclaration`&&H(e.declaration)){let t=e.declaration;t.type===`ClassDeclaration`&&y.push({cls:t,isDefault:!0})}for(let{cls:e,isDefault:n}of y){let r=G(e.id);if(!r)continue;let a=null;for(let t of Kr(e)){let e=qr(t);if(e&&Rr().has(e.name)){a=e.name;break}}a?o.push({className:r,decorator:a,filePath:t,relativePath:i,isDefault:n}):Gr(e,`AppModule`)&&o.push({className:r,decorator:`Module`,filePath:t,relativePath:i,isDefault:n})}for(let e of r.body??[]){if(e.type!==`ExportNamedDeclaration`||!H(e.declaration))continue;let n=e.declaration;if(n.type===`VariableDeclaration`)for(let e of n.declarations??[]){let n=G(e.id),r=e.init;!n||!H(r)||r.type!==`CallExpression`||Br(r)===`defineModule`&&(o.some(e=>e.className===n)||o.push({className:n,decorator:`Module`,filePath:t,relativePath:i,isDefault:!1}))}}U(r,e=>{if(e.type===`VariableDeclarator`){let n=e.init;if(H(n)&&n.type===`CallExpression`&&Br(n)===`createToken`){let r=W(n.arguments?.[0]);r!==null&&(_.add(n),s.push({name:r,variable:G(e.id),filePath:t,relativePath:i}))}return}if(e.type!==`CallExpression`){if(e.type===`Decorator`){let n=qr(e);if(n?.name===`Inject`){let e=W(n.call.arguments?.[0]);e!==null&&c.push({name:e,filePath:t,relativePath:i})}}return}let n=e.callee,r=Br(e);if(r===`createToken`&&!_.has(e)){let n=W(e.arguments?.[0]);n!==null&&s.push({name:n,variable:null,filePath:t,relativePath:i});return}if(r===`defineAdapter`||r===`definePlugin`){let n=W(K(Vr(e),`name`));if(n!==null){let e=r===`definePlugin`?`plugin`:`adapter`,a=`${r}::${n}::${t}`;h.has(a)||(h.add(a),l.push({kind:e,name:n,filePath:t,relativePath:i}))}return}if(r===`defineAugmentation`){let n=e.arguments??[],r=W(n[0]);if(r!==null){let e=H(n[1])&&n[1].type===`ObjectExpression`?n[1]:null;u.push({name:r,description:W(K(e,`description`)),example:W(K(e,`example`)),filePath:t,relativePath:i})}return}if(r===`defineContextDecorator`||r===`defineHttpContextDecorator`){let n=W(K(Vr(e),`key`));n!==null&&!g.has(n)&&(g.add(n),d.push({key:n,filePath:t,relativePath:i}));return}if(H(n)&&n.type===`CallExpression`){let r=n.callee;if(H(r)&&r.type===`MemberExpression`&&G(r.property)===`withParams`){let n=G(r.object);if(n===`defineContextDecorator`||n===`defineHttpContextDecorator`){let n=W(K(Vr(e),`key`));n!==null&&!g.has(n)&&(g.add(n),d.push({key:n,filePath:t,relativePath:i}))}}return}if(H(n)&&n.type===`MemberExpression`&&G(n.property)===`glob`){let t=n.object;H(t)&&t.type===`MetaProperty`&&U(e.arguments,e=>{let t=W(e);t!==null&&m.push(t)})}});let b=[];U(r,e=>{if(e.type===`ClassDeclaration`||e.type===`ClassExpression`){let t=G(e.id);t&&b.push({cls:e,className:t})}});for(let{cls:e,className:n}of b){let r=o.find(e=>e.className===n),s=e.body?.body;if(Gr(e,`AppAdapter`))for(let e of s??[]){if(e.type!==`PropertyDefinition`||G(e.key)!==`name`)continue;let n=W(e.value);if(n===null)continue;let r=`class::${n}::${t}`;h.has(r)||(h.add(r),l.push({kind:`adapter`,name:n,filePath:t,relativePath:i}));break}for(let e of s??[]){if(e.type!==`MethodDefinition`)continue;let o=G(e.key);if(!o)continue;if(o===`routes`){$r(e.value,p);continue}if(!r)continue;let s=Kr(e),c=Zr(s,v);for(let e of s){let s=qr(e);if(!s||!zr.has(s.name))continue;let l=s.call.arguments??[],u=W(l[0]),d=u&&u.length>0?u:`/`,p=H(l[1])&&l[1].type===`ObjectExpression`?l[1]:null;f.push({controller:n,method:o,httpMethod:s.name.toUpperCase(),path:d,pathParams:Wr(d),queryFilterable:c?.filterable??null,querySortable:c?.sortable??null,querySearchable:c?.searchable??null,bodySchema:Xr(p,`body`,a),querySchema:Xr(p,`query`,a),paramsSchema:Xr(p,`params`,a),filePath:t,relativePath:i,controllerIsDefaultExport:r.isDefault,mountedPath:d})}}}return U(r,e=>{if(e.type!==`Property`||G(e.key)!==`routes`)return;let t=e.value;H(t)&&(t.type===`FunctionExpression`||t.type===`ArrowFunctionExpression`)&&$r(t,p)}),{classes:o,tokens:s,injects:c,pluginsAndAdapters:l,augmentations:u,contextKeys:d,routes:f,moduleMounts:p,globPatterns:/\.module\.[mc]?[tj]sx?$/.test(t)?m:[]}}function $r(e,t){let n=[],r=[];U(e.body,e=>{if(e.type!==`Property`)return;let t=G(e.key);if(t===`path`){let t=W(e.value);t!==null&&n.push(t)}else if(t===`controller`){let t=G(e.value);t&&/^[A-Z]/.test(t)&&r.push(t)}});let i=Math.min(n.length,r.length);for(let e=0;e<i;e++)t.push({controller:r[e],mountPath:n[e]})}const ei=[`Service`,`Controller`,`Repository`,`Injectable`,`Component`,`Module`],ti=[`.ts`,`.tsx`,`.mts`,`.cts`],ni=[`node_modules`,`.kickjs`,`dist`,`build`,`.test.`,`.spec.`,`.d.ts`],ri=new RegExp(String.raw`@(${ei.join(`|`)})\s*\([^)]*\)`+String.raw`(?:\s*@[A-Z]\w*(?:\s*\([^)]*\))?)*`+String.raw`\s*export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`,`g`),ii=new RegExp(String.raw`export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`+String.raw`(?:\s+extends\s+\w+(?:<[^>]*>)?)?`+String.raw`\s+implements\s+[^{]*\bAppModule\b`,`g`),ai=/export\s+const\s+(\w+)\s*(?::\s*[^=]+)?=\s*defineModule\s*(?:<[^>]*>)?\s*\(/g,oi=/(?:export\s+)?const\s+(\w+)\s*(?::\s*[^=]+)?=\s*createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,si=/createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,ci=/@Inject\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,li=/\b(defineAdapter|definePlugin)\s*(?:<[^>]*>)?\s*\(/g,ui=/\b(?:defineContextDecorator|defineHttpContextDecorator)\s*(?:\.withParams\s*<(?:[^<>]|<[^<>]*>)*>\s*\(\s*\))?\s*(?:<(?:[^<>]|<[^<>]*>)*>)?\s*\(/g,di=new RegExp(String.raw`export\s+(?:default\s+)?(?:abstract\s+)?class\s+(\w+)`+String.raw`(?:\s+extends\s+\w+(?:<[^>]*>)?)?`+String.raw`\s+implements\s+[^{]*\bAppAdapter\b`,`g`),fi=/\bname\s*(?::\s*[^=]+)?=\s*['"`]([^'"`]+)['"`]/,pi=/\bdefineAugmentation\s*\(\s*['"`]([^'"`]+)['"`]\s*(,\s*\{)?/g,mi=new RegExp(String.raw`@(${[`Get`,`Post`,`Put`,`Delete`,`Patch`].join(`|`)})\s*\(`,`g`);function hi(e,t){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 gi(e,t){let n=t;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==`@`)break;let t=e.slice(n).match(/^@([A-Z]\w*)/);if(!t)break;for(n+=t[0].length;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]===`(`){let t=hi(e,n);if(t<0)return null;n=t+1}}for(;n<e.length&&/\s/.test(e[n]);)n++;for(let t of[`public`,`private`,`protected`])if(e.slice(n,n+t.length)===t&&/\s/.test(e.charAt(n+t.length))){for(n+=t.length;n<e.length&&/\s/.test(e[n]);)n++;break}if(e.slice(n,n+5)===`async`&&/\s/.test(e.charAt(n+5)))for(n+=5;n<e.length&&/\s/.test(e[n]);)n++;let r=e.slice(n).match(/^([a-zA-Z_]\w*)\s*\(/);return r?{methodName:r[1],endPos:n+r[0].length}:null}function _i(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function vi(e,t){let n=e.endsWith(`/`)?e.slice(0,-1):e;return!t||t===`/`?n||`/`:n+(t.startsWith(`/`)?t:`/`+t)||`/`}const yi=/\b(?:public\s+|private\s+|protected\s+)?routes\s*\([^)]*\)\s*(?::\s*[A-Za-z_][\w<>[\]\s,|]*\s*)?\{/g,bi=/\bpath\s*:\s*['"`]([^'"`]*)['"`]/g,xi=/\bcontroller\s*:\s*([A-Z]\w*)\b/g,Si=/\bimport\.meta\.glob\s*\(/g;function Ci(e){let t=[];for(Si.lastIndex=0;Si.exec(e)!==null;){let n=Si.lastIndex-1,r=hi(e,n);if(r<0)continue;let i=e.slice(n+1,r),a=/['"`]([^'"`]+)['"`]/g,o;for(;(o=a.exec(i))!==null;)t.push(o[1])}return t}function wi(e){let t=e.replace(/[.+^$()|[\]\\]/g,`\\$&`).replace(/\?/g,`.`).replace(/\*\*\//g,`___DOUBLESTAR_SLASH___`).replace(/\*\*/g,`___DOUBLESTAR___`).replace(/\*/g,`[^/]*`).replace(/___DOUBLESTAR_SLASH___/g,`(?:.+/)?`).replace(/___DOUBLESTAR___/g,`.*`);return RegExp(`^`+t+`$`)}function Ti(e,t){let n=e.startsWith(`./`)?e:`./`+e,r=!1;for(let e of t){let t=e.startsWith(`!`);wi(t?e.slice(1):e).test(n)&&(r=!t)}return r}function Ei(e){let t=[];yi.lastIndex=0;let n;for(;(n=yi.exec(e))!==null;){let r=e.indexOf(`{`,n.index+n[0].length-1);if(r<0)continue;let i=Ri(e,r);if(i<0)continue;let a=e.slice(r+1,i),o=[];bi.lastIndex=0;let s;for(;(s=bi.exec(a))!==null;)o.push(s[1]??``);let c=[];xi.lastIndex=0;let l;for(;(l=xi.exec(a))!==null;)c.push(l[1]);let u=Math.min(o.length,c.length);for(let e=0;e<u;e++)t.push({controller:c[e],mountPath:o[e]})}return t}function Di(e,t){let n=new RegExp(String.raw`\b${t}\s*:\s*([A-Za-z_$][\w$]*)`,`g`).exec(e);return n?n[1]:null}function Oi(e,t){let n=new RegExp(String.raw`import\s*(?:type\s+)?\{[^}]*\b${t}\b[^}]*\}\s*from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);if(n)return n[1];let r=new RegExp(String.raw`import\s+(?:type\s+)?${t}\s+from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);if(r)return r[1];let i=new RegExp(String.raw`import\s*\*\s*as\s+${t}\s+from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);return i?i[1]:new RegExp(String.raw`(?:^|\n)\s*(?:export\s+)?const\s+${t}\b`).test(e)?``:null}function ki(e,t){let n=/@ApiQueryParams\s*\(\s*([\s\S]*?)\s*\)\s*$/.exec(e);if(!n){let n=/@ApiQueryParams\s*\(([\s\S]*?)\)/.exec(e);return n?Ai(n[1].trim(),t):null}return Ai(n[1].trim(),t)}function Ai(e,t){if(e.startsWith(`{`))return Mi(e);let n=/^([A-Za-z_]\w*)/.exec(e);if(n){let e=n[1],r=new RegExp(String.raw`const\s+${e}\s*(?::\s*[^=]+)?=\s*(\{[\s\S]*?\n\})`,`m`).exec(t);if(r)return Mi(r[1])}return{filterable:[],sortable:[],searchable:[]}}function ji(e,t){let n=new RegExp(String.raw`${t}\s*:\s*\[([\s\S]*?)\]`).exec(e);return n?Array.from(n[1].matchAll(/['"`]([^'"`]+)['"`]/g)).map(e=>e[1]):[]}function Mi(e){return{filterable:ji(e,`filterable`),sortable:ji(e,`sortable`),searchable:ji(e,`searchable`)}}async function Ni(e,t){let n=t.extensions??ti,r=t.exclude??ni,i=[],a;try{a=await oe(e,{withFileTypes:!0,encoding:`utf-8`})}catch{return i}for(let o of a){let a=h(e,o.name),s=_(t.cwd,a);r.some(e=>s.includes(e))||(o.isDirectory()?i.push(...await Ni(a,t)):o.isFile()&&n.some(e=>o.name.endsWith(e))&&i.push(a))}return i}function q(e,t){return _(t,e).split(y).join(`/`)}function Pi(e,t,n){let r=[],i=q(t,n);ri.lastIndex=0;let a;for(;(a=ri.exec(e))!==null;){let[,e,n,o]=a;r.push({className:o,decorator:e,filePath:t,relativePath:i,isDefault:!!n})}ii.lastIndex=0;let o;for(;(o=ii.exec(e))!==null;){let[,e,n]=o;r.some(e=>e.className===n&&e.filePath===t)||r.push({className:n,decorator:`Module`,filePath:t,relativePath:i,isDefault:!!e})}ai.lastIndex=0;let s;for(;(s=ai.exec(e))!==null;){let[,e]=s;r.some(n=>n.className===e&&n.filePath===t)||r.push({className:e,decorator:`Module`,filePath:t,relativePath:i,isDefault:!1})}return r}function Fi(e,t,n){let r=[],i=q(t,n),a=new Set;oi.lastIndex=0;let o;for(;(o=oi.exec(e))!==null;){let[e,n,s]=o;a.add(e),r.push({name:s,variable:n,filePath:t,relativePath:i})}for(si.lastIndex=0;(o=si.exec(e))!==null;)a.has(o[0])||r.push({name:o[1],variable:null,filePath:t,relativePath:i});return r}function Ii(e,t,n,r,i=new Map){let a=[];if(r.length===0)return a;let o=q(t,n),s=[];for(let t of r){let n=new RegExp(String.raw`class\s+${t.className}\b`).exec(e);n?.index!==void 0&&s.push({cls:t,start:n.index})}s.sort((e,t)=>e.start-t.start);for(let n=0;n<s.length;n++){let{cls:r,start:c}=s[n],l=n+1<s.length?s[n+1].start:e.length,u=e.slice(c,l);mi.lastIndex=0;let d;for(;(d=mi.exec(u))!==null;){let n=d[1],s=d.index,c=mi.lastIndex-1,l=hi(u,c);if(l<0)continue;let f=u.slice(c+1,l),p=f.match(/^\s*['"`]([^'"`]*)['"`]/),m=p&&p[1].length>0?p[1]:`/`,h=gi(u,l+1);if(!h)continue;let{methodName:g,endPos:_}=h;mi.lastIndex=_;let v=ki(u.slice(s,_),e),y=Di(f,`body`),b=Di(f,`query`),x=Di(f,`params`),ee=i.get(r.className)??``,S=ee?vi(ee,m):m;a.push({controller:r.className,method:g,httpMethod:n.toUpperCase(),path:m,pathParams:_i(S),queryFilterable:v?.filterable??null,querySortable:v?.sortable??null,querySearchable:v?.searchable??null,bodySchema:y?{identifier:y,source:Oi(e,y)}:null,querySchema:b?{identifier:b,source:Oi(e,b)}:null,paramsSchema:x?{identifier:x,source:Oi(e,x)}:null,filePath:t,relativePath:o,controllerIsDefaultExport:r.isDefault,mountedPath:S})}}return a}function Li(e,t,n){let r=[],i=q(t,n);ci.lastIndex=0;let a;for(;(a=ci.exec(e))!==null;)r.push({name:a[1],filePath:t,relativePath:i});return r}function Ri(e,t){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 zi(e,t,n){let r=[],i=q(t,n),a=new Set;li.lastIndex=0;let o;for(;(o=li.exec(e))!==null;){let n=o[1],s=li.lastIndex-1,c=hi(e,s);if(c<0)continue;let l=e.slice(s+1,c),u=/\bname\s*:\s*['"`]([^'"`]+)['"`]/.exec(l);if(!u)continue;let d=u[1],f=`${n}::${d}::${t}`;a.has(f)||(a.add(f),r.push({kind:n===`definePlugin`?`plugin`:`adapter`,name:d,filePath:t,relativePath:i}))}di.lastIndex=0;let s;for(;(s=di.exec(e))!==null;){let n=s.index,o=e.indexOf(`{`,n);if(o<0)continue;let c=Ri(e,o);if(c<0)continue;let l=e.slice(o+1,c),u=fi.exec(l);if(!u)continue;let d=u[1],f=`class::${d}::${t}`;a.has(f)||(a.add(f),r.push({kind:`adapter`,name:d,filePath:t,relativePath:i}))}return r}function Bi(e,t,n){let r=[],i=q(t,n),a=new Set;for(ui.lastIndex=0;ui.exec(e)!==null;){let n=ui.lastIndex-1,o=hi(e,n);if(o<0)continue;let s=e.slice(n+1,o),c=/\bkey\s*:\s*['"`]([^'"`]+)['"`]/.exec(s);if(!c)continue;let l=c[1];a.has(l)||(a.add(l),r.push({key:l,filePath:t,relativePath:i}))}return r}function Vi(e,t,n){let r=[],i=q(t,n);pi.lastIndex=0;let a;for(;(a=pi.exec(e))!==null;){let n=a[1],o=null,s=null;if(a[2]){let t=e.indexOf(`{`,a.index+a[0].length-1);if(t>=0){let n=Ri(e,t);if(n>=0){let r=e.slice(t+1,n);o=Hi(r,`description`),s=Hi(r,`example`)}}}r.push({name:n,description:o,example:s,filePath:t,relativePath:i})}return r}function Hi(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\`])`,`g`).exec(e);if(!n)return null;let r=n[1],i=n.index+n[0].length,a=i,o=null;for(;a<e.length;){let t=e[a];if(t===`\\`){a+=2;continue}if(t===r){o=e.slice(i,a);break}a++}return o===null?null:o.replace(/\\(.)/g,(e,t)=>t===`n`?`
|
|
2423
|
+
`),s.push(l),s}const Pr=[`classes`,`tokens`,`injects`,`pluginsAndAdapters`,`augmentations`,`contextKeys`,`routes`,`moduleMounts`,`globPatterns`];function Fr(e){if(!e||typeof e!=`object`)return!1;let t=e;return Pr.every(e=>Array.isArray(t[e]))}var Ir=class e{path;prev;next=new Map;nextSig=new Map;constructor(e,t){this.path=e,this.prev=t}static async load(t){let n=h(t,`scan.json`),r=new Map;try{let e=await w(n,`utf-8`),t=JSON.parse(e);if(t.version===2&&t.files)for(let[e,n]of Object.entries(t.files))n&&typeof n.sig==`string`&&Fr(n.extract)&&r.set(e,n)}catch{}return new e(n,r)}static async signature(e){try{let t=await ce(e);return`${t.mtimeMs}:${t.size}`}catch{return null}}get(e,t){let n=this.prev.get(e);return n&&n.sig===t?n.extract:null}set(e,t,n){this.next.set(e,n),this.nextSig.set(e,t)}cachedFiles(){return[...this.prev.keys()]}peek(e){return this.prev.get(e)?.extract??null}carry(e){let t=this.prev.get(e);return t?(this.next.set(e,t.extract),this.nextSig.set(e,t.sig),!0):!1}async save(){let e={};for(let[t,n]of this.next){let r=this.nextSig.get(t);r&&(e[t]={sig:r,extract:n})}let t={version:2,files:e};try{await ae(f(this.path),{recursive:!0}),await T(this.path,JSON.stringify(t),`utf-8`)}catch{}}};let Lr=null;function Rr(){return Lr??=new Set(ei),Lr}const zr=new Set([`Get`,`Post`,`Put`,`Delete`,`Patch`]);function H(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(H(e)){t(e);for(let n of Object.keys(e)){if(n===`type`)continue;let r=e[n];typeof r==`object`&&r&&U(r,t)}}}function W(e){if(!H(e))return null;if(e.type===`Literal`&&typeof e.value==`string`)return e.value;if(e.type===`TemplateLiteral`){let t=e.quasis,n=e.expressions;if(t?.length===1&&(n?.length??0)===0){let e=t[0].value?.cooked;return typeof e==`string`?e:null}}return null}function G(e){return H(e)&&e.type===`Identifier`?e.name:null}function Br(e){return G(e.callee)}function K(e,t){if(!e||e.type!==`ObjectExpression`)return null;for(let n of e.properties??[]){if(n.type!==`Property`)continue;let e=n.key;if((G(e)??(e.type===`Literal`?String(e.value):W(e)))===t)return n.value}return null}function Vr(e){let t=e.arguments?.[0];return H(t)&&t.type===`ObjectExpression`?t:null}function Hr(e,t){let n=K(e,t);if(!H(n)||n.type!==`ArrayExpression`)return[];let r=[];for(let e of n.elements??[]){let t=W(e);t!==null&&r.push(t)}return r}function Ur(e,t){return _(t,e).split(y).join(`/`)}function Wr(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function Gr(e,t){for(let n of e.implements??[]){let e=n.expression??n;if(G(e)===t)return!0;if(e.type===`TSQualifiedName`||e.type===`MemberExpression`){let n=e.right??e.property;if(n&&G(n)===t)return!0}}return!1}function Kr(e){return e.decorators??[]}function qr(e){let t=e.expression;if(!H(t)||t.type!==`CallExpression`)return null;let n=Br(t);return n?{name:n,call:t}:null}function Jr(e){let t=new Map,n=new Set;for(let r of e.body??[]){if(r.type===`ImportDeclaration`){let e=W(r.source)??``;for(let n of r.specifiers??[]){let r=G(n.local);r&&t.set(r,{source:e})}continue}let e=r.type===`VariableDeclaration`?r:r.type===`ExportNamedDeclaration`&&H(r.declaration)?r.declaration:null;if(H(e)&&e.type===`VariableDeclaration`)for(let t of e.declarations??[]){let e=G(t.id);e&&n.add(e)}}return{imports:t,topLevelConsts:n}}function Yr(e,t){let n=t.imports.get(e);return n?{identifier:e,source:n.source}:t.topLevelConsts.has(e)?{identifier:e,source:``}:{identifier:e,source:null}}function Xr(e,t,n){let r=G(K(e,t));return r?Yr(r,n):null}function Zr(e,t){for(let n of e){let e=qr(n);if(!e||e.name!==`ApiQueryParams`)continue;let r=e.call.arguments?.[0],i=null;if(H(r)&&r.type===`ObjectExpression`)i=r;else{let e=G(r);if(e){let n=t.get(e);n&&n.type===`ObjectExpression`&&(i=n)}}return{filterable:Hr(i,`filterable`),sortable:Hr(i,`sortable`),searchable:Hr(i,`searchable`)}}return null}function Qr(e,t,n){let r;try{let n=fe(t,e);if(n.errors.length>0)return null;r=n.program}catch{return null}let i=Ur(t,n),a=Jr(r),o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m=[],h=new Set,g=new Set,_=new Set,v=new Map;for(let e of r.body??[]){let t=e.type===`VariableDeclaration`?e:e.type===`ExportNamedDeclaration`&&H(e.declaration)?e.declaration:null;if(H(t)&&t.type===`VariableDeclaration`)for(let e of t.declarations??[]){let t=G(e.id);t&&H(e.init)&&v.set(t,e.init)}}let y=[];for(let e of r.body??[])if(e.type===`ExportNamedDeclaration`&&H(e.declaration)){let t=e.declaration;t.type===`ClassDeclaration`&&y.push({cls:t,isDefault:!1})}else if(e.type===`ExportDefaultDeclaration`&&H(e.declaration)){let t=e.declaration;t.type===`ClassDeclaration`&&y.push({cls:t,isDefault:!0})}for(let{cls:e,isDefault:n}of y){let r=G(e.id);if(!r)continue;let a=null;for(let t of Kr(e)){let e=qr(t);if(e&&Rr().has(e.name)){a=e.name;break}}a?o.push({className:r,decorator:a,filePath:t,relativePath:i,isDefault:n}):Gr(e,`AppModule`)&&o.push({className:r,decorator:`Module`,filePath:t,relativePath:i,isDefault:n})}for(let e of r.body??[]){if(e.type!==`ExportNamedDeclaration`||!H(e.declaration))continue;let n=e.declaration;if(n.type===`VariableDeclaration`)for(let e of n.declarations??[]){let n=G(e.id),r=e.init;!n||!H(r)||r.type!==`CallExpression`||Br(r)===`defineModule`&&(o.some(e=>e.className===n)||o.push({className:n,decorator:`Module`,filePath:t,relativePath:i,isDefault:!1}))}}U(r,e=>{if(e.type===`VariableDeclarator`){let n=e.init;if(H(n)&&n.type===`CallExpression`&&Br(n)===`createToken`){let r=W(n.arguments?.[0]);r!==null&&(_.add(n),s.push({name:r,variable:G(e.id),filePath:t,relativePath:i}))}return}if(e.type!==`CallExpression`){if(e.type===`Decorator`){let n=qr(e);if(n?.name===`Inject`){let e=W(n.call.arguments?.[0]);e!==null&&c.push({name:e,filePath:t,relativePath:i})}}return}let n=e.callee,r=Br(e);if(r===`createToken`&&!_.has(e)){let n=W(e.arguments?.[0]);n!==null&&s.push({name:n,variable:null,filePath:t,relativePath:i});return}if(r===`defineAdapter`||r===`definePlugin`){let n=W(K(Vr(e),`name`));if(n!==null){let e=r===`definePlugin`?`plugin`:`adapter`,a=`${r}::${n}::${t}`;h.has(a)||(h.add(a),l.push({kind:e,name:n,filePath:t,relativePath:i}))}return}if(r===`defineAugmentation`){let n=e.arguments??[],r=W(n[0]);if(r!==null){let e=H(n[1])&&n[1].type===`ObjectExpression`?n[1]:null;u.push({name:r,description:W(K(e,`description`)),example:W(K(e,`example`)),filePath:t,relativePath:i})}return}if(r===`defineContextDecorator`||r===`defineHttpContextDecorator`){let n=W(K(Vr(e),`key`));n!==null&&!g.has(n)&&(g.add(n),d.push({key:n,filePath:t,relativePath:i}));return}if(H(n)&&n.type===`CallExpression`){let r=n.callee;if(H(r)&&r.type===`MemberExpression`&&G(r.property)===`withParams`){let n=G(r.object);if(n===`defineContextDecorator`||n===`defineHttpContextDecorator`){let n=W(K(Vr(e),`key`));n!==null&&!g.has(n)&&(g.add(n),d.push({key:n,filePath:t,relativePath:i}))}}return}if(H(n)&&n.type===`MemberExpression`&&G(n.property)===`glob`){let t=n.object;H(t)&&t.type===`MetaProperty`&&U(e.arguments,e=>{let t=W(e);t!==null&&m.push(t)})}});let b=[];U(r,e=>{if(e.type===`ClassDeclaration`||e.type===`ClassExpression`){let t=G(e.id);t&&b.push({cls:e,className:t})}});for(let{cls:e,className:n}of b){let r=o.find(e=>e.className===n),s=e.body?.body;if(Gr(e,`AppAdapter`))for(let e of s??[]){if(e.type!==`PropertyDefinition`||G(e.key)!==`name`)continue;let n=W(e.value);if(n===null)continue;let r=`class::${n}::${t}`;h.has(r)||(h.add(r),l.push({kind:`adapter`,name:n,filePath:t,relativePath:i}));break}for(let e of s??[]){if(e.type!==`MethodDefinition`)continue;let o=G(e.key);if(!o)continue;if(o===`routes`){$r(e.value,p);continue}if(!r)continue;let s=Kr(e),c=Zr(s,v);for(let e of s){let s=qr(e);if(!s||!zr.has(s.name))continue;let l=s.call.arguments??[],u=W(l[0]),d=u&&u.length>0?u:`/`,p=H(l[1])&&l[1].type===`ObjectExpression`?l[1]:null;f.push({controller:n,method:o,httpMethod:s.name.toUpperCase(),path:d,pathParams:Wr(d),queryFilterable:c?.filterable??null,querySortable:c?.sortable??null,querySearchable:c?.searchable??null,bodySchema:Xr(p,`body`,a),querySchema:Xr(p,`query`,a),paramsSchema:Xr(p,`params`,a),responseSchema:Xr(p,`response`,a),filePath:t,relativePath:i,controllerIsDefaultExport:r.isDefault,mountedPath:d})}}}return U(r,e=>{if(e.type!==`Property`||G(e.key)!==`routes`)return;let t=e.value;H(t)&&(t.type===`FunctionExpression`||t.type===`ArrowFunctionExpression`)&&$r(t,p)}),{classes:o,tokens:s,injects:c,pluginsAndAdapters:l,augmentations:u,contextKeys:d,routes:f,moduleMounts:p,globPatterns:/\.module\.[mc]?[tj]sx?$/.test(t)?m:[]}}function $r(e,t){let n=[],r=[];U(e.body,e=>{if(e.type!==`Property`)return;let t=G(e.key);if(t===`path`){let t=W(e.value);t!==null&&n.push(t)}else if(t===`controller`){let t=G(e.value);t&&/^[A-Z]/.test(t)&&r.push(t)}});let i=Math.min(n.length,r.length);for(let e=0;e<i;e++)t.push({controller:r[e],mountPath:n[e]})}const ei=[`Service`,`Controller`,`Repository`,`Injectable`,`Component`,`Module`],ti=[`.ts`,`.tsx`,`.mts`,`.cts`],ni=[`node_modules`,`.kickjs`,`dist`,`build`,`.test.`,`.spec.`,`.d.ts`],ri=new RegExp(String.raw`@(${ei.join(`|`)})\s*\([^)]*\)`+String.raw`(?:\s*@[A-Z]\w*(?:\s*\([^)]*\))?)*`+String.raw`\s*export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`,`g`),ii=new RegExp(String.raw`export\s+(default\s+)?(?:abstract\s+)?class\s+(\w+)`+String.raw`(?:\s+extends\s+\w+(?:<[^>]*>)?)?`+String.raw`\s+implements\s+[^{]*\bAppModule\b`,`g`),ai=/export\s+const\s+(\w+)\s*(?::\s*[^=]+)?=\s*defineModule\s*(?:<[^>]*>)?\s*\(/g,oi=/(?:export\s+)?const\s+(\w+)\s*(?::\s*[^=]+)?=\s*createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,si=/createToken\s*(?:<[^>]*>)?\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,ci=/@Inject\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g,li=/\b(defineAdapter|definePlugin)\s*(?:<[^>]*>)?\s*\(/g,ui=/\b(?:defineContextDecorator|defineHttpContextDecorator)\s*(?:\.withParams\s*<(?:[^<>]|<[^<>]*>)*>\s*\(\s*\))?\s*(?:<(?:[^<>]|<[^<>]*>)*>)?\s*\(/g,di=new RegExp(String.raw`export\s+(?:default\s+)?(?:abstract\s+)?class\s+(\w+)`+String.raw`(?:\s+extends\s+\w+(?:<[^>]*>)?)?`+String.raw`\s+implements\s+[^{]*\bAppAdapter\b`,`g`),fi=/\bname\s*(?::\s*[^=]+)?=\s*['"`]([^'"`]+)['"`]/,pi=/\bdefineAugmentation\s*\(\s*['"`]([^'"`]+)['"`]\s*(,\s*\{)?/g,mi=new RegExp(String.raw`@(${[`Get`,`Post`,`Put`,`Delete`,`Patch`].join(`|`)})\s*\(`,`g`);function hi(e,t){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 gi(e,t){let n=t;for(;n<e.length;){for(;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]!==`@`)break;let t=e.slice(n).match(/^@([A-Z]\w*)/);if(!t)break;for(n+=t[0].length;n<e.length&&/\s/.test(e[n]);)n++;if(e[n]===`(`){let t=hi(e,n);if(t<0)return null;n=t+1}}for(;n<e.length&&/\s/.test(e[n]);)n++;for(let t of[`public`,`private`,`protected`])if(e.slice(n,n+t.length)===t&&/\s/.test(e.charAt(n+t.length))){for(n+=t.length;n<e.length&&/\s/.test(e[n]);)n++;break}if(e.slice(n,n+5)===`async`&&/\s/.test(e.charAt(n+5)))for(n+=5;n<e.length&&/\s/.test(e[n]);)n++;let r=e.slice(n).match(/^([a-zA-Z_]\w*)\s*\(/);return r?{methodName:r[1],endPos:n+r[0].length}:null}function _i(e){return(e.match(/:([a-zA-Z_]\w*)/g)??[]).map(e=>e.slice(1))}function vi(e,t){let n=e.endsWith(`/`)?e.slice(0,-1):e;return!t||t===`/`?n||`/`:n+(t.startsWith(`/`)?t:`/`+t)||`/`}const yi=/\b(?:public\s+|private\s+|protected\s+)?routes\s*\([^)]*\)\s*(?::\s*[A-Za-z_][\w<>[\]\s,|]*\s*)?\{/g,bi=/\bpath\s*:\s*['"`]([^'"`]*)['"`]/g,xi=/\bcontroller\s*:\s*([A-Z]\w*)\b/g,Si=/\bimport\.meta\.glob\s*\(/g;function Ci(e){let t=[];for(Si.lastIndex=0;Si.exec(e)!==null;){let n=Si.lastIndex-1,r=hi(e,n);if(r<0)continue;let i=e.slice(n+1,r),a=/['"`]([^'"`]+)['"`]/g,o;for(;(o=a.exec(i))!==null;)t.push(o[1])}return t}function wi(e){let t=e.replace(/[.+^$()|[\]\\]/g,`\\$&`).replace(/\?/g,`.`).replace(/\*\*\//g,`___DOUBLESTAR_SLASH___`).replace(/\*\*/g,`___DOUBLESTAR___`).replace(/\*/g,`[^/]*`).replace(/___DOUBLESTAR_SLASH___/g,`(?:.+/)?`).replace(/___DOUBLESTAR___/g,`.*`);return RegExp(`^`+t+`$`)}function Ti(e,t){let n=e.startsWith(`./`)?e:`./`+e,r=!1;for(let e of t){let t=e.startsWith(`!`);wi(t?e.slice(1):e).test(n)&&(r=!t)}return r}function Ei(e){let t=[];yi.lastIndex=0;let n;for(;(n=yi.exec(e))!==null;){let r=e.indexOf(`{`,n.index+n[0].length-1);if(r<0)continue;let i=Ri(e,r);if(i<0)continue;let a=e.slice(r+1,i),o=[];bi.lastIndex=0;let s;for(;(s=bi.exec(a))!==null;)o.push(s[1]??``);let c=[];xi.lastIndex=0;let l;for(;(l=xi.exec(a))!==null;)c.push(l[1]);let u=Math.min(o.length,c.length);for(let e=0;e<u;e++)t.push({controller:c[e],mountPath:o[e]})}return t}function Di(e,t){let n=new RegExp(String.raw`\b${t}\s*:\s*([A-Za-z_$][\w$]*)`,`g`).exec(e);return n?n[1]:null}function Oi(e,t){let n=new RegExp(String.raw`import\s*(?:type\s+)?\{[^}]*\b${t}\b[^}]*\}\s*from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);if(n)return n[1];let r=new RegExp(String.raw`import\s+(?:type\s+)?${t}\s+from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);if(r)return r[1];let i=new RegExp(String.raw`import\s*\*\s*as\s+${t}\s+from\s*['"\`]([^'"\`]+)['"\`]`).exec(e);return i?i[1]:new RegExp(String.raw`(?:^|\n)\s*(?:export\s+)?const\s+${t}\b`).test(e)?``:null}function ki(e,t){let n=/@ApiQueryParams\s*\(\s*([\s\S]*?)\s*\)\s*$/.exec(e);if(!n){let n=/@ApiQueryParams\s*\(([\s\S]*?)\)/.exec(e);return n?Ai(n[1].trim(),t):null}return Ai(n[1].trim(),t)}function Ai(e,t){if(e.startsWith(`{`))return Mi(e);let n=/^([A-Za-z_]\w*)/.exec(e);if(n){let e=n[1],r=new RegExp(String.raw`const\s+${e}\s*(?::\s*[^=]+)?=\s*(\{[\s\S]*?\n\})`,`m`).exec(t);if(r)return Mi(r[1])}return{filterable:[],sortable:[],searchable:[]}}function ji(e,t){let n=new RegExp(String.raw`${t}\s*:\s*\[([\s\S]*?)\]`).exec(e);return n?Array.from(n[1].matchAll(/['"`]([^'"`]+)['"`]/g)).map(e=>e[1]):[]}function Mi(e){return{filterable:ji(e,`filterable`),sortable:ji(e,`sortable`),searchable:ji(e,`searchable`)}}async function Ni(e,t){let n=t.extensions??ti,r=t.exclude??ni,i=[],a;try{a=await oe(e,{withFileTypes:!0,encoding:`utf-8`})}catch{return i}for(let o of a){let a=h(e,o.name),s=_(t.cwd,a);r.some(e=>s.includes(e))||(o.isDirectory()?i.push(...await Ni(a,t)):o.isFile()&&n.some(e=>o.name.endsWith(e))&&i.push(a))}return i}function q(e,t){return _(t,e).split(y).join(`/`)}function Pi(e,t,n){let r=[],i=q(t,n);ri.lastIndex=0;let a;for(;(a=ri.exec(e))!==null;){let[,e,n,o]=a;r.push({className:o,decorator:e,filePath:t,relativePath:i,isDefault:!!n})}ii.lastIndex=0;let o;for(;(o=ii.exec(e))!==null;){let[,e,n]=o;r.some(e=>e.className===n&&e.filePath===t)||r.push({className:n,decorator:`Module`,filePath:t,relativePath:i,isDefault:!!e})}ai.lastIndex=0;let s;for(;(s=ai.exec(e))!==null;){let[,e]=s;r.some(n=>n.className===e&&n.filePath===t)||r.push({className:e,decorator:`Module`,filePath:t,relativePath:i,isDefault:!1})}return r}function Fi(e,t,n){let r=[],i=q(t,n),a=new Set;oi.lastIndex=0;let o;for(;(o=oi.exec(e))!==null;){let[e,n,s]=o;a.add(e),r.push({name:s,variable:n,filePath:t,relativePath:i})}for(si.lastIndex=0;(o=si.exec(e))!==null;)a.has(o[0])||r.push({name:o[1],variable:null,filePath:t,relativePath:i});return r}function Ii(e,t,n,r,i=new Map){let a=[];if(r.length===0)return a;let o=q(t,n),s=[];for(let t of r){let n=new RegExp(String.raw`class\s+${t.className}\b`).exec(e);n?.index!==void 0&&s.push({cls:t,start:n.index})}s.sort((e,t)=>e.start-t.start);for(let n=0;n<s.length;n++){let{cls:r,start:c}=s[n],l=n+1<s.length?s[n+1].start:e.length,u=e.slice(c,l);mi.lastIndex=0;let d;for(;(d=mi.exec(u))!==null;){let n=d[1],s=d.index,c=mi.lastIndex-1,l=hi(u,c);if(l<0)continue;let f=u.slice(c+1,l),p=f.match(/^\s*['"`]([^'"`]*)['"`]/),m=p&&p[1].length>0?p[1]:`/`,h=gi(u,l+1);if(!h)continue;let{methodName:g,endPos:_}=h;mi.lastIndex=_;let v=ki(u.slice(s,_),e),y=Di(f,`body`),b=Di(f,`query`),x=Di(f,`params`),S=Di(f,`response`),C=i.get(r.className)??``,ee=C?vi(C,m):m;a.push({controller:r.className,method:g,httpMethod:n.toUpperCase(),path:m,pathParams:_i(ee),queryFilterable:v?.filterable??null,querySortable:v?.sortable??null,querySearchable:v?.searchable??null,bodySchema:y?{identifier:y,source:Oi(e,y)}:null,querySchema:b?{identifier:b,source:Oi(e,b)}:null,paramsSchema:x?{identifier:x,source:Oi(e,x)}:null,responseSchema:S?{identifier:S,source:Oi(e,S)}:null,filePath:t,relativePath:o,controllerIsDefaultExport:r.isDefault,mountedPath:ee})}}return a}function Li(e,t,n){let r=[],i=q(t,n);ci.lastIndex=0;let a;for(;(a=ci.exec(e))!==null;)r.push({name:a[1],filePath:t,relativePath:i});return r}function Ri(e,t){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 zi(e,t,n){let r=[],i=q(t,n),a=new Set;li.lastIndex=0;let o;for(;(o=li.exec(e))!==null;){let n=o[1],s=li.lastIndex-1,c=hi(e,s);if(c<0)continue;let l=e.slice(s+1,c),u=/\bname\s*:\s*['"`]([^'"`]+)['"`]/.exec(l);if(!u)continue;let d=u[1],f=`${n}::${d}::${t}`;a.has(f)||(a.add(f),r.push({kind:n===`definePlugin`?`plugin`:`adapter`,name:d,filePath:t,relativePath:i}))}di.lastIndex=0;let s;for(;(s=di.exec(e))!==null;){let n=s.index,o=e.indexOf(`{`,n);if(o<0)continue;let c=Ri(e,o);if(c<0)continue;let l=e.slice(o+1,c),u=fi.exec(l);if(!u)continue;let d=u[1],f=`class::${d}::${t}`;a.has(f)||(a.add(f),r.push({kind:`adapter`,name:d,filePath:t,relativePath:i}))}return r}function Bi(e,t,n){let r=[],i=q(t,n),a=new Set;for(ui.lastIndex=0;ui.exec(e)!==null;){let n=ui.lastIndex-1,o=hi(e,n);if(o<0)continue;let s=e.slice(n+1,o),c=/\bkey\s*:\s*['"`]([^'"`]+)['"`]/.exec(s);if(!c)continue;let l=c[1];a.has(l)||(a.add(l),r.push({key:l,filePath:t,relativePath:i}))}return r}function Vi(e,t,n){let r=[],i=q(t,n);pi.lastIndex=0;let a;for(;(a=pi.exec(e))!==null;){let n=a[1],o=null,s=null;if(a[2]){let t=e.indexOf(`{`,a.index+a[0].length-1);if(t>=0){let n=Ri(e,t);if(n>=0){let r=e.slice(t+1,n);o=Hi(r,`description`),s=Hi(r,`example`)}}}r.push({name:n,description:o,example:s,filePath:t,relativePath:i})}return r}function Hi(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\`])`,`g`).exec(e);if(!n)return null;let r=n[1],i=n.index+n[0].length,a=i,o=null;for(;a<e.length;){let t=e[a];if(t===`\\`){a+=2;continue}if(t===r){o=e.slice(i,a);break}a++}return o===null?null:o.replace(/\\(.)/g,(e,t)=>t===`n`?`
|
|
2398
2424
|
`:t===`t`?` `:t===`r`?`\r`:t)}const Ui=[`src/config/index.ts`,`src/config/env.ts`,`src/config.ts`,`src/env.ts`];async function Wi(e,t){let n=t===`src/env.ts`?Ui:[t];for(let t of n){let n=v(e,t),r;try{r=await w(n,`utf-8`)}catch{continue}if(!(!/\bdefineEnv\s*\(/.test(r)&&!/\bfrom(Zod|Valibot|Yup)\s*\(/.test(r))&&/export\s+default\b/.test(r)&&!/export\s+default\s+loadEnvFromSchema\s*\(/.test(r))return{filePath:n,relativePath:q(n,e)}}return null}function Gi(e){let t=new Map;for(let n of e){let e=t.get(n.className)??[];e.push(n),t.set(n.className,e)}let n=[];for(let[e,r]of t)new Set(r.map(e=>e.filePath)).size>1&&n.push({className:e,classes:r});return n.sort((e,t)=>e.className.localeCompare(t.className)),n}function Ki(e,t,n){return Qr(e,t,n)||qi(e,t,n)}function qi(e,t,n){let r=Pi(e,t,n);return{classes:r,tokens:Fi(e,t,n),injects:Li(e,t,n),pluginsAndAdapters:zi(e,t,n),augmentations:Vi(e,t,n),contextKeys:Bi(e,t,n),routes:Ii(e,t,n,r,new Map),moduleMounts:Ei(e),globPatterns:/\.module\.[mc]?[tj]sx?$/.test(t)?Ci(e):[]}}async function Ji(e,t,n){let r=n?await Ir.signature(e):null;if(n&&r){let t=n.get(e,r);if(t)return n.set(e,r,t),t}let i;try{i=await w(e,`utf-8`)}catch{return null}let a=Ki(i,e,t);return n&&r&&n.set(e,r,a),a}async function Yi(e,t,n){let r=[],i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let t=i++;if(t>=e.length)return;r[t]=await n(e[t],t)}});return await Promise.all(a),r}async function Xi(e){let t=(await Ni(v(e.root),e)).toSorted(),n=e.cacheDir?await Ir.load(e.cacheDir):null,r=$i(t,await Yi(t,16,t=>Ji(t,e.cwd,n))),i=await Wi(e.cwd,e.envFile??`src/env.ts`);return n&&await n.save(),{...r,env:i}}function Zi(e,t,n){let r=n.extensions??ti,i=n.exclude??ni;if(!e.startsWith(t+y)&&e!==t||!r.some(t=>e.endsWith(t)))return!1;let a=_(n.cwd,e);return!i.some(e=>a.includes(e))}async function Qi(e,t){if(!e.cacheDir)return Xi(e);let n=v(e.root),r=await Ir.load(e.cacheDir),i=r.cachedFiles();if(i.length===0)return Xi(e);let a=new Set(t.removed.map(t=>v(e.cwd,t))),o=t.changed.map(t=>v(e.cwd,t)).filter(t=>!a.has(t)&&Zi(t,n,e)),s=new Set(o),c=new Set(i);for(let e of s)c.add(e);for(let e of a)c.delete(e);let l=new Map;await Yi(o,16,async t=>{if(!c.has(t))return;let n=await Ir.signature(t),i;try{i=await w(t,`utf-8`)}catch{c.delete(t);return}let a=Ki(i,t,e.cwd);l.set(t,a),n&&r.set(t,n,a)});let u=[...c].toSorted(),d=$i(u,u.map(e=>l.get(e)||(r.carry(e),r.peek(e)))),f=await Wi(e.cwd,e.envFile??`src/env.ts`);return await r.save(),{...d,env:f}}function $i(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=[],l=new Map;for(let e of t)if(e)for(let{controller:t,mountPath:n}of e.moduleMounts)l.has(t)||l.set(t,n);let u=new Map;for(let d=0;d<e.length;d++){let f=t[d];if(f){n.push(...f.classes),i.push(...f.tokens),a.push(...f.injects),o.push(...f.pluginsAndAdapters),s.push(...f.augmentations),c.push(...f.contextKeys),f.globPatterns.length>0&&u.set(e[d],f.globPatterns);for(let e of f.routes){let t=l.get(e.controller);if(t){let n=vi(t,e.path);r.push({...e,pathParams:_i(n),mountedPath:n})}else r.push({...e,mountedPath:e.mountedPath??e.path})}}}let d=[];for(let[e,t]of u){if(!/\.module\.[mc]?[tj]sx?$/.test(e)||t.length===0)continue;let r=e.replaceAll(y,`/`),i=r.slice(0,r.lastIndexOf(`/`));for(let a of n){if(a.decorator===`Module`)continue;let n=a.filePath.replaceAll(y,`/`);n.startsWith(i+`/`)&&n!==r&&(Ti(n.slice(i.length+1),t)||d.push({className:a.className,filePath:a.filePath,relativePath:a.relativePath,moduleFilePath:e,decorator:a.decorator}))}}n.sort((e,t)=>e.className===t.className?e.relativePath.localeCompare(t.relativePath):e.className.localeCompare(t.className)),i.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),a.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),r.sort((e,t)=>e.controller.localeCompare(t.controller)||e.method.localeCompare(t.method)),o.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),s.sort((e,t)=>e.name.localeCompare(t.name)||e.relativePath.localeCompare(t.relativePath)),c.sort((e,t)=>e.key.localeCompare(t.key)||e.relativePath.localeCompare(t.relativePath));let f=Gi(n);return d.sort((e,t)=>e.relativePath.localeCompare(t.relativePath)||e.className.localeCompare(t.className)),{classes:n,routes:r,tokens:i,injects:a,collisions:f,pluginsAndAdapters:o,augmentations:s,contextKeys:c,orphanedClasses:d}}function ea(e){let t=e.lastIndexOf(`.`);return t<=0?{stem:e,ext:``}:{stem:e.slice(0,t),ext:e.slice(t+1)}}function ta(e){let t=e.replaceAll(`\\`,`/`),{stem:n,ext:r}=ea(t.slice(t.lastIndexOf(`/`)+1)),i=r||`ts`,a=n.lastIndexOf(`.`);return a>0?`./**/*.${n.slice(a+1)}.${i}`:`./**/*.${i}`}function na(e){let t=new Set;for(let n of e)t.add(ta(n.relativePath));return[...t].toSorted()}function ra(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r){if(t===`\\`){i++;continue}t===r&&(r=null);continue}if(t===`'`||t===`"`||t==="`")r=t;else if(t===`(`)n++;else if(t===`)`&&(n--,n===0))return i}return-1}function ia(e,t,n,r){let i=null;for(let a=n;a<r;a++){let n=e[a];if(i){if(n===`\\`){a++;continue}n===i&&(i=null);continue}if(n===`'`||n===`"`||n==="`")i=n;else if(n===t)return a}return-1}function aa(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r){if(t===`\\`){i++;continue}t===r&&(r=null);continue}if(t===`'`||t===`"`||t==="`")r=t;else if(t===`[`)n++;else if(t===`]`&&(n--,n===0))return i}return-1}function oa(e){let t=/\bimport\.meta\.glob\s*\(/g,n=[],r;for(;(r=t.exec(e))!==null;){let t=e.indexOf(`(`,r.index);if(t<0)continue;let i=ra(e,t);i<0||n.push({start:r.index,open:t,close:i})}return n}function sa(e,t){let n=oa(e);if(n.length===0)return null;let r=n.find(t=>/\beager\s*:\s*true\b/.test(e.slice(t.open,t.close+1)))??n[0],i=e.slice(r.start,r.close+1),a=new Set(Ci(i).map(e=>e.startsWith(`!`)?e.slice(1):e)),o=t.filter(e=>!a.has(e));if(o.length===0)return null;let s=o.map(e=>`'${e}'`).join(`, `),c=ia(e,`[`,r.open,r.close);if(c>=0){let t=aa(e,c);if(t<0||t>r.close)return null;let n=e.slice(0,t);return n+(/[[,]\s*$/.test(n)?``:`, `)+s+e.slice(t)}let l=/(['"`])((?:\\.|(?!\1).)*)\1/,u=e.slice(r.open+1,r.close),d=l.exec(u);if(!d)return null;let f=r.open+1+d.index,p=f+d[0].length;return e.slice(0,f)+`[${d[0]}, ${s}]`+e.slice(p)}const J="/* 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",ca=new Set([`Service`,`Repository`,`Injectable`,`Component`]);var la=class extends Error{collisions;constructor(e){super(ua(e)),this.name=`TokenCollisionError`,this.collisions=e}};function ua(e){let t=[`kick typegen: token collision detected`];for(let n of e){t.push(``),t.push(` ${n.classes.length} classes named '${n.className}':`);for(let e of n.classes)t.push(` - ${e.relativePath}`)}return t.push(``),t.push(`Resolutions:`),t.push(` (a) Rename one of the classes`),t.push(` (b) Use createToken<T>('namespaced/Name') and import the token explicitly — see @forinda/kickjs`),t.push(` (c) Pass --allow-duplicates to namespace the registry keys automatically`),t.push(` (e.g. 'modules/users/UserService' instead of 'UserService')`),t.join(`
|
|
2399
2425
|
`)}function da(e,t){let n=_(f(t),e).split(y).join(`/`);return n=n.replace(/\.(ts|tsx|mts|cts)$/i,``),n.startsWith(`.`)||(n=`./`+n),n}function fa(e){let t=e.relativePath.replace(/^src\//,``).replace(/\.(ts|tsx|mts|cts)$/i,``).split(`/`);t.pop();let n=t.join(`/`);return n?`${n}/${e.className}`:e.className}function pa(e,t,n){let r=new Set,i=[];for(let a of e){if(!ca.has(a.decorator))continue;let e=n.has(a.className)?fa(a):a.className;if(r.has(e))continue;r.add(e);let o=da(a.filePath,t),s=a.isDefault?`import('${o}').default`:`import('${o}').${a.className}`;i.push(` '${e}': ${s}`)}let a=i.length?i.join(`
|
|
2400
2426
|
`):" // (no services discovered yet — run `kick g service <name>` to add one)";return`${J}
|
|
@@ -2492,7 +2518,7 @@ ${Da(n,` `)}
|
|
|
2492
2518
|
|
|
2493
2519
|
export {}
|
|
2494
2520
|
`}const Ea=Symbol(`asset-leaf`);function Da(e,t){let n=Object.keys(e).toSorted(),r=[];for(let i of n){let n=e[i],a=Oa(i)?i:JSON.stringify(i);n===Ea?r.push(`${t}${a}: () => string`):(r.push(`${t}${a}: {`),r.push(Da(n,`${t} `)),r.push(`${t}}`))}return r.join(`
|
|
2495
|
-
`)}function Oa(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function ka(e){try{return c(e).isDirectory()}catch{return!1}}var Aa=k({runTypegen:()=>Ma,sweepStaleTypegen:()=>La,watchTypegen:()=>Ia,writeTypegenArtifacts:()=>Fa});function ja(e){let t=e.cwd??process.cwd();return{cwd:t,srcDir:v(t,e.srcDir??`src`),outDir:v(t,e.outDir??`.kickjs/types`),silent:e.silent??!1,allowDuplicates:e.allowDuplicates??!1,schemaValidator:e.schemaValidator??!1,envFile:e.envFile??`src/env.ts`}}async function Ma(e={}){let{cwd:t,srcDir:n,outDir:r,silent:i,allowDuplicates:a,envFile:o}=ja(e),s=Date.now(),c={root:n,cwd:t,cacheDir:e.noCache?void 0:v(t,`.kickjs`,`cache`),envFile:o===!1?void 0:o},l=e.changedFiles?await Qi(c,e.changedFiles):await Xi(c);if(l.collisions.length>0&&!a)throw new la(l.collisions);let u=wa(e.assetMap,t),d=[],f=[];if(e.runPlugins!==!1){try{let{runAllPluginTypegens:n}=await Promise.resolve().then(()=>Xa),{loadKickConfig:r}=await Promise.resolve().then(()=>we);d=await n({cwd:t,config:await r(t),silent:!0,changedFiles:e.changedFiles})}catch(e){if(!i){let t=e instanceof Error?e.message:String(e);console.warn(` kick typegen: plugin pipeline failed (${t}) — continuing`)}}f.push(...await Fa(r,d,i))}let p=Sa(l.tokens),m=Pa(l,u.count,f),h=Date.now()-s;if(!i){let e=r.replace(t+`/`,``),n=m.resolvedCollisions>0?`, ${m.resolvedCollisions} collisions namespaced`:``,i=m.envWritten?`, env typed`:``,a=m.pluginEntries>0?`, ${m.pluginEntries} plugins/adapters`:``,o=m.augmentationEntries>0?`, ${m.augmentationEntries} augmentations`:``,s=m.assetEntries>0?`, ${m.assetEntries} assets`:``;if(console.log(` kick typegen → ${m.serviceTokens} services, ${m.routeEntries} routes, ${m.moduleTokens} modules${a}${o}${s}${i}${n} → ${e} (${h}ms)`),p.length>0){console.warn(` kick typegen: ${p.length} token(s) don't match the §22.2 convention:`);for(let e of p){let t=e.variable?` [${e.variable}]`:``;console.warn(` '${e.token}' (${e.filePath})${t} — ${e.reason}`),e.suggestion&&console.warn(` → suggestion: ${e.suggestion}`)}}}return l.orphanedClasses.length>0&&await Na(l.orphanedClasses,{fix:e.fix??!1,silent:i}),{scan:l,result:m,tokenWarnings:p}}async function Na(e,{fix:t,silent:n}){let r=new Map;for(let t of e){let e=r.get(t.moduleFilePath)??[];e.push(t),r.set(t.moduleFilePath,e)}if(t){let e=0,t=[];for(let[i,a]of r){let r=na(a);try{let a=await w(i,`utf-8`),o=sa(a,r);o&&o!==a?(await T(i,o),e++,n||console.log(` kick typegen --fix: patched ${i}\n + ${r.join(`, `)}`)):t.push(i)}catch{t.push(i)}}if(!n&&(e>0&&console.log(` kick typegen --fix: updated ${e} module glob(s) — re-run typegen to pick up the now-loaded classes.`),t.length>0)){console.warn(` kick typegen --fix: could not auto-patch ${t.length} module(s) (no import.meta.glob() call found) — add the patterns by hand:`);for(let e of t){let t=r.get(e)??[];console.warn(` ${e}: ${na(t).join(`, `)}`)}}return}if(!n){console.warn(` kick typegen: ${e.length} decorated class(es) not matched by any module's import.meta.glob():`);for(let[e,t]of r){for(let e of t)console.warn(` @${e.decorator} ${e.className} (${e.relativePath})`);let n=na(t);console.warn(` → add to import.meta.glob([...]) in ${e}:`),console.warn(` ${n.map(e=>`'${e}'`).join(`, `)}`)}console.warn(" → or run `kick typegen --fix` to apply these automatically.")}}function Pa(e,t,n){let r=new Set(e.collisions.map(e=>e.className)),i=e.classes.filter(e=>ca.has(e.decorator)),a=_a(e.classes,e.tokens,e.injects,r);return{registryEntries:i.length,serviceTokens:new Set(a).size,moduleTokens:va(e.classes).length,routeEntries:e.routes.length,pluginEntries:new Set(e.pluginsAndAdapters.map(e=>e.name)).size,augmentationEntries:new Set(e.augmentations.map(e=>e.name)).size,assetEntries:t,envWritten:e.env!==null,written:n,resolvedCollisions:e.collisions.length}}async function Fa(e,t,n){await
|
|
2521
|
+
`)}function Oa(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function ka(e){try{return c(e).isDirectory()}catch{return!1}}var Aa=k({runTypegen:()=>Ma,sweepStaleTypegen:()=>La,watchTypegen:()=>Ia,writeTypegenArtifacts:()=>Fa});function ja(e){let t=e.cwd??process.cwd();return{cwd:t,srcDir:v(t,e.srcDir??`src`),outDir:v(t,e.outDir??`.kickjs/types`),silent:e.silent??!1,allowDuplicates:e.allowDuplicates??!1,schemaValidator:e.schemaValidator??!1,envFile:e.envFile??`src/env.ts`}}async function Ma(e={}){let{cwd:t,srcDir:n,outDir:r,silent:i,allowDuplicates:a,envFile:o}=ja(e),s=Date.now(),c={root:n,cwd:t,cacheDir:e.noCache?void 0:v(t,`.kickjs`,`cache`),envFile:o===!1?void 0:o},l=e.changedFiles?await Qi(c,e.changedFiles):await Xi(c);if(l.collisions.length>0&&!a)throw new la(l.collisions);let u=wa(e.assetMap,t),d=[],f=[];if(e.runPlugins!==!1){try{let{runAllPluginTypegens:n}=await Promise.resolve().then(()=>Xa),{loadKickConfig:r}=await Promise.resolve().then(()=>we);d=await n({cwd:t,config:await r(t),silent:!0,changedFiles:e.changedFiles})}catch(e){if(!i){let t=e instanceof Error?e.message:String(e);console.warn(` kick typegen: plugin pipeline failed (${t}) — continuing`)}}f.push(...await Fa(r,d,i))}let p=Sa(l.tokens),m=Pa(l,u.count,f),h=Date.now()-s;if(!i){let e=r.replace(t+`/`,``),n=m.resolvedCollisions>0?`, ${m.resolvedCollisions} collisions namespaced`:``,i=m.envWritten?`, env typed`:``,a=m.pluginEntries>0?`, ${m.pluginEntries} plugins/adapters`:``,o=m.augmentationEntries>0?`, ${m.augmentationEntries} augmentations`:``,s=m.assetEntries>0?`, ${m.assetEntries} assets`:``;if(console.log(` kick typegen → ${m.serviceTokens} services, ${m.routeEntries} routes, ${m.moduleTokens} modules${a}${o}${s}${i}${n} → ${e} (${h}ms)`),p.length>0){console.warn(` kick typegen: ${p.length} token(s) don't match the §22.2 convention:`);for(let e of p){let t=e.variable?` [${e.variable}]`:``;console.warn(` '${e.token}' (${e.filePath})${t} — ${e.reason}`),e.suggestion&&console.warn(` → suggestion: ${e.suggestion}`)}}}return l.orphanedClasses.length>0&&await Na(l.orphanedClasses,{fix:e.fix??!1,silent:i}),{scan:l,result:m,tokenWarnings:p}}async function Na(e,{fix:t,silent:n}){let r=new Map;for(let t of e){let e=r.get(t.moduleFilePath)??[];e.push(t),r.set(t.moduleFilePath,e)}if(t){let e=0,t=[];for(let[i,a]of r){let r=na(a);try{let a=await w(i,`utf-8`),o=sa(a,r);o&&o!==a?(await T(i,o),e++,n||console.log(` kick typegen --fix: patched ${i}\n + ${r.join(`, `)}`)):t.push(i)}catch{t.push(i)}}if(!n&&(e>0&&console.log(` kick typegen --fix: updated ${e} module glob(s) — re-run typegen to pick up the now-loaded classes.`),t.length>0)){console.warn(` kick typegen --fix: could not auto-patch ${t.length} module(s) (no import.meta.glob() call found) — add the patterns by hand:`);for(let e of t){let t=r.get(e)??[];console.warn(` ${e}: ${na(t).join(`, `)}`)}}return}if(!n){console.warn(` kick typegen: ${e.length} decorated class(es) not matched by any module's import.meta.glob():`);for(let[e,t]of r){for(let e of t)console.warn(` @${e.decorator} ${e.className} (${e.relativePath})`);let n=na(t);console.warn(` → add to import.meta.glob([...]) in ${e}:`),console.warn(` ${n.map(e=>`'${e}'`).join(`, `)}`)}console.warn(" → or run `kick typegen --fix` to apply these automatically.")}}function Pa(e,t,n){let r=new Set(e.collisions.map(e=>e.className)),i=e.classes.filter(e=>ca.has(e.decorator)),a=_a(e.classes,e.tokens,e.injects,r);return{registryEntries:i.length,serviceTokens:new Set(a).size,moduleTokens:va(e.classes).length,routeEntries:e.routes.length,pluginEntries:new Set(e.pluginsAndAdapters.map(e=>e.name)).size,augmentationEntries:new Set(e.augmentations.map(e=>e.name)).size,assetEntries:t,envWritten:e.env!==null,written:n,resolvedCollisions:e.collisions.length}}async function Fa(e,t,n){await ae(e,{recursive:!0}),await T(h(f(e),`.gitignore`),`# Auto-generated by kick typegen
|
|
2496
2522
|
*
|
|
2497
2523
|
`,`utf-8`);let r=t.filter(e=>e.outFile).map(e=>e.outFile);return await La(e,r,t,n),r}async function Ia(e={}){let t=ja(e),{srcDir:n,silent:r,cwd:i}=t,a={...t,allowDuplicates:!0,runPlugins:!1,noCache:e.noCache},o=process.env.KICKJS_WATCH_POLLING===`1`||process.env.KICKJS_WATCH_POLLING===`true`,[{runAllPluginTypegens:s},{loadKickConfig:c}]=await Promise.all([Promise.resolve().then(()=>Xa),Promise.resolve().then(()=>we)]),l=await c(i),u=async()=>{try{await Ma({...a})}catch(e){if(r)return;if(e instanceof la)console.error(`
|
|
2498
2524
|
`+e.message+`
|
|
@@ -2521,9 +2547,9 @@ export {}
|
|
|
2521
2547
|
Usage: kick g scaffold <name> <field:type> [field:type...]
|
|
2522
2548
|
Example: kick g scaffold Post title:string body:text:optional published:boolean:optional
|
|
2523
2549
|
Optional: append :optional (shell-safe, no quoting needed)
|
|
2524
|
-
`),process.exit(1));let a=await j(process.cwd()),o=A(a),s=n.modulesDir??o.dir??`src/modules`,c=Or(t),l=Ae(a,process.cwd()),u=await kr({name:e,fields:c,modulesDir:v(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:l,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)`:``}`);X(u,i),await Ba(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=Y(t);M(n),X(await ir({outDir:v(`.`),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=Y(t);M(n);let r=e.only??`all`;if(!za.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${za.join(` | `)}`),process.exitCode=1;return}X(await dr({outDir:v(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])Ka(n,e,t?.projectRoot)}function Ka(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=Y(o);M(s);let c=await mn({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&X(c.files,s)})}async function qa(e){let t=u.resolve(e.cwd,`.kickjs/types`);await
|
|
2550
|
+
`),process.exit(1));let a=await j(process.cwd()),o=A(a),s=n.modulesDir??o.dir??`src/modules`,c=Or(t),l=Ae(a,process.cwd()),u=await kr({name:e,fields:c,modulesDir:v(s),noEntity:n.entity===!1,noTests:n.tests===!1,pluralize:n.pluralize===!1?!1:o.pluralize??!0,tokenScope:l,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)`:``}`);X(u,i),await Ba(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=Y(t);M(n),X(await ir({outDir:v(`.`),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=Y(t);M(n);let r=e.only??`all`;if(!za.includes(r)){console.error(` Invalid --only value: ${r}. Expected: ${za.join(` | `)}`),process.exitCode=1;return}X(await dr({outDir:v(`.`),only:r,name:e.name,pm:e.pm,template:e.template,force:e.force}),n)});for(let e of t?.generators??[])Ka(n,e,t?.projectRoot)}function Ka(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=Y(o);M(s);let c=await mn({generatorName:i.name,itemName:e??``,args:r??[],flags:a,cwd:process.cwd(),projectRoot:n},[t]);c&&X(c.files,s)})}async function qa(e){let t=u.resolve(e.cwd,`.kickjs/types`);await ae(t,{recursive:!0});let n=new Map,i=e.scan??Xi,a=u.resolve(e.cwd,`.kickjs`,`cache`),o=e.scan?void 0:e.changedFiles,s={cwd:e.cwd,config:e.config,async importTs(e){return await import(x(e).href)},async writeFile(t,n){let r=u.resolve(e.cwd,t);await ae(u.dirname(r),{recursive:!0}),await T(r,n,`utf8`)},getScanResult:e=>{let t=Ja(e),r=n.get(t);if(!r){let s={cacheDir:a,...e};r=o?Qi(s,o):i(s),n.set(t,r)}return r},log:console},c=[];for(let n of e.plugins){let i=n.outExtension??`.d.ts`,a=u.join(t,`${n.id.replace(/\//g,`__`)}${i}`),o;try{o=await n.generate(s)}catch(e){let t=e instanceof Error?e.message:String(e);s.log.error(` ${n.id}: typegen failed (${t}) — keeping previous output`),c.push({id:n.id,status:`error`,outFile:a});continue}if(o===null){c.push({id:n.id,status:`skipped`});continue}let l=`/* AUTO-GENERATED by kick typegen — do not edit. Plugin: ${n.id} */\n\n`+o+`
|
|
2525
2551
|
`,d=``;if(r(a)&&(d=await w(a,`utf8`)),d===l){c.push({id:n.id,status:`unchanged`,outFile:a});continue}if(e.check)throw Error(`kick typegen --check: drift detected for ${n.id} (${a})`);await T(a,l,`utf8`),c.push({id:n.id,status:`written`,outFile:a})}return c}function Ja(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 Ya(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 Xa=k({applyDisableFilter:()=>Ya,runAllPluginTypegens:()=>Qa});function Za(){let e=(process.env.LOG_LEVEL??process.env.KICKJS_LOG_LEVEL??``).toLowerCase();return e===`debug`||e===`trace`}async function Qa(e){let{enabled:t,skipped:n,unknown:r}=Ya(Ie([...Cc,...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 qa({cwd:e.cwd,config:e.config??{},plugins:t,check:e.check,changedFiles:e.changedFiles});if(!e.silent&&Za())for(let e of n)console.log(` ${e.id}: ${e.status}`);return n}catch(t){if(!e.silent){let e=t instanceof Error?t.message:String(t);console.warn(` kick typegen plugins: skipped (${e})`)}return[]}}var $a=k({ASSET_MANIFEST_VERSION:()=>1,buildAssets:()=>eo});async function eo(e,t){let{cwd:n,silent:r=!1}=t,a=t.distDir??e?.build?.outDir??`dist`,o=e?.assetMap;if(!o||Object.keys(o).length===0)return null;let s=r?()=>{}:console.log,c=v(n,a);i(c,{recursive:!0});let u=[],d={};for(let[e,t]of Object.entries(o)){let r=await to(e,t,n,c);u.push(r.entrySummary),Object.assign(d,r.manifestSlice),s(` ✓ ${e}: ${r.entrySummary.filesCopied} file(s) → ${r.entrySummary.dest}`)}let f={version:1,entries:d},p=h(c,`.kickjs-assets.json`);return l(p,JSON.stringify(f,null,2)+`
|
|
2526
|
-
`,`utf-8`),s(` ✓ wrote manifest → ${_(n,p)} (${Object.keys(d).length} entries)`),{manifestPath:p,entries:u,manifest:f}}async function to(e,t,a,o){let s=v(a,t.src),c=t.dest?v(a,t.dest):h(o,e);if(io(c,a))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};if(!r(s)||!ao(s))return{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};let l=await pe(t.glob??`**/*`,{cwd:s,nodir:!0,dot:!1,posix:!0});i(c,{recursive:!0});let u={},{pairs:d,collisionGroupsResolved:p}=he(e,[...l].toSorted(),{strategy:t.keys??`auto`}),m=0;for(let{rel:e,key:t}of d){let r=h(s,e),a=h(c,e);u[t]=ro(o,a),!no(r,a)&&(i(f(a),{recursive:!0}),n(r,a),m++)}return p>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${p} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:m},manifestSlice:u}}function no(e,t){if(!r(t))return!1;try{let n=c(e),r=c(t);return r.size===n.size&&r.mtimeMs>=n.mtimeMs}catch{return!1}}function ro(e,t){return _(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function io(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function ao(e){try{return c(e).isDirectory()}catch{return!1}}function oo(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 so(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await Promise.resolve().then(()=>Aa)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Xa)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await Promise.resolve().then(()=>Aa)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await Promise.resolve().then(()=>$a)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=u.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=>u.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,d=e=>e.replaceAll(`\\`,`/`),f=c.map(d),p=e=>{let t=d(e);return f.some(e=>t===e||t.startsWith(`${e}/`))},m=oo(e.emitWarning),h=null,g=!1,_=new Set,v=new Set,y=!1,b=!1;function x(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(()=>m.clear(`scan`)).catch(e=>m.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>m.clear(`plugins`)).catch(e=>m.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function
|
|
2552
|
+
`,`utf-8`),s(` ✓ wrote manifest → ${_(n,p)} (${Object.keys(d).length} entries)`),{manifestPath:p,entries:u,manifest:f}}async function to(e,t,a,o){let s=v(a,t.src),c=t.dest?v(a,t.dest):h(o,e);if(io(c,a))return console.warn(` ⚠ assetMap.${e}.dest ('${t.dest}') resolves outside the project root — skipping copy`),{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};if(!r(s)||!ao(s))return{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:0},manifestSlice:{}};let l=await pe(t.glob??`**/*`,{cwd:s,nodir:!0,dot:!1,posix:!0});i(c,{recursive:!0});let u={},{pairs:d,collisionGroupsResolved:p}=he(e,[...l].toSorted(),{strategy:t.keys??`auto`}),m=0;for(let{rel:e,key:t}of d){let r=h(s,e),a=h(c,e);u[t]=ro(o,a),!no(r,a)&&(i(f(a),{recursive:!0}),n(r,a),m++)}return p>0&&console.log(` ℹ assetMap.${e}: auto-resolved ${p} basename collision(s) by keeping extensions (set 'keys: "strip"' to opt back into legacy last-write-wins behaviour, or 'keys: "with-extension"' to keep all keys verbose).`),{entrySummary:{namespace:e,src:t.src,dest:_(a,c),filesCopied:m},manifestSlice:u}}function no(e,t){if(!r(t))return!1;try{let n=c(e),r=c(t);return r.size===n.size&&r.mtimeMs>=n.mtimeMs}catch{return!1}}function ro(e,t){return _(e,t).split(/[\\/]/).filter(Boolean).join(`/`)}function io(e,t){let n=_(t,e);return n===``?!1:n.startsWith(`..`)||m(n)}function ao(e){try{return c(e).isDirectory()}catch{return!1}}function oo(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 so(e){let{cwd:t,config:n}=e,r=e.debounceMs??100,i=e.pipeline??{runTypegen:async e=>(await Promise.resolve().then(()=>Aa)).runTypegen(e),runAllPluginTypegens:async e=>(await Promise.resolve().then(()=>Xa)).runAllPluginTypegens(e),writeTypegenArtifacts:async(e,t,n)=>(await Promise.resolve().then(()=>Aa)).writeTypegenArtifacts(e,t,n),buildAssets:async(e,t)=>(await Promise.resolve().then(()=>$a)).buildAssets(e,t)},a=n?.typegen?.schemaValidator??`zod`,o=n?.typegen?.envFile,s=u.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=>u.resolve(t,e)):[],l=!!n?.assetMap&&Object.keys(n.assetMap).length>0,d=e=>e.replaceAll(`\\`,`/`),f=c.map(d),p=e=>{let t=d(e);return f.some(e=>t===e||t.startsWith(`${e}/`))},m=oo(e.emitWarning),h=null,g=!1,_=new Set,v=new Set,y=!1,b=!1;function x(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(()=>m.clear(`scan`)).catch(e=>m.report(`scan`,e)),i.runAllPluginTypegens({cwd:t,config:n,silent:!0,changedFiles:r}).then(e=>i.writeTypegenArtifacts(s,e,!0)).then(()=>m.clear(`plugins`)).catch(e=>m.report(`plugins`,e)).finally(()=>e.onPassComplete?.()),c&&n&&i.buildAssets(n,{cwd:t,silent:!0}).catch(()=>{})}function S(){let e=y?void 0:{changed:[..._],removed:[...v]},t=b;_.clear(),v.clear(),y=!1,b=!1,x(e,t)}return{assetSrcRoots:c,handleWatchEvent(e,t){if(!g&&!d(t).includes(`/.kickjs/`)){if(e===`unlinkDir`)y=!0,l&&(b=!0);else{if(t.endsWith(`.d.ts`))return;let n=/\.(ts|tsx|mts|cts)$/.test(t),r=p(t);if(!n&&!r)return;r&&l&&(b=!0),n&&(e===`unlink`?(v.add(t),_.delete(t)):(_.add(t),v.delete(t)))}h&&clearTimeout(h),h=setTimeout(S,r)}},runOnce(){g||x(void 0,l)},dispose(){g=!0,h&&clearTimeout(h),h=null}}}function co(e){let t=h(e,`node_modules`,`.bin`),n=process.platform===`win32`;for(let e of[`tsgo`,`tsc`]){let i=n?[`${e}.CMD`,`${e}.cmd`,`${e}.exe`]:[e];for(let a of i){let i=h(t,a);if(r(i))return{cmd:i,args:[`--noEmit`],shell:n,kind:e}}}return null}function lo(e){let t=e.spawnFn??te,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 uo(e,t=12){let n=e.trim().split(/\r?\n/);return n.length<=t?n.join(`
|
|
2527
2553
|
`):`${n.slice(0,t).join(`
|
|
2528
2554
|
`)}\n… ${n.length-t} more line(s)`}function fo(e){if(typeof e==`boolean`)return e;let t=process.env.KICKJS_WATCH_POLLING;return t===`1`||t===`true`}async function po(e,t,n={}){t&&(process.env.PORT=t);let r=fo(n.polling),i=process.cwd(),a=await j(i),o=a?.typegen?.schemaValidator??`zod`,s=a?.typegen?.envFile;try{await Ma({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=v(i,a?.typegen?.outDir??`.kickjs/types`);try{await Fa(c,await Qa({cwd:i,config:a}),!1)}catch(e){console.warn(` kick typegen: plugin pass skipped (${e?.message??e})`)}let{createRequire:l}=await import(`node:module`),{createServer:u}=await import(x(l(v(`package.json`)).resolve(`vite`)).href);globalThis.__kickjs_typegen_owner=`kick-dev`;let d=await u({configFile:v(`vite.config.ts`),server:{port:t?parseInt(t,10):void 0,...r?{watch:{usePolling:!0,interval:100}}:{}}}),f=n.typecheck??a?.dev?.typecheck??!1,p=null,m=!0;if(f){let e=co(i);e?p=lo({cwd:i,bin:e,onResult:e=>{d.hot.send({type:`custom`,event:`kickjs:typecheck`,data:{ok:e.ok,output:e.output,durationMs:e.durationMs}}),e.ok?m||(m=!0,console.log(` kick typecheck: clean again (${e.kind}, ${e.durationMs}ms)`)):(m=!1,console.warn(`\n kick typecheck (${e.kind}, ${e.durationMs}ms):`),console.warn(uo(e.output).replace(/^/gm,` `)))}}):console.warn(` kick dev: --typecheck requested but neither tsgo (@typescript/native-preview) nor typescript is installed in this project — skipping type checks.`)}let h=so({cwd:i,config:a,emitWarning:e=>{console.warn(e),d.hot.send({type:`custom`,event:`kickjs:typegen-error`,data:{message:e,timestamp:Date.now()}})},onPassComplete:()=>p?.schedule()});d.watcher.on(`add`,e=>h.handleWatchEvent(`add`,e)),d.watcher.on(`unlink`,e=>h.handleWatchEvent(`unlink`,e)),d.watcher.on(`change`,e=>h.handleWatchEvent(`change`,e)),d.watcher.on(`unlinkDir`,e=>h.handleWatchEvent(`unlinkDir`,e)),h.assetSrcRoots.length>0&&d.watcher.add([...h.assetSrcRoots]),await d.listen(),d.printUrls(),console.log(`
|
|
2529
2555
|
KickJS dev server running (Vite + @forinda/kickjs-vite)
|
|
@@ -2652,10 +2678,10 @@ Pass a message as a positional arg, --message flag, or pipe via stdin:
|
|
|
2652
2678
|
|
|
2653
2679
|
`)}function qo(e,t){return e.split(`
|
|
2654
2680
|
`).map(e=>`${t}${e}`).join(`
|
|
2655
|
-
`)}function Jo(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Yo(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Xo(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(Zo),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(Qo)}function Zo(e){let t=v(e.entry);r(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],i=
|
|
2681
|
+
`)}function Jo(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function Yo(e){return e>=90?`high confidence`:e>=70?`good match`:e>=50?`medium confidence`:`low confidence — verify manually`}function Xo(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(Zo),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(Qo)}function Zo(e){let t=v(e.entry);r(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],i=te(process.execPath,n,{stdio:`inherit`,env:{...process.env,KICK_MCP_STDIO:`1`,NODE_ENV:process.env.NODE_ENV??`production`}});i.on(`error`,e=>{process.stderr.write(`Failed to start MCP server: ${e.message}\n`),process.exit(1)}),i.on(`exit`,(e,t)=>{if(t){process.kill(process.pid,t);return}process.exit(e??0)});let a=e=>{i.killed||i.kill(e)};process.on(`SIGINT`,()=>a(`SIGINT`)),process.on(`SIGTERM`,()=>a(`SIGTERM`))}function Qo(e){let t=process.cwd(),n=$o(t)??d(t),i=e.name??n,o=e.global?v(process.env.HOME??`.`,`.mcp.json`):v(t,e.out),s={command:`kick`,args:[`mcp`],cwd:t},c={mcpServers:{}};if(r(o))try{let e=a(o,`utf8`),t=JSON.parse(e);t&&typeof t==`object`&&t.mcpServers&&(c={mcpServers:{...t.mcpServers}})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`Error: existing ${o} is not valid JSON (${t}).\nFix the file or pass --force to overwrite the entry.\n`),process.exit(1)}c.mcpServers[i]&&!e.force&&(process.stderr.write(`Error: an entry for "${i}" already exists in ${o}.\nPass --force to overwrite it, or use --name to pick a different key.\n`),process.exit(1)),c.mcpServers[i]=s,l(o,JSON.stringify(c,null,2)+`
|
|
2656
2682
|
`,`utf8`),process.stdout.write(`\n ✓ Wrote MCP server entry "${i}" to ${o}\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 $o(e){let t=v(e,`package.json`);if(!r(t))return null;try{let e=a(t,`utf8`),n=JSON.parse(e);return typeof n.name==`string`?n.name:null}catch{return null}}function es(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=v(t,e.entry);r(n)||(console.error(`\n Error: ${e.entry} not found.\n`),process.exit(1));let i=ns(t,`tsx`);i||(console.error(`
|
|
2657
2683
|
Error: tsx not found. Install it: pnpm add -D tsx
|
|
2658
|
-
`),process.exit(1));let a=ts(n,e.entry),o=h(t,`.kick-tinker.mjs`),{writeFileSync:s,unlinkSync:c}=await import(`node:fs`);s(o,a,`utf-8`);try{let e=
|
|
2684
|
+
`),process.exit(1));let a=ts(n,e.entry),o=h(t,`.kick-tinker.mjs`),{writeFileSync:s,unlinkSync:c}=await import(`node:fs`);s(o,a,`utf-8`);try{let e=ee(o,[],{cwd:t,execPath:i,stdio:`inherit`});await new Promise(t=>{e.on(`exit`,()=>t())})}finally{try{c(o)}catch{}}})}function ts(e,t){return`
|
|
2659
2685
|
import 'reflect-metadata'
|
|
2660
2686
|
|
|
2661
2687
|
// Prevent bootstrap() from starting the HTTP server
|
|
@@ -2751,10 +2777,13 @@ declare global {
|
|
|
2751
2777
|
// first route exists (fresh project / pre-controller typegen runs).
|
|
2752
2778
|
interface Api {}
|
|
2753
2779
|
}
|
|
2780
|
+
|
|
2781
|
+
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
2782
|
+
type KickApi = KickRoutes.Api
|
|
2754
2783
|
}
|
|
2755
2784
|
|
|
2756
2785
|
export {}
|
|
2757
|
-
`;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=tc(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??$s(e),u
|
|
2786
|
+
`;let i=new Map;for(let t of e){let e=i.get(t.controller)??[];e.push(t),i.set(t.controller,e)}let a=new Map,o=new Map,s=e=>{let t=`${e.filePath}::${e.controller}`,n=o.get(t);return n||(n=`_C${o.size}`,o.set(t,n)),n},c=(e,i,o)=>{let s=tc(e,i.filePath,t,n,a);if(!s){if(e&&n!==!1){let t=o===`params`?`URL-pattern params`:o===`query`&&i.queryFilterable!==null?`the @ApiQueryParams-derived query shape`:`'unknown'`;r.onWarn?.(`route ${i.controller}.${i.method} (${i.httpMethod} ${i.path}): ${o} schema '${e.identifier}' could not be statically resolved — falling back to ${t}. Export the schema from the controller file or import it with a static specifier.`)}return null}return n===`kickjs-schema`?`import('@forinda/kickjs-schema').InferSchemaOutput<typeof ${s}>`:`import('zod').infer<typeof ${s}>`},l=[];for(let[e,t]of i){let n=[` interface ${e} {`];for(let e of t){let t=e.pathParams.length>0?`{ ${e.pathParams.map(e=>`${e}: string`).join(`; `)} }`:`{}`,r=c(e.bodySchema,e,`body`),i=c(e.querySchema,e,`query`),a=c(e.paramsSchema,e,`params`)??t,o=r??`unknown`,l=i??$s(e),u=c(e.responseSchema??null,e,`response`),d=s(e),f=u??`import('@forinda/kickjs').InferHandlerResponse<${d}['${e.method}']>`,p=ec(e);n.push(` /**`,` * ${e.httpMethod} ${e.path}`,...p.map(e=>` * ${e}`),` */`,` ${e.method}: {`,` params: ${a}`,` body: ${o}`,` query: ${l}`,` response: ${f}`,` }`)}n.push(` }`),l.push(n.join(`
|
|
2758
2787
|
`))}let u=[],d=new Set;i.has(`Api`)&&r.onWarn?.(`controller class 'Api' collides with the reserved KickRoutes.Api client map — its interface declaration-merges into the flat route map. Rename the controller.`);for(let[e,t]of i)for(let n of t){let t=`${n.httpMethod} ${n.mountedPath??n.path}`;if(d.has(t)){r.onWarn?.(`duplicate route '${t}' (${e}.${n.method}) — two handlers claim the same verb+path at runtime. KickRoutes.Api keeps the first (scan order, which may not match runtime dispatch); resolve the conflict in the modules.`);continue}d.add(t),u.push(` '${t}': ${e}['${n.method}']`)}let f=[` interface Api {`,...u,` }`].join(`
|
|
2759
2788
|
`);l.push(f);let p=[],m=new Map;for(let t of e)m.set(`${t.filePath}::${t.controller}`,t);for(let[e,n]of o){let r=m.get(e),i=rc(``,r.filePath,t),a=r.controllerIsDefaultExport?`default as ${n}`:`${r.controller} as ${n}`;p.push(`import type { ${a} } from '${i}'`)}let h=p.length>0?p.join(`
|
|
2760
2789
|
`)+`
|
|
@@ -2765,6 +2794,9 @@ declare global {
|
|
|
2765
2794
|
namespace KickRoutes {
|
|
2766
2795
|
${_}
|
|
2767
2796
|
}
|
|
2797
|
+
|
|
2798
|
+
/** Short alias for \`KickRoutes.Api\` — \`createClient<KickApi>(...)\`. */
|
|
2799
|
+
type KickApi = KickRoutes.Api
|
|
2768
2800
|
}
|
|
2769
2801
|
|
|
2770
2802
|
export {}
|
|
@@ -2809,4 +2841,4 @@ declare global {
|
|
|
2809
2841
|
|
|
2810
2842
|
export {}
|
|
2811
2843
|
`}const cc=()=>({id:`kick/env`,outExtension:`.ts`,inputs:[`src/env.ts`,`src/**/env.ts`,`src/**/*.env.ts`],async generate(e){let t=uc(e);if(t===!1)return null;let n=await e.getScanResult({root:lc(e),cwd:e.cwd,envFile:t});if(!n.env)return null;let r=e.config?.typegen?.schemaValidator??`zod`,i=u.resolve(e.cwd,`.kickjs/types/kick__env.ts`);return sc(n.env,i,r)}});function lc(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function uc(e){return e.config?.typegen?.envFile}function dc(e){return u.resolve(e.cwd,e.config?.typegen?.srcDir??`src`)}function fc(e){let t=e.config?.typegen?.envFile;if(t!==!1)return t}function pc(e){return{root:dc(e),cwd:e.cwd,envFile:fc(e)}}const mc=()=>({id:`kick/registry`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(pc(e)),n=u.resolve(e.cwd,`.kickjs/types/kick__registry.d.ts`),r=new Set(t.collisions.map(e=>e.className));return pa(t.classes,n,r)}}),hc=()=>({id:`kick/services`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(pc(e)),n=new Set(t.collisions.map(e=>e.className));return ga(`ServiceToken`,_a(t.classes,t.tokens,t.injects,n),"(no tokens discovered — declare with createToken<T>() or `kick g service <name>`)")}}),gc=()=>({id:`kick/modules`,inputs:[`src/**/*.ts`],async generate(e){return ga(`ModuleToken`,va((await e.getScanResult(pc(e))).classes),"(no @Module classes discovered — `kick g module <name>` to add one)")}}),_c=()=>({id:`kick/plugins`,inputs:[`src/**/*.ts`],async generate(e){return ya((await e.getScanResult(pc(e))).pluginsAndAdapters)}}),vc=()=>({id:`kick/augmentations`,inputs:[`src/**/*.ts`],async generate(e){return ba((await e.getScanResult(pc(e))).augmentations)}}),yc=()=>({id:`kick/context`,inputs:[`src/**/*.ts`],async generate(e){let t=await e.getScanResult(pc(e));return t.contextKeys.length===0?null:ha(t.contextKeys)}}),bc={fastify:{subpath:`@forinda/kickjs/fastify`,typeName:`FastifyRuntimeTypes`},h3:{subpath:`@forinda/kickjs/h3`,typeName:`H3RuntimeTypes`}},xc=()=>({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}=bc[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(`
|
|
2812
|
-
`)}});var Sc=k({builtinCliPlugins:()=>Cc});const Cc=[E({name:`kick/init`,register:$t}),E({name:`kick/generate`,register:Ga}),E({name:`kick/run`,register:mo}),E({name:`kick/info`,register:yo}),E({name:`kick/inspect`,register:ko}),E({name:`kick/add`,register:Mt}),E({name:`kick/list`,register:jt}),E({name:`kick/explain`,register:zo}),E({name:`kick/mcp`,register:Xo}),E({name:`kick/tinker`,register:es}),E({name:`kick/remove`,register:os}),E({name:`kick/typegen`,register:ls}),E({name:`kick/check`,register:xs}),E({name:`kick/doctor`,register:qs}),E({name:`kick/codemod`,register:Ys}),E({name:`kick/registry`,typegens:[mc()]}),E({name:`kick/services`,typegens:[hc()]}),E({name:`kick/modules`,typegens:[gc()]}),E({name:`kick/plugins`,typegens:[_c()]}),E({name:`kick/augmentations`,typegens:[vc()]}),E({name:`kick/context`,typegens:[yc()]}),E({name:`kick/assets`,typegens:[Xs()]}),E({name:`kick/routes`,typegens:[ic()]}),E({name:`kick/env`,typegens:[cc()]}),E({name:`kick/runtime`,typegens:[xc()]})],wc=f(b(import.meta.url)),Tc=JSON.parse(a(h(wc,`..`,`package.json`),`utf-8`));async function Ec(){let e=new t;e.name(`kick`).description(`KickJS — A production-grade, decorator-driven Node.js framework`).version(Tc.version);let n=rn(process.cwd()),r=n,i=await j(r)??{},a=Ie([...Cc,...i.plugins??[]],i.commands??[]);await a.register(e,{cwd:r,projectRoot:n,config:i,log:e=>console.log(e)}),Se(e,{...i,commands:a.commands}),e.showHelpAfterError();let o=process.argv.map(e=>e===`-v`?`--version`:e);await e.parseAsync(o)}Ec().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{N as i,
|
|
2844
|
+
`)}});var Sc=k({builtinCliPlugins:()=>Cc});const Cc=[E({name:`kick/init`,register:$t}),E({name:`kick/generate`,register:Ga}),E({name:`kick/run`,register:mo}),E({name:`kick/info`,register:yo}),E({name:`kick/inspect`,register:ko}),E({name:`kick/add`,register:Mt}),E({name:`kick/list`,register:jt}),E({name:`kick/explain`,register:zo}),E({name:`kick/mcp`,register:Xo}),E({name:`kick/tinker`,register:es}),E({name:`kick/remove`,register:os}),E({name:`kick/typegen`,register:ls}),E({name:`kick/check`,register:xs}),E({name:`kick/doctor`,register:qs}),E({name:`kick/codemod`,register:Ys}),E({name:`kick/registry`,typegens:[mc()]}),E({name:`kick/services`,typegens:[hc()]}),E({name:`kick/modules`,typegens:[gc()]}),E({name:`kick/plugins`,typegens:[_c()]}),E({name:`kick/augmentations`,typegens:[vc()]}),E({name:`kick/context`,typegens:[yc()]}),E({name:`kick/assets`,typegens:[Xs()]}),E({name:`kick/routes`,typegens:[ic()]}),E({name:`kick/env`,typegens:[cc()]}),E({name:`kick/runtime`,typegens:[xc()]})],wc=f(b(import.meta.url)),Tc=JSON.parse(a(h(wc,`..`,`package.json`),`utf-8`));async function Ec(){let e=new t;e.name(`kick`).description(`KickJS — A production-grade, decorator-driven Node.js framework`).version(Tc.version);let n=rn(process.cwd()),r=n,i=await j(r)??{},a=Ie([...Cc,...i.plugins??[]],i.commands??[]);await a.register(e,{cwd:r,projectRoot:n,config:i,log:e=>console.log(e)}),Se(e,{...i,commands:a.commands}),e.showHelpAfterError();let o=process.argv.map(e=>e===`-v`?`--version`:e);await e.parseAsync(o)}Ec().catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});export{N as a,Lt as i,ar as n,Ht as r,Aa as t};
|