@orpc/client 0.0.0-next.b0f324e → 0.0.0-next.b12bcdb

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,180 @@
1
+ import { resolveMaybeOptionalOptions, isObject, AsyncIteratorClass, isTypescriptObject } from '@orpc/shared';
2
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
3
+
4
+ const COMMON_ORPC_ERROR_DEFS = {
5
+ BAD_REQUEST: {
6
+ status: 400,
7
+ message: "Bad Request"
8
+ },
9
+ UNAUTHORIZED: {
10
+ status: 401,
11
+ message: "Unauthorized"
12
+ },
13
+ FORBIDDEN: {
14
+ status: 403,
15
+ message: "Forbidden"
16
+ },
17
+ NOT_FOUND: {
18
+ status: 404,
19
+ message: "Not Found"
20
+ },
21
+ METHOD_NOT_SUPPORTED: {
22
+ status: 405,
23
+ message: "Method Not Supported"
24
+ },
25
+ NOT_ACCEPTABLE: {
26
+ status: 406,
27
+ message: "Not Acceptable"
28
+ },
29
+ TIMEOUT: {
30
+ status: 408,
31
+ message: "Request Timeout"
32
+ },
33
+ CONFLICT: {
34
+ status: 409,
35
+ message: "Conflict"
36
+ },
37
+ PRECONDITION_FAILED: {
38
+ status: 412,
39
+ message: "Precondition Failed"
40
+ },
41
+ PAYLOAD_TOO_LARGE: {
42
+ status: 413,
43
+ message: "Payload Too Large"
44
+ },
45
+ UNSUPPORTED_MEDIA_TYPE: {
46
+ status: 415,
47
+ message: "Unsupported Media Type"
48
+ },
49
+ UNPROCESSABLE_CONTENT: {
50
+ status: 422,
51
+ message: "Unprocessable Content"
52
+ },
53
+ TOO_MANY_REQUESTS: {
54
+ status: 429,
55
+ message: "Too Many Requests"
56
+ },
57
+ CLIENT_CLOSED_REQUEST: {
58
+ status: 499,
59
+ message: "Client Closed Request"
60
+ },
61
+ INTERNAL_SERVER_ERROR: {
62
+ status: 500,
63
+ message: "Internal Server Error"
64
+ },
65
+ NOT_IMPLEMENTED: {
66
+ status: 501,
67
+ message: "Not Implemented"
68
+ },
69
+ BAD_GATEWAY: {
70
+ status: 502,
71
+ message: "Bad Gateway"
72
+ },
73
+ SERVICE_UNAVAILABLE: {
74
+ status: 503,
75
+ message: "Service Unavailable"
76
+ },
77
+ GATEWAY_TIMEOUT: {
78
+ status: 504,
79
+ message: "Gateway Timeout"
80
+ }
81
+ };
82
+ function fallbackORPCErrorStatus(code, status) {
83
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
84
+ }
85
+ function fallbackORPCErrorMessage(code, message) {
86
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
87
+ }
88
+ class ORPCError extends Error {
89
+ defined;
90
+ code;
91
+ status;
92
+ data;
93
+ constructor(code, ...rest) {
94
+ const options = resolveMaybeOptionalOptions(rest);
95
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {
96
+ throw new Error("[ORPCError] Invalid error status code.");
97
+ }
98
+ const message = fallbackORPCErrorMessage(code, options.message);
99
+ super(message, options);
100
+ this.code = code;
101
+ this.status = fallbackORPCErrorStatus(code, options.status);
102
+ this.defined = options.defined ?? false;
103
+ this.data = options.data;
104
+ }
105
+ toJSON() {
106
+ return {
107
+ defined: this.defined,
108
+ code: this.code,
109
+ status: this.status,
110
+ message: this.message,
111
+ data: this.data
112
+ };
113
+ }
114
+ }
115
+ function isDefinedError(error) {
116
+ return error instanceof ORPCError && error.defined;
117
+ }
118
+ function toORPCError(error) {
119
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
120
+ message: "Internal server error",
121
+ cause: error
122
+ });
123
+ }
124
+ function isORPCErrorStatus(status) {
125
+ return status < 200 || status >= 400;
126
+ }
127
+ function isORPCErrorJson(json) {
128
+ if (!isObject(json)) {
129
+ return false;
130
+ }
131
+ const validKeys = ["defined", "code", "status", "message", "data"];
132
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
133
+ return false;
134
+ }
135
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && isORPCErrorStatus(json.status) && "message" in json && typeof json.message === "string";
136
+ }
137
+ function createORPCErrorFromJson(json, options = {}) {
138
+ return new ORPCError(json.code, {
139
+ ...options,
140
+ ...json
141
+ });
142
+ }
143
+
144
+ function mapEventIterator(iterator, maps) {
145
+ const mapError = async (error) => {
146
+ let mappedError = await maps.error(error);
147
+ if (mappedError !== error) {
148
+ const meta = getEventMeta(error);
149
+ if (meta && isTypescriptObject(mappedError)) {
150
+ mappedError = withEventMeta(mappedError, meta);
151
+ }
152
+ }
153
+ return mappedError;
154
+ };
155
+ return new AsyncIteratorClass(async () => {
156
+ const { done, value } = await (async () => {
157
+ try {
158
+ return await iterator.next();
159
+ } catch (error) {
160
+ throw await mapError(error);
161
+ }
162
+ })();
163
+ let mappedValue = await maps.value(value, done);
164
+ if (mappedValue !== value) {
165
+ const meta = getEventMeta(value);
166
+ if (meta && isTypescriptObject(mappedValue)) {
167
+ mappedValue = withEventMeta(mappedValue, meta);
168
+ }
169
+ }
170
+ return { done, value: mappedValue };
171
+ }, async () => {
172
+ try {
173
+ await iterator.return?.();
174
+ } catch (error) {
175
+ throw await mapError(error);
176
+ }
177
+ });
178
+ }
179
+
180
+ export { COMMON_ORPC_ERROR_DEFS as C, ORPCError as O, fallbackORPCErrorMessage as a, isORPCErrorStatus as b, isORPCErrorJson as c, createORPCErrorFromJson as d, fallbackORPCErrorStatus as f, isDefinedError as i, mapEventIterator as m, toORPCError 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.b0f324e",
4
+ "version": "0.0.0-next.b12bcdb",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -19,6 +19,11 @@
19
19
  "import": "./dist/index.mjs",
20
20
  "default": "./dist/index.mjs"
21
21
  },
