@orpc/client 0.0.0-next.c59d67c → 0.0.0-next.c72b962

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,348 @@
1
+ import { toArray, intercept, isObject, value, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared';
2
+ import { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';
3
+ import { C as COMMON_ORPC_ERROR_DEFS, b as isORPCErrorStatus, c as isORPCErrorJson, d as createORPCErrorFromJson, O as ORPCError, m as mapEventIterator, t as toORPCError } from './client.CRWEpqLB.mjs';
4
+
5
+ class CompositeStandardLinkPlugin {
6
+ plugins;
7
+ constructor(plugins = []) {
8
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
9
+ }
10
+ init(options) {
11
+ for (const plugin of this.plugins) {
12
+ plugin.init?.(options);
13
+ }
14
+ }
15
+ }
16
+
17
+ class InvalidEventIteratorRetryResponse extends Error {
18
+ }
19
+ class StandardLink {
20
+ constructor(codec, sender, options = {}) {
21
+ this.codec = codec;
22
+ this.sender = sender;
23
+ const plugin = new CompositeStandardLinkPlugin(options.plugins);
24
+ plugin.init(options);
25
+ this.interceptors = toArray(options.interceptors);
26
+ this.clientInterceptors = toArray(options.clientInterceptors);
27
+ }
28
+ interceptors;
29
+ clientInterceptors;
30
+ call(path, input, options) {
31
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
32
+ const output = await this.#call(path2, input2, options2);
33
+ return output;
34
+ });
35
+ }
36
+ async #call(path, input, options) {
37
+ const request = await this.codec.encode(path, input, options);
38
+ const response = await intercept(
39
+ this.clientInterceptors,
40
+ { ...options, input, path, request },
41
+ ({ input: input2, path: path2, request: request2, ...options2 }) => this.sender.call(request2, options2, path2, input2)
42
+ );
43
+ const output = await this.codec.decode(response, options, path, input);
44
+ return output;
45
+ }
46
+ }
47
+
48
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
49
+ BIGINT: 0,
50
+ DATE: 1,
51
+ NAN: 2,
52
+ UNDEFINED: 3,
53
+ URL: 4,
54
+ REGEXP: 5,
55
+ SET: 6,
56
+ MAP: 7
57
+ };
58
+ class StandardRPCJsonSerializer {
59
+ customSerializers;
60
+ constructor(options = {}) {
61
+ this.customSerializers = options.customJsonSerializers ?? [];
62
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
63
+ throw new Error("Custom serializer type must be unique.");
64
+ }
65
+ }
66
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
67
+ for (const custom of this.customSerializers) {
68
+ if (custom.condition(data)) {
69
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
70
+ meta.push([custom.type, ...segments]);
71
+ return result;
72
+ }
73
+ }
74
+ if (data instanceof Blob) {
75
+ maps.push(segments);
76
+ blobs.push(data);
77
+ return [data, meta, maps, blobs];
78
+ }
79
+ if (typeof data === "bigint") {
80
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
81
+ return [data.toString(), meta, maps, blobs];
82
+ }
83
+ if (data instanceof Date) {
84
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
85
+ if (Number.isNaN(data.getTime())) {
86
+ return [null, meta, maps, blobs];
87
+ }
88
+ return [data.toISOString(), meta, maps, blobs];
89
+ }
90
+ if (Number.isNaN(data)) {
91
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
92
+ return [null, meta, maps, blobs];
93
+ }
94
+ if (data instanceof URL) {
95
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
96
+ return [data.toString(), meta, maps, blobs];
97
+ }
98
+ if (data instanceof RegExp) {
99
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
100
+ return [data.toString(), meta, maps, blobs];
101
+ }
102
+ if (data instanceof Set) {
103
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
104
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
105
+ return result;
106
+ }
107
+ if (data instanceof Map) {
108
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
109
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
110
+ return result;
111
+ }
112
+ if (Array.isArray(data)) {
113
+ const json = data.map((v, i) => {
114
+ if (v === void 0) {
115
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
116
+ return v;
117
+ }
118
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
119
+ });
120
+ return [json, meta, maps, blobs];
121
+ }
122
+ if (isObject(data)) {
123
+ const json = {};
124
+ for (const k in data) {
125
+ if (k === "toJSON" && typeof data[k] === "function") {
126
+ continue;
127
+ }
128
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
129
+ }
130
+ return [json, meta, maps, blobs];
131
+ }
132
+ return [data, meta, maps, blobs];
133
+ }
134
+ deserialize(json, meta, maps, getBlob) {
135
+ const ref = { data: json };
136
+ if (maps && getBlob) {
137
+ maps.forEach((segments, i) => {
138
+ let currentRef = ref;
139
+ let preSegment = "data";
140
+ segments.forEach((segment) => {
141
+ currentRef = currentRef[preSegment];
142
+ preSegment = segment;
143
+ });
144
+ currentRef[preSegment] = getBlob(i);
145
+ });
146
+ }
147
+ for (const item of meta) {
148
+ const type = item[0];
149
+ let currentRef = ref;
150
+ let preSegment = "data";
151
+ for (let i = 1; i < item.length; i++) {
152
+ currentRef = currentRef[preSegment];
153
+ preSegment = item[i];
154
+ }
155
+ for (const custom of this.customSerializers) {
156
+ if (custom.type === type) {
157
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
158
+ break;
159
+ }
160
+ }
161
+ switch (type) {
162
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
163
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
164
+ break;
165
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
166
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
167
+ break;
168
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
169
+ currentRef[preSegment] = Number.NaN;
170
+ break;
171
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
172
+ currentRef[preSegment] = void 0;
173
+ break;
174
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
175
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
176
+ break;
177
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
178
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
179
+ currentRef[preSegment] = new RegExp(pattern, flags);
180
+ break;
181
+ }
182
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
183
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
184
+ break;
185
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
186
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
187
+ break;
188
+ }
189
+ }
190
+ return ref.data;
191
+ }
192
+ }
193
+
194
+ function toHttpPath(path) {
195
+ return `/${path.map(encodeURIComponent).join("/")}`;
196
+ }
197
+ function getMalformedResponseErrorCode(status) {
198
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
199
+ }
200
+
201
+ class StandardRPCLinkCodec {
202
+ constructor(serializer, options) {
203
+ this.serializer = serializer;
204
+ this.baseUrl = options.url;
205
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
206
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
207
+ this.expectedMethod = options.method ?? this.fallbackMethod;
208
+ this.headers = options.headers ?? {};
209
+ }
210
+ baseUrl;
211
+ maxUrlLength;
212
+ fallbackMethod;
213
+ expectedMethod;
214
+ headers;
215
+ async encode(path, input, options) {
216
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
217
+ let headers = await value(this.headers, options, path, input);
218
+ const baseUrl = await value(this.baseUrl, options, path, input);
219
+ const url = new URL(baseUrl);
220
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
221
+ if (options.lastEventId !== void 0) {
222
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
223
+ }
224
+ const serialized = this.serializer.serialize(input);
225
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
226
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
227
+ const getUrl = new URL(url);
228
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
229
+ if (getUrl.toString().length <= maxUrlLength) {
230
+ return {
231
+ body: void 0,
232
+ method: expectedMethod,
233
+ headers,
234
+ url: getUrl,
235
+ signal: options.signal
236
+ };
237
+ }
238
+ }
239
+ return {
240
+ url,
241
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
242
+ headers,
243
+ body: serialized,
244
+ signal: options.signal
245
+ };
246
+ }
247
+ async decode(response) {
248
+ const isOk = !isORPCErrorStatus(response.status);
249
+ const deserialized = await (async () => {
250
+ let isBodyOk = false;
251
+ try {
252
+ const body = await response.body();
253
+ isBodyOk = true;
254
+ return this.serializer.deserialize(body);
255
+ } catch (error) {
256
+ if (!isBodyOk) {
257
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
258
+ cause: error
259
+ });
260
+ }
261
+ throw new Error("Invalid RPC response format.", {
262
+ cause: error
263
+ });
264
+ }
265
+ })();
266
+ if (!isOk) {
267
+ if (isORPCErrorJson(deserialized)) {
268
+ throw createORPCErrorFromJson(deserialized);
269
+ }
270
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
271
+ status: response.status,
272
+ data: { ...response, body: deserialized }
273
+ });
274
+ }
275
+ return deserialized;
276
+ }
277
+ }
278
+
279
+ class StandardRPCSerializer {
280
+ constructor(jsonSerializer) {
281
+ this.jsonSerializer = jsonSerializer;
282
+ }
283
+ serialize(data) {
284
+ if (isAsyncIteratorObject(data)) {
285
+ return mapEventIterator(data, {
286
+ value: async (value) => this.#serialize(value, false),
287
+ error: async (e) => {
288
+ return new ErrorEvent({
289
+ data: this.#serialize(toORPCError(e).toJSON(), false),
290
+ cause: e
291
+ });
292
+ }
293
+ });
294
+ }
295
+ return this.#serialize(data, true);
296
+ }
297
+ #serialize(data, enableFormData) {
298
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
299
+ const meta = meta_.length === 0 ? void 0 : meta_;
300
+ if (!enableFormData || blobs.length === 0) {
301
+ return {
302
+ json,
303
+ meta
304
+ };
305
+ }
306
+ const form = new FormData();
307
+ form.set("data", stringifyJSON({ json, meta, maps }));
308
+ blobs.forEach((blob, i) => {
309
+ form.set(i.toString(), blob);
310
+ });
311
+ return form;
312
+ }
313
+ deserialize(data) {
314
+ if (isAsyncIteratorObject(data)) {
315
+ return mapEventIterator(data, {
316
+ value: async (value) => this.#deserialize(value),
317
+ error: async (e) => {
318
+ if (!(e instanceof ErrorEvent)) {
319
+ return e;
320
+ }
321
+ const deserialized = this.#deserialize(e.data);
322
+ if (isORPCErrorJson(deserialized)) {
323
+ return createORPCErrorFromJson(deserialized, { cause: e });
324
+ }
325
+ return new ErrorEvent({
326
+ data: deserialized,
327
+ cause: e
328
+ });
329
+ }
330
+ });
331
+ }
332
+ return this.#deserialize(data);
333
+ }
334
+ #deserialize(data) {
335
+ if (!(data instanceof FormData)) {
336
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
337
+ }
338
+ const serialized = JSON.parse(data.get("data"));
339
+ return this.jsonSerializer.deserialize(
340
+ serialized.json,
341
+ serialized.meta ?? [],
342
+ serialized.maps,
343
+ (i) => data.get(i.toString())
344
+ );
345
+ }
346
+ }
347
+
348
+ export { CompositeStandardLinkPlugin as C, InvalidEventIteratorRetryResponse as I, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLinkCodec as c, StandardRPCSerializer as d, getMalformedResponseErrorCode as g, toHttpPath as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/client",
3
3
  "type": "module",
4
- "version": "0.0.0-next.c59d67c",
4
+ "version": "0.0.0-next.c72b962",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,33 +15,39 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
21
  },
