barejs 0.1.52 → 0.1.55

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.
@@ -92,7 +92,9 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
92
92
  onError(handler: (err: any, ctx: Context) => any): this;
93
93
  ws(path: string, handler: WebSocketRouteHandler): this;
94
94
  docs(path?: string, options?: OpenAPIOptions): this;
95
- rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this;
95
+ rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
96
+ maxBatchSize?: number;
97
+ }): this;
96
98
  get: AddRoute<Derived, Routes, 'GET'>;
97
99
  post: AddRoute<Derived, Routes, 'POST'>;
98
100
  put: AddRoute<Derived, Routes, 'PUT'>;
@@ -47,16 +47,18 @@ export declare class Context {
47
47
  _requestId: string | undefined;
48
48
  _peerIp: string | undefined;
49
49
  _trustProxy: boolean;
50
+ _detached: boolean;
50
51
  constructor(trustProxy?: boolean);
51
52
  get query(): Record<string, string>;
52
53
  getQuery(key: string): string | undefined;
53
54
  get cookies(): Record<string, string>;
54
55
  setCookie(name: string, value: string, options?: CookieOptions): this;
55
56
  getSignedCookie(name: string, secret: string): string | null;
56
- deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): this;
57
+ deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'>): this;
57
58
  jsonBody(maxBytes?: number): Promise<any>;
58
59
  reset(req: Request): this;
59
60
  status(code: number): this;
61
+ private _applyCookies;
60
62
  json(data: any): Response;
61
63
  set(key: string, value: any): this;
62
64
  get(key: string): any;
@@ -19,6 +19,8 @@ export interface BareAuthOptions {
19
19
  publicKey?: string | CryptoKey;
20
20
  jwksUri?: string;
21
21
  jwksCacheTtlMs?: number;
22
+ issuer?: string | string[];
23
+ audience?: string | string[];
22
24
  revocationStore?: RevocationStore;
23
25
  isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
24
26
  }
@@ -8,5 +8,7 @@ export interface CsrfOptions {
8
8
  cookieName?: string;
9
9
  headerName?: string;
10
10
  requireToken?: boolean;
11
+ /** Allow requests that omit both Origin and Referer headers (default: false) */
12
+ allowMissingOrigin?: boolean;
11
13
  }
12
14
  export declare const csrf: (options?: CsrfOptions) => Middleware;
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`) 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 (214 tests / 2,906 assertions)**.
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 (316 tests / 5,833 assertions)**.
4
4
 
5
5
  ## 1. Installation & Minimal App
6
6
  ```ts
