@orpc/server 0.0.0-next.62473ae → 0.0.0-next.624aa8b

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 +27 -17
  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 +51 -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 +51 -0
  11. package/dist/adapters/fetch/index.d.mts +62 -10
  12. package/dist/adapters/fetch/index.d.ts +62 -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 +64 -21
  18. package/dist/adapters/node/index.d.ts +64 -21
  19. package/dist/adapters/node/index.mjs +87 -23
  20. package/dist/adapters/standard/index.d.mts +12 -11
  21. package/dist/adapters/standard/index.d.ts +12 -11
  22. package/dist/adapters/standard/index.mjs +4 -3
  23. package/dist/adapters/websocket/index.d.mts +27 -0
  24. package/dist/adapters/websocket/index.d.ts +27 -0
  25. package/dist/adapters/websocket/index.mjs +38 -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 +38 -0
  29. package/dist/index.d.mts +701 -127
  30. package/dist/index.d.ts +701 -127
  31. package/dist/index.mjs +195 -53
  32. package/dist/plugins/index.d.mts +144 -19
  33. package/dist/plugins/index.d.ts +144 -19
  34. package/dist/plugins/index.mjs +163 -15
  35. package/dist/shared/server.-ACo36I0.d.ts +74 -0
  36. package/dist/shared/{server.DKrKGnk2.mjs → server.4FnxLwwr.mjs} +65 -40
  37. package/dist/shared/server.BPAWobQg.d.ts +12 -0
  38. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  39. package/dist/shared/server.BW-nUGgA.mjs +36 -0
  40. package/dist/shared/server.Bd52nNaH.d.mts +12 -0
  41. package/dist/shared/server.BliFSTnG.d.mts +10 -0
  42. package/dist/shared/server.DD2C4ujN.d.mts +192 -0
  43. package/dist/shared/server.DD2C4ujN.d.ts +192 -0
  44. package/dist/shared/{server.V6zT5iYQ.mjs → server.DG7Tamti.mjs} +161 -173
  45. package/dist/shared/server.Dq8xr7PQ.d.mts +74 -0
  46. package/dist/shared/server.IG2MjhrD.d.ts +10 -0
  47. package/package.json +54 -20
  48. package/dist/adapters/hono/index.d.mts +0 -19
  49. package/dist/adapters/hono/index.d.ts +0 -19
  50. package/dist/adapters/hono/index.mjs +0 -32
  51. package/dist/adapters/next/index.d.mts +0 -26
  52. package/dist/adapters/next/index.d.ts +0 -26
  53. package/dist/adapters/next/index.mjs +0 -29
  54. package/dist/shared/server.BHIDiY4a.mjs +0 -28
  55. package/dist/shared/server.CtBp-i4f.d.mts +0 -77
  56. package/dist/shared/server.Drm1Lma3.d.ts +0 -77
  57. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
  58. package/dist/shared/server.ptXwNGQr.d.mts +0 -158
  59. package/dist/shared/server.ptXwNGQr.d.ts +0 -158
