@forinda/kickjs 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,347 +1,560 @@
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
+ services: [UserService], // Register your services
243
+ middlewares: [LoggingMiddleware] // Optional: DI-managed middlewares
208
244
  });
209
245
  ```
210
246
 
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.
247
+ ## 🛠️ Creating Middlewares
212
248
 
213
- ### `kick init [directory]`
249
+ KickJS supports two types of middlewares: global middlewares and DI-managed middlewares.
214
250
 
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.
251
+ ### DI-Managed Middlewares (Recommended)
216
252
 
217
- ### `kick generate controller <name>`
253
+ These middlewares are managed by the dependency injection container and can inject services.
218
254
 
219
- Generate a convention-based controller file. The command derives the proper filename and class name, so:
255
+ ```typescript
256
+ // src/middlewares/logging.middleware.ts
257
+ import {
258
+ KickMiddleware,
259
+ KickAppMiddleware,
260
+ KickRequest,
261
+ KickResponse,
262
+ KickNextFn
263
+ } from "@forinda/kickjs";
220
264
 
221
- ```bash
222
- kick generate controller admin/reports/[id] --method get --tags admin,reports
265
+ @KickMiddleware({
266
+ name: "RequestLogger",
267
+ priority: 1, // Lower numbers execute first
268
+ global: true,
269
+ tags: ["logging", "development"]
270
+ })
271
+ export class LoggingMiddleware implements KickAppMiddleware {
272
+ use(req: KickRequest, res: KickResponse, next: KickNextFn): void {
273
+ const start = Date.now();
274
+
275
+ console.log(`→ ${req.method} ${req.url}`);
276
+
277
+ res.on('finish', () => {
278
+ const duration = Date.now() - start;
279
+ console.log(`← ${req.method} ${req.url} ${res.statusCode} (${duration}ms)`);
280
+ });
281
+
282
+ next();
283
+ }
284
+ }
223
285
  ```
224
286
 
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.
287
+ ### Global Middlewares
226
288
 
227
- ### `kick generate domain <name>`
289
+ Global middlewares are not managed by DI and are useful for framework-level concerns like CORS.
228
290
 
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.
291
+ ```typescript
292
+ // src/middlewares/cors.middleware.ts
293
+ import { KickAppMiddleware, KickRequest, KickResponse, KickNextFn } from "@forinda/kickjs";
230
294
 
231
- ### Custom commands
295
+ export class CorsMiddleware implements KickAppMiddleware {
296
+ use(req: KickRequest, res: KickResponse, next: KickNextFn): void {
297
+ res.setHeader('Access-Control-Allow-Origin', '*');
298
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
299
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
300
+
301
+ if (req.method === 'OPTIONS') {
302
+ res.status(200).end();
303
+ return;
304
+ }
305
+
306
+ next();
307
+ }
308
+ }
309
+ ```
232
310
 
233
- Add `kick.config.ts` (or `.js`/`.json`) to declare shorthand commands that proxy to shell steps:
311
+ Register global middlewares when creating your app:
234
312
 
235
- ```ts
236
- import type { KickConfig } from '@forinda/kickjs';
313
+ ```typescript
314
+ const corsMiddleware = new CorsMiddleware();
237
315
 
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;
316
+ const server = createKickApp({
317
+ name: "MyApp",
318
+ app,
319
+ globalMiddlewares: [corsMiddleware], // Global middlewares
320
+ modules: [AppModule] // DI-managed middlewares are in modules
321
+ });
322
+ ```
323
+
324
+ ## 🔌 Creating Plugins
325
+
326
+ Plugins allow you to extend the application context during initialization.
327
+
328
+ ```typescript
329
+ // src/plugins/database.plugin.ts
330
+ import { KickAppPlugin, KickApplicationContext } from "@forinda/kickjs";
331
+
332
+ export class DatabasePlugin implements KickAppPlugin {
333
+ install(context: KickApplicationContext): void {
334
+ // Initialize database connection
335
+ console.log("🗄️ Database plugin initialized");
336
+
337
+ // Add database middleware or modify app
338
+ context.app.use((req, res, next) => {
339
+ // Add database connection to request
340
+ (req as any).db = /* your database connection */;
341
+ next();
342
+ });
343
+ }
344
+ }
252
345
  ```
253
346
 
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.
347
+ Use plugins in your app:
255
348
 
256
- ## Configuration helper
349
+ ```typescript
350
+ const dbPlugin = new DatabasePlugin();
257
351
 
