@orpc/server 0.0.0-next.c12be86 → 0.0.0-next.c3068b4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (66) hide show
  1. package/dist/chunk-6RSW63UJ.js +136 -0
  2. package/dist/chunk-JHLUGXCM.js +294 -0
  3. package/dist/chunk-NOA3GBJQ.js +380 -0
  4. package/dist/fetch.js +13 -320
  5. package/dist/hono.js +41 -0
  6. package/dist/index.js +269 -383
  7. package/dist/next.js +38 -0
  8. package/dist/node.js +173 -0
  9. package/dist/src/adapters/fetch/index.d.ts +4 -0
  10. package/dist/src/adapters/fetch/rpc-handler.d.ts +10 -0
  11. package/dist/src/adapters/fetch/types.d.ts +13 -0
  12. package/dist/src/adapters/fetch/utils.d.ts +6 -0
  13. package/dist/src/adapters/hono/index.d.ts +3 -0
  14. package/dist/src/adapters/hono/middleware.d.ts +13 -0
  15. package/dist/src/adapters/next/index.d.ts +3 -0
  16. package/dist/src/adapters/next/serve.d.ts +20 -0
  17. package/dist/src/adapters/node/index.d.ts +4 -0
  18. package/dist/src/adapters/node/rpc-handler.d.ts +10 -0
  19. package/dist/src/adapters/node/types.d.ts +21 -0
  20. package/dist/src/adapters/node/utils.d.ts +5 -0
  21. package/dist/src/adapters/standard/handler.d.ts +33 -0
  22. package/dist/src/adapters/standard/index.d.ts +7 -0
  23. package/dist/src/adapters/standard/rpc-codec.d.ts +15 -0
  24. package/dist/src/adapters/standard/rpc-handler.d.ts +8 -0
  25. package/dist/src/adapters/standard/rpc-matcher.d.ts +10 -0
  26. package/dist/src/adapters/standard/rpc-serializer.d.ts +16 -0
  27. package/dist/src/adapters/standard/types.d.ts +44 -0
  28. package/dist/src/builder-variants.d.ts +74 -0
  29. package/dist/src/builder.d.ts +52 -30
  30. package/dist/src/config.d.ts +6 -0
  31. package/dist/src/context.d.ts +9 -0
  32. package/dist/src/hidden.d.ts +6 -4
  33. package/dist/src/implementer-procedure.d.ts +30 -0
  34. package/dist/src/implementer-variants.d.ts +17 -0
  35. package/dist/src/implementer.d.ts +28 -0
  36. package/dist/src/index.d.ts +11 -11
  37. package/dist/src/lazy-utils.d.ts +4 -2
  38. package/dist/src/lazy.d.ts +9 -5
  39. package/dist/src/middleware-decorated.d.ts +7 -5
  40. package/dist/src/middleware-utils.d.ts +5 -0
  41. package/dist/src/middleware.d.ts +28 -14
  42. package/dist/src/procedure-client.d.ts +8 -22
  43. package/dist/src/procedure-decorated.d.ts +18 -11
  44. package/dist/src/procedure-utils.d.ts +17 -0
  45. package/dist/src/procedure.d.ts +24 -18
  46. package/dist/src/router-accessible-lazy.d.ts +8 -0
  47. package/dist/src/router-client.d.ts +7 -10
  48. package/dist/src/router.d.ts +25 -12
  49. package/dist/src/utils.d.ts +23 -2
  50. package/dist/standard.js +16 -0
  51. package/package.json +31 -6
  52. package/dist/chunk-6A7XHEBH.js +0 -189
  53. package/dist/src/fetch/composite-handler.d.ts +0 -8
  54. package/dist/src/fetch/index.d.ts +0 -7
  55. package/dist/src/fetch/orpc-handler.d.ts +0 -20
  56. package/dist/src/fetch/orpc-payload-codec.d.ts +0 -16
  57. package/dist/src/fetch/orpc-procedure-matcher.d.ts +0 -12
  58. package/dist/src/fetch/super-json.d.ts +0 -12
  59. package/dist/src/fetch/types.d.ts +0 -16
  60. package/dist/src/implementer-chainable.d.ts +0 -10
  61. package/dist/src/lazy-decorated.d.ts +0 -10
  62. package/dist/src/procedure-builder.d.ts +0 -22
  63. package/dist/src/procedure-implementer.d.ts +0 -18
  64. package/dist/src/router-builder.d.ts +0 -29
  65. package/dist/src/router-implementer.d.ts +0 -21
  66. package/dist/src/types.d.ts +0 -12
