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.
@@ -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 = {};
@@ -12,35 +48,174 @@ export class Context {
12
48
  public _headers?: Record<string, string> | undefined = undefined;
13
49
  public store = new Map<string, any>();
14
50
  public body: any = undefined;
15
- public query: Record<string, string> = {};
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;
16
55
  constructor() { }
17
56
 
57
+ public get query(): Record<string, string> {
58
+ if (this._query !== undefined) return this._query;
59
+ const result: Record<string, string> = {};
60
+ const url = this.req?.url;
61
+ if (url) {
62
+ const qIdx = url.indexOf('?');
63
+ if (qIdx !== -1) {
64
+ let start = qIdx + 1;
65
+ const len = url.length;
66
+ while (start < len) {
67
+ let amp = url.indexOf('&', start);
68
+ if (amp === -1) amp = len;
69
+ if (amp > start) {
70
+ const eq = url.indexOf('=', start);
71
+ let k: string;
72
+ let v: string;
73
+ if (eq !== -1 && eq < amp) {
74
+ k = url.slice(start, eq);
75
+ v = url.slice(eq + 1, amp);
76
+ } else {
77
+ k = url.slice(start, amp);
78
+ v = '';
79
+ }
80
+ if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
81
+ if (k.indexOf('%') !== -1) {
82
+ try { k = decodeURIComponent(k); } catch { /* keep raw */ }
83
+ }
84
+ if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
85
+ if (v.indexOf('%') !== -1) {
86
+ try { v = decodeURIComponent(v); } catch { /* keep raw */ }
87
+ }
88
+ if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
89
+ result[k] = v;
90
+ }
91
+ }
92
+ start = amp + 1;
93
+ }
94
+ }
95
+ }
96
+ this._query = result;
97
+ return result;
98
+ }
18
99
 
19
- public async jsonBody(): Promise<any> {
100
+ public getQuery(key: string): string | undefined {
101
+ return this.query[key];
102
+ }
20
103
 
21
- if (this.body !== undefined) return this.body;
104
+ public get cookies(): Record<string, string> {
105
+ if (this._cookies !== undefined) return this._cookies;
106
+ const result: Record<string, string> = {};
107
+ const header = this.req?.headers?.get('cookie');
108
+ if (header) {
109
+ let start = 0;
110
+ const len = header.length;
111
+ while (start < len) {
112
+ let semi = header.indexOf(';', start);
113
+ if (semi === -1) semi = len;
114
+ const eq = header.indexOf('=', start);
115
+ if (eq !== -1 && eq < semi) {
116
+ const k = header.slice(start, eq).trim();
117
+ let v = header.slice(eq + 1, semi).trim();
118
+ try {
119
+ v = decodeURIComponent(v);
120
+ } catch { /* keep raw */ }
121
+ if (k && k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
122
+ result[k] = v;
123
+ }
124
+ }
125
+ start = semi + 1;
126
+ }
127
+ }
128
+ this._cookies = result;
129
+ return result;
130
+ }
131
+
132
+ public setCookie(name: string, value: string, options: CookieOptions = {}): this {
133
+ let finalVal = value;
134
+ if (options.secret) {
135
+ const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
136
+ finalVal = `${value}.${sig}`;
137
+ }
138
+ let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
139
+ cookieStr += `; Path=${options.path ?? '/'}`;
140
+ if (options.domain) cookieStr += `; Domain=${options.domain}`;
141
+ if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
142
+ if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
143
+ if (options.httpOnly !== false) cookieStr += '; HttpOnly';
144
+ if (options.secure) cookieStr += '; Secure';
145
+ cookieStr += `; SameSite=${options.sameSite ?? 'Lax'}`;
146
+
147
+ if (!this._setCookies) this._setCookies = [];
148
+ this._setCookies.push(cookieStr);
149
+ return this;
150
+ }
22
151
 
152
+ public getSignedCookie(name: string, secret: string): string | null {
153
+ const raw = this.cookies[name];
154
+ if (!raw) return null;
155
+ const dotIdx = raw.lastIndexOf('.');
156
+ if (dotIdx <= 0) return null;
157
+ const value = raw.slice(0, dotIdx);
158
+ const sigB64 = raw.slice(dotIdx + 1);
159
+ const expected = createHmac('sha256', secret).update(value).digest();
160
+ const actual = Buffer.from(sigB64, 'base64url');
161
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
162
+ return null;
163
+ }
164
+ return value;
165
+ }
166
+
167
+ public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): this {
168
+ return this.setCookie(name, '', {
169
+ ...options,
170
+ maxAge: 0,
171
+ expires: new Date(0)
172
+ });
173
+ }
174
+
175
+ public async jsonBody(maxBytes: number = 1048576): Promise<any> {
176
+ if (this.body !== undefined) return this.body;
23
177
 
24
178
  const contentType = this.req.headers.get("content-type");
25
179
  if (contentType && contentType.includes("application/json")) {
180
+ const lenHeader = this.req.headers.get("content-length");
181
+ if (lenHeader !== null) {
182
+ const lenNum = Number(lenHeader);
183
+ if (lenNum > maxBytes) {
184
+ const err: any = new Error("Payload Too Large");
185
+ err.status = 413;
186
+ throw err;
187
+ }
188
+ try {
189
+ return this.body = await this.req.json();
190
+ } catch {
191
+ return this.body = null;
192
+ }
193
+ }
26
194
  try {
27
-
28
- return this.body = await this.req.json();
29
- } catch {
195
+ const text = await this.req.text();
196
+ if (Buffer.byteLength(text, 'utf-8') > maxBytes) {
197
+ const err: any = new Error("Payload Too Large");
198
+ err.status = 413;
199
+ throw err;
200
+ }
201
+ return this.body = JSON.parse(text);
202
+ } catch (e: any) {
203
+ if (e?.status === 413) throw e;
30
204
  return this.body = null;
31
205
  }
32
206
  }
33
207
  return this.body = null;
34
208
  }
