barejs 0.1.48 → 0.1.49

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.
@@ -0,0 +1,48 @@
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>(baseUrl: string, clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
46
+ __routes?: infer R extends RouteSchema;
47
+ } ? R : RouteSchema>;
48
+ 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,20 @@ export declare class BareJS extends BareRouter {
13
20
  private compiled;
14
21
  private poolMask;
15
22
  private _useLog;
23
+ private errorHandler?;
24
+ private wsRoutes;
16
25
  useLog(enabled?: boolean): this;
17
26
  constructor(poolSize?: number);
18
27
  private notFoundHandler;
19
28
  setNotFound(handler: () => NotFoundResponse): void;
29
+ onError(handler: (err: any, ctx: Context) => any): this;
30
+ ws(path: string, handler: WebSocketRouteHandler): this;
31
+ docs(path?: string, options?: OpenAPIOptions): this;
32
+ rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this;
20
33
  private compileHandler;
21
34
  compile(): void;
22
35
  fetch: (req: Request) => any;
23
36
  name: string;
24
- listen(port?: number, hostname?: string, reusePort?: boolean): void;
37
+ listen(port?: number, hostname?: string, reusePort?: boolean): Bun.Server<WebSocketRouteHandler> | Bun.Server<undefined>;
25
38
  }
26
39
  export { Context, typebox, t };
@@ -11,8 +11,10 @@ export declare class Context {
11
11
  _headers?: Record<string, string> | undefined;
12
12
  store: Map<string, any>;
13
13
  body: any;
14
- query: Record<string, string>;
14
+ _query: Record<string, string> | undefined;
15
15
  constructor();
16
+ get query(): Record<string, string>;
17
+ getQuery(key: string): string | undefined;
16
18
  jsonBody(): Promise<any>;
17
19
  reset(req: Request): this;
18
20
  status(code: number): this;
@@ -21,4 +23,10 @@ export declare class Context {
21
23
  get(key: string): any;
22
24
  setHeader(name: string, value: string): this;
23
25
  send(message: string, extra?: Record<string, any>): Response;
26
+ sse(source: AsyncIterable<string | {
27
+ event?: string;
28
+ data: any;
29
+ id?: string;
30
+ retry?: number;
31
+ }> | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)): Response;
24
32
  }
@@ -11,6 +11,7 @@ export declare class BareRouter {
11
11
  put: (path: string, ...h: HandlersChain) => this;
12
12
  patch: (path: string, ...h: HandlersChain) => this;
13
13
  delete: (path: string, ...h: HandlersChain) => this;
14
+ options: (path: string, ...h: HandlersChain) => this;
14
15
  group: (path: string, ...args: any[]) => this;
15
16
  use(mw: any): this;
16
17
  }
@@ -4,7 +4,7 @@
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
  */
@@ -17,7 +17,11 @@ export { Type, Type as T, Type as TypeBox };
17
17
  import { typebox, zod, native, validate, Z } from './security/validators';
18
18
  export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v };
19
19
  export { cors } from './security/cors';
20
+ export { rateLimit, type RateLimitOptions } from './security/rateLimit';
21
+ export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
20
22
  export { staticFile } from './utils/static';
23
+ export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
21
24
  export { BareRouter } from './core/router';
22
- export { bareAuth, createToken } from './security/auth';
25
+ export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
23
26
  export { Hash as Password, Hash } from './security/hash';
27
+ export { bareClient, type BareClient, type BareClientOptions, type ClientRequestOptions, type RouteSchema } from './client/index';
@@ -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,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;
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.48",
3
+ "version": "0.1.49",
4
4
  "author": "xarhang",
