@forinda/kickjs-cli 5.8.1 → 5.8.3
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-BskiyzHm.mjs +12 -0
- package/dist/agent-docs-BskiyzHm.mjs.map +1 -0
- package/dist/{builtins-CF4q3JIg.mjs → builtins-DxlD3Bnh.mjs} +2 -2
- package/dist/cli.mjs +63 -312
- package/dist/{config-v6vsVMtc.mjs → config-DKQcNKrg.mjs} +3 -3
- package/dist/{config-v6vsVMtc.mjs.map → config-DKQcNKrg.mjs.map} +1 -1
- package/dist/generator-extension-CVVCnF6w.mjs +1977 -0
- package/dist/generator-extension-CVVCnF6w.mjs.map +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-1Oiz9_TD.mjs → plugin-HGOpDF54.mjs} +3 -3
- package/dist/{plugin-1Oiz9_TD.mjs.map → plugin-HGOpDF54.mjs.map} +1 -1
- package/dist/project-docs-DRR0mSJy.mjs +858 -0
- package/dist/project-docs-DRR0mSJy.mjs.map +1 -0
- package/dist/{project-root-BaUzB3D7.mjs → project-root-XvkHzCRu.mjs} +3 -3
- package/dist/{project-root-BaUzB3D7.mjs.map → project-root-XvkHzCRu.mjs.map} +1 -1
- package/dist/{rolldown-runtime-vNCSDkuE.mjs → rolldown-runtime-07ZxtVND.mjs} +1 -1
- package/dist/{run-plugins-Bg8kTYfa.mjs → run-plugins-BE1Dakam.mjs} +99 -99
- package/dist/run-plugins-BE1Dakam.mjs.map +1 -0
- package/dist/{typegen-B8lAhWXz.mjs → typegen-BK-C_dMm.mjs} +4 -4
- package/dist/{typegen-B8lAhWXz.mjs.map → typegen-BK-C_dMm.mjs.map} +1 -1
- package/dist/{types-BG2NeDgK.mjs → types-d0QsibKA.mjs} +2 -2
- package/dist/{types-BG2NeDgK.mjs.map → types-d0QsibKA.mjs.map} +1 -1
- package/package.json +7 -7
- package/dist/generator-extension-ChoCJW23.mjs +0 -3072
- package/dist/generator-extension-ChoCJW23.mjs.map +0 -1
- package/dist/run-plugins-Bg8kTYfa.mjs.map +0 -1
|
@@ -0,0 +1,858 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-cli v5.8.3
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import{createRequire as e}from"node:module";import{dirname as t,extname as n,join as r}from"node:path";import{existsSync as i}from"node:fs";import{access as a,mkdir as o,readFile as s,writeFile as c}from"node:fs/promises";import*as l from"@clack/prompts";import u from"picocolors";let d=!1;function f(e){d=e}const p=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`,`.md`]);async function m(e,r){d||(await o(t(e),{recursive:!0}),await c(e,r,`utf-8`),p.has(n(e))&&await _(e,r).catch(()=>{}))}let h;async function g(t){if(h!==void 0)return h;try{h=await import(e(r(t,`package.json`)).resolve(`oxfmt`))}catch{h=null}return h}async function _(e,t){let n=await g(process.cwd());if(!n)return;let r=await y(e);if(r===null)return;let i=await n.format(e,t,r);i.code!==t&&await c(e,i.code,`utf-8`)}const v=new Map;async function y(e){let n=t(e),a=n;if(v.has(a))return v.get(a);for(;;){let e=r(n,`.oxfmtrc.json`);if(i(e))try{let t=await s(e,`utf-8`),n=JSON.parse(t);return delete n.$schema,delete n.ignorePatterns,v.set(a,n),n}catch{return v.set(a,null),null}let o=t(n);if(o===n)return v.set(a,null),null;n=o}}async function b(e){try{return await a(e),!0}catch{return!1}}const x={GET:u.green,POST:u.cyan,PUT:u.yellow,PATCH:u.magenta,DELETE:u.red};function S(e){return(x[e]??u.dim)(e.padEnd(7))}function C(e){let t=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return u.red(t);case`WARNING`:return u.yellow(t);case`INFO`:return u.blue(u.dim(t));default:return t}}u.green(`✓`),u.red(`✖`),u.yellow(`⚠`),u.blue(`ℹ`);function w(e){l.intro(u.bgCyan(u.black(` ${e} `)))}function T(e){l.outro(e)}function E(e){l.isCancel(e)&&(l.cancel(`Operation cancelled.`),process.exit(0))}async function D(e){let t=await l.text(e);return E(t),t}async function O(e){let t=await l.select(e);return E(t),t}async function k(e){let t=await l.multiselect(e);return E(t),t}async function A(e){let t=await l.confirm(e);return E(t),t}function j(){return l.spinner()}const M=l.log;function N(e,t,n){let r={rest:`REST API`,ddd:`Domain-Driven Design`,cqrs:`CQRS + Event-Driven`,minimal:`Minimal`},i=[`@forinda/kickjs`,`@forinda/kickjs-vite`];return t!==`minimal`&&i.push(`@forinda/kickjs-swagger`,`@forinda/kickjs-devtools`),t===`cqrs`&&i.push(`@forinda/kickjs-queue`,`@forinda/kickjs-ws`),`# ${e}
|
|
12
|
+
|
|
13
|
+
A **${r[t]??`REST API`}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
|
|
14
|
+
|
|
15
|
+
## Getting Started
|
|
16
|
+
|
|
17
|
+
\`\`\`bash
|
|
18
|
+
${n} install
|
|
19
|
+
kick dev
|
|
20
|
+
\`\`\`
|
|
21
|
+
|
|
22
|
+
## Scripts
|
|
23
|
+
|
|
24
|
+
| Command | Description |
|
|
25
|
+
|---|---|
|
|
26
|
+
| \`kick dev\` | Start dev server with Vite HMR |
|
|
27
|
+
| \`kick build\` | Production build |
|
|
28
|
+
| \`kick start\` | Run production build |
|
|
29
|
+
| \`${n} run test\` | Run tests with Vitest |
|
|
30
|
+
| \`kick g module <name>\` | Generate a DDD module |
|
|
31
|
+
| \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
|
|
32
|
+
| \`kick add <package>\` | Add a KickJS package |
|
|
33
|
+
|
|
34
|
+
## Project Structure
|
|
35
|
+
|
|
36
|
+
\`\`\`
|
|
37
|
+
src/
|
|
38
|
+
├── index.ts # Application entry point
|
|
39
|
+
├── modules/ # Feature modules (controllers, services, repos)
|
|
40
|
+
│ └── index.ts # Module registry
|
|
41
|
+
└── ...
|
|
42
|
+
\`\`\`
|
|
43
|
+
|
|
44
|
+
## Packages
|
|
45
|
+
|
|
46
|
+
${i.map(e=>`- \`${e}\``).join(`
|
|
47
|
+
`)}
|
|
48
|
+
|
|
49
|
+
## Adding Features
|
|
50
|
+
|
|
51
|
+
\`\`\`bash
|
|
52
|
+
kick add auth # Authentication (JWT, API key, OAuth)
|
|
53
|
+
kick add swagger # OpenAPI documentation
|
|
54
|
+
kick add ws # WebSocket support
|
|
55
|
+
kick add queue # Background job processing
|
|
56
|
+
kick add --list # Show all available packages
|
|
57
|
+
\`\`\`
|
|
58
|
+
|
|
59
|
+
For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://forinda.github.io/kick-js/guide/) — they wire the upstream library through \`defineAdapter()\` / \`definePlugin()\` directly, so you keep control of the integration.
|
|
60
|
+
|
|
61
|
+
## Environment Variables
|
|
62
|
+
|
|
63
|
+
Copy \`.env.example\` to \`.env\` and configure:
|
|
64
|
+
|
|
65
|
+
| Variable | Default | Description |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| \`PORT\` | \`3000\` | Server port |
|
|
68
|
+
| \`NODE_ENV\` | \`development\` | Environment |
|
|
69
|
+
|
|
70
|
+
## Learn More
|
|
71
|
+
|
|
72
|
+
- [KickJS Documentation](https://forinda.github.io/kick-js/)
|
|
73
|
+
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
74
|
+
`}function P(e,t,n){return`# CLAUDE.md — ${e}
|
|
75
|
+
|
|
76
|
+
**Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
|
|
77
|
+
reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
|
|
78
|
+
project conventions, structure, decorator patterns, env wiring, CLI
|
|
79
|
+
generators, every gotcha.
|
|
80
|
+
|
|
81
|
+
**Then browse \`./.agents/skills/\`.** Each subdirectory is a single
|
|
82
|
+
task-oriented skill (\`add-module/\`, \`write-controller-test/\`,
|
|
83
|
+
\`bootstrap-export/\`, \`deny-list/\`, …) containing a \`SKILL.md\`
|
|
84
|
+
with YAML frontmatter (\`name\`, \`description\`) and the recipe body.
|
|
85
|
+
The structure follows the Claude Code skills convention — agents that
|
|
86
|
+
auto-load skills from \`.agents/skills/\` will pick each up by its
|
|
87
|
+
frontmatter. Use this directory as the playbook when executing common
|
|
88
|
+
KickJS workflows.
|
|
89
|
+
|
|
90
|
+
This file is a thin Claude-specific layer on top of those two; when
|
|
91
|
+
they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
|
|
92
|
+
authoritative and flag the discrepancy.
|
|
93
|
+
|
|
94
|
+
## Why \`.agents/\` + this thin pointer
|
|
95
|
+
|
|
96
|
+
\`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
|
|
97
|
+
Copilot, Aider, …) — one canonical source so the prose doesn't drift
|
|
98
|
+
across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
|
|
99
|
+
project context on each conversation, so it stays at the project root.
|
|
100
|
+
Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
|
|
101
|
+
out-of-sync copies of the same content. Per-agent files
|
|
102
|
+
(\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
|
|
103
|
+
\`AGENTS.md\` for tool-specific notes that don't belong in the shared
|
|
104
|
+
prose.
|
|
105
|
+
|
|
106
|
+
## Claude-specific notes
|
|
107
|
+
|
|
108
|
+
- **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
|
|
109
|
+
to refresh project memory if AGENTS.md changes substantially.
|
|
110
|
+
- **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
|
|
111
|
+
- **Persistent memory** — Claude maintains user/feedback/project/
|
|
112
|
+
reference memories under \`.claude/memory/\`. If you ask for
|
|
113
|
+
something that contradicts a remembered preference, Claude flags
|
|
114
|
+
it before acting; corrections update memory automatically.
|
|
115
|
+
- **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
|
|
116
|
+
or background work. Useful for "wait for the deploy then open a
|
|
117
|
+
cleanup PR" or "every Monday triage the issue board" patterns.
|
|
118
|
+
|
|
119
|
+
## Quick reference (full version in .agents/AGENTS.md)
|
|
120
|
+
|
|
121
|
+
\`\`\`bash
|
|
122
|
+
${n} install # Install dependencies
|
|
123
|
+
kick dev # Dev server with HMR + typegen
|
|
124
|
+
kick build && kick start # Production
|
|
125
|
+
${n} run test # Vitest
|
|
126
|
+
${n} run typecheck # tsc --noEmit
|
|
127
|
+
${n} run format # Prettier
|
|
128
|
+
\`\`\`
|
|
129
|
+
|
|
130
|
+
## v4 framework reminders
|
|
131
|
+
|
|
132
|
+
When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
|
|
133
|
+
|
|
134
|
+
- **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
|
|
135
|
+
- **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
|
|
136
|
+
- **DI tokens**: \`<scope>/<PascalKey>[/<suffix>]\` — scope is lowercase, the key segment is **PascalCase** (e.g. \`'app/Users/repository'\`, \`'mycorp/Cache/redis'\`). First-party uses the reserved \`'kick/'\` prefix; this project owns its own scope.
|
|
137
|
+
- **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
|
|
138
|
+
- **Module entry file** MUST be named \`<name>.module.ts\` and live under \`src/modules/<name>/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed \`projects.ts\` silently degrades every save into a full restart.
|
|
139
|
+
- **Env**: schema lives in \`src/config/index.ts\`; \`import './config'\` MUST be the first import in \`src/index.ts\` (side-effect registers the schema before any \`@Value\` resolves).
|
|
140
|
+
- **Assets**: drop new template files into \`src/templates/<namespace>/\`; the dev watcher auto-rebuilds the \`KickAssets\` augmentation + \`assets.x.y()\` re-walks on next call. No restart, no manual build.
|
|
141
|
+
- **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
|
|
142
|
+
- **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
|
|
143
|
+
- **Bootstrap export**: \`src/index.ts\` must end with \`export const app = await bootstrap({ ... })\`. The Vite plugin and \`createTestApp\` import the named \`app\`; without the export, HMR silently degrades to full restarts.
|
|
144
|
+
- **Thin entry file**: aggregate \`modules\`, \`middleware\`, \`plugins\`, \`adapters\` in their own folders (\`src/modules/index.ts\`, \`src/middleware/index.ts\`, …) and pass them by name to \`bootstrap()\` — never inline the lists in \`src/index.ts\`.
|
|
145
|
+
- **Refresh these files**: \`kick g agents -f\` regenerates \`CLAUDE.md\` at the project root and \`.agents/AGENTS.md\` + \`.agents/GEMINI.md\` + \`.agents/COPILOT.md\` + every \`.agents/skills/<name>/SKILL.md\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \`.agents/AGENTS.local.md\` or per-skill \`SKILL.local.md\` files alongside.
|
|
146
|
+
|
|
147
|
+
For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
|
|
148
|
+
`}function F(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
|
|
149
|
+
|
|
150
|
+
This guide is the **canonical, multi-agent reference** for this KickJS
|
|
151
|
+
application — Claude, Copilot, Codex, Gemini, etc. all read it first.
|
|
152
|
+
Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
|
|
153
|
+
add tool-specific affordances on top.
|
|
154
|
+
|
|
155
|
+
## Before You Start
|
|
156
|
+
|
|
157
|
+
1. Run \`${n} install\` to install dependencies
|
|
158
|
+
2. Run \`kick dev\` to verify the app starts
|
|
159
|
+
3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
|
|
160
|
+
|
|
161
|
+
## v4 Conventions (don't skip)
|
|
162
|
+
|
|
163
|
+
KickJS v4 made a handful of structural changes from v3. Internalise these
|
|
164
|
+
before generating or modifying code — they are the source of most agent
|
|
165
|
+
mistakes:
|
|
166
|
+
|
|
167
|
+
- **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
|
|
168
|
+
|
|
169
|
+
\`\`\`ts
|
|
170
|
+
export const MyAdapter = defineAdapter<MyOptions>({
|
|
171
|
+
name: 'MyAdapter',
|
|
172
|
+
defaults: { ... },
|
|
173
|
+
build: (config) => ({
|
|
174
|
+
beforeMount({ app }) { /* ... */ },
|
|
175
|
+
afterStart({ server }) { /* ... */ },
|
|
176
|
+
}),
|
|
177
|
+
})
|
|
178
|
+
\`\`\`
|
|
179
|
+
|
|
180
|
+
- **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
|
|
181
|
+
|
|
182
|
+
- **DI tokens** — \`<scope>/<PascalKey>[/<suffix>]\`. Scope is lowercase,
|
|
183
|
+
the key segment is **PascalCase** (the regex enforces both):
|
|
184
|
+
|
|
185
|
+
\`\`\`ts
|
|
186
|
+
const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
|
|
187
|
+
const DB = createToken<Database>('app/Db/connection')
|
|
188
|
+
\`\`\`
|
|
189
|
+
|
|
190
|
+
The \`kick/\` prefix is reserved for first-party packages; this project
|
|
191
|
+
owns its own scope (\`app/\`, your domain name, etc.).
|
|
192
|
+
|
|
193
|
+
- **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
|
|
194
|
+
the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
|
|
195
|
+
is a v3 leftover; the linter and codegen reject it.
|
|
196
|
+
|
|
197
|
+
- **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
|
|
198
|
+
side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
|
|
199
|
+
import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
|
|
200
|
+
returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
|
|
201
|
+
(Zod coercion + defaults silently skipped).
|
|
202
|
+
|
|
203
|
+
- **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
|
|
204
|
+
HMR contract at the top of "Module Pattern" below. The CLI enforces this;
|
|
205
|
+
hand-rolled files must too.
|
|
206
|
+
|
|
207
|
+
- **Assets** — drop new template files into \`src/templates/<namespace>/\`
|
|
208
|
+
(or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
|
|
209
|
+
\`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
|
|
210
|
+
no manual build step.
|
|
211
|
+
|
|
212
|
+
- **Context over \`@Middleware()\`** — when a middleware's only job is to
|
|
213
|
+
populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
|
|
214
|
+
(HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
|
|
215
|
+
Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
|
|
216
|
+
Reserve \`@Middleware()\` for response short-circuit / stream mutation /
|
|
217
|
+
pre-route-matching work.
|
|
218
|
+
|
|
219
|
+
Two ground rules around the data flow — both stem from the fact that
|
|
220
|
+
every per-request stage gets its OWN \`RequestContext\` instance, all
|
|
221
|
+
reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
|
|
222
|
+
- **\`resolve\` and \`onError\` must RETURN the value.** The runner
|
|
223
|
+
writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
|
|
224
|
+
property assignment (\`ctx.tenant = …\`) sticks to the contributor
|
|
225
|
+
instance only — the handler instance never sees it.
|
|
226
|
+
- **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
|
|
227
|
+
\`getRequestValue(key)\` from a service that has no \`ctx\` reference
|
|
228
|
+
— typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
|
|
229
|
+
Express request is shared; bespoke property assignments don't.
|
|
230
|
+
|
|
231
|
+
- **Test isolation** — default to \`Container.create()\` for fresh DI state.
|
|
232
|
+
Never \`new Container()\` and never \`getInstance().reset()\` — both leak
|
|
233
|
+
registrations between tests.
|
|
234
|
+
|
|
235
|
+
\`\`\`ts
|
|
236
|
+
const container = Container.create()
|
|
237
|
+
// ... register test-scoped providers, run, discard
|
|
238
|
+
\`\`\`
|
|
239
|
+
|
|
240
|
+
- **Bootstrap export** — \`src/index.ts\` MUST end with
|
|
241
|
+
\`export const app = await bootstrap({ ... })\`. The Vite plugin imports
|
|
242
|
+
the named \`app\` symbol to drive HMR module swaps; testing helpers
|
|
243
|
+
(\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
|
|
244
|
+
the \`export\` and \`kick dev\` will silently fall back to a full restart
|
|
245
|
+
on every save while \`createTestApp\` complains about a missing handle.
|
|
246
|
+
|
|
247
|
+
- **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
|
|
248
|
+
adapters in dedicated folders and re-export aggregated arrays. Do **not**
|
|
249
|
+
inline registration in the entry file:
|
|
250
|
+
|
|
251
|
+
\`\`\`ts
|
|
252
|
+
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
253
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
254
|
+
// OR with \`modules.style: 'class'\`:
|
|
255
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
256
|
+
|
|
257
|
+
// src/middleware/index.ts
|
|
258
|
+
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
259
|
+
|
|
260
|
+
// src/plugins/index.ts
|
|
261
|
+
export const plugins = [MetricsPlugin(), AuditPlugin()]
|
|
262
|
+
|
|
263
|
+
// src/adapters/index.ts
|
|
264
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
265
|
+
\`\`\`
|
|
266
|
+
|
|
267
|
+
\`\`\`ts
|
|
268
|
+
// src/index.ts — stays small; one import per category
|
|
269
|
+
import 'reflect-metadata'
|
|
270
|
+
import './config'
|
|
271
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
272
|
+
import { modules } from './modules'
|
|
273
|
+
import { middleware } from './middleware'
|
|
274
|
+
import { plugins } from './plugins'
|
|
275
|
+
import { adapters } from './adapters'
|
|
276
|
+
|
|
277
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
278
|
+
\`\`\`
|
|
279
|
+
|
|
280
|
+
This keeps the entry file diff-friendly, scales to dozens of modules
|
|
281
|
+
without git churn, and lets each domain own its own registration list.
|
|
282
|
+
The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
|
|
283
|
+
\`kick g adapter\`) follow this layout — manual additions should too.
|
|
284
|
+
|
|
285
|
+
Everything else (controllers, services, modules, RequestContext API, generators,
|
|
286
|
+
package additions, env access patterns, troubleshooting) is detailed below.
|
|
287
|
+
|
|
288
|
+
## Where to Find Things
|
|
289
|
+
|
|
290
|
+
### Application Structure
|
|
291
|
+
|
|
292
|
+
| What | Where |
|
|
293
|
+
|------|-------|
|
|
294
|
+
| Entry point | \`src/index.ts\` |
|
|
295
|
+
| Module registry | \`src/modules/index.ts\` |
|
|
296
|
+
| Feature modules | \`src/modules/<module-name>/\` |
|
|
297
|
+
| **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
|
|
298
|
+
| Env values | \`.env\` |
|
|
299
|
+
| Env schema (Zod) | \`src/config/index.ts\` |
|
|
300
|
+
| TypeScript config | \`tsconfig.json\` |
|
|
301
|
+
| Vite config (HMR) | \`vite.config.ts\` |
|
|
302
|
+
| Vitest config | \`vitest.config.ts\` |
|
|
303
|
+
| Prettier config | \`.prettierrc\` |
|
|
304
|
+
| CLI config | \`kick.config.ts\` |
|
|
305
|
+
|
|
306
|
+
### Module Pattern (${t.toUpperCase()})
|
|
307
|
+
|
|
308
|
+
> **Vite HMR auto-discovery contract:** module files **must** be named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and live under \`src/modules/\`. The Vite plugin scans for \`*.module.[tj]sx?\` to drive graceful HMR rebuilds; renaming a file to \`projects.ts\` (no \`.module\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\`kick g module <name>\`) follows the convention; manual files must too.
|
|
309
|
+
|
|
310
|
+
Each module in \`src/modules/<name>/\` typically contains:
|
|
311
|
+
|
|
312
|
+
${t===`ddd`?`\`\`\`
|
|
313
|
+
<name>/
|
|
314
|
+
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
315
|
+
├── <name>.service.ts # Business logic (@Service)
|
|
316
|
+
├── <name>.repository.ts # Data access (@Repository)
|
|
317
|
+
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
318
|
+
├── <name>.entity.ts # Domain entity (optional)
|
|
319
|
+
└── <name>.module.ts # Module definition (defineModule factory)
|
|
320
|
+
\`\`\`
|
|
321
|
+
`:t===`cqrs`?`\`\`\`
|
|
322
|
+
<name>/
|
|
323
|
+
├── commands/ # Write operations
|
|
324
|
+
│ ├── create-<name>.command.ts
|
|
325
|
+
│ └── create-<name>.handler.ts
|
|
326
|
+
├── queries/ # Read operations
|
|
327
|
+
│ ├── get-<name>.query.ts
|
|
328
|
+
│ └── get-<name>.handler.ts
|
|
329
|
+
├── events/ # Domain events
|
|
330
|
+
│ └── <name>-created.event.ts
|
|
331
|
+
├── <name>.controller.ts # HTTP routes
|
|
332
|
+
├── <name>.repository.ts # Data access
|
|
333
|
+
└── <name>.module.ts # Module definition (defineModule factory)
|
|
334
|
+
\`\`\`
|
|
335
|
+
`:t===`rest`?`\`\`\`
|
|
336
|
+
<name>/
|
|
337
|
+
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
338
|
+
├── <name>.service.ts # Business logic (@Service)
|
|
339
|
+
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
340
|
+
└── <name>.module.ts # Module definition (defineModule factory)
|
|
341
|
+
\`\`\`
|
|
342
|
+
`:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
|
|
343
|
+
|
|
344
|
+
## Checklist: Adding a Feature
|
|
345
|
+
|
|
346
|
+
### New Module (Recommended)
|
|
347
|
+
|
|
348
|
+
Use the CLI generator for consistency:
|
|
349
|
+
|
|
350
|
+
\`\`\`bash
|
|
351
|
+
kick g module <name> # Generate full module
|
|
352
|
+
# or
|
|
353
|
+
kick g scaffold <name> <fields> # Generate CRUD from fields
|
|
354
|
+
\`\`\`
|
|
355
|
+
|
|
356
|
+
Then:
|
|
357
|
+
- [ ] Review generated files in \`src/modules/<name>/\`
|
|
358
|
+
- [ ] Verify module is registered in \`src/modules/index.ts\`
|
|
359
|
+
- [ ] Update DTOs in \`<name>.dto.ts\` if needed
|
|
360
|
+
- [ ] Implement business logic in \`<name>.service.ts\`
|
|
361
|
+
- [ ] Run \`kick dev\` to test with HMR
|
|
362
|
+
- [ ] Write tests in \`<name>.test.ts\`
|
|
363
|
+
|
|
364
|
+
### Manual Controller
|
|
365
|
+
|
|
366
|
+
If not using generators:
|
|
367
|
+
|
|
368
|
+
- [ ] Create \`src/modules/<name>/<name>.controller.ts\`
|
|
369
|
+
- [ ] Add \`@Controller()\` decorator
|
|
370
|
+
- [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
|
|
371
|
+
- [ ] Create module file with \`defineModule({ name, build: () => ({ routes() { return { path, controller } } }) })\` — the framework derives the Express router from the controller. Class-form (\`class XModule implements AppModule\`) is the legacy alternative; toggle via \`kick.config.ts > modules.style\`.
|
|
372
|
+
- [ ] Register module in \`src/modules/index.ts\`. Default form is the fluent chain: \`defineModules().mount(MyModule()).mount(...)\`. \`kick g module <name>\` appends \`.mount(NewModule())\` automatically.
|
|
373
|
+
- [ ] Test with \`kick dev\`
|
|
374
|
+
|
|
375
|
+
### Manual Service
|
|
376
|
+
|
|
377
|
+
- [ ] Create \`src/modules/<name>/<name>.service.ts\`
|
|
378
|
+
- [ ] Add \`@Service()\` decorator
|
|
379
|
+
- [ ] Inject dependencies with \`@Autowired()\`
|
|
380
|
+
- [ ] Inject via \`@Autowired()\` where needed
|
|
381
|
+
- [ ] Write unit tests
|
|
382
|
+
|
|
383
|
+
### New Middleware
|
|
384
|
+
|
|
385
|
+
- [ ] Create \`src/middleware/<name>.middleware.ts\`
|
|
386
|
+
- [ ] Export middleware function (Express format)
|
|
387
|
+
- [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
|
|
388
|
+
- [ ] Test with sample requests
|
|
389
|
+
|
|
390
|
+
### Adding a Package
|
|
391
|
+
|
|
392
|
+
Use \`kick add\` to install KickJS packages with correct peer dependencies:
|
|
393
|
+
|
|
394
|
+
- [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
|
|
395
|
+
- [ ] Follow package-specific setup in terminal output
|
|
396
|
+
- [ ] Update \`src/index.ts\` to register adapter (if needed)
|
|
397
|
+
- [ ] Configure environment variables in \`.env\`
|
|
398
|
+
- [ ] Test integration with \`kick dev\`
|
|
399
|
+
|
|
400
|
+
## Common Tasks
|
|
401
|
+
|
|
402
|
+
### Generate CRUD Module
|
|
403
|
+
|
|
404
|
+
\`\`\`bash
|
|
405
|
+
kick g scaffold user name:string email:string:optional age:number
|
|
406
|
+
\`\`\`
|
|
407
|
+
|
|
408
|
+
Append \`:optional\` for optional fields (shell-safe, no quoting needed).
|
|
409
|
+
Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
|
|
410
|
+
|
|
411
|
+
This creates a full CRUD module with:
|
|
412
|
+
- Controller with GET, POST, PUT, DELETE routes
|
|
413
|
+
- Service with business logic
|
|
414
|
+
- Repository with data access
|
|
415
|
+
- DTOs with Zod validation
|
|
416
|
+
|
|
417
|
+
### Add Authentication
|
|
418
|
+
|
|
419
|
+
\`\`\`bash
|
|
420
|
+
kick add auth
|
|
421
|
+
\`\`\`
|
|
422
|
+
|
|
423
|
+
Then configure in \`src/index.ts\`:
|
|
424
|
+
|
|
425
|
+
\`\`\`ts
|
|
426
|
+
import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
|
|
427
|
+
|
|
428
|
+
bootstrap({
|
|
429
|
+
modules,
|
|
430
|
+
adapters: [
|
|
431
|
+
AuthAdapter({
|
|
432
|
+
strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
|
|
433
|
+
}),
|
|
434
|
+
],
|
|
435
|
+
})
|
|
436
|
+
\`\`\`
|
|
437
|
+
|
|
438
|
+
### Add Database (Prisma)
|
|
439
|
+
|
|
440
|
+
\`\`\`bash
|
|
441
|
+
kick add prisma
|
|
442
|
+
${n} install prisma @prisma/client
|
|
443
|
+
npx prisma init
|
|
444
|
+
# Edit prisma/schema.prisma
|
|
445
|
+
npx prisma migrate dev --name init
|
|
446
|
+
kick g module user --repo prisma
|
|
447
|
+
\`\`\`
|
|
448
|
+
|
|
449
|
+
### Add WebSocket Support
|
|
450
|
+
|
|
451
|
+
\`\`\`bash
|
|
452
|
+
kick add ws
|
|
453
|
+
\`\`\`
|
|
454
|
+
|
|
455
|
+
Then add adapter in \`src/index.ts\`:
|
|
456
|
+
|
|
457
|
+
\`\`\`ts
|
|
458
|
+
import { WsAdapter } from '@forinda/kickjs-ws'
|
|
459
|
+
|
|
460
|
+
bootstrap({
|
|
461
|
+
modules,
|
|
462
|
+
adapters: [WsAdapter()],
|
|
463
|
+
})
|
|
464
|
+
\`\`\`
|
|
465
|
+
|
|
466
|
+
Create WebSocket controller:
|
|
467
|
+
|
|
468
|
+
\`\`\`bash
|
|
469
|
+
kick g controller chat --ws
|
|
470
|
+
\`\`\`
|
|
471
|
+
|
|
472
|
+
## Testing Guidelines
|
|
473
|
+
|
|
474
|
+
All tests use Vitest:
|
|
475
|
+
|
|
476
|
+
\`\`\`ts
|
|
477
|
+
import { describe, it, expect, beforeEach } from 'vitest'
|
|
478
|
+
import { Container } from '@forinda/kickjs'
|
|
479
|
+
import { createTestApp } from '@forinda/kickjs-testing'
|
|
480
|
+
|
|
481
|
+
describe('UserController', () => {
|
|
482
|
+
it('should return users', async () => {
|
|
483
|
+
// Container.create() — isolated DI state per test, never new Container()
|
|
484
|
+
// and never getInstance().reset() (both leak registrations between tests).
|
|
485
|
+
const container = Container.create()
|
|
486
|
+
const app = await createTestApp([UserModule], { container })
|
|
487
|
+
const res = await app.get('/users')
|
|
488
|
+
|
|
489
|
+
expect(res.status).toBe(200)
|
|
490
|
+
expect(res.body).toHaveProperty('users')
|
|
491
|
+
})
|
|
492
|
+
})
|
|
493
|
+
\`\`\`
|
|
494
|
+
|
|
495
|
+
Run tests:
|
|
496
|
+
- \`${n} run test\` — run all tests once
|
|
497
|
+
- \`${n} run test:watch\` — watch mode
|
|
498
|
+
- Individual file: \`${n} run test src/modules/user/user.test.ts\`
|
|
499
|
+
|
|
500
|
+
## Environment Variables
|
|
501
|
+
|
|
502
|
+
Schema is declared in \`src/config/index.ts\` (extends the base
|
|
503
|
+
\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
|
|
504
|
+
with kickjs at module load. \`src/index.ts\` imports it via
|
|
505
|
+
\`import './config'\` **before** \`bootstrap()\` so the cache is populated
|
|
506
|
+
in time for DI. Add new keys to the schema, drop their values into
|
|
507
|
+
\`.env\`, and they're typed everywhere.
|
|
508
|
+
|
|
509
|
+
Access patterns:
|
|
510
|
+
|
|
511
|
+
1. **@Value() decorator** (recommended for known-at-construction keys):
|
|
512
|
+
\`\`\`ts
|
|
513
|
+
@Value('DATABASE_URL')
|
|
514
|
+
private dbUrl!: string
|
|
515
|
+
\`\`\`
|
|
516
|
+
|
|
517
|
+
2. **ConfigService** (recommended for dynamic / method-scoped access):
|
|
518
|
+
\`\`\`ts
|
|
519
|
+
@Autowired()
|
|
520
|
+
private config!: ConfigService
|
|
521
|
+
|
|
522
|
+
const port = this.config.get('PORT') // typed: number
|
|
523
|
+
\`\`\`
|
|
524
|
+
|
|
525
|
+
3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
|
|
526
|
+
\`\`\`ts
|
|
527
|
+
import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
|
|
528
|
+
|
|
529
|
+
const env = loadEnv(schema) // Parse + validate all vars
|
|
530
|
+
const port = getEnv('PORT') // Single value lookup
|
|
531
|
+
reloadEnv() // Re-read .env from disk
|
|
532
|
+
resetEnvCache() // Full reset (for tests)
|
|
533
|
+
\`\`\`
|
|
534
|
+
|
|
535
|
+
4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
|
|
536
|
+
coercion and the typed \`KickEnv\` registry.
|
|
537
|
+
|
|
538
|
+
> **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
|
|
539
|
+
> If the schema is not registered before DI runs, \`config.get()\`
|
|
540
|
+
> returns \`undefined\` for user keys (the base shape only) and
|
|
541
|
+
> \`@Value()\` only works because of its raw \`process.env\` fallback —
|
|
542
|
+
> Zod coercion + schema defaults are silently skipped.
|
|
543
|
+
|
|
544
|
+
## Standalone Utilities (No DI Required)
|
|
545
|
+
|
|
546
|
+
These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
|
|
547
|
+
|
|
548
|
+
| Utility | Import | Example |
|
|
549
|
+
|---------|--------|---------|
|
|
550
|
+
| \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
|
|
551
|
+
| \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
|
|
552
|
+
| \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
|
|
553
|
+
| \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
|
|
554
|
+
| \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
|
|
555
|
+
| \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
|
|
556
|
+
| \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
|
|
557
|
+
| \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
|
|
558
|
+
| \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
|
|
559
|
+
|
|
560
|
+
## Key Decorators
|
|
561
|
+
|
|
562
|
+
### HTTP Routes
|
|
563
|
+
| Decorator | Purpose |
|
|
564
|
+
|-----------|---------|
|
|
565
|
+
| \`@Controller()\` | Define route prefix |
|
|
566
|
+
| \`@Get('/'), @Post('/')\` | HTTP method handlers |
|
|
567
|
+
| \`@Middleware(fn)\` | Attach middleware |
|
|
568
|
+
| \`@Public()\` | Skip auth (requires auth adapter) |
|
|
569
|
+
| \`@Roles('admin')\` | Role-based access |
|
|
570
|
+
|
|
571
|
+
### Dependency Injection
|
|
572
|
+
| Decorator | Purpose |
|
|
573
|
+
|-----------|---------|
|
|
574
|
+
| \`defineModule({...})\` | Define feature module (factory; preferred — paired with \`defineModules()\` registry) |
|
|
575
|
+
| \`defineModules()\` | Build the modules registry as a chainable list (\`.mount(X())\`) |
|
|
576
|
+
| \`AppModule\` interface | Legacy module shape — \`class X implements AppModule\` (toggle via \`modules.style: 'class'\`) |
|
|
577
|
+
| \`@Service()\` | Register singleton service |
|
|
578
|
+
| \`@Repository()\` | Register repository |
|
|
579
|
+
| \`@Autowired()\` | Property injection |
|
|
580
|
+
| \`@Inject('token')\` | Token-based injection |
|
|
581
|
+
| \`@Value('VAR')\` | Inject env variable |
|
|
582
|
+
|
|
583
|
+
### Context Decorators
|
|
584
|
+
|
|
585
|
+
Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
|
|
586
|
+
Use this **instead of \`@Middleware()\`** when the middleware's only output
|
|
587
|
+
is a value other code reads off \`ctx\`.
|
|
588
|
+
|
|
589
|
+
| Concept | Where it lives |
|
|
590
|
+
|---------|----------------|
|
|
591
|
+
| \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
|
|
592
|
+
| Method/class decorator | \`@LoadX\` on a controller method/class |
|
|
593
|
+
| Module hook | \`build: () => ({ contributors() { return [...] } })\` (\`defineModule\`) — or \`AppModule.contributors?()\` for class form |
|
|
594
|
+
| Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
|
|
595
|
+
| Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
|
|
596
|
+
| Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
|
|
597
|
+
|
|
598
|
+
Precedence high → low: **method > class > module > adapter > global**.
|
|
599
|
+
Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
|
|
600
|
+
fast). The \`onError\` hook is async-permitted.
|
|
601
|
+
|
|
602
|
+
Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
|
|
603
|
+
|
|
604
|
+
${t===`cqrs`?`### Background Jobs
|
|
605
|
+
| Decorator | Purpose |
|
|
606
|
+
|-----------|---------|
|
|
607
|
+
| \`@Job('name')\` | Queue job handler |
|
|
608
|
+
| \`@Process('queue')\` | Queue processor |
|
|
609
|
+
| \`@Cron('0 * * * *')\` | Cron schedule |
|
|
610
|
+
| \`@WsController()\` | WebSocket controller |
|
|
611
|
+
|
|
612
|
+
`:``}## Common Pitfalls
|
|
613
|
+
|
|
614
|
+
1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
|
|
615
|
+
2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
|
|
616
|
+
3. **Tests failing randomly** — Sharing the global container between tests. Default to \`Container.create()\` per test (or per \`beforeEach\`) instead of \`new Container()\` / \`getInstance().reset()\`
|
|
617
|
+
4. **Routes not found** — Check controller path and module registration
|
|
618
|
+
5. **HMR not working** — Two checks: (a) \`vite.config.ts\` has \`hmr: true\`; (b) module file is named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and lives under \`src/modules/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed module file (e.g., \`projects.ts\`) silently degrades to a full restart on every save.
|
|
619
|
+
6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
|
|
620
|
+
7. **\`config.get('YOUR_KEY')\` returns \`undefined\`** — \`src/index.ts\` is missing \`import './config'\`. That side-effect import registers the env schema with kickjs (\`loadEnv(envSchema)\` runs at module load). Without it, \`ConfigService\` falls back to the base schema (\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` only) and every user-defined key reads as \`undefined\`. \`@Value()\` may *appear* to work because of a raw \`process.env\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \`src/index.ts\` and \`src/config/index.ts\` first.
|
|
621
|
+
8. **Used \`@Middleware()\` to compute a value for \`ctx\`** — prefer \`defineContextDecorator()\` (see Context Decorators above). It's typed via \`ContextMeta\`, supports \`dependsOn\` for ordering, and validates the pipeline at boot. \`@Middleware()\` is for response short-circuiting, stream mutation, and pre-route-matching work.
|
|
622
|
+
9. **Context contributor's \`dependsOn\` key not produced anywhere** — boot throws \`MissingContributorError\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).
|
|
623
|
+
10. **\`bootstrap()\` not exported** — \`src/index.ts\` calls \`await bootstrap({ ... })\` but discards the return value (no \`export const app = ...\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \`createTestApp\`/\`@forinda/kickjs-testing\` consumers can't import the handle either. Always: \`export const app = await bootstrap({ ... })\`.
|
|
624
|
+
11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \`kick g agents -f\` (or \`kick g agent-docs -f\`) to regenerate from the latest CLI templates after \`kick add\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \`AGENTS.local.md\`.
|
|
625
|
+
|
|
626
|
+
## CLI Commands Reference
|
|
627
|
+
|
|
628
|
+
| Command | Description |
|
|
629
|
+
|---------|-------------|
|
|
630
|
+
| \`kick dev\` | Dev server with HMR |
|
|
631
|
+
| \`kick dev:debug\` | Dev server with debugger |
|
|
632
|
+
| \`kick build\` | Production build |
|
|
633
|
+
| \`kick start\` | Run production build |
|
|
634
|
+
| \`kick g module <names...>\` | Generate one or more modules |
|
|
635
|
+
| \`kick g scaffold <name> <fields>\` | Generate CRUD |
|
|
636
|
+
| \`kick g controller <name>\` | Generate controller |
|
|
637
|
+
| \`kick g service <name>\` | Generate service |
|
|
638
|
+
| \`kick g middleware <name>\` | Generate middleware |
|
|
639
|
+
| \`kick add <package>\` | Add KickJS package |
|
|
640
|
+
| \`kick add --list\` | List available packages |
|
|
641
|
+
| \`kick rm module <names...>\` | Remove one or more modules |
|
|
642
|
+
|
|
643
|
+
> **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
|
|
644
|
+
> \`\`\`bash
|
|
645
|
+
> kick new my-api -t ddd -r prisma --pm ${n} --no-git --no-install -f
|
|
646
|
+
> \`\`\`
|
|
647
|
+
|
|
648
|
+
## Learn More
|
|
649
|
+
|
|
650
|
+
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
651
|
+
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
652
|
+
- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
653
|
+
- [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
|
|
654
|
+
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
655
|
+
`}function I(e,t,n){let r=`<!-- Generated by \`kick g agents\` for ${e}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`;return[{slug:`add-module`,frontmatterName:`kickjs-add-module`,description:`Use when the user asks to add a new feature module (controller + service + repo + DTOs).`,body:`**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
|
|
656
|
+
|
|
657
|
+
**Steps**:
|
|
658
|
+
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
659
|
+
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
|
|
660
|
+
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
661
|
+
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
662
|
+
5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
|
|
663
|
+
|
|
664
|
+
**Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
|
|
665
|
+
|
|
666
|
+
\`\`\`ts
|
|
667
|
+
export const TodosModule = defineModule({
|
|
668
|
+
name: 'TodosModule',
|
|
669
|
+
build: () => ({
|
|
670
|
+
register(container) {
|
|
671
|
+
container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))
|
|
672
|
+
},
|
|
673
|
+
routes() {
|
|
674
|
+
return { path: '/todos', controller: TodosController }
|
|
675
|
+
},
|
|
676
|
+
}),
|
|
677
|
+
})
|
|
678
|
+
\`\`\`
|
|
679
|
+
|
|
680
|
+
The module file MUST include \`import.meta.glob([...], { eager: true })\` for every \`@Service\` / \`@Repository\` / \`@Component\` class — without it, decorators never fire and DI silently resolves to \`undefined\`.
|
|
681
|
+
|
|
682
|
+
**Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
|
|
683
|
+
|
|
684
|
+
\`\`\`ts
|
|
685
|
+
routes() {
|
|
686
|
+
return [
|
|
687
|
+
{ path: '/todos', controller: TodosController }, // /api/v1/todos
|
|
688
|
+
{ path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
|
|
689
|
+
]
|
|
690
|
+
}
|
|
691
|
+
\`\`\`
|
|
692
|
+
|
|
693
|
+
**Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
|
|
694
|
+
|
|
695
|
+
**Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
|
|
696
|
+
|
|
697
|
+
**Red flags** (stop and ask):
|
|
698
|
+
- File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite plugin's \`*.module.[tj]sx?\` glob doesn't pick it up; every save becomes a full restart.
|
|
699
|
+
- \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
|
|
700
|
+
- \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
|
|
701
|
+
- \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
|
|
702
|
+
- 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**:
|
|
703
|
+
|
|
704
|
+
\`\`\`ts
|
|
705
|
+
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
706
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
707
|
+
// OR for class-form projects (\`modules.style: 'class'\`):
|
|
708
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
709
|
+
|
|
710
|
+
// src/middleware/index.ts — global middleware uses RAW EXPRESS signature
|
|
711
|
+
// (req, res, next), NOT (ctx, next)
|
|
712
|
+
export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
|
|
713
|
+
|
|
714
|
+
// src/plugins/index.ts
|
|
715
|
+
export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]
|
|
716
|
+
|
|
717
|
+
// src/adapters/index.ts
|
|
718
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
719
|
+
|
|
720
|
+
// src/index.ts — stays small
|
|
721
|
+
import 'reflect-metadata'
|
|
722
|
+
import './config' // MUST be early — side-effect schema load
|
|
723
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
724
|
+
import { modules } from './modules'
|
|
725
|
+
import { middleware } from './middleware'
|
|
726
|
+
import { plugins } from './plugins'
|
|
727
|
+
import { adapters } from './adapters'
|
|
728
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
729
|
+
\`\`\`
|
|
730
|
+
|
|
731
|
+
**One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
|
|
732
|
+
|
|
733
|
+
\`\`\`ts
|
|
734
|
+
plugins: [
|
|
735
|
+
...plugins,
|
|
736
|
+
{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
|
|
737
|
+
]
|
|
738
|
+
\`\`\`
|
|
739
|
+
|
|
740
|
+
**Red flags**:
|
|
741
|
+
- Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
742
|
+
- Mixing middleware signatures: \`bootstrap({ middleware })\` is **raw Express** \`(req, res, next)\`; \`@Middleware()\` decorators are \`(ctx, next)\`; adapter middleware is raw Express again. Wrong shape in the wrong slot throws "Cannot read properties of undefined".
|
|
743
|
+
- \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// Optionally publish discoverability for tooling (Swagger, DevTools)\ndefineAugmentation('ContextMeta', {\n description: 'Per-request tenant resolved from x-tenant-id header.',\n example: { id: 'acme', name: 'Acme Inc' },\n})\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n ctx.json(ctx.get('project'))\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying Express request is shared).\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- `defineAugmentation` without the `declare module` block (or vice-versa) — discoverability and types drift apart; `ctx.get('tenant')` becomes `unknown`.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
|
|
744
|
+
- \`kick new <name>\` — start a new project (prompts for template / repo / pm).
|
|
745
|
+
- \`kick dev\` — local dev server with Vite HMR.
|
|
746
|
+
- \`kick build\` — production bundle via Vite.
|
|
747
|
+
- \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
|
|
748
|
+
- \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
|
|
749
|
+
- \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
|
|
750
|
+
- \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
|
|
751
|
+
- \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
|
|
752
|
+
- \`kick info\` — environment / version dump for bug reports.
|
|
753
|
+
- \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
|
|
754
|
+
|
|
755
|
+
**Useful flag combos**:
|
|
756
|
+
|
|
757
|
+
\`\`\`bash
|
|
758
|
+
kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
|
|
759
|
+
kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
|
|
760
|
+
kick new . --yes --force # Scaffold into current dir, clear existing files
|
|
761
|
+
kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
|
|
762
|
+
kick g agents -f --only skills # Refresh just the skills after upgrade
|
|
763
|
+
kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
|
|
764
|
+
kick inspect --port 4000 --json # Machine-readable route/adapter dump
|
|
765
|
+
kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
|
|
766
|
+
\`\`\`
|
|
767
|
+
|
|
768
|
+
**Lesser-known, high-value**:
|
|
769
|
+
- \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
|
|
770
|
+
- \`kick g agents -f\` — regenerates \`CLAUDE.md\` (root) and \`.agents/AGENTS.md\` / \`GEMINI.md\` / \`COPILOT.md\` + every \`.agents/skills/<slug>/SKILL.md\` from the current CLI templates.
|
|
771
|
+
- \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
|
|
772
|
+
- \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
|
|
773
|
+
- \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
|
|
774
|
+
- \`kick check\` — preflight gate (typecheck + lint + format) before commit.
|
|
775
|
+
- \`kick codemod\` — automated AST-level migration between framework versions.
|
|
776
|
+
|
|
777
|
+
**Red flags**:
|
|
778
|
+
- Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
|
|
779
|
+
- Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
|
|
780
|
+
- Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
|
|
781
|
+
- Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
|
|
782
|
+
- Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`refresh-agent-docs`,frontmatterName:`kickjs-refresh-agent-docs`,description:`Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.`,body:"**Steps**:\n1. `kick g agents -f --only both` — overwrites `CLAUDE.md` (root) and `.agents/AGENTS.md`.\n2. `kick g agents -f --only skills` — refreshes every `.agents/skills/<slug>/SKILL.md`.\n3. `kick g agents -f --only gemini` / `--only copilot` — refresh the per-agent files when needed.\n4. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate `AGENTS.local.md` or per-skill `SKILL.local.md` alongside.\n5. Commit as `docs(agents): sync from CLI vX.Y`.\n\n**`.agents/` layout** (post-restructure):\n\n```\nCLAUDE.md # at root — Claude Code auto-loads from here\n.agents/\n├── AGENTS.md # canonical multi-agent reference\n├── GEMINI.md # Gemini-specific notes\n├── COPILOT.md # Copilot CLI notes\n└── skills/\n ├── add-module/SKILL.md\n ├── add-adapter/SKILL.md\n └── … # one SKILL.md per skill, frontmatter-namespaced\n```\n\nCustomisation goes in `.local.md` siblings (`AGENTS.local.md`, `skills/<slug>/SKILL.local.md`) — those are never overwritten."},{slug:`deny-list`,frontmatterName:`kickjs-deny-list`,description:`Patterns to refuse outright when the user asks for them — they break v4 invariants.`,body:"**Module / adapter / plugin shape**:\n- `class implements AppAdapter` → use `defineAdapter()`.\n- `class implements KickPlugin` / function returning `KickPlugin` → use `definePlugin()`.\n- `class implements AppModule` for new code → use `defineModule()`.\n- `bootstrap({ adapters: [MyAdapter] })` (factory) → `MyAdapter()` (instance, with parens).\n- `@Controller('/path')` with a path argument → drop the path; set the mount via `routes().path`. The decorator path is OpenAPI metadata only.\n- Module file named `<name>.ts` (no `.module` suffix) → rename to `<name>.module.ts`. Vite HMR's glob doesn't pick up the unsuffixed form.\n\n**DI**:\n- `new Container()` or `Container.getInstance().reset()` in tests → use `Container.reset()` in `beforeEach` (or `Container.create()` for fully isolated graphs).\n- DI tokens with `:` separator (`'app:db:url'`) or in PascalCase → use slash-delimited lower-case (`'app/db/url'`). First-party uses reserved `'kick/'` prefix.\n- `Symbol.for(...)` for DI tokens — globally interned, **collides across files**. Use `createToken<T>('name')`.\n- Raw string tokens (`@Inject('config')`) — silent collisions; widens to `unknown`. Use `createToken<T>`.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve time.\n\n**Bootstrap / entry file**:\n- `bootstrap({ ... })` without `export const app = ...` → always export. HMR degrades to full restart and `createTestApp` loses the handle.\n- `bootstrap({ register: ... })` — that option doesn't exist. Use an inline plugin in `plugins`.\n\n**Middleware**:\n- Using `(ctx, next)` for global middleware in `bootstrap({ middleware })` — global middleware uses raw Express `(req, res, next)`. Wrong signature throws \"Cannot read properties of undefined\".\n- Using `(req, res, next)` for an `@Middleware()` decorator — those use `(ctx, next)`.\n- `@Middleware()` whose only output is `ctx.set('x', v)` — should be a context decorator (typed, ordered, testable).\n\n**Context contributors**:\n- `ctx.tenant = x` from a contributor — only sticks to one `RequestContext` instance. **Return the value** so the runner writes it via `ctx.set(key, value)`.\n- `defineAugmentation('ContextMeta', ...)` without the matching `declare module '@forinda/kickjs'` block (or vice-versa).\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type.\n\n**Env / config**:\n- `@Value('NEW_KEY')` without the key in the Zod schema — silent fallback to raw `process.env`, no coercion.\n- `resetEnvCache()` outside tests — drops the registered schema.\n\n**List endpoints**:\n- Reading `req.query.status` directly — bypasses the allow-list. Use `ctx.qs({ filterable })`.\n- Returning a bare array from a list endpoint — breaks the `PaginatedResponse<T>` contract. Use `ctx.paginate()`.\n\n**Assets**:\n- Hand-rolled `__dirname` arithmetic for template paths — use `assets.<ns>.<key>()` and add the namespace to `kick.config.ts assetMap`."}].map(e=>({slug:e.slug,content:`---
|
|
783
|
+
name: ${e.frontmatterName}
|
|
784
|
+
description: ${e.description}
|
|
785
|
+
---
|
|
786
|
+
|
|
787
|
+
${r}
|
|
788
|
+
|
|
789
|
+
${e.body}
|
|
790
|
+
`}))}function L(e,t,n){return`# GEMINI.md — ${e}
|
|
791
|
+
|
|
792
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
793
|
+
reference for this project — every convention, structure, decorator
|
|
794
|
+
pattern, env wiring rule, generator usage. This file is a thin
|
|
795
|
+
Gemini-specific layer; when the two disagree on anything substantive,
|
|
796
|
+
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
797
|
+
|
|
798
|
+
## Why this file
|
|
799
|
+
|
|
800
|
+
Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
|
|
801
|
+
agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
|
|
802
|
+
means Gemini reads the same shared prose as Codex / Cursor / Copilot
|
|
803
|
+
without us copy-pasting.
|
|
804
|
+
|
|
805
|
+
## Gemini-specific notes
|
|
806
|
+
|
|
807
|
+
- **Skills activation** — Gemini activates skills via
|
|
808
|
+
\`activate_skill\` (its native MCP-style tool); the equivalent on
|
|
809
|
+
Claude Code is the \`Skill\` tool. Cross-reference the
|
|
810
|
+
\`kickjs-skills.md\` index for the available triggers.
|
|
811
|
+
- **Tool naming** — Gemini's tool names differ from Claude Code's
|
|
812
|
+
(e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
|
|
813
|
+
\`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
|
|
814
|
+
tool names; consult Gemini's docs for the concrete invocation.
|
|
815
|
+
- **File ops** — Gemini's file edits are sandboxed; large refactors
|
|
816
|
+
may need explicit confirmation. Prefer the smallest-possible-edit
|
|
817
|
+
pattern.
|
|
818
|
+
|
|
819
|
+
## Refreshing this file
|
|
820
|
+
|
|
821
|
+
\`kick g agents --only gemini -f\` regenerates this file from the
|
|
822
|
+
CLI template. Hand-edited content is overwritten — keep customisation
|
|
823
|
+
in \`.agents/GEMINI.local.md\`.
|
|
824
|
+
`}function R(e,t,n){return`# COPILOT.md — ${e}
|
|
825
|
+
|
|
826
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
827
|
+
reference for this project — every convention, structure, decorator
|
|
828
|
+
pattern, env wiring rule, generator usage. This file is a thin
|
|
829
|
+
Copilot-specific layer; when the two disagree on anything substantive,
|
|
830
|
+
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
831
|
+
|
|
832
|
+
## Why this file
|
|
833
|
+
|
|
834
|
+
GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
|
|
835
|
+
the agent-context files. Keeping it in \`.agents/\` next to
|
|
836
|
+
\`AGENTS.md\` means Copilot reads the same shared prose as
|
|
837
|
+
Codex / Cursor / Gemini / Claude Code without copy-pasting.
|
|
838
|
+
|
|
839
|
+
## Copilot-specific notes
|
|
840
|
+
|
|
841
|
+
- **Skills** — Copilot CLI auto-discovers skills from installed
|
|
842
|
+
plugins; cross-reference \`kickjs-skills.md\` for available
|
|
843
|
+
triggers in this project.
|
|
844
|
+
- **Tool naming** — Copilot's tool names differ from Claude Code's
|
|
845
|
+
(\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
|
|
846
|
+
prose in \`AGENTS.md\` describes intents, not tool names; consult
|
|
847
|
+
Copilot's docs for the concrete invocation.
|
|
848
|
+
- **Confirmation flows** — Copilot CLI surfaces destructive
|
|
849
|
+
operations through an explicit approval gate. Stage edits with
|
|
850
|
+
short, focused diffs so each one is easy to review at the prompt.
|
|
851
|
+
|
|
852
|
+
## Refreshing this file
|
|
853
|
+
|
|
854
|
+
\`kick g agents --only copilot -f\` regenerates this file from the
|
|
855
|
+
CLI template. Hand-edited content is overwritten — keep customisation
|
|
856
|
+
in \`.agents/COPILOT.local.md\`.
|
|
857
|
+
`}export{C as _,I as a,m as b,w as c,T as d,O as f,u as g,S as h,L as i,M as l,D as m,P as n,N as o,j as p,R as r,A as s,F as t,k as u,b as v,f as y};
|
|
858
|
+
//# sourceMappingURL=project-docs-DRR0mSJy.mjs.map
|