barejs 0.1.50 → 0.1.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -32
- package/dist/index.js +123 -115
- package/dist/types/client/index.d.ts +23 -23
- package/dist/types/core/bare.d.ts +83 -5
- package/dist/types/core/context.d.ts +3 -1
- package/dist/types/core/router.d.ts +71 -10
- package/dist/types/index.d.ts +10 -5
- package/dist/types/security/auth.d.ts +22 -4
- package/dist/types/security/idempotency.d.ts +3 -0
- package/dist/types/security/rateLimit.d.ts +3 -0
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/store.d.ts +36 -0
- package/dist/types/security/validators.d.ts +2 -0
- package/dist/types/utils/compress.d.ts +15 -0
- package/dist/types/utils/health.d.ts +17 -0
- package/dist/types/utils/logger.d.ts +22 -0
- package/dist/types/utils/openapi.d.ts +23 -1
- package/dist/types/utils/static.d.ts +8 -0
- package/llms.txt +19 -20
- package/package.json +1 -1
- package/src/client/index.ts +58 -17
- package/src/core/bare.ts +313 -58
- package/src/core/context.ts +38 -18
- package/src/core/router.ts +110 -16
- package/src/index.ts +18 -5
- package/src/security/auth.ts +286 -38
- package/src/security/hash.ts +8 -2
- package/src/security/idempotency.ts +133 -20
- package/src/security/rateLimit.ts +41 -28
- package/src/security/resilience.ts +91 -0
- package/src/security/store.ts +151 -0
- package/src/security/validators.ts +13 -5
- package/src/utils/compress.ts +80 -0
- package/src/utils/health.ts +65 -0
- package/src/utils/logger.ts +66 -0
- package/src/utils/openapi.ts +10 -0
- package/src/utils/static.ts +68 -9
|
@@ -13,38 +13,38 @@ type ExtractParams<Path extends string> = Path extends `${string}:${infer Param}
|
|
|
13
13
|
} : Path extends `${string}:${infer Param}` ? {
|
|
14
14
|
[K in Param]: string | number;
|
|
15
15
|
} : Record<string, never>;
|
|
16
|
-
export
|
|
16
|
+
export interface RouteEndpoint {
|
|
17
17
|
method: string;
|
|
18
|
+
path?: string;
|
|
18
19
|
params?: Record<string, any>;
|
|
20
|
+
query?: Record<string, any>;
|
|
21
|
+
headers?: Record<string, any>;
|
|
19
22
|
body?: any;
|
|
20
23
|
response?: any;
|
|
21
|
-
}
|
|
24
|
+
}
|
|
25
|
+
export type RouteSchema = Record<string, RouteEndpoint>;
|
|
26
|
+
type RouteKey<M extends string, P extends string> = `${M} ${P}`;
|
|
22
27
|
type PathsForMethod<Routes extends RouteSchema, M extends string> = {
|
|
23
|
-
[K in keyof Routes]: Routes[K]['method'] extends M ? K : never;
|
|
28
|
+
[K in keyof Routes]: Routes[K]['method'] extends M ? (Routes[K]['path'] extends string ? Routes[K]['path'] : K & string) : never;
|
|
24
29
|
}[keyof Routes] & string;
|
|
30
|
+
type LookupRoute<Routes extends RouteSchema, M extends string, P extends string> = RouteKey<M, P> extends keyof Routes ? Routes[RouteKey<M, P>] : P extends keyof Routes ? Routes[P] : never;
|
|
31
|
+
type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends boolean> = Omit<ClientRequestOptions, 'params' | 'query' | 'headers' | (WithBody extends true ? 'body' : never)> & {
|
|
32
|
+
params?: R['params'] extends Record<string, any> ? R['params'] : ExtractParams<P>;
|
|
33
|
+
query?: R['query'] extends Record<string, any> ? R['query'] : ClientRequestOptions['query'];
|
|
34
|
+
headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
|
|
35
|
+
} & (WithBody extends true ? {
|
|
36
|
+
body?: R['body'];
|
|
37
|
+
} : {});
|
|
25
38
|
export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
26
|
-
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(path: P, options?:
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
body?: Routes[P]['body'];
|
|
32
|
-
} : {})): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
33
|
-
put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(path: P, options?: ClientRequestOptions & (P extends keyof Routes ? {
|
|
34
|
-
params?: ExtractParams<P & string>;
|
|
35
|
-
body?: Routes[P]['body'];
|
|
36
|
-
} : {})): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
37
|
-
patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(path: P, options?: ClientRequestOptions & (P extends keyof Routes ? {
|
|
38
|
-
params?: ExtractParams<P & string>;
|
|
39
|
-
body?: Routes[P]['body'];
|
|
40
|
-
} : {})): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
41
|
-
delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(path: P, options?: ClientRequestOptions & (P extends keyof Routes ? {
|
|
42
|
-
params?: ExtractParams<P & string>;
|
|
43
|
-
} : {})): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
39
|
+
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
40
|
+
post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
41
|
+
put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
42
|
+
patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
43
|
+
delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
44
44
|
}
|
|
45
|
-
export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | {
|
|
45
|
+
export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | ({
|
|
46
46
|
fetch: (req: Request) => any;
|
|
47
|
-
}, clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
|
|
47
|
+
} & AppOrRoutes), clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
|
|
48
48
|
__routes?: infer R extends RouteSchema;
|
|
49
49
|
} ? R : RouteSchema>;
|
|
50
50
|
export {};
|
|
@@ -1,7 +1,15 @@
|
|
|
1
|
-
import { BareRouter } from './router';
|
|
1
|
+
import { BareRouter, type InferSchema, type PrefixRoutes } from './router';
|
|
2
2
|
import { Context } from './context';
|
|
3
3
|
import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
4
4
|
import { type OpenAPIOptions } from "../utils/openapi";
|
|
5
|
+
import type { RouteSchemas } from "../security/validators";
|
|
6
|
+
import type { RouteSchema } from "../client/index";
|
|
7
|
+
export interface CronOptions {
|
|
8
|
+
/** Execute the cron job immediately upon registration (default: false) */
|
|
9
|
+
runOnStart?: boolean;
|
|
10
|
+
/** Optional error handler when the cron callback throws or rejects */
|
|
11
|
+
onError?: (err: any) => void;
|
|
12
|
+
}
|
|
5
13
|
export interface WebSocketRouteHandler {
|
|
6
14
|
open?: (ws: any) => void;
|
|
7
15
|
message?: (ws: any, message: string | Buffer) => void;
|
|
@@ -13,23 +21,70 @@ export interface NotFoundResponse {
|
|
|
13
21
|
message: string;
|
|
14
22
|
[key: string]: any;
|
|
15
23
|
}
|
|
16
|
-
|
|
24
|
+
type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (ctx: Context & Derived & {
|
|
25
|
+
body: S extends {
|
|
26
|
+
body: infer B;
|
|
27
|
+
} ? InferSchema<B> : any;
|
|
28
|
+
query: S extends {
|
|
29
|
+
query: infer Q;
|
|
30
|
+
} ? InferSchema<Q> : Record<string, string>;
|
|
31
|
+
params: S extends {
|
|
32
|
+
params: infer Pa;
|
|
33
|
+
} ? InferSchema<Pa> : Record<string, any>;
|
|
34
|
+
}) => Res | Promise<Res>;
|
|
35
|
+
type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
|
|
36
|
+
<P extends string, S extends RouteSchemas, Res = S extends {
|
|
37
|
+
response: infer R;
|
|
38
|
+
} ? InferSchema<R> : any>(path: P, schemas: S, handler: TypedRouteHandler<Derived, S, Res>): BareJS<Derived, Routes & Record<`${M} ${P}`, {
|
|
39
|
+
method: M;
|
|
40
|
+
path: P;
|
|
41
|
+
params: S extends {
|
|
42
|
+
params: infer Pa;
|
|
43
|
+
} ? InferSchema<Pa> : Record<string, any>;
|
|
44
|
+
query: S extends {
|
|
45
|
+
query: infer Q;
|
|
46
|
+
} ? InferSchema<Q> : Record<string, any>;
|
|
47
|
+
headers: S extends {
|
|
48
|
+
headers: infer H;
|
|
49
|
+
} ? InferSchema<H> : Record<string, string>;
|
|
50
|
+
body: S extends {
|
|
51
|
+
body: infer B;
|
|
52
|
+
} ? InferSchema<B> : any;
|
|
53
|
+
response: S extends {
|
|
54
|
+
response: infer R;
|
|
55
|
+
} ? InferSchema<R> : Awaited<Res>;
|
|
56
|
+
}>>;
|
|
57
|
+
<P extends string, Res = any>(path: P, ...handlers: any[]): BareJS<Derived, Routes & Record<`${M} ${P}`, {
|
|
58
|
+
method: M;
|
|
59
|
+
path: P;
|
|
60
|
+
response: Awaited<Res>;
|
|
61
|
+
}>>;
|
|
62
|
+
};
|
|
63
|
+
export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}> extends BareRouter<Routes> {
|
|
64
|
+
readonly __routes: Routes;
|
|
17
65
|
private tree;
|
|
18
66
|
private pool;
|
|
19
67
|
private hotFetch?;
|
|
20
68
|
private compiled;
|
|
21
69
|
private poolMask;
|
|
22
70
|
private _useLog;
|
|
71
|
+
private _trustProxy;
|
|
23
72
|
private errorHandler?;
|
|
24
73
|
private wsRoutes;
|
|
25
74
|
private startHooks;
|
|
26
75
|
private stopHooks;
|
|
76
|
+
private crons;
|
|
27
77
|
private server?;
|
|
28
78
|
private shutdownHandler?;
|
|
29
79
|
private wsAdapter;
|
|
30
80
|
useLog(enabled?: boolean): this;
|
|
31
81
|
onStart(fn: () => void | Promise<void>): this;
|
|
32
82
|
onStop(fn: () => void | Promise<void>): this;
|
|
83
|
+
/**
|
|
84
|
+
* Built-in overlap-safe background interval scheduler.
|
|
85
|
+
* Automatically cleared when app.stop() is called.
|
|
86
|
+
*/
|
|
87
|
+
cron(name: string, intervalMs: number, fn: () => void | Promise<void>, options?: CronOptions): this;
|
|
33
88
|
stop(closeActiveConnections?: boolean): Promise<void>;
|
|
34
89
|
constructor(poolSize?: number);
|
|
35
90
|
private notFoundHandler;
|
|
@@ -38,12 +93,35 @@ export declare class BareJS extends BareRouter {
|
|
|
38
93
|
ws(path: string, handler: WebSocketRouteHandler): this;
|
|
39
94
|
docs(path?: string, options?: OpenAPIOptions): this;
|
|
40
95
|
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this;
|
|
96
|
+
get: AddRoute<Derived, Routes, 'GET'>;
|
|
97
|
+
post: AddRoute<Derived, Routes, 'POST'>;
|
|
98
|
+
put: AddRoute<Derived, Routes, 'PUT'>;
|
|
99
|
+
patch: AddRoute<Derived, Routes, 'PATCH'>;
|
|
100
|
+
delete: AddRoute<Derived, Routes, 'DELETE'>;
|
|
101
|
+
options: AddRoute<Derived, Routes, 'OPTIONS'>;
|
|
102
|
+
head: AddRoute<Derived, Routes, 'HEAD'>;
|
|
103
|
+
all: AddRoute<Derived, Routes, 'ALL'>;
|
|
104
|
+
route: <P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
|
|
105
|
+
use: {
|
|
106
|
+
<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
|
|
107
|
+
<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
|
|
108
|
+
(mw: any): BareJS<Derived, Routes>;
|
|
109
|
+
};
|
|
41
110
|
private _hasDerive;
|
|
42
|
-
derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T):
|
|
111
|
+
derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
|
|
43
112
|
private compileHandler;
|
|
44
113
|
compile(): void;
|
|
45
|
-
fetch: (req: Request) => any;
|
|
114
|
+
fetch: (req: Request, peerIp?: string) => any;
|
|
115
|
+
/**
|
|
116
|
+
* Ergonomic in-memory request helper for testing or internal invocations.
|
|
117
|
+
* Normalizes relative paths to http://localhost and delegates to this.fetch(req).
|
|
118
|
+
*/
|
|
119
|
+
request(path: string, init?: RequestInit): Promise<Response>;
|
|
46
120
|
name: string;
|
|
47
|
-
|
|
121
|
+
trustProxy(enabled?: boolean): this;
|
|
122
|
+
listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
|
|
123
|
+
maxRequestBodySize?: number;
|
|
124
|
+
trustProxy?: boolean;
|
|
125
|
+
}): Bun.Server<WebSocketRouteHandler> | Bun.Server<undefined>;
|
|
48
126
|
}
|
|
49
127
|
export { Context, typebox, t };
|
|
@@ -45,7 +45,9 @@ export declare class Context {
|
|
|
45
45
|
_cookies: Record<string, string> | undefined;
|
|
46
46
|
_setCookies: string[] | undefined;
|
|
47
47
|
_requestId: string | undefined;
|
|
48
|
-
|
|
48
|
+
_peerIp: string | undefined;
|
|
49
|
+
_trustProxy: boolean;
|
|
50
|
+
constructor(trustProxy?: boolean);
|
|
49
51
|
get query(): Record<string, string>;
|
|
50
52
|
getQuery(key: string): string | undefined;
|
|
51
53
|
get cookies(): Record<string, string>;
|
|
@@ -1,19 +1,80 @@
|
|
|
1
|
-
import { type Middleware, type Handler } from '../core/context';
|
|
1
|
+
import { type Context, type Middleware, type Handler } from '../core/context';
|
|
2
2
|
import { type RouteSchemas } from '../security/validators';
|
|
3
|
+
import type { RouteEndpoint, RouteSchema } from '../client/index';
|
|
3
4
|
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
4
|
-
export
|
|
5
|
+
export type InferSchema<S> = S extends {
|
|
6
|
+
static: infer T;
|
|
7
|
+
} ? T : S extends {
|
|
8
|
+
_output: infer T;
|
|
9
|
+
} ? T : any;
|
|
10
|
+
type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
|
|
11
|
+
type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
|
|
12
|
+
type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends '' ? '' : `/${StripTrailingSlash<StripLeadingSlash<P>>}`;
|
|
13
|
+
type JoinPath<P extends string, Sub extends string> = NormalizePrefix<P> extends '' ? (Sub extends '' ? '/' : (Sub extends `/${string}` ? Sub : `/${Sub}`)) : (StripLeadingSlash<Sub> extends '' ? NormalizePrefix<P> : `${NormalizePrefix<P>}/${StripLeadingSlash<Sub>}`);
|
|
14
|
+
export type PrefixRoutes<P extends string, R extends RouteSchema> = {
|
|
15
|
+
[K in keyof R as K extends `${infer M} ${infer Sub}` ? `${M} ${JoinPath<P, Sub>}` : K]: R[K] extends infer E extends RouteEndpoint ? Omit<E, 'path'> & {
|
|
16
|
+
path: E['path'] extends string ? JoinPath<P, E['path']> : JoinPath<P, K extends `${string} ${infer Sub}` ? Sub : (K & string)>;
|
|
17
|
+
} : R[K];
|
|
18
|
+
};
|
|
19
|
+
type TypedRouterHandler<S extends RouteSchemas, Res> = (ctx: Context & {
|
|
20
|
+
body: S extends {
|
|
21
|
+
body: infer B;
|
|
22
|
+
} ? InferSchema<B> : any;
|
|
23
|
+
query: S extends {
|
|
24
|
+
query: infer Q;
|
|
25
|
+
} ? InferSchema<Q> : Record<string, string>;
|
|
26
|
+
params: S extends {
|
|
27
|
+
params: infer Pa;
|
|
28
|
+
} ? InferSchema<Pa> : Record<string, any>;
|
|
29
|
+
}) => Res | Promise<Res>;
|
|
30
|
+
type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
31
|
+
<P extends string, S extends RouteSchemas, Res = S extends {
|
|
32
|
+
response: infer R;
|
|
33
|
+
} ? InferSchema<R> : any>(path: P, schemas: S, handler: TypedRouterHandler<S, Res>): BareRouter<Routes & Record<`${M} ${P}`, {
|
|
34
|
+
method: M;
|
|
35
|
+
path: P;
|
|
36
|
+
params: S extends {
|
|
37
|
+
params: infer Pa;
|
|
38
|
+
} ? InferSchema<Pa> : Record<string, any>;
|
|
39
|
+
query: S extends {
|
|
40
|
+
query: infer Q;
|
|
41
|
+
} ? InferSchema<Q> : Record<string, any>;
|
|
42
|
+
headers: S extends {
|
|
43
|
+
headers: infer H;
|
|
44
|
+
} ? InferSchema<H> : Record<string, string>;
|
|
45
|
+
body: S extends {
|
|
46
|
+
body: infer B;
|
|
47
|
+
} ? InferSchema<B> : any;
|
|
48
|
+
response: S extends {
|
|
49
|
+
response: infer R;
|
|
50
|
+
} ? InferSchema<R> : Awaited<Res>;
|
|
51
|
+
}>>;
|
|
52
|
+
<P extends string, Res = any>(path: P, ...handlers: any[]): BareRouter<Routes & Record<`${M} ${P}`, {
|
|
53
|
+
method: M;
|
|
54
|
+
path: P;
|
|
55
|
+
response: Awaited<Res>;
|
|
56
|
+
}>>;
|
|
57
|
+
};
|
|
58
|
+
export declare class BareRouter<Routes extends RouteSchema = {}> {
|
|
5
59
|
prefix: string;
|
|
6
60
|
groupMiddleware: any[];
|
|
61
|
+
readonly __routes: Routes;
|
|
7
62
|
routes: any[];
|
|
8
63
|
constructor(prefix?: string, groupMiddleware?: any[]);
|
|
9
|
-
|
|
10
|
-
get:
|
|
11
|
-
post:
|
|
12
|
-
put:
|
|
13
|
-
patch:
|
|
14
|
-
delete:
|
|
15
|
-
options:
|
|
64
|
+
protected _add(method: string, path: string, handlers: HandlersChain): this;
|
|
65
|
+
get: AddRouterRoute<Routes, 'GET'>;
|
|
66
|
+
post: AddRouterRoute<Routes, 'POST'>;
|
|
67
|
+
put: AddRouterRoute<Routes, 'PUT'>;
|
|
68
|
+
patch: AddRouterRoute<Routes, 'PATCH'>;
|
|
69
|
+
delete: AddRouterRoute<Routes, 'DELETE'>;
|
|
70
|
+
options: AddRouterRoute<Routes, 'OPTIONS'>;
|
|
71
|
+
head: AddRouterRoute<Routes, 'HEAD'>;
|
|
72
|
+
all: AddRouterRoute<Routes, 'ALL'>;
|
|
16
73
|
group: (path: string, ...args: any[]) => this;
|
|
17
|
-
|
|
74
|
+
private _mountRouter;
|
|
75
|
+
route<P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
|
76
|
+
use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
77
|
+
use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
|
78
|
+
use(mw: any): BareRouter<Routes>;
|
|
18
79
|
}
|
|
19
80
|
export {};
|
package/dist/types/index.d.ts
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* Built for Bun with Mechanical Sympathy
|
|
5
5
|
* Optimized to outperform competitors by 55% [2026-01-05]
|
|
6
6
|
*/
|
|
7
|
-
export { BareJS, type WebSocketRouteHandler } from './core/bare';
|
|
7
|
+
export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
|
|
8
|
+
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
8
9
|
/**
|
|
9
10
|
* Plugin Interface for BareJS
|
|
10
11
|
*/
|
|
@@ -17,15 +18,19 @@ import { Type } from "@sinclair/typebox";
|
|
|
17
18
|
export { Type, Type as T, Type as TypeBox };
|
|
18
19
|
import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
|
|
19
20
|
export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v, schemaValidator, createResponseFilter, type RouteSchemas, type RouteDetail };
|
|
21
|
+
export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
|
|
22
|
+
export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
|
|
20
23
|
export { cors } from './security/cors';
|
|
21
24
|
export { csrf, type CsrfOptions } from './security/csrf';
|
|
22
25
|
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
23
26
|
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
24
27
|
export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
|
|
28
|
+
export { redisStore, type BareStore, type RateLimitStore, type IdempotencyStore, type CachedIdempotentEntry, type RevocationStore, type RedisStoreOptions, } from './security/store';
|
|
29
|
+
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
25
30
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
26
|
-
export { staticFile, type StaticOptions } from './utils/static';
|
|
31
|
+
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
32
|
+
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
27
33
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
28
|
-
export {
|
|
29
|
-
export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
|
|
34
|
+
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
|
|
30
35
|
export { Hash as Password, Hash } from './security/hash';
|
|
31
|
-
export { bareClient, type BareClient, type BareClientOptions, type ClientRequestOptions, type RouteSchema } from './client/index';
|
|
36
|
+
export { bareClient, type BareClient, type BareClientOptions, type ClientRequestOptions, type RouteEndpoint, type RouteSchema } from './client/index';
|
|
@@ -1,15 +1,33 @@
|
|
|
1
1
|
import type { Next } from '../core/context';
|
|
2
|
+
import type { RevocationStore } from './store';
|
|
2
3
|
/**
|
|
3
4
|
* 4. TOKEN GENERATOR (Standard JWT)
|
|
4
5
|
*/
|
|
5
6
|
export declare const createToken: (payload: object, secret: string) => Promise<string>;
|
|
7
|
+
/**
|
|
8
|
+
* Revoke a JWT token or JTI for ttlMs (default: 1 hour).
|
|
9
|
+
* Optionally delegates to an external RevocationStore (e.g. redisStore).
|
|
10
|
+
*/
|
|
11
|
+
export declare function revokeToken(tokenOrJti: string, ttlMs?: number): void;
|
|
12
|
+
export declare function revokeToken(tokenOrJti: string, ttlMs: number, store: RevocationStore): Promise<void>;
|
|
13
|
+
export declare function isTokenRevoked(tokenOrJti: string): boolean;
|
|
14
|
+
export declare function isTokenRevoked(tokenOrJti: string, store: RevocationStore): Promise<boolean>;
|
|
15
|
+
export type JwtAlgorithm = 'HS256' | 'RS256' | 'ES256';
|
|
16
|
+
export interface BareAuthOptions {
|
|
17
|
+
secret?: string;
|
|
18
|
+
algorithms?: JwtAlgorithm[];
|
|
19
|
+
publicKey?: string | CryptoKey;
|
|
20
|
+
jwksUri?: string;
|
|
21
|
+
jwksCacheTtlMs?: number;
|
|
22
|
+
revocationStore?: RevocationStore;
|
|
23
|
+
isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
|
|
24
|
+
}
|
|
6
25
|
/**
|
|
7
26
|
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
8
|
-
* High-performance, constant-time JWT middleware for BareJS
|
|
27
|
+
* High-performance, constant-time JWT middleware for BareJS.
|
|
28
|
+
* Supports HS256 (sync fast-path), RS256, ES256, and JWKS with kid caching.
|
|
9
29
|
*/
|
|
10
|
-
export declare const bareAuth: (secretOrOpts: string |
|
|
11
|
-
secret: string;
|
|
12
|
-
}) => (ctx: any, next: any) => any;
|
|
30
|
+
export declare const bareAuth: (secretOrOpts: string | BareAuthOptions) => (ctx: any, next: any) => any;
|
|
13
31
|
/**
|
|
14
32
|
* 2. BASIC AUTH
|
|
15
33
|
* Useful for internal tools and simple admin panels
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Middleware } from '../core/context';
|
|
2
|
+
import type { IdempotencyStore } from './store';
|
|
2
3
|
export interface IdempotencyOptions {
|
|
3
4
|
/** Header name (default: 'idempotency-key') */
|
|
4
5
|
headerName?: string;
|
|
@@ -6,6 +7,8 @@ export interface IdempotencyOptions {
|
|
|
6
7
|
ttlMs?: number;
|
|
7
8
|
/** Maximum cached keys before LRU eviction (default: 10_000) */
|
|
8
9
|
maxKeys?: number;
|
|
10
|
+
/** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
|
|
11
|
+
store?: IdempotencyStore;
|
|
9
12
|
}
|
|
10
13
|
/**
|
|
11
14
|
* Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
import type { RateLimitStore } from './store';
|
|
2
3
|
export interface RateLimitOptions {
|
|
3
4
|
windowMs?: number;
|
|
4
5
|
max?: number;
|
|
5
6
|
message?: string;
|
|
6
7
|
keyGenerator?: (ctx: Context) => string;
|
|
7
8
|
maxEntries?: number;
|
|
9
|
+
/** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
|
|
10
|
+
store?: RateLimitStore;
|
|
8
11
|
}
|
|
9
12
|
export declare const rateLimit: (options?: RateLimitOptions) => Middleware;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
3
|
+
export interface CircuitBreakerOptions {
|
|
4
|
+
/** Number of consecutive failures before opening the circuit (default: 5) */
|
|
5
|
+
failureThreshold?: number;
|
|
6
|
+
/** Cooldown in milliseconds before transitioning from OPEN to HALF_OPEN (default: 30000) */
|
|
7
|
+
resetTimeoutMs?: number;
|
|
8
|
+
/** Custom predicate to determine if a response or error counts as a failure */
|
|
9
|
+
isFailure?: (res: any, err?: any) => boolean;
|
|
10
|
+
/** Optional callback fired when circuit state changes */
|
|
11
|
+
onStateChange?: (from: CircuitState, to: CircuitState) => void;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Lightweight Circuit Breaker middleware.
|
|
15
|
+
* Protects downstream databases and external APIs from cascading failures.
|
|
16
|
+
*/
|
|
17
|
+
export declare const circuitBreaker: (options?: CircuitBreakerOptions) => Middleware;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface RateLimitStore {
|
|
2
|
+
increment(key: string, windowMs: number): Promise<{
|
|
3
|
+
count: number;
|
|
4
|
+
resetAt: number;
|
|
5
|
+
}> | {
|
|
6
|
+
count: number;
|
|
7
|
+
resetAt: number;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export interface CachedIdempotentEntry {
|
|
11
|
+
status: number;
|
|
12
|
+
body?: any;
|
|
13
|
+
rawBody?: ArrayBuffer;
|
|
14
|
+
contentType?: string;
|
|
15
|
+
expiresAt: number;
|
|
16
|
+
}
|
|
17
|
+
export interface IdempotencyStore {
|
|
18
|
+
get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
|
|
19
|
+
set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
|
|
20
|
+
acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
|
|
21
|
+
release(key: string): Promise<void> | void;
|
|
22
|
+
}
|
|
23
|
+
export interface RevocationStore {
|
|
24
|
+
revoke(tokenOrJti: string, ttlMs: number): Promise<void> | void;
|
|
25
|
+
isRevoked(tokenOrJti: string): Promise<boolean> | boolean;
|
|
26
|
+
}
|
|
27
|
+
export type BareStore = RateLimitStore & IdempotencyStore & RevocationStore;
|
|
28
|
+
export interface RedisStoreOptions {
|
|
29
|
+
/** Key prefix for all entries (default: 'barejs:') */
|
|
30
|
+
prefix?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Lightweight Redis adapter compatible with both Bun.redis and ioredis.
|
|
34
|
+
* Implements RateLimitStore, IdempotencyStore, and RevocationStore.
|
|
35
|
+
*/
|
|
36
|
+
export declare const redisStore: (client: any, options?: RedisStoreOptions) => BareStore;
|
|
@@ -35,6 +35,8 @@ export interface RouteSchemas {
|
|
|
35
35
|
params?: any;
|
|
36
36
|
headers?: any;
|
|
37
37
|
response?: any;
|
|
38
|
+
/** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
|
|
39
|
+
stripUnknown?: boolean;
|
|
38
40
|
detail?: RouteDetail;
|
|
39
41
|
maxBodySize?: number;
|
|
40
42
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export type CompressionEncoding = 'zstd' | 'br' | 'gzip';
|
|
3
|
+
export interface CompressOptions {
|
|
4
|
+
/** Minimum response size in bytes before compression is applied (default: 1024) */
|
|
5
|
+
minSize?: number;
|
|
6
|
+
/** Gzip compression level 0-9 (default: 6) */
|
|
7
|
+
level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
8
|
+
/** Preferred compression encodings in priority order (default: ['zstd', 'br', 'gzip']) */
|
|
9
|
+
encodings?: CompressionEncoding[];
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Zero-dependency response compression middleware supporting zstd, brotli (br), and gzip.
|
|
13
|
+
* Negotiates encoding from Accept-Encoding, and skips streaming SSE, 204/304, already-encoded, and small payloads.
|
|
14
|
+
*/
|
|
15
|
+
export declare const compress: (options?: CompressOptions) => Middleware;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { BarePlugin } from '../index';
|
|
2
|
+
export type HealthCheckFn = () => boolean | Promise<boolean>;
|
|
3
|
+
export interface HealthcheckOptions {
|
|
4
|
+
/** Liveness endpoint path (default: '/health') */
|
|
5
|
+
path?: string;
|
|
6
|
+
/** Optional readiness endpoint path (e.g. '/ready') */
|
|
7
|
+
readyPath?: string;
|
|
8
|
+
/** Optional version string to include in response */
|
|
9
|
+
version?: string;
|
|
10
|
+
/** Named dependency checks (e.g. { db: () => pingDb() }) */
|
|
11
|
+
checks?: Record<string, HealthCheckFn>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Built-in Healthcheck & Readiness plugin for BareJS.
|
|
15
|
+
* Registers /health (and optional /ready) returning 200 OK or 503 Service Unavailable.
|
|
16
|
+
*/
|
|
17
|
+
export declare const healthcheck: (options?: HealthcheckOptions) => BarePlugin;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
export interface LogEntry {
|
|
3
|
+
timestamp: string;
|
|
4
|
+
method: string;
|
|
5
|
+
path: string;
|
|
6
|
+
requestId?: string;
|
|
7
|
+
ip?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface LoggerOptions {
|
|
10
|
+
/** Output format: 'pretty' (default) or 'json' */
|
|
11
|
+
format?: 'pretty' | 'json';
|
|
12
|
+
/** Attach X-Request-Id response header from ctx.requestId (default: true) */
|
|
13
|
+
requestId?: boolean;
|
|
14
|
+
/** Skip logging for matching requests */
|
|
15
|
+
skip?: (ctx: Context, path: string) => boolean;
|
|
16
|
+
/** Custom log sink (defaults to console.log) */
|
|
17
|
+
onLog?: (entry: LogEntry) => void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Lightweight structured/pretty request logger & X-Request-Id middleware.
|
|
21
|
+
*/
|
|
22
|
+
export declare const logger: (options?: LoggerOptions) => Middleware;
|
|
@@ -2,14 +2,36 @@ export interface OpenAPIOptions {
|
|
|
2
2
|
title?: string;
|
|
3
3
|
version?: string;
|
|
4
4
|
description?: string;
|
|
5
|
+
servers?: Array<{
|
|
6
|
+
url: string;
|
|
7
|
+
description?: string;
|
|
8
|
+
}>;
|
|
9
|
+
tags?: Array<{
|
|
10
|
+
name: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
}>;
|
|
13
|
+
securitySchemes?: Record<string, Record<string, any>>;
|
|
14
|
+
security?: Array<Record<string, string[]>>;
|
|
5
15
|
}
|
|
6
16
|
export declare const generateOpenAPISpec: (routes: any[], options?: OpenAPIOptions) => {
|
|
17
|
+
paths: Record<string, Record<string, any>>;
|
|
18
|
+
security?: Record<string, string[]>[] | undefined;
|
|
19
|
+
components?: {
|
|
20
|
+
securitySchemes: Record<string, Record<string, any>>;
|
|
21
|
+
} | undefined;
|
|
22
|
+
tags?: {
|
|
23
|
+
name: string;
|
|
24
|
+
description?: string;
|
|
25
|
+
}[] | undefined;
|
|
26
|
+
servers?: {
|
|
27
|
+
url: string;
|
|
28
|
+
description?: string;
|
|
29
|
+
}[] | undefined;
|
|
7
30
|
openapi: string;
|
|
8
31
|
info: {
|
|
9
32
|
description?: string | undefined;
|
|
10
33
|
title: string;
|
|
11
34
|
version: string;
|
|
12
35
|
};
|
|
13
|
-
paths: Record<string, Record<string, any>>;
|
|
14
36
|
};
|
|
15
37
|
export declare const renderDocsHTML: (specUrl: string, title?: string) => string;
|
|
@@ -1,5 +1,13 @@
|
|
|
1
|
+
export interface StaticMetadataCacheOptions {
|
|
2
|
+
/** Maximum cached file metadata entries (default: 1000) */
|
|
3
|
+
maxEntries?: number;
|
|
4
|
+
/** Cache TTL in milliseconds (default: 30_000) */
|
|
5
|
+
ttlMs?: number;
|
|
6
|
+
}
|
|
1
7
|
export interface StaticOptions {
|
|
2
8
|
maxAge?: number;
|
|
3
9
|
etag?: boolean;
|
|
10
|
+
/** Optional LRU metadata cache for realpath, stat, and ETag to avoid repeated syscalls */
|
|
11
|
+
cacheMetadata?: boolean | StaticMetadataCacheOptions;
|
|
4
12
|
}
|
|
5
13
|
export declare const staticFile: (root?: string, options?: StaticOptions) => (ctx: any, next: any) => Promise<any>;
|