35
209
 
36
-
37
210
  public reset(req: Request): this {
38
211
  this.req = req;
39
212
  this._status = 200;
40
213
  this._headers = undefined;
41
214
  if (this.store.size > 0) this.store.clear();
42
215
  this.params = {};
43
- this.query = {};
216
+ this._query = undefined;
217
+ this._cookies = undefined;
218
+ this._setCookies = undefined;
44
219
  this.body = undefined;
45
220
  return this;
46
221
  }
@@ -50,38 +225,28 @@ export class Context {
50
225
  return this;
51
226
  }
52
227
 
53
- // public json(data: any): Response {
54
- // if (this._headers !== undefined) {
55
- // if (this._headers["content-type"] === undefined) {
56
- // this._headers["content-type"] = "application/json";
57
- // }
58
- // return Response.json(data, {
59
- // status: this._status,
60
- // headers: this._headers
61
- // });
62
- // }
63
- // if (this._status === 200) {
64
- // return Response.json(data);
65
- // }
66
- // return Response.json(data, { status: this._status });
67
- // }
68
228
  public json(data: any): Response {
69
229
  const status = this._status || 200;
230
+ let res: Response;
70
231
 
71
- // No custom headers
72
232
  if (!this._headers) {
73
- return Response.json(data, { status });
233
+ res = Response.json(data, { status });
234
+ } else {
235
+ if (this._headers["content-type"] === undefined) {
236
+ this._headers["content-type"] = "application/json";
237
+ }
238
+ res = Response.json(data, {
239
+ status,
240
+ headers: this._headers as any
241
+ });
74
242
  }
75
243
 
76
- // Ensure Content-Type is set to application/json
77
- if (this._headers["content-type"] === undefined) {
78
- this._headers["content-type"] = "application/json";
244
+ if (this._setCookies) {
245
+ for (let i = 0; i < this._setCookies.length; i++) {
246
+ res.headers.append('Set-Cookie', this._setCookies[i]!);
247
+ }
79
248
  }
80
-
81
- return Response.json(data, {
82
- status,
83
- headers: this._headers as any // ⚠️ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' headers
84
- });
249
+ return res;
85
250
  }
86
251
 
87
252
  public set(key: string, value: any): this {
@@ -95,9 +260,14 @@ export class Context {
95
260
 
96
261
  public setHeader(name: string, value: string): this {
97
262
  if (!this._headers) this._headers = {};
263
+ else if (Object.isFrozen(this._headers)) this._headers = { ...this._headers };
98
264
  this._headers[name.toLowerCase()] = value;
99
265
  return this;
100
266
  }
267
+
268
+ public get user(): AuthUser | undefined {
269
+ return this.store.get('user');
270
+ }
101
271
 
102
272
 
103
273
  public send(message: string, extra: Record<string, any> = {}): Response {
@@ -109,4 +279,157 @@ export class Context {
109
279
  ...extra
110
280
  });
111
281
  }
282
+
283
+ public html(content: string, status?: number): Response {
284
+ const headers: Record<string, string> = {
285
+ 'content-type': 'text/html; charset=utf-8',
286
+ ...(this._headers || {})
287
+ };
288
+ return new Response(content, { status: status ?? this._status, headers });
289
+ }
290
+
291
+ public text(content: string, status?: number): Response {
292
+ const headers: Record<string, string> = {
293
+ 'content-type': 'text/plain; charset=utf-8',
294
+ ...(this._headers || {})
295
+ };
296
+ return new Response(content, { status: status ?? this._status, headers });
297
+ }
298
+
299
+ public redirect(url: string, status: number = 302): Response {
300
+ const headers: Record<string, string> = {
301
+ 'location': url,
302
+ ...(this._headers || {})
303
+ };
304
+ return new Response(null, { status, headers });
305
+ }
306
+
307
+ public sse(
308
+ source:
309
+ | AsyncIterable<string | { event?: string; data: any; id?: string; retry?: number }>
310
+ | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)
311
+ ): Response {
312
+ const encoder = new TextEncoder();
313
+ const formatChunk = (chunk: string | { event?: string; data: any; id?: string; retry?: number }): Uint8Array => {
314
+ if (typeof chunk === 'string') {
315
+ return encoder.encode(`data: ${chunk}\n\n`);
316
+ }
317
+ let out = '';
318
+ if (chunk.id !== undefined) out += `id: ${chunk.id}\n`;
319
+ if (chunk.event !== undefined) out += `event: ${chunk.event}\n`;
320
+ if (chunk.retry !== undefined) out += `retry: ${chunk.retry}\n`;
321
+ const payload = typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data);
322
+ out += `data: ${payload}\n\n`;
323
+ return encoder.encode(out);
324
+ };
325
+
326
+ const stream = new ReadableStream<Uint8Array>({
327
+ async start(controller) {
328
+ try {
329
+ if (typeof source === 'function') {
330
+ let closed = false;
331
+ const send = (data: any, event?: string, id?: string) => {
332
+ if (!closed) controller.enqueue(formatChunk({ data, event, id }));
333
+ };
334
+ const close = () => {
335
+ if (!closed) {
336
+ closed = true;
337
+ controller.close();
338
+ }
339
+ };
340
+ await source(send, close);
341
+ close();
342
+ } else {
343
+ for await (const item of source) {
344
+ controller.enqueue(formatChunk(item));
345
+ }
346
+ controller.close();
347
+ }
348
+ } catch (err) {
349
+ controller.error(err);
350
+ }
351
+ }
352
+ });
353
+
354
+ const headers: Record<string, string> = {
355
+ 'content-type': 'text/event-stream; charset=utf-8',
356
+ 'cache-control': 'no-cache, no-transform',
357
+ 'connection': 'keep-alive',
358
+ ...(this._headers || {})
359
+ };
360
+ return new Response(stream, { status: this._status || 200, headers });
361
+ }
362
+
363
+ public get requestId(): string {
364
+ if (this._requestId !== undefined) return this._requestId;
365
+ const hdr = this.req?.headers?.get('x-request-id');
366
+ this._requestId = hdr && hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
367
+ return this._requestId;
368
+ }
369
+
370
+ public get ip(): string {
371
+ const xff = this.req?.headers?.get('x-forwarded-for');
372
+ if (xff) return xff.split(',')[0]!.trim();
373
+ return (
374
+ this.req?.headers?.get('x-real-ip') ||
375
+ this.req?.headers?.get('cf-connecting-ip') ||
376
+ '127.0.0.1'
377
+ );
378
+ }
379
+
380
+ public async upload(options: UploadOptions = {}): Promise<UploadResult> {
381
+ const maxFileSize = options.maxFileSize ?? 5 * 1024 * 1024;
382
+ const maxFiles = options.maxFiles ?? 10;
383
+ const allowed = options.allowedTypes ? new Set(options.allowedTypes) : null;
384
+
385
+ const ct = this.req?.headers?.get('content-type') || '';
386
+ if (!ct.includes('multipart/form-data')) {
387
+ throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
388
+ }
389
+
390
+ const contentLen = Number(this.req?.headers?.get('content-length') || 0);
391
+ if (contentLen > maxFileSize * maxFiles + 65536) {
392
+ throw Object.assign(new Error('Payload Too Large'), { status: 413 });
393
+ }
394
+
395
+ const form = await this.req.formData();
396
+ const fields: Record<string, string> = {};
397
+ const files: UploadedFile[] = [];
398
+
399
+ for (const [fieldName, value] of form.entries()) {
400
+ if (typeof value === 'string') {
401
+ if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
402
+ fields[fieldName] = value;
403
+ }
404
+ continue;
405
+ }
406
+
407
+ const fileObj = value as unknown as File;
408
+ if (files.length >= maxFiles) {
409
+ throw Object.assign(new Error(`Too many files (max ${maxFiles})`), { status: 413 });
410
+ }
411
+ if (fileObj.size > maxFileSize) {
412
+ throw Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
413
+ }
414
+ const mime = (fileObj.type || '').split(';')[0]!.trim().toLowerCase();
415
+ if (allowed && !allowed.has(mime)) {
416
+ throw Object.assign(new Error(`Unsupported file type: ${fileObj.type || 'unknown'}`), { status: 415 });
417
+ }
418
+
419
+ const rawName = fileObj.name || 'file';
420
+ const baseName = rawName.split(/[\\/]/).pop() || 'file';
421
+ const safeName = baseName.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/^\.+/, '') || 'file';
422
+
423
+ files.push({
424
+ fieldName,
425
+ filename: rawName,
426
+ safeName,
427
+ type: fileObj.type,
428
+ size: fileObj.size,
429
+ file: fileObj
430
+ });
431
+ }
432
+
433
+ return { fields, files };
434
+ }
112
435
  }
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.startsWith(':')) {
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 === 0) {
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
 
@@ -3,8 +3,9 @@ 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 HandlersChain = (Middleware | Handler)[];
8
+ type HandlersChain = (Middleware | Handler | RouteSchemas)[];
8
9
 
9
10
  export class BareRouter {
10
11
  public routes: any[] = [];
@@ -16,16 +17,24 @@ export class BareRouter {
16
17
 
17
18
  private _add(method: string, path: string, handlers: HandlersChain) {
18
19
  let fullPath = (this.prefix + "/" + path)
19
- .replace(/\/+/g, "/")
20
-
21
-
20
+ .replace(/\/+/g, "/");
22
21
 
23
22
  if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
24
23
 
24
+ const resolvedHandlers: any[] = [];
25
+ for (let i = 0; i < handlers.length; i++) {
26
+ const h = handlers[i];
27
+ if (typeof h === 'function') {
28
+ resolvedHandlers.push(h);
29
+ } else if (h && typeof h === 'object') {
30
+ resolvedHandlers.push(schemaValidator(h as RouteSchemas));
31
+ }
32
+ }
33
+
25
34
  this.routes.push({
26
35
  method: method.toUpperCase(),
27
36
  path: fullPath || "",
28
- handlers: [...this.groupMiddleware, ...handlers]
37
+ handlers: [...this.groupMiddleware, ...resolvedHandlers]
29
38
  });
30
39
  return this;
31
40
  }
@@ -35,6 +44,7 @@ export class BareRouter {
35
44
  public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
36
45
  public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
37
46
  public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
47
+ public options = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
38
48
 
39
49
  public group = (path: string, ...args: any[]) => {
40
50
  const callback = args.pop();
@@ -52,6 +62,8 @@ export class BareRouter {
52
62
  public use(mw: any) {
53
63
  if (mw instanceof BareRouter || (mw && mw.routes)) {
54
64
  this.routes.push(...mw.routes);
65
+ } else if (mw && typeof mw.install === 'function') {
66
+ mw.install(this);
55
67
  } else {
56
68
  this.groupMiddleware.push(mw);
57
69
  }
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  // --- 1. Core Engine ---
9
- export { BareJS } from './core/bare';
9
+ export { BareJS, type WebSocketRouteHandler } from './core/bare';
10
10
 
11
11
  /**
12
12
  * Plugin Interface for BareJS
@@ -16,13 +16,17 @@ export interface BarePlugin {
16
16
  }
17
17
 
18
18
  // --- 2. Context & Types ---
19
+ export { Context } from './core/context';
19
20
  export type {
20
21
  Middleware,
21
22
  Handler,
22
23
  Next,
23
- Context,
24
24
  Params,
25
- AuthUser
25
+ AuthUser,
26
+ CookieOptions,
27
+ UploadOptions,
28
+ UploadedFile,
29
+ UploadResult
26
30
  } from './core/context';
27
31
 
28
32
  // --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
@@ -30,7 +34,7 @@ import { Type } from "@sinclair/typebox";
30
34
  export { Type, Type as T, Type as TypeBox };
31
35
 
32
36
  // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
33
- import { typebox, zod, native, validate, Z } from './security/validators';
37
+ import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
34
38
  export {
35
39
  // TypeBox Engine
36
40
  typebox,
@@ -45,17 +49,37 @@ export {
45
49
  native as n,
46
50
  // Auto-Detect Engine
47
51
  validate,
48
- validate as v
52
+ validate as v,
53
+ // Unified Route Schema Engine (body, query, params, headers, response, detail, maxBodySize)
54
+ schemaValidator,
55
+ createResponseFilter,
56
+ type RouteSchemas,
57
+ type RouteDetail
49
58
  };
50
59
 
51
60
  // --- 5. Middlewares & Utilities ---
52
61
  // export { logger } from './utils/logger';
53
62
  export { cors } from './security/cors';
54
- export { staticFile } from './utils/static';
63
+ export { csrf, type CsrfOptions } from './security/csrf';
64
+ export { timeout, type TimeoutOptions } from './security/timeout';
65
+ export { rateLimit, type RateLimitOptions } from './security/rateLimit';
66
+ export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
67
+ export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
68
+ export { staticFile, type StaticOptions } from './utils/static';
69
+ export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
55
70
  export { BareRouter } from './core/router';
56
71
 
57
72
  // --- 6. Authentication (Bun Native) ---
58
73
  // Always deploy using process.env [2026-01-06]
59
- export { bareAuth, createToken } from './security/auth';
74
+ export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
60
75
  // --- 7. Hashing ---
61
- export{Hash as Password, Hash} from './security/hash';
76
+ export { Hash as Password, Hash } from './security/hash';
77
+
78
+ // --- 8. Type-Safe RPC Client ---
79
+ export {
80
+ bareClient,
81
+ type BareClient,
82
+ type BareClientOptions,
83
+ type ClientRequestOptions,
84
+ type RouteSchema
85
+ } from './client/index';
@@ -58,7 +58,8 @@ export const createToken = async (payload: object, secret: string): Promise<stri
58
58
  * 1. BARE TOKEN AUTH (Standard JWT Middleware)
59
59
  * High-performance, constant-time JWT middleware for BareJS
60
60
  */
61
- export const bareAuth = (secret: string) => {
61
+ export const bareAuth = (secretOrOpts: string | { secret: string }) => {
62
+ const secret = typeof secretOrOpts === 'string' ? secretOrOpts : secretOrOpts.secret;
62
63
  return (ctx: any, next: any) => {
63
64
  const authHeader = ctx.req.headers.get('Authorization');
64
65