@orpc/server 0.0.0-next.b5ac9a3 → 0.0.0-next.b5e327f

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 (72) hide show
  1. package/README.md +29 -23
  2. package/dist/adapters/aws-lambda/index.d.mts +46 -0
  3. package/dist/adapters/aws-lambda/index.d.ts +46 -0
  4. package/dist/adapters/aws-lambda/index.mjs +42 -0
  5. package/dist/adapters/bun-ws/index.d.mts +36 -0
  6. package/dist/adapters/bun-ws/index.d.ts +36 -0
  7. package/dist/adapters/bun-ws/index.mjs +47 -0
  8. package/dist/adapters/crossws/index.d.mts +33 -0
  9. package/dist/adapters/crossws/index.d.ts +33 -0
  10. package/dist/adapters/crossws/index.mjs +45 -0
  11. package/dist/adapters/fetch/index.d.mts +107 -11
  12. package/dist/adapters/fetch/index.d.ts +107 -11
  13. package/dist/adapters/fetch/index.mjs +178 -8
  14. package/dist/adapters/message-port/index.d.mts +31 -0
  15. package/dist/adapters/message-port/index.d.ts +31 -0
  16. package/dist/adapters/message-port/index.mjs +39 -0
  17. package/dist/adapters/node/index.d.mts +85 -22
  18. package/dist/adapters/node/index.d.ts +85 -22
  19. package/dist/adapters/node/index.mjs +144 -24
  20. package/dist/adapters/standard/index.d.mts +8 -13
  21. package/dist/adapters/standard/index.d.ts +8 -13
  22. package/dist/adapters/standard/index.mjs +5 -3
  23. package/dist/adapters/standard-peer/index.d.mts +18 -0
  24. package/dist/adapters/standard-peer/index.d.ts +18 -0
  25. package/dist/adapters/standard-peer/index.mjs +7 -0
  26. package/dist/adapters/websocket/index.d.mts +54 -0
  27. package/dist/adapters/websocket/index.d.ts +54 -0
  28. package/dist/adapters/websocket/index.mjs +67 -0
  29. package/dist/adapters/ws/index.d.mts +31 -0
  30. package/dist/adapters/ws/index.d.ts +31 -0
  31. package/dist/adapters/ws/index.mjs +37 -0
  32. package/dist/helpers/index.d.mts +134 -0
  33. package/dist/helpers/index.d.ts +134 -0
  34. package/dist/helpers/index.mjs +188 -0
  35. package/dist/hibernation/index.d.mts +44 -0
  36. package/dist/hibernation/index.d.ts +44 -0
  37. package/dist/hibernation/index.mjs +65 -0
  38. package/dist/index.d.mts +609 -84
  39. package/dist/index.d.ts +609 -84
  40. package/dist/index.mjs +163 -16
  41. package/dist/plugins/index.d.mts +154 -16
  42. package/dist/plugins/index.d.ts +154 -16
  43. package/dist/plugins/index.mjs +198 -16
  44. package/dist/shared/{server.BtxZnWJ9.mjs → server.7jWaIryJ.mjs} +116 -74
  45. package/dist/shared/server.B7b2w3_i.d.ts +12 -0
  46. package/dist/shared/server.BEFBl-Cb.d.mts +12 -0
  47. package/dist/shared/server.BHZCyRuJ.mjs +219 -0
  48. package/dist/shared/server.BU4WI18A.d.mts +32 -0
  49. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  50. package/dist/shared/server.Bmh5xd4n.d.ts +74 -0
  51. package/dist/shared/{server.BYTulgUc.d.mts → server.CYNGeoCm.d.mts} +66 -16
  52. package/dist/shared/{server.BYTulgUc.d.ts → server.CYNGeoCm.d.ts} +66 -16
  53. package/dist/shared/server.D0H-iaY3.d.ts +32 -0
  54. package/dist/shared/server.DZ5BIITo.mjs +9 -0
  55. package/dist/shared/server.DhJj-1X9.d.mts +42 -0
  56. package/dist/shared/server.UVMTOWrk.mjs +26 -0
  57. package/dist/shared/server.gqRxT-yN.d.mts +74 -0
  58. package/dist/shared/server.jMTkVNIb.d.ts +42 -0
  59. package/package.json +71 -20
  60. package/dist/adapters/hono/index.d.mts +0 -21
  61. package/dist/adapters/hono/index.d.ts +0 -21
  62. package/dist/adapters/hono/index.mjs +0 -32
  63. package/dist/adapters/next/index.d.mts +0 -28
  64. package/dist/adapters/next/index.d.ts +0 -28
  65. package/dist/adapters/next/index.mjs +0 -29
  66. package/dist/shared/server.B52eKaNe.d.mts +0 -8
  67. package/dist/shared/server.BA-onDGB.d.ts +0 -8
  68. package/dist/shared/server.BY9sDlwl.mjs +0 -158
  69. package/dist/shared/server.CDzXh8DM.d.mts +0 -75
  70. package/dist/shared/server.CkGvC2T0.d.ts +0 -75
  71. package/dist/shared/server.Dba3Iiyp.mjs +0 -12
  72. package/dist/shared/server.Del5OmaY.mjs +0 -29
