barejs 0.1.50 → 0.1.52

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 } 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';
@@ -6,6 +6,15 @@ import { join } from "node:path";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { bootstrapConfig } from "./loader";
8
8
  import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
9
+ import type { RouteSchemas } from "../security/validators";
10
+ import type { RouteSchema } from "../client/index";
11
+
12
+ export interface CronOptions {
13
+ /** Execute the cron job immediately upon registration (default: false) */
14
+ runOnStart?: boolean;
15
+ /** Optional error handler when the cron callback throws or rejects */
16
+ onError?: (err: any) => void;
17
+ }
9
18
 
10
19
  export interface WebSocketRouteHandler {
11
20
  open?: (ws: any) => void;
@@ -19,18 +28,53 @@ export interface NotFoundResponse {
19
28
  message: string;
20
29
  [key: string]: any;
21
30
  }
22
- export class BareJS extends BareRouter {
31
+
32
+ type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (
33
+ ctx: Context & Derived & {
34
+ body: S extends { body: infer B } ? InferSchema<B> : any;
35
+ query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
36
+ params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
37
+ }
38
+ ) => Res | Promise<Res>;
39
+
40
+ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
41
+ <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
42
+ path: P,
43
+ schemas: S,
44
+ handler: TypedRouteHandler<Derived, S, Res>
45
+ ): BareJS<Derived, Routes & Record<`${M} ${P}`, {
46
+ method: M;
47
+ path: P;
48
+ params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
49
+ query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
50
+ headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
51
+ body: S extends { body: infer B } ? InferSchema<B> : any;
52
+ response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
53
+ }>>;
54
+ <P extends string, Res = any>(
55
+ path: P,
56
+ ...handlers: any[]
57
+ ): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
58
+ };
59
+
60
+ export class BareJS<
61
+ Derived extends Record<string, any> = {},
62
+ Routes extends RouteSchema = {}
63
+ > extends BareRouter<Routes> {
64
+ declare readonly __routes: Routes;
23
65
  private tree = new RadixNode();
24
66
  private pool: Context[] = [];
25
67
  // private poolIdx = 0;
26
- private hotFetch?: (req: Request) => any;
68
+ private hotFetch?: (req: Request, peerIp?: string) => any;
27
69
  private compiled = false;
28
70
  private poolMask: number;
29
71
  private _useLog: boolean = false;
72
+ private _trustProxy: boolean = true;
30
73
  private errorHandler?: (err: any, ctx: Context) => any;
31
74
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
32
75
  private startHooks: (() => void | Promise<void>)[] = [];
33
76
  private stopHooks: (() => void | Promise<void>)[] = [];
77
+ private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
34
78
  private server?: ReturnType<typeof Bun.serve>;
35
79
  private shutdownHandler?: () => Promise<void>;
36
80
  private wsAdapter = {
@@ -55,7 +99,42 @@ export class BareJS extends BareRouter {
55
99
  return this;
56
100
  }
57
101
 
102
+ /**
103
+ * Built-in overlap-safe background interval scheduler.
104
+ * Automatically cleared when app.stop() is called.
105
+ */
106
+ public cron(
107
+ name: string,
108
+ intervalMs: number,
109
+ fn: () => void | Promise<void>,
110
+ options: CronOptions = {}
111
+ ): this {
112
+ let running = false;
113
+ const tick = async () => {
114
+ if (running) return;
115
+ running = true;
116
+ try {
117
+ await fn();
118
+ } catch (err) {
119
+ options.onError?.(err);
120
+ } finally {
121
+ running = false;
122
+ }
123
+ };
124
+ const timer = setInterval(tick, intervalMs);
125
+ this.crons.push({ name, timer });
126
+ if (options.runOnStart) {
127
+ void tick();
128
+ }
129
+ return this;
130
+ }
131
+
58
132
  public async stop(closeActiveConnections = false): Promise<void> {
133
+ for (const c of this.crons) {
134
+ clearInterval(c.timer);
135
+ }
136
+ this.crons.length = 0;
137
+
59
138
  if (this.shutdownHandler) {
60
139
  process.off("SIGINT", this.shutdownHandler);
61
140
  process.off("SIGTERM", this.shutdownHandler);
@@ -178,8 +257,28 @@ export class BareJS extends BareRouter {
178
257
  }
179
258
 
180
259
 
260
+ declare public get: AddRoute<Derived, Routes, 'GET'>;
261
+ declare public post: AddRoute<Derived, Routes, 'POST'>;
262
+ declare public put: AddRoute<Derived, Routes, 'PUT'>;
263
+ declare public patch: AddRoute<Derived, Routes, 'PATCH'>;
264
+ declare public delete: AddRoute<Derived, Routes, 'DELETE'>;
265
+ declare public options: AddRoute<Derived, Routes, 'OPTIONS'>;
266
+ declare public head: AddRoute<Derived, Routes, 'HEAD'>;
267
+ declare public all: AddRoute<Derived, Routes, 'ALL'>;
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
+
274
+ declare public use: {
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>>;
277
+ (mw: any): BareJS<Derived, Routes>;
278
+ };
279
+
181
280
  private _hasDerive = false;
182
- public derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T): this {
281
+ public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
183
282
  this._hasDerive = true;
184
283
  this.use(async (ctx: any, next: any) => {
185
284
  const derived = await fn(ctx);
@@ -196,7 +295,7 @@ export class BareJS extends BareRouter {
196
295
  }
197
296
  return next();
198
297
  });
199
- return this;
298
+ return this as any;
200
299
  }
201
300
 
202
301
  // inherited use() from BareRouter handles router merging now
@@ -224,11 +323,31 @@ export class BareJS extends BareRouter {
224
323
  };
225
324
  }
226
325
 
326
+ const cbMw = pipeline.find((fn) => fn?.__circuitBreaker);
327
+ if (cbMw) {
328
+ const runWithBreaker = cbMw.__circuitBreaker;
329
+ const innerPipeline = pipeline.filter((fn) => !fn?.__circuitBreaker);
330
+ const innerCompiled = this.compileHandler(innerPipeline, isLog);
331
+ return (ctx: Context, doLog?: any) => runWithBreaker(() => innerCompiled(ctx, doLog));
332
+ }
333
+
334
+ const compMw = pipeline.find((fn) => fn?.__compress);
335
+ if (compMw) {
336
+ const applyCompress = compMw.__compress;
337
+ const innerPipeline = pipeline.filter((fn) => !fn?.__compress);
338
+ const innerCompiled = this.compileHandler(innerPipeline, isLog);
339
+ return async (ctx: Context, doLog?: any) => {
340
+ const res = await innerCompiled(ctx, doLog);
341
+ return applyCompress(ctx, res);
342
+ };
343
+ }
344
+
227
345
  const len = pipeline.length;
228
346
  const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
229
347
  const rFilter = rFilterMw?.__responseFilter;
230
348
  const idemMw = pipeline.find((fn) => fn?.__idempotencyCommit);
231
349
  const idemCommit = idemMw?.__idempotencyCommit;
350
+ const idemRelease = idemMw?.__idempotencyRelease;
232
351
 
233
352
  // Static ResponseInit for 200 OK (Zero Allocation)
234
353
  const json200 = { status: 200, headers: { "content-type": "application/json" } };
@@ -241,6 +360,7 @@ export class BareJS extends BareRouter {
241
360
  const finalizeCode = `
242
361
  ${rFilter ? 'res = rFilter(res);' : ''}
243
362
  if (res instanceof Response) {
363
+ ${idemCommit ? 'idemCommit(ctx, res, res.status);' : ''}
244
364
  if (ctx._headers) {
245
365
  for (const k in ctx._headers) {
246
366
  if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
@@ -268,12 +388,17 @@ export class BareJS extends BareRouter {
268
388
  });
269
389
  }
270
390
  } else if (finalStatus === 200 && !ctx._headers) {
271
- 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);
272
394
  } else {
273
- outRes = Response.json(res ?? null, {
274
- status: finalStatus,
275
- headers: ctx._headers || json200.headers
276
- });
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);
277
402
  }
278
403
 
279
404
  if (ctx._setCookies) {
@@ -284,19 +409,56 @@ export class BareJS extends BareRouter {
284
409
 
285
410
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
286
411
 
412
+ const extraNames = [
413
+ ...(rFilter ? ['rFilter'] : []),
414
+ ...(idemCommit ? ['idemCommit'] : []),
415
+ ...(idemRelease ? ['idemRelease'] : [])
416
+ ];
417
+ const extraVals = [
418
+ ...(rFilter ? [rFilter] : []),
419
+ ...(idemCommit ? [idemCommit] : []),
420
+ ...(idemRelease ? [idemRelease] : [])
421
+ ];
422
+
423
+ const wrapIdem = (compiled: Function): Function => {
424
+ if (!idemRelease) return compiled;
425
+ return (ctx: Context, doLog?: any) => {
426
+ try {
427
+ const out = compiled(ctx, doLog);
428
+ if (out && typeof out.then === 'function') {
429
+ return out.then(
430
+ (v: any) => v,
431
+ (err: any) => {
432
+ idemRelease(ctx);
433
+ throw err;
434
+ }
435
+ );
436
+ }
437
+ return out;
438
+ } catch (err) {
439
+ idemRelease(ctx);
440
+ throw err;
441
+ }
442
+ };
443
+ };
444
+
287
445
  if (len === 1) {
288
446
  const fn0 = pipeline[0]!;
289
447
  if (fn0.constructor.name === 'AsyncFunction') {
290
- return new Function('fn0', 'json200', 'text200', `return async function(${argSig}) {
291
- const res = await fn0(ctx);
292
- ${finalizeCode}
293
- }`)(fn0, json200, text200);
448
+ return wrapIdem(
449
+ new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return async function(${argSig}) {
450
+ const res = await fn0(ctx);
451
+ ${finalizeCode}
452
+ }`)(fn0, json200, text200, ...extraVals)
453
+ );
294
454
  }
