@forinda/kickjs-cli 6.12.2 → 6.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{agent-docs-CLu4CsQ7.mjs → agent-docs--YHAWIIm.mjs} +3 -3
  2. package/dist/{agent-docs-CLu4CsQ7.mjs.map → agent-docs--YHAWIIm.mjs.map} +1 -1
  3. package/dist/{agent-docs-CStVJrj8.mjs → agent-docs-0yI3L1Ky.mjs} +2 -2
  4. package/dist/{build-DzBNYKLj.mjs → build-BqNUj7A_.mjs} +3 -3
  5. package/dist/{build-DzBNYKLj.mjs.map → build-BqNUj7A_.mjs.map} +1 -1
  6. package/dist/{build-Db4cha4R.mjs → build-CcS6daf-.mjs} +2 -2
  7. package/dist/{builtins-DVQRavE0.mjs → builtins-C1OmkSrd.mjs} +18 -6
  8. package/dist/{builtins-Ho5elH40.mjs → builtins-q3q1QLLh.mjs} +2 -2
  9. package/dist/cli.mjs +2 -2
  10. package/dist/{config-CpfbwTOH.mjs → config-CaJIat9M.mjs} +3 -3
  11. package/dist/{config-CpfbwTOH.mjs.map → config-CaJIat9M.mjs.map} +1 -1
  12. package/dist/{config-CZQN6aLU.mjs → config-D35jG3kj.mjs} +2 -2
  13. package/dist/{doctor-BRKjTXg-.mjs → doctor-9yPpCaR7.mjs} +4 -4
  14. package/dist/{doctor-BRKjTXg-.mjs.map → doctor-9yPpCaR7.mjs.map} +1 -1
  15. package/dist/{fullstack-DrptYERV.mjs → fullstack-BDHCqNm_.mjs} +4 -4
  16. package/dist/{fullstack-DrptYERV.mjs.map → fullstack-BDHCqNm_.mjs.map} +1 -1
  17. package/dist/{fullstack-CWtFWYLl.mjs → fullstack-CvfO1yD9.mjs} +3 -3
  18. package/dist/index.mjs +2 -2
  19. package/dist/{plugin-BM0vR4Wp.mjs → plugin-BvgITdge.mjs} +2 -2
  20. package/dist/{plugin-Bl42_aUN.mjs → plugin-nMxvR1Lr.mjs} +3 -3
  21. package/dist/{plugin-Bl42_aUN.mjs.map → plugin-nMxvR1Lr.mjs.map} +1 -1
  22. package/dist/{project-K-Pg2DPp.mjs → project-BYH9LnTe.mjs} +26 -19
  23. package/dist/project-BYH9LnTe.mjs.map +1 -0
  24. package/dist/{project-Cr_EJhoL.mjs → project-dE-amvpe.mjs} +24 -17
  25. package/dist/{project-docs-CC4IryAZ.mjs → project-docs-0gAWhIiP.mjs} +89 -233
  26. package/dist/project-docs-0gAWhIiP.mjs.map +1 -0
  27. package/dist/{project-docs-NfXHhcln.mjs → project-docs-DHgCC8-a.mjs} +88 -232
  28. package/dist/{project-root-pbgtKIoC.mjs → project-root-BLGs_jD5.mjs} +2 -2
  29. package/dist/{project-root-DJr3x5pY.mjs → project-root-a9w4DpIE.mjs} +3 -3
  30. package/dist/{project-root-DJr3x5pY.mjs.map → project-root-a9w4DpIE.mjs.map} +1 -1
  31. package/dist/{prompts-XiiR969b.mjs → prompts-CxksOWrb.mjs} +2 -2
  32. package/dist/{prompts-XiiR969b.mjs.map → prompts-CxksOWrb.mjs.map} +1 -1
  33. package/dist/{rolldown-runtime-BTs2uP94.mjs → rolldown-runtime-_yCKTnUY.mjs} +1 -1
  34. package/dist/{run-plugins-CY13ekyP.mjs → run-plugins-BweCMpF_.mjs} +18 -6
  35. package/dist/run-plugins-BweCMpF_.mjs.map +1 -0
  36. package/dist/{typegen-BBSL503s.mjs → typegen-CqY0NnhZ.mjs} +5 -5
  37. package/dist/{typegen-BBSL503s.mjs.map → typegen-CqY0NnhZ.mjs.map} +1 -1
  38. package/dist/{typegen-e3DwxkVv.mjs → typegen-kJNiIRAS.mjs} +4 -4
  39. package/dist/{types-xWud6jrx.mjs → types-DZBP-FTX.mjs} +1 -1
  40. package/package.json +4 -4
  41. package/dist/project-K-Pg2DPp.mjs.map +0 -1
  42. package/dist/project-docs-CC4IryAZ.mjs.map +0 -1
  43. package/dist/run-plugins-CY13ekyP.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.12.2
