barejs 0.1.51 → 0.1.54

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/src/core/bare.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BareRouter, type InferSchema } from './router';
1
+ import { BareRouter, type InferSchema, type PrefixRoutes } from './router';
2
2
  import { RadixNode } from './radix';
3
3
  import { Context } from './context';
4
4
  import { Type as typebox, Type as t } from '@sinclair/typebox';
@@ -65,10 +65,11 @@ export class BareJS<
65
65
  private tree = new RadixNode();
66
66
  private pool: Context[] = [];
67
67
  // private poolIdx = 0;
68
- private hotFetch?: (req: Request) => any;
68
+ private hotFetch?: (req: Request, peerIp?: string) => any;
69
69
  private compiled = false;
70
70
  private poolMask: number;
71
71
  private _useLog: boolean = false;
72
+ private _trustProxy: boolean = true;
72
73
  private errorHandler?: (err: any, ctx: Context) => any;
73
74
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
74
75
  private startHooks: (() => void | Promise<void>)[] = [];
@@ -265,8 +266,14 @@ export class BareJS<
265
266
  declare public head: AddRoute<Derived, Routes, 'HEAD'>;
266
267
  declare public all: AddRoute<Derived, Routes, 'ALL'>;
267
268
 
269
+ declare public route: <P extends string, R2 extends RouteSchema = {}>(
270
+ prefix: P,
271
+ router: BareRouter<R2>
272
+ ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
273
+
268
274
  declare public use: {
269
275
  <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
276
+ <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
270
277
  (mw: any): BareJS<Derived, Routes>;
271
278
  };
272
279
 
@@ -353,7 +360,7 @@ export class BareJS<
353
360
  const finalizeCode = `
354
361
  ${rFilter ? 'res = rFilter(res);' : ''}
355
362
  if (res instanceof Response) {
356
- ${idemRelease ? 'idemRelease(ctx);' : ''}
363
+ ${idemCommit ? 'idemCommit(ctx, res, res.status);' : ''}
357
364
  if (ctx._headers) {
358
365
  for (const k in ctx._headers) {
359
366
  if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
@@ -381,12 +388,17 @@ export class BareJS<
381
388
  });
382
389
  }
383
390
  } else if (finalStatus === 200 && !ctx._headers) {
384
- outRes = Response.json(res ?? null, json200);
391
+ outRes = Response.json(res ?? null);
392
+ } else if (finalStatus === 200 && ctx._headers === lastHdrs) {
393
+ outRes = Response.json(res ?? null, lastInit200);
385
394
  } else {
386
- outRes = Response.json(res ?? null, {
387
- status: finalStatus,
388
- headers: ctx._headers || json200.headers
389
- });
395
+ const hdrs = ctx._headers || json200.headers;
396
+ const init = { status: finalStatus, headers: hdrs };
397
+ if (finalStatus === 200 && Object.isFrozen(hdrs)) {
398
+ lastHdrs = hdrs;
399
+ lastInit200 = init;
400
+ }
401
+ outRes = Response.json(res ?? null, init);
390
402
  }
391
403
 
392
404
  if (ctx._setCookies) {
@@ -434,14 +446,14 @@ export class BareJS<
434
446
  const fn0 = pipeline[0]!;
435
447
  if (fn0.constructor.name === 'AsyncFunction') {
436
448
  return wrapIdem(
437
- new Function('fn0', 'json200', 'text200', ...extraNames, `return async function(${argSig}) {
449
+ new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return async function(${argSig}) {
438
450
  const res = await fn0(ctx);
439
451
  ${finalizeCode}
440
452
  }`)(fn0, json200, text200, ...extraVals)
441
453
  );
442
454
  }
443
455
  return wrapIdem(
444
- new Function('fn0', 'json200', 'text200', ...extraNames, `return function(${argSig}) {
456
+ new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return function(${argSig}) {
445
457
  const res = fn0(ctx);
446
458
  if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
447
459
  ${finalizeCode}
@@ -483,8 +495,8 @@ export class BareJS<
483
495
 
484
496
  const noop = () => { };
485
497
  const fnHeader = isAsync
486
- ? `return async function(${argSig})`
487
- : `return function(${argSig})`;
498
+ ? `let lastHdrs = null, lastInit200 = null; return async function(${argSig})`
499
+ : `let lastHdrs = null, lastInit200 = null; return function(${argSig})`;
488
500
 
489
501
  return wrapIdem(
490
502
  new Function(...fnNames, 'noop', 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...extraVals)
@@ -503,25 +515,49 @@ export class BareJS<
503
515
  const maxPool = pool.length;
504
516
  const hNotFound = this.notFoundHandler;
505
517
  const customError = this.errorHandler;
506
- const hError = (err: any, ctx: Context) => {
518
+ const applyCtxHeaders = (res: Response, ctx: Context): Response => {
519
+ if (ctx._headers) {
520
+ for (const k in ctx._headers) {
521
+ const val = ctx._headers[k];
522
+ if (val !== undefined && !res.headers.has(k)) {
523
+ try { res.headers.set(k, val); } catch { /* ignore invalid header values on error path */ }
524
+ }
525
+ }
526
+ }
527
+ if (ctx._setCookies) {
528
+ for (let i = 0; i < ctx._setCookies.length; i++) {
529
+ try { res.headers.append('Set-Cookie', ctx._setCookies[i]!); } catch { /* ignore */ }
530
+ }
531
+ }
532
+ return res;
533
+ };
534
+
535
+ const formatCustomError = (res: any, ctx: Context): Response => {
536
+ if (res instanceof Response) return applyCtxHeaders(res, ctx);
537
+ const status = ctx._status >= 400 ? ctx._status : 500;
538
+ if (typeof res === 'string') return applyCtxHeaders(new Response(res, { status }), ctx);
539
+ return applyCtxHeaders(Response.json(res ?? null, { status }), ctx);
540
+ };
541
+
542
+ const hError = (err: any, ctx: Context): Response | Promise<Response> => {
507
543
  if (customError) {
508
544
  const res = customError(err, ctx);
509
- if (res instanceof Response) return res;
510
- const status = ctx._status >= 400 ? ctx._status : 500;
511
- if (typeof res === 'string') return new Response(res, { status });
512
- return Response.json(res ?? null, { status });
545
+ if (res && typeof res.then === 'function') {
546
+ return res.then((resolved: any) => formatCustomError(resolved, ctx));
547
+ }
548
+ return formatCustomError(res, ctx);
513
549
  }
514
550
  if (err?.status >= 400 && err?.status < 500) {
515
- return Response.json({
551
+ return applyCtxHeaders(Response.json({
516
552
  status: err.status,
517
553
  message: err.message || 'Bad Request'
518
- }, { status: err.status });
554
+ }, { status: err.status }), ctx);
519
555
  }
520
- return Response.json({
556
+ return applyCtxHeaders(Response.json({
521
557
  status: 500,
522
558
  message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
523
559
  stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
524
- }, { status: 500 });
560
+ }, { status: 500 }), ctx);
525
561
  };
526
562
 
527
563
  const hoistedHandlers: Function[] = [];
@@ -555,15 +591,22 @@ export class BareJS<
555
591
  ctx._setCookies = undefined;
556
592
  ctx._headers = undefined;
557
593
  ctx._requestId = undefined;
594
+ ctx._peerIp = undefined;
558
595
  ctx.params = EMPTY_PARAMS;
559
596
  if (poolTop < maxPool) pool[poolTop++] = ctx;
560
597
  `;
561
598
 
599
+ const handleErrCode = `const errRes = hError(e, ctx);
600
+ if (errRes && errRes.then) return errRes.then((r) => { ${isLog ? 'doLog(r.status || 500);' : ''} ${releaseCode} return r; });
601
+ ${isLog ? 'doLog(errRes.status || 500);' : ''}
602
+ ${releaseCode}
603
+ return errRes;`;
604
+
562
605
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
563
606
  const routerCode = rawRouterCode.replace(
564
607
  /return (h\d+)\(ctx\);/g,
565
608
  `out = $1${callSuffix};
566
- 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; });
609
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
567
610
  ${releaseCode}
568
611
  return out;`
569
612
  );
@@ -573,30 +616,23 @@ export class BareJS<
573
616
  const optionsFallback = hasGlobalMw
574
617
  ? `if (method === 'OPTIONS') {
575
618
  out = hOptions${callSuffix};
576
- 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; });
619
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
577
620
  ${releaseCode}
578
621
  return out;
579
622
  }`
580
623
  : '';
581
624
 
582
- const staticMws = this.groupMiddleware.filter((m: any) => m.__isStatic);
583
- const hasStaticMw = staticMws.length > 0;
625
+ const hasStaticMw = this.groupMiddleware.some((m: any) => m.__isStatic);
584
626
  const runStatic = hasStaticMw
585
627
  ? async (ctx: Context) => {
586
- const noop = () => {};
587
- for (let i = 0; i < staticMws.length; i++) {
588
- const r = await staticMws[i](ctx, noop);
589
- if (r instanceof Response) {
590
- if (ctx._headers) {
591
- for (const k in ctx._headers) {
592
- const val = ctx._headers[k];
593
- if (val !== undefined && !r.headers.has(k)) r.headers.set(k, val);
594
- }
595
- }
596
- return r;
597
- }
598
- }
599
- return undefined;
628
+ const mws = this.groupMiddleware;
629
+ const dispatch = async (idx: number): Promise<Response | undefined> => {
630
+ if (idx >= mws.length) return undefined;
631
+ const r = await mws[idx](ctx, () => dispatch(idx + 1));
632
+ if (r instanceof Response) return applyCtxHeaders(r, ctx);
633
+ return undefined;
634
+ };
635
+ return dispatch(0);
600
636
  }
601
637
  : undefined;
602
638
 
@@ -608,21 +644,20 @@ export class BareJS<
608
644
  if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
609
645
  const errorBody = hNotFound();
610
646
  const status = errorBody.status || 404;
647
+ const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
611
648
  ${isLog ? 'doLog(status);' : ''}
612
649
  ${releaseCode}
613
- return Response.json(errorBody, { status });
650
+ return nfRes;
614
651
  }, (e) => {
615
- const errRes = hError(e, ctx);
616
- ${releaseCode}
617
- ${isLog ? 'doLog(errRes.status || 500);' : ''}
618
- return errRes;
652
+ ${handleErrCode}
619
653
  });
620
654
  }
621
655
  }`
622
656
  : '';
623
657
 
624
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
625
- const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
658
+ const trustProxyVal = this._trustProxy;
659
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyVal', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
660
+ const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyVal, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
626
661
 
627
662
  const logInit = isLog ? `
628
663
  const start = performance.now();
@@ -639,7 +674,7 @@ export class BareJS<
639
674
 
640
675
  const fnBody = `
641
676
  let poolTop = maxPool;
642
- return function(req) {
677
+ return function(req, peerIp) {
643
678
  const url = req.url;
644
679
  let s = url.indexOf('/', 8);
645
680
  const q = s === -1 ? -1 : url.indexOf('?', s);
@@ -648,12 +683,13 @@ export class BareJS<
648
683
  else s = urlLen;
649
684
 
650
685
  const method = req.method;
651
- const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
686
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyVal);
652
687
  let out;
653
688
  ${logInit}
654
689
 
655
690
  try {
656
691
  ctx.req = req;
692
+ ctx._peerIp = peerIp;
657
693
 
658
694
  ${routerCode}
659
695
 
@@ -663,15 +699,13 @@ export class BareJS<
663
699
 
664
700
  const errorBody = hNotFound();
665
701
  const status = errorBody.status || 404;
702
+ const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
666
703
  ${isLog ? 'doLog(status);' : ''}
667
704
  ${releaseCode}
668
- return Response.json(errorBody, { status });
705
+ return nfRes;
669
706
 
670
707
  } catch (e) {
671
- const errRes = hError(e, ctx);
672
- ${isLog ? 'doLog(errRes.status || 500);' : ''}
673
- ${releaseCode}
674
- return errRes;
708
+ ${handleErrCode}
675
709
  }
676
710
  }
677
711
  `;
@@ -681,16 +715,32 @@ export class BareJS<
681
715
  this.fetch = this.hotFetch!;
682
716
  }
683
717
 
684
- public fetch = (req: Request): any => {
718
+ public fetch = (req: Request, peerIp?: string): any => {
685
719
  if (!this.compiled) {
686
720
  this.compile();
687
- return this.hotFetch!(req);
721
+ return this.hotFetch!(req, peerIp);
688
722
  }
689
- return this.hotFetch!(req);
723
+ return this.hotFetch!(req, peerIp);
690
724
  };
725
+
726
+ /**
727
+ * Ergonomic in-memory request helper for testing or internal invocations.
728
+ * Normalizes relative paths to http://localhost and delegates to this.fetch(req).
729
+ */
730
+ public async request(path: string, init?: RequestInit): Promise<Response> {
731
+ let url: string;
732
+ if (path.startsWith('http://') || path.startsWith('https://')) {
733
+ url = path;
734
+ } else {
735
+ const normalized = path.startsWith('/') ? path : `/${path}`;
736
+ url = `http://localhost${normalized}`;
737
+ }
738
+ return this.fetch(new Request(url, init));
739
+ }
691
740
  public name: string = "App";
