@orpc/server 0.0.0-next.ea0903c → 0.0.0-next.eaf61c7

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 (59) hide show
  1. package/README.md +18 -22
  2. package/dist/adapters/aws-lambda/index.d.mts +45 -0
  3. package/dist/adapters/aws-lambda/index.d.ts +45 -0
  4. package/dist/adapters/aws-lambda/index.mjs +41 -0
  5. package/dist/adapters/bun-ws/index.d.mts +35 -0
  6. package/dist/adapters/bun-ws/index.d.ts +35 -0
  7. package/dist/adapters/bun-ws/index.mjs +46 -0
  8. package/dist/adapters/crossws/index.d.mts +30 -0
  9. package/dist/adapters/crossws/index.d.ts +30 -0
  10. package/dist/adapters/crossws/index.mjs +46 -0
  11. package/dist/adapters/fetch/index.d.mts +34 -10
  12. package/dist/adapters/fetch/index.d.ts +34 -10
  13. package/dist/adapters/fetch/index.mjs +109 -8
  14. package/dist/adapters/message-port/index.d.mts +28 -0
  15. package/dist/adapters/message-port/index.d.ts +28 -0
  16. package/dist/adapters/message-port/index.mjs +41 -0
  17. package/dist/adapters/node/index.d.mts +35 -11
  18. package/dist/adapters/node/index.d.ts +35 -11
  19. package/dist/adapters/node/index.mjs +23 -13
  20. package/dist/adapters/standard/index.d.mts +4 -4
  21. package/dist/adapters/standard/index.d.ts +4 -4
  22. package/dist/adapters/standard/index.mjs +4 -3
  23. package/dist/adapters/websocket/index.d.mts +51 -0
  24. package/dist/adapters/websocket/index.d.ts +51 -0
  25. package/dist/adapters/websocket/index.mjs +69 -0
  26. package/dist/adapters/ws/index.d.mts +28 -0
  27. package/dist/adapters/ws/index.d.ts +28 -0
  28. package/dist/adapters/ws/index.mjs +39 -0
  29. package/dist/hibernation/index.d.mts +44 -0
  30. package/dist/hibernation/index.d.ts +44 -0
  31. package/dist/hibernation/index.mjs +65 -0
  32. package/dist/index.d.mts +597 -38
  33. package/dist/index.d.ts +597 -38
  34. package/dist/index.mjs +163 -17
  35. package/dist/plugins/index.d.mts +135 -9
  36. package/dist/plugins/index.d.ts +135 -9
  37. package/dist/plugins/index.mjs +155 -9
  38. package/dist/shared/{server.BMkFIQUb.d.mts → server.-ACo36I0.d.ts} +17 -9
  39. package/dist/shared/server.BPAWobQg.d.ts +12 -0
  40. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  41. package/dist/shared/server.Bd52nNaH.d.mts +12 -0
  42. package/dist/shared/{server.89QkKw3a.d.mts → server.BliFSTnG.d.mts} +2 -2
  43. package/dist/shared/{server.D9QduY95.mjs → server.CHvOkcM3.mjs} +42 -17
  44. package/dist/shared/{server.D0YVcfZk.d.mts → server.DD2C4ujN.d.mts} +62 -13
  45. package/dist/shared/{server.D0YVcfZk.d.ts → server.DD2C4ujN.d.ts} +62 -13
  46. package/dist/shared/{server.CjWkNG6l.mjs → server.DG7Tamti.mjs} +21 -24
  47. package/dist/shared/{server.BVwwTHyO.mjs → server.DZ5BIITo.mjs} +1 -1
  48. package/dist/shared/{server.ywWqDZgA.d.ts → server.Dq8xr7PQ.d.mts} +17 -9
  49. package/dist/shared/{server.taqJyaMn.d.ts → server.IG2MjhrD.d.ts} +2 -2
  50. package/package.json +59 -20
  51. package/dist/adapters/hono/index.d.mts +0 -22
  52. package/dist/adapters/hono/index.d.ts +0 -22
  53. package/dist/adapters/hono/index.mjs +0 -32
  54. package/dist/adapters/next/index.d.mts +0 -29
  55. package/dist/adapters/next/index.d.ts +0 -29
  56. package/dist/adapters/next/index.mjs +0 -29
  57. package/dist/shared/server.B1S3zwuw.d.mts +0 -8
  58. package/dist/shared/server.BT0gne12.d.ts +0 -8
  59. package/dist/shared/server.Et1O6Bm7.mjs +0 -98
