barejs 0.1.62 → 0.2.1
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 +7 -7
- package/dist/index.js +149 -149
- package/dist/node.js +149 -149
- package/dist/types/core/bare.d.ts +3 -0
- package/dist/types/runtime/types.d.ts +3 -0
- package/dist/types/runtime/uws.d.ts +13 -0
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/src/core/bare.ts +224 -1
- package/src/runtime/bun.ts +3 -0
- package/src/runtime/node.ts +10 -0
- package/src/runtime/types.ts +3 -0
- package/src/runtime/uws.ts +554 -0
|
@@ -133,9 +133,12 @@ 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;
|
|
137
|
+
private buildUwsRoutes;
|
|
136
138
|
listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
|
|
137
139
|
maxRequestBodySize?: number;
|
|
138
140
|
trustProxy?: boolean;
|
|
141
|
+
engine?: 'auto' | 'http' | 'uws';
|
|
139
142
|
}): any;
|
|
140
143
|
}
|
|
141
144
|
export { Context, typebox, t };
|
|
@@ -5,6 +5,9 @@ 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>;
|
|
9
|
+
engine?: 'auto' | 'http' | 'uws';
|
|
10
|
+
uwsRoutes?: any[];
|
|
8
11
|
ws?: {
|
|
9
12
|
routes: Map<string, WebSocketRouteHandler>;
|
|
10
13
|
adapter: {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ServeOptions, ServerHandle } from './types';
|
|
2
|
+
export interface UwsRouteEntry {
|
|
3
|
+
method: string;
|
|
4
|
+
path: string;
|
|
5
|
+
paramNames: string[];
|
|
6
|
+
rawHandler: Function;
|
|
7
|
+
isPureStaticString: boolean;
|
|
8
|
+
isTrulyZeroArg: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function tryLoadUws(): any | null;
|
|
11
|
+
export declare function serveUws(opts: ServeOptions & {
|
|
12
|
+
uwsRoutes?: UwsRouteEntry[];
|
|
13
|
+
}, uwsMod: any): ServerHandle;
|
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 (
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection), 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
|
|
3
|
+
"version": "0.2.1",
|
|
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,11 +1221,196 @@ 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
|
+
|
|
1345
|
+
private buildUwsRoutes(): Array<{
|
|
1346
|
+
method: string;
|
|
1347
|
+
path: string;
|
|
1348
|
+
paramNames: string[];
|
|
1349
|
+
rawHandler: Function;
|
|
1350
|
+
isPureStaticString: boolean;
|
|
1351
|
+
isTrulyZeroArg: boolean;
|
|
1352
|
+
}> | undefined {
|
|
1353
|
+
if (
|
|
1354
|
+
this._useLog ||
|
|
1355
|
+
this.groupMiddleware.length > 0 ||
|
|
1356
|
+
this.errorHandler !== undefined ||
|
|
1357
|
+
this._trustProxyBox.val ||
|
|
1358
|
+
this._hasDerive ||
|
|
1359
|
+
this.wsRoutes.size > 0 ||
|
|
1360
|
+
this.routes.length === 0
|
|
1361
|
+
) {
|
|
1362
|
+
return undefined;
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
const uwsRoutes: Array<{
|
|
1366
|
+
method: string;
|
|
1367
|
+
path: string;
|
|
1368
|
+
paramNames: string[];
|
|
1369
|
+
rawHandler: Function;
|
|
1370
|
+
isPureStaticString: boolean;
|
|
1371
|
+
isTrulyZeroArg: boolean;
|
|
1372
|
+
}> = [];
|
|
1373
|
+
const normStatic = (p: string) => {
|
|
1374
|
+
const c = p.replace(/\/+/g, '/');
|
|
1375
|
+
return c.length > 1 && c.endsWith('/') ? c.slice(0, -1) : (c || '/');
|
|
1376
|
+
};
|
|
1377
|
+
|
|
1378
|
+
for (const route of this.routes) {
|
|
1379
|
+
if (route.method !== 'GET' && route.method !== 'HEAD' && route.method !== 'DELETE' && route.method !== 'OPTIONS') continue;
|
|
1380
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1381
|
+
if (route.handlers.length !== 1) continue;
|
|
1382
|
+
|
|
1383
|
+
const rawHandler = route.handlers[0] as any;
|
|
1384
|
+
if (rawHandler?.__idempotencyCommit || rawHandler?.__isDerive || rawHandler?.__isCors) continue;
|
|
1385
|
+
|
|
1386
|
+
const normPath = normStatic(route.path);
|
|
1387
|
+
const paramNames: string[] = [];
|
|
1388
|
+
if (normPath.includes(':')) {
|
|
1389
|
+
const segs = normPath.split('/');
|
|
1390
|
+
for (let i = 0; i < segs.length; i++) {
|
|
1391
|
+
const seg = segs[i]!;
|
|
1392
|
+
if (seg.startsWith(':')) paramNames.push(seg.slice(1));
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
uwsRoutes.push({
|
|
1397
|
+
method: route.method,
|
|
1398
|
+
path: normPath,
|
|
1399
|
+
paramNames,
|
|
1400
|
+
rawHandler,
|
|
1401
|
+
isPureStaticString: isPureStaticStringFn(rawHandler),
|
|
1402
|
+
isTrulyZeroArg: isTrulyZeroArg(rawHandler)
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
return uwsRoutes.length > 0 ? uwsRoutes : undefined;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1191
1409
|
public listen(
|
|
1192
1410
|
port?: number,
|
|
1193
1411
|
hostname: string = '0.0.0.0',
|
|
1194
1412
|
reusePort: boolean = true,
|
|
1195
|
-
options: { maxRequestBodySize?: number; trustProxy?: boolean } = {}
|
|
1413
|
+
options: { maxRequestBodySize?: number; trustProxy?: boolean; engine?: 'auto' | 'http' | 'uws' } = {}
|
|
1196
1414
|
) {
|
|
1197
1415
|
if (options.trustProxy !== undefined) {
|
|
1198
1416
|
this.trustProxy(options.trustProxy);
|
|
@@ -1220,12 +1438,17 @@ export class BareJS<
|
|
|
1220
1438
|
const wsRoutes = this.wsRoutes;
|
|
1221
1439
|
const self = this;
|
|
1222
1440
|
const hasWs = wsRoutes.size > 0;
|
|
1441
|
+
const bunRoutes = runtime.name === 'bun' ? this.buildBunRoutes() : undefined;
|
|
1442
|
+
const uwsRoutes = runtime.name === 'node' && options.engine !== 'http' ? this.buildUwsRoutes() : undefined;
|
|
1223
1443
|
|
|
1224
1444
|
const server = runtime.serve({
|
|
1225
1445
|
port: finalPort,
|
|
1226
1446
|
hostname,
|
|
1227
1447
|
reusePort,
|
|
1228
1448
|
maxRequestBodySize,
|
|
1449
|
+
routes: bunRoutes,
|
|
1450
|
+
engine: options.engine,
|
|
1451
|
+
uwsRoutes,
|
|
1229
1452
|
fetch(req: Request, peerIp?: string) {
|
|
1230
1453
|
return self.fetch(req, peerIp);
|
|
1231
1454
|
},
|
package/src/runtime/bun.ts
CHANGED
|
@@ -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
|
}
|
package/src/runtime/node.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { Readable } from 'node:stream';
|
|
|
6
6
|
import * as zlib from 'node:zlib';
|
|
7
7
|
import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
|
|
8
8
|
import { matchWsRoute } from '../core/ws-match';
|
|
9
|
+
import { serveUws, tryLoadUws } from './uws';
|
|
9
10
|
|
|
10
11
|
const SCRYPT_N = 16384;
|
|
11
12
|
const SCRYPT_R = 8;
|
|
@@ -196,6 +197,15 @@ export const nodeDriver: RuntimeDriver = {
|
|
|
196
197
|
name: 'node',
|
|
197
198
|
|
|
198
199
|
serve(opts: ServeOptions): ServerHandle {
|
|
200
|
+
if (opts.engine !== 'http' && !opts.ws) {
|
|
201
|
+
const uwsMod = tryLoadUws();
|
|
202
|
+
if (uwsMod) {
|
|
203
|
+
return serveUws(opts, uwsMod);
|
|
204
|
+
}
|
|
205
|
+
if (opts.engine === 'uws') {
|
|
206
|
+
throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.");
|
|
207
|
+
}
|
|
208
|
+
}
|
|
199
209
|
const server = createServer(async (req, res) => {
|
|
200
210
|
const parsed = toWebRequest(req, opts.maxRequestBodySize);
|
|
201
211
|
if (parsed.errorStatus === 413 || !parsed.request) {
|
package/src/runtime/types.ts
CHANGED
|
@@ -6,6 +6,9 @@ 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>;
|
|
10
|
+
engine?: 'auto' | 'http' | 'uws';
|
|
11
|
+
uwsRoutes?: any[];
|
|
9
12
|
ws?: {
|
|
10
13
|
routes: Map<string, WebSocketRouteHandler>;
|
|
11
14
|
adapter: {
|