@orpc/server 0.0.0-next.ac2a918 → 0.0.0-next.ac518b6
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.
- package/README.md +29 -21
- package/dist/adapters/aws-lambda/index.d.mts +45 -0
- package/dist/adapters/aws-lambda/index.d.ts +45 -0
- package/dist/adapters/aws-lambda/index.mjs +41 -0
- package/dist/adapters/bun-ws/index.d.mts +35 -0
- package/dist/adapters/bun-ws/index.d.ts +35 -0
- package/dist/adapters/bun-ws/index.mjs +47 -0
- package/dist/adapters/crossws/index.d.mts +32 -0
- package/dist/adapters/crossws/index.d.ts +32 -0
- package/dist/adapters/crossws/index.mjs +47 -0
- package/dist/adapters/fetch/index.d.mts +78 -0
- package/dist/adapters/fetch/index.d.ts +78 -0
- package/dist/adapters/fetch/index.mjs +110 -0
- package/dist/adapters/message-port/index.d.mts +30 -0
- package/dist/adapters/message-port/index.d.ts +30 -0
- package/dist/adapters/message-port/index.mjs +41 -0
- package/dist/adapters/node/index.d.mts +77 -0
- package/dist/adapters/node/index.d.ts +77 -0
- package/dist/adapters/node/index.mjs +95 -0
- package/dist/adapters/standard/index.d.mts +27 -0
- package/dist/adapters/standard/index.d.ts +27 -0
- package/dist/adapters/standard/index.mjs +8 -0
- package/dist/adapters/standard-peer/index.d.mts +14 -0
- package/dist/adapters/standard-peer/index.d.ts +14 -0
- package/dist/adapters/standard-peer/index.mjs +7 -0
- package/dist/adapters/websocket/index.d.mts +53 -0
- package/dist/adapters/websocket/index.d.ts +53 -0
- package/dist/adapters/websocket/index.mjs +69 -0
- package/dist/adapters/ws/index.d.mts +30 -0
- package/dist/adapters/ws/index.d.ts +30 -0
- package/dist/adapters/ws/index.mjs +39 -0
- package/dist/hibernation/index.d.mts +44 -0
- package/dist/hibernation/index.d.ts +44 -0
- package/dist/hibernation/index.mjs +65 -0
- package/dist/index.d.mts +834 -0
- package/dist/index.d.ts +834 -0
- package/dist/index.mjs +488 -0
- package/dist/plugins/index.d.mts +156 -0
- package/dist/plugins/index.d.ts +156 -0
- package/dist/plugins/index.mjs +259 -0
- package/dist/shared/server.6ohwBdwx.d.mts +192 -0
- package/dist/shared/server.6ohwBdwx.d.ts +192 -0
- package/dist/shared/server.B3dVpAsJ.d.mts +12 -0
- package/dist/shared/server.B6GspgNq.d.ts +12 -0
- package/dist/shared/server.BE3B4vij.d.ts +74 -0
- package/dist/shared/server.BW-nUGgA.mjs +36 -0
- package/dist/shared/server.BtQsqpPB.d.mts +74 -0
- package/dist/shared/server.CB8Snncu.mjs +186 -0
- package/dist/shared/server.CKafa5G2.d.mts +12 -0
- package/dist/shared/server.CeW2jMCj.d.ts +12 -0
- package/dist/{chunk-MHVECKBC.js → shared/server.DLJzqnSX.mjs} +171 -224
- package/dist/shared/server.DZ5BIITo.mjs +9 -0
- package/dist/shared/server.DxNFsvpM.mjs +20 -0
- package/package.json +78 -39
- package/dist/chunk-MBMXGUNI.js +0 -32
- package/dist/chunk-NTHCS5CK.js +0 -182
- package/dist/chunk-TXHKQO7N.js +0 -120
- package/dist/fetch.js +0 -10
- package/dist/hono.js +0 -34
- package/dist/index.js +0 -413
- package/dist/next.js +0 -31
- package/dist/node.js +0 -31
- package/dist/plugins.js +0 -11
- package/dist/src/adapters/fetch/index.d.ts +0 -3
- package/dist/src/adapters/fetch/rpc-handler.d.ts +0 -11
- package/dist/src/adapters/fetch/types.d.ts +0 -14
- package/dist/src/adapters/hono/index.d.ts +0 -3
- package/dist/src/adapters/hono/middleware.d.ts +0 -12
- package/dist/src/adapters/next/index.d.ts +0 -3
- package/dist/src/adapters/next/serve.d.ts +0 -19
- package/dist/src/adapters/node/index.d.ts +0 -3
- package/dist/src/adapters/node/rpc-handler.d.ts +0 -11
- package/dist/src/adapters/node/types.d.ts +0 -22
- package/dist/src/adapters/standard/handler.d.ts +0 -53
- package/dist/src/adapters/standard/index.d.ts +0 -6
- package/dist/src/adapters/standard/rpc-codec.d.ts +0 -16
- package/dist/src/adapters/standard/rpc-handler.d.ts +0 -8
- package/dist/src/adapters/standard/rpc-matcher.d.ts +0 -10
- package/dist/src/adapters/standard/types.d.ts +0 -21
- package/dist/src/builder-variants.d.ts +0 -75
- package/dist/src/builder.d.ts +0 -58
- package/dist/src/config.d.ts +0 -6
- package/dist/src/context.d.ts +0 -8
- package/dist/src/error.d.ts +0 -12
- package/dist/src/hidden.d.ts +0 -8
- package/dist/src/implementer-procedure.d.ts +0 -33
- package/dist/src/implementer-variants.d.ts +0 -18
- package/dist/src/implementer.d.ts +0 -29
- package/dist/src/index.d.ts +0 -25
- package/dist/src/lazy-utils.d.ts +0 -6
- package/dist/src/lazy.d.ts +0 -22
- package/dist/src/middleware-decorated.d.ts +0 -11
- package/dist/src/middleware-utils.d.ts +0 -5
- package/dist/src/middleware.d.ts +0 -38
- package/dist/src/plugins/base.d.ts +0 -11
- package/dist/src/plugins/cors.d.ts +0 -19
- package/dist/src/plugins/index.d.ts +0 -4
- package/dist/src/plugins/response-headers.d.ts +0 -10
- package/dist/src/procedure-client.d.ts +0 -33
- package/dist/src/procedure-decorated.d.ts +0 -24
- package/dist/src/procedure-utils.d.ts +0 -19
- package/dist/src/procedure.d.ts +0 -31
- package/dist/src/router-accessible-lazy.d.ts +0 -8
- package/dist/src/router-client.d.ts +0 -12
- package/dist/src/router.d.ts +0 -30
- package/dist/src/utils.d.ts +0 -24
- package/dist/standard.js +0 -13
@@ -0,0 +1,156 @@
|
|
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 { i as StandardHandlerInterceptorOptions, c as StandardHandlerPlugin, S as StandardHandlerOptions } from '../shared/server.BE3B4vij.js';
|
5
|
+
import { C as Context, P as ProcedureClientInterceptorOptions } from '../shared/server.6ohwBdwx.js';
|
6
|
+
import { Meta, ORPCError as ORPCError$1 } from '@orpc/contract';
|
7
|
+
import { ORPCError } from '@orpc/client';
|
8
|
+
|
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 Requests 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-requests Batch Requests 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[];
|
56
|
+
maxAge?: number;
|
57
|
+
credentials?: boolean;
|
58
|
+
exposeHeaders?: readonly string[];
|
59
|
+
}
|
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> {
|
66
|
+
private readonly options;
|
67
|
+
order: number;
|
68
|
+
constructor(options?: CORSOptions<T>);
|
69
|
+
init(options: StandardHandlerOptions<T>): void;
|
70
|
+
}
|
71
|
+
|
72
|
+
interface ResponseHeadersPluginContext {
|
73
|
+
resHeaders?: Headers;
|
74
|
+
}
|
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;
|
153
|
+
}
|
154
|
+
|
155
|
+
export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin, StrictGetMethodPlugin };
|
156
|
+
export type { BatchHandlerOptions, CORSOptions, ResponseHeadersPluginContext, SimpleCsrfProtectionHandlerPluginOptions, StrictGetMethodPluginOptions };
|
@@ -0,0 +1,259 @@
|
|
1
|
+
import { value, isAsyncIteratorObject, clone } 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
|
+
}
|
106
|
+
|
107
|
+
class CORSPlugin {
|
108
|
+
options;
|
109
|
+
order = 9e6;
|
110
|
+
constructor(options = {}) {
|
111
|
+
const defaults = {
|
112
|
+
origin: (origin) => origin,
|
113
|
+
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"]
|
114
|
+
};
|
115
|
+
this.options = {
|
116
|
+
...defaults,
|
117
|
+
...options
|
118
|
+
};
|
119
|
+
}
|
120
|
+
init(options) {
|
121
|
+
options.rootInterceptors ??= [];
|
122
|
+
options.rootInterceptors.unshift(async (interceptorOptions) => {
|
123
|
+
if (interceptorOptions.request.method === "OPTIONS") {
|
124
|
+
const resHeaders = {};
|
125
|
+
if (this.options.maxAge !== void 0) {
|
126
|
+
resHeaders["access-control-max-age"] = this.options.maxAge.toString();
|
127
|
+
}
|
128
|
+
if (this.options.allowMethods?.length) {
|
129
|
+
resHeaders["access-control-allow-methods"] = flattenHeader(this.options.allowMethods);
|
130
|
+
}
|
131
|
+
const allowHeaders = this.options.allowHeaders ?? interceptorOptions.request.headers["access-control-request-headers"];
|
132
|
+
if (typeof allowHeaders === "string" || allowHeaders?.length) {
|
133
|
+
resHeaders["access-control-allow-headers"] = flattenHeader(allowHeaders);
|
134
|
+
}
|
135
|
+
return {
|
136
|
+
matched: true,
|
137
|
+
response: {
|
138
|
+
status: 204,
|
139
|
+
headers: resHeaders,
|
140
|
+
body: void 0
|
141
|
+
}
|
142
|
+
};
|
143
|
+
}
|
144
|
+
return interceptorOptions.next();
|
145
|
+
});
|
146
|
+
options.rootInterceptors.unshift(async (interceptorOptions) => {
|
147
|
+
const result = await interceptorOptions.next();
|
148
|
+
if (!result.matched) {
|
149
|
+
return result;
|
150
|
+
}
|
151
|
+
const origin = flattenHeader(interceptorOptions.request.headers.origin) ?? "";
|
152
|
+
const allowedOrigin = await value(this.options.origin, origin, interceptorOptions);
|
153
|
+
const allowedOriginArr = Array.isArray(allowedOrigin) ? allowedOrigin : [allowedOrigin];
|
154
|
+
if (allowedOriginArr.includes("*")) {
|
155
|
+
result.response.headers["access-control-allow-origin"] = "*";
|
156
|
+
} else {
|
157
|
+
if (allowedOriginArr.includes(origin)) {
|
158
|
+
result.response.headers["access-control-allow-origin"] = origin;
|
159
|
+
}
|
160
|
+
result.response.headers.vary = interceptorOptions.request.headers.vary ?? "origin";
|
161
|
+
}
|
162
|
+
const allowedTimingOrigin = await value(this.options.timingOrigin, origin, interceptorOptions);
|
163
|
+
const allowedTimingOriginArr = Array.isArray(allowedTimingOrigin) ? allowedTimingOrigin : [allowedTimingOrigin];
|
164
|
+
if (allowedTimingOriginArr.includes("*")) {
|
165
|
+
result.response.headers["timing-allow-origin"] = "*";
|
166
|
+
} else if (allowedTimingOriginArr.includes(origin)) {
|
167
|
+
result.response.headers["timing-allow-origin"] = origin;
|
168
|
+
}
|
169
|
+
if (this.options.credentials) {
|
170
|
+
result.response.headers["access-control-allow-credentials"] = "true";
|
171
|
+
}
|
172
|
+
if (this.options.exposeHeaders?.length) {
|
173
|
+
result.response.headers["access-control-expose-headers"] = flattenHeader(this.options.exposeHeaders);
|
174
|
+
}
|
175
|
+
return result;
|
176
|
+
});
|
177
|
+
}
|
178
|
+
}
|
179
|
+
|
180
|
+
class ResponseHeadersPlugin {
|
181
|
+
init(options) {
|
182
|
+
options.rootInterceptors ??= [];
|
183
|
+
options.rootInterceptors.push(async (interceptorOptions) => {
|
184
|
+
const resHeaders = interceptorOptions.context.resHeaders ?? new Headers();
|
185
|
+
const result = await interceptorOptions.next({
|
186
|
+
...interceptorOptions,
|
187
|
+
context: {
|
188
|
+
...interceptorOptions.context,
|
189
|
+
resHeaders
|
190
|
+
}
|
191
|
+
});
|
192
|
+
if (!result.matched) {
|
193
|
+
return result;
|
194
|
+
}
|
195
|
+
const responseHeaders = clone(result.response.headers);
|
196
|
+
for (const [key, value] of resHeaders) {
|
197
|
+
if (Array.isArray(responseHeaders[key])) {
|
198
|
+
responseHeaders[key].push(value);
|
199
|
+
} else if (responseHeaders[key] !== void 0) {
|
200
|
+
responseHeaders[key] = [responseHeaders[key], value];
|
201
|
+
} else {
|
202
|
+
responseHeaders[key] = value;
|
203
|
+
}
|
204
|
+
}
|
205
|
+
return {
|
206
|
+
...result,
|
207
|
+
response: {
|
208
|
+
...result.response,
|
209
|
+
headers: responseHeaders
|
210
|
+
}
|
211
|
+
};
|
212
|
+
});
|
213
|
+
}
|
214
|
+
}
|
215
|
+
|
216
|
+
const SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL = Symbol("SIMPLE_CSRF_PROTECTION_CONTEXT");
|
217
|
+
class SimpleCsrfProtectionHandlerPlugin {
|
218
|
+
headerName;
|
219
|
+
headerValue;
|
220
|
+
exclude;
|
221
|
+
error;
|
222
|
+
constructor(options = {}) {
|
223
|
+
this.headerName = options.headerName ?? "x-csrf-token";
|
224
|
+
this.headerValue = options.headerValue ?? "orpc";
|
225
|
+
this.exclude = options.exclude ?? false;
|
226
|
+
this.error = options.error ?? new ORPCError("CSRF_TOKEN_MISMATCH", {
|
227
|
+
status: 403,
|
228
|
+
message: "Invalid CSRF token"
|
229
|
+
});
|
230
|
+
}
|
231
|
+
order = 8e6;
|
232
|
+
init(options) {
|
233
|
+
options.rootInterceptors ??= [];
|
234
|
+
options.clientInterceptors ??= [];
|
235
|
+
options.rootInterceptors.unshift(async (options2) => {
|
236
|
+
const headerName = await value(this.headerName, options2);
|
237
|
+
const headerValue = await value(this.headerValue, options2);
|
238
|
+
return options2.next({
|
239
|
+
...options2,
|
240
|
+
context: {
|
241
|
+
...options2.context,
|
242
|
+
[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]: options2.request.headers[headerName] === headerValue
|
243
|
+
}
|
244
|
+
});
|
245
|
+
});
|
246
|
+
options.clientInterceptors.unshift(async (options2) => {
|
247
|
+
if (typeof options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL] !== "boolean") {
|
248
|
+
throw new TypeError("[SimpleCsrfProtectionHandlerPlugin] CSRF protection context has been corrupted or modified by another plugin or interceptor");
|
249
|
+
}
|
250
|
+
const excluded = await value(this.exclude, options2);
|
251
|
+
if (!excluded && !options2.context[SIMPLE_CSRF_PROTECTION_CONTEXT_SYMBOL]) {
|
252
|
+
throw this.error;
|
253
|
+
}
|
254
|
+
return options2.next();
|
255
|
+
});
|
256
|
+
}
|
257
|
+
}
|
258
|
+
|
259
|
+
export { BatchHandlerPlugin, CORSPlugin, ResponseHeadersPlugin, SimpleCsrfProtectionHandlerPlugin };
|
@@ -0,0 +1,192 @@
|
|
1
|
+
import { ORPCErrorCode, ORPCErrorOptions, ORPCError, HTTPPath, ClientContext, Client } from '@orpc/client';
|
2
|
+
import { ErrorMap, ErrorMapItem, InferSchemaInput, AnySchema, Meta, ContractProcedureDef, InferSchemaOutput, ErrorFromErrorMap, AnyContractRouter, ContractProcedure } from '@orpc/contract';
|
3
|
+
import { MaybeOptionalOptions, Promisable, Interceptor, PromiseWithError, Value } from '@orpc/shared';
|
4
|
+
|
5
|
+
type Context = Record<PropertyKey, any>;
|
6
|
+
type MergedInitialContext<TInitial extends Context, TAdditional extends Context, TCurrent extends Context> = TInitial & Omit<TAdditional, keyof TCurrent>;
|
7
|
+
type MergedCurrentContext<T extends Context, U extends Context> = Omit<T, keyof U> & U;
|
8
|
+
declare function mergeCurrentContext<T extends Context, U extends Context>(context: T, other: U): MergedCurrentContext<T, U>;
|
9
|
+
|
10
|
+
type ORPCErrorConstructorMapItemOptions<TData> = Omit<ORPCErrorOptions<TData>, 'defined' | 'status'>;
|
11
|
+
type ORPCErrorConstructorMapItem<TCode extends ORPCErrorCode, TInData> = (...rest: MaybeOptionalOptions<ORPCErrorConstructorMapItemOptions<TInData>>) => ORPCError<TCode, TInData>;
|
12
|
+
type ORPCErrorConstructorMap<T extends ErrorMap> = {
|
13
|
+
[K in keyof T]: K extends ORPCErrorCode ? T[K] extends ErrorMapItem<infer UInputSchema> ? ORPCErrorConstructorMapItem<K, InferSchemaInput<UInputSchema>> : never : never;
|
14
|
+
};
|
15
|
+
declare function createORPCErrorConstructorMap<T extends ErrorMap>(errors: T): ORPCErrorConstructorMap<T>;
|
16
|
+
declare function validateORPCError(map: ErrorMap, error: ORPCError<any, any>): Promise<ORPCError<string, unknown>>;
|
17
|
+
|
18
|
+
declare const LAZY_SYMBOL: unique symbol;
|
19
|
+
interface LazyMeta {
|
20
|
+
prefix?: HTTPPath;
|
21
|
+
}
|
22
|
+
interface Lazy<T> {
|
23
|
+
[LAZY_SYMBOL]: {
|
24
|
+
loader: () => Promise<{
|
25
|
+
default: T;
|
26
|
+
}>;
|
27
|
+
meta: LazyMeta;
|
28
|
+
};
|
29
|
+
}
|
30
|
+
type Lazyable<T> = T | Lazy<T>;
|
31
|
+
/**
|
32
|
+
* Create a lazy thing.
|
33
|
+
*/
|
34
|
+
declare function lazy<T>(loader: () => Promise<{
|
35
|
+
default: T;
|
36
|
+
}>, meta?: LazyMeta): Lazy<T>;
|
37
|
+
declare function isLazy(item: unknown): item is Lazy<any>;
|
38
|
+
declare function getLazyMeta(lazied: Lazy<any>): LazyMeta;
|
39
|
+
declare function unlazy<T extends Lazyable<any>>(lazied: T): Promise<{
|
40
|
+
default: T extends Lazy<infer U> ? U : T;
|
41
|
+
}>;
|
42
|
+
|
43
|
+
interface ProcedureHandlerOptions<TCurrentContext extends Context, TInput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
|
44
|
+
context: TCurrentContext;
|
45
|
+
input: TInput;
|
46
|
+
path: readonly string[];
|
47
|
+
procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
|
48
|
+
signal?: AbortSignal;
|
49
|
+
lastEventId: string | undefined;
|
50
|
+
errors: TErrorConstructorMap;
|
51
|
+
}
|
52
|
+
interface ProcedureHandler<TCurrentContext extends Context, TInput, THandlerOutput, TErrorMap extends ErrorMap, TMeta extends Meta> {
|
53
|
+
(opt: ProcedureHandlerOptions<TCurrentContext, TInput, ORPCErrorConstructorMap<TErrorMap>, TMeta>): Promisable<THandlerOutput>;
|
54
|
+
}
|
55
|
+
interface ProcedureDef<TInitialContext extends Context, TCurrentContext extends Context, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta> extends ContractProcedureDef<TInputSchema, TOutputSchema, TErrorMap, TMeta> {
|
56
|
+
__initialContext?: (type: TInitialContext) => unknown;
|
57
|
+
middlewares: readonly AnyMiddleware[];
|
58
|
+
inputValidationIndex: number;
|
59
|
+
outputValidationIndex: number;
|
60
|
+
handler: ProcedureHandler<TCurrentContext, any, any, any, any>;
|
61
|
+
}
|
62
|
+
/**
|
63
|
+
* This class represents a procedure.
|
64
|
+
*
|
65
|
+
* @see {@link https://orpc.unnoq.com/docs/procedure Procedure Docs}
|
66
|
+
*/
|
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
|
+
*/
|
71
|
+
'~orpc': ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>;
|
72
|
+
constructor(def: ProcedureDef<TInitialContext, TCurrentContext, TInputSchema, TOutputSchema, TErrorMap, TMeta>);
|
73
|
+
}
|
74
|
+
type AnyProcedure = Procedure<any, any, any, any, any, any>;
|
75
|
+
declare function isProcedure(item: unknown): item is AnyProcedure;
|
76
|
+
|
77
|
+
type MiddlewareResult<TOutContext extends Context, TOutput> = Promisable<{
|
78
|
+
output: TOutput;
|
79
|
+
context: TOutContext;
|
80
|
+
}>;
|
81
|
+
type MiddlewareNextFnOptions<TOutContext extends Context> = Record<never, never> extends TOutContext ? {
|
82
|
+
context?: TOutContext;
|
83
|
+
} : {
|
84
|
+
context: TOutContext;
|
85
|
+
};
|
86
|
+
interface MiddlewareNextFn<TOutput> {
|
87
|
+
<U extends Context = Record<never, never>>(...rest: MaybeOptionalOptions<MiddlewareNextFnOptions<U>>): MiddlewareResult<U, TOutput>;
|
88
|
+
}
|
89
|
+
interface MiddlewareOutputFn<TOutput> {
|
90
|
+
(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
|
91
|
+
}
|
92
|
+
interface MiddlewareOptions<TInContext extends Context, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
|
93
|
+
context: TInContext;
|
94
|
+
path: readonly string[];
|
95
|
+
procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
|
96
|
+
signal?: AbortSignal;
|
97
|
+
lastEventId: string | undefined;
|
98
|
+
next: MiddlewareNextFn<TOutput>;
|
99
|
+
errors: TErrorConstructorMap;
|
100
|
+
}
|
101
|
+
/**
|
102
|
+
* A function that represents a middleware.
|
103
|
+
*
|
104
|
+
* @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
|
105
|
+
*/
|
106
|
+
interface Middleware<TInContext extends Context, TOutContext extends Context, TInput, TOutput, TErrorConstructorMap extends ORPCErrorConstructorMap<any>, TMeta extends Meta> {
|
107
|
+
(options: MiddlewareOptions<TInContext, TOutput, TErrorConstructorMap, TMeta>, input: TInput, output: MiddlewareOutputFn<TOutput>): Promisable<MiddlewareResult<TOutContext, TOutput>>;
|
108
|
+
}
|
109
|
+
type AnyMiddleware = Middleware<any, any, any, any, any, any>;
|
110
|
+
interface MapInputMiddleware<TInput, TMappedInput> {
|
111
|
+
(input: TInput): TMappedInput;
|
112
|
+
}
|
113
|
+
declare function middlewareOutputFn<TOutput>(output: TOutput): MiddlewareResult<Record<never, never>, TOutput>;
|
114
|
+
|
115
|
+
type ProcedureClient<TClientContext extends ClientContext, TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> = Client<TClientContext, InferSchemaInput<TInputSchema>, InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>;
|
116
|
+
interface ProcedureClientInterceptorOptions<TInitialContext extends Context, TErrorMap extends ErrorMap, TMeta extends Meta> {
|
117
|
+
context: TInitialContext;
|
118
|
+
input: unknown;
|
119
|
+
errors: ORPCErrorConstructorMap<TErrorMap>;
|
120
|
+
path: readonly string[];
|
121
|
+
procedure: Procedure<Context, Context, AnySchema, AnySchema, ErrorMap, TMeta>;
|
122
|
+
signal?: AbortSignal;
|
123
|
+
lastEventId: string | undefined;
|
124
|
+
}
|
125
|
+
type CreateProcedureClientOptions<TInitialContext extends Context, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap, TMeta extends Meta, TClientContext extends ClientContext> = {
|
126
|
+
/**
|
127
|
+
* This is helpful for logging and analytics.
|
128
|
+
*/
|
129
|
+
path?: readonly string[];
|
130
|
+
interceptors?: Interceptor<ProcedureClientInterceptorOptions<TInitialContext, TErrorMap, TMeta>, PromiseWithError<InferSchemaOutput<TOutputSchema>, ErrorFromErrorMap<TErrorMap>>>[];
|
131
|
+
} & (Record<never, never> extends TInitialContext ? {
|
132
|
+
context?: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
|
133
|
+
} : {
|
134
|
+
context: Value<Promisable<TInitialContext>, [clientContext: TClientContext]>;
|
135
|
+
});
|
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>;
|
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
|
+
*/
|
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> : {
|
150
|
+
[K in keyof T]: T[K] extends AnyContractRouter ? Lazyable<Router<T[K], TInitialContext>> : never;
|
151
|
+
};
|
152
|
+
type AnyRouter = Router<any, any>;
|
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
|
+
*/
|
160
|
+
type InferRouterInitialContexts<T extends AnyRouter> = T extends Procedure<infer UInitialContext, any, any, any, any, any> ? UInitialContext : {
|
161
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInitialContexts<U> : never;
|
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
|
+
*/
|
169
|
+
type InferRouterCurrentContexts<T extends AnyRouter> = T extends Procedure<any, infer UCurrentContext, any, any, any, any> ? UCurrentContext : {
|
170
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterCurrentContexts<U> : never;
|
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
|
+
*/
|
178
|
+
type InferRouterInputs<T extends AnyRouter> = T extends Procedure<any, any, infer UInputSchema, any, any, any> ? InferSchemaInput<UInputSchema> : {
|
179
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterInputs<U> : never;
|
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
|
+
*/
|
187
|
+
type InferRouterOutputs<T extends AnyRouter> = T extends Procedure<any, any, any, infer UOutputSchema, any, any> ? InferSchemaOutput<UOutputSchema> : {
|
188
|
+
[K in keyof T]: T[K] extends Lazyable<infer U extends AnyRouter> ? InferRouterOutputs<U> : never;
|
189
|
+
};
|
190
|
+
|
191
|
+
export { middlewareOutputFn as B, isProcedure as F, createProcedureClient as G, Procedure as b, mergeCurrentContext as m, createORPCErrorConstructorMap as n, LAZY_SYMBOL as o, lazy as q, isLazy as r, getLazyMeta as s, unlazy as u, validateORPCError as v };
|
192
|
+
export type { AnyProcedure as A, Context as C, ProcedureHandlerOptions as D, ProcedureDef as E, InferRouterInitialContexts as H, InferRouterInitialContext as I, InferRouterCurrentContexts as J, InferRouterInputs as K, Lazyable as L, Middleware as M, InferRouterOutputs as N, ORPCErrorConstructorMap as O, ProcedureClientInterceptorOptions as P, Router as R, AnyRouter as a, MergedInitialContext as c, MergedCurrentContext as d, MapInputMiddleware as e, CreateProcedureClientOptions as f, ProcedureClient as g, AnyMiddleware as h, Lazy as i, ProcedureHandler as j, ORPCErrorConstructorMapItemOptions as k, ORPCErrorConstructorMapItem as l, LazyMeta as p, MiddlewareResult as t, MiddlewareNextFnOptions as w, MiddlewareNextFn as x, MiddlewareOutputFn as y, MiddlewareOptions as z };
|