@@ -1,7 +1,112 @@
1
- import { value } from '@orpc/shared';
1
+ import { value, isAsyncIteratorObject } from '@orpc/shared';
2
+ import { flattenHeader } from '@orpc/standard-server';
3
+ import { parseBatchRequest, toBatchResponse } from '@orpc/standard-server/batch';
4
+ import { ORPCError } from '@orpc/client';
5
+ export { S as StrictGetMethodPlugin } from '../shared/server.BW-nUGgA.mjs';
6
+ import '@orpc/contract';
7
+
8
+ class BatchHandlerPlugin {
9
+ maxSize;
10
+ mapRequestItem;
11
+ successStatus;
12
+ headers;
13
+ order = 5e6;
14
+ constructor(options = {}) {
15
+ this.maxSize = options.maxSize ?? 10;
16
+ this.mapRequestItem = options.mapRequestItem ?? ((request, { request: batchRequest }) => ({
17
+ ...request,
18
+ headers: {
19
+ ...batchRequest.headers,
20
+ ...request.headers
21
+ }
22
+ }));
23
+ this.successStatus = options.successStatus ?? 207;
24
+ this.headers = options.headers ?? {};
25
+ }
26
+ init(options) {
27
+ options.rootInterceptors ??= [];
28
+ options.rootInterceptors.unshift(async (options2) => {
29
+ const xHeader = flattenHeader(options2.request.headers["x-orpc-batch"]);
30
+ if (xHeader === void 0) {
31
+ return options2.next();
32
+ }
33
+ let isParsing = false;
34
+ try {
35
+ isParsing = true;
36
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
37
+ isParsing = false;
38
+ const maxSize = await value(this.maxSize, options2);
39
+ if (parsed.length > maxSize) {
40
+ return {
41
+ matched: true,
42
+ response: {
43
+ status: 413,
44
+ headers: {},
45
+ body: "Batch request size exceeds the maximum allowed size"
46
+ }
47
+ };
48
+ }
49
+ const responses = parsed.map(
50
+ (request, index) => {
51
+ const mapped = this.mapRequestItem(request, options2);
52
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
53
+ if (matched) {
54
+ if (response2.body instanceof Blob || response2.body instanceof FormData || isAsyncIteratorObject(response2.body)) {
55
+ return {
56
+ index,
57
+ status: 500,
58
+ headers: {},
59
+ body: "Batch responses do not support file/blob, or event-iterator. Please call this procedure separately outside of the batch request."
60
+ };
61
+ }
62
+ return { ...response2, index };
63
+ }
64
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
65
+ }).catch(() => {
66
+ return { index, status: 500, headers: {}, body: "Internal server error" };
67
+ });
68
+ }
69
+ );
70
+ await Promise.race(responses);
71
+ const status = await value(this.successStatus, responses, options2);
72
+ const headers = await value(this.headers, responses, options2);
73
+ const response = await toBatchResponse({
74
+ status,
75
+ headers,
76
+ mode: xHeader === "buffered" ? "buffered" : "streaming",
77
+ body: async function* () {
78
+ const promises = [...responses];
79
+ while (true) {
80
+ const handling = promises.filter((p) => p !== void 0);
81
+ if (handling.length === 0) {
82
+ return;
83
+ }
84
+ const result = await Promise.race(handling);
85
+ promises[result.index] = void 0;
86
+ yield result;
87
+ }
88
+ }()
89
+ });
90
+ return {
91
+ matched: true,
92
+ response
93
+ };
94
+ } catch (cause) {
95
+ if (isParsing) {
96
+ return {
97
+ matched: true,
98
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
99
+ };
100
+ }
101
+ throw cause;
102
+ }
103
+ });
104
+ }
105
+ }
2
106
 
