@yorun-ai/vrpc 0.9.0

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,288 @@
1
+ //#region src/contracts/errors.ts
2
+ var HTTP_TIMEOUT_ERROR_CODE = "HTTP_TIMEOUT";
3
+ var HttpTimeoutError = class extends Error {
4
+ code;
5
+ timeoutMs;
6
+ constructor(timeoutMs) {
7
+ super(`request timeout after ${timeoutMs}ms`);
8
+ this.name = "HttpTimeoutError";
9
+ this.code = HTTP_TIMEOUT_ERROR_CODE;
10
+ this.timeoutMs = timeoutMs;
11
+ }
12
+ };
13
+ function readServerErrorMessage(payload) {
14
+ if (!payload || typeof payload !== "object") return;
15
+ const body = payload;
16
+ if (typeof body.message !== "string" || !body.message.trim()) return;
17
+ const detail = typeof body.detail === "string" ? body.detail.trim() : "";
18
+ return detail ? `${body.message}\n${detail}` : body.message;
19
+ }
20
+ function readServerErrorStringField(payload, field) {
21
+ if (!payload || typeof payload !== "object") return;
22
+ const value = payload[field];
23
+ return typeof value === "string" ? value : void 0;
24
+ }
25
+ var HttpInvokeError = class extends Error {
26
+ type;
27
+ code;
28
+ reason;
29
+ detail;
30
+ status;
31
+ statusText;
32
+ responseHeaders;
33
+ payload;
34
+ url;
35
+ method;
36
+ constructor(response, payload, requestMeta = {}) {
37
+ const message = readServerErrorMessage(payload) || `request failed (status=${response.status})`;
38
+ super(message);
39
+ this.name = "HttpInvokeError";
40
+ this.status = response.status;
41
+ this.statusText = response.statusText;
42
+ this.responseHeaders = response.headers;
43
+ this.payload = payload;
44
+ this.type = readServerErrorStringField(payload, "type");
45
+ this.code = readServerErrorStringField(payload, "code");
46
+ this.reason = readServerErrorStringField(payload, "reason");
47
+ this.detail = readServerErrorStringField(payload, "detail");
48
+ this.url = requestMeta.url || response.url || "";
49
+ this.method = requestMeta.method || "GET";
50
+ }
51
+ };
52
+ var VrpcInvokeError = class extends HttpInvokeError {
53
+ vrpcStatus;
54
+ constructor(response, payload, requestMeta = {}) {
55
+ super(response, payload, requestMeta);
56
+ this.name = "VrpcInvokeError";
57
+ const vrpcStatus = response.headers.get("vrpc-status");
58
+ this.vrpcStatus = vrpcStatus;
59
+ }
60
+ };
61
+ //#endregion
62
+ //#region src/core/http-utils.ts
63
+ var NULL_BODY_STATUS_CODES = /* @__PURE__ */ new Set([
64
+ 101,
65
+ 103,
66
+ 204,
67
+ 205,
68
+ 304
69
+ ]);
70
+ function isNullBodyStatus(status) {
71
+ return NULL_BODY_STATUS_CODES.has(status);
72
+ }
73
+ function shouldTreatResponseAsBodyless(method, status) {
74
+ return method.toUpperCase() === "HEAD" || isNullBodyStatus(status);
75
+ }
76
+ function buildRequestUrl(prefixUrl, path) {
77
+ try {
78
+ return new URL(path).toString();
79
+ } catch {}
80
+ const base = String(prefixUrl).replace(/\/+$/, "");
81
+ const relativePath = path.replace(/^\/+/, "");
82
+ return relativePath ? `${base}/${relativePath}` : `${base}/`;
83
+ }
84
+ function appendQueryToUrl(url, query) {
85
+ if (!query) return url;
86
+ const hashIndex = url.indexOf("#");
87
+ const hash = hashIndex >= 0 ? url.slice(hashIndex) : "";
88
+ const urlWithoutHash = hashIndex >= 0 ? url.slice(0, hashIndex) : url;
89
+ const searchIndex = urlWithoutHash.indexOf("?");
90
+ const basePath = searchIndex >= 0 ? urlWithoutHash.slice(0, searchIndex) : urlWithoutHash;
91
+ const currentSearch = searchIndex >= 0 ? urlWithoutHash.slice(searchIndex + 1) : "";
92
+ const searchParams = new URLSearchParams(currentSearch);
93
+ if (query instanceof URLSearchParams) {
94
+ query.forEach((value, key) => {
95
+ searchParams.append(key, value);
96
+ });
97
+ const nextSearch = searchParams.toString();
98
+ return `${basePath}${nextSearch ? `?${nextSearch}` : ""}${hash}`;
99
+ }
100
+ for (const [key, rawValue] of Object.entries(query)) {
101
+ if (rawValue == null) continue;
102
+ const values = Array.isArray(rawValue) ? rawValue : [rawValue];
103
+ for (const value of values) searchParams.append(key, String(value));
104
+ }
105
+ const nextSearch = searchParams.toString();
106
+ return `${basePath}${nextSearch ? `?${nextSearch}` : ""}${hash}`;
107
+ }
108
+ function mergeHeaders(...values) {
109
+ const merged = new Headers();
110
+ values.forEach((value) => {
111
+ if (!value) return;
112
+ new Headers(value).forEach((headerValue, headerKey) => merged.set(headerKey, headerValue));
113
+ });
114
+ return merged;
115
+ }
116
+ async function parseResponsePayload(response) {
117
+ const text = await response.text();
118
+ if (!text) return null;
119
+ try {
120
+ return JSON.parse(text);
121
+ } catch {
122
+ return text;
123
+ }
124
+ }
125
+ //#endregion
126
+ //#region src/transports/fetch-transport.ts
127
+ function createTimeoutError(timeoutMs) {
128
+ return new HttpTimeoutError(timeoutMs);
129
+ }
130
+ function withTimeoutSignal(timeoutMs, signal) {
131
+ if (!timeoutMs || timeoutMs <= 0) return {
132
+ signal: signal || void 0,
133
+ cleanup: () => {}
134
+ };
135
+ const controller = new AbortController();
136
+ const timer = setTimeout(() => controller.abort(createTimeoutError(timeoutMs)), timeoutMs);
137
+ const clear = () => clearTimeout(timer);
138
+ if (!signal) return {
139
+ signal: controller.signal,
140
+ cleanup: clear
141
+ };
142
+ if (signal.aborted) {
143
+ controller.abort(signal.reason);
144
+ return {
145
+ signal: controller.signal,
146
+ cleanup: clear
147
+ };
148
+ }
149
+ const relayAbort = () => controller.abort(signal.reason);
150
+ signal.addEventListener("abort", relayAbort, { once: true });
151
+ return {
152
+ signal: controller.signal,
153
+ cleanup: () => {
154
+ clear();
155
+ signal.removeEventListener("abort", relayAbort);
156
+ }
157
+ };
158
+ }
159
+ function createFetchTransport(fetchImpl) {
160
+ const request = fetchImpl || globalThis.fetch;
161
+ if (!request) throw new Error("fetch is not available in current runtime.");
162
+ return { request: async (input) => {
163
+ const { signal, cleanup } = withTimeoutSignal(input.timeoutMs, input.init.signal || input.signal);
164
+ try {
165
+ const response = await request(input.url, {
166
+ ...input.init,
167
+ method: input.method,
168
+ headers: input.headers,
169
+ body: input.body,
170
+ signal,
171
+ credentials: input.init.credentials ?? "omit"
172
+ });
173
+ const body = shouldTreatResponseAsBodyless(input.method, response.status) ? null : new Uint8Array(await response.arrayBuffer());
174
+ return {
175
+ status: response.status,
176
+ statusText: response.statusText,
177
+ headers: response.headers,
178
+ body,
179
+ url: response.url || input.url
180
+ };
181
+ } finally {
182
+ cleanup();
183
+ }
184
+ } };
185
+ }
186
+ //#endregion
187
+ //#region src/core/interceptor-runner.ts
188
+ async function runBeforeRequestInterceptors(interceptors, context) {
189
+ for (const interceptor of interceptors) await interceptor.beforeRequest?.(context);
190
+ }
191
+ async function runAfterResponseInterceptors(interceptors, response, context) {
192
+ for (const interceptor of interceptors) await interceptor.afterResponse?.(response, context);
193
+ }
194
+ async function runOnErrorInterceptors(interceptors, error, context) {
195
+ for (const interceptor of interceptors) await interceptor.onError?.(error, context);
196
+ }
197
+ //#endregion
198
+ //#region src/core/transport-response.ts
199
+ function buildResponseFromTransportResult(result) {
200
+ const body = isNullBodyStatus(result.status) ? null : result.body;
201
+ const response = new Response(body, {
202
+ status: result.status,
203
+ statusText: result.statusText,
204
+ headers: result.headers
205
+ });
206
+ try {
207
+ Object.defineProperty(response, "url", {
208
+ value: result.url,
209
+ configurable: true
210
+ });
211
+ } catch {}
212
+ return response;
213
+ }
214
+ //#endregion
215
+ //#region src/core/create-client-core.ts
216
+ function resolveTransportBody(init, fallbackBody) {
217
+ if (init.body !== void 0) return init.body;
218
+ return fallbackBody;
219
+ }
220
+ function createClientCore(options) {
221
+ const { prefixUrl, baseOptions, fetchImpl, transport, interceptors: initInterceptors, splitRequestOptions, prepareRequest, parseResponse = parseResponsePayload, assertResponse, validateRequest } = options;
222
+ const splitBaseOptions = splitRequestOptions(baseOptions);
223
+ const httpTransport = transport || createFetchTransport(fetchImpl);
224
+ const interceptors = [...initInterceptors || []];
225
+ async function execute(request) {
226
+ const prepared = await prepareRequest(request, {
227
+ prefixUrl,
228
+ baseOptions: splitBaseOptions,
229
+ splitRequestOptions
230
+ });
231
+ const context = prepared.context;
232
+ try {
233
+ await runBeforeRequestInterceptors(interceptors, context);
234
+ const method = String(context.init.method || prepared.fallbackMethod || "GET").toUpperCase();
235
+ const headers = context.init.headers || prepared.fallbackHeaders || new Headers();
236
+ const requestMeta = {
237
+ method,
238
+ url: context.url
239
+ };
240
+ await validateRequest?.(context, requestMeta);
241
+ const response = buildResponseFromTransportResult(await httpTransport.request({
242
+ url: context.url,
243
+ init: context.init,
244
+ method,
245
+ headers,
246
+ body: resolveTransportBody(context.init, prepared.fallbackBody),
247
+ timeoutMs: prepared.timeoutMs,
248
+ signal: context.init.signal
249
+ }));
250
+ const payload = await parseResponse(response, context);
251
+ await runAfterResponseInterceptors(interceptors, response, context);
252
+ await assertResponse(response, payload, context, requestMeta);
253
+ return payload;
254
+ } catch (error) {
255
+ await runOnErrorInterceptors(interceptors, error, context);
256
+ throw error;
257
+ }
258
+ }
259
+ return {
260
+ execute,
261
+ use: (interceptor) => {
262
+ interceptors.push(interceptor);
263
+ }
264
+ };
265
+ }
266
+ //#endregion
267
+ //#region src/core/request-options.ts
268
+ function splitHttpRequestOptions(options) {
269
+ if (!options) return { requestInit: {} };
270
+ const { headers, timeoutMs, suppressGlobalToast, requestInit } = options;
271
+ return {
272
+ headers,
273
+ timeoutMs,
274
+ suppressGlobalToast,
275
+ requestInit: requestInit ?? {}
276
+ };
277
+ }
278
+ function splitVrpcRequestOptions(options) {
279
+ if (!options) return { requestInit: {} };
280
+ const { trace, wire } = options;
281
+ return {
282
+ ...splitHttpRequestOptions(options),
283
+ trace,
284
+ wire
285
+ };
286
+ }
287
+ //#endregion
288
+ export { appendQueryToUrl as a, HTTP_TIMEOUT_ERROR_CODE as c, VrpcInvokeError as d, createFetchTransport as i, HttpInvokeError as l, splitVrpcRequestOptions as n, buildRequestUrl as o, createClientCore as r, mergeHeaders as s, splitHttpRequestOptions as t, HttpTimeoutError as u };
@@ -0,0 +1,115 @@
1
+ # Axios integration
2
+
3
+ Axios can send JSON vRPC directly or be wrapped as a runtime transport. When automatic CBOR, wire schemas, interceptors, and consistent error semantics are needed, wrap Axios as a transport and use it with `createVrpcClient`.
4
+
5
+ ## Option A: send JSON vRPC directly
6
+
7
+ ```ts
8
+ import axios from "axios";
9
+ import {
10
+ buildVrpcHeaders,
11
+ buildVrpcPath,
12
+ buildVrpcRequestBody,
13
+ generateVrpcId,
14
+ unwrapVrpcResponse,
15
+ } from "@yorun-ai/vrpc";
16
+
17
+ const clientInfo = {
18
+ clientName: "demo.browser",
19
+ clientVersion: "1.0.0",
20
+ clientInstanceId: crypto.randomUUID(),
21
+ };
22
+
23
+ async function invoke<T>(serviceName: string, methodName: string, params: Record<string, unknown>) {
24
+ const timeoutMs = 3_000;
25
+ const response = await axios.request({
26
+ baseURL: "https://api.example.com/invoke",
27
+ url: buildVrpcPath(serviceName, methodName),
28
+ method: "POST",
29
+ headers: Object.fromEntries(
30
+ buildVrpcHeaders({
31
+ clientInfo,
32
+ trace: { id: generateVrpcId() },
33
+ timeoutMs,
34
+ }).entries(),
35
+ ),
36
+ data: buildVrpcRequestBody(params),
37
+ timeout: timeoutMs,
38
+ validateStatus: () => true,
39
+ });
40
+
41
+ return unwrapVrpcResponse<T>(
42
+ {
43
+ status: response.status,
44
+ statusText: response.statusText,
45
+ headers: response.headers,
46
+ url: response.config.url,
47
+ method: "POST",
48
+ },
49
+ response.data,
50
+ );
51
+ }
52
+ ```
53
+
54
+ This path supports JSON only. The caller must send `vrpc-trace`, `vrpc-client`, and optional `vrpc-options` headers and decode the response payload. Axios defaults `timeout` to `0` (no timeout); when a timeout is required, use the same value for the local `timeout` and `vrpc-options`.
55
+
56
+ ## Option B: Axios transport
57
+
58
+ A runtime transport returns the response body as raw bytes:
59
+
60
+ ```ts
61
+ import axios from "axios";
62
+ import type { VrpcTransport } from "@yorun-ai/vrpc";
63
+
64
+ export const axiosTransport: VrpcTransport = {
65
+ async request(request) {
66
+ const response = await axios.request<ArrayBuffer>({
67
+ url: request.url,
68
+ method: request.method,
69
+ headers: Object.fromEntries(new Headers(request.headers).entries()),
70
+ data: request.body,
71
+ signal: request.signal ?? undefined,
72
+ timeout: request.timeoutMs,
73
+ withCredentials: request.init.credentials === "include",
74
+ responseType: "arraybuffer",
75
+ validateStatus: () => true,
76
+ });
77
+
78
+ const body = response.data.byteLength ? new Uint8Array(response.data) : null;
79
+
80
+ return {
81
+ status: response.status,
82
+ statusText: response.statusText,
83
+ headers: new Headers(response.headers as Record<string, string>),
84
+ body,
85
+ url: request.url,
86
+ };
87
+ },
88
+ };
89
+ ```
90
+
91
+ Connect it to the runtime:
92
+
93
+ ```ts
94
+ const client = createVrpcClient({
95
+ prefixUrl: "https://api.example.com/invoke",
96
+ transport: axiosTransport,
97
+ clientInfo: {
98
+ clientName: "demo.browser",
99
+ clientVersion: "1.0.0",
100
+ clientInstanceId: crypto.randomUUID(),
101
+ },
102
+ cborCodec,
103
+ });
104
+ ```
105
+
106
+ Constraints:
107
+
108
+ - Use the complete `request.url` already calculated by the core.
109
+ - A custom transport applies optional `request.timeoutMs` to local I/O; when omitted it is `undefined` and the runtime enables no timeout.
110
+ - Do not regenerate the path, headers, or envelope.
111
+ - Do not parse JSON/CBOR or call `parseVrpcResponse`.
112
+ - Do not read `wire` or `suppressGlobalToast`; these fields never enter the transport request.
113
+ - The request body may be a JSON string or a CBOR `ArrayBuffer`.
114
+ - The response must return `Uint8Array | null` so the runtime can decode it according to content-type.
115
+ - Cookies are controlled by `requestInit.credentials: "include"`.
@@ -0,0 +1,259 @@
1
+ # Usage
2
+
3
+ ## 1. Generic HTTP client
4
+
5
+ ```ts
6
+ import { HttpInvokeError, HttpTimeoutError, createHttpClient } from "@yorun-ai/vrpc/http";
7
+
8
+ const client = createHttpClient({
9
+ prefixUrl: "https://api.example.com",
10
+ timeoutMs: 5_000,
11
+ suppressGlobalToast: false,
12
+ requestInit: {
13
+ credentials: "omit",
14
+ },
15
+ });
16
+
17
+ client.use({
18
+ beforeRequest(context) {
19
+ console.log(context.url, context.init.method);
20
+ },
21
+ onError(error, context) {
22
+ if (context.options.suppressGlobalToast) {
23
+ return;
24
+ }
25
+ console.error(error);
26
+ },
27
+ });
28
+
29
+ const profile = await client.request<{ id: number; name: string }>({
30
+ path: "/users/me",
31
+ query: {
32
+ withProfile: true,
33
+ lang: "zh-CN",
34
+ },
35
+ options: {
36
+ timeoutMs: 3_000,
37
+ suppressGlobalToast: true,
38
+ },
39
+ });
40
+
41
+ await client.request({
42
+ path: "/users",
43
+ method: "POST",
44
+ json: { name: "Vine" },
45
+ });
46
+ ```
47
+
48
+ Request shape:
49
+
50
+ ```ts
51
+ client.request({
52
+ path: string,
53
+ method?: string,
54
+ query?: HttpQueryParams | URLSearchParams,
55
+ json?: unknown,
56
+ body?: BodyInit | null,
57
+ options?: {
58
+ headers?: HeadersInit,
59
+ timeoutMs?: number,
60
+ requestInit?: Omit<RequestInit, "method" | "body" | "headers">,
61
+ suppressGlobalToast?: boolean,
62
+ },
63
+ });
64
+ ```
65
+
66
+ - `json` and `body` are mutually exclusive.
67
+ - `json` is serialized automatically and adds `content-type: application/json`.
68
+ - Pass `FormData` through `body`; do not set its content-type boundary manually.
69
+ - Create-time defaults are merged with per-request options; per-request scalar and requestInit fields take precedence.
70
+ - An interceptor receives merged configuration in `context.options` and the original call shape in `context.request`.
71
+ - Options do not leak into the transport request.
72
+ - `timeoutMs` is disabled by default. Set an application default at creation and override it per request when needed.
73
+ - The default is `credentials: "omit"`; use `requestInit.credentials: "include"` for cookies.
74
+ - An empty body returns `null`; a timeout throws `HttpTimeoutError`; a non-2xx response throws `HttpInvokeError`.
75
+
76
+ ## 2. vRPC client
77
+
78
+ ```ts
79
+ import { VrpcInvokeError, createVrpcClient, getClientInstanceId } from "@yorun-ai/vrpc/client";
80
+
81
+ const client = createVrpcClient({
82
+ prefixUrl: "https://api.example.com/invoke",
83
+ timeoutMs: 15_000,
84
+ suppressGlobalToast: false,
85
+ clientInfo: {
86
+ clientName: "demo.browser",
87
+ clientVersion: "1.0.0",
88
+ clientInstanceId: getClientInstanceId(),
89
+ },
90
+ });
91
+
92
+ client.use({
93
+ onError(error, context) {
94
+ if (context.options.suppressGlobalToast) {
95
+ return;
96
+ }
97
+
98
+ if (error instanceof VrpcInvokeError) {
99
+ console.error(error.status, error.vrpcStatus, error.code, error.reason);
100
+ }
101
+ },
102
+ });
103
+
104
+ const user = await client.invoke<{ id: number }>({
105
+ serviceName: "user.UserService",
106
+ methodName: "getUser",
107
+ params: { userId: 1 },
108
+ options: {
109
+ timeoutMs: 3_000,
110
+ headers: { "x-env": "dev" },
111
+ suppressGlobalToast: true,
112
+ },
113
+ });
114
+
115
+ await client.invoke({
116
+ serviceName: "user.UserService",
117
+ methodName: "ping",
118
+ params: null,
119
+ });
120
+ ```
121
+
122
+ vRPC always uses POST. Methods with arguments use a parameter object; argument-free methods accept `null` or `{}`. `options` is optional.
123
+
124
+ ### Trace and timeout
125
+
126
+ `traceMode` controls only the shape of the automatically generated `vrpc-trace` header. It does not select a route, change `prefixUrl`, or decide whether the request passes through Portal. The target is always determined by `prefixUrl`.
127
+
128
+ For requests through Vine Portal, use the default `"portal"` mode. The runtime generates only a trace id:
129
+
130
+ ```text
131
+ vrpc-trace: id=<32hex>
132
+ ```
133
+
134
+ For a direct connection to a vRPC service, set `traceMode: "direct"`. The runtime generates both a trace id and a span:
135
+
136
+ ```ts
137
+ const directClient = createVrpcClient({
138
+ prefixUrl: "https://service.example.com/rpc/invoke",
139
+ traceMode: "direct",
140
+ clientInfo,
141
+ });
142
+ ```
143
+
144
+ ```text
145
+ vrpc-trace: id=<32hex>,span=<16hex>
146
+ ```
147
+
148
+ An explicit per-call `options.trace` completely overrides the generated value and is suitable for propagating an upstream trace. Direct calls should provide both id and span:
149
+
150
+ ```ts
151
+ options: {
152
+ trace: {
153
+ id: "123e4567e89b12d3a456426614174000",
154
+ span: "1234567890abcdef",
155
+ },
156
+ }
157
+ ```
158
+
159
+ `timeoutMs` is disabled by default. Setting `timeoutMs: 2500` creates both a local timeout and `vrpc-options: timeout=2500ms`. The create-time value is the client default and may be overridden per call; a vRPC timeout must be a positive safe integer.
160
+
161
+ ## 3. Automatic CBOR
162
+
163
+ A generated method without Binary has no wire and uses JSON. A method whose arguments or result contain Binary includes the corresponding schema:
164
+
165
+ ```ts
166
+ import type { VrpcCborCodec, VrpcMethodWireSpec } from "@yorun-ai/vrpc";
167
+
168
+ const uploadWire = {
169
+ arguments: {
170
+ kind: "object",
171
+ fields: {
172
+ content: { kind: "binary" },
173
+ chunks: {
174
+ kind: "map",
175
+ key: "int",
176
+ value: { kind: "binary" },
177
+ },
178
+ },
179
+ },
180
+ } as const satisfies VrpcMethodWireSpec;
181
+
182
+ const cborCodec: VrpcCborCodec = {
183
+ encode: (value) => cbor.encode(value),
184
+ decode: (bytes) => cbor.decode(bytes),
185
+ };
186
+
187
+ const client = createVrpcClient({
188
+ prefixUrl,
189
+ clientInfo,
190
+ cborCodec,
191
+ });
192
+
193
+ await client.invoke({
194
+ serviceName: "file.FileService",
195
+ methodName: "upload",
196
+ params: {
197
+ content: new Uint8Array([1, 2]),
198
+ chunks: {
199
+ 1: new Uint8Array([3]),
200
+ },
201
+ },
202
+ options: {
203
+ wire: uploadWire,
204
+ },
205
+ });
206
+ ```
207
+
208
+ Selection depends entirely on wire-property presence:
209
+
210
+ - `arguments`: CBOR request.
211
+ - `result`: CBOR response negotiation.
212
+ - Both: CBOR in both directions.
213
+ - Wire without a codec throws a configuration error before transport.
214
+
215
+ Wire never appears in the HTTP body, custom headers, or transport request.
216
+
217
+ ## 4. Protocol helpers
218
+
219
+ ```ts
220
+ import {
221
+ buildVrpcHeaders,
222
+ buildVrpcPath,
223
+ buildVrpcRequestBody,
224
+ generateVrpcId,
225
+ parseVrpcResponse,
226
+ unwrapVrpcResponse,
227
+ } from "@yorun-ai/vrpc";
228
+
229
+ const path = buildVrpcPath("user.UserService", "getUser");
230
+ const headers = buildVrpcHeaders({
231
+ clientInfo,
232
+ trace: { id: generateVrpcId() },
233
+ timeoutMs: 3_000,
234
+ });
235
+ const body = buildVrpcRequestBody({ userId: 1 });
236
+ ```
237
+
238
+ `parseVrpcResponse` returns a normalized result without throwing; `unwrapVrpcResponse` throws `VrpcInvokeError` on failure. A fully custom HTTP client is responsible for JSON/CBOR decoding of the response body; `createVrpcClient` handles it when using a runtime transport.
239
+
240
+ ## 5. Custom transport
241
+
242
+ A transport performs I/O only, and the response body must remain raw bytes:
243
+
244
+ ```ts
245
+ const transport: VrpcTransport = {
246
+ async request(request) {
247
+ const response = await customRequest(request.url, request.init);
248
+ return {
249
+ status: response.status,
250
+ statusText: response.statusText,
251
+ headers: new Headers(response.headers),
252
+ body: response.bytes.length ? response.bytes : null,
253
+ url: response.url,
254
+ };
255
+ },
256
+ };
257
+ ```
258
+
259
+ A transport does not parse JSON/CBOR, evaluate `vrpc-status`, handle `suppressGlobalToast`, or regenerate paths or headers.
@@ -0,0 +1,47 @@
1
+ # Architecture
2
+
3
+ ## Scope
4
+
5
+ `@yorun-ai/vrpc` provides two layers:
6
+
7
+ - Generic HTTP client core: request orchestration, interceptors, timeouts, errors, and transports.
8
+ - vRPC protocol layer: Vine paths, headers, JSON/CBOR envelopes, and `vrpc-status`.
9
+
10
+ ## Layers
11
+
12
+ - `src/contracts/`: all public types and error contracts.
13
+ - `src/core/`: protocol-independent lifecycle and HTTP/vRPC client assembly, without runtime network I/O.
14
+ - `src/transports/`: network I/O, `AbortController`, and raw-byte responses.
15
+ - `src/protocol/`: Vine headers, paths, envelopes, wire-schema conversion, and response parsing.
16
+ - `src/entrypoints/`: public exports for `./client` and `./http`.
17
+
18
+ A transport response must preserve the original `Uint8Array | null`. The generic HTTP core parses JSON, text, or empty responses, while the vRPC core selects JSON or a user-provided CBOR codec according to `content-type`.
19
+
20
+ ## Generic HTTP flow
21
+
22
+ 1. Create options define defaults for headers, timeout, requestInit, and suppressGlobalToast. Timeout has no built-in default, so the built-in transport creates no local timer unless configured.
23
+ 2. Per-request `request.options` override defaults. Headers are merged, requestInit is shallow-merged, and per-request scalar values take precedence.
24
+ 3. Interceptors receive `{ url, init, request, options }`; `options` contains the merged configuration.
25
+ 4. The transport sends the request and returns raw bytes.
26
+ 5. The core reconstructs a `Response`, parses JSON, text, or an empty response, and throws `HttpInvokeError` for a non-success status.
27
+
28
+ Request options and interceptor-only fields must not enter `HttpTransportRequest`.
29
+
30
+ ## Protocol boundary
31
+
32
+ The vRPC protocol layer owns path construction, request and response envelopes, content negotiation, protocol headers, wire-schema conversion, and protocol-level errors. `core` orchestrates those operations; `transports` only send HTTP requests and preserve raw response bytes.
33
+
34
+ The complete wire contract and the requirements for generated clients are documented in [vRPC protocol](protocol.md). Changes to that contract must be reviewed across the runtime, protocol tests, generated-code consumers, and documentation.
35
+
36
+ ## Verification
37
+
38
+ Run after behavioral or public-contract changes:
39
+
40
+ ```bash
41
+ pnpm type-check
42
+ pnpm test
43
+ pnpm build
44
+ pnpm test:package
45
+ pnpm fmt:check
46
+ pnpm lint
47
+ ```