barejs 0.1.55 → 0.1.57

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.
@@ -66,9 +66,8 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
66
66
  private pool;
67
67
  private hotFetch?;
68
68
  private compiled;
69
- private poolMask;
70
69
  private _useLog;
71
- private _trustProxy;
70
+ private _trustProxyBox;
72
71
  private errorHandler?;
73
72
  private wsRoutes;
74
73
  private startHooks;
@@ -110,6 +109,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
110
109
  (mw: any): BareJS<Derived, Routes>;
111
110
  };
112
111
  private _hasDerive;
112
+ private static readonly DERIVE_RESERVED;
113
113
  derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
114
114
  private compileHandler;
115
115
  compile(): void;
@@ -50,11 +50,16 @@ export declare class Context {
50
50
  _detached: boolean;
51
51
  constructor(trustProxy?: boolean);
52
52
  get query(): Record<string, string>;
53
+ /** All values for a (possibly repeated) query key, in order. */
54
+ queryAll(key: string): string[];
53
55
  getQuery(key: string): string | undefined;
54
56
  get cookies(): Record<string, string>;
55
57
  setCookie(name: string, value: string, options?: CookieOptions): this;
56
58
  getSignedCookie(name: string, secret: string): string | null;
57
59
  deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'>): this;
60
+ private readBodyWithLimit;
61
+ private _parseAndSanitizeJson;
62
+ jsonBodySyncOrAsync(maxBytes?: number): any;
58
63
  jsonBody(maxBytes?: number): Promise<any>;
59
64
  reset(req: Request): this;
60
65
  status(code: number): this;
@@ -6,11 +6,9 @@ export declare class RadixNode {
6
6
  paramName: string | null;
7
7
  wildcardNode: RadixNode | null;
8
8
  handlers: Record<string, Function>;
9
+ handlerParams: Record<string, string[]>;
9
10
  insert(path: string, method: string, handler: Function): void;
10
11
  lookup(method: string, url: string, start: number, ctx: Context): Function | null;
11
- jitCompile(register: (h: Function) => string, level?: number, pathPrefix?: string, idxPrefix?: string, paramAccumulator?: {
12
- name: string;
13
- varName: string;
14
- }[]): string;
15
- id: string;
12
+ private emitParamsAssign;
13
+ jitCompile(register: (h: Function) => string, level?: number, pathPrefix?: string, idxPrefix?: string, paramVars?: string[], emitCall?: (hName: string) => string): string;
16
14
  }
@@ -75,6 +75,6 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
75
75
  route<P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
76
76
  use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
77
77
  use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
78
- use(mw: any): BareRouter<Routes>;
78
+ use(...mws: any[]): BareRouter<Routes>;
79
79
  }
80
80
  export {};
@@ -4,7 +4,7 @@
4
4
  * Built for Bun with Mechanical Sympathy
5
5
  * Optimized to outperform competitors by 55% [2026-01-05]
6
6
  */
7
- export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
7
+ export { BareJS, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
8
8
  export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
9
9
  /**
10
10
  * Plugin Interface for BareJS
@@ -20,7 +20,7 @@ import { typebox, zod, native, validate, schemaValidator, createResponseFilter,
20
20
  export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v, schemaValidator, createResponseFilter, type RouteSchemas, type RouteDetail };
21
21
  export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
22
22
  export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
23
- export { cors } from './security/cors';
23
+ export { cors, type CorsOptions } from './security/cors';
24
24
  export { csrf, type CsrfOptions } from './security/csrf';
25
25
  export { timeout, type TimeoutOptions } from './security/timeout';
26
26
  export { rateLimit, type RateLimitOptions } from './security/rateLimit';
@@ -1,4 +1,4 @@
1
- import type { Middleware } from '../core/context';
1
+ import type { Context, Middleware } from '../core/context';
2
2
  import type { IdempotencyStore } from './store';
3
3
  export interface IdempotencyOptions {
4
4
  /** Header name (default: 'idempotency-key') */
@@ -9,6 +9,11 @@ export interface IdempotencyOptions {
9
9
  maxKeys?: number;
10
10
  /** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
11
11
  store?: IdempotencyStore;
12
+ /**
13
+ * Scope string mixed into the cache key so one caller can never replay another caller's response.
14
+ * Default: SHA-256 of the Authorization and Cookie headers.
15
+ */
16
+ keyScope?: (ctx: Context) => string | undefined;
12
17
  }
13
18
  /**
14
19
  * Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
@@ -12,13 +12,16 @@ export interface CachedIdempotentEntry {
12
12
  body?: any;
13
13
  rawBody?: ArrayBuffer;
14
14
  contentType?: string;
15
+ /** Replayed safe headers (Location, Content-Location, ETag) */
16
+ headers?: Record<string, string>;
15
17
  expiresAt: number;
16
18
  }