3
107
  class CORSPlugin {
4
108
  options;
109
+ order = 9e6;
5
110
  constructor(options = {}) {
6
111
  const defaults = {
7
112
  origin: (origin) => origin,
@@ -21,13 +126,11 @@ class CORSPlugin {
21
126
  resHeaders["access-control-max-age"] = this.options.maxAge.toString();
22
127
  }
23
128
  if (this.options.allowMethods?.length) {
24
- resHeaders["access-control-allow-methods"] = this.options.allowMethods.join(",");
129
+ resHeaders["access-control-allow-methods"] = flattenHeader(this.options.allowMethods);
25
130
  }
26
131
  const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
27
- if (Array.isArray(allowHeaders) && allowHeaders.length) {
28
- resHeaders["access-control-allow-headers"] = allowHeaders.join(",");
29
- } else if (typeof allowHeaders === "string") {
30
- resHeaders["access-control-allow-headers"] = allowHeaders;
132
+ if (typeof allowHeaders === "string" || allowHeaders?.length) {
133
+ resHeaders["access-control-allow-headers"] = flattenHeader(allowHeaders);
31
134
  }
32
135
  return {
33
136
  matched: true,
@@ -45,7 +148,7 @@ class CORSPlugin {
45
148
  if (!result.matched) {
46
149
  return result;
47
150
  }
48
- const origin = Array.isArray(interceptorOptions.request.headers.origin) ? interceptorOptions.request.headers.origin.join(",") : interceptorOptions.request.headers.origin || "";
151
+ const origin = flattenHeader(interceptorOptions.request.headers.origin) ?? "";
49
152
  const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
50
153
  const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
51
154
  if (allowedOriginArr.includes("*")) {
@@ -67,7 +170,7 @@ class CORSPlugin {
67
170
  result.response.headers["access-control-allow-credentials"] = "true";
68
171
  }
69
172
  if (this.options.exposeHeaders?.length) {
70
- result.response.headers["access-control-expose-headers"] = this.options.exposeHeaders.join(",");
173
+ result.response.headers["access-control-expose-headers"] = flattenHeader(this.options.exposeHeaders);
71
174
  }
72
175
  return result;
73
176
  });
@@ -104,4 +207,47 @@ class ResponseHeadersPlugin {
104
207
  }
105
208
  }
106
209
 
107
- export { CORSPlugin, ResponseHeadersPlugin };
210
+ const SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL = Symbol("SIMPLE_CSRF_PROTECTION_CONTEXT");
211
+ class SimpleCsrfProtectionHandlerPlugin {
212
+ headerName;
213
+ headerValue;
214
+ exclude;
215
+ error;
216
+ constructor(options = {}) {
217
+ this.headerName = options.headerName ?? "x-csrf-token";
218
+ this.headerValue = options.headerValue ?? "orpc";
219
+ this.exclude = options.exclude ?? false;
220
+ this.error = options.error ?? new ORPCError("CSRF_TOKEN_MISMATCH", {
221
+ status: 403,
222
+ message: "Invalid CSRF token"
223
+ });
224
+ }
225
+ order = 8e6;
226
+ init(options) {
227
+ options.rootInterceptors ??= [];
228
+ options.clientInterceptors ??= [];
229
+ options.rootInterceptors.unshift(async (options2) => {
230
+ const headerName = await value(this.headerName, options2);
231
+ const headerValue = await value(this.headerValue, options2);
232
+ return options2.next({
233
+ ...options2,
234
+ context: {
235
+ ...options2.context,
236
+ [SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]: options2.request.headers[headerName] === headerValue
237
+ }
238
+ });
239
+ });
240
+ options.clientInterceptors.unshift(async (options2) => {
241
+ if (typeof options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL] !== "boolean") {
242
+ throw new TypeError("[SimpleCsrfProtectionHandlerPlugin] CSRF protection context has been corrupted or modified by another plugin or interceptor");
243
+ }
244
+ const excluded = await value(this.exclude, options2);
245
+ if (!excluded && !options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]) {
246
+ throw this.error;
247
+ }
248
+ return options2.next();
249
+ });
250
+ }
251
+ }
252
+
253
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin };
@@ -1,8 +1,18 @@
1
1
  import { HTTPPath, ORPCError } from '@orpc/client';
2
- import { AnySchema, Meta, InferSchemaOutput, ErrorFromErrorMap } from '@orpc/contract';
2
+ import { Meta } from '@orpc/contract';
3
3
  import { Interceptor } from '@orpc/shared';
4
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.mjs';
5
+ import { C as Context, R as Router, f as AnyRouter, h as AnyProcedure, F as ProcedureClientInterceptorOptions } from './server.DD2C4ujN.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
+ }
6
16
 
