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

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 (80) hide show
  1. package/dist/chunk-6A7XHEBH.js +189 -0
  2. package/dist/fetch.js +273 -630
  3. package/dist/index.js +404 -280
  4. package/dist/src/builder.d.ts +27 -41
  5. package/dist/src/fetch/composite-handler.d.ts +8 -0
  6. package/dist/src/fetch/index.d.ts +7 -0
  7. package/dist/src/fetch/orpc-handler.d.ts +20 -0
  8. package/dist/src/fetch/orpc-payload-codec.d.ts +16 -0
  9. package/dist/src/fetch/orpc-procedure-matcher.d.ts +12 -0
  10. package/dist/src/fetch/super-json.d.ts +12 -0
  11. package/dist/src/fetch/types.d.ts +16 -0
  12. package/dist/src/hidden.d.ts +6 -0
  13. package/dist/src/implementer-chainable.d.ts +10 -0
  14. package/dist/src/index.d.ts +11 -3
  15. package/dist/src/lazy-decorated.d.ts +10 -0
  16. package/dist/src/lazy-utils.d.ts +4 -0
  17. package/dist/src/lazy.d.ts +18 -0
  18. package/dist/src/middleware-decorated.d.ts +8 -0
  19. package/dist/src/middleware.d.ts +3 -6
  20. package/dist/src/procedure-builder.d.ts +15 -24
  21. package/dist/src/procedure-client.d.ts +34 -0
  22. package/dist/src/procedure-decorated.d.ts +14 -0
  23. package/dist/src/procedure-implementer.d.ts +13 -13
  24. package/dist/src/procedure.d.ts +18 -24
  25. package/dist/src/router-builder.d.ts +24 -17
  26. package/dist/src/router-client.d.ts +25 -0
  27. package/dist/src/router-implementer.d.ts +18 -17
  28. package/dist/src/router.d.ts +11 -15
  29. package/dist/src/types.d.ts +8 -4
  30. package/package.json +13 -21
  31. package/dist/chunk-TDFYNRZV.js +0 -190
  32. package/dist/chunk-TDFYNRZV.js.map +0 -1
  33. package/dist/fetch.js.map +0 -1
  34. package/dist/index.js.map +0 -1
  35. package/dist/src/adapters/fetch.d.ts +0 -42
  36. package/dist/src/adapters/fetch.d.ts.map +0 -1
  37. package/dist/src/builder.d.ts.map +0 -1
  38. package/dist/src/index.d.ts.map +0 -1
  39. package/dist/src/middleware.d.ts.map +0 -1
  40. package/dist/src/procedure-builder.d.ts.map +0 -1
  41. package/dist/src/procedure-caller.d.ts +0 -19
  42. package/dist/src/procedure-caller.d.ts.map +0 -1
  43. package/dist/src/procedure-implementer.d.ts.map +0 -1
  44. package/dist/src/procedure.d.ts.map +0 -1
  45. package/dist/src/router-builder.d.ts.map +0 -1
  46. package/dist/src/router-caller.d.ts +0 -22
  47. package/dist/src/router-caller.d.ts.map +0 -1
  48. package/dist/src/router-implementer.d.ts.map +0 -1
  49. package/dist/src/router.d.ts.map +0 -1
  50. package/dist/src/types.d.ts.map +0 -1
  51. package/dist/src/utils.d.ts.map +0 -1
  52. package/dist/tsconfig.tsbuildinfo +0 -1
  53. package/src/adapters/fetch.test.ts +0 -629
  54. package/src/adapters/fetch.ts +0 -290
  55. package/src/builder.test.ts +0 -371
  56. package/src/builder.ts +0 -238
  57. package/src/index.ts +0 -16
  58. package/src/middleware.test.ts +0 -260
  59. package/src/middleware.ts +0 -136
  60. package/src/procedure-builder.test.ts +0 -223
  61. package/src/procedure-builder.ts +0 -158
  62. package/src/procedure-caller.test.ts +0 -171
  63. package/src/procedure-caller.ts +0 -138
  64. package/src/procedure-implementer.test.ts +0 -220
  65. package/src/procedure-implementer.ts +0 -102
  66. package/src/procedure.test.ts +0 -317
  67. package/src/procedure.ts +0 -237
  68. package/src/router-builder.test.ts +0 -106
  69. package/src/router-builder.ts +0 -122
  70. package/src/router-caller.test.ts +0 -126
  71. package/src/router-caller.ts +0 -64
  72. package/src/router-implementer.test.ts +0 -116
  73. package/src/router-implementer.ts +0 -113
  74. package/src/router.test-d.ts +0 -48
  75. package/src/router.test.ts +0 -142
  76. package/src/router.ts +0 -91
  77. package/src/types.test.ts +0 -18
  78. package/src/types.ts +0 -13
  79. package/src/utils.test.ts +0 -16
  80. package/src/utils.ts +0 -16
