@orpc/server 0.0.0-next.93e7a4c → 0.0.0-next.9486ab5

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 (65) hide show
  1. package/README.md +131 -0
  2. package/dist/adapters/fetch/index.d.mts +54 -0
  3. package/dist/adapters/fetch/index.d.ts +54 -0
  4. package/dist/adapters/fetch/index.mjs +9 -0
  5. package/dist/adapters/hono/index.d.mts +22 -0
  6. package/dist/adapters/hono/index.d.ts +22 -0
  7. package/dist/adapters/hono/index.mjs +32 -0
  8. package/dist/adapters/next/index.d.mts +29 -0
  9. package/dist/adapters/next/index.d.ts +29 -0
  10. package/dist/adapters/next/index.mjs +29 -0
  11. package/dist/adapters/node/index.d.mts +53 -0
  12. package/dist/adapters/node/index.d.ts +53 -0
  13. package/dist/adapters/node/index.mjs +85 -0
  14. package/dist/adapters/standard/index.d.mts +26 -0
  15. package/dist/adapters/standard/index.d.ts +26 -0
  16. package/dist/adapters/standard/index.mjs +6 -0
  17. package/dist/index.d.mts +291 -0
  18. package/dist/index.d.ts +291 -0
  19. package/dist/index.mjs +363 -0
  20. package/dist/plugins/index.d.mts +30 -0
  21. package/dist/plugins/index.d.ts +30 -0
  22. package/dist/plugins/index.mjs +107 -0
  23. package/dist/shared/server.89QkKw3a.d.mts +10 -0
  24. package/dist/shared/server.B1S3zwuw.d.mts +8 -0
  25. package/dist/shared/server.BMkFIQUb.d.mts +66 -0
  26. package/dist/shared/server.BT0gne12.d.ts +8 -0
  27. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  28. package/dist/shared/server.CjWkNG6l.mjs +370 -0
  29. package/dist/shared/server.D0YVcfZk.d.mts +143 -0
  30. package/dist/shared/server.D0YVcfZk.d.ts +143 -0
  31. package/dist/shared/server.D9QduY95.mjs +161 -0
  32. package/dist/shared/server.Et1O6Bm7.mjs +98 -0
  33. package/dist/shared/server.taqJyaMn.d.ts +10 -0
  34. package/dist/shared/server.ywWqDZgA.d.ts +66 -0
  35. package/package.json +43 -15
  36. package/dist/chunk-FN62GL22.js +0 -182
  37. package/dist/fetch.js +0 -286
  38. package/dist/index.js +0 -518
  39. package/dist/src/builder.d.ts +0 -35
  40. package/dist/src/fetch/composite-handler.d.ts +0 -8
  41. package/dist/src/fetch/index.d.ts +0 -6
  42. package/dist/src/fetch/orpc-handler.d.ts +0 -20
  43. package/dist/src/fetch/orpc-payload-codec.d.ts +0 -9
  44. package/dist/src/fetch/orpc-procedure-matcher.d.ts +0 -12
  45. package/dist/src/fetch/super-json.d.ts +0 -12
  46. package/dist/src/fetch/types.d.ts +0 -16
  47. package/dist/src/hidden.d.ts +0 -6
  48. package/dist/src/implementer-chainable.d.ts +0 -10
  49. package/dist/src/index.d.ts +0 -23
  50. package/dist/src/lazy-decorated.d.ts +0 -10
  51. package/dist/src/lazy-utils.d.ts +0 -4
  52. package/dist/src/lazy.d.ts +0 -18
  53. package/dist/src/middleware-decorated.d.ts +0 -8
  54. package/dist/src/middleware.d.ts +0 -23
  55. package/dist/src/procedure-builder.d.ts +0 -22
  56. package/dist/src/procedure-client.d.ts +0 -29
  57. package/dist/src/procedure-decorated.d.ts +0 -14
  58. package/dist/src/procedure-implementer.d.ts +0 -18
  59. package/dist/src/procedure.d.ts +0 -23
  60. package/dist/src/router-builder.d.ts +0 -29
  61. package/dist/src/router-client.d.ts +0 -25
  62. package/dist/src/router-implementer.d.ts +0 -21
  63. package/dist/src/router.d.ts +0 -16
  64. package/dist/src/types.d.ts +0 -12
  65. package/dist/src/utils.d.ts +0 -3