2
+ * @forinda/kickjs-cli v6.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -384,203 +384,47 @@ ${t===`rest`?`\`\`\`
384
384
 
385
385
  ## Checklist: Adding a Feature
386
386
 
387
- ### New Module (Recommended)
388
-
389
- Use the CLI generator for consistency:
390
-
391
- \`\`\`bash
392
- kick g module <name> # Generate full module
393
- # or
394
- kick g scaffold <name> <fields> # Generate CRUD from fields
395
- \`\`\`
396
-
397
- Then:
398
- - [ ] Review generated files in \`src/modules/<name>/\`
399
- - [ ] Verify module is registered in \`src/modules/index.ts\`
400
- - [ ] Update DTOs in \`<name>.dto.ts\` if needed
401
- - [ ] Implement business logic in \`<name>.service.ts\`
402
- - [ ] Run \`kick dev\` to test with HMR
403
- - [ ] Write tests in \`<name>.test.ts\`
404
-
405
- ### Manual Controller
406
-
407
- If not using generators:
408
-
409
- - [ ] Create \`src/modules/<name>/<name>.controller.ts\`
410
- - [ ] Add \`@Controller()\` decorator
411
- - [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
412
- - [ ] Create module file with \`defineModule({ name, build: () => ({ routes() { return { path, controller } } }) })\` — the framework derives the Express router from the controller. Class-form (\`class XModule implements AppModule\`) is the legacy alternative; toggle via \`kick.config.ts > modules.style\`.
413
- - [ ] Register module in \`src/modules/index.ts\`. Default form is the fluent chain: \`defineModules().mount(MyModule()).mount(...)\`. \`kick g module <name>\` appends \`.mount(NewModule())\` automatically.
414
- - [ ] Test with \`kick dev\`
415
-
416
- ### Manual Service
417
-
418
- - [ ] Create \`src/modules/<name>/<name>.service.ts\`
419
- - [ ] Add \`@Service()\` decorator
420
- - [ ] Inject dependencies with \`@Autowired()\`
421
- - [ ] Inject via \`@Autowired()\` where needed
422
- - [ ] Write unit tests
423
-
424
- ### New Middleware
425
-
426
- - [ ] Create \`src/middleware/<name>.middleware.ts\`
427
- - [ ] Export middleware function (Express format)
428
- - [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
429
- - [ ] Test with sample requests
430
-
431
- ### Adding a Package
432
-
433
- Use \`kick add\` to install KickJS packages with correct peer dependencies:
434
-
435
- - [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
436
- - [ ] Follow package-specific setup in terminal output
437
- - [ ] Update \`src/index.ts\` to register adapter (if needed)
438
- - [ ] Configure environment variables in \`.env\`
439
- - [ ] Test integration with \`kick dev\`
387
+ Follow the **\`kickjs-add-module\`** skill — it has the ordered steps, the
388
+ canonical \`defineModule\` shape, and the \`import.meta.glob\` requirement that
389
+ silently breaks DI when omitted.
440
390
 
441
391
  ## Common Tasks
442
392
 
443
- ### Generate CRUD Module
444
-
445
- \`\`\`bash
446
- kick g scaffold user name:string email:string:optional age:number
447
- \`\`\`
448
-
449
- Append \`:optional\` for optional fields (shell-safe, no quoting needed).
450
- Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
451
-
452
- This creates a full CRUD module with:
453
- - Controller with GET, POST, PUT, DELETE routes
454
- - Service with business logic
455
- - Repository with data access
456
- - DTOs with Zod validation
457
-
458
- ### Add Authentication
459
-
460
- \`\`\`bash
461
- kick add auth
462
- \`\`\`
463
-
464
- Then configure in \`src/index.ts\`:
465
-
466
- \`\`\`ts
467
- import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
468
-
469
- bootstrap({
470
- modules,
471
- adapters: [
472
- AuthAdapter({
473
- strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
474
- }),
475
- ],
476
- })
477
- \`\`\`
478
-
479
- ### Add Database (Prisma)
480
-
481
- \`\`\`bash
482
- kick add prisma
483
- ${n} install prisma @prisma/client
484
- npx prisma init
485
- # Edit prisma/schema.prisma
486
- npx prisma migrate dev --name init
487
- kick g module user --repo prisma
488
- \`\`\`
489
-
490
- ### Add WebSocket Support
393
+ Each of these has a skill with the steps and the traps:
491
394
 
492
- \`\`\`bash
493
- kick add ws
494
- \`\`\`
495
-
496
- Then add adapter in \`src/index.ts\`:
497
-
498
- \`\`\`ts
499
- import { WsAdapter } from '@forinda/kickjs-ws'
500
-
501
- bootstrap({
502
- modules,
503
- adapters: [WsAdapter()],
504
- })
505
- \`\`\`
506
-
507
- Create WebSocket controller:
508
-
509
- \`\`\`bash
510
- kick g controller chat --ws
511
- \`\`\`
395
+ | Task | Skill |
396
+ | --- | --- |
397
+ | Add a feature module | \`kickjs-add-module\` |
398
+ | Add an adapter | \`kickjs-add-adapter\` |
399
+ | Add a plugin | \`kickjs-add-plugin\` |
400
+ | Add a context contributor | \`kickjs-context-contributor\` |
401
+ | Write a controller test | \`kickjs-write-controller-test\` |
402
+ | List endpoint with filters / pagination | \`kickjs-query-parsing-list-endpoint\` |
403
+ | Serve bundled assets | \`kickjs-use-asset-manager\` |
404
+ | Anything else | \`kickjs-docs-lookup\` |
512
405
 
513
406
  ## Testing Guidelines
514
407
 
515
- All tests use Vitest:
408
+ See the **\`kickjs-write-controller-test\`** skill for the canonical test — it
409
+ carries the call shape, the DI reset, and the env side-effect import, each of
410
+ which has its own failure mode.
516
411
 
517
- \`\`\`ts
518
- import { describe, it, expect, beforeEach } from 'vitest'
519
- import { Container } from '@forinda/kickjs'
520
- import { createTestApp } from '@forinda/kickjs-testing'
521
-
522
- describe('UserController', () => {
523
- it('should return users', async () => {
524
- // Container.create() — isolated DI state per test, never new Container()
525
- // and never getInstance().reset() (both leak registrations between tests).
526
- const container = Container.create()
527
- const app = await createTestApp([UserModule], { container })
528
- const res = await app.get('/users')
529
-
530
- expect(res.status).toBe(200)
531
- expect(res.body).toHaveProperty('users')
532
- })
533
- })
534
- \`\`\`
535
-
536
- Run tests:
537
- - \`${n} run test\` — run all tests once
538
- - \`${n} run test:watch\` — watch mode
539
- - Individual file: \`${n} run test src/modules/user/user.test.ts\`
412
+ Run with \`${n} run test\` (\`test:watch\` for watch mode).
540
413
 
541
414
  ## Environment Variables
542
415
 
543
- Schema is declared in \`src/config/index.ts\` (extends the base
544
- \`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
545
- with kickjs at module load. \`src/index.ts\` imports it via
546
- \`import './config'\` **before** \`bootstrap()\` so the cache is populated
547
- in time for DI. Add new keys to the schema, drop their values into
548
- \`.env\`, and they're typed everywhere.
549
-
550
- Access patterns:
416
+ The schema lives in \`src/config/index.ts\` and registers itself with kickjs **at
417
+ module load**; \`src/index.ts\` imports it (\`import './config'\`) before
418
+ \`bootstrap()\` so the cache is populated before DI resolves anything. Add a key
419
+ to the schema, put its value in \`.env\`, and it is typed everywhere.
551
420
 
552
- 1. **@Value() decorator** (recommended for known-at-construction keys):
553
- \`\`\`ts
554
- @Value('DATABASE_URL')
555
- private dbUrl!: string
556
- \`\`\`
557
-
558
- 2. **ConfigService** (recommended for dynamic / method-scoped access):
559
- \`\`\`ts
560
- @Autowired()
561
- private config!: ConfigService
562
-
563
- const port = this.config.get('PORT') // typed: number
564
- \`\`\`
565
-
566
- 3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
567
- \`\`\`ts
568
- import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
569
-
570
- const env = loadEnv(schema) // Parse + validate all vars
571
- const port = getEnv('PORT') // Single value lookup
572
- reloadEnv() // Re-read .env from disk
573
- resetEnvCache() // Full reset (for tests)
574
- \`\`\`
575
-
576
- 4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
577
- coercion and the typed \`KickEnv\` registry.
421
+ Read it with \`@Value('KEY')\` for construction-time values, or inject
422
+ \`ConfigService\` for dynamic access.
578
423
 
579
- > **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
580
- > If the schema is not registered before DI runs, \`config.get()\`
581
- > returns \`undefined\` for user keys (the base shape only) and
582
- > \`@Value()\` only works because of its raw \`process.env\` fallback —
583
- > Zod coercion + schema defaults are silently skipped.
424
+ When a key reads as \`undefined\`, use the **\`kickjs-env-wiring-check\`** skill or
425
+ run \`kick explain "ConfigService.get('KEY') returned undefined"\`. The cause
426
+ differs between app code and tests and the two look identical, which is what
427
+ makes it slow to spot.
584
428
 
585
429
  ## Standalone Utilities (No DI Required)
586
430
 
@@ -680,57 +524,34 @@ Full guide: <https://kickjs.app/guide/context-decorators>.
680
524
 
681
525
  ## Common Pitfalls
682
526
 
683
- 1. **Forgot to register module** Add to \`src/modules/index.ts\` exports array
684
- 2. **DI not working** Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
685
- 3. **Tests failing randomly** — Sharing the global container between tests. Default to \`Container.create()\` per test (or per \`beforeEach\`) instead of \`new Container()\` / \`getInstance().reset()\`
686
- 4. **Routes not found** Check controller path and module registration
687
- 5. **HMR not working** Two checks: (a) \`vite.config.ts\` has \`hmr: true\`; (b) module file is named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and lives under \`src/modules/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed module file (e.g., \`projects.ts\`) silently degrades to a full restart on every save.
688
- 6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
689
- 7. **\`config.get('YOUR_KEY')\` returns \`undefined\`** — \`src/index.ts\` is missing \`import './config'\`. That side-effect import registers the env schema with kickjs (\`loadEnv(envSchema)\` runs at module load). Without it, \`ConfigService\` falls back to the base schema (\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` only) and every user-defined key reads as \`undefined\`. \`@Value()\` may *appear* to work because of a raw \`process.env\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \`src/index.ts\` and \`src/config/index.ts\` first.
690
- 8. **Used \`@Middleware()\` to compute a value for \`ctx\`** — prefer \`defineContextDecorator()\` (see Context Decorators above). It's typed via \`ContextMeta\`, supports \`dependsOn\` for ordering, and validates the pipeline at boot. \`@Middleware()\` is for response short-circuiting, stream mutation, and pre-route-matching work.
691
- 9. **Context contributor's \`dependsOn\` key not produced anywhere** — boot throws \`MissingContributorError\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).
692
- 10. **\`bootstrap()\` not exported** — \`src/index.ts\` calls \`await bootstrap({ ... })\` but discards the return value (no \`export const app = ...\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \`createTestApp\`/\`@forinda/kickjs-testing\` consumers can't import the handle either. Always: \`export const app = await bootstrap({ ... })\`.
693
- 11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \`kick g agents -f\` (or \`kick g agent-docs -f\`) to regenerate from the latest CLI templates after \`kick add\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \`AGENTS.local.md\`.
527
+ See the **\`kickjs-deny-list\`** skillthe maintained list of things that
528
+ compile, run, and are still wrong.
529
+
530
+ For a specific failure, \`kick explain "<error message>"\` beats reading either:
531
+ it matches the message against known causes and prints the fix.
694
532
 
695
533
  ## CLI Commands Reference
696
534
 
697
- | Command | Description |
698
- |---------|-------------|
699
- | \`kick dev\` | Dev server with HMR |
700
- | \`kick dev:debug\` | Dev server with debugger |
701
- | \`kick build\` | Production build |
702
- | \`kick start\` | Run production build |
703
- | \`kick g module <names...>\` | Generate one or more modules |
704
- | \`kick g scaffold <name> <fields>\` | Generate CRUD |
705
- | \`kick g controller <name>\` | Generate controller |
706
- | \`kick g service <name>\` | Generate service |
707
- | \`kick g middleware <name>\` | Generate middleware |
708
- | \`kick add <package>\` | Add KickJS package |
709
- | \`kick add upload\` | Install the multipart upload driver for this project's runtime |
710
- | \`kick add --list\` | List available packages |
711
- | \`kick doctor\` | Pre-flight checks — runtime engine peers, upload driver, env wiring |
712
- | \`kick rm module <names...>\` | Remove one or more modules |
713
-
714
- > **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`), \`-r\` (or \`--repo\`), and \`--runtime express|fastify|h3\` to bypass interactive prompts:
715
- > \`\`\`bash
716
- > kick new my-api -t ddd -r prisma --runtime fastify --pm ${n} --no-git --no-install -f
717
- > \`\`\`
535
+ See the **\`kickjs-cli-commands-cheatsheet\`** skill for the full table, the
536
+ shell-safe field syntax, and the non-obvious flags. \`kick --help\` and
537
+ \`kick <cmd> --help\` are authoritative for the installed version.
718
538
 
719
539
  ## Learn More
720
540
 
721
- - [KickJS Docs](https://kickjs.app/)
722
- - [CLI Reference](https://kickjs.app/api/cli.html)
723
- - [Decorators Guide](https://kickjs.app/guide/decorators.html)
724
- - [DI System](https://kickjs.app/guide/dependency-injection.html)
725
- - [Testing](https://kickjs.app/api/testing.html)
726
- `}function S(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".
541
+ Use the **\`kickjs-docs-lookup\`** skill — it maps questions to the right guide
542
+ page and lists the local tools (\`kick explain\`, \`kick doctor\`, \`kick inspect\`,
543
+ \`.kickjs/types/\`) that usually answer faster than a search.
544
+
545
+ Start at <https://kickjs.app/>.
546
+
547
+ `}function S(e){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".
727
548
 
728
549
  **Steps**:
729
550
  1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
730
551
  2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for Vite HMR).