@@ -1,6 +1,7 @@
1
1
  import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
- import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
- import { value, intercept, toError } from '@orpc/shared';
2
+ import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, asyncIteratorWithSpan } from '@orpc/shared';
3
+ import { ORPCError, fallbackORPCErrorStatus, mapEventIterator } from '@orpc/client';
4
+ import { HibernationEventIterator } from '@orpc/standard-server';
4
5
 
5
6
  const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
6
7
  function lazy(loader, meta = {}) {
@@ -46,6 +47,9 @@ function addMiddleware(middlewares, addition) {
46
47
  }
47
48
 
48
49
  class Procedure {
50
+ /**
51
+ * This property holds the defined options.
52
+ */
49
53
  "~orpc";
50
54
  constructor(def) {
51
55
  this["~orpc"] = def;
@@ -68,14 +72,15 @@ function createORPCErrorConstructorMap(errors) {
68
72
  if (typeof code !== "string") {
69
73
  return Reflect.get(target, code);
70
74
  }
71
- const item = (...[options]) => {
75
+ const item = (...rest) => {
76
+ const options = resolveMaybeOptionalOptions(rest);
72
77
  const config = errors[code];
73
78
  return new ORPCError(code, {
74
79
  defined: Boolean(config),
75
80
  status: config?.status,
76
- message: options?.message ?? config?.message,
77
- data: options?.data,
78
- cause: options?.cause
81
+ message: options.message ?? config?.message,
82
+ data: options.data,
83
+ cause: options.cause
79
84
  });
80
85
  };
81
86
  return item;
@@ -103,34 +108,59 @@ function middlewareOutputFn(output) {
103
108
  return { output, context: {} };
104
109
  }
105
110
 
106
- function createProcedureClient(lazyableProcedure, ...[options]) {
111
+ function createProcedureClient(lazyableProcedure, ...rest) {
112
+ const options = resolveMaybeOptionalOptions(rest);
107
113
  return async (...[input, callerOptions]) => {
108
- const path = options?.path ?? [];
114
+ const path = toArray(options.path);
109
115
  const { default: procedure } = await unlazy(lazyableProcedure);
110
116
  const clientContext = callerOptions?.context ?? {};
111
- const context = await value(options?.context ?? {}, clientContext);
117
+ const context = await value(options.context ?? {}, clientContext);
112
118
  const errors = createORPCErrorConstructorMap(procedure["~orpc"].errorMap);
119
+ const validateError = async (e) => {
120
+ if (e instanceof ORPCError) {
121
+ return await validateORPCError(procedure["~orpc"].errorMap, e);
122
+ }
123
+ return e;
124
+ };
113
125
  try {
114
- return await intercept(
115
- options?.interceptors ?? [],
116
- {
117
- context,
118
- input,
119
- // input only optional when it undefinable so we can safely cast it
120
- errors,
121
- path,
122
- procedure,
123
- signal: callerOptions?.signal,
124
- lastEventId: callerOptions?.lastEventId
125
- },
126
- (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
126
+ const output = await runWithSpan(
127
+ { name: "call_procedure", signal: callerOptions?.signal },
128
+ (span) => {
129
+ span?.setAttribute("procedure.path", [...path]);
130
+ return intercept(
131
+ toArray(options.interceptors),
132
+ {
133
+ context,
134
+ input,
135
+ // input only optional when it undefinable so we can safely cast it
136
+ errors,
137
+ path,
138
+ procedure,
139
+ signal: callerOptions?.signal,
140
+ lastEventId: callerOptions?.lastEventId
141
+ },
142
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
143
+ );
144
+ }
127
145
  );
128
- } catch (e) {
129
- if (!(e instanceof ORPCError)) {
130
- throw toError(e);
146
+ if (isAsyncIteratorObject(output)) {
147
+ if (output instanceof HibernationEventIterator) {
148
+ return output;
149
+ }
150
+ return mapEventIterator(
151
+ asyncIteratorWithSpan(
152
+ { name: "consume_event_iterator_output", signal: callerOptions?.signal },
153
+ output
154
+ ),
155
+ {
156
+ value: (v) => v,
157
+ error: (e) => validateError(e)
158
+ }
159
+ );
131
160
  }
132
- const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
133
- throw validated;
161
+ return output;
162
+ } catch (e) {
163
+ throw await validateError(e);
134
164
  }
135
165
  };
136
166
  }
@@ -139,65 +169,80 @@ async function validateInput(procedure, input) {
139
169
  if (!schema) {
140
170
  return input;
141
171
  }
142
- const result = await schema["~standard"].validate(input);
143
- if (result.issues) {
144
- throw new ORPCError("BAD_REQUEST", {
145
- message: "Input validation failed",
146
- data: {
147
- issues: result.issues
148
- },
149
- cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
150
- });
151
- }
152
- return result.value;
172
+ return runWithSpan(
173
+ { name: "validate_input" },
174
+ async () => {
175
+ const result = await schema["~standard"].validate(input);
176
+ if (result.issues) {
177
+ throw new ORPCError("BAD_REQUEST", {
178
+ message: "Input validation failed",
179
+ data: {
180
+ issues: result.issues
181
+ },
182
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
183
+ });
184
+ }
185
+ return result.value;
186
+ }
187
+ );
153
188
  }
154
189
  async function validateOutput(procedure, output) {
155
190
  const schema = procedure["~orpc"].outputSchema;
156
191
  if (!schema) {
157
192
  return output;
158
193
  }
159
- const result = await schema["~standard"].validate(output);
160
- if (result.issues) {
161
- throw new ORPCError("INTERNAL_SERVER_ERROR", {
162
- message: "Output validation failed",
163
- cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
164
- });
165
- }
166
- return result.value;
194
+ return runWithSpan(
195
+ { name: "validate_output" },
196
+ async () => {
197
+ const result = await schema["~standard"].validate(output);
198
+ if (result.issues) {
199
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
200
+ message: "Output validation failed",
201
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
202
+ });
203
+ }
204
+ return result.value;
205
+ }
206
+ );
167
207
  }
168
208
  async function executeProcedureInternal(procedure, options) {
169
209
  const middlewares = procedure["~orpc"].middlewares;
170
210
  const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
171
211
  const outputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].outputValidationIndex), middlewares.length);
172
- let currentIndex = 0;
173
- let currentContext = options.context;
174
- let currentInput = options.input;
175
- const next = async (...[nextOptions]) => {
176
- const index = currentIndex;
177
- const midContext = nextOptions?.context ?? {};
178
- currentIndex += 1;
179
- currentContext = mergeCurrentContext(currentContext, midContext);
212
+ const next = async (index, context, input) => {
213
+ let currentInput = input;
180
214
  if (index === inputValidationIndex) {
181
215
  currentInput = await validateInput(procedure, currentInput);
182
216
  }
183
217
  const mid = middlewares[index];
184
- const result = mid ? {
185
- context: midContext,
186
- output: (await mid({ ...options, context: currentContext, next }, currentInput, middlewareOutputFn)).output
187
- } : {
188
- context: midContext,
189
- output: await procedure["~orpc"].handler({ ...options, context: currentContext, input: currentInput })
190
- };
218
+ const output = mid ? await runWithSpan(
219
+ { name: `middleware.${mid.name}`, signal: options.signal },
220
+ async (span) => {
221
+ span?.setAttribute("middleware.index", index);
222
+ span?.setAttribute("middleware.name", mid.name);
223
+ const result = await mid({
224
+ ...options,
225
+ context,
226
+ next: async (...[nextOptions]) => {
227
+ const nextContext = nextOptions?.context ?? {};
228
+ return {
229
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
230
+ context: nextContext
231
+ };
232
+ }
233
+ }, currentInput, middlewareOutputFn);
234
+ return result.output;
235
+ }
236
+ ) : await runWithSpan(
237
+ { name: "handler", signal: options.signal },
238
+ () => procedure["~orpc"].handler({ ...options, context, input: currentInput })
239
+ );
191
240
  if (index === outputValidationIndex) {
192
- const validatedOutput = await validateOutput(procedure, result.output);
193
- return {
194
- context: result.context,
195
- output: validatedOutput
196
- };
241
+ return await validateOutput(procedure, output);
197
242
  }
198
- return result;
243
+ return output;
199
244
  };
200
- return (await next()).output;
245
+ return next(0, options.context, options.input);
201
246
  }
202
247
 
203
248
  const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
@@ -364,11 +409,8 @@ function createContractedProcedure(procedure, contract) {
364
409
  });
365
410
  }
366
411
  function call(procedure, input, ...rest) {
367
- return createProcedureClient(procedure, ...rest)(input);
368
- }
369
-
370
- function toHttpPath(path) {
371
- return `/${path.map(encodeURIComponent).join("/")}`;
412
+ const options = resolveMaybeOptionalOptions(rest);
413
+ return createProcedureClient(procedure, options)(input, options);
372
414
  }
373
415
 
374
- export { LAZY_SYMBOL as L, Procedure as P, toHttpPath as a, createContractedProcedure as b, createProcedureClient as c, addMiddleware as d, enhanceRouter as e, isLazy as f, getRouter as g, createAssertedLazyProcedure as h, isProcedure as i, createORPCErrorConstructorMap as j, getLazyMeta as k, lazy as l, mergeCurrentContext as m, middlewareOutputFn as n, isStartWithMiddlewares as o, mergeMiddlewares as p, call as q, getHiddenRouterContract as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u, validateORPCError as v, createAccessibleLazyRouter as w, resolveContractProcedures as x, unlazyRouter as y };
416
+ export { LAZY_SYMBOL as L, Procedure as P, createContractedProcedure as a, addMiddleware as b, createProcedureClient as c, isLazy as d, enhanceRouter as e, createAssertedLazyProcedure as f, getRouter as g, createORPCErrorConstructorMap as h, isProcedure as i, getLazyMeta as j, middlewareOutputFn as k, lazy as l, mergeCurrentContext as m, isStartWithMiddlewares as n, mergeMiddlewares as o, call as p, getHiddenRouterContract as q, createAccessibleLazyRouter as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u, validateORPCError as v, resolveContractProcedures as w, unlazyRouter as x };
@@ -0,0 +1,12 @@
1
+ import { C as Context } from './server.CYNGeoCm.js';
2
+ import { b as StandardHandleOptions } from './server.Bmh5xd4n.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
+ declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
10
+
11
+ export { resolveFriendlyStandardHandleOptions as r };
12
+ export type { FriendlyStandardHandleOptions as F };
@@ -0,0 +1,12 @@
1
+ import { C as Context } from './server.CYNGeoCm.mjs';
2
+ import { b as StandardHandleOptions } from './server.gqRxT-yN.mjs';
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
+ declare function resolveFriendlyStandardHandleOptions<T extends Context>(options: FriendlyStandardHandleOptions<T>): StandardHandleOptions<T>;
10
+
11
+ export { resolveFriendlyStandardHandleOptions as r };
12
+ export type { FriendlyStandardHandleOptions as F };
@@ -0,0 +1,219 @@
1
+ import { toHttpPath, StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
2
+ import { ORPCError, toORPCError } from '@orpc/client';
3
+ import { toArray, intercept, runWithSpan, ORPC_NAME, isAsyncIteratorObject, asyncIteratorWithSpan, setSpanError, parseEmptyableJSON, NullProtoObj, value } from '@orpc/shared';
4
+ import { flattenHeader } from '@orpc/standard-server';
5
+ import { c as createProcedureClient, t as traverseContractProcedures, i as isProcedure, u as unlazy, g as getRouter, a as createContractedProcedure } from './server.7jWaIryJ.mjs';
6
+
7
+ class CompositeStandardHandlerPlugin {
8
+ plugins;
9
+ constructor(plugins = []) {
10
+ this.plugins = [...plugins].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
11
+ }
12
+ init(options, router) {
13
+ for (const plugin of this.plugins) {
14
+ plugin.init?.(options, router);
15
+ }
16
+ }
17
+ }
18
+
19
+ class StandardHandler {
20
+ constructor(router, matcher, codec, options) {
21
+ this.matcher = matcher;
22
+ this.codec = codec;
23
+ const plugins = new CompositeStandardHandlerPlugin(options.plugins);
24
+ plugins.init(options, router);
25
+ this.interceptors = toArray(options.interceptors);
26
+ this.clientInterceptors = toArray(options.clientInterceptors);
27
+ this.rootInterceptors = toArray(options.rootInterceptors);
28
+ this.matcher.init(router);
29
+ }
30
+ interceptors;
31
+ clientInterceptors;
32
+ rootInterceptors;
33
+ async handle(request, options) {
34
+ const prefix = options.prefix?.replace(/\/$/, "") || void 0;
35
+ if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
36
+ return { matched: false, response: void 0 };
37
+ }
38
+ return intercept(
39
+ this.rootInterceptors,
40
+ { ...options, request, prefix },
41
+ async (interceptorOptions) => {
42
+ return runWithSpan(
43
+ { name: `${request.method} ${request.url.pathname}` },
44
+ async (span) => {
45
+ let step;
46
+ try {
47
+ return await intercept(
48
+ this.interceptors,
49
+ interceptorOptions,
50
+ async ({ request: request2, context, prefix: prefix2 }) => {
51
+ const method = request2.method;
52
+ const url = request2.url;
53
+ const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
54
+ const match = await runWithSpan(
55
+ { name: "find_procedure" },
56
+ () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
57
+ );
58
+ if (!match) {
59
+ return { matched: false, response: void 0 };
60
+ }
61
+ span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
62
+ span?.setAttribute("rpc.system", ORPC_NAME);
63
+ span?.setAttribute("rpc.method", match.path.join("."));
64
+ step = "decode_input";
65
+ let input = await runWithSpan(
66
+ { name: "decode_input" },
67
+ () => this.codec.decode(request2, match.params, match.procedure)
68
+ );
69
+ step = void 0;
70
+ if (isAsyncIteratorObject(input)) {
71
+ input = asyncIteratorWithSpan(
72
+ { name: "consume_event_iterator_input", signal: request2.signal },
73
+ input
74
+ );
75
+ }
76
+ const client = createProcedureClient(match.procedure, {
77
+ context,
78
+ path: match.path,
79
+ interceptors: this.clientInterceptors
80
+ });
81
+ step = "call_procedure";
82
+ const output = await client(input, {
83
+ signal: request2.signal,
84
+ lastEventId: flattenHeader(request2.headers["last-event-id"])
85
+ });
86
+ step = void 0;
87
+ const response = this.codec.encode(output, match.procedure);
88
+ return {
89
+ matched: true,
90
+ response
91
+ };
92
+ }
93
+ );
94
+ } catch (e) {
95
+ if (step !== "call_procedure") {
96
+ setSpanError(span, e);
97
+ }
98
+ const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
99
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
100
+ cause: e
101
+ }) : toORPCError(e);
102
+ const response = this.codec.encodeError(error);
103
+ return {
104
+ matched: true,
105
+ response
106
+ };
107
+ }
108
+ }
109
+ );
110
+ }
111
+ );
112
+ }
113
+ }
114
+
115
+ class StandardRPCCodec {
116
+ constructor(serializer) {
117
+ this.serializer = serializer;
118
+ }
119
+ async decode(request, _params, _procedure) {
120
+ const serialized = request.method === "GET" ? parseEmptyableJSON(request.url.searchParams.getAll("data").at(-1)) : await request.body();
121
+ return this.serializer.deserialize(serialized);
122
+ }
123
+ encode(output, _procedure) {
124
+ return {
125
+ status: 200,
126
+ headers: {},
127
+ body: this.serializer.serialize(output)
128
+ };
129
+ }
130
+ encodeError(error) {
131
+ return {
132
+ status: error.status,
133
+ headers: {},
134
+ body: this.serializer.serialize(error.toJSON())
135
+ };
136
+ }
137
+ }
138
+
139
+ class StandardRPCMatcher {
140
+ filter;
141
+ tree = new NullProtoObj();
142
+ pendingRouters = [];
143
+ constructor(options = {}) {
144
+ this.filter = options.filter ?? true;
145
+ }
146
+ init(router, path = []) {
147
+ const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
148
+ if (!value(this.filter, traverseOptions)) {
149
+ return;
150
+ }
151
+ const { path: path2, contract } = traverseOptions;
152
+ const httpPath = toHttpPath(path2);
153
+ if (isProcedure(contract)) {
154
+ this.tree[httpPath] = {
155
+ path: path2,
156
+ contract,
157
+ procedure: contract,
158
+ // this mean dev not used contract-first so we can used contract as procedure directly
159
+ router
160
+ };
161
+ } else {
162
+ this.tree[httpPath] = {
163
+ path: path2,
164
+ contract,
165
+ procedure: void 0,
166
+ router
167
+ };
168
+ }
169
+ });
170
+ this.pendingRouters.push(...laziedOptions.map((option) => ({
171
+ ...option,
172
+ httpPathPrefix: toHttpPath(option.path)
173
+ })));
174
+ }
175
+ async match(_method, pathname) {
176
+ if (this.pendingRouters.length) {
177
+ const newPendingRouters = [];
178
+ for (const pendingRouter of this.pendingRouters) {
179
+ if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
180
+ const { default: router } = await unlazy(pendingRouter.router);
181
+ this.init(router, pendingRouter.path);
182
+ } else {
183
+ newPendingRouters.push(pendingRouter);
184
+ }
185
+ }
186
+ this.pendingRouters = newPendingRouters;
187
+ }
188
+ const match = this.tree[pathname];
189
+ if (!match) {
190
+ return void 0;
191
+ }
192
+ if (!match.procedure) {
193
+ const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
194
+ if (!isProcedure(maybeProcedure)) {
195
+ throw new Error(`
196
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
197
+ Ensure that the procedure is correctly defined and matches the expected contract.
198
+ `);
199
+ }
200
+ match.procedure = createContractedProcedure(maybeProcedure, match.contract);
201
+ }
202
+ return {
203
+ path: match.path,
204
+ procedure: match.procedure
205
+ };
206
+ }
207
+ }
208
+
209
+ class StandardRPCHandler extends StandardHandler {
210
+ constructor(router, options = {}) {
211
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
212
+ const serializer = new StandardRPCSerializer(jsonSerializer);
213
+ const matcher = new StandardRPCMatcher(options);
214
+ const codec = new StandardRPCCodec(serializer);
215
+ super(router, matcher, codec, options);
216
+ }
217
+ }
218
+
219
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as S, StandardRPCCodec as a, StandardRPCHandler as b, StandardRPCMatcher as c };
@@ -0,0 +1,32 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { b as AnyRouter, C as Context, R as Router } from './server.CYNGeoCm.mjs';
3
+ import { i as StandardMatcher, h as StandardMatchResult, e as StandardHandlerOptions, f as StandardHandler } from './server.gqRxT-yN.mjs';
4
+ import { HTTPPath } from '@orpc/client';
5
+ import { Value } from '@orpc/shared';
6
+ import { T as TraverseContractProcedureCallbackOptions } from './server.DhJj-1X9.mjs';
7
+
8
+ interface StandardRPCMatcherOptions {
9
+ /**
10
+ * Filter procedures. Return `false` to exclude a procedure from matching.
11
+ *
12
+ * @default true
13
+ */
14
+ filter?: Value<boolean, [options: TraverseContractProcedureCallbackOptions]>;
15
+ }
16
+ declare class StandardRPCMatcher implements StandardMatcher {
17
+ private readonly filter;
18
+ private readonly tree;
19
+ private pendingRouters;
20
+ constructor(options?: StandardRPCMatcherOptions);
21
+ init(router: AnyRouter, path?: readonly string[]): void;
22
+ match(_method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
23
+ }
24
+
25
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions, StandardRPCMatcherOptions {
26
+ }
27
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
28
+ constructor(router: Router<any, T>, options?: StandardRPCHandlerOptions<T>);
29
+ }
30
+
31
+ export { StandardRPCHandler as a, StandardRPCMatcher as c };
32
+ export type { StandardRPCHandlerOptions as S, StandardRPCMatcherOptions as b };
@@ -0,0 +1,36 @@
1
+ import { ORPCError, fallbackContractConfig } from '@orpc/contract';
2
+
3
+ const STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL = Symbol("STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT");
4
+ class StrictGetMethodPlugin {
5
+ error;
6
+ order = 7e6;
7
+ constructor(options = {}) {
8
+ this.error = options.error ?? new ORPCError("METHOD_NOT_SUPPORTED");
9
+ }
10
+ init(options) {
11
+ options.rootInterceptors ??= [];
12
+ options.clientInterceptors ??= [];
13
+ options.rootInterceptors.unshift((options2) => {
14
+ const isGetMethod = options2.request.method === "GET";
15
+ return options2.next({
16
+ ...options2,
17
+ context: {
18
+ ...options2.context,
19
+ [STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL]: isGetMethod
20
+ }
21
+ });
22
+ });
23
+ options.clientInterceptors.unshift((options2) => {
24
+ if (typeof options2.context[STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL] !== "boolean") {
25
+ throw new TypeError("[StrictGetMethodPlugin] strict GET method context has been corrupted or modified by another plugin or interceptor");
26
+ }
27
+ const procedureMethod = fallbackContractConfig("defaultMethod", options2.procedure["~orpc"].route.method);
28
+ if (options2.context[STRICT_GET_METHOD_PLUGIN_IS_GET_METHOD_CONTEXT_SYMBOL] && procedureMethod !== "GET") {
29
+ throw this.error;
30
+ }
31
+ return options2.next();
32
+ });
33
+ }
34
+ }
35
+
36
+ export { StrictGetMethodPlugin as S };
@@ -0,0 +1,74 @@
1
+ import { HTTPPath, ORPCError } from '@orpc/client';
2
+ import { Meta } from '@orpc/contract';
3
+ import { Interceptor } from '@orpc/shared';
4
+ import { StandardResponse, StandardLazyRequest } from '@orpc/standard-server';
5
+ import { C as Context, R as Router, b as AnyRouter, A as AnyProcedure, d as ProcedureClientInterceptorOptions } from './server.CYNGeoCm.js';
6
+
7
+ interface StandardHandlerPlugin<T extends Context> {
8
+ order?: number;
9
+ init?(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
10
+ }
11
+ declare class CompositeStandardHandlerPlugin<T extends Context, TPlugin extends StandardHandlerPlugin<T>> implements StandardHandlerPlugin<T> {
12
+ protected readonly plugins: TPlugin[];
13
+ constructor(plugins?: readonly TPlugin[]);
14
+ init(options: StandardHandlerOptions<T>, router: Router<any, T>): void;
15
+ }
16
+
17
+ type StandardParams = Record<string, string>;
18
+ type StandardMatchResult = {
19
+ path: readonly string[];
20
+ procedure: AnyProcedure;
21
+ params?: StandardParams;
22
+ } | undefined;
23
+ interface StandardMatcher {
24
+ init(router: AnyRouter): void;
25
+ match(method: string, pathname: HTTPPath): Promise<StandardMatchResult>;
26
+ }
27
+ interface StandardCodec {
28
+ encode(output: unknown, procedure: AnyProcedure): StandardResponse;
29
+ encodeError(error: ORPCError<any, any>): StandardResponse;
30
+ decode(request: StandardLazyRequest, params: StandardParams | undefined, procedure: AnyProcedure): Promise<unknown>;
31
+ }
32
+
33
+ interface StandardHandleOptions<T extends Context> {
34
+ prefix?: HTTPPath;
35
+ context: T;
36
+ }
37
+ type StandardHandleResult = {
38
+ matched: true;
39
+ response: StandardResponse;
40
+ } | {
41
+ matched: false;
42
+ response: undefined;
43
+ };
44
+ interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
45
+ request: StandardLazyRequest;
46
+ }
47
+ interface StandardHandlerOptions<TContext extends Context> {
48
+ plugins?: StandardHandlerPlugin<TContext>[];
49
+ /**
50
+ * Interceptors at the request level, helpful when you want catch errors
51
+ */
52
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
53
+ /**
54
+ * Interceptors at the root level, helpful when you want override the request/response
55
+ */
56
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
57
+ /**
58
+ *
59
+ * Interceptors for procedure client.
60
+ */
61
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
62
+ }
63
+ declare class StandardHandler<T extends Context> {
64
+ private readonly matcher;
65
+ private readonly codec;
66
+ private readonly interceptors;
67
+ private readonly clientInterceptors;
68
+ private readonly rootInterceptors;
69
+ constructor(router: Router<any, T>, matcher: StandardMatcher, codec: StandardCodec, options: NoInfer<StandardHandlerOptions<T>>);
70
+ handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
71
+ }
72
+
73
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as f };
74
+ export type { StandardCodec as S, StandardParams as a, StandardHandleOptions as b, StandardHandleResult as c, StandardHandlerInterceptorOptions as d, StandardHandlerOptions as e, StandardHandlerPlugin as g, StandardMatchResult as h, StandardMatcher as i };