barejs 0.1.62 → 0.1.63

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.
@@ -133,6 +133,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
133
133
  request(path: string, init?: RequestInit): Promise<Response>;
134
134
  name: string;
135
135
  trustProxy(enabled?: boolean): this;
136
+ private buildBunRoutes;
136
137
  listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
137
138
  maxRequestBodySize?: number;
138
139
  trustProxy?: boolean;
@@ -5,6 +5,7 @@ export interface ServeOptions {
5
5
  reusePort: boolean;
6
6
  maxRequestBodySize: number;
7
7
  fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
8
+ routes?: Record<string, any>;
8
9
  ws?: {
9
10
  routes: Map<string, WebSocketRouteHandler>;
10
11
  adapter: {
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`), **Node.js** (`>= 20` via `barejs/node`), and **Deno** with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **Full Multi-Runtime Test Suite (425 tests / 6,255 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
3
+ > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`), **Node.js** (`>= 20` via `barejs/node`), and **Deno** with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **Full Multi-Runtime Test Suite (427 tests / 6,279 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
4
4
 
5
5
  ## 1. Installation & Minimal App (Bun, Node.js, Deno)
6
6
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.62",
3
+ "version": "0.1.63",
4
4
  "author": "xarhang",
5
5
  "description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
6
6
  "main": "./dist/index.js",
package/src/core/bare.ts CHANGED
@@ -23,6 +23,39 @@ export function normalizePoolSize(
23
23
  return Math.min(maximumSize, Math.max(0, requested));
24
24
  }
25
25
 
26
+ const ZERO_ARG_RE = /^\s*(?:async\s+)?(?:\(\s*\)|function\s*(?:\w+\s*)?\(\s*\))/;
27
+ const PURE_STATIC_STR_RE = /^\s*\(\s*\)\s*=>\s*(?:'[^'\\]*'|"[^"\\]*")\s*$/;
28
+
29
+ function isTrulyZeroArg(fn: unknown): fn is (...args: any[]) => any {
30
+ if (typeof fn !== 'function' || fn.length !== 0) return false;
31
+ const src = fn.toString();
32
+ return ZERO_ARG_RE.test(src) && !/\barguments\b/.test(src);
33
+ }
34
+
35
+ function isPureStaticStringFn(fn: unknown): fn is () => string {
36
+ return typeof fn === 'function' && fn.length === 0 && PURE_STATIC_STR_RE.test(fn.toString());
37
+ }
38
+
39
+ function toZeroArgResponse(out: any): Response {
40
+ if (out instanceof Response) return out;
41
+ if (typeof out === 'string') return new Response(out);
42
+ return Response.json(out ?? null);
43
+ }
44
+
45
+ function zeroArgErrorRes(err: any): Response {
46
+ if (err?.status >= 400 && err?.status < 500) {
47
+ return Response.json({
48
+ status: err.status,
49
+ message: err.message || 'Bad Request'
50
+ }, { status: err.status });
51
+ }
52
+ return Response.json({
53
+ status: 500,
54
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
55
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
56
+ }, { status: 500 });
57
+ }
58
+
26
59
  export interface CronOptions {
27
60
  /** Execute the cron job immediately upon registration (default: false) */
28
61
  runOnStart?: boolean;
@@ -1188,6 +1221,127 @@ export class BareJS<
1188
1221
  return this;
1189
1222
  }
1190
1223
 
1224
+ private buildBunRoutes(): Record<string, any> | undefined {
1225
+ if (
1226
+ this._useLog ||
1227
+ this.groupMiddleware.length > 0 ||
1228
+ this.errorHandler !== undefined ||
1229
+ this._trustProxyBox.val ||
1230
+ this._hasDerive ||
1231
+ this.routes.length === 0
1232
+ ) {
1233
+ return undefined;
1234
+ }
1235
+
1236
+ const routes: Record<string, Record<string, any>> = {};
1237
+ const pool = this.pool;
1238
+ const poolState = this._poolState;
1239
+ const maxPool = this.maxPool;
1240
+ const isProd = process.env.NODE_ENV === 'production';
1241
+ const normStatic = (p: string) => {
1242
+ const c = p.replace(/\/+/g, '/');
1243
+ return c.length > 1 && c.endsWith('/') ? c.slice(0, -1) : (c || '/');
1244
+ };
1245
+
1246
+ let count = 0;
1247
+ for (const route of this.routes) {
1248
+ if (route.method === 'ALL') continue;
1249
+ if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
1250
+ if (route.handlers.length !== 1) continue;
1251
+
1252
+ const rawHandler = route.handlers[0] as any;
1253
+ if (rawHandler?.__idempotencyCommit || rawHandler?.__isDerive || rawHandler?.__isCors) continue;
1254
+
1255
+ const normPath = normStatic(route.path);
1256
+ if (this.wsRoutes.has(normPath)) continue;
1257
+
1258
+ let methodMap = routes[normPath];
1259
+ if (!methodMap) {
1260
+ methodMap = {};
1261
+ routes[normPath] = methodMap;
1262
+ }
1263
+
1264
+ if (isProd && isPureStaticStringFn(rawHandler)) {
1265
+ methodMap[route.method] = new Response(rawHandler());
1266
+ count++;
1267
+ continue;
1268
+ }
1269
+
1270
+ if (isProd && isTrulyZeroArg(rawHandler)) {
1271
+ const isAsync = rawHandler.constructor?.name === 'AsyncFunction';
1272
+ methodMap[route.method] = isAsync
1273
+ ? () => {
1274
+ try {
1275
+ const out = rawHandler();
1276
+ if (out && typeof out.then === 'function') {
1277
+ return out.then(toZeroArgResponse, zeroArgErrorRes);
1278
+ }
1279
+ return toZeroArgResponse(out);
1280
+ } catch (e) {
1281
+ return zeroArgErrorRes(e);
1282
+ }
1283
+ }
1284
+ : () => {
1285
+ try {
1286
+ const out = rawHandler();
1287
+ if (typeof out === 'string') return new Response(out);
1288
+ if (out instanceof Response) return out;
1289
+ if (out && typeof out.then === 'function') {
1290
+ return out.then(toZeroArgResponse, zeroArgErrorRes);
1291
+ }
1292
+ return Response.json(out ?? null);
1293
+ } catch (e) {
1294
+ return zeroArgErrorRes(e);
1295
+ }
1296
+ };
1297
+ count++;
1298
+ continue;
1299
+ }
1300
+
1301
+ const compiledFn = this.compileHandler([rawHandler], false);
1302
+ const hasParams = normPath.includes(':');
1303
+ methodMap[route.method] = (req: any) => {
1304
+ let ctx: Context;
1305
+ if (poolState.top > 0) {
1306
+ const slot = --poolState.top;
1307
+ ctx = pool[slot]!;
1308
+ pool[slot] = undefined;
1309
+ } else {
1310
+ ctx = new Context(false);
1311
+ }
1312
+ ctx.req = req;
1313
+ if (hasParams) ctx.params = req.params;
1314
+ try {
1315
+ const out = compiledFn(ctx);
1316
+ if (out && typeof out.then === 'function') {
1317
+ return out.then(
1318
+ (v: Response) => {
1319
+ ctx.reset(undefined as any);
1320
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1321
+ return v;
1322
+ },
1323
+ (e: any) => {
1324
+ ctx.reset(undefined as any);
1325
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1326
+ return zeroArgErrorRes(e);
1327
+ }
1328
+ );
1329
+ }
1330
+ ctx.reset(undefined as any);
1331
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1332
+ return out;
1333
+ } catch (e) {
1334
+ ctx.reset(undefined as any);
1335
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1336
+ return zeroArgErrorRes(e);
1337
+ }
1338
+ };
1339
+ count++;
1340
+ }
1341
+
1342
+ return count > 0 ? routes : undefined;
1343
+ }
1344
+
1191
1345
  public listen(
1192
1346
  port?: number,
1193
1347
  hostname: string = '0.0.0.0',
@@ -1220,12 +1374,14 @@ export class BareJS<
1220
1374
  const wsRoutes = this.wsRoutes;
1221
1375
  const self = this;
1222
1376
  const hasWs = wsRoutes.size > 0;
1377
+ const bunRoutes = runtime.name === 'bun' ? this.buildBunRoutes() : undefined;
1223
1378
 
1224
1379
  const server = runtime.serve({
1225
1380
  port: finalPort,
1226
1381
  hostname,
1227
1382
  reusePort,
1228
1383
  maxRequestBodySize,
1384
+ routes: bunRoutes,
1229
1385
  fetch(req: Request, peerIp?: string) {
1230
1386
  return self.fetch(req, peerIp);
1231
1387
  },
@@ -10,12 +10,14 @@ export const bunDriver: RuntimeDriver = {
10
10
 
11
11
  serve(opts: ServeOptions): ServerHandle {
12
12
  const wsCfg = opts.ws;
13
+ const routes = opts.routes;
13
14
  const server = wsCfg
14
15
  ? Bun.serve<WebSocketRouteHandler>({
15
16
  port: opts.port,
16
17
  hostname: opts.hostname,
17
18
  reusePort: opts.reusePort,
18
19
  maxRequestBodySize: opts.maxRequestBodySize,
20
+ ...(routes ? { routes } : {}),
19
21
  fetch(req: Request, srv: any) {
20
22
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
21
23
  const matched = matchWsRoute(wsCfg.routes, req.url);
@@ -37,6 +39,7 @@ export const bunDriver: RuntimeDriver = {
37
39
  hostname: opts.hostname,
38
40
  reusePort: opts.reusePort,
39
41
  maxRequestBodySize: opts.maxRequestBodySize,
42
+ ...(routes ? { routes } : {}),
40
43
  fetch(req: Request, srv: any) {
41
44
  return opts.fetch(req, srv?.requestIP?.(req)?.address);
42
45
  }
@@ -6,6 +6,7 @@ export interface ServeOptions {
6
6
  reusePort: boolean;
7
7
  maxRequestBodySize: number;
8
8
  fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
9
+ routes?: Record<string, any>;
9
10
  ws?: {
10
11
  routes: Map<string, WebSocketRouteHandler>;
11
12
  adapter: {