@@ -61,7 +61,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
61
61
  - `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
62
62
  - `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`).
63
63
  - `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`.
64
- - `ctx.ip`: Client IP extracted from `x-forwarded-for`, `x-real-ip`, `cf-connecting-ip`, or `'127.0.0.1'`.
64
+ - `ctx.ip`: Client IP from `x-forwarded-for` (first non-empty), `x-real-ip`, `cf-connecting-ip` (only when `trustProxy` is enabled), else peer IP or `'127.0.0.1'`.
65
65
  - `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`.
66
66
  - `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map<string, any>` (automatically cleared on pool release).
67
67
  - **Response Helpers (Hono / Express style):**
@@ -107,7 +107,7 @@ app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store }), (ct
107
107
 
108
108
  // Thundering-herd / Cache-stampede request coalescer
109
109
  const sf = createSingleflight();
110
- app.get('/report', () => sf.do('report-key', async () => ({ total: 100 })));
110
+ app.get('/report', () => sf('report-key', async () => ({ total: 100 })));
111
111
 
112
112
  // Auth & Hashing (HS256 sync fast-path + RS256/ES256/JWKS async verification + revocationStore)
113
113
  const hash = await Hash.make('password'); // Argon2id (64MB default)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.52",
3
+ "version": "0.1.55",
4
4
  "author": "xarhang",
5
5
  "description": "High-performance JIT-specialized web framework for Bun",
6
6
  "main": "./dist/index.js",
@@ -91,9 +91,10 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
91
91
  const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
92
92
  let finalPath = path;
93
93
  if (options?.params) {
94
- for (const [k, v] of Object.entries(options.params)) {
95
- finalPath = finalPath.replaceAll(`:${k}`, encodeURIComponent(String(v)));
96
- }
94
+ const params = options.params;
95
+ finalPath = finalPath.replace(/:([a-zA-Z0-9_]+)(?=\/|$)/g, (match, key) =>
96
+ Object.hasOwn(params, key) ? encodeURIComponent(String(params[key])) : match
97
+ );
97
98
  }
98
99
  const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
99
100
  const normalizedPath = finalPath.startsWith('/') ? finalPath : `/${finalPath}`;
package/src/core/bare.ts CHANGED
@@ -5,6 +5,7 @@ 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 { BARE_CONFIG } from "./config";
8
9
  import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
9
10
  import type { RouteSchemas } from "../security/validators";
10
11
  import type { RouteSchema } from "../client/index";
@@ -69,7 +70,7 @@ export class BareJS<
69
70
  private compiled = false;
70
71
  private poolMask: number;
71
72
  private _useLog: boolean = false;
72
- private _trustProxy: boolean = true;
73
+ private _trustProxy: boolean = false;
73
74
  private errorHandler?: (err: any, ctx: Context) => any;
74
75
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
75
76
  private startHooks: (() => void | Promise<void>)[] = [];
@@ -215,7 +216,14 @@ export class BareJS<
215
216
  return this;
216
217
  }
217
218
 
218
- public rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this {
219
+ public rpc(
220
+ path: string,
221
+ procedures: Record<string, (params: any, ctx: Context) => any>,
222
+ options: { maxBatchSize?: number } = {}
223
+ ): this {
224
+ const maxBatchSize = options.maxBatchSize ?? 100;
225
+ const isProd = process.env.NODE_ENV === 'production';
226
+
219
227
  const execCall = async (reqObj: any, ctx: Context) => {
220
228
  if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
221
229
  return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: reqObj?.id ?? null };
@@ -229,9 +237,12 @@ export class BareJS<
229
237
  if (reqObj.id === undefined) return null; // Notification
230
238
  return { jsonrpc: '2.0', result, id: reqObj.id };
231
239
  } catch (err: any) {
240
+ const msg = !isProd || err?.expose || (err?.status >= 400 && err?.status < 500)
241
+ ? (err?.message || 'Internal error')
242
+ : 'Internal error';
232
243
  return {
233
244
  jsonrpc: '2.0',
234
- error: { code: -32603, message: err?.message || 'Internal error' },
245
+ error: { code: -32603, message: msg },
235
246
  id: reqObj.id ?? null
236
247
  };
237
248
  }
@@ -243,7 +254,7 @@ export class BareJS<
243
254
  return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
244
255
  }
245
256
  if (Array.isArray(payload)) {
246
- if (payload.length === 0) {
257
+ if (payload.length === 0 || payload.length > maxBatchSize) {
247
258
  return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null });
248
259
  }
249
260
  const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
@@ -301,6 +312,28 @@ export class BareJS<
301
312
  // inherited use() from BareRouter handles router merging now
302
313
 
303
314
  private compileHandler(pipeline: any[], isLog: boolean): Function {
315
+ if (pipeline.length === 0) {
316
+ return () => undefined;
317
+ }
318
+
319
+ const applyCtxHeadersToRes = (res: Response, ctx: Context): Response => {
320
+ if (ctx._headers) {
321
+ for (const k in ctx._headers) {
322
+ const val = ctx._headers[k];
323
+ if (val !== undefined && !res.headers.has(k)) {
324
+ try { res.headers.set(k, val); } catch { /* ignore invalid header */ }
325
+ }
326
+ }
327
+ }
328
+ if (ctx._setCookies) {
329
+ for (let i = 0; i < ctx._setCookies.length; i++) {
330
+ try { res.headers.append('Set-Cookie', ctx._setCookies[i]!); } catch { /* ignore */ }
331
+ }
332
+ ctx._setCookies = undefined;
333
+ }
334
+ return res;
335
+ };
336
+
304
337
  const timeoutMw = pipeline.find((fn) => fn?.__timeout);
305
338
  if (timeoutMw) {
306
339
  const { ms, status, message } = timeoutMw.__timeout;
@@ -313,7 +346,9 @@ export class BareJS<
313
346
  try {
314
347
  const timeoutPromise = new Promise<Response>((resolve) => {
315
348
  timer = setTimeout(() => {
316
- resolve(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }));
349
+ ctx._detached = true;
350
+ if (typeof res.catch === 'function') res.catch(() => {});
351
+ resolve(applyCtxHeadersToRes(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }), ctx));
317
352
  }, ms);
318
353
  });
319
354
  return await Promise.race([res, timeoutPromise]);
@@ -410,11 +445,13 @@ export class BareJS<
410
445
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
411
446
 
412
447
  const extraNames = [
448
+ 'applyShortCircuit',
413
449
  ...(rFilter ? ['rFilter'] : []),
414
450
  ...(idemCommit ? ['idemCommit'] : []),
415
451
  ...(idemRelease ? ['idemRelease'] : [])
416
452
  ];
417
453
  const extraVals = [
454
+ applyCtxHeadersToRes,
418
455
  ...(rFilter ? [rFilter] : []),
419
456
  ...(idemCommit ? [idemCommit] : []),
420
457
  ...(idemRelease ? [idemRelease] : [])
@@ -473,7 +510,7 @@ export class BareJS<
473
510
  code += `let r${i} = fn${i}(ctx, noop);\n`;
474
511
  code += `if (r${i}) {\n`;
475
512
  code += ` if (r${i}.then) r${i} = await r${i};\n`;
476
- code += ` if (r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
513
+ code += ` if (r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
477
514
  code += `}\n`;
478
515
  }
479
516
  code += `
@@ -484,7 +521,7 @@ export class BareJS<
484
521
  } else {
485
522
  for (let i = 0; i < len - 1; i++) {
486
523
  code += `const r${i} = fn${i}(ctx, noop);\n`;
487
- code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
524
+ code += `if (r${i} && r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
488
525
  }
489
526
  code += `
490
527
  let res = fn${len - 1}(ctx);
@@ -580,20 +617,22 @@ export class BareJS<
580
617
  : '';
581
618
 
582
619
  const releaseCode = `
583
- if (ctx.store.size > 0) ctx.store.clear();
584
- ${deriveCleanup}
585
- ${idemCleanup}
586
- ctx.req = undefined;
587
- ctx._status = 200;
588
- ctx.body = undefined;
589
- ctx._query = undefined;
590
- ctx._cookies = undefined;
591
- ctx._setCookies = undefined;
592
- ctx._headers = undefined;
593
- ctx._requestId = undefined;
594
- ctx._peerIp = undefined;
595
- ctx.params = EMPTY_PARAMS;
596
- if (poolTop < maxPool) pool[poolTop++] = ctx;
620
+ if (!ctx._detached) {
621
+ if (ctx.store.size > 0) ctx.store.clear();
622
+ ${deriveCleanup}
623
+ ${idemCleanup}
624
+ ctx.req = undefined;
625
+ ctx._status = 200;
626
+ ctx.body = undefined;
627
+ ctx._query = undefined;
628
+ ctx._cookies = undefined;
629
+ ctx._setCookies = undefined;
630
+ ctx._headers = undefined;
631
+ ctx._requestId = undefined;
632
+ ctx._peerIp = undefined;
633
+ ctx.params = EMPTY_PARAMS;
634
+ if (poolTop < maxPool) pool[poolTop++] = ctx;
635
+ }
597
636
  `;
598
637
 
599
638
  const handleErrCode = `const errRes = hError(e, ctx);
@@ -622,24 +661,17 @@ export class BareJS<
622
661
  }`
623
662
  : '';
624
663
 
625
- const staticMws = this.groupMiddleware.filter((m: any) => m.__isStatic);
626
- const hasStaticMw = staticMws.length > 0;
664
+ const hasStaticMw = this.groupMiddleware.some((m: any) => m.__isStatic);
627
665
  const runStatic = hasStaticMw
628
666
  ? async (ctx: Context) => {
629
- const noop = () => {};
630
- for (let i = 0; i < staticMws.length; i++) {
631
- const r = await staticMws[i](ctx, noop);
632
- if (r instanceof Response) {
633
- if (ctx._headers) {
634
- for (const k in ctx._headers) {
635
- const val = ctx._headers[k];
636
- if (val !== undefined && !r.headers.has(k)) r.headers.set(k, val);
637
- }
638
- }
639
- return r;
640
- }
641
- }
642
- return undefined;
667
+ const mws = this.groupMiddleware;
668
+ const dispatch = async (idx: number): Promise<Response | undefined> => {
669
+ if (idx >= mws.length) return undefined;
670
+ const r = await mws[idx](ctx, () => dispatch(idx + 1));
671
+ if (r instanceof Response) return applyCtxHeaders(r, ctx);
672
+ return undefined;
673
+ };
674
+ return dispatch(0);
643
675
  }
644
676
  : undefined;
645
677
 
@@ -766,8 +798,6 @@ export class BareJS<
766
798
  }
767
799
  const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
768
800
 
769
- const { BARE_CONFIG } = require("./config");
770
-
771
801
  const finalPort = port || BARE_CONFIG.port || 3000;
772
802
  const isProd = process.env.NODE_ENV === 'production';
773
803
 
@@ -53,8 +53,9 @@ export class Context {
53
53
  public _setCookies: string[] | undefined = undefined;
54
54
  public _requestId: string | undefined = undefined;
55
55
  public _peerIp: string | undefined = undefined;
56
- public _trustProxy: boolean = true;
57
- constructor(trustProxy: boolean = true) {
56
+ public _trustProxy: boolean = false;
57
+ public _detached: boolean = false;
58
+ constructor(trustProxy: boolean = false) {
58
59
  this._trustProxy = trustProxy;
59
60
  }
60
61
 
@@ -108,7 +109,8 @@ export class Context {
108
109
  }
109
110
 
110
111
  public getQuery(key: string): string | undefined {
111
- return this.query[key];
112
+ const q = this.query;
113
+ return Object.hasOwn(q, key) ? q[key] : undefined;
112
114
  }
113
115
 
114
116
  public get cookies(): Record<string, string> {
@@ -140,13 +142,23 @@ export class Context {
140
142
  }
141
143
 
142
144
  public setCookie(name: string, value: string, options: CookieOptions = {}): this {
145
+ if (!name || /[\r\n;= \t]/.test(name)) {
146
+ throw new Error('Invalid cookie name');
147
+ }
148
+ const path = options.path ?? '/';
149
+ if (/[\r\n;]/.test(path)) {
150
+ throw new Error('Invalid cookie path');
151
+ }
152
+ if (options.domain && /[\r\n;]/.test(options.domain)) {
153
+ throw new Error('Invalid cookie domain');
154
+ }
143
155
  let finalVal = value;
144
156
  if (options.secret) {
145
157
  const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
146
158
  finalVal = `${value}.${sig}`;
147
159
  }
148
160
  let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
149
- cookieStr += `; Path=${options.path ?? '/'}`;
161
+ cookieStr += `; Path=${path}`;
150
162
  if (options.domain) cookieStr += `; Domain=${options.domain}`;
151
163
  if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
152
164
  if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
@@ -174,7 +186,7 @@ export class Context {
174
186
  return value;
175
187
  }
176
188
 
177
- public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): this {
189
+ public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'> = {}): this {
178
190
  return this.setCookie(name, '', {
179
191
  ...options,
180
192
  maxAge: 0,
@@ -186,20 +198,16 @@ export class Context {
186
198
  if (this.body !== undefined) return this.body;
187
199
 
188
200
  const contentType = this.req.headers.get("content-type");
189
- if (contentType && contentType.includes("application/json")) {
201
+ if (contentType && contentType.toLowerCase().includes("application/json")) {
190
202
  const lenHeader = this.req.headers.get("content-length");
191
203
  if (lenHeader !== null) {
192
- const lenNum = Number(lenHeader);
193
- if (lenNum > maxBytes) {
204
+ const trimmed = lenHeader.trim();
205
+ const lenNum = trimmed.length > 0 ? Number(trimmed) : NaN;
206
+ if (Number.isInteger(lenNum) && lenNum > maxBytes) {
194
207
  const err: any = new Error("Payload Too Large");
195
208
  err.status = 413;
196
209
  throw err;
197
210
  }
198
- try {
199
- return this.body = await this.req.json();
200
- } catch {
201
- return this.body = null;
202
- }
203
211
  }
204
212
  try {
205
213
  const text = await this.req.text();
@@ -236,6 +244,16 @@ export class Context {
236
244
  return this;
237
245
  }
238
246
 
247
+ private _applyCookies(res: Response): Response {
248
+ if (this._setCookies) {
249
+ for (let i = 0; i < this._setCookies.length; i++) {
250
+ res.headers.append('Set-Cookie', this._setCookies[i]!);
251
+ }
252
+ this._setCookies = undefined;
253
+ }
254
+ return res;
255
+ }
256
+
239
257
  public json(data: any): Response {
240
258
  const status = this._status || 200;
241
259
  let res: Response;
@@ -259,12 +277,7 @@ export class Context {
259
277
  });
260
278
  }
261
279
 
262
- if (this._setCookies) {
263
- for (let i = 0; i < this._setCookies.length; i++) {
264
- res.headers.append('Set-Cookie', this._setCookies[i]!);
265
- }
266
- }
267
- return res;
280
+ return this._applyCookies(res);
268
281
  }
269
282
 
270
283
  public set(key: string, value: any): this {
@@ -303,7 +316,7 @@ export class Context {
303
316
  'content-type': 'text/html; charset=utf-8',
304
317
  ...(this._headers || {})
305
318
  };
306
- return new Response(content, { status: status ?? this._status, headers });
319
+ return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
307
320
  }
308
321
 
309
322
  public text(content: string, status?: number): Response {
@@ -311,7 +324,7 @@ export class Context {
311
324
  'content-type': 'text/plain; charset=utf-8',
312
325
  ...(this._headers || {})
313
326
  };
314
- return new Response(content, { status: status ?? this._status, headers });
327
+ return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
315
328
  }
316
329
 
317
330
  public redirect(url: string, status: number = 302): Response {
@@ -319,7 +332,7 @@ export class Context {
319
332
  'location': url,
320
333
  ...(this._headers || {})
321
334
  };
322
- return new Response(null, { status, headers });
335
+ return this._applyCookies(new Response(null, { status, headers }));
323
336
  }
324
337
 
325
338
  public sse(
@@ -328,16 +341,18 @@ export class Context {
328
341
  | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)
329
342
  ): Response {
330
343
  const encoder = new TextEncoder();
344
+ const formatDataLines = (raw: string): string =>
345
+ raw.split(/\r?\n/).map((line) => `data: ${line}`).join('\n') + '\n\n';
331
346
  const formatChunk = (chunk: string | { event?: string; data: any; id?: string; retry?: number }): Uint8Array => {
332
347
  if (typeof chunk === 'string') {
333
- return encoder.encode(`data: ${chunk}\n\n`);
348
+ return encoder.encode(formatDataLines(chunk));
334
349
  }
335
350
  let out = '';
336
- if (chunk.id !== undefined) out += `id: ${chunk.id}\n`;
337
- if (chunk.event !== undefined) out += `event: ${chunk.event}\n`;
338
- if (chunk.retry !== undefined) out += `retry: ${chunk.retry}\n`;
351
+ if (chunk.id !== undefined) out += `id: ${String(chunk.id).replace(/[\r\n]/g, '')}\n`;
352
+ if (chunk.event !== undefined) out += `event: ${String(chunk.event).replace(/[\r\n]/g, '')}\n`;
353
+ if (chunk.retry !== undefined && Number.isFinite(chunk.retry)) out += `retry: ${Math.max(0, Math.floor(chunk.retry))}\n`;
339
354
  const payload = typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data);
340
- out += `data: ${payload}\n\n`;
355
+ out += formatDataLines(payload);
341
356
  return encoder.encode(out);
342
357
  };
343
358
 
@@ -375,7 +390,7 @@ export class Context {
375
390
  'connection': 'keep-alive',
376
391
  ...(this._headers || {})
377
392
  };
378
- return new Response(stream, { status: this._status || 200, headers });
393
+ return this._applyCookies(new Response(stream, { status: this._status || 200, headers }));
379
394
  }
380
395
 
381
396
  public get requestId(): string {
@@ -388,10 +403,13 @@ export class Context {
388
403
  public get ip(): string {
389
404
  if (this._trustProxy) {
390
405
  const xff = this.req?.headers?.get('x-forwarded-for');
391
- if (xff) return xff.split(',')[0]!.trim();
406
+ if (xff) {
407
+ const first = xff.split(',')[0]?.trim();
408
+ if (first) return first;
409
+ }
392
410
  const forwarded =
393
- this.req?.headers?.get('x-real-ip') ||
394
- this.req?.headers?.get('cf-connecting-ip');
411
+ this.req?.headers?.get('x-real-ip')?.trim() ||
412
+ this.req?.headers?.get('cf-connecting-ip')?.trim();
395
413
  if (forwarded) return forwarded;
396
414
  }
397
415
  return this._peerIp || '127.0.0.1';
@@ -400,21 +418,25 @@ export class Context {
400
418
  public async upload(options: UploadOptions = {}): Promise<UploadResult> {
401
419
  const maxFileSize = options.maxFileSize ?? 5 * 1024 * 1024;
402
420
  const maxFiles = options.maxFiles ?? 10;
403
- const allowed = options.allowedTypes ? new Set(options.allowedTypes) : null;
421
+ const allowed = options.allowedTypes
422
+ ? new Set(options.allowedTypes.map((t) => t.trim().toLowerCase()))
423
+ : null;
404
424
 
405
- const ct = this.req?.headers?.get('content-type') || '';
425
+ const ct = (this.req?.headers?.get('content-type') || '').toLowerCase();
406
426
  if (!ct.includes('multipart/form-data')) {
407
427
  throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
408
428
  }
409
429
 
430
+ const maxTotalBytes = maxFileSize * maxFiles;
410
431
  const contentLen = Number(this.req?.headers?.get('content-length') || 0);
411
- if (contentLen > maxFileSize * maxFiles + 65536) {
432
+ if (Number.isFinite(contentLen) && contentLen > maxTotalBytes + 65536) {
412
433
  throw Object.assign(new Error('Payload Too Large'), { status: 413 });
413
434
  }
414
435
 
415
436
  const form = await this.req.formData();
416
437
  const fields: Record<string, string> = {};
417
438
  const files: UploadedFile[] = [];
439
+ let totalBytes = 0;
418
440
 
419
441
  for (const [fieldName, value] of form.entries()) {
420
442
  if (typeof value === 'string') {
@@ -431,6 +453,10 @@ export class Context {
431
453
  if (fileObj.size > maxFileSize) {
432
454
  throw Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
433
455
  }
456
+ totalBytes += fileObj.size;
457
+ if (totalBytes > maxTotalBytes) {
458
+ throw Object.assign(new Error(`Total upload size exceeds ${maxTotalBytes} bytes`), { status: 413 });
459
+ }
434
460
  const mime = (fileObj.type || '').split(';')[0]!.trim().toLowerCase();
435
461
  if (allowed && !allowed.has(mime)) {
436
462
  throw Object.assign(new Error(`Unsupported file type: ${fileObj.type || 'unknown'}`), { status: 415 });
package/src/core/radix.ts CHANGED
@@ -190,10 +190,12 @@ export class RadixNode {
190
190
  }
191
191
 
192
192
  const pVar = `pL${level}`;
193
- code += `${indent}const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
193
+ code += `${indent}if (slash${level} > ${idxPrefix}) {\n`;
194
+ code += `${indent} const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
194
195
 
195
196
  const newAccumulator = [...paramAccumulator, { name: this.paramName!, varName: pVar }];
196
197
  code += pNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newAccumulator);
198
+ code += `${indent}}\n`;
197
199
  }
198
200
 
199
201
  // 3. Wildcard Node Logic (Catch-All *)