5
5
  "description": "High-performance JIT-specialized web framework for Bun",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,121 @@
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
+ baseUrl: string,
82
+ clientOptions: BareClientOptions = {}
83
+ ): BareClient<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> => {
84
+ const fetchImpl = clientOptions.fetch ?? fetch;
85
+ const defaultHeaders = clientOptions.headers ?? {};
86
+
87
+ const request = async (method: string, path: string, options?: ClientRequestOptions) => {
88
+ const url = buildUrl(baseUrl, path, options);
89
+ const headers: Record<string, string> = {
90
+ ...defaultHeaders,
91
+ ...(options?.headers ?? {})
92
+ };
93
+
94
+ const init: RequestInit = { method, headers };
95
+ if (options?.body !== undefined && method !== 'GET' && method !== 'HEAD') {
96
+ if (!headers['Content-Type'] && !headers['content-type']) {
97
+ headers['Content-Type'] = 'application/json';
98
+ }
99
+ init.body = typeof options.body === 'string' ? options.body : JSON.stringify(options.body);
100
+ }
101
+
102
+ const res = await fetchImpl(url, init);
103
+ const ct = res.headers.get('content-type') || '';
104
+ const data = ct.includes('application/json') ? await res.json() : await res.text();
105
+ if (!res.ok) {
106
+ const err: any = new Error(`HTTP ${res.status}`);
107
+ err.status = res.status;
108
+ err.data = data;
109
+ throw err;
110
+ }
111
+ return data;
112
+ };
113
+
114
+ return {
115
+ get: (path: string, options?: ClientRequestOptions) => request('GET', path, options),
116
+ post: (path: string, options?: ClientRequestOptions) => request('POST', path, options),
117
+ put: (path: string, options?: ClientRequestOptions) => request('PUT', path, options),
118
+ patch: (path: string, options?: ClientRequestOptions) => request('PATCH', path, options),
119
+ delete: (path: string, options?: ClientRequestOptions) => request('DELETE', path, options)
120
+ } as any;
121
+ };
package/src/core/bare.ts CHANGED
@@ -5,6 +5,14 @@ import { Type as typebox, Type as t } from '@sinclair/typebox';
5
5
  import { join } from "node:path";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { bootstrapConfig } from "./loader";
8
+ import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
9
+
10
+ export interface WebSocketRouteHandler {
11
+ open?: (ws: any) => void;
12
+ message?: (ws: any, message: string | Buffer) => void;
13
+ close?: (ws: any, code: number, reason: string) => void;
14
+ drain?: (ws: any) => void;
15
+ }
8
16
 
9
17
  export interface NotFoundResponse {
10
18
  status: number;
@@ -19,6 +27,9 @@ export class BareJS extends BareRouter {
19
27
  private compiled = false;
20
28
  private poolMask: number;
21
29
  private _useLog: boolean = false;
30
+ private errorHandler?: (err: any, ctx: Context) => any;
31
+ private wsRoutes = new Map<string, WebSocketRouteHandler>();
32
+
22
33
  public useLog(enabled: boolean = true): this {
23
34
  this._useLog = enabled;
24
35
  return this;
@@ -53,6 +64,81 @@ export class BareJS extends BareRouter {
53
64
  this.notFoundHandler = handler;
54
65
  }
55
66
 
67
+ public onError(handler: (err: any, ctx: Context) => any): this {
68
+ this.errorHandler = handler;
69
+ return this;
70
+ }
71
+
72
+ public ws(path: string, handler: WebSocketRouteHandler): this {
73
+ const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
74
+ this.wsRoutes.set(normalized, handler);
75
+ return this;
76
+ }
77
+
78
+ public docs(path: string = '/docs', options: OpenAPIOptions = {}): this {
79
+ const basePath = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/docs';
80
+ const jsonPath = `${basePath}/json`;
81
+ let cachedSpec: string | null = null;
82
+ const html = renderDocsHTML(jsonPath, options.title || `${this.name} API Docs`);
83
+
84
+ this.get(jsonPath, () => {
85
+ if (!cachedSpec) {
86
+ cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, ...options }));
87
+ }
88
+ return new Response(cachedSpec, {
89
+ status: 200,
90
+ headers: { 'content-type': 'application/json' }
91
+ });
92
+ });
93
+
94
+ this.get(basePath, () => {
95
+ return new Response(html, {
96
+ status: 200,
97
+ headers: { 'content-type': 'text/html; charset=utf-8' }
98
+ });
99
+ });
100
+
101
+ return this;
102
+ }
103
+
104
+ public rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this {
105
+ const execCall = async (reqObj: any, ctx: Context) => {
106
+ if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
107
+ return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: reqObj?.id ?? null };
108
+ }
109
+ const fn = Object.hasOwn(procedures, reqObj.method) ? procedures[reqObj.method] : undefined;
110
+ if (!fn) {
111
+ return { jsonrpc: '2.0', error: { code: -32601, message: 'Method not found' }, id: reqObj.id ?? null };
112
+ }
113
+ try {
114
+ const result = await fn(reqObj.params, ctx);
115
+ if (reqObj.id === undefined) return null; // Notification
116
+ return { jsonrpc: '2.0', result, id: reqObj.id };
117
+ } catch (err: any) {
118
+ return {
119
+ jsonrpc: '2.0',
120
+ error: { code: -32603, message: err?.message || 'Internal error' },
121
+ id: reqObj.id ?? null
122
+ };
123
+ }
124
+ };
125
+
126
+ this.post(path, async (ctx: Context) => {
127
+ const payload = await ctx.jsonBody();
128
+ if (!payload) {
129
+ return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
130
+ }
131
+ if (Array.isArray(payload)) {
132
+ const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
133
+ return results.length > 0 ? results : new Response(null, { status: 204 });
134
+ }
135
+ const res = await execCall(payload, ctx);
136
+ return res === null ? new Response(null, { status: 204 }) : res;
137
+ });
138
+
139
+ return this;
140
+ }
141
+
56
142
 