731
552
  3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
732
553
  4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
733
- 5. Run \`${n} run typecheck\` and \`${n} run test\` before claiming done.
554
+ 5. Run \`${e} run typecheck\` and \`${e} run test\` before claiming done.
734
555
 
735
556
  **Canonical module shape** — \`defineModule\` factory, never \`class implements AppModule\`:
736
557
 
@@ -770,7 +591,7 @@ routes() {
770
591
  - \`@Controller('/path')\` with a path argument combined with module \`routes().path\` — duplicates the prefix. The decorator path is OpenAPI metadata only.
771
592
  - \`TodosModule\` in \`bootstrap({ modules: [TodosModule] })\` instead of \`TodosModule()\` — passing the factory instead of the invoked instance.
772
593
  - \`routes()\` returning \`router: …\` when a \`controller:\` would do — controller form is required for OpenAPI/Swagger introspection.
773
- - 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 })\nasync create(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route.\n // Returning (vs ctx.created) lets typegen infer the response type.\n return reply(201, 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**:
594
+ - 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 request from 'supertest'\nimport { Container } from '@forinda/kickjs'\nimport { createTestApp } from '@forinda/kickjs-testing'\n// Side-effect import — registers the env schema, exactly as src/index.ts does.\n// `createTestApp` never loads the entry file, so without this\n// `ConfigService.get('YOUR_KEY')` is undefined under test while `@Value()`\n// still appears to work via its process.env fallback — the two disagree only\n// in tests.\nimport '@/config'\n\ndescribe('UserController', () => {\n beforeEach(() => Container.reset()) // isolate DI between tests\n\n it('returns users', async () => {\n // `createTestApp` takes an OPTIONS OBJECT and returns\n // `{ app, expressApp, container }`. Passing a bare array throws\n // \"this.options.modules is not iterable\"; the result has no `.get()`.\n const { expressApp } = await createTestApp({\n modules: [UserModule],\n })\n const res = await request(expressApp).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 })\nasync create(ctx: Ctx<KickRoutes.TodoController['create']>) {\n // ctx.body is typed from createTodoSchema; ctx.params from the route.\n // Returning (vs ctx.created) lets typegen infer the response type.\n return reply(201, 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:"**Fastest path**: `kick explain \"ConfigService.get('MY_KEY') returned undefined\"` —\npipe a failing run straight in if you prefer (`pnpm test 2>&1 | kick explain`). It\ndistinguishes the entry-file cause from the test-file one, which is the step most\npeople lose time on. The manual checks below are the same reasoning.\n\n**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 run the loader as a top-level side effect — not just declare the schema. This is what `kick new` generates:\n ```ts\n import { loadEnvFromSchema } from '@forinda/kickjs/config'\n import { fromZod } from '@forinda/kickjs-schema/zod'\n const envSchema = fromZod(z.object({ DATABASE_URL: z.string().url() }))\n export const env = loadEnvFromSchema(envSchema)\n ```\n (`loadEnv(zodSchema)` from `@forinda/kickjs` is the equivalent for a bare Zod\n object. Either is fine — what matters is that it RUNS at module load.)\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\n5. **In a test?** `createTestApp` never loads `src/index.ts`, so the entry's\n `import './config'` never runs no matter how correct it is. The test file\n must import it itself:\n ```ts\n import '@/config'\n ```\n Symptom is identical to the missing-entry-import case, and step 1 will look\n fine, which is what makes it slow to spot.\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`; add `import '@/config'` to any test that reads config; re-run `kick typegen`."},{slug:`bootstrap-export`,frontmatterName:`kickjs-bootstrap-export`,description:`Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.`,body:"**Check** `src/index.ts`'s last line:\n\n```ts\n// CORRECT — Vite plugin + createTestApp import the named `app` symbol\nexport const app = await bootstrap({ ... })\n\n// WRONG — HMR degrades to full restart, createTestApp loses the handle\nawait bootstrap({ ... })\n```\n\nThe Vite plugin imports the named `app` symbol via `virtual:kickjs/app`; testing helpers do too. Without the export, both fall back to slower paths (full restart on save, mock handle in tests) **without warning**.\n\n**Red flags**:\n- A bare `await bootstrap(...)` with no `export` — fix by adding `export const app =`.\n- Re-assigning `app` later in the file (`app = somethingElse`) — Vite imports by reference at module-load time; reassignments don't propagate.\n- Multiple files calling `bootstrap()` — only the entry should. Tests use `createTestApp` instead."},{slug:`thin-entry-file`,frontmatterName:`kickjs-thin-entry-file`,description:`Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.`,body:`**Refactor target**:
774
595
 
775
596
  \`\`\`ts
776
597
  // src/modules/index.ts — fluent chain (default for \`modules.style: 'define'\`)
@@ -780,6 +601,8 @@ export const modules = defineModules().mount(HelloModule()).mount(UsersModule())
780
601
 
781
602
  // src/middleware/index.ts — global middleware uses RAW EXPRESS signature
782
603
  // (req, res, next), NOT (ctx, next)
604
+ // \`express.json()\` is auto-skipped on Fastify and h3, which parse bodies
605
+ // natively — harmless to list, but don't reach for it as the body parser there.
783
606
  export const middleware = [requestId(), express.json(), helmet(), cors(), traceContext()]
784
607
 
785
608
  // src/plugins/index.ts
@@ -811,7 +634,7 @@ plugins: [
811
634
  **Red flags**:
812
635
  - Any \`new SomeAdapter()\` / \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
813
636
  - 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".
814
- - \`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 return ctx.get('project')\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying 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.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- `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**:
637
+ - \`bootstrap({ register: ... })\` — that option doesn't exist. Use an inline plugin.`},{slug:`context-contributor`,frontmatterName:`kickjs-context-contributor`,description:`Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).`,body:"**Pattern** (HTTP — most common):\n\n```ts\nimport { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'\n\n// Augment ContextMeta — required for ctx.get('tenant') to be typed\ndeclare module '@forinda/kickjs' {\n interface ContextMeta {\n tenant: { id: string; name: string }\n }\n}\n\n// The `declare module` block above is all you need. `defineAugmentation` is\n// DEPRECATED — it only added a typegen catalogue entry, never any types.\n\nconst LoadTenant = defineHttpContextDecorator({\n key: 'tenant',\n deps: { repo: TENANT_REPO }, // typed DI\n resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),\n})\n\nconst LoadProject = defineHttpContextDecorator({\n key: 'project',\n dependsOn: ['tenant'], // typo'd key = tsc error\n resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),\n})\n\n@LoadTenant\n@LoadProject\n@Get('/projects/:id')\ngetProject(ctx: RequestContext) {\n return ctx.get('project')\n}\n```\n\nUse `defineContextDecorator` (no Http prefix) only when the contributor must run across HTTP, WebSocket, queue, and cron transports — `Ctx` defaults to the smaller `ExecutionContext` surface (`get` / `set` / `requestId` only, no `req`).\n\n**Five precedence levels** (high → low):\n**method > class > module > adapter > global**\n\nSame-key collisions WITHIN a precedence level throw `DuplicateContributorError`. Across levels, the higher precedence silently overrides — a feature, not a bug, but debug it by giving resolvers distinguishable return values.\n\n**Boot-time validation**:\n- Cycles in `dependsOn` → `ContributorCycleError`.\n- `dependsOn` referring to an unknown key → `MissingContributorError`.\n- Both errors fail boot, not first request.\n\n**Critical rules — all stem from the same shared-via-ALS instance model**:\n- Every per-request stage (middleware → contributors → handler) gets its OWN `RequestContext` instance, but they all read/write the SAME `AsyncLocalStorage`-backed bag.\n- **`resolve` and `onError` must RETURN the value** — the runner writes it via `ctx.set(key, value)`. Direct property assignment (`ctx.tenant = …`) sticks to one instance only and the handler instance never sees it.\n- `ctx.set('tenant', x)` then `ctx.get('tenant')` works across instances. `ctx.req.headers[...]` works (the underlying node request is shared). Note it is a node `IncomingMessage` on Fastify and h3, not an `express.Request`.\n- Services with no `ctx` reference: `getRequestValue('tenant')` returns `MetaValue<'tenant'> | undefined` (typed via the augmented `ContextMeta`). For `requestId` use `getRequestStore()`.\n- **No `setRequestValue` — writes flow through `ctx.set` or a contributor's return value.** Avoids \"spooky action at a distance\" where any service can pollute the per-request bag.\n\n**Error matrix**:\n- `optional: true` — `resolve` throws → key left unset; downstream sees `ctx.get(key) === undefined`.\n- `optional: false` (default) + `onError` — return a fallback value to write; return `undefined` to skip; throw to forward to the request error handler.\n- `optional: false` + no `onError` — throw propagates straight to the request error handler.\n\n**Don't use this for**: response short-circuit, stream mutation, or pre-route-matching work — keep `@Middleware()` for those.\n\n**Red flags**:\n- `ctx.get('key')!` — the non-null assertion compiles even when the producing decorator isn't on the route. Use `ctx.require('key')`.\n- `contributors: [LoadX]` at a module / adapter / bootstrap site — those take registrations: `LoadX.registration` or `LoadX.with({ ... }).registration`.\n- A `paramDefaults` value that every call site overrides (`action: 'settings:read'`) — drop it and let the compiler require the field at each site.\n- `defineContextDecorator<'k', Deps, Params>(spec)` positional form for a parameterised contributor — use `.withParams<Params>()(spec)` or `deps` inference is lost.\n- `ctx.tenant = x` instead of returning the value from `resolve` — sticks to one instance only.\n- Reaching for `defineAugmentation` — deprecated, and it never affected types. The `declare module` block alone is what makes `ctx.get('tenant')` typed.\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**:
815
638
  - \`kick new <name>\` — start a new project (prompts for template / repo / pm).
816
639
  - \`kick dev\` — local dev server with Vite HMR.
817
640
  - \`kick build\` — production bundle via Vite.
@@ -827,13 +650,13 @@ plugins: [
827
650
 
828
651
  \`\`\`bash
829
652
  kick new my-api --yes # CI-safe: minimal + inmemory, no prompts
830
- kick new my-api -t ddd --pm ${n} --no-git --install # Fully scriptable DDD scaffold
653
+ kick new my-api -t ddd --pm ${e} --no-git --install # Fully scriptable DDD scaffold
831
654
  kick new . --yes --force # Scaffold into current dir, clear existing files
832
655
  kick g scaffold Post title:string body:text:optional # Shell-safe optional field syntax
833
656
  kick g agents -f --only skills # Refresh just the skills after upgrade
834
657
  kick add queue:bullmq # Package + peer deps (bullmq + ioredis) in one shot
835
658
  kick inspect --port 4000 --json # Machine-readable route/adapter dump
836
- kick g config --force --repo drizzle # Drop a kick.config.ts into a legacy project
659
+ kick g config --force --repo postgres # Drop a kick.config.ts into a legacy project
837
660
  \`\`\`
838
661
 
839
662
  **Lesser-known, high-value**:
@@ -850,7 +673,40 @@ kick g config --force --repo drizzle # Drop a kick.config.ts i
850
673
  - Writing \`"name:type?"\` for optional scaffold fields — \`?\` is a shell glob in bash/zsh; use \`name:type:optional\`.
851
674
  - Running \`kick new <name> --yes\` in a non-empty directory expecting it to wipe — \`--yes\` aborts without \`--force\`; pair them when destruction is intended.
852
675
  - Skipping \`kick g config\` on a legacy project then wondering why generators ignore \`modules.dir\` / \`modules.repo\`.
853
- - 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:`---
676
+ - Editing \`kick.config.ts\` with deprecated top-level \`modulesDir\` / \`defaultRepo\` / \`schemaDir\` / \`pluralize\` instead of the nested \`modules\` block.`},{slug:`docs-lookup`,frontmatterName:`kickjs-docs-lookup`,description:`Use FIRST when unsure about any KickJS API, option, or behaviour before guessing from memory or inferring from surrounding code.`,body:`These skills are deliberately short — they cover the traps, not the whole API
677
+ surface. When the answer is not in one of them, read the docs rather than
678
+ inferring it from nearby code: a wrong guess about a framework API compiles
679
+ fine and fails at runtime.
680
+
681
+ **Where to look**
682
+
683
+ | Question | Page |
684
+ | --- | --- |
685
+ | Anything — start here | https://kickjs.app/ |
686
+ | Controllers, routing, \`ctx\` helpers | https://kickjs.app/guide/controllers |
687
+ | DI, tokens, scopes | https://kickjs.app/guide/dependency-injection |
688
+ | Modules and mounting | https://kickjs.app/guide/modules |
689
+ | Adapters, plugins, lifecycle hooks | https://kickjs.app/guide/adapters |
690
+ | Context Contributors | https://kickjs.app/guide/context-decorators |
691
+ | Env, \`ConfigService\`, \`@Value\` | https://kickjs.app/guide/configuration |
692
+ | Middleware and guards | https://kickjs.app/guide/middleware |
693
+ | Testing (\`createTestApp\`) | https://kickjs.app/guide/testing |
694
+ | Typegen and generated types | https://kickjs.app/guide/typegen |
695
+ | HMR and the dev server | https://kickjs.app/guide/hmr |
696
+
697
+ **Local, and usually faster**
698
+
699
+ - \`kick explain "<error message>"\` — matches known failures and gives the fix.
700
+ Pipe a failing run in: \`${e} test 2>&1 | kick explain\`.
701
+ - \`kick doctor\` — checks this project's wiring.
702
+ - \`kick inspect\` — the live route / adapter table.
703
+ - \`.kickjs/types/\` — generated types are ground truth for what exists.
704
+ - \`node_modules/@forinda/kickjs/dist/*.d.mts\` — the real signature when a doc
705
+ page and the code disagree.
706
+
707
+ **Rule**: if you would be guessing, look it up. If a doc page contradicts the
708
+ installed \`.d.mts\`, trust the \`.d.mts\` and say so — the docs may be behind the
709
+ version this project has.`},{slug:`refresh-agent-docs`,frontmatterName:`kickjs-refresh-agent-docs`,description:`Use after a KickJS version bump to sync the .agents/ docs with the latest CLI templates.`,body:"**Steps**:\n1. `kick g agents -f --only both` — overwrites `CLAUDE.md` (root) and `.agents/AGENTS.md`.\n2. `kick g agents -f --only skills` — refreshes every `.agents/skills/<slug>/SKILL.md`.\n3. `kick g agents -f --only gemini` / `--only copilot` — refresh the per-agent files when needed.\n4. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate `AGENTS.local.md` or per-skill `SKILL.local.md` alongside.\n5. Commit as `docs(agents): sync from CLI vX.Y`.\n\n**`.agents/` layout** (post-restructure):\n\n```\nCLAUDE.md # at root — Claude Code auto-loads from here\n.agents/\n├── AGENTS.md # canonical multi-agent reference\n├── GEMINI.md # Gemini-specific notes\n├── COPILOT.md # Copilot CLI notes\n└── skills/\n ├── add-module/SKILL.md\n ├── add-adapter/SKILL.md\n └── … # one SKILL.md per skill, frontmatter-namespaced\n```\n\nCustomisation goes in `.local.md` siblings (`AGENTS.local.md`, `skills/<slug>/SKILL.local.md`) — those are never overwritten."},{slug:`deny-list`,frontmatterName:`kickjs-deny-list`,description:`Patterns to refuse outright when the user asks for them — they break v4 invariants.`,body:"**Module / adapter / plugin shape**:\n- `class implements AppAdapter` → use `defineAdapter()`.\n- `class implements KickPlugin` / function returning `KickPlugin` → use `definePlugin()`.\n- `class implements AppModule` for new code → use `defineModule()`.\n- `bootstrap({ adapters: [MyAdapter] })` (factory) → `MyAdapter()` (instance, with parens).\n- `@Controller('/path')` with a path argument → 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- Omitting the `declare module '@forinda/kickjs'` block — without it `ctx.get('tenant')` is `unknown`. (`defineAugmentation` is deprecated and was never a substitute for it.)\n- `getRequestValue<string>('traceId')` — generic is the **key** type, not value type.\n\n**Env / config**:\n- `@Value('NEW_KEY')` without the key in the Zod schema — silent fallback to raw `process.env`, no coercion.\n- `resetEnvCache()` outside tests — drops the registered schema.\n\n**List endpoints**:\n- Reading `req.query.status` directly — bypasses the allow-list. Use `ctx.qs({ filterable })`.\n- Returning a bare array from a list endpoint — breaks the `PaginatedResponse<T>` contract. Use `ctx.paginate()`.\n\n**Assets**:\n- Hand-rolled `__dirname` arithmetic for template paths — use `assets.<ns>.<key>()` and add the namespace to `kick.config.ts assetMap`."}]}function C(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 S(n).map(e=>({slug:e.slug,content:`---
854
710
  name: ${e.frontmatterName}
855
711
  description: ${e.description}
856
712
  ---
@@ -858,7 +714,7 @@ description: ${e.description}
858
714
  ${r}
859
715
 
860
716
  ${e.body}
861
- `}))}function C(e,t,n){return`# GEMINI.md — ${e}
717
+ `}))}function w(e,t,n){return`# GEMINI.md — ${e}
862
718
 
863
719
  **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
864
720
  reference for this project — every convention, structure, decorator
@@ -892,7 +748,7 @@ without us copy-pasting.
892
748
  \`kick g agents --only gemini -f\` regenerates this file from the
893
749
  CLI template. Hand-edited content is overwritten — keep customisation
894
750
  in \`.agents/GEMINI.local.md\`.
895
- `}function w(e,t,n){return`# COPILOT.md — ${e}
751
+ `}function T(e,t,n){return`# COPILOT.md — ${e}
896
752
 
897
753
  **Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
898
754
  reference for this project — every convention, structure, decorator
@@ -925,4 +781,4 @@ Codex / Cursor / Gemini / Claude Code without copy-pasting.
925
781
  \`kick g agents --only copilot -f\` regenerates this file from the
926
782
  CLI template. Hand-edited content is overwritten — keep customisation
927
783
  in \`.agents/COPILOT.local.md\`.
928
- `}export{S as a,u as c,C as i,f as l,b as n,y as o,w as r,v as s,x as t};
784
+ `}export{C as a,u as c,w as i,f as l,b as n,y as o,T as r,v as s,x as t};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.12.2
2
+ * @forinda/kickjs-cli v6.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as e}from"./rolldown-runtime-BTs2uP94.mjs";import{existsSync as t}from"node:fs";import{dirname as n,parse as r,resolve as i}from"node:path";var a=e({findProjectRoot:()=>s});const o=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function s(e=process.cwd()){let a=i(e),{root:s}=r(a),c=null,l=a;for(;;){for(let e of o)if(t(i(l,e)))return l;if(c===null&&t(i(l,`package.json`))&&(c=l),l===s)break;let e=n(l);if(e===l)break;l=e}return c??a}export{a as n,s as t};
11
+ import{t as e}from"./rolldown-runtime-_yCKTnUY.mjs";import{existsSync as t}from"node:fs";import{dirname as n,parse as r,resolve as i}from"node:path";var a=e({findProjectRoot:()=>s});const o=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function s(e=process.cwd()){let a=i(e),{root:s}=r(a),c=null,l=a;for(;;){for(let e of o)if(t(i(l,e)))return l;if(c===null&&t(i(l,`package.json`))&&(c=l),l===s)break;let e=n(l);if(e===l)break;l=e}return c??a}export{a as n,s as t};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.12.2
2
+ * @forinda/kickjs-cli v6.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as e}from"./rolldown-runtime-BTs2uP94.mjs";import{dirname as t,parse as n,resolve as r}from"node:path";import{existsSync as i}from"node:fs";var a=e({findProjectRoot:()=>s});const o=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function s(e=process.cwd()){let a=r(e),{root:s}=n(a),c=null,l=a;for(;;){for(let e of o)if(i(r(l,e)))return l;if(c===null&&i(r(l,`package.json`))&&(c=l),l===s)break;let e=t(l);if(e===l)break;l=e}return c??a}export{a as n,s as t};
12
- //# sourceMappingURL=project-root-DJr3x5pY.mjs.map
11
+ import{t as e}from"./rolldown-runtime-_yCKTnUY.mjs";import{dirname as t,parse as n,resolve as r}from"node:path";import{existsSync as i}from"node:fs";var a=e({findProjectRoot:()=>s});const o=[`kick.config.ts`,`kick.config.js`,`kick.config.mjs`,`kick.config.json`];function s(e=process.cwd()){let a=r(e),{root:s}=n(a),c=null,l=a;for(;;){for(let e of o)if(i(r(l,e)))return l;if(c===null&&i(r(l,`package.json`))&&(c=l),l===s)break;let e=t(l);if(e===l)break;l=e}return c??a}export{a as n,s as t};
12
+ //# sourceMappingURL=project-root-a9w4DpIE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"project-root-DJr3x5pY.mjs","names":[],"sources":["../src/utils/project-root.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { dirname, parse, resolve } from 'node:path'\n\nconst CONFIG_FILENAMES = ['kick.config.ts', 'kick.config.js', 'kick.config.mjs', 'kick.config.json']\n\n/**\n * Walk up from `startDir` looking for the project root. A directory\n * counts as the root when it contains any of:\n * - `kick.config.{ts,js,mjs,json}` (strongest signal)\n * - `package.json` (fallback when no config file exists yet)\n *\n * Returns the absolute path of the first matching directory, or\n * `startDir` itself when nothing was found (no surprises — callers\n * that didn't find a config still get a reasonable cwd).\n *\n * `kick.config.*` wins over `package.json` when both appear at\n * different levels, so adopters running `kick typegen` from `src/`\n * land on the project root that owns the config, not on the nearest\n * workspace package boundary in a monorepo.\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string {\n const start = resolve(startDir)\n const { root: fsRoot } = parse(start)\n\n let firstPackageJson: string | null = null\n let cursor = start\n while (true) {\n for (const name of CONFIG_FILENAMES) {\n if (existsSync(resolve(cursor, name))) return cursor\n }\n if (firstPackageJson === null && existsSync(resolve(cursor, 'package.json'))) {\n firstPackageJson = cursor\n }\n if (cursor === fsRoot) break\n const parent = dirname(cursor)\n if (parent === cursor) break\n cursor = parent\n }\n\n return firstPackageJson ?? start\n}\n"],"mappings":";;;;;;;;;;sLAGA,MAAM,EAAmB,CAAC,iBAAkB,iBAAkB,kBAAmB,kBAAkB,EAiBnG,SAAgB,EAAgB,EAAmB,QAAQ,IAAI,EAAW,CACxE,IAAM,EAAQ,EAAQ,CAAQ,EACxB,CAAE,KAAM,GAAW,EAAM,CAAK,EAEhC,EAAkC,KAClC,EAAS,EACb,OAAa,CACX,IAAK,IAAM,KAAQ,EACjB,GAAI,EAAW,EAAQ,EAAQ,CAAI,CAAC,EAAG,OAAO,EAKhD,GAHI,IAAqB,MAAQ,EAAW,EAAQ,EAAQ,cAAc,CAAC,IACzE,EAAmB,GAEjB,IAAW,EAAQ,MACvB,IAAM,EAAS,EAAQ,CAAM,EAC7B,GAAI,IAAW,EAAQ,MACvB,EAAS,CACX,CAEA,OAAO,GAAoB,CAC7B"}
1
+ {"version":3,"file":"project-root-a9w4DpIE.mjs","names":[],"sources":["../src/utils/project-root.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { dirname, parse, resolve } from 'node:path'\n\nconst CONFIG_FILENAMES = ['kick.config.ts', 'kick.config.js', 'kick.config.mjs', 'kick.config.json']\n\n/**\n * Walk up from `startDir` looking for the project root. A directory\n * counts as the root when it contains any of:\n * - `kick.config.{ts,js,mjs,json}` (strongest signal)\n * - `package.json` (fallback when no config file exists yet)\n *\n * Returns the absolute path of the first matching directory, or\n * `startDir` itself when nothing was found (no surprises — callers\n * that didn't find a config still get a reasonable cwd).\n *\n * `kick.config.*` wins over `package.json` when both appear at\n * different levels, so adopters running `kick typegen` from `src/`\n * land on the project root that owns the config, not on the nearest\n * workspace package boundary in a monorepo.\n */\nexport function findProjectRoot(startDir: string = process.cwd()): string {\n const start = resolve(startDir)\n const { root: fsRoot } = parse(start)\n\n let firstPackageJson: string | null = null\n let cursor = start\n while (true) {\n for (const name of CONFIG_FILENAMES) {\n if (existsSync(resolve(cursor, name))) return cursor\n }\n if (firstPackageJson === null && existsSync(resolve(cursor, 'package.json'))) {\n firstPackageJson = cursor\n }\n if (cursor === fsRoot) break\n const parent = dirname(cursor)\n if (parent === cursor) break\n cursor = parent\n }\n\n return firstPackageJson ?? start\n}\n"],"mappings":";;;;;;;;;;sLAGA,MAAM,EAAmB,CAAC,iBAAkB,iBAAkB,kBAAmB,kBAAkB,EAiBnG,SAAgB,EAAgB,EAAmB,QAAQ,IAAI,EAAW,CACxE,IAAM,EAAQ,EAAQ,CAAQ,EACxB,CAAE,KAAM,GAAW,EAAM,CAAK,EAEhC,EAAkC,KAClC,EAAS,EACb,OAAa,CACX,IAAK,IAAM,KAAQ,EACjB,GAAI,EAAW,EAAQ,EAAQ,CAAI,CAAC,EAAG,OAAO,EAKhD,GAHI,IAAqB,MAAQ,EAAW,EAAQ,EAAQ,cAAc,CAAC,IACzE,EAAmB,GAEjB,IAAW,EAAQ,MACvB,IAAM,EAAS,EAAQ,CAAM,EAC7B,GAAI,IAAW,EAAQ,MACvB,EAAS,CACX,CAEA,OAAO,GAAoB,CAC7B"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-cli v6.12.2
2
+ * @forinda/kickjs-cli v6.13.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,4 +9,4 @@
9
9
  * @license MIT
10
10
  */
11
11
  import*as e from"@clack/prompts";import t from"picocolors";const n={GET:t.green,POST:t.cyan,PUT:t.yellow,PATCH:t.magenta,DELETE:t.red};function r(e){return(n[e]??t.dim)(e.padEnd(7))}function i(e){let n=`[${e}]`.padEnd(10);switch(e){case`CRITICAL`:return t.red(n);case`WARNING`:return t.yellow(n);case`INFO`:return t.blue(t.dim(n));default:return n}}t.green(`✓`),t.red(`✖`),t.yellow(`⚠`),t.blue(`ℹ`);function a(n){e.intro(t.bgCyan(t.black(` ${n} `)))}function o(t){e.outro(t)}function s(t){e.isCancel(t)&&(e.cancel(`Operation cancelled.`),process.exit(0))}async function c(t){let n=await e.text(t);return s(n),n}async function l(t){let n=await e.select(t);return s(n),n}async function u(t){let n=await e.multiselect(t);return s(n),n}async function d(t){let n=await e.confirm(t);return s(n),n}function f(){return e.spinner()}const p=e.log;export{o as a,c,i as d,u as i,r as l,a as n,l as o,p as r,f as s,d as t,t as u};
12
- //# sourceMappingURL=prompts-XiiR969b.mjs.map
12
+ //# sourceMappingURL=prompts-CxksOWrb.mjs.map