@temporary-name/server 1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e → 1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd

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 (39) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +12 -7
  2. package/dist/adapters/aws-lambda/index.d.ts +12 -7
  3. package/dist/adapters/aws-lambda/index.mjs +12 -4
  4. package/dist/adapters/fetch/index.d.mts +12 -7
  5. package/dist/adapters/fetch/index.d.ts +12 -7
  6. package/dist/adapters/fetch/index.mjs +12 -11
  7. package/dist/adapters/node/index.d.mts +12 -7
  8. package/dist/adapters/node/index.d.ts +12 -7
  9. package/dist/adapters/node/index.mjs +12 -11
  10. package/dist/adapters/standard/index.d.mts +27 -13
  11. package/dist/adapters/standard/index.d.ts +27 -13
  12. package/dist/adapters/standard/index.mjs +8 -100
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +62 -583
  15. package/dist/index.d.ts +62 -583
  16. package/dist/index.mjs +212 -446
  17. package/dist/openapi/index.d.mts +220 -0
  18. package/dist/openapi/index.d.ts +220 -0
  19. package/dist/openapi/index.mjs +707 -0
  20. package/dist/plugins/index.d.mts +5 -83
  21. package/dist/plugins/index.d.ts +5 -83
  22. package/dist/plugins/index.mjs +17 -189
  23. package/dist/shared/server.BR0GBxlv.d.ts +23 -0
  24. package/dist/shared/server.C1RJffw4.mjs +30 -0
  25. package/dist/shared/server.C7HccVwN.d.mts +23 -0
  26. package/dist/shared/{server.Btxrgkj5.d.ts → server.CPThlZ_E.d.ts} +9 -27
  27. package/dist/shared/server.D-DR5Z00.mjs +362 -0
  28. package/dist/shared/server.JtIZ8YG7.mjs +237 -0
  29. package/dist/shared/server.oy0285uM.d.mts +252 -0
  30. package/dist/shared/server.oy0285uM.d.ts +252 -0
  31. package/dist/shared/server.rZDPWnA8.mjs +234 -0
  32. package/dist/shared/{server.Bo94xDTv.d.mts → server.y97Td78c.d.mts} +9 -27
  33. package/package.json +17 -22
  34. package/dist/shared/server.BEQrAa3A.mjs +0 -207
  35. package/dist/shared/server.C1YnHvvf.d.mts +0 -192
  36. package/dist/shared/server.C1YnHvvf.d.ts +0 -192
  37. package/dist/shared/server.D6K9uoPI.mjs +0 -35
  38. package/dist/shared/server.DZ5BIITo.mjs +0 -9
  39. package/dist/shared/server.X0YaZxSJ.mjs +0 -13
