@orpc/server 0.0.0

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