barejs 0.1.57 → 0.1.58
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 +32 -18
- package/dist/index.js +198 -186
- package/dist/types/core/bare.d.ts +16 -0
- package/dist/types/core/context.d.ts +24 -0
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/index.d.ts +2 -2
- package/llms.txt +4 -1
- package/package.json +1 -1
- package/src/core/bare.ts +153 -42
- package/src/core/context.ts +290 -0
- package/src/core/router.ts +6 -0
- package/src/index.ts +4 -2
- package/src/security/idempotency.ts +3 -1
|
@@ -4,6 +4,7 @@ import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
|
4
4
|
import { type OpenAPIOptions } from "../utils/openapi";
|
|
5
5
|
import type { RouteSchemas } from "../security/validators";
|
|
6
6
|
import type { RouteSchema } from "../client/index";
|
|
7
|
+
export declare function normalizePoolSize(poolSize: number, defaultSize?: number, maximumSize?: number): number;
|
|
7
8
|
export interface CronOptions {
|
|
8
9
|
/** Execute the cron job immediately upon registration (default: false) */
|
|
9
10
|
runOnStart?: boolean;
|
|
@@ -64,27 +65,41 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
64
65
|
readonly __routes: Routes;
|
|
65
66
|
private tree;
|
|
66
67
|
private pool;
|
|
68
|
+
private readonly _poolState;
|
|
69
|
+
private readonly maxPool;
|
|
67
70
|
private hotFetch?;
|
|
68
71
|
private compiled;
|
|
69
72
|
private _useLog;
|
|
70
73
|
private _trustProxyBox;
|
|
74
|
+
protected _onRouteMutate(): void;
|
|
71
75
|
private errorHandler?;
|
|
72
76
|
private wsRoutes;
|
|
73
77
|
private startHooks;
|
|
74
78
|
private stopHooks;
|
|
79
|
+
private drainHooks;
|
|
75
80
|
private crons;
|
|
76
81
|
private server?;
|
|
77
82
|
private shutdownHandler?;
|
|
83
|
+
private ipcDrainHandler?;
|
|
84
|
+
private _draining;
|
|
78
85
|
private wsAdapter;
|
|
79
86
|
useLog(enabled?: boolean): this;
|
|
80
87
|
onStart(fn: () => void | Promise<void>): this;
|
|
81
88
|
onStop(fn: () => void | Promise<void>): this;
|
|
89
|
+
onDrain(fn: () => void | Promise<void>): this;
|
|
90
|
+
/**
|
|
91
|
+
* Gracefully drains the server by running all onDrain hooks and stopping
|
|
92
|
+
* the server while allowing in-flight requests to complete.
|
|
93
|
+
*/
|
|
94
|
+
drain(closeActiveConnections?: boolean): Promise<void>;
|
|
82
95
|
/**
|
|
83
96
|
* Built-in overlap-safe background interval scheduler.
|
|
84
97
|
* Automatically cleared when app.stop() is called.
|
|
85
98
|
*/
|
|
86
99
|
cron(name: string, intervalMs: number, fn: () => void | Promise<void>, options?: CronOptions): this;
|
|
87
100
|
stop(closeActiveConnections?: boolean): Promise<void>;
|
|
101
|
+
private static readonly DEFAULT_POOL_SIZE;
|
|
102
|
+
private static readonly MAX_POOL_SIZE;
|
|
88
103
|
constructor(poolSize?: number);
|
|
89
104
|
private notFoundHandler;
|
|
90
105
|
setNotFound(handler: () => NotFoundResponse): void;
|
|
@@ -113,6 +128,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
113
128
|
derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
|
|
114
129
|
private compileHandler;
|
|
115
130
|
compile(): void;
|
|
131
|
+
private readonly _lazyFetch;
|
|
116
132
|
fetch: (req: Request, peerIp?: string) => any;
|
|
117
133
|
/**
|
|
118
134
|
* Ergonomic in-memory request helper for testing or internal invocations.
|
|
@@ -34,6 +34,25 @@ export interface UploadResult {
|
|
|
34
34
|
fields: Record<string, string>;
|
|
35
35
|
files: UploadedFile[];
|
|
36
36
|
}
|
|
37
|
+
export interface UploadStreamOptions {
|
|
38
|
+
/** Max size per file in bytes (default: 100MB) */
|
|
39
|
+
maxFileSize?: number;
|
|
40
|
+
/** Max number of uploaded files (default: 10) */
|
|
41
|
+
maxFiles?: number;
|
|
42
|
+
/** Max size per text field in bytes (default: 1MB) */
|
|
43
|
+
maxFieldSize?: number;
|
|
44
|
+
/** Allowed MIME types (e.g. ['image/png', 'application/octet-stream']) */
|
|
45
|
+
allowedTypes?: string[];
|
|
46
|
+
}
|
|
47
|
+
export interface UploadStreamPart {
|
|
48
|
+
type: 'file' | 'field';
|
|
49
|
+
fieldName: string;
|
|
50
|
+
filename?: string;
|
|
51
|
+
safeName?: string;
|
|
52
|
+
contentType?: string;
|
|
53
|
+
stream?: ReadableStream<Uint8Array>;
|
|
54
|
+
value?: string;
|
|
55
|
+
}
|
|
37
56
|
export declare class Context {
|
|
38
57
|
req: Request;
|
|
39
58
|
params: Params;
|
|
@@ -82,4 +101,9 @@ export declare class Context {
|
|
|
82
101
|
get requestId(): string;
|
|
83
102
|
get ip(): string;
|
|
84
103
|
upload(options?: UploadOptions): Promise<UploadResult>;
|
|
104
|
+
/**
|
|
105
|
+
* True streaming multipart/form-data parser.
|
|
106
|
+
* Streams file parts chunk-by-chunk with backpressure and constant O(chunk) memory usage.
|
|
107
|
+
*/
|
|
108
|
+
uploadStream(options?: UploadStreamOptions): AsyncGenerator<UploadStreamPart>;
|
|
85
109
|
}
|
|
@@ -60,6 +60,7 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
60
60
|
groupMiddleware: any[];
|
|
61
61
|
readonly __routes: Routes;
|
|
62
62
|
routes: any[];
|
|
63
|
+
protected _onRouteMutate?(): void;
|
|
63
64
|
constructor(prefix?: string, groupMiddleware?: any[]);
|
|
64
65
|
protected _add(method: string, path: string, handlers: HandlersChain): this;
|
|
65
66
|
get: AddRouterRoute<Routes, 'GET'>;
|
package/dist/types/index.d.ts
CHANGED
|
@@ -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, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
7
|
+
export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
8
8
|
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
9
9
|
/**
|
|
10
10
|
* Plugin Interface for BareJS
|
|
@@ -13,7 +13,7 @@ export interface BarePlugin {
|
|
|
13
13
|
install: (app: any) => void;
|
|
14
14
|
}
|
|
15
15
|
export { Context } from './core/context';
|
|
16
|
-
export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult } from './core/context';
|
|
16
|
+
export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult, UploadStreamOptions, UploadStreamPart } from './core/context';
|
|
17
17
|
import { Type } from "@sinclair/typebox";
|
|
18
18
|
export { Type, Type as T, Type as TypeBox };
|
|
19
19
|
import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
|
package/llms.txt
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
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`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (413 tests / 6,205 assertions)**.
|
|
4
4
|
|
|
5
5
|
## 1. Installation & Minimal App
|
|
6
6
|
```ts
|
|
7
7
|
import { BareJS, Context, Type } from 'barejs';
|
|
8
8
|
|
|
9
|
+
// Optional poolSize (0..65536, default 1024): lazy bounded LIFO Context pool with in-flight slot clearing, shared state across JIT recompiles, & dev-mode UAF guard (0 overhead in prod)
|
|
9
10
|
const app = new BareJS();
|
|
10
11
|
|
|
11
12
|
// Direct return (Elysia style — auto-detects JSON, text, or Response)
|
|
@@ -56,6 +57,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
|
|
|
56
57
|
- `ctx.query` / `ctx.getQuery(key)` / `ctx.queryAll(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`) with repeated query key support.
|
|
57
58
|
- `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit.
|
|
58
59
|
- `await ctx.upload({ maxFileSize, maxFiles, allowedTypes })`: Safe `multipart/form-data` parser; returns `{ fields, files }` with `safeName` (sanitized against path traversal) and enforces `413` (size/count) and `415` (MIME type).
|
|
60
|
+
- `ctx.uploadStream({ maxFileSize, maxFiles, maxFieldSize, allowedTypes })`: True streaming `multipart/form-data` async generator yielding `{ type: 'field', fieldName, value }` and `{ type: 'file', fieldName, filename, safeName, contentType, stream }` (`ReadableStream<Uint8Array>`, $O(\text{chunk})$ memory).
|
|
59
61
|
- `ctx.cookies`: Lazy parsed request cookies (`Record<string, string>`).
|
|
60
62
|
- `await ctx.setCookie(name, value, { secret?, httpOnly?, sameSite?, secure?, maxAge?, expires?, domain?, path? })`: Defaults to `HttpOnly; SameSite=Lax; Path=/`. Pass `secret` for HMAC-SHA256 signing.
|
|
61
63
|
- `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
|
|
@@ -129,6 +131,7 @@ app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://aut
|
|
|
129
131
|
## 7. Lifecycle & Error Handling
|
|
130
132
|
```ts
|
|
131
133
|
app.onStart(() => console.log('Server started'));
|
|
134
|
+
app.onDrain(async () => console.log('Draining...')); // Also triggered by IPC DRAIN_REQUEST
|
|
132
135
|
app.onStop(async () => await db.close());
|
|
133
136
|
app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId }));
|
|
134
137
|
app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' }));
|
package/package.json
CHANGED
package/src/core/bare.ts
CHANGED
|
@@ -10,6 +10,15 @@ import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../uti
|
|
|
10
10
|
import type { RouteSchemas } from "../security/validators";
|
|
11
11
|
import type { RouteSchema } from "../client/index";
|
|
12
12
|
|
|
13
|
+
export function normalizePoolSize(
|
|
14
|
+
poolSize: number,
|
|
15
|
+
defaultSize = 1024,
|
|
16
|
+
maximumSize = 65_536
|
|
17
|
+
): number {
|
|
18
|
+
const requested = Number.isFinite(poolSize) ? Math.floor(poolSize) : defaultSize;
|
|
19
|
+
return Math.min(maximumSize, Math.max(0, requested));
|
|
20
|
+
}
|
|
21
|
+
|
|
13
22
|
export interface CronOptions {
|
|
14
23
|
/** Execute the cron job immediately upon registration (default: false) */
|
|
15
24
|
runOnStart?: boolean;
|
|
@@ -64,19 +73,31 @@ export class BareJS<
|
|
|
64
73
|
> extends BareRouter<Routes> {
|
|
65
74
|
declare readonly __routes: Routes;
|
|
66
75
|
private tree = new RadixNode();
|
|
67
|
-
private pool: Context
|
|
76
|
+
private pool: Array<Context | undefined> = [];
|
|
77
|
+
private readonly _poolState = { top: 0 };
|
|
78
|
+
private readonly maxPool: number;
|
|
68
79
|
// private poolIdx = 0;
|
|
69
80
|
private hotFetch?: (req: Request, peerIp?: string) => any;
|
|
70
81
|
private compiled = false;
|
|
71
82
|
private _useLog: boolean = false;
|
|
72
83
|
private _trustProxyBox = { val: false };
|
|
84
|
+
|
|
85
|
+
protected override _onRouteMutate(): void {
|
|
86
|
+
if (this.compiled) {
|
|
87
|
+
this.compiled = false;
|
|
88
|
+
this.fetch = this._lazyFetch;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
73
91
|
private errorHandler?: (err: any, ctx: Context) => any;
|
|
74
92
|
private wsRoutes = new Map<string, WebSocketRouteHandler>();
|
|
75
93
|
private startHooks: (() => void | Promise<void>)[] = [];
|
|
76
94
|
private stopHooks: (() => void | Promise<void>)[] = [];
|
|
95
|
+
private drainHooks: (() => void | Promise<void>)[] = [];
|
|
77
96
|
private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
|
|
78
97
|
private server?: ReturnType<typeof Bun.serve>;
|
|
79
98
|
private shutdownHandler?: () => Promise<void>;
|
|
99
|
+
private ipcDrainHandler?: (msg: any) => void;
|
|
100
|
+
private _draining = false;
|
|
80
101
|
private wsAdapter = {
|
|
81
102
|
open(ws: any) { ws.data?.open?.(ws); },
|
|
82
103
|
message(ws: any, msg: any) { ws.data?.message?.(ws, msg); },
|
|
@@ -86,6 +107,7 @@ export class BareJS<
|
|
|
86
107
|
|
|
87
108
|
public useLog(enabled: boolean = true): this {
|
|
88
109
|
this._useLog = enabled;
|
|
110
|
+
this._onRouteMutate();
|
|
89
111
|
return this;
|
|
90
112
|
}
|
|
91
113
|
|
|
@@ -99,6 +121,28 @@ export class BareJS<
|
|
|
99
121
|
return this;
|
|
100
122
|
}
|
|
101
123
|
|
|
124
|
+
public onDrain(fn: () => void | Promise<void>): this {
|
|
125
|
+
this.drainHooks.push(fn);
|
|
126
|
+
return this;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Gracefully drains the server by running all onDrain hooks and stopping
|
|
131
|
+
* the server while allowing in-flight requests to complete.
|
|
132
|
+
*/
|
|
133
|
+
public async drain(closeActiveConnections = false): Promise<void> {
|
|
134
|
+
if (this._draining) return;
|
|
135
|
+
this._draining = true;
|
|
136
|
+
for (const hook of this.drainHooks) {
|
|
137
|
+
try {
|
|
138
|
+
await hook();
|
|
139
|
+
} catch (e) {
|
|
140
|
+
console.error(`[${this.name}] onDrain error:`, e);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
await this.stop(closeActiveConnections);
|
|
144
|
+
}
|
|
145
|
+
|
|
102
146
|
/**
|
|
103
147
|
* Built-in overlap-safe background interval scheduler.
|
|
104
148
|
* Automatically cleared when app.stop() is called.
|
|
@@ -143,6 +187,10 @@ export class BareJS<
|
|
|
143
187
|
process.off("SIGTERM", this.shutdownHandler);
|
|
144
188
|
this.shutdownHandler = undefined;
|
|
145
189
|
}
|
|
190
|
+
if (this.ipcDrainHandler) {
|
|
191
|
+
process.off("message", this.ipcDrainHandler);
|
|
192
|
+
this.ipcDrainHandler = undefined;
|
|
193
|
+
}
|
|
146
194
|
if (this.server) {
|
|
147
195
|
this.server.stop(closeActiveConnections);
|
|
148
196
|
this.server = undefined;
|
|
@@ -155,13 +203,17 @@ export class BareJS<
|
|
|
155
203
|
}
|
|
156
204
|
}
|
|
157
205
|
}
|
|
158
|
-
|
|
206
|
+
private static readonly DEFAULT_POOL_SIZE = 1024;
|
|
207
|
+
private static readonly MAX_POOL_SIZE = 65_536;
|
|
208
|
+
|
|
209
|
+
constructor(poolSize: number = BareJS.DEFAULT_POOL_SIZE) {
|
|
159
210
|
super();
|
|
160
211
|
bootstrapConfig();
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
212
|
+
this.maxPool = normalizePoolSize(
|
|
213
|
+
poolSize,
|
|
214
|
+
BareJS.DEFAULT_POOL_SIZE,
|
|
215
|
+
BareJS.MAX_POOL_SIZE
|
|
216
|
+
);
|
|
165
217
|
try {
|
|
166
218
|
const pkgPath = join(process.cwd(), "package.json");
|
|
167
219
|
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
@@ -182,10 +234,12 @@ export class BareJS<
|
|
|
182
234
|
});
|
|
183
235
|
public setNotFound(handler: () => NotFoundResponse) {
|
|
184
236
|
this.notFoundHandler = handler;
|
|
237
|
+
this._onRouteMutate();
|
|
185
238
|
}
|
|
186
239
|
|
|
187
240
|
public onError(handler: (err: any, ctx: Context) => any): this {
|
|
188
241
|
this.errorHandler = handler;
|
|
242
|
+
this._onRouteMutate();
|
|
189
243
|
return this;
|
|
190
244
|
}
|
|
191
245
|
|
|
@@ -687,7 +741,7 @@ export class BareJS<
|
|
|
687
741
|
|
|
688
742
|
const tree = this.tree;
|
|
689
743
|
const pool = this.pool;
|
|
690
|
-
const maxPool =
|
|
744
|
+
const maxPool = this.maxPool;
|
|
691
745
|
const hNotFound = this.notFoundHandler;
|
|
692
746
|
const customError = this.errorHandler;
|
|
693
747
|
const applyCtxHeaders = (res: Response, ctx: Context): Response => {
|
|
@@ -773,26 +827,60 @@ export class BareJS<
|
|
|
773
827
|
? `if (ctx._idempotencyKey) { if (ctx._idemInFlight) ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
|
|
774
828
|
: '';
|
|
775
829
|
|
|
830
|
+
const isDevUaf = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
|
|
831
|
+
const ctxVar = isDevUaf ? 'rawCtx' : 'ctx';
|
|
832
|
+
const wrapUaf = isDevUaf
|
|
833
|
+
? (rawCtx: Context, state: { released: boolean }): Context => {
|
|
834
|
+
const warn = (prop: string | symbol) => {
|
|
835
|
+
console.warn(
|
|
836
|
+
`[BareJS] Use-after-free detected: Context.${String(prop)} accessed after response was sent and Context was released to pool.`
|
|
837
|
+
);
|
|
838
|
+
};
|
|
839
|
+
const proxy: any = new Proxy(rawCtx, {
|
|
840
|
+
get(target: any, prop) {
|
|
841
|
+
if (state.released && prop !== Symbol.toStringTag && prop !== 'then') {
|
|
842
|
+
warn(prop);
|
|
843
|
+
}
|
|
844
|
+
const val = target[prop];
|
|
845
|
+
if (typeof val === 'function') {
|
|
846
|
+
return function (this: any, ...args: any[]) {
|
|
847
|
+
const ret = val.apply(target, args);
|
|
848
|
+
return ret === target ? proxy : ret;
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
return val;
|
|
852
|
+
},
|
|
853
|
+
set(target: any, prop, value) {
|
|
854
|
+
if (state.released) warn(prop);
|
|
855
|
+
target[prop] = value;
|
|
856
|
+
return true;
|
|
857
|
+
}
|
|
858
|
+
});
|
|
859
|
+
return proxy;
|
|
860
|
+
}
|
|
861
|
+
: undefined;
|
|
862
|
+
|
|
776
863
|
const releaseCode = `
|
|
777
|
-
if (
|
|
778
|
-
|
|
779
|
-
${
|
|
780
|
-
${
|
|
781
|
-
ctx.
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
864
|
+
if (!${ctxVar}._detached) {
|
|
865
|
+
${isDevUaf ? '_uaf.released = true;' : ''}
|
|
866
|
+
if (${ctxVar}.store.size > 0) ${ctxVar}.store.clear();
|
|
867
|
+
${deriveCleanup.replaceAll('ctx.', `${ctxVar}.`).replaceAll('[ctx.', `[${ctxVar}.`)}
|
|
868
|
+
${idemCleanup.replaceAll('ctx.', `${ctxVar}.`)}
|
|
869
|
+
${ctxVar}.req = undefined;
|
|
870
|
+
${ctxVar}._status = 200;
|
|
871
|
+
${ctxVar}.body = undefined;
|
|
872
|
+
${ctxVar}._query = undefined;
|
|
873
|
+
${ctxVar}._cookies = undefined;
|
|
874
|
+
${ctxVar}._setCookies = undefined;
|
|
875
|
+
${ctxVar}._headers = undefined;
|
|
876
|
+
${ctxVar}._requestId = undefined;
|
|
877
|
+
${ctxVar}._peerIp = undefined;
|
|
878
|
+
${ctxVar}.params = EMPTY_PARAMS;
|
|
879
|
+
if (poolState.top < maxPool) pool[poolState.top++] = ${ctxVar};
|
|
792
880
|
}
|
|
793
881
|
`;
|
|
794
882
|
|
|
795
|
-
const handleErrCode = `const errRes = hError(e,
|
|
883
|
+
const handleErrCode = `const errRes = hError(e, ${ctxVar});
|
|
796
884
|
if (errRes && errRes.then) return errRes.then((r) => { ${isLog ? 'doLog(r.status || 500);' : ''} ${releaseCode} return r; });
|
|
797
885
|
${isLog ? 'doLog(errRes.status || 500);' : ''}
|
|
798
886
|
${releaseCode}
|
|
@@ -800,11 +888,13 @@ export class BareJS<
|
|
|
800
888
|
|
|
801
889
|
const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
|
|
802
890
|
const useCompactEmit = this.routes.length > 16;
|
|
891
|
+
const relArgs = isDevUaf ? 'rawCtx, _uaf' : 'ctx';
|
|
892
|
+
const errArgs = isDevUaf ? `e, rawCtx, _uaf${isLog ? ', doLog' : ''}` : `e, ctx${isLog ? ', doLog' : ''}`;
|
|
803
893
|
const routerCode = tree.jitCompile(register, 0, 'url', 's', [], (hName: string) =>
|
|
804
894
|
useCompactEmit
|
|
805
895
|
? `out = ${hName}${callSuffix};
|
|
806
|
-
if (out && out.then) return out.then((v) => { _rel(
|
|
807
|
-
_rel(
|
|
896
|
+
if (out && out.then) return out.then((v) => { _rel(${relArgs}); return v; }, (e) => _onErr(${errArgs}));
|
|
897
|
+
_rel(${relArgs});
|
|
808
898
|
return out;`
|
|
809
899
|
: `out = ${hName}${callSuffix};
|
|
810
900
|
if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
|
|
@@ -909,9 +999,10 @@ export class BareJS<
|
|
|
909
999
|
}
|
|
910
1000
|
: undefined;
|
|
911
1001
|
|
|
1002
|
+
const poolState = this._poolState;
|
|
912
1003
|
const trustProxyBox = this._trustProxyBox;
|
|
913
|
-
const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
|
|
914
|
-
const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
|
|
1004
|
+
const args = ['pool', 'poolState', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(isDevUaf ? ['wrapUaf'] : []), ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
|
|
1005
|
+
const values = [pool, poolState, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(isDevUaf ? [wrapUaf] : []), ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
|
|
915
1006
|
|
|
916
1007
|
const logInit = isLog ? `
|
|
917
1008
|
const start = performance.now();
|
|
@@ -928,11 +1019,10 @@ export class BareJS<
|
|
|
928
1019
|
|
|
929
1020
|
const compactHelpers = useCompactEmit
|
|
930
1021
|
? `
|
|
931
|
-
const _rel = (
|
|
932
|
-
const _onErr = (
|
|
1022
|
+
const _rel = (${relArgs}) => { ${releaseCode} };
|
|
1023
|
+
const _onErr = (${errArgs}) => { ${handleErrCode} };`
|
|
933
1024
|
: '';
|
|
934
|
-
const fnBody =
|
|
935
|
-
let poolTop = maxPool;${compactHelpers}
|
|
1025
|
+
const fnBody = `${compactHelpers}
|
|
936
1026
|
return function(req, peerIp) {
|
|
937
1027
|
const url = req.url;
|
|
938
1028
|
let s = url.indexOf('/', 8);
|
|
@@ -942,13 +1032,21 @@ export class BareJS<
|
|
|
942
1032
|
else s = urlLen;
|
|
943
1033
|
|
|
944
1034
|
const method = req.method;
|
|
945
|
-
|
|
1035
|
+
let ${ctxVar};
|
|
1036
|
+
if (poolState.top > 0) {
|
|
1037
|
+
const slot = --poolState.top;
|
|
1038
|
+
${ctxVar} = pool[slot];
|
|
1039
|
+
pool[slot] = undefined;
|
|
1040
|
+
} else {
|
|
1041
|
+
${ctxVar} = new Context(trustProxyBox.val);
|
|
1042
|
+
}
|
|
1043
|
+
${isDevUaf ? 'const _uaf = { released: false }; const ctx = wrapUaf(rawCtx, _uaf);' : ''}
|
|
946
1044
|
let out;
|
|
947
1045
|
${logInit}
|
|
948
1046
|
|
|
949
1047
|
try {
|
|
950
|
-
|
|
951
|
-
|
|
1048
|
+
${ctxVar}.req = req;
|
|
1049
|
+
${ctxVar}._peerIp = peerIp;
|
|
952
1050
|
|
|
953
1051
|
${routerCode}
|
|
954
1052
|
|
|
@@ -958,7 +1056,7 @@ export class BareJS<
|
|
|
958
1056
|
|
|
959
1057
|
const errorBody = hNotFound();
|
|
960
1058
|
const status = errorBody.status || 404;
|
|
961
|
-
const nfRes = ${apply404Cors ?
|
|
1059
|
+
const nfRes = ${apply404Cors ? `apply404Cors(Response.json(errorBody, { status }), ${ctxVar})` : `applyCtxHeaders(Response.json(errorBody, { status }), ${ctxVar})`};
|
|
962
1060
|
${isLog ? 'doLog(status);' : ''}
|
|
963
1061
|
${releaseCode}
|
|
964
1062
|
return nfRes;
|
|
@@ -966,7 +1064,7 @@ export class BareJS<
|
|
|
966
1064
|
} catch (e) {
|
|
967
1065
|
${handleErrCode}
|
|
968
1066
|
}
|
|
969
|
-
}
|
|
1067
|
+
};
|
|
970
1068
|
`;
|
|
971
1069
|
|
|
972
1070
|
this.hotFetch = new Function(...args, fnBody)(...values);
|
|
@@ -974,7 +1072,7 @@ export class BareJS<
|
|
|
974
1072
|
this.fetch = this.hotFetch!;
|
|
975
1073
|
}
|
|
976
1074
|
|
|
977
|
-
|
|
1075
|
+
private readonly _lazyFetch = (req: Request, peerIp?: string): any => {
|
|
978
1076
|
if (!this.compiled) {
|
|
979
1077
|
this.compile();
|
|
980
1078
|
return this.hotFetch!(req, peerIp);
|
|
@@ -982,6 +1080,8 @@ export class BareJS<
|
|
|
982
1080
|
return this.hotFetch!(req, peerIp);
|
|
983
1081
|
};
|
|
984
1082
|
|
|
1083
|
+
public fetch = this._lazyFetch;
|
|
1084
|
+
|
|
985
1085
|
/**
|
|
986
1086
|
* Ergonomic in-memory request helper for testing or internal invocations.
|
|
987
1087
|
* Normalizes relative paths to http://localhost and delegates to this.fetch(req).
|
|
@@ -1001,7 +1101,8 @@ export class BareJS<
|
|
|
1001
1101
|
public trustProxy(enabled: boolean = true): this {
|
|
1002
1102
|
this._trustProxyBox.val = enabled;
|
|
1003
1103
|
for (let i = 0; i < this.pool.length; i++) {
|
|
1004
|
-
this.pool[i]
|
|
1104
|
+
const ctx = this.pool[i];
|
|
1105
|
+
if (ctx) ctx._trustProxy = enabled;
|
|
1005
1106
|
}
|
|
1006
1107
|
return this;
|
|
1007
1108
|
}
|
|
@@ -1030,13 +1131,13 @@ export class BareJS<
|
|
|
1030
1131
|
\x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
|
|
1031
1132
|
|
|
1032
1133
|
\x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
|
|
1033
|
-
\x1b[90m⚙️ Pool Size: ${this.
|
|
1134
|
+
\x1b[90m⚙️ Pool Size: ${this.maxPool} | JIT: Enabled | Port: ${finalPort}\x1b[0m
|
|
1034
1135
|
\x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
|
|
1035
1136
|
`);
|
|
1036
1137
|
}
|
|
1037
1138
|
|
|
1038
1139
|
const wsRoutes = this.wsRoutes;
|
|
1039
|
-
const
|
|
1140
|
+
const self = this;
|
|
1040
1141
|
const hasWs = wsRoutes.size > 0;
|
|
1041
1142
|
|
|
1042
1143
|
const server = hasWs
|
|
@@ -1086,7 +1187,7 @@ export class BareJS<
|
|
|
1086
1187
|
return undefined as any;
|
|
1087
1188
|
}
|
|
1088
1189
|
}
|
|
1089
|
-
return
|
|
1190
|
+
return self.fetch(req, srv?.requestIP?.(req)?.address);
|
|
1090
1191
|
},
|
|
1091
1192
|
websocket: this.wsAdapter
|
|
1092
1193
|
})
|
|
@@ -1096,7 +1197,7 @@ export class BareJS<
|
|
|
1096
1197
|
reusePort,
|
|
1097
1198
|
maxRequestBodySize,
|
|
1098
1199
|
fetch(req: Request, srv: any) {
|
|
1099
|
-
return
|
|
1200
|
+
return self.fetch(req, srv?.requestIP?.(req)?.address);
|
|
1100
1201
|
}
|
|
1101
1202
|
});
|
|
1102
1203
|
|
|
@@ -1123,9 +1224,19 @@ export class BareJS<
|
|
|
1123
1224
|
process.exit(0);
|
|
1124
1225
|
};
|
|
1125
1226
|
|
|
1227
|
+
this._draining = false;
|
|
1126
1228
|
this.shutdownHandler = shutdown;
|
|
1127
1229
|
process.on("SIGINT", shutdown);
|
|
1128
1230
|
process.on("SIGTERM", shutdown);
|
|
1231
|
+
|
|
1232
|
+
const onIpcMessage = async (msg: any) => {
|
|
1233
|
+
if (msg === "DRAIN_REQUEST" || msg?.type === "DRAIN_REQUEST") {
|
|
1234
|
+
await this.drain(false);
|
|
1235
|
+
process.exit(0);
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
this.ipcDrainHandler = onIpcMessage;
|
|
1239
|
+
process.on("message", onIpcMessage);
|
|
1129
1240
|
return server;
|
|
1130
1241
|
}
|
|
1131
1242
|
}
|