@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.
- package/dist/agent-docs-DhiaLsBj.mjs +591 -0
- package/dist/agent-docs-DhiaLsBj.mjs.map +1 -0
- package/dist/agent-docs-lNvu1K1x.mjs +590 -0
- package/dist/{build-Czsf4CBN.mjs → build-BNHMWtNY.mjs} +2 -2
- package/dist/{build-gqxIH3D8.mjs → build-vY0bmwuH.mjs} +3 -3
- package/dist/{build-gqxIH3D8.mjs.map → build-vY0bmwuH.mjs.map} +1 -1
- package/dist/{builtins-6euI1-lN.mjs → builtins-CRRb7Lq1.mjs} +2 -2
- package/dist/{builtins-xahWxQLw.mjs → builtins-tE4nrAZ_.mjs} +59 -59
- package/dist/cli.mjs +2 -2
- package/dist/{config-DCM2vXUJ.mjs → config-mXO3F69m.mjs} +2 -2
- package/dist/{config-8jdSKLKJ.mjs → config-zWl1-NCq.mjs} +3 -3
- package/dist/{config-8jdSKLKJ.mjs.map → config-zWl1-NCq.mjs.map} +1 -1
- package/dist/{doctor-CwGU9orm.mjs → doctor-z92r35fo.mjs} +9 -9
- package/dist/{doctor-CwGU9orm.mjs.map → doctor-z92r35fo.mjs.map} +1 -1
- package/dist/{fullstack-9HywHQL-.mjs → fullstack-BqevN8LJ.mjs} +13 -13
- package/dist/{fullstack-9HywHQL-.mjs.map → fullstack-BqevN8LJ.mjs.map} +1 -1
- package/dist/{fullstack-BmIFnryN.mjs → fullstack-eMi-9BtZ.mjs} +9 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{plugin-DLZP4hZ0.mjs → plugin-BbbHEAzr.mjs} +2 -2
- package/dist/{plugin-BjmLRF7t.mjs → plugin-CH4X4T0O.mjs} +2 -2
- package/dist/project-Bp6SIRyt.mjs +132 -0
- package/dist/project-D96UoR0P.mjs +133 -0
- package/dist/project-D96UoR0P.mjs.map +1 -0
- package/dist/{project-root-Dk8r8FMi.mjs → project-root-Bw3CEPC7.mjs} +3 -3
- package/dist/{project-root-Dk8r8FMi.mjs.map → project-root-Bw3CEPC7.mjs.map} +1 -1
- package/dist/{project-root-8DH00M-b.mjs → project-root-DN0YbQE5.mjs} +2 -2
- package/dist/{rolldown-runtime-CRasMkPY.mjs → rolldown-runtime-CYy3EyO3.mjs} +1 -1
- package/dist/{run-plugins-R0bVf_nK.mjs → run-plugins-f7i7TlPV.mjs} +67 -67
- package/dist/run-plugins-f7i7TlPV.mjs.map +1 -0
- package/dist/{typegen-BZ8cQ1YM.mjs → typegen-Bq4Fis9G.mjs} +5 -5
- package/dist/{typegen-BZ8cQ1YM.mjs.map → typegen-Bq4Fis9G.mjs.map} +1 -1
- package/dist/{typegen-DNufBmjE.mjs → typegen-_x_Q5O0b.mjs} +4 -4
- package/dist/{types-DOcxTXlP.mjs → types-BLZecxnS.mjs} +1 -1
- package/package.json +2 -2
- package/templates/base/files/_dot_vscode/extensions.json +3 -0
- package/templates/base/files/kick.config.ts +4 -0
- package/templates/base/skills/add-adapter.txt +56 -0
- package/templates/base/skills/add-module.txt +53 -0
- package/templates/base/skills/add-plugin.txt +69 -0
- package/templates/base/skills/bootstrap-export.txt +21 -0
- package/templates/base/skills/cli-commands-cheatsheet.txt +46 -0
- package/templates/base/skills/cli-plugin.txt +61 -0
- package/templates/base/skills/context-contributor.txt +73 -0
- package/templates/base/skills/deny-list.txt +44 -0
- package/templates/base/skills/deploy.txt +99 -0
- package/templates/base/skills/docs-lookup.txt +40 -0
- package/templates/base/skills/env-wiring-check.txt +44 -0
- package/templates/base/skills/guard-vs-middleware-vs-contributor.txt +95 -0
- package/templates/base/skills/query-parsing-list-endpoint.txt +48 -0
- package/templates/base/skills/refresh-agent-docs.txt +27 -0
- package/templates/base/skills/route-flags.txt +73 -0
- package/templates/base/skills/thin-entry-file.txt +49 -0
- package/templates/base/skills/use-asset-manager.txt +61 -0
- package/templates/base/skills/write-controller-test.txt +63 -0
- package/templates/feature-views/feature.json +21 -0
- package/templates/feature-views/files/src/adapters/views.ts +5 -0
- package/templates/feature-views/files/src/views/home.kick +3 -0
- package/templates/feature-views/files/src/views/layouts/main.kick +13 -0
- package/templates/feature-views/files/src/views.ts +9 -0
- package/templates/feature-views/skills/views-forms.txt +68 -0
- package/templates/feature-views/skills/views.txt +49 -0
- package/templates/fullstack-root/files/_dot_vscode/extensions.json +3 -0
- package/dist/agent-docs-CrVQtJgn.mjs +0 -932
- package/dist/agent-docs-D7K6R5C3.mjs +0 -933
- package/dist/agent-docs-D7K6R5C3.mjs.map +0 -1
- package/dist/package-manager-9XxrErw1.mjs +0 -11
- package/dist/package-manager-Dwaolesm.mjs +0 -12
- package/dist/package-manager-Dwaolesm.mjs.map +0 -1
- package/dist/project-CFi3NvO9.mjs +0 -136
- package/dist/project-CFi3NvO9.mjs.map +0 -1
- package/dist/project-CO0D8B0V.mjs +0 -135
- package/dist/run-plugins-R0bVf_nK.mjs.map +0 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-deny-list
|
|
3
|
+
description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Module / adapter / plugin shape**:
|
|
7
|
+
- `class implements AppAdapter` → use `defineAdapter()`.
|
|
8
|
+
- `class implements KickPlugin` / function returning `KickPlugin` → use `definePlugin()`.
|
|
9
|
+
- `class implements AppModule` for new code → use `defineModule()`.
|
|
10
|
+
- `bootstrap({ adapters: [MyAdapter] })` (factory) → `MyAdapter()` (instance, with parens).
|
|
11
|
+
- `@Controller('/path')` with a path argument → `@Controller()`, with the prefix in `routes().path`.
|
|
12
|
+
- Module file named `<name>.ts` (no `.module` suffix) → rename to `<name>.module.ts`. Vite HMR's glob doesn't pick up the unsuffixed form.
|
|
13
|
+
|
|
14
|
+
**DI**:
|
|
15
|
+
- `new Container()` or `Container.getInstance().reset()` in tests → use `Container.reset()` in `beforeEach` (or `Container.create()` for fully isolated graphs).
|
|
16
|
+
- DI tokens with `:` separator (`'app:db:url'`) or in PascalCase → use slash-delimited lower-case (`'app/db/url'`). First-party uses reserved `'kick/'` prefix.
|
|
17
|
+
- `Symbol.for(...)` for DI tokens — globally interned, **collides across files**. Use `createToken<T>('name')`.
|
|
18
|
+
- Raw string tokens (`@Inject('config')`) — silent collisions; widens to `unknown`. Use `createToken<T>`.
|
|
19
|
+
- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve time.
|
|
20
|
+
|
|
21
|
+
**Bootstrap / entry file**:
|
|
22
|
+
- `bootstrap({ ... })` without `export const app = ...` → always export. HMR degrades to full restart and `createTestApp` loses the handle.
|
|
23
|
+
- `bootstrap({ register: ... })` — that option doesn't exist. Use an inline plugin in `plugins`.
|
|
24
|
+
|
|
25
|
+
**Middleware**:
|
|
26
|
+
- 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".
|
|
27
|
+
- Using `(req, res, next)` for an `@Middleware()` decorator — those use `(ctx, next)`.
|
|
28
|
+
- `@Middleware()` whose only output is `ctx.set('x', v)` — should be a context decorator (typed, ordered, testable).
|
|
29
|
+
|
|
30
|
+
**Context contributors**:
|
|
31
|
+
- `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)`.
|
|
32
|
+
- Omitting the `declare module '@forinda/kickjs'` block — without it `ctx.get('tenant')` is `unknown`.
|
|
33
|
+
- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type.
|
|
34
|
+
|
|
35
|
+
**Env / config**:
|
|
36
|
+
- `@Value('NEW_KEY')` without the key in the Zod schema — silent fallback to raw `process.env`, no coercion.
|
|
37
|
+
- `resetEnvCache()` outside tests — drops the registered schema.
|
|
38
|
+
|
|
39
|
+
**List endpoints**:
|
|
40
|
+
- Reading `req.query.status` directly — bypasses the allow-list. Use `ctx.qs({ filterable })`.
|
|
41
|
+
- Returning a bare array from a list endpoint — breaks the `PaginatedResponse<T>` contract. Use `ctx.paginate()`.
|
|
42
|
+
|
|
43
|
+
**Assets**:
|
|
44
|
+
- Hand-rolled `__dirname` arithmetic for template paths — use `assets.<ns>.<key>()` and add the namespace to `kick.config.ts assetMap`.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-deploy
|
|
3
|
+
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.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Deploy files are added on demand: `kick g deploy docker` writes a
|
|
7
|
+
`Dockerfile` and `.dockerignore`; `kick g deploy netlify vercel` writes
|
|
8
|
+
`netlify.toml` / `vercel.json`, `src/serverless.ts` and the
|
|
9
|
+
`build:netlify` / `build:vercel` scripts.
|
|
10
|
+
|
|
11
|
+
**A Node host or a container** runs the long-running server. Without Docker:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
{{pm}} run build && NODE_ENV=production node dist/index.js
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Start it with `node`, not `kick start`: the CLI is a dev dependency, gone
|
|
18
|
+
after a production install. The image installs from the lockfile, so commit it.
|
|
19
|
+
|
|
20
|
+
**Netlify and Vercel** run the app as a Node function; the CLI builds both:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
{{pm}} run build:netlify # → .netlify/v1/functions/api.mjs
|
|
24
|
+
{{pm}} run build:vercel # → .vercel/output (Build Output API v3)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Both bundle `src/serverless.ts`:
|
|
28
|
+
`createHandler(() => import('./index'))` serves the app `src/index.ts`
|
|
29
|
+
describes — its `bootstrap()` call builds the app without listening — so
|
|
30
|
+
there is one set of options. Add middleware and adapters to `src/index.ts`
|
|
31
|
+
as usual.
|
|
32
|
+
|
|
33
|
+
Settings are detected from the layout: a workspace member beside a `web`
|
|
34
|
+
package publishes `web/dist` and routes `/api/*`; an Inertia app publishes
|
|
35
|
+
`dist/client`, packages the asset manifest and SSR bundle with the function,
|
|
36
|
+
and lets it take every other path; a standalone API takes every path.
|
|
37
|
+
Override in `kick.config.ts`:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
export default defineConfig({
|
|
41
|
+
deploy: { apiPath: '/api', staticDir: '../web/dist', include: ['data/geo.json'] },
|
|
42
|
+
})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`include` lists files the app reads at runtime; they are packaged with the
|
|
46
|
+
function. Memory does not survive between function instances: keep sessions in
|
|
47
|
+
`session({ store: 'cookie' })` or a shared store, and data in a database.
|
|
48
|
+
|
|
49
|
+
**Cloudflare Workers** is a different entry, not a third flag on this one.
|
|
50
|
+
Workers have no `node:http`, so `createHandler` cannot run there; use the
|
|
51
|
+
web entry over h3 v2:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// src/worker.ts
|
|
55
|
+
import 'reflect-metadata'
|
|
56
|
+
import { createFetchHandler } from '@forinda/kickjs/web'
|
|
57
|
+
import * as h3 from 'h3' // v2 — passed in, edge bundlers have no createRequire
|
|
58
|
+
import { modules } from './modules'
|
|
59
|
+
|
|
60
|
+
export default createFetchHandler((env) => ({ h3, modules, env }))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Two things make or break that deploy:
|
|
64
|
+
|
|
65
|
+
1. **Pre-bundle it yourself.** Point `wrangler.jsonc`'s `main` at a bundle
|
|
66
|
+
built with SWC (the same Vite + `unplugin-swc` setup as the other
|
|
67
|
+
targets), never at `src/worker.ts`. Wrangler's own esbuild compiles
|
|
68
|
+
decorators as ES decorators and emits no decorator metadata, so DI fails
|
|
69
|
+
at startup with a `getOwnMetadata` TypeError before any request lands.
|
|
70
|
+
2. **`compatibility_flags = ["nodejs_compat"]`** — request-scoped DI and
|
|
71
|
+
`ctx.set` / `ctx.get` ride on `AsyncLocalStorage`.
|
|
72
|
+
3. **Do not `import './config'` here.** It is required in `src/index.ts` and
|
|
73
|
+
`src/serverless.ts`, and wrong in a Worker twice over: the config module
|
|
74
|
+
reaches for `node:fs` / `createRequire`, which kills the Worker at
|
|
75
|
+
startup, and `loadEnvFromSchema` parses `process.env`, which Workers do
|
|
76
|
+
not have. The `env` binding threaded through `createFetchHandler` is what
|
|
77
|
+
feeds `ConfigService.get()` and `@Value()` instead — so values arrive as
|
|
78
|
+
the raw strings the platform holds, without the schema's coercion or
|
|
79
|
+
defaults. Coerce where you read them.
|
|
80
|
+
|
|
81
|
+
Not available on Workers: views, SPA/static serving, `@Asset`, adapters and
|
|
82
|
+
plugins. Serve static files from Workers Assets or a separate deploy.
|
|
83
|
+
|
|
84
|
+
**Red flags**:
|
|
85
|
+
- An `/api/*` route returning `index.html` on Netlify — the function is not
|
|
86
|
+
routed. Check the deploy summary says a function was deployed, keep
|
|
87
|
+
`preferStatic` out of a fullstack function's config, and leave Netlify's
|
|
88
|
+
**Package directory** unset so it reads the function at the repo root.
|
|
89
|
+
- Validation errors or flash messages that vanish on Netlify / Vercel — the
|
|
90
|
+
session lives in one instance's memory. Use `session({ store: 'cookie' })`.
|
|
91
|
+
- Committing `.netlify/` or `.vercel/` — both are build output.
|
|
92
|
+
- A frontend that builds somewhere other than `web/dist` and only one of
|
|
93
|
+
`deploy.staticDir`, `SpaAdapter({ clientDir })` and netlify.toml's
|
|
94
|
+
`publish` updated. All three name that directory.
|
|
95
|
+
- Pointing a platform at `src/index.ts` — it calls `bootstrap()`, which
|
|
96
|
+
listens on a port and registers signal handlers inside the function. The
|
|
97
|
+
platform entry is `src/serverless.ts`.
|
|
98
|
+
- Expecting `kick build` alone to produce a deployable function; it builds
|
|
99
|
+
the server. Run the target command after it.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-docs-lookup
|
|
3
|
+
description: Use FIRST when unsure about any KickJS API, option, or behaviour — before guessing from memory or inferring from surrounding code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
These skills are deliberately short — they cover the traps, not the whole API
|
|
7
|
+
surface. When the answer is not in one of them, read the docs rather than
|
|
8
|
+
inferring it from nearby code: a wrong guess about a framework API compiles
|
|
9
|
+
fine and fails at runtime.
|
|
10
|
+
|
|
11
|
+
**Where to look**
|
|
12
|
+
|
|
13
|
+
| Question | Page |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| Anything — start here | https://kickjs.app/ |
|
|
16
|
+
| Controllers, routing, `ctx` helpers | https://kickjs.app/guide/controllers |
|
|
17
|
+
| DI, tokens, scopes | https://kickjs.app/guide/dependency-injection |
|
|
18
|
+
| Modules and mounting | https://kickjs.app/guide/modules |
|
|
19
|
+
| Adapters, plugins, lifecycle hooks | https://kickjs.app/guide/adapters |
|
|
20
|
+
| Context Contributors | https://kickjs.app/guide/context-decorators |
|
|
21
|
+
| Env, `ConfigService`, `@Value` | https://kickjs.app/guide/configuration |
|
|
22
|
+
| Middleware and guards | https://kickjs.app/guide/middleware |
|
|
23
|
+
| Testing (`createTestApp`) | https://kickjs.app/guide/testing |
|
|
24
|
+
| Typegen and generated types | https://kickjs.app/guide/typegen |
|
|
25
|
+
| HMR and the dev server | https://kickjs.app/guide/hmr |
|
|
26
|
+
| `.kick` views, forms, components | https://kickjs.app/guide/views |
|
|
27
|
+
|
|
28
|
+
**Local, and usually faster**
|
|
29
|
+
|
|
30
|
+
- `kick explain "<error message>"` — matches known failures and gives the fix.
|
|
31
|
+
Pipe a failing run in: `{{test}} 2>&1 | {{kick}} explain`.
|
|
32
|
+
- `kick doctor` — checks this project's wiring.
|
|
33
|
+
- `kick inspect` — the live route / adapter table.
|
|
34
|
+
- `.kickjs/types/` — generated types are ground truth for what exists.
|
|
35
|
+
- `node_modules/@forinda/kickjs/dist/*.d.mts` — the real signature when a doc
|
|
36
|
+
page and the code disagree.
|
|
37
|
+
|
|
38
|
+
**Rule**: if you would be guessing, look it up. If a doc page contradicts the
|
|
39
|
+
installed `.d.mts`, trust the `.d.mts` and say so — the docs may be behind the
|
|
40
|
+
version this project has.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-env-wiring-check
|
|
3
|
+
description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Fastest path**: `kick explain "ConfigService.get('MY_KEY') returned undefined"` —
|
|
7
|
+
pipe a failing run straight in if you prefer (`{{test}} 2>&1 | {{kick}} explain`). It
|
|
8
|
+
distinguishes the entry-file cause from the test-file one, which is the step most
|
|
9
|
+
people lose time on. The manual checks below are the same reasoning.
|
|
10
|
+
|
|
11
|
+
**Diagnosis (in order)**:
|
|
12
|
+
1. Open `src/index.ts`. The **first non-`reflect-metadata`** import MUST be `import './config'`.
|
|
13
|
+
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:
|
|
14
|
+
```ts
|
|
15
|
+
import { loadEnvFromSchema } from '@forinda/kickjs/config'
|
|
16
|
+
import { fromZod } from '@forinda/kickjs-schema/zod'
|
|
17
|
+
const envSchema = fromZod(z.object({ DATABASE_URL: z.url() }))
|
|
18
|
+
loadEnvFromSchema(envSchema) // side effect: registers the schema
|
|
19
|
+
export default envSchema
|
|
20
|
+
```
|
|
21
|
+
App code reads values with `getEnv('DATABASE_URL')` (from `@forinda/kickjs`), an injected `ConfigService`, or `@Value()` — the config file exports no env object.
|
|
22
|
+
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.
|
|
23
|
+
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.
|
|
24
|
+
|
|
25
|
+
5. **In a test?** `createTestApp` never loads `src/index.ts`, so the entry's
|
|
26
|
+
`import './config'` never runs no matter how correct it is. The test file
|
|
27
|
+
must import it itself:
|
|
28
|
+
```ts
|
|
29
|
+
import '@/config'
|
|
30
|
+
```
|
|
31
|
+
Symptom is identical to the missing-entry-import case, and step 1 will look
|
|
32
|
+
fine, which is what makes it slow to spot.
|
|
33
|
+
|
|
34
|
+
**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.
|
|
35
|
+
|
|
36
|
+
**`reloadEnv` vs `resetEnvCache`** — distinct, frequently mixed up:
|
|
37
|
+
- `reloadEnv()` — re-reads `process.env` against the **already registered** schema. Use in HMR plugins after `.env` file changes. Schema survives.
|
|
38
|
+
- `resetEnvCache()` — drops the registered schema entirely. **Test-only.** Calling it between dev requests drops the project's keys.
|
|
39
|
+
|
|
40
|
+
**Nuances**:
|
|
41
|
+
- `dotenv` is an **optional peer dep** in v5+ — projects upgrading from older versions may need to add it explicitly.
|
|
42
|
+
- For HMR-friendly `.env` edits, add `envWatchPlugin()` to `vite.config.ts` — calls `reloadEnv()` automatically.
|
|
43
|
+
|
|
44
|
+
**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`.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-guard-vs-middleware-vs-contributor
|
|
3
|
+
description: Use when adding auth checks, request-scoped values, or anything "before the handler" — picks between a guard, a middleware, and a context contributor.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**KickJS has no guard primitive.** There is no `@Guard`, no `canActivate`, no guard
|
|
7
|
+
class to implement. A guard IS a middleware — the word only names a convention
|
|
8
|
+
and a directory. If you are porting NestJS habits, this is the first thing to
|
|
9
|
+
unlearn.
|
|
10
|
+
|
|
11
|
+
| | Guard | Middleware | Context contributor |
|
|
12
|
+
|---|---|---|---|
|
|
13
|
+
| What it is | a middleware, by convention | a middleware | a declarative value producer |
|
|
14
|
+
| Signature | `(ctx, next)` | `(ctx, next)` on `@Middleware()`, `(req, res, next)` in `bootstrap({ middlewares })` | `resolve(ctx, deps)` returning a value |
|
|
15
|
+
| Can end the request | yes | yes | **no** |
|
|
16
|
+
| Runs | in the middleware stage | in the middleware stage | after ALL middleware |
|
|
17
|
+
| Attached by | `@Middleware(fn)` | `@Middleware(fn)` or `bootstrap({ middlewares })` | `@LoadX`, or a registration at module / adapter / bootstrap level |
|
|
18
|
+
| Generator | `kick g guard <name>` | `kick g middleware <name>` | `kick g contributor <name>` |
|
|
19
|
+
| Lands in | `src/guards/<name>.guard.ts` | `src/middleware/<name>.middleware.ts` | `src/contributors/<name>.contributor.ts` |
|
|
20
|
+
|
|
21
|
+
Add `-m <module>` to any of those generators to place the file inside a module
|
|
22
|
+
instead of the app-level directory.
|
|
23
|
+
|
|
24
|
+
**Choosing**: does the thing ever need to STOP the request?
|
|
25
|
+
- Yes, and it is authorization → guard.
|
|
26
|
+
- Yes, anything else (rate limit, body rewrite, response stream, work before route matching) → middleware.
|
|
27
|
+
- 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.
|
|
28
|
+
|
|
29
|
+
**Ordering — guards run BEFORE contributors.** Every runtime does the same
|
|
30
|
+
thing: run `entry.middlewares` in order, bail if the response was written,
|
|
31
|
+
then run the contributor pipeline, then the handler. So:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// WRONG — tenant is always undefined here.
|
|
35
|
+
export async function tenantGuard(ctx: RequestContext, next: () => void) {
|
|
36
|
+
const tenant = ctx.get('tenant') // contributors have not run yet
|
|
37
|
+
if (!tenant) return ctx.problem.forbidden()
|
|
38
|
+
next()
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
A guard that needs a resolved value must resolve it itself, or the check
|
|
43
|
+
belongs in the contributor's own `resolve` (throw from there and the request
|
|
44
|
+
error handler takes over).
|
|
45
|
+
|
|
46
|
+
**Write responses with `ctx.*`, never `ctx.res`.** `ctx.res` is the ENGINE-NATIVE
|
|
47
|
+
response object, so `ctx.res.status(401).json(...)` only works on Express —
|
|
48
|
+
`FastifyReply` has no `.json()` and h3's event has no `.status()`. Use
|
|
49
|
+
`ctx.problem.unauthorized({ detail })` (RFC 9457) or `ctx.json(body, status)`,
|
|
50
|
+
and the helper for anything else you would reach `ctx.res` for:
|
|
51
|
+
`ctx.download(buffer, filename, contentType?)` for a generated file,
|
|
52
|
+
`ctx.html(content)`, `ctx.redirect(url, status?)`, `ctx.sse()` for a stream.
|
|
53
|
+
All of them work on all four runtimes. Never hand `ctx.redirect` a destination
|
|
54
|
+
taken from the request unchecked — allow-list it, or accept only a same-site path
|
|
55
|
+
(one leading `/`, not `//`) — or the route is an open redirect.
|
|
56
|
+
|
|
57
|
+
**Guard shape**:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import type { RequestContext } from '@forinda/kickjs'
|
|
61
|
+
|
|
62
|
+
export async function adminGuard(ctx: RequestContext, next: () => void): Promise<void> {
|
|
63
|
+
// Requires the session() middleware. Type the key once:
|
|
64
|
+
// declare module '@forinda/kickjs' { interface SessionData { role?: 'admin' | 'member' } }
|
|
65
|
+
const role = ctx.session?.data.role
|
|
66
|
+
if (!role) {
|
|
67
|
+
ctx.problem.unauthorized({ detail: 'Not signed in' })
|
|
68
|
+
return // do NOT call next()
|
|
69
|
+
}
|
|
70
|
+
if (role !== 'admin') {
|
|
71
|
+
ctx.problem.forbidden({ detail: 'Admin only' })
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
next()
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
@Middleware(adminGuard)
|
|
80
|
+
@Get('/admin/stats')
|
|
81
|
+
stats(ctx: RequestContext) { ... }
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Role checks that are purely declarative (`@Public()`, `@Roles('admin')`,
|
|
85
|
+
`@Can(...)`) are yours to define — see the BYO Auth recipe in the docs.
|
|
86
|
+
Hand-write a guard only for logic those don't express.
|
|
87
|
+
|
|
88
|
+
**Red flags**:
|
|
89
|
+
- `class AdminGuard implements CanActivate` / `@UseGuards()` — NestJS, not KickJS. Export a `(ctx, next)` function and attach with `@Middleware()`.
|
|
90
|
+
- A guard calling `next()` AND writing a response — pick one; writing then continuing double-sends.
|
|
91
|
+
- A guard reading `ctx.get(...)` for a contributor-produced key — contributors have not run yet.
|
|
92
|
+
- `ctx.res.status(403).json(...)` in a guard — Express-only. Use `ctx.problem.forbidden()`.
|
|
93
|
+
- A "guard" that only sets a value and always calls `next()` — that is a contributor wearing a guard's name.
|
|
94
|
+
- Passing a `(ctx, next)` guard to `bootstrap({ middlewares })` — global middleware is connect-style `(req, res, next)`. Mount guards per-route with `@Middleware()`.
|
|
95
|
+
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-query-parsing-list-endpoint
|
|
3
|
+
description: Use when adding a paginated/filterable list route — emit ctx.qs + ctx.paginate with an allow-list.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Canonical list endpoint**:
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
@Get('/')
|
|
10
|
+
async list(ctx: Ctx<KickRoutes.TodoController['list']>) {
|
|
11
|
+
const parsed = ctx.qs({
|
|
12
|
+
filterable: ['status', 'priority', 'assigneeId'], // allow-list, MUST be set
|
|
13
|
+
sortable: ['createdAt', 'updatedAt', 'priority'],
|
|
14
|
+
searchColumns: ['title', 'description'], // free-text search targets
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
return ctx.paginate(async () => {
|
|
18
|
+
const { data, total } = await this.service.list(parsed)
|
|
19
|
+
return { data, total }
|
|
20
|
+
}, parsed)
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**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`).
|
|
25
|
+
|
|
26
|
+
**Drizzle adopters** — pass a `DrizzleQueryParamsConfig` with column refs:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
const TASK_QUERY_CONFIG = {
|
|
30
|
+
filterable: { status: tasks.status, priority: tasks.priority },
|
|
31
|
+
sortable: { createdAt: tasks.createdAt },
|
|
32
|
+
searchColumns: [tasks.title, tasks.description],
|
|
33
|
+
}
|
|
34
|
+
const parsed = ctx.qs(TASK_QUERY_CONFIG)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**ORM-agnostic builders** — implement `QueryBuilderAdapter<TResult, TConfig>` with `build(parsed, config)`. The Drizzle + Prisma adapters live here.
|
|
38
|
+
|
|
39
|
+
**Red flags**:
|
|
40
|
+
- Reading `req.query.status` directly — bypasses the allow-list; opens unbounded filtering. Use `ctx.qs({ filterable })`.
|
|
41
|
+
- Omitting `filterable` / `sortable` allow-list — every client-supplied filter is **silently dropped** (security default, but looks like a bug).
|
|
42
|
+
- Hand-building the pagination meta in the controller — inconsistent response shape across endpoints. Always use `ctx.paginate()`.
|
|
43
|
+
- Returning a bare array from a list endpoint when pagination is implied — breaks the `PaginatedResponse<T>` contract.
|
|
44
|
+
- Mixing string `searchable` config with column `searchColumns` (Drizzle) — silently no-ops.
|
|
45
|
+
|
|
46
|
+
**Nuances**:
|
|
47
|
+
- `limit` is capped at 100 server-side; `q` (search) is truncated to 200 chars. Don't re-validate client-side.
|
|
48
|
+
- Sort direction defaults to `asc` when omitted (`?sort=createdAt` ≡ `?sort=createdAt:asc`).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-refresh-agent-docs
|
|
3
|
+
description: Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Steps**:
|
|
7
|
+
1. `kick g agents -f --only both` — overwrites `CLAUDE.md` (root) and `.agents/AGENTS.md`.
|
|
8
|
+
2. `kick g agents -f --only skills` — refreshes every `.agents/skills/<slug>/SKILL.md`.
|
|
9
|
+
3. `kick g agents -f --only gemini` / `--only copilot` — refresh the per-agent files when needed.
|
|
10
|
+
4. 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.
|
|
11
|
+
5. Commit as `docs(agents): sync from CLI vX.Y`.
|
|
12
|
+
|
|
13
|
+
**`.agents/` layout** (post-restructure):
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
CLAUDE.md # at root — Claude Code auto-loads from here
|
|
17
|
+
.agents/
|
|
18
|
+
├── AGENTS.md # canonical multi-agent reference
|
|
19
|
+
├── GEMINI.md # Gemini-specific notes
|
|
20
|
+
├── COPILOT.md # Copilot CLI notes
|
|
21
|
+
└── skills/
|
|
22
|
+
├── add-module/SKILL.md
|
|
23
|
+
├── add-adapter/SKILL.md
|
|
24
|
+
└── … # one SKILL.md per skill, frontmatter-namespaced
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Customisation goes in `.local.md` siblings (`AGENTS.local.md`, `skills/<slug>/SKILL.local.md`) — those are never overwritten.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-route-flags
|
|
3
|
+
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.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
A route flag is a named, inheritable fact about a route. It carries no
|
|
7
|
+
behaviour: it records something every consumer can read, so "this endpoint is
|
|
8
|
+
open" is declared once instead of restated as an auth contributor, a
|
|
9
|
+
`csrf ignorePaths` entry and a `rateLimit skipPaths` entry — two of which are
|
|
10
|
+
pathname strings that cannot express `/users/:id`.
|
|
11
|
+
|
|
12
|
+
**Steps**:
|
|
13
|
+
1. Declare it once, in its own module:
|
|
14
|
+
```ts
|
|
15
|
+
import { defineRouteFlag } from '@forinda/kickjs'
|
|
16
|
+
|
|
17
|
+
export const Public = defineRouteFlag('auth.public')
|
|
18
|
+
export const Limit = defineRouteFlag<{ rpm: number }>('rate.limit')
|
|
19
|
+
```
|
|
20
|
+
2. Apply it. A class flag is inherited by every route under it; `.off` on a
|
|
21
|
+
method removes it:
|
|
22
|
+
```ts
|
|
23
|
+
@Public // every route below inherits it
|
|
24
|
+
@Controller()
|
|
25
|
+
export class WebhooksController {
|
|
26
|
+
@Get('/health')
|
|
27
|
+
health(ctx: RequestContext) {} // public
|
|
28
|
+
|
|
29
|
+
@Public.off // the method wins
|
|
30
|
+
@Post('/admin')
|
|
31
|
+
admin(ctx: RequestContext) {} // not public
|
|
32
|
+
|
|
33
|
+
@Limit({ rpm: 10 }) // flags can carry a value
|
|
34
|
+
@Post('/login')
|
|
35
|
+
login(ctx: RequestContext) {}
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
3. Read it from the consumer that already exists, rather than a new one.
|
|
39
|
+
**Where a consumer is mounted decides how it reads flags** — everything
|
|
40
|
+
after route matching gets `ctx.route`; anything before it does not:
|
|
41
|
+
|
|
42
|
+
| Consumer | Mounted at | Reads flags by |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| Handler | the route itself | `ctx.route?.flags.has('auth.public')` |
|
|
45
|
+
| Guard / `@Middleware()` | `@Middleware(fn)` on a method or controller class | `ctx.route`, or the built-ins' `exemptWhen` |
|
|
46
|
+
| `csrfGuard()` / `rateLimitGuard()` | same — `@Middleware()`, class or method | `exemptWhen: 'csrf.exempt'` |
|
|
47
|
+
| Contributor | method > class > module `contributors()` > adapter `contributors()` > `bootstrap({ contributors })` | `skipWhen` / `onlyWhen` on the registration |
|
|
48
|
+
| Global middleware (`rateLimit()`) | `bootstrap({ middlewares: [...] })` — runs **before** matching | the route policy table (`bindRoutePolicy`); `ctx.route` is `undefined` here |
|
|
49
|
+
| 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 |
|
|
50
|
+
| OpenAPI | `SwaggerAdapter({ publicFlag: 'auth.public' })` | read once at startup, not per request |
|
|
51
|
+
| MCP / AI tools | `McpAdapter({ exposeWhen: 'mcp.tool', hideWhen: 'mcp.hidden' })` | read once at startup |
|
|
52
|
+
|
|
53
|
+
The contributor row is the one that buys the most: those five levels mean a
|
|
54
|
+
plugin's contributor can be skipped on one route (`skipWhen`) without
|
|
55
|
+
forking it, and a method-level registration beats the adapter's.
|
|
56
|
+
|
|
57
|
+
4. Run `kick typegen`. It writes the `KickRouteFlags` augmentation, so flag
|
|
58
|
+
names autocomplete and a typo fails `tsc` instead of silently never matching.
|
|
59
|
+
|
|
60
|
+
**Red flags**:
|
|
61
|
+
- Writing `@Public(false)` to remove a flag — removal is `@Public.off`. A
|
|
62
|
+
resolved flag is present or absent; `false` is a legitimate *value* for a
|
|
63
|
+
flag declared `boolean`, and a presence check would still answer `true`.
|
|
64
|
+
- A new consumer growing its own `skipPaths` / `ignorePaths` list — that is
|
|
65
|
+
the duplication flags exist to remove, and path strings break on params and
|
|
66
|
+
on any `apiPrefix` change.
|
|
67
|
+
- `@Public.off` on a route that never inherited the flag — a no-op, and
|
|
68
|
+
usually a sign the expected class-level flag is not there.
|
|
69
|
+
- Reading `ctx.route` in global middleware — it is `undefined` before a route
|
|
70
|
+
is matched (steps 1-6 of the pipeline). Move the check into a guard mounted
|
|
71
|
+
with `@Middleware()`, or read the policy table.
|
|
72
|
+
- Inventing a flag name per consumer (`auth.open`, `public`, `isPublic`). The
|
|
73
|
+
framework names none of them; pick one name per fact and reuse it.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-thin-entry-file
|
|
3
|
+
description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Refactor target**:
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
// src/modules/index.ts — fluent chain (default for `modules.style: 'define'`)
|
|
10
|
+
export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
|
|
11
|
+
// OR for class-form projects (`modules.style: 'class'`):
|
|
12
|
+
// export const modules: AppModuleEntry[] = [HelloModule, UsersModule]
|
|
13
|
+
|
|
14
|
+
// src/middleware/index.ts — global middleware uses RAW EXPRESS signature
|
|
15
|
+
// (req, res, next), NOT (ctx, next)
|
|
16
|
+
// `express.json()` is auto-skipped on Fastify and h3, which parse bodies
|
|
17
|
+
// natively — harmless to list, but don't reach for it as the body parser there.
|
|
18
|
+
export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
|
|
19
|
+
|
|
20
|
+
// src/plugins/index.ts
|
|
21
|
+
export const plugins = [MetricsPlugin(), AuthPlugin({ tokenTtl: getEnv('TOKEN_TTL') })]
|
|
22
|
+
|
|
23
|
+
// src/adapters/index.ts
|
|
24
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
25
|
+
|
|
26
|
+
// src/index.ts — stays small
|
|
27
|
+
import 'reflect-metadata'
|
|
28
|
+
import './config' // MUST be early — side-effect schema load
|
|
29
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
30
|
+
import { modules } from './modules'
|
|
31
|
+
import { middleware } from './middleware'
|
|
32
|
+
import { plugins } from './plugins'
|
|
33
|
+
import { adapters } from './adapters'
|
|
34
|
+
export const app = await bootstrap({ modules, middlewares, plugins, adapters })
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**One-off DI binding** — inline a literal plugin inside `plugins`, not a top-level option:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
plugins: [
|
|
41
|
+
...plugins,
|
|
42
|
+
{ name: 'vector-store', register(c) { c.registerInstance(VECTOR_STORE, store) } },
|
|
43
|
+
]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
**Red flags**:
|
|
47
|
+
- Any `new SomeAdapter()` / `SomePlugin()` literal inside `bootstrap({ ... })` instead of imported from a category folder.
|
|
48
|
+
- 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".
|
|
49
|
+
- `bootstrap({ register: ... })` — that option doesn't exist. Use an inline plugin.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-use-asset-manager
|
|
3
|
+
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.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Configure** `kick.config.ts`:
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
export default defineConfig({
|
|
10
|
+
assetMap: {
|
|
11
|
+
mails: { src: 'src/templates/mails' },
|
|
12
|
+
reports: { src: 'src/templates/reports', glob: '**/*.{ejs,html}' },
|
|
13
|
+
},
|
|
14
|
+
})
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
**Consume** via the typed Proxy — no `__dirname` arithmetic, dev/prod paths handled:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { assets } from '@forinda/kickjs'
|
|
21
|
+
|
|
22
|
+
const html = await assets.mails.welcome() // typed: tsc errors on bad key
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**Class-field decorator** (lazy getter, swappable in tests):
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
class WelcomeMailService {
|
|
29
|
+
@Asset('mails/welcome') private welcomeTemplate!: () => Promise<string>
|
|
30
|
+
|
|
31
|
+
async send(to: string) {
|
|
32
|
+
const body = await this.welcomeTemplate()
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**Dynamic dispatch** (CMS templates, codegen) — `resolveAsset(ns, key)` throws `UnknownAssetError` with `{ namespace, key }` fields when the key is missing.
|
|
38
|
+
|
|
39
|
+
**Test fixtures** — swap via env override + cache clear:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
beforeEach(() => {
|
|
43
|
+
process.env.KICK_ASSETS_ROOT = path.resolve('__fixtures__/assets')
|
|
44
|
+
clearAssetCache()
|
|
45
|
+
})
|
|
46
|
+
afterEach(() => {
|
|
47
|
+
delete process.env.KICK_ASSETS_ROOT
|
|
48
|
+
clearAssetCache()
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**Red flags**:
|
|
53
|
+
- Hand-rolled `process.env.NODE_ENV === 'production' ? join(__dirname, '../templates') : join(__dirname, 'templates')` — exactly what the asset manager replaces.
|
|
54
|
+
- `keys: 'strip'` setting in `assetMap.<ns>` when basenames may collide — silent last-walk-wins data loss. Default `'auto'` keeps extensions only for colliding groups.
|
|
55
|
+
- 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`.
|
|
56
|
+
- 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).
|
|
57
|
+
- Same-name `welcome.ejs` + `welcome/login.ejs` — directory wins in the typed surface; the `.ejs` file still copies but isn't addressable.
|
|
58
|
+
|
|
59
|
+
**Nuances**:
|
|
60
|
+
- 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."
|
|
61
|
+
- 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.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: kickjs-write-controller-test
|
|
3
|
+
description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Template** (copy/paste, adjust):
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { describe, it, expect, beforeEach } from 'vitest'
|
|
10
|
+
import request from 'supertest'
|
|
11
|
+
import { Container } from '@forinda/kickjs'
|
|
12
|
+
import { createTestApp } from '@forinda/kickjs-testing'
|
|
13
|
+
// Side-effect import — registers the env schema, exactly as src/index.ts does.
|
|
14
|
+
// `createTestApp` never loads the entry file, so without this
|
|
15
|
+
// `ConfigService.get('YOUR_KEY')` is undefined under test while `@Value()`
|
|
16
|
+
// still appears to work via its process.env fallback — the two disagree only
|
|
17
|
+
// in tests.
|
|
18
|
+
import '@/config'
|
|
19
|
+
|
|
20
|
+
describe('UserController', () => {
|
|
21
|
+
beforeEach(() => Container.reset()) // isolate DI between tests
|
|
22
|
+
|
|
23
|
+
it('returns users', async () => {
|
|
24
|
+
// `createTestApp` takes an OPTIONS OBJECT and returns
|
|
25
|
+
// `{ app, container }`. Passing a bare array throws
|
|
26
|
+
// "this.options.modules is not iterable"; the result has no `.get()`.
|
|
27
|
+
//
|
|
28
|
+
// Drive `app.handle` rather than `expressApp`: it is the Application's
|
|
29
|
+
// own Node listener, so the test runs on whichever runtime the app is
|
|
30
|
+
// configured with. Pass `runtime` to `createTestApp` to match production.
|
|
31
|
+
const { app } = await createTestApp({
|
|
32
|
+
// Matches this project's `modules.style`.
|
|
33
|
+
modules: [{{moduleEntry}}],
|
|
34
|
+
})
|
|
35
|
+
const res = await request(app.handle.bind(app)).get('/api/v1/users')
|
|
36
|
+
expect(res.status).toBe(200)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**Typed handler signature** — pair with `kick typegen` so `ctx.body` / `params` / `query` are typed by the route's Zod schema:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
@Post('/', { body: createTodoSchema })
|
|
45
|
+
async create(ctx: Ctx<KickRoutes.TodoController['create']>) {
|
|
46
|
+
// ctx.body is typed from createTodoSchema; ctx.params from the route.
|
|
47
|
+
// Returning (vs ctx.created) lets typegen infer the response type.
|
|
48
|
+
return reply(201, await this.service.create(ctx.body))
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**Red flags**:
|
|
53
|
+
- `new Container()` — wrong; use `Container.reset()` in `beforeEach` or `Container.create()` for fully isolated graphs.
|
|
54
|
+
- `Container.getInstance().reset()` — wrong; same fix.
|
|
55
|
+
- Sharing a container instance across `it()` blocks — leaks registrations between tests.
|
|
56
|
+
- Injecting a `Scope.REQUEST` service into a `SINGLETON` — container throws at resolve. Singletons must resolve request-scoped services explicitly per call.
|
|
57
|
+
- Calling `getRequestValue<string>('traceId')` — the generic slot is the **key** type, not the value type; widens key and bypasses typed lookup.
|
|
58
|
+
- Asserting on `res.body.requestId` when `requestId()` middleware isn't mounted in the test app — value will be `undefined`.
|
|
59
|
+
- Using `Scope.REQUEST` services in a test without mounting `requestScopeMiddleware()` — `getRequestValue` silently returns `undefined`; `getRequestStore` throws.
|
|
60
|
+
|
|
61
|
+
**Nuances**:
|
|
62
|
+
- `@Inject` and `@Autowired` are interchangeable — same runtime, same types; pick by readability.
|
|
63
|
+
- `@Value('MISSING_KEY')` with no default **throws on property access**, not at construction — tests that exercise the getter will surface the missing-env issue.
|