22
- "./🔒/*": {
23
- "types": "./dist/src/*.d.ts"
22
+ "./plugins": {
23
+ "types": "./dist/plugins/index.d.mts",
24
+ "import": "./dist/plugins/index.mjs",
25
+ "default": "./dist/plugins/index.mjs"
26
+ },
27
+ "./standard": {
28
+ "types": "./dist/adapters/standard/index.d.mts",
29
+ "import": "./dist/adapters/standard/index.mjs",
30
+ "default": "./dist/adapters/standard/index.mjs"
31
+ },
32
+ "./fetch": {
33
+ "types": "./dist/adapters/fetch/index.d.mts",
34
+ "import": "./dist/adapters/fetch/index.mjs",
35
+ "default": "./dist/adapters/fetch/index.mjs"
24
36
  }
25
37
  },
26
38
  "files": [
27
- "!**/*.map",
28
- "!**/*.tsbuildinfo",
29
39
  "dist"
30
40
  ],
31
- "peerDependencies": {
32
- "@orpc/contract": "0.0.0-next.c59d67c",
33
- "@orpc/server": "0.0.0-next.c59d67c"
34
- },
35
41
  "dependencies": {
36
- "@orpc/shared": "0.0.0-next.c59d67c",
37
- "@orpc/transformer": "0.0.0-next.c59d67c"
42
+ "@orpc/shared": "0.0.0-next.c72b962",
43
+ "@orpc/standard-server-fetch": "0.0.0-next.c72b962",
44
+ "@orpc/standard-server": "0.0.0-next.c72b962"
38
45
  },
