@yorun-ai/vrpc 0.10.0 → 0.11.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.
package/dist/client.es.js CHANGED
@@ -1,261 +1,9 @@
1
- import { _ as isVrpcError, c as HTTP_TIMEOUT_ERROR_CODE, d as HttpInvokeError, f as HttpTimeoutError, h as VrpcProtocolError, i as createFetchTransport, l as HttpAbortError, m as VrpcInvokeError, n as splitVrpcRequestOptions, o as buildRequestUrl, p as HttpTransportError, r as createClientCore, s as mergeHeaders, u as HttpClientError } from "./request-options-2g2EJjOi.js";
2
- //#region src/protocol/id.ts
3
- var DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY = "vrpc-client-instance-id";
4
- function getRandomByteArray(length) {
5
- const array = new Uint8Array(length);
6
- if (globalThis.crypto?.getRandomValues) {
7
- globalThis.crypto.getRandomValues(array);
8
- return array;
9
- }
10
- for (let i = 0; i < length; i++) array[i] = Math.floor(Math.random() * 256);
11
- return array;
12
- }
13
- function toHex(bytes) {
14
- return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
15
- }
16
- function newNonZeroHex(bytesLength, zeroValue) {
17
- for (;;) {
18
- const value = toHex(getRandomByteArray(bytesLength));
19
- if (value !== zeroValue) return value;
20
- }
21
- }
22
- function generateVrpcId() {
23
- return newNonZeroHex(16, "00000000000000000000000000000000");
24
- }
25
- function generateVrpcSpan() {
26
- return newNonZeroHex(8, "0000000000000000");
27
- }
28
- function generateClientInstanceId() {
29
- if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().toLowerCase();
30
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
31
- const value = Math.floor(Math.random() * 16);
32
- return (char === "x" ? value : value & 3 | 8).toString(16);
33
- });
34
- }
35
- function getClientInstanceId({ key } = {}) {
36
- const storageKey = key?.trim() || "vrpc-client-instance-id";
37
- try {
38
- const existingClientInstanceId = globalThis.localStorage.getItem(storageKey);
39
- if (existingClientInstanceId) return existingClientInstanceId;
40
- const clientInstanceId = generateClientInstanceId();
41
- globalThis.localStorage.setItem(storageKey, clientInstanceId);
42
- return clientInstanceId;
43
- } catch {
44
- return generateClientInstanceId();
45
- }
46
- }
47
- //#endregion
48
- //#region src/protocol/headers.ts
49
- var VRPC_JSON_CONTENT_TYPE = "application/vrpc+json";
50
- var VRPC_CBOR_CONTENT_TYPE = "application/vrpc+cbor";
51
- var CLIENT_NAME_PATTERN = /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/;
52
- var SEMVER_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
53
- var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
54
- var TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
55
- var TRACE_SPAN_PATTERN = /^[0-9a-f]{16}$/;
56
- function assertClientInfo(clientInfo, scope = "client") {
57
- if (!CLIENT_NAME_PATTERN.test(clientInfo.clientName)) throw new Error(`Invalid vRPC ${scope} name: ${clientInfo.clientName}`);
58
- if (!SEMVER_PATTERN.test(clientInfo.clientVersion)) throw new Error(`Invalid vRPC ${scope} version: ${clientInfo.clientVersion}`);
59
- if (!UUID_PATTERN.test(clientInfo.clientInstanceId)) throw new Error(`Invalid vRPC ${scope} instanceId: ${clientInfo.clientInstanceId}`);
60
- }
61
- function decodeDelimitedAppInfo(value) {
62
- const fields = {};
63
- for (const entry of value.split(",")) {
64
- const separator = entry.indexOf("=");
65
- if (separator <= 0) return null;
66
- const key = entry.slice(0, separator).trim();
67
- const fieldValue = entry.slice(separator + 1).trim();
68
- if (!key || !fieldValue || key in fields) return null;
69
- fields[key] = fieldValue;
70
- }
71
- if (Object.keys(fields).length !== 3) return null;
72
- const name = fields.name;
73
- const version = fields.version;
74
- const instanceId = fields.instanceId;
75
- if (!name || !version || !instanceId) return null;
76
- return {
77
- clientName: name,
78
- clientVersion: version,
79
- clientInstanceId: instanceId
80
- };
81
- }
82
- function assertValidVrpcServerHeader(value) {
83
- if (!value) throw new Error("Invalid vRPC response: missing vrpc-server header.");
84
- const serverInfo = decodeDelimitedAppInfo(value);
85
- if (!serverInfo) throw new Error("Invalid vRPC response: invalid vrpc-server header.");
86
- try {
87
- assertClientInfo(serverInfo, "server");
88
- } catch {
89
- throw new Error("Invalid vRPC response: invalid vrpc-server header.");
90
- }
91
- }
92
- function assertValidVrpcTrace(trace) {
93
- if (!TRACE_ID_PATTERN.test(trace.id)) throw new Error(`Invalid vRPC trace id: ${trace.id}`);
94
- if (trace.span !== void 0 && !TRACE_SPAN_PATTERN.test(trace.span)) throw new Error(`Invalid vRPC trace span: ${trace.span}`);
95
- }
96
- function assertValidVrpcTimeout(timeoutMs) {
97
- if (timeoutMs !== void 0 && (!Number.isSafeInteger(timeoutMs) || !Number.isFinite(timeoutMs) || timeoutMs <= 0)) throw new Error(`Invalid vRPC timeoutMs: ${timeoutMs}`);
98
- }
99
- function isReservedVrpcHeader(name) {
100
- const normalized = name.toLowerCase();
101
- return normalized === "accept" || normalized === "content-type" || normalized.startsWith("vrpc-");
102
- }
103
- function assertNoReservedVrpcHeaders(...values) {
104
- for (const value of values) {
105
- if (!value) continue;
106
- const headers = new Headers(value);
107
- for (const name of headers.keys()) if (isReservedVrpcHeader(name)) throw new Error(`vRPC protocol header cannot be overridden: ${name}`);
108
- }
109
- }
110
- function mediaTypeOf(value) {
111
- return value?.split(";", 1)[0]?.trim().toLowerCase() || "";
112
- }
113
- function buildVrpcHeaders({ clientInfo, trace, timeoutMs, requestUsesCbor = false, responseUsesCbor = false }) {
114
- assertClientInfo(clientInfo);
115
- assertValidVrpcTrace(trace);
116
- assertValidVrpcTimeout(timeoutMs);
117
- const headers = new Headers();
118
- headers.set("content-type", requestUsesCbor ? VRPC_CBOR_CONTENT_TYPE : VRPC_JSON_CONTENT_TYPE);
119
- headers.set("accept", responseUsesCbor ? `${VRPC_CBOR_CONTENT_TYPE}, ${VRPC_JSON_CONTENT_TYPE}` : VRPC_JSON_CONTENT_TYPE);
120
- headers.set("vrpc-client", `name=${clientInfo.clientName},version=${clientInfo.clientVersion},instanceId=${clientInfo.clientInstanceId}`);
121
- headers.set("vrpc-trace", trace.span ? `id=${trace.id},span=${trace.span}` : `id=${trace.id}`);
122
- if (timeoutMs !== void 0) headers.set("vrpc-options", `timeout=${timeoutMs}ms`);
123
- return headers;
124
- }
125
- //#endregion
126
- //#region src/protocol/wire.ts
127
- function resolveFields(schema) {
128
- return typeof schema.fields === "function" ? schema.fields() : schema.fields;
129
- }
130
- function entriesOf(value) {
131
- if (value instanceof Map) return Array.from(value.entries());
132
- if (value && typeof value === "object" && !Array.isArray(value)) return Object.entries(value);
133
- throw new Error("vRPC wire map value must be a Record or Map.");
134
- }
135
- function objectOf(value) {
136
- if (value instanceof Map) return Object.fromEntries(Array.from(value.entries(), ([key, item]) => [String(key), item]));
137
- if (value && typeof value === "object" && !Array.isArray(value)) return value;
138
- throw new Error("vRPC wire object value must be an object.");
139
- }
140
- function toIntegerKey(value) {
141
- const integer = typeof value === "number" ? value : Number(value);
142
- if (!Number.isSafeInteger(integer)) throw new Error(`vRPC wire map key must be an integer: ${String(value)}`);
143
- return integer;
144
- }
145
- function normalizeBinary(value) {
146
- if (value instanceof Uint8Array) return value;
147
- if (value instanceof ArrayBuffer) return new Uint8Array(value);
148
- if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
149
- throw new Error("vRPC Binary value must be a Uint8Array.");
150
- }
151
- function toCborWireValue(value, schema) {
152
- if (value == null) return value;
153
- switch (schema.kind) {
154
- case "value": return value;
155
- case "binary": return normalizeBinary(value);
156
- case "list":
157
- if (!Array.isArray(value)) throw new Error("vRPC wire list value must be an array.");
158
- return value.map((item) => toCborWireValue(item, schema.value));
159
- case "map": {
160
- const entries = entriesOf(value);
161
- if (schema.key === "int") return new Map(entries.map(([key, item]) => [toIntegerKey(key), toCborWireValue(item, schema.value)]));
162
- return Object.fromEntries(entries.map(([key, item]) => [String(key), toCborWireValue(item, schema.value)]));
163
- }
164
- case "object": {
165
- const input = objectOf(value);
166
- const output = { ...input };
167
- for (const [field, fieldSchema] of Object.entries(resolveFields(schema))) if (field in input) output[field] = toCborWireValue(input[field], fieldSchema);
168
- return output;
169
- }
170
- }
171
- }
172
- function fromCborWireValue(value, schema) {
173
- if (value == null) return value;
174
- switch (schema.kind) {
175
- case "value": return value;
176
- case "binary": return normalizeBinary(value);
177
- case "list":
178
- if (!Array.isArray(value)) throw new Error("vRPC wire list value must be an array.");
179
- return value.map((item) => fromCborWireValue(item, schema.value));
180
- case "map": return Object.fromEntries(entriesOf(value).map(([key, item]) => {
181
- const normalizedKey = schema.key === "int" ? toIntegerKey(key) : String(key);
182
- return [String(normalizedKey), fromCborWireValue(item, schema.value)];
183
- }));
184
- case "object": {
185
- const input = objectOf(value);
186
- const output = { ...input };
187
- for (const [field, fieldSchema] of Object.entries(resolveFields(schema))) if (field in input) output[field] = fromCborWireValue(input[field], fieldSchema);
188
- return output;
189
- }
190
- }
191
- }
192
- function normalizeCborValue(value) {
193
- if (value instanceof Uint8Array) return value;
194
- if (value instanceof Map) return Object.fromEntries(Array.from(value.entries(), ([key, item]) => [String(key), normalizeCborValue(item)]));
195
- if (Array.isArray(value)) return value.map(normalizeCborValue);
196
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeCborValue(item)]));
197
- return value;
198
- }
199
- //#endregion
200
- //#region src/protocol/request.ts
201
- function buildVrpcPath(serviceName, methodName) {
202
- return `${encodeURIComponent(serviceName)}/${encodeURIComponent(methodName)}`;
203
- }
204
- function buildVrpcRequestBody(params) {
205
- return JSON.stringify({ params: params ?? null });
206
- }
207
- async function encodeVrpcRequestBody(params, schema, cborCodec) {
208
- if (!schema) return buildVrpcRequestBody(params);
209
- if (!cborCodec) throw new Error("A cborCodec is required to encode a CBOR vRPC request.");
210
- const bytes = await cborCodec.encode({ params: toCborWireValue(params, schema) });
211
- if (!(bytes instanceof Uint8Array)) throw new Error("cborCodec.encode() must return a Uint8Array.");
212
- const body = new Uint8Array(bytes.byteLength);
213
- body.set(bytes);
214
- return body.buffer;
215
- }
216
- //#endregion
1
+ import { _ as isVrpcError, c as HTTP_TIMEOUT_ERROR_CODE, d as HttpInvokeError, f as HttpTimeoutError, h as VrpcProtocolError, i as createFetchTransport, l as HttpAbortError, m as VrpcInvokeError, n as splitVrpcRequestOptions, o as buildRequestUrl, p as HttpTransportError, r as createClientCore, s as mergeHeaders, u as HttpClientError } from "./request-options-CV6EPON5.js";
2
+ import { S as getClientInstanceId, _ as buildVrpcHeaders, b as generateVrpcId, c as decodeVrpcBody, d as buildVrpcRequestBody, f as encodeVrpcRequestBody, h as assertNoReservedVrpcHeaders, m as VRPC_JSON_CONTENT_TYPE, o as resolveVrpcEnvelope, p as VRPC_CBOR_CONTENT_TYPE, u as buildVrpcPath, v as DEFAULT_CLIENT_INSTANCE_ID_STORAGE_KEY, x as generateVrpcSpan, y as generateClientInstanceId } from "./data-DOZk_tFi.js";
217
3
  //#region src/protocol/response.ts