295
- return new Function('fn0', 'json200', 'text200', `return function(${argSig}) {
296
- const res = fn0(ctx);
297
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
298
- ${finalizeCode}
299
- }`)(fn0, json200, text200);
455
+ return wrapIdem(
456
+ new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return function(${argSig}) {
457
+ const res = fn0(ctx);
458
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
459
+ ${finalizeCode}
460
+ }`)(fn0, json200, text200, ...extraVals)
461
+ );
300
462
  }
301
463
 
302
464
  // Check async
@@ -333,10 +495,12 @@ export class BareJS extends BareRouter {
333
495
 
334
496
  const noop = () => { };
335
497
  const fnHeader = isAsync
336
- ? `return async function(${argSig})`
337
- : `return function(${argSig})`;
498
+ ? `let lastHdrs = null, lastInit200 = null; return async function(${argSig})`
499
+ : `let lastHdrs = null, lastInit200 = null; return function(${argSig})`;
338
500
 
339
- return new Function(...fnNames, 'noop', 'json200', 'text200', ...(rFilter ? ['rFilter'] : []), ...(idemCommit ? ['idemCommit'] : []), `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...(rFilter ? [rFilter] : []), ...(idemCommit ? [idemCommit] : []));
501
+ return wrapIdem(
502
+ new Function(...fnNames, 'noop', 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...extraVals)
503
+ );
340
504
  }
