@orpc/server 0.0.0-next.2ebf00e → 0.0.0-next.2f2dbaa

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 (37) hide show
  1. package/README.md +11 -0
  2. package/dist/adapters/fetch/index.d.mts +41 -11
  3. package/dist/adapters/fetch/index.d.ts +41 -11
  4. package/dist/adapters/fetch/index.mjs +6 -6
  5. package/dist/adapters/hono/index.d.mts +5 -4
  6. package/dist/adapters/hono/index.d.ts +5 -4
  7. package/dist/adapters/hono/index.mjs +6 -6
  8. package/dist/adapters/next/index.d.mts +5 -4
  9. package/dist/adapters/next/index.d.ts +5 -4
  10. package/dist/adapters/next/index.mjs +6 -6
  11. package/dist/adapters/node/index.d.mts +43 -22
  12. package/dist/adapters/node/index.d.ts +43 -22
  13. package/dist/adapters/node/index.mjs +81 -21
  14. package/dist/adapters/standard/index.d.mts +6 -6
  15. package/dist/adapters/standard/index.d.ts +6 -6
  16. package/dist/adapters/standard/index.mjs +3 -3
  17. package/dist/index.d.mts +56 -43
  18. package/dist/index.d.ts +56 -43
  19. package/dist/index.mjs +27 -6
  20. package/dist/plugins/index.d.mts +93 -15
  21. package/dist/plugins/index.d.ts +93 -15
  22. package/dist/plugins/index.mjs +145 -6
  23. package/dist/shared/server.BVwwTHyO.mjs +9 -0
  24. package/dist/shared/{server.BtxZnWJ9.mjs → server.C37gDhSZ.mjs} +19 -29
  25. package/dist/shared/server.C56IpPNj.d.mts +10 -0
  26. package/dist/shared/{server.jG7ZuX3S.mjs → server.C78d5yfh.mjs} +43 -28
  27. package/dist/shared/server.CSIDw0mq.mjs +106 -0
  28. package/dist/shared/{server.EhgR_5_I.d.ts → server.CyrwhzzU.d.ts} +2 -2
  29. package/dist/shared/{server.BYTulgUc.d.mts → server.DLt5njUb.d.mts} +9 -10
  30. package/dist/shared/{server.BYTulgUc.d.ts → server.DLt5njUb.d.ts} +9 -10
  31. package/dist/shared/{server.B3Tm0IXY.d.ts → server.DfyOFejj.d.ts} +27 -29
  32. package/dist/shared/{server.Bz_xNBjz.d.mts → server.DgrNIRDf.d.mts} +2 -2
  33. package/dist/shared/{server.BeJithK4.d.mts → server.Dm5DEJl5.d.mts} +27 -29
  34. package/dist/shared/server.DnuwaDJo.d.ts +10 -0
  35. package/package.json +8 -8
  36. package/dist/shared/server.DoP20NVH.mjs +0 -29
  37. package/dist/shared/server.Q6ZmnTgO.mjs +0 -12
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { mergeErrorMap, mergeMeta, mergeRoute, mergePrefix, mergeTags, isContractProcedure, getContractRouter } from '@orpc/contract';
2
2
  export { ValidationError, eventIterator, type } from '@orpc/contract';
3
- import { P as Procedure, d as addMiddleware, c as createProcedureClient, e as enhanceRouter, l as lazy, s as setHiddenRouterContract, i as isProcedure, f as isLazy, h as createAssertedLazyProcedure, g as getRouter } from './shared/server.BtxZnWJ9.mjs';
4
- export { L as LAZY_SYMBOL, q as call, w as createAccessibleLazyRouter, b as createContractedProcedure, j as createORPCErrorConstructorMap, r as getHiddenRouterContract, k as getLazyMeta, o as isStartWithMiddlewares, m as mergeCurrentContext, p as mergeMiddlewares, n as middlewareOutputFn, x as resolveContractProcedures, a as toHttpPath, t as traverseContractProcedures, u as unlazy, y as unlazyRouter, v as validateORPCError } from './shared/server.BtxZnWJ9.mjs';
3
+ import { P as Procedure, b as addMiddleware, c as createProcedureClient, e as enhanceRouter, l as lazy, s as setHiddenRouterContract, i as isProcedure, d as isLazy, f as createAssertedLazyProcedure, g as getRouter } from './shared/server.C37gDhSZ.mjs';
4
+ export { L as LAZY_SYMBOL, p as call, r as createAccessibleLazyRouter, a as createContractedProcedure, h as createORPCErrorConstructorMap, q as getHiddenRouterContract, j as getLazyMeta, n as isStartWithMiddlewares, m as mergeCurrentContext, o as mergeMiddlewares, k as middlewareOutputFn, w as resolveContractProcedures, t as traverseContractProcedures, u as unlazy, x as unlazyRouter, v as validateORPCError } from './shared/server.C37gDhSZ.mjs';
5
+ import { toORPCError } from '@orpc/client';
5
6
  export { ORPCError, isDefinedError, safe } from '@orpc/client';