22
+ "./plugins": {
23
+ "types": "./dist/plugins/index.d.mts",
24
+ "import": "./dist/plugins/index.mjs",
25
+ "default": "./dist/plugins/index.mjs"
26
+ },
22
27
  "./standard": {
23
28
  "types": "./dist/adapters/standard/index.d.mts",
24
29
  "import": "./dist/adapters/standard/index.mjs",
@@ -28,18 +33,29 @@
28
33
  "types": "./dist/adapters/fetch/index.d.mts",
29
34
  "import": "./dist/adapters/fetch/index.mjs",
30
35
  "default": "./dist/adapters/fetch/index.mjs"
36
+ },
37
+ "./websocket": {
38
+ "types": "./dist/adapters/websocket/index.d.mts",
39
+ "import": "./dist/adapters/websocket/index.mjs",
40
+ "default": "./dist/adapters/websocket/index.mjs"
41
+ },
42
+ "./message-port": {
43
+ "types": "./dist/adapters/message-port/index.d.mts",
44
+ "import": "./dist/adapters/message-port/index.mjs",
45
+ "default": "./dist/adapters/message-port/index.mjs"
31
46
  }
32
47
  },
33
48
  "files": [
34
49
  "dist"
35
50
  ],
36
51
  "dependencies": {
37
- "@orpc/shared": "0.0.0-next.b0f324e",
38
- "@orpc/standard-server-fetch": "0.0.0-next.b0f324e",
39
- "@orpc/standard-server": "0.0.0-next.b0f324e"
52
+ "@orpc/shared": "0.0.0-next.b12bcdb",
53
+ "@orpc/standard-server-peer": "0.0.0-next.b12bcdb",
54
+ "@orpc/standard-server": "0.0.0-next.b12bcdb",
55
+ "@orpc/standard-server-fetch": "0.0.0-next.b12bcdb"
40
56
  },
