barejs 0.1.49 → 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 +257 -98
- package/dist/index.js +157 -94
- package/dist/types/client/index.d.ts +24 -22
- package/dist/types/core/bare.d.ts +83 -3
- package/dist/types/core/context.d.ts +47 -1
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +21 -10
- package/dist/types/index.d.ts +16 -8
- package/dist/types/security/auth.d.ts +10 -1
- package/dist/types/security/cors.d.ts +7 -3
- package/dist/types/security/csrf.d.ts +12 -0
- package/dist/types/security/idempotency.d.ts +22 -0
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +18 -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/dist/types/utils/static.d.ts +5 -1
- package/llms.txt +138 -0
- package/package.json +3 -1
- package/src/client/index.ts +61 -18
- package/src/core/bare.ts +409 -49
- package/src/core/context.ts +266 -32
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +43 -16
- package/src/index.ts +25 -9
- package/src/security/auth.ts +68 -11
- package/src/security/cors.ts +85 -31
- package/src/security/csrf.ts +84 -0
- package/src/security/hash.ts +8 -2
- package/src/security/headers.ts +12 -3
- package/src/security/idempotency.ts +118 -0
- package/src/security/rateLimit.ts +1 -6
- package/src/security/resilience.ts +91 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +201 -5
- 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 +59 -14
- package/src/utils/static.ts +71 -5
package/src/core/context.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
|
|
1
3
|
export type Params = Record<string, string>;
|
|
2
4
|
export type Next = () => Promise<any> | any;
|
|
3
5
|
export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
|
|
@@ -5,6 +7,40 @@ export type Handler = (ctx: Context) => Promise<any> | any;
|
|
|
5
7
|
export type GroupCallback = (router: any) => void;
|
|
6
8
|
export type AuthUser = Record<string, any>;
|
|
7
9
|
|
|
10
|
+
export interface CookieOptions {
|
|
11
|
+
httpOnly?: boolean;
|
|
12
|
+
secure?: boolean;
|
|
13
|
+
sameSite?: 'Strict' | 'Lax' | 'None';
|
|
14
|
+
path?: string;
|
|
15
|
+
domain?: string;
|
|
16
|
+
maxAge?: number;
|
|
17
|
+
expires?: Date;
|
|
18
|
+
secret?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface UploadOptions {
|
|
22
|
+
/** Max size per file in bytes (default: 5MB) */
|
|
23
|
+
maxFileSize?: number;
|
|
24
|
+
/** Max number of uploaded files (default: 10) */
|
|
25
|
+
maxFiles?: number;
|
|
26
|
+
/** Allowed MIME types (e.g. ['image/png', 'image/jpeg', 'application/pdf']) */
|
|
27
|
+
allowedTypes?: string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface UploadedFile {
|
|
31
|
+
fieldName: string;
|
|
32
|
+
filename: string;
|
|
33
|
+
safeName: string;
|
|
34
|
+
type: string;
|
|
35
|
+
size: number;
|
|
36
|
+
file: File;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface UploadResult {
|
|
40
|
+
fields: Record<string, string>;
|
|
41
|
+
files: UploadedFile[];
|
|
42
|
+
}
|
|
43
|
+
|
|
8
44
|
export class Context {
|
|
9
45
|
public req!: Request;
|
|
10
46
|
public params: Params = {};
|
|
@@ -13,6 +49,11 @@ export class Context {
|
|
|
13
49
|
public store = new Map<string, any>();
|
|
14
50
|
public body: any = undefined;
|
|
15
51
|
public _query: Record<string, string> | undefined = undefined;
|
|
52
|
+
public _cookies: Record<string, string> | undefined = undefined;
|
|
53
|
+
public _setCookies: string[] | undefined = undefined;
|
|
54
|
+
public _requestId: string | undefined = undefined;
|
|
55
|
+
public _peerIp: string | undefined = undefined;
|
|
56
|
+
public _trustProxy: boolean = true;
|
|
16
57
|
constructor() { }
|
|
17
58
|
|
|
18
59
|
public get query(): Record<string, string> {
|
|
@@ -38,10 +79,14 @@ export class Context {
|
|
|
38
79
|
k = url.slice(start, amp);
|
|
39
80
|
v = '';
|
|
40
81
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
82
|
+
if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
|
|
83
|
+
if (k.indexOf('%') !== -1) {
|
|
84
|
+
try { k = decodeURIComponent(k); } catch { /* keep raw */ }
|
|
85
|
+
}
|
|
86
|
+
if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
|
|
87
|
+
if (v.indexOf('%') !== -1) {
|
|
88
|
+
try { v = decodeURIComponent(v); } catch { /* keep raw */ }
|
|
89
|
+
}
|
|
45
90
|
if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
|
|
46
91
|
result[k] = v;
|
|
47
92
|
}
|
|
@@ -58,14 +103,106 @@ export class Context {
|
|
|
58
103
|
return this.query[key];
|
|
59
104
|
}
|
|
60
105
|
|
|
61
|
-
public
|
|
106
|
+
public get cookies(): Record<string, string> {
|
|
107
|
+
if (this._cookies !== undefined) return this._cookies;
|
|
108
|
+
const result: Record<string, string> = {};
|
|
109
|
+
const header = this.req?.headers?.get('cookie');
|
|
110
|
+
if (header) {
|
|
111
|
+
let start = 0;
|
|
112
|
+
const len = header.length;
|
|
113
|
+
while (start < len) {
|
|
114
|
+
let semi = header.indexOf(';', start);
|
|
115
|
+
if (semi === -1) semi = len;
|
|
116
|
+
const eq = header.indexOf('=', start);
|
|
117
|
+
if (eq !== -1 && eq < semi) {
|
|
118
|
+
const k = header.slice(start, eq).trim();
|
|
119
|
+
let v = header.slice(eq + 1, semi).trim();
|
|
120
|
+
try {
|
|
121
|
+
v = decodeURIComponent(v);
|
|
122
|
+
} catch { /* keep raw */ }
|
|
123
|
+
if (k && k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
|
|
124
|
+
result[k] = v;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
start = semi + 1;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
this._cookies = result;
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
public setCookie(name: string, value: string, options: CookieOptions = {}): this {
|
|
135
|
+
let finalVal = value;
|
|
136
|
+
if (options.secret) {
|
|
137
|
+
const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
|
|
138
|
+
finalVal = `${value}.${sig}`;
|
|
139
|
+
}
|
|
140
|
+
let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
|
|
141
|
+
cookieStr += `; Path=${options.path ?? '/'}`;
|
|
142
|
+
if (options.domain) cookieStr += `; Domain=${options.domain}`;
|
|
143
|
+
if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
|
|
144
|
+
if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
|
|
145
|
+
if (options.httpOnly !== false) cookieStr += '; HttpOnly';
|
|
146
|
+
if (options.secure) cookieStr += '; Secure';
|
|
147
|
+
cookieStr += `; SameSite=${options.sameSite ?? 'Lax'}`;
|
|
148
|
+
|
|
149
|
+
if (!this._setCookies) this._setCookies = [];
|
|
150
|
+
this._setCookies.push(cookieStr);
|
|
151
|
+
return this;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
public getSignedCookie(name: string, secret: string): string | null {
|
|
155
|
+
const raw = this.cookies[name];
|
|
156
|
+
if (!raw) return null;
|
|
157
|
+
const dotIdx = raw.lastIndexOf('.');
|
|
158
|
+
if (dotIdx <= 0) return null;
|
|
159
|
+
const value = raw.slice(0, dotIdx);
|
|
160
|
+
const sigB64 = raw.slice(dotIdx + 1);
|
|
161
|
+
const expected = createHmac('sha256', secret).update(value).digest();
|
|
162
|
+
const actual = Buffer.from(sigB64, 'base64url');
|
|
163
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
return value;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): this {
|
|
170
|
+
return this.setCookie(name, '', {
|
|
171
|
+
...options,
|
|
172
|
+
maxAge: 0,
|
|
173
|
+
expires: new Date(0)
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
public async jsonBody(maxBytes: number = 1048576): Promise<any> {
|
|
62
178
|
if (this.body !== undefined) return this.body;
|
|
63
179
|
|
|
64
180
|
const contentType = this.req.headers.get("content-type");
|
|
65
181
|
if (contentType && contentType.includes("application/json")) {
|
|
182
|
+
const lenHeader = this.req.headers.get("content-length");
|
|
183
|
+
if (lenHeader !== null) {
|
|
184
|
+
const lenNum = Number(lenHeader);
|
|
185
|
+
if (lenNum > maxBytes) {
|
|
186
|
+
const err: any = new Error("Payload Too Large");
|
|
187
|
+
err.status = 413;
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
return this.body = await this.req.json();
|
|
192
|
+
} catch {
|
|
193
|
+
return this.body = null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
66
196
|
try {
|
|
67
|
-
|
|
68
|
-
|
|
197
|
+
const text = await this.req.text();
|
|
198
|
+
if (Buffer.byteLength(text, 'utf-8') > maxBytes) {
|
|
199
|
+
const err: any = new Error("Payload Too Large");
|
|
200
|
+
err.status = 413;
|
|
201
|
+
throw err;
|
|
202
|
+
}
|
|
203
|
+
return this.body = JSON.parse(text);
|
|
204
|
+
} catch (e: any) {
|
|
205
|
+
if (e?.status === 413) throw e;
|
|
69
206
|
return this.body = null;
|
|
70
207
|
}
|
|
71
208
|
}
|
|
@@ -79,7 +216,10 @@ export class Context {
|
|
|
79
216
|
if (this.store.size > 0) this.store.clear();
|
|
80
217
|
this.params = {};
|
|
81
218
|
this._query = undefined;
|
|
219
|
+
this._cookies = undefined;
|
|
220
|
+
this._setCookies = undefined;
|
|
82
221
|
this.body = undefined;
|
|
222
|
+
this._peerIp = undefined;
|
|
83
223
|
return this;
|
|
84
224
|
}
|
|
85
225
|
|
|
@@ -88,38 +228,28 @@ export class Context {
|
|
|
88
228
|
return this;
|
|
89
229
|
}
|
|
90
230
|
|
|
91
|
-
// public json(data: any): Response {
|
|
92
|
-
// if (this._headers !== undefined) {
|
|
93
|
-
// if (this._headers["content-type"] === undefined) {
|
|
94
|
-
// this._headers["content-type"] = "application/json";
|
|
95
|
-
// }
|
|
96
|
-
// return Response.json(data, {
|
|
97
|
-
// status: this._status,
|
|
98
|
-
// headers: this._headers
|
|
99
|
-
// });
|
|
100
|
-
// }
|
|
101
|
-
// if (this._status === 200) {
|
|
102
|
-
// return Response.json(data);
|
|
103
|
-
// }
|
|
104
|
-
// return Response.json(data, { status: this._status });
|
|
105
|
-
// }
|
|
106
231
|
public json(data: any): Response {
|
|
107
232
|
const status = this._status || 200;
|
|
233
|
+
let res: Response;
|
|
108
234
|
|
|
109
|
-
// No custom headers
|
|
110
235
|
if (!this._headers) {
|
|
111
|
-
|
|
236
|
+
res = Response.json(data, { status });
|
|
237
|
+
} else {
|
|
238
|
+
if (this._headers["content-type"] === undefined) {
|
|
239
|
+
this._headers["content-type"] = "application/json";
|
|
240
|
+
}
|
|
241
|
+
res = Response.json(data, {
|
|
242
|
+
status,
|
|
243
|
+
headers: this._headers as any
|
|
244
|
+
});
|
|
112
245
|
}
|
|
113
246
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
247
|
+
if (this._setCookies) {
|
|
248
|
+
for (let i = 0; i < this._setCookies.length; i++) {
|
|
249
|
+
res.headers.append('Set-Cookie', this._setCookies[i]!);
|
|
250
|
+
}
|
|
117
251
|
}
|
|
118
|
-
|
|
119
|
-
return Response.json(data, {
|
|
120
|
-
status,
|
|
121
|
-
headers: this._headers as any // ⚠️ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' headers
|
|
122
|
-
});
|
|
252
|
+
return res;
|
|
123
253
|
}
|
|
124
254
|
|
|
125
255
|
public set(key: string, value: any): this {
|
|
@@ -133,9 +263,14 @@ export class Context {
|
|
|
133
263
|
|
|
134
264
|
public setHeader(name: string, value: string): this {
|
|
135
265
|
if (!this._headers) this._headers = {};
|
|
266
|
+
else if (Object.isFrozen(this._headers)) this._headers = { ...this._headers };
|
|
136
267
|
this._headers[name.toLowerCase()] = value;
|
|
137
268
|
return this;
|
|
138
269
|
}
|
|
270
|
+
|
|
271
|
+
public get user(): AuthUser | undefined {
|
|
272
|
+
return this.store.get('user');
|
|
273
|
+
}
|
|
139
274
|
|
|
140
275
|
|
|
141
276
|
public send(message: string, extra: Record<string, any> = {}): Response {
|
|
@@ -148,6 +283,30 @@ export class Context {
|
|
|
148
283
|
});
|
|
149
284
|
}
|
|
150
285
|
|
|
286
|
+
public html(content: string, status?: number): Response {
|
|
287
|
+
const headers: Record<string, string> = {
|
|
288
|
+
'content-type': 'text/html; charset=utf-8',
|
|
289
|
+
...(this._headers || {})
|
|
290
|
+
};
|
|
291
|
+
return new Response(content, { status: status ?? this._status, headers });
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
public text(content: string, status?: number): Response {
|
|
295
|
+
const headers: Record<string, string> = {
|
|
296
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
297
|
+
...(this._headers || {})
|
|
298
|
+
};
|
|
299
|
+
return new Response(content, { status: status ?? this._status, headers });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
public redirect(url: string, status: number = 302): Response {
|
|
303
|
+
const headers: Record<string, string> = {
|
|
304
|
+
'location': url,
|
|
305
|
+
...(this._headers || {})
|
|
306
|
+
};
|
|
307
|
+
return new Response(null, { status, headers });
|
|
308
|
+
}
|
|
309
|
+
|
|
151
310
|
public sse(
|
|
152
311
|
source:
|
|
153
312
|
| AsyncIterable<string | { event?: string; data: any; id?: string; retry?: number }>
|
|
@@ -203,4 +362,79 @@ export class Context {
|
|
|
203
362
|
};
|
|
204
363
|
return new Response(stream, { status: this._status || 200, headers });
|
|
205
364
|
}
|
|
365
|
+
|
|
366
|
+
public get requestId(): string {
|
|
367
|
+
if (this._requestId !== undefined) return this._requestId;
|
|
368
|
+
const hdr = this.req?.headers?.get('x-request-id');
|
|
369
|
+
this._requestId = hdr && hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
|
|
370
|
+
return this._requestId;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
public get ip(): string {
|
|
374
|
+
if (this._trustProxy) {
|
|
375
|
+
const xff = this.req?.headers?.get('x-forwarded-for');
|
|
376
|
+
if (xff) return xff.split(',')[0]!.trim();
|
|
377
|
+
const forwarded =
|
|
378
|
+
this.req?.headers?.get('x-real-ip') ||
|
|
379
|
+
this.req?.headers?.get('cf-connecting-ip');
|
|
380
|
+
if (forwarded) return forwarded;
|
|
381
|
+
}
|
|
382
|
+
return this._peerIp || '127.0.0.1';
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
public async upload(options: UploadOptions = {}): Promise<UploadResult> {
|
|
386
|
+
const maxFileSize = options.maxFileSize ?? 5 * 1024 * 1024;
|
|
387
|
+
const maxFiles = options.maxFiles ?? 10;
|
|
388
|
+
const allowed = options.allowedTypes ? new Set(options.allowedTypes) : null;
|
|
389
|
+
|
|
390
|
+
const ct = this.req?.headers?.get('content-type') || '';
|
|
391
|
+
if (!ct.includes('multipart/form-data')) {
|
|
392
|
+
throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const contentLen = Number(this.req?.headers?.get('content-length') || 0);
|
|
396
|
+
if (contentLen > maxFileSize * maxFiles + 65536) {
|
|
397
|
+
throw Object.assign(new Error('Payload Too Large'), { status: 413 });
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const form = await this.req.formData();
|
|
401
|
+
const fields: Record<string, string> = {};
|
|
402
|
+
const files: UploadedFile[] = [];
|
|
403
|
+
|
|
404
|
+
for (const [fieldName, value] of form.entries()) {
|
|
405
|
+
if (typeof value === 'string') {
|
|
406
|
+
if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
|
|
407
|
+
fields[fieldName] = value;
|
|
408
|
+
}
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const fileObj = value as unknown as File;
|
|
413
|
+
if (files.length >= maxFiles) {
|
|
414
|
+
throw Object.assign(new Error(`Too many files (max ${maxFiles})`), { status: 413 });
|
|
415
|
+
}
|
|
416
|
+
if (fileObj.size > maxFileSize) {
|
|
417
|
+
throw Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
|
|
418
|
+
}
|
|
419
|
+
const mime = (fileObj.type || '').split(';')[0]!.trim().toLowerCase();
|
|
420
|
+
if (allowed && !allowed.has(mime)) {
|
|
421
|
+
throw Object.assign(new Error(`Unsupported file type: ${fileObj.type || 'unknown'}`), { status: 415 });
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const rawName = fileObj.name || 'file';
|
|
425
|
+
const baseName = rawName.split(/[\\/]/).pop() || 'file';
|
|
426
|
+
const safeName = baseName.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/^\.+/, '') || 'file';
|
|
427
|
+
|
|
428
|
+
files.push({
|
|
429
|
+
fieldName,
|
|
430
|
+
filename: rawName,
|
|
431
|
+
safeName,
|
|
432
|
+
type: fileObj.type,
|
|
433
|
+
size: fileObj.size,
|
|
434
|
+
file: fileObj
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
return { fields, files };
|
|
439
|
+
}
|
|
206
440
|
}
|
package/src/core/radix.ts
CHANGED
|
@@ -5,13 +5,18 @@ export class RadixNode {
|
|
|
5
5
|
public staticKeys: string[] = [];
|
|
6
6
|
public paramNode: RadixNode | null = null;
|
|
7
7
|
public paramName: string | null = null;
|
|
8
|
+
public wildcardNode: RadixNode | null = null;
|
|
8
9
|
public handlers: Record<string, Function> = {};
|
|
9
10
|
|
|
10
11
|
public insert(path: string, method: string, handler: Function) {
|
|
11
12
|
let node: RadixNode = this;
|
|
12
13
|
const parts = path.split('/').filter(Boolean);
|
|
13
14
|
for (const part of parts) {
|
|
14
|
-
if (part
|
|
15
|
+
if (part === '*') {
|
|
16
|
+
if (!node.wildcardNode) node.wildcardNode = new RadixNode();
|
|
17
|
+
node = node.wildcardNode;
|
|
18
|
+
break;
|
|
19
|
+
} else if (part.startsWith(':')) {
|
|
15
20
|
if (!node.paramNode) node.paramNode = new RadixNode();
|
|
16
21
|
node.paramName = part.slice(1);
|
|
17
22
|
node = node.paramNode;
|
|
@@ -69,6 +74,9 @@ export class RadixNode {
|
|
|
69
74
|
if (node.paramNode) {
|
|
70
75
|
ctx.params[node.paramName!] = url.slice(i, j);
|
|
71
76
|
node = node.paramNode;
|
|
77
|
+
} else if (node.wildcardNode) {
|
|
78
|
+
ctx.params['*'] = url.slice(i);
|
|
79
|
+
return node.wildcardNode.handlers[method] || null;
|
|
72
80
|
} else return null;
|
|
73
81
|
}
|
|
74
82
|
i = j + 1;
|
|
@@ -125,8 +133,19 @@ export class RadixNode {
|
|
|
125
133
|
code += `${indent} }\n`;
|
|
126
134
|
code += `${indent}}\n`;
|
|
127
135
|
|
|
136
|
+
} else if (this.staticKeys.length > 4) {
|
|
137
|
+
code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
|
|
138
|
+
code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
|
|
139
|
+
code += `${indent}switch (${pathPrefix}.slice(${idxPrefix}, slash${level})) {\n`;
|
|
140
|
+
for (const key of this.staticKeys) {
|
|
141
|
+
code += `${indent} case ${JSON.stringify(key)}: {\n`;
|
|
142
|
+
const child = this.children[key]!;
|
|
143
|
+
code += child.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, paramAccumulator);
|
|
144
|
+
code += `${indent} break;\n`;
|
|
145
|
+
code += `${indent} }\n`;
|
|
146
|
+
}
|
|
147
|
+
code += `${indent}}\n`;
|
|
128
148
|
} else {
|
|
129
|
-
|
|
130
149
|
code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
|
|
131
150
|
code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
|
|
132
151
|
code += `${indent}const len${level} = slash${level} - (${idxPrefix});\n\n`;
|
|
@@ -165,7 +184,7 @@ export class RadixNode {
|
|
|
165
184
|
// 2. Param Node Logic (Fallback)
|
|
166
185
|
if (this.paramNode) {
|
|
167
186
|
const pNode = this.paramNode;
|
|
168
|
-
if (this.staticKeys.length
|
|
187
|
+
if (this.staticKeys.length <= 1) {
|
|
169
188
|
code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
|
|
170
189
|
code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
|
|
171
190
|
}
|
|
@@ -177,6 +196,21 @@ export class RadixNode {
|
|
|
177
196
|
code += pNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newAccumulator);
|
|
178
197
|
}
|
|
179
198
|
|
|
199
|
+
// 3. Wildcard Node Logic (Catch-All *)
|
|
200
|
+
if (this.wildcardNode && Object.keys(this.wildcardNode.handlers).length > 0) {
|
|
201
|
+
const wVar = `wL${level}`;
|
|
202
|
+
code += `${indent}const ${wVar} = ${pathPrefix}.slice(${idxPrefix}, urlLen);\n`;
|
|
203
|
+
const wAcc = [...paramAccumulator, { name: '*', varName: wVar }];
|
|
204
|
+
const props = wAcc.map((p: any) => `${JSON.stringify(p.name)}: ${p.varName}`).join(', ');
|
|
205
|
+
code += `${indent}ctx.params = { ${props} };\n`;
|
|
206
|
+
code += `${indent}switch(method) {\n`;
|
|
207
|
+
for (const [m, h] of Object.entries(this.wildcardNode.handlers)) {
|
|
208
|
+
const hName = register(h as Function);
|
|
209
|
+
code += `${indent} case ${JSON.stringify(m)}: return ${hName}(ctx);\n`;
|
|
210
|
+
}
|
|
211
|
+
code += `${indent}}\n`;
|
|
212
|
+
}
|
|
213
|
+
|
|
180
214
|
return code;
|
|
181
215
|
}
|
|
182
216
|
|
package/src/core/router.ts
CHANGED
|
@@ -3,10 +3,19 @@ import {
|
|
|
3
3
|
type Handler,
|
|
4
4
|
type GroupCallback
|
|
5
5
|
} from '../core/context';
|
|
6
|
+
import { schemaValidator, type RouteSchemas } from '../security/validators';
|
|
6
7
|
|
|
7
|
-
type
|
|
8
|
+
import type { RouteSchema } from '../client/index';
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
11
|
+
|
|
12
|
+
export type InferSchema<S> =
|
|
13
|
+
S extends { static: infer T } ? T
|
|
14
|
+
: S extends { _output: infer T } ? T
|
|
15
|
+
: any;
|
|
16
|
+
|
|
17
|
+
export class BareRouter<Routes extends RouteSchema = {}> {
|
|
18
|
+
declare readonly __routes: Routes;
|
|
10
19
|
public routes: any[] = [];
|
|
11
20
|
|
|
12
21
|
constructor(
|
|
@@ -14,45 +23,63 @@ export class BareRouter {
|
|
|
14
23
|
public groupMiddleware: any[] = []
|
|
15
24
|
) { }
|
|
16
25
|
|
|
17
|
-
|
|
26
|
+
protected _add(method: string, path: string, handlers: HandlersChain) {
|
|
18
27
|
let fullPath = (this.prefix + "/" + path)
|
|
19
|
-
.replace(/\/+/g, "/")
|
|
20
|
-
|
|
21
|
-
|
|
28
|
+
.replace(/\/+/g, "/");
|
|
22
29
|
|
|
23
30
|
if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
|
|
24
31
|
|
|
32
|
+
const resolvedHandlers: any[] = [];
|
|
33
|
+
for (let i = 0; i < handlers.length; i++) {
|
|
34
|
+
const h = handlers[i];
|
|
35
|
+
if (typeof h === 'function') {
|
|
36
|
+
resolvedHandlers.push(h);
|
|
37
|
+
} else if (h && typeof h === 'object') {
|
|
38
|
+
resolvedHandlers.push(schemaValidator(h as RouteSchemas));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
25
42
|
this.routes.push({
|
|
26
43
|
method: method.toUpperCase(),
|
|
27
44
|
path: fullPath || "",
|
|
28
|
-
handlers: [...this.groupMiddleware, ...
|
|
45
|
+
handlers: [...this.groupMiddleware, ...resolvedHandlers]
|
|
29
46
|
});
|
|
30
47
|
return this;
|
|
31
48
|
}
|
|
32
49
|
|
|
33
|
-
public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
|
|
34
|
-
public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
|
|
35
|
-
public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
|
|
36
|
-
public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
|
|
37
|
-
public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
|
|
38
|
-
public options = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
|
|
50
|
+
public get: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
|
|
51
|
+
public post: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
|
|
52
|
+
public put: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
|
|
53
|
+
public patch: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
|
|
54
|
+
public delete: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
|
|
55
|
+
public options: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
|
|
56
|
+
public head: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("HEAD", path, h);
|
|
57
|
+
public all: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => {
|
|
58
|
+
for (const m of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
|
|
59
|
+
this._add(m, path, h);
|
|
60
|
+
}
|
|
61
|
+
return this;
|
|
62
|
+
};
|
|
39
63
|
|
|
40
64
|
public group = (path: string, ...args: any[]) => {
|
|
41
65
|
const callback = args.pop();
|
|
42
66
|
const middleware = args;
|
|
43
67
|
|
|
44
|
-
|
|
45
68
|
const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
|
|
46
69
|
const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
|
|
47
70
|
|
|
48
71
|
callback(subRouter);
|
|
49
72
|
this.routes.push(...subRouter.routes);
|
|
50
73
|
return this;
|
|
51
|
-
};
|
|
74
|
+
};
|
|
52
75
|
|
|
53
|
-
public use(mw:
|
|
76
|
+
public use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
77
|
+
public use(mw: any): BareRouter<Routes>;
|
|
78
|
+
public use(mw: any): any {
|
|
54
79
|
if (mw instanceof BareRouter || (mw && mw.routes)) {
|
|
55
80
|
this.routes.push(...mw.routes);
|
|
81
|
+
} else if (mw && typeof mw.install === 'function') {
|
|
82
|
+
mw.install(this);
|
|
56
83
|
} else {
|
|
57
84
|
this.groupMiddleware.push(mw);
|
|
58
85
|
}
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS, type WebSocketRouteHandler } from './core/bare';
|
|
9
|
+
export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
|
|
10
|
+
export { BareRouter, type InferSchema } from './core/router';
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Plugin Interface for BareJS
|
|
@@ -16,13 +17,17 @@ export interface BarePlugin {
|
|
|
16
17
|
}
|
|
17
18
|
|
|
18
19
|
// --- 2. Context & Types ---
|
|
20
|
+
export { Context } from './core/context';
|
|
19
21
|
export type {
|
|
20
22
|
Middleware,
|
|
21
23
|
Handler,
|
|
22
24
|
Next,
|
|
23
|
-
Context,
|
|
24
25
|
Params,
|
|
25
|
-
AuthUser
|
|
26
|
+
AuthUser,
|
|
27
|
+
CookieOptions,
|
|
28
|
+
UploadOptions,
|
|
29
|
+
UploadedFile,
|
|
30
|
+
UploadResult
|
|
26
31
|
} from './core/context';
|
|
27
32
|
|
|
28
33
|
// --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
|
|
@@ -30,7 +35,7 @@ import { Type } from "@sinclair/typebox";
|
|
|
30
35
|
export { Type, Type as T, Type as TypeBox };
|
|
31
36
|
|
|
32
37
|
// --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
|
|
33
|
-
import { typebox, zod, native, validate, Z } from './security/validators';
|
|
38
|
+
import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
|
|
34
39
|
export {
|
|
35
40
|
// TypeBox Engine
|
|
36
41
|
typebox,
|
|
@@ -45,21 +50,31 @@ export {
|
|
|
45
50
|
native as n,
|
|
46
51
|
// Auto-Detect Engine
|
|
47
52
|
validate,
|
|
48
|
-
validate as v
|
|
53
|
+
validate as v,
|
|
54
|
+
// Unified Route Schema Engine (body, query, params, headers, response, detail, maxBodySize)
|
|
55
|
+
schemaValidator,
|
|
56
|
+
createResponseFilter,
|
|
57
|
+
type RouteSchemas,
|
|
58
|
+
type RouteDetail
|
|
49
59
|
};
|
|
50
60
|
|
|
51
61
|
// --- 5. Middlewares & Utilities ---
|
|
52
|
-
|
|
62
|
+
export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
|
|
63
|
+
export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
|
|
53
64
|
export { cors } from './security/cors';
|
|
65
|
+
export { csrf, type CsrfOptions } from './security/csrf';
|
|
66
|
+
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
54
67
|
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
68
|
+
export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
|
|
69
|
+
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
55
70
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
56
|
-
export { staticFile } from './utils/static';
|
|
71
|
+
export { staticFile, type StaticOptions } from './utils/static';
|
|
72
|
+
export { compress, type CompressOptions } from './utils/compress';
|
|
57
73
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
58
|
-
export { BareRouter } from './core/router';
|
|
59
74
|
|
|
60
75
|
// --- 6. Authentication (Bun Native) ---
|
|
61
76
|
// Always deploy using process.env [2026-01-06]
|
|
62
|
-
export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
|
|
77
|
+
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions } from './security/auth';
|
|
63
78
|
// --- 7. Hashing ---
|
|
64
79
|
export { Hash as Password, Hash } from './security/hash';
|
|
65
80
|
|
|
@@ -69,5 +84,6 @@ export {
|
|
|
69
84
|
type BareClient,
|
|
70
85
|
type BareClientOptions,
|
|
71
86
|
type ClientRequestOptions,
|
|
87
|
+
type RouteEndpoint,
|
|
72
88
|
type RouteSchema
|
|
73
89
|
} from './client/index';
|