package/dist/fetch.js CHANGED
@@ -1,681 +1,324 @@
1
1
  import {
2
- createProcedureCaller,
3
- isProcedure
4
- } from "./chunk-TDFYNRZV.js";
2
+ __export,
3
+ createProcedureClient,
4
+ getRouterChild,
5
+ isProcedure,
6
+ unlazy
7
+ } from "./chunk-6A7XHEBH.js";
5
8
 
6
- // src/adapters/fetch.ts
7
- import {
8
- ORPC_HEADER,
9
- ORPC_HEADER_VALUE,
10
- standardizeHTTPPath
11
- } from "@orpc/contract";
12
- import {
13
- get,
14
- isPlainObject,
15
- mapValues,
16
- trim,
17
- value
18
- } from "@orpc/shared";
19
- import { ORPCError } from "@orpc/shared/error";
20
- import {
21
- OpenAPIDeserializer,
22
- OpenAPISerializer,
23
- ORPCDeserializer,
24
- ORPCSerializer,
25
- zodCoerce
26
- } from "@orpc/transformer";
27
-
28
- // ../../node_modules/.pnpm/hono@4.6.6/node_modules/hono/dist/router.js
29
- var METHOD_NAME_ALL = "ALL";
30
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
31
- var UnsupportedPathError = class extends Error {
32
- };
33
-
34
- // ../../node_modules/.pnpm/hono@4.6.6/node_modules/hono/dist/utils/url.js
35
- var checkOptionalParameter = (path) => {
36
- if (!path.match(/\:.+\?$/)) {
37
- return null;
9
+ // src/fetch/composite-handler.ts
10
+ var CompositeHandler = class {
11
+ constructor(handlers) {
12
+ this.handlers = handlers;
38
13
  }
39
- const segments = path.split("/");
40
- const results = [];
41
- let basePath = "";
42
- segments.forEach((segment) => {
43
- if (segment !== "" && !/\:/.test(segment)) {
44
- basePath += "/" + segment;
45
- } else if (/\:/.test(segment)) {
46
- if (/\?/.test(segment)) {
47
- if (results.length === 0 && basePath === "") {
48
- results.push("/");
49
- } else {
50
- results.push(basePath);
51
- }
52
- const optionalSegment = segment.replace("?", "");
53
- basePath += "/" + optionalSegment;
54
- results.push(basePath);
55
- } else {
56
- basePath += "/" + segment;
14
+ async fetch(request, ...opt) {
15
+ for (const handler of this.handlers) {
16
+ if (handler.condition(request)) {
17
+ return handler.fetch(request, ...opt);
57
18
  }
58
19
  }
59
- });
60
- return results.filter((v, i, a) => a.indexOf(v) === i);
61
- };
62
-
63
- // ../../node_modules/.pnpm/hono@4.6.6/node_modules/hono/dist/router/linear-router/router.js
64
- var emptyParams = /* @__PURE__ */ Object.create(null);
65
- var splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/g;
66
- var splitByStarRe = /\*/;
67
- var LinearRouter = class {
68
- name = "LinearRouter";
69
- routes = [];
70
- add(method, path, handler) {
71
- ;
72
- (checkOptionalParameter(path) || [path]).forEach((p) => {
73
- this.routes.push([method, p, handler]);
20
+ return new Response("None of the handlers can handle the request.", {
21
+ status: 404
74
22
  });
75
23
  }
76
- match(method, path) {
77
- const handlers = [];
78
- ROUTES_LOOP:
79
- for (let i = 0, len = this.routes.length; i < len; i++) {
80
- const [routeMethod, routePath, handler] = this.routes[i];
81
- if (routeMethod !== method && routeMethod !== METHOD_NAME_ALL) {
82
- continue;
83
- }
84
- if (routePath === "*" || routePath === "/*") {
85
- handlers.push([handler, emptyParams]);
86
- continue;
87
- }
88
- const hasStar = routePath.indexOf("*") !== -1;
89
- const hasLabel = routePath.indexOf(":") !== -1;
90
- if (!hasStar && !hasLabel) {
91
- if (routePath === path || routePath + "/" === path) {
92
- handlers.push([handler, emptyParams]);
93
- }
94
- } else if (hasStar && !hasLabel) {
95
- const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42;
96
- const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe);
97
- const lastIndex = parts.length - 1;
98
- for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) {
99
- const part = parts[j];
100
- const index = path.indexOf(part, pos);
101
- if (index !== pos) {
102
- continue ROUTES_LOOP;
103
- }
104
- pos += part.length;
105
- if (j === lastIndex) {
106
- if (!endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
107
- continue ROUTES_LOOP;
108
- }
109
- } else {
110
- const index2 = path.indexOf("/", pos);
111
- if (index2 === -1) {
112
- continue ROUTES_LOOP;
113
- }
114
- pos = index2;
115
- }
116
- }
117
- handlers.push([handler, emptyParams]);
118
- } else if (hasLabel && !hasStar) {
119
- const params = /* @__PURE__ */ Object.create(null);
120
- const parts = routePath.match(splitPathRe);
121
- const lastIndex = parts.length - 1;
122
- for (let j = 0, pos = 0, len2 = parts.length; j < len2; j++) {
123
- if (pos === -1 || pos >= path.length) {
124
- continue ROUTES_LOOP;
125
- }
126
- const part = parts[j];
127
- if (part.charCodeAt(1) === 58) {
128
- let name = part.slice(2);
129
- let value2;
130
- if (name.charCodeAt(name.length - 1) === 125) {
131
- const openBracePos = name.indexOf("{");
132
- const pattern = name.slice(openBracePos + 1, -1);
133
- const restPath = path.slice(pos + 1);
134
- const match = new RegExp(pattern, "d").exec(restPath);
135
- if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) {
136
- continue ROUTES_LOOP;
137
- }
138
- name = name.slice(0, openBracePos);
139
- value2 = restPath.slice(...match.indices[0]);
140
- pos += match.indices[0][1] + 1;
141
- } else {
142
- let endValuePos = path.indexOf("/", pos + 1);
143
- if (endValuePos === -1) {
144
- if (pos + 1 === path.length) {
145
- continue ROUTES_LOOP;
146
- }
147
- endValuePos = path.length;
148
- }
149
- value2 = path.slice(pos + 1, endValuePos);
150
- pos = endValuePos;
151
- }
152
- params[name] ||= value2;
153
- } else {
154
- const index = path.indexOf(part, pos);
155
- if (index !== pos) {
156
- continue ROUTES_LOOP;
157
- }
158
- pos += part.length;
159
- }
160
- if (j === lastIndex) {
161
- if (pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {
162
- continue ROUTES_LOOP;
163
- }
164
- }
165
- }
166
- handlers.push([handler, params]);
167
- } else if (hasLabel && hasStar) {
168
- throw new UnsupportedPathError();
169
- }
170
- }
171
- return [handlers];
172
- }
173
24
  };
174
25
 
175
- // ../../node_modules/.pnpm/hono@4.6.6/node_modules/hono/dist/router/reg-exp-router/node.js
176
- var LABEL_REG_EXP_STR = "[^/]+";
177
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
178
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
179
- var PATH_ERROR = Symbol();
180
- var regExpMetaChars = new Set(".\\+*[^]$()");
181
- function compareKey(a, b) {
182
- if (a.length === 1) {
183
- return b.length === 1 ? a < b ? -1 : 1 : -1;
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 };
184
59
  }
185
- if (b.length === 1) {
186
- return 1;
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 };
187
64
  }
188
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
189
- return 1;
190
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
191
- return -1;
65
+ if (Number.isNaN(value)) {
66
+ meta.push(["nan", segments]);
67
+ return { data: "NaN", meta };
192
68
  }
193
- if (a === LABEL_REG_EXP_STR) {
194
- return 1;
195
- } else if (b === LABEL_REG_EXP_STR) {
196
- return -1;
69
+ if (value instanceof RegExp) {
70
+ meta.push(["regexp", segments]);
71
+ return { data: value.toString(), meta };
197
72
  }
198
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
199
- }
200
- var Node = class {
201
- index;
202
- varIndex;
203
- children = /* @__PURE__ */ Object.create(null);
204
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
205
- if (tokens.length === 0) {
206
- if (this.index !== void 0) {
207
- throw PATH_ERROR;
208
- }
209
- if (pathErrorCheckOnly) {
210
- return;
211
- }
212
- this.index = index;
213
- return;
214
- }
215
- const [token, ...restTokens] = tokens;
216
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
217
- let node;
218
- if (pattern) {
219
- const name = pattern[1];
220
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
221
- if (name && pattern[2]) {
222
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
223
- if (/\((?!\?:)/.test(regexpStr)) {
224
- throw PATH_ERROR;
225
- }
226
- }
227
- node = this.children[regexpStr];
228
- if (!node) {
229
- if (Object.keys(this.children).some(
230
- (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
231
- )) {
232
- throw PATH_ERROR;
233
- }
234
- if (pathErrorCheckOnly) {
235
- return;
236
- }
237
- node = this.children[regexpStr] = new Node();
238
- if (name !== "") {
239
- node.varIndex = context.varIndex++;
240
- }
241
- }
242
- if (!pathErrorCheckOnly && name !== "") {
243
- paramMap.push([name, node.varIndex]);
244
- }
245
- } else {
246
- node = this.children[token];
247
- if (!node) {
248
- if (Object.keys(this.children).some(
249
- (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
250
- )) {
251
- throw PATH_ERROR;
252
- }
253
- if (pathErrorCheckOnly) {
254
- return;
255
- }
256
- node = this.children[token] = new Node();
257
- }
258
- }
259
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
73
+ if (value instanceof URL) {
74
+ meta.push(["url", segments]);
75
+ return { data: value.toString(), meta };
260
76
  }
261
- buildRegExpStr() {
262
- const childKeys = Object.keys(this.children).sort(compareKey);
263
- const strList = childKeys.map((k) => {
264
- const c = this.children[k];
265
- return (typeof c.varIndex === "number" ? `(${k})@${c.varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
266
- });
267
- if (typeof this.index === "number") {
268
- strList.unshift(`#${this.index}`);
269
- }
270
- if (strList.length === 0) {
271
- return "";
77
+ if (isPlainObject(value)) {
78
+ const data = {};
79
+ for (const k in value) {
80
+ data[k] = serialize(value[k], [...segments, k], meta).data;
272
81
  }
273
- if (strList.length === 1) {
274
- return strList[0];
275
- }
276
- return "(?:" + strList.join("|") + ")";
82
+ return { data, meta };
277
83
  }
278
- };
279
-
280
- // ../../node_modules/.pnpm/hono@4.6.6/node_modules/hono/dist/router/reg-exp-router/trie.js
281
- var Trie = class {
282
- context = { varIndex: 0 };
283
- root = new Node();
284
- insert(path, index, pathErrorCheckOnly) {
285
- const paramAssoc = [];
286
- const groups = [];
287
- for (let i = 0; ; ) {
288
- let replaced = false;
289
- path = path.replace(/\{[^}]+\}/g, (m) => {
290
- const mark = `@\\${i}`;
291
- groups[i] = [mark, m];
292
- i++;
293
- replaced = true;
294
- return mark;
295
- });
296
- if (!replaced) {
297
- break;
298
- }
299
- }
300
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
301
- for (let i = groups.length - 1; i >= 0; i--) {
302
- const [mark] = groups[i];
303
- for (let j = tokens.length - 1; j >= 0; j--) {
304
- if (tokens[j].indexOf(mark) !== -1) {
305
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
306
- break;
307
- }
308
- }
309
- }
310
- this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly);
311
- return paramAssoc;
312
- }
313
- buildRegExp() {
314
- let regexp = this.root.buildRegExpStr();
315
- if (regexp === "") {
316
- return [/^$/, [], []];
317
- }
318
- let captureIndex = 0;
319
- const indexReplacementMap = [];
320
- const paramReplacementMap = [];
321
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
322
- if (typeof handlerIndex !== "undefined") {
323
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
324
- return "$()";
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;
325
89
  }
326
- if (typeof paramIndex !== "undefined") {
327
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
328
- return "";
329
- }
330
- return "";
90
+ return serialize(v, [...segments, i], meta).data;
331
91
  });
332
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
92
+ return { data, meta };
333
93
  }
334
- };
335
-
336
- // ../../node_modules/.pnpm/hono@4.6.6/node_modules/hono/dist/router/reg-exp-router/router.js
337
- var emptyParam = [];
338
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
339
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
340
- function buildWildcardRegExp(path) {
341
- return wildcardRegExpCache[path] ??= new RegExp(
342
- path === "*" ? "" : `^${path.replace(
343
- /\/\*$|([.\\+*[^\]$()])/g,
344
- (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
345
- )}$`
346
- );
347
- }
348
- function clearWildcardRegExpCache() {
349
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
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 };
350
105
  }
351
- function buildMatcherFromPreprocessedRoutes(routes) {
352
- const trie = new Trie();
353
- const handlerData = [];
354
- if (routes.length === 0) {
355
- return nullMatcher;
106
+ function deserialize({
107
+ data,
108
+ meta
109
+ }) {
110
+ if (meta.length === 0) {
111
+ return data;
356
112
  }
357
- const routesWithStaticPathFlag = routes.map(
358
- (route) => [!/\*|\/:/.test(route[0]), ...route]
359
- ).sort(
360
- ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
361
- );
362
- const staticMap = /* @__PURE__ */ Object.create(null);
363
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
364
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
365
- if (pathErrorCheckOnly) {
366
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
367
- } else {
368
- j++;
369
- }
370
- let paramAssoc;
371
- try {
372
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
373
- } catch (e) {
374
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
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];
375
120
  }
376
- if (pathErrorCheckOnly) {
377
- continue;
378
- }
379
- handlerData[j] = handlers.map(([h, paramCount]) => {
380
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
381
- paramCount -= 1;
382
- for (; paramCount >= 0; paramCount--) {
383
- const [key, value2] = paramAssoc[paramCount];
384
- paramIndexMap[key] = value2;
385
- }
386
- return [h, paramIndexMap];
387
- });
388
- }
389
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
390
- for (let i = 0, len = handlerData.length; i < len; i++) {
391
- for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
392
- const map = handlerData[i][j]?.[1];
393
- if (!map) {
394
- continue;
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;
395
135
  }
396
- const keys = Object.keys(map);
397
- for (let k = 0, len3 = keys.length; k < len3; k++) {
398
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
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;
399
151
  }
400
152
  }
401
153
  }
402
- const handlerMap = [];
403
- for (const i in indexReplacementMap) {
404
- handlerMap[i] = handlerData[indexReplacementMap[i]];
405
- }
406
- return [regexp, handlerMap, staticMap];
407
- }
408
- function findMiddleware(middleware, path) {
409
- if (!middleware) {
410
- return void 0;
411
- }
412
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
413
- if (buildWildcardRegExp(k).test(path)) {
414
- return [...middleware[k]];
415
- }
416
- }
417
- return void 0;
154
+ return ref.data;
418
155
  }
419
- var RegExpRouter = class {
420
- name = "RegExpRouter";
421
- middleware;
422
- routes;
423
- constructor() {
424
- this.middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
425
- this.routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
426
- }
427
- add(method, path, handler) {
428
- const { middleware, routes } = this;
429
- if (!middleware || !routes) {
430
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
431
- }
432
- if (!middleware[method]) {
433
- ;
434
- [middleware, routes].forEach((handlerMap) => {
435
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
436
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
437
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
438
- });
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)
439
170
  });
171
+ return {
172
+ query,
173
+ method: "GET"
174
+ };
440
175
  }
441
- if (path === "/*") {
442
- path = "*";
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
+ };
443
192
  }
444
- const paramCount = (path.match(/\/:/g) || []).length;
445
- if (/\*$/.test(path)) {
446
- const re = buildWildcardRegExp(path);
447
- if (method === METHOD_NAME_ALL) {
448
- Object.keys(middleware).forEach((m) => {
449
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
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
450
211
  });
451
- } else {
452
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
453
212
  }
454
- Object.keys(middleware).forEach((m) => {
455
- if (method === METHOD_NAME_ALL || method === m) {
456
- Object.keys(middleware[m]).forEach((p) => {
457
- re.test(p) && middleware[m][p].push([handler, paramCount]);
458
- });
459
- }
460
- });
461
- Object.keys(routes).forEach((m) => {
462
- if (method === METHOD_NAME_ALL || method === m) {
463
- Object.keys(routes[m]).forEach(
464
- (p) => re.test(p) && routes[m][p].push([handler, paramCount])
465
- );
466
- }
467
- });
468
- return;
469
- }
470
- const paths = checkOptionalParameter(path) || [path];
471
- for (let i = 0, len = paths.length; i < len; i++) {
472
- const path2 = paths[i];
473
- Object.keys(routes).forEach((m) => {
474
- if (method === METHOD_NAME_ALL || method === m) {
475
- routes[m][path2] ||= [
476
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
477
- ];
478
- routes[m][path2].push([handler, paramCount - len + i + 1]);
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));
479
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
480
236
  });
481
237
  }
482
238
  }