41
57
  "devDependencies": {
42
- "zod": "^3.24.1"
58
+ "zod": "^4.1.5"
43
59
  },
44
60
  "scripts": {
45
61
  "build": "unbuild",
@@ -1,192 +0,0 @@
1
- import { isObject, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared';
2
- import { ErrorEvent } from '@orpc/standard-server';
3
- import { m as mapEventIterator, t as toORPCError, O as ORPCError } from './client.Ly4zGQrc.mjs';
4
-
5
- class RPCJsonSerializer {
6
- serialize(data, segments = [], meta = [], maps = [], blobs = []) {
7
- if (data instanceof Blob) {
8
- maps.push(segments);
9
- blobs.push(data);
10
- return [data, meta, maps, blobs];
11
- }
12
- if (typeof data === "bigint") {
13
- meta.push([0, segments]);
14
- return [data.toString(), meta, maps, blobs];
15
- }
16
- if (data instanceof Date) {
17
- meta.push([1, segments]);
18
- if (Number.isNaN(data.getTime())) {
19
- return [null, meta, maps, blobs];
20
- }
21
- return [data.toISOString(), meta, maps, blobs];
22
- }
23
- if (Number.isNaN(data)) {
24
- meta.push([2, segments]);
25
- return [null, meta, maps, blobs];
26
- }
27
- if (data instanceof URL) {
28
- meta.push([4, segments]);
29
- return [data.toString(), meta, maps, blobs];
30
- }
31
- if (data instanceof RegExp) {
32
- meta.push([5, segments]);
33
- return [data.toString(), meta, maps, blobs];
34
- }
35
- if (data instanceof Set) {
36
- const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
37
- meta.push([6, segments]);
38
- return result;
39
- }
40
- if (data instanceof Map) {
41
- const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
42
- meta.push([7, segments]);
43
- return result;
44
- }
45
- if (Array.isArray(data)) {
46
- const json = data.map((v, i) => {
47
- if (v === void 0) {
48
- meta.push([3, [...segments, i]]);
49
- return v;
50
- }
51
- return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
52
- });
53
- return [json, meta, maps, blobs];
54
- }
55
- if (isObject(data)) {
56
- const json = {};
57
- for (const k in data) {
58
- json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
59
- }
60
- return [json, meta, maps, blobs];
61
- }
62
- return [data, meta, maps, blobs];
63
- }
64
- deserialize(json, meta, maps, getBlob) {
65
- const ref = { data: json };
66
- if (maps && getBlob) {
67
- maps.forEach((segments, i) => {
68
- let currentRef = ref;
69
- let preSegment = "data";
70
- segments.forEach((segment) => {
71
- currentRef = currentRef[preSegment];
72
- preSegment = segment;
73
- });
74
- currentRef[preSegment] = getBlob(i);
75
- });
76
- }
77
- for (const [type, segments] of meta) {
78
- let currentRef = ref;
79
- let preSegment = "data";
80
- segments.forEach((segment) => {
81
- currentRef = currentRef[preSegment];
82
- preSegment = segment;
83
- });
84
- switch (type) {
85
- case 0:
86
- currentRef[preSegment] = BigInt(currentRef[preSegment]);
87
- break;
88
- case 1:
89
- currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
90
- break;
91
- case 2:
92
- currentRef[preSegment] = Number.NaN;
93
- break;
94
- case 3:
95
- currentRef[preSegment] = void 0;
96
- break;
97
- case 4:
98
- currentRef[preSegment] = new URL(currentRef[preSegment]);
99
- break;
100
- case 5: {
101
- const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
102
- currentRef[preSegment] = new RegExp(pattern, flags);
103
- break;
104
- }
105
- case 6:
106
- currentRef[preSegment] = new Set(currentRef[preSegment]);
107
- break;
108
- case 7:
109
- currentRef[preSegment] = new Map(currentRef[preSegment]);
110
- break;
111
- }
112
- }
113
- return ref.data;
114
- }
115
- }
116
-
117
- class RPCSerializer {
118
- constructor(jsonSerializer = new RPCJsonSerializer()) {
119
- this.jsonSerializer = jsonSerializer;
120
- }
121
- serialize(data) {
122
- if (isAsyncIteratorObject(data)) {
123
- return mapEventIterator(data, {
124
- value: async (value) => this.#serialize(value, false),
125
- error: async (e) => {
126
- return new ErrorEvent({
127
- data: this.#serialize(toORPCError(e).toJSON(), false),
128
- cause: e
129
- });
130
- }
131
- });
132
- }
133
- return this.#serialize(data, true);
134
- }
135
- #serialize(data, enableFormData) {
136
- if (data === void 0 || data instanceof Blob) {
137
- return data;
138
- }
139
- const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
140
- const meta = meta_.length === 0 ? void 0 : meta_;
141
- if (!enableFormData || blobs.length === 0) {
142
- return {
143
- json,
144
- meta
145
- };
146
- }
147
- const form = new FormData();
148
- form.set("data", stringifyJSON({ json, meta, maps }));
149
- blobs.forEach((blob, i) => {
150
- form.set(i.toString(), blob);
151
- });
152
- return form;
153
- }
154
- deserialize(data) {
155
- if (isAsyncIteratorObject(data)) {
156
- return mapEventIterator(data, {
157
- value: async (value) => this.#deserialize(value),
158
- error: async (e) => {
159
- if (!(e instanceof ErrorEvent)) {
160
- return e;
161
- }
162
- const deserialized = this.#deserialize(e.data);
163
- if (ORPCError.isValidJSON(deserialized)) {
164
- return ORPCError.fromJSON(deserialized, { cause: e });
165
- }
166
- return new ErrorEvent({
167
- data: deserialized,
168
- cause: e
169
- });
170
- }
171
- });
172
- }
173
- return this.#deserialize(data);
174
- }
175
- #deserialize(data) {
176
- if (data === void 0 || data instanceof Blob) {
177
- return data;
178
- }
179
- if (!(data instanceof FormData)) {
180
- return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
181
- }
182
- const serialized = JSON.parse(data.get("data"));
183
- return this.jsonSerializer.deserialize(
184
- serialized.json,
185
- serialized.meta ?? [],
186
- serialized.maps,
187
- (i) => data.get(i.toString())
188
- );
189
- }
190
- }
191
-
192
- export { RPCJsonSerializer as R, RPCSerializer as a };
@@ -1,42 +0,0 @@
1
- type ClientContext = Record<string, any>;
2
- type ClientOptions<TClientContext extends ClientContext> = {
3
- signal?: AbortSignal;
4
- lastEventId?: string | undefined;
5
- } & (Record<never, never> extends TClientContext ? {
6
- context?: TClientContext;
7
- } : {
8
- context: TClientContext;
9
- });
10
- type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options: ClientOptions<TClientContext>];
11
- type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
12
- __error?: {
13
- type: TError;
14
- };
15
- };
16
- interface Client<TClientContext extends ClientContext, TInput, TOutput, TError extends Error> {
17
- (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
18
- }
19
- type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
- [k: string]: NestedClient<TClientContext>;
21
- };
22
- type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
23
- type ClientOptionsOut<TClientContext extends ClientContext> = ClientOptions<TClientContext> & {
24
- context: TClientContext;
25
- };
26
- interface ClientLink<TClientContext extends ClientContext> {
27
- call: (path: readonly string[], input: unknown, options: ClientOptionsOut<TClientContext>) => Promise<unknown>;
28
- }
29
-
30
- declare function mapEventIterator<TYield, TReturn, TNext, TMap = TYield | TReturn>(iterator: AsyncIterator<TYield, TReturn, TNext>, maps: {
31
- value: (value: NoInfer<TYield | TReturn>, done: boolean | undefined) => Promise<TMap>;
32
- error: (error: unknown) => Promise<unknown>;
33
- }): AsyncGenerator<TMap, TMap, TNext>;
34
- interface EventIteratorReconnectOptions {
35
- lastRetry: number | undefined;
36
- lastEventId: string | undefined;
37
- retryTimes: number;
38
- error: unknown;
39
- }
40
- declare function createAutoRetryEventIterator<TYield, TReturn>(initial: AsyncIterator<TYield, TReturn, void>, reconnect: (options: EventIteratorReconnectOptions) => Promise<AsyncIterator<TYield, TReturn, void> | null>, initialLastEventId: string | undefined): AsyncGenerator<TYield, TReturn, void>;
41
-
42
- export { type ClientContext as C, type EventIteratorReconnectOptions as E, type InferClientContext as I, type NestedClient as N, type ClientOptionsOut as a, type ClientLink as b, type ClientPromiseResult as c, createAutoRetryEventIterator as d, type ClientOptions as e, type ClientRest as f, type Client as g, mapEventIterator as m };
@@ -1,42 +0,0 @@
1
- type ClientContext = Record<string, any>;
2
- type ClientOptions<TClientContext extends ClientContext> = {
3
- signal?: AbortSignal;
4
- lastEventId?: string | undefined;
5
- } & (Record<never, never> extends TClientContext ? {
6
- context?: TClientContext;
7
- } : {
8
- context: TClientContext;
9
- });
10
- type ClientRest<TClientContext extends ClientContext, TInput> = Record<never, never> extends TClientContext ? undefined extends TInput ? [input?: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options?: ClientOptions<TClientContext>] : [input: TInput, options: ClientOptions<TClientContext>];
11
- type ClientPromiseResult<TOutput, TError extends Error> = Promise<TOutput> & {
12
- __error?: {
13
- type: TError;
14
- };
15
- };
16
- interface Client<TClientContext extends ClientContext, TInput, TOutput, TError extends Error> {
17
- (...rest: ClientRest<TClientContext, TInput>): ClientPromiseResult<TOutput, TError>;
18
- }
19
- type NestedClient<TClientContext extends ClientContext> = Client<TClientContext, any, any, any> | {
20
- [k: string]: NestedClient<TClientContext>;
21
- };
22
- type InferClientContext<T extends NestedClient<any>> = T extends NestedClient<infer U> ? U : never;
23
- type ClientOptionsOut<TClientContext extends ClientContext> = ClientOptions<TClientContext> & {
24
- context: TClientContext;
25
- };
26
- interface ClientLink<TClientContext extends ClientContext> {
27
- call: (path: readonly string[], input: unknown, options: ClientOptionsOut<TClientContext>) => Promise<unknown>;
28
- }
29
-
30
- declare function mapEventIterator<TYield, TReturn, TNext, TMap = TYield | TReturn>(iterator: AsyncIterator<TYield, TReturn, TNext>, maps: {
31
- value: (value: NoInfer<TYield | TReturn>, done: boolean | undefined) => Promise<TMap>;
32
- error: (error: unknown) => Promise<unknown>;
33
- }): AsyncGenerator<TMap, TMap, TNext>;
34
- interface EventIteratorReconnectOptions {
35
- lastRetry: number | undefined;
36
- lastEventId: string | undefined;
37
- retryTimes: number;
38
- error: unknown;
39
- }
40
- declare function createAutoRetryEventIterator<TYield, TReturn>(initial: AsyncIterator<TYield, TReturn, void>, reconnect: (options: EventIteratorReconnectOptions) => Promise<AsyncIterator<TYield, TReturn, void> | null>, initialLastEventId: string | undefined): AsyncGenerator<TYield, TReturn, void>;
41
-
42
- export { type ClientContext as C, type EventIteratorReconnectOptions as E, type InferClientContext as I, type NestedClient as N, type ClientOptionsOut as a, type ClientLink as b, type ClientPromiseResult as c, createAutoRetryEventIterator as d, type ClientOptions as e, type ClientRest as f, type Client as g, mapEventIterator as m };