@forinda/kickjs-cli 8.15.0 → 8.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/agent-docs-BVFt7K8T.mjs +591 -0
  2. package/dist/agent-docs-BVFt7K8T.mjs.map +1 -0
  3. package/dist/agent-docs-DBLN2Mp9.mjs +590 -0
  4. package/dist/{build-gqxIH3D8.mjs → build-BKGmBYPE.mjs} +3 -3
  5. package/dist/{build-gqxIH3D8.mjs.map → build-BKGmBYPE.mjs.map} +1 -1
  6. package/dist/{build-Czsf4CBN.mjs → build-BmjXHtAh.mjs} +2 -2
  7. package/dist/{builtins-6euI1-lN.mjs → builtins-C-qFcIBD.mjs} +2 -2
  8. package/dist/{builtins-xahWxQLw.mjs → builtins-NIDfVClB.mjs} +59 -59
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-DCM2vXUJ.mjs → config-C881BGnv.mjs} +2 -2
  11. package/dist/{config-8jdSKLKJ.mjs → config-CgoZjmsu.mjs} +3 -3
  12. package/dist/{config-8jdSKLKJ.mjs.map → config-CgoZjmsu.mjs.map} +1 -1
  13. package/dist/{doctor-CwGU9orm.mjs → doctor-CWP1-2fB.mjs} +9 -9
  14. package/dist/{doctor-CwGU9orm.mjs.map → doctor-CWP1-2fB.mjs.map} +1 -1
  15. package/dist/{fullstack-9HywHQL-.mjs → fullstack-BPB6BkL8.mjs} +13 -13
  16. package/dist/{fullstack-9HywHQL-.mjs.map → fullstack-BPB6BkL8.mjs.map} +1 -1
  17. package/dist/{fullstack-BmIFnryN.mjs → fullstack-_0qGKsG7.mjs} +9 -9
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +2 -2
  20. package/dist/{plugin-BjmLRF7t.mjs → plugin-KpSiVmlT.mjs} +2 -2
  21. package/dist/{plugin-DLZP4hZ0.mjs → plugin-_Xkj7vNO.mjs} +2 -2
  22. package/dist/project-CO9buk5F.mjs +133 -0
  23. package/dist/project-CO9buk5F.mjs.map +1 -0
  24. package/dist/project-qHDV333j.mjs +132 -0
  25. package/dist/{project-root-Dk8r8FMi.mjs → project-root-BAZV1qId.mjs} +3 -3
  26. package/dist/{project-root-Dk8r8FMi.mjs.map → project-root-BAZV1qId.mjs.map} +1 -1
  27. package/dist/{project-root-8DH00M-b.mjs → project-root-DdPFoCw6.mjs} +2 -2
  28. package/dist/{rolldown-runtime-CRasMkPY.mjs → rolldown-runtime-B0Wm12ok.mjs} +1 -1
  29. package/dist/{run-plugins-R0bVf_nK.mjs → run-plugins-DLCZx7uc.mjs} +67 -67
  30. package/dist/run-plugins-DLCZx7uc.mjs.map +1 -0
  31. package/dist/{typegen-DNufBmjE.mjs → typegen-B8uRTy_3.mjs} +4 -4
  32. package/dist/{typegen-BZ8cQ1YM.mjs → typegen-DGq3DowV.mjs} +5 -5
  33. package/dist/{typegen-BZ8cQ1YM.mjs.map → typegen-DGq3DowV.mjs.map} +1 -1
  34. package/dist/{types-DOcxTXlP.mjs → types-CokUufqE.mjs} +1 -1
  35. package/package.json +4 -4
  36. package/templates/base/files/_dot_vscode/extensions.json +3 -0
  37. package/templates/base/files/kick.config.ts +4 -0
  38. package/templates/base/skills/add-adapter.txt +56 -0
  39. package/templates/base/skills/add-module.txt +53 -0
  40. package/templates/base/skills/add-plugin.txt +69 -0
  41. package/templates/base/skills/bootstrap-export.txt +21 -0
  42. package/templates/base/skills/cli-commands-cheatsheet.txt +46 -0
  43. package/templates/base/skills/cli-plugin.txt +61 -0
  44. package/templates/base/skills/context-contributor.txt +73 -0
  45. package/templates/base/skills/deny-list.txt +44 -0
  46. package/templates/base/skills/deploy.txt +99 -0
  47. package/templates/base/skills/docs-lookup.txt +40 -0
  48. package/templates/base/skills/env-wiring-check.txt +44 -0
  49. package/templates/base/skills/guard-vs-middleware-vs-contributor.txt +95 -0
  50. package/templates/base/skills/query-parsing-list-endpoint.txt +48 -0
  51. package/templates/base/skills/refresh-agent-docs.txt +27 -0
  52. package/templates/base/skills/route-flags.txt +73 -0
  53. package/templates/base/skills/thin-entry-file.txt +49 -0
  54. package/templates/base/skills/use-asset-manager.txt +61 -0
  55. package/templates/base/skills/write-controller-test.txt +63 -0
  56. package/templates/feature-views/feature.json +21 -0
  57. package/templates/feature-views/files/src/adapters/views.ts +5 -0
  58. package/templates/feature-views/files/src/views/home.kick +3 -0
  59. package/templates/feature-views/files/src/views/layouts/main.kick +13 -0
  60. package/templates/feature-views/files/src/views.ts +9 -0
  61. package/templates/feature-views/skills/views-forms.txt +68 -0
  62. package/templates/feature-views/skills/views.txt +49 -0
  63. package/templates/fullstack-root/files/_dot_vscode/extensions.json +3 -0
  64. package/dist/agent-docs-CrVQtJgn.mjs +0 -932
  65. package/dist/agent-docs-D7K6R5C3.mjs +0 -933
  66. package/dist/agent-docs-D7K6R5C3.mjs.map +0 -1
  67. package/dist/package-manager-9XxrErw1.mjs +0 -11
  68. package/dist/package-manager-Dwaolesm.mjs +0 -12
  69. package/dist/package-manager-Dwaolesm.mjs.map +0 -1
  70. package/dist/project-CFi3NvO9.mjs +0 -136
  71. package/dist/project-CFi3NvO9.mjs.map +0 -1
  72. package/dist/project-CO0D8B0V.mjs +0 -135
  73. package/dist/run-plugins-R0bVf_nK.mjs.map +0 -1
