balda-js 0.0.2 → 0.0.3

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/lib/index.d.cts DELETED
@@ -1,1492 +0,0 @@
1
- import { TSchema } from '@sinclair/typebox/type';
2
- import { TSchema as TSchema$1, Type, Static } from '@sinclair/typebox';
3
- import { IncomingMessage, Server as Server$1 } from 'node:http';
4
- import { pino } from 'pino';
5
- import nodeCron, { TaskContext } from 'node-cron';
6
-
7
- /**
8
- * Type of Swagger UI to use
9
- */
10
- type SwaggerUIType = "standard" | "redoc" | "rapidoc";
11
- /**
12
- * Type of request body for a route
13
- */
14
- type SwaggerBodyType = "json" | "form-data" | "urlencoded";
15
- /**
16
- * JSONSchema type for OpenAPI/AJV-compatible schemas
17
- */
18
- type JSONSchema = {
19
- $id?: string;
20
- $schema?: string;
21
- type?: string | string[];
22
- properties?: Record<string, JSONSchema>;
23
- items?: JSONSchema | JSONSchema[];
24
- required?: string[];
25
- enum?: any[];
26
- allOf?: JSONSchema[];
27
- oneOf?: JSONSchema[];
28
- anyOf?: JSONSchema[];
29
- not?: JSONSchema;
30
- additionalProperties?: boolean | JSONSchema;
31
- description?: string;
32
- format?: string;
33
- default?: any;
34
- title?: string;
35
- definitions?: Record<string, JSONSchema>;
36
- [key: string]: any;
37
- };
38
- /**
39
- * Global documentation options for the API (OpenAPI/Swagger style)
40
- */
41
- type SwaggerGlobalOptions = {
42
- /** The path to the swagger documentation, defaults to /docs for the UI and /docs/json for the raw json */
43
- path?: string;
44
- /** Type of Swagger UI to use, one of 'standard', 'redoc', or 'rapidoc'. Defaults to 'standard'. */
45
- type?: SwaggerUIType;
46
- /** API title */
47
- title?: string;
48
- /** API description */
49
- description?: string;
50
- /** API version */
51
- version?: string;
52
- /** Server URLs */
53
- servers?: string[];
54
- /** Components (schemas, responses, parameters, etc.) */
55
- components?: Record<string, any>;
56
- /** Security schemes (OpenAPI 3.0 style) */
57
- securitySchemes?: Record<string, Security>;
58
- /** OpenID Connect configuration (discovery document) */
59
- openIdConnect?: OpenIDConnectConfig;
60
- /** API tags */
61
- tags?: Record<string, any>;
62
- /** Global security requirements */
63
- security?: Security[];
64
- /** External documentation */
65
- externalDocs?: {
66
- description?: string;
67
- url: string;
68
- };
69
- /** Info object (detailed metadata) */
70
- info?: {
71
- title: string;
72
- description?: string;
73
- version: string;
74
- termsOfService?: string;
75
- contact?: {
76
- name?: string;
77
- url?: string;
78
- email?: string;
79
- };
80
- license?: {
81
- name: string;
82
- url?: string;
83
- };
84
- };
85
- /**
86
- * OpenAPI models to be shown in the documentation. Must be valid OpenAPI/AJV JSONSchema objects.
87
- */
88
- models?: Record<string, JSONSchema>;
89
- };
90
- /**
91
- * Route-specific documentation options (for individual endpoints)
92
- */
93
- type SwaggerRouteOptions = {
94
- /** Service category where the route belongs to */
95
- service?: string;
96
- /** Name of the route */
97
- name?: string;
98
- /** Query parameters schema */
99
- query?: TSchema;
100
- /** Request body schema */
101
- requestBody?: TSchema;
102
- /** Responses for this route */
103
- responses?: Record<number, TSchema>;
104
- /** Errors for this route */
105
- errors?: Record<number, TSchema>;
106
- /** Security requirements for this route */
107
- security?: Security[] | Security;
108
- /** Description of the route */
109
- description?: string;
110
- /** Deprecated flag */
111
- deprecated?: boolean;
112
- /** Exclude from swagger */
113
- excludeFromSwagger?: boolean;
114
- /**
115
- * The request body type for this route. Allowed values: 'json', 'form-data', 'urlencoded'. Defaults to 'json'.
116
- */
117
- bodyType?: SwaggerBodyType;
118
- };
119
- type OAuth2Flows = {
120
- implicit?: OAuth2Flow;
121
- authorizationCode?: OAuth2Flow;
122
- clientCredentials?: OAuth2Flow;
123
- password?: OAuth2Flow;
124
- };
125
- type OAuth2Flow = {
126
- authorizationUrl?: string;
127
- tokenUrl?: string;
128
- refreshUrl?: string;
129
- scopes: Record<string, string>;
130
- };
131
- type OpenIDConnectConfig = {
132
- issuer: string;
133
- authorizationEndpoint: string;
134
- tokenEndpoint: string;
135
- userinfoEndpoint?: string;
136
- jwksUri: string;
137
- endSessionEndpoint?: string;
138
- introspectionEndpoint?: string;
139
- revocationEndpoint?: string;
140
- scopesSupported?: string[];
141
- responseTypesSupported?: string[];
142
- grantTypesSupported?: string[];
143
- tokenEndpointAuthMethodsSupported?: string[];
144
- subjectTypesSupported?: string[];
145
- idTokenSigningAlgValuesSupported?: string[];
146
- claimsSupported?: string[];
147
- codeChallengeMethodsSupported?: string[];
148
- };
149
- type Security = BearerOptions | ApiKeyOptions | OAuth2Options | OpenIdConnectOptions;
150
- type BearerOptions = {
151
- type: "bearer";
152
- bearerFormat?: string;
153
- description?: string;
154
- };
155
- type ApiKeyOptions = {
156
- type: "apiKey";
157
- name: string;
158
- in: "header" | "query" | "cookie";
159
- description?: string;
160
- };
161
- type OAuth2Options = {
162
- type: "oauth2";
163
- flows: OAuth2Flows;
164
- description?: string;
165
- name?: string;
166
- };
167
- type OpenIdConnectOptions = {
168
- type: "openIdConnect";
169
- openIdConnectUrl: string;
170
- description?: string;
171
- name?: string;
172
- };
173
-
174
- /**
175
- * Decorator to mark a class as a controller, routes defined in the controller will be registered at import time when calling the `listen` method.
176
- * You can customize the path pattern for controller imports in the server options `controllerPatterns`
177
- * @param path - The path pattern for the controller.
178
- * @param swaggerOptions - The swagger options for the controller that will be applied to all routes defined in the controller. Controller options will override route options.
179
- * @swagger If swagger is enabled, the default service name for all routes defined in the controller will be the controller name.
180
- * @swagger For naming commodity, the default service name will remove the "Controller" suffix if it exists. e.g. "UserController" -> "User"
181
- */
182
- declare const controller: (path?: string, swaggerOptions?: SwaggerRouteOptions) => (target: any) => void;
183
-
184
- type FormFile = {
185
- /**
186
- * The name of the form field.
187
- */
188
- formName: string;
189
- /**
190
- * The mime type of the file. (e.g. "image/png")
191
- */
192
- mimeType: string;
193
- /**
194
- * The size of the file in bytes.
195
- */
196
- size: number;
197
- /**
198
- * The temporary path of the file. Will be deleted after the request is processed automatically even in error cases.
199
- */
200
- tmpPath: string;
201
- /**
202
- * The original filename (including extension) as sent by the client
203
- * (e.g. "avatar.png", "document.txt").
204
- */
205
- originalName: string;
206
- };
207
- type FilePluginOptions = {
208
- /**
209
- * The maximum size of the file in bytes.
210
- */
211
- maxFileSize?: number;
212
- };
213
-
214
- declare global {
215
- interface Request {
216
- params: Record<string, string>;
217
- query: Record<string, string>;
218
- }
219
- }
220
- declare class NativeRequest extends Request {
221
- }
222
-
223
- /**
224
- * The request object.
225
- * This is the main object that is passed to the handler function.
226
- * It contains the request body, query parameters, files, cookies, etc.
227
- * It also contains the validation methods.
228
- */
229
- declare class Request$1 extends NativeRequest {
230
- static fromRequest(request: Request$1 | NativeRequest): Request$1;
231
- /**
232
- * Enrich native request with validation methods.
233
- */
234
- static enrichRequest(request: Request$1): Request$1;
235
- /**
236
- * The file of the request. Only available for multipart/form-data requests and if the file parser middleware is used.
237
- */
238
- file: (fieldName: string) => FormFile | null;
239
- /**
240
- * The cookies of the request. Only available if the cookie middleware is used.
241
- */
242
- cookies: Record<string, string>;
243
- /**
244
- * The cookie of the request. Only available if the cookie middleware is used.
245
- */
246
- cookie: (name: string) => string | undefined;
247
- /**
248
- * The ip address of the request.
249
- * Tries to get the ip address from the `x-forwarded-for` header. If not available, it will use the remote address from the request.
250
- */
251
- ip?: string;
252
- /**
253
- * The files of the request. Only available for multipart/form-data requests and if the file parser middleware is used.
254
- */
255
- files: FormFile[];
256
- /**
257
- * The parameters of the request.
258
- */
259
- params: Record<string, string>;
260
- /**
261
- * The query parameters of the request.
262
- */
263
- query: Record<string, string>;
264
- /**
265
- * The raw body of the request. Only available for POST, PUT, PATCH and DELETE requests.
266
- */
267
- rawBody?: ArrayBuffer;
268
- private _id;
269
- /**
270
- * The id of the request.
271
- */
272
- get id(): string;
273
- /**
274
- * The parsed body of the request
275
- */
276
- body: any;
277
- /**
278
- * The validated body of the request.
279
- * @param inputSchema - The schema to validate the body against.
280
- * @param safe - If true, the function will return the original body if the validation fails instead of throwing an error.
281
- */
282
- validate<T extends TSchema$1>(inputSchema: T | ((schema: typeof Type) => T), safe?: boolean): Static<T>;
283
- /**
284
- * Validates the query string of the request.
285
- */
286
- validateQuery<T extends TSchema$1>(inputSchema: T | ((schema: typeof Type) => T), safe?: boolean): Static<T>;
287
- /**
288
- * Validates the body and query string of the request.
289
- */
290
- validateAll<T extends TSchema$1>(inputSchema: T | ((schema: typeof Type) => T), safe?: boolean): Static<T>;
291
- }
292
-
293
- /**
294
- * Cookie options for setting cookies
295
- */
296
- type CookieOptions = {
297
- /**
298
- * Domain for the cookie
299
- */
300
- domain?: string;
301
- /**
302
- * Path for the cookie
303
- */
304
- path?: string;
305
- /**
306
- * Expiration date for the cookie
307
- */
308
- expires?: Date;
309
- /**
310
- * Max age in seconds for the cookie
311
- */
312
- maxAge?: number;
313
- /**
314
- * Whether the cookie is secure (HTTPS only)
315
- */
316
- secure?: boolean;
317
- /**
318
- * Whether the cookie is HTTP only
319
- */
320
- httpOnly?: boolean;
321
- /**
322
- * SameSite attribute for the cookie
323
- */
324
- sameSite?: "Strict" | "Lax" | "None";
325
- /**
326
- * Whether the cookie should be signed
327
- */
328
- signed?: boolean;
329
- /**
330
- * Priority for the cookie
331
- */
332
- priority?: "Low" | "Medium" | "High";
333
- };
334
- /**
335
- * Options for the cookie middleware
336
- */
337
- type CookieMiddlewareOptions = {
338
- /**
339
- * Secret key for signing cookies (required if using signed cookies)
340
- */
341
- secret?: string;
342
- /**
343
- * Default options for all cookies set by this middleware
344
- */
345
- defaults?: CookieOptions;
346
- /**
347
- * Whether to enable cookie parsing (defaults to true)
348
- */
349
- parse?: boolean;
350
- /**
351
- * Whether to enable cookie signing (defaults to false)
352
- */
353
- sign?: boolean;
354
- };
355
-
356
- /**
357
- * The response object.
358
- * This is the main object that is passed to the handler function.
359
- * It contains the response body, status, headers, etc.
360
- * It also contains the methods to send the response.
361
- */
362
- declare class Response {
363
- /**
364
- * The status of the response
365
- */
366
- responseStatus: number;
367
- /**
368
- * The headers of the response
369
- */
370
- headers: Record<string, string>;
371
- /**
372
- * The body of the response
373
- */
374
- private body;
375
- constructor(status?: number);
376
- /**
377
- * Set a header for the response
378
- */
379
- setHeader(key: string, value: string): this;
380
- /**
381
- * Set the status of the response, status defaults to 200
382
- */
383
- status(status: number): this;
384
- /**
385
- * Send a response with the given body, tries to determine the content type based on the body type, status defaults to 200
386
- * @warning If cannot determine the content type, it will be sent as is
387
- */
388
- send(body: any): void;
389
- /**
390
- * Send a response with the given body without any content type or encoding (as is), status defaults to 200
391
- */
392
- raw(body: any): void;
393
- /**
394
- * Send a response with the given text, status defaults to 200
395
- */
396
- text(body: string): void;
397
- /**
398
- * Send a response with the given JSON, status defaults to 200
399
- */
400
- json<T extends Record<string, unknown> | Array<unknown>>(body: T): void;
401
- /**
402
- * Send a response with the given HTML, status defaults to 200
403
- */
404
- html(body: string): void;
405
- /**
406
- * Send a response with the given XML, status defaults to 200
407
- */
408
- xml(body: string): void;
409
- /**
410
- * Send a response with the given binary with Content-Type of application/octet-stream header, status defaults to 200
411
- */
412
- download(body: Uint8Array): void;
413
- /**
414
- * Send a response with the given file, status defaults to 200
415
- */
416
- file(pathToFile: string): void;
417
- /**
418
- * 2XX Success
419
- */
420
- /**
421
- * 200 OK
422
- */
423
- ok(body?: any): void;
424
- /**
425
- * 201 Created
426
- */
427
- created(body?: any): void;
428
- /**
429
- * 202 Accepted
430
- */
431
- accepted(body?: any): void;
432
- /**
433
- * 204 No Content
434
- */
435
- noContent(): void;
436
- /**
437
- * 206 Partial Content
438
- */
439
- partialContent(body?: any): void;
440
- /**
441
- * 3XX Redirection
442
- */
443
- /**
444
- * 300 Multiple Choices
445
- */
446
- multipleChoices(url: string): void;
447
- redirect(url: string): void;
448
- /**
449
- * 301 Moved Permanently
450
- */
451
- movedPermanently(url: string): void;
452
- /**
453
- * 302 Found (Temporary Redirect)
454
- */
455
- found(url: string): void;
456
- /**
457
- * 303 See Other
458
- */
459
- seeOther(url: string): void;
460
- /**
461
- * 304 Not Modified
462
- */
463
- notModified(): void;
464
- /**
465
- * 307 Temporary Redirect
466
- */
467
- temporaryRedirect(url: string): void;
468
- /**
469
- * 308 Permanent Redirect
470
- */
471
- permanentRedirect(url: string): void;
472
- /**
473
- * 4XX Client Errors
474
- */
475
- /**
476
- * 400 Bad Request
477
- */
478
- badRequest(body?: any): void;
479
- /**
480
- * 401 Unauthorized
481
- */
482
- unauthorized(body?: any): void;
483
- /**
484
- * 403 Forbidden
485
- */
486
- forbidden(body?: any): void;
487
- /**
488
- * 404 Not Found
489
- */
490
- notFound(body?: any): void;
491
- /**
492
- * 405 Method Not Allowed
493
- */
494
- methodNotAllowed(body?: any): void;
495
- /**
496
- * 406 Not Acceptable
497
- */
498
- notAcceptable(body?: any): void;
499
- /**
500
- * 409 Conflict
501
- */
502
- conflict(body?: any): void;
503
- /**
504
- * 410 Gone
505
- */
506
- gone(body?: any): void;
507
- /**
508
- * 413 Payload Too Large
509
- */
510
- payloadTooLarge(body?: any): void;
511
- /**
512
- * 415 Unsupported Media Type
513
- */
514
- unsupportedMediaType(body?: any): void;
515
- /**
516
- * 422 Unprocessable Entity
517
- */
518
- unprocessableEntity(body?: any): void;
519
- /**
520
- * 429 Too Many Requests
521
- */
522
- tooManyRequests(body?: any): void;
523
- /**
524
- * 5XX Server Errors
525
- */
526
- internalServerError(body?: any): void;
527
- /**
528
- * 501 Not Implemented
529
- */
530
- notImplemented(body?: any): void;
531
- /**
532
- * 502 Bad Gateway
533
- */
534
- badGateway(body?: any): void;
535
- /**
536
- * 503 Service Unavailable
537
- */
538
- serviceUnavailable(body?: any): void;
539
- /**
540
- * 504 Gateway Timeout
541
- */
542
- gatewayTimeout(body?: any): void;
543
- /**
544
- * 505 HTTP Version Not Supported
545
- */
546
- httpVersionNotSupported(body?: any): void;
547
- /**
548
- * Set a cookie for the response, does nothing if the cookie middleware is not registered
549
- */
550
- cookie(_name: string, _value: string, _options?: CookieOptions): void;
551
- /**
552
- * Clear a cookie for the response, does nothing if the cookie middleware is not registered
553
- */
554
- clearCookie(_name: string, _options?: CookieOptions): void;
555
- /**
556
- * Get the body of the response
557
- */
558
- getBody(): any;
559
- }
560
-
561
- type DelHandler = (req: Request$1, res: Response, ...args: any[]) => any;
562
- /**
563
- * Decorator to mark an handler for a DELETE request
564
- * @param path - The path of the route
565
- * @param options - The options for the route
566
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
567
- * @example
568
- * ```ts
569
- * import { del, controller, Request, Response } from "balda";
570
- *
571
- * @controller("/api")
572
- * class MyController {
573
- * @del("/")
574
- * async handler(req: Request, res: Response) {
575
- * // ...
576
- * }
577
- * }
578
- * ```
579
- */
580
- declare const del: (path: string, options?: SwaggerRouteOptions) => <T extends DelHandler>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
581
-
582
- type GetHandler = (req: Request$1, res: Response, ...args: any[]) => any;
583
- /**
584
- * Decorator to mark an handler for a GET request
585
- * @param path - The path of the route
586
- * @param options - The options for the route
587
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
588
- * @example
589
- * ```ts
590
- * import { get, controller, Request, Response } from "balda";
591
- *
592
- * @controller("/api")
593
- * class MyController {
594
- * @get("/")
595
- * async handler(req: Request, res: Response) {
596
- * // ...
597
- * }
598
- * }
599
- * ```
600
- */
601
- declare const get: (path: string, options?: SwaggerRouteOptions) => <T extends GetHandler>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
602
-
603
- type PatchHandler = (req: Request$1, res: Response, ...args: any[]) => any;
604
- /**
605
- * Decorator to mark an handler for a PATCH request
606
- * @param path - The path of the route
607
- * @param options - The options for the route
608
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
609
- * @example
610
- * ```ts
611
- * import { patch, controller, Request, Response } from "balda";
612
- *
613
- * @controller("/api")
614
- * class MyController {
615
- * @patch("/")
616
- * async handler(req: Request, res: Response) {
617
- * // ...
618
- * }
619
- * }
620
- * ```
621
- */
622
- declare const patch: (path: string, options?: SwaggerRouteOptions) => <T extends PatchHandler>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
623
-
624
- type PostHandler = (req: Request$1, res: Response, ...args: any[]) => any;
625
- /**
626
- * Decorator to mark an handler for a POST request
627
- * @param path - The path of the route
628
- * @param options - The options for the route
629
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
630
- * @example
631
- * ```ts
632
- * import { post, controller, Request, Response } from "balda";
633
- *
634
- * @controller("/api")
635
- * class MyController {
636
- * @post("/")
637
- * async handler(req: Request, res: Response) {
638
- * // ...
639
- * }
640
- * }
641
- * ```
642
- */
643
- declare const post: (path: string, options?: SwaggerRouteOptions) => <T extends PostHandler>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
644
-
645
- type PutHandler = (req: Request$1, res: Response, ...args: any[]) => any;
646
- /**
647
- * Decorator to mark an handler for a PUT request
648
- * @param path - The path of the route
649
- * @param options - The options for the route
650
- * @warning Must receive the request and response as the first two arguments or it might not work as expected.
651
- * @example
652
- * ```ts
653
- * import { put, controller, Request, Response } from "balda";
654
- *
655
- * @controller("/api")
656
- * class MyController {
657
- * @put("/")
658
- * async handler(req: Request, res: Response) {
659
- * // ...
660
- * }
661
- */
662
- declare const put: (path: string, options?: SwaggerRouteOptions) => <T extends PutHandler>(target: any, propertyKey: string, descriptor: PropertyDescriptor) => TypedPropertyDescriptor<T>;
663
-
664
- /**
665
- * The next function.
666
- * This is the function that is passed to the handler function.
667
- * It has a pointer to the next middleware or handler function of the middleware chain.
668
- */
669
- type NextFunction = () => void | Promise<void>;
670
-
671
- type RunTimeType = "bun" | "node" | "deno";
672
-
673
- type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
674
- type RuntimeServerMap<T extends RunTimeType> = T extends "node" ? Server$1 : never;
675
- type ServerRouteMiddleware = (req: Request$1, res: Response, next: NextFunction) => void | Promise<void>;
676
- type ServerRouteHandler = (req: Request$1, res: Response) => void | Promise<void>;
677
- type ServerListenCallback = ({ port, host, url, }: {
678
- port: number;
679
- host: string;
680
- url: string;
681
- }) => void;
682
- /**
683
- * Custom bun fetch call to be used as an hook inside Bun.serve method
684
- */
685
- type CustomBunFetch = (...options: Parameters<Bun.ServeOptions["fetch"]>) => Promise<void> | void;
686
- /**
687
- * Custom deno fetch call to be used as an hook inside Deno.serve method
688
- */
689
- type CustomDenoFetch = (...options: Parameters<Parameters<typeof Deno.serve>[0]["handler"]>) => Promise<void> | void;
690
- /**
691
- * The options for the server tap function, allows you to interact with the server behavior before it is used to listen for incoming requests
692
- */
693
- type ServerTapOptionsBuilder<T extends RunTimeType> = T extends "node" ? (req: Omit<IncomingMessage, "url">) => Promise<void> : T extends "bun" ? Partial<Parameters<typeof Bun.serve>[0]> & {
694
- fetch?: CustomBunFetch;
695
- } : T extends "deno" ? Partial<Omit<Parameters<typeof Deno.serve>[0], "handler">> & {
696
- handler?: CustomDenoFetch;
697
- } : never;
698
- type BunTapOptions = {
699
- type: "bun";
700
- options: ServerTapOptionsBuilder<"bun">;
701
- };
702
- type NodeTapOptions = {
703
- type: "node";
704
- options: ServerTapOptionsBuilder<"node">;
705
- };
706
- type DenoTapOptions = {
707
- type: "deno";
708
- options: ServerTapOptionsBuilder<"deno">;
709
- };
710
- type ServerTapOptions = BunTapOptions | NodeTapOptions | DenoTapOptions;
711
-
712
- /**
713
- * Decorator to mark a middleware for a route or a controller class
714
- */
715
- declare const middleware: (middleware: ServerRouteMiddleware | ServerRouteMiddleware[]) => (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => any;
716
-
717
- interface CustomValidationError {
718
- status?: number;
719
- message?: string;
720
- }
721
- interface ValidationOptions {
722
- /**
723
- * The schema to validate the request body against
724
- */
725
- body?: TSchema$1;
726
- /**
727
- * The schema to validate the query parameters against
728
- */
729
- query?: TSchema$1;
730
- /**
731
- * The schema to validate both body and query against
732
- */
733
- all?: TSchema$1;
734
- /**
735
- * Whether to use safe validation (returns original data if validation fails instead of throwing)
736
- * @default false
737
- */
738
- safe?: boolean;
739
- }
740
-
741
- declare const validate: {
742
- (options: ValidationOptions & {
743
- customError?: CustomValidationError;
744
- }): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
745
- query(schema: TSchema$1, customError?: CustomValidationError): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
746
- body(schema: TSchema$1, customError?: CustomValidationError): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
747
- all(schema: TSchema$1, customError?: CustomValidationError): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
748
- };
749
-
750
- /**
751
- * Options for helmet middleware
752
- */
753
- interface HelmetOptions {
754
- dnsPrefetchControl?: boolean;
755
- frameguard?: boolean | {
756
- action: "DENY" | "SAMEORIGIN" | string;
757
- };
758
- hsts?: boolean | {
759
- maxAge?: number;
760
- includeSubDomains?: boolean;
761
- preload?: boolean;
762
- };
763
- contentTypeOptions?: boolean;
764
- ieNoOpen?: boolean;
765
- xssFilter?: boolean;
766
- referrerPolicy?: false | string;
767
- crossOriginResourcePolicy?: false | string;
768
- crossOriginOpenerPolicy?: false | string;
769
- crossOriginEmbedderPolicy?: false | string;
770
- contentSecurityPolicy?: false | string;
771
- }
772
-
773
- type LoggerOptions = Parameters<typeof pino>[0];
774
-
775
- interface LogOptions {
776
- /**
777
- * Whether to log the request.
778
- * @default true
779
- */
780
- logRequest?: boolean;
781
- /**
782
- * What to log for the request.
783
- * @default true for all properties
784
- */
785
- requestPayload?: {
786
- method?: boolean;
787
- url?: boolean;
788
- ip?: boolean;
789
- headers?: boolean;
790
- /** Only json objects and strings are logged */
791
- body?: boolean;
792
- };
793
- /**
794
- * Whether to log the response.
795
- * @default true
796
- */
797
- logResponse?: boolean;
798
- /**
799
- * Whether to log the response body.
800
- * @default false
801
- */
802
- responsePayload?: {
803
- status?: boolean;
804
- headers?: boolean;
805
- body?: boolean;
806
- };
807
- /**
808
- * What to log for the response.
809
- * @default true for all properties
810
- */
811
- pinoOptions?: LoggerOptions;
812
- }
813
-
814
- type StorageStrategy = "memory" | "custom";
815
- type BaseRateLimiterOptions = {
816
- /**
817
- * The number of requests per window
818
- * @default 100
819
- */
820
- limit?: number;
821
- /**
822
- * The message to return when the rate limit is exceeded
823
- * @default "ERR_RATE_LIMIT_EXCEEDED"
824
- */
825
- message?: string;
826
- /**
827
- * The status code to return when the rate limit is exceeded
828
- * @default 429
829
- */
830
- statusCode?: number;
831
- /**
832
- * The storage strategy to use
833
- * @default "memory"
834
- */
835
- storageStrategy?: StorageStrategy;
836
- };
837
- /**
838
- * Key Strategy
839
- */
840
- type IpRateLimiterOptions = {
841
- /**
842
- * The type of rate limiter
843
- */
844
- type: "ip";
845
- } & BaseRateLimiterOptions;
846
- type CustomRateLimiterOptions = {
847
- /**
848
- * The type of rate limiter
849
- */
850
- type: "custom";
851
- /**
852
- * Generate a key for the rate limiter from the request (e.g. user id, email, etc.)
853
- */
854
- key: (req: Request$1) => string;
855
- /**
856
- * The storage strategy to use
857
- * @default "memory"
858
- */
859
- storageStrategy?: StorageStrategy;
860
- } & BaseRateLimiterOptions;
861
- /**
862
- * Memory Storage Strategy
863
- */
864
- type MemoryStorageStrategy = {
865
- /**
866
- * The type of storage strategy
867
- */
868
- type: "memory";
869
- /**
870
- * The window in milliseconds
871
- * @default 60000
872
- */
873
- windowMs?: number;
874
- };
875
- /**
876
- * Custom Storage Strategy
877
- */
878
- type CustomStorageStrategy = {
879
- /**
880
- * The type of storage strategy
881
- */
882
- type: "custom";
883
- /**
884
- * Set a value in the storage
885
- */
886
- set: (key: string, value: any) => Promise<void>;
887
- /**
888
- * Get a value from the storage
889
- */
890
- get: (key: string) => Promise<any>;
891
- };
892
- type StorageOptions = MemoryStorageStrategy | CustomStorageStrategy;
893
- /**
894
- * Rate limiter options
895
- */
896
- type RateLimiterKeyOptions = IpRateLimiterOptions | CustomRateLimiterOptions;
897
-
898
- type CorsMethods = "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS" | "PATCH" | "HEAD";
899
- /**
900
- * Options for CORS middleware, similar to Express.js
901
- */
902
- type CorsOptions = {
903
- /**
904
- * Configures the Access-Control-Allow-Origin CORS header, defaults to '*'
905
- */
906
- origin?: string | RegExp | (string | RegExp)[];
907
- /**
908
- * Configures the Access-Control-Allow-Methods CORS header. Defaults to 'GET,HEAD,PUT,PATCH,POST,DELETE'.
909
- */
910
- methods?: CorsMethods[] | string;
911
- /**
912
- * Configures the Access-Control-Allow-Headers CORS header. Defaults to allowing all requested headers.
913
- */
914
- allowedHeaders?: string[] | string;
915
- /**
916
- * Configures the Access-Control-Expose-Headers CORS header. Defaults to none.
917
- */
918
- exposedHeaders?: string[] | string;
919
- /**
920
- * Configures the Access-Control-Allow-Credentials CORS header. Defaults to false.
921
- */
922
- credentials?: boolean;
923
- /**
924
- * Configures the Access-Control-Max-Age CORS header. Defaults to undefined (not sent).
925
- */
926
- maxAge?: number;
927
- /**
928
- * Pass the CORS preflight response to the next handler. Defaults to false (ends response).
929
- */
930
- preflightContinue?: boolean;
931
- /**
932
- * Provides a status code to use for successful OPTIONS requests, if preflightContinue is false. Defaults to 204.
933
- */
934
- optionsSuccessStatus?: number;
935
- };
936
-
937
- interface JsonOptions {
938
- /**
939
- * The maximum size of the JSON body in bytes.
940
- * If the body is larger than this limit, the request will be rejected.
941
- * Default: 5mb
942
- */
943
- sizeLimit?: number;
944
- /**
945
- * If true, the JSON body will be parsed as an empty object if it is empty.
946
- * Default: false (body will be undefined)
947
- */
948
- parseEmptyBodyAsObject?: boolean;
949
- /**
950
- * The encoding to use when decoding the request body.
951
- * Default: "utf-8"
952
- */
953
- encoding?: TextDecoderEncoding;
954
- /**
955
- * The custom error message to return when the JSON body is too large.
956
- * Default: response with status 413 and body { message: "ERR_REQUEST_BODY_TOO_LARGE" }
957
- */
958
- customErrorMessage?: {
959
- status?: number;
960
- message?: string;
961
- };
962
- }
963
- /**
964
- * Supported text encodings for TextDecoder.
965
- * Based on the WHATWG Encoding Standard.
966
- */
967
- type TextDecoderEncoding = "utf-8" | "utf-16le" | "utf-16be" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift-jis" | "euc-kr" | "iso-2022-kr" | "iso-8859-1" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-9" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "x-mac-greek" | "x-mac-icelandic" | "x-mac-latin2" | "x-mac-roman" | "x-mac-turkish" | "koi8-r" | "koi8-u";
968
-
969
- declare class MockResponse<T = any> {
970
- private readonly response;
971
- constructor(response: Response);
972
- body(): T;
973
- statusCode(): number;
974
- headers(): Record<string, string>;
975
- assertStatus(status: number): this;
976
- assertHeader(header: string, value: string): this;
977
- assertHeaderExists(header: string): this;
978
- assertHeaderNotExists(header: string): this;
979
- assertBodySubset(subset: Partial<T>): this;
980
- assertBodyDeepEqual(expected: T): this;
981
- assertBodyNotSubset(subset: Partial<T>): this;
982
- assertBodyNotDeepEqual(expected: T): this;
983
- assertCustom(assertion: (response: Response) => void): this;
984
- private assertSubset;
985
- private assertDeepEqual;
986
- private assertNotSubset;
987
- private assertNotDeepEqual;
988
- private assertArraySubset;
989
- private assertArrayDeepEqual;
990
- private isObject;
991
- }
992
-
993
- /**
994
- * The options for the mock server, only one of body, formData, urlencoded can be provided
995
- */
996
- interface MockServerOptions {
997
- /**
998
- * The body of the request, if formData is provided, it will be ignored
999
- */
1000
- body?: any;
1001
- /**
1002
- * The form data of the request
1003
- */
1004
- formData?: FormData;
1005
- /**
1006
- * The urlencoded body of the request
1007
- */
1008
- urlencoded?: Record<string, string>;
1009
- /**
1010
- * The headers of the request
1011
- */
1012
- headers?: Record<string, string>;
1013
- /**
1014
- * The query parameters of the request, if provided, they will be merged with the query parameters from the path (precedence is given to the query parameters provided here)
1015
- */
1016
- query?: Record<string, string>;
1017
- /**
1018
- * The cookies of the request
1019
- */
1020
- cookies?: Record<string, string>;
1021
- /**
1022
- * The ip of the request
1023
- */
1024
- ip?: string;
1025
- }
1026
-
1027
- /**
1028
- * Allows to mock server requests without needing to start the server, useful for testing purposes
1029
- */
1030
- declare class MockServer {
1031
- private readonly server;
1032
- constructor(server: Server);
1033
- /**
1034
- * Simulates an HTTP request without making an actual network call, useful for testing purposes
1035
- * Executes the middleware chain and handler of the route
1036
- * @param method - The HTTP method (GET, POST, PUT, DELETE, PATCH)
1037
- * @param path - The request path
1038
- * @param options - Request options including body, headers, query params, etc.
1039
- * @throws {Error} - If more than one of body, formData, urlencoded is provided
1040
- */
1041
- request<T>(method: HttpMethod, path: string, options?: MockServerOptions): Promise<MockResponse<T>>;
1042
- get<T>(path: string, options?: Omit<MockServerOptions, "body" | "formData" | "urlencoded">): Promise<MockResponse<T>>;
1043
- post<T>(path: string, options?: MockServerOptions): Promise<MockResponse<T>>;
1044
- put<T>(path: string, options?: MockServerOptions): Promise<MockResponse<T>>;
1045
- patch<T>(path: string, options?: MockServerOptions): Promise<MockResponse<T>>;
1046
- delete<T>(path: string, options?: Omit<MockServerOptions, "body" | "formData">): Promise<MockResponse<T>>;
1047
- /**
1048
- * Converts FormData to a proper multipart/form-data body with boundaries
1049
- */
1050
- private formDataToMultipart;
1051
- private validateOptions;
1052
- }
1053
-
1054
- /**
1055
- * Options for URL-encoded middleware
1056
- */
1057
- type UrlEncodedOptions = {
1058
- /**
1059
- * The maximum size of the URL-encoded body in bytes. Defaults to 1MB.
1060
- */
1061
- limit?: number;
1062
- /**
1063
- * Whether to parse extended syntax (objects and arrays). Defaults to false.
1064
- */
1065
- extended?: boolean;
1066
- /**
1067
- * The character encoding to use when parsing. Defaults to 'utf8'.
1068
- */
1069
- charset?: string;
1070
- /**
1071
- * Whether to allow empty values. Defaults to true.
1072
- */
1073
- allowEmpty?: boolean;
1074
- /**
1075
- * Maximum number of parameters to parse. Defaults to 1000.
1076
- */
1077
- parameterLimit?: number;
1078
- };
1079
-
1080
- /**
1081
- * Swagger plugin that serves the swagger UI and JSON specification, by default the UI will be available at /docs and the JSON specification at /docs/json
1082
- * @warning The json specification is always available at /${globalOptions.path}/json
1083
- * @internal
1084
- */
1085
- declare const swagger: (globalOptions?: SwaggerGlobalOptions | boolean) => void;
1086
-
1087
- type CronSchedule = {
1088
- name: string;
1089
- args: Parameters<typeof nodeCron.schedule>;
1090
- };
1091
- type CronScheduleParams = Parameters<typeof nodeCron.schedule>;
1092
-
1093
- declare class CronService {
1094
- static scheduledJobs: CronSchedule[];
1095
- /**
1096
- * @description Schedule a cron job.
1097
- * @internal
1098
- * @example
1099
- * CronService.register('test', '0 0 * * *', () => {
1100
- * console.log('test');
1101
- * }, {
1102
- * timezone: 'Europe/Istanbul',
1103
- * });
1104
- */
1105
- static register(name: string, ...args: CronScheduleParams): void;
1106
- /**
1107
- * @description Start the cron scheduler.
1108
- */
1109
- static run(): Promise<void>;
1110
- /**
1111
- * @description Main error handler for cron jobs. You can write your own error handler by overriding this static method for example with sentry.
1112
- */
1113
- static globalErrorHandler(context: TaskContext): void;
1114
- /**
1115
- * @description Import all cron jobs from the app/cron/schedules directory
1116
- */
1117
- static massiveImportCronJobs(cronJobPatterns: string[]): Promise<void>;
1118
- }
1119
-
1120
- type ServerPlugin = {
1121
- cors?: CorsOptions;
1122
- json?: JsonOptions;
1123
- static?: string;
1124
- fileParser?: FilePluginOptions;
1125
- helmet?: HelmetOptions;
1126
- cookie?: CookieMiddlewareOptions;
1127
- log?: LogOptions;
1128
- urlencoded?: UrlEncodedOptions;
1129
- rateLimiter?: {
1130
- keyOptions?: RateLimiterKeyOptions;
1131
- storageOptions?: StorageOptions;
1132
- };
1133
- };
1134
- interface ServerOptions {
1135
- /** The port to listen on, defaults to 80 */
1136
- port?: number;
1137
- /** The hostname to listen on, defaults to 0.0.0.0 */
1138
- host?: string;
1139
- /** Controller patterns to match, defaults to an empty array */
1140
- controllerPatterns?: string[];
1141
- /** Basic plugins to apply to the server, by default no plugins are applied */
1142
- plugins?: ServerPlugin;
1143
- /** The tap options to interact with the underlying server connector before it is used to listen for incoming requests */
1144
- tapOptions?: ServerTapOptions;
1145
- /**
1146
- * The swagger options to apply to the server, by default swagger plugin is applied with standard options, you can pass a boolean to enable or disable the plugin or you can pass an object to apply custom options to the plugin
1147
- * @example
1148
- * ```ts
1149
- * const server = new Server({
1150
- * swagger: true,
1151
- * });
1152
- * ```
1153
- */
1154
- swagger?: Parameters<typeof swagger>[0] | boolean;
1155
- }
1156
- type ServerErrorHandler = (req: Request, res: Response, next: NextFunction, error: Error) => void | Promise<void>;
1157
- interface ServerInterface {
1158
- /**
1159
- * Whether the server is listening for requests
1160
- */
1161
- isListening: boolean;
1162
- /**
1163
- * The url of the server
1164
- */
1165
- url: string;
1166
- /**
1167
- * The port of the server
1168
- */
1169
- port: number;
1170
- /**
1171
- * The host of the server
1172
- */
1173
- host: string;
1174
- /**
1175
- * Settings applied before server is listening, this is used to tap into the server connector for the current runtime and modify it before it is used to listen for incoming requests
1176
- * @warning Must be used before `listen` method
1177
- */
1178
- tapOptions?: ServerTapOptions;
1179
- /**
1180
- * The path to the temporary directory, you can append a path to the temporary directory to get a new path.
1181
- * It uses the current working directory of the runtime to get the base path.
1182
- * @example
1183
- * ```ts
1184
- * server.tmpPath("my-app"); // -> ${cwd}/tmp/my-app
1185
- * ```
1186
- */
1187
- tmpDir: (...append: string[]) => string;
1188
- /**
1189
- * Adds a GET route to the server, useful for defining simple global routes, use decorators to define more complex routes
1190
- */
1191
- get: (...args: any[]) => void;
1192
- /**
1193
- * Adds a POST route to the server, useful for defining simple global routes, use decorators to define more complex routes
1194
- */
1195
- post: (...args: any[]) => void;
1196
- /**
1197
- * Adds a PUT route to the server, useful for defining simple global routes, use decorators to define more complex routes
1198
- */
1199
- put: (...args: any[]) => void;
1200
- /**
1201
- * Adds a PATCH route to the server, useful for defining simple global routes, use decorators to define more complex routes
1202
- */
1203
- patch: (...args: any[]) => void;
1204
- /**
1205
- * Adds a DELETE route to the server, useful for defining simple global routes, use decorators to define more complex routes
1206
- */
1207
- delete: (...args: any[]) => void;
1208
- /**
1209
- * Get the node server instance, you must be using node runtime to use this method
1210
- * @throws if the runtime is not node
1211
- */
1212
- getNodeServer: () => RuntimeServerMap<"node">;
1213
- /**
1214
- * Embed the given key into the server instance, this is useful for embedding the server with custom context inside the server instance, you can extend the server with your own properties to type it
1215
- * @param key - The key to embed
1216
- * @param value - The value to embed
1217
- * @warning There are some keys that are protected and cannot be embedded, you can find the list of protected keys in the PROTECTED_KEYS constant
1218
- * @throws An error if the key is already defined in the server instance or if the key is protected
1219
- * @example
1220
- * ```typescript
1221
- * // For better type safety, you can declare a module for the server interface
1222
- * declare module "balda" {
1223
- * interface ServerInterface {
1224
- * myCustomProperty: string;
1225
- * }
1226
- * }
1227
- *
1228
- * server.embed("myCustomProperty", "myCustomValue");
1229
- * console.log(server.myCustomProperty); // Type safe if ServerInterface is extended
1230
- * ```
1231
- */
1232
- embed: (key: string, value: any) => void;
1233
- /**
1234
- * Register a signal event listener to the server, this is useful for handling signals like SIGINT, SIGTERM, etc.
1235
- * @param event - The signal event to listen for
1236
- * @param cb - The callback to be called when the signal event is received
1237
- */
1238
- on: (event: SignalEvent, cb: () => void) => void;
1239
- /**
1240
- * Register a global middleware to be applied to all routes after the listener is bound, the middleware is applied in the order it is registered
1241
- */
1242
- use: (middleware: ServerRouteMiddleware) => void;
1243
- /**
1244
- * Set the error handler for the server
1245
- * @param errorHandler - The error handler to be applied to all routes
1246
- */
1247
- setErrorHandler: (errorHandler?: ServerErrorHandler) => void;
1248
- /**
1249
- * Binds the server to the port and hostname defined in the serverOptions, meant to be called only once
1250
- * @warning All routes defined with decorators are defined on this method just before the server starts listening for requests
1251
- */
1252
- listen: (cb?: ServerListenCallback) => void;
1253
- /**
1254
- * Closes the server and frees the port
1255
- */
1256
- close: () => Promise<void>;
1257
- /**
1258
- * Get a mock server instance, useful for testing purposes
1259
- */
1260
- getMockServer: () => Promise<MockServer>;
1261
- /**
1262
- * Exit current runtime process with the given code based on the current runtime
1263
- * @param code - The code to exit with, defaults to 0
1264
- * @example
1265
- * ```typescript
1266
- * server.exit(1); // If node process.exit(1) is called
1267
- * server.exit(); // If deno Deno.exit(0) is called
1268
- * ```
1269
- */
1270
- exit: (code?: number) => void;
1271
- /**
1272
- * Sets the global cron error handler
1273
- * @param globalErrorHandler - The global cron error handler
1274
- */
1275
- setGlobalCronErrorHandler: (globalErrorHandler: (...args: Parameters<(typeof CronService)["globalErrorHandler"]>) => void) => void;
1276
- /**
1277
- * Starts the registered cron jobs
1278
- * @param cronJobPatterns - The cron job patterns to that will be imported and registered before starting the cron jobs
1279
- * @param onStart - The callback to be called when the cron jobs are started
1280
- */
1281
- startRegisteredCrons: (cronJobPatterns?: string[], onStart?: () => void) => Promise<void>;
1282
- }
1283
- type StandardMethodOptions = {
1284
- middlewares?: ServerRouteMiddleware[] | ServerRouteMiddleware;
1285
- swagger?: SwaggerRouteOptions;
1286
- };
1287
- type SignalEvent = Deno.Signal | NodeJS.Signals;
1288
-
1289
- /**
1290
- * The server class that is used to create and manage the server
1291
- */
1292
- declare class Server implements ServerInterface {
1293
- isListening: boolean;
1294
- private wasInitialized;
1295
- private serverConnector;
1296
- private globalMiddlewares;
1297
- private options;
1298
- private controllerImportBlacklistedPaths;
1299
- /**
1300
- * The constructor for the server
1301
- * @warning Routes will only be defined after calling the `listen` method so you're free to define middlewares before calling it
1302
- * @param options - The options for the server
1303
- * @param options.port - The port to listen on, defaults to 80
1304
- * @param options.host - The hostname to listen on, defaults to 0.0.0.0
1305
- * @param options.controllerPatterns - The patterns to match for controllers, defaults to an empty array
1306
- * @param options.plugins - The plugins to apply to the server, by default no plugins are applied, plugins are applied in the order they are defined in the options
1307
- * @param options.logger - The logger to use for the server, by default a default logger is used
1308
- * @param options.tapOptions - Options fetch to the runtime server before the server is up and running
1309
- */
1310
- constructor(options?: ServerOptions);
1311
- get url(): string;
1312
- get port(): number;
1313
- get host(): string;
1314
- tmpDir(...append: string[]): string;
1315
- get(path: string, handler: ServerRouteHandler): void;
1316
- get(path: string, options: StandardMethodOptions, handler: ServerRouteHandler): void;
1317
- post(path: string, handler: ServerRouteHandler): void;
1318
- post(path: string, options: StandardMethodOptions, handler: ServerRouteHandler): void;
1319
- patch(path: string, handler: ServerRouteHandler): void;
1320
- patch(path: string, options: StandardMethodOptions, handler: ServerRouteHandler): void;
1321
- put(path: string, handler: ServerRouteHandler): void;
1322
- put(path: string, options: StandardMethodOptions, handler: ServerRouteHandler): void;
1323
- delete(path: string, handler: ServerRouteHandler): void;
1324
- delete(path: string, options: StandardMethodOptions, handler: ServerRouteHandler): void;
1325
- getNodeServer(): RuntimeServerMap<"node">;
1326
- embed(key: string, value: any): void;
1327
- exit(code?: number): void;
1328
- on(event: SignalEvent, cb: () => void): void;
1329
- on(event: string, cb: () => void): void;
1330
- use(...middlewares: ServerRouteMiddleware[]): void;
1331
- setErrorHandler(errorHandler?: ServerErrorHandler): void;
1332
- setGlobalCronErrorHandler(globalErrorHandler: (...args: Parameters<(typeof CronService)["globalErrorHandler"]>) => void): void;
1333
- startRegisteredCrons: (cronJobPatterns?: string[], onStart?: () => void) => Promise<void>;
1334
- listen(cb?: ServerListenCallback): void;
1335
- close(): Promise<void>;
1336
- /**
1337
- * Returns a mock server instance that can be used to test the server without starting it
1338
- * It will import the controllers and apply the plugins to the mock server
1339
- */
1340
- getMockServer(): Promise<MockServer>;
1341
- private importControllers;
1342
- private extractOptionsAndHandlerFromRouteRegistration;
1343
- private applyPlugins;
1344
- /**
1345
- * Initializes the server by importing the controllers and applying the plugins, it's idempotent, it will not re-import the controllers or apply the plugins if the server was already initialized (e.g. mockServer init)
1346
- * @internal
1347
- */
1348
- private bootstrap;
1349
- /**
1350
- * Registers a not found route for all routes that are not defined
1351
- * @internal
1352
- */
1353
- private registerNotFoundRoutes;
1354
- }
1355
-
1356
- /**
1357
- * CORS plugin
1358
- * @param options CORS options (all optional)
1359
- */
1360
- declare const cors: (options?: CorsOptions) => ServerRouteMiddleware;
1361
-
1362
- /**
1363
- * Middleware to parse the JSON body of the request. GET, DELETE and OPTIONS requests are not parsed.
1364
- * @param options - The options for the JSON middleware.
1365
- */
1366
- declare const json: (options?: JsonOptions) => ServerRouteMiddleware;
1367
-
1368
- /**
1369
- * Creates a static file serving middleware and registers all routes for the given path (path + "/*")
1370
- * @param path - The api path to serve static files from.
1371
- * @example 'public' -> localhost:3000/public/index.html will search for public/index.html in the current directory
1372
- */
1373
- declare const serveStatic: (path?: string, swaggerOptions?: SwaggerRouteOptions) => ServerRouteMiddleware;
1374
- declare function getContentType(ext: string): string;
1375
-
1376
- /**
1377
- * Cookie middleware for parsing and setting cookies, must be used in order to use the cookie methods on the request and response objects
1378
- * @param options Cookie middleware options
1379
- */
1380
- declare const cookie: (options?: CookieMiddlewareOptions) => ServerRouteMiddleware;
1381
-
1382
- /**
1383
- * Base class for all plugins.
1384
- *
1385
- * Plugins are used to extend the functionality of the server.
1386
- *
1387
- * @example
1388
- * ```ts
1389
- * import { Server, BasePlugin } from "balda";
1390
- *
1391
- * export class MyPlugin extends BasePlugin {
1392
- * async handle(): Promise<ServerRouteMiddleware> {
1393
- * return async (req, res, next) => {
1394
- * console.log("My plugin is running");
1395
- * await next();
1396
- * };
1397
- * }
1398
- * }
1399
- *
1400
- * const server = new Server();
1401
- * server.use(new MyPlugin().handle());
1402
- * ```
1403
- *
1404
- * @abstract
1405
- */
1406
- declare abstract class BasePlugin {
1407
- abstract handle(...args: any[]): Promise<ServerRouteMiddleware>;
1408
- }
1409
-
1410
- /**
1411
- * Rate limiter plugin
1412
- * Rate limiter is a plugin that limits the number of requests to a resource.
1413
- * It can be used to protect a resource from abuse.
1414
- * @param keyOptions Rate limiter key options, tells the middleware how to retrieve the key from the request in to discriminate what to rate limit (all optional, defaults to ip)
1415
- * @param storageOptions Rate limiter storage options, tells the middleware how to store the rate limit data (all optional, defaults to memory)
1416
- */
1417
- declare const rateLimiter: (keyOptions?: RateLimiterKeyOptions, storageOptions?: StorageOptions) => ServerRouteMiddleware;
1418
-
1419
- /**
1420
- * Logs the request and response of the handler, can be set both on a specific route or on a global middleware.
1421
- * @warning Only json objects and strings are logged from the request and response.
1422
- */
1423
- declare const log: (options?: LogOptions) => ServerRouteMiddleware;
1424
-
1425
- /**
1426
- * Middleware to handle multipart/form-data file uploads.
1427
- * - Validates each file against the given `FilePluginOptions` (currently only size limit).
1428
- * - Stores every uploaded file in a runtime-agnostic temporary directory and exposes them via `req.files` & `req.file`.
1429
- * - Cleans the temporary files both after successful handler execution and when an unhandled error bubbles up.
1430
- * - Can be used both as a global middleware to check all incoming requests for files and as a route middleware to check only the files for a specific route
1431
- */
1432
- declare const fileParser: (options?: FilePluginOptions) => ServerRouteMiddleware;
1433
-
1434
- /**
1435
- * Sets common HTTP security headers
1436
- * @param options Helmet options (all optional)
1437
- */
1438
- declare const helmet: (options?: HelmetOptions) => ServerRouteMiddleware;
1439
-
1440
- /**
1441
- * URL-encoded form data parser middleware
1442
- * Parses application/x-www-form-urlencoded bodies and populates req.body
1443
- * @param options URL-encoded parsing options
1444
- * @param options.limit The maximum size of the URL-encoded body in bytes. Defaults to 1MB.
1445
- * @param options.extended Whether to parse extended syntax (objects and arrays). Defaults to false.
1446
- * @param options.charset The character encoding to use when parsing. Defaults to 'utf8'.
1447
- * @param options.allowEmpty Whether to allow empty values. Defaults to true.
1448
- * @param options.parameterLimit Maximum number of parameters to parse. Defaults to 1000.
1449
- */
1450
- declare const urlencoded: (options?: UrlEncodedOptions) => ServerRouteMiddleware;
1451
-
1452
- /**
1453
- * Singleton that handles the routing of requests to the appropriate handler(s).
1454
- */
1455
- declare class Router {
1456
- private trees;
1457
- private routes;
1458
- constructor();
1459
- getRoutes(): Route[];
1460
- addOrUpdate(method: HttpMethod, path: string, middleware: ServerRouteMiddleware[], handler: ServerRouteHandler, swaggerOptions?: SwaggerRouteOptions): void;
1461
- find(method: string, rawPath: string): {
1462
- middleware: ServerRouteMiddleware[];
1463
- handler: ServerRouteHandler;
1464
- params: Params;
1465
- } | null;
1466
- /**
1467
- * Apply global middlewares to all routes
1468
- * @param middlewares - The middlewares to apply
1469
- * @internal
1470
- */
1471
- applyGlobalMiddlewaresToAllRoutes(middlewares: ServerRouteMiddleware[]): void;
1472
- }
1473
-
1474
- type Params = Record<string, string>;
1475
- interface Route {
1476
- method: string;
1477
- path: string;
1478
- middleware: ServerRouteMiddleware[];
1479
- handler: ServerRouteHandler;
1480
- swaggerOptions?: SwaggerRouteOptions;
1481
- }
1482
- /**
1483
- * The client router is a subset of the router that is used to define routes on library level by the end user.
1484
- */
1485
- type ClientRouter = Omit<Router, "applyGlobalMiddlewaresToAllRoutes">;
1486
-
1487
- /**
1488
- * Main router instance that handles all route registrations inside the balda server
1489
- */
1490
- declare const router: ClientRouter;
1491
-
1492
- export { BasePlugin, type NextFunction, Request$1 as Request, Response, Server, type ServerErrorHandler, type ServerInterface, type ServerOptions, type ServerPlugin, type SignalEvent, type StandardMethodOptions, controller, cookie, cors, del, fileParser, get, getContentType, helmet, json, log, middleware, patch, post, put, rateLimiter, router, serveStatic, urlencoded, validate };