-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.d.ts
More file actions
1523 lines (1425 loc) · 42.1 KB
/
Copy pathindex.d.ts
File metadata and controls
1523 lines (1425 loc) · 42.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Configuration, Context, Workflow } from "@axiosleo/cli-tool";
import { EventEmitter } from "events";
import { IncomingHttpHeaders } from "http";
import * as Koa from "koa";
import * as session from "koa-session";
import * as KoaStaticServer from "koa-static-server";
import type { Socket } from "net";
import { Transform } from "stream";
import { ErrorMessages, Rules, Validator } from "validatorjs";
import type { ServerOptions, WebSocket } from "ws";
// ========================================
// Status Code Types
// ========================================
/**
* Predefined status codes with format "code;message"
* Used for standardized API responses
*/
type StatusCode =
| string
| "000;Unknown Error"
| "200;Success"
| "404;Not Found"
| "500;Internal Server Error"
| "400;Bad Data"
| "401;Unauthorized"
| "403;Not Authorized"
| "400;Invalid Signature"
| "501;Failed"
| "409;Data Already Exists";
// ========================================
// HTTP Method Types
// ========================================
/**
* HTTP methods supported by the framework
* Includes both uppercase and lowercase variants
*/
type HttpMethod =
| "ANY"
| "GET"
| "POST"
| "PUT"
| "DELETE"
| "PATCH"
| "HEAD"
| "OPTIONS"
| "TRACE"
| "CONNECT"
| "any"
| "get"
| "post"
| "put"
| "delete"
| "patch"
| "head"
| "options"
| "trace"
| "connect"
| string;
// ========================================
// Response Functions
// ========================================
/**
* Send a response with data, status code, and optional headers
* @template T Type of response data
* @param data Response data
* @param code Status code in format "code;message"
* @param httpStatus HTTP status code (default: 200)
* @param headers Optional response headers
*/
export function response<T = unknown>(
data: T,
code?: StatusCode,
httpStatus?: number,
headers?: Record<string, string>,
): never;
/**
* Send a result response with data and optional headers
* @template T Type of response data
* @param data Response data
* @param httpStatus HTTP status code (default: 200)
* @param headers Optional response headers
*/
export function result<T = unknown>(
data: T,
httpStatus?: number,
headers?: Record<string, string>,
): never;
/**
* Send a success response with optional data and headers
* @template T Type of response data
* @param data Optional response data
* @param headers Optional response headers
*/
export function success<T = unknown>(
data?: T,
headers?: Record<string, string>,
): never;
/**
* Send a failed response with error data and status
* @template T Type of response data
* @param data Error data
* @param code Status code in format "code;message"
* @param httpStatus HTTP status code (default: 500)
* @param headers Optional response headers
*/
export function failed<T = unknown>(
data?: T,
code?: StatusCode,
httpStatus?: number,
headers?: Record<string, string>,
): never;
/**
* Send an error response with HTTP status and message
* @param httpStatus HTTP status code
* @param msg Error message
* @param headers Optional response headers
*/
export function error(
httpStatus: number,
msg: string,
headers?: Record<string, string>,
): never;
// ========================================
// HTTP Response Classes
// ========================================
/**
* Configuration for HTTP response
*/
export interface HttpResponseConfig {
/** HTTP status code */
status?: number;
/** Response headers */
headers?: IncomingHttpHeaders;
/** Response data */
data?: unknown;
/** Response format */
format?: "json" | "text";
}
/**
* HTTP response class for structured responses
* Extends Error to work with error handling middleware
*/
export declare class HttpResponse extends Error {
public readonly status: number;
public readonly headers: IncomingHttpHeaders;
public readonly data: unknown;
constructor(config?: HttpResponseConfig);
}
/**
* HTTP error class for error responses
* Extends Error to work with error handling middleware
*/
export declare class HttpError extends Error {
public readonly status: number;
public readonly headers: IncomingHttpHeaders;
public readonly message: string;
constructor(
httpStatus: number,
message: string,
headers?: IncomingHttpHeaders,
);
}
// ========================================
// Controller Interface and Class
// ========================================
/**
* Interface defining controller response methods
*/
interface ControllerInterface {
response<T = unknown>(
data: T,
code?: StatusCode,
status?: number,
headers?: Record<string, string>,
): never;
result<T = unknown>(
data: T,
status?: number,
headers?: Record<string, string>,
): never;
success<T = unknown>(data?: T, headers?: Record<string, string>): never;
failed<T = unknown>(
data?: T,
code?: StatusCode,
status?: number,
headers?: Record<string, string>,
): never;
error(status: number, msg: string, headers?: Record<string, string>): never;
log(...data: any): void;
}
/**
* Base controller class providing response methods
* Implements standard response patterns for API endpoints
*/
export declare class Controller implements ControllerInterface {
response<T = unknown>(
data: T,
code?: StatusCode,
status?: number,
headers?: Record<string, string>,
): never;
result<T = unknown>(
data: T,
status?: number,
headers?: Record<string, string>,
): never;
success<T = unknown>(data?: T, headers?: Record<string, string>): never;
failed<T = unknown>(
data?: T,
code?: StatusCode,
status?: number,
headers?: Record<string, string>,
): never;
error(status: number, msg: string, headers?: Record<string, string>): never;
log(...data: any): void;
}
// ========================================
// Validation Types
// ========================================
/**
* Configuration for request validation
*/
interface ValidatorConfig {
/** Validation rules */
rules: Rules;
/** Custom error messages */
messages?: ErrorMessages;
}
/**
* Validators for different parts of the request
*/
interface RouterValidator {
/** Path parameter validation */
params?: ValidatorConfig;
/** Query parameter validation */
query?: ValidatorConfig;
/** Request body validation */
body?: ValidatorConfig;
}
// ========================================
// Router Types
// ========================================
/**
* Information about a matched route
* @template TParams Type of route parameters (defaults to Record<string, string>)
* @template TBody Type of request body (defaults to any)
* @template TQuery Type of query parameters (defaults to any)
* @template TContext Context type extending AppContext (defaults to KoaContext)
*
* @example
* ```typescript
* // RouterInfo with default KoaContext
* interface UserParams { id: string; action: 'view' | 'edit'; }
* interface UserBody { name: string; email: string; }
* interface UserQuery { include?: 'profile'; }
*
* type UserRouterInfo = RouterInfo<UserParams, UserBody, UserQuery>;
*
* // Can be used with any context type that extends AppContext
* const routerInfo: UserRouterInfo = {
* pathinfo: '/user/{:id}/{:action}',
* validators: {},
* middlewares: [], // ContextHandler<KoaContext<UserParams, UserBody, UserQuery>>[]
* handlers: [], // ContextHandler<KoaContext<UserParams, UserBody, UserQuery>>[]
* afters: [], // ContextHandler<KoaContext<UserParams, UserBody, UserQuery>>[]
* methods: ['POST', 'PUT'],
* params: { id: '123', action: 'edit' }
* };
* ```
*/
interface RouterInfo<
TParams = Record<string, string>,
TBody = any,
TQuery = any,
TContext extends AppContext<TParams, TBody, TQuery> = KoaContext<
TParams,
TBody,
TQuery
>,
> {
/** Route path pattern */
pathinfo: string;
/** Route validators */
validators: RouterValidator;
/** Middleware functions */
middlewares: ContextHandler<TContext>[];
/** Handler functions */
handlers: ContextHandler<TContext>[];
/** After middleware functions */
afters: ContextHandler<TContext>[];
/** Supported HTTP methods */
methods: string[];
/** Extracted path parameters */
params: TParams;
}
// ========================================
// Context Types
// ========================================
// ========================================
// Server-Sent Events Types
// ========================================
/**
* Server-sent event data structure
*/
interface IKoaSSEvent {
/** Event ID */
id?: number;
/** Event data */
data?: string | object;
/** Event type */
event?: string;
}
/**
* Server-sent events interface extending Transform stream
*/
interface IKoaSSE extends Transform {
/** Send SSE event */
send(data: IKoaSSEvent | string): void;
/** Send keep-alive ping */
keepAlive(): void;
/** Close SSE connection */
close(): void;
}
/**
* Base application context interface
* @template TParams Type of route parameters (defaults to Record<string, string>)
* @template TBody Type of request body (defaults to any)
* @template TQuery Type of query parameters (defaults to any)
*
* @example
* ```typescript
* // Basic usage with default types
* interface MyContext extends AppContext {}
*
* // Usage with specific types
* interface UserParams { id: string; action: 'view' | 'edit'; }
* interface UserBody { name: string; email: string; }
* interface UserQuery { include?: 'profile' | 'settings'; }
*
* interface UserContext extends AppContext<UserParams, UserBody, UserQuery> {}
*
* // In route handler
* const handler = async (context: UserContext) => {
* // context.router is now fully typed
* const routerParams = context.router.params; // UserParams
* const handlers = context.router.handlers; // ContextHandler<KoaContext<UserParams, UserBody, UserQuery>>[]
* };
* ```
*/
interface AppContext<
TParams = Record<string, string>,
TBody = any,
TQuery = any,
> extends Context {
app:
| KoaApplication
| SocketApplication
| WebSocketApplication
| Application
| null;
app_id: string;
method: string;
pathinfo: string;
request_id?: string;
router?: RouterInfo<TParams, TBody, TQuery, any> | null;
}
/**
* Koa-specific context extending AppContext
* @template TParams Type of route parameters (defaults to Record<string, string>)
* @template TBody Type of request body (defaults to any)
* @template TQuery Type of query parameters (defaults to any)
*
* @example
* ```typescript
* // Define specific parameter and body types
* interface ProductParams {
* id: string;
* category: string;
* }
*
* interface CreateProductBody {
* name: string;
* price: number;
* description?: string;
* tags?: string[];
* }
*
* interface ProductQuery {
* sort?: 'asc' | 'desc';
* limit?: number;
* include?: 'details' | 'reviews' | 'images';
* }
*
* // Create fully typed context
* type ProductContext = KoaContext<ProductParams, CreateProductBody, ProductQuery>;
*
* // Use in route handler with full type safety
* router.post('/product/{:id}/category/{:category}', async (context: ProductContext) => {
* // Full type safety for params
* const productId = context.params.id; // string
* const category = context.params.category; // string
*
* // Type-safe body access - TypeScript will enforce required fields
* const productName = context.body.name; // string
* const price = context.body.price; // number
* const desc = context.body.description; // string | undefined
* const tags = context.body.tags; // string[] | undefined
*
* // Type-safe query access
* const sortOrder = context.query.sort; // 'asc' | 'desc' | undefined
* const limit = context.query.limit; // number | undefined
* const include = context.query.include; // 'details' | 'reviews' | 'images' | undefined
*
* // TypeScript will catch type errors at compile time
* // const invalid = context.body.invalidField; // ❌ TypeScript error
* // const wrongType = context.query.sort === 'invalid'; // ❌ TypeScript error
* });
*
* // Partial typing - only specify what you need
* type SimpleContext = KoaContext<{}, CreateProductBody>; // Only body typed
* type ParamsOnlyContext = KoaContext<ProductParams>; // Only params typed
* type QueryOnlyContext = KoaContext<{}, any, ProductQuery>; // Only query typed
*
* // Real-world example: User management API
* interface UserParams { id: string; }
* interface UpdateUserBody {
* name?: string;
* email?: string;
* role?: 'admin' | 'user';
* }
* interface UserQuery {
* expand?: 'profile' | 'permissions';
* format?: 'json' | 'xml';
* }
*
* const userRouter = new Router<KoaContext<UserParams, UpdateUserBody, UserQuery>>();
*
* userRouter.put('/user/{:id}', async (context) => {
* // All properties are fully typed with IntelliSense support
* const userId = context.params.id;
* const updates = context.body; // UpdateUserBody
* const options = context.query; // UserQuery
*
* // Type-safe validation
* if (updates.role && !['admin', 'user'].includes(updates.role)) {
* // This would be caught at compile time due to literal types
* }
* });
* ```
*/
interface KoaContext<
TParams = Record<string, string>,
TBody = any,
TQuery = any,
> extends AppContext<TParams, TBody, TQuery> {
/** Application instance */
app: KoaApplication;
/** Route parameters */
params?: TParams;
/** Application configuration */
config?: AppConfiguration;
/** Koa context with optional SSE support */
koa: Koa.ParameterizedContext & { sse?: IKoaSSE };
/** Request URL */
url: string;
/** Request body */
body?: TBody;
/** Query parameters */
query?: TQuery;
/** Request headers */
headers?: IncomingHttpHeaders;
/** Response object */
response?: HttpResponse | HttpError;
}
/**
* Socket context extending AppContext
* @template TParams Type of route parameters (defaults to Record<string, string>)
* @template TBody Type of request body (defaults to any)
* @template TQuery Type of query parameters (defaults to any)
*
* @example
* ```typescript
* // Define socket-specific types
* interface SocketParams { room: string; userId: string; }
* interface SocketBody { message: string; type: 'text' | 'image'; }
* interface SocketQuery { token?: string; }
*
* type ChatContext = SocketContext<SocketParams, SocketBody, SocketQuery>;
*
* // Use in socket handler
* const socketHandler = async (context: ChatContext) => {
* // All properties are fully typed
* const room = context.params.room; // string
* const userId = context.params.userId; // string
* const message = context.body.message; // string
* const msgType = context.body.type; // 'text' | 'image'
* const token = context.query.token; // string | undefined
*
* // Router info is also typed
* const routerParams = context.router?.params; // SocketParams
* };
* ```
*/
export interface SocketContext<
TParams = Record<string, string>,
TBody = any,
TQuery = any,
> extends AppContext<TParams, TBody, TQuery> {
/** Application instance */
app: SocketApplication;
/** Connection ID */
connection_id: string;
/** Route parameters */
params?: TParams;
/** Application configuration */
config?: AppConfiguration;
/** Socket connection */
socket: Socket;
/** Request body */
body?: TBody;
/** Query parameters */
query?: TQuery;
/** Request headers */
headers?: IncomingHttpHeaders;
/** Response object */
response?: HttpResponse | HttpError;
}
/**
* WebSocket context extending AppContext
* @template TParams Type of route parameters (defaults to Record<string, string>)
* @template TBody Type of request body (defaults to any)
* @template TQuery Type of query parameters (defaults to any)
*
* @example
* ```typescript
* // Define WebSocket-specific types
* interface WSParams { roomId: string; }
* interface WSBody { content: string; type: 'text' | 'image'; }
* interface WSQuery { token: string; }
*
* type ChatContext = WebSocketContext<WSParams, WSBody, WSQuery>;
*
* // Use in WebSocket handler
* const wsHandler = async (context: ChatContext) => {
* const roomId = context.params.roomId; // string
* const content = context.body.content; // string
* const token = context.query.token; // string
*
* // Send raw data via WebSocket
* context.socket.send(JSON.stringify({ type: 'ack' }));
* };
* ```
*/
export interface WebSocketContext<
TParams = Record<string, string>,
TBody = any,
TQuery = any,
> extends AppContext<TParams, TBody, TQuery> {
/** Application instance */
app: WebSocketApplication;
/** Connection ID */
connection_id: string;
/** Route parameters */
params?: TParams;
/** Application configuration */
config?: AppConfiguration;
/** WebSocket connection */
socket: WebSocket;
/** Request body */
body?: TBody;
/** Query parameters */
query?: TQuery;
/** Request headers */
headers?: IncomingHttpHeaders;
/** Response object */
response?: HttpResponse | HttpError;
}
/**
* Interface for defining context data specification
* This allows flexible type configuration without order dependency
*/
interface ContextDataSpec<
TParams extends Record<string, string> = Record<string, string>,
TBody = any,
TQuery extends Record<string, string> = Record<string, string>,
> {
params?: TParams;
body?: TBody;
query?: TQuery;
}
/**
* Context type with all data properties required (params, body, query)
* @template TParams Type of route parameters
* @template TBody Type of request body
* @template TQuery Type of query parameters
*
* @example
* ```typescript
* // All properties are required
* type StrictContext = RequiredContext<
* { id: string }, // params
* { name: string }, // body
* { format: 'json' | 'xml' } // query
* >;
*
* // Usage in route handler
* router.post<StrictContext>('/users/{:id}', async (context) => {
* const id = context.params.id; // ✅ always available
* const name = context.body.name; // ✅ always available
* const format = context.query.format; // ✅ always available
* });
* ```
*/
export type RequiredContext<
TParams extends Record<string, string> = Record<string, string>,
TBody = any,
TQuery extends Record<string, string> = Record<string, string>,
> = AppContext<TParams, TBody, TQuery> & {
params: TParams;
body: TBody;
query: TQuery;
};
/**
* Object-style context type definition for flexible configuration
* @template T ContextDataSpec object with optional params, body, and query types
*
* @example
* ```typescript
* // Object-style usage - no order dependency, only specify what you need
* type UserContext = ContextFromSpec<{
* body: { name: string; email: string };
* params: { id: string };
* query: { format?: 'json' | 'xml' };
* }>;
*
* type ProductContext = ContextFromSpec<{
* query: { sort: 'asc' | 'desc' };
* body: { data: any };
* }>; // No params needed
*
* type SimpleContext = ContextFromSpec<{
* params: { userId: string };
* }>; // Only params needed
*
* // Usage
* router.put<UserContext>('/user/{:id}', async (context) => {
* const id = context.params.id; // ✅ always available
* const name = context.body.name; // ✅ always available
* const format = context.query.format; // ✅ always available
* });
* ```
*/
export type ContextFromSpec<T extends ContextDataSpec = ContextDataSpec> =
AppContext<
T["params"] extends Record<string, string>
? T["params"]
: Record<string, string>,
T["body"] extends undefined ? any : T["body"],
T["query"] extends Record<string, string>
? T["query"]
: Record<string, string>
> & {
params: T["params"] extends Record<string, string>
? T["params"]
: Record<string, string>;
body: T["body"] extends undefined ? any : T["body"];
query: T["query"] extends Record<string, string>
? T["query"]
: Record<string, string>;
};
/**
* Context handler function type
* @template T Context type extending AppContext
*
* @example
* ```typescript
* // Default usage (KoaContext)
* const handler: ContextHandler = async (context) => {
* // context is KoaContext by default
* const url = context.url; // Available
* const koa = context.koa; // Available
* };
*
* // Explicit KoaContext usage
* const koaHandler: ContextHandler<KoaContext> = async (context) => {
* const url = context.url; // Available
* const koa = context.koa; // Available
* };
*
* // SocketContext usage
* const socketHandler: ContextHandler<SocketContext> = async (context) => {
* const socket = context.socket; // Available
* };
*
* // Base AppContext usage
* const baseHandler: ContextHandler<AppContext> = async (context) => {
* const appId = context.app_id; // Available
* };
* ```
*/
type ContextHandler<T extends AppContext<any, any, any> = KoaContext> = (
context: T,
) => Promise<void>;
// ========================================
// Router Class
// ========================================
/**
* Router options for configuration
* @template T Context type extending AppContext
*
* @example
* ```typescript
* // RouterOptions now uses KoaContext by default
* interface UserParams { id: string; }
* interface UserBody { name: string; }
* interface UserQuery { format?: 'json' | 'xml'; }
*
* type UserContext = KoaContext<UserParams, UserBody, UserQuery>;
*
* const routerOptions: RouterOptions<UserContext> = {
* method: 'POST',
* middlewares: [
* async (context) => {
* // context is typed as UserContext
* console.log(`Processing user ${context.params?.id}`);
* console.log(`URL: ${context.url}`); // Available with KoaContext
* }
* ],
* handlers: [
* async (context) => {
* // Full type safety
* const userId = context.params?.id; // string | undefined
* const userName = context.body?.name; // string | undefined
* const format = context.query?.format; // 'json' | 'xml' | undefined
* const koaCtx = context.koa; // Available with KoaContext
* }
* ]
* };
* ```
*/
interface RouterOptions<T extends AppContext<any, any, any> = KoaContext> {
/** Default HTTP method */
method?: HttpMethod;
/** Route handlers */
handlers?: ContextHandler<T>[];
/** Middleware functions */
middlewares?: ContextHandler<T>[];
/** After middleware functions */
afters?: ContextHandler<T>[];
/** Route description */
intro?: string;
/** Sub-routers - can have different context types */
routers?: Router<AppContext<any, any, any>>[];
/** Route validators */
validators?: RouterValidator;
}
/**
* Router class for defining API routes and middleware
* @template T Context type extending AppContext (can be KoaContext, SocketContext, etc.)
*
* @example
* ```typescript
* // Basic router usage (uses KoaContext by default)
* const mainRouter = new Router();
*
* // Define different context types for different sub-routers
* interface UserParams { id: string; action: 'view' | 'edit' | 'delete'; }
* interface UserBody { name?: string; email?: string; age?: number; }
* interface UserQuery { include?: 'profile' | 'settings'; format?: 'json' | 'xml'; }
* type UserContext = KoaContext<UserParams, UserBody, UserQuery>;
*
* interface ProductParams { productId: string; }
* interface ProductBody { name: string; price: number; }
* interface ProductQuery { category?: string; }
* type ProductContext = KoaContext<ProductParams, ProductBody, ProductQuery>;
*
* // Create sub-routers with different context types
* const userRouter = new Router<UserContext>();
* const productRouter = new Router<ProductContext>();
*
* userRouter.post('/user/{:id}/{:action}', async (context) => {
* // context is typed as UserContext
* const userId = context.params?.id; // string | undefined
* const action = context.params?.action; // 'view' | 'edit' | 'delete' | undefined
* const userName = context.body?.name; // string | undefined
* const format = context.query?.format; // 'json' | 'xml' | undefined
* });
*
* productRouter.get('/product/{:productId}', async (context) => {
* // context is typed as ProductContext
* const productId = context.params?.productId; // string | undefined
* const category = context.query?.category; // string | undefined
* });
*
* // Add sub-routers with different context types to main router
* mainRouter.add('/api/v1', userRouter); // UserContext
* mainRouter.add('/api/v1', productRouter); // ProductContext
*
* // Or create sub-routers with different context types directly
* const adminRouter = mainRouter.new<AdminContext>('/admin', {
* middlewares: [authMiddleware]
* });
*
* // You can also add routes with different context types to the same router
* mainRouter.get<UserContext>('/profile/{:id}', async (context) => {
* const userId = context.params.id; // Typed as UserContext
* });
*
* mainRouter.post<ProductContext>('/products/{:productId}', async (context) => {
* const productId = context.params.productId; // Typed as ProductContext
* });
*
* // This flexibility allows different sub-routers to have their own context types
* // while being managed by the same parent router
* ```
*/
export class Router<T extends AppContext<any, any, any> = KoaContext> {
/** Route prefix */
prefix: string;
/** Default HTTP method */
method: HttpMethod;
/** Sub-routers - can have different context types as long as they extend AppContext */
routers: Router<AppContext<any, any, any>>[];
/** Route handlers */
handlers: ContextHandler<T>[];
/** Middleware functions */
middlewares: ContextHandler<T>[];
/** Route validators */
validators: RouterValidator;
/** After middleware functions */
afters?: ContextHandler<T>[];
constructor(prefix?: string, options?: RouterOptions<T>);
/**
* Add sub-routers to this router
* @template U Context type of the sub-router (can be different from parent)
*/
add<U extends AppContext<any, any, any>>(...router: Router<U>[]): this;
add<U extends AppContext<any, any, any>>(
prefix: string,
...router: Router<U>[]
): this;
/**
* Create a new sub-router with a different context type
* @template U Context type of the new sub-router (can be different from parent)
*/
new<U extends AppContext<any, any, any>>(
prefix: string,
options?: RouterOptions<U>,
): Router<U>;
/**
* Add a route with specific HTTP method
* @template U Context type for the route handler (can be different from router's context type)
*/
push<U extends AppContext<any, any, any> = T>(
method: HttpMethod,
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
/**
* Add a GET route
* @template U Context type for the route handler (can be different from router's context type)
*/
get<U extends AppContext<any, any, any> = T>(
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
/**
* Add a POST route
* @template U Context type for the route handler (can be different from router's context type)
*/
post<U extends AppContext<any, any, any> = T>(
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
/**
* Add a PUT route
* @template U Context type for the route handler (can be different from router's context type)
*/
put<U extends AppContext<any, any, any> = T>(
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
/**
* Add a PATCH route
* @template U Context type for the route handler (can be different from router's context type)
*/
patch<U extends AppContext<any, any, any> = T>(
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
/**
* Add a DELETE route
* @template U Context type for the route handler (can be different from router's context type)
*/
delete<U extends AppContext<any, any, any> = T>(
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
/**
* Add a route that accepts any HTTP method
* @template U Context type for the route handler (can be different from router's context type)
*/
any<U extends AppContext<any, any, any> = T>(
prefix: string,
handle: ContextHandler<U>,
validator?: RouterValidator,
): this;
}
// ========================================
// SSE Middleware Types
// ========================================
/**
* Options for Server-Sent Events middleware
*/
type SSEOptions = {
/** Ping interval in milliseconds (default: 60000) */
pingInterval?: number;
/** Event name for close event (default: 'close') */
closeEvent?: string;
};
/**
* SSE context handler function type
*/
type SSEContextHandler = (
context: Koa.ParameterizedContext,
next: () => Promise<void>,
) => Promise<void>;
/**
* Middleware namespace containing utility middleware functions
*/
export namespace middlewares {
/**
* Create Server-Sent Events middleware
* @param options SSE configuration options
* @returns SSE middleware function
*/
function KoaSSEMiddleware(options?: SSEOptions): SSEContextHandler;
}
// ========================================
// Application Configuration Types
// ========================================