@ozanarslan/corpus 0.1.6 → 0.1.9

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.
Files changed (4) hide show
  1. package/dist/index.cjs +2051 -979
  2. package/dist/index.d.ts +385 -152
  3. package/dist/index.js +2043 -945
  4. package/package.json +6 -2
package/dist/index.d.ts CHANGED
@@ -10,6 +10,11 @@ declare abstract class StoreAbstract<T> {
10
10
  declare class GlobalPrefixStore extends StoreAbstract<string> {
11
11
  protected value: string;
12
12
  }
13
+ export type _Default = typeof _Default;
14
+ declare const _Default: unique symbol;
15
+ export type ConstructorOf<A extends abstract new (...args: any) => any, I = _Default> = {
16
+ new (...args: ConstructorParameters<A>): I extends _Default ? InstanceType<A> : I;
17
+ };
13
18
  export type CookieOptions = {
14
19
  name: string;
15
20
  value: string;
@@ -26,7 +31,11 @@ export type CookieOptions = {
26
31
  };
27
32
  export type CookiesInit = CookiesAbstract | CookieOptions | CookieOptions[];
28
33
  declare abstract class CookiesAbstract {
29
- protected abstract map: Bun.CookieMap | Map<string, string>;
34
+ constructor(_?: CookiesInit);
35
+ protected abstract map: Iterable<[
36
+ string,
37
+ string
38
+ ]>;
30
39
  abstract set(opts: CookieOptions): void;
31
40
  abstract get(name: string): string | null;
32
41
  abstract has(name: string): boolean;
@@ -42,12 +51,8 @@ declare abstract class CookiesAbstract {
42
51
  abstract setMany(optsArr: Array<CookieOptions>): void;
43
52
  protected applyInit(init?: CookiesInit): void;
44
53
  }
45
- declare class CookiesUsingBun extends CookiesAbstract {
46
- constructor(init?: CookiesInit);
47
- protected map: Bun.CookieMap;
48
- toSetCookieHeaders(): Array<string>;
54
+ export interface CookiesInterface {
49
55
  set(opts: CookieOptions): void;
50
- setMany(optsArr: Array<CookieOptions>): void;
51
56
  get(name: string): string | null;
52
57
  has(name: string): boolean;
53
58
  get count(): number;
@@ -58,8 +63,11 @@ declare class CookiesUsingBun extends CookiesAbstract {
58
63
  ]>;
59
64
  values(): Array<string>;
60
65
  keys(): Array<string>;
66
+ toSetCookieHeaders(): Array<string>;
67
+ setMany(optsArr: Array<CookieOptions>): void;
61
68
  }
62
- export declare class Cookies extends CookiesUsingBun {
69
+ declare const Adapted: ConstructorOf<typeof CookiesAbstract, CookiesInterface>;
70
+ export declare class Cookies extends Adapted {
63
71
  }
64
72
  export type ValueOf<T> = T[keyof T];
65
73
  /** Just some common headers. */
@@ -86,6 +94,7 @@ export declare const CommonHeaders: {
86
94
  readonly Referer: "Referer";
87
95
  /** Indicates whether the connection should be kept alive */
88
96
  readonly Connection: "Connection";
97
+ readonly Upgrade: "Upgrade";
89
98
  /** Used to specify directives that must be obeyed by caching mechanisms */
90
99
  readonly Pragma: "Pragma";
91
100
  /** The date and time at which the message was sent */
@@ -163,6 +172,7 @@ declare class CRequest extends Request {
163
172
  constructor(info: CRequestInfo, init?: CRequestInit | undefined);
164
173
  readonly urlObject: URL;
165
174
  readonly isPreflight: boolean;
175
+ readonly isWebsocket: boolean;
166
176
  readonly cookies: Cookies;
167
177
  headers: CHeaders;
168
178
  private resolveUrlObject;
@@ -170,6 +180,7 @@ declare class CRequest extends Request {
170
180
  /** Gets cookie header and collects cookies for the jar */
171
181
  private resolveCookies;
172
182
  private resolveIsPreflight;
183
+ private resolveIsWebsocketUpgrade;
173
184
  }
174
185
  export type OrNumber<T> = T | (number & {});
175
186
  /** Commonly used HTTP status codes. */
@@ -356,9 +367,9 @@ export type NdjsonSource = Func<[
356
367
  * - {@link CResponse.file} — Respond with a static file
357
368
  */
358
369
  declare class CResponse<R = unknown> {
359
- protected readonly data?: CResponseBody<R>;
360
- protected readonly init?: CResponseInit | undefined;
361
- constructor(data?: CResponseBody<R>, init?: CResponseInit | undefined);
370
+ data?: CResponseBody<R>;
371
+ protected readonly init?: (CResponseInit | CResponse) | undefined;
372
+ constructor(data?: CResponseBody<R>, init?: (CResponseInit | CResponse) | undefined);
362
373
  body: BodyInit;
363
374
  headers: CHeaders;
364
375
  status: Status;
@@ -379,17 +390,8 @@ declare class CResponse<R = unknown> {
379
390
  private resolveStatus;
380
391
  private setContentType;
381
392
  private resolveBody;
382
- private getDefaultStatusText;
393
+ static getDefaultStatusText(status: number): string;
383
394
  }
384
- declare const RouteVariant: {
385
- readonly static: "static";
386
- readonly dynamic: "dynamic";
387
- };
388
- export type RouteVariant = ValueOf<typeof RouteVariant>;
389
- export type RouteDefinition<Path extends string = string> = {
390
- method: Method;
391
- path: Path;
392
- } | Path;
393
395
  export interface DatabaseClientInterface {
394
396
  }
395
397
  export interface ContextDataInterface {
@@ -559,9 +561,8 @@ export declare class Context<B = unknown, S = unknown, P = unknown, R = unknown>
559
561
  }
560
562
  export type MaybePromise<T> = Promise<T> | T;
561
563
  export type RouteHandler<B = unknown, S = unknown, P = unknown, R = unknown> = Func<[
562
- Context<B, S, P, R>
564
+ context: Context<B, S, P, R>
563
565
  ], MaybePromise<R>>;
564
- export type RouteId = `${string} ${string}`;
565
566
  export interface Schema<T = unknown> extends StandardSchemaV1<unknown, T> {
566
567
  }
567
568
  export type RouteModel<B = unknown, S = unknown, P = unknown, R = unknown> = {
@@ -570,7 +571,42 @@ export type RouteModel<B = unknown, S = unknown, P = unknown, R = unknown> = {
570
571
  search?: Schema<S>;
571
572
  params?: Schema<P>;
572
573
  };
573
- declare abstract class RouteAbstract<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown> {
574
+ declare const RouteVariant: {
575
+ readonly static: "static";
576
+ readonly dynamic: "dynamic";
577
+ readonly websocket: "websocket";
578
+ };
579
+ export type RouteVariant = ValueOf<typeof RouteVariant>;
580
+ export type RouteId = `${string} ${string}`;
581
+ export interface RouteInterface<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown> {
582
+ variant: RouteVariant;
583
+ id: RouteId;
584
+ method: OrString<Method>;
585
+ endpoint: Path;
586
+ pattern: RegExp;
587
+ handler: RouteHandler<B, S, P, R>;
588
+ model?: RouteModel<B, S, P, R>;
589
+ }
590
+ export type AnyRoute = RouteInterface<string, any, any, any, any>;
591
+ export type RouterRouteData = Pick<AnyRoute, "id" | "endpoint" | "method" | "pattern" | "handler" | "variant">;
592
+ export type RouterReturnData = {
593
+ route: RouterRouteData;
594
+ params: Record<string, string>;
595
+ search: Record<string, string>;
596
+ };
597
+ export interface RouterAdapterInterface {
598
+ find(req: CRequest): RouterReturnData | null;
599
+ list(): Array<RouterRouteData>;
600
+ add(data: RouterRouteData): void;
601
+ }
602
+ export type MiddlewareHandler = Func<[
603
+ Context
604
+ ], MaybePromise<void>>;
605
+ export type DynamicRouteDefinition<Path extends string = string> = {
606
+ method: Method;
607
+ path: Path;
608
+ } | Path;
609
+ declare abstract class RouteAbstract<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown> implements RouteInterface<Path, B, S, P, R> {
574
610
  abstract variant: RouteVariant;
575
611
  abstract endpoint: Path;
576
612
  abstract method: OrString<Method>;
@@ -578,13 +614,18 @@ declare abstract class RouteAbstract<Path extends string = string, B = unknown,
578
614
  abstract id: RouteId;
579
615
  abstract handler: RouteHandler<B, S, P, R>;
580
616
  abstract model?: RouteModel<B, S, P, R>;
581
- protected resolveEndpoint(definition: RouteDefinition<Path>, variant: RouteVariant): Path;
582
- protected resolveMethod(definition: RouteDefinition<Path>): Method;
583
617
  protected resolvePattern(endpoint: Path): RegExp;
584
618
  protected resolveId(method: string, endpoint: Path): RouteId;
619
+ static makeRouteId(method: string, endpoint: string): RouteId;
620
+ static makeRoutePattern(endpoint: string): RegExp;
621
+ }
622
+ export declare abstract class DynamicRouteAbstract<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown> extends RouteAbstract<Path, B, S, P, R> {
623
+ variant: RouteVariant;
624
+ protected resolveEndpoint(definition: DynamicRouteDefinition<Path>): Path;
625
+ protected resolveMethod(definition: DynamicRouteDefinition<Path>): Method;
585
626
  }
586
627
  /**
587
- * Defines an HTTP endpoint. Accepts a {@link RouteDefinition} which can either be a plain
628
+ * Defines an HTTP endpoint. Accepts a {@link DynamicRouteDefinition} which can either be a plain
588
629
  * path string (defaults to GET) or an object with a `method` and `path` for other HTTP methods.
589
630
  *
590
631
  * The handler receives a {@link Context} and can return any data, a {@link CResponse} directly,
@@ -606,66 +647,42 @@ declare abstract class RouteAbstract<Path extends string = string, B = unknown,
606
647
  * return { created: c.body.name };
607
648
  * }, { body: UserModel });
608
649
  */
609
- export declare class Route<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown> extends RouteAbstract<Path, B, S, P, R> {
610
- constructor(definition: RouteDefinition<Path>, handler: RouteHandler<B, S, P, R>, model?: RouteModel<B, S, P, R>);
611
- variant: RouteVariant;
612
- endpoint: Path;
650
+ declare class DynamicRoute<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown> extends DynamicRouteAbstract<Path, B, S, P, R> {
651
+ constructor(definition: DynamicRouteDefinition<Path>, handler: RouteHandler<B, S, P, R>, model?: RouteModel<B, S, P, R>);
652
+ id: RouteId;
613
653
  method: OrString<Method>;
654
+ endpoint: Path;
614
655
  pattern: RegExp;
615
- id: RouteId;
616
656
  handler: RouteHandler<B, S, P, R>;
617
- model?: RouteModel<B, S, P, R> | undefined;
618
- static makeRouteId(method: string, endpoint: string): RouteId;
619
- static makeRoutePattern(endpoint: string): RegExp;
657
+ model?: RouteModel<B, S, P, R>;
620
658
  }
621
- export type AnyRoute = Route<string, any, any, any, any>;
622
- export type MiddlewareHandler = Func<[
623
- Context
624
- ], MaybePromise<void>>;
659
+ export type R = string | CResponse;
625
660
  export type StaticRouteHandler<B = unknown, S = unknown, P = unknown> = Func<[
626
- context: Context<B, S, P, string | CResponse>,
661
+ context: Context<B, S, P, R>,
627
662
  content: string
628
- ], MaybePromise<string | CResponse>>;
663
+ ], MaybePromise<R>>;
629
664
  export type StaticRouteDefinition = string | {
630
665
  filePath: string;
631
666
  stream: true;
632
667
  disposition?: "attachment" | "inline";
633
668
  };
634
- /**
635
- * Defines a route that serves a static file. Accepts a path and a {@link StaticRouteDefinition}
636
- * which can either be a plain file path string for a standard file response, or an object
637
- * with `stream: true` to stream the file directly from disk — useful for large files like
638
- * videos, PDFs, or large assets where reading the entire file into memory is undesirable.
639
- *
640
- * An optional custom handler can be provided to intercept the file content before it is sent,
641
- * for example to modify headers or transform the content. Route instantiation automatically
642
- * registers to the router.
643
- *
644
- * @example
645
- * // Serve a file normally
646
- * new StaticRoute("/style", "assets/style.css");
647
- *
648
- * // Stream a large file
649
- * new StaticRoute("/video", { filePath: "assets/video.mp4", stream: true });
650
- *
651
- * // Custom handler
652
- * new StaticRoute("/doc", "assets/doc.txt", (c, content) => {
653
- * c.res.headers.set("x-custom", "value");
654
- * return content;
655
- * });
656
- */
657
- export declare class StaticRoute<Path extends string = string, B = unknown, S = unknown, P = unknown> extends RouteAbstract<Path, B, S, P, string | CResponse> {
658
- constructor(path: Path, definition: StaticRouteDefinition, handler?: StaticRouteHandler<B, S, P>, model?: RouteModel<B, S, P, string | CResponse>);
659
- id: RouteId;
669
+ type R$1 = string | CResponse;
670
+ export declare abstract class StaticRouteAbstract<Path extends string = string, B = unknown, S = unknown, P = unknown> extends RouteAbstract<Path, B, S, P, R$1> {
660
671
  variant: RouteVariant;
661
- method: Method;
672
+ protected abstract filePath: string;
673
+ protected resolveFilePath(definition: StaticRouteDefinition): string;
674
+ protected resolveHandler(definition: StaticRouteDefinition, customHandler?: StaticRouteHandler<B, S, P>): RouteHandler<B, S, P, R$1>;
675
+ }
676
+ type R$2 = string | CResponse;
677
+ export declare class StaticRoute<Path extends string = string, B = unknown, S = unknown, P = unknown> extends StaticRouteAbstract<Path, B, S, P> {
678
+ constructor(path: Path, definition: StaticRouteDefinition, handler?: StaticRouteHandler<B, S, P>, model?: RouteModel<B, S, P, R$2>);
679
+ id: RouteId;
680
+ method: OrString<Method>;
662
681
  endpoint: Path;
663
682
  pattern: RegExp;
664
- model?: RouteModel<B, S, P, string | CResponse> | undefined;
665
- handler: RouteHandler<B, S, P, string | CResponse>;
666
- private filePath;
667
- private resolveFilePath;
668
- private resolveHandler;
683
+ handler: RouteHandler<B, S, P, R$2>;
684
+ model?: RouteModel<B, S, P, R$2>;
685
+ protected filePath: string;
669
686
  }
670
687
  export type ControllerOptions = {
671
688
  prefix?: string;
@@ -675,7 +692,7 @@ export type ControllerOptions = {
675
692
  * Base class for grouping related routes under a shared prefix and optional middleware.
676
693
  * Extend this class to create your own controllers.
677
694
  *
678
- * All routes registered via {@link ControllerAbstract.route} and {@link ControllerAbstract.staticRoute}
695
+ * All routes registered via {@link Controller.route} and {@link Controller.staticRoute}
679
696
  * automatically inherit the controller's prefix and run `beforeEach` before the handler if set.
680
697
  *
681
698
  * @example
@@ -693,16 +710,16 @@ export type ControllerOptions = {
693
710
  *
694
711
  * new UserController();
695
712
  */
696
- declare abstract class ControllerAbstract {
713
+ export declare abstract class Controller {
697
714
  constructor(opts?: ControllerOptions);
698
715
  routeIds: Set<RouteId>;
699
716
  protected prefix?: string;
700
717
  protected beforeEach?: MiddlewareHandler;
701
718
  /**
702
- * Registers a dynamic route under this controller. Behaves identically to {@link Route}
719
+ * Registers a dynamic route under this controller. Behaves identically to {@link DynamicRoute}
703
720
  * but automatically prepends the controller prefix and runs `beforeEach` before the handler.
704
721
  */
705
- protected route<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown>(...args: ConstructorParameters<typeof Route<Path, B, S, P, R>>): Route<Path, B, S, P, R>;
722
+ protected route<Path extends string = string, B = unknown, S = unknown, P = unknown, R = unknown>(...args: ConstructorParameters<typeof DynamicRoute<Path, B, S, P, R>>): DynamicRoute<Path, B, S, P, R>;
706
723
  /**
707
724
  * Registers a static file route under this controller. Behaves identically to {@link StaticRoute}
708
725
  * but automatically prepends the controller prefix.
@@ -710,7 +727,11 @@ declare abstract class ControllerAbstract {
710
727
  protected staticRoute<Path extends string = string, B = unknown, S = unknown, P = unknown>(...args: ConstructorParameters<typeof StaticRoute<Path, B, S, P>>): StaticRoute<Path, B, S, P>;
711
728
  private resolveRouteDefinition;
712
729
  }
713
- export type MiddlewareUseOn = Array<AnyRoute | ControllerAbstract> | AnyRoute | ControllerAbstract | "*";
730
+ export type MiddlewareUseOn = Array<AnyRoute | Controller> | AnyRoute | Controller | "*";
731
+ export declare abstract class MiddlewareAbstract {
732
+ abstract useOn: MiddlewareUseOn;
733
+ abstract handler: MiddlewareHandler;
734
+ }
714
735
  export type MiddlewareOptions = {
715
736
  useOn: MiddlewareUseOn;
716
737
  handler: MiddlewareHandler;
@@ -719,38 +740,96 @@ export type MiddlewareOptions = {
719
740
  * Simple middleware that runs before the Route "callback" parameters.
720
741
  * Manipulates context.
721
742
  * */
722
- export declare class Middleware {
743
+ export declare class Middleware extends MiddlewareAbstract {
723
744
  constructor(opts: MiddlewareOptions);
724
745
  useOn: MiddlewareUseOn;
725
746
  handler: MiddlewareHandler;
726
747
  }
727
- export type AnyRouteModel = RouteModel<any, any, any, any>;
728
- export type RouterRouteData = Pick<AnyRoute, "id" | "endpoint" | "method" | "pattern" | "handler">;
729
- export type RouterReturnData = {
730
- route: RouterRouteData;
731
- model: RouterModelData | undefined;
732
- middleware: MiddlewareHandler | undefined;
733
- params: Record<string, string>;
734
- search: Record<string, string>;
735
- };
736
- export interface RouterAdapterInterface {
737
- find(req: CRequest): RouterReturnData | null;
738
- list(): Array<RouterRouteData>;
739
- addRoute(data: RouterRouteData): void;
740
- addModel(route: AnyRoute, model: AnyRouteModel): void;
741
- addMiddleware(middleware: Middleware): void;
748
+ export interface CWebSocketInterface {
749
+ /**
750
+ * - if **0**, the message was **dropped**.
751
+ * - if **-1**, there is **backpressure** of messages.
752
+ * - if **>0**, it represents the **number of bytes sent**.
753
+ */
754
+ send(data: string | ArrayBufferLike): number;
755
+ publish(topic: string, data: string | ArrayBufferLike): number;
756
+ cork(callback: (ws: CWebSocketInterface) => unknown): unknown;
757
+ /**
758
+ * Closes the connection.
759
+ * To close the connection abruptly, use `terminate()`.
760
+ */
761
+ close(code?: number, reason?: string): void;
762
+ /**
763
+ * Abruptly close the connection.
764
+ * To gracefully close the connection, use `close()`.
765
+ */
766
+ terminate(): void;
767
+ subscribe(topic: string): void;
768
+ unsubscribe(topic: string): void;
769
+ isSubscribed(topic: string): boolean;
770
+ readonly subscriptions: string[];
771
+ /** The IP address of the client. */
772
+ readonly remoteAddress: string;
773
+ /**
774
+ * The ready state of the client.
775
+ *
776
+ * - if `0`, the client is connecting.
777
+ * - if `1`, the client is connected.
778
+ * - if `2`, the client is closing.
779
+ * - if `3`, the client is closed.
780
+ */
781
+ readonly readyState: 0 | 1 | 2 | 3;
782
+ }
783
+ export interface WebSocketHandlers {
784
+ onOpen?: Func<[
785
+ ws: CWebSocketInterface
786
+ ], MaybePromise<void>>;
787
+ onClose?: Func<[
788
+ ws: CWebSocketInterface,
789
+ code?: number,
790
+ reason?: string
791
+ ], MaybePromise<void>>;
792
+ onMessage: Func<[
793
+ ws: CWebSocketInterface,
794
+ message: string | Buffer
795
+ ], MaybePromise<void>>;
796
+ }
797
+ export declare class WebSocketRoute<Path extends string = string, B = unknown, S = unknown, P = unknown> extends RouteAbstract<Path, B, S, P, WebSocketRoute> {
798
+ constructor(path: Path, handlers: WebSocketHandlers);
799
+ id: RouteId;
800
+ method: OrString<Method>;
801
+ endpoint: Path;
802
+ pattern: RegExp;
803
+ model?: RouteModel<B, S, P, WebSocketRoute>;
804
+ handler: RouteHandler<B, S, P, WebSocketRoute>;
805
+ variant: RouteVariant;
806
+ readonly onOpen?: Func<[
807
+ ws: CWebSocketInterface
808
+ ], MaybePromise<void>>;
809
+ readonly onClose?: Func<[
810
+ ws: CWebSocketInterface,
811
+ code?: number,
812
+ reason?: string
813
+ ], MaybePromise<void>>;
814
+ readonly onMessage: Func<[
815
+ ws: CWebSocketInterface,
816
+ message: string | Buffer
817
+ ], MaybePromise<void>>;
742
818
  }
743
819
  declare class Router {
820
+ private adapter;
744
821
  constructor(adapter?: RouterAdapterInterface);
745
- models: AnyRouteModel[];
746
- private _adapter;
822
+ private modelRegistry;
823
+ private middlewareRegistry;
747
824
  private cache;
748
- checkPossibleCollision(n: RouterRouteData): boolean;
749
- addModel(route: AnyRoute, model: AnyRouteModel): void;
750
825
  addMiddleware(middleware: Middleware): void;
751
- addRoute(r: AnyRoute): void;
826
+ findMiddleware(id: RouteId | "*"): Func<[
827
+ Context
828
+ ]>;
829
+ addRoute(route: AnyRoute): void;
752
830
  findRouteHandler(req: CRequest): Func<[
753
- ], Promise<CResponse>>;
831
+ Context
832
+ ], Promise<CResponse | WebSocketRoute>> | null;
754
833
  getRouteList(): Array<[
755
834
  string,
756
835
  string
@@ -761,24 +840,35 @@ declare class GlobalRouterStore extends StoreAbstract<Router | null> {
761
840
  get(): Router;
762
841
  }
763
842
  export type CorsOptions = {
843
+ /** Which origins are allowed to access the resource */
764
844
  allowedOrigins?: string[];
845
+ /** Which HTTP methods are allowed (GET, POST, etc.) */
765
846
  allowedMethods?: string[];
847
+ /** Which headers can be sent in the request */
766
848
  allowedHeaders?: HeaderKey[];
849
+ /** Which headers should be exposed to the client/browser JavaScript
850
+ * These are response headers that the client can read
851
+ * @example ['RateLimit-Limit', 'RateLimit-Remaining', 'X-Custom-Header']
852
+ */
853
+ exposedHeaders?: HeaderKey[];
854
+ /** Whether to expose cookies and auth headers to the client */
767
855
  credentials?: boolean;
768
856
  };
769
857
  /** Simple cors helper object to set cors headers */
770
- export declare class Cors {
771
- readonly opts: CorsOptions | undefined;
858
+ declare class XCors {
859
+ opts: CorsOptions | undefined;
772
860
  constructor(opts: CorsOptions | undefined);
773
861
  private readonly originKey;
774
862
  private readonly methodsKey;
775
863
  private readonly headersKey;
776
864
  private readonly credentialsKey;
777
- getCorsHeaders(req: CRequest, res: CResponse): CHeaders;
865
+ private readonly exposedHeadersKey;
866
+ private getCorsHeaders;
778
867
  apply(req: CRequest, res: CResponse): void;
868
+ updateOptions(newOpts: CorsOptions): void;
779
869
  }
780
- declare class GlobalCorsStore extends StoreAbstract<Cors | null> {
781
- protected value: Cors | null;
870
+ declare class GlobalCorsStore extends StoreAbstract<XCors | null> {
871
+ protected value: XCors | null;
782
872
  }
783
873
  export type ConfigEnvKey = OrString<keyof Env>;
784
874
  export type ConfigValueParser<T> = Func<[
@@ -803,11 +893,6 @@ declare class CError extends Error {
803
893
  constructor(message: string, status: Status, data?: unknown | undefined);
804
894
  toResponse(): CResponse;
805
895
  isStatusOf(status: Status): boolean;
806
- static internalServerError(msg?: string): CError;
807
- static badRequest(msg?: string): CError;
808
- static notFound(msg?: string): CError;
809
- static methodNotAllowed(msg?: string): CError;
810
- static unprocessableEntity(msg?: string): CError;
811
896
  }
812
897
  export type InferSchema<T extends Schema> = StandardSchemaV1.InferOutput<T>;
813
898
  export type ServerTlsOptions = {
@@ -823,7 +908,6 @@ export type ServerOptions = {
823
908
  export type ServeArgs = {
824
909
  port: number;
825
910
  hostname?: "0.0.0.0" | "127.0.0.1" | "localhost" | (string & {}) | undefined;
826
- fetch: (request: Request) => Promise<Response>;
827
911
  };
828
912
  export type ErrorHandler<R = unknown> = Func<[
829
913
  Error
@@ -837,7 +921,13 @@ export type AfterResponseHandler = Func<[
837
921
  export interface ServerInterface {
838
922
  serve(options: ServeArgs): void;
839
923
  close(): Promise<void>;
924
+ get routes(): Array<[
925
+ string,
926
+ string
927
+ ]>;
840
928
  setGlobalPrefix(value: string): void;
929
+ listen(port: ServeArgs["port"], hostname?: ServeArgs["hostname"]): Promise<void>;
930
+ handle(request: Request): Promise<Response>;
841
931
  /**
842
932
  *
843
933
  * Default error handler response will have a status of C.Error or 500 and json:
@@ -854,6 +944,7 @@ export interface ServerInterface {
854
944
  * ```
855
945
  */
856
946
  setOnError(handler: ErrorHandler): void;
947
+ defaultErrorHandler: ErrorHandler;
857
948
  /**
858
949
  *
859
950
  * Default not found handler response will have a status of 404 and json:
@@ -863,11 +954,18 @@ export interface ServerInterface {
863
954
  * ```
864
955
  */
865
956
  setOnNotFound(handler: RequestHandler): void;
866
- setOnBeforeListen(handler: () => MaybePromise<void>): void;
957
+ defaultNotFoundHandler: RequestHandler;
958
+ setOnBeforeListen(handler: Func<[
959
+ ], MaybePromise<void>> | undefined): void;
960
+ defaultOnBeforeListen: Func<[
961
+ ], MaybePromise<void>> | undefined;
867
962
  setOnBeforeClose(handler: () => MaybePromise<void>): void;
868
- setOnAfterResponse(handler: AfterResponseHandler): void;
869
- listen(port: ServeArgs["port"], hostname: ServeArgs["hostname"]): Promise<void>;
870
- handle(request: Request): Promise<Response>;
963
+ defaultOnBeforeClose: Func<[
964
+ ], MaybePromise<void>> | undefined;
965
+ setOnAfterResponse(handler: AfterResponseHandler | undefined): void;
966
+ defaultOnAfterResponse: AfterResponseHandler | undefined;
967
+ setOnPreflight(handler: RequestHandler): void;
968
+ defaultPreflightHandler: RequestHandler;
871
969
  }
872
970
  declare abstract class ServerAbstract implements ServerInterface {
873
971
  protected readonly opts?: ServerOptions | undefined;
@@ -881,7 +979,9 @@ declare abstract class ServerAbstract implements ServerInterface {
881
979
  setGlobalPrefix(value: string): void;
882
980
  listen(port: ServeArgs["port"], hostname?: ServeArgs["hostname"]): Promise<void>;
883
981
  handle(request: Request): Promise<Response>;
884
- private getResponse;
982
+ protected handleRequest(req: CRequest, onUpgrade: Func<[
983
+ WebSocketRoute
984
+ ], undefined>): Promise<Response | undefined>;
885
985
  protected handleBeforeListen: Func<[
886
986
  ], MaybePromise<void>> | undefined;
887
987
  setOnBeforeListen(handler: Func<[
@@ -902,20 +1002,12 @@ declare abstract class ServerAbstract implements ServerInterface {
902
1002
  protected handleNotFound: RequestHandler;
903
1003
  setOnNotFound(handler: RequestHandler): void;
904
1004
  defaultNotFoundHandler: RequestHandler;
905
- protected handleMethodNotAllowed: RequestHandler;
906
- defaultMethodNotFoundHandler: RequestHandler;
1005
+ protected handlePreflight: RequestHandler;
1006
+ setOnPreflight(handler: RequestHandler): void;
1007
+ defaultPreflightHandler: RequestHandler;
907
1008
  }
908
- declare class ServerUsingBun extends ServerAbstract {
909
- private app;
910
- serve(args: ServeArgs): void;
911
- close(): Promise<void>;
912
- private createApp;
913
- }
914
- /**
915
- * Server is the entrypoint to the app. It must be initialized before registering routes and middlewares.
916
- * ".listen()" to start listening.
917
- */
918
- export declare class Server extends ServerUsingBun {
1009
+ declare const Adapted$1: ConstructorOf<typeof ServerAbstract, ServerInterface>;
1010
+ export declare class Server extends Adapted$1 {
919
1011
  }
920
1012
  export interface XFileInterface {
921
1013
  get name(): string;
@@ -936,32 +1028,169 @@ declare abstract class XFileAbstract implements XFileInterface {
936
1028
  get extension(): string;
937
1029
  get mimeType(): string;
938
1030
  }
939
- declare class XFileUsingBun extends XFileAbstract implements XFileInterface {
940
- constructor(...args: ConstructorParameters<typeof XFileAbstract>);
941
- file: Bun.BunFile;
942
- exists(): Promise<boolean>;
943
- text(): Promise<string>;
944
- stream(): ReadableStream;
945
- }
946
- declare class XFile extends XFileUsingBun {
1031
+ declare const Adapted$2: ConstructorOf<typeof XFileAbstract, XFileInterface>;
1032
+ declare class XFile extends Adapted$2 {
947
1033
  }
948
1034
  /** Abstract class for repository implementations */
949
- declare abstract class RepositoryAbstract {
1035
+ declare abstract class XRepository {
950
1036
  readonly db: DatabaseClientInterface;
951
1037
  constructor(db: DatabaseClientInterface);
952
1038
  }
953
1039
  /** Router Adapter for the "memoirist" package. */
954
1040
  export declare class MemoiristAdapter implements RouterAdapterInterface {
955
1041
  private router;
956
- private pendingMiddlewares;
957
1042
  find(req: CRequest): RouterReturnData | null;
958
1043
  list(): Array<RouterRouteData>;
959
- addRoute(data: RouterRouteData): void;
960
- addModel(route: AnyRoute, model: AnyRouteModel): void;
961
- addMiddleware(middleware: Middleware): void;
1044
+ add(data: RouterRouteData): void;
1045
+ }
1046
+ export interface BasicRedisClientInterface {
1047
+ get: Func<[
1048
+ string
1049
+ ], Promise<string>>;
1050
+ set: Func<[
1051
+ string,
1052
+ string,
1053
+ string,
1054
+ number
1055
+ ], Promise<void>>;
1056
+ del: Func<string[], Promise<void>>;
1057
+ keys: Func<[
1058
+ string
1059
+ ], Promise<string[]>>;
1060
+ }
1061
+ export type RateLimitIdPrefix = "u" | "i" | "f";
1062
+ export type RateLimitConfig<R extends BasicRedisClientInterface | undefined = undefined> = {
1063
+ /**
1064
+ * Limits based on identifier type:
1065
+ * u: Authenticated users — higher limit, accountable identity (e.g., 120 requests)
1066
+ * i: IP-based — moderate, may be shared (NAT, proxies) (e.g., 60 requests)
1067
+ * f: Fingerprint / anonymous — lowest, least trustworthy (e.g., 20 requests)
1068
+ * */
1069
+ limits: Record<RateLimitIdPrefix, number>;
1070
+ /** Time window in milliseconds during which the rate limit applies (default: 60,000ms = 1 minute) */
1071
+ windowMs: number;
1072
+ /** How often to rotate the salt used for hashing identifiers (default: 24h)
1073
+ * Prevents long-term tracking and adds an extra layer of privacy */
1074
+ saltRotateMs: number;
1075
+ /** Probability (0-1) of triggering a cleanup of expired entries on each request
1076
+ * Balances memory usage against performance (default: 0.005 = 0.5%) */
1077
+ cleanProbability: number;
1078
+ /** Maximum number of entries before forcing a cleanup
1079
+ * Prevents unbounded memory growth (default: 50,000) */
1080
+ maxStoreSize: number;
1081
+ /** Storage backend type:
1082
+ * - memory: Fastest, but resets on server restart (default)
1083
+ * - file: Persistent across restarts, good for single instance
1084
+ * - redis: Distributed, for multi-instance deployments
1085
+ * */
1086
+ storeType: "memory" | "file" | "redis";
1087
+ /** Redis client instance (required when storeType = "redis") */
1088
+ redisClient?: R;
1089
+ /** Directory path for file-based storage (required when storeType = "file") */
1090
+ storeDir?: string;
1091
+ /**
1092
+ * Customizable HTTP header names for rate limit information.
1093
+ * Allows integration with different API conventions or frontend expectations.
1094
+ *
1095
+ * @example
1096
+ * // Custom header names (e.g., for legacy systems)
1097
+ * headerNames: {
1098
+ * limit: "X-RateLimit-Limit",
1099
+ * remaining: "X-RateLimit-Remaining",
1100
+ * reset: "X-RateLimit-Reset",
1101
+ * retryAfter: "Retry-After"
1102
+ * }
1103
+ *
1104
+ * @default Uses standard RateLimit-* headers as defined in IETF draft:
1105
+ * - limit: "RateLimit-Limit"
1106
+ * - remaining: "RateLimit-Remaining"
1107
+ * - reset: "RateLimit-Reset"
1108
+ * - retryAfter: "Retry-After"
1109
+ */
1110
+ headerNames: {
1111
+ /** Header name for the maximum allowed requests in the current window */
1112
+ limit: string;
1113
+ /** Header name for the remaining requests in the current window */
1114
+ remaining: string;
1115
+ /** Header name for the timestamp (Unix seconds) when the window resets */
1116
+ reset: string;
1117
+ /** Header name for seconds to wait before retrying when rate limited */
1118
+ retryAfter: string;
1119
+ };
1120
+ };
1121
+ declare class XRateLimiter {
1122
+ constructor(config?: Partial<RateLimitConfig>);
1123
+ private readonly config;
1124
+ private store;
1125
+ private storedSalt;
1126
+ private saltRotatesAt;
1127
+ getResult(headers: CHeaders): Promise<{
1128
+ success: boolean;
1129
+ headers: CHeaders;
1130
+ }>;
1131
+ private getId;
1132
+ private getMax;
1133
+ private extractIp;
1134
+ private isValidIp;
1135
+ private salt;
1136
+ private maybeCleanStore;
1137
+ private cleanStore;
1138
+ private hash;
1139
+ private getRandomBytes;
1140
+ clearStore(): Promise<void>;
1141
+ getStoreSize(): Promise<number>;
1142
+ private readonly defaultConfig;
1143
+ private resolveStore;
1144
+ private registerMiddleware;
1145
+ }
1146
+ export interface RateLimitEntry {
1147
+ hits: number;
1148
+ resetAt: number;
1149
+ }
1150
+ export interface RateLimitStoreInterface {
1151
+ get(id: string): Promise<RateLimitEntry | undefined>;
1152
+ set(id: string, entry: RateLimitEntry): Promise<void>;
1153
+ delete(id: string): Promise<void>;
1154
+ cleanup(now: number): Promise<void>;
1155
+ clear(): Promise<void>;
1156
+ size(): Promise<number>;
1157
+ }
1158
+ export declare class RateLimiterFileStore implements RateLimitStoreInterface {
1159
+ private readonly storeDir;
1160
+ private locks;
1161
+ constructor(storeDir?: string);
1162
+ private ensureStoreDir;
1163
+ private getFilePath;
1164
+ get(id: string): Promise<RateLimitEntry | undefined>;
1165
+ set(id: string, entry: RateLimitEntry): Promise<void>;
1166
+ delete(id: string): Promise<void>;
1167
+ cleanup(now: number): Promise<void>;
1168
+ clear(): Promise<void>;
1169
+ size(): Promise<number>;
1170
+ }
1171
+ export declare class RateLimiterMemoryStore implements RateLimitStoreInterface {
1172
+ private store;
1173
+ private locks;
1174
+ get(id: string): Promise<RateLimitEntry | undefined>;
1175
+ set(id: string, entry: RateLimitEntry): Promise<void>;
1176
+ delete(id: string): Promise<void>;
1177
+ cleanup(now: number): Promise<void>;
1178
+ clear(): Promise<void>;
1179
+ size(): Promise<number>;
1180
+ }
1181
+ export declare class RateLimiterRedisStore<R extends BasicRedisClientInterface> implements RateLimitStoreInterface {
1182
+ private readonly redis;
1183
+ private readonly prefix;
1184
+ constructor(redis: R, prefix?: string);
1185
+ get(id: string): Promise<RateLimitEntry | undefined>;
1186
+ set(id: string, entry: RateLimitEntry): Promise<void>;
1187
+ delete(id: string): Promise<void>;
1188
+ cleanup(_now: number): Promise<void>;
1189
+ clear(): Promise<void>;
1190
+ size(): Promise<number>;
962
1191
  }
963
1192
  export type UnknownObject = Record<string, unknown>;
964
- export declare class Parser {
1193
+ declare class XParser {
965
1194
  static parse<T = UnknownObject>(data: unknown, validate?: SchemaValidator<T>): Promise<T>;
966
1195
  static issuesToErrorMessage(issues: readonly StandardSchemaV1.Issue[]): string;
967
1196
  static parseUrlData<P = UnknownObject>(params: Record<string, string>, validate?: SchemaValidator<P>): Promise<P>;
@@ -978,7 +1207,7 @@ export type Prettify<T> = {
978
1207
  [K in keyof T]: T[K];
979
1208
  } & {};
980
1209
  /** If you prefer to put all schemas into a single object, this will be helpful */
981
- export type InferModel<T extends Record<string, any>> = {
1210
+ type XInferModel<T extends Record<string, any>> = {
982
1211
  [K in keyof T]: T[K] extends RouteModel<any, any, any, any> ? Prettify<(T[K]["body"] extends Schema ? {
983
1212
  body: InferSchema<T[K]["body"]>;
984
1213
  } : {}) & (T[K]["search"] extends Schema ? {
@@ -989,21 +1218,21 @@ export type InferModel<T extends Record<string, any>> = {
989
1218
  response: InferSchema<T[K]["response"]>;
990
1219
  } : {})> : T[K] extends Schema ? InferSchema<T[K]> : never;
991
1220
  };
992
- export declare const _prefixStore: GlobalPrefixStore;
993
- export declare const _routerStore: GlobalRouterStore;
994
- export declare const _corsStore: GlobalCorsStore;
1221
+ export declare const $prefixStore: GlobalPrefixStore;
1222
+ export declare const $routerStore: GlobalRouterStore;
1223
+ export declare const $corsStore: GlobalCorsStore;
995
1224
 
996
1225
  declare namespace X {
997
- export { Cors, CorsOptions, InferModel, MemoiristAdapter, Parser, RepositoryAbstract as Repository, XFile as File };
1226
+ export { CorsOptions, MemoiristAdapter, RateLimiterFileStore, RateLimiterMemoryStore, RateLimiterRedisStore, RouterAdapterInterface, XCors as Cors, XFile as File, XInferModel as InferModel, XParser as Parser, XRateLimiter as RateLimiter, XRepository as Repository };
998
1227
  }
999
1228
  declare namespace C {
1000
- export { CError as Error, CHeaders as Headers, CHeadersInit as HeadersInit, CRequest as Request, CRequestInfo as RequestInfo, CRequestInit as RequestInit, CResponse as Response, CResponseBody as ResponseBody, CResponseInit as ResponseInit, CommonHeaders, Config, Context, ControllerAbstract as Controller, ControllerOptions, CookieOptions, Cookies, CookiesInit, HeaderKey, InferSchema, Method, Middleware, MiddlewareHandler, MiddlewareOptions, MiddlewareUseOn, Route, RouteDefinition, RouteHandler, Schema, SchemaValidator, ServeArgs, Server, ServerOptions, ServerTlsOptions, StaticRoute, StaticRouteHandler, Status };
1229
+ export { CError as Error, CHeaders as Headers, CHeadersInit as HeadersInit, CRequest as Request, CRequestInfo as RequestInfo, CRequestInit as RequestInit, CResponse as Response, CResponseBody as ResponseBody, CResponseInit as ResponseInit, CommonHeaders, Config, Context, Controller, ControllerOptions, CookieOptions, Cookies, CookiesInit, DynamicRoute as Route, DynamicRouteAbstract, DynamicRouteDefinition, HeaderKey, InferSchema, Method, Middleware, MiddlewareAbstract, MiddlewareHandler, MiddlewareOptions, MiddlewareUseOn, RouteHandler, RouteInterface, Schema, SchemaValidator, ServeArgs, Server, ServerOptions, StaticRoute, StaticRouteAbstract, StaticRouteDefinition, StaticRouteHandler, Status, WebSocketRoute };
1001
1230
  }
1002
1231
  declare namespace _default {
1003
- export { CError as Error, CHeaders as Headers, CHeadersInit as HeadersInit, CRequest as Request, CRequestInfo as RequestInfo, CRequestInit as RequestInit, CResponse as Response, CResponseBody as ResponseBody, CResponseInit as ResponseInit, CommonHeaders, Config, Context, ControllerAbstract as Controller, ControllerOptions, CookieOptions, Cookies, CookiesInit, HeaderKey, InferSchema, Method, Middleware, MiddlewareHandler, MiddlewareOptions, MiddlewareUseOn, Route, RouteDefinition, RouteHandler, Schema, SchemaValidator, ServeArgs, Server, ServerOptions, ServerTlsOptions, StaticRoute, StaticRouteHandler, Status };
1232
+ export { CError as Error, CHeaders as Headers, CHeadersInit as HeadersInit, CRequest as Request, CRequestInfo as RequestInfo, CRequestInit as RequestInit, CResponse as Response, CResponseBody as ResponseBody, CResponseInit as ResponseInit, CommonHeaders, Config, Context, Controller, ControllerOptions, CookieOptions, Cookies, CookiesInit, DynamicRoute as Route, DynamicRouteAbstract, DynamicRouteDefinition, HeaderKey, InferSchema, Method, Middleware, MiddlewareAbstract, MiddlewareHandler, MiddlewareOptions, MiddlewareUseOn, RouteHandler, RouteInterface, Schema, SchemaValidator, ServeArgs, Server, ServerOptions, StaticRoute, StaticRouteAbstract, StaticRouteDefinition, StaticRouteHandler, Status, WebSocketRoute };
1004
1233
  }
1005
1234
  declare namespace Extra {
1006
- export { Cors, CorsOptions, InferModel, MemoiristAdapter, Parser, RepositoryAbstract as Repository, XFile as File };
1235
+ export { CorsOptions, MemoiristAdapter, RateLimiterFileStore, RateLimiterMemoryStore, RateLimiterRedisStore, RouterAdapterInterface, XCors as Cors, XFile as File, XInferModel as InferModel, XParser as Parser, XRateLimiter as RateLimiter, XRepository as Repository };
1007
1236
  }
1008
1237
 
1009
1238
  export {
@@ -1018,11 +1247,15 @@ export {
1018
1247
  CResponse as Response,
1019
1248
  CResponseBody as ResponseBody,
1020
1249
  CResponseInit as ResponseInit,
1021
- ControllerAbstract as Controller,
1250
+ DynamicRoute as Route,
1022
1251
  Extra,
1023
- RepositoryAbstract as Repository,
1024
1252
  X,
1253
+ XCors as Cors,
1025
1254
  XFile as File,
1255
+ XInferModel as InferModel,
1256
+ XParser as Parser,
1257
+ XRateLimiter as RateLimiter,
1258
+ XRepository as Repository,
1026
1259
  };
1027
1260
 
1028
1261
  export {};