@forinda/kickjs 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,347 +1,566 @@
1
- # Kick
1
+ # KickJS
2
2
 
3
- Opinionated Express + TypeScript framework starter that feels like Spring Boot: decorator-driven controllers, configuration-first bootstrap, and fully instrumented telemetry ready for custom devtools.
3
+ 🚀 A modern, decorator-driven TypeScript framework built on Express with dependency injection, reactive state management, and enterprise-ready features.
4
4
 
5
- ## Highlights
5
+ ## ✨ Features
6
6
 
7
- - Spring Boot-style controllers via `@Controller`, `@Get`, etc., auto-registered at decoration time
8
- - Nuxt-style, file-system driven controller discovery powered by verb-specific base controllers (`src/domains/app/controllers/users.get.controller.ts` ➜ `GET /users`)
9
- - Batteries-included `kick` CLI for bootstrapping projects, generating controllers, and wiring custom commands
10
- - Domain-first scaffolding with configurable folder layout for controllers, services, and domain logic
11
- - Schema-aware route decorators (Zod/Joi) with duplicate-route protection hashed at bootstrap
12
- - Built-in `BaseController` helper with structured responses, request logging, and `fail()` AppError helpers
13
- - `configureApp` and per-call `config` options for prefixes, health endpoints, logging levels, and telemetry limits
14
- - Request telemetry tracked behind the scenes and exposed via `AppDiagnostics`
15
- - Dependency injection utilities (`@Inject`, `@Injectable`, …) that hide raw Inversify decorators
16
- - `tsup` build pipeline producing CommonJS bundles + type declarations
17
- - GitHub Actions workflow for CI and optional npm publishing
7
+ - **Decorator-Driven Architecture**: Spring Boot-style controllers with `@KickController`, `@KickGet`, `@KickPost`, etc.
8
+ - **Dependency Injection**: Powered by Inversify with automatic binding and container management
9
+ - **Reactive State Management**: Built-in EventEmitter-based state with observable properties
10
+ - **Middleware System**: Priority-based middleware with both global and DI-managed middlewares
11
+ - **Request Context Injection**: Automatic injection of request context with metadata
12
+ - **Route Prefixing**: Flexible API prefixing for better organization
13
+ - **Module System**: Organize your application into reusable, self-contained modules
14
+ - **Auto-Binding**: Automatic method binding with `@AutoBind` decorator
15
+ - **Type Safety**: Full TypeScript support with comprehensive type definitions
18
16
 
19
- ## Install
17
+ ## 📦 Installation
20
18
 
21
19
  ```bash
22
20
  npm install @forinda/kickjs
21
+ # or
22
+ pnpm add @forinda/kickjs
23
+ # or
24
+ yarn add @forinda/kickjs
23
25
  ```
24
26
 
25
- ## Creating your first service
26
-
27
- ```ts
28
- // app.ts
29
- import "reflect-metadata";
30
- import type { Request, Response } from "express";
31
- import {
32
- BaseController,
33
- Controller,
34
- Get,
35
- bootstrap,
36
- configureApp,
37
- } from "@forinda/kickjs";
38
-
39
- configureApp({ prefix: "/api/v1" });
27
+ ## 🏗️ Creating Your First App
40
28
 
41
- @Controller("/hello")
42
- class HelloController extends BaseController {
43
- protected controllerId(): string {
44
- return "HelloController";
45
- }
29
+ ### Basic Setup
46
30
 
47
- @Get({
48
- path: "/",
49
- middlewares: [],
50
- validate: {},
51
- })
52
- handle(req: Request, res: Response) {
53
- const name = typeof req.query.name === "string" ? req.query.name : "World";
54
- this.mergeRequestMetadata(res, { greeted: name });
55
- return this.ok(res, { message: `Hello ${name}` });
56
- }
57
- }
31
+ ```typescript
32
+ // src/index.ts
33
+ import express from "express";
34
+ import { createKickApp, KickController, KickGet, KickRequestContext } from "@forinda/kickjs";
35
+ import { AppModule } from "./app.module";
58
36
 
59
- async function main() {
60
- const port = Number(process.env.PORT ?? 3000);
61
- await bootstrap({ port });
62
- console.log(`Server started on http://localhost:${port}`);
63
- }
37
+ const app = express();
38
+ app.use(express.json());
64
39
 