7
17
  type StandardParams = Record<string, string>;
8
18
  type StandardMatchResult = {
@@ -31,9 +41,6 @@ type StandardHandleResult = {
31
41
  matched: false;
32
42
  response: undefined;
33
43
  };
34
- interface StandardHandlerPlugin<TContext extends Context> {
35
- init?(options: StandardHandlerOptions<TContext>): void;
36
- }
37
44
  interface StandardHandlerInterceptorOptions<T extends Context> extends StandardHandleOptions<T> {
38
45
  request: StandardLazyRequest;
39
46
  }
@@ -42,16 +49,16 @@ interface StandardHandlerOptions<TContext extends Context> {
42
49
  /**
43
50
  * Interceptors at the request level, helpful when you want catch errors
44
51
  */
45
- interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
52
+ interceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
46
53
  /**
47
54
  * Interceptors at the root level, helpful when you want override the request/response
48
55
  */
49
- rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, StandardHandleResult, unknown>[];
56
+ rootInterceptors?: Interceptor<StandardHandlerInterceptorOptions<TContext>, Promise<StandardHandleResult>>[];
50
57
  /**
51
58
  *
52
59
  * Interceptors for procedure client.
53
60
  */
54
- clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, AnySchema, Record<never, never>, Meta>, InferSchemaOutput<AnySchema>, ErrorFromErrorMap<Record<never, never>>>[];
61
+ clientInterceptors?: Interceptor<ProcedureClientInterceptorOptions<TContext, Record<never, never>, Meta>, Promise<unknown>>[];
55
62
  }
56
63
  declare class StandardHandler<T extends Context> {
57
64
  private readonly matcher;
@@ -63,4 +70,5 @@ declare class StandardHandler<T extends Context> {
63
70
  handle(request: StandardLazyRequest, options: StandardHandleOptions<T>): Promise<StandardHandleResult>;
64
71
  }
65
72
 
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 };
73
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as i };
74
+ export type { StandardHandlerInterceptorOptions as S, StandardHandlerPlugin as a, StandardHandlerOptions as b, StandardCodec as c, StandardParams as d, StandardMatcher as e, StandardMatchResult as f, StandardHandleOptions as g, StandardHandleResult as h };
@@ -0,0 +1,12 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { C as Context, R as Router } from './server.DD2C4ujN.js';
3
+ import { b as StandardHandlerOptions, i as StandardHandler } from './server.-ACo36I0.js';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ }
7
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
8
+ constructor(router: Router<any, T>, options?: StandardRPCHandlerOptions<T>);
9
+ }
10
+
11
+ export { StandardRPCHandler as a };
12
+ export type { StandardRPCHandlerOptions as S };
@@ -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,12 @@
1
+ import { StandardRPCJsonSerializerOptions } from '@orpc/client/standard';
2
+ import { C as Context, R as Router } from './server.DD2C4ujN.mjs';
3
+ import { b as StandardHandlerOptions, i as StandardHandler } from './server.Dq8xr7PQ.mjs';
4
+
5
+ interface StandardRPCHandlerOptions<T extends Context> extends StandardHandlerOptions<T>, StandardRPCJsonSerializerOptions {
6
+ }
7
+ declare class StandardRPCHandler<T extends Context> extends StandardHandler<T> {
8
+ constructor(router: Router<any, T>, options?: StandardRPCHandlerOptions<T>);
9
+ }
10
+
11
+ export { StandardRPCHandler as a };
12
+ export type { StandardRPCHandlerOptions as S };
@@ -1,5 +1,5 @@
1
- import { C as Context } from './server.D0YVcfZk.mjs';
2
- import { S as StandardHandleOptions } from './server.BMkFIQUb.mjs';
1
+ import { C as Context } from './server.DD2C4ujN.mjs';
2
+ import { g as StandardHandleOptions } from './server.Dq8xr7PQ.mjs';
3
3
 