@@ -0,0 +1,234 @@
1
+ import { stringifyJSON, isObject, isORPCErrorStatus, tryDecodeURIComponent, toHttpPath, toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, ORPCError, toORPCError } from '@temporary-name/shared';
2
+ import { c as createProcedureClient } from './server.D-DR5Z00.mjs';
3
+ import { fallbackContractConfig, standardizeHTTPPath } from '@temporary-name/contract';
4
+ import { d as deserialize, b as bracketNotationDeserialize, s as serialize } from './server.JtIZ8YG7.mjs';
5
+ import { traverseContractProcedures, getLazyMeta, unlazy } from '@temporary-name/server';
6
+ import { createRouter, addRoute, findRoute } from 'rou3';
7
+
8
+ async function decode(request, pathParams) {
9
+ return {
10
+ path: pathParams ?? {},
11
+ query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
12
+ headers: request.headers,
13
+ body: deserialize(await request.body()) ?? {}
14
+ };
15
+ }
16
+ function encode(output, procedure) {
17
+ const successStatus = fallbackContractConfig(
18
+ "defaultSuccessStatus",
19
+ procedure["~orpc"].route.successStatus
20
+ );
21
+ const outputStructure = fallbackContractConfig(
22
+ "defaultOutputStructure",
23
+ procedure["~orpc"].route.outputStructure
24
+ );
25
+ if (outputStructure === "compact") {
26
+ return {
27
+ status: successStatus,
28
+ headers: new Headers(),
29
+ body: serialize(output)
30
+ };
31
+ }
32
+ if (!isDetailedOutput(output)) {
33
+ throw new Error(`
34
+ Invalid "detailed" output structure:
35
+ \u2022 Expected an object with optional properties:
36
+ - status (number 200-399)
37
+ - headers (Record<string, string | string[]>)
38
+ - body (any)
39
+ \u2022 No extra keys allowed.
40
+
41
+ Actual value:
42
+ ${stringifyJSON(output)}
43
+ `);
44
+ }
45
+ return {
46
+ status: output.status ?? successStatus,
47
+ headers: output.headers ?? new Headers(),
48
+ body: serialize(output.body)
49
+ };
50
+ }
51
+ function encodeError(error) {
52
+ return {
53
+ status: error.status,
54
+ headers: new Headers(),
55
+ body: serialize(error.toJSON(), { outputFormat: "plain" })
56
+ };
57
+ }
58
+ function isDetailedOutput(output) {
59
+ if (!isObject(output)) {
60
+ return false;
61
+ }
62
+ if (output.headers && !isObject(output.headers)) {
63
+ return false;
64
+ }
65
+ if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
66
+ return false;
67
+ }
68
+ return true;
69
+ }
70
+
71
+ function resolveFriendlyStandardHandleOptions(options) {
72
+ return {
73
+ ...options,
74
+ context: options.context ?? {}
75
+ // Context only optional if all fields are optional
76
+ };
77
+ }
78
+ function toRou3Pattern(path) {
79
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
80
+ }
81
+ function decodeParams(params) {
82
+ return Object.fromEntries(
83
+ Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
84
+ );
85
+ }
86
+
87
+ class StandardOpenAPIMatcher {
88
+ tree = createRouter();
89
+ pendingRouters = [];
90
+ init(router, path = []) {
91
+ const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
92
+ const { path: path2, contract } = traverseOptions;
93
+ const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
94
+ const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
95
+ addRoute(this.tree, method, httpPath, {
96
+ path: path2,
97
+ // cast is safe because router is typed as Router (not ContractRouter)
98
+ procedure: contract,
99
+ router
100
+ });
101
+ });
102
+ this.pendingRouters.push(
103
+ ...laziedOptions.map((option) => ({
104
+ ...option,
105
+ httpPathPrefix: toHttpPath(option.path),
106
+ laziedPrefix: getLazyMeta(option.router).prefix
107
+ }))
108
+ );
109
+ }
110
+ async match(method, pathname) {
111
+ if (this.pendingRouters.length) {
112
+ const newPendingRouters = [];
113
+ for (const pendingRouter of this.pendingRouters) {
114
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
115
+ const { default: router } = await unlazy(pendingRouter.router);
116
+ this.init(router, pendingRouter.path);
117
+ } else {
118
+ newPendingRouters.push(pendingRouter);
119
+ }
120
+ }
121
+ this.pendingRouters = newPendingRouters;
122
+ }
123
+ const match = findRoute(this.tree, method, pathname);
124
+ if (!match) {
125
+ return void 0;
126
+ }
127
+ return {
128
+ path: match.data.path,
129
+ procedure: match.data.procedure,
130
+ params: match.params ? decodeParams(match.params) : void 0
131
+ };
132
+ }
133
+ }
134
+
135
+ class CompositeStandardHandlerPlugin {
136
+ plugins;
137
+ constructor(plugins = []) {
138
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
139
+ }
140
+ init(options, router) {
141
+ for (const plugin of this.plugins) {
142
+ plugin.init?.(options, router);
143
+ }
144
+ }
145
+ }
146
+
147
+ class StandardHandler {
148
+ interceptors;
149
+ clientInterceptors;
150
+ rootInterceptors;
151
+ matcher;
152
+ constructor(router, options) {
153
+ this.matcher = new StandardOpenAPIMatcher();
154
+ const plugins = new CompositeStandardHandlerPlugin(options.plugins);
155
+ plugins.init(options, router);
156
+ this.interceptors = toArray(options.interceptors);
157
+ this.clientInterceptors = toArray(options.clientInterceptors);
158
+ this.rootInterceptors = toArray(options.rootInterceptors);
159
+ this.matcher.init(router);
160
+ }
161
+ async handle(request, options) {
162
+ const prefix = options.prefix?.replace(/\/$/, "") || void 0;
163
+ if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
164
+ return { matched: false, response: void 0 };
165
+ }
166
+ return intercept(this.rootInterceptors, { ...options, request, prefix }, async (interceptorOptions) => {
167
+ return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
168
+ let step;
169
+ try {
170
+ return await intercept(
171
+ this.interceptors,
172
+ interceptorOptions,
173
+ async ({ request: request2, context, prefix: prefix2 }) => {
174
+ const method = request2.method;
175
+ const url = request2.url;
176
+ const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
177
+ const match = await runWithSpan(
178
+ { name: "find_procedure" },
179
+ () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
180
+ );
181
+ if (!match) {
182
+ return { matched: false, response: void 0 };
183
+ }
184
+ span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
185
+ span?.setAttribute("rpc.system", ORPC_NAME);
186
+ span?.setAttribute("rpc.method", match.path.join("."));
187
+ step = "decode_input";
188
+ const input = await runWithSpan({ name: "decode_input" }, () => decode(request2, match.params));
189
+ step = void 0;
190
+ if (isAsyncIteratorObject(input.body)) {
191
+ input.body = asyncIteratorWithSpan(
192
+ { name: "consume_event_iterator_input", signal: request2.signal },
193
+ input.body
194
+ );
195
+ }
196
+ const client = createProcedureClient(match.procedure, {
197
+ context,
198
+ path: match.path,
199
+ interceptors: this.clientInterceptors
200
+ });
201
+ step = "call_procedure";
202
+ const output = await client(input, {
203
+ request: request2,
204
+ signal: request2.signal,
205
+ lastEventId: request2.headers.get("last-event-id") ?? void 0
206
+ });
207
+ step = void 0;
208
+ const response = encode(output, match.procedure);
209
+ return {
210
+ matched: true,
211
+ response
212
+ };
213
+ }
214
+ );
215
+ } catch (e) {
216
+ if (step !== "call_procedure") {
217
+ setSpanError(span, e);
218
+ }
219
+ const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
220
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
221
+ cause: e
222
+ }) : toORPCError(e);
223
+ const response = encodeError(error);
224
+ return {
225
+ matched: true,
226
+ response
227
+ };
228
+ }
229
+ });
230
+ });
231
+ }
232
+ }
233
+
234
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as S, encodeError as a, StandardOpenAPIMatcher as b, decodeParams as c, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };
@@ -1,32 +1,15 @@
1
1
  import { Meta } from '@temporary-name/contract';