6
7
  export { onError, onFinish, onStart, onSuccess } from '@orpc/shared';
7
8
  export { getEventMeta, withEventMeta } from '@orpc/standard-server';
@@ -44,6 +45,17 @@ function decorateMiddleware(middleware) {
44
45
  return decorated;
45
46
  }
46
47
 
48
+ function createActionableClient(client) {
49
+ const action = async (input) => {
50
+ try {
51
+ return [null, await client(input)];
52
+ } catch (error) {
53
+ return [toORPCError(error).toJSON(), void 0];
54
+ }
55
+ };
56
+ return action;
57
+ }
58
+
47
59
  class DecoratedProcedure extends Procedure {
48
60
  errors(errors) {
49
61
  return new DecoratedProcedure({
@@ -74,7 +86,8 @@ class DecoratedProcedure extends Procedure {
74
86
  * Make this procedure callable (works like a function while still being a procedure).
75
87
  */
76
88
  callable(...rest) {
77
- return new Proxy(createProcedureClient(this, ...rest), {
89
+ const client = createProcedureClient(this, ...rest);
90
+ return new Proxy(client, {
78
91
  get: (target, key) => {
79
92
  return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
80
93
  },
@@ -84,10 +97,18 @@ class DecoratedProcedure extends Procedure {
84
97
  });
85
98
  }
86
99
  /**
87
- * Make this procedure compatible with server action (the same as .callable, but the type is compatible with server action).
100
+ * Make this procedure compatible with server action.
88
101
  */
89
102
  actionable(...rest) {
90
- return this.callable(...rest);
103
+ const action = createActionableClient(createProcedureClient(this, ...rest));
104
+ return new Proxy(action, {
105
+ get: (target, key) => {
106
+ return Reflect.has(this, key) ? Reflect.get(this, key) : Reflect.get(target, key);
107
+ },
108
+ has: (target, key) => {
109
+ return Reflect.has(this, key) || Reflect.has(target, key);
110
+ }
111
+ });
91
112
  }
92
113
  }
93
114
 
@@ -339,4 +360,4 @@ function createRouterClient(router, ...[options]) {
339
360
  return recursive;
340
361
  }
341
362
 
342
- export { Builder, DecoratedProcedure, Procedure, addMiddleware, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, fallbackConfig, getRouter, implement, implementerInternal, isLazy, isProcedure, lazy, os, setHiddenRouterContract };
363
+ export { Builder, DecoratedProcedure, Procedure, addMiddleware, createActionableClient, createAssertedLazyProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, fallbackConfig, getRouter, implement, implementerInternal, isLazy, isProcedure, lazy, os, setHiddenRouterContract };
@@ -1,31 +1,109 @@
1
- import { b as StandardHandlerInterceptorOptions, H as HandlerPlugin, a as StandardHandlerOptions } from '../shared/server.BeJithK4.mjs';
2
- export { C as CompositePlugin } from '../shared/server.BeJithK4.mjs';
3
1
  import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.BYTulgUc.mjs';
5
- import '@orpc/contract';
6
- import '@orpc/standard-server';
7
- import '@orpc/client';
2
+ import { StandardRequest, StandardHeaders } from '@orpc/standard-server';
3
+ import { BatchResponseBodyItem } from '@orpc/standard-server/batch';
4
+ import { g as StandardHandlerInterceptorOptions, i as StandardHandlerPlugin, a as StandardHandlerOptions } from '../shared/server.Dm5DEJl5.mjs';
5
+ import { C as Context, P as ProcedureClientInterceptorOptions } from '../shared/server.DLt5njUb.mjs';
6
+ import { Meta } from '@orpc/contract';
7
+ import { ORPCError } from '@orpc/client';
8
8
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
9
+ interface BatchHandlerOptions<T extends Context> {
10
+ /**
11
+ * The max size of the batch allowed.
12
+ *
13
+ * @default 10
14
+ */
15
+ maxSize?: Value<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<number, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
28
+ /**
29
+ * success batch response headers.
30
+ *
31
+ * @default {}
32
+ */
33
+ headers?: Value<StandardHeaders, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
34
+ }
35
+ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
36
+ private readonly maxSize;
37
+ private readonly mapRequestItem;
38
+ private readonly successStatus;
39
+ private readonly headers;
40
+ order: number;
41
+ constructor(options?: BatchHandlerOptions<T>);
42
+ init(options: StandardHandlerOptions<T>): void;
43
+ }
44
+
45
+ interface CORSOptions<T extends Context> {
46
+ origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
47
+ timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
12
48
  allowMethods?: readonly string[];
13
49
  allowHeaders?: readonly string[];
14
50
  maxAge?: number;
15
51
  credentials?: boolean;
16
52
  exposeHeaders?: readonly string[];
17
53
  }
18
- declare class CORSPlugin<TContext extends Context> implements HandlerPlugin<TContext> {
54
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
55
  private readonly options;
20
- constructor(options?: CORSOptions<TContext>);
21
- init(options: StandardHandlerOptions<TContext>): void;
56
+ order: number;
57
+ constructor(options?: CORSOptions<T>);
58
+ init(options: StandardHandlerOptions<T>): void;
22
59
  }
23
60
 
24
61
  interface ResponseHeadersPluginContext {
25
62
  resHeaders?: Headers;
26
63
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements HandlerPlugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
64
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
65
+ init(options: StandardHandlerOptions<T>): void;
66
+ }
67
+
68
+ interface SimpleCsrfProtectionHandlerPluginOptions<T extends Context> {
69
+ /**
70
+ * The name of the header to check.
71
+ *
72
+ * @default 'x-csrf-token'
73
+ */
74
+ headerName?: Value<string, [options: StandardHandlerInterceptorOptions<T>]>;
75
+ /**
76
+ * The value of the header to check.
77
+ *
78
+ * @default 'orpc'
79
+ *
80
+ */
81
+ headerValue?: Value<string, [options: StandardHandlerInterceptorOptions<T>]>;
82
+ /**
83
+ * Exclude a procedure from the plugin.
84
+ *
85
+ * @default false
86
+ *
87
+ */
88
+ exclude?: Value<boolean, [options: ProcedureClientInterceptorOptions<T, Record<never, never>, Meta>]>;
89
+ /**
90
+ * The error thrown when the CSRF token is invalid.
91
+ *
92
+ * @default new ORPCError('CSRF_TOKEN_MISMATCH', {
93
+ * status: 403,
94
+ * message: 'Invalid CSRF token',
95
+ * })
96
+ */
97
+ error?: InstanceType<typeof ORPCError>;
98
+ }
99
+ declare class SimpleCsrfProtectionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
100
+ private readonly headerName;
101
+ private readonly headerValue;
102
+ private readonly exclude;
103
+ private readonly error;
104
+ constructor(options?: SimpleCsrfProtectionHandlerPluginOptions<T>);
105
+ order: number;
106
+ init(options: StandardHandlerOptions<T>): void;
29
107
  }
30
108
 
31
- export { type CORSOptions, CORSPlugin, HandlerPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
109
+ export { type BatchHandlerOptions, BatchHandlerPlugin, type CORSOptions, CORSPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext, SimpleCsrfProtectionHandlerPlugin, type SimpleCsrfProtectionHandlerPluginOptions };
@@ -1,31 +1,109 @@
1
- import { b as StandardHandlerInterceptorOptions, H as HandlerPlugin, a as StandardHandlerOptions } from '../shared/server.B3Tm0IXY.js';
2
- export { C as CompositePlugin } from '../shared/server.B3Tm0IXY.js';
3
1
  import { Value } from '@orpc/shared';
4
- import { C as Context } from '../shared/server.BYTulgUc.js';
5
- import '@orpc/contract';
6
- import '@orpc/standard-server';
7
- import '@orpc/client';
2
+ import { StandardRequest, StandardHeaders } from '@orpc/standard-server';
3
+ import { BatchResponseBodyItem } from '@orpc/standard-server/batch';
4
+ import { g as StandardHandlerInterceptorOptions, i as StandardHandlerPlugin, a as StandardHandlerOptions } from '../shared/server.DfyOFejj.js';
5
+ import { C as Context, P as ProcedureClientInterceptorOptions } from '../shared/server.DLt5njUb.js';
6
+ import { Meta } from '@orpc/contract';
7
+ import { ORPCError } from '@orpc/client';
8
8
 
9
- interface CORSOptions<TContext extends Context> {
10
- origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
11
- timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<TContext>]>;
9
+ interface BatchHandlerOptions<T extends Context> {
10
+ /**
11
+ * The max size of the batch allowed.
12
+ *
13
+ * @default 10
14
+ */
15
+ maxSize?: Value<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<number, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
28
+ /**
29
+ * success batch response headers.
30
+ *
31
+ * @default {}
32
+ */
33
+ headers?: Value<StandardHeaders, [responses: Promise<BatchResponseBodyItem>[], batchOptions: StandardHandlerInterceptorOptions<T>]>;
34
+ }
35
+ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
36
+ private readonly maxSize;
37
+ private readonly mapRequestItem;
38
+ private readonly successStatus;
39
+ private readonly headers;
40
+ order: number;
41
+ constructor(options?: BatchHandlerOptions<T>);
42
+ init(options: StandardHandlerOptions<T>): void;
43
+ }
44
+
45
+ interface CORSOptions<T extends Context> {
46
+ origin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
47
+ timingOrigin?: Value<string | readonly string[] | null | undefined, [origin: string, options: StandardHandlerInterceptorOptions<T>]>;
12
48
  allowMethods?: readonly string[];
13
49
  allowHeaders?: readonly string[];
14
50
  maxAge?: number;
15
51
  credentials?: boolean;
16
52
  exposeHeaders?: readonly string[];
17
53
  }
18
- declare class CORSPlugin<TContext extends Context> implements HandlerPlugin<TContext> {
54
+ declare class CORSPlugin<T extends Context> implements StandardHandlerPlugin<T> {
19
55
  private readonly options;
20
- constructor(options?: CORSOptions<TContext>);
21
- init(options: StandardHandlerOptions<TContext>): void;
56
+ order: number;
57
+ constructor(options?: CORSOptions<T>);
58
+ init(options: StandardHandlerOptions<T>): void;
22
59
  }
23
60
 
24
61
  interface ResponseHeadersPluginContext {
25
62
  resHeaders?: Headers;
26
63
  }
27
- declare class ResponseHeadersPlugin<TContext extends ResponseHeadersPluginContext & Context> implements HandlerPlugin<TContext> {
28
- init(options: StandardHandlerOptions<TContext>): void;
64
+ declare class ResponseHeadersPlugin<T extends ResponseHeadersPluginContext> implements StandardHandlerPlugin<T> {
65
+ init(options: StandardHandlerOptions<T>): void;
66
+ }
67
+
68
+ interface SimpleCsrfProtectionHandlerPluginOptions<T extends Context> {
69
+ /**
70
+ * The name of the header to check.
71
+ *
72
+ * @default 'x-csrf-token'
73
+ */
74
+ headerName?: Value<string, [options: StandardHandlerInterceptorOptions<T>]>;
75
+ /**
76
+ * The value of the header to check.
77
+ *
78
+ * @default 'orpc'
79
+ *
80
+ */
81
+ headerValue?: Value<string, [options: StandardHandlerInterceptorOptions<T>]>;
82
+ /**
83
+ * Exclude a procedure from the plugin.
84
+ *
85
+ * @default false
86
+ *
87
+ */
88
+ exclude?: Value<boolean, [options: ProcedureClientInterceptorOptions<T, Record<never, never>, Meta>]>;
89
+ /**
90
+ * The error thrown when the CSRF token is invalid.
91
+ *
92
+ * @default new ORPCError('CSRF_TOKEN_MISMATCH', {
93
+ * status: 403,
94
+ * message: 'Invalid CSRF token',
95
+ * })
96
+ */
97
+ error?: InstanceType<typeof ORPCError>;
98
+ }
99
+ declare class SimpleCsrfProtectionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
100
+ private readonly headerName;
101
+ private readonly headerValue;
102
+ private readonly exclude;
103
+ private readonly error;
104
+ constructor(options?: SimpleCsrfProtectionHandlerPluginOptions<T>);
105
+ order: number;
106
+ init(options: StandardHandlerOptions<T>): void;
29
107
  }
30
108
 
31
- export { type CORSOptions, CORSPlugin, HandlerPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext };
109
+ export { type BatchHandlerOptions, BatchHandlerPlugin, type CORSOptions, CORSPlugin, ResponseHeadersPlugin, type ResponseHeadersPluginContext, SimpleCsrfProtectionHandlerPlugin, type SimpleCsrfProtectionHandlerPluginOptions };
@@ -1,8 +1,99 @@
1
- export { C as CompositePlugin } from '../shared/server.Q6ZmnTgO.mjs';
2
1
  import { value } from '@orpc/shared';
2
+ import { parseBatchRequest, toBatchResponse } from '@orpc/standard-server/batch';
3
+ import { ORPCError } from '@orpc/client';
4
+
5
+ class BatchHandlerPlugin {
6
+ maxSize;
7
+ mapRequestItem;
8
+ successStatus;
9
+ headers;
10
+ order = 5e6;
11
+ constructor(options = {}) {
12
+ this.maxSize = options.maxSize ?? 10;
13
+ this.mapRequestItem = options.mapRequestItem ?? ((request, { request: batchRequest }) => ({
14
+ ...request,
15
+ headers: {
16
+ ...batchRequest.headers,
17
+ ...request.headers
18
+ }
19
+ }));
20
+ this.successStatus = options.successStatus ?? 207;
21
+ this.headers = options.headers ?? {};
22
+ }
23
+ init(options) {
24
+ options.rootInterceptors ??= [];
25
+ options.rootInterceptors.unshift(async (options2) => {
26
+ if (options2.request.headers["x-orpc-batch"] !== "1") {
27
+ return options2.next();
28
+ }
29
+ let isParsing = false;
30
+ try {
31
+ isParsing = true;
32
+ const parsed = parseBatchRequest({ ...options2.request, body: await options2.request.body() });
33
+ isParsing = false;
34
+ const maxSize = await value(this.maxSize, options2);
35
+ if (parsed.length > maxSize) {
36
+ return {
37
+ matched: true,
38
+ response: {
39
+ status: 413,
40
+ headers: {},
41
+ body: "Batch request size exceeds the maximum allowed size"
42
+ }
43
+ };
44
+ }
45
+ const responses = parsed.map(
46
+ (request, index) => {
47
+ const mapped = this.mapRequestItem(request, options2);
48
+ return options2.next({ ...options2, request: { ...mapped, body: () => Promise.resolve(mapped.body) } }).then(({ response: response2, matched }) => {
49
+ if (matched) {
50
+ return { ...response2, index };
51
+ }
52
+ return { index, status: 404, headers: {}, body: "No procedure matched" };
53
+ }).catch(() => {
54
+ return { index, status: 500, headers: {}, body: "Internal server error" };
55
+ });
56
+ }
57
+ );
58
+ await Promise.race(responses);
59
+ const status = await value(this.successStatus, responses, options2);
60
+ const headers = await value(this.headers, responses, options2);
61
+ const response = toBatchResponse({
62
+ status,
63
+ headers,
64
+ body: async function* () {
65
+ const promises = [...responses];
66
+ while (true) {
67
+ const handling = promises.filter((p) => p !== void 0);
68
+ if (handling.length === 0) {
69
+ return;
70
+ }
71
+ const result = await Promise.race(handling);
72
+ promises[result.index] = void 0;
73
+ yield result;
74
+ }
75
+ }()
76
+ });
77
+ return {
78
+ matched: true,
79
+ response
80
+ };
81
+ } catch (cause) {
82
+ if (isParsing) {
83
+ return {
84
+ matched: true,
85
+ response: { status: 400, headers: {}, body: "Invalid batch request, this could be caused by a malformed request body or a missing header" }
86
+ };
87
+ }
88
+ throw cause;
89
+ }
90
+ });
91
+ }
92
+ }
3
93
 
4
94
  class CORSPlugin {
5
95
  options;
96
+ order = 9e6;
6
97
  constructor(options = {}) {
7
98
  const defaults = {
8
99
  origin: (origin) => origin,
@@ -79,14 +170,19 @@ class ResponseHeadersPlugin {
79
170
  init(options) {
80
171
  options.rootInterceptors ??= [];
81
172
  options.rootInterceptors.push(async (interceptorOptions) => {
82
- const headers = new Headers();
83
- interceptorOptions.context.resHeaders = headers;
84
- const result = await interceptorOptions.next();
173
+ const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
174
+ const result = await interceptorOptions.next({
175
+ ...interceptorOptions,
176
+ context: {
177
+ ...interceptorOptions.context,
178
+ resHeaders
179
+ }
180
+ });
85
181
  if (!result.matched) {
86
182
  return result;
87
183
  }
88
184
  const responseHeaders = result.response.headers;
89
- for (const [key, value] of headers) {
185
+ for (const [key, value] of resHeaders) {
90
186
  if (Array.isArray(responseHeaders[key])) {
91
187
  responseHeaders[key].push(value);
92
188
  } else if (responseHeaders[key] !== void 0) {
@@ -100,4 +196,47 @@ class ResponseHeadersPlugin {
100
196
  }
101
197
  }
102
198
 
103
- export { CORSPlugin, ResponseHeadersPlugin };
199
+ const SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL = Symbol("SIMPLE_CSRF_PROTECTION_CONTEXT");
200
+ class SimpleCsrfProtectionHandlerPlugin {
201
+ headerName;
202
+ headerValue;
203
+ exclude;
204
+ error;
205
+ constructor(options = {}) {
206
+ this.headerName = options.headerName ?? "x-csrf-token";
207
+ this.headerValue = options.headerValue ?? "orpc";
208
+ this.exclude = options.exclude ?? false;
209
+ this.error = options.error ?? new ORPCError("CSRF_TOKEN_MISMATCH", {
210
+ status: 403,
211
+ message: "Invalid CSRF token"
212
+ });
213
+ }
214
+ order = 8e6;
215
+ init(options) {
216
+ options.rootInterceptors ??= [];
217
+ options.clientInterceptors ??= [];
218
+ options.rootInterceptors.unshift(async (options2) => {
219
+ const headerName = await value(this.headerName, options2);
220
+ const headerValue = await value(this.headerValue, options2);
221
+ return options2.next({
222
+ ...options2,
223
+ context: {
224
+ ...options2.context,
225
+ [SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]: options2.request.headers[headerName] === headerValue
226
+ }
227
+ });
228
+ });
229
+ options.clientInterceptors.unshift(async (options2) => {
230
+ if (typeof options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL] !== "boolean") {
231
+ throw new TypeError("[SimpleCsrfProtectionHandlerPlugin] CSRF protection context has been corrupted or modified by another plugin or interceptor");
232
+ }
233
+ const excluded = await value(this.exclude, options2);
234
+ if (!excluded && !options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]) {
235
+ throw this.error;
236
+ }
237
+ return options2.next();
238
+ });
239
+ }
240
+ }
241
+
242
+ export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin };
@@ -0,0 +1,9 @@
1
+ function resolveFriendlyStandardHandleOptions(options) {
2
+ return {
3
+ ...options,
4
+ context: options?.context ?? {}
5
+ // Context only optional if all fields are optional
6
+ };
7
+ }
8
+
9
+ export { resolveFriendlyStandardHandleOptions as r };
@@ -1,6 +1,6 @@
1
1
  import { isContractProcedure, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from '@orpc/contract';
2
2
  import { fallbackORPCErrorStatus, ORPCError } from '@orpc/client';
3
- import { value, intercept, toError } from '@orpc/shared';
3
+ import { value, intercept } from '@orpc/shared';
4
4
 
5
5
  const LAZY_SYMBOL = Symbol("ORPC_LAZY_SYMBOL");
6
6
  function lazy(loader, meta = {}) {
@@ -127,7 +127,7 @@ function createProcedureClient(lazyableProcedure, ...[options]) {
127
127
  );
128
128
  } catch (e) {
129
129
  if (!(e instanceof ORPCError)) {
130
- throw toError(e);
130
+ throw e;
131
131
  }
132
132
  const validated = await validateORPCError(procedure["~orpc"].errorMap, e);
133
133
  throw validated;
@@ -169,35 +169,29 @@ async function executeProcedureInternal(procedure, options) {
169
169
  const middlewares = procedure["~orpc"].middlewares;
170
170
  const inputValidationIndex = Math.min(Math.max(0, procedure["~orpc"].inputValidationIndex), middlewares.length);
171
171
  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);
172
+ const next = async (index, context, input) => {
173
+ let currentInput = input;
180
174
  if (index === inputValidationIndex) {
181
175
  currentInput = await validateInput(procedure, currentInput);
182
176
  }
183
177
  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
- };
178
+ const output = mid ? (await mid({
179
+ ...options,
180
+ context,
181
+ next: async (...[nextOptions]) => {
182
+ const nextContext = nextOptions?.context ?? {};
183
+ return {
184
+ output: await next(index + 1, mergeCurrentContext(context, nextContext), currentInput),
185
+ context: nextContext
186
+ };
187
+ }
188
+ }, currentInput, middlewareOutputFn)).output : await procedure["~orpc"].handler({ ...options, context, input: currentInput });
191
189
  if (index === outputValidationIndex) {
192
- const validatedOutput = await validateOutput(procedure, result.output);
193
- return {
194
- context: result.context,
195
- output: validatedOutput
196
- };
190
+ return await validateOutput(procedure, output);
197
191
  }
198
- return result;
192
+ return output;
199
193
  };
200
- return (await next()).output;
194
+ return next(0, options.context, options.input);
201
195
  }
202
196
 
203
197
  const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol("ORPC_HIDDEN_ROUTER_CONTRACT");
@@ -367,8 +361,4 @@ function call(procedure, input, ...rest) {
367
361
  return createProcedureClient(procedure, ...rest)(input);
368
362
  }
369
363
 
370
- function toHttpPath(path) {
371
- return `/${path.map(encodeURIComponent).join("/")}`;
372
- }
373
-
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 };
364
+ export { LAZY_SYMBOL as L, Procedure as P, createContractedProcedure as a, addMiddleware as b, createProcedureClient as c, isLazy as d, enhanceRouter as e, createAssertedLazyProcedure as f, getRouter as g, createORPCErrorConstructorMap as h, isProcedure as i, getLazyMeta as j, middlewareOutputFn as k, lazy as l, mergeCurrentContext as m, isStartWithMiddlewares as n, mergeMiddlewares as o, call as p, getHiddenRouterContract as q, createAccessibleLazyRouter as r, setHiddenRouterContract as s, traverseContractProcedures as t, unlazy as u, validateORPCError as v, resolveContractProcedures as w, unlazyRouter as x };
@@ -0,0 +1,10 @@
1
+ import { C as Context } from './server.DLt5njUb.mjs';
2
+ import { S as StandardHandleOptions } from './server.Dm5DEJl5.mjs';
3
+
4
+ type FriendlyStandardHandleOptions<T extends Context> = Omit<StandardHandleOptions<T>, 'context'> & (Record<never, never> extends T ? {
5
+ context?: T;
6
+ } : {
7
+ context: T;
8
+ });
9
+
10
+ export type { FriendlyStandardHandleOptions as F };