@forinda/kickjs-cli 8.15.0 → 8.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/agent-docs-DhiaLsBj.mjs +591 -0
  2. package/dist/agent-docs-DhiaLsBj.mjs.map +1 -0
  3. package/dist/agent-docs-lNvu1K1x.mjs +590 -0
  4. package/dist/{build-Czsf4CBN.mjs → build-BNHMWtNY.mjs} +2 -2
  5. package/dist/{build-gqxIH3D8.mjs → build-vY0bmwuH.mjs} +3 -3
  6. package/dist/{build-gqxIH3D8.mjs.map → build-vY0bmwuH.mjs.map} +1 -1
  7. package/dist/{builtins-6euI1-lN.mjs → builtins-CRRb7Lq1.mjs} +2 -2
  8. package/dist/{builtins-xahWxQLw.mjs → builtins-tE4nrAZ_.mjs} +59 -59
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-DCM2vXUJ.mjs → config-mXO3F69m.mjs} +2 -2
  11. package/dist/{config-8jdSKLKJ.mjs → config-zWl1-NCq.mjs} +3 -3
  12. package/dist/{config-8jdSKLKJ.mjs.map → config-zWl1-NCq.mjs.map} +1 -1
  13. package/dist/{doctor-CwGU9orm.mjs → doctor-z92r35fo.mjs} +9 -9
  14. package/dist/{doctor-CwGU9orm.mjs.map → doctor-z92r35fo.mjs.map} +1 -1
  15. package/dist/{fullstack-9HywHQL-.mjs → fullstack-BqevN8LJ.mjs} +13 -13
  16. package/dist/{fullstack-9HywHQL-.mjs.map → fullstack-BqevN8LJ.mjs.map} +1 -1
  17. package/dist/{fullstack-BmIFnryN.mjs → fullstack-eMi-9BtZ.mjs} +9 -9
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +2 -2
  20. package/dist/{plugin-DLZP4hZ0.mjs → plugin-BbbHEAzr.mjs} +2 -2
  21. package/dist/{plugin-BjmLRF7t.mjs → plugin-CH4X4T0O.mjs} +2 -2
  22. package/dist/project-Bp6SIRyt.mjs +132 -0
  23. package/dist/project-D96UoR0P.mjs +133 -0
  24. package/dist/project-D96UoR0P.mjs.map +1 -0
  25. package/dist/{project-root-Dk8r8FMi.mjs → project-root-Bw3CEPC7.mjs} +3 -3
  26. package/dist/{project-root-Dk8r8FMi.mjs.map → project-root-Bw3CEPC7.mjs.map} +1 -1
  27. package/dist/{project-root-8DH00M-b.mjs → project-root-DN0YbQE5.mjs} +2 -2
  28. package/dist/{rolldown-runtime-CRasMkPY.mjs → rolldown-runtime-CYy3EyO3.mjs} +1 -1
  29. package/dist/{run-plugins-R0bVf_nK.mjs → run-plugins-f7i7TlPV.mjs} +67 -67
  30. package/dist/run-plugins-f7i7TlPV.mjs.map +1 -0
  31. package/dist/{typegen-BZ8cQ1YM.mjs → typegen-Bq4Fis9G.mjs} +5 -5
  32. package/dist/{typegen-BZ8cQ1YM.mjs.map → typegen-Bq4Fis9G.mjs.map} +1 -1
  33. package/dist/{typegen-DNufBmjE.mjs → typegen-_x_Q5O0b.mjs} +4 -4
  34. package/dist/{types-DOcxTXlP.mjs → types-BLZecxnS.mjs} +1 -1
  35. package/package.json +2 -2
  36. package/templates/base/files/_dot_vscode/extensions.json +3 -0
  37. package/templates/base/files/kick.config.ts +4 -0
  38. package/templates/base/skills/add-adapter.txt +56 -0
  39. package/templates/base/skills/add-module.txt +53 -0
  40. package/templates/base/skills/add-plugin.txt +69 -0
  41. package/templates/base/skills/bootstrap-export.txt +21 -0
  42. package/templates/base/skills/cli-commands-cheatsheet.txt +46 -0
  43. package/templates/base/skills/cli-plugin.txt +61 -0
  44. package/templates/base/skills/context-contributor.txt +73 -0
  45. package/templates/base/skills/deny-list.txt +44 -0
  46. package/templates/base/skills/deploy.txt +99 -0
  47. package/templates/base/skills/docs-lookup.txt +40 -0
  48. package/templates/base/skills/env-wiring-check.txt +44 -0
  49. package/templates/base/skills/guard-vs-middleware-vs-contributor.txt +95 -0
  50. package/templates/base/skills/query-parsing-list-endpoint.txt +48 -0
  51. package/templates/base/skills/refresh-agent-docs.txt +27 -0
  52. package/templates/base/skills/route-flags.txt +73 -0
  53. package/templates/base/skills/thin-entry-file.txt +49 -0
  54. package/templates/base/skills/use-asset-manager.txt +61 -0
  55. package/templates/base/skills/write-controller-test.txt +63 -0
  56. package/templates/feature-views/feature.json +21 -0
  57. package/templates/feature-views/files/src/adapters/views.ts +5 -0
  58. package/templates/feature-views/files/src/views/home.kick +3 -0
  59. package/templates/feature-views/files/src/views/layouts/main.kick +13 -0
  60. package/templates/feature-views/files/src/views.ts +9 -0
  61. package/templates/feature-views/skills/views-forms.txt +68 -0
  62. package/templates/feature-views/skills/views.txt +49 -0
  63. package/templates/fullstack-root/files/_dot_vscode/extensions.json +3 -0
  64. package/dist/agent-docs-CrVQtJgn.mjs +0 -932
  65. package/dist/agent-docs-D7K6R5C3.mjs +0 -933
  66. package/dist/agent-docs-D7K6R5C3.mjs.map +0 -1
  67. package/dist/package-manager-9XxrErw1.mjs +0 -11
  68. package/dist/package-manager-Dwaolesm.mjs +0 -12
  69. package/dist/package-manager-Dwaolesm.mjs.map +0 -1
  70. package/dist/project-CFi3NvO9.mjs +0 -136
  71. package/dist/project-CFi3NvO9.mjs.map +0 -1
  72. package/dist/project-CO0D8B0V.mjs +0 -135
  73. package/dist/run-plugins-R0bVf_nK.mjs.map +0 -1
