barejs 0.2.8 → 0.2.9

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.
@@ -94,6 +94,12 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
94
94
  error: any;
95
95
  }>, Macros>;
96
96
  };
97
+ export interface BareJSOptions {
98
+ /** Context object pool size (default: 1024, max: 65536). */
99
+ poolSize?: number;
100
+ /** Base path prefix applied to all registered routes (e.g. '/api' for Next.js, Astro, SvelteKit). */
101
+ prefix?: string;
102
+ }
97
103
  export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> extends BareRouter<Routes> {
98
104
  readonly __routes: Routes;
99
105
  private tree;
@@ -140,9 +146,14 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
140
146
  stop(closeActiveConnections?: boolean): Promise<void>;
141
147
  private static readonly DEFAULT_POOL_SIZE;
142
148
  private static readonly MAX_POOL_SIZE;
143
- constructor(poolSize?: number);
149
+ constructor(poolSizeOrOptions?: number | BareJSOptions);
150
+ /**
151
+ * Set or append a base path prefix for all subsequently registered routes
152
+ * (e.g. `new BareJS().basePath('/api')` for Next.js / Astro / SvelteKit).
153
+ */
154
+ basePath(path: string): this;
144
155
  private notFoundHandler;
145
- setNotFound(handler: () => NotFoundResponse): void;
156
+ setNotFound(handler: () => NotFoundResponse): this;
146
157
  onError(handler: (err: any, ctx: Context) => any): this;
147
158
  ws<P extends string, BodySchema = undefined, QuerySchema = undefined, HeadersSchema = undefined, ResponseSchema = undefined>(path: P, handler: Omit<WebSocketRouteHandler<any, any, any, any>, 'body' | 'query' | 'headers' | 'response' | 'message'> & {
148
159
  body?: BodySchema;
@@ -182,6 +193,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
182
193
  * Zero overhead on routes that do not opt into a macro.
183
194
  */
184
195
  macro<M extends Record<string, MacroDefinition<any, Derived, any>>>(defs: M): BareJS<Derived, Routes, Macros & M>;
196
+ protected _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any>;
185
197
  protected _add(method: string, path: string, handlers: any[]): this;
186
198
  private _hasDerive;
187
199
  private static readonly DERIVE_RESERVED;
@@ -189,7 +201,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
189
201
  private compileHandler;
190
202
  compile(): void;
191
203
  private readonly _lazyFetch;
192
- fetch: (req: Request, peerIp?: string) => any;
204
+ fetch: (req: Request, peerIp?: any) => any;
193
205
  /**
194
206
  * Ergonomic in-memory request helper for testing or internal invocations.
195
207
  * Normalizes relative paths to http://localhost and delegates to this.fetch(req).
@@ -100,6 +100,7 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
100
100
  options: AddRouterRoute<Routes, 'OPTIONS'>;
101
101
  head: AddRouterRoute<Routes, 'HEAD'>;
102
102
  all: AddRouterRoute<Routes, 'ALL'>;
103
+ protected _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any>;
103
104
  group: (path: string, ...args: any[]) => this;
104
105
  private _mountRouter;
105
106
  route<P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
@@ -63,17 +63,28 @@ export declare class EdgeContext<Env = Record<string, any>> {
63
63
  send(msg: string, extra?: Record<string, any>): Response;
64
64
  redirect(url: string, status?: number): Response;
65
65
  }
66
+ export interface BareEdgeOptions {
67
+ /** Base path prefix applied to all registered routes (e.g. '/api'). */
68
+ prefix?: string;
69
+ }
66
70
  /**
67
71
  * Zero-Node Edge Web Framework (`barejs/edge`).
68
72
  * Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
69
73
  */
70
74
  export declare class BareEdge<Env = Record<string, any>> {
75
+ private prefix;
71
76
  private staticRoutes;
72
77
  private dynamicTrees;
73
78
  private middlewares;
74
79
  private requestHooks;
75
80
  private responseHooks;
76
81
  private errorHandler;
82
+ constructor(options?: BareEdgeOptions);
83
+ /**
84
+ * Set or append a base path prefix for all subsequently registered routes
85
+ * (e.g. `new BareEdge().basePath('/api')` for Next.js Edge / Astro / SvelteKit).
86
+ */
87
+ basePath(path: string): this;
77
88
  use(mw: EdgeMiddleware<Env>): this;
78
89
  onRequest(fn: (ctx: EdgeContext<Env>) => Promise<void> | void): this;
79
90
  onResponse(fn: (ctx: EdgeContext<Env>, res: Response) => Promise<void> | void): this;
@@ -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, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
7
+ export { BareJS, normalizePoolSize, type BareJSOptions, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
8
8
  export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
9
9
  /**
10
10
  * Plugin Interface for BareJS
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 `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, **Edge Workers** (`barejs/edge` — `53 KB`, zero `node:*` imports), **AWS Lambda**, **Cloudflare Pages**, and **Netlify** with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** and **502 tests across 37 files verified in CI (Bun, Node.js 20/22, Deno 2)**.
3
+ > BareJS is a batteries-included, JIT-compiled TypeScript web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, **Edge Workers** (`barejs/edge` — `53 KB`, zero `node:*` imports), **AWS Lambda**, **Cloudflare Pages**, **Netlify**, and **Meta Frameworks** (Next.js App Router, Astro, SvelteKit, Nuxt/Nitro, Remix, SolidStart, TanStack Start via `new BareJS({ prefix: '/api' })` + `export const GET = app.fetch`) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** and **508 tests across 38 files verified in CI (Bun, Node.js 20/22, Deno 2)**.
4
4
 
5
5
  ## 0. Complete Export & Subpath Index (Check Here First!)
6
6
  - `barejs` (core): `BareJS`, `BareRouter`, `Context`, `Type`/`T`/`TypeBox`, `Z`/`z`, `native`, `bareClient`, `bareTreaty`, `bareAuth`, `createToken`, `basicAuth`, `hasRole`, `revokeToken`, `isTokenRevoked`, `Hash`/`Password`, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `timeout`, `idempotency`, `createSingleflight`, `circuitBreaker`, `redisStore`, `compress`, `staticFile`, `file`, `etag`, `html`, `raw`, `escapeHtml`, `tracing`, `serverTiming`, `logger`, `healthcheck`, `generateOpenAPISpec`, `renderDocsHTML` (router supports `:param`, optional `:param?`, regex `:id{[0-9]+}`, and `*` wildcards)
@@ -23,7 +23,7 @@ bun create barejs my-app --bun # --bun | --node | --node-uws | --deno
23
23
  ```ts
24
24
  import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
25
25
 
26
- // 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)
26
+ // Optional { poolSize, prefix } (or numeric poolSize 0..65536, default 1024): lazy bounded LIFO Context pool + optional base path prefix (e.g. `new BareJS({ prefix: '/api' })` or `app.basePath('/api')`)
27
27
  const app = new BareJS();
28
28
 
29
29
  // Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams)
@@ -40,7 +40,7 @@ app.listen(3000); // or app.listen(8443, '0.0.0.0', false, { tls: { keyFileName,
40
40
  ```
41
41
 
42
42
  ## 2. Routing, Plugins & Unified Schema Validation
43
- Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.useAll`, `app.group(prefix, fn)`, `app.use(mwOrRouterOrPlugin)`.
43
+ Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.all`, `app.basePath(prefix)`, `app.group(prefix, fn)`, `app.route(prefix, router)`, `app.use(mwOrRouterOrPlugin)`.
44
44
  Pass a `RouteSchemas` object directly before the handler for AOT-compiled validation + auto-coercion (`number`/`integer`/`boolean` on `query` & `params`):
45
45
  ```ts
46
46
  app.post('/users/:id', {
@@ -166,6 +166,6 @@ await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners
166
166
  - **HTML Templates (`barejs/html`, `649 B`)**: `html\`<h1>Hello ${name}</h1>${raw('<span>✓</span>')}\`.toResponse()` — auto-escapes XSS, supports nested `html`, arrays, and falsy values.
167
167
  - **Dynamic ETag (`barejs/etag`, `1.8 KB`)**: `app.use(etag())` (weak FNV-1a 64-bit default) or `etag({ weak: false })` (strong SHA-256) with `304 Not Modified`.
168
168
  - **AWS Lambda (`barejs/aws-lambda`, `2.4 KB`)**: `export const handler = awsLambda(app)` (alias `handle`) — supports API Gateway v1, v2, ALB, `Set-Cookie`, and binary base64.
169
- - **Composable Macros (`app.macro`)**: `const plugin = new BareJS().macro('auth', { beforeHandle, resolve }); app.use(plugin).get('/me', { auth: 'admin' }, handler);`
169
+ - **Composable Macros (`app.macro`)**: `const plugin = new BareJS().macro({ auth: { beforeHandle, resolve } }); app.use(plugin).get('/me', { auth: 'admin' }, handler);`
170
170
  - **Cookie & Per-Status Response Schemas**: `RouteSchemas` supports `cookies` validation and `response: { 200: OkSchema, 404: ErrSchema }` (reflected in OpenAPI 3.1 & `bareTreaty`).
171
171
  - **Observability (`tracing`, `serverTiming`)**: `app.use(tracing({ serverTiming: 'app', onSpan }))` — zero-dep W3C `traceparent` + `Server-Timing` header.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "author": "xarhang",
5
- "description": "Batteries-included, zero-bloat TypeScript web framework for Bun, Node.js (uWebSockets.js), Deno, Edge & AWS Lambda — O(1) JIT routing, Standard Schema/TypeBox/Zod, bareTreaty RPC, OpenAPI 3.1, WebSockets, JSX SSR, and built-in zero-trust security.",
5
+ "description": "Batteries-included TypeScript web framework for Bun, Node.js (uWebSockets.js), Deno, Edge & AWS Lambda — O(1) JIT routing, Standard Schema/TypeBox/Zod, bareTreaty RPC, OpenAPI 3.1, WebSockets, JSX SSR, and built-in security.",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "types": "./dist/types/index.d.ts",
package/src/core/bare.ts CHANGED
@@ -155,6 +155,13 @@ type AddRoute<
155
155
  ): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>, Macros>;
156
156
  };
157
157
 
158
+ export interface BareJSOptions {
159
+ /** Context object pool size (default: 1024, max: 65536). */
160
+ poolSize?: number;
161
+ /** Base path prefix applied to all registered routes (e.g. '/api' for Next.js, Astro, SvelteKit). */
162
+ prefix?: string;
163
+ }
164
+
158
165
  export class BareJS<
159
166
  Derived extends Record<string, any> = {},
160
167
  Routes extends RouteSchema = {},
@@ -320,11 +327,17 @@ export class BareJS<
320
327
  private static readonly DEFAULT_POOL_SIZE = 1024;
321
328
  private static readonly MAX_POOL_SIZE = 65_536;
322
329
 
323
- constructor(poolSize: number = BareJS.DEFAULT_POOL_SIZE) {
324
- super();
330
+ constructor(poolSizeOrOptions: number | BareJSOptions = BareJS.DEFAULT_POOL_SIZE) {
331
+ const opts = typeof poolSizeOrOptions === 'object' && poolSizeOrOptions !== null
332
+ ? poolSizeOrOptions
333
+ : { poolSize: poolSizeOrOptions };
334
+ const normalizedPrefix = opts.prefix
335
+ ? ('/' + opts.prefix).replace(/\/+/g, '/').replace(/\/$/, '')
336
+ : '';
337
+ super(normalizedPrefix);
325
338
  bootstrapConfig();
326
339
  this.maxPool = normalizePoolSize(
327
- poolSize,
340
+ opts.poolSize ?? BareJS.DEFAULT_POOL_SIZE,
328
341
  BareJS.DEFAULT_POOL_SIZE,
329
342
  BareJS.MAX_POOL_SIZE
330
343
  );
@@ -342,13 +355,27 @@ export class BareJS<
342
355
  }
343
356
  }
344
357
 
358
+ /**
359
+ * Set or append a base path prefix for all subsequently registered routes
360
+ * (e.g. `new BareJS().basePath('/api')` for Next.js / Astro / SvelteKit).
361
+ */
362
+ public basePath(path: string): this {
363
+ const clean = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '');
364
+ if (clean) {
365
+ this.prefix = (this.prefix + clean).replace(/\/+/g, '/').replace(/\/$/, '');
366
+ this._onRouteMutate();
367
+ }
368
+ return this;
369
+ }
370
+
345
371
  private notFoundHandler: () => NotFoundResponse = () => ({
346
372
  status: 404,
347
373
  message: "Route not found"
348
374
  });
349
- public setNotFound(handler: () => NotFoundResponse) {
375
+ public setNotFound(handler: () => NotFoundResponse): this {
350
376
  this.notFoundHandler = handler;
351
377
  this._onRouteMutate();
378
+ return this;
352
379
  }
353
380
 
354
381
  public onError(handler: (err: any, ctx: Context) => any): this {
@@ -388,7 +415,7 @@ export class BareJS<
388
415
  }>,
389
416
  Macros
390
417
  > {
391
- const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
418
+ const normalized = (this.prefix + '/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
392
419
  const hasBody = Boolean(handler.body);
393
420
  const hasQuery = Boolean(handler.query);
394
421
  const hasHeaders = Boolean(handler.headers);
@@ -665,6 +692,13 @@ export class BareJS<
665
692
  return this as any;
666
693
  }
667
694
 
695
+ protected override _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any> {
696
+ const sub = new BareJS({ prefix });
697
+ sub.groupMiddleware = middleware;
698
+ sub.macros = { ...this.macros };
699
+ return sub;
700
+ }
701
+
668
702
  protected override _add(method: string, path: string, handlers: any[]) {
669
703
  const macroKeys = Object.keys(this.macros);
670
704
  if (macroKeys.length === 0) {
@@ -1284,15 +1318,14 @@ export class BareJS<
1284
1318
  const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit)) ||
1285
1319
  this.groupMiddleware.some((m: any) => m?.__idempotencyCommit);
1286
1320
  const hasDerive = this._hasDerive || this.routes.some((r: any) => r.handlers.some((h: any) => h?.__isDerive));
1321
+ const isDevUaf = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
1322
+ const ctxVar = isDevUaf ? 'rawCtx' : 'ctx';
1287
1323
  const deriveCleanup = hasDerive
1288
- ? `if (ctx._derivedKeys) { for (let i = 0; i < ctx._derivedKeys.length; i++) delete ctx[ctx._derivedKeys[i]]; ctx._derivedKeys = undefined; }`
1324
+ ? `if (${ctxVar}._derivedKeys) { for (let i = 0; i < ${ctxVar}._derivedKeys.length; i++) delete ${ctxVar}[${ctxVar}._derivedKeys[i]]; ${ctxVar}._derivedKeys = undefined; }`
1289
1325
  : '';
1290
1326
  const idemCleanup = hasIdem
1291
- ? `if (ctx._idempotencyKey) { if (ctx._idemInFlight) ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
1327
+ ? `if (${ctxVar}._idempotencyKey) { if (${ctxVar}._idemInFlight) ${ctxVar}._idemInFlight.delete(${ctxVar}._idempotencyKey); ${ctxVar}._idempotencyKey = undefined; ${ctxVar}._idemInFlight = undefined; }`
1292
1328
  : '';
1293
-
1294
- const isDevUaf = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
1295
- const ctxVar = isDevUaf ? 'rawCtx' : 'ctx';
1296
1329
  const wrapUaf = isDevUaf
1297
1330
  ? (rawCtx: Context, state: { released: boolean }): Context => {
1298
1331
  const warn = (prop: string | symbol) => {
@@ -1328,8 +1361,8 @@ export class BareJS<
1328
1361
  if (!${ctxVar}._detached) {
1329
1362
  ${isDevUaf ? '_uaf.released = true;' : ''}
1330
1363
  if (${ctxVar}.store.size > 0) ${ctxVar}.store.clear();
1331
- ${deriveCleanup.replaceAll('ctx.', `${ctxVar}.`).replaceAll('[ctx.', `[${ctxVar}.`)}
1332
- ${idemCleanup.replaceAll('ctx.', `${ctxVar}.`)}
1364
+ ${deriveCleanup}
1365
+ ${idemCleanup}
1333
1366
  ${ctxVar}.req = undefined;
1334
1367
  ${ctxVar}._status = 200;
1335
1368
  ${ctxVar}.body = undefined;
@@ -1506,10 +1539,11 @@ export class BareJS<
1506
1539
  const poolState = this._poolState;
1507
1540
  const trustProxyBox = this._trustProxyBox;
1508
1541
  const emitStructuredLog = isLog && (this._logFormat === 'json' || this._logSink !== undefined)
1509
- ? (method: string, rawUrl: string, status: number, durationMs: number, peerIp?: string) => {
1542
+ ? (method: string, rawUrl: string, status: number, durationMs: number, peerIp?: unknown) => {
1510
1543
  const idx = rawUrl.indexOf('/', 8);
1511
1544
  const qIdx = idx === -1 ? -1 : rawUrl.indexOf('?', idx);
1512
1545
  const path = idx === -1 ? '/' : (qIdx === -1 ? rawUrl.slice(idx) : rawUrl.slice(idx, qIdx));
1546
+ const ip = typeof peerIp === 'string' && peerIp ? peerIp : undefined;
1513
1547
  const entry: UseLogEntry = {
1514
1548
  level: status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info',
1515
1549
  timestamp: new Date().toISOString(),
@@ -1517,7 +1551,7 @@ export class BareJS<
1517
1551
  path,
1518
1552
  status,
1519
1553
  durationMs: Number(durationMs.toFixed(3)),
1520
- ...(peerIp ? { ip: peerIp } : {})
1554
+ ...(ip ? { ip } : {})
1521
1555
  };
1522
1556
  if (this._logSink) this._logSink(entry);
1523
1557
  else console.log(JSON.stringify(entry));
@@ -1575,7 +1609,7 @@ export class BareJS<
1575
1609
 
1576
1610
  try {
1577
1611
  ${ctxVar}.req = req;
1578
- ${ctxVar}._peerIp = peerIp;
1612
+ ${ctxVar}._peerIp = typeof peerIp === 'string' ? peerIp : undefined;
1579
1613
 
1580
1614
  ${staticFastPathCode}
1581
1615
 
@@ -1654,13 +1688,14 @@ export class BareJS<
1654
1688
  const innerFetch = this.hotFetch!;
1655
1689
  const reqHooks = this.requestHooks.slice();
1656
1690
  const resHooks = this.responseHooks.slice();
1657
- this.hotFetch = async (req: Request, peerIp?: string) => {
1691
+ this.hotFetch = async (req: Request, peerIp?: any) => {
1692
+ const ip = typeof peerIp === 'string' ? peerIp : undefined;
1658
1693
  const start = performance.now();
1659
1694
  for (let i = 0; i < reqHooks.length; i++) {
1660
- const maybeRes = await reqHooks[i]!(req, peerIp);
1695
+ const maybeRes = await reqHooks[i]!(req, ip);
1661
1696
  if (maybeRes instanceof Response) return maybeRes;
1662
1697
  }
1663
- let res: Response = await innerFetch(req, peerIp);
1698
+ let res: Response = await innerFetch(req, ip);
1664
1699
  const durationMs = performance.now() - start;
1665
1700
  for (let i = 0; i < resHooks.length; i++) {
1666
1701
  const updated = await resHooks[i]!(req, res, durationMs);
@@ -1673,7 +1708,7 @@ export class BareJS<
1673
1708
  this.fetch = this.hotFetch!;
1674
1709
  }
1675
1710
 
1676
- private readonly _lazyFetch = (req: Request, peerIp?: string): any => {
1711
+ private readonly _lazyFetch = (req: Request, peerIp?: any): any => {
1677
1712
  if (!this.compiled) {
1678
1713
  this.compile();
1679
1714
  return this.hotFetch!(req, peerIp);
@@ -1681,7 +1716,7 @@ export class BareJS<
1681
1716
  return this.hotFetch!(req, peerIp);
1682
1717
  };
1683
1718
 
1684
- public fetch = this._lazyFetch;
1719
+ public fetch: (req: Request, peerIp?: any) => any = this._lazyFetch;
1685
1720
 
1686
1721
  /**
1687
1722
  * Ergonomic in-memory request helper for testing or internal invocations.
@@ -98,7 +98,7 @@ function ipv4ToInt(ip: string): number | null {
98
98
 
99
99
  export function isTrustedProxyIp(peerIp: string | undefined, trustProxy: boolean | string[]): boolean {
100
100
  if (trustProxy === true) return true;
101
- if (!trustProxy || !Array.isArray(trustProxy) || trustProxy.length === 0 || !peerIp) return false;
101
+ if (!trustProxy || !Array.isArray(trustProxy) || trustProxy.length === 0 || typeof peerIp !== 'string' || !peerIp) return false;
102
102
  const normalized = peerIp.startsWith('::ffff:') ? peerIp.slice(7) : peerIp;
103
103
  const peerInt = ipv4ToInt(normalized);
104
104
  for (let i = 0; i < trustProxy.length; i++) {
@@ -180,12 +180,16 @@ export class BareRouter<Routes extends RouteSchema = {}> {
180
180
  return this;
181
181
  }) as any;
182
182
 
183
+ protected _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any> {
184
+ return new BareRouter(prefix, middleware);
185
+ }
186
+
183
187
  public group = (path: string, ...args: any[]) => {
184
188
  const callback = args.pop();
185
189
  const middleware = args;
186
190
 
187
191
  const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
188
- const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
192
+ const subRouter = this._createGroupRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
189
193
 
190
194
  callback(subRouter);
191
195
  this.routes.push(...subRouter.routes);
package/src/edge.ts CHANGED
@@ -304,11 +304,17 @@ class EdgeRadixNode<Env> {
304
304
  }
305
305
  }
306
306
 
307
+ export interface BareEdgeOptions {
308
+ /** Base path prefix applied to all registered routes (e.g. '/api'). */
309
+ prefix?: string;
310
+ }
311
+
307
312
  /**
308
313
  * Zero-Node Edge Web Framework (`barejs/edge`).
309
314
  * Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
310
315
  */
311
316
  export class BareEdge<Env = Record<string, any>> {
317
+ private prefix: string = '';
312
318
  private staticRoutes: Map<string, EdgeRouteEntry<Env>> = new Map();
313
319
  private dynamicTrees: Map<string, EdgeRadixNode<Env>> = new Map();
314
320
  private middlewares: EdgeMiddleware<Env>[] = [];
@@ -316,6 +322,24 @@ export class BareEdge<Env = Record<string, any>> {
316
322
  private responseHooks: Array<(ctx: EdgeContext<Env>, res: Response) => Promise<void> | void> = [];
317
323
  private errorHandler: ((err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>) | null = null;
318
324
 
325
+ constructor(options?: BareEdgeOptions) {
326
+ if (options?.prefix) {
327
+ this.prefix = ('/' + options.prefix).replace(/\/+/g, '/').replace(/\/$/, '');
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Set or append a base path prefix for all subsequently registered routes
333
+ * (e.g. `new BareEdge().basePath('/api')` for Next.js Edge / Astro / SvelteKit).
334
+ */
335
+ public basePath(path: string): this {
336
+ const clean = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '');
337
+ if (clean) {
338
+ this.prefix = (this.prefix + clean).replace(/\/+/g, '/').replace(/\/$/, '');
339
+ }
340
+ return this;
341
+ }
342
+
319
343
  public use(mw: EdgeMiddleware<Env>): this {
320
344
  this.middlewares.push(mw);
321
345
  return this;
@@ -340,7 +364,8 @@ export class BareEdge<Env = Record<string, any>> {
340
364
  if (fns.length === 0) return this;
341
365
  const handler = fns[fns.length - 1] as EdgeHandler<Env>;
342
366
  const middlewares = fns.slice(0, -1);
343
- const cleanPath = path.startsWith('/') ? path : `/${path}`;
367
+ const joined = (this.prefix + '/' + path).replace(/\/+/g, '/');
368
+ const cleanPath = joined.length > 1 && joined.endsWith('/') ? joined.slice(0, -1) : (joined || '/');
344
369
  const entry: EdgeRouteEntry<Env> = { middlewares, handler };
345
370
 
346
371
  if (!cleanPath.includes(':') && !cleanPath.includes('*')) {
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  // --- 1. Core Engine ---
9
- export { BareJS, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
9
+ export { BareJS, normalizePoolSize, type BareJSOptions, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
10
10
  export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
11
11
 
12
12
  /**