4
4
  type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
5
5
  context?: T;
@@ -1,15 +1,27 @@
1
+ import { toHttpPath, StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
1
2
  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';
3
+ import { toArray, intercept, parseEmptyableJSON, NullProtoObj } 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.DG7Tamti.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
+ }
5
18
 
6
19
  class StandardHandler {
7
20
  constructor(router, matcher, codec, options) {
8
21
  this.matcher = matcher;
9
22
  this.codec = codec;
10
- for (const plugin of toArray(options.plugins)) {
11
- plugin.init?.(options);
12
- }
23
+ const plugins = new CompositeStandardHandlerPlugin(options.plugins);
24
+ plugins.init(options, router);
13
25
  this.interceptors = toArray(options.interceptors);
14
26
  this.clientInterceptors = toArray(options.clientInterceptors);
15
27
  this.rootInterceptors = toArray(options.rootInterceptors);
@@ -18,23 +30,24 @@ class StandardHandler {
18
30
  interceptors;
19
31
  clientInterceptors;
20
32
  rootInterceptors;
21
- handle(request, options) {
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
+ }
22
38
  return intercept(
23
39
  this.rootInterceptors,
24
- { ...options, request },
40
+ { ...options, request, prefix },
25
41
  async (interceptorOptions) => {
26
42
  let isDecoding = false;
27
43
  try {
28
44
  return await intercept(
29
45
  this.interceptors,
30
46
  interceptorOptions,
31
- async ({ request: request2, context, prefix }) => {
47
+ async ({ request: request2, context, prefix: prefix2 }) => {
32
48
  const method = request2.method;
33
49
  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;
50
+ const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
38
51
  const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`);
39
52
  if (!match) {
40
53
  return { matched: false, response: void 0 };
@@ -47,8 +60,10 @@ class StandardHandler {
47
60
  isDecoding = true;
48
61
  const input = await this.codec.decode(request2, match.params, match.procedure);
49
62
  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 });
63
+ const output = await client(input, {
64
+ signal: request2.signal,
65
+ lastEventId: flattenHeader(request2.headers["last-event-id"])
66
+ });
52
67
  const response = this.codec.encode(output, match.procedure);
53
68
  return {
54
69
  matched: true,
@@ -97,7 +112,7 @@ class StandardRPCCodec {
97
112
  }
98
113
 
99
114
  class StandardRPCMatcher {
100
- tree = {};
115
+ tree = new NullProtoObj();
101
116
  pendingRouters = [];
102
117
  init(router, path = []) {
103
118
  const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
@@ -158,4 +173,14 @@ class StandardRPCMatcher {
158
173
  }
159
174
  }
160
175
 
161
- export { StandardHandler as S, StandardRPCCodec as a, StandardRPCMatcher as b };
176
+ class StandardRPCHandler extends StandardHandler {
177
+ constructor(router, options = {}) {
178
+ const jsonSerializer = new StandardRPCJsonSerializer(options);
179
+ const serializer = new StandardRPCSerializer(jsonSerializer);
180
+ const matcher = new StandardRPCMatcher();
181
+ const codec = new StandardRPCCodec(serializer);
182
+ super(router, matcher, codec, options);
183
+ }
184
+ }
185
+
186
+ export { CompositeStandardHandlerPlugin as C, StandardHandler as S, StandardRPCCodec as a, StandardRPCHandler as b, StandardRPCMatcher as c };
@@ -1,8 +1,8 @@
1
1
  import { ORPCErrorCode, ORPCErrorOptions, ORPCError, HTTPPath, ClientContext, Client } from '@orpc/client';
2
- import { MaybeOptionalOptions, Promisable, Interceptor, Value } from '@orpc/shared';
3
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>;
@@ -28,6 +28,9 @@ interface Lazy<T> {
28
28
  };
29
29
  }
30
30
  type Lazyable<T> = T | Lazy<T>;
31
+ /**
32
+ * Create a lazy thing.
33
+ */
31
34
  declare function lazy<T>(loader: () => Promise<{
32
35
  default: T;
33
36
  }>, meta?: LazyMeta): Lazy<T>;
@@ -56,7 +59,15 @@ interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends
56
59
  outputValidationIndex: number;
57
60
  handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
58
61
  }
62
+ /**
63
+ * This class represents a procedure.
64
+ *
65
+ * @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
66
+ */
59
67
  declare class Procedure<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
68
+ /**
69
+ * This property holds the defined options.
70
+ */
60
71
  '~orpc': ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>;
61
72
  constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>);
62
73
  }
@@ -87,6 +98,11 @@ interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstruct
87
98
  next: MiddlewareNextFn<TOutput>;
88
99
  errors: TErrorConstructorMap;
89
100
  }
101
+ /**
102
+ * A function that represents a middleware.
103
+ *
104
+ * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
105
+ */
90
106
  interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
91
107
  (options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
92
108
  }
@@ -97,47 +113,80 @@ interface MapInputMiddleware<TInput, TMappedInput> {
97
113
  declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
98
114
 
99
115
  type ProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
100
- interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TInputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> {
116
+ interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> {
101
117
  context: TInitialContext;
102
- input: InferSchemaInput<TInputSchema>;
118
+ input: unknown;
103
119
  errors: ORPCErrorConstructorMap<TErrorMap>;
104
120
  path: readonly string[];
105
121
  procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
106
122
  signal?: AbortSignal;
107
123
  lastEventId: string | undefined;
108
124
  }
109
- /**
110
- * Options for creating a procedure caller with comprehensive type safety
111
- */
112
- type CreateProcedureClientOptions<TInitialContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
125
+ type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
113
126
  /**
114
127
  * This is helpful for logging and analytics.
115
128
  */
116
129
  path?: readonly string[];
117
- interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TInputSchema, TErrorMap, TMeta>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>[];
130
+ interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, PromiseWithError<InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>>[];
118
131
  } & (Record<never, never> extends TInitialContext ? {
119
- context?: Value<TInitialContext, [clientContext: TClientContext]>;
132
+ context?: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
120
133
  } : {
121
- context: Value<TInitialContext, [clientContext: TClientContext]>;
134
+ context: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
122
135
  });
123
- 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>;
136
+ /**
137
+ * Create Server-side client from a procedure.
138
+ *
139
+ * @see {@link https://orpc.unnoq.com/docs/client/server-side Server-side Client Docs}
140
+ */
141
+ 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, TOutputSchema, TErrorMap, TMeta, TClientContext>>): ProcedureClient<TClientContext, TInputSchema, TOutputSchema, TErrorMap>;
124
142
 
143
+ /**
144
+ * Represents a router, which defines a hierarchical structure of procedures.
145
+ *
146
+ * @info A procedure is a router too.
147
+ * @see {@link https://orpc.unnoq.com/docs/contract-first/define-contract#contract-router Contract Router Docs}
148
+ */
125
149
  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> : {
126
150
  [K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
127
151
  };
128
152
  type AnyRouter = Router<any, any>;
129
153
  type InferRouterInitialContext<T extends AnyRouter> = T extends Router<any, infer UInitialContext> ? UInitialContext : never;
154
+ /**
155
+ * Infer all initial context of the router.
156
+ *
157
+ * @info A procedure is a router too.
158
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
159
+ */
130
160
  type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any, any> ? UInitialContext : {
131
161
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
132
162
  };
163
+ /**
164
+ * Infer all current context of the router.
165
+ *
166
+ * @info A procedure is a router too.
167
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
168
+ */
133
169
  type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any, any> ? UCurrentContext : {
134
170
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
135
171
  };
172
+ /**
173
+ * Infer all router inputs
174
+ *
175
+ * @info A procedure is a router too.
176
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
177
+ */
136
178
  type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
137
179
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
138
180
  };
181
+ /**
182
+ * Infer all router outputs
183
+ *
184
+ * @info A procedure is a router too.
185
+ * @see {@link https://orpc.unnoq.com/docs/router#utilities Router Utilities Docs}
186
+ */
139
187
  type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
140
188
  [K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
141
189
  };
142
190
 
143
- export { type AnyProcedure as A, middlewareOutputFn as B, type Context as C, type ProcedureHandlerOptions as D, type ProcedureDef as E, isProcedure as F, createProcedureClient as G, type InferRouterInitialContexts as H, type InferRouterInitialContext as I, type InferRouterCurrentContexts as J, type InferRouterInputs as K, type Lazyable as L, type Middleware as M, type InferRouterOutputs as N, type ORPCErrorConstructorMap as O, type ProcedureClientInterceptorOptions as P, type Router as R, type AnyRouter as a, Procedure as b, type MergedInitialContext as c, type MergedCurrentContext as d, type MapInputMiddleware as e, type CreateProcedureClientOptions as f, type ProcedureClient as g, type AnyMiddleware as h, type Lazy as i, type ProcedureHandler as j, type ORPCErrorConstructorMapItemOptions as k, type ORPCErrorConstructorMapItem as l, mergeCurrentContext as m, createORPCErrorConstructorMap as n, LAZY_SYMBOL as o, type LazyMeta as p, lazy as q, isLazy as r, getLazyMeta as s, type MiddlewareResult as t, unlazy as u, validateORPCError as v, type MiddlewareNextFnOptions as w, type MiddlewareNextFn as x, type MiddlewareOutputFn as y, type MiddlewareOptions as z };
191
+ export { isProcedure as E, createProcedureClient as G, Procedure as P, createORPCErrorConstructorMap as l, mergeCurrentContext as m, LAZY_SYMBOL as n, lazy as p, isLazy as q, getLazyMeta as r, unlazy as u, validateORPCError as v, middlewareOutputFn as z };
192
+ export type { AnyMiddleware as A, ProcedureHandlerOptions as B, Context as C, ProcedureDef as D, ProcedureClientInterceptorOptions as F, InferRouterInitialContexts as H, InferRouterInitialContext as I, InferRouterCurrentContexts as J, InferRouterInputs as K, Lazyable as L, Middleware as M, InferRouterOutputs as N, ORPCErrorConstructorMap as O, Router as R, MergedInitialContext as a, MergedCurrentContext as b, MapInputMiddleware as c, CreateProcedureClientOptions as d, ProcedureClient as e, AnyRouter as f, Lazy as g, AnyProcedure as h, ProcedureHandler as i, ORPCErrorConstructorMapItemOptions as j, ORPCErrorConstructorMapItem as k, LazyMeta as o, MiddlewareResult as s, MiddlewareNextFnOptions as t, MiddlewareNextFn as w, MiddlewareOutputFn as x, MiddlewareOptions as y };