@orpc/server 0.0.0-next.c59d67c → 0.0.0-next.cba521d

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 (51) hide show
  1. package/dist/chunk-3EVCPLVI.js +301 -0
  2. package/dist/chunk-OUPZ7QGV.js +245 -0
  3. package/dist/chunk-WUOGVGWG.js +1 -0
  4. package/dist/fetch.js +11 -102
  5. package/dist/hono.js +30 -0
  6. package/dist/index.js +442 -274
  7. package/dist/next.js +36 -0
  8. package/dist/node.js +87 -0
  9. package/dist/src/adapters/fetch/index.d.ts +6 -0
  10. package/dist/src/adapters/fetch/orpc-handler.d.ts +20 -0
  11. package/dist/src/adapters/fetch/orpc-payload-codec.d.ts +16 -0
  12. package/dist/src/adapters/fetch/orpc-procedure-matcher.d.ts +12 -0
  13. package/dist/src/adapters/fetch/super-json.d.ts +12 -0
  14. package/dist/src/adapters/fetch/types.d.ts +21 -0
  15. package/dist/src/adapters/hono/index.d.ts +3 -0
  16. package/dist/src/adapters/hono/middleware.d.ts +12 -0
  17. package/dist/src/adapters/next/index.d.ts +3 -0
  18. package/dist/src/adapters/next/serve.d.ts +19 -0
  19. package/dist/src/adapters/node/index.d.ts +5 -0
  20. package/dist/src/adapters/node/orpc-handler.d.ts +12 -0
  21. package/dist/src/adapters/node/request-listener.d.ts +28 -0
  22. package/dist/src/adapters/node/types.d.ts +22 -0
  23. package/dist/src/builder.d.ts +30 -43
  24. package/dist/src/error.d.ts +10 -0
  25. package/dist/src/hidden.d.ts +6 -0
  26. package/dist/src/implementer-chainable.d.ts +10 -0
  27. package/dist/src/index.d.ts +14 -4
  28. package/dist/src/lazy-decorated.d.ts +7 -0
  29. package/dist/src/lazy-utils.d.ts +4 -0
  30. package/dist/src/lazy.d.ts +18 -0
  31. package/dist/src/middleware-decorated.d.ts +9 -0
  32. package/dist/src/middleware.d.ts +22 -12
  33. package/dist/src/procedure-builder.d.ts +19 -26
  34. package/dist/src/procedure-client.d.ts +22 -0
  35. package/dist/src/procedure-decorated.d.ts +26 -0
  36. package/dist/src/procedure-implementer.d.ts +17 -15
  37. package/dist/src/procedure-utils.d.ts +17 -0
  38. package/dist/src/procedure.d.ts +40 -25
  39. package/dist/src/router-builder.d.ts +24 -17
  40. package/dist/src/router-client.d.ts +26 -0
  41. package/dist/src/router-implementer.d.ts +18 -17
  42. package/dist/src/router.d.ts +11 -15
  43. package/dist/src/types.d.ts +10 -4
  44. package/package.json +22 -11
  45. package/dist/chunk-TDFYNRZV.js +0 -190
  46. package/dist/src/fetch/handle.d.ts +0 -7
  47. package/dist/src/fetch/handler.d.ts +0 -3
  48. package/dist/src/fetch/index.d.ts +0 -4
  49. package/dist/src/fetch/types.d.ts +0 -35
  50. package/dist/src/procedure-caller.d.ts +0 -19
  51. package/dist/src/router-caller.d.ts +0 -22
