@orpc/server 0.0.0-next.8900489 → 0.0.0-next.890a8ab

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 +28 -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 +62 -11
  12. package/dist/adapters/fetch/index.d.ts +62 -11
  13. package/dist/adapters/fetch/index.mjs +109 -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 +64 -22
  18. package/dist/adapters/node/index.d.ts +64 -22
  19. package/dist/adapters/node/index.mjs +88 -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 +162 -15
  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.B7b2w3_i.d.ts +12 -0
  45. package/dist/shared/server.BEFBl-Cb.d.mts +12 -0
  46. package/dist/shared/server.BU4WI18A.d.mts +32 -0
  47. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  48. package/dist/shared/server.Bmh5xd4n.d.ts +74 -0
  49. package/dist/shared/server.BohymmQ6.mjs +219 -0
  50. package/dist/shared/{server.BtxZnWJ9.mjs → server.CQr6WNc2.mjs} +103 -69
  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 +70 -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.B3Tm0IXY.d.ts +0 -75
  67. package/dist/shared/server.BeJithK4.d.mts +0 -75
  68. package/dist/shared/server.Bz_xNBjz.d.mts +0 -8
  69. package/dist/shared/server.DoP20NVH.mjs +0 -29
  70. package/dist/shared/server.EhgR_5_I.d.ts +0 -8
  71. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
  72. package/dist/shared/server.jG7ZuX3S.mjs +0 -158
@@ -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.CQr6WNc2.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 };
@@ -1,6 +1,7 @@
1
1
  import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
+ import { resolveMaybeOptionalOptions, toArray, value, runWithSpan, intercept, isAsyncIteratorObject, asyncIteratorWithSpan } from '@orpc/shared';
2
3
  import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
- import { value, intercept, toError } from '@orpc/shared';
4
+ import { experimental_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,31 +108,48 @@ 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);
113
119
  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)
120
+ const output = await runWithSpan(
121
+ { name: "call_procedure", signal: callerOptions?.signal },
122
+ (span) => {
123
+ span?.setAttribute("procedure.path", [...path]);
124
+ return intercept(
125
+ toArray(options.interceptors),
126
+ {
127
+ context,
128
+ input,
129
+ // input only optional when it undefinable so we can safely cast it
130
+ errors,
131
+ path,
132
+ procedure,
133
+ signal: callerOptions?.signal,
134
+ lastEventId: callerOptions?.lastEventId
135
+ },
136
+ (interceptorOptions) => executeProcedureInternal(interceptorOptions.procedure, interceptorOptions)
137
+ );
138
+ }
127
139
  );