692
741
 
693
742
  public trustProxy(enabled: boolean = true): this {
743
+ this._trustProxy = enabled;
694
744
  for (let i = 0; i < this.pool.length; i++) {
695
745
  this.pool[i]!._trustProxy = enabled;
696
746
  }
@@ -778,7 +828,7 @@ export class BareJS<
778
828
  return undefined as any;
779
829
  }
780
830
  }
781
- return baseFetch(req);
831
+ return baseFetch(req, srv?.requestIP?.(req)?.address);
782
832
  },
783
833
  websocket: this.wsAdapter
784
834
  })
@@ -787,7 +837,9 @@ export class BareJS<
787
837
  hostname,
788
838
  reusePort,
789
839
  maxRequestBodySize,
790
- fetch: baseFetch
840
+ fetch(req: Request, srv: any) {
841
+ return baseFetch(req, srv?.requestIP?.(req)?.address);
842
+ }
791
843
  });
792
844
 
793
845
  this.server = server;
@@ -54,7 +54,9 @@ export class Context {
54
54
  public _requestId: string | undefined = undefined;
55
55
  public _peerIp: string | undefined = undefined;
56
56
  public _trustProxy: boolean = true;
57
- constructor() { }
57
+ constructor(trustProxy: boolean = true) {
58
+ this._trustProxy = trustProxy;
59
+ }
58
60
 
59
61
  public get query(): Record<string, string> {
60
62
  if (this._query !== undefined) return this._query;
@@ -65,6 +67,8 @@ export class Context {
65
67
  if (qIdx !== -1) {
66
68
  let start = qIdx + 1;
67
69
  const len = url.length;
70
+ const hasPlus = url.indexOf('+', start) !== -1;
71
+ const hasPct = url.indexOf('%', start) !== -1;
68
72
  while (start < len) {
69
73
  let amp = url.indexOf('&', start);
70
74
  if (amp === -1) amp = len;
@@ -79,13 +83,17 @@ export class Context {
79
83
  k = url.slice(start, amp);
80
84
  v = '';
81
85
  }
82
- if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
83
- if (k.indexOf('%') !== -1) {
84
- try { k = decodeURIComponent(k); } catch { /* keep raw */ }
86
+ if (hasPlus) {
87
+ if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
88
+ if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
85
89
  }
86
- if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
87
- if (v.indexOf('%') !== -1) {
88
- try { v = decodeURIComponent(v); } catch { /* keep raw */ }
90
+ if (hasPct) {
91
+ if (k.indexOf('%') !== -1) {
92
+ try { k = decodeURIComponent(k); } catch { /* keep raw */ }
93
+ }
94
+ if (v.indexOf('%') !== -1) {
95
+ try { v = decodeURIComponent(v); } catch { /* keep raw */ }
96
+ }
89
97
  }
90
98
  if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
91
99
  result[k] = v;
@@ -100,7 +108,8 @@ export class Context {
100
108
  }
101
109
 
102
110
  public getQuery(key: string): string | undefined {
103
- return this.query[key];
111
+ const q = this.query;
112
+ return Object.hasOwn(q, key) ? q[key] : undefined;
104
113
  }
105
114
 
106
115
  public get cookies(): Record<string, string> {
@@ -132,13 +141,23 @@ export class Context {
132
141
  }
133
142
 
134
143
  public setCookie(name: string, value: string, options: CookieOptions = {}): this {
144
+ if (!name || /[\r\n;= \t]/.test(name)) {
145
+ throw new Error('Invalid cookie name');
146
+ }
147
+ const path = options.path ?? '/';
148
+ if (/[\r\n;]/.test(path)) {
149
+ throw new Error('Invalid cookie path');
150
+ }
151
+ if (options.domain && /[\r\n;]/.test(options.domain)) {
152
+ throw new Error('Invalid cookie domain');
153
+ }
135
154
  let finalVal = value;
136
155
  if (options.secret) {
137
156
  const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
138
157
  finalVal = `${value}.${sig}`;
139
158
  }
140
159
  let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
141
- cookieStr += `; Path=${options.path ?? '/'}`;
160
+ cookieStr += `; Path=${path}`;
142
161
  if (options.domain) cookieStr += `; Domain=${options.domain}`;
143
162
  if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
144
163
  if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
@@ -181,16 +200,19 @@ export class Context {
181
200
  if (contentType && contentType.includes("application/json")) {
182
201
  const lenHeader = this.req.headers.get("content-length");
183
202
  if (lenHeader !== null) {
184
- const lenNum = Number(lenHeader);
185
- if (lenNum > maxBytes) {
186
- const err: any = new Error("Payload Too Large");
187
- err.status = 413;
188
- throw err;
189
- }
190
- try {
191
- return this.body = await this.req.json();
192
- } catch {
193
- return this.body = null;
203
+ const trimmed = lenHeader.trim();
204
+ const lenNum = trimmed.length > 0 ? Number(trimmed) : NaN;
205
+ if (Number.isInteger(lenNum) && lenNum >= 0) {
206
+ if (lenNum > maxBytes) {
207
+ const err: any = new Error("Payload Too Large");
208
+ err.status = 413;
209
+ throw err;
210
+ }
211
+ try {
212
+ return this.body = await this.req.json();
213
+ } catch {
214
+ return this.body = null;
215
+ }
194
216
  }
195
217
  }
196
218
  try {
@@ -228,28 +250,40 @@ export class Context {
228
250
  return this;
229
251
  }
230
252
 
253
+ private _applyCookies(res: Response): Response {
254
+ if (this._setCookies) {
255
+ for (let i = 0; i < this._setCookies.length; i++) {
256
+ res.headers.append('Set-Cookie', this._setCookies[i]!);
257
+ }
258
+ this._setCookies = undefined;
259
+ }
260
+ return res;
261
+ }
262
+
231
263
  public json(data: any): Response {
232
264
  const status = this._status || 200;
233
265
  let res: Response;
234
266
 
235
267
  if (!this._headers) {
236
- res = Response.json(data, { status });
268
+ res = status === 200
269
+ ? Response.json(data)
270
+ : Response.json(data, { status });
237
271
  } else {
238
- if (this._headers["content-type"] === undefined) {
239
- this._headers["content-type"] = "application/json";
272
+ let headers = this._headers;
273
+ if (headers["content-type"] === undefined) {
274
+ if (Object.isFrozen(headers)) {
275
+ headers = { ...headers };
276
+ this._headers = headers;
277
+ }
278
+ headers["content-type"] = "application/json";
240
279
  }
241
280
  res = Response.json(data, {
242
281
  status,
243
- headers: this._headers as any
282
+ headers: headers as any
244
283
  });
245
284
  }
246
285
 
247
- if (this._setCookies) {
248
- for (let i = 0; i < this._setCookies.length; i++) {
249
- res.headers.append('Set-Cookie', this._setCookies[i]!);
250
- }
251
- }
252
- return res;
286
+ return this._applyCookies(res);
253
287
  }
254
288
 
255
289
  public set(key: string, value: any): this {
@@ -288,7 +322,7 @@ export class Context {
288
322
  'content-type': 'text/html; charset=utf-8',
289
323
  ...(this._headers || {})
290
324
  };
291
- return new Response(content, { status: status ?? this._status, headers });
325
+ return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
292
326
  }
293
327
 
294
328
  public text(content: string, status?: number): Response {
@@ -296,7 +330,7 @@ export class Context {
296
330
  'content-type': 'text/plain; charset=utf-8',
297
331
  ...(this._headers || {})
298
332
  };
299
- return new Response(content, { status: status ?? this._status, headers });
333
+ return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
300
334
  }
301
335
 
302
336
  public redirect(url: string, status: number = 302): Response {
@@ -304,7 +338,7 @@ export class Context {
304
338
  'location': url,
305
339
  ...(this._headers || {})
306
340
  };
307
- return new Response(null, { status, headers });
341
+ return this._applyCookies(new Response(null, { status, headers }));
308
342
  }
309
343
 
310
344
  public sse(
@@ -360,7 +394,7 @@ export class Context {
360
394
  'connection': 'keep-alive',
361
395
  ...(this._headers || {})
362
396
  };
363
- return new Response(stream, { status: this._status || 200, headers });
397
+ return this._applyCookies(new Response(stream, { status: this._status || 200, headers }));
364
398
  }
365
399
 
366
400
  public get requestId(): string {
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 *)