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