140
+ if (isAsyncIteratorObject(output)) {
141
+ if (output instanceof experimental_HibernationEventIterator) {
142
+ return output;
143
+ }
144
+ return asyncIteratorWithSpan(
145
+ { name: "consume_event_iterator_output", signal: callerOptions?.signal },
146
+ output
147
+ );
148
+ }
149
+ return output;
128
150
  } catch (e) {
129
151
  if (!(e instanceof ORPCError)) {
130
- throw toError(e);
152
+ throw e;
131
153
  }
132
154
  const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
133
155
  throw validated;
@@ -139,65 +161,80 @@ async function validateInput(procedure, input) {
139
161
  if (!schema) {
140
162
  return input;
141
163
  }
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;
164
+ return runWithSpan(
165
+ { name: "validate_input" },
166
+ async () => {
167
+ const result = await schema["~standard"].validate(input);
168
+ if (result.issues) {
169
+ throw new ORPCError("BAD_REQUEST", {
170
+ message: "Input validation failed",
171
+ data: {
172
+ issues: result.issues
173
+ },
174
+ cause: new ValidationError({ message: "Input validation failed", issues: result.issues })
175
+ });
176
+ }
177
+ return result.value;
178
+ }
179
+ );
153
180
  }
154
181
  async function validateOutput(procedure, output) {
155
182
  const schema = procedure["~orpc"].outputSchema;
156
183
  if (!schema) {
157
184
  return output;
158
185
  }
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;
186
+ return runWithSpan(
187
+ { name: "validate_output" },
188
+ async () => {
189
+ const result = await schema["~standard"].validate(output);
190
+ if (result.issues) {
191
+ throw new ORPCError("INTERNAL_SERVER_ERROR", {
192
+ message: "Output validation failed",
193
+ cause: new ValidationError({ message: "Output validation failed", issues: result.issues })
194
+ });
195
+ }
196
+ return result.value;
197
+ }
198
+ );
167
199
  }
168
200
  async function executeProcedureInternal(procedure, options) {
169
201
  const middlewares = procedure["~orpc"].middlewares;
170
202
  const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
171
203
  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);
204
+ const next = async (index, context, input) => {
205
+ let currentInput = input;
180
206
  if (index === inputValidationIndex) {
181
207
  currentInput = await validateInput(procedure, currentInput);
182
208
  }
183
209
  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
- };
210
+ const output = mid ? await runWithSpan(
211
+ { name: `middleware.${mid.name}`, signal: options.signal },
212
+ async (span) => {
213
+ span?.setAttribute("middleware.index", index);
214
+ span?.setAttribute("middleware.name", mid.name);
215
+ const result = await mid({
216
+ ...options,
217
+ context,
218
+ next: async (...[nextOptions]) => {
219
+ const nextContext = nextOptions?.context ?? {};
220
+ return {
221
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
222
+ context: nextContext
223
+ };
224
+ }
225
+ }, currentInput, middlewareOutputFn);
226
+ return result.output;
227
+ }
228
+ ) : await runWithSpan(
229
+ { name: "handler", signal: options.signal },
230
+ () => procedure["~orpc"].handler({ ...options, context, input: currentInput })
231
+ );
191
232
  if (index === outputValidationIndex) {
192
- const validatedOutput = await validateOutput(procedure, result.output);
193
- return {
194
- context: result.context,
195
- output: validatedOutput
196
- };
233
+ return await validateOutput(procedure, output);
197
234
  }
198
- return result;
235
+ return output;
199
236
  };
200
- return (await next()).output;
237
+ return next(0, options.context, options.input);
201
238
  }
202
239
 
203
240
  const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
@@ -364,11 +401,8 @@ function createContractedProcedure(procedure, contract) {
364
401
  });
365
402
  }
366
403
  function call(procedure, input, ...rest) {
367
- return createProcedureClient(procedure, ...rest)(input);
368
- }
369
-
370
- function toHttpPath(path) {
371
- return `/${path.map(encodeURIComponent).join("/")}`;
404
+ const options = resolveMaybeOptionalOptions(rest);
405
+ return createProcedureClient(procedure, options)(input, options);
372
406
  }
373
407
 
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 };
408
+ 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 };
@@ -1,12 +1,11 @@
1
- import { ORPCErrorCode, ORPCErrorOptions, ORPCError, ClientContext, Client } from '@orpc/client';
2
- import { MaybeOptionalOptions, Promisable, Interceptor, Value } from '@orpc/shared';
3
- import { ErrorMap, ErrorMapItem, InferSchemaInput, HTTPPath, AnySchema, Meta, ContractProcedureDef, InferSchemaOutput, ErrorFromErrorMap, AnyContractRouter, ContractProcedure } from '@orpc/contract';
1
+ import { ORPCErrorCode, ORPCErrorOptions, ORPCError, HTTPPath, ClientContext, Client } from '@orpc/client';
2
+ import { ErrorMap, ErrorMapItem, InferSchemaInput, AnySchema, Meta, ContractProcedureDef, InferSchemaOutput, ErrorFromErrorMap, AnyContractRouter, ContractProcedure } from '@orpc/contract';
3
+ import { MaybeOptionalOptions, Promisable, Interceptor, PromiseWithError, Value } from '@orpc/shared';
4
4
 
5
- type Context = Record<string, any>;
5
+ type Context = Record<PropertyKey, any>;
6
6
  type MergedInitialContext<TInitial extends Context, TAdditional extends Context, TCurrent extends Context> = TInitial & Omit<TAdditional, keyof TCurrent>;
7
7
  type MergedCurrentContext<T extends Context, U extends Context> = Omit<T, keyof U> & U;