341
505
 
342
506
  public compile() {
@@ -351,25 +515,49 @@ export class BareJS extends BareRouter {
351
515
  const maxPool = pool.length;
352
516
  const hNotFound = this.notFoundHandler;
353
517
  const customError = this.errorHandler;
354
- 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> => {
355
543
  if (customError) {
356
544
  const res = customError(err, ctx);
357
- if (res instanceof Response) return res;
358
- const status = ctx._status >= 400 ? ctx._status : 500;
359
- if (typeof res === 'string') return new Response(res, { status });
360
- 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);
361
549
  }
362
550
  if (err?.status >= 400 && err?.status < 500) {
363
- return Response.json({
551
+ return applyCtxHeaders(Response.json({
364
552
  status: err.status,
365
553
  message: err.message || 'Bad Request'
366
- }, { status: err.status });
554
+ }, { status: err.status }), ctx);
367
555
  }
368
- return Response.json({
556
+ return applyCtxHeaders(Response.json({
369
557
  status: 500,
370
558
  message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
371
559
  stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
372
- }, { status: 500 });
560
+ }, { status: 500 }), ctx);
373
561
  };
374
562
 
375
563
  const hoistedHandlers: Function[] = [];
@@ -403,15 +591,22 @@ export class BareJS extends BareRouter {
403
591
  ctx._setCookies = undefined;
404
592
  ctx._headers = undefined;
405
593
  ctx._requestId = undefined;
594
+ ctx._peerIp = undefined;
406
595
  ctx.params = EMPTY_PARAMS;
407
596
  if (poolTop < maxPool) pool[poolTop++] = ctx;
408
597
  `;
409
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
+
410
605
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
411
606
  const routerCode = rawRouterCode.replace(
412
607
  /return (h\d+)\(ctx\);/g,
413
608
  `out = $1${callSuffix};
414
- 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} });
415
610
  ${releaseCode}
