@yorun-ai/vrpc 0.9.1 → 0.9.3
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/CONTRIBUTING.md +24 -2
- package/README.md +147 -163
- package/README.zh-CN.md +128 -158
- package/dist/client.cjs +46 -24
- package/dist/client.d.cts +47 -11
- package/dist/client.d.ts +47 -11
- package/dist/client.es.js +42 -25
- package/dist/http.cjs +7 -3
- package/dist/http.d.cts +35 -9
- package/dist/http.d.ts +35 -9
- package/dist/http.es.js +4 -4
- package/dist/{request-options-disym648.js → request-options-Bjy2LvRE.js} +175 -47
- package/dist/{request-options-2HZzkj4w.cjs → request-options-m8_63jpk.cjs} +210 -46
- package/docs/guides/axios.md +46 -21
- package/docs/guides/cdn.md +221 -0
- package/docs/guides/usage.md +172 -7
- package/docs/maintainers/architecture.md +26 -4
- package/docs/maintainers/protocol.md +16 -1
- package/docs/reference/README.md +240 -0
- package/package.json +2 -2
package/docs/guides/axios.md
CHANGED
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
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
4
|
|
|
5
|
+
For client configuration shared by both options, see the [Usage guide](./usage.md)
|
|
6
|
+
and the [API Reference](../reference/README.md).
|
|
7
|
+
|
|
5
8
|
## Option A: send JSON vRPC directly
|
|
6
9
|
|
|
7
10
|
```ts
|
|
@@ -59,31 +62,52 @@ A runtime transport returns the response body as raw bytes:
|
|
|
59
62
|
|
|
60
63
|
```ts
|
|
61
64
|
import axios from "axios";
|
|
65
|
+
import { HttpAbortError, HttpTimeoutError, HttpTransportError } from "@yorun-ai/vrpc";
|
|
62
66
|
import type { VrpcTransport } from "@yorun-ai/vrpc";
|
|
63
67
|
|
|
64
68
|
export const axiosTransport: VrpcTransport = {
|
|
65
69
|
async request(request) {
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
70
|
+
const requestMeta = { url: request.url, method: request.method };
|
|
71
|
+
try {
|
|
72
|
+
const response = await axios.request<ArrayBuffer>({
|
|
73
|
+
url: request.url,
|
|
74
|
+
method: request.method,
|
|
75
|
+
headers: Object.fromEntries(new Headers(request.headers).entries()),
|
|
76
|
+
data: request.body,
|
|
77
|
+
signal: request.signal ?? undefined,
|
|
78
|
+
timeout: request.timeoutMs,
|
|
79
|
+
withCredentials: request.init.credentials === "include",
|
|
80
|
+
responseType: "arraybuffer",
|
|
81
|
+
validateStatus: () => true,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const body = response.data.byteLength ? new Uint8Array(response.data) : null;
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
status: response.status,
|
|
88
|
+
statusText: response.statusText,
|
|
89
|
+
headers: new Headers(response.headers as Record<string, string>),
|
|
90
|
+
body,
|
|
91
|
+
url: request.url,
|
|
92
|
+
};
|
|
93
|
+
} catch (cause) {
|
|
94
|
+
if (axios.isCancel(cause)) {
|
|
95
|
+
throw new HttpAbortError(requestMeta, {
|
|
96
|
+
cause,
|
|
97
|
+
reason: request.signal?.reason,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (
|
|
102
|
+
request.timeoutMs !== undefined &&
|
|
103
|
+
axios.isAxiosError(cause) &&
|
|
104
|
+
(cause.code === "ECONNABORTED" || cause.code === "ETIMEDOUT")
|
|
105
|
+
) {
|
|
106
|
+
throw new HttpTimeoutError(request.timeoutMs, requestMeta, { cause });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
throw new HttpTransportError(requestMeta, { cause });
|
|
110
|
+
}
|
|
87
111
|
},
|
|
88
112
|
};
|
|
89
113
|
```
|
|
@@ -107,6 +131,7 @@ Constraints:
|
|
|
107
131
|
|
|
108
132
|
- Use the complete `request.url` already calculated by the core.
|
|
109
133
|
- A custom transport applies optional `request.timeoutMs` to local I/O; when omitted it is `undefined` and the runtime enables no timeout.
|
|
134
|
+
- Convert adapter cancellation, timeout, and transport failures to the package error classes as shown above. The core wraps any remaining unknown transport failure as `HttpTransportError`, but only the adapter can reliably identify its own timeout codes.
|
|
110
135
|
- Do not regenerate the path, headers, or envelope.
|
|
111
136
|
- Do not parse JSON/CBOR or call `parseVrpcResponse`.
|
|
112
137
|
- Do not read `wire` or `suppressGlobalToast`; these fields never enter the transport request.
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# Browser CDN usage
|
|
2
|
+
|
|
3
|
+
This guide shows how to use `@yorun-ai/vrpc` from a CDN in a plain HTML page,
|
|
4
|
+
without a bundler or a package install. For packaged applications, prefer the
|
|
5
|
+
npm installation and the [Usage guide](./usage.md).
|
|
6
|
+
|
|
7
|
+
## 1. Overview
|
|
8
|
+
|
|
9
|
+
Use the CDN builds when you want to:
|
|
10
|
+
|
|
11
|
+
- prototype against a real vRPC or HTTP endpoint from a static page,
|
|
12
|
+
- embed the client in a CodePen, JSFiddle, or documentation snippet,
|
|
13
|
+
- keep a small internal tool free of a build step.
|
|
14
|
+
|
|
15
|
+
Two constraints apply to every CDN setup:
|
|
16
|
+
|
|
17
|
+
- **ES modules only.** The published package ships ES module and CommonJS
|
|
18
|
+
builds, not an IIFE/UMD bundle. There is no `window.Vrpc` or `window.Http`
|
|
19
|
+
global, and a classic `<script src="...">` without `type="module"` fails with
|
|
20
|
+
a syntax error because the file contains `import` statements.
|
|
21
|
+
- **Pin the version.** Use an exact version such as `@0.9.3` so a new release
|
|
22
|
+
cannot change the behavior of a page you already published.
|
|
23
|
+
|
|
24
|
+
The runtime needs native ES modules, `fetch`, `AbortController`, and `Headers`.
|
|
25
|
+
All current evergreen browsers provide these.
|
|
26
|
+
|
|
27
|
+
## 2. Available bundles
|
|
28
|
+
|
|
29
|
+
| Import | File | Format |
|
|
30
|
+
| ------------------------------ | ------------------- | -------------------------------------------------------- |
|
|
31
|
+
| vRPC client + protocol helpers | `dist/client.es.js` | ES module; imports one relative shared chunk |
|
|
32
|
+
| Generic HTTP client | `dist/http.es.js` | ES module; imports the same shared chunk |
|
|
33
|
+
| vRPC client (bundled) | `+esm` | ES module; single self-contained file, no extra requests |
|
|
34
|
+
| Generic HTTP client (bundled) | `/http/+esm` | ES module; single self-contained file, no extra requests |
|
|
35
|
+
|
|
36
|
+
Notes:
|
|
37
|
+
|
|
38
|
+
- `dist/client.cjs` and `dist/http.cjs` are CommonJS builds and cannot be
|
|
39
|
+
loaded directly by a browser.
|
|
40
|
+
- `dist/client.es.min.js` and `dist/http.es.min.js` are minified on demand by
|
|
41
|
+
jsDelivr from the published `.es.js` files. They are still ES modules, and
|
|
42
|
+
because they are generated they must not be used with subresource integrity
|
|
43
|
+
hashes.
|
|
44
|
+
- `dist/client.es.js` and `dist/http.es.js` import a build-specific shared chunk
|
|
45
|
+
whose name changes on every release. Do not copy a chunk filename into your
|
|
46
|
+
page; import the entry file and let the browser resolve it, or use `+esm` to
|
|
47
|
+
avoid the extra request entirely.
|
|
48
|
+
|
|
49
|
+
## 3. Loading the module
|
|
50
|
+
|
|
51
|
+
Browser ESM with jsDelivr:
|
|
52
|
+
|
|
53
|
+
```html
|
|
54
|
+
<script type="module">
|
|
55
|
+
import { createVrpcClient } from "https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/+esm";
|
|
56
|
+
|
|
57
|
+
// ...
|
|
58
|
+
</script>
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The same API is available from the unbundled entry file:
|
|
62
|
+
|
|
63
|
+
```html
|
|
64
|
+
<script type="module">
|
|
65
|
+
import { createVrpcClient } from "https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/dist/client.es.js";
|
|
66
|
+
</script>
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Import the HTTP client from its own module path:
|
|
70
|
+
|
|
71
|
+
```html
|
|
72
|
+
<script type="module">
|
|
73
|
+
import { createHttpClient } from "https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/http/+esm";
|
|
74
|
+
</script>
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
This form does **not** work, because the bundle is an ES module:
|
|
78
|
+
|
|
79
|
+
```html
|
|
80
|
+
<!-- Fails: the runtime has no global build. -->
|
|
81
|
+
<script src="https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/dist/client.es.js"></script>
|
|
82
|
+
<script>
|
|
83
|
+
const client = Vrpc.createVrpcClient({/* ... */}); // Vrpc is undefined
|
|
84
|
+
</script>
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## 4. Complete vRPC example
|
|
88
|
+
|
|
89
|
+
Save this as `vrpc-demo.html` and open it in a browser. It creates a client,
|
|
90
|
+
invokes a method, and renders either the result or a classified error.
|
|
91
|
+
|
|
92
|
+
```html
|
|
93
|
+
<!doctype html>
|
|
94
|
+
<html lang="en">
|
|
95
|
+
<head>
|
|
96
|
+
<meta charset="utf-8" />
|
|
97
|
+
<title>vRPC CDN demo</title>
|
|
98
|
+
</head>
|
|
99
|
+
<body>
|
|
100
|
+
<pre id="output">loading…</pre>
|
|
101
|
+
|
|
102
|
+
<script type="module">
|
|
103
|
+
import {
|
|
104
|
+
createVrpcClient,
|
|
105
|
+
getClientInstanceId,
|
|
106
|
+
isVrpcError,
|
|
107
|
+
} from "https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/+esm";
|
|
108
|
+
|
|
109
|
+
const output = document.getElementById("output");
|
|
110
|
+
|
|
111
|
+
const client = createVrpcClient({
|
|
112
|
+
prefixUrl: "https://api.example.com/invoke",
|
|
113
|
+
clientInfo: {
|
|
114
|
+
clientName: "demo.browser",
|
|
115
|
+
clientVersion: "1.0.0",
|
|
116
|
+
clientInstanceId: getClientInstanceId(),
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
const profile = await client.invoke({
|
|
122
|
+
serviceName: "user.UserService",
|
|
123
|
+
methodName: "getProfile",
|
|
124
|
+
params: { userId: 1 },
|
|
125
|
+
});
|
|
126
|
+
output.textContent = JSON.stringify(profile, null, 2);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (!isVrpcError(error)) {
|
|
129
|
+
output.textContent = String(error);
|
|
130
|
+
} else if (error.kind === "invoke") {
|
|
131
|
+
output.textContent = `${error.vrpcStatus} ${error.code} ${error.reason}`;
|
|
132
|
+
} else {
|
|
133
|
+
output.textContent = `${error.kind}: ${error.message}`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
</script>
|
|
137
|
+
</body>
|
|
138
|
+
</html>
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Top-level `await` is valid inside a module script, so no wrapper function is
|
|
142
|
+
required.
|
|
143
|
+
|
|
144
|
+
## 5. Complete HTTP example
|
|
145
|
+
|
|
146
|
+
The generic HTTP client is a separate module and does not use vRPC protocol
|
|
147
|
+
headers.
|
|
148
|
+
|
|
149
|
+
```html
|
|
150
|
+
<!doctype html>
|
|
151
|
+
<html lang="en">
|
|
152
|
+
<head>
|
|
153
|
+
<meta charset="utf-8" />
|
|
154
|
+
<title>HTTP CDN demo</title>
|
|
155
|
+
</head>
|
|
156
|
+
<body>
|
|
157
|
+
<pre id="output">loading…</pre>
|
|
158
|
+
|
|
159
|
+
<script type="module">
|
|
160
|
+
import {
|
|
161
|
+
createHttpClient,
|
|
162
|
+
isHttpError,
|
|
163
|
+
} from "https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/http/+esm";
|
|
164
|
+
|
|
165
|
+
const output = document.getElementById("output");
|
|
166
|
+
|
|
167
|
+
const http = createHttpClient({
|
|
168
|
+
prefixUrl: "https://api.example.com",
|
|
169
|
+
timeoutMs: 5_000,
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
try {
|
|
173
|
+
const profile = await http.request({ path: "/users/me" });
|
|
174
|
+
output.textContent = JSON.stringify(profile, null, 2);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
output.textContent = isHttpError(error) ? `${error.kind}: ${error.message}` : String(error);
|
|
177
|
+
}
|
|
178
|
+
</script>
|
|
179
|
+
</body>
|
|
180
|
+
</html>
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## 6. Version pinning
|
|
184
|
+
|
|
185
|
+
Always pin an exact version in the URL:
|
|
186
|
+
|
|
187
|
+
```text
|
|
188
|
+
https://cdn.jsdelivr.net/npm/@yorun-ai/vrpc@0.9.3/+esm
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`@0.9.3` is immutable on jsDelivr. A floating range such as `@0` resolves to the
|
|
192
|
+
newest `0.x` release and can pick up behavior changes; use it only for a
|
|
193
|
+
throwaway prototype. Keep the pinned version aligned with the version in your
|
|
194
|
+
`package.json` when the same project uses both.
|
|
195
|
+
|
|
196
|
+
## 7. Troubleshooting
|
|
197
|
+
|
|
198
|
+
| Symptom | Cause and fix |
|
|
199
|
+
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
200
|
+
| `Cannot use import statement outside a module` | The script tag is missing `type="module"`. |
|
|
201
|
+
| `window.Vrpc is undefined` / `window.Http is undefined` | There is no global build. Import the module instead. |
|
|
202
|
+
| `Failed to resolve module specifier` | A bare specifier such as `@yorun-ai/vrpc` was used in a browser import without a CDN URL or an import map. |
|
|
203
|
+
| `404` when importing the shared chunk | A hashed chunk filename was copied into a page. Import `dist/client.es.js` / `dist/http.es.js` and let the browser resolve it, or use `+esm`. |
|
|
204
|
+
| Blocked by CORS | The target API must return `Access-Control-Allow-Origin`. Cookies additionally require `requestInit: { credentials: "include" }` on the client and `Access-Control-Allow-Credentials: true` on the server. |
|
|
205
|
+
| Unexpected behavior after a release | The CDN URL is not pinned to an exact version. |
|
|
206
|
+
| `fetch is not available in current runtime` | The page runs in an environment without a global `fetch`, such as a very old browser. |
|
|
207
|
+
| An interceptor is never called | `client.use(...)` must be called on the same client instance that performs the request. |
|
|
208
|
+
|
|
209
|
+
For protocol-level failures such as a missing `vrpc-status` or `vrpc-server`
|
|
210
|
+
header, see the [vRPC protocol](../maintainers/protocol.md) reference.
|
|
211
|
+
|
|
212
|
+
## 8. Verification status
|
|
213
|
+
|
|
214
|
+
The examples in this guide were checked against the `0.9.3` bundle in a real
|
|
215
|
+
browser: the bundled `+esm` imports, the unbundled `dist/*.es.js` entry files,
|
|
216
|
+
and the jsDelivr-generated `dist/*.es.min.js` variants all load as ES modules
|
|
217
|
+
and complete a real invocation. Loading any of them as a classic script fails,
|
|
218
|
+
and no global variable is created.
|
|
219
|
+
|
|
220
|
+
Each version ships its own build, so re-check these loading modes when you move
|
|
221
|
+
the pinned version.
|
package/docs/guides/usage.md
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
# Usage
|
|
2
2
|
|
|
3
|
+
This guide is the canonical reference for client configuration and extension
|
|
4
|
+
points. For a no-build browser setup see [Browser CDN usage](./cdn.md), for the
|
|
5
|
+
public API surface see the [API Reference](../reference/README.md), and for
|
|
6
|
+
wire-level details see the [vRPC protocol](../maintainers/protocol.md).
|
|
7
|
+
|
|
3
8
|
## 1. Generic HTTP client
|
|
4
9
|
|
|
5
10
|
```ts
|
|
6
|
-
import {
|
|
11
|
+
import { createHttpClient, isHttpError } from "@yorun-ai/vrpc/http";
|
|
7
12
|
|
|
8
13
|
const client = createHttpClient({
|
|
9
14
|
prefixUrl: "https://api.example.com",
|
|
@@ -19,6 +24,9 @@ client.use({
|
|
|
19
24
|
console.log(context.url, context.init.method);
|
|
20
25
|
},
|
|
21
26
|
onError(error, context) {
|
|
27
|
+
if (isHttpError(error) && error.kind === "abort") {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
22
30
|
if (context.options.suppressGlobalToast) {
|
|
23
31
|
return;
|
|
24
32
|
}
|
|
@@ -66,17 +74,20 @@ client.request({
|
|
|
66
74
|
- `json` and `body` are mutually exclusive.
|
|
67
75
|
- `json` is serialized automatically and adds `content-type: application/json`.
|
|
68
76
|
- Pass `FormData` through `body`; do not set its content-type boundary manually.
|
|
77
|
+
- `path` is relative to `prefixUrl` by default. Absolute request URLs are rejected before transport.
|
|
78
|
+
- Set create-time `allowAbsoluteUrls: true` only for trusted complete URLs. The opt-in accepts `http:` and `https:`, forwards configured headers to the selected URL, and still rejects protocol-relative URLs such as `//example.com/path`.
|
|
69
79
|
- Create-time defaults are merged with per-request options; per-request scalar and requestInit fields take precedence.
|
|
70
80
|
- An interceptor receives merged configuration in `context.options` and the original call shape in `context.request`.
|
|
71
81
|
- Options do not leak into the transport request.
|
|
72
82
|
- `timeoutMs` is disabled by default. Set an application default at creation and override it per request when needed.
|
|
73
83
|
- The default is `credentials: "omit"`; use `requestInit.credentials: "include"` for cookies.
|
|
74
|
-
-
|
|
84
|
+
- Response parsing is intentionally lenient and independent of `content-type`: an empty body returns `null`, valid JSON is decoded, and any other body is returned as text.
|
|
85
|
+
- A timeout throws `HttpTimeoutError`; a non-2xx response throws `HttpInvokeError`.
|
|
75
86
|
|
|
76
87
|
## 2. vRPC client
|
|
77
88
|
|
|
78
89
|
```ts
|
|
79
|
-
import {
|
|
90
|
+
import { createVrpcClient, getClientInstanceId, isVrpcError } from "@yorun-ai/vrpc/client";
|
|
80
91
|
|
|
81
92
|
const client = createVrpcClient({
|
|
82
93
|
prefixUrl: "https://api.example.com/invoke",
|
|
@@ -91,13 +102,19 @@ const client = createVrpcClient({
|
|
|
91
102
|
|
|
92
103
|
client.use({
|
|
93
104
|
onError(error, context) {
|
|
105
|
+
if (isVrpcError(error) && error.kind === "abort") {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
94
108
|
if (context.options.suppressGlobalToast) {
|
|
95
109
|
return;
|
|
96
110
|
}
|
|
97
111
|
|
|
98
|
-
if (error
|
|
112
|
+
if (isVrpcError(error) && error.kind === "invoke") {
|
|
99
113
|
console.error(error.status, error.vrpcStatus, error.code, error.reason);
|
|
114
|
+
return;
|
|
100
115
|
}
|
|
116
|
+
|
|
117
|
+
console.error(error);
|
|
101
118
|
},
|
|
102
119
|
});
|
|
103
120
|
|
|
@@ -158,7 +175,155 @@ options: {
|
|
|
158
175
|
|
|
159
176
|
`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
177
|
|
|
161
|
-
## 3.
|
|
178
|
+
## 3. Error handling
|
|
179
|
+
|
|
180
|
+
The vRPC entry point exposes one client-level guard, `isVrpcError`. After it succeeds, use only the discriminating `kind` field for error policy and server business fields:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import { isVrpcError } from "@yorun-ai/vrpc";
|
|
184
|
+
|
|
185
|
+
function handleVrpcError(error: unknown) {
|
|
186
|
+
if (!isVrpcError(error)) {
|
|
187
|
+
console.error("Unexpected error", error);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
switch (error.kind) {
|
|
192
|
+
case "abort":
|
|
193
|
+
return;
|
|
194
|
+
case "timeout":
|
|
195
|
+
console.error(`Request timed out after ${error.timeoutMs}ms`);
|
|
196
|
+
return;
|
|
197
|
+
case "transport":
|
|
198
|
+
console.error("Network request failed", error.cause);
|
|
199
|
+
return;
|
|
200
|
+
case "invoke":
|
|
201
|
+
console.error(error.status, error.vrpcStatus, error.code, error.reason, error.message);
|
|
202
|
+
return;
|
|
203
|
+
case "protocol":
|
|
204
|
+
console.error("Invalid vRPC response", error.cause);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
The generic HTTP entry point exposes the equivalent `isHttpError` guard. Both guards recognize only normalized errors produced by this package; compatibility handling for native Fetch and custom adapter errors stays inside the transport boundary. Error classes remain available for compatibility and specialized tests, but ordinary application code does not need a second `instanceof` check after the guard.
|
|
211
|
+
|
|
212
|
+
| `kind` | Client | Meaning |
|
|
213
|
+
| ----------- | ------------- | ------------------------------------------------------------------------------------------ |
|
|
214
|
+
| `abort` | HTTP and vRPC | The caller canceled through an `AbortSignal`. Usually silent in the UI. |
|
|
215
|
+
| `timeout` | HTTP and vRPC | The configured client timeout expired. |
|
|
216
|
+
| `transport` | HTTP and vRPC | No usable HTTP response was received. The original adapter error is available as `cause`. |
|
|
217
|
+
| `invoke` | HTTP and vRPC | The server rejected the invocation. vRPC errors expose `vrpcStatus`, `code`, and `reason`. |
|
|
218
|
+
| `protocol` | vRPC only | Required vRPC metadata is missing, or a successful response cannot be decoded. |
|
|
219
|
+
|
|
220
|
+
`VrpcInvokeError` uses `vrpc-status` as the authoritative vRPC outcome. The body error is auxiliary: `code` identifies the business category, `reason` identifies a more specific case, and a non-empty `detail` remains appended to `message`. If a failed vRPC response has an undecodable body, the client still throws `VrpcInvokeError` and records the decoding failure in `cause`.
|
|
221
|
+
|
|
222
|
+
An interceptor `onError` observes the error but does not consume it; the request promise still rejects. Put the `abort` check before logging or global toast logic when caller cancellation should be quiet.
|
|
223
|
+
|
|
224
|
+
Recommended application policy:
|
|
225
|
+
|
|
226
|
+
- Handle `abort` once in the global `onError` interceptor and show no error UI.
|
|
227
|
+
- Handle `timeout`, `transport`, and `protocol` globally with a stable user-facing message; retain `cause` for logging or reporting rather than displaying it directly.
|
|
228
|
+
- Branch on expected `invoke` values such as `code` and `reason` near the feature that understands them. Use `suppressGlobalToast` when that feature owns the UI, preventing duplicate messages.
|
|
229
|
+
- Treat values that fail `isVrpcError` as configuration, interceptor, or other unexpected application errors; do not silently classify them as network failures.
|
|
230
|
+
|
|
231
|
+
### Global `onError` and local `try/catch`
|
|
232
|
+
|
|
233
|
+
Global and local handlers have different responsibilities. A global `onError` interceptor is suitable for shared logging, reporting, and fallback UI. A local `try/catch` is suitable for an expected business outcome that the current feature can explain or recover from.
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
client.use({
|
|
237
|
+
onError(error, context) {
|
|
238
|
+
if (isVrpcError(error) && error.kind === "abort") {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
reportError(error);
|
|
243
|
+
|
|
244
|
+
if (!context.options.suppressGlobalToast) {
|
|
245
|
+
showToast("Request failed. Please try again.");
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
async function loadProfile() {
|
|
251
|
+
try {
|
|
252
|
+
return await client.invoke({
|
|
253
|
+
serviceName: "user.UserService",
|
|
254
|
+
methodName: "getProfile",
|
|
255
|
+
params: { userId: 1 },
|
|
256
|
+
options: {
|
|
257
|
+
// This feature owns the error UI shown in the catch block below.
|
|
258
|
+
suppressGlobalToast: true,
|
|
259
|
+
},
|
|
260
|
+
});
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (!isVrpcError(error)) {
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (error.kind === "abort") {
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (error.kind === "invoke" && error.code === "USER" && error.reason === "NOT_FOUND") {
|
|
271
|
+
showToast(error.message);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// suppressGlobalToast also suppressed the global fallback, so keep a local fallback.
|
|
276
|
+
showToast("Unable to load the profile. Please try again.");
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
For transport and response failures, the lifecycle is:
|
|
282
|
+
|
|
283
|
+
```text
|
|
284
|
+
request fails -> onError runs -> the Promise rejects -> local catch runs
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`onError` should perform side effects and complete normally. It does not turn a failed request into a successful result; after the interceptors complete, the request Promise still rejects.
|
|
288
|
+
|
|
289
|
+
`suppressGlobalToast` is policy metadata for application interceptors. The package does not display or suppress UI by itself. Setting it to `true` does not skip `onError`, logging, or Promise rejection; it only has an effect when an interceptor reads `context.options.suppressGlobalToast`. A per-request `true` or `false` overrides the client-level default. Set it to `true` only when the local caller owns a complete error experience, including a fallback for errors it does not specifically recognize.
|
|
290
|
+
|
|
291
|
+
Request-construction errors that occur before an interceptor context exists, such as invalid configuration, reject directly and may only reach the local `catch`. The same global/local pattern applies to the generic HTTP client with `isHttpError`.
|
|
292
|
+
|
|
293
|
+
## 4. Cancel requests
|
|
294
|
+
|
|
295
|
+
Both clients accept an `AbortSignal` through `requestInit.signal`:
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
import { isVrpcError } from "@yorun-ai/vrpc";
|
|
299
|
+
|
|
300
|
+
const controller = new AbortController();
|
|
301
|
+
const request = client.invoke({
|
|
302
|
+
serviceName: "user.UserService",
|
|
303
|
+
methodName: "getUser",
|
|
304
|
+
params: { userId: 1 },
|
|
305
|
+
options: {
|
|
306
|
+
requestInit: { signal: controller.signal },
|
|
307
|
+
},
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
// For example: the user closes a dialog or navigates away.
|
|
311
|
+
controller.abort();
|
|
312
|
+
|
|
313
|
+
try {
|
|
314
|
+
await request;
|
|
315
|
+
} catch (error) {
|
|
316
|
+
if (!(isVrpcError(error) && error.kind === "abort")) {
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
Cancellation remains a rejected promise so frameworks and callers can finish loading-state cleanup. The normalized error preserves a custom `controller.abort(reason)` value as `reason` and the underlying runtime error as `cause`. A single controller may cancel multiple requests that share its signal. Aborting after a request has settled has no effect.
|
|
323
|
+
|
|
324
|
+
Timeouts may also use `AbortController` internally, but they remain `kind: "timeout"`; applications should not silently treat them as caller cancellation.
|
|
325
|
+
|
|
326
|
+
## 5. Automatic CBOR
|
|
162
327
|
|
|
163
328
|
A generated method without Binary has no wire and uses JSON. A method whose arguments or result contain Binary includes the corresponding schema:
|
|
164
329
|
|
|
@@ -214,7 +379,7 @@ Selection depends entirely on wire-property presence:
|
|
|
214
379
|
|
|
215
380
|
Wire never appears in the HTTP body, custom headers, or transport request.
|
|
216
381
|
|
|
217
|
-
##
|
|
382
|
+
## 6. Protocol helpers
|
|
218
383
|
|
|
219
384
|
```ts
|
|
220
385
|
import {
|
|
@@ -237,7 +402,7 @@ const body = buildVrpcRequestBody({ userId: 1 });
|
|
|
237
402
|
|
|
238
403
|
`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
404
|
|
|
240
|
-
##
|
|
405
|
+
## 7. Custom transport
|
|
241
406
|
|
|
242
407
|
A transport performs I/O only, and the response body must remain raw bytes:
|
|
243
408
|
|
|
@@ -20,13 +20,35 @@ A transport response must preserve the original `Uint8Array | null`. The generic
|
|
|
20
20
|
## Generic HTTP flow
|
|
21
21
|
|
|
22
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.
|
|
24
|
-
3.
|
|
25
|
-
4.
|
|
26
|
-
5. The
|
|
23
|
+
2. Request paths are joined to `prefixUrl`. Absolute paths are rejected before transport unless the HTTP client was created with `allowAbsoluteUrls: true`; the opt-in permits only HTTP(S), while protocol-relative URLs remain invalid. This policy is HTTP-only and does not constrain a vRPC client's `prefixUrl`.
|
|
24
|
+
3. Per-request `request.options` override defaults. Headers are merged, requestInit is shallow-merged, and per-request scalar values take precedence.
|
|
25
|
+
4. Interceptors receive `{ url, init, request, options }`; `options` contains the merged configuration.
|
|
26
|
+
5. The transport sends the request and returns raw bytes.
|
|
27
|
+
6. The core reconstructs a `Response`, parses JSON, text, or an empty response, and throws `HttpInvokeError` for a non-success status.
|
|
27
28
|
|
|
28
29
|
Request options and interceptor-only fields must not enter `HttpTransportRequest`.
|
|
29
30
|
|
|
31
|
+
## Error model
|
|
32
|
+
|
|
33
|
+
Normalized transport, protocol, and invocation errors extend `HttpClientError` and carry a stable `kind`, request URL and method, plus the original error in `cause` when one exists. Request-construction and user-interceptor exceptions remain ordinary developer errors. The public entry points expose a single guard followed by kind-based classification:
|
|
34
|
+
|
|
35
|
+
- vRPC: `isVrpcError(error)`
|
|
36
|
+
- Generic HTTP: `isHttpError(error)`
|
|
37
|
+
|
|
38
|
+
`HttpError` is the discriminated union of caller abort, timeout, transport, and HTTP invoke errors. `VrpcError` adds vRPC invoke and protocol errors to the three shared lifecycle errors. In particular, a generic `HttpInvokeError` is not a `VrpcError`; after `isVrpcError`, `kind: "invoke"` narrows directly to `VrpcInvokeError`. Application code therefore does not need to mix `kind` checks with `instanceof` checks.
|
|
39
|
+
|
|
40
|
+
The built-in Fetch transport determines whether its composed signal was aborted by the caller or by the configured timeout. Caller cancellation becomes `HttpAbortError`; timeout becomes `HttpTimeoutError`; other Fetch failures become `HttpTransportError`. The core preserves known package errors and wraps unknown custom-transport failures as `HttpTransportError`. Native `AbortError` and common adapter cancellation shapes are normalized internally rather than exposed through an additional public cancellation guard.
|
|
41
|
+
|
|
42
|
+
Generic HTTP response parsing is deliberately lenient and independent of `content-type`: an empty body becomes `null`, valid JSON is decoded, and a body that is not valid JSON remains text. JSON syntax is therefore not an HTTP failure category. The transport owns body reading; a failure to obtain complete response bytes becomes `HttpTransportError`.
|
|
43
|
+
|
|
44
|
+
vRPC decoding remains strict about its media type and required protocol metadata. A malformed successful vRPC response becomes `VrpcProtocolError` and retains HTTP status, response headers, `vrpc-status` when present, and the decoding failure as `cause`.
|
|
45
|
+
|
|
46
|
+
For a failed vRPC response, `vrpc-status` remains authoritative and the body error remains auxiliary. If the body cannot be decoded but a failing `vrpc-status` is present, the client throws `VrpcInvokeError` with `payload: null` and preserves the decoding error in `cause`. It does not replace the invocation failure with a protocol error or validate `result` and `error` as a strict mutually exclusive envelope.
|
|
47
|
+
|
|
48
|
+
Caller cancellation still reaches `onError` and still rejects the request promise. Applications that want quiet cancellation should return early from their global error handler when `error.kind === "abort"`; the transport and core must not convert cancellation into a successful result.
|
|
49
|
+
|
|
50
|
+
`suppressGlobalToast` is interceptor-only application policy metadata. The runtime merges the client default with the per-request override and exposes the resolved value through `context.options`; it never performs UI work, skips `onError`, consumes the rejection, or copies the field into a transport request. A normally completed `onError` chain is followed by rejection of the request Promise, allowing a local `try/catch` to implement feature-specific recovery.
|
|
51
|
+
|
|
30
52
|
## Protocol boundary
|
|
31
53
|
|
|
32
54
|
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.
|
|
@@ -46,7 +46,22 @@ An error response has a null result and may carry a structured error:
|
|
|
46
46
|
}
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
The client treats a response as successful only when the HTTP status is successful and `vrpc-status` is `OK`.
|
|
49
|
+
The client treats a response as successful only when the HTTP status is successful and `vrpc-status` is `OK`. `vrpc-status` is the authoritative vRPC outcome; the body `error` supplies auxiliary `type`, `code`, `reason`, `message`, and `detail` fields. The runtime does not infer success from body fields or require `result` and `error` to form a strictly validated mutually exclusive envelope.
|
|
50
|
+
|
|
51
|
+
Other responses are unwrapped as `VrpcInvokeError`. If a response already carries a failing `vrpc-status` but its body or auxiliary protocol metadata cannot be decoded, it remains a `VrpcInvokeError` with `payload: null`, while the decoding failure is preserved as `cause`. Every response must contain valid `content-type`, `vrpc-status`, and `vrpc-server` headers; a JSON body must be non-empty and parseable. A missing `vrpc-status`, or an otherwise undecodable successful response, produces `VrpcProtocolError` with the HTTP response metadata intact.
|
|
52
|
+
|
|
53
|
+
### Error message construction
|
|
54
|
+
|
|
55
|
+
`VrpcInvokeError.message` deliberately combines the auxiliary body fields `message` and `detail`. When `message` is a non-empty string and trimmed `detail` is non-empty, the runtime produces:
|
|
56
|
+
|
|
57
|
+
```text
|
|
58
|
+
<message>
|
|
59
|
+
<detail>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The newline keeps the primary human-readable summary separate from the additional diagnostic or explanatory text while preserving both in ordinary logs, error boundaries, and UI fallbacks that display only `Error.message`. This behavior also preserves compatibility for applications that already surface the combined message.
|
|
63
|
+
|
|
64
|
+
The combined text is presentation data, not a classification contract. Applications must use `vrpc-status` for the protocol outcome and `code` plus `reason` for business branching; they must not parse `message` or `detail`. If the body has no usable `message`, the runtime falls back to the HTTP status-based error message.
|
|
50
65
|
|
|
51
66
|
## Content negotiation
|
|
52
67
|
|