258
- Use `createKickConfig` to compose application settings that blend defaults, environment variables, and ad-hoc overrides:
352
+ const server = createKickApp({
353
+ name: "MyApp",
354
+ app,
355
+ plugins: [dbPlugin],
356
+ modules: [AppModule]
357
+ });
358
+ ```
259
359
 
260
- ```ts
261
- // src/config/kick.config.ts
262
- import { createKickConfig } from '@forinda/kickjs';
360
+ ## 🎯 Advanced Features
361
+
362
+ ### Request Context
363
+
364
+ Every controller method receives a `KickRequestContext` with rich metadata:
365
+
366
+ ```typescript
367
+ interface KickRequestContext {
368
+ req: KickRequest; // Express request
369
+ res: KickResponse; // Express response
370
+ next: KickNextFn; // Express next function
371
+ meta: {
372
+ routePath: string; // Route pattern
373
+ method: string; // HTTP method
374
+ controllerName: string; // Controller class name
375
+ handlerName: string; // Method name
376
+ startTime: number; // Request start timestamp
377
+ requestId: string; // Unique request ID
378
+ };
379
+ }
380
+ ```
263
381
 
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
- })
382
+ ### Reactive State Management
383
+
384
+ KickApp includes reactive state management:
385
+
386
+ ```typescript
387
+ // Set state
388
+ server.kickApp.setState('userCount', 42);
389
+
390
+ // Listen to state changes
391
+ server.kickApp.onStateChange('userCount', (data) => {
392
+ console.log(`User count changed: ${data.oldValue} → ${data.value}`);
393
+ });
394
+
395
+ // Get current state
396
+ const currentState = server.kickApp.state;
397
+ ```
398
+
399
+ ### Event System
400
+
401
+ Listen to application events:
402
+
403
+ ```typescript
404
+ server.kickApp.on('route:registered', (route) => {
405
+ console.log(`Route registered: ${route.method} ${route.path}`);
406
+ });
407
+
408
+ server.kickApp.on('middleware:registered', (middleware) => {
409
+ console.log(`Middleware registered: ${middleware.count} middlewares`);
410
+ });
411
+
412
+ server.kickApp.on('controller:mapped', (controller) => {
413
+ console.log(`Controller mapped: ${controller.controller}`);
283
414
  });
284
415
  ```
285
416
 
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.
417
+ ### Error Handling
287
418
 
288
- ## Diagnostics & telemetry
419
+ Add global error handlers:
289
420
 
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:
421
+ ```typescript
422
+ server.addErrorHandler((errorData) => {
423
+ console.error('Application error:', errorData);
424
+ // Send to logging service, etc.
425
+ });
426
+ ```
427
+
428
+ ## 🚀 Running Your Application
291
429
 
292
- ```ts
293
- const { diagnostics } = createApp();
294
- const stores = diagnostics.stores();
295
- // -> [{ id, label, snapshot, history }, ... ]
430
+ ### Development
296
431
 
297
- const requests = diagnostics.requests();
298
- // -> [{ id, path, status, logs, metadata, ... }, ... ]
432
+ ```bash
433
+ # Using tsx for development
434
+ npx tsx watch src/index.ts
435
+
436
+ # Or with nodemon
437
+ npx nodemon --exec tsx src/index.ts
299
438
  ```
300
439
 
301
- Stores whose `label` starts with `request:` represent in-flight or completed requests, ready for live dashboards.
440
+ ### Production
441
+
442
+ ```bash
443
+ # Build your TypeScript
444
+ npx tsc
302
445
 