@@ -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.
@@ -0,0 +1,21 @@
1
+ {
2
+ "dependencies": ["@forinda/kickjs-view"],
3
+ "integrations": [
4
+ {
5
+ "import": {
6
+ "from": "./adapters/views",
7
+ "names": ["viewsAdapter"]
8
+ },
9
+ "slot": "adapter",
10
+ "code": "// .kick templates in src/views: ctx.render('home').\nviewsAdapter()"
11
+ },
12
+ {
13
+ "import": {
14
+ "from": "@forinda/kickjs-view/cli",
15
+ "names": ["viewCliPlugin"]
16
+ },
17
+ "slot": "config-plugin",
18
+ "code": "// kick check:views and kick fmt:views\nviewCliPlugin"
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,5 @@
1
+ import { KickView } from '@forinda/kickjs-view'
2
+ import { views } from '../views'
3
+
4
+ /** Server-rendered pages: `await ctx.render('home', data)` in a controller. */
5
+ export const viewsAdapter = () => KickView({ views })
@@ -0,0 +1,3 @@
1
+ @layout('layouts/main')
2
+ <h1>Hello from {{ title }}</h1>
3
+ <p>Edit src/views/home.kick, then render it from a controller: ctx.render('home', { title }).</p>
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <slot name="head">
7
+ <title>Home</title>
8
+ </slot>
9
+ </head>
10
+ <body>
11
+ <slot />
12
+ </body>
13
+ </html>
@@ -0,0 +1,9 @@
1
+ /// <reference types="@forinda/kickjs-view/virtual" />
2
+ import kickViews from 'virtual:kick-views'
3
+ import { createViews } from '@forinda/kickjs-view'
4
+
5
+ /**
6
+ * The app's `.kick` templates (src/views). `kick build` checks them and ships
7
+ * them in the build; `kick dev` reads them on each request.
8
+ */
9
+ export const views = createViews({ ...kickViews, layout: 'layouts/main' })
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: kickjs-views-forms
3
+ description: Use when building an HTML form with .kick views — validation errors back on the form, refilled values, flash messages, browser-side checks (validate="…"), CSRF for form posts — or when a form post arrives with an empty body.
4
+ ---
5
+
6
+ **Wiring** (once):
7
+
8
+ ```ts
9
+ import express from 'express'
10
+ import { bootstrap, csrf, formErrorHandler, getEnv, session } from '@forinda/kickjs'
11
+ import { KickView } from '@forinda/kickjs-view'
12
+ import { views } from './views'
13
+
14
+ export const app = await bootstrap({
15
+ modules,
16
+ middlewares: [
17
+ // Express only: listing middlewares replaces the default body parsers —
18
+ // forms post urlencoded, and keep JSON for any JSON routes.
19
+ express.urlencoded({ extended: false }),
20
+ express.json(),
21
+ session({ secret: getEnv('SESSION_SECRET'), store: 'cookie' }),
22
+ csrf(),
23
+ ],
24
+ adapters: [KickView({ views })],
25
+ onError: formErrorHandler(),
26
+ })
27
+ ```
28
+
29
+ Without `express.urlencoded` on Express, `ctx.body` is empty for form posts; without `express.json()`, for JSON. When the app already lists `middlewares`, add these to its list rather than replacing it. Fastify and h3 parse bodies themselves.
30
+
31
+ **The round trip**
32
+
33
+ ```ts
34
+ @Post('/tasks', { body: taskSchema })
35
+ async create(ctx: RequestContext) {
36
+ await this.tasks.create(ctx.body)
37
+ flash(ctx, { success: 'Task added' })
38
+ ctx.redirect('/tasks', 303)
39
+ }
40
+ ```
41
+
42
+ A failed `body` schema on a browser form post: `formErrorHandler()` stores the errors and the submitted values in the session and redirects (303) back to the page the form was on. API and `fetch()` calls get the usual 422.
43
+
44
+ ```kick
45
+ <form method="post" action="/tasks">
46
+ <input type="hidden" name="_csrf" value="{{ csrfToken }}">
47
+ <input name="title" validate="required | maxLength:200">
48
+ @error('title') {
49
+ {{ $message }}
50
+ }
51
+ <button>Add</button>
52
+ </form>
53
+ ```
54
+
55
+ - Every template has `$errors` (field → first message, `form` for the whole body), `$old` and `$flash` — for the next page only.
56
+ - Named inputs refill from `$old` by themselves; passwords, hidden fields and secret-looking names never do.
57
+ - A check the schema can't do (email already taken): re-render with `ctx.render('tasks/new', { $errors: { email: '…' }, $old: ctx.body })`.
58
+ - Flash messages: `@for ([kind, message] of $flash | entries; track kind) { … }` in the layout.
59
+
60
+ **CSRF.** `csrf()` takes the token from the `_csrf` form field when there's no `x-csrf-token` header. Give pages the token with `createViews({ share: (ctx) => ({ csrfToken: csrfToken(ctx) }) })` (`csrfToken` from `@forinda/kickjs`).
61
+
62
+ **Checking in the browser**
63
+
64
+ - `validate="required | email | minLength:3"` on a named field: built-ins `required`, `email`, `url`, `minLength:n`, `maxLength:n`, `min:n`, `max:n`, `pattern:'re'`, `in:'a, b'`. Messages land in the field's `@error` spot. Only pages with such a field get the small validator script.
65
+ - Rich rules: a component with a `<script client>` can import the route's own schema (`import { taskSchema } from '@/modules/tasks/tasks.schemas'`) and run `safeParse` on blur and submit — one set of rules for server and browser. Keep the schema file free of server imports.
66
+ - The browser checks are for quick feedback. The route's schema still decides.
67
+
68
+ Full guide: https://kickjs.app/guide/views#forms.
@@ -0,0 +1,49 @@
1
+ ---
2
+ name: kickjs-views
3
+ description: Use when rendering server-side HTML with .kick templates — setting up views, adding a page, layout, component or pipe, a component with a <script client>, or when a template fails kick build / kick check:views.
4
+ ---
5
+
6
+ **Setup** (once): `{{kick}} add views` does it all. By hand: `{{pm}} add @forinda/kickjs-view`, then
7
+
8
+ ```ts
9
+ // src/views.ts
10
+ /// <reference types="@forinda/kickjs-view/virtual" />
11
+ import kickViews from 'virtual:kick-views'
12
+ import { createViews } from '@forinda/kickjs-view'
13
+
14
+ export const views = createViews({ ...kickViews, layout: 'layouts/main' })
15
+ ```
16
+
17
+ and `adapters: [KickView({ views })]` in `bootstrap()`. For `kick check:views` / `kick fmt:views`, register the CLI plugin in `kick.config.ts`: `import { viewCliPlugin } from '@forinda/kickjs-view/cli'` and `plugins: [viewCliPlugin]` (`kick add views` prints this line; `kick new --packages views` writes it). `virtual:kick-views` comes from `kickjsVitePlugin()`: `kick build` checks every template and ships them; `kick dev` reads `src/views` on each request.
18
+
19
+ **Where things go**
20
+
21
+ | Thing | File | Used as |
22
+ | --- | --- | --- |
23
+ | Page | `src/views/users/show.kick` | `await ctx.render('users/show', { user })` |
24
+ | Layout | `src/views/layouts/main.kick` (`<slot />`, `<slot name="head">`) | `@layout('layouts/main')` or `createViews({ layout })` |
25
+ | Component | `src/views/components/user-card.kick` (`@input user`) | `<user-card [user]="u" />` |
26
+ | Pipe | an export of `src/views/pipes.ts` | `{{ total \| money }}` |
27
+ | Data every page gets | `createViews({ share: (ctx) => ({ user: ctx?.get('user') }) })` | `{{ user.email }}` |
28
+
29
+ **Syntax that trips people**
30
+
31
+ - `{{ expr }}` escapes. Expressions read data: **no function calls**, no object literals. Compute in the controller and pass the result.
32
+ - `class` and `style` can't be interpolated: use `[class.done]="task.done"` and `[style.width.px]="n"`. `[attr]="expr"` drops the attribute for `null`/`false`.
33
+ - `@if (items.length)`, not `@if (items)`: an empty array is truthy. Or `@for (x of items; track x.id) { … } @empty { … }`.
34
+ - `[flag]="false"` on a component input, not `flag="false"` (a non-empty string is truthy).
35
+ - A component tag needs a hyphen and matches `components/<path>.kick`, folders joined by `-` (`components/forms/text-field.kick` → `<forms-text-field>`). A missing or unknown input fails the check.
36
+ - `{{-- comment --}}` stays out of the output.
37
+
38
+ **Components with a script.** A top-level `<script client>` in a component is TypeScript that runs in the browser — typically a custom element that the component's markup contains. It ships once per page that renders the component, as `/_kick/c/<tag>.<hash>.js`. It can `import` npm packages and your own files (`@/…` aliases work): `kick build` bundles them into `dist/public/_kick/c/`, `kick dev` serves them through Vite. Running from source without either, a script that imports fails with "client scripts that import need kick dev or a kick build". Keep imported files browser-safe — whatever they import ships too.
39
+
40
+ **Check before claiming done**
41
+
42
+ ```bash
43
+ {{kick}} check:views # every template parsed and checked, as kick build does
44
+ {{kick}} fmt:views # format .kick files (--check in CI)
45
+ ```
46
+
47
+ Errors name the file, line and column. An unknown pipe, input or slot, a `{{ }}` inside `<script>`/`<style>` or an `on*` attribute, and an unquoted attribute value are all check errors — fix the template, not the checker.
48
+
49
+ Full guide: https://kickjs.app/guide/views. Forms and validation: the `kickjs-views-forms` skill.
@@ -0,0 +1,3 @@
1
+ {
2
+ "recommendations": ["forinda.forinda-kickjs-devtools"]
3
+ }