@forinda/kickjs-cli 5.5.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{run-plugins-GOyvsWi5.mjs → builtins-BIpoT6cb.mjs} +2 -2
- package/dist/cli.mjs +4086 -2
- package/dist/config-BQUzGk6m.mjs +12 -0
- package/dist/{config-BSo8gLtM.mjs.map → config-BQUzGk6m.mjs.map} +1 -1
- package/dist/{generator-extension-CEYm6tuj.mjs → generator-extension-Cd2DU_XX.mjs} +264 -28
- package/dist/generator-extension-Cd2DU_XX.mjs.map +1 -0
- package/dist/index.d.mts +100 -30
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -0
- package/dist/{plugin-CVRofuDz.mjs → plugin-B6ANfh7O.mjs} +3 -3
- package/dist/{plugin-CVRofuDz.mjs.map → plugin-B6ANfh7O.mjs.map} +1 -1
- package/dist/project-root-Dsxhm7OL.mjs +12 -0
- package/dist/project-root-Dsxhm7OL.mjs.map +1 -0
- package/dist/{rolldown-runtime-BrsfUx5e.mjs → rolldown-runtime-jjtMmVBF.mjs} +1 -1
- package/dist/{builtins-BpWIctor.mjs → run-plugins-DaO1FtZb.mjs} +90 -288
- package/dist/run-plugins-DaO1FtZb.mjs.map +1 -0
- package/dist/{typegen-DyXcnNCk.mjs → typegen-D-1Q9yBD.mjs} +4 -4
- package/dist/{typegen-DyXcnNCk.mjs.map → typegen-D-1Q9yBD.mjs.map} +1 -1
- package/dist/{types-CYw_hoZY.mjs → types-Du3p7CZ5.mjs} +2 -2
- package/dist/types-Du3p7CZ5.mjs.map +1 -0
- package/package.json +8 -7
- package/dist/builtins-5aWa9xTa.mjs +0 -3952
- package/dist/builtins-BpWIctor.mjs.map +0 -1
- package/dist/config-BSo8gLtM.mjs +0 -12
- package/dist/config-BefQBc0L.mjs +0 -11
- package/dist/generator-extension-CEYm6tuj.mjs.map +0 -1
- package/dist/plugin-By4fjCki.mjs +0 -11
- package/dist/typegen-CZMLNEJQ.mjs +0 -116
- package/dist/types-CYw_hoZY.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-cli v5.
|
|
2
|
+
* @forinda/kickjs-cli v5.7.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -1762,24 +1762,50 @@ export const ${a}Adapter = defineAdapter<${a}AdapterConfig>({
|
|
|
1762
1762
|
`),o.push(s),o}const Ye={controller:`presentation`,service:`domain/services`,dto:`application/dtos`,guard:`presentation/guards`,middleware:`middleware`},Xe={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`},Ze={controller:``,service:``,dto:`dtos`,guard:`guards`,middleware:`middleware`,command:`commands`,query:`queries`,event:`events`};function Q(e){let{type:t,outDir:n,moduleName:a,modulesDir:o=`src/modules`,defaultDir:s,pattern:c=`ddd`,shouldPluralize:l=!0}=e;if(n)return i(n);if(a){let e=c===`ddd`?Ye:c===`cqrs`?Ze:Xe,n=k(a),s=l?A(n):n,u=e[t]??``,d=r(o,s);return i(u?r(d,u):d)}return i(s)}async function Qe(e){let{name:t,moduleName:n,modulesDir:i,pattern:a}=e,o=Q({type:`middleware`,outDir:e.outDir,moduleName:n,modulesDir:i,defaultDir:`src/middleware`,pattern:a,shouldPluralize:e.pluralize??!0}),s=k(t),c=O(t),l=[],u=r(o,`${s}.middleware.ts`);return await b(u,`import type { Request, Response, NextFunction } from 'express'
|
|
1763
1763
|
|
|
1764
1764
|
export interface ${D(t)}Options {
|
|
1765
|
-
// Add configuration options here
|
|
1765
|
+
// Add configuration options here. The factory below closes over the
|
|
1766
|
+
// resolved options object; pass them at the call site —
|
|
1767
|
+
// \`${c}({ foo: 'bar' })\` — and the closure preserves them across
|
|
1768
|
+
// every request.
|
|
1766
1769
|
}
|
|
1767
1770
|
|
|
1768
1771
|
/**
|
|
1769
1772
|
* ${D(t)} middleware.
|
|
1770
1773
|
*
|
|
1771
|
-
* Usage in bootstrap:
|
|
1774
|
+
* Usage in bootstrap (fires on every request):
|
|
1772
1775
|
* middleware: [${c}()]
|
|
1773
1776
|
*
|
|
1774
|
-
* Usage with adapter:
|
|
1775
|
-
*
|
|
1777
|
+
* Usage with adapter — phase controls *when* the handler runs:
|
|
1778
|
+
*
|
|
1779
|
+
* middleware() {
|
|
1780
|
+
* return [{ handler: ${c}(), phase: 'afterGlobal' }]
|
|
1781
|
+
* }
|
|
1782
|
+
*
|
|
1783
|
+
* Phase semantics (see \`MiddlewarePhase\` JSDoc for the full contract):
|
|
1784
|
+
* - 'beforeGlobal' / 'afterGlobal' / 'beforeRoutes' — fire on every
|
|
1785
|
+
* request, before module routes run.
|
|
1786
|
+
* - 'afterRoutes' — fires ONLY when no route matched (404 fall-through)
|
|
1787
|
+
* OR a route handler called \`next()\` without ending the response.
|
|
1788
|
+
* Controllers that call \`ctx.json(…)\` end the chain and skip this
|
|
1789
|
+
* phase. For per-response work (logging, metrics) attach to
|
|
1790
|
+
* \`res.on('finish', …)\` from an earlier-phase middleware instead.
|
|
1791
|
+
*
|
|
1792
|
+
* Optional path scope — string, RegExp, or array of either:
|
|
1793
|
+
* middleware() {
|
|
1794
|
+
* return [{
|
|
1795
|
+
* handler: ${c}({ region: 'eu' }),
|
|
1796
|
+
* phase: 'afterGlobal',
|
|
1797
|
+
* path: ['/api', /^\\/admin/],
|
|
1798
|
+
* }]
|
|
1799
|
+
* }
|
|
1776
1800
|
*
|
|
1777
1801
|
* Usage with @Middleware decorator:
|
|
1778
1802
|
* @Middleware(${c}())
|
|
1779
1803
|
*/
|
|
1780
1804
|
export function ${c}(options: ${D(t)}Options = {}) {
|
|
1781
1805
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
1782
|
-
// Implement your middleware logic here
|
|
1806
|
+
// Implement your middleware logic here. \`options\` is captured by
|
|
1807
|
+
// closure — log or read it anywhere in this handler body.
|
|
1808
|
+
void options
|
|
1783
1809
|
next()
|
|
1784
1810
|
}
|
|
1785
1811
|
}
|
|
@@ -1857,7 +1883,7 @@ export const ${l}Schema = z.object({
|
|
|
1857
1883
|
})
|
|
1858
1884
|
|
|
1859
1885
|
export type ${c}DTO = z.infer<typeof ${l}Schema>
|
|
1860
|
-
`),u.push(d),u}const rt={
|
|
1886
|
+
`),u.push(d),u}const rt={swagger:`@forinda/kickjs-swagger`,ws:`@forinda/kickjs-ws`,queue:`@forinda/kickjs-queue`,devtools:`@forinda/kickjs-devtools`};function $(e,t){let n=e[t];if(!n)throw Error(`generatePackageJson: missing resolved version for ${t}. Add it to SIBLING_PACKAGES in generators/project.ts.`);return n}function it(e,t,n,r=[]){let i={"@forinda/kickjs":$(n,`@forinda/kickjs`),dotenv:`^17.3.1`,express:`^5.1.0`,"reflect-metadata":`^0.2.2`,zod:`^4.3.6`,pino:`^10.3.1`,"pino-pretty":`^13.1.3`};for(let e of r){let t=rt[e];t&&!i[t]&&(i[t]=$(n,t))}return JSON.stringify({name:e,version:`0.0.0`,type:`module`,scripts:{dev:`vite`,"dev:debug":`kick dev:debug`,build:`kick build`,start:`kick start`,test:`vitest run`,"test:watch":`vitest`,typecheck:`tsc --noEmit`,typegen:`kick typegen`,lint:`eslint src/`,format:`prettier --write src/`},dependencies:i,devDependencies:{"@forinda/kickjs-cli":$(n,`@forinda/kickjs-cli`),"@forinda/kickjs-vite":$(n,`@forinda/kickjs-vite`),"@swc/core":`^1.15.21`,"@types/express":`^5.0.6`,"@types/node":`^25.0.0`,"unplugin-swc":`^1.5.9`,vite:`^8.0.3`,vitest:`^4.1.2`,typescript:`^6.0.3`,prettier:`^3.8.1`}},null,2)}function at(){return`import { defineConfig } from 'vite'
|
|
1861
1887
|
import { resolve } from 'node:path'
|
|
1862
1888
|
import swc from 'unplugin-swc'
|
|
1863
1889
|
import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
|
|
@@ -2010,27 +2036,35 @@ Copy \`.env.example\` to \`.env\` and configure:
|
|
|
2010
2036
|
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
2011
2037
|
`}function ht(e,t,n){return`# CLAUDE.md — ${e}
|
|
2012
2038
|
|
|
2013
|
-
**Read
|
|
2039
|
+
**Read \`./.agents/AGENTS.md\` first.** It is the canonical, multi-agent
|
|
2014
2040
|
reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
|
|
2015
2041
|
project conventions, structure, decorator patterns, env wiring, CLI
|
|
2016
2042
|
generators, every gotcha.
|
|
2017
2043
|
|
|
2018
|
-
**Then
|
|
2019
|
-
skill
|
|
2020
|
-
|
|
2021
|
-
|
|
2044
|
+
**Then browse \`./.agents/skills/\`.** Each subdirectory is a single
|
|
2045
|
+
task-oriented skill (\`add-module/\`, \`write-controller-test/\`,
|
|
2046
|
+
\`bootstrap-export/\`, \`deny-list/\`, …) containing a \`SKILL.md\`
|
|
2047
|
+
with YAML frontmatter (\`name\`, \`description\`) and the recipe body.
|
|
2048
|
+
The structure follows the Claude Code skills convention — agents that
|
|
2049
|
+
auto-load skills from \`.agents/skills/\` will pick each up by its
|
|
2050
|
+
frontmatter. Use this directory as the playbook when executing common
|
|
2051
|
+
KickJS workflows.
|
|
2022
2052
|
|
|
2023
2053
|
This file is a thin Claude-specific layer on top of those two; when
|
|
2024
|
-
they disagree on anything substantive, treat
|
|
2054
|
+
they disagree on anything substantive, treat \`.agents/AGENTS.md\` as
|
|
2025
2055
|
authoritative and flag the discrepancy.
|
|
2026
2056
|
|
|
2027
|
-
## Why
|
|
2057
|
+
## Why \`.agents/\` + this thin pointer
|
|
2028
2058
|
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2059
|
+
\`.agents/AGENTS.md\` is what every agent reads (Codex, Cursor, Gemini,
|
|
2060
|
+
Copilot, Aider, …) — one canonical source so the prose doesn't drift
|
|
2061
|
+
across copies. \`CLAUDE.md\` is what Claude Code automatically loads as
|
|
2062
|
+
project context on each conversation, so it stays at the project root.
|
|
2063
|
+
Keeping CLAUDE.md slim and pointing at \`.agents/\` avoids two
|
|
2064
|
+
out-of-sync copies of the same content. Per-agent files
|
|
2065
|
+
(\`.agents/GEMINI.md\`, \`.agents/COPILOT.md\`) live alongside
|
|
2066
|
+
\`AGENTS.md\` for tool-specific notes that don't belong in the shared
|
|
2067
|
+
prose.
|
|
2034
2068
|
|
|
2035
2069
|
## Claude-specific notes
|
|
2036
2070
|
|
|
@@ -2045,7 +2079,7 @@ us copy-pasting.
|
|
|
2045
2079
|
or background work. Useful for "wait for the deploy then open a
|
|
2046
2080
|
cleanup PR" or "every Monday triage the issue board" patterns.
|
|
2047
2081
|
|
|
2048
|
-
## Quick reference (full version in AGENTS.md)
|
|
2082
|
+
## Quick reference (full version in .agents/AGENTS.md)
|
|
2049
2083
|
|
|
2050
2084
|
\`\`\`bash
|
|
2051
2085
|
${n} install # Install dependencies
|
|
@@ -2058,7 +2092,7 @@ ${n} run format # Prettier
|
|
|
2058
2092
|
|
|
2059
2093
|
## v4 framework reminders
|
|
2060
2094
|
|
|
2061
|
-
When generating or modifying code in this project, stay aligned with the v4 conventions documented in
|
|
2095
|
+
When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`.agents/AGENTS.md\`:
|
|
2062
2096
|
|
|
2063
2097
|
- **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
|
|
2064
2098
|
- **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
|
|
@@ -2071,9 +2105,9 @@ When generating or modifying code in this project, stay aligned with the v4 conv
|
|
|
2071
2105
|
- **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
|
|
2072
2106
|
- **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.
|
|
2073
2107
|
- **Thin entry file**: aggregate \`modules\`, \`middleware\`, \`plugins\`, \`adapters\` in their own folders (\`src/modules/index.ts\`, \`src/middleware/index.ts\`, …) and pass them by name to \`bootstrap()\` — never inline the lists in \`src/index.ts\`.
|
|
2074
|
-
- **Refresh these files**: \`kick g agents -f\` regenerates \`AGENTS.md\` + \`
|
|
2108
|
+
- **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.
|
|
2075
2109
|
|
|
2076
|
-
For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) →
|
|
2110
|
+
For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`.agents/AGENTS.md\`.
|
|
2077
2111
|
`}function gt(e,t,n){return`# AGENTS.md — AI Agent Guide for ${e}
|
|
2078
2112
|
|
|
2079
2113
|
This guide is the **canonical, multi-agent reference** for this KickJS
|
|
@@ -2581,7 +2615,142 @@ ${t===`cqrs`?`### Background Jobs
|
|
|
2581
2615
|
- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
2582
2616
|
- [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
|
|
2583
2617
|
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
2584
|
-
`}function _t(e,t,n){
|
|
2618
|
+
`}function _t(e,t,n){let r=`<!-- Generated by \`kick g agents\` for ${e}. Edits are overwritten on the next refresh; keep customisation in a SKILL.local.md alongside. -->`;return[{slug:`add-module`,frontmatterName:`kickjs-add-module`,description:`Use when the user asks to add a new feature module (controller + service + repo + DTOs).`,body:`**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
|
|
2619
|
+
|
|
2620
|
+
**Steps**:
|
|
2621
|
+
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
2622
|
+
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
|
|
2623
|
+
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
2624
|
+
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
2625
|
+
5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
|
|
2626
|
+
|
|
2627
|
+
**Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
|
|
2628
|
+
|
|
2629
|
+
\`\`\`ts
|
|
2630
|
+
export const TodosModule = defineModule({
|
|
2631
|
+
name: 'TodosModule',
|
|
2632
|
+
build: () => ({
|
|
2633
|
+
register(container) {
|
|
2634
|
+
container.registerFactory(TODO_REPO, () => container.resolve(InMemoryTodoRepository))
|
|
2635
|
+
},
|
|
2636
|
+
routes() {
|
|
2637
|
+
return { path: '/todos', controller: TodosController }
|
|
2638
|
+
},
|
|
2639
|
+
}),
|
|
2640
|
+
})
|
|
2641
|
+
\`\`\`
|
|
2642
|
+
|
|
2643
|
+
The module file MUST include \`import.meta.glob([...], { eager: true })\` for every \`@Service\` / \`@Repository\` / \`@Component\` class — without it, decorators never fire and DI silently resolves to \`undefined\`.
|
|
2644
|
+
|
|
2645
|
+
**Multiple route sets / versioning** — \`routes()\` may return an array with per-entry \`version\` override:
|
|
2646
|
+
|
|
2647
|
+
\`\`\`ts
|
|
2648
|
+
routes() {
|
|
2649
|
+
return [
|
|
2650
|
+
{ path: '/todos', controller: TodosController }, // /api/v1/todos
|
|
2651
|
+
{ path: '/todos', version: 2, controller: TodosV2Controller }, // /api/v2/todos
|
|
2652
|
+
]
|
|
2653
|
+
}
|
|
2654
|
+
\`\`\`
|
|
2655
|
+
|
|
2656
|
+
**Conditional / per-tenant mounting** — use \`bootstrap({ setup(registry) { registry.mount(...) } })\`, not the static \`modules\` array.
|
|
2657
|
+
|
|
2658
|
+
**Composition** — \`defineModules().mount(TodosModule()).mount(UsersModule())\` (fluent) or \`AppModuleEntry[]\` (array form).
|
|
2659
|
+
|
|
2660
|
+
**Red flags** (stop and ask):
|
|
2661
|
+
- 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.
|
|
2662
|
+
- \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
|
|
2663
|
+
- \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
|
|
2664
|
+
- \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
|
|
2665
|
+
- Module not registered in \`src/modules/index.ts\`.`},{slug:`add-adapter`,frontmatterName:`kickjs-add-adapter`,description:`Use when wiring a single-concern lifecycle integration (Swagger, DevTools, Sentry, Redis client).`,body:"**Steps**:\n1. `kick g adapter <name>` to scaffold the boilerplate, OR install via `kick add <package>` for first-party adapters.\n2. The generated file uses `defineAdapter()` — never `class implements AppAdapter`.\n3. Add the adapter instance (note the parens) to `src/adapters/index.ts` — don't inline in `src/index.ts`.\n4. Pick the right hook and middleware phase deliberately.\n5. Verify with `kick dev` that the adapter's lifecycle logs fire.\n\n**Canonical shape** — factory closure owns instance state:\n\n```ts\nexport const RedisAdapter = defineAdapter<RedisConfig>({\n name: 'RedisAdapter',\n defaults: { url: 'redis://localhost' },\n build: (config) => {\n const client = createClient(config.url)\n return {\n beforeStart: ({ container }) => {\n container.registerInstance(REDIS_CLIENT, client)\n },\n afterStart: () => client.connect(),\n shutdown: () => client.quit(),\n }\n },\n})\n\n// In src/adapters/index.ts:\nexport const adapters = [RedisAdapter({ url: env.REDIS_URL })] // <-- note parens\n```\n\n**Lifecycle hook decision tree**:\n- `beforeMount` — register early routes that should bypass middleware (health, docs UI).\n- `beforeStart` — DI ready, server not listening yet. **Use this for `container.registerInstance(...)` calls** so they work under `createTestApp` too.\n- `afterStart` — server has `ctx.server` available. Only use for things that need a listening server (Socket.IO upgrades, port logging). **Doesn't fire under `createTestApp`.**\n- `shutdown` — runs concurrently via `Promise.allSettled`, so one failure doesn't block siblings (but errors are swallowed — log inside).\n\n**Middleware phases** (see `MiddlewarePhase` JSDoc):\n`beforeGlobal` | `afterGlobal` (default) | `beforeRoutes` | `afterRoutes` (fires only on fall-through — matched routes that respond skip it).\n\n**Multi-instance** — `.scoped('cache', { url: ... })` makes `name` become `RedisAdapter:cache`. **Deferred config** — `.async({ inject, useFactory })` for config that depends on DI-resolved services.\n\n**Red flags**:\n- `bootstrap({ adapters: [MyAdapter] })` — passed the factory, not the instance. Call it: `MyAdapter()`.\n- Inlining the adapter list directly in `src/index.ts` — entry file should stay thin.\n- Returning a plain object instead of going through `defineAdapter()` — type inference for `config` will be wrong.\n- Using `.async()` for an adapter that returns `middleware()` / `contributors()` / `beforeMount()` / `onRouteMount()` — those hooks have already run by the time `.async()` resolves and are silently skipped.\n- Cross-adapter ordering via array position when it's load-bearing — use `dependsOn: ['OtelAdapter']`; cycles throw `MountCycleError` at boot.\n- Using an adapter when the integration ships **modules + DI bindings + middleware** together → that's a plugin. Promote to `definePlugin()` (see `add-plugin` skill).\n\n**Nuances**:\n- `AdapterContext.server` is `undefined` outside `afterStart`.\n- `shutdown` errors are swallowed by `Promise.allSettled` — wrap in try/catch and log if you care."},{slug:`add-plugin`,frontmatterName:`kickjs-add-plugin`,description:`Use when scaffolding a feature that bundles modules + DI + middleware + adapters together (auth, monitoring suite, multi-tenant scaffolding).`,body:"**When plugin > adapter**: a plugin is the right answer when the integration ships **more than one** of: a module, a DI binding, middleware, or another adapter. If you have a single hook (`beforeStart`) and no other contributions, use `defineAdapter` instead.\n\n**Canonical shape**:\n\n```ts\nimport { definePlugin } from '@forinda/kickjs'\n\nexport const AuthPlugin = definePlugin({\n name: 'AuthPlugin',\n defaults: { tokenTtl: '1h' },\n build: (config, { name }) => ({\n modules: () => [AuthModule()],\n adapters: () => [JwtAdapter({ ttl: config.tokenTtl })],\n middleware: () => [requestIdMiddleware()],\n register(container) {\n container.registerFactory(TOKEN_SIGNER, () => createSigner(config))\n },\n contributors() {\n return [LoadCurrentUser.registration]\n },\n onReady({ server }) {\n log.info(`AuthPlugin listening on port ${server.address().port}`)\n },\n }),\n})\n\n// In bootstrap:\nbootstrap({ plugins: [AuthPlugin({ tokenTtl: env.TOKEN_TTL })] }) // <-- parens\n```\n\n**Inline plugin literal** — the canonical answer for one-off DI bindings. There's no top-level `register:` on `bootstrap` itself:\n\n```ts\nbootstrap({\n plugins: [{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } }],\n})\n```\n\n**Execution order** (memorize):\nplugin `register()` → plugin `middleware()` → plugin `modules()` + user modules → plugin `adapters()` + user adapters → server listens → plugin `onReady()`.\n\n**Static vs dynamic modules**: `modules()` returning an array is introspectable (Swagger, DevTools see it). `setup(registry)` is imperative — pick the latter when the module set depends on resolved config.\n\n**Multi-instance** — `.scoped('users', { url })`; derive unique DI tokens from `ctx.name` inside `build`:\n\n```ts\nbuild: (config, { name }) => ({\n register(c) {\n c.registerInstance(createToken(`cache/${name}`), client)\n },\n})\n```\n\n**Precedence**: plugin contributors land at `'adapter'` precedence — beat global, lose to module/class/method same-key.\n\n**Red flags**:\n- `bootstrap({ plugins: [AuthPlugin] })` — passed factory. Call it: `AuthPlugin()`.\n- Reaching for a plugin when an adapter would do (no modules, no DI bindings, no contributors) — overkill; use `defineAdapter()`.\n- `.async()` plugin that depends on `modules()` / `middleware()` / `adapters()` / `contributors()` — those are dropped. `.async()` only resolves `register()` + `onReady()`.\n- Confusing CLI plugins (`defineCliPlugin` from `@forinda/kickjs-cli`) with runtime plugins (`definePlugin` from `@forinda/kickjs`) — different surfaces, different registration sites.\n- `dependsOn: ['SomePlugin']` referring to a plugin not in the boot list — throws `MissingMountDepError` at boot.\n\n**Nuances**:\n- `definition` is `Object.freeze`'d metadata; useful for version checks (`compare(AuthPlugin.definition.version, '1.2.0')`) — not mountable."},{slug:`write-controller-test`,frontmatterName:`kickjs-write-controller-test`,description:`Use when adding a Vitest test that exercises an HTTP route or DI graph.`,body:"**Template** (copy/paste, adjust):\n\n```ts\nimport { describe, it, expect, beforeEach } from 'vitest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n\nbeforeEach(() => {\n Container.reset() // isolated DI per test\n})\n\ndescribe('UserController', () => {\n it('returns users', async () => {\n const app = await createTestApp([UserModule])\n const res = await app.get('/api/v1/users')\n expect(res.status).toBe(200)\n })\n})\n```\n\n**Typed handler signature** — pair with `kick typegen` so `ctx.body` / `params` / `query` are typed by the route's Zod schema:\n\n```ts\n@Post('/', { body: createTodoSchema })\ncreate(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route\n ctx.created(await this.service.create(ctx.body))\n}\n```\n\n**Red flags**:\n- `new Container()` — wrong; use `Container.reset()` in `beforeEach` or `Container.create()` for fully isolated graphs.\n- `Container.getInstance().reset()` — wrong; same fix.\n- Sharing a container instance across `it()` blocks — leaks registrations between tests.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.\n- Calling `getRequestValue<string>('traceId')` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.\n- Asserting on `res.body.requestId` when `requestId()` middleware isn't mounted in the test app — value will be `undefined`.\n- Using `Scope.REQUEST` services in a test without mounting `requestScopeMiddleware()` — `getRequestValue` silently returns `undefined`; `getRequestStore` throws.\n\n**Nuances**:\n- `@Inject` and `@Autowired` are interchangeable — same runtime, same types; pick by readability.\n- `@Value('MISSING_KEY')` with no default **throws on property access**, not at construction — tests that exercise the getter will surface the missing-env issue."},{slug:`env-wiring-check`,frontmatterName:`kickjs-env-wiring-check`,description:`Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.`,body:"**Diagnosis (in order)**:\n1. Open `src/index.ts`. The **first non-`reflect-metadata`** import MUST be `import './config'`.\n2. Open `src/config/index.ts`. It MUST call `loadEnv(envSchema)` as a top-level side effect — not just declare the schema:\n ```ts\n import { loadEnv, defineEnv } from '@forinda/kickjs'\n const envSchema = defineEnv((base) => base.extend({ DATABASE_URL: z.string().url() }))\n export const env = loadEnv(envSchema)\n ```\n3. The new key MUST be declared in the Zod schema. `@Value('NEW_KEY')` accepts any string at the type level and **falls back to raw `process.env`** when the schema doesn't know the key — silently skipping Zod coercion.\n4. After adding a key, re-run `kick typegen` (or restart `kick dev` if the typegen watcher missed it) so the global `KickEnv` augmentation picks it up.\n\n**Why `@Value` \"works\" but `ConfigService.get` doesn't**: `@Value` has the `process.env` fallback that masks missing-side-effect-import bugs; `ConfigService` has none. If `@Value('FOO')` returns a value but `ConfigService.get('FOO')` returns `undefined`, the side-effect import of `./config` is missing.\n\n**`reloadEnv` vs `resetEnvCache`** — distinct, frequently mixed up:\n- `reloadEnv()` — re-reads `process.env` against the **already registered** schema. Use in HMR plugins after `.env` file changes. Schema survives.\n- `resetEnvCache()` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.\n\n**Nuances**:\n- `loadEnv()` cache is **sticky**: once `loadEnv(extendedSchema)` runs anywhere, no-arg calls reuse it — but only if it actually ran. Schema downgrades silently if `src/config/index.ts` isn't imported.\n- `createConfigService(envSchema)` is deprecated; the typegen-driven `ConfigService` covers it.\n- `dotenv` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.\n- For HMR-friendly `.env` edits, add `envWatchPlugin()` to `vite.config.ts` — calls `reloadEnv()` automatically.\n\n**Fix recipe**: add the key to the schema; add `import './config'` as the first non-reflect-metadata import in `src/index.ts`; re-run `kick typegen`."},{slug:`bootstrap-export`,frontmatterName:`kickjs-bootstrap-export`,description:`Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.`,body:"**Check** `src/index.ts`'s last line:\n\n```ts\n// CORRECT — Vite plugin + createTestApp import the named `app` symbol\nexport const app = await bootstrap({ ... })\n\n// WRONG — HMR degrades to full restart, createTestApp loses the handle\nawait bootstrap({ ... })\n```\n\nThe Vite plugin imports the named `app` symbol via `virtual:kickjs/app`; testing helpers do too. Without the export, both fall back to slower paths (full restart on save, mock handle in tests) **without warning**.\n\n**Red flags**:\n- A bare `await bootstrap(...)` with no `export` — fix by adding `export const app =`.\n- Re-assigning `app` later in the file (`app = somethingElse`) — Vite imports by reference at module-load time; reassignments don't propagate.\n- Multiple files calling `bootstrap()` — only the entry should. Tests use `createTestApp` instead."},{slug:`thin-entry-file`,frontmatterName:`kickjs-thin-entry-file`,description:`Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.`,body:`**Refactor target**:
|
|
2666
|
+
|
|
2667
|
+
\`\`\`ts
|
|
2668
|
+
// src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
|
|
2669
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
2670
|
+
// OR for class-form projects (\`modules.style: 'class'\`):
|
|
2671
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
2672
|
+
|
|
2673
|
+
// src/middleware/index.ts — global middleware uses RAW EXPRESS signature
|
|
2674
|
+
// (req, res, next), NOT (ctx, next)
|
|
2675
|
+
export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
|
|
2676
|
+
|
|
2677
|
+
// src/plugins/index.ts
|
|
2678
|
+
export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: env.TOKEN_TTL })]
|
|
2679
|
+
|
|
2680
|
+
// src/adapters/index.ts
|
|
2681
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
2682
|
+
|
|
2683
|
+
// src/index.ts — stays small
|
|
2684
|
+
import 'reflect-metadata'
|
|
2685
|
+
import './config' // MUST be early — side-effect schema load
|
|
2686
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
2687
|
+
import { modules } from './modules'
|
|
2688
|
+
import { middleware } from './middleware'
|
|
2689
|
+
import { plugins } from './plugins'
|
|
2690
|
+
import { adapters } from './adapters'
|
|
2691
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
2692
|
+
\`\`\`
|
|
2693
|
+
|
|
2694
|
+
**One-off DI binding** — inline a literal plugin inside \`plugins\`, not a top-level option:
|
|
2695
|
+
|
|
2696
|
+
\`\`\`ts
|
|
2697
|
+
plugins: [
|
|
2698
|
+
...plugins,
|
|
2699
|
+
{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
|
|
2700
|
+
]
|
|
2701
|
+
\`\`\`
|
|
2702
|
+
|
|
2703
|
+
**Red flags**:
|
|
2704
|
+
- Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
2705
|
+
- Mixing middleware signatures: \`bootstrap({ middleware })\` is **raw Express** \`(req, res, next)\`; \`@Middleware()\` decorators are \`(ctx, next)\`; adapter middleware is raw Express again. Wrong shape in the wrong slot throws "Cannot read properties of undefined".
|
|
2706
|
+
- \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// Optionally publish discoverability for tooling (Swagger, DevTools)\ndefineAugmentation('ContextMeta', {\n description: 'Per-request tenant resolved from x-tenant-id header.',\n example: { id: 'acme', name: 'Acme Inc' },\n})\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n ctx.json(ctx.get('project'))\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying Express request is shared).\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- `defineAugmentation` without the `declare module` block (or vice-versa) — discoverability and types drift apart; `ctx.get('tenant')` becomes `unknown`.\n- Plugin / adapter authors using bare keys (`'state'`) instead of namespaced (`'@my-plugin/state'`) — collides with adopter keys.\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type."},{slug:`query-parsing-list-endpoint`,frontmatterName:`kickjs-query-parsing-list-endpoint`,description:`Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.`,body:"**Canonical list endpoint**:\n\n```ts\n@Get('/')\nasync list(ctx: Ctx<KickRoutes.TodoController['list']>) {\n const parsed = ctx.qs({\n filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set\n sortable: ['createdAt', 'updatedAt', 'priority'],\n searchColumns: ['title', 'description'], // free-text search targets\n })\n\n return ctx.paginate(async () => {\n const { data, total } = await this.service.list(parsed)\n return { data, total }\n }, parsed)\n}\n```\n\n**Operator format** (fixed): `?filter=field:op:value` where `op ∈ eq | neq | gt | gte | lt | lte | between | in | contains | starts | ends`. Sort is `?sort=field:asc|desc`. Only the first two colons are delimiters, so timestamps work (`createdAt:gt:2026-01-01T00:00:00Z`).\n\n**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:\n\n```ts\nconst TASK_QUERY_CONFIG = {\n filterable: { status: tasks.status, priority: tasks.priority },\n sortable: { createdAt: tasks.createdAt },\n searchColumns: [tasks.title, tasks.description],\n}\nconst parsed = ctx.qs(TASK_QUERY_CONFIG)\n```\n\n**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.\n\n**Red flags**:\n- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.\n- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).\n- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.\n- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.\n- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.\n\n**Nuances**:\n- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.\n- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`)."},{slug:`use-asset-manager`,frontmatterName:`kickjs-use-asset-manager`,description:`Use when code reads template files / JSON fixtures via fs.readFile + path arithmetic — switch to assets.<ns>.<key>() and the kick.config.ts assetMap.`,body:"**Configure** `kick.config.ts`:\n\n```ts\nexport default defineConfig({\n assetMap: {\n mails: { src: 'src/templates/mails' },\n reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },\n },\n})\n```\n\n**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:\n\n```ts\nimport { assets } from '@forinda/kickjs'\n\nconst html = await assets.mails.welcome() // typed: tsc errors on bad key\n```\n\n**Class-field decorator** (lazy getter, swappable in tests):\n\n```ts\nclass WelcomeMailService {\n @Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>\n\n async send(to: string) {\n const body = await this.welcomeTemplate()\n }\n}\n```\n\n**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.\n\n**Test fixtures** — swap via env override + cache clear:\n\n```ts\nbeforeEach(() => {\n process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')\n clearAssetCache()\n})\nafterEach(() => {\n delete process.env.KICK_ASSETS_ROOT\n clearAssetCache()\n})\n```\n\n**Red flags**:\n- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.\n- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.\n- Non-default Vite `outDir` without mirroring in `kick.config.ts` — manifest writes at `dist/.kickjs-assets.json` but the resolver can't find it. Mirror via `build.outDir`.\n- Forgetting to re-run `kick typegen` after adding files — `assets.mails.newTemplate` is a tsc error even though the file ships. `kick dev` does this on-change; one-shot CI builds need `kick build` (or `kick build:assets` for manifest-only).\n- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.\n\n**Nuances**:\n- Resolution pipeline (cached): `KICK_ASSETS_ROOT` env override > built manifest at `build.outDir` / `dist` / `build` / `out` > dev-fallback in-memory walk. Manifest presence = \"running from built dist.\"\n- Dev-mode glob matcher is a lite implementation — `**/*`, `**/*.ext`, `**/*.{a,b}` are guaranteed; exotic globs warn-once and accept everything. Run `kick build:assets` to exercise the real glob engine."},{slug:`cli-commands-cheatsheet`,frontmatterName:`kickjs-cli-commands-cheatsheet`,description:`Use as a quick reference for the most common kick CLI workflows — scaffolding, dev/build/start, generation, inspection.`,body:`**Top commands**:
|
|
2707
|
+
- \`kick new <name>\` — start a new project (prompts for template / repo / pm).
|
|
2708
|
+
- \`kick dev\` — local dev server with Vite HMR.
|
|
2709
|
+
- \`kick build\` — production bundle via Vite.
|
|
2710
|
+
- \`kick start\` — run the built artifact (\`NODE_ENV=production\` auto-set).
|
|
2711
|
+
- \`kick g module <name>\` — add a feature module; structure follows \`pattern\` in \`kick.config.ts\`.
|
|
2712
|
+
- \`kick g scaffold <Name> <field:type>...\` — full CRUD module from field definitions.
|
|
2713
|
+
- \`kick add <pkg>\` — install optional packages (auto-resolves peer deps + package manager).
|
|
2714
|
+
- \`kick g --list\` — list every available generator (built-ins + plugin-shipped).
|
|
2715
|
+
- \`kick info\` — environment / version dump for bug reports.
|
|
2716
|
+
- \`kick inspect\` — introspect a running app: routes, middleware, adapters, DI graph.
|
|
2717
|
+
|
|
2718
|
+
**Useful flag combos**:
|
|
2719
|
+
|
|
2720
|
+
\`\`\`bash
|
|
2721
|
+
kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
|
|
2722
|
+
kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
|
|
2723
|
+
kick new . --yes --force # Scaffold into current dir, clear existing files
|
|
2724
|
+
kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
|
|
2725
|
+
kick g agents -f --only skills # Refresh just the skills after upgrade
|
|
2726
|
+
kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
|
|
2727
|
+
kick inspect --port 4000 --json # Machine-readable route/adapter dump
|
|
2728
|
+
kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
|
|
2729
|
+
\`\`\`
|
|
2730
|
+
|
|
2731
|
+
**Lesser-known, high-value**:
|
|
2732
|
+
- \`kick inspect --watch\` — live route/middleware/adapter table that re-renders on hot reload; faster than re-curling \`/_debug\`.
|
|
2733
|
+
- \`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.
|
|
2734
|
+
- \`kick dev:debug\` — same flags as \`kick dev\` but opens a Node inspector port for IDE attach.
|
|
2735
|
+
- \`kick list --all\` (alias \`kick ls --all\`) — full optional-package catalog at this CLI version.
|
|
2736
|
+
- \`kick typegen --watch\` — standalone typegen watcher when \`kick dev\` isn't running.
|
|
2737
|
+
- \`kick check\` — preflight gate (typecheck + lint + format) before commit.
|
|
2738
|
+
- \`kick codemod\` — automated AST-level migration between framework versions.
|
|
2739
|
+
|
|
2740
|
+
**Red flags**:
|
|
2741
|
+
- Using globally-installed \`@forinda/kickjs-cli\` while contributing to the monorepo — \`pnpm link --global\` from \`packages/cli\` so generators match the framework.
|
|
2742
|
+
- Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
|
|
2743
|
+
- Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
|
|
2744
|
+
- Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
|
|
2745
|
+
- Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`refresh-agent-docs`,frontmatterName:`kickjs-refresh-agent-docs`,description:`Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.`,body:"**Steps**:\n1. `kick g agents -f --only both` — overwrites `CLAUDE.md` (root) and `.agents/AGENTS.md`.\n2. `kick g agents -f --only skills` — refreshes every `.agents/skills/<slug>/SKILL.md`.\n3. `kick g agents -f --only gemini` / `--only copilot` — refresh the per-agent files when needed.\n4. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate `AGENTS.local.md` or per-skill `SKILL.local.md` alongside.\n5. Commit as `docs(agents): sync from CLI vX.Y`.\n\n**`.agents/` layout** (post-restructure):\n\n```\nCLAUDE.md # at root — Claude Code auto-loads from here\n.agents/\n├── AGENTS.md # canonical multi-agent reference\n├── GEMINI.md # Gemini-specific notes\n├── COPILOT.md # Copilot CLI notes\n└── skills/\n ├── add-module/SKILL.md\n ├── add-adapter/SKILL.md\n └── … # one SKILL.md per skill, frontmatter-namespaced\n```\n\nCustomisation goes in `.local.md` siblings (`AGENTS.local.md`, `skills/<slug>/SKILL.local.md`) — those are never overwritten."},{slug:`deny-list`,frontmatterName:`kickjs-deny-list`,description:`Patterns to refuse outright when the user asks for them — they break v4 invariants.`,body:"**Module / adapter / plugin shape**:\n- `class implements AppAdapter` → use `defineAdapter()`.\n- `class implements KickPlugin` / function returning `KickPlugin` → use `definePlugin()`.\n- `class implements AppModule` for new code → use `defineModule()`.\n- `bootstrap({ adapters: [MyAdapter] })` (factory) → `MyAdapter()` (instance, with parens).\n- `@Controller('/path')` with a path argument → drop the path; set the mount via `routes().path`. The decorator path is OpenAPI metadata only.\n- Module file named `<name>.ts` (no `.module` suffix) → rename to `<name>.module.ts`. Vite HMR's glob doesn't pick up the unsuffixed form.\n\n**DI**:\n- `new Container()` or `Container.getInstance().reset()` in tests → use `Container.reset()` in `beforeEach` (or `Container.create()` for fully isolated graphs).\n- DI tokens with `:` separator (`'app:db:url'`) or in PascalCase → use slash-delimited lower-case (`'app/db/url'`). First-party uses reserved `'kick/'` prefix.\n- `Symbol.for(...)` for DI tokens — globally interned, **collides across files**. Use `createToken<T>('name')`.\n- Raw string tokens (`@Inject('config')`) — silent collisions; widens to `unknown`. Use `createToken<T>`.\n- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve time.\n\n**Bootstrap / entry file**:\n- `bootstrap({ ... })` without `export const app = ...` → always export. HMR degrades to full restart and `createTestApp` loses the handle.\n- `bootstrap({ register: ... })` — that option doesn't exist. Use an inline plugin in `plugins`.\n\n**Middleware**:\n- Using `(ctx, next)` for global middleware in `bootstrap({ middleware })` — global middleware uses raw Express `(req, res, next)`. Wrong signature throws \"Cannot read properties of undefined\".\n- Using `(req, res, next)` for an `@Middleware()` decorator — those use `(ctx, next)`.\n- `@Middleware()` whose only output is `ctx.set('x', v)` — should be a context decorator (typed, ordered, testable).\n\n**Context contributors**:\n- `ctx.tenant = x` from a contributor — only sticks to one `RequestContext` instance. **Return the value** so the runner writes it via `ctx.set(key, value)`.\n- `defineAugmentation('ContextMeta', ...)` without the matching `declare module '@forinda/kickjs'` block (or vice-versa).\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type.\n\n**Env / config**:\n- `@Value('NEW_KEY')` without the key in the Zod schema — silent fallback to raw `process.env`, no coercion.\n- `resetEnvCache()` outside tests — drops the registered schema.\n\n**List endpoints**:\n- Reading `req.query.status` directly — bypasses the allow-list. Use `ctx.qs({ filterable })`.\n- Returning a bare array from a list endpoint — breaks the `PaginatedResponse<T>` contract. Use `ctx.paginate()`.\n\n**Assets**:\n- Hand-rolled `__dirname` arithmetic for template paths — use `assets.<ns>.<key>()` and add the namespace to `kick.config.ts assetMap`."}].map(e=>({slug:e.slug,content:`---
|
|
2746
|
+
name: ${e.frontmatterName}
|
|
2747
|
+
description: ${e.description}
|
|
2748
|
+
---
|
|
2749
|
+
|
|
2750
|
+
${r}
|
|
2751
|
+
|
|
2752
|
+
${e.body}
|
|
2753
|
+
`}))}function vt(e,t,n){return`# kickjs-skills.md — Task Skills for AI Agents (${e})
|
|
2585
2754
|
|
|
2586
2755
|
This file is the agent-facing **skills index** for KickJS work in this
|
|
2587
2756
|
repo. Each block below is a short, rigid workflow keyed to a specific
|
|
@@ -2830,7 +2999,74 @@ description: Patterns to refuse outright when the user asks for them — they br
|
|
|
2830
2999
|
- [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
2831
3000
|
- [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
|
|
2832
3001
|
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
2833
|
-
`}
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
3002
|
+
`}function yt(e,t,n){return`# GEMINI.md — ${e}
|
|
3003
|
+
|
|
3004
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
3005
|
+
reference for this project — every convention, structure, decorator
|
|
3006
|
+
pattern, env wiring rule, generator usage. This file is a thin
|
|
3007
|
+
Gemini-specific layer; when the two disagree on anything substantive,
|
|
3008
|
+
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
3009
|
+
|
|
3010
|
+
## Why this file
|
|
3011
|
+
|
|
3012
|
+
Gemini CLI auto-loads \`GEMINI.md\` when it lives alongside the
|
|
3013
|
+
agent-context files. Keeping it in \`.agents/\` next to \`AGENTS.md\`
|
|
3014
|
+
means Gemini reads the same shared prose as Codex / Cursor / Copilot
|
|
3015
|
+
without us copy-pasting.
|
|
3016
|
+
|
|
3017
|
+
## Gemini-specific notes
|
|
3018
|
+
|
|
3019
|
+
- **Skills activation** — Gemini activates skills via
|
|
3020
|
+
\`activate_skill\` (its native MCP-style tool); the equivalent on
|
|
3021
|
+
Claude Code is the \`Skill\` tool. Cross-reference the
|
|
3022
|
+
\`kickjs-skills.md\` index for the available triggers.
|
|
3023
|
+
- **Tool naming** — Gemini's tool names differ from Claude Code's
|
|
3024
|
+
(e.g. \`read_file\` vs \`Read\`, \`run_terminal_command\` vs
|
|
3025
|
+
\`Bash\`). The shared prose in \`AGENTS.md\` describes intents, not
|
|
3026
|
+
tool names; consult Gemini's docs for the concrete invocation.
|
|
3027
|
+
- **File ops** — Gemini's file edits are sandboxed; large refactors
|
|
3028
|
+
may need explicit confirmation. Prefer the smallest-possible-edit
|
|
3029
|
+
pattern.
|
|
3030
|
+
|
|
3031
|
+
## Refreshing this file
|
|
3032
|
+
|
|
3033
|
+
\`kick g agents --only gemini -f\` regenerates this file from the
|
|
3034
|
+
CLI template. Hand-edited content is overwritten — keep customisation
|
|
3035
|
+
in \`.agents/GEMINI.local.md\`.
|
|
3036
|
+
`}function bt(e,t,n){return`# COPILOT.md — ${e}
|
|
3037
|
+
|
|
3038
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
3039
|
+
reference for this project — every convention, structure, decorator
|
|
3040
|
+
pattern, env wiring rule, generator usage. This file is a thin
|
|
3041
|
+
Copilot-specific layer; when the two disagree on anything substantive,
|
|
3042
|
+
treat \`AGENTS.md\` as authoritative and flag the discrepancy.
|
|
3043
|
+
|
|
3044
|
+
## Why this file
|
|
3045
|
+
|
|
3046
|
+
GitHub Copilot CLI auto-loads \`COPILOT.md\` when it lives alongside
|
|
3047
|
+
the agent-context files. Keeping it in \`.agents/\` next to
|
|
3048
|
+
\`AGENTS.md\` means Copilot reads the same shared prose as
|
|
3049
|
+
Codex / Cursor / Gemini / Claude Code without copy-pasting.
|
|
3050
|
+
|
|
3051
|
+
## Copilot-specific notes
|
|
3052
|
+
|
|
3053
|
+
- **Skills** — Copilot CLI auto-discovers skills from installed
|
|
3054
|
+
plugins; cross-reference \`kickjs-skills.md\` for available
|
|
3055
|
+
triggers in this project.
|
|
3056
|
+
- **Tool naming** — Copilot's tool names differ from Claude Code's
|
|
3057
|
+
(\`edit\` vs \`Edit\`, \`shell\` vs \`Bash\`, etc.). The shared
|
|
3058
|
+
prose in \`AGENTS.md\` describes intents, not tool names; consult
|
|
3059
|
+
Copilot's docs for the concrete invocation.
|
|
3060
|
+
- **Confirmation flows** — Copilot CLI surfaces destructive
|
|
3061
|
+
operations through an explicit approval gate. Stage edits with
|
|
3062
|
+
short, focused diffs so each one is easy to review at the prompt.
|
|
3063
|
+
|
|
3064
|
+
## Refreshing this file
|
|
3065
|
+
|
|
3066
|
+
\`kick g agents --only copilot -f\` regenerates this file from the
|
|
3067
|
+
CLI template. Hand-edited content is overwritten — keep customisation
|
|
3068
|
+
in \`.agents/COPILOT.local.md\`.
|
|
3069
|
+
`}const xt=t(g(import.meta.url)),St=JSON.parse(o(r(xt,`..`,`package.json`),`utf-8`)),Ct=`^${St.version}`,wt=[`@forinda/kickjs`,`@forinda/kickjs-cli`,`@forinda/kickjs-vite`,`@forinda/kickjs-swagger`,`@forinda/kickjs-ws`,`@forinda/kickjs-queue`,`@forinda/kickjs-devtools`,`@forinda/kickjs-testing`];async function Tt(){let e=await Promise.all(wt.map(async e=>{try{let t=m(`npm`,[`view`,e,`version`],{encoding:`utf-8`,timeout:5e3,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim();if(t&&/^\d+\.\d+\.\d+/.test(t))return[e,`^${t}`]}catch{}return[e,Ct]}));return Object.fromEntries(e)}async function Et(e){let{name:t,directory:n,packageManager:i=`pnpm`,template:a=`rest`,defaultRepo:o=`inmemory`,packages:s=[]}=e,c=n,l=e=>console.log(` ${e}`);console.log(`\n Creating KickJS project: ${t}\n`),l(`Resolving package versions...`);let u=await Tt();if(await b(r(c,`package.json`),it(t,a,u,s)),await b(r(c,`vite.config.ts`),at()),await b(r(c,`tsconfig.json`),ot()),await b(r(c,`.prettierrc`),st()),await b(r(c,`.editorconfig`),ct()),await b(r(c,`.gitignore`),lt()),await b(r(c,`.gitattributes`),ut()),await b(r(c,`.env`),dt()),await b(r(c,`.env.example`),ft()),await b(r(c,`src/config/index.ts`),Fe()),await b(r(c,`src/index.ts`),Ne(t,a,St.version,s)),await b(r(c,`src/modules/index.ts`),Pe()),await b(r(c,`src/modules/hello/hello.service.ts`),Ie()),await b(r(c,`src/modules/hello/hello.controller.ts`),Le()),await b(r(c,`src/modules/hello/hello.module.ts`),Re()),await b(r(c,`kick.config.ts`),ze(a,o,i)),await b(r(c,`vitest.config.ts`),pt()),await b(r(c,`README.md`),mt(t,a,i)),await b(r(c,`CLAUDE.md`),ht(t,a,i)),await b(r(c,`AGENTS.md`),gt(t,a,i)),await b(r(c,`kickjs-skills.md`),vt(t,a,i)),e.installDeps){console.log(`\n Installing dependencies with ${i}...\n`);try{h(`${i} install`,{cwd:c,stdio:`inherit`}),console.log(`
|
|
3070
|
+
Dependencies installed successfully!`)}catch{console.log(`\n Warning: ${i} install failed. Run it manually.`)}}try{let{runTypegen:e}=await import(`./typegen-D-1Q9yBD.mjs`).then(e=>e.r);await e({cwd:c,allowDuplicates:!0,silent:!0})}catch{}if(e.initGit)try{h(`git init`,{cwd:c,stdio:`pipe`}),h(`git branch -M main`,{cwd:c,stdio:`pipe`}),h(`git add -A`,{cwd:c,stdio:`pipe`}),h(`git commit -m "chore: initial commit from kick new"`,{cwd:c,stdio:`pipe`}),l(`Git repository initialized`)}catch{l(`Warning: git init failed (git may not be installed)`)}console.log(`
|
|
3071
|
+
Project scaffolded successfully!`),console.log();let d=c!==process.cwd();l(`Next steps:`),d&&l(` cd ${t}`),e.installDeps||l(` ${i} install`);let f={rest:`kick g module user`,ddd:`kick g module user --repo drizzle`,cqrs:`kick g module user --pattern cqrs`,minimal:`# add your routes to src/index.ts`};l(` ${f[a]??f.rest}`),l(` kick dev`),l(``),l(`Commands:`),l(` kick dev Start dev server with Vite HMR`),l(` kick build Production build via Vite`),l(` kick start Run production build`),l(``),l(`Generators:`),l(` kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)`),l(` kick g scaffold <n> <f..> CRUD module from field definitions`),l(` kick g controller <name> Standalone controller`),l(` kick g service <name> @Service() class`),l(` kick g middleware <name> Express middleware`),l(` kick g guard <name> Route guard (auth, roles, etc.)`),l(` kick g adapter <name> AppAdapter with lifecycle hooks`),l(` kick g dto <name> Zod DTO schema`),a===`cqrs`&&l(` kick g job <name> Queue job processor`),l(` kick g config Generate kick.config.ts`),l(``),l(`Add packages:`),l(` kick add <pkg> Install a KickJS package + peers`),l(` kick add --list Show all available packages`),l(``),l(`Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing`),l(``)}function Dt(e){return e}function Ot(e){return k(e).replace(/-/g,`_`)}function kt(e){let t=e.cwd??process.cwd(),n=e.pluralize??!0,r=D(e.name),i=O(e.name),a=k(e.name),o=Ot(e.name),s={name:e.name,pascal:r,camel:i,kebab:a,snake:o,modulesDir:e.modulesDir??`src/modules`,cwd:t,args:e.args??[],flags:e.flags??{}};if(n){let e=A(a);s.pluralKebab=e,s.pluralPascal=D(e),s.pluralCamel=O(e)}return s}function At(e,t){return i(e.cwd,t)}async function jt(e){return import(_(e).href)}const Mt=new Map;async function Nt(e){let t=Mt.get(e);if(t)return t;let n=Pt(e);return Mt.set(e,n),n}async function Pt(n){let r=i(n,`package.json`);if(!a(r))return{generators:[],loaded:[],failed:[]};let o=Ft(JSON.parse(await l(r,`utf-8`))),s=e(i(n,`package.json`)),c=[],u=[],d=[];for(let e of o){let n;try{n=s.resolve(`${e}/package.json`)}catch{continue}let r;try{r=JSON.parse(await l(n,`utf-8`))}catch(t){d.push({source:e,reason:`failed to parse package.json: ${t}`});continue}if(!r.kickjs?.generators)continue;let o=r.kickjs.generators,f=i(t(n),o);if(!a(f)){d.push({source:e,reason:`kickjs.generators points to missing file: ${o}`});continue}let p;try{p=await jt(f)}catch(t){d.push({source:e,reason:`failed to import manifest: ${t}`});continue}let m=p.default;if(!Array.isArray(m)){d.push({source:e,reason:`manifest's default export is not an array of GeneratorSpec`});continue}for(let t of m){if(!It(t)){d.push({source:e,reason:`manifest entry is not a valid GeneratorSpec (missing name/files)`});continue}c.push({source:e,spec:t})}u.push(e)}return{generators:c,loaded:u,failed:d}}function Ft(e){let t=new Set;for(let n of[e.dependencies,e.devDependencies,e.peerDependencies])if(n)for(let e of Object.keys(n))t.add(e);return Array.from(t)}function It(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.name==`string`&&typeof t.files==`function`}async function Lt(e,t=[]){let n=e.cwd??process.cwd(),r=t.find(t=>t.spec.name===e.generatorName);if(r)return Bt(r.spec,r.source,e,n);let i=zt(await Nt(n),e.generatorName);return i?Bt(i.spec,i.source,e,n):null}async function Rt(e,t=[]){let n=await Nt(e),r=new Set(t.map(e=>e.spec.name)),i=n.generators.filter(e=>!r.has(e.spec.name));return{generators:[...t,...i],loaded:n.loaded,failed:n.failed}}function zt(e,t){return e.generators.find(e=>e.spec.name===t)}async function Bt(e,t,n,r){let i=kt({name:n.itemName,args:n.args,flags:n.flags,modulesDir:n.modulesDir,pluralize:n.pluralize,cwd:r}),a=await e.files(i),o=[];for(let e of a){let t=At(i,e.path);await b(t,e.content),o.push(t)}return{files:o,source:t}}export{de as A,b as B,j as C,T as D,D as E,ae as F,f as I,oe as L,ue as M,fe as N,se as O,le as P,C as R,A as S,k as T,q as _,Et as a,We as b,bt as c,nt as d,tt as f,Je as g,Qe as h,Dt as i,ce as j,E as k,yt as l,$e as m,Lt as n,gt as o,et as p,kt as r,ht as s,Rt as t,_t as u,Y as v,O as w,M as x,Ge as y,y as z};
|
|
3072
|
+
//# sourceMappingURL=generator-extension-Cd2DU_XX.mjs.map
|