483
- match(method, path) {
484
- clearWildcardRegExpCache();
485
- const matchers = this.buildAllMatchers();
486
- this.match = (method2, path2) => {
487
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
488
- const staticMatch = matcher[2][path2];
489
- if (staticMatch) {
490
- return staticMatch;
491
- }
492
- const match = path2.match(matcher[0]);
493
- if (!match) {
494
- return [[], emptyParam];
495
- }
496
- const index = match.indexOf("", 1);
497
- return [matcher[1][index], match];
498
- };
499
- return this.match(method, path);
500
- }
501
- buildAllMatchers() {
502
- const matchers = /* @__PURE__ */ Object.create(null);
503
- [...Object.keys(this.routes), ...Object.keys(this.middleware)].forEach((method) => {
504
- matchers[method] ||= this.buildMatcher(method);
505
- });
506
- this.middleware = this.routes = void 0;
507
- return matchers;
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;
508
246
  }
509
- buildMatcher(method) {
510
- const routes = [];
511
- let hasOwnRoute = method === METHOD_NAME_ALL;
512
- [this.middleware, this.routes].forEach((r) => {
513
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
514
- if (ownRoute.length !== 0) {
515
- hasOwnRoute ||= true;
516
- routes.push(...ownRoute);
517
- } else if (method !== METHOD_NAME_ALL) {
518
- routes.push(
519
- ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
520
- );
521
- }
522
- });
523
- if (!hasOwnRoute) {
524
- return null;
525
- } else {
526
- return buildMatcherFromPreprocessedRoutes(routes);
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;
527
253
  }
254
+ return {
255
+ procedure: maybeProcedure,
256
+ path
257
+ };
528
258
  }