57
143
  // inherited use() from BareRouter handles router merging now
58
144
 
@@ -78,16 +164,20 @@ export class BareJS extends BareRouter {
78
164
 
79
165
  if (typeof res === 'string') {
80
166
  if (finalStatus === 200 && !ctx._headers) return new Response(res, text200);
167
+ const h = ctx._headers;
168
+ if (h && !h["content-type"]) h["content-type"] = "text/plain";
81
169
  return new Response(res, {
82
170
  status: finalStatus,
83
- headers: ctx._headers || text200.headers
171
+ headers: h || text200.headers
84
172
  });
85
173
  }
86
174
 
87
175
  if (finalStatus === 200 && !ctx._headers) return Response.json(res ?? null, json200);
176
+ const h = ctx._headers;
177
+ if (h && !h["content-type"]) h["content-type"] = "application/json";
88
178
  return Response.json(res ?? null, {
89
179
  status: finalStatus,
90
- headers: ctx._headers && ctx._headers["content-type"] ? ctx._headers : json200.headers
180
+ headers: h || json200.headers
91
181
  });
92
182
  `;
93
183
 
@@ -153,11 +243,21 @@ export class BareJS extends BareRouter {
153
243
  const pool = this.pool;
154
244
  const maxPool = pool.length;
155
245
  const hNotFound = this.notFoundHandler;
156
- const hError = (err: any) => ({
157
- status: 500,
158
- message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
159
- stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
160
- });
246
+ const customError = this.errorHandler;
247
+ const hError = (err: any, ctx: Context) => {
248
+ if (customError) {
249
+ const res = customError(err, ctx);
250
+ if (res instanceof Response) return res;
251
+ const status = ctx._status >= 400 ? ctx._status : 500;
252
+ if (typeof res === 'string') return new Response(res, { status });
253
+ return Response.json(res ?? null, { status });
254
+ }
255
+ return Response.json({
256
+ status: 500,
257
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
258
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
259
+ }, { status: 500 });
260
+ };
161
261
 
162
262
  const hoistedHandlers: Function[] = [];
163
263
  const register = (h: Function) => {
@@ -174,6 +274,7 @@ export class BareJS extends BareRouter {
174
274
  if (ctx.store.size > 0) ctx.store.clear();
175
275
  ctx.req = undefined;
176
276
  ctx.body = undefined;
277
+ ctx._query = undefined;
177
278
  ctx._headers = undefined;
178
279
  ctx.params = EMPTY_PARAMS;
179
280
  if (poolTop < maxPool) pool[poolTop++] = ctx;
@@ -182,14 +283,25 @@ export class BareJS extends BareRouter {
182
283
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
183
284
  const routerCode = rawRouterCode.replace(
184
285
  /return (h\d+)\(ctx\);/g,
185
- `const out = $1${callSuffix};
186
- if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${releaseCode} ${isLog ? 'doLog(500);' : ''} return Response.json(hError(e), { status: 500 }); });
286
+ `out = $1${callSuffix};
287
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { const errRes = hError(e, ctx); ${releaseCode} ${isLog ? 'doLog(errRes.status || 500);' : ''} return errRes; });
187
288
  ${releaseCode}
188
289
  return out;`