8
8
  declare function mergeCurrentContext<T extends Context, U extends Context>(context: T, other: U): MergedCurrentContext<T, U>;
9
- type ContextExtendsGuard<T extends Context, U extends Context> = T extends U ? unknown : never;
10
9
 
11
10
  type ORPCErrorConstructorMapItemOptions<TData> = Omit<ORPCErrorOptions<TData>, 'defined' | 'status'>;
12
11
  type ORPCErrorConstructorMapItem<TCode extends ORPCErrorCode, TInData> = (...rest: MaybeOptionalOptions<ORPCErrorConstructorMapItemOptions<TInData>>) => ORPCError<TCode, TInData>;
@@ -29,6 +28,11 @@ interface Lazy<T> {
29
28
  };
30
29
  }
31
30
  type Lazyable<T> = T | Lazy<T>;
31
+ /**
32
+ * Creates a lazy-loaded item.
33
+ *
34
+ * @warning The `prefix` in `meta` only holds metadata and does not apply the prefix to the lazy router, use `os.prefix(...).lazy(...)` instead.
35
+ */
32
36
  declare function lazy<T>(loader: () => Promise<{
33
37
  default: T;
34
38
  }>, meta?: LazyMeta): Lazy<T>;
@@ -57,7 +61,15 @@ interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends
57
61
  outputValidationIndex: number;
58
62
  handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
59
63
  }
64
+ /**
65
+ * This class represents a procedure.
66
+ *
67
+ * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
68
+ */
60
69
  declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
70
+ /**
71
+ * This property holds the defined options.
72
+ */
61
73
  '~orpc': ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>;
62
74
  constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>);
63
75
  }
@@ -88,6 +100,11 @@ interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstruct
88
100
  next: MiddlewareNextFn<TOutput>;
89
101
  errors: TErrorConstructorMap;
90
102
  }
103
+ /**
104
+ * A function that represents a middleware.
105
+ *
106
+ * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
107
+ */
91
108
  interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
92
109
  (options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
93
110
  }
@@ -98,47 +115,80 @@ interface MapInputMiddleware<TInput, TMappedInput> {
98
115
  declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
99
116
 
100
117
  type ProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
101
- interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TInputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
118
+ interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> {
102
119
  context: TInitialContext;
103
- input: InferSchemaInput<TInputSchema>;
120
+ input: unknown;
104
121
  errors: ORPCErrorConstructorMap<TErrorMap>;
105
122
  path: readonly string[];
106
123
  procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
107
124
  signal?: AbortSignal;
108
125
  lastEventId: string | undefined;
109
126
  }
110
- /**
111
- * Options for creating a procedure caller with comprehensive type safety
112
- */
113
- type CreateProcedureClientOptions<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
127
+ type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
114
128
  /**
115
129
  * This is helpful for logging and analytics.
116
130
  */
117
131
  path?: readonly string[];
118
- interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TInputSchema, TErrorMap, TMeta>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>[];
132
+ interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, PromiseWithError<InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>>[];
119
133
  } & (Record<never, never> extends TInitialContext ? {
120
- context?: Value<TInitialContext, [clientContext: TClientContext]>;
134
+ context?: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
121
135
  } : {
122
- context: Value<TInitialContext, [clientContext: TClientContext]>;
136
+ context: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
123
137
  });