@@ -1,31 +1,156 @@
1
- import { a as StandardHandlerInterceptorOptions, P as Plugin, b as StandardHandlerOptions } from '../shared/server.Drm1Lma3.js';
2
- export { C as CompositePlugin } from '../shared/server.Drm1Lma3.js';
3
- import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.ptXwNGQr.js';
5
- import '@orpc/contract';
6
- import '@orpc/standard-server';
7
- import '@orpc/client';
1
+ import { Value, Promisable } from '@orpc/shared';
2
+ import { StandardRequest, StandardHeaders } from '@orpc/standard-server';
3
+ import { BatchResponseBodyItem } from '@orpc/standard-server/batch';
4
+ import { S as StandardHandlerInterceptorOptions, a as StandardHandlerPlugin, b as StandardHandlerOptions } from '../shared/server.-ACo36I0.js';
5
+ import { C as Context, F as ProcedureClientInterceptorOptions } from '../shared/server.DD2C4ujN.js';
6
+ import { Meta, ORPCError as ORPCError$1 } from '@orpc/contract';
7
+ import { ORPCError } from '@orpc/client';
8
8
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
12
- allowMethods?: string[];
13
- allowHeaders?: string[];
9
+ interface BatchHandlerOptions<T extends Context> {
10
+ /**
11
+ * The max size of the batch allowed.
12
+ *
13
+ * @default 10
14
+ */
15
+ maxSize?: Value<Promisable<number>, [StandardHandlerInterceptorOptions<T>]>;
16
+ /**
17
+ * Map the request before processing it.
18
+ *
19
+ * @default merged back batch request headers into the request
20
+ */
21
+ mapRequestItem?(request: StandardRequest, batchOptions: StandardHandlerInterceptorOptions<T>): StandardRequest;
22
+ /**
23
+ * Success batch response status code.
24
+ *
25
+ * @default 207
26
+ */
27
+ successStatus?: Value<Promisable<number>, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
28
+ /**
29
+ * success batch response headers.
30
+ *
31
+ * @default {}
32
+ */
33
+ headers?: Value<Promisable<StandardHeaders>, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
34
+ }
35
+ /**
36
+ * The Batch Request/Response Plugin allows you to combine multiple requests and responses into a single batch,
37
+ * reducing the overhead of sending each one separately.
38
+ *
39
+ * @see {@link https://orpc.unnoq.com/docs/plugins/batch-request-response Batch Request/Response Plugin Docs}
40
+ */
41
+ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
42
+ private readonly maxSize;
43
+ private readonly mapRequestItem;
44
+ private readonly successStatus;
45
+ private readonly headers;
46
+ order: number;
47
+ constructor(options?: BatchHandlerOptions<T>);
48
+ init(options: StandardHandlerOptions<T>): void;
49
+ }
50
+
51
+ interface CORSOptions<T extends Context> {
52
+ origin?: Value<Promisable<string | readonly string[] | null | undefined>, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
53
+ timingOrigin?: Value<Promisable<string | readonly string[] | null | undefined>, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
54
+ allowMethods?: readonly string[];
55
+ allowHeaders?: readonly string[];
14
56
  maxAge?: number;
15
57
  credentials?: boolean;
16
- exposeHeaders?: string[];
58
+ exposeHeaders?: readonly string[];
17
59
  }
18
- declare class CORSPlugin<TContext extends Context> implements Plugin<TContext> {
60
+ /**
61
+ * CORSPlugin is a plugin for oRPC that allows you to configure CORS for your API.
62
+ *
63
+ * @see {@link https://orpc.unnoq.com/docs/plugins/cors CORS Plugin Docs}
64
+ */
65
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
66
  private readonly options;
20
- constructor(options?: Partial<CORSOptions<TContext>>);
21
- init(options: StandardHandlerOptions<TContext>): void;
67
+ order: number;
68
+ constructor(options?: CORSOptions<T>);
69
+ init(options: StandardHandlerOptions<T>): void;
22
70
  }
23
71
 