@@ -0,0 +1,161 @@
1
+ import { ORPCError, toORPCError } from '@orpc/client';
2
+ import { toArray, intercept, parseEmptyableJSON } from '@orpc/shared';
3
+ import { c as createProcedureClient, t as traverseContractProcedures, i as isProcedure, u as unlazy, g as getRouter, a as createContractedProcedure } from './server.CjWkNG6l.mjs';
4
+ import { toHttpPath } from '@orpc/client/standard';
5
+
6
+ class StandardHandler {
7
+ constructor(router, matcher, codec, options) {
8
+ this.matcher = matcher;
9
+ this.codec = codec;
10
+ for (const plugin of toArray(options.plugins)) {
11
+ plugin.init?.(options);
12
+ }
13
+ this.interceptors = toArray(options.interceptors);
14
+ this.clientInterceptors = toArray(options.clientInterceptors);
15
+ this.rootInterceptors = toArray(options.rootInterceptors);
16
+ this.matcher.init(router);
17
+ }
18
+ interceptors;
19
+ clientInterceptors;
20
+ rootInterceptors;
21
+ handle(request, options) {
22
+ return intercept(
23
+ this.rootInterceptors,
24
+ { ...options, request },
25
+ async (interceptorOptions) => {
26
+ let isDecoding = false;
27
+ try {
28
+ return await intercept(
29
+ this.interceptors,
30
+ interceptorOptions,
31
+ async ({ request: request2, context, prefix }) => {
32
+ const method = request2.method;
33
+ const url = request2.url;
34
+ if (prefix && !url.pathname.startsWith(prefix)) {
35
+ return { matched: false, response: void 0 };
36
+ }
37
+ const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
38
+ const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`);
39
+ if (!match) {
40
+ return { matched: false, response: void 0 };
41
+ }
42
+ const client = createProcedureClient(match.procedure, {
43
+ context,
44
+ path: match.path,
45
+ interceptors: this.clientInterceptors
46
+ });
47
+ isDecoding = true;
48
+ const input = await this.codec.decode(request2, match.params, match.procedure);
49
+ isDecoding = false;
50
+ const lastEventId = Array.isArray(request2.headers["last-event-id"]) ? request2.headers["last-event-id"].at(-1) : request2.headers["last-event-id"];
51
+ const output = await client(input, { signal: request2.signal, lastEventId });
52
+ const response = this.codec.encode(output, match.procedure);
53
+ return {
54
+ matched: true,
55
+ response
56
+ };
57
+ }
58
+ );
59
+ } catch (e) {
60
+ const error = isDecoding && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
61
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
62
+ cause: e
63
+ }) : toORPCError(e);
64
+ const response = this.codec.encodeError(error);
65
+ return {
66
+ matched: true,
67
+ response
68
+ };
69
+ }
70
+ }
71
+ );
72
+ }
73
+ }
74
+
75
+ class StandardRPCCodec {
76
+ constructor(serializer) {
77
+ this.serializer = serializer;
78
+ }
79
+ async decode(request, _params, _procedure) {
80
+ const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
81
+ return this.serializer.deserialize(serialized);
82
+ }
83
+ encode(output, _procedure) {
84
+ return {
85
+ status: 200,
86
+ headers: {},
87
+ body: this.serializer.serialize(output)
88
+ };
89
+ }
90
+ encodeError(error) {
91
+ return {
92
+ status: error.status,
93
+ headers: {},
94
+ body: this.serializer.serialize(error.toJSON())
95
+ };
96
+ }
97
+ }
98
+
99
+ class StandardRPCMatcher {
100
+ tree = {};
101
+ pendingRouters = [];
102
+ init(router, path = []) {
103
+ const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
104
+ const httpPath = toHttpPath(path2);
105
+ if (isProcedure(contract)) {
106
+ this.tree[httpPath] = {
107
+ path: path2,
108
+ contract,
109
+ procedure: contract,
110
+ // this mean dev not used contract-first so we can used contract as procedure directly
111
+ router
112
+ };
113
+ } else {
114
+ this.tree[httpPath] = {
115
+ path: path2,
116
+ contract,
117
+ procedure: void 0,
118
+ router
119
+ };
120
+ }
121
+ });
122
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
123
+ ...option,
124
+ httpPathPrefix: toHttpPath(option.path)
125
+ })));
126
+ }
127
+ async match(_method, pathname) {
128
+ if (this.pendingRouters.length) {
129
+ const newPendingRouters = [];
130
+ for (const pendingRouter of this.pendingRouters) {
131
+ if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
132
+ const { default: router } = await unlazy(pendingRouter.router);
133
+ this.init(router, pendingRouter.path);
134
+ } else {
135
+ newPendingRouters.push(pendingRouter);
136
+ }
137
+ }
138
+ this.pendingRouters = newPendingRouters;
139
+ }
140
+ const match = this.tree[pathname];
141
+ if (!match) {
142
+ return void 0;
143
+ }
144
+ if (!match.procedure) {
145
+ const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
146
+ if (!isProcedure(maybeProcedure)) {
147
+ throw new Error(`
148
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
149
+ Ensure that the procedure is correctly defined and matches the expected contract.
150
+ `);
151
+ }
152
+ match.procedure = createContractedProcedure(maybeProcedure, match.contract);
153
+ }
154
+ return {
155
+ path: match.path,
156
+ procedure: match.procedure
157
+ };
158
+ }
159
+ }
160
+
161
+ export { StandardHandler as S, StandardRPCCodec as a, StandardRPCMatcher as b };
@@ -0,0 +1,98 @@
1
+ import { ORPCError } from '@orpc/client';
2
+ import { StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
3
+ import { S as StandardHandler, b as StandardRPCMatcher, a as StandardRPCCodec } from './server.D9QduY95.mjs';
4
+ import { toArray, intercept, resolveMaybeOptionalOptions } from '@orpc/shared';
5
+ import { toStandardLazyRequest, toFetchResponse } from '@orpc/standard-server-fetch';
6
+ import { r as resolveFriendlyStandardHandleOptions } from './server.BVwwTHyO.mjs';
7
+
8
+ class BodyLimitPlugin {
9
+ maxBodySize;
10
+ constructor(options) {
11
+ this.maxBodySize = options.maxBodySize;
12
+ }
13
+ initRuntimeAdapter(options) {
14
+ options.adapterInterceptors ??= [];
15
+ options.adapterInterceptors.push(async (options2) => {
16
+ if (!options2.request.body) {
17
+ return options2.next();
18
+ }
19
+ let currentBodySize = 0;
20
+ const rawReader = options2.request.body.getReader();
21
+ const reader = new ReadableStream({
22
+ start: async (controller) => {
23
+ try {
24
+ if (Number(options2.request.headers.get("content-length")) > this.maxBodySize) {
25
+ controller.error(new ORPCError("PAYLOAD_TOO_LARGE"));
26
+ return;
27
+ }
28
+ while (true) {
29
+ const { done, value } = await rawReader.read();
30
+ if (done) {
31
+ break;
32
+ }
33
+ currentBodySize += value.length;
34
+ if (currentBodySize > this.maxBodySize) {
35
+ controller.error(new ORPCError("PAYLOAD_TOO_LARGE"));
36
+ break;
37
+ }
38
+ controller.enqueue(value);
39
+ }
40
+ } finally {
41
+ controller.close();
42
+ }
43
+ }
44
+ });
45
+ const requestInit = { body: reader, duplex: "half" };
46
+ return options2.next({
47
+ ...options2,
48
+ request: new Request(options2.request, requestInit)
49
+ });
50
+ });
51
+ }
52
+ }
53
+
54
+ class FetchHandler {
55
+ constructor(standardHandler, options = {}) {
56
+ this.standardHandler = standardHandler;
57
+ for (const plugin of toArray(options.plugins)) {
58
+ plugin.initRuntimeAdapter?.(options);
59
+ }
60
+ this.adapterInterceptors = toArray(options.adapterInterceptors);
61
+ this.toFetchResponseOptions = options;
62
+ }
63
+ toFetchResponseOptions;
64
+ adapterInterceptors;
65
+ async handle(request, ...rest) {
66
+ return intercept(
67
+ this.adapterInterceptors,
68
+ {
69
+ ...resolveFriendlyStandardHandleOptions(resolveMaybeOptionalOptions(rest)),
70
+ request,
71
+ toFetchResponseOptions: this.toFetchResponseOptions
72
+ },
73
+ async ({ request: request2, toFetchResponseOptions, ...options }) => {
74
+ const standardRequest = toStandardLazyRequest(request2);
75
+ const result = await this.standardHandler.handle(standardRequest, options);
76
+ if (!result.matched) {
77
+ return result;
78
+ }
79
+ return {
80
+ matched: true,
81
+ response: toFetchResponse(result.response, toFetchResponseOptions)
82
+ };
83
+ }
84
+ );
85
+ }
86
+ }
87
+
88
+ class RPCHandler extends FetchHandler {
89
+ constructor(router, options = {}) {
90
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
91
+ const serializer = new StandardRPCSerializer(jsonSerializer);
92
+ const matcher = new StandardRPCMatcher();
93
+ const codec = new StandardRPCCodec(serializer);
94
+ super(new StandardHandler(router, matcher, codec, options), options);
95
+ }
96
+ }
97
+
98
+ export { BodyLimitPlugin as B, FetchHandler as F, RPCHandler as R };
@@ -0,0 +1,10 @@
1
+ import { C as Context } from './server.D0YVcfZk.js';
2
+ import { S as StandardHandleOptions } from './server.ywWqDZgA.js';
3
+
4
+ type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
5
+ context?: T;
6
+ } : {
7
+ context: T;
8
+ });
9
+
10
+ export type { FriendlyStandardHandleOptions as F };
@@ -0,0 +1,66 @@
1
+ import { HTTPPath, ORPCError } from '@orpc/client';
2
+ import { AnySchema, Meta, InferSchemaOutput, ErrorFromErrorMap } from '@orpc/contract';
3
+ import { Interceptor } from '@orpc/shared';
4
+ import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
5
+ import { a as AnyRouter, A as AnyProcedure, C as Context, P as ProcedureClientInterceptorOptions, R as Router } from './server.D0YVcfZk.js';
6
+
7
+ type StandardParams = Record<string, string>;
8
+ type StandardMatchResult = {
9
+ path: readonly string[];
10
+ procedure: AnyProcedure;
11
+ params?: StandardParams;
12
+ } | undefined;
13
+ interface StandardMatcher {
14
+ init(router: AnyRouter): void;
15
+ match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
16
+ }
17
+ interface StandardCodec {
18
+ encode(output: unknown, procedure: AnyProcedure): StandardResponse;
19
+ encodeError(error: ORPCError<any, any>): StandardResponse;
20
+ decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
21
+ }
22
+
23
+ interface StandardHandleOptions<T extends Context> {
24
+ prefix?: HTTPPath;
25
+ context: T;
26
+ }
27
+ type StandardHandleResult = {
28
+ matched: true;
29
+ response: StandardResponse;
30
+ } | {
31
+ matched: false;
32
+ response: undefined;
33
+ };
34
+ interface StandardHandlerPlugin<TContext extends Context> {
35
+ init?(options: StandardHandlerOptions<TContext>): void;
36
+ }
37
+ interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
38
+ request: StandardLazyRequest;
39
+ }
40
+ interface StandardHandlerOptions<TContext extends Context> {
41
+ plugins?: StandardHandlerPlugin<TContext>[];
42
+ /**
43
+ * Interceptors at the request level, helpful when you want catch errors
44
+ */
45
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
46
+ /**
47
+ * Interceptors at the root level, helpful when you want override the request/response
48
+ */
49
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
50
+ /**
51
+ *
52
+ * Interceptors for procedure client.
53
+ */
54
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, AnySchema, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
55
+ }
56
+ declare class StandardHandler<T extends Context> {
57
+ private readonly matcher;
58
+ private readonly codec;
59
+ private readonly interceptors;
60
+ private readonly clientInterceptors;
61
+ private readonly rootInterceptors;
62
+ constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
63
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
64
+ }
65
+
66
+ export { type StandardHandleOptions as S, type StandardHandlerOptions as a, type StandardHandlerInterceptorOptions as b, type StandardHandlerPlugin as c, type StandardCodec as d, type StandardParams as e, type StandardMatcher as f, type StandardMatchResult as g, type StandardHandleResult as h, StandardHandler as i };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/server",
3
3
  "type": "module",
4
- "version": "0.0.0-next.93e7a4c",
4
+ "version": "0.0.0-next.9486ab5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.unnoq.com",
7
7
  "repository": {
@@ -15,33 +15,61 @@
15
15
  ],
16
16
  "exports": {
17
17
  ".": {
18
- "types": "./dist/src/index.d.ts",
19
- "import": "./dist/index.js",
20
- "default": "./dist/index.js"
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
+ },
22
+ "./plugins": {
23
+ "types": "./dist/plugins/index.d.mts",
24
+ "import": "./dist/plugins/index.mjs",
25
+ "default": "./dist/plugins/index.mjs"
26
+ },
27
+ "./standard": {
28
+ "types": "./dist/adapters/standard/index.d.mts",
29
+ "import": "./dist/adapters/standard/index.mjs",
30
+ "default": "./dist/adapters/standard/index.mjs"
21
31
  },
22
32
  "./fetch": {
23
- "types": "./dist/src/fetch/index.d.ts",
24
- "import": "./dist/fetch.js",
25
- "default": "./dist/fetch.js"
33
+ "types": "./dist/adapters/fetch/index.d.mts",
34
+ "import": "./dist/adapters/fetch/index.mjs",
35
+ "default": "./dist/adapters/fetch/index.mjs"
36
+ },
37
+ "./hono": {
38
+ "types": "./dist/adapters/hono/index.d.mts",
39
+ "import": "./dist/adapters/hono/index.mjs",
40
+ "default": "./dist/adapters/hono/index.mjs"
26
41
  },
27
- "./🔒/*": {
28
- "types": "./dist/src/*.d.ts"
42
+ "./next": {
43
+ "types": "./dist/adapters/next/index.d.mts",
44
+ "import": "./dist/adapters/next/index.mjs",
45
+ "default": "./dist/adapters/next/index.mjs"
46
+ },
47
+ "./node": {
48
+ "types": "./dist/adapters/node/index.d.mts",
49
+ "import": "./dist/adapters/node/index.mjs",
50
+ "default": "./dist/adapters/node/index.mjs"
29
51
  }
30
52
  },
31
53
  "files": [
32
- "!**/*.map",
33
- "!**/*.tsbuildinfo",
34
54
  "dist"
35
55
  ],
56
+ "peerDependencies": {
57
+ "hono": ">=4.6.0",
58
+ "next": ">=14.0.0"
59
+ },
36
60
  "dependencies": {
37
- "@orpc/contract": "0.0.0-next.93e7a4c",
38
- "@orpc/shared": "0.0.0-next.93e7a4c"
61
+ "@orpc/client": "0.0.0-next.9486ab5",
62
+ "@orpc/contract": "0.0.0-next.9486ab5",
63
+ "@orpc/shared": "0.0.0-next.9486ab5",
64
+ "@orpc/standard-server": "0.0.0-next.9486ab5",
65
+ "@orpc/standard-server-node": "0.0.0-next.9486ab5",
66
+ "@orpc/standard-server-fetch": "0.0.0-next.9486ab5"
39
67
  },
40
68
  "devDependencies": {
41
- "zod": "^3.24.1"
69
+ "supertest": "^7.0.0"
42
70
  },
43
71
  "scripts": {
44
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --entry.fetch=src/fetch/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
72
+ "build": "unbuild",
45
73
  "build:watch": "pnpm run build --watch",
46
74
  "type:check": "tsc -b"
47
75
  }
@@ -1,182 +0,0 @@
1
- // src/utils.ts
2
- function mergeContext(a, b) {
3
- if (!a)
4
- return b;
5
- if (!b)
6
- return a;
7
- return {
8
- ...a,
9
- ...b
10
- };
11
- }
12
-
13
- // src/procedure.ts
14
- import { isContractProcedure } from "@orpc/contract";
15
- var Procedure = class {
16
- "~type" = "Procedure";
17
- "~orpc";
18
- constructor(def) {
19
- this["~orpc"] = def;
20
- }
21
- };
22
- function isProcedure(item) {
23
- if (item instanceof Procedure) {
24
- return true;
25
- }
26
- 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) && "func" in item["~orpc"] && typeof item["~orpc"].func === "function";
27
- }
28
-
29
- // src/lazy.ts
30
- var LAZY_LOADER_SYMBOL = Symbol("ORPC_LAZY_LOADER");
31
- function lazy(loader) {
32
- return {
33
- [LAZY_LOADER_SYMBOL]: loader
34
- };
35
- }
36
- function isLazy(item) {
37
- return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_LOADER_SYMBOL in item && typeof item[LAZY_LOADER_SYMBOL] === "function";
38
- }
39
- function unlazy(lazied) {
40
- return isLazy(lazied) ? lazied[LAZY_LOADER_SYMBOL]() : Promise.resolve({ default: lazied });
41
- }
42
- function flatLazy(lazied) {
43
- const flattenLoader = async () => {
44
- let current = await unlazy(lazied);
45
- while (true) {
46
- if (!isLazy(current.default)) {
47
- break;
48
- }
49
- current = await unlazy(current.default);
50
- }
51
- return current;
52
- };
53
- return lazy(flattenLoader);
54
- }
55
-
56
- // src/procedure-client.ts
57
- import { executeWithHooks, value } from "@orpc/shared";
58
- import { ORPCError } from "@orpc/shared/error";
59
- function createProcedureClient(options) {
60
- return async (...[input, callerOptions]) => {
61
- const path = options.path ?? [];
62
- const { default: procedure } = await unlazy(options.procedure);
63
- const context = await value(options.context);
64
- const meta = {
65
- path,
66
- procedure,
67
- signal: callerOptions?.signal
68
- };
69
- const executeWithValidation = async () => {
70
- const validInput = await validateInput(procedure, input);
71
- const output = await executeMiddlewareChain(
72
- procedure,
73
- validInput,
74
- context,
75
- meta
76
- );
77
- return validateOutput(procedure, output);
78
- };
79
- return executeWithHooks({
80
- hooks: options,
81
- input,
82
- context,
83
- meta,
84
- execute: executeWithValidation
85
- });
86
- };
87
- }
88
- async function validateInput(procedure, input) {
89
- const schema = procedure["~orpc"].contract["~orpc"].InputSchema;
90
- if (!schema)
91
- return input;
92
- const result = await schema["~standard"].validate(input);
93
- if (result.issues) {
94
- throw new ORPCError({
95
- message: "Input validation failed",
96
- code: "BAD_REQUEST",
97
- issues: result.issues
98
- });
99
- }
100
- return result.value;
101
- }
102
- async function validateOutput(procedure, output) {
103
- const schema = procedure["~orpc"].contract["~orpc"].OutputSchema;
104
- if (!schema)
105
- return output;
106
- const result = await schema["~standard"].validate(output);
107
- if (result.issues) {
108
- throw new ORPCError({
109
- message: "Output validation failed",
110
- code: "INTERNAL_SERVER_ERROR",
111
- issues: result.issues
112
- });
113
- }
114
- return result.value;
115
- }
116
- async function executeMiddlewareChain(procedure, input, context, meta) {
117
- const middlewares = procedure["~orpc"].middlewares ?? [];
118
- let currentMidIndex = 0;
119
- let currentContext = context;
120
- const next = async (nextOptions) => {
121
- const mid = middlewares[currentMidIndex];
122
- currentMidIndex += 1;
123
- currentContext = mergeContext(currentContext, nextOptions.context);
124
- if (mid) {
125
- return await mid(input, currentContext, {
126
- ...meta,
127
- next,
128
- output: (output) => ({ output, context: void 0 })
129
- });
130
- }
131
- const result = {
132
- output: await procedure["~orpc"].func(input, currentContext, meta),
133
- context: currentContext
134
- };
135
- return result;
136
- };
137
- return (await next({})).output;
138
- }
139
-
140
- // src/router.ts
141
- function getRouterChild(router, ...path) {
142
- let current = router;
143
- for (let i = 0; i < path.length; i++) {
144
- const segment = path[i];
145
- if (!current) {
146
- return void 0;
147
- }
148
- if (isProcedure(current)) {
149
- return void 0;
150
- }
151
- if (!isLazy(current)) {
152
- current = current[segment];
153
- continue;
154
- }
155
- const lazied = current;
156
- const rest = path.slice(i);
157
- const newLazy = lazy(async () => {
158
- const unwrapped = await unlazy(lazied);
159
- if (!unwrapped.default) {
160
- return unwrapped;
161
- }
162
- const next = getRouterChild(unwrapped.default, ...rest);
163
- return { default: next };
164
- });
165
- return flatLazy(newLazy);
166
- }
167
- return current;
168
- }
169
-
170
- export {
171
- mergeContext,
172
- Procedure,
173
- isProcedure,
174
- LAZY_LOADER_SYMBOL,
175
- lazy,
176
- isLazy,
177
- unlazy,
178
- flatLazy,
179
- createProcedureClient,
180
- getRouterChild
181
- };
182
- //# sourceMappingURL=chunk-FN62GL22.js.map