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
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
|
|
@@ -44,18 +44,13 @@ Supports **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({
|
|
|
44
44
|
// Sub-router
|
|
45
45
|
const api = new BareRouter();
|
|
46
46
|
api.get('/items', () => []);
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
//
|
|
50
|
-
app.use({
|
|
51
|
-
name: 'metrics-plugin',
|
|
52
|
-
install(app) {
|
|
53
|
-
app.get('/metrics', () => ({ uptime: process.uptime() }));
|
|
54
|
-
}
|
|
55
|
-
});
|
|
47
|
+
// Modular sub-routers preserve full bareClient() type inference across prefixes:
|
|
48
|
+
const api = new BareRouter().get('/items', () => []);
|
|
49
|
+
const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
|
|
56
50
|
```
|
|
57
51
|
|
|
58
|
-
## 3. Context (`ctx`)
|
|
52
|
+
## 3. Context (`ctx`) & Testing (`app.request`)
|
|
53
|
+
- `await app.request('/items', { method: 'POST', body: JSON.stringify({ name: 'a' }) })`: Ergonomic in-memory helper (normalizes relative paths to `http://localhost` and delegates to `app.fetch`).
|
|
59
54
|
- `ctx.req`: Raw incoming Bun `Request`.
|
|
60
55
|
- `ctx.params`: Route params (`Record<string, any>`, including `ctx.params['*']` for wildcards).
|
|
61
56
|
- `ctx.query` / `ctx.getQuery(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`).
|
|
@@ -88,35 +83,39 @@ const derivedApp = app.derive((ctx) => ({
|
|
|
88
83
|
```
|
|
89
84
|
Derived properties are attached directly onto `ctx` with TypeScript inference (`Bare<Derived>`) and automatically cleaned up when `Context` returns to the pool.
|
|
90
85
|
|
|
91
|
-
## 5. Built-in Security Middlewares,
|
|
86
|
+
## 5. Built-in Security Middlewares, Pluggable Redis Store, Compression & Static Cache
|
|
92
87
|
```ts
|
|
93
88
|
import {
|
|
94
89
|
cors, csrf, timeout, rateLimit, securityHeaders,
|
|
95
|
-
idempotency, createSingleflight,
|
|
96
|
-
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
90
|
+
idempotency, createSingleflight, redisStore, compress,
|
|
91
|
+
bareAuth, createToken, basicAuth, hasRole, revokeToken, Hash, staticFile
|
|
97
92
|
} from 'barejs';
|
|
98
93
|
|
|
94
|
+
// Optional shared Redis store (compatible with Bun.redis and ioredis)
|
|
95
|
+
const store = redisStore(Bun.redis, { prefix: 'myapp:' });
|
|
96
|
+
|
|
99
97
|
app.use(securityHeaders());
|
|
100
98
|
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
|
|
101
99
|
app.use(csrf({ allowedOrigins: ['https://app.example.com'], requireToken: true }));
|
|
102
100
|
app.use(timeout(10_000, { status: 408, message: 'Timed out' }));
|
|
103
|
-
app.use(
|
|
104
|
-
app.use(
|
|
101
|
+
app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip
|
|
102
|
+
app.use(rateLimit({ windowMs: 60_000, max: 100, store })); // Omit store for zero-overhead in-memory Map
|
|
103
|
+
app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
|
|
105
104
|
|
|
106
105
|
// 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 }));
|
|
106
|
+
app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store }), (ctx) => ({ paid: true }));
|
|
108
107
|
|
|
109
108
|
// Thundering-herd / Cache-stampede request coalescer
|
|
110
109
|
const sf = createSingleflight();
|
|
111
110
|
app.get('/report', () => sf.do('report-key', async () => ({ total: 100 })));
|
|
112
111
|
|
|
113
|
-
// Auth & Hashing
|
|
112
|
+
// Auth & Hashing (HS256 sync fast-path + RS256/ES256/JWKS async verification + revocationStore)
|
|
114
113
|
const hash = await Hash.make('password'); // Argon2id (64MB default)
|
|
115
114
|
const ok = await Hash.verify('password', hash);
|
|
116
115
|
const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, process.env.JWT_SECRET!);
|
|
117
116
|
|
|
118
|
-
|
|
119
|
-
app.get('/
|
|
117
|
+
app.get('/admin', bareAuth({ secret: process.env.JWT_SECRET!, revocationStore: store }), hasRole('admin'), (ctx) => ctx.user);
|
|
118
|
+
app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user);
|
|
120
119
|
```
|
|
121
120
|
|
|
122
121
|
## 6. Real-Time, RPC, OpenAPI & Client
|
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;
|