2
- import { HTTPPath, ORPCError, Interceptor } from '@temporary-name/shared';
3
- import { StandardResponse, StandardLazyRequest } from '@temporary-name/standard-server';
4
- import { C as Context, R as Router, A as AnyRouter, a as AnyProcedure, P as ProcedureClientInterceptorOptions } from './server.C1YnHvvf.mjs';
2
+ import { HTTPPath, StandardLazyRequest, Interceptor, StandardResponse } from '@temporary-name/shared';
3
+ import { C as Context, R as Router, N as ProcedureClientInterceptorOptions } from './server.oy0285uM.mjs';
5
4
 
6
5
  interface StandardHandlerPlugin<T extends Context> {
7
6
  order?: number;
8
- init?(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
7
+ init?(options: StandardHandlerOptions<T>, router: Router<T>): void;
9
8
  }
10
9
  declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
11
10
  protected readonly plugins: TPlugin[];
12
11
  constructor(plugins?: readonly TPlugin[]);
13
- init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
14
- }
15
-
16
- type StandardParams = Record<string, string>;
17
- type StandardMatchResult = {
18
- path: readonly string[];
19
- procedure: AnyProcedure;
20
- params?: StandardParams;
21
- } | undefined;
22
- interface StandardMatcher {
23
- init(router: AnyRouter): void;
24
- match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
25
- }
26
- interface StandardCodec {
27
- encode(output: unknown, procedure: AnyProcedure): StandardResponse;
28
- encodeError(error: ORPCError<any, any>): StandardResponse;
29
- decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
12
+ init(options: StandardHandlerOptions<T>, router: Router<T>): void;
30
13
  }
