@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.
package/dist/http.d.ts ADDED
@@ -0,0 +1,100 @@
1
+ //#region src/contracts/types.d.ts
2
+ type HttpRequestInit = Omit<RequestInit, "method" | "body" | "headers">;
3
+ type HttpQueryPrimitive = string | number | boolean;
4
+ type HttpQueryValue = HttpQueryPrimitive | HttpQueryPrimitive[] | null | undefined;
5
+ type HttpQueryParams = Record<string, HttpQueryValue>;
6
+ type HttpRequestOptions = {
7
+ headers?: HeadersInit;
8
+ timeoutMs?: number;
9
+ requestInit?: HttpRequestInit;
10
+ suppressGlobalToast?: boolean;
11
+ };
12
+ type HttpRequestConfig = {
13
+ path: string;
14
+ method?: string;
15
+ query?: HttpQueryParams | URLSearchParams;
16
+ json?: unknown;
17
+ body?: BodyInit | null;
18
+ options?: HttpRequestOptions;
19
+ };
20
+ type HttpClientOptions = HttpRequestOptions & {
21
+ prefixUrl: string | URL;
22
+ fetchImpl?: typeof fetch;
23
+ transport?: HttpTransport;
24
+ interceptors?: HttpInterceptor[];
25
+ };
26
+ type HttpInvokeContext = {
27
+ url: string;
28
+ init: RequestInit;
29
+ request: HttpRequestConfig;
30
+ options: HttpRequestOptions;
31
+ };
32
+ type HttpInterceptor = {
33
+ beforeRequest?: (context: HttpInvokeContext) => void | Promise<void>;
34
+ afterResponse?: (response: Response, context: HttpInvokeContext) => void | Promise<void>;
35
+ onError?: (error: unknown, context: HttpInvokeContext) => void | Promise<void>;
36
+ };
37
+ type HttpTransportRequest = {
38
+ url: string;
39
+ init: RequestInit;
40
+ method: string;
41
+ headers: HeadersInit;
42
+ body?: BodyInit | null;
43
+ timeoutMs?: number;
44
+ signal?: AbortSignal | null;
45
+ };
46
+ type HttpTransportResponse = {
47
+ status: number;
48
+ statusText?: string;
49
+ headers: Headers;
50
+ body: Uint8Array | null;
51
+ url: string;
52
+ };
53
+ type HttpTransport = {
54
+ request: (request: HttpTransportRequest) => Promise<HttpTransportResponse>;
55
+ close?: () => Promise<void> | void;
56
+ };
57
+ type HttpClient = {
58
+ request: <TResponse = unknown>(request: HttpRequestConfig) => Promise<TResponse>;
59
+ use: (interceptor: HttpInterceptor) => void;
60
+ };
61
+ //#endregion
62
+ //#region src/contracts/errors.d.ts
63
+ type HttpErrorPayload = {
64
+ type?: string;
65
+ code?: string;
66
+ message?: string;
67
+ reason?: string;
68
+ detail?: string;
69
+ };
70
+ type HttpErrorRequestMeta = {
71
+ url?: string;
72
+ method?: string;
73
+ };
74
+ declare const HTTP_TIMEOUT_ERROR_CODE: "HTTP_TIMEOUT";
75
+ declare class HttpTimeoutError extends Error {
76
+ code: typeof HTTP_TIMEOUT_ERROR_CODE;
77
+ timeoutMs: number;
78
+ constructor(timeoutMs: number);
79
+ }
80
+ declare class HttpInvokeError extends Error {
81
+ type?: string;
82
+ code?: string;
83
+ reason?: string;
84
+ detail?: string;
85
+ status: number;
86
+ statusText: string;
87
+ responseHeaders: Headers;
88
+ payload: unknown;
89
+ url: string;
90
+ method: string;
91
+ constructor(response: Response, payload: unknown, requestMeta?: HttpErrorRequestMeta);
92
+ }
93
+ //#endregion
94
+ //#region src/core/create-http-client.d.ts
95
+ declare function createHttpClient(options: HttpClientOptions): HttpClient;
96
+ //#endregion
97
+ //#region src/transports/fetch-transport.d.ts
98
+ declare function createFetchTransport(fetchImpl?: typeof fetch): HttpTransport;
99
+ //#endregion
100
+ export { HTTP_TIMEOUT_ERROR_CODE, type HttpClient, type HttpClientOptions, type HttpErrorPayload, type HttpInterceptor, type HttpInvokeContext, HttpInvokeError, type HttpQueryParams, type HttpQueryPrimitive, type HttpQueryValue, type HttpRequestConfig, type HttpRequestInit, type HttpRequestOptions, HttpTimeoutError, type HttpTransport, type HttpTransportRequest, type HttpTransportResponse, createFetchTransport, createHttpClient };
@@ -0,0 +1,64 @@
1
+ import { a as appendQueryToUrl, c as HTTP_TIMEOUT_ERROR_CODE, i as createFetchTransport, l as HttpInvokeError, o as buildRequestUrl, r as createClientCore, s as mergeHeaders, t as splitHttpRequestOptions, u as HttpTimeoutError } from "./request-options-disym648.js";
2
+ //#region src/core/create-http-client.ts
3
+ function resolveJsonBody(request) {
4
+ if (request.json !== void 0 && request.body !== void 0) throw new Error("Request json and body cannot be used together.");
5
+ if (request.json !== void 0) return JSON.stringify(request.json);
6
+ return request.body;
7
+ }
8
+ function createHttpClient(options) {
9
+ const { prefixUrl, fetchImpl, transport, interceptors, ...baseOptions } = options;
10
+ const core = createClientCore({
11
+ prefixUrl,
12
+ baseOptions,
13
+ fetchImpl,
14
+ transport,
15
+ interceptors,
16
+ splitRequestOptions: splitHttpRequestOptions,
17
+ prepareRequest: (request, helpers) => {
18
+ const requestOptions = helpers.splitRequestOptions(request.options);
19
+ const method = String(request.method || "GET").toUpperCase();
20
+ const url = appendQueryToUrl(buildRequestUrl(helpers.prefixUrl, request.path), request.query);
21
+ const finalHeaders = mergeHeaders(helpers.baseOptions.headers, requestOptions.headers);
22
+ const body = resolveJsonBody(request);
23
+ if (request.json !== void 0 && !finalHeaders.has("content-type")) finalHeaders.set("content-type", "application/json");
24
+ const resolvedRequestInit = {
25
+ ...helpers.baseOptions.requestInit,
26
+ ...requestOptions.requestInit
27
+ };
28
+ const timeoutMs = requestOptions.timeoutMs ?? helpers.baseOptions.timeoutMs;
29
+ const resolvedOptions = {
30
+ headers: finalHeaders,
31
+ timeoutMs,
32
+ requestInit: resolvedRequestInit,
33
+ suppressGlobalToast: requestOptions.suppressGlobalToast ?? helpers.baseOptions.suppressGlobalToast
34
+ };
35
+ const init = {
36
+ ...resolvedRequestInit,
37
+ method,
38
+ headers: finalHeaders
39
+ };
40
+ if (body !== void 0) init.body = body;
41
+ return {
42
+ timeoutMs,
43
+ fallbackMethod: method,
44
+ fallbackHeaders: finalHeaders,
45
+ fallbackBody: body,
46
+ context: {
47
+ url,
48
+ init,
49
+ request,
50
+ options: resolvedOptions
51
+ }
52
+ };
53
+ },
54
+ assertResponse: (response, payload, _context, requestMeta) => {
55
+ if (!response.ok) throw new HttpInvokeError(response, payload, requestMeta);
56
+ }
57
+ });
58
+ return {
59
+ request: core.execute,
60
+ use: core.use
61
+ };
62
+ }
63
+ //#endregion
64
+ export { HTTP_TIMEOUT_ERROR_CODE, HttpInvokeError, HttpTimeoutError, createFetchTransport, createHttpClient };
@@ -0,0 +1,353 @@
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
+ Object.defineProperty(exports, "HTTP_TIMEOUT_ERROR_CODE", {
289
+ enumerable: true,
290
+ get: function() {
291
+ return HTTP_TIMEOUT_ERROR_CODE;
292
+ }
293
+ });
294
+ Object.defineProperty(exports, "HttpInvokeError", {
295
+ enumerable: true,
296
+ get: function() {
297
+ return HttpInvokeError;
298
+ }
299
+ });
300
+ Object.defineProperty(exports, "HttpTimeoutError", {
301
+ enumerable: true,
302
+ get: function() {
303
+ return HttpTimeoutError;
304
+ }
305
+ });
306
+ Object.defineProperty(exports, "VrpcInvokeError", {
307
+ enumerable: true,
308
+ get: function() {
309
+ return VrpcInvokeError;
310
+ }
311
+ });
312
+ Object.defineProperty(exports, "appendQueryToUrl", {
313
+ enumerable: true,
314
+ get: function() {
315
+ return appendQueryToUrl;
316
+ }
317
+ });
318
+ Object.defineProperty(exports, "buildRequestUrl", {
319
+ enumerable: true,
320
+ get: function() {
321
+ return buildRequestUrl;
322
+ }
323
+ });
324
+ Object.defineProperty(exports, "createClientCore", {
325
+ enumerable: true,
326
+ get: function() {
327
+ return createClientCore;
328
+ }
329
+ });
330
+ Object.defineProperty(exports, "createFetchTransport", {
331
+ enumerable: true,
332
+ get: function() {
333
+ return createFetchTransport;
334
+ }
335
+ });
336
+ Object.defineProperty(exports, "mergeHeaders", {
337
+ enumerable: true,
338
+ get: function() {
339
+ return mergeHeaders;
340
+ }
341
+ });
342
+ Object.defineProperty(exports, "splitHttpRequestOptions", {
343
+ enumerable: true,
344
+ get: function() {
345
+ return splitHttpRequestOptions;
346
+ }
347
+ });
348
+ Object.defineProperty(exports, "splitVrpcRequestOptions", {
349
+ enumerable: true,
350
+ get: function() {
351
+ return splitVrpcRequestOptions;
352
+ }
353
+ });