barejs 0.1.50 → 0.1.51
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 +47 -10
- package/dist/index.js +92 -91
- package/dist/types/client/index.d.ts +23 -23
- package/dist/types/core/bare.d.ts +74 -4
- package/dist/types/core/context.d.ts +2 -0
- package/dist/types/core/router.d.ts +19 -9
- package/dist/types/index.d.ts +8 -4
- package/dist/types/security/auth.d.ts +10 -3
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/validators.d.ts +2 -0
- package/dist/types/utils/compress.d.ts +12 -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/llms.txt +1 -1
- package/package.json +1 -1
- package/src/client/index.ts +58 -17
- package/src/core/bare.ts +216 -20
- package/src/core/context.ts +12 -7
- package/src/core/router.ts +27 -11
- package/src/index.ts +8 -4
- package/src/security/auth.ts +67 -11
- package/src/security/hash.ts +8 -2
- package/src/security/idempotency.ts +22 -3
- package/src/security/rateLimit.ts +1 -6
- package/src/security/resilience.ts +91 -0
- package/src/security/validators.ts +4 -1
- package/src/utils/compress.ts +49 -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 +11 -2
|
@@ -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 } 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,7 +21,47 @@ 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?;
|
|
@@ -24,12 +72,18 @@ export declare class BareJS extends BareRouter {
|
|
|
24
72
|
private wsRoutes;
|
|
25
73
|
private startHooks;
|
|
26
74
|
private stopHooks;
|
|
75
|
+
private crons;
|
|
27
76
|
private server?;
|
|
28
77
|
private shutdownHandler?;
|
|
29
78
|
private wsAdapter;
|
|
30
79
|
useLog(enabled?: boolean): this;
|
|
31
80
|
onStart(fn: () => void | Promise<void>): this;
|
|
32
81
|
onStop(fn: () => void | Promise<void>): this;
|
|
82
|
+
/**
|
|
83
|
+
* Built-in overlap-safe background interval scheduler.
|
|
84
|
+
* Automatically cleared when app.stop() is called.
|
|
85
|
+
*/
|
|
86
|
+
cron(name: string, intervalMs: number, fn: () => void | Promise<void>, options?: CronOptions): this;
|
|
33
87
|
stop(closeActiveConnections?: boolean): Promise<void>;
|
|
34
88
|
constructor(poolSize?: number);
|
|
35
89
|
private notFoundHandler;
|
|
@@ -38,12 +92,28 @@ export declare class BareJS extends BareRouter {
|
|
|
38
92
|
ws(path: string, handler: WebSocketRouteHandler): this;
|
|
39
93
|
docs(path?: string, options?: OpenAPIOptions): this;
|
|
40
94
|
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this;
|
|
95
|
+
get: AddRoute<Derived, Routes, 'GET'>;
|
|
96
|
+
post: AddRoute<Derived, Routes, 'POST'>;
|
|
97
|
+
put: AddRoute<Derived, Routes, 'PUT'>;
|
|
98
|
+
patch: AddRoute<Derived, Routes, 'PATCH'>;
|
|
99
|
+
delete: AddRoute<Derived, Routes, 'DELETE'>;
|
|
100
|
+
options: AddRoute<Derived, Routes, 'OPTIONS'>;
|
|
101
|
+
head: AddRoute<Derived, Routes, 'HEAD'>;
|
|
102
|
+
all: AddRoute<Derived, Routes, 'ALL'>;
|
|
103
|
+
use: {
|
|
104
|
+
<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
|
|
105
|
+
(mw: any): BareJS<Derived, Routes>;
|
|
106
|
+
};
|
|
41
107
|
private _hasDerive;
|
|
42
|
-
derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T):
|
|
108
|
+
derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
|
|
43
109
|
private compileHandler;
|
|
44
110
|
compile(): void;
|
|
45
111
|
fetch: (req: Request) => any;
|
|
46
112
|
name: string;
|
|
47
|
-
|
|
113
|
+
trustProxy(enabled?: boolean): this;
|
|
114
|
+
listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
|
|
115
|
+
maxRequestBodySize?: number;
|
|
116
|
+
trustProxy?: boolean;
|
|
117
|
+
}): Bun.Server<WebSocketRouteHandler> | Bun.Server<undefined>;
|
|
48
118
|
}
|
|
49
119
|
export { Context, typebox, t };
|
|
@@ -45,6 +45,8 @@ export declare class Context {
|
|
|
45
45
|
_cookies: Record<string, string> | undefined;
|
|
46
46
|
_setCookies: string[] | undefined;
|
|
47
47
|
_requestId: string | undefined;
|
|
48
|
+
_peerIp: string | undefined;
|
|
49
|
+
_trustProxy: boolean;
|
|
48
50
|
constructor();
|
|
49
51
|
get query(): Record<string, string>;
|
|
50
52
|
getQuery(key: string): string | undefined;
|
|
@@ -1,19 +1,29 @@
|
|
|
1
1
|
import { type Middleware, type Handler } from '../core/context';
|
|
2
2
|
import { type RouteSchemas } from '../security/validators';
|
|
3
|
+
import type { 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
|
+
export declare class BareRouter<Routes extends RouteSchema = {}> {
|
|
5
11
|
prefix: string;
|
|
6
12
|
groupMiddleware: any[];
|
|
13
|
+
readonly __routes: Routes;
|
|
7
14
|
routes: any[];
|
|
8
15
|
constructor(prefix?: string, groupMiddleware?: any[]);
|
|
9
|
-
|
|
10
|
-
get: (path: string, ...h:
|
|
11
|
-
post: (path: string, ...h:
|
|
12
|
-
put: (path: string, ...h:
|
|
13
|
-
patch: (path: string, ...h:
|
|
14
|
-
delete: (path: string, ...h:
|
|
15
|
-
options: (path: string, ...h:
|
|
16
|
+
protected _add(method: string, path: string, handlers: HandlersChain): this;
|
|
17
|
+
get: (path: string, ...h: any[]) => any;
|
|
18
|
+
post: (path: string, ...h: any[]) => any;
|
|
19
|
+
put: (path: string, ...h: any[]) => any;
|
|
20
|
+
patch: (path: string, ...h: any[]) => any;
|
|
21
|
+
delete: (path: string, ...h: any[]) => any;
|
|
22
|
+
options: (path: string, ...h: any[]) => any;
|
|
23
|
+
head: (path: string, ...h: any[]) => any;
|
|
24
|
+
all: (path: string, ...h: any[]) => any;
|
|
16
25
|
group: (path: string, ...args: any[]) => this;
|
|
17
|
-
use(mw:
|
|
26
|
+
use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
27
|
+
use(mw: any): BareRouter<Routes>;
|
|
18
28
|
}
|
|
19
29
|
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 } from './core/router';
|
|
8
9
|
/**
|
|
9
10
|
* Plugin Interface for BareJS
|
|
10
11
|
*/
|
|
@@ -17,15 +18,18 @@ 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 { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
25
29
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
26
30
|
export { staticFile, type StaticOptions } from './utils/static';
|
|
31
|
+
export { compress, type CompressOptions } from './utils/compress';
|
|
27
32
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
28
|
-
export {
|
|
29
|
-
export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
|
|
33
|
+
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions } from './security/auth';
|
|
30
34
|
export { Hash as Password, Hash } from './security/hash';
|
|
31
|
-
export { bareClient, type BareClient, type BareClientOptions, type ClientRequestOptions, type RouteSchema } from './client/index';
|
|
35
|
+
export { bareClient, type BareClient, type BareClientOptions, type ClientRequestOptions, type RouteEndpoint, type RouteSchema } from './client/index';
|
|
@@ -3,13 +3,20 @@ import type { Next } from '../core/context';
|
|
|
3
3
|
* 4. TOKEN GENERATOR (Standard JWT)
|
|
4
4
|
*/
|
|
5
5
|
export declare const createToken: (payload: object, secret: string) => Promise<string>;
|
|
6
|
+
/**
|
|
7
|
+
* Revoke a JWT token or JTI for ttlMs (default: 1 hour).
|
|
8
|
+
*/
|
|
9
|
+
export declare const revokeToken: (tokenOrJti: string, ttlMs?: number) => void;
|
|
10
|
+
export declare const isTokenRevoked: (tokenOrJti: string) => boolean;
|
|
11
|
+
export interface BareAuthOptions {
|
|
12
|
+
secret: string;
|
|
13
|
+
isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
|
|
14
|
+
}
|
|
6
15
|
/**
|
|
7
16
|
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
8
17
|
* High-performance, constant-time JWT middleware for BareJS
|
|
9
18
|
*/
|
|
10
|
-
export declare const bareAuth: (secretOrOpts: string |
|
|
11
|
-
secret: string;
|
|
12
|
-
}) => (ctx: any, next: any) => any;
|
|
19
|
+
export declare const bareAuth: (secretOrOpts: string | BareAuthOptions) => (ctx: any, next: any) => any;
|
|
13
20
|
/**
|
|
14
21
|
* 2. BASIC AUTH
|
|
15
22
|
* Useful for internal tools and simple admin panels
|
|
@@ -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;
|
|
@@ -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,12 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export interface CompressOptions {
|
|
3
|
+
/** Minimum response size in bytes before gzip compression is applied (default: 1024) */
|
|
4
|
+
minSize?: number;
|
|
5
|
+
/** Gzip compression level 0-9 (default: 6) */
|
|
6
|
+
level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Zero-dependency Gzip compression middleware powered by Bun.gzipSync (native C/Zig).
|
|
10
|
+
* Skips streaming SSE responses, already-encoded responses, and payloads below minSize.
|
|
11
|
+
*/
|
|
12
|
+
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;
|
package/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
|
|
2
2
|
|
|
3
|
-
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Idempotency-Key double-charge protection, Singleflight request coalescing, Security Headers, DoS
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (214 tests / 2,906 assertions)**.
|
|
4
4
|
|
|
5
5
|
## 1. Installation & Minimal App
|
|
6
6
|
```ts
|
package/package.json
CHANGED
package/src/client/index.ts
CHANGED
|
@@ -17,49 +17,82 @@ type ExtractParams<Path extends string> =
|
|
|
17
17
|
? { [K in Param]: string | number }
|
|
18
18
|
: Record<string, never>;
|
|
19
19
|
|
|
20
|
-
export
|
|
20
|
+
export interface RouteEndpoint {
|
|
21
21
|
method: string;
|
|
22
|
+
path?: string;
|
|
22
23
|
params?: Record<string, any>;
|
|
24
|
+
query?: Record<string, any>;
|
|
25
|
+
headers?: Record<string, any>;
|
|
23
26
|
body?: any;
|
|
24
27
|
response?: any;
|
|
25
|
-
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type RouteSchema = Record<string, RouteEndpoint>;
|
|
31
|
+
|
|
32
|
+
type RouteKey<M extends string, P extends string> = `${M} ${P}`;
|
|
26
33
|
|
|
27
34
|
type PathsForMethod<Routes extends RouteSchema, M extends string> = {
|
|
28
|
-
[K in keyof Routes]: Routes[K]['method'] extends M
|
|
35
|
+
[K in keyof Routes]: Routes[K]['method'] extends M
|
|
36
|
+
? (Routes[K]['path'] extends string ? Routes[K]['path'] : K & string)
|
|
37
|
+
: never;
|
|
29
38
|
}[keyof Routes] & string;
|
|
30
39
|
|
|
40
|
+
type LookupRoute<Routes extends RouteSchema, M extends string, P extends string> =
|
|
41
|
+
RouteKey<M, P> extends keyof Routes
|
|
42
|
+
? Routes[RouteKey<M, P>]
|
|
43
|
+
: P extends keyof Routes
|
|
44
|
+
? Routes[P]
|
|
45
|
+
: never;
|
|
46
|
+
|
|
47
|
+
type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends boolean> =
|
|
48
|
+
Omit<ClientRequestOptions, 'params' | 'query' | 'headers' | (WithBody extends true ? 'body' : never)> & {
|
|
49
|
+
params?: R['params'] extends Record<string, any> ? R['params'] : ExtractParams<P>;
|
|
50
|
+
query?: R['query'] extends Record<string, any> ? R['query'] : ClientRequestOptions['query'];
|
|
51
|
+
headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
|
|
52
|
+
} & (WithBody extends true ? { body?: R['body'] } : {});
|
|
53
|
+
|
|
31
54
|
export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
32
55
|
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
|
|
33
56
|
path: P,
|
|
34
|
-
options?:
|
|
35
|
-
|
|
57
|
+
options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint
|
|
58
|
+
? EndpointOptions<R, P & string, false>
|
|
59
|
+
: ClientRequestOptions
|
|
60
|
+
): Promise<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
36
61
|
|
|
37
62
|
post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(
|
|
38
63
|
path: P,
|
|
39
|
-
options?:
|
|
40
|
-
|
|
64
|
+
options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint
|
|
65
|
+
? EndpointOptions<R, P & string, true>
|
|
66
|
+
: ClientRequestOptions
|
|
67
|
+
): Promise<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
41
68
|
|
|
42
69
|
put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(
|
|
43
70
|
path: P,
|
|
44
|
-
options?:
|
|
45
|
-
|
|
71
|
+
options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint
|
|
72
|
+
? EndpointOptions<R, P & string, true>
|
|
73
|
+
: ClientRequestOptions
|
|
74
|
+
): Promise<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
46
75
|
|
|
47
76
|
patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(
|
|
48
77
|
path: P,
|
|
49
|
-
options?:
|
|
50
|
-
|
|
78
|
+
options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint
|
|
79
|
+
? EndpointOptions<R, P & string, true>
|
|
80
|
+
: ClientRequestOptions
|
|
81
|
+
): Promise<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
51
82
|
|
|
52
83
|
delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(
|
|
53
84
|
path: P,
|
|
54
|
-
options?:
|
|
55
|
-
|
|
85
|
+
options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint
|
|
86
|
+
? EndpointOptions<R, P & string, false>
|
|
87
|
+
: ClientRequestOptions
|
|
88
|
+
): Promise<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
56
89
|
}
|
|
57
90
|
|
|
58
91
|
const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
|
|
59
92
|
let finalPath = path;
|
|
60
93
|
if (options?.params) {
|
|
61
94
|
for (const [k, v] of Object.entries(options.params)) {
|
|
62
|
-
finalPath = finalPath.
|
|
95
|
+
finalPath = finalPath.replaceAll(`:${k}`, encodeURIComponent(String(v)));
|
|
63
96
|
}
|
|
64
97
|
}
|
|
65
98
|
const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
|
@@ -78,7 +111,7 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
|
|
|
78
111
|
};
|
|
79
112
|
|
|
80
113
|
export const bareClient = <AppOrRoutes = any>(
|
|
81
|
-
baseUrlOrApp: string | { fetch: (req: Request) => any },
|
|
114
|
+
baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
|
|
82
115
|
clientOptions: BareClientOptions = {}
|
|
83
116
|
): BareClient<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> => {
|
|
84
117
|
const isApp = typeof baseUrlOrApp === 'object' && baseUrlOrApp !== null && typeof baseUrlOrApp.fetch === 'function';
|
|
@@ -102,8 +135,16 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
102
135
|
}
|
|
103
136
|
|
|
104
137
|
const res = await fetchImpl(url, init);
|
|
105
|
-
|
|
106
|
-
|
|
138
|
+
let data: any = null;
|
|
139
|
+
if (res.status !== 204 && res.status !== 205 && res.status !== 304) {
|
|
140
|
+
const ct = res.headers.get('content-type') || '';
|
|
141
|
+
if (ct.includes('application/json')) {
|
|
142
|
+
const text = await res.text();
|
|
143
|
+
data = text ? JSON.parse(text) : null;
|
|
144
|
+
} else {
|
|
145
|
+
data = await res.text();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
107
148
|
if (!res.ok) {
|
|
108
149
|
const err: any = new Error(`HTTP ${res.status}`);
|
|
109
150
|
err.status = res.status;
|