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
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export interface TracingSpan {
|
|
3
|
+
traceId: string;
|
|
4
|
+
spanId: string;
|
|
5
|
+
parentSpanId?: string;
|
|
6
|
+
traceparent: string;
|
|
7
|
+
method: string;
|
|
8
|
+
path: string;
|
|
9
|
+
status: number;
|
|
10
|
+
durationMs: number;
|
|
11
|
+
}
|
|
12
|
+
export interface TracingOptions {
|
|
13
|
+
/** Metric name emitted in `Server-Timing` header (default: `'app'`). Set `false` to omit. */
|
|
14
|
+
serverTiming?: string | false;
|
|
15
|
+
/** Echo W3C `traceparent` response header (default: `true`) */
|
|
16
|
+
exposeTraceparent?: boolean;
|
|
17
|
+
/** Optional span callback for forwarding to OTLP / APM / structured logger */
|
|
18
|
+
onSpan?: (span: TracingSpan) => void;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Zero-dependency W3C `traceparent` + `Server-Timing` middleware.
|
|
22
|
+
* Tree-shakeable and Edge-safe (uses Web Crypto `crypto.getRandomValues` + `performance.now()`).
|
|
23
|
+
*/
|
|
24
|
+
export declare const tracing: (options?: TracingOptions) => Middleware;
|
|
25
|
+
export declare const serverTiming: (metricName?: string) => Middleware;
|
package/llms.txt
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
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), and **
|
|
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**, and **Edge Workers** (`barejs/edge` — zero `node:*` imports) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** (`bun create barejs my-app [--bun|--node|--node-uws|--deno]`), built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CRLF injection protection, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits), and **Full Multi-Runtime Test Suite (487 tests / 6,772 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
|
|
4
4
|
|
|
5
|
-
## 1.
|
|
5
|
+
## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge)
|
|
6
|
+
```bash
|
|
7
|
+
bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWebSockets.js, Deno)
|
|
8
|
+
bun create barejs my-app --bun # --bun | --node | --node-uws | --deno
|
|
9
|
+
```
|
|
6
10
|
```ts
|
|
7
|
-
import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20)
|
|
11
|
+
import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
|
|
8
12
|
|
|
9
13
|
// 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)
|
|
10
14
|
const app = new BareJS();
|
|
@@ -16,7 +20,8 @@ app.get('/ping', () => 'pong');
|
|
|
16
20
|
// Wildcard catch-all route (`ctx.params['*']`)
|
|
17
21
|
app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
|
|
18
22
|
|
|
19
|
-
|
|
23
|
+
// Native TLS works across Bun, uWebSockets.js (SSLApp), and Node https:
|
|
24
|
+
app.listen(3000); // or app.listen(8443, '0.0.0.0', false, { tls: { keyFileName, certFileName } })
|
|
20
25
|
```
|
|
21
26
|
|
|
22
27
|
## 2. Routing, Plugins & Unified Schema Validation
|
|
@@ -38,7 +43,7 @@ app.post('/users/:id', {
|
|
|
38
43
|
password_hash: 'secret' // automatically stripped before sending to client!
|
|
39
44
|
}));
|
|
40
45
|
```
|
|
41
|
-
Supports **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({ properties: { a: { type: 'string' }, b: { type: 'number' } }, required: ['a'] })`).
|
|
46
|
+
Supports **Standard Schema v1** (`~standard` — Valibot, ArkType, Zod 4, Effect; sync & async fail-closed), **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({ properties: { a: { type: 'string' }, b: { type: 'number' } }, required: ['a'] })`).
|
|
42
47
|
|
|
43
48
|
### Modular Routers & Plugins
|
|
44
49
|
```ts
|
|
@@ -125,9 +130,11 @@ app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://aut
|
|
|
125
130
|
- **SSE**: `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` (works across Bun, Node.js, Deno)
|
|
126
131
|
- **JSON-RPC 2.0**: `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b })` (supports single, batch, notifications, and standard `-32700`/`-32600`/`-32601`/`-32603` error codes)
|
|
127
132
|
- **OpenAPI 3.1 + Scalar UI**: `app.docs('/docs', { title: 'My API', version: '1.0.0' })` (serves `/docs` & `/docs/json` with full `params`, `query`, `headers`, `body`, `response`, and `detail`)
|
|
128
|
-
- **Type-Safe Client (URL or Zero-Network In-Memory `app`)**:
|
|
133
|
+
- **Type-Safe Client & Chained RPC (`bareClient` / `bareTreaty`, URL or Zero-Network In-Memory `app`)**:
|
|
129
134
|
- Network: `const api = bareClient('http://localhost:3000');`
|
|
130
135
|
- In-Memory (SSR / Unit Tests): `const api = bareClient(app); await api.get('/users/:id', { params: { id: 1 } });`
|
|
136
|
+
- Non-Throwing Result Union: `const res = await api.safe.get('/users/:id', { params: { id: 1 } }); // { ok: true, data } | { ok: false, error, status }`
|
|
137
|
+
- Chained Proxy RPC & Typed WebSockets: `const treaty = bareTreaty(app); await treaty.users({ id: 1 }).get(); const ws = treaty.ws.chat.subscribe();`
|
|
131
138
|
|
|
132
139
|
## 7. Lifecycle & Error Handling
|
|
133
140
|
```ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"author": "xarhang",
|
|
5
5
|
"description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -17,6 +17,10 @@
|
|
|
17
17
|
"./node": {
|
|
18
18
|
"types": "./dist/types/node.d.ts",
|
|
19
19
|
"import": "./dist/node.js"
|
|
20
|
+
},
|
|
21
|
+
"./edge": {
|
|
22
|
+
"types": "./dist/types/edge.d.ts",
|
|
23
|
+
"import": "./dist/edge.js"
|
|
20
24
|
}
|
|
21
25
|
},
|
|
22
26
|
"engines": {
|
|
@@ -32,8 +36,8 @@
|
|
|
32
36
|
"test": "bun test",
|
|
33
37
|
"test:node": "NODE_OPTIONS=--expose-gc vitest run && node tests/node-smoke.mjs",
|
|
34
38
|
"test:deno": "deno test --allow-all --unstable-sloppy-imports --no-check --v8-flags=--expose-gc --config deno.test.json --ignore=tests/playwright.test.ts,tests/production-db.test.ts tests/ && deno run --allow-net --allow-read --allow-write --allow-env tests/deno-smoke.ts",
|
|
35
|
-
"benchs": "bun run benchmarks/index.ts",
|
|
36
|
-
"bench": "bun run benchmarks/head-to-head.ts",
|
|
39
|
+
"benchs": "NODE_ENV=production bun run benchmarks/index.ts",
|
|
40
|
+
"bench": "NODE_ENV=production bun run benchmarks/head-to-head.ts",
|
|
37
41
|
"dev": "bun --watch Example/index.ts",
|
|
38
42
|
"build": "bun ./scripts/build.ts",
|
|
39
43
|
"prepublishOnly": "bun run build",
|
package/src/client/index.ts
CHANGED
|
@@ -10,6 +10,19 @@ export interface BareClientOptions {
|
|
|
10
10
|
fetch?: typeof fetch;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
export type BareClientResult<T = any, E = any> =
|
|
14
|
+
| { ok: true; data: T; error: null; status: number; headers: Headers }
|
|
15
|
+
| { ok: false; data: null; error: E; status: number; headers: Headers };
|
|
16
|
+
|
|
17
|
+
export interface BareWsClient<In = any, Out = In> {
|
|
18
|
+
send(data: Out): void;
|
|
19
|
+
onMessage(cb: (data: In) => void): () => void;
|
|
20
|
+
onOpen(cb: () => void): () => void;
|
|
21
|
+
onClose(cb: (code: number, reason: string) => void): () => void;
|
|
22
|
+
close(code?: number, reason?: string): void;
|
|
23
|
+
readonly readyState: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
13
26
|
type ExtractParams<Path extends string> =
|
|
14
27
|
Path extends `${string}:${infer Param}/${infer Rest}`
|
|
15
28
|
? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string | number }
|
|
@@ -25,6 +38,7 @@ export interface RouteEndpoint {
|
|
|
25
38
|
headers?: Record<string, any>;
|
|
26
39
|
body?: any;
|
|
27
40
|
response?: any;
|
|
41
|
+
error?: any;
|
|
28
42
|
}
|
|
29
43
|
|
|
30
44
|
export type RouteSchema = Record<string, RouteEndpoint>;
|
|
@@ -51,6 +65,130 @@ type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends
|
|
|
51
65
|
headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
|
|
52
66
|
} & (WithBody extends true ? { body?: R['body'] } : {});
|
|
53
67
|
|
|
68
|
+
type TreatyMethodOptions<R extends RouteEndpoint, WithBody extends boolean> =
|
|
69
|
+
Omit<ClientRequestOptions, 'params' | 'query' | 'headers' | (WithBody extends true ? 'body' : never)> & {
|
|
70
|
+
query?: R['query'] extends Record<string, any> ? R['query'] : ClientRequestOptions['query'];
|
|
71
|
+
headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
|
|
72
|
+
} & (WithBody extends true ? { body?: R['body'] } : {});
|
|
73
|
+
|
|
74
|
+
type EndpointError<R extends RouteEndpoint> = 'error' extends keyof R ? R['error'] : any;
|
|
75
|
+
|
|
76
|
+
export interface BareSafeClient<Routes extends RouteSchema = RouteSchema> {
|
|
77
|
+
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
|
|
78
|
+
path: P,
|
|
79
|
+
options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint
|
|
80
|
+
? EndpointOptions<R, P & string, false>
|
|
81
|
+
: ClientRequestOptions
|
|
82
|
+
): Promise<BareClientResult<
|
|
83
|
+
LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
|
|
84
|
+
LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
|
|
85
|
+
>>;
|
|
86
|
+
|
|
87
|
+
post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(
|
|
88
|
+
path: P,
|
|
89
|
+
options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint
|
|
90
|
+
? EndpointOptions<R, P & string, true>
|
|
91
|
+
: ClientRequestOptions
|
|
92
|
+
): Promise<BareClientResult<
|
|
93
|
+
LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
|
|
94
|
+
LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
|
|
95
|
+
>>;
|
|
96
|
+
|
|
97
|
+
put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(
|
|
98
|
+
path: P,
|
|
99
|
+
options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint
|
|
100
|
+
? EndpointOptions<R, P & string, true>
|
|
101
|
+
: ClientRequestOptions
|
|
102
|
+
): Promise<BareClientResult<
|
|
103
|
+
LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
|
|
104
|
+
LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
|
|
105
|
+
>>;
|
|
106
|
+
|
|
107
|
+
patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(
|
|
108
|
+
path: P,
|
|
109
|
+
options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint
|
|
110
|
+
? EndpointOptions<R, P & string, true>
|
|
111
|
+
: ClientRequestOptions
|
|
112
|
+
): Promise<BareClientResult<
|
|
113
|
+
LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
|
|
114
|
+
LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
|
|
115
|
+
>>;
|
|
116
|
+
|
|
117
|
+
delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(
|
|
118
|
+
path: P,
|
|
119
|
+
options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint
|
|
120
|
+
? EndpointOptions<R, P & string, false>
|
|
121
|
+
: ClientRequestOptions
|
|
122
|
+
): Promise<BareClientResult<
|
|
123
|
+
LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
|
|
124
|
+
LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
|
|
125
|
+
>>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Chained Proxy RPC fallback type (for untyped remote URLs)
|
|
129
|
+
export type BareTreatyNode = {
|
|
130
|
+
get<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
|
|
131
|
+
post<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
|
|
132
|
+
put<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
|
|
133
|
+
patch<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
|
|
134
|
+
delete<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
|
|
135
|
+
subscribe<In = any, Out = In>(options?: { query?: Record<string, string | number | boolean | undefined>; headers?: Record<string, string> }): BareWsClient<In, Out>;
|
|
136
|
+
(params: Record<string, string | number> | string | number): BareTreatyNode;
|
|
137
|
+
} & {
|
|
138
|
+
[segment: string]: BareTreatyNode;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
// Strict compile-time path-tree builder for Eden Treaty-style autocomplete (0 runtime overhead)
|
|
142
|
+
type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
|
|
143
|
+
type TrimLeadingSlash<P extends string> = P extends `/${infer Rest}` ? TrimLeadingSlash<Rest> : P;
|
|
144
|
+
|
|
145
|
+
type TreatyLeaf<R extends RouteEndpoint> =
|
|
146
|
+
R['method'] extends 'GET'
|
|
147
|
+
? { get(options?: TreatyMethodOptions<R, false>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
|
|
148
|
+
: R['method'] extends 'POST'
|
|
149
|
+
? { post(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
|
|
150
|
+
: R['method'] extends 'PUT'
|
|
151
|
+
? { put(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
|
|
152
|
+
: R['method'] extends 'PATCH'
|
|
153
|
+
? { patch(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
|
|
154
|
+
: R['method'] extends 'DELETE'
|
|
155
|
+
? { delete(options?: TreatyMethodOptions<R, false>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
|
|
156
|
+
: R['method'] extends 'WS'
|
|
157
|
+
? {
|
|
158
|
+
subscribe(options?: {
|
|
159
|
+
query?: R['query'] extends Record<string, any> ? R['query'] : Record<string, string | number | boolean | undefined>;
|
|
160
|
+
headers?: R['headers'] extends Record<string, any> ? R['headers'] : Record<string, string>;
|
|
161
|
+
}): BareWsClient<R['response'], R['body']>;
|
|
162
|
+
}
|
|
163
|
+
: {};
|
|
164
|
+
|
|
165
|
+
type PathToTree<Path extends string, Leaf> =
|
|
166
|
+
Path extends ''
|
|
167
|
+
? Leaf
|
|
168
|
+
: Path extends `:${infer Param}/${infer Rest}`
|
|
169
|
+
? { (params: Record<Param, string | number> | string | number): PathToTree<Rest, Leaf> }
|
|
170
|
+
: Path extends `:${infer Param}`
|
|
171
|
+
? { (params: Record<Param, string | number> | string | number): Leaf }
|
|
172
|
+
: Path extends `${infer Seg}/${infer Rest}`
|
|
173
|
+
? { [K in Seg]: PathToTree<Rest, Leaf> }
|
|
174
|
+
: { [K in Path]: Leaf };
|
|
175
|
+
|
|
176
|
+
export type TreatyTree<Routes extends RouteSchema> =
|
|
177
|
+
string extends keyof Routes
|
|
178
|
+
? BareTreatyNode
|
|
179
|
+
: [keyof Routes] extends [never]
|
|
180
|
+
? BareTreatyNode
|
|
181
|
+
: UnionToIntersection<
|
|
182
|
+
{
|
|
183
|
+
[K in keyof Routes]: Routes[K] extends infer R extends RouteEndpoint
|
|
184
|
+
? PathToTree<
|
|
185
|
+
TrimLeadingSlash<R['path'] extends string ? R['path'] : (K extends `${string} ${infer P}` ? P : '')>,
|
|
186
|
+
TreatyLeaf<R>
|
|
187
|
+
>
|
|
188
|
+
: never;
|
|
189
|
+
}[keyof Routes]
|
|
190
|
+
>;
|
|
191
|
+
|
|
54
192
|
export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
55
193
|
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
|
|
56
194
|
path: P,
|
|
@@ -86,6 +224,22 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
|
86
224
|
? EndpointOptions<R, P & string, false>
|
|
87
225
|
: ClientRequestOptions
|
|
88
226
|
): Promise<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
227
|
+
|
|
228
|
+
/** Discriminated Result Union client (never throws on 4xx/5xx) */
|
|
229
|
+
safe: BareSafeClient<Routes>;
|
|
230
|
+
|
|
231
|
+
/** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult with strict compile-time inference */
|
|
232
|
+
treaty: TreatyTree<Routes>;
|
|
233
|
+
|
|
234
|
+
/** Typed WebSocket client (supports both ws:// network URLs and in-memory BareJS app testing) */
|
|
235
|
+
ws<In = any, Out = In>(
|
|
236
|
+
path: string,
|
|
237
|
+
options?: {
|
|
238
|
+
params?: Record<string, string | number>;
|
|
239
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
240
|
+
headers?: Record<string, string>;
|
|
241
|
+
}
|
|
242
|
+
): BareWsClient<In, Out>;
|
|
89
243
|
}
|
|
90
244
|
|
|
91
245
|
const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
|
|
@@ -111,6 +265,171 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
|
|
|
111
265
|
return url;
|
|
112
266
|
};
|
|
113
267
|
|
|
268
|
+
const parseWsPayload = (raw: any): any => {
|
|
269
|
+
if (typeof raw === 'string') {
|
|
270
|
+
const trimmed = raw.trim();
|
|
271
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
272
|
+
try {
|
|
273
|
+
return JSON.parse(trimmed);
|
|
274
|
+
} catch {
|
|
275
|
+
return raw;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return raw;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const serializeWsPayload = (data: any): any => {
|
|
283
|
+
if (typeof data === 'string' || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
284
|
+
return data;
|
|
285
|
+
}
|
|
286
|
+
return JSON.stringify(data);
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
const createInMemoryWsClient = <In = any, Out = In>(
|
|
290
|
+
app: any,
|
|
291
|
+
url: string,
|
|
292
|
+
headers?: Record<string, string>
|
|
293
|
+
): BareWsClient<In, Out> => {
|
|
294
|
+
const msgListeners = new Set<(data: In) => void>();
|
|
295
|
+
const openListeners = new Set<() => void>();
|
|
296
|
+
const closeListeners = new Set<(code: number, reason: string) => void>();
|
|
297
|
+
let readyState = 1; // OPEN
|
|
298
|
+
|
|
299
|
+
const parsed = new URL(url);
|
|
300
|
+
const wsRoutes: Map<string, any> | undefined = app?.wsRoutes;
|
|
301
|
+
let matchedHandler: any = null;
|
|
302
|
+
let matchedParams: Record<string, string> = {};
|
|
303
|
+
|
|
304
|
+
if (wsRoutes && wsRoutes.size > 0) {
|
|
305
|
+
const exact = wsRoutes.get(parsed.pathname);
|
|
306
|
+
if (exact) {
|
|
307
|
+
matchedHandler = exact;
|
|
308
|
+
} else {
|
|
309
|
+
const segs = parsed.pathname.split('/').filter(Boolean);
|
|
310
|
+
for (const [pattern, handler] of wsRoutes.entries()) {
|
|
311
|
+
const pSegs = pattern.split('/').filter(Boolean);
|
|
312
|
+
if (pSegs.length !== segs.length) continue;
|
|
313
|
+
const params: Record<string, string> = {};
|
|
314
|
+
let ok = true;
|
|
315
|
+
for (let i = 0; i < pSegs.length; i++) {
|
|
316
|
+
if (pSegs[i]!.startsWith(':')) params[pSegs[i]!.slice(1)] = decodeURIComponent(segs[i]!);
|
|
317
|
+
else if (pSegs[i] !== segs[i]) { ok = false; break; }
|
|
318
|
+
}
|
|
319
|
+
if (ok) {
|
|
320
|
+
matchedHandler = handler;
|
|
321
|
+
matchedParams = params;
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const serverWs = {
|
|
329
|
+
data: matchedHandler ? { ...matchedHandler, params: matchedParams } : { params: matchedParams },
|
|
330
|
+
send(payload: any) {
|
|
331
|
+
if (readyState !== 1) return;
|
|
332
|
+
const decoded = parseWsPayload(payload);
|
|
333
|
+
for (const cb of msgListeners) cb(decoded);
|
|
334
|
+
},
|
|
335
|
+
close(code = 1000, reason = '') {
|
|
336
|
+
if (readyState === 3) return;
|
|
337
|
+
readyState = 3;
|
|
338
|
+
for (const cb of closeListeners) cb(code, reason);
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
queueMicrotask(async () => {
|
|
343
|
+
if (readyState !== 1) return;
|
|
344
|
+
if (matchedHandler?.__validateUpgrade) {
|
|
345
|
+
try {
|
|
346
|
+
const vr = await matchedHandler.__validateUpgrade(url, headers);
|
|
347
|
+
if (!vr?.ok) {
|
|
348
|
+
serverWs.close(1008, vr?.code || 'WS_UPGRADE_INVALID');
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
if (vr.query !== undefined) serverWs.data.query = vr.query;
|
|
352
|
+
if (vr.headers !== undefined) serverWs.data.headers = vr.headers;
|
|
353
|
+
} catch {
|
|
354
|
+
serverWs.close(1008, 'WS_UPGRADE_INVALID');
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (readyState !== 1) return;
|
|
359
|
+
matchedHandler?.open?.(serverWs);
|
|
360
|
+
for (const cb of openListeners) cb();
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
get readyState() { return readyState; },
|
|
365
|
+
send(data: Out) {
|
|
366
|
+
if (readyState !== 1) throw new Error('WebSocket is closed');
|
|
367
|
+
matchedHandler?.message?.(serverWs, serializeWsPayload(data));
|
|
368
|
+
},
|
|
369
|
+
onMessage(cb) {
|
|
370
|
+
msgListeners.add(cb);
|
|
371
|
+
return () => msgListeners.delete(cb);
|
|
372
|
+
},
|
|
373
|
+
onOpen(cb) {
|
|
374
|
+
openListeners.add(cb);
|
|
375
|
+
return () => openListeners.delete(cb);
|
|
376
|
+
},
|
|
377
|
+
onClose(cb) {
|
|
378
|
+
closeListeners.add(cb);
|
|
379
|
+
return () => closeListeners.delete(cb);
|
|
380
|
+
},
|
|
381
|
+
close(code = 1000, reason = '') {
|
|
382
|
+
if (readyState === 3) return;
|
|
383
|
+
readyState = 3;
|
|
384
|
+
matchedHandler?.close?.(serverWs, code, reason);
|
|
385
|
+
for (const cb of closeListeners) cb(code, reason);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
const createNetworkWsClient = <In = any, Out = In>(url: string): BareWsClient<In, Out> => {
|
|
391
|
+
const wsUrl = url.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:');
|
|
392
|
+
const socket = new WebSocket(wsUrl);
|
|
393
|
+
const msgListeners = new Set<(data: In) => void>();
|
|
394
|
+
const openListeners = new Set<() => void>();
|
|
395
|
+
const closeListeners = new Set<(code: number, reason: string) => void>();
|
|
396
|
+
|
|
397
|
+
socket.onmessage = (ev) => {
|
|
398
|
+
const decoded = parseWsPayload(ev.data);
|
|
399
|
+
for (const cb of msgListeners) cb(decoded);
|
|
400
|
+
};
|
|
401
|
+
socket.onopen = () => {
|
|
402
|
+
for (const cb of openListeners) cb();
|
|
403
|
+
};
|
|
404
|
+
socket.onclose = (ev) => {
|
|
405
|
+
for (const cb of closeListeners) cb(ev.code, ev.reason);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
get readyState() { return socket.readyState; },
|
|
410
|
+
send(data: Out) {
|
|
411
|
+
socket.send(serializeWsPayload(data));
|
|
412
|
+
},
|
|
413
|
+
onMessage(cb) {
|
|
414
|
+
msgListeners.add(cb);
|
|
415
|
+
return () => msgListeners.delete(cb);
|
|
416
|
+
},
|
|
417
|
+
onOpen(cb) {
|
|
418
|
+
openListeners.add(cb);
|
|
419
|
+
return () => openListeners.delete(cb);
|
|
420
|
+
},
|
|
421
|
+
onClose(cb) {
|
|
422
|
+
closeListeners.add(cb);
|
|
423
|
+
return () => closeListeners.delete(cb);
|
|
424
|
+
},
|
|
425
|
+
close(code?: number, reason?: string) {
|
|
426
|
+
socket.close(code, reason);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete']);
|
|
432
|
+
|
|
114
433
|
export const bareClient = <AppOrRoutes = any>(
|
|
115
434
|
baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
|
|
116
435
|
clientOptions: BareClientOptions = {}
|
|
@@ -120,7 +439,7 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
120
439
|
const fetchImpl = clientOptions.fetch ?? (isApp ? ((input: any, init?: RequestInit) => baseUrlOrApp.fetch(new Request(String(input), init))) as any : fetch);
|
|
121
440
|
const defaultHeaders = clientOptions.headers ?? {};
|
|
122
441
|
|
|
123
|
-
const
|
|
442
|
+
const requestRaw = async (method: string, path: string, options?: ClientRequestOptions): Promise<BareClientResult> => {
|
|
124
443
|
const url = buildUrl(baseUrl, path, options);
|
|
125
444
|
const headers = new Headers();
|
|
126
445
|
for (const [k, v] of Object.entries(defaultHeaders)) {
|
|
@@ -175,12 +494,72 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
175
494
|
}
|
|
176
495
|
}
|
|
177
496
|
if (!res.ok) {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
497
|
+
return { ok: false, data: null, error: data, status: res.status, headers: res.headers };
|
|
498
|
+
}
|
|
499
|
+
return { ok: true, data, error: null, status: res.status, headers: res.headers };
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
const request = async (method: string, path: string, options?: ClientRequestOptions) => {
|
|
503
|
+
const result = await requestRaw(method, path, options);
|
|
504
|
+
if (!result.ok) {
|
|
505
|
+
const err: any = new Error(`HTTP ${result.status}`);
|
|
506
|
+
err.status = result.status;
|
|
507
|
+
err.data = result.error;
|
|
181
508
|
throw err;
|
|
182
509
|
}
|
|
183
|
-
return data;
|
|
510
|
+
return result.data;
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
const openWs = <In = any, Out = In>(
|
|
514
|
+
path: string,
|
|
515
|
+
options?: {
|
|
516
|
+
params?: Record<string, string | number>;
|
|
517
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
518
|
+
headers?: Record<string, string>;
|
|
519
|
+
}
|
|
520
|
+
): BareWsClient<In, Out> => {
|
|
521
|
+
const url = buildUrl(baseUrl, path, options);
|
|
522
|
+
const mergedHeaders = { ...defaultHeaders, ...(options?.headers || {}) };
|
|
523
|
+
return isApp ? createInMemoryWsClient<In, Out>(baseUrlOrApp, url, mergedHeaders) : createNetworkWsClient<In, Out>(url);
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
const makeTreatyProxy = (segments: string[]): BareTreatyNode => {
|
|
527
|
+
const target = ((paramArg: Record<string, string | number> | string | number) => {
|
|
528
|
+
if (typeof paramArg === 'string' || typeof paramArg === 'number') {
|
|
529
|
+
return makeTreatyProxy([...segments, encodeURIComponent(String(paramArg))]);
|
|
530
|
+
}
|
|
531
|
+
const nextSegs = [...segments];
|
|
532
|
+
for (const val of Object.values(paramArg)) {
|
|
533
|
+
nextSegs.push(encodeURIComponent(String(val)));
|
|
534
|
+
}
|
|
535
|
+
return makeTreatyProxy(nextSegs);
|
|
536
|
+
}) as any;
|
|
537
|
+
|
|
538
|
+
return new Proxy(target, {
|
|
539
|
+
get(_t, prop: string | symbol) {
|
|
540
|
+
if (typeof prop === 'symbol') return undefined;
|
|
541
|
+
if (prop === 'then' || prop === 'catch' || prop === 'finally') return undefined;
|
|
542
|
+
if (HTTP_METHODS.has(prop)) {
|
|
543
|
+
const method = prop.toUpperCase();
|
|
544
|
+
const path = '/' + segments.join('/');
|
|
545
|
+
return (options?: ClientRequestOptions) => requestRaw(method, path, options);
|
|
546
|
+
}
|
|
547
|
+
if (prop === 'subscribe') {
|
|
548
|
+
const path = '/' + segments.join('/');
|
|
549
|
+
return (options?: { query?: Record<string, string | number | boolean | undefined>; headers?: Record<string, string> }) =>
|
|
550
|
+
openWs(path, options);
|
|
551
|
+
}
|
|
552
|
+
return makeTreatyProxy([...segments, prop]);
|
|
553
|
+
}
|
|
554
|
+
});
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
const safe = {
|
|
558
|
+
get: (path: string, options?: ClientRequestOptions) => requestRaw('GET', path, options),
|
|
559
|
+
post: (path: string, options?: ClientRequestOptions) => requestRaw('POST', path, options),
|
|
560
|
+
put: (path: string, options?: ClientRequestOptions) => requestRaw('PUT', path, options),
|
|
561
|
+
patch: (path: string, options?: ClientRequestOptions) => requestRaw('PATCH', path, options),
|
|
562
|
+
delete: (path: string, options?: ClientRequestOptions) => requestRaw('DELETE', path, options)
|
|
184
563
|
};
|
|
185
564
|
|
|
186
565
|
return {
|
|
@@ -188,6 +567,20 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
188
567
|
post: (path: string, options?: ClientRequestOptions) => request('POST', path, options),
|
|
189
568
|
put: (path: string, options?: ClientRequestOptions) => request('PUT', path, options),
|
|
190
569
|
patch: (path: string, options?: ClientRequestOptions) => request('PATCH', path, options),
|
|
191
|
-
delete: (path: string, options?: ClientRequestOptions) => request('DELETE', path, options)
|
|
570
|
+
delete: (path: string, options?: ClientRequestOptions) => request('DELETE', path, options),
|
|
571
|
+
safe,
|
|
572
|
+
treaty: makeTreatyProxy([]),
|
|
573
|
+
ws: openWs
|
|
192
574
|
} as any;
|
|
193
575
|
};
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Chained Proxy RPC client (Eden Treaty-style) with strict compile-time route,
|
|
579
|
+
* param, body, response, and per-status error inference (zero runtime overhead).
|
|
580
|
+
* Works both in-memory (`bareTreaty(app)`) and over network (`bareTreaty<typeof app>('https://api.example.com')`).
|
|
581
|
+
*/
|
|
582
|
+
export const bareTreaty = <AppOrRoutes = any>(
|
|
583
|
+
baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
|
|
584
|
+
clientOptions: BareClientOptions = {}
|
|
585
|
+
): TreatyTree<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> =>
|
|
586
|
+
bareClient<AppOrRoutes>(baseUrlOrApp, clientOptions).treaty as any;
|