barejs 0.1.51 → 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.
@@ -0,0 +1,151 @@
1
+ export interface RateLimitStore {
2
+ increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> | { count: number; resetAt: number };
3
+ }
4
+
5
+ export interface CachedIdempotentEntry {
6
+ status: number;
7
+ body?: any;
8
+ rawBody?: ArrayBuffer;
9
+ contentType?: string;
10
+ expiresAt: number;
11
+ }
12
+
13
+ export interface IdempotencyStore {
14
+ get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
15
+ set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
16
+ acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
17
+ release(key: string): Promise<void> | void;
18
+ }
19
+
20
+ export interface RevocationStore {
21
+ revoke(tokenOrJti: string, ttlMs: number): Promise<void> | void;
22
+ isRevoked(tokenOrJti: string): Promise<boolean> | boolean;
23
+ }
24
+
25
+ export type BareStore = RateLimitStore & IdempotencyStore & RevocationStore;
26
+
27
+ export interface RedisStoreOptions {
28
+ /** Key prefix for all entries (default: 'barejs:') */
29
+ prefix?: string;
30
+ }
31
+
32
+ /**
33
+ * Lightweight Redis adapter compatible with both Bun.redis and ioredis.
34
+ * Implements RateLimitStore, IdempotencyStore, and RevocationStore.
35
+ */
36
+ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareStore => {
37
+ const prefix = options.prefix ?? 'barejs:';
38
+
39
+ const useSend = typeof client.send === 'function';
40
+
41
+ const cmdGet = (key: string) =>
42
+ useSend ? client.send('GET', [key]) : client.get(key);
43
+
44
+ const cmdDel = (key: string) =>
45
+ useSend ? client.send('DEL', [key]) : client.del(key);
46
+
47
+ const cmdIncr = (key: string) =>
48
+ useSend ? client.send('INCR', [key]) : client.incr(key);
49
+
50
+ const setWithTtl = async (key: string, value: string, ttlMs: number): Promise<void> => {
51
+ if (useSend) {
52
+ await client.send('SET', [key, value, 'PX', String(ttlMs)]);
53
+ return;
54
+ }
55
+ try {
56
+ await client.set(key, value, 'PX', ttlMs);
57
+ } catch {
58
+ await client.set(key, value);
59
+ if (typeof client.pexpire === 'function') {
60
+ await client.pexpire(key, ttlMs);
61
+ } else if (typeof client.expire === 'function') {
62
+ await client.expire(key, Math.max(1, Math.ceil(ttlMs / 1000)));
63
+ }
64
+ }
65
+ };
66
+
67
+ return {
68
+ async increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> {
69
+ const fullKey = `${prefix}rl:${key}`;
70
+ const count = Number(await cmdIncr(fullKey));
71
+ if (count === 1) {
72
+ if (useSend) {
73
+ await client.send('PEXPIRE', [fullKey, String(windowMs)]);
74
+ } else if (typeof client.pexpire === 'function') {
75
+ await client.pexpire(fullKey, windowMs);
76
+ } else if (typeof client.expire === 'function') {
77
+ await client.expire(fullKey, Math.max(1, Math.ceil(windowMs / 1000)));
78
+ }
79
+ }
80
+ let pttl = windowMs;
81
+ if (useSend) {
82
+ const res = Number(await client.send('PTTL', [fullKey]));
83
+ if (Number.isFinite(res) && res > 0) pttl = res;
84
+ } else if (typeof client.pttl === 'function') {
85
+ const res = Number(await client.pttl(fullKey));
86
+ if (Number.isFinite(res) && res > 0) pttl = res;
87
+ } else if (typeof client.ttl === 'function') {
88
+ const res = Number(await client.ttl(fullKey));
89
+ if (Number.isFinite(res) && res > 0) pttl = res * 1000;
90
+ }
91
+ return { count, resetAt: Date.now() + pttl };
92
+ },
93
+
94
+ async get(key: string): Promise<CachedIdempotentEntry | undefined> {
95
+ const raw = await cmdGet(`${prefix}idem:${key}`);
96
+ if (!raw) return undefined;
97
+ try {
98
+ const parsed = JSON.parse(typeof raw === 'string' ? raw : String(raw));
99
+ if (parsed.rawBodyBase64) {
100
+ const buf = Buffer.from(parsed.rawBodyBase64, 'base64');
101
+ return {
102
+ status: parsed.status,
103
+ rawBody: buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
104
+ contentType: parsed.contentType,
105
+ expiresAt: parsed.expiresAt
106
+ };
107
+ }
108
+ return parsed;
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ },
113
+
114
+ async set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> {
115
+ const serializable: any = {
116
+ status: entry.status,
117
+ expiresAt: entry.expiresAt
118
+ };
119
+ if (entry.rawBody !== undefined) {
120
+ serializable.rawBodyBase64 = Buffer.from(entry.rawBody).toString('base64');
121
+ serializable.contentType = entry.contentType;
122
+ } else {
123
+ serializable.body = entry.body;
124
+ }
125
+ await setWithTtl(`${prefix}idem:${key}`, JSON.stringify(serializable), ttlMs);
126
+ },
127
+
128
+ async acquire(key: string, ttlMs: number = 30_000): Promise<boolean> {
129
+ const lockKey = `${prefix}idem:lock:${key}`;
130
+ if (useSend) {
131
+ const res = await client.send('SET', [lockKey, '1', 'PX', String(ttlMs), 'NX']);
132
+ return res === 'OK' || res === true;
133
+ }
134
+ const res = await client.set(lockKey, '1', 'PX', ttlMs, 'NX');
135
+ return res === 'OK' || res === true || res === 1;
136
+ },
137
+
138
+ async release(key: string): Promise<void> {
139
+ await cmdDel(`${prefix}idem:lock:${key}`);
140
+ },
141
+
142
+ async revoke(tokenOrJti: string, ttlMs: number): Promise<void> {
143
+ await setWithTtl(`${prefix}rev:${tokenOrJti}`, '1', ttlMs);
144
+ },
145
+
146
+ async isRevoked(tokenOrJti: string): Promise<boolean> {
147
+ const val = await cmdGet(`${prefix}rev:${tokenOrJti}`);
148
+ return val !== null && val !== undefined;
149
+ }
150
+ };
151
+ };
@@ -274,6 +274,7 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
274
274
  const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
275
275
  const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
276
276
  const maxBodySize = schemas.maxBodySize ?? 1048576;
277
+ const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
277
278
 
278
279
  const validateSyncParts = (ctx: Context): Response | undefined => {
279
280
  if (paramsCheck) {
@@ -299,8 +300,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
299
300
 
300
301
  if (!bodyCheck) {
301
302
  const syncMw: Middleware = (ctx: Context, next?: Next) => {
302
- const errRes = validateSyncParts(ctx);
303
- if (errRes) return errRes;
303
+ if (hasSyncParts) {
304
+ const errRes = validateSyncParts(ctx);
305
+ if (errRes) return errRes;
306
+ }
304
307
  return next ? next() : undefined;
305
308
  };
306
309
  (syncMw as any).__routeSchemas = schemas;
@@ -309,8 +312,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
309
312
  }
310
313
 
311
314
  const mw: Middleware = async (ctx: Context, next?: Next) => {
312
- const errRes = validateSyncParts(ctx);
313
- if (errRes) return errRes;
315
+ if (hasSyncParts) {
316
+ const errRes = validateSyncParts(ctx);
317
+ if (errRes) return errRes;
318
+ }
314
319
 
315
320
  let body: any;
316
321
  try {
@@ -1,24 +1,44 @@
1
1
  import type { Context, Middleware, Next } from '../core/context';
2
+ import { brotliCompressSync, constants as zlibConstants } from 'node:zlib';
3
+
4
+ export type CompressionEncoding = 'zstd' | 'br' | 'gzip';
2
5
 
3
6
  export interface CompressOptions {
4
- /** Minimum response size in bytes before gzip compression is applied (default: 1024) */
7
+ /** Minimum response size in bytes before compression is applied (default: 1024) */
5
8
  minSize?: number;
6
9
  /** Gzip compression level 0-9 (default: 6) */
7
10
  level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
11
+ /** Preferred compression encodings in priority order (default: ['zstd', 'br', 'gzip']) */
12
+ encodings?: CompressionEncoding[];
8
13
  }
9
14
 
10
15
  /**
11
- * Zero-dependency Gzip compression middleware powered by Bun.gzipSync (native C/Zig).
12
- * Skips streaming SSE responses, already-encoded responses, and payloads below minSize.
16
+ * Zero-dependency response compression middleware supporting zstd, brotli (br), and gzip.
17
+ * Negotiates encoding from Accept-Encoding, and skips streaming SSE, 204/304, already-encoded, and small payloads.
13
18
  */
14
19
  export const compress = (options: CompressOptions = {}): Middleware => {
15
20
  const minSize = options.minSize ?? 1024;
16
21
  const level = options.level ?? 6;
22
+ const encodings: CompressionEncoding[] = options.encodings ?? ['zstd', 'br', 'gzip'];
23
+ const hasZstd = typeof (Bun as any).zstdCompressSync === 'function';
24
+
25
+ const negotiate = (accept: string): CompressionEncoding | null => {
26
+ const lower = accept.toLowerCase();
27
+ for (let i = 0; i < encodings.length; i++) {
28
+ const enc = encodings[i]!;
29
+ if (enc === 'zstd' && hasZstd && lower.includes('zstd')) return 'zstd';
30
+ if (enc === 'br' && lower.includes('br')) return 'br';
31
+ if (enc === 'gzip' && lower.includes('gzip')) return 'gzip';
32
+ }
33
+ return null;
34
+ };
17
35
 
18
36
  const applyCompress = async (ctx: Context, res: any) => {
19
37
  if (ctx.req.method === 'HEAD') return res;
20
38
  const accept = ctx.req.headers.get('accept-encoding');
21
- if (!accept || !accept.includes('gzip')) return res;
39
+ if (!accept) return res;
40
+ const chosen = negotiate(accept);
41
+ if (!chosen) return res;
22
42
  if (!(res instanceof Response)) return res;
23
43
  if (res.status === 204 || res.status === 304) return res;
24
44
  if (res.headers.has('content-encoding')) return res;
@@ -31,13 +51,24 @@ export const compress = (options: CompressOptions = {}): Middleware => {
31
51
  return new Response(buf, { status: res.status, headers: res.headers });
32
52
  }
33
53
 
34
- const gz = Bun.gzipSync(new Uint8Array(buf), { level });
54
+ const raw = new Uint8Array(buf);
55
+ let compressed: Uint8Array;
56
+ if (chosen === 'zstd') {
57
+ compressed = (Bun as any).zstdCompressSync(raw);
58
+ } else if (chosen === 'br') {
59
+ compressed = brotliCompressSync(raw, {
60
+ params: { [zlibConstants.BROTLI_PARAM_QUALITY]: Math.min(11, Math.max(1, level)) }
61
+ });
62
+ } else {
63
+ compressed = Bun.gzipSync(raw, { level });
64
+ }
65
+
35
66
  const headers = new Headers(res.headers);
36
- headers.set('Content-Encoding', 'gzip');
67
+ headers.set('Content-Encoding', chosen);
37
68
  headers.set('Vary', 'Accept-Encoding');
38
69
  headers.delete('Content-Length');
39
70
 
40
- return new Response(gz, { status: res.status, headers });
71
+ return new Response(compressed, { status: res.status, headers });
41
72
  };
42
73
 
43
74
  const mw: Middleware = async (ctx: Context, next?: Next) => {
@@ -1,9 +1,26 @@
1
1
  import { resolve, sep } from 'node:path';
2
2
  import { stat, realpath } from 'node:fs/promises';
3
3
 
4
+ export interface StaticMetadataCacheOptions {
5
+ /** Maximum cached file metadata entries (default: 1000) */
6
+ maxEntries?: number;
7
+ /** Cache TTL in milliseconds (default: 30_000) */
8
+ ttlMs?: number;
9
+ }
10
+
4
11
  export interface StaticOptions {
5
12
  maxAge?: number;
6
13
  etag?: boolean;
14
+ /** Optional LRU metadata cache for realpath, stat, and ETag to avoid repeated syscalls */
15
+ cacheMetadata?: boolean | StaticMetadataCacheOptions;
16
+ }
17
+
18
+ interface StaticMetaEntry {
19
+ realFile: string;
20
+ fileSize: number;
21
+ mtimeMs: number;
22
+ etag: string;
23
+ expiresAt: number;
7
24
  }
8
25
 
9
26
  export const staticFile = (root: string = 'public', options: StaticOptions = {}) => {
@@ -13,6 +30,12 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
13
30
  const maxAge = options.maxAge ?? 3600;
14
31
  const enableEtag = options.etag !== false;
15
32
 
33
+ const cacheOpt = options.cacheMetadata;
34
+ const useCache = Boolean(cacheOpt);
35
+ const cacheMax = typeof cacheOpt === 'object' ? (cacheOpt.maxEntries ?? 1000) : 1000;
36
+ const cacheTtl = typeof cacheOpt === 'object' ? (cacheOpt.ttlMs ?? 30_000) : 30_000;
37
+ const metaCache = useCache ? new Map<string, StaticMetaEntry>() : null;
38
+
16
39
  const mw = async (ctx: any, next: any) => {
17
40
  const method = ctx.req.method;
18
41
  if (method !== 'GET' && method !== 'HEAD') return next();
@@ -44,22 +67,50 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
44
67
 
45
68
  let fileSize = 0;
46
69
  let mtimeMs = 0;
47
- try {
48
- const [realRoot, realFile] = await Promise.all([
49
- (realRootPromise ??= realpath(rootDir)),
50
- realpath(filePath)
51
- ]);
52
- const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
53
- if (realFile !== realRoot && !realFile.startsWith(realPrefix)) {
54
- return ctx.status(403).send('Forbidden');
70
+ let etag = '';
71
+
72
+ const cached = metaCache?.get(filePath);
73
+ if (cached && Date.now() < cached.expiresAt) {
74
+ // Refresh LRU position
75
+ metaCache!.delete(filePath);
76
+ metaCache!.set(filePath, cached);
77
+ fileSize = cached.fileSize;
78
+ mtimeMs = cached.mtimeMs;
79
+ etag = cached.etag;
80
+ } else {
81
+ try {
82
+ const [realRoot, realFile] = await Promise.all([
83
+ (realRootPromise ??= realpath(rootDir)),
84
+ realpath(filePath)
85
+ ]);
86
+ const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
87
+ if (realFile !== realRoot && !realFile.startsWith(realPrefix)) {
88
+ return ctx.status(403).send('Forbidden');
89
+ }
90
+ const st = await stat(realFile);
91
+ if (st.isDirectory()) return next();
92
+ fileSize = st.size;
93
+ mtimeMs = Math.floor(st.mtimeMs);
94
+ etag = enableEtag ? `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"` : '';
95
+
96
+ if (metaCache) {
97
+ if (metaCache.size >= cacheMax) {
98
+ const oldest = metaCache.keys().next().value;
99
+ if (oldest !== undefined) metaCache.delete(oldest);
100
+ }
101
+ metaCache.set(filePath, {
102
+ realFile,
103
+ fileSize,
104
+ mtimeMs,
105
+ etag,
106
+ expiresAt: Date.now() + cacheTtl
107
+ });
108
+ }
109
+ } catch {
110
+ return next();
55
111
  }
56
- const st = await stat(realFile);
57
- if (st.isDirectory()) return next();
58
- fileSize = st.size;
59
- mtimeMs = Math.floor(st.mtimeMs);
60
- } catch {
61
- return next();
62
112
  }
113
+
63
114
  const file = Bun.file(filePath);
64
115
 
65
116
  const headers: Record<string, string> = {
@@ -68,7 +119,6 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
68
119
  };
69
120
 
70
121
  if (enableEtag) {
71
- const etag = `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"`;
72
122
  headers['ETag'] = etag;
73
123
  const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
74
124
  if (ifNoneMatch && ifNoneMatch === etag) {