416
611
  return out;`
417
612
  );
@@ -421,7 +616,7 @@ export class BareJS extends BareRouter {
421
616
  const optionsFallback = hasGlobalMw
422
617
  ? `if (method === 'OPTIONS') {
423
618
  out = hOptions${callSuffix};
424
- 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} });
425
620
  ${releaseCode}
426
621
  return out;
427
622
  }`
@@ -456,21 +651,20 @@ export class BareJS extends BareRouter {
456
651
  if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
457
652
  const errorBody = hNotFound();
458
653
  const status = errorBody.status || 404;
654
+ const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
459
655
  ${isLog ? 'doLog(status);' : ''}
460
656
  ${releaseCode}
461
- return Response.json(errorBody, { status });
657
+ return nfRes;
462
658
  }, (e) => {
463
- const errRes = hError(e, ctx);
464
- ${releaseCode}
465
- ${isLog ? 'doLog(errRes.status || 500);' : ''}
466
- return errRes;
659
+ ${handleErrCode}
467
660
  });
468
661
  }
469
662
  }`
470
663
  : '';
471
664
 
472
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
473
- const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
665
+ const trustProxyVal = this._trustProxy;
666
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyVal', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
667
+ const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyVal, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
474
668
 
475
669
  const logInit = isLog ? `
476
670
  const start = performance.now();
@@ -487,7 +681,7 @@ export class BareJS extends BareRouter {
487
681
 
488
682
  const fnBody = `
489
683
  let poolTop = maxPool;
490
- return function(req) {
684
+ return function(req, peerIp) {
491
685
  const url = req.url;
492
686
  let s = url.indexOf('/', 8);
493
687
  const q = s === -1 ? -1 : url.indexOf('?', s);
@@ -496,12 +690,13 @@ export class BareJS extends BareRouter {
496
690
  else s = urlLen;
497
691
 
498
692
  const method = req.method;
499
- const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
693
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyVal);
500
694
  let out;
501
695
  ${logInit}
502
696
 
503
697
  try {
504
698
  ctx.req = req;
699
+ ctx._peerIp = peerIp;
505
700
 
506
701
  ${routerCode}
507
702
 
@@ -511,15 +706,13 @@ export class BareJS extends BareRouter {
511
706
 
512
707
  const errorBody = hNotFound();
513
708
  const status = errorBody.status || 404;
709
+ const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
514
710
  ${isLog ? 'doLog(status);' : ''}
515
711
  ${releaseCode}
516
- return Response.json(errorBody, { status });
712
+ return nfRes;
517
713
 
518
714
  } catch (e) {
519
- const errRes = hError(e, ctx);
520
- ${isLog ? 'doLog(errRes.status || 500);' : ''}
521
- ${releaseCode}
522
- return errRes;
715
+ ${handleErrCode}
523
716
  }
524
717
  }
525
718
  `;
@@ -529,22 +722,52 @@ export class BareJS extends BareRouter {
529
722
  this.fetch = this.hotFetch!;
530
723
  }
531
724
 
532
- public fetch = (req: Request): any => {
725
+ public fetch = (req: Request, peerIp?: string): any => {
533
726
  if (!this.compiled) {
534
727
  this.compile();
535
- return this.hotFetch!(req);
728
+ return this.hotFetch!(req, peerIp);
536
729
  }
537
- return this.hotFetch!(req);
730
+ return this.hotFetch!(req, peerIp);
538
731
  };
732
+
733
+ /**
734
+ * Ergonomic in-memory request helper for testing or internal invocations.
735
+ * Normalizes relative paths to http://localhost and delegates to this.fetch(req).
736
+ */
737
+ public async request(path: string, init?: RequestInit): Promise<Response> {
738
+ let url: string;
739
+ if (path.startsWith('http://') || path.startsWith('https://')) {
740
+ url = path;
741
+ } else {
742
+ const normalized = path.startsWith('/') ? path : `/${path}`;
743
+ url = `http://localhost${normalized}`;
744
+ }
745
+ return this.fetch(new Request(url, init));
746
+ }
539
747
  public name: string = "App";