124
- declare function createProcedureClient<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, TErrorMap, TMeta>>, ...[options]: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TInputSchema, TOutputSchema, TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TInputSchema, TOutputSchema, TErrorMap>;
138
+ /**
139
+ * Create Server-side client from a procedure.
140
+ *
141
+ * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
142
+ */
143
+ declare function createProcedureClient<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext>(lazyableProcedure: Lazyable<Procedure<TInitialContext, any, TInputSchema, TOutputSchema, TErrorMap, TMeta>>, ...rest: MaybeOptionalOptions<CreateProcedureClientOptions<TInitialContext, TOutputSchema, TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TInputSchema, TOutputSchema, TErrorMap>;
125
144
 
145
+ /**
146
+ * Represents a router, which defines a hierarchical structure of procedures.
147
+ *
148
+ * @info A procedure is a router too.
149
+ * @see {@link https://orpc.unnoq.com/docs/contract-first/define-contract#contract-router Contract Router Docs}
150
+ */
126
151
  type Router<T extends AnyContractRouter, TInitialContext extends Context> = T extends ContractProcedure<infer UInputSchema, infer UOutputSchema, infer UErrorMap, infer UMeta> ? Procedure<TInitialContext, any, UInputSchema, UOutputSchema, UErrorMap, UMeta> : {
127
152
  [K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
128
153
  };
129
154
  type AnyRouter = Router<any, any>;
130
155
  type InferRouterInitialContext<T extends AnyRouter> = T extends Router<any, infer UInitialContext> ? UInitialContext : never;
156
+ /**
157
+ * Infer all initial context of the router.
158
+ *
159
+ * @info A procedure is a router too.
160
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
161
+ */
131
162
  type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any, any> ? UInitialContext : {
132
163
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
133
164
  };
165
+ /**
166
+ * Infer all current context of the router.
167
+ *
168
+ * @info A procedure is a router too.
169
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
170
+ */
134
171
  type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any, any> ? UCurrentContext : {
135
172
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
136
173
  };
174
+ /**
175
+ * Infer all router inputs
176
+ *
177
+ * @info A procedure is a router too.
178
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
179
+ */
137
180
  type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
138
181
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
139
182
  };
183
+ /**
184
+ * Infer all router outputs
185
+ *
186
+ * @info A procedure is a router too.
187
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
188
+ */
140
189
  type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
141
190
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
142
191
  };
143
192
 
144
- export { type AnyProcedure as A, type MiddlewareOptions as B, type Context as C, middlewareOutputFn as D, type ProcedureHandlerOptions as E, type ProcedureDef as F, isProcedure as G, createProcedureClient as H, type InferRouterInitialContext as I, type InferRouterInitialContexts as J, type InferRouterCurrentContexts as K, type Lazyable as L, type Middleware as M, type InferRouterInputs as N, type ORPCErrorConstructorMap as O, type ProcedureClientInterceptorOptions as P, type InferRouterOutputs as Q, type Router as R, type AnyRouter as a, Procedure as b, type ContextExtendsGuard as c, type MergedCurrentContext as d, type MergedInitialContext as e, type MapInputMiddleware as f, type CreateProcedureClientOptions as g, type ProcedureClient as h, type AnyMiddleware as i, type Lazy as j, type ProcedureHandler as k, type ORPCErrorConstructorMapItemOptions as l, mergeCurrentContext as m, type ORPCErrorConstructorMapItem as n, createORPCErrorConstructorMap as o, LAZY_SYMBOL as p, type LazyMeta as q, lazy as r, isLazy as s, getLazyMeta as t, unlazy as u, validateORPCError as v, type MiddlewareResult as w, type MiddlewareNextFnOptions as x, type MiddlewareNextFn as y, type MiddlewareOutputFn as z };
193
+ export { middlewareOutputFn as B, isProcedure as F, createProcedureClient as G, Procedure as P, mergeCurrentContext as m, createORPCErrorConstructorMap as n, LAZY_SYMBOL as o, lazy as q, isLazy as r, getLazyMeta as s, unlazy as u, validateORPCError as v };
194
+ export type { AnyProcedure as A, Context as C, ProcedureHandlerOptions as D, ProcedureDef as E, InferRouterInitialContexts as H, InferRouterInitialContext as I, InferRouterCurrentContexts as J, InferRouterInputs as K, Lazyable as L, MergedInitialContext as M, InferRouterOutputs as N, ORPCErrorConstructorMap as O, Router as R, AnyMiddleware as a, AnyRouter as b, Lazy as c, ProcedureClientInterceptorOptions as d, Middleware as e, MergedCurrentContext as f, MapInputMiddleware as g, CreateProcedureClientOptions as h, ProcedureClient as i, ProcedureHandler as j, ORPCErrorConstructorMapItemOptions as k, ORPCErrorConstructorMapItem as l, LazyMeta as p, MiddlewareResult as t, MiddlewareNextFnOptions as w, MiddlewareNextFn as x, MiddlewareOutputFn as y, MiddlewareOptions as z };