529
259
  };
530
260
 
531
- // src/adapters/fetch.ts
532
- function createFetchHandler(options) {
533
- const routing = options.serverless ? new LinearRouter() : new RegExpRouter();
534
- const addRouteRecursively = (router, basePath) => {
535
- for (const key in router) {
536
- const currentPath = [...basePath, key];
537
- const item = router[key];
538
- if (isProcedure(item)) {
539
- if (item.zz$p.contract.zz$cp.path) {
540
- const method = item.zz$p.contract.zz$cp.method ?? "POST";
541
- const path = openAPIPathToRouterPath(item.zz$p.contract.zz$cp.path);
542
- routing.add(method, path, [currentPath, item]);
543
- }
544
- } else {
545
- addRouteRecursively(item, currentPath);
546
- }
547
- }
548
- };
549
- addRouteRecursively(options.router, []);
550
- return async (requestOptions) => {
551
- const isORPCTransformer = requestOptions.request.headers.get(ORPC_HEADER) === ORPC_HEADER_VALUE;
552
- const accept = requestOptions.request.headers.get("Accept") || void 0;
553
- const serializer = isORPCTransformer ? new ORPCSerializer() : new OpenAPISerializer({ accept });
554
- const context = await value(requestOptions.context);
555
- const handler = async () => {
556
- const url = new URL(requestOptions.request.url);
557
- const pathname = `/${trim(url.pathname.replace(requestOptions.prefix ?? "", ""), "/")}`;
558
- let path;
559
- let procedure;
560
- let params;
561
- if (isORPCTransformer) {
562
- path = trim(pathname, "/").split("/").map(decodeURIComponent);
563
- const val = get(options.router, path);
564
- if (isProcedure(val)) {
565
- procedure = val;
566
- }
567
- } else {
568
- const customMethod = requestOptions.request.method === "POST" ? url.searchParams.get("method")?.toUpperCase() : void 0;
569
- const method = customMethod || requestOptions.request.method;
570
- const [matches, params_] = routing.match(method, pathname);
571
- const [match] = matches.sort((a, b) => {
572
- return Object.keys(a[1]).length - Object.keys(b[1]).length;
573
- });
574
- if (match) {
575
- path = match[0][0];
576
- procedure = match[0][1];
577
- if (params_) {
578
- params = mapValues(
579
- match[1],
580
- (v) => params_[v]
581
- );
582
- } else {
583
- params = match[1];
584
- }
585
- }
586
- if (!path || !procedure) {
587
- path = trim(pathname, "/").split("/").map(decodeURIComponent);
588
- const val = get(options.router, path);
589
- if (isProcedure(val)) {
590
- procedure = val;
591
- }
592
- }
593
- }
594
- if (!path || !procedure) {
595
- throw new ORPCError({ code: "NOT_FOUND", message: "Not found" });
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" });
596
282
  }
597
- const deserializer = isORPCTransformer ? new ORPCDeserializer() : new OpenAPIDeserializer({
598
- schema: procedure.zz$p.contract.zz$cp.InputSchema
599
- });
600
- const input_ = await (async () => {
601
- try {
602
- return await deserializer.deserialize(requestOptions.request);
603
- } catch (e) {
604
- throw new ORPCError({
605
- code: "BAD_REQUEST",
606
- message: "Cannot parse request. Please check the request body and Content-Type header.",
607
- cause: e
608
- });
609
- }
610
- })();
611
- const input = (() => {
612
- if (!params || Object.keys(params).length === 0) {
613
- return input_;
614
- }
615
- const coercedParams = procedure.zz$p.contract.zz$cp.InputSchema ? zodCoerce(
616
- procedure.zz$p.contract.zz$cp.InputSchema,
617
- { ...params },
618
- {
619
- bracketNotation: true
620
- }
621
- ) : params;
622
- if (!isPlainObject(input_)) {
623
- return coercedParams;
624
- }
625
- return {
626
- ...coercedParams,
627
- ...input_
628
- };
629
- })();
630
- const caller = createProcedureCaller({
283
+ const input = await this.payloadCodec.decode(request);
284
+ const client = createProcedureClient({
631
285
  context,
632
- procedure,
633
- path
634
- });
635
- const output = await caller(input);
636
- const { body, headers } = serializer.serialize(output);
637
- return new Response(body, {
638
- status: 200,
639
- headers
286
+ procedure: match.procedure,
287
+ path: match.path
640
288
  });
289
+ const output = await client(input, { signal: options?.signal });
290
+ const { body, headers } = this.payloadCodec.encode(output);
291
+ return new Response(body, { headers });
641
292
  };
642
293
  try {
643
- return await options.hooks?.(context, {
644
- next: handler,
645
- response: (response) => response
646
- }) ?? await handler();
294
+ return await executeWithHooks({
295
+ context,
296
+ execute,
297
+ input: request,
298
+ hooks: this.options,
299
+ meta: {
300
+ signal: options?.signal
301
+ }
302
+ });
647
303
  } catch (e) {
648
- const error = toORPCError(e);
649
- try {
650
- const { body, headers } = serializer.serialize(error.toJSON());
651
- return new Response(body, {
652
- status: error.status,
653
- headers
654
- });
655
- } catch (e2) {
656
- const error2 = toORPCError(e2);
657
- const { body, headers } = new OpenAPISerializer().serialize(
658
- error2.toJSON()
659
- );
660
- return new Response(body, {
661
- status: error2.status,
662
- headers
663
- });
664
- }
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
+ });
665
314
  }
666
- };
667
- }
668
- function openAPIPathToRouterPath(path) {
669
- return standardizeHTTPPath(path).replace(/\{([^}]+)\}/g, ":$1");
670
- }
671
- function toORPCError(e) {
672
- return e instanceof ORPCError ? e : new ORPCError({
673
- code: "INTERNAL_SERVER_ERROR",
674
- message: "Internal server error",
675
- cause: e
676
- });
677
- }
315
+ }
316
+ };
678
317
  export {
679
- createFetchHandler
318
+ CompositeHandler,
319
+ ORPCHandler,
320
+ ORPCPayloadCodec,
321
+ ORPCProcedureMatcher,
322
+ super_json_exports as SuperJSON
680
323
  };
681
324
  //# sourceMappingURL=fetch.js.map