@@ -0,0 +1,301 @@
1
+ import {
2
+ __export,
3
+ createProcedureClient,
4
+ getRouterChild,
5
+ isProcedure,
6
+ unlazy
7
+ } from "./chunk-OUPZ7QGV.js";
8
+
9
+ // src/adapters/fetch/super-json.ts
10
+ var super_json_exports = {};
11
+ __export(super_json_exports, {
12
+ deserialize: () => deserialize,
13
+ serialize: () => serialize
14
+ });
15
+
16
+ // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/getType.js
17
+ function getType(payload) {
18
+ return Object.prototype.toString.call(payload).slice(8, -1);
19
+ }
20
+
21
+ // ../../node_modules/.pnpm/is-what@5.0.2/node_modules/is-what/dist/isPlainObject.js
22
+ function isPlainObject(payload) {
23
+ if (getType(payload) !== "Object")
24
+ return false;
25
+ const prototype = Object.getPrototypeOf(payload);
26
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
27
+ }
28
+
29
+ // src/adapters/fetch/super-json.ts
30
+ function serialize(value, segments = [], meta = []) {
31
+ if (typeof value === "bigint") {
32
+ meta.push(["bigint", segments]);
33
+ return { data: value.toString(), meta };
34
+ }
35
+ if (value instanceof Date) {
36
+ meta.push(["date", segments]);
37
+ const data = Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
38
+ return { data, meta };
39
+ }
40
+ if (Number.isNaN(value)) {
41
+ meta.push(["nan", segments]);
42
+ return { data: "NaN", meta };
43
+ }
44
+ if (value instanceof RegExp) {
45
+ meta.push(["regexp", segments]);
46
+ return { data: value.toString(), meta };
47
+ }
48
+ if (value instanceof URL) {
49
+ meta.push(["url", segments]);
50
+ return { data: value.toString(), meta };
51
+ }
52
+ if (isPlainObject(value)) {
53
+ const data = {};
54
+ for (const k in value) {
55
+ data[k] = serialize(value[k], [...segments, k], meta).data;
56
+ }
57
+ return { data, meta };
58
+ }
59
+ if (Array.isArray(value)) {
60
+ const data = value.map((v, i) => {
61
+ if (v === void 0) {
62
+ meta.push(["undefined", [...segments, i]]);
63
+ return null;
64
+ }
65
+ return serialize(v, [...segments, i], meta).data;
66
+ });
67
+ return { data, meta };
68
+ }
69
+ if (value instanceof Set) {
70
+ const result = serialize(Array.from(value), segments, meta);
71
+ meta.push(["set", segments]);
72
+ return result;
73
+ }
74
+ if (value instanceof Map) {
75
+ const result = serialize(Array.from(value.entries()), segments, meta);
76
+ meta.push(["map", segments]);
77
+ return result;
78
+ }
79
+ return { data: value, meta };
80
+ }
81
+ function deserialize({
82
+ data,
83
+ meta
84
+ }) {
85
+ if (meta.length === 0) {
86
+ return data;
87
+ }
88
+ const ref = { data };
89
+ for (const [type, segments] of meta) {
90
+ let currentRef = ref;
91
+ let preSegment = "data";
92
+ for (let i = 0; i < segments.length; i++) {
93
+ currentRef = currentRef[preSegment];
94
+ preSegment = segments[i];
95
+ }
96
+ switch (type) {
97
+ case "nan":
98
+ currentRef[preSegment] = Number.NaN;
99
+ break;
100
+ case "bigint":
101
+ currentRef[preSegment] = BigInt(currentRef[preSegment]);
102
+ break;
103
+ case "date":
104
+ currentRef[preSegment] = new Date(currentRef[preSegment]);
105
+ break;
106
+ case "regexp": {
107
+ const [, pattern, flags] = currentRef[preSegment].match(/^\/(.*)\/([a-z]*)$/);
108
+ currentRef[preSegment] = new RegExp(pattern, flags);
109
+ break;
110
+ }
111
+ case "url":
112
+ currentRef[preSegment] = new URL(currentRef[preSegment]);
113
+ break;
114
+ case "undefined":
115
+ currentRef[preSegment] = void 0;
116
+ break;
117
+ case "map":
118
+ currentRef[preSegment] = new Map(currentRef[preSegment]);
119
+ break;
120
+ case "set":
121
+ currentRef[preSegment] = new Set(currentRef[preSegment]);
122
+ break;
123
+ /* v8 ignore next 3 */
124
+ default: {
125
+ const _expected = type;
126
+ }
127
+ }
128
+ }
129
+ return ref.data;
130
+ }
131
+
132
+ // src/adapters/fetch/orpc-payload-codec.ts
133
+ import { ORPCError } from "@orpc/contract";
134
+ import { findDeepMatches, set } from "@orpc/shared";
135
+ var ORPCPayloadCodec = class {
136
+ /**
137
+ * If method is GET, the payload will be encoded as query string.
138
+ * If method is GET and payload contain file, the method will be fallback to fallbackMethod. (fallbackMethod = GET will force to use GET method)
139
+ */
140
+ encode(payload, method = "POST", fallbackMethod = "POST") {
141
+ const { data, meta } = serialize(payload);
142
+ const { maps, values } = findDeepMatches((v) => v instanceof Blob, data);
143
+ if (method === "GET" && (values.length === 0 || fallbackMethod === "GET")) {
144
+ const query = new URLSearchParams({
145
+ data: JSON.stringify(data),
146
+ meta: JSON.stringify(meta)
147
+ });
148
+ return {
149
+ query,
150
+ method: "GET"
151
+ };
152
+ }
153
+ const nonGETMethod = method === "GET" ? fallbackMethod : method;
154
+ if (values.length > 0) {
155
+ const form = new FormData();
156
+ if (data !== void 0) {
157
+ form.append("data", JSON.stringify(data));
158
+ }
159
+ form.append("meta", JSON.stringify(meta));
160
+ form.append("maps", JSON.stringify(maps));
161
+ for (const i in values) {
162
+ const value = values[i];
163
+ form.append(i, value);
164
+ }
165
+ return {
166
+ body: form,
167
+ method: nonGETMethod
168
+ };
169
+ }
170
+ return {
171
+ body: JSON.stringify({ data, meta }),
172
+ headers: new Headers({
173
+ "content-type": "application/json"
174
+ }),
175
+ method: nonGETMethod
176
+ };
177
+ }
178
+ async decode(re) {
179
+ try {
180
+ if ("method" in re && re.method === "GET") {
181
+ const url = new URL(re.url);
182
+ const query = url.searchParams;
183
+ const data = JSON.parse(query.getAll("data").at(-1));
184
+ const meta = JSON.parse(query.getAll("meta").at(-1));
185
+ return deserialize({
186
+ data,
187
+ meta
188
+ });
189
+ }
190
+ if (re.headers.get("content-type")?.startsWith("multipart/form-data")) {
191
+ const form = await re.formData();
192
+ const rawData = form.get("data");
193
+ const rawMeta = form.get("meta");
194
+ const rawMaps = form.get("maps");
195
+ let data = JSON.parse(rawData);
196
+ const meta = JSON.parse(rawMeta);
197
+ const maps = JSON.parse(rawMaps);
198
+ for (const i in maps) {
199
+ data = set(data, maps[i], form.get(i));
200
+ }
201
+ return deserialize({
202
+ data,
203
+ meta
204
+ });
205
+ }
206
+ const json = await re.json();
207
+ return deserialize(json);
208
+ } catch (e) {
209
+ throw new ORPCError({
210
+ code: "BAD_REQUEST",
211
+ message: "Cannot parse request/response. Please check the request/response body and Content-Type header.",
212
+ cause: e
213
+ });
214
+ }
215
+ }
216
+ };
217
+
218
+ // src/adapters/fetch/orpc-procedure-matcher.ts
219
+ import { trim } from "@orpc/shared";
220
+ var ORPCProcedureMatcher = class {
221
+ constructor(router) {
222
+ this.router = router;
223
+ }
224
+ async match(pathname) {
225
+ const path = trim(pathname, "/").split("/").map(decodeURIComponent);
226
+ const match = getRouterChild(this.router, ...path);
227
+ const { default: maybeProcedure } = await unlazy(match);
228
+ if (!isProcedure(maybeProcedure)) {
229
+ return void 0;
230
+ }
231
+ return {
232
+ procedure: maybeProcedure,
233
+ path
234
+ };
235
+ }
236
+ };
237
+
238
+ // src/adapters/fetch/orpc-handler.ts
239
+ import { ORPCError as ORPCError2 } from "@orpc/contract";
240
+ import { executeWithHooks, trim as trim2 } from "@orpc/shared";
241
+ var RPCHandler = class {
242
+ constructor(router, options) {
243
+ this.options = options;
244
+ this.procedureMatcher = options?.procedureMatcher ?? new ORPCProcedureMatcher(router);
245
+ this.payloadCodec = options?.payloadCodec ?? new ORPCPayloadCodec();
246
+ }
247
+ procedureMatcher;
248
+ payloadCodec;
249
+ async handle(request, ...[options]) {
250
+ const context = options?.context;
251
+ const execute = async () => {
252
+ const url = new URL(request.url);
253
+ const pathname = `/${trim2(url.pathname.replace(options?.prefix ?? "", ""), "/")}`;
254
+ const match = await this.procedureMatcher.match(pathname);
255
+ if (!match) {
256
+ return { matched: false, response: void 0 };
257
+ }
258
+ const input = await this.payloadCodec.decode(request);
259
+ const client = createProcedureClient(match.procedure, {
260
+ context,
261
+ path: match.path
262
+ });
263
+ const output = await client(input, { signal: request.signal });
264
+ const { body, headers } = this.payloadCodec.encode(output);
265
+ const response = new Response(body, { headers });
266
+ return { matched: true, response };
267
+ };
268
+ try {
269
+ const result = await executeWithHooks({
270
+ context,
271
+ execute,
272
+ input: request,
273
+ hooks: this.options,
274
+ meta: {
275
+ signal: request.signal
276
+ }
277
+ });
278
+ return result;
279
+ } catch (e) {
280
+ const error = e instanceof ORPCError2 ? e : new ORPCError2({
281
+ code: "INTERNAL_SERVER_ERROR",
282
+ message: "Internal server error",
283
+ cause: e
284
+ });
285
+ const { body, headers } = this.payloadCodec.encode(error.toJSON());
286
+ const response = new Response(body, {
287
+ headers,
288
+ status: error.status
289
+ });
290
+ return { matched: true, response };
291
+ }
292
+ }
293
+ };
294
+
295
+ export {
296
+ super_json_exports,
297
+ ORPCPayloadCodec,
298
+ ORPCProcedureMatcher,
299
+ RPCHandler
300
+ };
301
+ //# sourceMappingURL=chunk-3EVCPLVI.js.map
@@ -0,0 +1,245 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/utils.ts
8
+ function mergeContext(a, b) {
9
+ if (!a)
10
+ return b;
11
+ if (!b)
12
+ return a;
13
+ return {
14
+ ...a,
15
+ ...b
16
+ };
17
+ }
18
+
19
+ // src/procedure.ts
20
+ import { isContractProcedure } from "@orpc/contract";
21
+ var Procedure = class {
22
+ "~type" = "Procedure";
23
+ "~orpc";
24
+ constructor(def) {
25
+ this["~orpc"] = def;
26
+ }
27
+ };
28
+ function isProcedure(item) {
29
+ if (item instanceof Procedure) {
30
+ return true;
31
+ }
32
+ return (typeof item === "object" || typeof item === "function") && item !== null && "~type" in item && item["~type"] === "Procedure" && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "contract" in item["~orpc"] && isContractProcedure(item["~orpc"].contract) && "handler" in item["~orpc"] && typeof item["~orpc"].handler === "function";
33
+ }
34
+
35
+ // src/error.ts
36
+ import { ORPCError } from "@orpc/contract";
37
+ function createORPCErrorConstructorMap(errors) {
38
+ const constructors = {};
39
+ if (!errors) {
40
+ return constructors;
41
+ }
42
+ for (const code in errors) {
43
+ const config = errors[code];
44
+ if (!config) {
45
+ continue;
46
+ }
47
+ const constructor = (...[options]) => {
48
+ return new ORPCError({
49
+ code,
50
+ defined: true,
51
+ status: config.status,
52
+ message: options?.message ?? config.message,
53
+ data: options?.data,
54
+ cause: options?.cause
55
+ });
56
+ };
57
+ constructors[code] = constructor;
58
+ }
59
+ return constructors;
60
+ }
61
+
62
+ // src/lazy.ts
63
+ var LAZY_LOADER_SYMBOL = Symbol("ORPC_LAZY_LOADER");
64
+ function lazy(loader) {
65
+ return {
66
+ [LAZY_LOADER_SYMBOL]: loader
67
+ };
68
+ }
69
+ function isLazy(item) {
70
+ return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_LOADER_SYMBOL in item && typeof item[LAZY_LOADER_SYMBOL] === "function";
71
+ }
72
+ function unlazy(lazied) {
73
+ return isLazy(lazied) ? lazied[LAZY_LOADER_SYMBOL]() : Promise.resolve({ default: lazied });
74
+ }
75
+ function flatLazy(lazied) {
76
+ const flattenLoader = async () => {
77
+ let current = await unlazy(lazied);
78
+ while (true) {
79
+ if (!isLazy(current.default)) {
80
+ break;
81
+ }
82
+ current = await unlazy(current.default);
83
+ }
84
+ return current;
85
+ };
86
+ return lazy(flattenLoader);
87
+ }
88
+
89
+ // src/middleware.ts
90
+ function middlewareOutputFn(output) {
91
+ return { output, context: void 0 };
92
+ }
93
+
94
+ // src/procedure-client.ts
95
+ import { ORPCError as ORPCError2, validateORPCError, ValidationError } from "@orpc/contract";
96
+ import { executeWithHooks, toError, value } from "@orpc/shared";
97
+ function createProcedureClient(lazyableProcedure, ...[options]) {
98
+ return async (...[input, callerOptions]) => {
99
+ const path = options?.path ?? [];
100
+ const { default: procedure } = await unlazy(lazyableProcedure);
101
+ const context = await value(options?.context, callerOptions?.context);
102
+ const errors = createORPCErrorConstructorMap(procedure["~orpc"].contract["~orpc"].errorMap);
103
+ const executeOptions = {
104
+ input,
105
+ context,
106
+ errors,
107
+ path,
108
+ procedure,
109
+ signal: callerOptions?.signal
110
+ };
111
+ try {
112
+ const output = await executeWithHooks({
113
+ hooks: options,
114
+ input,
115
+ context,
116
+ meta: executeOptions,
117
+ execute: () => executeProcedureInternal(procedure, executeOptions)
118
+ });
119
+ return output;
120
+ } catch (e) {
121
+ if (!(e instanceof ORPCError2)) {
122
+ throw toError(e);
123
+ }
124
+ const validated = await validateORPCError(procedure["~orpc"].contract["~orpc"].errorMap, e);
125
+ throw validated;
126
+ }
127
+ };
128
+ }
129
+ async function validateInput(procedure, input) {
130
+ const schema = procedure["~orpc"].contract["~orpc"].InputSchema;
131
+ if (!schema)
132
+ return input;
133
+ const result = await schema["~standard"].validate(input);
134
+ if (result.issues) {
135
+ throw new ORPCError2({
136
+ message: "Input validation failed",
137
+ code: "BAD_REQUEST",
138
+ data: {
139
+ issues: result.issues
140
+ },
141
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
142
+ });
143
+ }
144
+ return result.value;
145
+ }
146
+ async function validateOutput(procedure, output) {
147
+ const schema = procedure["~orpc"].contract["~orpc"].OutputSchema;
148
+ if (!schema)
149
+ return output;
150
+ const result = await schema["~standard"].validate(output);
151
+ if (result.issues) {
152
+ throw new ORPCError2({
153
+ message: "Output validation failed",
154
+ code: "INTERNAL_SERVER_ERROR",
155
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
156
+ });
157
+ }
158
+ return result.value;
159
+ }
160
+ function executeMiddlewareChain(middlewares, opt, input) {
161
+ let currentIndex = 0;
162
+ let currentContext = opt.context;
163
+ const executeMiddlewareChain2 = async (nextOptions) => {
164
+ const mid = middlewares[currentIndex];
165
+ currentIndex += 1;
166
+ currentContext = mergeContext(currentContext, nextOptions.context);
167
+ if (mid) {
168
+ return await mid({ ...opt, context: currentContext, next: executeMiddlewareChain2 }, input, middlewareOutputFn);
169
+ }
170
+ return opt.next({ context: currentContext });
171
+ };
172
+ return executeMiddlewareChain2({});
173
+ }
174
+ async function executeProcedureInternal(procedure, options) {
175
+ const executeHandler = async (context, input) => {
176
+ return await procedure["~orpc"].handler({ ...options, context, input });
177
+ };
178
+ const executePostMiddlewares = async (context, input) => {
179
+ const validatedInput = await validateInput(procedure, input);
180
+ const result2 = await executeMiddlewareChain(procedure["~orpc"].postMiddlewares, {
181
+ ...options,
182
+ context,
183
+ next: async ({ context: context2 }) => {
184
+ return middlewareOutputFn(
185
+ await executeHandler(context2, validatedInput)
186
+ );
187
+ }
188
+ }, validatedInput);
189
+ const validatedOutput = await validateOutput(procedure, result2.output);
190
+ return { ...result2, output: validatedOutput };
191
+ };
192
+ const result = await executeMiddlewareChain(procedure["~orpc"].preMiddlewares, {
193
+ ...options,
194
+ context: options.context,
195
+ next: ({ context }) => executePostMiddlewares(context, options.input)
196
+ }, options.input);
197
+ return result.output;
198
+ }
199
+
200
+ // src/router.ts
201
+ function getRouterChild(router, ...path) {
202
+ let current = router;
203
+ for (let i = 0; i < path.length; i++) {
204
+ const segment = path[i];
205
+ if (!current) {
206
+ return void 0;
207
+ }
208
+ if (isProcedure(current)) {
209
+ return void 0;
210
+ }
211
+ if (!isLazy(current)) {
212
+ current = current[segment];
213
+ continue;
214
+ }
215
+ const lazied = current;
216
+ const rest = path.slice(i);
217
+ const newLazy = lazy(async () => {
218
+ const unwrapped = await unlazy(lazied);
219
+ if (!unwrapped.default) {
220
+ return unwrapped;
221
+ }
222
+ const next = getRouterChild(unwrapped.default, ...rest);
223
+ return { default: next };
224
+ });
225
+ return flatLazy(newLazy);
226
+ }
227
+ return current;
228
+ }
229
+
230
+ export {
231
+ __export,
232
+ mergeContext,
233
+ Procedure,
234
+ isProcedure,
235
+ createORPCErrorConstructorMap,
236
+ LAZY_LOADER_SYMBOL,
237
+ lazy,
238
+ isLazy,
239
+ unlazy,
240
+ flatLazy,
241
+ middlewareOutputFn,
242
+ createProcedureClient,
243
+ getRouterChild
244
+ };
245
+ //# sourceMappingURL=chunk-OUPZ7QGV.js.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-WUOGVGWG.js.map
package/dist/fetch.js CHANGED
@@ -1,106 +1,15 @@
1
+ import "./chunk-WUOGVGWG.js";
1
2
  import {
2
- createProcedureCaller,
3
- isProcedure
4
- } from "./chunk-TDFYNRZV.js";
5
-
6
- // src/fetch/handle.ts
7
- import { ORPCError } from "@orpc/shared/error";
8
- async function handleFetchRequest(options) {
9
- for (const handler of options.handlers) {
10
- const response = await handler(options);
11
- if (response) {
12
- return response;
13
- }
14
- }
15
- const error = new ORPCError({ code: "NOT_FOUND", message: "Not found" });
16
- return new Response(JSON.stringify(error.toJSON()), {
17
- status: error.status,
18
- headers: {
19
- "Content-Type": "application/json"
20
- }
21
- });
22
- }
23
-
24
- // src/fetch/handler.ts
25
- import { ORPC_HEADER, ORPC_HEADER_VALUE } from "@orpc/contract";
26
- import { trim, value } from "@orpc/shared";
27
- import { ORPCError as ORPCError2 } from "@orpc/shared/error";
28
- import { ORPCDeserializer, ORPCSerializer } from "@orpc/transformer";
29
- var serializer = new ORPCSerializer();
30
- var deserializer = new ORPCDeserializer();
31
- function createORPCHandler() {
32
- return async (options) => {
33
- if (options.request.headers.get(ORPC_HEADER) !== ORPC_HEADER_VALUE) {
34
- return void 0;
35
- }
36
- const context = await value(options.context);
37
- const handler = async () => {
38
- const url = new URL(options.request.url);
39
- const pathname = `/${trim(url.pathname.replace(options.prefix ?? "", ""), "/")}`;
40
- const match = resolveORPCRouter(options.router, pathname);
41
- if (!match) {
42
- throw new ORPCError2({ code: "NOT_FOUND", message: "Not found" });
43
- }
44
- const input = await deserializeRequest(options.request);
45
- const caller = createProcedureCaller({
46
- context,
47
- procedure: match.procedure,
48
- path: match.path
49
- });
50
- const output = await caller(input);
51
- const { body, headers } = serializer.serialize(output);
52
- return new Response(body, {
53
- status: 200,
54
- headers
55
- });
56
- };
57
- try {
58
- return await options.hooks?.(
59
- context,
60
- { next: handler, response: (response) => response }
61
- ) ?? await handler();
62
- } catch (e) {
63
- const error = e instanceof ORPCError2 ? e : new ORPCError2({
64
- code: "INTERNAL_SERVER_ERROR",
65
- message: "Internal server error",
66
- cause: e
67
- });
68
- const { body, headers } = serializer.serialize(error.toJSON());
69
- return new Response(body, {
70
- status: error.status,
71
- headers
72
- });
73
- }
74
- };
75
- }
76
- function resolveORPCRouter(router, pathname) {
77
- const path = trim(pathname, "/").split("/").map(decodeURIComponent);
78
- let current = router;
79
- for (const segment of path) {
80
- if ((typeof current !== "object" || current === null) && typeof current !== "function") {
81
- current = void 0;
82
- break;
83
- }
84
- current = current[segment];
85
- }
86
- return isProcedure(current) ? {
87
- procedure: current,
88
- path
89
- } : void 0;
90
- }
91
- async function deserializeRequest(request) {
92
- try {
93
- return await deserializer.deserialize(request);
94
- } catch (e) {
95
- throw new ORPCError2({
96
- code: "BAD_REQUEST",
97
- message: "Cannot parse request. Please check the request body and Content-Type header.",
98
- cause: e
99
- });
100
- }
101
- }
3
+ ORPCPayloadCodec,
4
+ ORPCProcedureMatcher,
5
+ RPCHandler,
6
+ super_json_exports
7
+ } from "./chunk-3EVCPLVI.js";
8
+ import "./chunk-OUPZ7QGV.js";
102
9
  export {
103
- createORPCHandler,
104
- handleFetchRequest
10
+ ORPCPayloadCodec,
11
+ ORPCProcedureMatcher,
12
+ RPCHandler,
13
+ super_json_exports as SuperJSON
105
14
  };
106
15
  //# sourceMappingURL=fetch.js.map
package/dist/hono.js ADDED
@@ -0,0 +1,30 @@
1
+ import "./chunk-WUOGVGWG.js";
2
+ import {
3
+ ORPCPayloadCodec,
4
+ ORPCProcedureMatcher,
5
+ RPCHandler,
6
+ super_json_exports
7
+ } from "./chunk-3EVCPLVI.js";
8
+ import "./chunk-OUPZ7QGV.js";
9
+
10
+ // src/adapters/hono/middleware.ts
11
+ import { value } from "@orpc/shared";
12
+ function createMiddleware(handler, ...[options]) {
13
+ return async (c, next) => {
14
+ const context = await value(options?.context, c);
15
+ const { matched, response } = await handler.handle(c.req.raw, { ...options, context });
16
+ if (matched) {
17
+ c.res = response;
18
+ return;
19
+ }
20
+ await next();
21
+ };
22
+ }
23
+ export {
24
+ ORPCPayloadCodec,
25
+ ORPCProcedureMatcher,
26
+ RPCHandler,
27
+ super_json_exports as SuperJSON,
28
+ createMiddleware
29
+ };
30
+ //# sourceMappingURL=hono.js.map