barejs 0.1.48 → 0.1.50
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 +243 -84
- package/dist/index.js +162 -67
- package/dist/types/client/index.d.ts +50 -0
- package/dist/types/core/bare.d.ts +24 -1
- package/dist/types/core/context.d.ts +54 -2
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +3 -1
- package/dist/types/index.d.ts +14 -6
- package/dist/types/security/auth.d.ts +3 -1
- package/dist/types/security/cors.d.ts +7 -3
- package/dist/types/security/csrf.d.ts +12 -0
- package/dist/types/security/headers.d.ts +9 -0
- package/dist/types/security/idempotency.d.ts +22 -0
- package/dist/types/security/rateLimit.d.ts +9 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +16 -0
- package/dist/types/utils/openapi.d.ts +15 -0
- package/dist/types/utils/static.d.ts +5 -1
- package/llms.txt +138 -0
- package/package.json +3 -1
- package/src/client/index.ts +123 -0
- package/src/core/bare.ts +352 -40
- package/src/core/context.ts +356 -33
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +17 -5
- package/src/index.ts +32 -8
- package/src/security/auth.ts +2 -1
- package/src/security/cors.ts +85 -31
- package/src/security/csrf.ts +84 -0
- package/src/security/headers.ts +68 -0
- package/src/security/idempotency.ts +99 -0
- package/src/security/rateLimit.ts +76 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +206 -9
- package/src/utils/openapi.ts +151 -0
- package/src/utils/static.ts +62 -5
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export interface ClientRequestOptions {
|
|
2
|
+
params?: Record<string, string | number>;
|
|
3
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
4
|
+
body?: any;
|
|
5
|
+
headers?: Record<string, string>;
|
|
6
|
+
}
|
|
7
|
+
export interface BareClientOptions {
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
}
|
|
11
|
+
type ExtractParams<Path extends string> = Path extends `${string}:${infer Param}/${infer Rest}` ? {
|
|
12
|
+
[K in Param | keyof ExtractParams<`/${Rest}`>]: string | number;
|
|
13
|
+
} : Path extends `${string}:${infer Param}` ? {
|
|
14
|
+
[K in Param]: string | number;
|
|
15
|
+
} : Record<string, never>;
|
|
16
|
+
export type RouteSchema = Record<string, {
|
|
17
|
+
method: string;
|
|
18
|
+
params?: Record<string, any>;
|
|
19
|
+
body?: any;
|
|
20
|
+
response?: any;
|
|
21
|
+
}>;
|
|
22
|
+
type PathsForMethod<Routes extends RouteSchema, M extends string> = {
|
|
23
|
+
[K in keyof Routes]: Routes[K]['method'] extends M ? K : never;
|
|
24
|
+
}[keyof Routes] & string;
|
|
25
|
+
export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
26
|
+
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(path: P, options?: ClientRequestOptions & (P extends keyof Routes ? {
|
|
27
|
+
params?: ExtractParams<P & string>;
|
|
28
|
+
} : {})): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
29
|
+
post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(path: P, options?: ClientRequestOptions & (P extends keyof Routes ? {
|
|
30
|
+
params?: ExtractParams<P & string>;
|
|
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>;
|
|
44
|
+
}
|
|
45
|
+
export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | {
|
|
46
|
+
fetch: (req: Request) => any;
|
|
47
|
+
}, clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
|
|
48
|
+
__routes?: infer R extends RouteSchema;
|
|
49
|
+
} ? R : RouteSchema>;
|
|
50
|
+
export {};
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { BareRouter } from './router';
|
|
2
2
|
import { Context } from './context';
|
|
3
3
|
import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
4
|
+
import { type OpenAPIOptions } from "../utils/openapi";
|
|
5
|
+
export interface WebSocketRouteHandler {
|
|
6
|
+
open?: (ws: any) => void;
|
|
7
|
+
message?: (ws: any, message: string | Buffer) => void;
|
|
8
|
+
close?: (ws: any, code: number, reason: string) => void;
|
|
9
|
+
drain?: (ws: any) => void;
|
|
10
|
+
}
|
|
4
11
|
export interface NotFoundResponse {
|
|
5
12
|
status: number;
|
|
6
13
|
message: string;
|
|
@@ -13,14 +20,30 @@ export declare class BareJS extends BareRouter {
|
|
|
13
20
|
private compiled;
|
|
14
21
|
private poolMask;
|
|
15
22
|
private _useLog;
|
|
23
|
+
private errorHandler?;
|
|
24
|
+
private wsRoutes;
|
|
25
|
+
private startHooks;
|
|
26
|
+
private stopHooks;
|
|
27
|
+
private server?;
|
|
28
|
+
private shutdownHandler?;
|
|
29
|
+
private wsAdapter;
|
|
16
30
|
useLog(enabled?: boolean): this;
|
|
31
|
+
onStart(fn: () => void | Promise<void>): this;
|
|
32
|
+
onStop(fn: () => void | Promise<void>): this;
|
|
33
|
+
stop(closeActiveConnections?: boolean): Promise<void>;
|
|
17
34
|
constructor(poolSize?: number);
|
|
18
35
|
private notFoundHandler;
|
|
19
36
|
setNotFound(handler: () => NotFoundResponse): void;
|
|
37
|
+
onError(handler: (err: any, ctx: Context) => any): this;
|
|
38
|
+
ws(path: string, handler: WebSocketRouteHandler): this;
|
|
39
|
+
docs(path?: string, options?: OpenAPIOptions): this;
|
|
40
|
+
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this;
|
|
41
|
+
private _hasDerive;
|
|
42
|
+
derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T): this;
|
|
20
43
|
private compileHandler;
|
|
21
44
|
compile(): void;
|
|
22
45
|
fetch: (req: Request) => any;
|
|
23
46
|
name: string;
|
|
24
|
-
listen(port?: number, hostname?: string, reusePort?: boolean):
|
|
47
|
+
listen(port?: number, hostname?: string, reusePort?: boolean): Bun.Server<WebSocketRouteHandler> | Bun.Server<undefined>;
|
|
25
48
|
}
|
|
26
49
|
export { Context, typebox, t };
|
|
@@ -4,6 +4,36 @@ export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
|
|
|
4
4
|
export type Handler = (ctx: Context) => Promise<any> | any;
|
|
5
5
|
export type GroupCallback = (router: any) => void;
|
|
6
6
|
export type AuthUser = Record<string, any>;
|
|
7
|
+
export interface CookieOptions {
|
|
8
|
+
httpOnly?: boolean;
|
|
9
|
+
secure?: boolean;
|
|
10
|
+
sameSite?: 'Strict' | 'Lax' | 'None';
|
|
11
|
+
path?: string;
|
|
12
|
+
domain?: string;
|
|
13
|
+
maxAge?: number;
|
|
14
|
+
expires?: Date;
|
|
15
|
+
secret?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface UploadOptions {
|
|
18
|
+
/** Max size per file in bytes (default: 5MB) */
|
|
19
|
+
maxFileSize?: number;
|
|
20
|
+
/** Max number of uploaded files (default: 10) */
|
|
21
|
+
maxFiles?: number;
|
|
22
|
+
/** Allowed MIME types (e.g. ['image/png', 'image/jpeg', 'application/pdf']) */
|
|
23
|
+
allowedTypes?: string[];
|
|
24
|
+
}
|
|
25
|
+
export interface UploadedFile {
|
|
26
|
+
fieldName: string;
|
|
27
|
+
filename: string;
|
|
28
|
+
safeName: string;
|
|
29
|
+
type: string;
|
|
30
|
+
size: number;
|
|
31
|
+
file: File;
|
|
32
|
+
}
|
|
33
|
+
export interface UploadResult {
|
|
34
|
+
fields: Record<string, string>;
|
|
35
|
+
files: UploadedFile[];
|
|
36
|
+
}
|
|
7
37
|
export declare class Context {
|
|
8
38
|
req: Request;
|
|
9
39
|
params: Params;
|
|
@@ -11,14 +41,36 @@ export declare class Context {
|
|
|
11
41
|
_headers?: Record<string, string> | undefined;
|
|
12
42
|
store: Map<string, any>;
|
|
13
43
|
body: any;
|
|
14
|
-
|
|
44
|
+
_query: Record<string, string> | undefined;
|
|
45
|
+
_cookies: Record<string, string> | undefined;
|
|
46
|
+
_setCookies: string[] | undefined;
|
|
47
|
+
_requestId: string | undefined;
|
|
15
48
|
constructor();
|
|
16
|
-
|
|
49
|
+
get query(): Record<string, string>;
|
|
50
|
+
getQuery(key: string): string | undefined;
|
|
51
|
+
get cookies(): Record<string, string>;
|
|
52
|
+
setCookie(name: string, value: string, options?: CookieOptions): this;
|
|
53
|
+
getSignedCookie(name: string, secret: string): string | null;
|
|
54
|
+
deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): this;
|
|
55
|
+
jsonBody(maxBytes?: number): Promise<any>;
|
|
17
56
|
reset(req: Request): this;
|
|
18
57
|
status(code: number): this;
|
|
19
58
|
json(data: any): Response;
|
|
20
59
|
set(key: string, value: any): this;
|
|
21
60
|
get(key: string): any;
|
|
22
61
|
setHeader(name: string, value: string): this;
|
|
62
|
+
get user(): AuthUser | undefined;
|
|
23
63
|
send(message: string, extra?: Record<string, any>): Response;
|
|
64
|
+
html(content: string, status?: number): Response;
|
|
65
|
+
text(content: string, status?: number): Response;
|
|
66
|
+
redirect(url: string, status?: number): Response;
|
|
67
|
+
sse(source: AsyncIterable<string | {
|
|
68
|
+
event?: string;
|
|
69
|
+
data: any;
|
|
70
|
+
id?: string;
|
|
71
|
+
retry?: number;
|
|
72
|
+
}> | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)): Response;
|
|
73
|
+
get requestId(): string;
|
|
74
|
+
get ip(): string;
|
|
75
|
+
upload(options?: UploadOptions): Promise<UploadResult>;
|
|
24
76
|
}
|
|
@@ -4,6 +4,7 @@ export declare class RadixNode {
|
|
|
4
4
|
staticKeys: string[];
|
|
5
5
|
paramNode: RadixNode | null;
|
|
6
6
|
paramName: string | null;
|
|
7
|
+
wildcardNode: RadixNode | null;
|
|
7
8
|
handlers: Record<string, Function>;
|
|
8
9
|
insert(path: string, method: string, handler: Function): void;
|
|
9
10
|
lookup(method: string, url: string, start: number, ctx: Context): Function | null;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Middleware, type Handler } from '../core/context';
|
|
2
|
-
type
|
|
2
|
+
import { type RouteSchemas } from '../security/validators';
|
|
3
|
+
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
3
4
|
export declare class BareRouter {
|
|
4
5
|
prefix: string;
|
|
5
6
|
groupMiddleware: any[];
|
|
@@ -11,6 +12,7 @@ export declare class BareRouter {
|
|
|
11
12
|
put: (path: string, ...h: HandlersChain) => this;
|
|
12
13
|
patch: (path: string, ...h: HandlersChain) => this;
|
|
13
14
|
delete: (path: string, ...h: HandlersChain) => this;
|
|
15
|
+
options: (path: string, ...h: HandlersChain) => this;
|
|
14
16
|
group: (path: string, ...args: any[]) => this;
|
|
15
17
|
use(mw: any): this;
|
|
16
18
|
}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -4,20 +4,28 @@
|
|
|
4
4
|
* Built for Bun with Mechanical Sympathy
|
|
5
5
|
* Optimized to outperform competitors by 55% [2026-01-05]
|
|
6
6
|
*/
|
|
7
|
-
export { BareJS } from './core/bare';
|
|
7
|
+
export { BareJS, type WebSocketRouteHandler } from './core/bare';
|
|
8
8
|
/**
|
|
9
9
|
* Plugin Interface for BareJS
|
|
10
10
|
*/
|
|
11
11
|
export interface BarePlugin {
|
|
12
12
|
install: (app: any) => void;
|
|
13
13
|
}
|
|
14
|
-
export
|
|
14
|
+
export { Context } from './core/context';
|
|
15
|
+
export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult } from './core/context';
|
|
15
16
|
import { Type } from "@sinclair/typebox";
|
|
16
17
|
export { Type, Type as T, Type as TypeBox };
|
|
17
|
-
import { typebox, zod, native, validate, Z } from './security/validators';
|
|
18
|
-
export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v };
|
|
18
|
+
import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
|
|
19
|
+
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 };
|
|
19
20
|
export { cors } from './security/cors';
|
|
20
|
-
export {
|
|
21
|
+
export { csrf, type CsrfOptions } from './security/csrf';
|
|
22
|
+
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
23
|
+
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
24
|
+
export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
|
|
25
|
+
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
26
|
+
export { staticFile, type StaticOptions } from './utils/static';
|
|
27
|
+
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
21
28
|
export { BareRouter } from './core/router';
|
|
22
|
-
export { bareAuth, createToken } from './security/auth';
|
|
29
|
+
export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
|
|
23
30
|
export { Hash as Password, Hash } from './security/hash';
|
|
31
|
+
export { bareClient, type BareClient, type BareClientOptions, type ClientRequestOptions, type RouteSchema } from './client/index';
|
|
@@ -7,7 +7,9 @@ export declare const createToken: (payload: object, secret: string) => Promise<s
|
|
|
7
7
|
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
8
8
|
* High-performance, constant-time JWT middleware for BareJS
|
|
9
9
|
*/
|
|
10
|
-
export declare const bareAuth: (
|
|
10
|
+
export declare const bareAuth: (secretOrOpts: string | {
|
|
11
|
+
secret: string;
|
|
12
|
+
}) => (ctx: any, next: any) => any;
|
|
11
13
|
/**
|
|
12
14
|
* 2. BASIC AUTH
|
|
13
15
|
* Useful for internal tools and simple admin panels
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { Middleware } from '../core/context';
|
|
2
|
-
export
|
|
3
|
-
origin?: string;
|
|
2
|
+
export interface CorsOptions {
|
|
3
|
+
origin?: string | string[] | ((origin: string) => boolean);
|
|
4
4
|
methods?: string;
|
|
5
|
-
|
|
5
|
+
credentials?: boolean;
|
|
6
|
+
allowedHeaders?: string | string[];
|
|
7
|
+
exposedHeaders?: string | string[];
|
|
8
|
+
}
|
|
9
|
+
export declare const cors: (options?: CorsOptions) => Middleware;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export interface CsrfOptions {
|
|
3
|
+
/** Allowed origins for state-changing requests (defaults to same-origin matching request Host) */
|
|
4
|
+
allowedOrigins?: string[];
|
|
5
|
+
/** HTTP methods exempt from CSRF checks (default: ['GET', 'HEAD', 'OPTIONS']) */
|
|
6
|
+
ignoreMethods?: string[];
|
|
7
|
+
/** Optional cookie + header double-submit check */
|
|
8
|
+
cookieName?: string;
|
|
9
|
+
headerName?: string;
|
|
10
|
+
requireToken?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare const csrf: (options?: CsrfOptions) => Middleware;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export interface SecurityHeadersOptions {
|
|
3
|
+
contentSecurityPolicy?: string | false;
|
|
4
|
+
frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
|
|
5
|
+
hsts?: string | false;
|
|
6
|
+
referrerPolicy?: string | false;
|
|
7
|
+
noSniff?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare const securityHeaders: (options?: SecurityHeadersOptions) => Middleware;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export interface IdempotencyOptions {
|
|
3
|
+
/** Header name (default: 'idempotency-key') */
|
|
4
|
+
headerName?: string;
|
|
5
|
+
/** Cache TTL in milliseconds (default: 300_000 = 5 minutes) */
|
|
6
|
+
ttlMs?: number;
|
|
7
|
+
/** Maximum cached keys before LRU eviction (default: 10_000) */
|
|
8
|
+
maxKeys?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
|
|
12
|
+
* Prevents duplicate state-changing executions and concurrent race conditions.
|
|
13
|
+
*/
|
|
14
|
+
export declare const idempotency: (options?: IdempotencyOptions) => Middleware;
|
|
15
|
+
/**
|
|
16
|
+
* Singleflight Helper for Thundering-Herd / Cache-Stampede Protection.
|
|
17
|
+
* Coalesces N concurrent identical async calls into 1 underlying execution.
|
|
18
|
+
*/
|
|
19
|
+
export declare const createSingleflight: () => <T>(key: string, fn: () => Promise<T>) => Promise<{
|
|
20
|
+
data: T;
|
|
21
|
+
shared: boolean;
|
|
22
|
+
}>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
export interface RateLimitOptions {
|
|
3
|
+
windowMs?: number;
|
|
4
|
+
max?: number;
|
|
5
|
+
message?: string;
|
|
6
|
+
keyGenerator?: (ctx: Context) => string;
|
|
7
|
+
maxEntries?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare const rateLimit: (options?: RateLimitOptions) => Middleware;
|
|
@@ -24,3 +24,19 @@ export declare const zod: (schema: z.ZodSchema) => Middleware;
|
|
|
24
24
|
*/
|
|
25
25
|
export declare const validate: (schema: any) => Middleware;
|
|
26
26
|
export { typebox as t, zod as z, native as n, validate as v };
|
|
27
|
+
export interface RouteDetail {
|
|
28
|
+
summary?: string;
|
|
29
|
+
description?: string;
|
|
30
|
+
tags?: string[];
|
|
31
|
+
}
|
|
32
|
+
export interface RouteSchemas {
|
|
33
|
+
body?: any;
|
|
34
|
+
query?: any;
|
|
35
|
+
params?: any;
|
|
36
|
+
headers?: any;
|
|
37
|
+
response?: any;
|
|
38
|
+
detail?: RouteDetail;
|
|
39
|
+
maxBodySize?: number;
|
|
40
|
+
}
|
|
41
|
+
export declare const createResponseFilter: (schema: any) => ((val: any) => any);
|
|
42
|
+
export declare const schemaValidator: (schemas: RouteSchemas) => Middleware;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface OpenAPIOptions {
|
|
2
|
+
title?: string;
|
|
3
|
+
version?: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare const generateOpenAPISpec: (routes: any[], options?: OpenAPIOptions) => {
|
|
7
|
+
openapi: string;
|
|
8
|
+
info: {
|
|
9
|
+
description?: string | undefined;
|
|
10
|
+
title: string;
|
|
11
|
+
version: string;
|
|
12
|
+
};
|
|
13
|
+
paths: Record<string, Record<string, any>>;
|
|
14
|
+
};
|
|
15
|
+
export declare const renderDocsHTML: (specUrl: string, title?: string) => string;
|
|
@@ -1 +1,5 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface StaticOptions {
|
|
2
|
+
maxAge?: number;
|
|
3
|
+
etag?: boolean;
|
|
4
|
+
}
|
|
5
|
+
export declare const staticFile: (root?: string, options?: StaticOptions) => (ctx: any, next: any) => Promise<any>;
|
package/llms.txt
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
|
|
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 body/upload limits, Prototype Pollution guards) and **100% Function & Line Test Coverage (209 tests / 2,878 assertions)**.
|
|
4
|
+
|
|
5
|
+
## 1. Installation & Minimal App
|
|
6
|
+
```ts
|
|
7
|
+
import { BareJS, Context, Type } from 'barejs';
|
|
8
|
+
|
|
9
|
+
const app = new BareJS();
|
|
10
|
+
|
|
11
|
+
// Direct return (Elysia style — auto-detects JSON, text, or Response)
|
|
12
|
+
app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name }));
|
|
13
|
+
app.get('/ping', () => 'pong');
|
|
14
|
+
|
|
15
|
+
// Wildcard catch-all route (`ctx.params['*']`)
|
|
16
|
+
app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
|
|
17
|
+
|
|
18
|
+
app.listen(3000);
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 2. Routing, Plugins & Unified Schema Validation
|
|
22
|
+
Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.useAll`, `app.group(prefix, fn)`, `app.use(mwOrRouterOrPlugin)`.
|
|
23
|
+
Pass a `RouteSchemas` object directly before the handler for AOT-compiled validation + auto-coercion (`number`/`integer`/`boolean` on `query` & `params`):
|
|
24
|
+
```ts
|
|
25
|
+
app.post('/users/:id', {
|
|
26
|
+
detail: { summary: 'Update user', description: 'Updates user profile', tags: ['Users'] },
|
|
27
|
+
params: Type.Object({ id: Type.Integer() }),
|
|
28
|
+
query: Type.Object({ active: Type.Optional(Type.Boolean()) }),
|
|
29
|
+
headers: Type.Object({ 'x-client': Type.Optional(Type.String()) }),
|
|
30
|
+
body: Type.Object({ name: Type.String({ minLength: 1 }) }),
|
|
31
|
+
response: Type.Object({ id: Type.Number(), name: Type.String() }), // Recursive JIT projector auto-strips undeclared fields (e.g. password_hash)!
|
|
32
|
+
maxBodySize: 1024 * 1024 // default 1MB (returns 413 on overflow)
|
|
33
|
+
}, (ctx: Context) => ({
|
|
34
|
+
id: ctx.params.id, // auto-coerced to number
|
|
35
|
+
active: ctx.query.active, // auto-coerced to boolean
|
|
36
|
+
name: ctx.body.name,
|
|
37
|
+
password_hash: 'secret' // automatically stripped before sending to client!
|
|
38
|
+
}));
|
|
39
|
+
```
|
|
40
|
+
Supports **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({ properties: { a: { type: 'string' }, b: { type: 'number' } }, required: ['a'] })`).
|
|
41
|
+
|
|
42
|
+
### Modular Routers & Plugins
|
|
43
|
+
```ts
|
|
44
|
+
// Sub-router
|
|
45
|
+
const api = new BareRouter();
|
|
46
|
+
api.get('/items', () => []);
|
|
47
|
+
app.use('/api/v1', api);
|
|
48
|
+
|
|
49
|
+
// Reusable Plugin
|
|
50
|
+
app.use({
|
|
51
|
+
name: 'metrics-plugin',
|
|
52
|
+
install(app) {
|
|
53
|
+
app.get('/metrics', () => ({ uptime: process.uptime() }));
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## 3. Context (`ctx`) Complete API
|
|
59
|
+
- `ctx.req`: Raw incoming Bun `Request`.
|
|
60
|
+
- `ctx.params`: Route params (`Record<string, any>`, including `ctx.params['*']` for wildcards).
|
|
61
|
+
- `ctx.query` / `ctx.getQuery(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`).
|
|
62
|
+
- `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit.
|
|
63
|
+
- `await ctx.upload({ maxFileSize, maxFiles, allowedTypes })`: Safe `multipart/form-data` parser; returns `{ fields, files }` with `safeName` (sanitized against path traversal) and enforces `413` (size/count) and `415` (MIME type).
|
|
64
|
+
- `ctx.cookies`: Lazy parsed request cookies (`Record<string, string>`).
|
|
65
|
+
- `await ctx.setCookie(name, value, { secret?, httpOnly?, sameSite?, secure?, maxAge?, expires?, domain?, path? })`: Defaults to `HttpOnly; SameSite=Lax; Path=/`. Pass `secret` for HMAC-SHA256 signing.
|
|
66
|
+
- `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
|
|
67
|
+
- `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`).
|
|
68
|
+
- `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`.
|
|
69
|
+
- `ctx.ip`: Client IP extracted from `x-forwarded-for`, `x-real-ip`, `cf-connecting-ip`, or `'127.0.0.1'`.
|
|
70
|
+
- `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`.
|
|
71
|
+
- `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map<string, any>` (automatically cleared on pool release).
|
|
72
|
+
- **Response Helpers (Hono / Express style):**
|
|
73
|
+
- `ctx.status(code)` (chainable)
|
|
74
|
+
- `ctx.setHeader(name, val)` (chainable, copy-on-write safe)
|
|
75
|
+
- `ctx.json(data)` -> `application/json`
|
|
76
|
+
- `ctx.send(message, extra?)` -> `{ status: 'success' | 'error', msg: message, ...extra }`
|
|
77
|
+
- `ctx.html(html, status?)` -> `text/html; charset=utf-8`
|
|
78
|
+
- `ctx.text(text, status?)` -> `text/plain; charset=utf-8`
|
|
79
|
+
- `ctx.redirect(url, status = 302)` -> `Location: url`
|
|
80
|
+
- `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` -> `text/event-stream`
|
|
81
|
+
|
|
82
|
+
## 4. Context Enrichment (`app.derive`)
|
|
83
|
+
```ts
|
|
84
|
+
const derivedApp = app.derive((ctx) => ({
|
|
85
|
+
requestTime: Date.now(),
|
|
86
|
+
tenant: ctx.req.headers.get('x-tenant') || 'public'
|
|
87
|
+
}));
|
|
88
|
+
```
|
|
89
|
+
Derived properties are attached directly onto `ctx` with TypeScript inference (`Bare<Derived>`) and automatically cleaned up when `Context` returns to the pool.
|
|
90
|
+
|
|
91
|
+
## 5. Built-in Security Middlewares, Idempotency & Singleflight
|
|
92
|
+
```ts
|
|
93
|
+
import {
|
|
94
|
+
cors, csrf, timeout, rateLimit, securityHeaders,
|
|
95
|
+
idempotency, createSingleflight,
|
|
96
|
+
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
97
|
+
} from 'barejs';
|
|
98
|
+
|
|
99
|
+
app.use(securityHeaders());
|
|
100
|
+
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
|
|
101
|
+
app.use(csrf({ allowedOrigins: ['https://app.example.com'], requireToken: true }));
|
|
102
|
+
app.use(timeout(10_000, { status: 408, message: 'Timed out' }));
|
|
103
|
+
app.use(rateLimit({ windowMs: 60_000, max: 100 }));
|
|
104
|
+
app.use(staticFile('public', { maxAge: 3600, etag: true })); // ETag, 304, Range 206/416, HEAD
|
|
105
|
+
|
|
106
|
+
// Idempotency-Key double-charge & race condition guard (409 IDEMPOTENT_IN_FLIGHT + X-Idempotent-Replayed: true)
|
|
107
|
+
app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000 }), (ctx) => ({ paid: true }));
|
|
108
|
+
|
|
109
|
+
// Thundering-herd / Cache-stampede request coalescer
|
|
110
|
+
const sf = createSingleflight();
|
|
111
|
+
app.get('/report', () => sf.do('report-key', async () => ({ total: 100 })));
|
|
112
|
+
|
|
113
|
+
// Auth & Hashing
|
|
114
|
+
const hash = await Hash.make('password'); // Argon2id (64MB default)
|
|
115
|
+
const ok = await Hash.verify('password', hash);
|
|
116
|
+
const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, process.env.JWT_SECRET!);
|
|
117
|
+
|
|
118
|
+
// bareAuth accepts either secret string or { secret } object
|
|
119
|
+
app.get('/admin', bareAuth(process.env.JWT_SECRET!), hasRole('admin'), (ctx) => ctx.user);
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## 6. Real-Time, RPC, OpenAPI & Client
|
|
123
|
+
- **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })`
|
|
124
|
+
- **JSON-RPC 2.0**: `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b })` (supports single, batch, notifications, and standard `-32700`/`-32600`/`-32601`/`-32603` error codes)
|
|
125
|
+
- **OpenAPI 3.1 + Scalar UI**: `app.docs('/docs', { title: 'My API', version: '1.0.0' })` (serves `/docs` & `/docs/json` with full `params`, `query`, `headers`, `body`, `response`, and `detail`)
|
|
126
|
+
- **Type-Safe Client (URL or Zero-Network In-Memory `app`)**:
|
|
127
|
+
- Network: `const api = bareClient('http://localhost:3000');`
|
|
128
|
+
- In-Memory (SSR / Unit Tests): `const api = bareClient(app); await api.get('/users/:id', { params: { id: 1 } });`
|
|
129
|
+
|
|
130
|
+
## 7. Lifecycle & Error Handling
|
|
131
|
+
```ts
|
|
132
|
+
app.onStart(() => console.log('Server started'));
|
|
133
|
+
app.onStop(async () => await db.close());
|
|
134
|
+
app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId }));
|
|
135
|
+
app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' }));
|
|
136
|
+
await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners
|
|
137
|
+
```
|
|
138
|
+
> **Note**: In `NODE_ENV=production`, unhandled 500 errors automatically mask internal `err.message` and `stack` unless overridden by `app.onError()`, while preserving client 4xx errors (`400`, `413`, `415`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.50",
|
|
4
4
|
"author": "xarhang",
|
|
5
5
|
"description": "High-performance JIT-specialized web framework for Bun",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -56,6 +56,7 @@
|
|
|
56
56
|
"elysia": "latest",
|
|
57
57
|
"hono": "latest",
|
|
58
58
|
"mitata": "^1.0.34",
|
|
59
|
+
"playwright-core": "^1.65.1",
|
|
59
60
|
"typescript": "latest",
|
|
60
61
|
"zod": "^3.25.76"
|
|
61
62
|
},
|
|
@@ -63,6 +64,7 @@
|
|
|
63
64
|
"dist",
|
|
64
65
|
"src",
|
|
65
66
|
"README.md",
|
|
67
|
+
"llms.txt",
|
|
66
68
|
"LICENSE"
|
|
67
69
|
]
|
|
68
70
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
export interface ClientRequestOptions {
|
|
2
|
+
params?: Record<string, string | number>;
|
|
3
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
4
|
+
body?: any;
|
|
5
|
+
headers?: Record<string, string>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface BareClientOptions {
|
|
9
|
+
headers?: Record<string, string>;
|
|
10
|
+
fetch?: typeof fetch;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
type ExtractParams<Path extends string> =
|
|
14
|
+
Path extends `${string}:${infer Param}/${infer Rest}`
|
|
15
|
+
? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string | number }
|
|
16
|
+
: Path extends `${string}:${infer Param}`
|
|
17
|
+
? { [K in Param]: string | number }
|
|
18
|
+
: Record<string, never>;
|
|
19
|
+
|
|
20
|
+
export type RouteSchema = Record<string, {
|
|
21
|
+
method: string;
|
|
22
|
+
params?: Record<string, any>;
|
|
23
|
+
body?: any;
|
|
24
|
+
response?: any;
|
|
25
|
+
}>;
|
|
26
|
+
|
|
27
|
+
type PathsForMethod<Routes extends RouteSchema, M extends string> = {
|
|
28
|
+
[K in keyof Routes]: Routes[K]['method'] extends M ? K : never;
|
|
29
|
+
}[keyof Routes] & string;
|
|
30
|
+
|
|
31
|
+
export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
32
|
+
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
|
|
33
|
+
path: P,
|
|
34
|
+
options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string> } : {})
|
|
35
|
+
): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
36
|
+
|
|
37
|
+
post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(
|
|
38
|
+
path: P,
|
|
39
|
+
options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string>; body?: Routes[P]['body'] } : {})
|
|
40
|
+
): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
41
|
+
|
|
42
|
+
put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(
|
|
43
|
+
path: P,
|
|
44
|
+
options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string>; body?: Routes[P]['body'] } : {})
|
|
45
|
+
): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
46
|
+
|
|
47
|
+
patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(
|
|
48
|
+
path: P,
|
|
49
|
+
options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string>; body?: Routes[P]['body'] } : {})
|
|
50
|
+
): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
51
|
+
|
|
52
|
+
delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(
|
|
53
|
+
path: P,
|
|
54
|
+
options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string> } : {})
|
|
55
|
+
): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
|
|
59
|
+
let finalPath = path;
|
|
60
|
+
if (options?.params) {
|
|
61
|
+
for (const [k, v] of Object.entries(options.params)) {
|
|
62
|
+
finalPath = finalPath.replace(`:${k}`, encodeURIComponent(String(v)));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
|
66
|
+
const normalizedPath = finalPath.startsWith('/') ? finalPath : `/${finalPath}`;
|
|
67
|
+
let url = `${base}${normalizedPath}`;
|
|
68
|
+
|
|
69
|
+
if (options?.query) {
|
|
70
|
+
const qs = new URLSearchParams();
|
|
71
|
+
for (const [k, v] of Object.entries(options.query)) {
|
|
72
|
+
if (v !== undefined) qs.set(k, String(v));
|
|
73
|
+
}
|
|
74
|
+
const str = qs.toString();
|
|
75
|
+
if (str) url += `?${str}`;
|
|
76
|
+
}
|
|
77
|
+
return url;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export const bareClient = <AppOrRoutes = any>(
|
|
81
|
+
baseUrlOrApp: string | { fetch: (req: Request) => any },
|
|
82
|
+
clientOptions: BareClientOptions = {}
|
|
83
|
+
): BareClient<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> => {
|
|
84
|
+
const isApp = typeof baseUrlOrApp === 'object' && baseUrlOrApp !== null && typeof baseUrlOrApp.fetch === 'function';
|
|
85
|
+
const baseUrl = isApp ? 'http://localhost' : (baseUrlOrApp as string);
|
|
86
|
+
const fetchImpl = clientOptions.fetch ?? (isApp ? ((input: any, init?: RequestInit) => baseUrlOrApp.fetch(new Request(String(input), init))) as any : fetch);
|
|
87
|
+
const defaultHeaders = clientOptions.headers ?? {};
|
|
88
|
+
|
|
89
|
+
const request = async (method: string, path: string, options?: ClientRequestOptions) => {
|
|
90
|
+
const url = buildUrl(baseUrl, path, options);
|
|
91
|
+
const headers: Record<string, string> = {
|
|
92
|
+
...defaultHeaders,
|
|
93
|
+
...(options?.headers ?? {})
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const init: RequestInit = { method, headers };
|
|
97
|
+
if (options?.body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
98
|
+
if (!headers['Content-Type'] && !headers['content-type']) {
|
|
99
|
+
headers['Content-Type'] = 'application/json';
|
|
100
|
+
}
|
|
101
|
+
init.body = typeof options.body === 'string' ? options.body : JSON.stringify(options.body);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const res = await fetchImpl(url, init);
|
|
105
|
+
const ct = res.headers.get('content-type') || '';
|
|
106
|
+
const data = ct.includes('application/json') ? await res.json() : await res.text();
|
|
107
|
+
if (!res.ok) {
|
|
108
|
+
const err: any = new Error(`HTTP ${res.status}`);
|
|
109
|
+
err.status = res.status;
|
|
110
|
+
err.data = data;
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
return data;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
get: (path: string, options?: ClientRequestOptions) => request('GET', path, options),
|
|
118
|
+
post: (path: string, options?: ClientRequestOptions) => request('POST', path, options),
|
|
119
|
+
put: (path: string, options?: ClientRequestOptions) => request('PUT', path, options),
|
|
120
|
+
patch: (path: string, options?: ClientRequestOptions) => request('PATCH', path, options),
|
|
121
|
+
delete: (path: string, options?: ClientRequestOptions) => request('DELETE', path, options)
|
|
122
|
+
} as any;
|
|
123
|
+
};
|