@orpc/client 0.0.0-next.db1f26d → 0.0.0-next.df024bb

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,265 @@
1
+ import { isObject, isTypescriptObject, retry } 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, ...[options]) {
94
+ if (options?.status && (options.status < 400 || options.status >= 600)) {
95
+ throw new Error("[ORPCError] The error status code must be in the 400-599 range.");
96
+ }
97
+ const message = fallbackORPCErrorMessage(code, options?.message);
98
+ super(message, options);
99
+ this.code = code;
100
+ this.status = fallbackORPCErrorStatus(code, options?.status);
101
+ this.defined = options?.defined ?? false;
102
+ this.data = options?.data;
103
+ }
104
+ toJSON() {
105
+ return {
106
+ defined: this.defined,
107
+ code: this.code,
108
+ status: this.status,
109
+ message: this.message,
110
+ data: this.data
111
+ };
112
+ }
113
+ static fromJSON(json, options) {
114
+ return new ORPCError(json.code, {
115
+ ...options,
116
+ ...json
117
+ });
118
+ }
119
+ static isValidJSON(json) {
120
+ if (!isObject(json)) {
121
+ return false;
122
+ }
123
+ const validKeys = ["defined", "code", "status", "message", "data"];
124
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
125
+ return false;
126
+ }
127
+ return "defined" in json && typeof json.defined === "boolean" && "code" in json && typeof json.code === "string" && "status" in json && typeof json.status === "number" && "message" in json && typeof json.message === "string";
128
+ }
129
+ }
130
+ function isDefinedError(error) {
131
+ return error instanceof ORPCError && error.defined;
132
+ }
133
+ function toORPCError(error) {
134
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
135
+ message: "Internal server error",
136
+ cause: error
137
+ });
138
+ }
139
+
140
+ const iteratorStates = /* @__PURE__ */ new WeakMap();
141
+ function registerEventIteratorState(iterator, state) {
142
+ iteratorStates.set(iterator, state);
143
+ }
144
+ function updateEventIteratorStatus(state, status) {
145
+ if (state.status !== status) {
146
+ state.status = status;
147
+ state.listeners.forEach((cb) => cb(status));
148
+ }
149
+ }
150
+ function onEventIteratorStatusChange(iterator, callback, notifyImmediately = true) {
151
+ const state = iteratorStates.get(iterator);
152
+ if (!state) {
153
+ throw new Error("Iterator is not registered.");
154
+ }
155
+ if (notifyImmediately) {
156
+ callback(state.status);
157
+ }
158
+ state.listeners.push(callback);
159
+ return () => {
160
+ const index = state.listeners.indexOf(callback);
161
+ if (index !== -1) {
162
+ state.listeners.splice(index, 1);
163
+ }
164
+ };
165
+ }
166
+
167
+ function mapEventIterator(iterator, maps) {
168
+ return async function* () {
169
+ try {
170
+ while (true) {
171
+ const { done, value } = await iterator.next();
172
+ let mappedValue = await maps.value(value, done);
173
+ if (mappedValue !== value) {
174
+ const meta = getEventMeta(value);
175
+ if (meta && isTypescriptObject(mappedValue)) {
176
+ mappedValue = withEventMeta(mappedValue, meta);
177
+ }
178
+ }
179
+ if (done) {
180
+ return mappedValue;
181
+ }
182
+ yield mappedValue;
183
+ }
184
+ } catch (error) {
185
+ let mappedError = await maps.error(error);
186
+ if (mappedError !== error) {
187
+ const meta = getEventMeta(error);
188
+ if (meta && isTypescriptObject(mappedError)) {
189
+ mappedError = withEventMeta(mappedError, meta);
190
+ }
191
+ }
192
+ throw mappedError;
193
+ } finally {
194
+ await iterator.return?.();
195
+ }
196
+ }();
197
+ }
198
+ const MAX_ALLOWED_RETRY_TIMES = 99;
199
+ function createAutoRetryEventIterator(initial, reconnect, initialLastEventId) {
200
+ const state = {
201
+ status: "connected",
202
+ listeners: []
203
+ };
204
+ const iterator = async function* () {
205
+ let current = initial;
206
+ let lastEventId = initialLastEventId;
207
+ let lastRetry;
208
+ let retryTimes = 0;
209
+ try {
210
+ while (true) {
211
+ try {
212
+ updateEventIteratorStatus(state, "connected");
213
+ const { done, value } = await current.next();
214
+ const meta = getEventMeta(value);
215
+ lastEventId = meta?.id ?? lastEventId;
216
+ lastRetry = meta?.retry ?? lastRetry;
217
+ retryTimes = 0;
218
+ if (done) {
219
+ return value;
220
+ }
221
+ yield value;
222
+ } catch (e) {
223
+ updateEventIteratorStatus(state, "reconnecting");
224
+ const meta = getEventMeta(e);
225
+ lastEventId = meta?.id ?? lastEventId;
226
+ lastRetry = meta?.retry ?? lastRetry;
227
+ let currentError = e;
228
+ current = await retry({ times: MAX_ALLOWED_RETRY_TIMES }, async (exit) => {
229
+ retryTimes += 1;
230
+ if (retryTimes > MAX_ALLOWED_RETRY_TIMES) {
231
+ throw exit(new Error(
232
+ `Exceeded maximum retry attempts (${MAX_ALLOWED_RETRY_TIMES}) for event iterator. Possible infinite retry loop detected. Please review the retry logic.`,
233
+ { cause: currentError }
234
+ ));
235
+ }
236
+ const reconnected = await (async () => {
237
+ try {
238
+ return await reconnect({
239
+ lastRetry,
240
+ lastEventId,
241
+ retryTimes,
242
+ error: currentError
243
+ });
244
+ } catch (e2) {
245
+ currentError = e2;
246
+ throw e2;
247
+ }
248
+ })();
249
+ if (!reconnected) {
250
+ throw exit(currentError);
251
+ }
252
+ return reconnected;
253
+ });
254
+ }
255
+ }
256
+ } finally {
257
+ updateEventIteratorStatus(state, "closed");
258
+ await current.return?.();
259
+ }
260
+ }();
261
+ registerEventIteratorState(iterator, state);
262
+ return iterator;
263
+ }
264
+
265
+ export { COMMON_ORPC_ERROR_DEFS as C, ORPCError as O, fallbackORPCErrorMessage as a, createAutoRetryEventIterator as c, fallbackORPCErrorStatus as f, isDefinedError as i, mapEventIterator as m, onEventIteratorStatusChange as o, registerEventIteratorState as r, toORPCError as t, updateEventIteratorStatus as u };
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.db1f26d",
4
+ "version": "0.0.0-next.df024bb",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,33 +15,34 @@
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
+ "./standard": {
23
+ "types": "./dist/adapters/standard/index.d.mts",
24
+ "import": "./dist/adapters/standard/index.mjs",
25
+ "default": "./dist/adapters/standard/index.mjs"
26
+ },
27
+ "./fetch": {
28
+ "types": "./dist/adapters/fetch/index.d.mts",
29
+ "import": "./dist/adapters/fetch/index.mjs",
30
+ "default": "./dist/adapters/fetch/index.mjs"
24
31
  }
25
32
  },
26
33
  "files": [
27
- "!**/*.map",
28
- "!**/*.tsbuildinfo",
29
34
  "dist"
30
35
  ],
31
- "peerDependencies": {
32
- "@orpc/contract": "0.0.0-next.db1f26d",
33
- "@orpc/server": "0.0.0-next.db1f26d"
34
- },
35
36
  "dependencies": {
36
- "@orpc/shared": "0.0.0-next.db1f26d",
37
- "@orpc/transformer": "0.0.0-next.db1f26d"
37
+ "@orpc/shared": "0.0.0-next.df024bb",
38
+ "@orpc/standard-server": "0.0.0-next.df024bb",
39
+ "@orpc/standard-server-fetch": "0.0.0-next.df024bb"
38
40
  },
39
41
  "devDependencies": {
40
- "zod": "^3.23.8",
41
- "@orpc/openapi": "0.0.0-next.db1f26d"
42
+ "zod": "^3.24.1"
42
43
  },
43
44
  "scripts": {
44
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
45
+ "build": "unbuild",
45
46
  "build:watch": "pnpm run build --watch",
46
47
  "type:check": "tsc -b"
47
48
  }
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 { Lazy, 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> | Lazy<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