303
- ## Request validation
446
+ # Run the compiled JavaScript
447
+ node dist/index.js
448
+ ```
304
449
 
305
- Provide Zod or Joi schemas directly to the HTTP decorators – the framework will validate `params`, `query`, and `body` before your handler executes:
450
+ ### Example Scripts (package.json)
306
451
 
307
- ```ts
308
- @Post({
309
- path: '/users',
310
- validate: {
311
- body: z.object({ email: z.string().email(), name: z.string().min(1) })
452
+ ```json
453
+ {
454
+ "scripts": {
455
+ "dev": "tsx watch src/index.ts",
456
+ "build": "tsc",
457
+ "start": "node dist/index.js",
458
+ "test": "vitest"
312
459
  }
313
- })
314
- createUser(req: Request, res: Response) {
315
- return this.created(res, req.body);
316
460
  }
317
461
  ```
318
462
 
319
- If validation fails, the request short-circuits with a structured `VALIDATION_ERROR` payload and a 400 response.
463
+ ## 📁 Project Structure
464
+
465
+ ```
466
+ src/
467
+ ├── controllers/ # HTTP controllers
468
+ │ ├── user.controller.ts
469
+ │ └── auth.controller.ts
470
+ ├── services/ # Business logic services
471
+ │ ├── user.service.ts
472
+ │ └── auth.service.ts
473
+ ├── middlewares/ # Custom middlewares
474
+ │ ├── logging.middleware.ts
475
+ │ └── auth.middleware.ts
476
+ ├── plugins/ # Application plugins
477
+ │ └── database.plugin.ts
478
+ ├── types/ # Type definitions
479
+ │ └── user.types.ts
480
+ ├── modules/ # Application modules
481
+ │ ├── user.module.ts
482
+ │ └── auth.module.ts
483
+ └── index.ts # Application entry point
484
+ ```
485
+
486
+ ## 📚 API Reference
487
+
488
+ ### Decorators
489
+
490
+ - `@KickController(path)` - Define a controller class
491
+ - `@KickGet(path)` - HTTP GET route
492
+ - `@KickPost(path)` - HTTP POST route
493
+ - `@KickPut(path)` - HTTP PUT route
494
+ - `@KickPatch(path)` - HTTP PATCH route
495
+ - `@KickDelete(path)` - HTTP DELETE route
496
+ - `@KickMiddleware(options)` - Define a middleware class
497
+ - `@KickInject(token)` - Inject dependencies
498
+ - `@KickInjectable()` - Mark class as injectable service
499
+ - `@AutoBind` - Automatically bind class methods
500
+
501
+ ### Core Functions
502
+
503
+ - `createKickApp(options)` - Create a KickJS application
504
+ - `createModule(name, options)` - Create a module
505
+ - `isKickMiddleware(target)` - Check if class is a middleware
506
+ - `getMiddlewareMetadata(target)` - Get middleware metadata
507
+
508
+ ### Types
509
+
510
+ - `KickRequestContext` - Request context interface
511
+ - `KickAppMiddleware` - Middleware interface
512
+ - `KickAppPlugin` - Plugin interface
513
+ - `KickApplicationContext` - Application context interface
514
+
515
+ ## 🤝 Contributing
516
+
517
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for detailed information on how to get started.
518
+
519
+ ### Quick Start for Contributors
520
+
521
+ 1. **Fork and clone the repository**
522
+ ```bash
523
+ git clone https://github.com/yourusername/kickjs.git
524
+ cd kickjs
525
+ pnpm install
526
+ ```
320
527
 
321
- ## Route uniqueness
528
+ 2. **Run tests to ensure everything works**
529
+ ```bash
530
+ pnpm test
531
+ pnpm build
532
+ ```
322
533
 
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.
534
+ 3. **Create a feature branch and make your changes**
535
+ ```bash
536
+ git checkout -b feature/amazing-feature
537
+ # Make your changes...
538
+ git commit -m "feat: add amazing feature"
539
+ ```
324
540
 
325
- ## Sample projects
541
+ 4. **Submit a pull request**
326
542
 
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`).
543
+ For detailed guidelines, development setup, coding standards, and more, please read our [Contributing Guide](CONTRIBUTING.md).
330
544
 
331
- Additional internal documentation describing the folder layout lives in `docs/structure.md`.
545
+ ### 📞 Getting Help
332
546
 
333
- ## Development scripts
547
+ - 📖 Check the [documentation](README.md) and [examples](examples/)
548
+ - 🐛 Search [existing issues](https://github.com/forinda/kickjs/issues)
549
+ - 💬 Join our community discussions
550
+ - 📧 Contact maintainers for security issues
334
551
 
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
552
+ Thank you for contributing to KickJS! 🚀
339
553
 
340
- ## CI & release pipeline
554
+ ## 📄 License
341
555
 
342
- `.github/workflows/release.yml` performs type-checking, tests, and build on pushes to `main`. Publishing happens automatically when:
556
+ MIT License - see [LICENSE](LICENSE) file for details.
343
557
 
344
- 1. A GitHub release is published, or
345
- 2. The workflow is dispatched manually with `publish=true`.
558
+ ---
346
559
 
347
- Configure the `NPM_TOKEN` repository secret before triggering the publish job.
560
+ **Made with ❤️ by the KickJS team**