218
- function readEnvelopeError(payload) {
219
- if (!payload || typeof payload !== "object") return payload;
220
- return payload.error ?? payload;
221
- }
222
- function readEnvelopeResult(payload) {
223
- if (!payload || typeof payload !== "object") return;
224
- return payload.result;
225
- }
226
- function requireResponseHeader(response, name) {
227
- const value = response.headers.get(name);
228
- if (!value) throw new Error(`Invalid vRPC response: missing ${name} header.`);
229
- return value;
230
- }
231
- function readDecodedEnvelopeField(payload, field) {
232
- if (payload instanceof Map) return payload.get(field);
233
- if (payload && typeof payload === "object") return payload[field];
234
- }
235
4
  async function decodeVrpcResponsePayload(response, cborCodec, resultSchema) {
236
5
  try {
237
- requireResponseHeader(response, "vrpc-status");
238
- assertValidVrpcServerHeader(response.headers.get("vrpc-server"));
239
- const contentType = mediaTypeOf(requireResponseHeader(response, "content-type"));
240
- if (contentType === "application/vrpc+json") {
241
- const text = await response.text();
242
- if (!text) throw new Error("Invalid vRPC response: empty response body.");
243
- try {
244
- return JSON.parse(text);
245
- } catch {
246
- throw new Error("Invalid vRPC response: JSON body cannot be parsed.");
247
- }
248
- }
249
- if (contentType !== "application/vrpc+cbor") throw new Error(`Invalid vRPC response content-type: ${contentType || "empty"}.`);
250
- if (!resultSchema) throw new Error("Invalid vRPC response: unexpected CBOR body for a JSON method.");
251
- if (!cborCodec) throw new Error("A cborCodec is required to decode a CBOR vRPC response.");
252
- const decoded = await cborCodec.decode(new Uint8Array(await response.arrayBuffer()));
253
- const result = readDecodedEnvelopeField(decoded, "result");
254
- const error = readDecodedEnvelopeField(decoded, "error");
255
- return {
256
- result: fromCborWireValue(result, resultSchema),
257
- error: normalizeCborValue(error)
258
- };
6
+ return await decodeVrpcBody(response, cborCodec, resultSchema);
259
7
  } catch (cause) {
260
8
  if (cause instanceof VrpcProtocolError) throw cause;
261
9
  const message = cause instanceof Error ? cause.message : "Invalid vRPC response.";
@@ -294,34 +42,16 @@ function resolveVrpcResponse(responseLike, payload) {
294
42
  const statusText = response.statusText || "";
295
43
  const url = responseLike.url || response.url || "";
296
44
  const method = responseLike.method || "POST";
297
- if (response.ok && vrpcStatus === "OK") return {
298
- response,
299
- parsed: {
300
- ok: true,
301
- status: response.status,
302
- statusText,
303
- vrpcStatus: "OK",
304
- headers: response.headers,
305
- url,
306
- method,
307
- payload,
308
- result: payload.result,
309
- error: null
310
- }
311
- };
312
45
  return {
313
46
  response,
314
47
  parsed: {
315
- ok: false,
316
48
  status: response.status,
317
49
  statusText,
318
- vrpcStatus,
319
50
  headers: response.headers,
320
51
  url,
321
52
  method,
322
53
  payload,
323
- result: readEnvelopeResult(payload),
324
- error: readEnvelopeError(payload)
54
+ ...resolveVrpcEnvelope(response.status, vrpcStatus, payload)
325
55
  }
326
56
  };
327
57
  }