189
290
  );
190
291
 
191
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...hNames];
192
- const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...hoistedHandlers];
292
+ const hasGlobalMw = this.groupMiddleware.length > 0;
293
+ const hOptions = hasGlobalMw ? this.compileHandler(this.groupMiddleware, isLog) : undefined;
294
+ const optionsFallback = hasGlobalMw
295
+ ? `if (method === 'OPTIONS') {
296
+ out = hOptions${callSuffix};
297
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { const errRes = hError(e, ctx); ${releaseCode} ${isLog ? 'doLog(errRes.status || 500);' : ''} return errRes; });
298
+ ${releaseCode}
299
+ return out;
300
+ }`
301
+ : '';
302
+
303
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...hNames];
304
+ const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...hoistedHandlers];
193
305
 
194
306
  const logInit = isLog ? `
195
307
  const start = performance.now();
@@ -216,6 +328,7 @@ export class BareJS extends BareRouter {
216
328
 
217
329
  const method = req.method;
218
330
  const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
331
+ let out;
219
332
  ${logInit}
220
333
 
221
334
  try {
@@ -225,9 +338,12 @@ export class BareJS extends BareRouter {
225
338
  if (ctx.store.size > 0) ctx.store.clear();
226
339
  ctx.params = EMPTY_PARAMS;
227
340
  ctx.body = undefined;
341
+ ctx._query = undefined;
228
342
 
229
343
  ${routerCode}
230
344
 
345
+ ${optionsFallback}
346
+
231
347
  const errorBody = hNotFound();
232
348
  const status = errorBody.status || 404;
233
349
  ${isLog ? 'doLog(status);' : ''}
@@ -235,9 +351,10 @@ export class BareJS extends BareRouter {
235
351
  return Response.json(errorBody, { status });
236
352
 
237
353
  } catch (e) {
238
- ${isLog ? 'doLog(500);' : ''}
354
+ const errRes = hError(e, ctx);
355
+ ${isLog ? 'doLog(errRes.status || 500);' : ''}
239
356
  ${releaseCode}
240
- return Response.json(hError(e), { status: 500 });
357
+ return errRes;
241
358
  }
242
359
  }
243
360
  `;
@@ -280,12 +397,42 @@ export class BareJS extends BareRouter {
280
397
  `);
281
398
  }
282
399
 
283
- const server = Bun.serve({
284
- port: finalPort,
285
- hostname,
286
- fetch: this.fetch,
287
- reusePort: reusePort,
288
- });
400
+ const wsRoutes = this.wsRoutes;
401
+ const baseFetch = this.fetch;
402
+ const hasWs = wsRoutes.size > 0;
403
+
404
+ const server = hasWs
405
+ ? Bun.serve<WebSocketRouteHandler>({
406
+ port: finalPort,
407
+ hostname,
408
+ reusePort,
409
+ fetch(req: Request, srv: any) {
410
+ if (req.headers.get('upgrade') === 'websocket') {
411
+ const url = req.url;
412
+ const s = url.indexOf('/', 8);
413
+ const q = s === -1 ? -1 : url.indexOf('?', s);
414
+ const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
415
+ const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
416
+ const handler = wsRoutes.get(normalized);
417
+ if (handler && srv.upgrade(req, { data: handler })) {
418
+ return undefined as any;
419
+ }
420
+ }
421
+ return baseFetch(req);
422
+ },
423
+ websocket: {
424
+ open(ws) { ws.data?.open?.(ws); },
425
+ message(ws, msg) { ws.data?.message?.(ws, msg); },
426
+ close(ws, code, reason) { ws.data?.close?.(ws, code, reason); },
427
+ drain(ws) { ws.data?.drain?.(ws); }
428
+ }
429
+ })
430
+ : Bun.serve({
431
+ port: finalPort,
432
+ hostname,
433
+ reusePort,
434
+ fetch: baseFetch
435
+ });
289
436
 
290
437
  const shutdown = () => {
291
438
  const isProd = process.env.NODE_ENV === 'production';
@@ -309,6 +456,7 @@ export class BareJS extends BareRouter {
309
456
 
310
457
  process.on("SIGINT", shutdown);
311
458
  process.on("SIGTERM", shutdown);
459
+ return server;
312
460
  }
313
461
  }
314
462