@orpc/client 0.0.0-next.e7b4f63 → 0.0.0-next.e7bc0b8

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.
Files changed (37) hide show
  1. package/README.md +98 -0
  2. package/dist/adapters/fetch/index.d.mts +46 -0
  3. package/dist/adapters/fetch/index.d.ts +46 -0
  4. package/dist/adapters/fetch/index.mjs +45 -0
  5. package/dist/adapters/message-port/index.d.mts +59 -0
  6. package/dist/adapters/message-port/index.d.ts +59 -0
  7. package/dist/adapters/message-port/index.mjs +72 -0
  8. package/dist/adapters/standard/index.d.mts +11 -0
  9. package/dist/adapters/standard/index.d.ts +11 -0
  10. package/dist/adapters/standard/index.mjs +5 -0
  11. package/dist/adapters/websocket/index.d.mts +29 -0
  12. package/dist/adapters/websocket/index.d.ts +29 -0
  13. package/dist/adapters/websocket/index.mjs +46 -0
  14. package/dist/index.d.mts +230 -0
  15. package/dist/index.d.ts +230 -0
  16. package/dist/index.mjs +111 -0
  17. package/dist/plugins/index.d.mts +203 -0
  18. package/dist/plugins/index.d.ts +203 -0
  19. package/dist/plugins/index.mjs +407 -0
  20. package/dist/shared/client.BG98rYdO.d.ts +45 -0
  21. package/dist/shared/client.BOYsZIRq.d.mts +29 -0
  22. package/dist/shared/client.BOYsZIRq.d.ts +29 -0
  23. package/dist/shared/client.Bwgm6dgk.d.mts +45 -0
  24. package/dist/shared/client.CVVVqf1Y.d.ts +91 -0
  25. package/dist/shared/client.CccQ0WhR.mjs +397 -0
  26. package/dist/shared/client.DoRXk1jY.mjs +208 -0
  27. package/dist/shared/client._Y_enhib.d.mts +91 -0
  28. package/package.json +32 -19
  29. package/dist/fetch.js +0 -87
  30. package/dist/index.js +0 -39
  31. package/dist/src/adapters/fetch/index.d.ts +0 -3
  32. package/dist/src/adapters/fetch/orpc-link.d.ts +0 -47
  33. package/dist/src/adapters/fetch/types.d.ts +0 -4
  34. package/dist/src/client.d.ts +0 -11
  35. package/dist/src/dynamic-link.d.ts +0 -13
  36. package/dist/src/index.d.ts +0 -6
  37. package/dist/src/types.d.ts +0 -5
