barejs 0.2.4 → 0.2.6
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/README.md +80 -33
- package/dist/edge.js +70 -0
- package/dist/index.js +200 -189
- package/dist/node.js +200 -189
- package/dist/types/client/index.d.ts +100 -0
- package/dist/types/core/bare.d.ts +68 -25
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/core/router.d.ts +27 -2
- package/dist/types/core/ws-match.d.ts +34 -2
- package/dist/types/edge.d.ts +99 -0
- package/dist/types/index.d.ts +6 -5
- package/dist/types/runtime/types.d.ts +15 -0
- package/dist/types/security/validators.d.ts +46 -1
- package/dist/types/utils/tracing.d.ts +25 -0
- package/llms.txt +13 -6
- package/package.json +7 -3
- package/src/client/index.ts +399 -6
- package/src/core/bare.ts +366 -46
- package/src/core/context.ts +10 -3
- package/src/core/radix.ts +54 -31
- package/src/core/router.ts +37 -4
- package/src/core/ws-match.ts +17 -2
- package/src/edge.ts +494 -0
- package/src/index.ts +16 -5
- package/src/runtime/bun.ts +39 -7
- package/src/runtime/node.ts +37 -4
- package/src/runtime/types.ts +16 -0
- package/src/runtime/uws.ts +60 -12
- package/src/security/auth.ts +7 -5
- package/src/security/validators.ts +240 -38
- package/src/utils/openapi.ts +39 -9
- package/src/utils/tracing.ts +86 -0
package/src/core/router.ts
CHANGED
|
@@ -10,10 +10,42 @@ import type { RouteEndpoint, RouteSchema } from '../client/index';
|
|
|
10
10
|
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
11
11
|
|
|
12
12
|
export type InferSchema<S> =
|
|
13
|
-
S extends {
|
|
13
|
+
S extends { '~standard': { types?: { output: infer T } } } ? T
|
|
14
|
+
: S extends { static: infer T } ? T
|
|
14
15
|
: S extends { _output: infer T } ? T
|
|
15
16
|
: any;
|
|
16
17
|
|
|
18
|
+
type SuccessStatusKey = 200 | 201 | 202 | 203 | 204 | '200' | '201' | '202' | '203' | '204';
|
|
19
|
+
type ErrorStatusKey =
|
|
20
|
+
| 400 | 401 | 403 | 404 | 409 | 413 | 415 | 422 | 429 | 500 | 502 | 503
|
|
21
|
+
| '400' | '401' | '403' | '404' | '409' | '413' | '415' | '422' | '429' | '500' | '502' | '503';
|
|
22
|
+
|
|
23
|
+
type IsSingleSchema<S> =
|
|
24
|
+
S extends { '~standard': any } ? true
|
|
25
|
+
: S extends { static: any } ? true
|
|
26
|
+
: S extends { _output: any } ? true
|
|
27
|
+
: S extends { type: string } ? true
|
|
28
|
+
: S extends { properties: Record<string, any> } ? true
|
|
29
|
+
: false;
|
|
30
|
+
|
|
31
|
+
export type InferResponseSuccess<R> =
|
|
32
|
+
IsSingleSchema<R> extends true
|
|
33
|
+
? InferSchema<R>
|
|
34
|
+
: R extends Record<string | number, any>
|
|
35
|
+
? ([Extract<keyof R, SuccessStatusKey>] extends [never]
|
|
36
|
+
? InferSchema<R[keyof R]>
|
|
37
|
+
: InferSchema<R[Extract<keyof R, SuccessStatusKey>]>)
|
|
38
|
+
: InferSchema<R>;
|
|
39
|
+
|
|
40
|
+
export type InferResponseError<R> =
|
|
41
|
+
IsSingleSchema<R> extends true
|
|
42
|
+
? any
|
|
43
|
+
: R extends Record<string | number, any>
|
|
44
|
+
? ([Extract<keyof R, ErrorStatusKey>] extends [never]
|
|
45
|
+
? any
|
|
46
|
+
: InferSchema<R[Extract<keyof R, ErrorStatusKey>]>)
|
|
47
|
+
: any;
|
|
48
|
+
|
|
17
49
|
type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
|
|
18
50
|
type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
|
|
19
51
|
type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends ''
|
|
@@ -48,7 +80,7 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (
|
|
|
48
80
|
) => Res | Promise<Res>;
|
|
49
81
|
|
|
50
82
|
type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
51
|
-
<P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ?
|
|
83
|
+
<P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(
|
|
52
84
|
path: P,
|
|
53
85
|
schemas: S,
|
|
54
86
|
handler: TypedRouterHandler<S, Res>
|
|
@@ -59,12 +91,13 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
|
59
91
|
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
|
|
60
92
|
headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
|
|
61
93
|
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
62
|
-
response: S extends { response: infer R } ?
|
|
94
|
+
response: S extends { response: infer R } ? InferResponseSuccess<R> : Awaited<Res>;
|
|
95
|
+
error: S extends { response: infer R } ? InferResponseError<R> : any;
|
|
63
96
|
}>>;
|
|
64
97
|
<P extends string, Res = any>(
|
|
65
98
|
path: P,
|
|
66
99
|
...handlers: any[]
|
|
67
|
-
): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res
|
|
100
|
+
): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>>;
|
|
68
101
|
};
|
|
69
102
|
|
|
70
103
|
export class BareRouter<Routes extends RouteSchema = {}> {
|
package/src/core/ws-match.ts
CHANGED
|
@@ -1,8 +1,23 @@
|
|
|
1
|
-
export interface WebSocketRouteHandler {
|
|
1
|
+
export interface WebSocketRouteHandler<Body = string | Buffer, Query = any, Headers = any, Res = any> {
|
|
2
|
+
/** Optional schema (Standard Schema v1 / TypeBox / Zod / Native) for incoming JSON messages */
|
|
3
|
+
body?: any;
|
|
4
|
+
/** Optional schema for WebSocket upgrade query parameters */
|
|
5
|
+
query?: any;
|
|
6
|
+
/** Optional schema for WebSocket upgrade request headers */
|
|
7
|
+
headers?: any;
|
|
8
|
+
/** Optional schema describing outgoing server messages (for typed bareTreaty/bareClient) */
|
|
9
|
+
response?: any;
|
|
10
|
+
/** Optional error callback when an incoming WS message fails `body` validation */
|
|
11
|
+
onValidationError?: (ws: any, error: { code: string; error: any; raw: any }) => void;
|
|
2
12
|
open?: (ws: any) => void;
|
|
3
|
-
message?: (ws: any, message:
|
|
13
|
+
message?: (ws: any, message: Body) => void | Promise<void>;
|
|
4
14
|
close?: (ws: any, code: number, reason: string) => void;
|
|
5
15
|
drain?: (ws: any) => void;
|
|
16
|
+
/** @internal Pre-compiled fail-closed upgrade validator (only present when query/headers schema is set) */
|
|
17
|
+
__validateUpgrade?: (urlOrReq: string | Request, headers?: Record<string, string> | Headers) =>
|
|
18
|
+
| { ok: true; query?: Query; headers?: Headers }
|
|
19
|
+
| { ok: false; code: string; error: any }
|
|
20
|
+
| Promise<{ ok: true; query?: Query; headers?: Headers } | { ok: false; code: string; error: any }>;
|
|
6
21
|
}
|
|
7
22
|
|
|
8
23
|
export interface WsMatchResult {
|
package/src/edge.ts
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
import { BareRouter } from './core/router';
|
|
2
|
+
import { Type, Type as t } from '@sinclair/typebox';
|
|
3
|
+
import { Z, Z as z, native, standard } from './security/validators';
|
|
4
|
+
import { bareClient, bareTreaty } from './client/index';
|
|
5
|
+
import { cors } from './security/cors';
|
|
6
|
+
import { securityHeaders } from './security/headers';
|
|
7
|
+
import { rateLimit } from './security/rateLimit';
|
|
8
|
+
import { timeout } from './security/timeout';
|
|
9
|
+
import { circuitBreaker } from './security/resilience';
|
|
10
|
+
import { redisStore } from './security/store';
|
|
11
|
+
import { healthcheck } from './utils/health';
|
|
12
|
+
import { logger } from './utils/logger';
|
|
13
|
+
import { generateOpenAPISpec, renderDocsHTML } from './utils/openapi';
|
|
14
|
+
|
|
15
|
+
export type EdgeNext = () => Promise<any> | any;
|
|
16
|
+
export type EdgeMiddleware<Env = Record<string, any>> = (ctx: EdgeContext<Env>, next: EdgeNext) => Promise<any> | any;
|
|
17
|
+
export type EdgeHandler<Env = Record<string, any>> = (ctx: EdgeContext<Env>) => Promise<any> | any;
|
|
18
|
+
|
|
19
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Pure Web-Standard request/response Context for Edge runtimes
|
|
23
|
+
* (Cloudflare Workers, Vercel Edge, Deno Deploy, Fastly Compute, Bun).
|
|
24
|
+
* Zero `node:*` imports.
|
|
25
|
+
*/
|
|
26
|
+
export class EdgeContext<Env = Record<string, any>> {
|
|
27
|
+
public req: Request;
|
|
28
|
+
public params: Record<string, string>;
|
|
29
|
+
public env: Env;
|
|
30
|
+
public executionCtx: any;
|
|
31
|
+
public store: Map<string, any> = new Map();
|
|
32
|
+
public body: any = undefined;
|
|
33
|
+
public user: any = undefined;
|
|
34
|
+
|
|
35
|
+
public _status: number = 200;
|
|
36
|
+
public _headers: Record<string, string> | undefined = undefined;
|
|
37
|
+
public _setCookies: string[] | undefined = undefined;
|
|
38
|
+
private _query: Record<string, string> | null = null;
|
|
39
|
+
private _cookies: Record<string, string> | null = null;
|
|
40
|
+
private _jsonCache: any = undefined;
|
|
41
|
+
private _jsonParsed: boolean = false;
|
|
42
|
+
private _requestId: string | null = null;
|
|
43
|
+
|
|
44
|
+
constructor(req: Request, params: Record<string, string> = {}, env: Env = {} as Env, executionCtx?: any) {
|
|
45
|
+
this.req = req;
|
|
46
|
+
this.params = params;
|
|
47
|
+
this.env = env;
|
|
48
|
+
this.executionCtx = executionCtx;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
public get requestId(): string {
|
|
52
|
+
if (!this._requestId) {
|
|
53
|
+
this._requestId = this.req.headers.get('x-request-id') || crypto.randomUUID();
|
|
54
|
+
}
|
|
55
|
+
return this._requestId;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
public get ip(): string {
|
|
59
|
+
return (
|
|
60
|
+
this.req.headers.get('cf-connecting-ip') ||
|
|
61
|
+
this.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
|
|
62
|
+
this.req.headers.get('x-real-ip') ||
|
|
63
|
+
'127.0.0.1'
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
public get query(): Record<string, string> {
|
|
68
|
+
if (this._query) return this._query;
|
|
69
|
+
const out: Record<string, string> = Object.create(null);
|
|
70
|
+
const qIdx = this.req.url.indexOf('?');
|
|
71
|
+
if (qIdx !== -1) {
|
|
72
|
+
const sp = new URLSearchParams(this.req.url.slice(qIdx + 1));
|
|
73
|
+
for (const [k, v] of sp) {
|
|
74
|
+
if (!FORBIDDEN_KEYS.has(k)) out[k] = v;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
this._query = out;
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
public get cookies(): Record<string, string> {
|
|
82
|
+
if (this._cookies) return this._cookies;
|
|
83
|
+
const out: Record<string, string> = Object.create(null);
|
|
84
|
+
const header = this.req.headers.get('cookie');
|
|
85
|
+
if (header) {
|
|
86
|
+
for (const pair of header.split(';')) {
|
|
87
|
+
const eq = pair.indexOf('=');
|
|
88
|
+
if (eq === -1) continue;
|
|
89
|
+
const k = pair.slice(0, eq).trim();
|
|
90
|
+
if (!k || FORBIDDEN_KEYS.has(k)) continue;
|
|
91
|
+
try {
|
|
92
|
+
out[k] = decodeURIComponent(pair.slice(eq + 1).trim());
|
|
93
|
+
} catch {
|
|
94
|
+
out[k] = pair.slice(eq + 1).trim();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
this._cookies = out;
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
public get(key: string): any {
|
|
103
|
+
return this.store.get(key);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
public set(key: string, value: any): this {
|
|
107
|
+
this.store.set(key, value);
|
|
108
|
+
return this;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
public status(code: number): this {
|
|
112
|
+
this._status = code;
|
|
113
|
+
return this;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
public setHeader(name: string, value: string): this {
|
|
117
|
+
if (!this._headers) this._headers = Object.create(null);
|
|
118
|
+
else if (Object.getPrototypeOf(this._headers) === Object.prototype) {
|
|
119
|
+
this._headers = { ...this._headers };
|
|
120
|
+
}
|
|
121
|
+
const safeName = (name.indexOf('\r') !== -1 || name.indexOf('\n') !== -1) ? name.replace(/[\r\n]+/g, '') : name;
|
|
122
|
+
const safeVal = (value.indexOf('\r') !== -1 || value.indexOf('\n') !== -1) ? value.replace(/[\r\n]+/g, '') : value;
|
|
123
|
+
this._headers![safeName.toLowerCase()] = safeVal;
|
|
124
|
+
return this;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
public appendHeader(name: string, value: string): this {
|
|
128
|
+
if (name.toLowerCase() === 'set-cookie') {
|
|
129
|
+
if (!this._setCookies) this._setCookies = [];
|
|
130
|
+
this._setCookies.push(value);
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
133
|
+
return this.setHeader(name, value);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
public setCookie(
|
|
137
|
+
name: string,
|
|
138
|
+
value: string,
|
|
139
|
+
opts: { maxAge?: number; path?: string; domain?: string; httpOnly?: boolean; secure?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' } = {}
|
|
140
|
+
): this {
|
|
141
|
+
const cleanName = name.replace(/[\r\n;= ]+/g, '');
|
|
142
|
+
const parts = [`${cleanName}=${encodeURIComponent(value)}`];
|
|
143
|
+
parts.push(`Path=${(opts.path ?? '/').replace(/[\r\n;]+/g, '')}`);
|
|
144
|
+
if (opts.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(opts.maxAge)}`);
|
|
145
|
+
if (opts.domain) parts.push(`Domain=${opts.domain.replace(/[\r\n;]+/g, '')}`);
|
|
146
|
+
if (opts.httpOnly !== false) parts.push('HttpOnly');
|
|
147
|
+
if (opts.secure) parts.push('Secure');
|
|
148
|
+
parts.push(`SameSite=${opts.sameSite ?? 'Lax'}`);
|
|
149
|
+
return this.appendHeader('Set-Cookie', parts.join('; '));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
public deleteCookie(name: string, path: string = '/'): this {
|
|
153
|
+
return this.setCookie(name, '', { maxAge: 0, path });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
public async jsonBody(maxBytes: number = 1024 * 1024): Promise<any> {
|
|
157
|
+
if (this._jsonParsed) return this._jsonCache;
|
|
158
|
+
const raw = await this.req.text();
|
|
159
|
+
if (new TextEncoder().encode(raw).byteLength > maxBytes) {
|
|
160
|
+
const err: any = new Error('Payload Too Large');
|
|
161
|
+
err.status = 413;
|
|
162
|
+
throw err;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
this._jsonCache = raw ? JSON.parse(raw) : null;
|
|
166
|
+
} catch {
|
|
167
|
+
const err: any = new Error('Malformed JSON payload');
|
|
168
|
+
err.status = 400;
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
this._jsonParsed = true;
|
|
172
|
+
return this._jsonCache;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public async textBody(): Promise<string> {
|
|
176
|
+
return this.req.text();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private buildHeaders(defaultContentType: string): Headers {
|
|
180
|
+
const h = new Headers();
|
|
181
|
+
if (this._headers) {
|
|
182
|
+
for (const k in this._headers) {
|
|
183
|
+
h.set(k, this._headers[k]!);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (this._setCookies) {
|
|
187
|
+
for (let i = 0; i < this._setCookies.length; i++) {
|
|
188
|
+
h.append('set-cookie', this._setCookies[i]!);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!h.has('content-type')) h.set('content-type', defaultContentType);
|
|
192
|
+
return h;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
public json(data: any, status?: number): Response {
|
|
196
|
+
return new Response(JSON.stringify(data), {
|
|
197
|
+
status: status ?? this._status,
|
|
198
|
+
headers: this.buildHeaders('application/json; charset=utf-8')
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
public text(data: string, status?: number): Response {
|
|
203
|
+
return new Response(data, {
|
|
204
|
+
status: status ?? this._status,
|
|
205
|
+
headers: this.buildHeaders('text/plain; charset=utf-8')
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
public html(data: string, status?: number): Response {
|
|
210
|
+
return new Response(data, {
|
|
211
|
+
status: status ?? this._status,
|
|
212
|
+
headers: this.buildHeaders('text/html; charset=utf-8')
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
public send(msg: string, extra?: Record<string, any>): Response {
|
|
217
|
+
return this.json({ status: this._status, msg, ...extra });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
public redirect(url: string, status: number = 302): Response {
|
|
221
|
+
const h = new Headers();
|
|
222
|
+
if (this._headers) {
|
|
223
|
+
for (const k in this._headers) h.set(k, this._headers[k]!);
|
|
224
|
+
}
|
|
225
|
+
h.set('location', url.replace(/[\r\n]+/g, ''));
|
|
226
|
+
return new Response(null, { status, headers: h });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
interface EdgeRouteEntry<Env> {
|
|
231
|
+
middlewares: EdgeMiddleware<Env>[];
|
|
232
|
+
handler: EdgeHandler<Env>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
class EdgeRadixNode<Env> {
|
|
236
|
+
children: Record<string, EdgeRadixNode<Env>> = Object.create(null);
|
|
237
|
+
paramNode: EdgeRadixNode<Env> | null = null;
|
|
238
|
+
wildcardNode: EdgeRadixNode<Env> | null = null;
|
|
239
|
+
entry: EdgeRouteEntry<Env> | null = null;
|
|
240
|
+
paramNames: string[] = [];
|
|
241
|
+
|
|
242
|
+
insert(path: string, entry: EdgeRouteEntry<Env>): void {
|
|
243
|
+
let node: EdgeRadixNode<Env> = this;
|
|
244
|
+
const parts = path.split('/').filter(Boolean);
|
|
245
|
+
const paramNames: string[] = [];
|
|
246
|
+
for (const part of parts) {
|
|
247
|
+
if (part === '*') {
|
|
248
|
+
if (!node.wildcardNode) node.wildcardNode = new EdgeRadixNode<Env>();
|
|
249
|
+
node = node.wildcardNode;
|
|
250
|
+
break;
|
|
251
|
+
} else if (part.startsWith(':')) {
|
|
252
|
+
if (!node.paramNode) node.paramNode = new EdgeRadixNode<Env>();
|
|
253
|
+
paramNames.push(part.slice(1));
|
|
254
|
+
node = node.paramNode;
|
|
255
|
+
} else {
|
|
256
|
+
if (!node.children[part]) node.children[part] = new EdgeRadixNode<Env>();
|
|
257
|
+
node = node.children[part]!;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
node.entry = entry;
|
|
261
|
+
node.paramNames = paramNames;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
search(pathname: string): { entry: EdgeRouteEntry<Env>; params: Record<string, string> } | null {
|
|
265
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
266
|
+
const match = (
|
|
267
|
+
node: EdgeRadixNode<Env>,
|
|
268
|
+
idx: number,
|
|
269
|
+
vals: string[]
|
|
270
|
+
): { entry: EdgeRouteEntry<Env>; params: Record<string, string> } | null => {
|
|
271
|
+
if (idx === parts.length) {
|
|
272
|
+
if (!node.entry) return null;
|
|
273
|
+
const params: Record<string, string> = Object.create(null);
|
|
274
|
+
for (let i = 0; i < node.paramNames.length; i++) {
|
|
275
|
+
const name = node.paramNames[i]!;
|
|
276
|
+
if (!FORBIDDEN_KEYS.has(name)) params[name] = vals[i]!;
|
|
277
|
+
}
|
|
278
|
+
return { entry: node.entry, params };
|
|
279
|
+
}
|
|
280
|
+
const seg = parts[idx]!;
|
|
281
|
+
const child = node.children[seg];
|
|
282
|
+
if (child) {
|
|
283
|
+
const res = match(child, idx + 1, vals);
|
|
284
|
+
if (res) return res;
|
|
285
|
+
}
|
|
286
|
+
if (node.paramNode) {
|
|
287
|
+
vals.push(seg);
|
|
288
|
+
const res = match(node.paramNode, idx + 1, vals);
|
|
289
|
+
if (res) return res;
|
|
290
|
+
vals.pop();
|
|
291
|
+
}
|
|
292
|
+
if (node.wildcardNode && node.wildcardNode.entry) {
|
|
293
|
+
const params: Record<string, string> = Object.create(null);
|
|
294
|
+
for (let i = 0; i < node.wildcardNode.paramNames.length; i++) {
|
|
295
|
+
const name = node.wildcardNode.paramNames[i]!;
|
|
296
|
+
if (!FORBIDDEN_KEYS.has(name)) params[name] = vals[i]!;
|
|
297
|
+
}
|
|
298
|
+
params['*'] = parts.slice(idx).join('/');
|
|
299
|
+
return { entry: node.wildcardNode.entry, params };
|
|
300
|
+
}
|
|
301
|
+
return null;
|
|
302
|
+
};
|
|
303
|
+
return match(this, 0, []);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Zero-Node Edge Web Framework (`barejs/edge`).
|
|
309
|
+
* Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
|
|
310
|
+
*/
|
|
311
|
+
export class BareEdge<Env = Record<string, any>> {
|
|
312
|
+
private staticRoutes: Map<string, EdgeRouteEntry<Env>> = new Map();
|
|
313
|
+
private dynamicTrees: Map<string, EdgeRadixNode<Env>> = new Map();
|
|
314
|
+
private middlewares: EdgeMiddleware<Env>[] = [];
|
|
315
|
+
private requestHooks: Array<(ctx: EdgeContext<Env>) => Promise<void> | void> = [];
|
|
316
|
+
private responseHooks: Array<(ctx: EdgeContext<Env>, res: Response) => Promise<void> | void> = [];
|
|
317
|
+
private errorHandler: ((err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>) | null = null;
|
|
318
|
+
|
|
319
|
+
public use(mw: EdgeMiddleware<Env>): this {
|
|
320
|
+
this.middlewares.push(mw);
|
|
321
|
+
return this;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
public onRequest(fn: (ctx: EdgeContext<Env>) => Promise<void> | void): this {
|
|
325
|
+
this.requestHooks.push(fn);
|
|
326
|
+
return this;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
public onResponse(fn: (ctx: EdgeContext<Env>, res: Response) => Promise<void> | void): this {
|
|
330
|
+
this.responseHooks.push(fn);
|
|
331
|
+
return this;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
public onError(fn: (err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>): this {
|
|
335
|
+
this.errorHandler = fn;
|
|
336
|
+
return this;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private add(method: string, path: string, ...fns: EdgeMiddleware<Env>[]): this {
|
|
340
|
+
if (fns.length === 0) return this;
|
|
341
|
+
const handler = fns[fns.length - 1] as EdgeHandler<Env>;
|
|
342
|
+
const middlewares = fns.slice(0, -1);
|
|
343
|
+
const cleanPath = path.startsWith('/') ? path : `/${path}`;
|
|
344
|
+
const entry: EdgeRouteEntry<Env> = { middlewares, handler };
|
|
345
|
+
|
|
346
|
+
if (!cleanPath.includes(':') && !cleanPath.includes('*')) {
|
|
347
|
+
this.staticRoutes.set(`${method}:${cleanPath}`, entry);
|
|
348
|
+
} else {
|
|
349
|
+
let tree = this.dynamicTrees.get(method);
|
|
350
|
+
if (!tree) {
|
|
351
|
+
tree = new EdgeRadixNode<Env>();
|
|
352
|
+
this.dynamicTrees.set(method, tree);
|
|
353
|
+
}
|
|
354
|
+
tree.insert(cleanPath, entry);
|
|
355
|
+
}
|
|
356
|
+
return this;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
public get(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('GET', path, ...fns); }
|
|
360
|
+
public post(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('POST', path, ...fns); }
|
|
361
|
+
public put(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('PUT', path, ...fns); }
|
|
362
|
+
public patch(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('PATCH', path, ...fns); }
|
|
363
|
+
public delete(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('DELETE', path, ...fns); }
|
|
364
|
+
public options(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('OPTIONS', path, ...fns); }
|
|
365
|
+
public head(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('HEAD', path, ...fns); }
|
|
366
|
+
public all(path: string, ...fns: EdgeMiddleware<Env>[]): this {
|
|
367
|
+
for (const m of ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']) {
|
|
368
|
+
this.add(m, path, ...fns);
|
|
369
|
+
}
|
|
370
|
+
return this;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private normalizeResponse(ctx: EdgeContext<Env>, out: any): Response {
|
|
374
|
+
if (out instanceof Response) return out;
|
|
375
|
+
if (typeof out === 'string') return ctx.text(out);
|
|
376
|
+
if (out === null || out === undefined) return new Response(null, { status: 204 });
|
|
377
|
+
return ctx.json(out);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
public fetch = async (req: Request, env?: Env, executionCtx?: any): Promise<Response> => {
|
|
381
|
+
const url = req.url;
|
|
382
|
+
const pathStart = url.indexOf('/', 8);
|
|
383
|
+
const qStart = pathStart === -1 ? -1 : url.indexOf('?', pathStart);
|
|
384
|
+
const pathname = pathStart === -1 ? '/' : (qStart === -1 ? url.slice(pathStart) : url.slice(pathStart, qStart));
|
|
385
|
+
const method = req.method;
|
|
386
|
+
|
|
387
|
+
let entry: EdgeRouteEntry<Env> | undefined = this.staticRoutes.get(`${method}:${pathname}`);
|
|
388
|
+
let params: Record<string, string> = {};
|
|
389
|
+
|
|
390
|
+
if (!entry) {
|
|
391
|
+
const tree = this.dynamicTrees.get(method);
|
|
392
|
+
if (tree) {
|
|
393
|
+
const matched = tree.search(pathname);
|
|
394
|
+
if (matched) {
|
|
395
|
+
entry = matched.entry;
|
|
396
|
+
params = matched.params;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const ctx = new EdgeContext<Env>(req, params, env ?? ({} as Env), executionCtx);
|
|
402
|
+
|
|
403
|
+
try {
|
|
404
|
+
for (let i = 0; i < this.requestHooks.length; i++) {
|
|
405
|
+
await this.requestHooks[i]!(ctx);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const chain: EdgeMiddleware<Env>[] = entry
|
|
409
|
+
? [...this.middlewares, ...entry.middlewares, entry.handler]
|
|
410
|
+
: [...this.middlewares, () => new Response(JSON.stringify({ status: 404, message: 'Not Found' }), {
|
|
411
|
+
status: 404,
|
|
412
|
+
headers: { 'content-type': 'application/json; charset=utf-8' }
|
|
413
|
+
})];
|
|
414
|
+
|
|
415
|
+
let idx = -1;
|
|
416
|
+
const dispatch = async (i: number): Promise<any> => {
|
|
417
|
+
if (i <= idx) throw new Error('next() called multiple times');
|
|
418
|
+
idx = i;
|
|
419
|
+
const fn = chain[i];
|
|
420
|
+
if (!fn) return undefined;
|
|
421
|
+
return fn(ctx, () => dispatch(i + 1));
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
const raw = await dispatch(0);
|
|
425
|
+
const res = this.normalizeResponse(ctx, raw);
|
|
426
|
+
|
|
427
|
+
for (let i = 0; i < this.responseHooks.length; i++) {
|
|
428
|
+
await this.responseHooks[i]!(ctx, res);
|
|
429
|
+
}
|
|
430
|
+
return res;
|
|
431
|
+
} catch (err: any) {
|
|
432
|
+
if (this.errorHandler) {
|
|
433
|
+
return this.errorHandler(err, ctx);
|
|
434
|
+
}
|
|
435
|
+
const status = err?.status >= 400 && err?.status < 600 ? err.status : 500;
|
|
436
|
+
return new Response(
|
|
437
|
+
JSON.stringify({ status, message: status < 500 ? (err?.message || 'Bad Request') : 'Internal Server Error' }),
|
|
438
|
+
{ status, headers: { 'content-type': 'application/json; charset=utf-8' } }
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
public request(path: string, init?: RequestInit, env?: Env): Promise<Response> {
|
|
444
|
+
const url = path.startsWith('http://') || path.startsWith('https://')
|
|
445
|
+
? path
|
|
446
|
+
: `http://localhost${path.startsWith('/') ? path : `/${path}`}`;
|
|
447
|
+
return this.fetch(new Request(url, init), env);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export function createSingleflight() {
|
|
452
|
+
const inflight = new Map<string, Promise<any>>();
|
|
453
|
+
return {
|
|
454
|
+
do<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
455
|
+
const existing = inflight.get(key);
|
|
456
|
+
if (existing) return existing;
|
|
457
|
+
const p = Promise.resolve()
|
|
458
|
+
.then(fn)
|
|
459
|
+
.finally(() => {
|
|
460
|
+
inflight.delete(key);
|
|
461
|
+
});
|
|
462
|
+
inflight.set(key, p);
|
|
463
|
+
return p;
|
|
464
|
+
},
|
|
465
|
+
size(): number {
|
|
466
|
+
return inflight.size;
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
472
|
+
|
|
473
|
+
export {
|
|
474
|
+
BareEdge as BareJS,
|
|
475
|
+
BareRouter,
|
|
476
|
+
Type,
|
|
477
|
+
t,
|
|
478
|
+
Z,
|
|
479
|
+
z,
|
|
480
|
+
native,
|
|
481
|
+
standard,
|
|
482
|
+
bareClient,
|
|
483
|
+
bareTreaty,
|
|
484
|
+
cors,
|
|
485
|
+
securityHeaders,
|
|
486
|
+
rateLimit,
|
|
487
|
+
timeout,
|
|
488
|
+
circuitBreaker,
|
|
489
|
+
redisStore,
|
|
490
|
+
healthcheck,
|
|
491
|
+
logger,
|
|
492
|
+
generateOpenAPISpec,
|
|
493
|
+
renderDocsHTML
|
|
494
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
10
|
-
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
9
|
+
export { BareJS, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
10
|
+
export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Plugin Interface for BareJS
|
|
@@ -37,7 +37,7 @@ import { Type } from "@sinclair/typebox";
|
|
|
37
37
|
export { Type, Type as T, Type as TypeBox };
|
|
38
38
|
|
|
39
39
|
// --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
|
|
40
|
-
import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
|
|
40
|
+
import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, isStatusResponseMap, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
|
|
41
41
|
export {
|
|
42
42
|
// TypeBox Engine
|
|
43
43
|
typebox,
|
|
@@ -50,14 +50,18 @@ export {
|
|
|
50
50
|
// Native Engine
|
|
51
51
|
native,
|
|
52
52
|
native as n,
|
|
53
|
+
// Standard Schema v1 Engine (Valibot, ArkType, Zod 4, Effect, etc.)
|
|
54
|
+
standard,
|
|
53
55
|
// Auto-Detect Engine
|
|
54
56
|
validate,
|
|
55
57
|
validate as v,
|
|
56
58
|
// Unified Route Schema Engine (body, query, params, headers, response, detail, maxBodySize)
|
|
57
59
|
schemaValidator,
|
|
58
60
|
createResponseFilter,
|
|
61
|
+
isStatusResponseMap,
|
|
59
62
|
type RouteSchemas,
|
|
60
|
-
type RouteDetail
|
|
63
|
+
type RouteDetail,
|
|
64
|
+
type StandardSchemaV1
|
|
61
65
|
};
|
|
62
66
|
|
|
63
67
|
// --- 5. Middlewares & Utilities ---
|
|
@@ -82,6 +86,7 @@ export { securityHeaders, type SecurityHeadersOptions } from './security/headers
|
|
|
82
86
|
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
83
87
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
84
88
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
89
|
+
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
85
90
|
|
|
86
91
|
// --- 6. Authentication (Bun Native) ---
|
|
87
92
|
// Always deploy using process.env [2026-01-06]
|
|
@@ -89,10 +94,16 @@ export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked,
|
|
|
89
94
|
// --- 7. Hashing ---
|
|
90
95
|
export { Hash as Password, Hash } from './security/hash';
|
|
91
96
|
|
|
92
|
-
// --- 8. Type-Safe RPC Client ---
|
|
97
|
+
// --- 8. Type-Safe RPC Client & Treaty ---
|
|
93
98
|
export {
|
|
94
99
|
bareClient,
|
|
100
|
+
bareTreaty,
|
|
95
101
|
type BareClient,
|
|
102
|
+
type BareSafeClient,
|
|
103
|
+
type BareTreatyNode,
|
|
104
|
+
type TreatyTree,
|
|
105
|
+
type BareClientResult,
|
|
106
|
+
type BareWsClient,
|
|
96
107
|
type BareClientOptions,
|
|
97
108
|
type ClientRequestOptions,
|
|
98
109
|
type RouteEndpoint,
|