24
72
  interface ResponseHeadersPluginContext {
25
73
  resHeaders?: Headers;
26
74
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements Plugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
75
+ /**
76
+ * The Response Headers Plugin allows you to set response headers in oRPC.
77
+ * It injects a resHeaders instance into the context, enabling you to modify response headers easily.
78
+ *
79
+ * @see {@link https://orpc.unnoq.com/docs/plugins/response-headers Response Headers Plugin Docs}
80
+ */
81
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
82
+ init(options: StandardHandlerOptions<T>): void;
83
+ }
84
+
85
+ interface SimpleCsrfProtectionHandlerPluginOptions<T extends Context> {
86
+ /**
87
+ * The name of the header to check.
88
+ *
89
+ * @default 'x-csrf-token'
90
+ */
91
+ headerName?: Value<Promisable<string>, [options: StandardHandlerInterceptorOptions<T>]>;
92
+ /**
93
+ * The value of the header to check.
94
+ *
95
+ * @default 'orpc'
96
+ *
97
+ */
98
+ headerValue?: Value<Promisable<string>, [options: StandardHandlerInterceptorOptions<T>]>;
99
+ /**
100
+ * Exclude a procedure from the plugin.
101
+ *
102
+ * @default false
103
+ *
104
+ */
105
+ exclude?: Value<Promisable<boolean>, [options: ProcedureClientInterceptorOptions<T, Record<never, never>, Meta>]>;
106
+ /**
107
+ * The error thrown when the CSRF token is invalid.
108
+ *
109
+ * @default new ORPCError('CSRF_TOKEN_MISMATCH', {
110
+ * status: 403,
111
+ * message: 'Invalid CSRF token',
112
+ * })
113
+ */
114
+ error?: InstanceType<typeof ORPCError>;
115
+ }
116
+ /**
117
+ * This plugin adds basic Cross-Site Request Forgery (CSRF) protection to your oRPC application.
118
+ * It helps ensure that requests to your procedures originate from JavaScript code,
119
+ * not from other sources like standard HTML forms or direct browser navigation.
120
+ *
121
+ * @see {@link https://orpc.unnoq.com/docs/plugins/simple-csrf-protection Simple CSRF Protection Plugin Docs}
122
+ */
123
+ declare class SimpleCsrfProtectionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
124
+ private readonly headerName;
125
+ private readonly headerValue;
126
+ private readonly exclude;
127
+ private readonly error;
128
+ constructor(options?: SimpleCsrfProtectionHandlerPluginOptions<T>);
129
+ order: number;
130
+ init(options: StandardHandlerOptions<T>): void;
131
+ }
132
+
133
+ interface StrictGetMethodPluginOptions {
134
+ /**
135
+ * The error thrown when a GET request is made to a procedure that doesn't allow GET.
136
+ *
137
+ * @default new ORPCError('METHOD_NOT_SUPPORTED')
138
+ */
139
+ error?: InstanceType<typeof ORPCError$1>;
140
+ }
141
+ /**
142
+ * This plugin enhances security by ensuring only procedures explicitly marked to accept GET requests
143
+ * can be called using the HTTP GET method for RPC Protocol. This helps prevent certain types of
144
+ * Cross-Site Request Forgery (CSRF) attacks.
145
+ *
146
+ * @see {@link https://orpc.unnoq.com/docs/plugins/strict-get-method Strict Get Method Plugin Docs}
147
+ */
148
+ declare class StrictGetMethodPlugin<T extends Context> implements StandardHandlerPlugin<T> {
149
+ private readonly error;
150
+ order: number;
151
+ constructor(options?: StrictGetMethodPluginOptions);
152
+ init(options: StandardHandlerOptions<T>): void;
29
153
  }
30
154
 
31
- export { type CORSOptions, CORSPlugin, Plugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
155
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin, StrictGetMethodPlugin };
156
+ export type { BatchHandlerOptions, CORSOptions, ResponseHeadersPluginContext, SimpleCsrfProtectionHandlerPluginOptions, StrictGetMethodPluginOptions };
@@ -1,9 +1,111 @@
1
- export { C as CompositePlugin } from '../shared/server.Q6ZmnTgO.mjs';
2
- import { value } from '@orpc/shared';
1
+ import { value, isAsyncIteratorObject } from '@orpc/shared';
2
+ import { parseBatchRequest, toBatchResponse } from '@orpc/standard-server/batch';
3
+ import { flattenHeader } from '@orpc/standard-server';
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
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
30
+ return options2.next();
31
+ }
32
+ let isParsing = false;
33
+ try {
34
+ isParsing = true;
35
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
36
+ isParsing = false;
37
+ const maxSize = await value(this.maxSize, options2);
38
+ if (parsed.length > maxSize) {
39
+ return {
40
+ matched: true,
41
+ response: {
42
+ status: 413,
43
+ headers: {},
44
+ body: "Batch request size exceeds the maximum allowed size"
45
+ }
46
+ };
47
+ }
48
+ const responses = parsed.map(
49
+ (request, index) => {
50
+ const mapped = this.mapRequestItem(request, options2);
51
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
52
+ if (matched) {
53
+ if (response2.body instanceof Blob || response2.body instanceof FormData || isAsyncIteratorObject(response2.body)) {
54
+ return {
55
+ index,
56
+ status: 500,
57
+ headers: {},
58
+ body: "Batch responses do not support file/blob, or event-iterator. Please call this procedure separately outside of the batch request."
59
+ };
60
+ }
61
+ return { ...response2, index };
62
+ }
63
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
64
+ }).catch(() => {
65
+ return { index, status: 500, headers: {}, body: "Internal server error" };
66
+ });
67
+ }
68
+ );
69
+ await Promise.race(responses);
70
+ const status = await value(this.successStatus, responses, options2);
71
+ const headers = await value(this.headers, responses, options2);
72
+ const response = toBatchResponse({
73
+ status,
74
+ headers,
75
+ body: async function* () {
76
+ const promises = [...responses];
77
+ while (true) {
78
+ const handling = promises.filter((p) => p !== void 0);
79
+ if (handling.length === 0) {
80
+ return;
81
+ }
82
+ const result = await Promise.race(handling);
83
+ promises[result.index] = void 0;
84
+ yield result;
85
+ }
86
+ }()
87
+ });
88
+ return {
89
+ matched: true,
90
+ response
91
+ };
92
+ } catch (cause) {
93
+ if (isParsing) {
94
+ return {
95
+ matched: true,
96
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
97
+ };
98
+ }
99
+ throw cause;
100
+ }
101
+ });
102
+ }
103
+ }
3
104
 