65
- main().catch((error) => {
66
- console.error("Failed to bootstrap application", error);
67
- process.exitCode = 1;
40
+ const server = createKickApp({
41
+ name: "MyApp",
42
+ prefix: "/api/v1", // Optional: prefix all routes
43
+ app,
44
+ modules: [AppModule]
68
45
  });
69
46
 
47
+ server.listen(3000, () => {
48
+ console.log("🚀 Server running on http://localhost:3000");
49
+ console.log("📊 App Stats:", server.getStats());
50
+ });
70
51
  ```
71
52
 
72
- `bootstrap` wires Express, the Inversify container, and the request tracker. Controllers extending `BaseController` get ergonomic helpers for responses, structured logging, request metadata annotations, and a `fail()` helper for consistent error payloads. Route decorators accept Zod/Joi schemas for request validation without additional middleware.
73
-
74
- ## Public API surface
75
-
76
- ```ts
77
- import {
78
- Controller,
79
- Get,
80
- Post,
81
- Put,
82
- Patch,
83
- Delete,
84
- HttpVerbController,
85
- GetController,
86
- PostController,
87
- PutController,
88
- PatchController,
89
- DeleteController,
90
- Inject,
91
- Injectable,
92
- Optional,
93
- MultiInject,
94
- Named,
95
- Tagged,
96
- Unmanaged,
97
- BaseController,
98
- discoverControllersFromFilesystem,
99
- RequestTracker,
100
- AppDiagnostics,
101
- TYPES,
102
- configureApp,
103
- createApp,
104
- bootstrap,
105
- createError,
106
- AppError,
107
- isAppError,
108
- resetControllerRegistry,
109
- resetAppConfig
110
- } from '@forinda/kickjs';
111
- ```
53
+ ### Creating Controllers
112
54
 
113
- - `Controller`, `Get`, `Post`, `Put`, `Patch`, `Delete`: decorators for routing with built-in schema validation and duplicate-route protection
114
- - `Inject`, `Injectable`, `Optional`, `MultiInject`, `Named`, `Tagged`, `Unmanaged`: DI helpers wrapping Inversify without exposing its API surface
115
- - `HttpVerbController` & the verb-specific subclasses (`GetController`, `PostController`, …): enforce single-verb controllers with shared response/logging helpers and Nuxt-style route derivation
116
- - `BaseController`: abstract class with response + logging helpers for traditional decorator-driven controllers. The request tracker is injected automatically, so subclasses never pass it through `super()`.
117
- - `configureApp(config)`: set global prefix, logging level, telemetry limits, and health endpoint before bootstrapping
118
- - `createApp(options)`: create an Express application with auto-registered controllers (optionally override config per call) and get back a `discovery.controllers` list for diagnostics
119
- - `bootstrap(options)`: create & start the HTTP server (accepts `port`, config overrides, extra middleware)
120
- - `RequestTracker`: injectable request context tracker used internally by `BaseController`
121
- - `AppDiagnostics`: inspect application/request telemetry without touching internal reactive state
122
- - `createError` / `AppError` / `isAppError`: structured error helpers for consistent codes and statuses
123
- - `discoverControllersFromFilesystem(config)`: manually trigger file-system discovery when building custom tooling or CLIs
124
- - `TYPES`: symbol map to wire container bindings
125
- - `resetControllerRegistry()` / `resetAppConfig()`: utilities for clearing global state in integration tests
126
- - `createKickConfig(options)`: compose environment-aware app configuration objects that can be passed to `configureApp` or `createApp`
127
-
128
- ## File-based controllers
129
-
130
- Kick bootstraps controllers automatically by scanning `src/http` (configurable) for files that follow Nuxt-style naming. Each file becomes a single-verb controller by extending the appropriate base class:
55
+ Controllers are the heart of your KickJS application. They handle HTTP requests and contain your business logic.
131
56
 
132
- ```
133
- src/http/
134
- └─ users.get.controller.ts ➜ GET /users
135
- └─ users.post.controller.ts ➜ POST /users
136
- └─ admin/reports.[id].get.controller.ts ➜ GET /admin/reports/:id
137
- ```
57
+ ```typescript
58
+ // src/controllers/users.controller.ts
59
+ import {
60
+ KickController,
61
+ KickGet,
62
+ KickPost,
63
+ KickRequestContext,
64
+ KickInject
65
+ } from "@forinda/kickjs";
66
+ import { UserService } from "../services/user.service";
67
+
68
+ @KickController("/users")
69
+ export class UserController {
70
+ constructor(
71
+ @KickInject(UserService)
72
+ private readonly userService: UserService
73
+ ) {}
74
+
75
+ @KickGet("/")
76
+ async getUsers(context: KickRequestContext) {
77
+ const { res } = context;
78
+ const users = await this.userService.findAll();
79
+
80
+ res.json({
81
+ users,
82
+ requestId: context.meta.requestId,
83
+ timestamp: context.meta.startTime
84
+ });
85
+ }
138
86
 
139
- ```ts
140
- // src/http/users.get.controller.ts
141
- import type { Request, Response } from 'express';
142
- import { GetController } from '@forinda/kickjs';
87
+ @KickPost("/")
88
+ async createUser(context: KickRequestContext) {
89
+ const { req, res } = context;
90
+
91
+ if (!req.body.name || !req.body.email) {
92
+ return res.status(400).json({
93
+ error: "Name and email are required",
94
+ requestId: context.meta.requestId
95
+ });
96
+ }
143
97
 
144
- export default class UsersGetController extends GetController {
145
- handle(_req: Request, res: Response) {
146
- return this.ok(res, { users: ['Ada', 'Linus'] });
98
+ const user = await this.userService.create(req.body);
99
+ res.status(201).json({
100
+ user,
101
+ requestId: context.meta.requestId
102
+ });
147
103
  }
148
104
  }
149
105
  ```
150
106
 
151
- Naming rules:
107
+ ### Configuration
152
108
 
153
- - `<segments>.<verb>.controller.(ts|js)` – the last token before `.controller` defines the HTTP method
154
- - Directory names and file segments turn into URL fragments (`[id]` → `:id`, `[...slug]` → `:slug*`, `index` is omitted)
155
- - Set `static route = '/custom/path'` on the class to override the derived path, and `static tags = ['admin']` to enrich diagnostics metadata
109
+ KickJS supports flexible configuration through `kick.config.ts` files. This provides type safety and prevents configuration errors.
156
110
 
157
- Discovery can be customised through `configureApp({ api: { discovery: { ... } } })`:
111
+ ```typescript
112
+ // kick.config.ts
113
+ import { createKickConfig } from "@forinda/kickjs";
158
114
 
159
- ```ts
160
- configureApp({
161
- prefix: '/api',
162
- api: {
163
- discovery: {
164
- roots: ['apps/api/http'],
165
- baseRoute: '/',
166
- ignore: ['__mocks__']
115
+ export default createKickConfig({
116
+ app: {
117
+ name: 'My App',
118
+ port: 3000,
119
+ host: 'localhost',
120
+ prefix: '/api/v1',
121
+ env: 'development'
122
+ },
123
+ dev: {
124
+ port: 3000,
125
+ host: 'localhost',
126
+ entry: 'src/index.ts',
127
+ watch: true,
128
+ env: {
129
+ NODE_ENV: 'development',
130
+ DEBUG: 'app:*'
131
+ }
132
+ },
133
+ start: {
134
+ port: 3000,
135
+ host: '0.0.0.0',
136
+ entry: 'dist/index.js',
137
+ env: {
138
+ NODE_ENV: 'production'
167
139
  }
168
140
  }
169
141
  });
170
142
  ```
171
143
 
172
- Disable discovery (e.g. for legacy decorator-driven projects) with `configureApp({ api: { discovery: { enabled: false } } })` and pass controllers explicitly to `createApp({ controllers: [...] })`.
144
+ #### Using Configuration in Your App
145
+
146
+ ```typescript
147
+ // src/index.ts
148
+ import { createKickAppWithConfig } from "@forinda/kickjs";
149
+ import { AppModule } from "./app.module";
150
+
151
+ async function startApp() {
152
+ const server = await createKickAppWithConfig({
153
+ app: express(),
154
+ modules: [AppModule]
155
+ });
156
+
157
+ // Access config in your app
158
+ console.log('App Name:', server.kickApp.getConfig('name'));
159
+ console.log('API Prefix:', server.kickApp.getConfig('prefix'));
160
+
161
+ // Config with fallback
162
+ const theme = server.kickApp.getConfigOrDefault('ui.theme', 'dark');
163
+
164
+ const port = server.kickApp.getConfig('port') || 3000;
165
+ server.listen(port, () => {
166
+ console.log(`🚀 ${server.kickApp.getConfig('name')} running on port ${port}`);
167
+ });
168
+ }
173
169
 
174
- ## CLI
170
+ startApp();
171
+ ```
175
172
 
176
- Kick ships with a `kick` executable once the package is installed locally (`npx kick --help`).
173
+ #### CLI Configuration Support
177
174
 
178
- ### Bootstrapping a project
175
+ The KickJS CLI automatically loads your configuration:
179
176
 
180
177
  ```bash
181
- npm create kick@latest my-app
182
- cd my-app
183
- npm install
184
- npm run dev
178
+ # Uses config file values
179
+ kick dev
180
+
181
+ # Override specific values
182
+ kick dev --port 8080 --host 0.0.0.0
183
+
184
+ # Production mode
185
+ kick start --port 3000
185
186
  ```
186
187
 
187
- The initializer mirrors running `kick init my-app` inside an empty directory: it scaffolds a domain-first folder layout, creates `kick.config.ts` at the repo root for CLI defaults, and generates `src/config/kick.config.ts` for runtime configuration. Both files are plain TypeScript modules you can edit.
188
+ ### Creating Services
189
+
190
+ Services contain your business logic and can be injected into controllers and other services.
191
+
192
+ ```typescript
193
+ // src/services/user.service.ts
194
+ import { KickInjectable } from "@forinda/kickjs";
188
195
 
189
- During `bootstrap`, load the runtime config and pass it to `configureApp` once before invoking `createApp`/`bootstrap`:
196
+ export interface User {
197
+ id: string;
198
+ name: string;
199
+ email: string;
200
+ createdAt: Date;
201
+ }
202
+
203
+ @KickInjectable()
204
+ export class UserService {
205
+ private users: User[] = [];
190
206
 
191
- ```ts
192
- // src/main.ts
193
- import 'reflect-metadata';
194
- import { bootstrap, configureApp } from '@forinda/kickjs';
195
- import appConfig from './config/kick.config';
207
+ async findAll(): Promise<User[]> {
208
+ return this.users;
209
+ }
196
210
 
197
- configureApp(appConfig);
211
+ async create(userData: { name: string; email: string }): Promise<User> {
212
+ const user: User = {
213
+ id: Math.random().toString(36).substr(2, 9),
214
+ name: userData.name,
215
+ email: userData.email,
216
+ createdAt: new Date()
217
+ };
218
+
219
+ this.users.push(user);
220
+ return user;
221
+ }
198
222
 
199
- async function main() {
200
- const { shutdown } = await bootstrap({ port: process.env.PORT ?? 3000 });
201
- process.once('SIGINT', shutdown);
202
- process.once('SIGTERM', shutdown);
223
+ async findById(id: string): Promise<User | undefined> {
224
+ return this.users.find(user => user.id === id);
225
+ }
203
226
  }
227
+ ```
204
228
 
205
- main().catch((error) => {
206
- console.error('Failed to bootstrap Kick app', error);
207
- process.exitCode = 1;
229
+ ### Creating Modules
230
+
231
+ Modules help organize your application by grouping related controllers, services, and middlewares.
232
+
233
+ ```typescript
234
+ // src/app.module.ts
235
+ import { createModule } from "@forinda/kickjs";
236
+ import { UserController } from "./controllers/user.controller";
237
+ import { UserService } from "./services/user.service";
238
+ import { LoggingMiddleware } from "./middlewares/logging.middleware";
239
+
240
+ export const AppModule = createModule("app", {
241
+ controllers: [UserController],
242
+ middlewares: [LoggingMiddleware] // Optional: DI-managed middlewares
208
243
  });
209
244
  ```
210
245
 
211
- `createKickConfig` handles `.env`, `.env.<NODE_ENV>`, and `.env.local` files automatically, so populating `src/config/kick.config.ts` with env bindings ensures local and production deployments share a single source of truth.
246
+ ## 🛠️ Creating Middlewares
212
247
 
213
- ### `kick init [directory]`
248
+ KickJS supports two types of middlewares: global middlewares and DI-managed middlewares.
214
249
 
215
- Scaffold a fresh project with a minimal `package.json`, `tsconfig.json`, `kick.config.ts`, `src/main.ts`, and a sample domain under `src/domains/app`. Use `--force` to overwrite existing files and `--name` to control the package name.
250
+ ### DI-Managed Middlewares (Recommended)
216
251
 
217
- ### `kick generate controller <name>`
252
+ These middlewares are managed by the dependency injection container and can inject services.
218
253
 
219
- Generate a convention-based controller file. The command derives the proper filename and class name, so:
254
+ ```typescript
255
+ // src/middlewares/logging.middleware.ts
256
+ import {
257
+ KickMiddleware,
258
+ KickAppMiddleware,
259
+ KickRequest,
260
+ KickResponse,
261
+ KickNextFn,
262
+ KickInject
263
+ } from "@forinda/kickjs";
264
+ import { LoggerService } from "../services/logger.service";
220
265
 
221
- ```bash
222
- kick generate controller admin/reports/[id] --method get --tags admin,reports
266
+ @KickMiddleware({
267
+ name: "RequestLogger",
268
+ priority: 1, // Lower numbers execute first
269
+ global: true,
270
+ tags: ["logging", "development"]
271
+ })
272
+ export class LoggingMiddleware implements KickAppMiddleware {
273
+ constructor(
274
+ @KickInject(LoggerService)
275
+ private readonly logger: LoggerService
276
+ ) {}
277
+
278
+ use(req: KickRequest, res: KickResponse, next: KickNextFn): void {
279
+ const start = Date.now();
280
+
281
+ this.logger.info(`→ ${req.method} ${req.url}`);
282
+
283
+ res.on('finish', () => {
284
+ const duration = Date.now() - start;
285
+ this.logger.info(`← ${req.method} ${req.url} ${res.statusCode} (${duration}ms)`);
286
+ });
287
+
288
+ next();
289
+ }
290
+ }
223
291
  ```
224
292
 
225
- creates `src/domains/admin/controllers/reports.[id].get.controller.ts` when using the default domain layout. Override the discovery root with `--root` when your project stores controllers elsewhere.
293
+ ### Global Middlewares
226
294
 
227
- ### `kick generate domain <name>`
295
+ Global middlewares are not managed by DI and are useful for framework-level concerns like CORS.
228
296
 
229
- Create a domain folder following your configured layout (defaults to `src/domains/<name>/(controllers|services|domain)`) and, unless `--no-controller` is passed, drop in a starter `index.get.controller.ts` file you can immediately extend.
297
+ ```typescript
298
+ // src/middlewares/cors.middleware.ts
299
+ import { KickAppMiddleware, KickRequest, KickResponse, KickNextFn } from "@forinda/kickjs";
230
300
 
231
- ### Custom commands
301
+ export class CorsMiddleware implements KickAppMiddleware {
302
+ use(req: KickRequest, res: KickResponse, next: KickNextFn): void {
303
+ res.setHeader('Access-Control-Allow-Origin', '*');
304
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
305
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
306
+
307
+ if (req.method === 'OPTIONS') {
308
+ res.status(200).end();
309
+ return;
310
+ }
311
+
312
+ next();
313
+ }
314
+ }
315
+ ```
232
316
 
233
- Add `kick.config.ts` (or `.js`/`.json`) to declare shorthand commands that proxy to shell steps:
317
+ Register global middlewares when creating your app:
234
318
 
235
- ```ts
236
- import type { KickConfig } from '@forinda/kickjs';
319
+ ```typescript
320
+ const corsMiddleware = new CorsMiddleware();
237
321
 
238
- const config: KickConfig = {
239
- structure: {
240
- domainRoot: 'src/domains',
241
- domainFolders: ['controllers', 'services', 'domain'],
242
- defaultDomain: 'app'
243
- },
244
- generators: { controllerRoot: 'src/domains/app/controllers' },
245
- commands: [
246
- { name: 'dev', description: 'Start the dev server', steps: 'npm run dev' },
247
- { name: 'lint', steps: ['npm run lint', 'npm run typecheck'] }
248
- ]
249
- };
250
-
251
- export default config;
322
+ const server = createKickApp({
323
+ name: "MyApp",
324
+ app,
325
+ globalMiddlewares: [corsMiddleware], // Global middlewares
326
+ modules: [AppModule] // DI-managed middlewares are in modules
327
+ });
328
+ ```
329
+
330
+ ## 🔌 Creating Plugins
331
+
332
+ Plugins allow you to extend the application context during initialization.
333
+
334
+ ```typescript
335
+ // src/plugins/database.plugin.ts
336
+ import { KickAppPlugin, KickApplicationContext } from "@forinda/kickjs";
337
+
338
+ export class DatabasePlugin implements KickAppPlugin {
339
+ install(context: KickApplicationContext): void {
340
+ // Initialize database connection
341
+ console.log("🗄️ Database plugin initialized");
342
+
343
+ // Add database middleware or modify app
344
+ context.app.use((req, res, next) => {
345
+ // Add database connection to request
346
+ (req as any).db = /* your database connection */;
347
+ next();
348
+ });
349
+ }
350
+ }
252
351
  ```
253
352
 
254
- Any command listed becomes available directly, so `kick lint` runs the declared steps. The `structure` block informs both discovery defaults and the CLI generators/initialiser.
353
+ Use plugins in your app:
255
354
 
256
- ## Configuration helper
355
+ ```typescript
356
+ const dbPlugin = new DatabasePlugin();
257
357
 
258
- Use `createKickConfig` to compose application settings that blend defaults, environment variables, and ad-hoc overrides:
358
+ const server = createKickApp({
359
+ name: "MyApp",
360
+ app,
361
+ plugins: [dbPlugin],
362
+ modules: [AppModule]
363
+ });
364
+ ```
259
365
 
260
- ```ts
261
- // src/config/kick.config.ts
262
- import { createKickConfig } from '@forinda/kickjs';
366
+ ## 🎯 Advanced Features
367
+
368
+ ### Request Context
369
+
370
+ Every controller method receives a `KickRequestContext` with rich metadata:
371
+
372
+ ```typescript
373
+ interface KickRequestContext {
374
+ req: KickRequest; // Express request
375
+ res: KickResponse; // Express response
376
+ next: KickNextFn; // Express next function
377
+ meta: {
378
+ routePath: string; // Route pattern
379
+ method: string; // HTTP method
380
+ controllerName: string; // Controller class name
381
+ handlerName: string; // Method name
382
+ startTime: number; // Request start timestamp
383
+ requestId: string; // Unique request ID
384
+ };
385
+ }
386
+ ```
263
387
 
264
- export default createKickConfig({
265
- defaults: {
266
- prefix: '/api',
267
- api: {
268
- discovery: {
269
- roots: ['src/domains/app/controllers', 'src/http']
270
- }
271
- }
272
- },
273
- env: {
274
- KICK_PREFIX: 'prefix',
275
- KICK_HEALTH: 'healthEndpoint',
276
- KICK_LOG_LEVEL: { path: 'logging.level' }
277
- },
278
- overrides: (current) => ({
279
- telemetry: {
280
- trackReactiveHistory: process.env.NODE_ENV !== 'production'
281
- }
282
- })
388
+ ### Reactive State Management
389
+
390
+ KickApp includes reactive state management:
391
+
392
+ ```typescript
393
+ // Set state
394
+ server.kickApp.setState('userCount', 42);
395
+
396
+ // Listen to state changes
397
+ server.kickApp.onStateChange('userCount', (data) => {
398
+ console.log(`User count changed: ${data.oldValue} → ${data.value}`);
399
+ });
400
+
401
+ // Get current state
402
+ const currentState = server.kickApp.state;
403
+ ```
404
+
405
+ ### Event System
406
+
407
+ Listen to application events:
408
+
409
+ ```typescript
410
+ server.kickApp.on('route:registered', (route) => {
411
+ console.log(`Route registered: ${route.method} ${route.path}`);
412
+ });
413
+
414
+ server.kickApp.on('middleware:registered', (middleware) => {
415
+ console.log(`Middleware registered: ${middleware.count} middlewares`);
416
+ });
417
+
418
+ server.kickApp.on('controller:mapped', (controller) => {
419
+ console.log(`Controller mapped: ${controller.controller}`);
283
420
  });
284
421
  ```
285
422
 
286
- You can pass the resulting `AppConfig` to `configureApp(config)` during bootstrap or supply it via `createApp({ config })` when composing tests. Environment bindings auto-cast booleans/numbers and accept custom transformers for complex structures.
423
+ ### Error Handling
287
424
 
288
- ## Diagnostics & telemetry
425
+ Add global error handlers:
289
426
 
290
- `AppDiagnostics` surfaces sanitized snapshots of the framework's internal state so you can build devtools without touching the underlying reactive registry. After creating or bootstrapping the app, read diagnostics straight from the returned context:
427
+ ```typescript
428
+ server.addErrorHandler((errorData) => {
429
+ console.error('Application error:', errorData);
430
+ // Send to logging service, etc.
431
+ });
432
+ ```
433
+
434
+ ## 🚀 Running Your Application
291
435
 
292
- ```ts
293
- const { diagnostics } = createApp();
294
- const stores = diagnostics.stores();
295
- // -> [{ id, label, snapshot, history }, ... ]
436
+ ### Development
296
437
 
297
- const requests = diagnostics.requests();
298
- // -> [{ id, path, status, logs, metadata, ... }, ... ]
438
+ ```bash
439
+ # Using tsx for development
440
+ npx tsx watch src/index.ts
441
+
442
+ # Or with nodemon
443
+ npx nodemon --exec tsx src/index.ts
299
444
  ```
300
445
 
301
- Stores whose `label` starts with `request:` represent in-flight or completed requests, ready for live dashboards.
446
+ ### Production
447
+
448
+ ```bash
449
+ # Build your TypeScript
450
+ npx tsc
302
451
 
303
- ## Request validation
452
+ # Run the compiled JavaScript
453
+ node dist/index.js
454
+ ```
304
455
 
305
- Provide Zod or Joi schemas directly to the HTTP decorators – the framework will validate `params`, `query`, and `body` before your handler executes:
456
+ ### Example Scripts (package.json)
306
457
 
307
- ```ts
308
- @Post({
309
- path: '/users',
310
- validate: {
311
- body: z.object({ email: z.string().email(), name: z.string().min(1) })
458
+ ```json
459
+ {
460
+ "scripts": {
461
+ "dev": "tsx watch src/index.ts",
462
+ "build": "tsc",
463
+ "start": "node dist/index.js",
464
+ "test": "vitest"
312
465
  }
313
- })
314
- createUser(req: Request, res: Response) {
315
- return this.created(res, req.body);
316
466
  }
317
467
  ```
318
468
 
319
- If validation fails, the request short-circuits with a structured `VALIDATION_ERROR` payload and a 400 response.
469
+ ## 📁 Project Structure
470
+
471
+ ```
472
+ src/
473
+ ├── controllers/ # HTTP controllers
474
+ │ ├── user.controller.ts
475
+ │ └── auth.controller.ts
476
+ ├── services/ # Business logic services
477
+ │ ├── user.service.ts
478
+ │ └── auth.service.ts
479
+ ├── middlewares/ # Custom middlewares
480
+ │ ├── logging.middleware.ts
481
+ │ └── auth.middleware.ts
482
+ ├── plugins/ # Application plugins
483
+ │ └── database.plugin.ts
484
+ ├── types/ # Type definitions
485
+ │ └── user.types.ts
486
+ ├── modules/ # Application modules
487
+ │ ├── user.module.ts
488
+ │ └── auth.module.ts
489
+ └── index.ts # Application entry point
490
+ ```
491
+
492
+ ## 📚 API Reference
493
+
494
+ ### Decorators
495
+
496
+ - `@KickController(path)` - Define a controller class
497
+ - `@KickGet(path)` - HTTP GET route
498
+ - `@KickPost(path)` - HTTP POST route
499
+ - `@KickPut(path)` - HTTP PUT route
500
+ - `@KickPatch(path)` - HTTP PATCH route
501
+ - `@KickDelete(path)` - HTTP DELETE route
502
+ - `@KickMiddleware(options)` - Define a middleware class
503
+ - `@KickInject(token)` - Inject dependencies
504
+ - `@KickInjectable()` - Mark class as injectable service
505
+ - `@AutoBind` - Automatically bind class methods
506
+
507
+ ### Core Functions
508
+
509
+ - `createKickApp(options)` - Create a KickJS application
510
+ - `createModule(name, options)` - Create a module
511
+ - `isKickMiddleware(target)` - Check if class is a middleware
512
+ - `getMiddlewareMetadata(target)` - Get middleware metadata
513
+
514
+ ### Types
515
+
516
+ - `KickRequestContext` - Request context interface
517
+ - `KickAppMiddleware` - Middleware interface
518
+ - `KickAppPlugin` - Plugin interface
519
+ - `KickApplicationContext` - Application context interface
520
+
521
+ ## 🤝 Contributing
522
+
523
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for detailed information on how to get started.
524
+
525
+ ### Quick Start for Contributors
526
+
527
+ 1. **Fork and clone the repository**
528
+ ```bash
529
+ git clone https://github.com/yourusername/kickjs.git
530
+ cd kickjs
531
+ pnpm install
532
+ ```
320
533
 
321
- ## Route uniqueness
534
+ 2. **Run tests to ensure everything works**
535
+ ```bash
536
+ pnpm test
537
+ pnpm build
538
+ ```
322
539
 
323
- `registerControllers` hashes every `[METHOD] path` combination to block duplicate routes. If two handlers resolve to the same normalized path, the framework throws a `ROUTE_CONFLICT` error during bootstrap so you catch collisions early.
540
+ 3. **Create a feature branch and make your changes**
541
+ ```bash
542
+ git checkout -b feature/amazing-feature
543
+ # Make your changes...
544
+ git commit -m "feat: add amazing feature"
545
+ ```
324
546
 
325
- ## Sample projects
547
+ 4. **Submit a pull request**
326
548
 
327
- - `examples/basic-todo` – minimal CRUD organised as `src/(controllers|services|domain)` (`node --loader ts-node/esm examples/basic-todo/index.ts`).
328
- - `examples/medium-kanban` – workflow + metrics sample with the same structure (`node --loader ts-node/esm examples/medium-kanban/index.ts`).
329
- - `examples/complex-analytics` – reactive event DB + aggregations with an additional `src/db/` layer (`node --loader ts-node/esm examples/complex-analytics/index.ts`).
549
+ For detailed guidelines, development setup, coding standards, and more, please read our [Contributing Guide](CONTRIBUTING.md).
330
550
 
331
- Additional internal documentation describing the folder layout lives in `docs/structure.md`.
551
+ ### 📞 Getting Help
332
552
 
333
- ## Development scripts
553
+ - 📖 Check the [documentation](README.md) and [examples](examples/)
554
+ - 🐛 Search [existing issues](https://github.com/forinda/kickjs/issues)
555
+ - 💬 Join our community discussions
556
+ - 📧 Contact maintainers for security issues
334
557
 
335
- - `npm run dev` – run the sample app (`src/main.ts`) with hot reload
336
- - `npm run build` – bundle library to `dist/`
337
- - `npm run check` – type-check
338
- - `npm test` – runs Vitest against the integration-style specs
558
+ Thank you for contributing to KickJS! 🚀
339
559
 
340
- ## CI & release pipeline
560
+ ## 📄 License
341
561
 
342
- `.github/workflows/release.yml` performs type-checking, tests, and build on pushes to `main`. Publishing happens automatically when:
562
+ MIT License - see [LICENSE](LICENSE) file for details.
343
563
 
344
- 1. A GitHub release is published, or
345
- 2. The workflow is dispatched manually with `publish=true`.
564
+ ---
346
565
 
347
- Configure the `NPM_TOKEN` repository secret before triggering the publish job.
566
+ **Made with ❤️ by the KickJS team**