39
46
  "devDependencies": {
40
- "zod": "^3.23.8",
41
- "@orpc/openapi": "0.0.0-next.c59d67c"
47
+ "zod": "^3.24.2"
42
48
  },
43
49
  "scripts": {
44
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
50
+ "build": "unbuild",
45
51
  "build:watch": "pnpm run build --watch",
46
52
  "type:check": "tsc -b"
47
53
  }
package/dist/index.js DELETED
@@ -1,83 +0,0 @@
1
- // src/procedure.ts
2
- import {
3
- ORPC_HEADER,
4
- ORPC_HEADER_VALUE
5
- } from "@orpc/contract";
6
- import { trim } from "@orpc/shared";
7
- import { ORPCError } from "@orpc/shared/error";
8
- import { ORPCDeserializer, ORPCSerializer } from "@orpc/transformer";
9
- function createProcedureClient(options) {
10
- const serializer = new ORPCSerializer();
11
- const deserializer = new ORPCDeserializer();
12
- const client = async (input) => {
13
- const fetch_ = options.fetch ?? fetch;
14
- const url = `${trim(options.baseURL, "/")}/${options.path.map(encodeURIComponent).join("/")}`;
15
- let headers = await options.headers?.(input);
16
- headers = headers instanceof Headers ? headers : new Headers(headers);
17
- const { body, headers: headers_ } = serializer.serialize(input);
18
- for (const [key, value] of headers_.entries()) {
19
- headers.set(key, value);
20
- }
21
- headers.set(ORPC_HEADER, ORPC_HEADER_VALUE);
22
- const response = await fetch_(url, {
23
- method: "POST",
24
- headers,
25
- body
26
- });
27
- const json = await (async () => {
28
- try {
29
- return await deserializer.deserialize(response);
30
- } catch (e) {
31
- throw new ORPCError({
32
- code: "INTERNAL_SERVER_ERROR",
33
- message: "Cannot parse response.",
34
- cause: e
35
- });
36
- }
37
- })();
38
- if (!response.ok) {
39
- throw ORPCError.fromJSON(json) ?? new ORPCError({
40
- status: response.status,
41
- code: "INTERNAL_SERVER_ERROR",
42
- message: "Internal server error"
43
- });
44
- }
45
- return json;
46
- };
47
- return client;
48
- }
49
-
50
- // src/router.ts
51
- function createRouterClient(options) {
52
- const path = options?.path ?? [];
53
- const client = new Proxy(
54
- createProcedureClient({
55
- baseURL: options.baseURL,
56
- fetch: options.fetch,
57
- headers: options.headers,
58
- path
59
- }),
60
- {
61
- get(target, key) {
62
- if (typeof key !== "string") {
63
- return Reflect.get(target, key);
64
- }
65
- return createRouterClient({
66
- ...options,
67
- path: [...path, key]
68
- });
69
- }
70
- }
71
- );
72
- return client;
73
- }
74
-
75
- // src/index.ts
76
- export * from "@orpc/shared/error";
77
- var createORPCClient = createRouterClient;
78
- export {
79
- createORPCClient,
80
- createProcedureClient,
81
- createRouterClient
82
- };
83
- //# sourceMappingURL=index.js.map
@@ -1,7 +0,0 @@
1
- /** unnoq */
2
- import { createRouterClient } from './router';
3
- export * from './procedure';
4
- export * from './router';
5
- export * from '@orpc/shared/error';
6
- export declare const createORPCClient: typeof createRouterClient;
7
- //# sourceMappingURL=index.d.ts.map
@@ -1,27 +0,0 @@
1
- import type { Promisable } from '@orpc/shared';
2
- import { type Schema, type SchemaInput, type SchemaOutput } from '@orpc/contract';
3
- export interface ProcedureClient<TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaOutput<TOutputSchema>> {
4
- (input: SchemaInput<TInputSchema>): Promise<SchemaOutput<TOutputSchema, TFuncOutput>>;
5
- }
6
- export interface CreateProcedureClientOptions {
7
- /**
8
- * The base url of the server.
9
- */
10
- baseURL: string;
11
- /**
12
- * The fetch function used to make the request.
13
- * @default global fetch
14
- */
15
- fetch?: typeof fetch;
16
- /**
17
- * The headers used to make the request.
18
- * Invoked before the request is made.
19
- */
20
- headers?: (input: unknown) => Promisable<Headers | Record<string, string>>;
21
- /**
22
- * The path of the procedure on server.
23
- */
24
- path: string[];
25
- }
26
- export declare function createProcedureClient<TInputSchema extends Schema, TOutputSchema extends Schema, TFuncOutput extends SchemaOutput<TOutputSchema>>(options: CreateProcedureClientOptions): ProcedureClient<TInputSchema, TOutputSchema, TFuncOutput>;
27
- //# sourceMappingURL=procedure.d.ts.map
@@ -1,34 +0,0 @@
1
- import type { ContractProcedure, ContractRouter, SchemaOutput } from '@orpc/contract';
2
- import type { Procedure, Router } from '@orpc/server';
3
- import type { Promisable } from '@orpc/shared';
4
- import { type ProcedureClient } from './procedure';
5
- export type RouterClientWithContractRouter<TRouter extends ContractRouter> = {
6
- [K in keyof TRouter]: TRouter[K] extends ContractProcedure<infer UInputSchema, infer UOutputSchema> ? ProcedureClient<UInputSchema, UOutputSchema, SchemaOutput<UOutputSchema>> : TRouter[K] extends ContractRouter ? RouterClientWithContractRouter<TRouter[K]> : never;
7
- };
8
- export type RouterClientWithRouter<TRouter extends Router<any>> = {
9
- [K in keyof TRouter]: TRouter[K] extends Procedure<any, any, infer UInputSchema, infer UOutputSchema, infer UFuncOutput> ? ProcedureClient<UInputSchema, UOutputSchema, UFuncOutput> : TRouter[K] extends Router<any> ? RouterClientWithRouter<TRouter[K]> : never;
10
- };
11
- export interface CreateRouterClientOptions {
12
- /**
13
- * The base url of the server.
14
- */
15
- baseURL: string;
16
- /**
17
- * The fetch function used to make the request.
18
- * @default global fetch
19
- */
20
- fetch?: typeof fetch;
21
- /**
22
- * The headers used to make the request.
23
- * Invoked before the request is made.
24
- */
25
- headers?: (input: unknown) => Promisable<Headers | Record<string, string>>;
26
- /**
27
- * This used for internal purpose only.
28
- *
29
- * @internal
30
- */
31
- path?: string[];
32
- }
33
- export declare function createRouterClient<TRouter extends Router<any> | ContractRouter>(options: CreateRouterClientOptions): TRouter extends Router<any> ? RouterClientWithRouter<TRouter> : TRouter extends ContractRouter ? RouterClientWithContractRouter<TRouter> : never;
34
- //# sourceMappingURL=router.d.ts.map