4
105
  class CORSPlugin {
5
106
  options;
6
- constructor(options) {
107
+ order = 9e6;
108
+ constructor(options = {}) {
7
109
  const defaults = {
8
110
  origin: (origin) => origin,
9
111
  allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
@@ -22,13 +124,11 @@ class CORSPlugin {
22
124
  resHeaders["access-control-max-age"] = this.options.maxAge.toString();
23
125
  }
24
126
  if (this.options.allowMethods?.length) {
25
- resHeaders["access-control-allow-methods"] = this.options.allowMethods.join(",");
127
+ resHeaders["access-control-allow-methods"] = flattenHeader(this.options.allowMethods);
26
128
  }
27
129
  const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
28
- if (Array.isArray(allowHeaders) && allowHeaders.length) {
29
- resHeaders["access-control-allow-headers"] = allowHeaders.join(",");
30
- } else if (typeof allowHeaders === "string") {
31
- resHeaders["access-control-allow-headers"] = allowHeaders;
130
+ if (typeof allowHeaders === "string" || allowHeaders?.length) {
131
+ resHeaders["access-control-allow-headers"] = flattenHeader(allowHeaders);
32
132
  }
33
133
  return {
34
134
  matched: true,
@@ -46,7 +146,7 @@ class CORSPlugin {
46
146
  if (!result.matched) {
47
147
  return result;
48
148
  }
49
- const origin = Array.isArray(interceptorOptions.request.headers.origin) ? interceptorOptions.request.headers.origin.join(",") : interceptorOptions.request.headers.origin || "";
149
+ const origin = flattenHeader(interceptorOptions.request.headers.origin) ?? "";
50
150
  const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
51
151
  const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
52
152
  if (allowedOriginArr.includes("*")) {
@@ -68,7 +168,7 @@ class CORSPlugin {
68
168
  result.response.headers["access-control-allow-credentials"] = "true";
69
169
  }
70
170
  if (this.options.exposeHeaders?.length) {
71
- result.response.headers["access-control-expose-headers"] = this.options.exposeHeaders.join(",");
171
+ result.response.headers["access-control-expose-headers"] = flattenHeader(this.options.exposeHeaders);
72
172
  }
73
173
  return result;
74
174
  });
@@ -79,14 +179,19 @@ class ResponseHeadersPlugin {
79
179
  init(options) {
80
180
  options.rootInterceptors ??= [];
81
181
  options.rootInterceptors.push(async (interceptorOptions) => {
82
- const headers = new Headers();
83
- interceptorOptions.context.resHeaders = headers;
84
- const result = await interceptorOptions.next();
182
+ const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
183
+ const result = await interceptorOptions.next({
184
+ ...interceptorOptions,
185
+ context: {
186
+ ...interceptorOptions.context,
187
+ resHeaders
188
+ }
189
+ });
85
190
  if (!result.matched) {
86
191
  return result;
87
192
  }
88
193
  const responseHeaders = result.response.headers;
89
- for (const [key, value] of headers) {
194
+ for (const [key, value] of resHeaders) {
90
195
  if (Array.isArray(responseHeaders[key])) {
91
196
  responseHeaders[key].push(value);
92
197
  } else if (responseHeaders[key] !== void 0) {
@@ -100,4 +205,47 @@ class ResponseHeadersPlugin {
100
205
  }
101
206
  }
102
207
 
103
- export { CORSPlugin, ResponseHeadersPlugin };
208
+ const SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL = Symbol("SIMPLE_CSRF_PROTECTION_CONTEXT");
209
+ class SimpleCsrfProtectionHandlerPlugin {
210
+ headerName;
211
+ headerValue;
212
+ exclude;
213
+ error;
214
+ constructor(options = {}) {
215
+ this.headerName = options.headerName ?? "x-csrf-token";
216
+ this.headerValue = options.headerValue ?? "orpc";
217
+ this.exclude = options.exclude ?? false;
218
+ this.error = options.error ?? new ORPCError("CSRF_TOKEN_MISMATCH", {
219
+ status: 403,
220
+ message: "Invalid CSRF token"
221
+ });
222
+ }
223
+ order = 8e6;
224
+ init(options) {
225
+ options.rootInterceptors ??= [];
226
+ options.clientInterceptors ??= [];
227
+ options.rootInterceptors.unshift(async (options2) => {
228
+ const headerName = await value(this.headerName, options2);
229
+ const headerValue = await value(this.headerValue, options2);
230
+ return options2.next({
231
+ ...options2,
232
+ context: {
233
+ ...options2.context,
234
+ [SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]: options2.request.headers[headerName] === headerValue
235
+ }
236
+ });
237
+ });
238
+ options.clientInterceptors.unshift(async (options2) => {
239
+ if (typeof options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL] !== "boolean") {
240
+ throw new TypeError("[SimpleCsrfProtectionHandlerPlugin] CSRF protection context has been corrupted or modified by another plugin or interceptor");
241
+ }
242
+ const excluded = await value(this.exclude, options2);
243
+ if (!excluded && !options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]) {
244
+ throw this.error;
245
+ }
246
+ return options2.next();
247
+ });
248
+ }
249
+ }
250
+
251
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin };
@@ -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, 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
+ }
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 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 };
@@ -1,51 +1,69 @@
1
+ import { toHttpPath, StandardRPCJsonSerializer, StandardRPCSerializer } from '@orpc/client/standard';
1
2
  import { ORPCError, toORPCError } from '@orpc/client';
2
- import { intercept, trim, parseEmptyableJSON } from '@orpc/shared';
3
- import { C as CompositePlugin } from './server.Q6ZmnTgO.mjs';
4
- import { c as createProcedureClient, e as eachContractProcedure, a as convertPathToHttpPath, i as isProcedure, u as unlazy, g as getRouterChild, b as createContractedProcedure } from './server.V6zT5iYQ.mjs';
3
+ import { toArray, intercept, parseEmptyableJSON } 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
- this.options = options;
11
- this.plugin = new CompositePlugin(options.plugins);
12
- this.plugin.init(this.options);
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);
13
28
  this.matcher.init(router);
14
29
  }
15
- plugin;
16
- handle(request, ...[options]) {
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
+ }
17
38
  return intercept(
18
- this.options.rootInterceptors ?? [],
19
- {
20
- request,
21
- ...options,
22
- context: options?.context ?? {}
23
- // context is optional only when all fields are optional so we can safely force it to have a context
24
- },
39
+ this.rootInterceptors,
40
+ { ...options, request, prefix },
25
41
  async (interceptorOptions) => {
26
42
  let isDecoding = false;
27
43
  try {
28
44
  return await intercept(
29
- this.options.interceptors ?? [],
45
+ this.interceptors,
30
46
  interceptorOptions,
31
- async (interceptorOptions2) => {
32
- const method = interceptorOptions2.request.method;
33
- const url = interceptorOptions2.request.url;
34
- const pathname = `/${trim(url.pathname.replace(interceptorOptions2.prefix ?? "", ""), "/")}`;
35
- const match = await this.matcher.match(method, pathname);
47
+ async ({ request: request2, context, prefix: prefix2 }) => {
48
+ const method = request2.method;
49
+ const url = request2.url;
50
+ const pathname = prefix2 ? url.pathname.replace(prefix2, "") : url.pathname;
51
+ const match = await this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`);
36
52
  if (!match) {
37
53
  return { matched: false, response: void 0 };
38
54
  }
39
55
  const client = createProcedureClient(match.procedure, {
40
- context: interceptorOptions2.context,
56
+ context,
41
57
  path: match.path,
42
- interceptors: this.options.clientInterceptors
58
+ interceptors: this.clientInterceptors
43
59
  });
44
60
  isDecoding = true;
45
- const input = await this.codec.decode(request, match.params, match.procedure);
61
+ const input = await this.codec.decode(request2, match.params, match.procedure);
46
62
  isDecoding = false;
47
- const lastEventId = Array.isArray(request.headers["last-event-id"]) ? request.headers["last-event-id"].at(-1) : request.headers["last-event-id"];
48
- const output = await client(input, { signal: request.signal, lastEventId });
63
+ const output = await client(input, {
64
+ signal: request2.signal,
65
+ lastEventId: flattenHeader(request2.headers["last-event-id"])
66
+ });
49
67
  const response = this.codec.encode(output, match.procedure);
50
68
  return {
51
69
  matched: true,
@@ -54,7 +72,7 @@ class StandardHandler {
54
72
  }
55
73
  );
56
74
  } catch (e) {
57
- const error = isDecoding ? new ORPCError("BAD_REQUEST", {
75
+ const error = isDecoding && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
58
76
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
59
77
  cause: e
60
78
  }) : toORPCError(e);
@@ -69,7 +87,7 @@ class StandardHandler {
69
87
  }
70
88
  }
71
89
 
72
- class RPCCodec {
90
+ class StandardRPCCodec {
73
91
  constructor(serializer) {
74
92
  this.serializer = serializer;
75
93
  }
@@ -93,15 +111,12 @@ class RPCCodec {
93
111
  }
94
112
  }
95
113
 
96
- class RPCMatcher {
114
+ class StandardRPCMatcher {
97
115
  tree = {};
98
116
  pendingRouters = [];
99
117
  init(router, path = []) {
100
- const laziedOptions = eachContractProcedure({
101
- router,
102
- path
103
- }, ({ path: path2, contract }) => {
104
- const httpPath = convertPathToHttpPath(path2);
118
+ const laziedOptions = traverseContractProcedures({ router, path }, ({ path: path2, contract }) => {
119
+ const httpPath = toHttpPath(path2);
105
120
  if (isProcedure(contract)) {
106
121
  this.tree[httpPath] = {
107
122
  path: path2,
@@ -121,7 +136,7 @@ class RPCMatcher {
121
136
  });
122
137
  this.pendingRouters.push(...laziedOptions.map((option) => ({
123
138
  ...option,
124
- httpPathPrefix: convertPathToHttpPath(option.path)
139
+ httpPathPrefix: toHttpPath(option.path)
125
140
  })));
126
141
  }
127
142
  async match(_method, pathname) {
@@ -129,7 +144,7 @@ class RPCMatcher {
129
144
  const newPendingRouters = [];
130
145
  for (const pendingRouter of this.pendingRouters) {
131
146
  if (pathname.startsWith(pendingRouter.httpPathPrefix)) {
132
- const { default: router } = await unlazy(pendingRouter.lazied);
147
+ const { default: router } = await unlazy(pendingRouter.router);
133
148
  this.init(router, pendingRouter.path);
134
149
  } else {
135
150
  newPendingRouters.push(pendingRouter);
@@ -142,14 +157,14 @@ class RPCMatcher {
142
157
  return void 0;
143
158
  }
144
159
  if (!match.procedure) {
145
- const { default: maybeProcedure } = await unlazy(getRouterChild(match.router, ...match.path));
160
+ const { default: maybeProcedure } = await unlazy(getRouter(match.router, match.path));
146
161
  if (!isProcedure(maybeProcedure)) {
147
162
  throw new Error(`
148
- [Contract-First] Missing or invalid implementation for procedure at path: ${convertPathToHttpPath(match.path)}.
163
+ [Contract-First] Missing or invalid implementation for procedure at path: ${toHttpPath(match.path)}.
149
164
  Ensure that the procedure is correctly defined and matches the expected contract.
150
165
  `);
151
166
  }
152
- match.procedure = createContractedProcedure(match.contract, maybeProcedure);
167
+ match.procedure = createContractedProcedure(maybeProcedure, match.contract);
153
168
  }
154
169
  return {
155
170
  path: match.path,
@@ -158,4 +173,14 @@ class RPCMatcher {
158
173
  }
159
174
  }
160
175
 
161
- export { RPCCodec as R, StandardHandler as S, RPCMatcher as a };
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 };
@@ -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 };