@@ -1,932 +0,0 @@
1
- /**
2
- * @forinda/kickjs-cli v8.15.0
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{t as e}from"./rolldown-runtime-CRasMkPY.mjs";import{f as t,o as n,r}from"./config-DCM2vXUJ.mjs";import{_ as i,i as a,n as o}from"./package-manager-9XxrErw1.mjs";import{existsSync as s,readFileSync as c}from"node:fs";import{join as l}from"node:path";function u(e,n){let r=e;return n===`fullstack`&&r!==`pnpm`?`${t(r,`dev:server`)} + ${t(r,`dev:web`)}`:t(r,`dev`)}function d(e,n,i){return`# CLAUDE.md — ${e}
12
-
13
- **Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
14
- reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
15
- project conventions, structure, decorator patterns, env wiring, CLI
16
- generators, every gotcha.
17
-
18
- **Skills, when you want them:** \`kick g agents --only skills\` writes
19
- \`./.agents/skills/\` — one task-oriented skill per subdirectory
20
- (\`add-module/\`, \`write-controller-test/\`, \`bootstrap-export/\`,
21
- \`deny-list/\`, …), each a \`SKILL.md\` with YAML frontmatter (\`name\`,
22
- \`description\`) and the recipe body. The structure follows the Claude
23
- Code skills convention — agents that auto-load skills from
24
- \`.agents/skills/\` pick each up by its frontmatter. \`kick g agents\`
25
- alone also adds \`GEMINI.md\` and \`COPILOT.md\`.
26
-
27
- This file is a thin Claude-specific layer on top of those two; when
28
- they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
29
- authoritative and flag the discrepancy.
30
-
31
- ## Why \`.agents/\` + this thin pointer
32
-
33
- \`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
34
- Copilot, Aider, …) — one canonical source so the prose doesn't drift
35
- across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
36
- project context on each conversation, so it stays at the project root.
37
- Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
38
- out-of-sync copies of the same content. Per-agent files
39
- (\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
40
- \`AGENTS.md\` for tool-specific notes that don't belong in the shared
41
- prose.
42
-
43
- ## Claude-specific notes
44
-
45
- - **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
46
- to refresh project memory if AGENTS.md changes substantially.
47
- - **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
48
- - **Persistent memory** — Claude maintains user/feedback/project/
49
- reference memories under \`.claude/memory/\`. If you ask for
50
- something that contradicts a remembered preference, Claude flags
51
- it before acting; corrections update memory automatically.
52
- - **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
53
- or background work. Useful for "wait for the deploy then open a
54
- cleanup PR" or "every Monday triage the issue board" patterns.
55
-
56
- ## Quick reference (full version in .agents/AGENTS.md)
57
-
58
- \`\`\`bash
59
- ${i} install
60
- ${u(i,n)} # Dev server with HMR + typegen
61
- ${t(i,`build`)} && ${t(i,`start`)} # Production
62
- ${t(i,`test`)} # Vitest
63
- ${n===`fullstack`?t(i,`typecheck`):`${r(i,`kick`)} typecheck`} # tsc/tsgo, whichever the project has
64
- ${n===`fullstack`?t(i,`format`):`${r(i,`kick`)} format`} # oxfmt
65
- \`\`\`
66
-
67
- \`kick\` is this project's dev dependency, not a global command: every \`kick …\`
68
- in these docs runs as \`${r(i,`kick`)} …\` in a shell.
69
-
70
- ## v4 framework reminders
71
-
72
- When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
73
-
74
- - **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
75
- - **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
76
- - **DI tokens**: \`<scope>/<area>/<key>[:<instance>]\` — a lowercase scope, then slash-separated segments (e.g. \`'app/users/repository'\`, \`'app/Users/repository'\`, \`'mycorp/cache/redis'\`). First-party uses the reserved \`'kick/'\` prefix; this project owns its own scope.
77
- - **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
78
- - **HTTP runtime**: this app may run on Express, Fastify, or h3 — check \`kick.config.ts\` \`runtime\` (or \`bootstrap({ runtime })\`) before writing engine-specific code. Prefer engine-neutral \`ctx\` APIs (\`ctx.json\`/\`ctx.body\`/\`ctx.params\`/\`ctx.sse\`); don't assume \`ctx.req\` is an Express request. Uploads (\`@FileUpload\` → \`ctx.file\`/\`ctx.files\`) work on all three (\`kick add upload\` installs the driver). Full rules in \`.agents/AGENTS.md\` → "HTTP runtime".
79
- - **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.
80
- - **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).
81
- - **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.
82
- - **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
83
- - **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
84
- - **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.
85
- - **Thin entry file**: aggregate \`modules\`, \`middlewares\`, \`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\`.
86
- - **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.
87
-
88
- For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
89
- `}function f(e,n,i){return`# AGENTS.md — AI Agent Guide for ${e}
90
-
91
- This guide is the **canonical, multi-agent reference** for this KickJS
92
- application — Claude, Copilot, Codex, Gemini, etc. all read it first.
93
- Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
94
- add tool-specific affordances on top.
95
-
96
- ## Before You Start
97
-
98
- 1. Run \`${i} install\` to install dependencies
99
- 2. Run \`${u(i,n)}\` to verify the app starts
100
-
101
- \`kick\` is this project's dev dependency, not a global command: every \`kick …\`
102
- below runs as \`${r(i,`kick`)} …\` in a shell.${n===`fullstack`?`
103
-
104
- ## Fullstack workspace layout
105
-
106
- This is a WORKSPACE root — the KickJS API lives in \`server/\`, the typed web
107
- app in \`web/\`. Run both with \`${u(i,n)}\`. From this root,
108
- \`${t(i,`test`)}\`, \`${t(i,`typecheck`)}\` and \`${t(i,`format`)}\` reach into
109
- \`server/\` (and \`web/\` for typecheck).
110
-
111
- The type loop (do not break it):
112
- 1. \`server/\` handlers RETURN their payloads → \`kick typegen\` emits
113
- \`server/.kickjs/types/kick__client.d.ts\`: the ambient \`KickClientApi\`
114
- namespace, every response resolved to a plain shape. \`kick dev\` writes it
115
- at startup but NOT on save — run \`kick typegen\` in \`server/\` after changing a route or a
116
- response (the root \`build\` script runs it too).
117
- 2. \`web/tsconfig.json\` lists that file in \`compilerOptions.types\`.
118
- 3. \`web/src/api.ts\` = \`createClient<KickClientApi.Api>({ baseUrl })\`
119
- — every call site is typed from the server's handlers. \`baseUrl\` is the
120
- relative \`/api/v1\` (Vite proxies it in dev) unless \`VITE_API_URL\` points at
121
- an API on another origin.
122
-
123
- Rules: kick commands (\`kick g\`, \`kick typegen\`, \`kick dev\`, \`kick typecheck\`)
124
- run in \`server/\` — the root has no \`kick.config.ts\`; never import server runtime code into \`web/\` (the d.ts bridge is
125
- type-only); prefer return-value handlers so responses stay inferable.`:``}
126
- 3. Read the [KickJS documentation](https://kickjs.app/) for framework details
127
-
128
- ## HTTP runtime — DON'T assume Express-only
129
-
130
- KickJS is **engine-pluggable**. It runs on **Express (default), Fastify, or h3** —
131
- chosen with one line: \`bootstrap({ runtime: fastifyRuntime() })\`. Before writing
132
- any engine-specific code, **check which engine this project uses**:
133
-
134
- - \`kick.config.ts\` → the \`runtime\` field (\`'express'\` | \`'fastify'\` | \`'h3'\`), and/or
135
- - \`src/index.ts\` → the \`runtime:\` passed to \`bootstrap()\`, and/or
136
- - \`package.json\` → \`fastify\` / \`h3\` in deps.
137
-
138
- Rules that keep generated code correct on **every** engine:
139
-
140
- - **Prefer return-value handlers.** \`return payload\` sends 200 json on every
141
- engine and lets \`kick typegen\` infer the response type into
142
- \`KickRoutes.Api\` (consumed by the \`@forinda/kickjs-client\` typed client);
143
- \`reply(status, body)\` for non-200, \`reply.noContent()\` for 204. A declared
144
- \`{ response: schema }\` on the route feeds BOTH the OpenAPI success response
145
- and the typegen response type. \`ctx.json(...)\` stays fully supported but
146
- infers \`unknown\`.
147
- - **Lifecycle hooks:** \`@PostConstruct()\` after instantiation; \`@PreDestroy()\`
148
- when a REQUEST-scoped service's request closes (release transactions/handles).
149
- - **Write to \`ctx\`, not the raw request/response.** \`ctx.json()\`, \`ctx.body\`,
150
- \`ctx.params\`, \`ctx.query\`, \`ctx.set/get\`, \`ctx.sse()\` are engine-neutral and
151
- work identically everywhere. \`ctx.req\` / \`ctx.res\` are the engine-native
152
- objects — their **type follows the active runtime** (Express by default; the
153
- \`kick/runtime\` typegen retypes them to Fastify / h3 when \`runtime\` is set).
154
- Don't assume \`ctx.req\` is an \`express.Request\` in portable code.
155
- - **Global middleware** in \`bootstrap({ middlewares })\` is connect-style
156
- \`(req, res, next)\` — it runs on all engines (Fastify via \`@fastify/middie\`,
157
- h3 via \`fromNodeHandler\`). But on Fastify / h3 the engine parses the body
158
- natively, so the default \`express.json()\` is **auto-skipped** (\`nativeBodyParsing\`).
159
- Don't add \`express.json()\` manually on those engines.
160
- - **File uploads** work on all three: \`@FileUpload({ mode, fieldName, ... })\` →
161
- \`ctx.file\` / \`ctx.files\` (same Multer-shaped object everywhere). Backends:
162
- Express \`multer\`, Fastify \`@fastify/multipart\`, h3 native. Run
163
- \`kick add upload\` to install the runtime-correct driver. The \`@FileUpload\`
164
- decorator is **memory-only** (portable); disk / custom-storage (\`storage\` /
165
- \`dest\`) is Express-only via the \`upload.single/array()\` middleware.
166
- - **Engine subpaths**: \`import { fastifyRuntime } from '@forinda/kickjs/fastify'\`
167
- or \`h3Runtime\` from \`'@forinda/kickjs/h3'\`. Express is the zero-config default
168
- (no import, nothing to install).
169
- - **Not supported on Fastify / h3**: \`ctx.render()\` (no view engine). Calling it
170
- throws a clear error rather than failing silently.
171
- - Run \`kick doctor\` to verify the runtime's engine peers + upload driver are installed.
172
-
173
- ## v4 Conventions (don't skip)
174
-
175
- KickJS v4 made a handful of structural changes from v3. Internalise these
176
- before generating or modifying code — they are the source of most agent
177
- mistakes:
178
-
179
- - **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
180
-
181
- \`\`\`ts
182
- export const MyAdapter = defineAdapter<MyOptions>({
183
- name: 'MyAdapter',
184
- defaults: { ... },
185
- build: (config) => ({
186
- beforeMount({ app }) { /* ... */ },
187
- afterStart({ server }) { /* ... */ },
188
- }),
189
- })
190
- \`\`\`
191
-
192
- - **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
193
-
194
- - **DI tokens** — \`<scope>/<area>/<key>[:<instance>]\`. The scope is
195
- lowercase; the segments after it are identifiers (\`kick typegen\` warns
196
- on names that don't fit — a bare \`'UserRepository'\`, a dotted
197
- \`'app.db'\`):
198
-
199
- \`\`\`ts
200
- const USERS_REPO = createToken<UsersRepo>('app/Users/repository')
201
- const DB = createToken<Database>('app/Db/connection')
202
- \`\`\`
203
-
204
- The \`kick/\` prefix is reserved for first-party packages; this project
205
- owns its own scope (\`app/\`, your domain name, etc.).
206
-
207
- - **\`@Controller()\`** takes **no arguments**. Set the route prefix with the
208
- module's \`routes().path\`.
209
-
210
- - **Env** — the schema lives in \`src/config/index.ts\`. \`src/index.ts\` imports
211
- it once, as its **first** import (\`import './config'\`, before \`bootstrap()\`);
212
- tests that read config import it too (\`import '@/config'\`). Nothing else
213
- imports from \`src/config\`: read values with \`getEnv('KEY')\`, an injected
214
- \`ConfigService\` (\`config.get('KEY')\`), or \`@Value('KEY')\` typed as
215
- \`Env<'KEY'>\` — never \`process.env\`. Add a key to the schema before reading it.
216
- A concern with several keys (a database, a mail provider) gets a typed section
217
- instead: \`defineSettings('DB', schema)\` in the module's own
218
- \`<name>.settings.ts\` — not in \`src/config\` — declared by the module that
219
- needs it (\`settings: () => [DbSettings]\`) and read through
220
- \`@Inject(DbSettings)\` or \`DbSettings.get()\`. Its variables are \`DB_*\`.
221
-
222
- - **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
223
- HMR contract at the top of "Module Pattern" below. The CLI enforces this;
224
- hand-rolled files must too.
225
-
226
- - **Assets** — drop new template files into \`src/templates/<namespace>/\`
227
- (or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
228
- \`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
229
- no manual build step.
230
-
231
- - **Context over \`@Middleware()\`** — when a middleware's only job is to
232
- populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
233
- (HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
234
- Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
235
- Reserve \`@Middleware()\` for response short-circuit / stream mutation /
236
- pre-route-matching work.
237
-
238
- Two ground rules around the data flow — both stem from the fact that
239
- every per-request stage gets its OWN \`RequestContext\` instance, all
240
- reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
241
- - **\`resolve\` and \`onError\` must RETURN the value.** The runner
242
- writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
243
- property assignment (\`ctx.tenant = …\`) sticks to the contributor
244
- instance only — the handler instance never sees it.
245
- - **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
246
- \`getRequestValue(key)\` from a service that has no \`ctx\` reference
247
- — typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
248
- Express request is shared; bespoke property assignments don't.
249
-
250
- - **Test isolation** — default to \`Container.create()\` for fresh DI state.
251
- Never \`new Container()\` and never \`getInstance().reset()\` — both leak
252
- registrations between tests.
253
-
254
- \`\`\`ts
255
- const container = Container.create()
256
- // ... register test-scoped providers, run, discard
257
- \`\`\`
258
-
259
- - **Bootstrap export** — \`src/index.ts\` MUST end with
260
- \`export const app = await bootstrap({ ... })\`. The Vite plugin imports
261
- the named \`app\` symbol to drive HMR module swaps; testing helpers
262
- (\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
263
- the \`export\` and \`kick dev\` will silently fall back to a full restart
264
- on every save while \`createTestApp\` complains about a missing handle.
265
-
266
- - **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
267
- adapters in dedicated folders and re-export aggregated arrays. Do **not**
268
- inline registration in the entry file:
269
-
270
- \`\`\`ts
271
- // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
272
- export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
273
- // OR with \`modules.style: 'class'\`:
274
- // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
275
-
276
- // src/middleware/index.ts
277
- export const middleware = [helmet(), cors(), requestId(), ...]
278
-
279
- // src/plugins/index.ts
280
- export const plugins = [MetricsPlugin(), AuditPlugin()]
281
-
282
- // src/adapters/index.ts
283
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
284
- \`\`\`
285
-
286
- \`\`\`ts
287
- // src/index.ts — stays small; one import per category
288
- import 'reflect-metadata'
289
- import './config'
290
- import { bootstrap } from '@forinda/kickjs'
291
- import { modules } from './modules'
292
- import { middleware } from './middleware'
293
- import { plugins } from './plugins'
294
- import { adapters } from './adapters'
295
-
296
- export const app = await bootstrap({ modules, middlewares, plugins, adapters })
297
- \`\`\`
298
-
299
- This keeps the entry file diff-friendly, scales to dozens of modules
300
- without git churn, and lets each domain own its own registration list.
301
- The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
302
- \`kick g adapter\`) follow this layout — manual additions should too.
303
-
304
- Everything else (controllers, services, modules, RequestContext API, generators,
305
- package additions, env access patterns, troubleshooting) is detailed below.
306
-
307
- ## Where to Find Things
308
-
309
- ### Application Structure
310
-
311
- | What | Where |
312
- |------|-------|
313
- | Entry point | \`src/index.ts\` |
314
- | Module registry | \`src/modules/index.ts\` |
315
- | Feature modules | \`src/modules/<module-name>/\` |
316
- | **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
317
- | Env values | \`.env\` |
318
- | Env schema (Zod) | \`src/config/index.ts\` |
319
- | TypeScript config | \`tsconfig.json\` |
320
- | Vite config (HMR) | \`vite.config.ts\` |
321
- | Vitest config | \`vitest.config.ts\` |
322
- | Formatter config | \`.oxfmtrc.json\` (oxfmt) |
323
- | CLI config | \`kick.config.ts\` |
324
-
325
- ### Module Pattern (${n.toUpperCase()})
326
-
327
- > **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.
328
-
329
- Each module in \`src/modules/<name>/\` typically contains:
330
-
331
- ${n===`rest`?`\`\`\`
332
- <name>/
333
- ├── <name>.controller.ts # HTTP routes (@Controller)
334
- ├── <name>.service.ts # Business logic (@Service)
335
- ├── <name>.repository.ts # Data access — factory + contract + token
336
- ├── dtos/ # Request/response schemas (Zod)
337
- └── <name>.module.ts # Module definition (defineModule factory)
338
- \`\`\`
339
- `:"```\nsrc/\n├── index.ts # Add routes here\n└── ... # Custom structure\n```\n"}
340
-
341
- ## Checklist: Adding a Feature
342
-
343
- Follow the **\`kickjs-add-module\`** skill — it has the ordered steps, the
344
- canonical \`defineModule\` shape, and the \`import.meta.glob\` requirement that
345
- silently breaks DI when omitted.
346
-
347
- ## Common Tasks
348
-
349
- Each of these has a skill with the steps and the traps:
350
-
351
- | Task | Skill |
352
- | --- | --- |
353
- | Add a feature module | \`kickjs-add-module\` |
354
- | Add an adapter | \`kickjs-add-adapter\` |
355
- | Add a plugin | \`kickjs-add-plugin\` |
356
- | Add a context contributor | \`kickjs-context-contributor\` |
357
- | Write a controller test | \`kickjs-write-controller-test\` |
358
- | List endpoint with filters / pagination | \`kickjs-query-parsing-list-endpoint\` |
359
- | Serve bundled assets | \`kickjs-use-asset-manager\` |
360
- | Flag a route (public, exempt, unmetered) | \`kickjs-route-flags\` |
361
- | Add a kick CLI command or generator | \`kickjs-cli-plugin\` |
362
- | Deploy to Netlify / Vercel / Cloudflare | \`kickjs-deploy\` |
363
- | Anything else | \`kickjs-docs-lookup\` |
364
-
365
- ## Testing Guidelines
366
-
367
- See the **\`kickjs-write-controller-test\`** skill for the canonical test — it
368
- carries the call shape, the DI reset, and the env side-effect import, each of
369
- which has its own failure mode.
370
-
371
- Run with \`${i} run test\` (\`test:watch\` for watch mode).
372
-
373
- ## Environment Variables
374
-
375
- The schema lives in \`src/config/index.ts\` and registers itself with kickjs **at
376
- module load**; \`src/index.ts\` imports it (\`import './config'\`) before
377
- \`bootstrap()\` so the cache is populated before DI resolves anything. Add a key
378
- to the schema, put its value in \`.env\`, and it is typed everywhere.
379
-
380
- Read it with \`@Value('KEY')\` for construction-time values, or inject
381
- \`ConfigService\` for dynamic access.
382
-
383
- When a key reads as \`undefined\`, use the **\`kickjs-env-wiring-check\`** skill or
384
- run \`kick explain "ConfigService.get('KEY') returned undefined"\`. The cause
385
- differs between app code and tests and the two look identical, which is what
386
- makes it slow to spot.
387
-
388
- ## Standalone Utilities (No DI Required)
389
-
390
- These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
391
-
392
- | Utility | Import | Example |
393
- |---------|--------|---------|
394
- | \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
395
- | \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
396
- | \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/Db/url')\` |
397
- | \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
398
- | \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
399
- | \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
400
- | \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
401
- | \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
402
- | \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
403
-
404
- ## Key Decorators
405
-
406
- ### HTTP Routes
407
- | Decorator | Purpose |
408
- |-----------|---------|
409
- | \`@Controller()\` | Define route prefix |
410
- | \`@Get('/'), @Post('/')\` | HTTP method handlers |
411
- | \`@Middleware(fn)\` | Attach middleware |
412
- | \`@Public()\` | Skip auth (requires auth adapter) |
413
- | \`@Roles('admin')\` | Role-based access |
414
-
415
- ### Dependency Injection
416
- | Decorator | Purpose |
417
- |-----------|---------|
418
- | \`defineModule({...})\` | Define feature module (factory; preferred — paired with \`defineModules()\` registry) |
419
- | \`defineModules()\` | Build the modules registry as a chainable list (\`.mount(X())\`) |
420
- | \`AppModule\` interface | Legacy module shape — \`class X implements AppModule\` (toggle via \`modules.style: 'class'\`) |
421
- | \`@Service()\` | Register singleton service |
422
- | \`@Repository()\` | Register repository |
423
- | \`@Autowired()\` | Property injection |
424
- | \`@Inject('token')\` | Token-based injection |
425
- | \`@Value('VAR')\` | Inject env variable |
426
-
427
- ### Context Decorators
428
-
429
- Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
430
- Use this **instead of \`@Middleware()\`** when the middleware's only output
431
- is a value other code reads off \`ctx\`.
432
-
433
- **Authoring** — pick the right factory:
434
-
435
- | Factory | When |
436
- |---------|------|
437
- | \`defineHttpContextDecorator(spec)\` | HTTP only (the common case). \`Ctx\` is \`RequestContext\`, so \`ctx.req\` / \`ctx.params\` / \`ctx.query\` are typed. |
438
- | \`defineContextDecorator(spec)\` | Transport-agnostic (HTTP + WS + queue + cron). \`Ctx\` is \`ExecutionContext\` — only \`get\` / \`require\` / \`set\` / \`requestId\`. |
439
- | \`<either>.withParams<P>()(spec)\` | The contributor takes per-call params. **Always use the curried form for params** — the positional form forces you to spell \`K\` and \`D\` and loses \`deps\` inference. |
440
-
441
- Spec fields: \`{ key, deps, dependsOn, optional, paramDefaults, requiredParams, onError, resolve }\`.
442
-
443
- **Call sites — all five, precedence high → low:**
444
-
445
- | # | Site | Form |
446
- |---|------|------|
447
- | 1 | Method | \`@LoadX\` / \`@LoadX({ ... })\` above a controller method |
448
- | 2 | Class | \`@LoadX\` / \`@LoadX({ ... })\` above the controller class |
449
- | 3 | Module | \`defineModule({ build: () => ({ contributors: () => [LoadX.registration] }) })\` — or \`AppModule.contributors?()\` in class form |
450
- | 4 | Adapter | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
451
- | 5 | Global | \`bootstrap({ contributors: [LoadX.registration] })\` |
452
-
453
- Sites 3–5 take **registrations**, not decorators:
454
-
455
- - \`LoadX.registration\` — uses \`paramDefaults\` as-is.
456
- - \`LoadX.with({ ...params }).registration\` — call-site params merged over \`paramDefaults\`.
457
-
458
- Duplicate keys are resolved by precedence; the lower-precedence one is
459
- dropped silently, which is how a method-level decorator overrides an
460
- adapter-shipped default.
461
-
462
- **Params:** a **required** field of \`P\` with no \`paramDefaults\` entry must be
463
- supplied at every call site — \`@LoadX\` bare, \`@LoadX()\`, and \`.registration\`
464
- are compile errors for such a decorator. Never invent a placeholder default
465
- just to make the type check; add \`requiredParams: ['field']\` for runtime
466
- enforcement at JS call sites.
467
-
468
- **Reading values:** \`ctx.require('key')\` for values a contributor guarantees
469
- (throws \`MissingContextValueError\`, returns a non-optional type);
470
- \`ctx.get('key')\` for \`optional: true\` contributors and ad-hoc keys (returns
471
- \`| undefined\`). Never \`ctx.get('key')!\` — it compiles even when the producing
472
- decorator isn't applied to the route.
473
-
474
- | Concept | Where it lives |
475
- |---------|----------------|
476
- | Type augmentation (value types) | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
477
- | Type augmentation (key-only) | \`declare module '@forinda/kickjs' { interface ContextKeys { ... } }\` — valid in \`dependsOn\`, value stays \`unknown\` |
478
-
479
- Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
480
- fast). The \`onError\` hook is async-permitted.
481
-
482
- Full guide: <https://kickjs.app/guide/context-decorators>.
483
-
484
- ## Common Pitfalls
485
-
486
- See the **\`kickjs-deny-list\`** skill — the maintained list of things that
487
- compile, run, and are still wrong.
488
-
489
- For a specific failure, \`kick explain "<error message>"\` beats reading either:
490
- it matches the message against known causes and prints the fix.
491
-
492
- ## CLI Commands Reference
493
-
494
- See the **\`kickjs-cli-commands-cheatsheet\`** skill for the full table, the
495
- shell-safe field syntax, and the non-obvious flags. \`kick --help\` and
496
- \`kick <cmd> --help\` are authoritative for the installed version.
497
-
498
- ## Learn More
499
-
500
- Use the **\`kickjs-docs-lookup\`** skill — it maps questions to the right guide
501
- page and lists the local tools (\`kick explain\`, \`kick doctor\`, \`kick inspect\`,
502
- \`.kickjs/types/\`) that usually answer faster than a search.
503
-
504
- Start at <https://kickjs.app/>.
505
-
506
- `}function p(e,n=`define`){let i=n===`class`?`UserModule`:`UserModule()`;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".
507
-
508
- **Steps**:
509
- 1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
510
- 2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
511
- 3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
512
- 4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
513
- 5. Run \`kick typecheck\` and \`${e} run test\` before claiming done.
514
-
515
- **Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
516
-
517
- \`\`\`ts
518
- export const TodosModule = defineModule({
519
- name: 'TodosModule',
520
- build: () => ({
521
- register(container) {
522
- container.registerFactory(TODO_REPO, () => createTodoRepository())
523
- },
524
- routes() {
525
- return { path: '/todos', controller: TodosController }
526
- },
527
- }),
528
- })
529
- \`\`\`
530
-
531
- The module file MUST include \`import.meta.glob([...], { eager: true })\` for every \`@Controller\` / \`@Service\` / \`@Repository\` / \`@Component\` class — without it, decorators never fire and DI silently resolves to \`undefined\` (or routes vanish). Use **recursive** patterns (\`./**/*.controller.ts\`) so the glob keeps working when you nest files into sub-folders (\`controllers/\`, \`presentation/\`, …). If you reorganise and a class stops loading, \`kick typegen\` flags it as orphaned and \`kick typegen --fix\` patches the glob for you.
532
-
533
- **Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
534
-
535
- \`\`\`ts
536
- routes() {
537
- return [
538
- { path: '/todos', controller: TodosController }, // /api/v1/todos
539
- { path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
540
- ]
541
- }
542
- \`\`\`
543
-
544
- **Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
545
-
546
- **Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
547
-
548
- **Red flags** (stop and ask):
549
- - 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.
550
- - \`@Controller('/path')\` with a path argument — \`@Controller()\` takes no arguments; the prefix goes in the module's \`routes().path\`.
551
- - \`TodosModule\` instead of \`TodosModule()\` for a module that takes config — refused, since the bare name would silently select the defaults. A module with no config accepts either, but prefer the invoked form for consistency.
552
- - \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
553
- - 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: getEnv('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: getEnv('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):
554
-
555
- \`\`\`ts
556
- import { describe, it, expect, beforeEach } from 'vitest'
557
- import request from 'supertest'
558
- import { Container } from '@forinda/kickjs'
559
- import { createTestApp } from '@forinda/kickjs-testing'
560
- // Side-effect import — registers the env schema, exactly as src/index.ts does.
561
- // \`createTestApp\` never loads the entry file, so without this
562
- // \`ConfigService.get('YOUR_KEY')\` is undefined under test while \`@Value()\`
563
- // still appears to work via its process.env fallback — the two disagree only
564
- // in tests.
565
- import '@/config'
566
-
567
- describe('UserController', () => {
568
- beforeEach(() => Container.reset()) // isolate DI between tests
569
-
570
- it('returns users', async () => {
571
- // \`createTestApp\` takes an OPTIONS OBJECT and returns
572
- // \`{ app, container }\`. Passing a bare array throws
573
- // "this.options.modules is not iterable"; the result has no \`.get()\`.
574
- //
575
- // Drive \`app.handle\` rather than \`expressApp\`: it is the Application's
576
- // own Node listener, so the test runs on whichever runtime the app is
577
- // configured with. Pass \`runtime\` to \`createTestApp\` to match production.
578
- const { app } = await createTestApp({
579
- // Matches this project's \`modules.style\`.
580
- modules: [${i}],
581
- })
582
- const res = await request(app.handle.bind(app)).get('/api/v1/users')
583
- expect(res.status).toBe(200)
584
- })
585
- })
586
- \`\`\`
587
-
588
- **Typed handler signature** — pair with \`kick typegen\` so \`ctx.body\` / \`params\` / \`query\` are typed by the route's Zod schema:
589
-
590
- \`\`\`ts
591
- @Post('/', { body: createTodoSchema })
592
- async create(ctx: Ctx<KickRoutes.TodoController['create']>) {
593
- // ctx.body is typed from createTodoSchema; ctx.params from the route.
594
- // Returning (vs ctx.created) lets typegen infer the response type.
595
- return reply(201, await this.service.create(ctx.body))
596
- }
597
- \`\`\`
598
-
599
- **Red flags**:
600
- - \`new Container()\` — wrong; use \`Container.reset()\` in \`beforeEach\` or \`Container.create()\` for fully isolated graphs.
601
- - \`Container.getInstance().reset()\` — wrong; same fix.
602
- - Sharing a container instance across \`it()\` blocks — leaks registrations between tests.
603
- - Injecting a \`Scope.REQUEST\` service into a \`SINGLETON\` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.
604
- - Calling \`getRequestValue<string>('traceId')\` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.
605
- - Asserting on \`res.body.requestId\` when \`requestId()\` middleware isn't mounted in the test app — value will be \`undefined\`.
606
- - Using \`Scope.REQUEST\` services in a test without mounting \`requestScopeMiddleware()\` — \`getRequestValue\` silently returns \`undefined\`; \`getRequestStore\` throws.
607
-
608
- **Nuances**:
609
- - \`@Inject\` and \`@Autowired\` are interchangeable — same runtime, same types; pick by readability.
610
- - \`@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:`**Fastest path**: \`kick explain "ConfigService.get('MY_KEY') returned undefined"\` —
611
- pipe a failing run straight in if you prefer (\`${t(e,`test`)} 2>&1 | ${r(e,`kick`)} explain\`). It
612
- distinguishes the entry-file cause from the test-file one, which is the step most
613
- people lose time on. The manual checks below are the same reasoning.
614
-
615
- **Diagnosis (in order)**:
616
- 1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
617
- 2. Open \`src/config/index.ts\`. It MUST run the loader as a top-level side effect — not just declare the schema. This is what \`kick new\` generates:
618
- \`\`\`ts
619
- import { loadEnvFromSchema } from '@forinda/kickjs/config'
620
- import { fromZod } from '@forinda/kickjs-schema/zod'
621
- const envSchema = fromZod(z.object({ DATABASE_URL: z.url() }))
622
- loadEnvFromSchema(envSchema) // side effect: registers the schema
623
- export default envSchema
624
- \`\`\`
625
- App code reads values with \`getEnv('DATABASE_URL')\` (from \`@forinda/kickjs\`), an injected \`ConfigService\`, or \`@Value()\` — the config file exports no env object.
626
- 3. The new key MUST be declared in the 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 its parsing and defaults.
627
- 4. 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.
628
-
629
- 5. **In a test?** \`createTestApp\` never loads \`src/index.ts\`, so the entry's
630
- \`import './config'\` never runs no matter how correct it is. The test file
631
- must import it itself:
632
- \`\`\`ts
633
- import '@/config'
634
- \`\`\`
635
- Symptom is identical to the missing-entry-import case, and step 1 will look
636
- fine, which is what makes it slow to spot.
637
-
638
- **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.
639
-
640
- **\`reloadEnv\` vs \`resetEnvCache\`** — distinct, frequently mixed up:
641
- - \`reloadEnv()\` — re-reads \`process.env\` against the **already registered** schema. Use in HMR plugins after \`.env\` file changes. Schema survives.
642
- - \`resetEnvCache()\` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.
643
-
644
- **Nuances**:
645
- - \`dotenv\` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.
646
- - For HMR-friendly \`.env\` edits, add \`envWatchPlugin()\` to \`vite.config.ts\` — calls \`reloadEnv()\` automatically.
647
-
648
- **Fix recipe**: add the key to the schema; add \`import './config'\` as the first non-reflect-metadata import in \`src/index.ts\`; add \`import '@/config'\` to any test that reads config; 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**:
649
-
650
- \`\`\`ts
651
- // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
652
- export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
653
- // OR for class-form projects (\`modules.style: 'class'\`):
654
- // export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
655
-
656
- // src/middleware/index.ts — global middleware uses RAW EXPRESS signature
657
- // (req, res, next), NOT (ctx, next)
658
- // \`express.json()\` is auto-skipped on Fastify and h3, which parse bodies
659
- // natively — harmless to list, but don't reach for it as the body parser there.
660
- export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
661
-
662
- // src/plugins/index.ts
663
- export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: getEnv('TOKEN_TTL') })]
664
-
665
- // src/adapters/index.ts
666
- export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
667
-
668
- // src/index.ts — stays small
669
- import 'reflect-metadata'
670
- import './config' // MUST be early — side-effect schema load
671
- import { bootstrap } from '@forinda/kickjs'
672
- import { modules } from './modules'
673
- import { middleware } from './middleware'
674
- import { plugins } from './plugins'
675
- import { adapters } from './adapters'
676
- export const app = await bootstrap({ modules, middlewares, plugins, adapters })
677
- \`\`\`
678
-
679
- **One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
680
-
681
- \`\`\`ts
682
- plugins: [
683
- ...plugins,
684
- { name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
685
- ]
686
- \`\`\`
687
-
688
- **Red flags**:
689
- - Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
690
- - Mixing middleware signatures: \`bootstrap({ middlewares })\` is **raw Express** \`(req, res, next)\`; \`@Middleware()\` decorators are \`(ctx, next)\`; adapter middleware is connect-style too (mounted through the runtime seam, so it is not Express-only). Wrong shape in the wrong slot throws "Cannot read properties of undefined".
691
- - \`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// The `declare module` block above is all you need for typed `ctx.get`.\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 return 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 node request is shared). Note it is a node `IncomingMessage` on Fastify and a web-backed request on h3, not an `express.Request`.\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.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\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:`guard-vs-middleware-vs-contributor`,frontmatterName:`kickjs-guard-vs-middleware-vs-contributor`,description:`Use when adding auth checks, request-scoped values, or anything "before the handler" — picks between a guard, a middleware, and a context contributor.`,body:"**KickJS has no guard primitive.** There is no `@Guard`, no `canActivate`, no guard\nclass to implement. A guard IS a middleware — the word only names a convention\nand a directory. If you are porting NestJS habits, this is the first thing to\nunlearn.\n\n| | Guard | Middleware | Context contributor |\n|---|---|---|---|\n| What it is | a middleware, by convention | a middleware | a declarative value producer |\n| Signature | `(ctx, next)` | `(ctx, next)` on `@Middleware()`, `(req, res, next)` in `bootstrap({ middlewares })` | `resolve(ctx, deps)` returning a value |\n| Can end the request | yes | yes | **no** |\n| Runs | in the middleware stage | in the middleware stage | after ALL middleware |\n| Attached by | `@Middleware(fn)` | `@Middleware(fn)` or `bootstrap({ middlewares })` | `@LoadX`, or a registration at module / adapter / bootstrap level |\n| Generator | `kick g guard <name>` | `kick g middleware <name>` | `kick g contributor <name>` |\n| Lands in | `src/guards/<name>.guard.ts` | `src/middleware/<name>.middleware.ts` | `src/contributors/<name>.contributor.ts` |\n\nAdd `-m <module>` to any of those generators to place the file inside a module\ninstead of the app-level directory.\n\n**Choosing**: does the thing ever need to STOP the request?\n- Yes, and it is authorization → guard.\n- Yes, anything else (rate limit, body rewrite, response stream, work before route matching) → middleware.\n- No, it only computes a value the handler or a service reads off `ctx` → contributor. Typed, ordered, boot-validated, and it cannot silently swallow the request.\n\n**Ordering — guards run BEFORE contributors.** Every runtime does the same\nthing: run `entry.middlewares` in order, bail if the response was written,\nthen run the contributor pipeline, then the handler. So:\n\n```ts\n// WRONG — tenant is always undefined here.\nexport async function tenantGuard(ctx: RequestContext, next: () => void) {\n const tenant = ctx.get('tenant') // contributors have not run yet\n if (!tenant) return ctx.problem.forbidden()\n next()\n}\n```\n\nA guard that needs a resolved value must resolve it itself, or the check\nbelongs in the contributor's own `resolve` (throw from there and the request\nerror handler takes over).\n\n**Write responses with `ctx.*`, never `ctx.res`.** `ctx.res` is the ENGINE-NATIVE\nresponse object, so `ctx.res.status(401).json(...)` only works on Express —\n`FastifyReply` has no `.json()` and h3's event has no `.status()`. Use\n`ctx.problem.unauthorized({ detail })` (RFC 9457) or `ctx.json(body, status)`,\nand the helper for anything else you would reach `ctx.res` for:\n`ctx.download(buffer, filename, contentType?)` for a generated file,\n`ctx.html(content)`, `ctx.redirect(url, status?)`, `ctx.sse()` for a stream.\nAll of them work on all four runtimes. Never hand `ctx.redirect` a destination\ntaken from the request unchecked — allow-list it, or accept only a same-site path\n(one leading `/`, not `//`) — or the route is an open redirect.\n\n**Guard shape**:\n\n```ts\nimport type { RequestContext } from '@forinda/kickjs'\n\nexport async function adminGuard(ctx: RequestContext, next: () => void): Promise<void> {\n // Requires the session() middleware. Type the key once:\n // declare module '@forinda/kickjs' { interface SessionData { role?: 'admin' | 'member' } }\n const role = ctx.session?.data.role\n if (!role) {\n ctx.problem.unauthorized({ detail: 'Not signed in' })\n return // do NOT call next()\n }\n if (role !== 'admin') {\n ctx.problem.forbidden({ detail: 'Admin only' })\n return\n }\n next()\n}\n```\n\n```ts\n@Middleware(adminGuard)\n@Get('/admin/stats')\nstats(ctx: RequestContext) { ... }\n```\n\nRole checks that are purely declarative (`@Public()`, `@Roles('admin')`,\n`@Can(...)`) are yours to define — see the BYO Auth recipe in the docs.\nHand-write a guard only for logic those don't express.\n\n**Red flags**:\n- `class AdminGuard implements CanActivate` / `@UseGuards()` — NestJS, not KickJS. Export a `(ctx, next)` function and attach with `@Middleware()`.\n- A guard calling `next()` AND writing a response — pick one; writing then continuing double-sends.\n- A guard reading `ctx.get(...)` for a contributor-produced key — contributors have not run yet.\n- `ctx.res.status(403).json(...)` in a guard — Express-only. Use `ctx.problem.forbidden()`.\n- A \"guard\" that only sets a value and always calls `next()` — that is a contributor wearing a guard's name.\n- Passing a `(ctx, next)` guard to `bootstrap({ middlewares })` — global middleware is connect-style `(req, res, next)`. Mount guards per-route with `@Middleware()`.\n"},{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**:
692
- - \`kick new <name>\` — start a new project (prompts for template / repo / pm).
693
- - \`kick dev\` — local dev server with Vite HMR.
694
- - \`kick build\` — production bundle via Vite.
695
- - \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
696
- - \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
697
- - \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
698
- - \`kick g guard <name>\` / \`kick g middleware <name>\` / \`kick g contributor <name>\` — the three "before the handler" shapes. A guard is a middleware by convention, NOT a separate primitive.
699
- - \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
700
- - \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
701
- - \`kick info\` — environment / version dump for bug reports.
702
- - \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
703
-
704
- **Useful flag combos**:
705
-
706
- \`\`\`bash
707
- kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
708
- kick new my-api -t rest --pm ${e} --no-git --install # Fully scriptable REST scaffold
709
- kick new . --yes --force # Scaffold into current dir, clear existing files
710
- kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
711
- kick g agents -f --only skills # Refresh just the skills after upgrade
712
- kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
713
- kick inspect --port 4000 --json # Machine-readable route/adapter dump
714
- kick g config --force --repo postgres # Drop a kick.config.ts into a legacy project
715
- \`\`\`
716
-
717
- **Lesser-known, high-value**:
718
- - \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
719
- - \`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.
720
- - \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
721
- - \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
722
- - \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
723
- - \`kick check\` — preflight gate (typecheck + lint + format) before commit.
724
- - \`kick codemod\` — automated AST-level migration between framework versions.
725
-
726
- **Red flags**:
727
- - Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
728
- - Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
729
- - Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
730
- - Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
731
- - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`route-flags`,frontmatterName:`kickjs-route-flags`,description:`Use when a fact about a route (public, CSRF-exempt, unmetered, expose as a tool) has to be read by auth, CSRF, rate limiting, OpenAPI or MCP — instead of repeating it as paths in each consumer.`,body:"A route flag is a named, inheritable fact about a route. It carries no\nbehaviour: it records something every consumer can read, so \"this endpoint is\nopen\" is declared once instead of restated as an auth contributor, a\n`csrf ignorePaths` entry and a `rateLimit skipPaths` entry — two of which are\npathname strings that cannot express `/users/:id`.\n\n**Steps**:\n1. Declare it once, in its own module:\n ```ts\n import { defineRouteFlag } from '@forinda/kickjs'\n\n export const Public = defineRouteFlag('auth.public')\n export const Limit = defineRouteFlag<{ rpm: number }>('rate.limit')\n ```\n2. Apply it. A class flag is inherited by every route under it; `.off` on a\n method removes it:\n ```ts\n @Public // every route below inherits it\n @Controller()\n export class WebhooksController {\n @Get('/health')\n health(ctx: RequestContext) {} // public\n\n @Public.off // the method wins\n @Post('/admin')\n admin(ctx: RequestContext) {} // not public\n\n @Limit({ rpm: 10 }) // flags can carry a value\n @Post('/login')\n login(ctx: RequestContext) {}\n }\n ```\n3. Read it from the consumer that already exists, rather than a new one.\n **Where a consumer is mounted decides how it reads flags** — everything\n after route matching gets `ctx.route`; anything before it does not:\n\n | Consumer | Mounted at | Reads flags by |\n | --- | --- | --- |\n | Handler | the route itself | `ctx.route?.flags.has('auth.public')` |\n | Guard / `@Middleware()` | `@Middleware(fn)` on a method or controller class | `ctx.route`, or the built-ins' `exemptWhen` |\n | `csrfGuard()` / `rateLimitGuard()` | same — `@Middleware()`, class or method | `exemptWhen: 'csrf.exempt'` |\n | Contributor | method > class > module `contributors()` > adapter `contributors()` > `bootstrap({ contributors })` | `skipWhen` / `onlyWhen` on the registration |\n | Global middleware (`rateLimit()`) | `bootstrap({ middlewares: [...] })` — runs **before** matching | the route policy table (`bindRoutePolicy`); `ctx.route` is `undefined` here |\n | Adapter middleware | `AppAdapter.middleware()`, phase `beforeGlobal` … `afterRoutes` | the policy table — the handler is Express-style `(req, res, next)`, so there is no `ctx` in any phase |\n | OpenAPI | `SwaggerAdapter({ publicFlag: 'auth.public' })` | read once at startup, not per request |\n | MCP / AI tools | `McpAdapter({ exposeWhen: 'mcp.tool', hideWhen: 'mcp.hidden' })` | read once at startup |\n\n The contributor row is the one that buys the most: those five levels mean a\n plugin's contributor can be skipped on one route (`skipWhen`) without\n forking it, and a method-level registration beats the adapter's.\n\n4. Run `kick typegen`. It writes the `KickRouteFlags` augmentation, so flag\n names autocomplete and a typo fails `tsc` instead of silently never matching.\n\n**Red flags**:\n- Writing `@Public(false)` to remove a flag — removal is `@Public.off`. A\n resolved flag is present or absent; `false` is a legitimate *value* for a\n flag declared `boolean`, and a presence check would still answer `true`.\n- A new consumer growing its own `skipPaths` / `ignorePaths` list — that is\n the duplication flags exist to remove, and path strings break on params and\n on any `apiPrefix` change.\n- `@Public.off` on a route that never inherited the flag — a no-op, and\n usually a sign the expected class-level flag is not there.\n- Reading `ctx.route` in global middleware — it is `undefined` before a route\n is matched (steps 1-6 of the pipeline). Move the check into a guard mounted\n with `@Middleware()`, or read the policy table.\n- Inventing a flag name per consumer (`auth.open`, `public`, `isPublic`). The\n framework names none of them; pick one name per fact and reuse it."},{slug:`cli-plugin`,frontmatterName:`kickjs-cli-plugin`,description:`Use when adding a kick <name> command, a kick g <name> generator, or a typegen emitter to this project or a package it ships.`,body:"A CLI plugin contributes commands, generators and typegen emitters to the\n`kick` CLI. Every built-in command ships as one, so the contract is the same\none the framework uses.\n\n**Steps**:\n1. Write the plugin. All four contribution kinds are optional:\n ```ts\n // kick-tool.ts\n import { defineCliPlugin } from '@forinda/kickjs-cli'\n\n export const toolPlugin = (options: { watch?: boolean } = {}) =>\n defineCliPlugin({\n // Stable id, unique across plugins — it names the plugin in conflict errors.\n name: 'my-tool',\n // Declarative: same shape as kick.config.ts `commands`.\n commands: [{ name: 'db:migrate', description: 'Apply migrations', steps: 'node ./scripts/migrate.js' }],\n // Programmatic: full commander API, when you need options or subcommands.\n register(program, ctx) {\n program\n .command('my-tool')\n .description('Do the thing')\n .option('--watch', 'Watch mode')\n .action(async () => {\n ctx.log(`running in ${ctx.projectRoot}`)\n // ctx.config is the loaded kick.config.ts\n })\n },\n })\n ```\n2. Register it in `kick.config.ts`:\n ```ts\n import { toolPlugin } from './kick-tool'\n\n export default defineConfig({ plugins: [toolPlugin()] })\n ```\n3. Check it is loaded, per contribution kind: `kick --help` lists a command,\n `kick g --list` lists a generator, `kick typegen` runs an emitter. A\n plugin that fails to load takes the whole CLI down with a conflict error,\n so silence here means the config never referenced it.\n\n**Which kind to use**: `commands` for a shell one-liner, `register` for\noptions / subcommands / async work, `generators` (`defineGenerator`) for\n`kick g <name>` scaffolders, `typegens` for a file under `.kickjs/types/`.\n\n**Red flags**:\n- Confusing this with a runtime plugin: `defineCliPlugin` (from\n `@forinda/kickjs-cli`) extends the CLI; `definePlugin` (from\n `@forinda/kickjs`) hooks the running app. They share nothing.\n- Claiming a command name a built-in owns (`build:netlify`, `typegen`,\n `generate`) — duplicate declarative names are a startup conflict, and\n `register` has no conflict detection at all, so it silently loses. Namespace\n your own (`my-tool:build`).\n- Doing real work inside `register` — it runs at CLI startup for every\n command, so it must only register. Put the work in the action.\n- Importing heavy dependencies at module scope. `await import()` them inside\n the action, so an unrelated `kick dev` does not pay for them."},{slug:`deploy`,frontmatterName:`kickjs-deploy`,description:`Use when deploying this app — a Node host or Docker, Netlify, Vercel or Cloudflare Workers — or when an API route returns the SPA shell, the platform build fails, or the function is missing from a deploy.`,body:`Deploy files are added on demand: \`kick g deploy docker\` writes a
732
- \`Dockerfile\` and \`.dockerignore\`; \`kick g deploy netlify vercel\` writes
733
- \`netlify.toml\` / \`vercel.json\`, \`src/serverless.ts\` and the
734
- \`build:netlify\` / \`build:vercel\` scripts.
735
-
736
- **A Node host or a container** runs the long-running server. Without Docker:
737
-
738
- \`\`\`bash
739
- ${e} run build && NODE_ENV=production node dist/index.js
740
- \`\`\`
741
-
742
- Start it with \`node\`, not \`kick start\`: the CLI is a dev dependency, gone
743
- after a production install. The image installs from the lockfile, so commit it.
744
-
745
- **Netlify and Vercel** run the app as a Node function; the CLI builds both:
746
-
747
- \`\`\`bash
748
- ${e} run build:netlify # → .netlify/v1/functions/api.mjs
749
- ${e} run build:vercel # → .vercel/output (Build Output API v3)
750
- \`\`\`
751
-
752
- Both bundle \`src/serverless.ts\`:
753
- \`createHandler(() => import('./index'))\` serves the app \`src/index.ts\`
754
- describes — its \`bootstrap()\` call builds the app without listening — so
755
- there is one set of options. Add middleware and adapters to \`src/index.ts\`
756
- as usual.
757
-
758
- Settings are detected from the layout: a workspace member beside a \`web\`
759
- package publishes \`web/dist\` and routes \`/api/*\`; an Inertia app publishes
760
- \`dist/client\`, packages the asset manifest and SSR bundle with the function,
761
- and lets it take every other path; a standalone API takes every path.
762
- Override in \`kick.config.ts\`:
763
-
764
- \`\`\`ts
765
- export default defineConfig({
766
- deploy: { apiPath: '/api', staticDir: '../web/dist', include: ['data/geo.json'] },
767
- })
768
- \`\`\`
769
-
770
- \`include\` lists files the app reads at runtime; they are packaged with the
771
- function. Memory does not survive between function instances: keep sessions in
772
- \`session({ store: 'cookie' })\` or a shared store, and data in a database.
773
-
774
- **Cloudflare Workers** is a different entry, not a third flag on this one.
775
- Workers have no \`node:http\`, so \`createHandler\` cannot run there; use the
776
- web entry over h3 v2:
777
-
778
- \`\`\`ts
779
- // src/worker.ts
780
- import 'reflect-metadata'
781
- import { createFetchHandler } from '@forinda/kickjs/web'
782
- import * as h3 from 'h3' // v2 — passed in, edge bundlers have no createRequire
783
- import { modules } from './modules'
784
-
785
- export default createFetchHandler((env) => ({ h3, modules, env }))
786
- \`\`\`
787
-
788
- Two things make or break that deploy:
789
-
790
- 1. **Pre-bundle it yourself.** Point \`wrangler.jsonc\`'s \`main\` at a bundle
791
- built with SWC (the same Vite + \`unplugin-swc\` setup as the other
792
- targets), never at \`src/worker.ts\`. Wrangler's own esbuild compiles
793
- decorators as ES decorators and emits no decorator metadata, so DI fails
794
- at startup with a \`getOwnMetadata\` TypeError before any request lands.
795
- 2. **\`compatibility_flags = ["nodejs_compat"]\`** — request-scoped DI and
796
- \`ctx.set\` / \`ctx.get\` ride on \`AsyncLocalStorage\`.
797
- 3. **Do not \`import './config'\` here.** It is required in \`src/index.ts\` and
798
- \`src/serverless.ts\`, and wrong in a Worker twice over: the config module
799
- reaches for \`node:fs\` / \`createRequire\`, which kills the Worker at
800
- startup, and \`loadEnvFromSchema\` parses \`process.env\`, which Workers do
801
- not have. The \`env\` binding threaded through \`createFetchHandler\` is what
802
- feeds \`ConfigService.get()\` and \`@Value()\` instead — so values arrive as
803
- the raw strings the platform holds, without the schema's coercion or
804
- defaults. Coerce where you read them.
805
-
806
- Not available on Workers: views, SPA/static serving, \`@Asset\`, adapters and
807
- plugins. Serve static files from Workers Assets or a separate deploy.
808
-
809
- **Red flags**:
810
- - An \`/api/*\` route returning \`index.html\` on Netlify — the function is not
811
- routed. Check the deploy summary says a function was deployed, keep
812
- \`preferStatic\` out of a fullstack function's config, and leave Netlify's
813
- **Package directory** unset so it reads the function at the repo root.
814
- - Validation errors or flash messages that vanish on Netlify / Vercel — the
815
- session lives in one instance's memory. Use \`session({ store: 'cookie' })\`.
816
- - Committing \`.netlify/\` or \`.vercel/\` — both are build output.
817
- - A frontend that builds somewhere other than \`web/dist\` and only one of
818
- \`deploy.staticDir\`, \`SpaAdapter({ clientDir })\` and netlify.toml's
819
- \`publish\` updated. All three name that directory.
820
- - Pointing a platform at \`src/index.ts\` — it calls \`bootstrap()\`, which
821
- listens on a port and registers signal handlers inside the function. The
822
- platform entry is \`src/serverless.ts\`.
823
- - Expecting \`kick build\` alone to produce a deployable function; it builds
824
- the server. Run the target command after it.`},{slug:`docs-lookup`,frontmatterName:`kickjs-docs-lookup`,description:`Use FIRST when unsure about any KickJS API, option, or behaviour — before guessing from memory or inferring from surrounding code.`,body:`These skills are deliberately short — they cover the traps, not the whole API
825
- surface. When the answer is not in one of them, read the docs rather than
826
- inferring it from nearby code: a wrong guess about a framework API compiles
827
- fine and fails at runtime.
828
-
829
- **Where to look**
830
-
831
- | Question | Page |
832
- | --- | --- |
833
- | Anything — start here | https://kickjs.app/ |
834
- | Controllers, routing, \`ctx\` helpers | https://kickjs.app/guide/controllers |
835
- | DI, tokens, scopes | https://kickjs.app/guide/dependency-injection |
836
- | Modules and mounting | https://kickjs.app/guide/modules |
837
- | Adapters, plugins, lifecycle hooks | https://kickjs.app/guide/adapters |
838
- | Context Contributors | https://kickjs.app/guide/context-decorators |
839
- | Env, \`ConfigService\`, \`@Value\` | https://kickjs.app/guide/configuration |
840
- | Middleware and guards | https://kickjs.app/guide/middleware |
841
- | Testing (\`createTestApp\`) | https://kickjs.app/guide/testing |
842
- | Typegen and generated types | https://kickjs.app/guide/typegen |
843
- | HMR and the dev server | https://kickjs.app/guide/hmr |
844
-
845
- **Local, and usually faster**
846
-
847
- - \`kick explain "<error message>"\` — matches known failures and gives the fix.
848
- Pipe a failing run in: \`${t(e,`test`)} 2>&1 | ${r(e,`kick`)} explain\`.
849
- - \`kick doctor\` — checks this project's wiring.
850
- - \`kick inspect\` — the live route / adapter table.
851
- - \`.kickjs/types/\` — generated types are ground truth for what exists.
852
- - \`node_modules/@forinda/kickjs/dist/*.d.mts\` — the real signature when a doc
853
- page and the code disagree.
854
-
855
- **Rule**: if you would be guessing, look it up. If a doc page contradicts the
856
- installed \`.d.mts\`, trust the \`.d.mts\` and say so — the docs may be behind the
857
- version this project has.`},{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 → `@Controller()`, with the prefix in `routes().path`.\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({ middlewares })` — 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- Omitting the `declare module '@forinda/kickjs'` block — without it `ctx.get('tenant')` is `unknown`.\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`."}]}function m(e,t,n,r=`define`){let i=`<!-- Generated by \`kick g agents\` for ${e}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`;return p(n,r).map(e=>({slug:e.slug,content:`---
858
- name: ${e.frontmatterName}
859
- description: ${e.description}
860
- ---
861
-
862
- ${i}
863
-
864
- ${e.body}
865
- `}))}function h(e,t,n){return`# GEMINI.md — ${e}
866
-
867
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
868
- reference for this project — every convention, structure, decorator
869
- pattern, env wiring rule, generator usage. This file is a thin
870
- Gemini-specific layer; when the two disagree on anything substantive,
871
- treat \`AGENTS.md\` as authoritative and flag the discrepancy.
872
-
873
- ## Why this file
874
-
875
- Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
876
- agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
877
- means Gemini reads the same shared prose as Codex / Cursor / Copilot
878
- without us copy-pasting.
879
-
880
- ## Gemini-specific notes
881
-
882
- - **Skills activation** — Gemini activates skills via
883
- \`activate_skill\` (its native MCP-style tool); the equivalent on
884
- Claude Code is the \`Skill\` tool. Cross-reference the
885
- \`kickjs-skills.md\` index for the available triggers.
886
- - **Tool naming** — Gemini's tool names differ from Claude Code's
887
- (e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
888
- \`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
889
- tool names; consult Gemini's docs for the concrete invocation.
890
- - **File ops** — Gemini's file edits are sandboxed; large refactors
891
- may need explicit confirmation. Prefer the smallest-possible-edit
892
- pattern.
893
-
894
- ## Refreshing this file
895
-
896
- \`kick g agents --only gemini -f\` regenerates this file from the
897
- CLI template. Hand-edited content is overwritten — keep customisation
898
- in \`.agents/GEMINI.local.md\`.
899
- `}function g(e,t,n){return`# COPILOT.md — ${e}
900
-
901
- **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
902
- reference for this project — every convention, structure, decorator
903
- pattern, env wiring rule, generator usage. This file is a thin
904
- Copilot-specific layer; when the two disagree on anything substantive,
905
- treat \`AGENTS.md\` as authoritative and flag the discrepancy.
906
-
907
- ## Why this file
908
-
909
- GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
910
- the agent-context files. Keeping it in \`.agents/\` next to
911
- \`AGENTS.md\` means Copilot reads the same shared prose as
912
- Codex / Cursor / Gemini / Claude Code without copy-pasting.
913
-
914
- ## Copilot-specific notes
915
-
916
- - **Skills** — Copilot CLI auto-discovers skills from installed
917
- plugins; cross-reference \`kickjs-skills.md\` for available
918
- triggers in this project.
919
- - **Tool naming** — Copilot's tool names differ from Claude Code's
920
- (\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
921
- prose in \`AGENTS.md\` describes intents, not tool names; consult
922
- Copilot's docs for the concrete invocation.
923
- - **Confirmation flows** — Copilot CLI surfaces destructive
924
- operations through an explicit approval gate. Stage edits with
925
- short, focused diffs so each one is easy to review at the prompt.
926
-
927
- ## Refreshing this file
928
-
929
- \`kick g agents --only copilot -f\` regenerates this file from the
930
- CLI template. Hand-edited content is overwritten — keep customisation
931
- in \`.agents/COPILOT.local.md\`.
932
- `}var _=/* @__PURE__ */ e({generateAgentDocs:()=>C});const v=`.agents`,y=/* @__PURE__ */ new Set([`rest`,`minimal`,`fullstack`,`inertia`]);function b(e,t){if(t)return t;try{let t=JSON.parse(c(l(e,`package.json`),`utf-8`));if(t.name)return t.name.replace(/^@[^/]+\//,``)}catch{}return e.split(`/`).findLast(Boolean)??`app`}async function x(e){try{return(await n(e))?.modules?.style===`class`?`class`:`define`}catch{return`define`}}async function S(e,t){if(t)return t;try{let t=(await n(e))?.pattern;if(t&&y.has(t))return t}catch{}return`rest`}async function C(e){let t=e.only??`all`,n=b(e.outDir,e.name),r=await o(e.pm,e.outDir),c=await S(e.outDir,e.template),u=await x(e.outDir),p=t===`agents`||t===`both`||t===`all`,_=t===`claude`||t===`both`||t===`all`,y=t===`skills`||t===`all`,C=t===`gemini`||t===`all`,w=t===`copilot`||t===`all`,T=[];if(p&&T.push({file:l(e.outDir,v,`AGENTS.md`),render:()=>f(n,c,r)}),_&&T.push({file:l(e.outDir,`CLAUDE.md`),render:()=>d(n,c,r)}),y)for(let t of m(n,c,r,u))T.push({file:l(e.outDir,v,`skills`,t.slug,`SKILL.md`),render:()=>t.content});C&&T.push({file:l(e.outDir,v,`GEMINI.md`),render:()=>h(n,c,r)}),w&&T.push({file:l(e.outDir,v,`COPILOT.md`),render:()=>g(n,c,r)});let E=[];for(let{file:t,render:n}of T)s(t)&&!e.force&&!await a({message:`${t.replace(e.outDir+`/`,``)} already exists. Overwrite?`,initialValue:!1})?console.log(` Skipped — existing ${t.replace(e.outDir+`/`,``)} preserved.`):(await i(t,n()),E.push(t));return E}export{C as n,_ as t};