17
19
  export interface IdempotencyStore {
18
20
  get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
19
21
  set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
20
22
  acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
21
- release(key: string): Promise<void> | void;
23
+ acquireToken?(key: string, ttlMs?: number): Promise<string | null> | string | null;
24
+ release(key: string, tokenOverride?: string): Promise<void> | void;
22
25
  }
23
26
  export interface RevocationStore {
24
27
  revoke(tokenOrJti: string, ttlMs: number): Promise<void> | void;
@@ -12,6 +12,7 @@ export interface OpenAPIOptions {
12
12
  }>;
13
13
  securitySchemes?: Record<string, Record<string, any>>;
14
14
  security?: Array<Record<string, string[]>>;
15
+ excludePaths?: string[];
15
16
  }
16
17
  export declare const generateOpenAPISpec: (routes: any[], options?: OpenAPIOptions) => {
17
18
  paths: Record<string, Record<string, any>>;
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 (316 tests / 5,833 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 (401 tests / 6,129 assertions)**.
4
4
 
5
5
  ## 1. Installation & Minimal App
6
6
  ```ts
@@ -53,7 +53,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
53
53
  - `await app.request('/items', { method: 'POST', body: JSON.stringify({ name: 'a' }) })`: Ergonomic in-memory helper (normalizes relative paths to `http://localhost` and delegates to `app.fetch`).
54
54
  - `ctx.req`: Raw incoming Bun `Request`.
55
55
  - `ctx.params`: Route params (`Record<string, any>`, including `ctx.params['*']` for wildcards).
56
- - `ctx.query` / `ctx.getQuery(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`).
56
+ - `ctx.query` / `ctx.getQuery(key)` / `ctx.queryAll(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`) with repeated query key support.
57
57
  - `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit.
58
58
  - `await ctx.upload({ maxFileSize, maxFiles, allowedTypes })`: Safe `multipart/form-data` parser; returns `{ fields, files }` with `safeName` (sanitized against path traversal) and enforces `413` (size/count) and `415` (MIME type).
59
59
  - `ctx.cookies`: Lazy parsed request cookies (`Record<string, string>`).
@@ -103,7 +103,7 @@ app.use(rateLimit({ windowMs: 60_000, max: 100, store })); // Omit store for zer
103
103
  app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
104
104
 
105
105
  // Idempotency-Key double-charge & race condition guard (409 IDEMPOTENT_IN_FLIGHT + X-Idempotent-Replayed: true)
106
- app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store }), (ctx) => ({ paid: true }));
106
+ app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store, keyScope: (ctx) => ctx.user?.id }), (ctx) => ({ paid: true }));
107
107
 
108
108
  // Thundering-herd / Cache-stampede request coalescer
109
109
  const sf = createSingleflight();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.55",
3
+ "version": "0.1.57",
4
4
  "author": "xarhang",
5
5
  "description": "High-performance JIT-specialized web framework for Bun",
6
6
  "main": "./dist/index.js",
@@ -22,7 +22,7 @@
22
22
  "test": "bun test",
23
23
  "benchs": "bun run benchmarks/index.ts",
24
24
  "bench": "bun run benchmarks/head-to-head.ts",
25
- "dev": "bun --watch example/index.ts",
25
+ "dev": "bun --watch Example/index.ts",
26
26
  "build": "bun ./scripts/build.ts",
27
27
  "prepublishOnly": "bun run build",
28
28
  "release": "bun run build && npm version patch && npm publish --access public"
@@ -92,8 +92,8 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
92
92
  let finalPath = path;
93
93
  if (options?.params) {
94
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
95
+ finalPath = finalPath.replace(/:([a-zA-Z0-9_]+)(?=\/|\?|$)/g, (match, key) =>
96
+ Object.hasOwn(params, key) && params[key] !== undefined ? encodeURIComponent(String(params[key])) : match
97
97
  );
98
98
  }
99
99
  const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
@@ -106,7 +106,7 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
106
106
  if (v !== undefined) qs.set(k, String(v));
107
107
  }
108
108
  const str = qs.toString();
109
- if (str) url += `?${str}`;
109
+ if (str) url += (url.includes('?') ? '&' : '?') + str;
110
110
  }
111
111
  return url;
112
112
  };
@@ -122,26 +122,54 @@ export const bareClient = <AppOrRoutes = any>(
122
122
 
123
123
  const request = async (method: string, path: string, options?: ClientRequestOptions) => {
124
124
  const url = buildUrl(baseUrl, path, options);
125
- const headers: Record<string, string> = {
126
- ...defaultHeaders,
127
- ...(options?.headers ?? {})
128
- };
125
+ const headers = new Headers();
126
+ for (const [k, v] of Object.entries(defaultHeaders)) {
127
+ headers.set(k, v);
128
+ }
129
+ if (options?.headers) {
130
+ for (const [k, v] of Object.entries(options.headers)) {
131
+ headers.set(k, v);
132
+ }
133
+ }
129
134
 
130
135
  const init: RequestInit = { method, headers };
131
136
  if (options?.body !== undefined && method !== 'GET' && method !== 'HEAD') {
132
- if (!headers['Content-Type'] && !headers['content-type']) {
133
- headers['Content-Type'] = 'application/json';
137
+ const b = options.body;
138
+ const isRawBody =
139
+ typeof b === 'string' ||
140
+ b instanceof FormData ||
141
+ b instanceof URLSearchParams ||
142
+ b instanceof Blob ||
143
+ b instanceof ArrayBuffer ||
144
+ ArrayBuffer.isView(b) ||
145
+ (typeof ReadableStream !== 'undefined' && b instanceof ReadableStream);
146
+
147
+ if (isRawBody) {
148
+ if (b instanceof FormData) headers.delete('content-type');
149
+ init.body = b as RequestInit['body'];
150
+ } else {
151
+ if (!headers.has('content-type')) {
152
+ headers.set('Content-Type', 'application/json');
153
+ }
154
+ init.body = JSON.stringify(b);
134
155
  }
135
- init.body = typeof options.body === 'string' ? options.body : JSON.stringify(options.body);
136
156
  }
137
157
 
138
158
  const res = await fetchImpl(url, init);
139
159
  let data: any = null;
140
160
  if (res.status !== 204 && res.status !== 205 && res.status !== 304) {
141
- const ct = res.headers.get('content-type') || '';
142
- if (ct.includes('application/json')) {
161
+ const ct = (res.headers.get('content-type') || '').toLowerCase();
162
+ if (ct.includes('application/json') || ct.includes('+json')) {
143
163
  const text = await res.text();
144
- data = text ? JSON.parse(text) : null;
164
+ if (text) {
165
+ try {
166
+ data = JSON.parse(text);
167
+ } catch {
168
+ data = text;
169
+ }
170
+ } else {
171
+ data = null;
172
+ }
145
173
  } else {
146
174
  data = await res.text();
147
175
  }