API Reference
Types API Reference
Complete TypeScript type definitions for MoroJS. Build type-safe applications with full IntelliSense support and compile-time validation.
Core Types
Essential TypeScript interfaces and types for building MoroJS applications.
Application Typestypescript
1import type {
2 Moro,
3 MoroConfig,
4 MoroOptions,
5 RuntimeAdapter
6} from '@morojs/moro';
7
8// Main application interface
9interface Moro {
10 // HTTP methods. Called with a path only, they return a chainable route
11 // builder; called with a handler, they register the route directly.
12 get(path: string): UnifiedRouteBuilder;
13 get(path: string, handler: RouteHandler, options?: RouteOptions): this;
14 post(path: string): UnifiedRouteBuilder;
15 post(path: string, handler: RouteHandler, options?: RouteOptions): this;
16 put(path: string): UnifiedRouteBuilder;
17 put(path: string, handler: RouteHandler, options?: RouteOptions): this;
18 delete(path: string): UnifiedRouteBuilder;
19 delete(path: string, handler: RouteHandler, options?: RouteOptions): this;
20 patch(path: string): UnifiedRouteBuilder;
21 patch(path: string, handler: RouteHandler, options?: RouteOptions): this;
22
23 // Schema-first registration
24 route(schema: RouteSchema): void;
25
26 // Application methods
27 use(...middleware: MiddlewareFunction[]): void;
28 group(prefix: string, callback: (group: Moro) => void): void;
29 listen(port: number, host?: string, callback?: () => void): void;
30 close(): Promise<void>;
31
32 // Configuration
33 configure(config: Partial<MoroConfig>): void;
34 getConfig(): MoroConfig;
35 getConfig<K extends keyof MoroConfig>(key: K): MoroConfig[K];
36
37 // Environment
38 env(): Record<string, string>;
39 env<T = Record<string, string>>(): T;
40 env(key: string): string | undefined;
41 env(schema: EnvSchema): void;
42}
43
44// Configuration interface
45interface MoroConfig {
46 server?: ServerConfig;
47 security?: SecurityConfig;
48 database?: DatabaseConfig;
49 logging?: LoggingConfig;
50 features?: FeaturesConfig;
51}
52
53// Runtime adapter interface
54interface RuntimeAdapter {
55 name: 'node' | 'edge' | 'lambda' | 'worker';
56 createHandler(app: Moro): any;
57 transformRequest(request: any): Request;
58 transformResponse(response: Response): any;
59}Request/Response Types
Handler and Context Typestypescript
1// Route handler function type
2type RouteHandler<T = any> = (context: RequestContext) => T | Promise<T>;
3
4// Request context interface
5interface RequestContext {
6 // HTTP primitives
7 request: Request;
8 response: Response;
9
10 // Parsed request data
11 params: Record<string, string>;
12 query: Record<string, string | string[]>;
13 headers: Record<string, string>;
14 body: any;
15
16 // Request metadata
17 ip: string;
18 userAgent: string;
19 method: HttpMethod;
20 url: string;
21 path: string;
22
23 // Shared context for middleware communication
24 context: Record<string, any>;
25
26 // Response builders
27 json(data: any, status?: number): Response;
28 text(data: string, status?: number): Response;
29 html(data: string, status?: number): Response;
30 status(code: number): ResponseBuilder;
31 redirect(url: string, status?: number): Response;
32
33 // Context utilities
34 set(key: string, value: any): void;
35 get(key: string): any;
36 has(key: string): boolean;
37 delete(key: string): void;
38}
39
40// Response builder interface
41interface ResponseBuilder {
42 json(data: any): Response;
43 text(data: string): Response;
44 html(data: string): Response;
45 send(data: any): Response;
46 end(): Response;
47 header(name: string, value: string): ResponseBuilder;
48 headers(headers: Record<string, string>): ResponseBuilder;
49 cookie(name: string, value: string, options?: CookieOptions): ResponseBuilder;
50}
51
52// HTTP method type
53type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
54
55// Cookie options
56interface CookieOptions {
57 domain?: string;
58 expires?: Date;
59 httpOnly?: boolean;
60 maxAge?: number;
61 path?: string;
62 secure?: boolean;
63 signed?: boolean;
64 sameSite?: boolean | 'lax' | 'strict' | 'none';
65}Route Configuration Types
Route Configuration Interfacetypescript
1// The chainable route builder returned by app.get('/path') etc.
2// Every method returns the builder, so calls chain in any order -
3// execution order is fixed by the pipeline, not by chain order.
4interface UnifiedRouteBuilder {
5 // Validation
6 body(schema: ValidationSchema): this;
7 query(schema: ValidationSchema): this;
8 params(schema: ValidationSchema): this;
9 headers(schema: ValidationSchema): this;
10 validate(config: ValidationConfig): this;
11
12 // Route features
13 auth(config: AuthConfig): this;
14 rateLimit(config: RateLimitConfig): this;
15 cache(config: CacheConfig): this;
16
17 // Custom middleware, by phase
18 before(...middleware: Middleware[]): this;
19 transform(...middleware: Middleware[]): this;
20 after(...middleware: Middleware[]): this;
21 use(...middleware: Middleware[]): this; // alias for after()
22
23 // Metadata
24 describe(description: string): this;
25 tag(...tags: string[]): this;
26
27 // Terminal - registers the route
28 handler(fn: RouteHandler): void;
29}
30
31// Options accepted by the direct form: app.get(path, handler, options)
32interface RouteOptions {
33 middleware?: Middleware[];
34 validation?: ValidationConfig;
35 rateLimit?: RateLimitConfig;
36 cache?: CacheConfig;
37}
38
39// The schema behind app.route({ ... }) and the chainable builder.
40// Chainable calls populate exactly these fields.
41interface RouteSchema {
42 method: HttpMethod;
43 path: string;
44 handler: RouteHandler;
45
46 validation?: ValidationConfig; // .body() / .query() / .params() / .headers() / .validate()
47 auth?: AuthConfig; // .auth()
48 rateLimit?: RateLimitConfig; // .rateLimit()
49 cache?: CacheConfig; // .cache()
50 middleware?: MiddlewarePhases; // .before() / .transform() / .after() / .use()
51 description?: string; // .describe()
52 tags?: string[]; // .tag()
53}
54
55interface ValidationConfig {
56 body?: ValidationSchema;
57 query?: ValidationSchema;
58 params?: ValidationSchema;
59 headers?: ValidationSchema;
60 // Shapes the 4xx when a schema rejects the request. Route-level handler
61 // wins over the global one passed to createApp().
62 onValidationError?: (
63 errors: ValidationErrorDetail[],
64 context: ValidationErrorContext
65 ) => ValidationErrorResponse;
66}
67
68interface AuthConfig {
69 roles?: string[];
70 permissions?: string[];
71 optional?: boolean;
72}
73
74interface RateLimitConfig {
75 requests: number; // allowed requests per window
76 window: number; // window length in milliseconds
77 skipSuccessfulRequests?: boolean;
78}
79
80interface CacheConfig {
81 ttl: number; // SECONDS (note: rateLimit.window is milliseconds)
82 key?: string; // static cache key (not a function)
83 tags?: string[];
84}
85
86// Custom middleware is placed by phase, then runs in declaration order
87// within that phase.
88interface MiddlewarePhases {
89 before?: Middleware[]; // ahead of rate limiting and auth
90 transform?: Middleware[]; // after validation, before the cache check
91 after?: Middleware[]; // just before the handler (.use() lands here)
92}
93
94interface ValidationErrorDetail {
95 field: string;
96 message: string;
97 code?: string;
98 value?: any;
99 path?: (string | number)[];
100}
101
102interface ValidationErrorResponse {
103 status: number;
104 body: any;
105 headers?: Record<string, string>;
106}
107
108type ValidationSchema = z.ZodSchema<any>;Middleware Types
Middleware Function Typestypescript
1// Middleware function type
2type MiddlewareFunction = (
3 context: RequestContext,
4 next: NextFunction
5) => void | Promise<void>;
6
7// Next function type
8type NextFunction = () => void | Promise<void>;
9
10// Middleware factory type (for configurable middleware)
11type MiddlewareFactory<T = any> = (options?: T) => MiddlewareFunction;
12
13// Built-in middleware options
14interface CorsOptions {
15 origin?: string | string[] | ((origin: string) => boolean);
16 methods?: string[];
17 allowedHeaders?: string[];
18 exposedHeaders?: string[];
19 credentials?: boolean;
20 maxAge?: number;
21 preflightContinue?: boolean;
22 optionsSuccessStatus?: number;
23}
24
25interface RateLimitOptions {
26 requests?: number; // or max
27 max?: number;
28 window?: number; // milliseconds; or windowMs
29 windowMs?: number;
30 message?: string;
31 statusCode?: number; // default 429
32 skipSuccessfulRequests?: boolean;
33 skipFailedRequests?: boolean;
34}
35
36interface HelmetOptions {
37 contentSecurityPolicy?: {
38 directives?: Record<string, string[]>;
39 reportOnly?: boolean;
40 };
41 crossOriginEmbedderPolicy?: boolean;
42 crossOriginOpenerPolicy?: boolean;
43 crossOriginResourcePolicy?: { policy: 'same-site' | 'same-origin' | 'cross-origin' };
44 dnsPrefetchControl?: boolean;
45 frameguard?: { action: 'deny' | 'sameorigin' };
46 hidePoweredBy?: boolean;
47 hsts?: {
48 maxAge?: number;
49 includeSubDomains?: boolean;
50 preload?: boolean;
51 };
52 ieNoOpen?: boolean;
53 noSniff?: boolean;
54 originAgentCluster?: boolean;
55 permittedCrossDomainPolicies?: boolean;
56 referrerPolicy?: string;
57 xssFilter?: boolean;
58}
59
60// Rate limit store interface
61interface RateLimitStore {
62 get(key: string): Promise<number | null>;
63 set(key: string, value: number, ttl: number): Promise<void>;
64 increment(key: string, ttl: number): Promise<number>;
65 reset(key: string): Promise<void>;
66}Configuration Types
Configuration Interfacestypescript
1// Server configuration
2interface ServerConfig {
3 port?: number;
4 host?: string;
5 environment?: 'development' | 'staging' | 'production';
6 gracefulShutdown?: {
7 timeout?: number;
8 signals?: string[];
9 };
10 keepAlive?: boolean;
11 bodyLimit?: string;
12}
13
14// Security configuration
15interface SecurityConfig {
16 cors?: CorsOptions;
17 helmet?: HelmetOptions;
18 rateLimit?: {
19 global?: RateLimitOptions;
20 api?: RateLimitOptions;
21 };
22 csrf?: {
23 enabled?: boolean;
24 secret?: string;
25 cookie?: CookieOptions;
26 };
27}
28
29// Database configuration
30interface DatabaseConfig {
31 default?: {
32 type?: 'postgresql' | 'mysql' | 'sqlite' | 'mongodb';
33 url?: string;
34 pool?: {
35 min?: number;
36 max?: number;
37 acquireTimeoutMillis?: number;
38 idleTimeoutMillis?: number;
39 createTimeoutMillis?: number;
40 };
41 migrations?: {
42 directory?: string;
43 autoRun?: boolean;
44 table?: string;
45 };
46 ssl?: boolean | {
47 rejectUnauthorized?: boolean;
48 ca?: string;
49 key?: string;
50 cert?: string;
51 };
52 };
53 cache?: {
54 type?: 'redis' | 'memory' | 'file';
55 url?: string;
56 ttl?: string;
57 prefix?: string;
58 maxSize?: number;
59 };
60}
61
62// Logging configuration
63interface LoggingConfig {
64 level?: 'debug' | 'info' | 'warn' | 'error';
65 format?: 'json' | 'pretty';
66 destinations?: Array<{
67 type: 'console' | 'file' | 'http';
68 path?: string;
69 url?: string;
70 level?: string;
71 }>;
72 requestLogging?: {
73 enabled?: boolean;
74 skipHealthChecks?: boolean;
75 skipPaths?: string[];
76 format?: string;
77 };
78}
79
80// Features configuration
81interface FeaturesConfig {
82 websockets?: boolean | {
83 enabled?: boolean;
84 path?: string;
85 cors?: CorsOptions;
86 };
87 fileUploads?: {
88 enabled?: boolean;
89 maxSize?: string;
90 allowedTypes?: string[];
91 destination?: string;
92 };
93 apiDocs?: {
94 enabled?: boolean;
95 path?: string;
96 title?: string;
97 version?: string;
98 description?: string;
99 };
100 clustering?: {
101 enabled?: boolean;
102 workers?: number;
103 };
104}
105
106// Environment schema
107interface EnvSchema {
108 [key: string]: {
109 required?: boolean;
110 type?: 'string' | 'number' | 'boolean';
111 default?: any;
112 enum?: string[];
113 minLength?: number;
114 maxLength?: number;
115 min?: number;
116 max?: number;
117 };
118}Utility Types
Helper Types and Utilitiestypescript
1// Generic utility types
2type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
3type Required<T, K extends keyof T> = T & Required<Pick<T, K>>;
4
5// Route parameter extraction
6type ExtractParams<T extends string> = T extends `${infer Start}:${infer Param}/${infer Rest}`
7 ? { [K in Param]: string } & ExtractParams<Rest>
8 : T extends `${infer Start}:${infer Param}`
9 ? { [K in Param]: string }
10 : {};
11
12// Type-safe route handler with parameter inference
13type TypedRouteHandler<TPath extends string, TBody = any, TResponse = any> = (
14 context: RequestContext & {
15 params: ExtractParams<TPath>;
16 body: TBody;
17 }
18) => TResponse | Promise<TResponse>;
19
20// WebSocket types
21interface WebSocketConnection {
22 id: string;
23 send(data: any): void;
24 close(code?: number, reason?: string): void;
25 ping(data?: Buffer): void;
26 pong(data?: Buffer): void;
27 on(event: 'message' | 'close' | 'error' | 'ping' | 'pong', handler: Function): void;
28 off(event: string, handler: Function): void;
29}
30
31interface WebSocketManager {
32 connections: Map<string, WebSocketConnection>;
33 broadcast(data: any, filter?: (connection: WebSocketConnection) => boolean): void;
34 getConnection(id: string): WebSocketConnection | undefined;
35 closeConnection(id: string): void;
36 closeAll(): void;
37}
38
39// Event system types
40interface EventBus {
41 emit(event: string, data?: any): void;
42 on(event: string, handler: (data: any) => void): void;
43 off(event: string, handler: (data: any) => void): void;
44 once(event: string, handler: (data: any) => void): void;
45 removeAllListeners(event?: string): void;
46}
47
48// Cache types
49interface CacheStore {
50 get<T = any>(key: string): Promise<T | null>;
51 set<T = any>(key: string, value: T, options?: { ttl?: string | number }): Promise<void>;
52 delete(key: string): Promise<boolean>;
53 clear(): Promise<void>;
54 has(key: string): Promise<boolean>;
55 keys(pattern?: string): Promise<string[]>;
56}
57
58// Logger types
59interface Logger {
60 debug(message: string, meta?: any): void;
61 info(message: string, meta?: any): void;
62 warn(message: string, meta?: any): void;
63 error(message: string, meta?: any): void;
64 child(meta: any): Logger;
65}Type Safety Benefits
- Full IntelliSense and autocomplete support
- Compile-time type checking for routes and handlers
- Automatic parameter type inference from route paths
- Schema-based request/response validation
- Type-safe configuration and environment variables