@forinda/kickjs 0.1.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 ADDED
@@ -0,0 +1,173 @@
1
+ # Kick
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.
4
+
5
+ ## Highlights
6
+
7
+ - Spring Boot-style controllers via `@Controller`, `@Get`, etc., auto-registered at decoration time
8
+ - Schema-aware route decorators (Zod/Joi) with duplicate-route protection hashed at bootstrap
9
+ - Built-in `BaseController` helper with structured responses, request logging, and `fail()` AppError helpers
10
+ - `configureApp` and per-call `config` options for prefixes, health endpoints, logging levels, and telemetry limits
11
+ - Request telemetry tracked behind the scenes and exposed via `AppDiagnostics`
12
+ - Dependency injection utilities (`@Inject`, `@Injectable`, …) that hide raw Inversify decorators
13
+ - `tsup` build pipeline producing CommonJS bundles + type declarations
14
+ - GitHub Actions workflow for CI and optional npm publishing
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @forinda/kickjs
20
+ ```
21
+
22
+ ## Creating your first service
23
+
24
+ ```ts
25
+ // app.ts
26
+ import 'reflect-metadata';
27
+ import type { Request, Response } from 'express';
28
+ import { z } from 'zod';
29
+ import {
30
+ BaseController,
31
+ Controller,
32
+ Get,
33
+ Inject,
34
+ RequestTracker,
35
+ TYPES,
36
+ bootstrap,
37
+ configureApp
38
+ } from '@forinda/kickjs';
39
+
40
+ configureApp({ prefix: '/api' });
41
+
42
+ @Controller('/hello')
43
+ class HelloController extends BaseController {
44
+ constructor(@Inject(TYPES.RequestTracker) tracker: RequestTracker) {
45
+ super(tracker);
46
+ }
47
+
48
+ protected controllerId(): string {
49
+ return 'HelloController';
50
+ }
51
+
52
+ @Get({
53
+ path: '/',
54
+ validate: {
55
+ query: z.object({ name: z.string().optional() })
56
+ }
57
+ })
58
+ handle(req: Request, res: Response) {
59
+ const name = typeof req.query.name === 'string' ? req.query.name : 'World';
60
+ this.mergeRequestMetadata(res, { greeted: name });
61
+ return this.ok(res, { message: `Hello ${name}` });
62
+ }
63
+ }
64
+
65
+ bootstrap();
66
+ ```
67
+
68
+ `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.
69
+
70
+ ## Public API surface
71
+
72
+ ```ts
73
+ import {
74
+ Controller,
75
+ Get,
76
+ Post,
77
+ Put,
78
+ Patch,
79
+ Delete,
80
+ Inject,
81
+ Injectable,
82
+ Optional,
83
+ MultiInject,
84
+ Named,
85
+ Tagged,
86
+ Unmanaged,
87
+ BaseController,
88
+ RequestTracker,
89
+ AppDiagnostics,
90
+ TYPES,
91
+ configureApp,
92
+ createApp,
93
+ bootstrap,
94
+ createError,
95
+ AppError,
96
+ isAppError,
97
+ resetControllerRegistry,
98
+ resetAppConfig
99
+ } from '@forinda/kickjs';
100
+ ```
101
+
102
+ - `Controller`, `Get`, `Post`, `Put`, `Patch`, `Delete`: decorators for routing with built-in schema validation and duplicate-route protection
103
+ - `Inject`, `Injectable`, `Optional`, `MultiInject`, `Named`, `Tagged`, `Unmanaged`: DI helpers wrapping Inversify without exposing its API surface
104
+ - `BaseController`: abstract class with response + logging helpers
105
+ - `configureApp(config)`: set global prefix, logging level, telemetry limits, and health endpoint before bootstrapping
106
+ - `createApp(options)`: create an Express application with auto-registered controllers (optionally override config per call)
107
+ - `bootstrap(options)`: create & start the HTTP server (accepts `port`, config overrides, extra middleware)
108
+ - `RequestTracker`: injectable request context tracker used internally by `BaseController`
109
+ - `AppDiagnostics`: inspect application/request telemetry without touching internal reactive state
110
+ - `createError` / `AppError` / `isAppError`: structured error helpers for consistent codes and statuses
111
+ - `TYPES`: symbol map to wire container bindings
112
+ - `resetControllerRegistry()` / `resetAppConfig()`: utilities for clearing global state in integration tests
113
+
114
+ ## Diagnostics & telemetry
115
+
116
+ `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:
117
+
118
+ ```ts
119
+ const { diagnostics } = createApp();
120
+ const stores = diagnostics.stores();
121
+ // -> [{ id, label, snapshot, history }, ... ]
122
+
123
+ const requests = diagnostics.requests();
124
+ // -> [{ id, path, status, logs, metadata, ... }, ... ]
125
+ ```
126
+
127
+ Stores whose `label` starts with `request:` represent in-flight or completed requests, ready for live dashboards.
128
+
129
+ ## Request validation
130
+
131
+ Provide Zod or Joi schemas directly to the HTTP decorators – the framework will validate `params`, `query`, and `body` before your handler executes:
132
+
133
+ ```ts
134
+ @Post({
135
+ path: '/users',
136
+ validate: {
137
+ body: z.object({ email: z.string().email(), name: z.string().min(1) })
138
+ }
139
+ })
140
+ createUser(req: Request, res: Response) {
141
+ return this.created(res, req.body);
142
+ }
143
+ ```
144
+
145
+ If validation fails, the request short-circuits with a structured `VALIDATION_ERROR` payload and a 400 response.
146
+
147
+ ## Route uniqueness
148
+
149
+ `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.
150
+
151
+ ## Sample projects
152
+
153
+ - `examples/basic-todo` – minimal CRUD organised as `src/(controllers|services|domain)` (`node --loader ts-node/esm examples/basic-todo/index.ts`).
154
+ - `examples/medium-kanban` – workflow + metrics sample with the same structure (`node --loader ts-node/esm examples/medium-kanban/index.ts`).
155
+ - `examples/complex-analytics` – reactive event DB + aggregations with an additional `src/db/` layer (`node --loader ts-node/esm examples/complex-analytics/index.ts`).
156
+
157
+ Additional internal documentation describing the folder layout lives in `docs/structure.md`.
158
+
159
+ ## Development scripts
160
+
161
+ - `npm run dev` – run the sample app (`src/main.ts`) with hot reload
162
+ - `npm run build` – bundle library to `dist/`
163
+ - `npm run check` – type-check
164
+ - `npm test` – runs Vitest against the integration-style specs
165
+
166
+ ## CI & release pipeline
167
+
168
+ `.github/workflows/release.yml` performs type-checking, tests, and build on pushes to `main`. Publishing happens automatically when:
169
+
170
+ 1. A GitHub release is published, or
171
+ 2. The workflow is dispatched manually with `publish=true`.
172
+
173
+ Configure the `NPM_TOKEN` repository secret before triggering the publish job.
@@ -0,0 +1,248 @@
1
+ import { RequestHandler, Request, Response, NextFunction, Application } from 'express';
2
+ import { Server } from 'http';
3
+ import { Container, ServiceIdentifier } from 'inversify';
4
+
5
+ interface ControllerOptions {
6
+ path?: string;
7
+ autoRegister?: boolean;
8
+ tags?: string[];
9
+ }
10
+ type SchemaLike = {
11
+ safeParse?: (data: unknown) => {
12
+ success: boolean;
13
+ data?: unknown;
14
+ error?: unknown;
15
+ };
16
+ parse?: (data: unknown) => unknown;
17
+ validate?: (data: unknown, options?: Record<string, unknown>) => {
18
+ error?: {
19
+ details?: Array<{
20
+ message: string;
21
+ }>;
22
+ };
23
+ value: unknown;
24
+ };
25
+ };
26
+ interface RouteValidation {
27
+ params?: SchemaLike;
28
+ query?: SchemaLike;
29
+ body?: SchemaLike;
30
+ }
31
+ interface RouteOptions {
32
+ path?: string;
33
+ middlewares?: RequestHandler[];
34
+ validate?: RouteValidation;
35
+ }
36
+ type ControllerConstructor<T = unknown> = new (...args: never[]) => T;
37
+ declare function Controller(pathOrOptions?: string | ControllerOptions): <T extends ControllerConstructor>(target: T) => void;
38
+ declare function Get(path?: string | RouteOptions, ...middlewares: RequestHandler[]): (target: object, propertyKey: string | symbol) => void;
39
+ declare function Post(path?: string | RouteOptions, ...middlewares: RequestHandler[]): (target: object, propertyKey: string | symbol) => void;
40
+ declare function Put(path?: string | RouteOptions, ...middlewares: RequestHandler[]): (target: object, propertyKey: string | symbol) => void;
41
+ declare function Patch(path?: string | RouteOptions, ...middlewares: RequestHandler[]): (target: object, propertyKey: string | symbol) => void;
42
+ declare function Delete(path?: string | RouteOptions, ...middlewares: RequestHandler[]): (target: object, propertyKey: string | symbol) => void;
43
+ declare function listRegisteredControllers(): ControllerConstructor[];
44
+ declare function registerController(controller: ControllerConstructor): void;
45
+ declare function resetControllerRegistry(): void;
46
+
47
+ interface AppErrorOptions {
48
+ status?: number;
49
+ cause?: unknown;
50
+ details?: Record<string, unknown>;
51
+ }
52
+ declare class AppError extends Error {
53
+ readonly code: string;
54
+ readonly status?: number;
55
+ readonly details?: Record<string, unknown>;
56
+ constructor(code: string, message: string, options?: AppErrorOptions);
57
+ }
58
+ declare function createError(code: string, message: string, options?: AppErrorOptions): AppError;
59
+ declare function isAppError(error: unknown): error is AppError;
60
+
61
+ interface ReactiveChangeDetails<TState> {
62
+ property: keyof TState;
63
+ value: TState[keyof TState];
64
+ previous: TState[keyof TState];
65
+ timestamp: number;
66
+ }
67
+ type ReactiveWatcher<TState> = (state: TState, details: ReactiveChangeDetails<TState>) => void;
68
+ interface Reactive<TState> {
69
+ readonly id: string;
70
+ readonly label?: string;
71
+ state: TState;
72
+ watch(watcher: ReactiveWatcher<TState>): () => void;
73
+ snapshot(): TState;
74
+ history(): ReactiveChangeDetails<TState>[];
75
+ }
76
+ declare class ReactiveRegistry {
77
+ private readonly stores;
78
+ register<TState>(store: Reactive<TState>): void;
79
+ unregister(id: string): void;
80
+ get<TState>(id: string): Reactive<TState> | undefined;
81
+ list(): {
82
+ id: string;
83
+ label: string | undefined;
84
+ snapshot: unknown;
85
+ history: ReactiveChangeDetails<unknown>[];
86
+ }[];
87
+ }
88
+
89
+ declare const TYPES: {
90
+ readonly AppState: symbol;
91
+ readonly Config: symbol;
92
+ readonly Diagnostics: symbol;
93
+ readonly Logger: symbol;
94
+ readonly StateRegistry: symbol;
95
+ readonly RequestTracker: symbol;
96
+ };
97
+ interface AppState extends Record<string, unknown> {
98
+ bootedAt: number;
99
+ metadata: Record<string, unknown>;
100
+ }
101
+ interface RequestLogEntry {
102
+ timestamp: number;
103
+ level: 'debug' | 'info' | 'warn' | 'error';
104
+ message: string;
105
+ metadata?: Record<string, unknown>;
106
+ }
107
+ interface RequestState extends Record<string, unknown> {
108
+ id: string;
109
+ method: string;
110
+ path: string;
111
+ status?: number;
112
+ startedAt: number;
113
+ endedAt?: number;
114
+ durationMs?: number;
115
+ error?: string;
116
+ errorCode?: string;
117
+ response?: unknown;
118
+ logs: RequestLogEntry[];
119
+ metadata: Record<string, unknown>;
120
+ }
121
+
122
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
123
+ interface LoggerConfig {
124
+ level?: LogLevel;
125
+ }
126
+ interface AppLogger {
127
+ readonly level: LogLevel;
128
+ debug(message: string, metadata?: Record<string, unknown>): void;
129
+ info(message: string, metadata?: Record<string, unknown>): void;
130
+ warn(message: string, metadata?: Record<string, unknown>): void;
131
+ error(message: string, metadata?: Record<string, unknown>): void;
132
+ }
133
+
134
+ interface TelemetryConfig {
135
+ trackReactiveHistory?: boolean;
136
+ requestHistoryLimit?: number;
137
+ }
138
+ interface AppConfig {
139
+ prefix?: string;
140
+ healthEndpoint?: string | false;
141
+ logging?: LoggerConfig;
142
+ telemetry?: TelemetryConfig;
143
+ }
144
+ interface ResolvedAppConfig {
145
+ prefix: string;
146
+ healthEndpoint: string | false;
147
+ logging: Required<LoggerConfig>;
148
+ telemetry: Required<TelemetryConfig>;
149
+ }
150
+ declare function configureApp(config: AppConfig): void;
151
+ declare function getAppConfig(): ResolvedAppConfig;
152
+ declare function resolveConfig(overrides?: AppConfig): ResolvedAppConfig;
153
+ declare function resetAppConfig(): void;
154
+
155
+ declare module 'express-serve-static-core' {
156
+ interface Locals {
157
+ requestState?: Reactive<RequestState>;
158
+ }
159
+ }
160
+ declare class RequestTracker {
161
+ private readonly registry;
162
+ private readonly config;
163
+ private readonly logger;
164
+ constructor(registry: ReactiveRegistry, config: ResolvedAppConfig, logger: AppLogger);
165
+ middleware(): (req: Request, res: Response, next: NextFunction) => void;
166
+ get(res: Response): Reactive<RequestState> | undefined;
167
+ log(res: Response, message: string, level?: RequestLogEntry['level'], metadata?: Record<string, unknown>): void;
168
+ mergeMetadata(res: Response, patch: Record<string, unknown>): void;
169
+ recordResponse(res: Response, status: number, payload?: unknown): void;
170
+ recordError(res: Response, error: unknown): void;
171
+ private finalise;
172
+ private dispatchLog;
173
+ }
174
+
175
+ declare abstract class BaseController {
176
+ private readonly requestTracker;
177
+ protected constructor(requestTracker: RequestTracker);
178
+ protected abstract controllerId(): string;
179
+ protected ok<T>(res: Response, payload: T): Response<any, Record<string, any>>;
180
+ protected created<T>(res: Response, payload: T): Response<any, Record<string, any>>;
181
+ protected accepted<T>(res: Response, payload: T): Response<any, Record<string, any>>;
182
+ protected noContent(res: Response): Response<any, Record<string, any>>;
183
+ protected respond<T>(res: Response, status: number, payload?: T): Response<any, Record<string, any>>;
184
+ protected logDebug(res: Response, message: string, metadata?: Record<string, unknown>): void;
185
+ protected logInfo(res: Response, message: string, metadata?: Record<string, unknown>): void;
186
+ protected logWarn(res: Response, message: string, metadata?: Record<string, unknown>): void;
187
+ protected logError(res: Response, message: string, metadata?: Record<string, unknown>): void;
188
+ protected mergeRequestMetadata(res: Response, patch: Record<string, unknown>): void;
189
+ protected getRequestState(res: Response): RequestState | undefined;
190
+ protected fail(code: string, message: string, options?: AppErrorOptions): never;
191
+ }
192
+
193
+ interface StoreSnapshot {
194
+ id: string;
195
+ label?: string;
196
+ snapshot: Record<string, unknown>;
197
+ history: ReadonlyArray<unknown>;
198
+ }
199
+ interface RequestSnapshot extends RequestState {
200
+ }
201
+ declare class AppDiagnostics {
202
+ private readonly registry;
203
+ private readonly config;
204
+ constructor(registry: ReactiveRegistry, config: ResolvedAppConfig);
205
+ settings(): ResolvedAppConfig;
206
+ stores(): StoreSnapshot[];
207
+ requests(): RequestSnapshot[];
208
+ }
209
+
210
+ interface CreateAppOptions {
211
+ controllers?: Array<new (...args: never[]) => unknown>;
212
+ container?: Container;
213
+ additionalMiddleware?: Array<(req: Request, res: Response, next: NextFunction) => void>;
214
+ config?: AppConfig;
215
+ configureContainer?: (container: Container) => void;
216
+ }
217
+ interface CreateAppResult {
218
+ app: Application;
219
+ container: Container;
220
+ requestTracker: RequestTracker;
221
+ diagnostics: AppDiagnostics;
222
+ config: ResolvedAppConfig;
223
+ }
224
+ interface BootstrapOptions extends CreateAppOptions {
225
+ port?: number | string;
226
+ }
227
+ interface BootstrapContext {
228
+ app: Application;
229
+ server: Server;
230
+ container: Container;
231
+ requestTracker: RequestTracker;
232
+ diagnostics: AppDiagnostics;
233
+ config: ResolvedAppConfig;
234
+ shutdown(): void;
235
+ }
236
+ declare function createApp(options?: CreateAppOptions): CreateAppResult;
237
+ declare function bootstrap(options?: BootstrapOptions): Promise<BootstrapContext>;
238
+
239
+ type BindingIdentifier<T = unknown> = ServiceIdentifier<T>;
240
+ declare function Injectable(): ClassDecorator;
241
+ declare function Inject<T = unknown>(identifier: BindingIdentifier<T>): MethodDecorator & ParameterDecorator & PropertyDecorator;
242
+ declare function Optional(): MethodDecorator & ParameterDecorator & PropertyDecorator;
243
+ declare function MultiInject<T = unknown>(identifier: BindingIdentifier<T>): MethodDecorator & ParameterDecorator & PropertyDecorator;
244
+ declare function Named(name: string | number | symbol): MethodDecorator & ParameterDecorator & PropertyDecorator;
245
+ declare function Tagged(metadataKey: string | number | symbol, metadataValue: unknown): MethodDecorator & ParameterDecorator & PropertyDecorator;
246
+ declare function Unmanaged(): MethodDecorator & ParameterDecorator & PropertyDecorator;
247
+
248
+ export { type AppConfig, AppDiagnostics, AppError, type AppErrorOptions, type AppState, BaseController, type BindingIdentifier, type BootstrapContext, type BootstrapOptions, Controller, type ControllerConstructor, type CreateAppOptions, type CreateAppResult, Delete, Get, Inject, Injectable, MultiInject, Named, Optional, Patch, Post, Put, type RequestLogEntry, type RequestState, RequestTracker, type ResolvedAppConfig, type RouteOptions, type RouteValidation, TYPES, Tagged, Unmanaged, bootstrap, configureApp, createApp, createError, getAppConfig, isAppError, listRegisteredControllers, registerController, resetAppConfig, resetControllerRegistry, resolveConfig };