@@ -0,0 +1,380 @@
1
+ // src/lazy.ts
2
+ var LAZY_LOADER_SYMBOL = Symbol("ORPC_LAZY_LOADER");
3
+ function lazy(loader) {
4
+ return {
5
+ [LAZY_LOADER_SYMBOL]: loader
6
+ };
7
+ }
8
+ function isLazy(item) {
9
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_LOADER_SYMBOL in item && typeof item[LAZY_LOADER_SYMBOL] === "function";
10
+ }
11
+ function unlazy(lazied) {
12
+ return isLazy(lazied) ? lazied[LAZY_LOADER_SYMBOL]() : Promise.resolve({ default: lazied });
13
+ }
14
+
15
+ // src/procedure.ts
16
+ import { isContractProcedure } from "@orpc/contract";
17
+ var Procedure = class {
18
+ "~orpc";
19
+ constructor(def) {
20
+ this["~orpc"] = def;
21
+ }
22
+ };
23
+ function isProcedure(item) {
24
+ if (item instanceof Procedure) {
25
+ return true;
26
+ }
27
+ return isContractProcedure(item) && "middlewares" in item["~orpc"] && "inputValidationIndex" in item["~orpc"] && "outputValidationIndex" in item["~orpc"] && "handler" in item["~orpc"];
28
+ }
29
+
30
+ // src/lazy-utils.ts
31
+ function flatLazy(lazied) {
32
+ const flattenLoader = async () => {
33
+ let current = await unlazy(lazied);
34
+ while (true) {
35
+ if (!isLazy(current.default)) {
36
+ break;
37
+ }
38
+ current = await unlazy(current.default);
39
+ }
40
+ return current;
41
+ };
42
+ return lazy(flattenLoader);
43
+ }
44
+ function createLazyProcedureFormAnyLazy(lazied) {
45
+ const lazyProcedure = lazy(async () => {
46
+ const { default: maybeProcedure } = await unlazy(flatLazy(lazied));
47
+ if (!isProcedure(maybeProcedure)) {
48
+ throw new Error(`
49
+ Expected a lazy<procedure> but got lazy<unknown>.
50
+ This should be caught by TypeScript compilation.
51
+ Please report this issue if this makes you feel uncomfortable.
52
+ `);
53
+ }
54
+ return { default: maybeProcedure };
55
+ });
56
+ return lazyProcedure;
57
+ }
58
+
59
+ // src/middleware.ts
60
+ function middlewareOutputFn(output) {
61
+ return { output, context: {} };
62
+ }
63
+
64
+ // src/procedure-client.ts
65
+ import { createORPCErrorConstructorMap, ORPCError, validateORPCError, ValidationError } from "@orpc/contract";
66
+ import { executeWithHooks, toError, value } from "@orpc/shared";
67
+ function createProcedureClient(lazyableProcedure, ...[options]) {
68
+ return async (...[input, callerOptions]) => {
69
+ const path = options?.path ?? [];
70
+ const { default: procedure } = await unlazy(lazyableProcedure);
71
+ const context = await value(options?.context ?? {}, callerOptions?.context);
72
+ const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
73
+ const executeOptions = {
74
+ input,
75
+ context,
76
+ errors,
77
+ path,
78
+ procedure,
79
+ signal: callerOptions?.signal
80
+ };
81
+ try {
82
+ const output = await executeWithHooks({
83
+ hooks: options,
84
+ input,
85
+ context,
86
+ meta: executeOptions,
87
+ execute: () => executeProcedureInternal(procedure, executeOptions)
88
+ });
89
+ return output;
90
+ } catch (e) {
91
+ if (!(e instanceof ORPCError)) {
92
+ throw toError(e);
93
+ }
94
+ const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
95
+ throw validated;
96
+ }
97
+ };
98
+ }
99
+ async function validateInput(procedure, input) {
100
+ const schema = procedure["~orpc"].inputSchema;
101
+ if (!schema) {
102
+ return input;
103
+ }
104
+ const result = await schema["~standard"].validate(input);
105
+ if (result.issues) {
106
+ throw new ORPCError("BAD_REQUEST", {
107
+ message: "Input validation failed",
108
+ data: {
109
+ issues: result.issues
110
+ },
111
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
112
+ });
113
+ }
114
+ return result.value;
115
+ }
116
+ async function validateOutput(procedure, output) {
117
+ const schema = procedure["~orpc"].outputSchema;
118
+ if (!schema) {
119
+ return output;
120
+ }
121
+ const result = await schema["~standard"].validate(output);
122
+ if (result.issues) {
123
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
124
+ message: "Output validation failed",
125
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
126
+ });
127
+ }
128
+ return result.value;
129
+ }
130
+ async function executeProcedureInternal(procedure, options) {
131
+ const middlewares = procedure["~orpc"].middlewares;
132
+ const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
133
+ const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
134
+ let currentIndex = 0;
135
+ let currentContext = options.context;
136
+ let currentInput = options.input;
137
+ const next = async (...[nextOptions]) => {
138
+ const index = currentIndex;
139
+ currentIndex += 1;
140
+ currentContext = { ...currentContext, ...nextOptions?.context };
141
+ if (index === inputValidationIndex) {
142
+ currentInput = await validateInput(procedure, currentInput);
143
+ }
144
+ const mid = middlewares[index];
145
+ const result = mid ? await mid({ ...options, context: currentContext, next }, currentInput, middlewareOutputFn) : { output: await procedure["~orpc"].handler({ ...options, context: currentContext, input: currentInput }), context: currentContext };
146
+ if (index === outputValidationIndex) {
147
+ const validatedOutput = await validateOutput(procedure, result.output);
148
+ return {
149
+ ...result,
150
+ output: validatedOutput
151
+ };
152
+ }
153
+ return result;
154
+ };
155
+ return (await next({})).output;
156
+ }
157
+
158
+ // src/hidden.ts
159
+ var ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_ROUTER_CONTRACT");
160
+ function setRouterContract(obj, contract) {
161
+ return new Proxy(obj, {
162
+ get(target, key) {
163
+ if (key === ROUTER_CONTRACT_SYMBOL) {
164
+ return contract;
165
+ }
166
+ return Reflect.get(target, key);
167
+ }
168
+ });
169
+ }
170
+ function getRouterContract(obj) {
171
+ return obj[ROUTER_CONTRACT_SYMBOL];
172
+ }
173
+ var LAZY_ROUTER_PREFIX_SYMBOL = Symbol("ORPC_LAZY_ROUTER_PREFIX");
174
+ function deepSetLazyRouterPrefix(router, prefix) {
175
+ return new Proxy(router, {
176
+ get(target, key) {
177
+ if (key !== LAZY_ROUTER_PREFIX_SYMBOL) {
178
+ const val = Reflect.get(target, key);
179
+ if (isLazy(val)) {
180
+ return deepSetLazyRouterPrefix(val, prefix);
181
+ }
182
+ return val;
183
+ }
184
+ return prefix;
185
+ }
186
+ });
187
+ }
188
+ function getLazyRouterPrefix(obj) {
189
+ return obj[LAZY_ROUTER_PREFIX_SYMBOL];
190
+ }
191
+
192
+ // src/router.ts
193
+ import { adaptRoute, mergeErrorMap, mergePrefix } from "@orpc/contract";
194
+
195
+ // src/middleware-utils.ts
196
+ function dedupeMiddlewares(compare, middlewares) {
197
+ let min = 0;
198
+ for (let i = 0; i < middlewares.length; i++) {
199
+ const index = compare.indexOf(middlewares[i], min);
200
+ if (index === -1) {
201
+ return middlewares.slice(i);
202
+ }
203
+ min = index + 1;
204
+ }
205
+ return [];
206
+ }
207
+ function mergeMiddlewares(first, second) {
208
+ return [...first, ...dedupeMiddlewares(first, second)];
209
+ }
210
+ function addMiddleware(middlewares, addition) {
211
+ return [...middlewares, addition];
212
+ }
213
+
214
+ // src/router.ts
215
+ function adaptRouter(router, options) {
216
+ if (isLazy(router)) {
217
+ const adapted2 = lazy(async () => {
218
+ const unlaziedRouter = (await unlazy(router)).default;
219
+ const adapted3 = adaptRouter(unlaziedRouter, options);
220
+ return { default: adapted3 };
221
+ });
222
+ const accessible = createAccessibleLazyRouter(adapted2);
223
+ const currentPrefix = getLazyRouterPrefix(router);
224
+ const prefix = currentPrefix ? mergePrefix(options.prefix, currentPrefix) : options.prefix;
225
+ if (prefix) {
226
+ return deepSetLazyRouterPrefix(accessible, prefix);
227
+ }
228
+ return accessible;
229
+ }
230
+ if (isProcedure(router)) {
231
+ const newMiddlewares = mergeMiddlewares(options.middlewares, router["~orpc"].middlewares);
232
+ const newMiddlewareAdded = newMiddlewares.length - router["~orpc"].middlewares.length;
233
+ const adapted2 = new Procedure({
234
+ ...router["~orpc"],
235
+ route: adaptRoute(router["~orpc"].route, options),
236
+ errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
237
+ middlewares: newMiddlewares,
238
+ inputValidationIndex: router["~orpc"].inputValidationIndex + newMiddlewareAdded,
239
+ outputValidationIndex: router["~orpc"].outputValidationIndex + newMiddlewareAdded
240
+ });
241
+ return adapted2;
242
+ }
243
+ const adapted = {};
244
+ for (const key in router) {
245
+ adapted[key] = adaptRouter(router[key], options);
246
+ }
247
+ return adapted;
248
+ }
249
+ function getRouterChild(router, ...path) {
250
+ let current = router;
251
+ for (let i = 0; i < path.length; i++) {
252
+ const segment = path[i];
253
+ if (!current) {
254
+ return void 0;
255
+ }
256
+ if (isProcedure(current)) {
257
+ return void 0;
258
+ }
259
+ if (!isLazy(current)) {
260
+ current = current[segment];
261
+ continue;
262
+ }
263
+ const lazied = current;
264
+ const rest = path.slice(i);
265
+ const newLazy = lazy(async () => {
266
+ const unwrapped = await unlazy(lazied);
267
+ if (!unwrapped.default) {
268
+ return unwrapped;
269
+ }
270
+ const next = getRouterChild(unwrapped.default, ...rest);
271
+ return { default: next };
272
+ });
273
+ return flatLazy(newLazy);
274
+ }
275
+ return current;
276
+ }
277
+
278
+ // src/router-accessible-lazy.ts
279
+ function createAccessibleLazyRouter(lazied) {
280
+ const flattenLazy = flatLazy(lazied);
281
+ const recursive = new Proxy(flattenLazy, {
282
+ get(target, key) {
283
+ if (typeof key !== "string") {
284
+ return Reflect.get(target, key);
285
+ }
286
+ const next = getRouterChild(flattenLazy, key);
287
+ return createAccessibleLazyRouter(next);
288
+ }
289
+ });
290
+ return recursive;
291
+ }
292
+
293
+ // src/utils.ts
294
+ import { isContractProcedure as isContractProcedure2 } from "@orpc/contract";
295
+ function eachContractProcedure(options, callback, laziedOptions = []) {
296
+ const hiddenContract = getRouterContract(options.router);
297
+ if (hiddenContract) {
298
+ return eachContractProcedure(
299
+ {
300
+ router: hiddenContract,
301
+ path: options.path
302
+ },
303
+ callback,
304
+ laziedOptions
305
+ );
306
+ }
307
+ if (isLazy(options.router)) {
308
+ laziedOptions.push({
309
+ lazied: options.router,
310
+ path: options.path
311
+ });
312
+ } else if (isContractProcedure2(options.router)) {
313
+ callback({
314
+ contract: options.router,
315
+ path: options.path
316
+ });
317
+ } else {
318
+ for (const key in options.router) {
319
+ eachContractProcedure(
320
+ {
321
+ router: options.router[key],
322
+ path: [...options.path, key]
323
+ },
324
+ callback,
325
+ laziedOptions
326
+ );
327
+ }
328
+ }
329
+ return laziedOptions;
330
+ }
331
+ async function eachAllContractProcedure(options, callback) {
332
+ const pending = [options];
333
+ for (const item of pending) {
334
+ const lazies = eachContractProcedure(item, callback);
335
+ for (const lazy2 of lazies) {
336
+ const { default: router } = await unlazy(lazy2.lazied);
337
+ pending.push({
338
+ path: lazy2.path,
339
+ router
340
+ });
341
+ }
342
+ }
343
+ }
344
+ function convertPathToHttpPath(path) {
345
+ return `/${path.map(encodeURIComponent).join("/")}`;
346
+ }
347
+ function createContractedProcedure(contract, procedure) {
348
+ return new Procedure({
349
+ ...procedure["~orpc"],
350
+ errorMap: contract["~orpc"].errorMap,
351
+ route: contract["~orpc"].route,
352
+ meta: contract["~orpc"].meta
353
+ });
354
+ }
355
+
356
+ export {
357
+ LAZY_LOADER_SYMBOL,
358
+ lazy,
359
+ isLazy,
360
+ unlazy,
361
+ Procedure,
362
+ isProcedure,
363
+ flatLazy,
364
+ createLazyProcedureFormAnyLazy,
365
+ addMiddleware,
366
+ middlewareOutputFn,
367
+ createProcedureClient,
368
+ setRouterContract,
369
+ getRouterContract,
370
+ deepSetLazyRouterPrefix,
371
+ getLazyRouterPrefix,
372
+ createAccessibleLazyRouter,
373
+ adaptRouter,
374
+ getRouterChild,
375
+ eachContractProcedure,
376
+ eachAllContractProcedure,
377
+ convertPathToHttpPath,
378
+ createContractedProcedure
379
+ };
380
+ //# sourceMappingURL=chunk-NOA3GBJQ.js.map
package/dist/fetch.js CHANGED
@@ -1,324 +1,17 @@
1
1
  import {
2
- __export,
3
- createProcedureClient,
4
- getRouterChild,
5
- isProcedure,
6
- unlazy
7
- } from "./chunk-6A7XHEBH.js";
8
-
9
- // src/fetch/composite-handler.ts
10
- var CompositeHandler = class {
11
- constructor(handlers) {
12
- this.handlers = handlers;
13
- }
14
- async fetch(request, ...opt) {
15
- for (const handler of this.handlers) {
16
- if (handler.condition(request)) {
17
- return handler.fetch(request, ...opt);
18
- }
19
- }
20
- return new Response("None of the handlers can handle the request.", {
21
- status: 404
22
- });
23
- }
24
- };
25
-
26
- // src/fetch/orpc-handler.ts
27
- import { executeWithHooks, ORPC_HANDLER_HEADER, ORPC_HANDLER_VALUE, trim as trim2 } from "@orpc/shared";
28
- import { ORPCError as ORPCError2 } from "@orpc/shared/error";
29
-
30
- // src/fetch/orpc-payload-codec.ts
31
- import { findDeepMatches, set } from "@orpc/shared";
32
- import { ORPCError } from "@orpc/shared/error";
33
-
34
- // src/fetch/super-json.ts
35
- var super_json_exports = {};
36
- __export(super_json_exports, {
37
- deserialize: () => deserialize,
38
- serialize: () => serialize
39
- });
40
-
41
- // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/getType.js
42
- function getType(payload) {
43
- return Object.prototype.toString.call(payload).slice(8, -1);
44
- }
45
-
46
- // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/isPlainObject.js
47
- function isPlainObject(payload) {
48
- if (getType(payload) !== "Object")
49
- return false;
50
- const prototype = Object.getPrototypeOf(payload);
51
- return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
52
- }
53
-
54
- // src/fetch/super-json.ts
55
- function serialize(value, segments = [], meta = []) {
56
- if (typeof value === "bigint") {
57
- meta.push(["bigint", segments]);
58
- return { data: value.toString(), meta };
59
- }
60
- if (value instanceof Date) {
61
- meta.push(["date", segments]);
62
- const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
63
- return { data, meta };
64
- }
65
- if (Number.isNaN(value)) {
66
- meta.push(["nan", segments]);
67
- return { data: "NaN", meta };
68
- }
69
- if (value instanceof RegExp) {
70
- meta.push(["regexp", segments]);
71
- return { data: value.toString(), meta };
72
- }
73
- if (value instanceof URL) {
74
- meta.push(["url", segments]);
75
- return { data: value.toString(), meta };
76
- }
77
- if (isPlainObject(value)) {
78
- const data = {};
79
- for (const k in value) {
80
- data[k] = serialize(value[k], [...segments, k], meta).data;
81
- }
82
- return { data, meta };
83
- }
84
- if (Array.isArray(value)) {
85
- const data = value.map((v, i) => {
86
- if (v === void 0) {
87
- meta.push(["undefined", [...segments, i]]);
88
- return null;
89
- }
90
- return serialize(v, [...segments, i], meta).data;
91
- });
92
- return { data, meta };
93
- }
94
- if (value instanceof Set) {
95
- const result = serialize(Array.from(value), segments, meta);
96
- meta.push(["set", segments]);
97
- return result;
98
- }
99
- if (value instanceof Map) {
100
- const result = serialize(Array.from(value.entries()), segments, meta);
101
- meta.push(["map", segments]);
102
- return result;
103
- }
104
- return { data: value, meta };
105
- }
106
- function deserialize({
107
- data,
108
- meta
109
- }) {
110
- if (meta.length === 0) {
111
- return data;
112
- }
113
- const ref = { data };
114
- for (const [type, segments] of meta) {
115
- let currentRef = ref;
116
- let preSegment = "data";
117
- for (let i = 0; i < segments.length; i++) {
118
- currentRef = currentRef[preSegment];
119
- preSegment = segments[i];
120
- }
121
- switch (type) {
122
- case "nan":
123
- currentRef[preSegment] = Number.NaN;
124
- break;
125
- case "bigint":
126
- currentRef[preSegment] = BigInt(currentRef[preSegment]);
127
- break;
128
- case "date":
129
- currentRef[preSegment] = new Date(currentRef[preSegment]);
130
- break;
131
- case "regexp": {
132
- const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
133
- currentRef[preSegment] = new RegExp(pattern, flags);
134
- break;
135
- }
136
- case "url":
137
- currentRef[preSegment] = new URL(currentRef[preSegment]);
138
- break;
139
- case "undefined":
140
- currentRef[preSegment] = void 0;
141
- break;
142
- case "map":
143
- currentRef[preSegment] = new Map(currentRef[preSegment]);
144
- break;
145
- case "set":
146
- currentRef[preSegment] = new Set(currentRef[preSegment]);
147
- break;
148
- /* v8 ignore next 3 */
149
- default: {
150
- const _expected = type;
151
- }
152
- }
153
- }
154
- return ref.data;
155
- }
156
-
157
- // src/fetch/orpc-payload-codec.ts
158
- var ORPCPayloadCodec = class {
159
- /**
160
- * If method is GET, the payload will be encoded as query string.
161
- * If method is GET and payload contain file, the method will be fallback to fallbackMethod. (fallbackMethod = GET will force to use GET method)
162
- */
163
- encode(payload, method = "POST", fallbackMethod = "POST") {
164
- const { data, meta } = serialize(payload);
165
- const { maps, values } = findDeepMatches((v) => v instanceof Blob, data);
166
- if (method === "GET" && (values.length === 0 || fallbackMethod === "GET")) {
167
- const query = new URLSearchParams({
168
- data: JSON.stringify(data),
169
- meta: JSON.stringify(meta)
170
- });
171
- return {
172
- query,
173
- method: "GET"
174
- };
175
- }
176
- const nonGETMethod = method === "GET" ? fallbackMethod : method;
177
- if (values.length > 0) {
178
- const form = new FormData();
179
- if (data !== void 0) {
180
- form.append("data", JSON.stringify(data));
181
- }
182
- form.append("meta", JSON.stringify(meta));
183
- form.append("maps", JSON.stringify(maps));
184
- for (const i in values) {
185
- const value = values[i];
186
- form.append(i, value);
187
- }
188
- return {
189
- body: form,
190
- method: nonGETMethod
191
- };
192
- }
193
- return {
194
- body: JSON.stringify({ data, meta }),
195
- headers: new Headers({
196
- "content-type": "application/json"
197
- }),
198
- method: nonGETMethod
199
- };
200
- }
201
- async decode(re) {
202
- try {
203
- if ("method" in re && re.method === "GET") {
204
- const url = new URL(re.url);
205
- const query = url.searchParams;
206
- const data = JSON.parse(query.getAll("data").at(-1));
207
- const meta = JSON.parse(query.getAll("meta").at(-1));
208
- return deserialize({
209
- data,
210
- meta
211
- });
212
- }
213
- if (re.headers.get("content-type")?.startsWith("multipart/form-data")) {
214
- const form = await re.formData();
215
- const rawData = form.get("data");
216
- const rawMeta = form.get("meta");
217
- const rawMaps = form.get("maps");
218
- let data = JSON.parse(rawData);
219
- const meta = JSON.parse(rawMeta);
220
- const maps = JSON.parse(rawMaps);
221
- for (const i in maps) {
222
- data = set(data, maps[i], form.get(i));
223
- }
224
- return deserialize({
225
- data,
226
- meta
227
- });
228
- }
229
- const json = await re.json();
230
- return deserialize(json);
231
- } catch (e) {
232
- throw new ORPCError({
233
- code: "BAD_REQUEST",
234
- message: "Cannot parse request/response. Please check the request/response body and Content-Type header.",
235
- cause: e
236
- });
237
- }
238
- }
239
- };
240
-
241
- // src/fetch/orpc-procedure-matcher.ts
242
- import { trim } from "@orpc/shared";
243
- var ORPCProcedureMatcher = class {
244
- constructor(router) {
245
- this.router = router;
246
- }
247
- async match(pathname) {
248
- const path = trim(pathname, "/").split("/").map(decodeURIComponent);
249
- const match = getRouterChild(this.router, ...path);
250
- const { default: maybeProcedure } = await unlazy(match);
251
- if (!isProcedure(maybeProcedure)) {
252
- return void 0;
253
- }
254
- return {
255
- procedure: maybeProcedure,
256
- path
257
- };
258
- }
259
- };
260
-
261
- // src/fetch/orpc-handler.ts
262
- var ORPCHandler = class {
263
- constructor(router, options) {
264
- this.router = router;
265
- this.options = options;
266
- this.procedureMatcher = options?.procedureMatcher ?? new ORPCProcedureMatcher(router);
267
- this.payloadCodec = options?.payloadCodec ?? new ORPCPayloadCodec();
268
- }
269
- procedureMatcher;
270
- payloadCodec;
271
- condition(request) {
272
- return Boolean(request.headers.get(ORPC_HANDLER_HEADER)?.includes(ORPC_HANDLER_VALUE));
273
- }
274
- async fetch(request, ...[options]) {
275
- const context = options?.context;
276
- const execute = async () => {
277
- const url = new URL(request.url);
278
- const pathname = `/${trim2(url.pathname.replace(options?.prefix ?? "", ""), "/")}`;
279
- const match = await this.procedureMatcher.match(pathname);
280
- if (!match) {
281
- throw new ORPCError2({ code: "NOT_FOUND", message: "Not found" });
282
- }
283
- const input = await this.payloadCodec.decode(request);
284
- const client = createProcedureClient({
285
- context,
286
- procedure: match.procedure,
287
- path: match.path
288
- });
289
- const output = await client(input, { signal: options?.signal });
290
- const { body, headers } = this.payloadCodec.encode(output);
291
- return new Response(body, { headers });
292
- };
293
- try {
294
- return await executeWithHooks({
295
- context,
296
- execute,
297
- input: request,
298
- hooks: this.options,
299
- meta: {
300
- signal: options?.signal
301
- }
302
- });
303
- } catch (e) {
304
- const error = e instanceof ORPCError2 ? e : new ORPCError2({
305
- code: "INTERNAL_SERVER_ERROR",
306
- message: "Internal server error",
307
- cause: e
308
- });
309
- const { body, headers } = this.payloadCodec.encode(error.toJSON());
310
- return new Response(body, {
311
- headers,
312
- status: error.status
313
- });
314
- }
315
- }
316
- };
2
+ RPCHandler,
3
+ fetchReToStandardBody,
4
+ fetchRequestToStandardRequest,
5
+ standardBodyToFetchBody,
6
+ standardResponseToFetchResponse
7
+ } from "./chunk-6RSW63UJ.js";
8
+ import "./chunk-JHLUGXCM.js";
9
+ import "./chunk-NOA3GBJQ.js";
317
10
  export {
318
- CompositeHandler,
319
- ORPCHandler,
320
- ORPCPayloadCodec,
321
- ORPCProcedureMatcher,
322
- super_json_exports as SuperJSON
11
+ RPCHandler,
12
+ fetchReToStandardBody,
13
+ fetchRequestToStandardRequest,
14
+ standardBodyToFetchBody,
15
+ standardResponseToFetchResponse
323
16
  };
324
17
  //# sourceMappingURL=fetch.js.map