31
14
 
32
15
  interface StandardHandleOptions<T extends Context> {
@@ -57,17 +40,16 @@ interface StandardHandlerOptions<TContext extends Context> {
57
40
  *
58
41
  * Interceptors for procedure client.
59
42
  */
60
- clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
43
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Meta>, Promise<unknown>>[];
61
44
  }
62
45
  declare class StandardHandler<T extends Context> {
63
- private readonly matcher;
64
- private readonly codec;
65
46
  private readonly interceptors;
66
47
  private readonly clientInterceptors;
67
48
  private readonly rootInterceptors;
68
- constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
49
+ private readonly matcher;
50
+ constructor(router: Router<T>, options: NoInfer<StandardHandlerOptions<T>>);
69
51
  handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
70
52
  }
71
53
 
72
- export { CompositeStandardHandlerPlugin as C, StandardHandler as S };
73
- export type { StandardHandlerPlugin as a, StandardHandleOptions as b, StandardHandlerInterceptorOptions as c, StandardHandlerOptions as d, StandardHandleResult as e, StandardParams as f, StandardMatchResult as g, StandardMatcher as h, StandardCodec as i };
54
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as e };
55
+ export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardHandleOptions as c, StandardHandleResult as d };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@temporary-name/server",
3
3
  "type": "module",
4
- "version": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
4
+ "version": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
5
5
  "license": "MIT",
6
6
  "homepage": "https://www.stainless.com/",
7
7
  "repository": {
@@ -47,37 +47,32 @@
47
47
  "types": "./dist/adapters/aws-lambda/index.d.mts",
48
48
  "import": "./dist/adapters/aws-lambda/index.mjs",
49
49
  "default": "./dist/adapters/aws-lambda/index.mjs"
50
+ },
51
+ "./openapi": {
52
+ "types": "./dist/openapi/index.d.mts",
53
+ "import": "./dist/openapi/index.mjs",
54
+ "default": "./dist/openapi/index.mjs"
50
55
  }
51
56
  },
52
57
  "files": [
53
58
  "dist"
54
59
  ],
55
- "peerDependencies": {
56
- "drizzle-orm": "^0.44.5",
57
- "drizzle-zod": "^0.8.3"
58
- },
59
- "peerDependenciesMeta": {
60
- "drizzle-orm": {
61
- "optional": true
62
- },
63
- "drizzle-zod": {
64
- "optional": true
65
- }
66
- },
67
60
  "dependencies": {
68
61
  "cookie": "^1.0.2",
69
- "@standard-schema/spec": "^1.0.0",
62
+ "rou3": "^0.7.7",
70
63
  "zod": "^4.1.12",
71
- "@temporary-name/interop": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
72
- "@temporary-name/contract": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
73
- "@temporary-name/openapi": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
74
- "@temporary-name/shared": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
75
- "@temporary-name/standard-server-fetch": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
76
- "@temporary-name/standard-server-node": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
77
- "@temporary-name/standard-server": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e",
78
- "@temporary-name/standard-server-aws-lambda": "1.9.3-alpha.9f176ca3f9388d51e8dffa98a15fcf9f14f6a75e"
64
+ "@temporary-name/interop": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
65
+ "@temporary-name/contract": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
66
+ "@temporary-name/json-schema": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
67
+ "@temporary-name/shared": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
68
+ "@temporary-name/standard-server": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
69
+ "@temporary-name/standard-server-aws-lambda": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
70
+ "@temporary-name/standard-server-fetch": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
71
+ "@temporary-name/standard-server-node": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd",
72
+ "@temporary-name/zod": "1.9.3-alpha.a253b67a3639148c12f13a47295e1922182adecd"
79
73
  },