540
748
 
541
- public listen(port?: number, hostname: string = '0.0.0.0', reusePort: boolean = true) {
542
- if (!this.compiled) this.compile();
749
+ public trustProxy(enabled: boolean = true): this {
750
+ this._trustProxy = enabled;
751
+ for (let i = 0; i < this.pool.length; i++) {
752
+ this.pool[i]!._trustProxy = enabled;
753
+ }
754
+ return this;
755
+ }
543
756
 
757
+ public listen(
758
+ port?: number,
759
+ hostname: string = '0.0.0.0',
760
+ reusePort: boolean = true,
761
+ options: { maxRequestBodySize?: number; trustProxy?: boolean } = {}
762
+ ) {
763
+ if (!this.compiled) this.compile();
764
+ if (options.trustProxy !== undefined) {
765
+ this.trustProxy(options.trustProxy);
766
+ }
767
+ const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
544
768
 
545
769
  const { BARE_CONFIG } = require("./config");
546
770
 
547
-
548
771
  const finalPort = port || BARE_CONFIG.port || 3000;
549
772
  const isProd = process.env.NODE_ENV === 'production';
550
773
 
@@ -571,19 +794,48 @@ export class BareJS extends BareRouter {
571
794
  port: finalPort,
572
795
  hostname,
573
796
  reusePort,
797
+ maxRequestBodySize,
574
798
  fetch(req: Request, srv: any) {
575
- if (req.headers.get('upgrade') === 'websocket') {
799
+ if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
576
800
  const url = req.url;
577
801
  const s = url.indexOf('/', 8);
578
802
  const q = s === -1 ? -1 : url.indexOf('?', s);
579
803
  const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
580
804
  const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
581
- const handler = wsRoutes.get(normalized);
582
- if (handler && srv.upgrade(req, { data: handler })) {
805
+ let handler = wsRoutes.get(normalized);
806
+ let params: Record<string, string> | undefined;
807
+ if (!handler) {
808
+ const reqParts = normalized.split('/').filter(Boolean);
809
+ for (const [pattern, h] of wsRoutes) {
810
+ if (!pattern.includes(':') && !pattern.includes('*')) continue;
811
+ const patParts = pattern.split('/').filter(Boolean);
812
+ const matched: Record<string, string> = {};
813
+ let ok = true;
814
+ for (let i = 0; i < patParts.length; i++) {
815
+ const pp = patParts[i]!;
816
+ if (pp === '*') {
817
+ matched['*'] = reqParts.slice(i).join('/');
818
+ break;
819
+ }
820
+ if (i >= reqParts.length) { ok = false; break; }
821
+ if (pp.startsWith(':')) {
822
+ matched[pp.slice(1)] = reqParts[i]!;
823
+ } else if (pp !== reqParts[i]) {
824
+ ok = false; break;
825
+ }
826
+ }
827
+ if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
828
+ handler = h;
829
+ params = matched;
830
+ break;
831
+ }
832
+ }
833
+ }
834
+ if (handler && srv.upgrade(req, { data: params ? { ...handler, params } : handler })) {
583
835
  return undefined as any;
584
836
  }
585
837
  }
586
- return baseFetch(req);
838
+ return baseFetch(req, srv?.requestIP?.(req)?.address);
587
839
  },
588
840
  websocket: this.wsAdapter
589
841
  })
@@ -591,7 +843,10 @@ export class BareJS extends BareRouter {
591
843
  port: finalPort,
592
844
  hostname,
593
845
  reusePort,
594
- fetch: baseFetch
846
+ maxRequestBodySize,
847
+ fetch(req: Request, srv: any) {
848
+ return baseFetch(req, srv?.requestIP?.(req)?.address);
849
+ }
595
850
  });
596
851
 
597
852
  this.server = server;