@@ -0,0 +1,397 @@
1
+ import { toArray, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, intercept, getGlobalOtelConfig, isObject, value, stringifyJSON } from '@orpc/shared';
2
+ import { mergeStandardHeaders, ErrorEvent } from '@orpc/standard-server';
3
+ import { C as COMMON_ORPC_ERROR_DEFS, d as isORPCErrorStatus, e as isORPCErrorJson, g as createORPCErrorFromJson, c as ORPCError, m as mapEventIterator, t as toORPCError } from './client.DoRXk1jY.mjs';
4
+ import { toStandardHeaders as toStandardHeaders$1 } from '@orpc/standard-server-fetch';
5
+
6
+ class CompositeStandardLinkPlugin {
7
+ plugins;
8
+ constructor(plugins = []) {
9
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
10
+ }
11
+ init(options) {
12
+ for (const plugin of this.plugins) {
13
+ plugin.init?.(options);
14
+ }
15
+ }
16
+ }
17
+
18
+ class StandardLink {
19
+ constructor(codec, sender, options = {}) {
20
+ this.codec = codec;
21
+ this.sender = sender;
22
+ const plugin = new CompositeStandardLinkPlugin(options.plugins);
23
+ plugin.init(options);
24
+ this.interceptors = toArray(options.interceptors);
25
+ this.clientInterceptors = toArray(options.clientInterceptors);
26
+ }
27
+ interceptors;
28
+ clientInterceptors;
29
+ call(path, input, options) {
30
+ return runWithSpan(
31
+ { name: `${ORPC_NAME}.${path.join("/")}`, signal: options.signal },
32
+ (span) => {
33
+ span?.setAttribute("rpc.system", ORPC_NAME);
34
+ span?.setAttribute("rpc.method", path.join("."));
35
+ if (isAsyncIteratorObject(input)) {
36
+ input = asyncIteratorWithSpan(
37
+ { name: "consume_event_iterator_input", signal: options.signal },
38
+ input
39
+ );
40
+ }
41
+ return intercept(this.interceptors, { ...options, path, input }, async ({ path: path2, input: input2, ...options2 }) => {
42
+ const otelConfig = getGlobalOtelConfig();
43
+ let otelContext;
44
+ const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
45
+ if (currentSpan && otelConfig) {
46
+ otelContext = otelConfig?.trace.setSpan(otelConfig.context.active(), currentSpan);
47
+ }
48
+ const request = await runWithSpan(
49
+ { name: "encode_request", context: otelContext },
50
+ () => this.codec.encode(path2, input2, options2)
51
+ );
52
+ const response = await intercept(
53
+ this.clientInterceptors,
54
+ { ...options2, input: input2, path: path2, request },
55
+ ({ input: input3, path: path3, request: request2, ...options3 }) => {
56
+ return runWithSpan(
57
+ { name: "send_request", signal: options3.signal, context: otelContext },
58
+ () => this.sender.call(request2, options3, path3, input3)
59
+ );
60
+ }
61
+ );
62
+ const output = await runWithSpan(
63
+ { name: "decode_response", context: otelContext },
64
+ () => this.codec.decode(response, options2, path2, input2)
65
+ );
66
+ if (isAsyncIteratorObject(output)) {
67
+ return asyncIteratorWithSpan(
68
+ { name: "consume_event_iterator_output", signal: options2.signal },
69
+ output
70
+ );
71
+ }
72
+ return output;
73
+ });
74
+ }
75
+ );
76
+ }
77
+ }
78
+
79
+ const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES = {
80
+ BIGINT: 0,
81
+ DATE: 1,
82
+ NAN: 2,
83
+ UNDEFINED: 3,
84
+ URL: 4,
85
+ REGEXP: 5,
86
+ SET: 6,
87
+ MAP: 7
88
+ };
89
+ class StandardRPCJsonSerializer {
90
+ customSerializers;
91
+ constructor(options = {}) {
92
+ this.customSerializers = options.customJsonSerializers ?? [];
93
+ if (this.customSerializers.length !== new Set(this.customSerializers.map((custom) => custom.type)).size) {
94
+ throw new Error("Custom serializer type must be unique.");
95
+ }
96
+ }
97
+ serialize(data, segments = [], meta = [], maps = [], blobs = []) {
98
+ for (const custom of this.customSerializers) {
99
+ if (custom.condition(data)) {
100
+ const result = this.serialize(custom.serialize(data), segments, meta, maps, blobs);
101
+ meta.push([custom.type, ...segments]);
102
+ return result;
103
+ }
104
+ }
105
+ if (data instanceof Blob) {
106
+ maps.push(segments);
107
+ blobs.push(data);
108
+ return [data, meta, maps, blobs];
109
+ }
110
+ if (typeof data === "bigint") {
111
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT, ...segments]);
112
+ return [data.toString(), meta, maps, blobs];
113
+ }
114
+ if (data instanceof Date) {
115
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE, ...segments]);
116
+ if (Number.isNaN(data.getTime())) {
117
+ return [null, meta, maps, blobs];
118
+ }
119
+ return [data.toISOString(), meta, maps, blobs];
120
+ }
121
+ if (Number.isNaN(data)) {
122
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN, ...segments]);
123
+ return [null, meta, maps, blobs];
124
+ }
125
+ if (data instanceof URL) {
126
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL, ...segments]);
127
+ return [data.toString(), meta, maps, blobs];
128
+ }
129
+ if (data instanceof RegExp) {
130
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP, ...segments]);
131
+ return [data.toString(), meta, maps, blobs];
132
+ }
133
+ if (data instanceof Set) {
134
+ const result = this.serialize(Array.from(data), segments, meta, maps, blobs);
135
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET, ...segments]);
136
+ return result;
137
+ }
138
+ if (data instanceof Map) {
139
+ const result = this.serialize(Array.from(data.entries()), segments, meta, maps, blobs);
140
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP, ...segments]);
141
+ return result;
142
+ }
143
+ if (Array.isArray(data)) {
144
+ const json = data.map((v, i) => {
145
+ if (v === void 0) {
146
+ meta.push([STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED, ...segments, i]);
147
+ return v;
148
+ }
149
+ return this.serialize(v, [...segments, i], meta, maps, blobs)[0];
150
+ });
151
+ return [json, meta, maps, blobs];
152
+ }
153
+ if (isObject(data)) {
154
+ const json = {};
155
+ for (const k in data) {
156
+ if (k === "toJSON" && typeof data[k] === "function") {
157
+ continue;
158
+ }
159
+ json[k] = this.serialize(data[k], [...segments, k], meta, maps, blobs)[0];
160
+ }
161
+ return [json, meta, maps, blobs];
162
+ }
163
+ return [data, meta, maps, blobs];
164
+ }
165
+ deserialize(json, meta, maps, getBlob) {
166
+ const ref = { data: json };
167
+ if (maps && getBlob) {
168
+ maps.forEach((segments, i) => {
169
+ let currentRef = ref;
170
+ let preSegment = "data";
171
+ segments.forEach((segment) => {
172
+ currentRef = currentRef[preSegment];
173
+ preSegment = segment;
174
+ });
175
+ currentRef[preSegment] = getBlob(i);
176
+ });
177
+ }
178
+ for (const item of meta) {
179
+ const type = item[0];
180
+ let currentRef = ref;
181
+ let preSegment = "data";
182
+ for (let i = 1; i < item.length; i++) {
183
+ currentRef = currentRef[preSegment];
184
+ preSegment = item[i];
185
+ }
186
+ for (const custom of this.customSerializers) {
187
+ if (custom.type === type) {
188
+ currentRef[preSegment] = custom.deserialize(currentRef[preSegment]);
189
+ break;
190
+ }
191
+ }
192
+ switch (type) {
193
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.BIGINT:
194
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
195
+ break;
196
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.DATE:
197
+ currentRef[preSegment] = new Date(currentRef[preSegment] ?? "Invalid Date");
198
+ break;
199
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.NAN:
200
+ currentRef[preSegment] = Number.NaN;
201
+ break;
202
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.UNDEFINED:
203
+ currentRef[preSegment] = void 0;
204
+ break;
205
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.URL:
206
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
207
+ break;
208
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.REGEXP: {
209
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
210
+ currentRef[preSegment] = new RegExp(pattern, flags);
211
+ break;
212
+ }
213
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.SET:
214
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
215
+ break;
216
+ case STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES.MAP:
217
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
218
+ break;
219
+ }
220
+ }
221
+ return ref.data;
222
+ }
223
+ }
224
+
225
+ function toHttpPath(path) {
226
+ return `/${path.map(encodeURIComponent).join("/")}`;
227
+ }
228
+ function toStandardHeaders(headers) {
229
+ if (typeof headers.forEach === "function") {
230
+ return toStandardHeaders$1(headers);
231
+ }
232
+ return headers;
233
+ }
234
+ function getMalformedResponseErrorCode(status) {
235
+ return Object.entries(COMMON_ORPC_ERROR_DEFS).find(([, def]) => def.status === status)?.[0] ?? "MALFORMED_ORPC_ERROR_RESPONSE";
236
+ }
237
+
238
+ class StandardRPCLinkCodec {
239
+ constructor(serializer, options) {
240
+ this.serializer = serializer;
241
+ this.baseUrl = options.url;
242
+ this.maxUrlLength = options.maxUrlLength ?? 2083;
243
+ this.fallbackMethod = options.fallbackMethod ?? "POST";
244
+ this.expectedMethod = options.method ?? this.fallbackMethod;
245
+ this.headers = options.headers ?? {};
246
+ }
247
+ baseUrl;
248
+ maxUrlLength;
249
+ fallbackMethod;
250
+ expectedMethod;
251
+ headers;
252
+ async encode(path, input, options) {
253
+ let headers = toStandardHeaders(await value(this.headers, options, path, input));
254
+ if (options.lastEventId !== void 0) {
255
+ headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
256
+ }
257
+ const expectedMethod = await value(this.expectedMethod, options, path, input);
258
+ const baseUrl = await value(this.baseUrl, options, path, input);
259
+ const url = new URL(baseUrl);
260
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${toHttpPath(path)}`;
261
+ const serialized = this.serializer.serialize(input);
262
+ if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
263
+ const maxUrlLength = await value(this.maxUrlLength, options, path, input);
264
+ const getUrl = new URL(url);
265
+ getUrl.searchParams.append("data", stringifyJSON(serialized));
266
+ if (getUrl.toString().length <= maxUrlLength) {
267
+ return {
268
+ body: void 0,
269
+ method: expectedMethod,
270
+ headers,
271
+ url: getUrl,
272
+ signal: options.signal
273
+ };
274
+ }
275
+ }
276
+ return {
277
+ url,
278
+ method: expectedMethod === "GET" ? this.fallbackMethod : expectedMethod,
279
+ headers,
280
+ body: serialized,
281
+ signal: options.signal
282
+ };
283
+ }
284
+ async decode(response) {
285
+ const isOk = !isORPCErrorStatus(response.status);
286
+ const deserialized = await (async () => {
287
+ let isBodyOk = false;
288
+ try {
289
+ const body = await response.body();
290
+ isBodyOk = true;
291
+ return this.serializer.deserialize(body);
292
+ } catch (error) {
293
+ if (!isBodyOk) {
294
+ throw new Error("Cannot parse response body, please check the response body and content-type.", {
295
+ cause: error
296
+ });
297
+ }
298
+ throw new Error("Invalid RPC response format.", {
299
+ cause: error
300
+ });
301
+ }
302
+ })();
303
+ if (!isOk) {
304
+ if (isORPCErrorJson(deserialized)) {
305
+ throw createORPCErrorFromJson(deserialized);
306
+ }
307
+ throw new ORPCError(getMalformedResponseErrorCode(response.status), {
308
+ status: response.status,
309
+ data: { ...response, body: deserialized }
310
+ });
311
+ }
312
+ return deserialized;
313
+ }
314
+ }
315
+
316
+ class StandardRPCSerializer {
317
+ constructor(jsonSerializer) {
318
+ this.jsonSerializer = jsonSerializer;
319
+ }
320
+ serialize(data) {
321
+ if (isAsyncIteratorObject(data)) {
322
+ return mapEventIterator(data, {
323
+ value: async (value) => this.#serialize(value, false),
324
+ error: async (e) => {
325
+ return new ErrorEvent({
326
+ data: this.#serialize(toORPCError(e).toJSON(), false),
327
+ cause: e
328
+ });
329
+ }
330
+ });
331
+ }
332
+ return this.#serialize(data, true);
333
+ }
334
+ #serialize(data, enableFormData) {
335
+ const [json, meta_, maps, blobs] = this.jsonSerializer.serialize(data);
336
+ const meta = meta_.length === 0 ? void 0 : meta_;
337
+ if (!enableFormData || blobs.length === 0) {
338
+ return {
339
+ json,
340
+ meta
341
+ };
342
+ }
343
+ const form = new FormData();
344
+ form.set("data", stringifyJSON({ json, meta, maps }));
345
+ blobs.forEach((blob, i) => {
346
+ form.set(i.toString(), blob);
347
+ });
348
+ return form;
349
+ }
350
+ deserialize(data) {
351
+ if (isAsyncIteratorObject(data)) {
352
+ return mapEventIterator(data, {
353
+ value: async (value) => this.#deserialize(value),
354
+ error: async (e) => {
355
+ if (!(e instanceof ErrorEvent)) {
356
+ return e;
357
+ }
358
+ const deserialized = this.#deserialize(e.data);
359
+ if (isORPCErrorJson(deserialized)) {
360
+ return createORPCErrorFromJson(deserialized, { cause: e });
361
+ }
362
+ return new ErrorEvent({
363
+ data: deserialized,
364
+ cause: e
365
+ });
366
+ }
367
+ });
368
+ }
369
+ return this.#deserialize(data);
370
+ }
371
+ #deserialize(data) {
372
+ if (data === void 0) {
373
+ return void 0;
374
+ }
375
+ if (!(data instanceof FormData)) {
376
+ return this.jsonSerializer.deserialize(data.json, data.meta ?? []);
377
+ }
378
+ const serialized = JSON.parse(data.get("data"));
379
+ return this.jsonSerializer.deserialize(
380
+ serialized.json,
381
+ serialized.meta ?? [],
382
+ serialized.maps,
383
+ (i) => data.get(i.toString())
384
+ );
385
+ }
386
+ }
387
+
388
+ class StandardRPCLink extends StandardLink {
389
+ constructor(linkClient, options) {
390
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
391
+ const serializer = new StandardRPCSerializer(jsonSerializer);
392
+ const linkCodec = new StandardRPCLinkCodec(serializer, options);
393
+ super(linkCodec, linkClient, options);
394
+ }
395
+ }
396
+
397
+ export { CompositeStandardLinkPlugin as C, StandardLink as S, STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as a, StandardRPCJsonSerializer as b, StandardRPCLink as c, StandardRPCLinkCodec as d, StandardRPCSerializer as e, toStandardHeaders as f, getMalformedResponseErrorCode as g, toHttpPath as t };
@@ -0,0 +1,208 @@
1
+ import { resolveMaybeOptionalOptions, getConstructor, isObject, AsyncIteratorClass, isTypescriptObject } from '@orpc/shared';
2
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
3
+
4
+ const ORPC_CLIENT_PACKAGE_NAME = "@orpc/client";
5
+ const ORPC_CLIENT_PACKAGE_VERSION = "0.0.0-next.e7bc0b8";
6
+
7
+ const COMMON_ORPC_ERROR_DEFS = {
8
+ BAD_REQUEST: {
9
+ status: 400,
10
+ message: "Bad Request"
11
+ },
12
+ UNAUTHORIZED: {
13
+ status: 401,
14
+ message: "Unauthorized"
15
+ },
16
+ FORBIDDEN: {
17
+ status: 403,
18
+ message: "Forbidden"
19
+ },
20
+ NOT_FOUND: {
21
+ status: 404,
22
+ message: "Not Found"
23
+ },
24
+ METHOD_NOT_SUPPORTED: {
25
+ status: 405,
26
+ message: "Method Not Supported"
27
+ },
28
+ NOT_ACCEPTABLE: {
29
+ status: 406,
30
+ message: "Not Acceptable"
31
+ },
32
+ TIMEOUT: {
33
+ status: 408,
34
+ message: "Request Timeout"
35
+ },
36
+ CONFLICT: {
37
+ status: 409,
38
+ message: "Conflict"
39
+ },
40
+ PRECONDITION_FAILED: {
41
+ status: 412,
42
+ message: "Precondition Failed"
43
+ },
44
+ PAYLOAD_TOO_LARGE: {
45
+ status: 413,
46
+ message: "Payload Too Large"
47
+ },
48
+ UNSUPPORTED_MEDIA_TYPE: {
49
+ status: 415,
50
+ message: "Unsupported Media Type"
51
+ },
52
+ UNPROCESSABLE_CONTENT: {
53
+ status: 422,
54
+ message: "Unprocessable Content"
55
+ },
56
+ TOO_MANY_REQUESTS: {
57
+ status: 429,
58
+ message: "Too Many Requests"
59
+ },
60
+ CLIENT_CLOSED_REQUEST: {
61
+ status: 499,
62
+ message: "Client Closed Request"
63
+ },
64
+ INTERNAL_SERVER_ERROR: {
65
+ status: 500,
66
+ message: "Internal Server Error"
67
+ },
68
+ NOT_IMPLEMENTED: {
69
+ status: 501,
70
+ message: "Not Implemented"
71
+ },
72
+ BAD_GATEWAY: {
73
+ status: 502,
74
+ message: "Bad Gateway"
75
+ },
76
+ SERVICE_UNAVAILABLE: {
77
+ status: 503,
78
+ message: "Service Unavailable"
79
+ },
80
+ GATEWAY_TIMEOUT: {
81
+ status: 504,
82
+ message: "Gateway Timeout"
83
+ }
84
+ };
85
+ function fallbackORPCErrorStatus(code, status) {
86
+ return status ?? COMMON_ORPC_ERROR_DEFS[code]?.status ?? 500;
87
+ }
88
+ function fallbackORPCErrorMessage(code, message) {
89
+ return message || COMMON_ORPC_ERROR_DEFS[code]?.message || code;
90
+ }
91
+ const GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL = Symbol.for(`__${ORPC_CLIENT_PACKAGE_NAME}@${ORPC_CLIENT_PACKAGE_VERSION}/error/ORPC_ERROR_CONSTRUCTORS__`);
92
+ void (globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL] ??= /* @__PURE__ */ new WeakSet());
93
+ const globalORPCErrorConstructors = globalThis[GLOBAL_ORPC_ERROR_CONSTRUCTORS_SYMBOL];
94
+ class ORPCError extends Error {
95
+ defined;
96
+ code;
97
+ status;
98
+ data;
99
+ constructor(code, ...rest) {
100
+ const options = resolveMaybeOptionalOptions(rest);
101
+ if (options.status !== void 0 && !isORPCErrorStatus(options.status)) {
102
+ throw new Error("[ORPCError] Invalid error status code.");
103
+ }
104
+ const message = fallbackORPCErrorMessage(code, options.message);
105
+ super(message, options);
106
+ this.code = code;
107
+ this.status = fallbackORPCErrorStatus(code, options.status);
108
+ this.defined = options.defined ?? false;
109
+ this.data = options.data;
110
+ }
111
+ toJSON() {
112
+ return {
113
+ defined: this.defined,
114
+ code: this.code,
115
+ status: this.status,
116
+ message: this.message,
117
+ data: this.data
118
+ };
119
+ }
120
+ /**
121
+ * Workaround for Next.js where different contexts use separate
122
+ * dependency graphs, causing multiple ORPCError constructors existing and breaking
123
+ * `instanceof` checks across contexts.
124
+ *
125
+ * This is particularly problematic with "Optimized SSR", where orpc-client
126
+ * executes in one context but is invoked from another. When an error is thrown
127
+ * in the execution context, `instanceof ORPCError` checks fail in the
128
+ * invocation context due to separate class constructors.
129
+ *
130
+ * @todo Remove this and related code if Next.js resolves the multiple dependency graph issue.
131
+ */
132
+ static [Symbol.hasInstance](instance) {
133
+ if (globalORPCErrorConstructors.has(this)) {
134
+ const constructor = getConstructor(instance);
135
+ if (constructor && globalORPCErrorConstructors.has(constructor)) {
136
+ return true;
137
+ }
138
+ }
139
+ return super[Symbol.hasInstance](instance);
140
+ }
141
+ }
142
+ globalORPCErrorConstructors.add(ORPCError);
143
+ function isDefinedError(error) {
144
+ return error instanceof ORPCError && error.defined;
145
+ }
146
+ function toORPCError(error) {
147
+ return error instanceof ORPCError ? error : new ORPCError("INTERNAL_SERVER_ERROR", {
148
+ message: "Internal server error",
149
+ cause: error
150
+ });
151
+ }
152
+ function isORPCErrorStatus(status) {
153
+ return status < 200 || status >= 400;
154
+ }
155
+ function isORPCErrorJson(json) {
156
+ if (!isObject(json)) {
157
+ return false;
158
+ }
159
+ const validKeys = ["defined", "code", "status", "message", "data"];
160
+ if (Object.keys(json).some((k) => !validKeys.includes(k))) {
161
+ return false;
162
+ }
163
+ 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";
164
+ }
165
+ function createORPCErrorFromJson(json, options = {}) {
166
+ return new ORPCError(json.code, {
167
+ ...options,
168
+ ...json
169
+ });
170
+ }
171
+
172
+ function mapEventIterator(iterator, maps) {
173
+ const mapError = async (error) => {
174
+ let mappedError = await maps.error(error);
175
+ if (mappedError !== error) {
176
+ const meta = getEventMeta(error);
177
+ if (meta && isTypescriptObject(mappedError)) {
178
+ mappedError = withEventMeta(mappedError, meta);
179
+ }
180
+ }
181
+ return mappedError;
182
+ };
183
+ return new AsyncIteratorClass(async () => {
184
+ const { done, value } = await (async () => {
185
+ try {
186
+ return await iterator.next();
187
+ } catch (error) {
188
+ throw await mapError(error);
189
+ }
190
+ })();
191
+ let mappedValue = await maps.value(value, done);
192
+ if (mappedValue !== value) {
193
+ const meta = getEventMeta(value);
194
+ if (meta && isTypescriptObject(mappedValue)) {
195
+ mappedValue = withEventMeta(mappedValue, meta);
196
+ }
197
+ }
198
+ return { done, value: mappedValue };
199
+ }, async () => {
200
+ try {
201
+ await iterator.return?.();
202
+ } catch (error) {
203
+ throw await mapError(error);
204
+ }
205
+ });
206
+ }
207
+
208
+ export { COMMON_ORPC_ERROR_DEFS as C, ORPC_CLIENT_PACKAGE_NAME as O, ORPC_CLIENT_PACKAGE_VERSION as a, fallbackORPCErrorMessage as b, ORPCError as c, isORPCErrorStatus as d, isORPCErrorJson as e, fallbackORPCErrorStatus as f, createORPCErrorFromJson as g, isDefinedError as i, mapEventIterator as m, toORPCError as t };
@@ -0,0 +1,91 @@
1
+ import { b as ClientContext, c as ClientOptions, f as HTTPMethod } from './client.BOYsZIRq.mjs';
2
+ import { e as StandardLinkCodec, b as StandardLinkOptions, d as StandardLink, f as StandardLinkClient } from './client.Bwgm6dgk.mjs';
3
+ import { Segment, Value, Promisable } from '@orpc/shared';
4
+ import { StandardHeaders, StandardRequest, StandardLazyResponse } from '@orpc/standard-server';
5
+
6
+ declare const STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES: {
7
+ readonly BIGINT: 0;
8
+ readonly DATE: 1;
9
+ readonly NAN: 2;
10
+ readonly UNDEFINED: 3;
11
+ readonly URL: 4;
12
+ readonly REGEXP: 5;
13
+ readonly SET: 6;
14
+ readonly MAP: 7;
15
+ };
16
+ type StandardRPCJsonSerializedMetaItem = readonly [type: number, ...path: Segment[]];
17
+ type StandardRPCJsonSerialized = [json: unknown, meta: StandardRPCJsonSerializedMetaItem[], maps: Segment[][], blobs: Blob[]];
18
+ interface StandardRPCCustomJsonSerializer {
19
+ type: number;
20
+ condition(data: unknown): boolean;
21
+ serialize(data: any): unknown;
22
+ deserialize(serialized: any): unknown;
23
+ }
24
+ interface StandardRPCJsonSerializerOptions {
25
+ customJsonSerializers?: readonly StandardRPCCustomJsonSerializer[];
26
+ }
27
+ declare class StandardRPCJsonSerializer {
28
+ private readonly customSerializers;
29
+ constructor(options?: StandardRPCJsonSerializerOptions);
30
+ serialize(data: unknown, segments?: Segment[], meta?: StandardRPCJsonSerializedMetaItem[], maps?: Segment[][], blobs?: Blob[]): StandardRPCJsonSerialized;
31
+ deserialize(json: unknown, meta: readonly StandardRPCJsonSerializedMetaItem[]): unknown;
32
+ deserialize(json: unknown, meta: readonly StandardRPCJsonSerializedMetaItem[], maps: readonly Segment[][], getBlob: (index: number) => Blob): unknown;
33
+ }
34
+
35
+ declare class StandardRPCSerializer {
36
+ #private;
37
+ private readonly jsonSerializer;
38
+ constructor(jsonSerializer: StandardRPCJsonSerializer);
39
+ serialize(data: unknown): object;
40
+ deserialize(data: unknown): unknown;
41
+ }
42
+
43
+ interface StandardRPCLinkCodecOptions<T extends ClientContext> {
44
+ /**
45
+ * Base url for all requests.
46
+ */
47
+ url: Value<Promisable<string | URL>, [options: ClientOptions<T>, path: readonly string[], input: unknown]>;
48
+ /**
49
+ * The maximum length of the URL.
50
+ *
51
+ * @default 2083
52
+ */
53
+ maxUrlLength?: Value<Promisable<number>, [options: ClientOptions<T>, path: readonly string[], input: unknown]>;
54
+ /**
55
+ * The method used to make the request.
56
+ *
57
+ * @default 'POST'
58
+ */
59
+ method?: Value<Promisable<Exclude<HTTPMethod, 'HEAD'>>, [options: ClientOptions<T>, path: readonly string[], input: unknown]>;
60
+ /**
61
+ * The method to use when the payload cannot safely pass to the server with method return from method function.
62
+ * GET is not allowed, it's very dangerous.
63
+ *
64
+ * @default 'POST'
65
+ */
66
+ fallbackMethod?: Exclude<HTTPMethod, 'HEAD' | 'GET'>;
67
+ /**
68
+ * Inject headers to the request.
69
+ */
70
+ headers?: Value<Promisable<StandardHeaders | Headers>, [options: ClientOptions<T>, path: readonly string[], input: unknown]>;
71
+ }
72
+ declare class StandardRPCLinkCodec<T extends ClientContext> implements StandardLinkCodec<T> {
73
+ private readonly serializer;
74
+ private readonly baseUrl;
75
+ private readonly maxUrlLength;
76
+ private readonly fallbackMethod;
77
+ private readonly expectedMethod;
78
+ private readonly headers;
79
+ constructor(serializer: StandardRPCSerializer, options: StandardRPCLinkCodecOptions<T>);
80
+ encode(path: readonly string[], input: unknown, options: ClientOptions<T>): Promise<StandardRequest>;
81
+ decode(response: StandardLazyResponse): Promise<unknown>;
82
+ }
83
+
84
+ interface StandardRPCLinkOptions<T extends ClientContext> extends StandardLinkOptions<T>, StandardRPCLinkCodecOptions<T>, StandardRPCJsonSerializerOptions {
85
+ }
86
+ declare class StandardRPCLink<T extends ClientContext> extends StandardLink<T> {
87
+ constructor(linkClient: StandardLinkClient<T>, options: StandardRPCLinkOptions<T>);
88
+ }
89
+
90
+ export { STANDARD_RPC_JSON_SERIALIZER_BUILT_IN_TYPES as S, StandardRPCJsonSerializer as e, StandardRPCLink as g, StandardRPCLinkCodec as i, StandardRPCSerializer as j };
91
+ export type { StandardRPCJsonSerializedMetaItem as a, StandardRPCJsonSerialized as b, StandardRPCCustomJsonSerializer as c, StandardRPCJsonSerializerOptions as d, StandardRPCLinkOptions as f, StandardRPCLinkCodecOptions as h };