80
74
  "devDependencies": {
75
+ "@types/supertest": "^6.0.3",
81
76
  "@types/ws": "^8.18.1",
82
77
  "supertest": "^7.1.4"
83
78
  },
@@ -1,207 +0,0 @@
1
- import { validateORPCError, ValidationError } from '@temporary-name/contract';
2
- import { resolveMaybeOptionalOptions, ORPCError, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan } from '@temporary-name/shared';
3
- import { HibernationEventIterator, mapEventIterator } from '@temporary-name/standard-server';
4
- import { g as gatingContext, w as withoutGatedFields } from './server.D6K9uoPI.mjs';
5
-
6
- const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
7
- function lazy(loader, meta = {}) {
8
- return {
9
- [LAZY_SYMBOL]: {
10
- loader,
11
- meta
12
- }
13
- };
14
- }
15
- function isLazy(item) {
16
- return (typeof item === "object" || typeof item === "function") && item !== null && LAZY_SYMBOL in item;
17
- }
18
- function getLazyMeta(lazied) {
19
- return lazied[LAZY_SYMBOL].meta;
20
- }
21
- function unlazy(lazied) {
22
- return isLazy(lazied) ? lazied[LAZY_SYMBOL].loader() : Promise.resolve({ default: lazied });
23
- }
24
-
25
- function mergeCurrentContext(context, other) {
26
- return { ...context, ...other };
27
- }
28
-
29
- function createORPCErrorConstructorMap(errors) {
30
- const proxy = new Proxy(errors, {
31
- get(target, code) {
32
- if (typeof code !== "string") {
33
- return Reflect.get(target, code);
34
- }
35
- const item = (...rest) => {
36
- const options = resolveMaybeOptionalOptions(rest);
37
- const config = errors[code];
38
- return new ORPCError(code, {
39
- defined: Boolean(config),
40
- status: config?.status,
41
- message: options.message ?? config?.message,
42
- data: options.data,
43
- cause: options.cause
44
- });
45
- };
46
- return item;
47
- }
48
- });
49
- return proxy;
50
- }
51
-
52
- function middlewareOutputFn(output) {
53
- return { output, context: {} };
54
- }
55
-
56
- function createProcedureClient(lazyableProcedure, ...rest) {
57
- const options = resolveMaybeOptionalOptions(rest);
58
- return async (...[input, callerOptions]) => {
59
- const path = toArray(options.path);
60
- const { default: procedure } = await unlazy(lazyableProcedure);
61
- const clientContext = callerOptions?.context ?? {};
62
- const context = await value(options.context ?? {}, clientContext);
63
- const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
64
- const validateError = async (e) => {
65
- if (e instanceof ORPCError) {
66
- return await validateORPCError(procedure["~orpc"].errorMap, e);
67
- }
68
- return e;
69
- };
70
- try {
71
- const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
72
- span?.setAttribute("procedure.path", [...path]);
73
- return intercept(
74
- toArray(options.interceptors),
75
- {
76
- context,
77
- input,
78
- // input only optional when it undefinable so we can safely cast it
79
- errors,
80
- path,
81
- procedure,
82
- signal: callerOptions?.signal,
83
- lastEventId: callerOptions?.lastEventId
84
- },
85
- (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
86
- );
87
- });
88
- if (isAsyncIteratorObject(output)) {
89
- if (output instanceof HibernationEventIterator) {
90
- return output;
91
- }
92
- return overlayProxy(
93
- output,
94
- mapEventIterator(
95
- asyncIteratorWithSpan(
96
- { name: "consume_event_iterator_output", signal: callerOptions?.signal },
97
- output
98
- ),
99
- {
100
- value: (v) => v,
101
- error: (e) => validateError(e)
102
- }
103
- )
104
- );
105
- }
106
- return output;
107
- } catch (e) {
108
- throw await validateError(e);
109
- }
110
- };
111
- }
112
- async function validateInput(procedure, input) {
113
- const schema = procedure["~orpc"].inputSchema;
114
- if (!schema) {
115
- return input;
116
- }
117
- return runWithSpan({ name: "validate_input" }, async () => {
118
- const result = await schema["~standard"].validate(input);
119
- if (result.issues) {
120
- throw new ORPCError("BAD_REQUEST", {
121
- message: "Input validation failed",
122
- data: {
123
- issues: result.issues
124
- },
125
- cause: new ValidationError({
126
- message: "Input validation failed",
127
- issues: result.issues,
128
- data: input
129
- })
130
- });
131
- }
132
- return result.value;
133
- });
134
- }
135
- async function validateOutput(schema, output) {
136
- return runWithSpan({ name: "validate_output" }, async () => {
137
- const result = await schema["~standard"].validate(output);
138
- if (result.issues) {
139
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
140
- message: "Output validation failed",
141
- cause: new ValidationError({
142
- message: "Output validation failed",
143
- issues: result.issues,
144
- data: output
145
- })
146
- });
147
- }
148
- return result.value;
149
- });
150
- }
151
- async function executeProcedureInternal(procedure, options) {
152
- const middlewares = procedure["~orpc"].middlewares;
153
- const inputValidationIndex = Math.min(
154
- Math.max(0, procedure["~orpc"].inputValidationIndex),
155
- middlewares.length
156
- );
157
- const outputValidationIndex = Math.min(
158
- Math.max(0, procedure["~orpc"].outputValidationIndex),
159
- middlewares.length
160
- );
161
- const next = async (index, context, input) => {
162
- let currentInput = input;
163
- if (index === inputValidationIndex) {
164
- currentInput = await validateInput(procedure, currentInput);
165
- }
166
- const mid = middlewares[index];
167
- const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
168
- span?.setAttribute("middleware.index", index);
169
- span?.setAttribute("middleware.name", mid.name);
170
- const result = await mid(
171
- {
172
- ...options,
173
- context,
174
- next: async (...[nextOptions]) => {
175
- const nextContext = nextOptions?.context ?? {};
176
- return {
177
- output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
178
- context: nextContext
179
- };
180
- }
181
- },
182
- currentInput,
183
- middlewareOutputFn
184
- );
185
- return result.output;
186
- }) : await runWithSpan(
187
- { name: "handler", signal: options.signal },
188
- () => procedure["~orpc"].handler({ ...options, context, input: currentInput })
189
- );
190
- if (index === outputValidationIndex) {
191
- const schema = procedure["~orpc"].outputSchema;
192
- if (!schema) {
193
- return output;
194
- }
195
- const validated = await validateOutput(schema, output);
196
- const isGateEnabled = gatingContext.getStore();
197
- if (!validated || !isGateEnabled) {
198
- return validated;
199
- }
200
- return withoutGatedFields(validated, schema, isGateEnabled);
201
- }
202
- return output;
203
- };
204
- return next(0, options.context, options.input);
205
- }
206
-
207
- export { LAZY_SYMBOL as L, createORPCErrorConstructorMap as a, middlewareOutputFn as b, createProcedureClient as c, getLazyMeta as g, isLazy as i, lazy as l, mergeCurrentContext as m, unlazy as u };