@orpc/server 2.0.0-beta.15 → 2.0.0-beta.17

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 CHANGED
@@ -175,7 +175,7 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
175
175
  <a href="https://github.com/illarionvk?ref=orpc" target="_blank" rel="noopener" title="Illarion Koperski"><img src="https://avatars.githubusercontent.com/u/5012724?u=7cfa13652f7ac5fb3c56d880e3eb3fbe40c3ea34&amp;v=4" width="32" height="32" alt="Illarion Koperski" /></a>
176
176
  <a href="https://github.com/steelbrain?ref=orpc" target="_blank" rel="noopener" title="Anees Iqbal"><img src="https://avatars.githubusercontent.com/u/4278113?u=22b80b5399eed68ac76cd58b02961b0481f1db11&amp;v=4" width="32" height="32" alt="Anees Iqbal" /></a>
177
177
  <a href="https://github.com/Scrumplex?ref=orpc" target="_blank" rel="noopener" title="Sefa Eyeoglu"><img src="https://avatars.githubusercontent.com/u/11587657?u=ab503582165c0bbff0cca47ce31c9450bb1553c9&amp;v=4" width="32" height="32" alt="Sefa Eyeoglu" /></a>
178
- <a href="https://github.com/nattstack?ref=orpc" target="_blank" rel="noopener" title="Natt"><img src="https://avatars.githubusercontent.com/u/31426677?u=fa9dbb8b3e66eb0ea3c88db5dc07f31c8c5418fe&amp;v=4" width="32" height="32" alt="Natt" /></a>
178
+ <a href="https://github.com/nattstack?ref=orpc" target="_blank" rel="noopener" title="natt"><img src="https://avatars.githubusercontent.com/u/31426677?u=fa9dbb8b3e66eb0ea3c88db5dc07f31c8c5418fe&amp;v=4" width="32" height="32" alt="natt" /></a>
179
179
  <a href="https://github.com/ChromeGG?ref=orpc" target="_blank" rel="noopener" title="Adam Tkaczyk"><img src="https://avatars.githubusercontent.com/u/39050595?u=a58ca6042a6950e94e6e92442db76ef584279bc0&amp;v=4" width="32" height="32" alt="Adam Tkaczyk" /></a>
180
180
  <a href="https://github.com/plancraft?ref=orpc" target="_blank" rel="noopener" title="plancraft"><img src="https://avatars.githubusercontent.com/u/46482287?v=4" width="32" height="32" alt="plancraft" /></a>
181
181
  </p>
@@ -1,6 +1,6 @@
1
- import { C as Context } from '../../shared/server.BL22TloH.mjs';
2
1
  import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
3
2
  import { ToFetchResponseOptions } from '@standardserver/fetch';
3
+ import { C as Context } from '../../shared/server.BL22TloH.mjs';
4
4
  import { e as StandardHandlerPlugin, b as StandardHandlerHandleOptions, S as StandardHandler, a as StandardHandlerOptions } from '../../shared/server.DJIkub_t.mjs';
5
5
  import { FriendlyStandardHandlerHandleOptions } from '../standard/index.mjs';
6
6
  import { R as Router } from '../../shared/server.BsNNjG5J.mjs';
@@ -71,54 +71,6 @@ declare class FetchHandler<T extends Context> {
71
71
  handle(request: Request, ...rest: MaybeOptionalOptions<FriendlyStandardHandlerHandleOptions<T>>): Promise<FetchHandlerHandleResult>;
72
72
  }
73
73
 
74
- declare const ORDERED_SUPPORTED_ENCODINGS: readonly ["gzip", "deflate"];
75
- interface BodyCompressionHandlerPluginOptions {
76
- /**
77
- * The compression schemes to use for response compression.
78
- * Schemes are prioritized by their order in this array and
79
- * only applied if the client supports them.
80
- *
81
- * @default ['gzip', 'deflate']
82
- */
83
- encodings?: readonly (typeof ORDERED_SUPPORTED_ENCODINGS)[number][];
84
- /**
85
- * The minimum response size in bytes required to trigger compression.
86
- * Responses smaller than this threshold will not be compressed to avoid overhead.
87
- * If the response size cannot be determined, compression will still be applied.
88
- *
89
- * @default 1024 (1KB)
90
- */
91
- threshold?: number;
92
- /**
93
- * Override the default content-type filter used to determine which responses should be compressed.
94
- *
95
- * @warning Event stream responses are never compressed, regardless of this filter's return value.
96
- * @default only responses with compressible content types are compressed.
97
- */
98
- filter?: (request: Request, response: Response) => boolean;
99
- }
100
- declare class BodyCompressionHandlerPlugin<T extends Context> implements FetchHandlerPlugin<T> {
101
- name: string;
102
- private readonly encodings;
103
- private readonly threshold;
104
- private readonly filter;
105
- constructor(options?: BodyCompressionHandlerPluginOptions);
106
- initFetchHandlerOptions(options: FetchHandlerOptions<T>): FetchHandlerOptions<T>;
107
- }
108
-
109
- interface BodyLimitHandlerPluginOptions {
110
- /**
111
- * The maximum size of the body in bytes.
112
- */
113
- maxBodySize: number;
114
- }
115
- declare class BodyLimitHandlerPlugin<T extends Context> implements FetchHandlerPlugin<T> {
116
- name: string;
117
- private readonly maxBodySize;
118
- constructor(options: BodyLimitHandlerPluginOptions);
119
- initFetchHandlerOptions(options: FetchHandlerOptions<T>): FetchHandlerOptions<T>;
120
- }
121
-
122
74
  interface RPCHandlerOptions<T extends Context> extends FetchHandlerOptions<T>, Omit<StandardHandlerOptions<T>, 'plugins'>, RPCHandlerCodecOptions<T> {
123
75
  /**
124
76
  * Configuration for {@link CSRFGuardHandlerPlugin}, which is enabled by default for `RPCHandler` over HTTP.
@@ -136,5 +88,5 @@ declare class RPCHandler<T extends Context> extends FetchHandler<T> {
136
88
  constructor(router: Router<T>, options?: NoInfer<RPCHandlerOptions<T>>);
137
89
  }
138
90
 
139
- export { BodyCompressionHandlerPlugin, BodyLimitHandlerPlugin, CompositeFetchHandlerPlugin, FetchHandler, RPCHandler };
140
- export type { BodyCompressionHandlerPluginOptions, BodyLimitHandlerPluginOptions, FetchHandlerFetchInterceptor, FetchHandlerFetchInterceptorOptions, FetchHandlerHandleResult, FetchHandlerOptions, FetchHandlerPlugin, RPCHandlerOptions };
91
+ export { CompositeFetchHandlerPlugin, FetchHandler, RPCHandler };
92
+ export type { FetchHandlerFetchInterceptor, FetchHandlerFetchInterceptorOptions, FetchHandlerHandleResult, FetchHandlerOptions, FetchHandlerPlugin, RPCHandlerOptions };
@@ -1,6 +1,6 @@
1
- import { C as Context } from '../../shared/server.BL22TloH.js';
2
1
  import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
3
2
  import { ToFetchResponseOptions } from '@standardserver/fetch';
3
+ import { C as Context } from '../../shared/server.BL22TloH.js';
4
4
  import { e as StandardHandlerPlugin, b as StandardHandlerHandleOptions, S as StandardHandler, a as StandardHandlerOptions } from '../../shared/server.DBANIheG.js';
5
5
  import { FriendlyStandardHandlerHandleOptions } from '../standard/index.js';
6
6
  import { R as Router } from '../../shared/server.Pa0F03f_.js';
@@ -71,54 +71,6 @@ declare class FetchHandler<T extends Context> {
71
71
  handle(request: Request, ...rest: MaybeOptionalOptions<FriendlyStandardHandlerHandleOptions<T>>): Promise<FetchHandlerHandleResult>;
72
72
  }
73
73
 
74
- declare const ORDERED_SUPPORTED_ENCODINGS: readonly ["gzip", "deflate"];
75
- interface BodyCompressionHandlerPluginOptions {
76
- /**
77
- * The compression schemes to use for response compression.
78
- * Schemes are prioritized by their order in this array and
79
- * only applied if the client supports them.
80
- *
81
- * @default ['gzip', 'deflate']
82
- */
83
- encodings?: readonly (typeof ORDERED_SUPPORTED_ENCODINGS)[number][];
84
- /**
85
- * The minimum response size in bytes required to trigger compression.
86
- * Responses smaller than this threshold will not be compressed to avoid overhead.
87
- * If the response size cannot be determined, compression will still be applied.
88
- *
89
- * @default 1024 (1KB)
90
- */
91
- threshold?: number;
92
- /**
93
- * Override the default content-type filter used to determine which responses should be compressed.
94
- *
95
- * @warning Event stream responses are never compressed, regardless of this filter's return value.
96
- * @default only responses with compressible content types are compressed.
97
- */
98
- filter?: (request: Request, response: Response) => boolean;
99
- }
100
- declare class BodyCompressionHandlerPlugin<T extends Context> implements FetchHandlerPlugin<T> {
101
- name: string;
102
- private readonly encodings;
103
- private readonly threshold;
104
- private readonly filter;
105
- constructor(options?: BodyCompressionHandlerPluginOptions);
106
- initFetchHandlerOptions(options: FetchHandlerOptions<T>): FetchHandlerOptions<T>;
107
- }
108
-
109
- interface BodyLimitHandlerPluginOptions {
110
- /**
111
- * The maximum size of the body in bytes.
112
- */
113
- maxBodySize: number;
114
- }
115
- declare class BodyLimitHandlerPlugin<T extends Context> implements FetchHandlerPlugin<T> {
116
- name: string;
117
- private readonly maxBodySize;
118
- constructor(options: BodyLimitHandlerPluginOptions);
119
- initFetchHandlerOptions(options: FetchHandlerOptions<T>): FetchHandlerOptions<T>;
120
- }
121
-
122
74
  interface RPCHandlerOptions<T extends Context> extends FetchHandlerOptions<T>, Omit<StandardHandlerOptions<T>, 'plugins'>, RPCHandlerCodecOptions<T> {
123
75
  /**
124
76
  * Configuration for {@link CSRFGuardHandlerPlugin}, which is enabled by default for `RPCHandler` over HTTP.
@@ -136,5 +88,5 @@ declare class RPCHandler<T extends Context> extends FetchHandler<T> {
136
88
  constructor(router: Router<T>, options?: NoInfer<RPCHandlerOptions<T>>);
137
89
  }
138
90
 
139
- export { BodyCompressionHandlerPlugin, BodyLimitHandlerPlugin, CompositeFetchHandlerPlugin, FetchHandler, RPCHandler };
140
- export type { BodyCompressionHandlerPluginOptions, BodyLimitHandlerPluginOptions, FetchHandlerFetchInterceptor, FetchHandlerFetchInterceptorOptions, FetchHandlerHandleResult, FetchHandlerOptions, FetchHandlerPlugin, RPCHandlerOptions };
91
+ export { CompositeFetchHandlerPlugin, FetchHandler, RPCHandler };
92
+ export type { FetchHandlerFetchInterceptor, FetchHandlerFetchInterceptorOptions, FetchHandlerHandleResult, FetchHandlerOptions, FetchHandlerPlugin, RPCHandlerOptions };
@@ -1,144 +1,14 @@
1
- import { toArray, sortPlugins, intercept, resolveMaybeOptionalOptions } from '@orpc/shared';
2
- import { ORPCError } from '@orpc/client';
1
+ import { sortPlugins, intercept, resolveMaybeOptionalOptions, toArray } from '@orpc/shared';
3
2
  import { toStandardLazyRequest, toFetchResponse } from '@standardserver/fetch';
4
3
  import { r as resolveFriendlyStandardHandlerHandleOptions } from '../../shared/server.W91HSRkE.mjs';
5
4
  import { C as CSRFGuardHandlerPlugin } from '../../shared/server.D_QauotT.mjs';
6
5
  import { R as RPCHandlerCodec, S as StandardHandler } from '../../shared/server.DZEvIn7o.mjs';
6
+ import '@orpc/client';
7
7
  import '@standardserver/core';
8
8
  import '../../shared/server.BDeup7Ky.mjs';
9
9
  import '@orpc/contract';
10
10
  import '../../shared/server.C_osSBcd.mjs';
11
11
 
12
- const ORDERED_SUPPORTED_ENCODINGS = ["gzip", "deflate"];
13
- class BodyCompressionHandlerPlugin {
14
- name = "~body-compression";
15
- encodings;
16
- threshold;
17
- filter;
18
- constructor(options = {}) {
19
- this.encodings = options.encodings ?? ORDERED_SUPPORTED_ENCODINGS;
20
- this.threshold = options.threshold ?? 1024;
21
- this.filter = (request, response) => {
22
- const hasContentDisposition = response.headers.has("content-disposition");
23
- const contentType = response.headers.get("content-type");
24
- if (!hasContentDisposition && contentType?.startsWith("text/event-stream")) {
25
- return false;
26
- }
27
- return options.filter ? options.filter(request, response) : isCompressibleContentType(contentType);
28
- };
29
- }
30
- initFetchHandlerOptions(options) {
31
- return {
32
- ...options,
33
- fetchInterceptors: [
34
- async (interceptorOptions) => {
35
- const result = await interceptorOptions.next();
36
- if (!result.matched) {
37
- return result;
38
- }
39
- const response = result.response;
40
- if (response.headers.has("content-encoding") || response.headers.has("transfer-encoding") || isNoTransformCacheControl(response.headers.get("cache-control"))) {
41
- return result;
42
- }
43
- const contentLength = response.headers.get("content-length");
44
- if (contentLength && Number(contentLength) < this.threshold) {
45
- return result;
46
- }
47
- const acceptEncoding = interceptorOptions.request.headers.get("accept-encoding")?.split(",").map((enc) => enc.trim().split(";")[0]);
48
- const encoding = this.encodings.find((enc) => acceptEncoding?.includes(enc));
49
- if (!response.body || encoding === void 0) {
50
- return result;
51
- }
52
- if (!this.filter(interceptorOptions.request, response)) {
53
- return result;
54
- }
55
- const compressedBody = response.body.pipeThrough(new CompressionStream(encoding));
56
- const compressedHeaders = new Headers(response.headers);
57
- compressedHeaders.delete("content-length");
58
- compressedHeaders.set("content-encoding", encoding);
59
- return {
60
- ...result,
61
- response: new Response(compressedBody, {
62
- status: response.status,
63
- statusText: response.statusText,
64
- headers: compressedHeaders
65
- })
66
- };
67
- },
68
- ...toArray(options.fetchInterceptors)
69
- ]
70
- };
71
- }
72
- }
73
- const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
74
- function isCompressibleContentType(contentType) {
75
- if (contentType === null) {
76
- return false;
77
- }
78
- return COMPRESSIBLE_CONTENT_TYPE_REGEX.test(contentType);
79
- }
80
- const CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
81
- function isNoTransformCacheControl(cacheControl) {
82
- if (cacheControl === null) {
83
- return false;
84
- }
85
- return CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
86
- }
87
-
88
- class BodyLimitHandlerPlugin {
89
- name = "~body-limit";
90
- maxBodySize;
91
- constructor(options) {
92
- this.maxBodySize = options.maxBodySize;
93
- }
94
- initFetchHandlerOptions(options) {
95
- return {
96
- ...options,
97
- fetchInterceptors: [
98
- async (interceptorOptions) => {
99
- if (!interceptorOptions.request.body) {
100
- return interceptorOptions.next();
101
- }
102
- let currentBodySize = 0;
103
- const rawReader = interceptorOptions.request.body.getReader();
104
- const body = new ReadableStream({
105
- start: async (controller) => {
106
- const reject = async (error) => {
107
- controller.error(error);
108
- await rawReader.cancel(error);
109
- };
110
- const contentLength = interceptorOptions.request.headers.get("content-length");
111
- if (contentLength && Number(contentLength) > this.maxBodySize) {
112
- await reject(new ORPCError("PAYLOAD_TOO_LARGE"));
113
- return;
114
- }
115
- while (true) {
116
- const { done, value } = await rawReader.read();
117
- if (done) {
118
- controller.close();
119
- return;
120
- }
121
- currentBodySize += value.length;
122
- if (currentBodySize > this.maxBodySize) {
123
- await reject(new ORPCError("PAYLOAD_TOO_LARGE"));
124
- return;
125
- }
126
- controller.enqueue(value);
127
- }
128
- }
129
- });
130
- const requestInit = { body, duplex: "half" };
131
- return interceptorOptions.next({
132
- ...interceptorOptions,
133
- request: new Request(interceptorOptions.request, requestInit)
134
- });
135
- },
136
- ...toArray(options.fetchInterceptors)
137
- ]
138
- };
139
- }
140
- }
141
-
142
12
  class CompositeFetchHandlerPlugin {
143
13
  name = "~composite/fetch-handler";
144
14
  plugins;
@@ -201,4 +71,4 @@ class RPCHandler extends FetchHandler {
201
71
  }
202
72
  }
203
73
 
204
- export { BodyCompressionHandlerPlugin, BodyLimitHandlerPlugin, CompositeFetchHandlerPlugin, FetchHandler, RPCHandler };
74
+ export { CompositeFetchHandlerPlugin, FetchHandler, RPCHandler };
@@ -1,9 +1,8 @@
1
+ import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
1
2
  import { SendStandardResponseOptions, NodeHttpRequest, NodeHttpResponse } from '@standardserver/node';
2
3
  import { C as Context } from '../../shared/server.BL22TloH.mjs';
3
- import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
4
4
  import { e as StandardHandlerPlugin, b as StandardHandlerHandleOptions, S as StandardHandler, a as StandardHandlerOptions } from '../../shared/server.DJIkub_t.mjs';
5
5
  import { FriendlyStandardHandlerHandleOptions } from '../standard/index.mjs';
6
- import compression from '@orpc/interop/compression';
7
6
  import { R as Router } from '../../shared/server.BsNNjG5J.mjs';
8
7
  import { R as RPCHandlerCodecOptions } from '../../shared/server.D8cib80w.mjs';
9
8
  import '@orpc/client';
@@ -71,35 +70,6 @@ declare class NodeHttpHandler<T extends Context> {
71
70
  handle(request: NodeHttpRequest, response: NodeHttpResponse, ...rest: MaybeOptionalOptions<FriendlyStandardHandlerHandleOptions<T>>): Promise<NodeHttpHandlerHandleResult>;
72
71
  }
73
72
 
74
- interface BodyCompressionHandlerPluginOptions extends compression.CompressionOptions {
75
- /**
76
- * Override the default content-type filter used to determine which responses should be compressed.
77
- *
78
- * @warning Event stream responses are never compressed, regardless of this filter's return value.
79
- * @default only responses with compressible content types are compressed.
80
- */
81
- filter?: (request: NodeHttpRequest, response: NodeHttpResponse) => boolean;
82
- }
83
- declare class BodyCompressionHandlerPlugin<T extends Context> implements NodeHttpHandlerPlugin<T> {
84
- name: string;
85
- private readonly compressionHandler;
86
- constructor(options?: BodyCompressionHandlerPluginOptions);
87
- initNodeHttpHandlerOptions(options: NodeHttpHandlerOptions<T>): NodeHttpHandlerOptions<T>;
88
- }
89
-
90
- interface BodyLimitHandlerPluginOptions {
91
- /**
92
- * The maximum size of the body in bytes.
93
- */
94
- maxBodySize: number;
95
- }
96
- declare class BodyLimitHandlerPlugin<T extends Context> implements NodeHttpHandlerPlugin<T> {
97
- name: string;
98
- private readonly maxBodySize;
99
- constructor(options: BodyLimitHandlerPluginOptions);
100
- initNodeHttpHandlerOptions(options: NodeHttpHandlerOptions<T>): NodeHttpHandlerOptions<T>;
101
- }
102
-
103
73
  interface RPCHandlerOptions<T extends Context> extends NodeHttpHandlerOptions<T>, Omit<StandardHandlerOptions<T>, 'plugins'>, RPCHandlerCodecOptions<T> {
104
74
  /**
105
75
  * Configuration for {@link CSRFGuardHandlerPlugin}, which is enabled by default for `RPCHandler` over HTTP.
@@ -117,5 +87,5 @@ declare class RPCHandler<T extends Context> extends NodeHttpHandler<T> {
117
87
  constructor(router: Router<T>, options?: NoInfer<RPCHandlerOptions<T>>);
118
88
  }
119
89
 
120
- export { BodyCompressionHandlerPlugin, BodyLimitHandlerPlugin, CompositeNodeHttpHandlerPlugin, NodeHttpHandler, RPCHandler };
121
- export type { BodyCompressionHandlerPluginOptions, BodyLimitHandlerPluginOptions, NodeHttpHandlerHandleResult, NodeHttpHandlerNodeHttpInterceptor, NodeHttpHandlerNodeHttpInterceptorOptions, NodeHttpHandlerOptions, NodeHttpHandlerPlugin, RPCHandlerOptions };
90
+ export { CompositeNodeHttpHandlerPlugin, NodeHttpHandler, RPCHandler };
91
+ export type { NodeHttpHandlerHandleResult, NodeHttpHandlerNodeHttpInterceptor, NodeHttpHandlerNodeHttpInterceptorOptions, NodeHttpHandlerOptions, NodeHttpHandlerPlugin, RPCHandlerOptions };
@@ -1,9 +1,8 @@
1
+ import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
1
2
  import { SendStandardResponseOptions, NodeHttpRequest, NodeHttpResponse } from '@standardserver/node';
2
3
  import { C as Context } from '../../shared/server.BL22TloH.js';
3
- import { Interceptor, MaybeOptionalOptions } from '@orpc/shared';
4
4
  import { e as StandardHandlerPlugin, b as StandardHandlerHandleOptions, S as StandardHandler, a as StandardHandlerOptions } from '../../shared/server.DBANIheG.js';
5
5
  import { FriendlyStandardHandlerHandleOptions } from '../standard/index.js';
6
- import compression from '@orpc/interop/compression';
7
6
  import { R as Router } from '../../shared/server.Pa0F03f_.js';
8
7
  import { R as RPCHandlerCodecOptions } from '../../shared/server.D0WUu0EH.js';
9
8
  import '@orpc/client';
@@ -71,35 +70,6 @@ declare class NodeHttpHandler<T extends Context> {
71
70
  handle(request: NodeHttpRequest, response: NodeHttpResponse, ...rest: MaybeOptionalOptions<FriendlyStandardHandlerHandleOptions<T>>): Promise<NodeHttpHandlerHandleResult>;
72
71
  }
73
72
 
74
- interface BodyCompressionHandlerPluginOptions extends compression.CompressionOptions {
75
- /**
76
- * Override the default content-type filter used to determine which responses should be compressed.
77
- *
78
- * @warning Event stream responses are never compressed, regardless of this filter's return value.
79
- * @default only responses with compressible content types are compressed.
80
- */
81
- filter?: (request: NodeHttpRequest, response: NodeHttpResponse) => boolean;
82
- }
83
- declare class BodyCompressionHandlerPlugin<T extends Context> implements NodeHttpHandlerPlugin<T> {
84
- name: string;
85
- private readonly compressionHandler;
86
- constructor(options?: BodyCompressionHandlerPluginOptions);
87
- initNodeHttpHandlerOptions(options: NodeHttpHandlerOptions<T>): NodeHttpHandlerOptions<T>;
88
- }
89
-
90
- interface BodyLimitHandlerPluginOptions {
91
- /**
92
- * The maximum size of the body in bytes.
93
- */
94
- maxBodySize: number;
95
- }
96
- declare class BodyLimitHandlerPlugin<T extends Context> implements NodeHttpHandlerPlugin<T> {
97
- name: string;
98
- private readonly maxBodySize;
99
- constructor(options: BodyLimitHandlerPluginOptions);
100
- initNodeHttpHandlerOptions(options: NodeHttpHandlerOptions<T>): NodeHttpHandlerOptions<T>;
101
- }
102
-
103
73
  interface RPCHandlerOptions<T extends Context> extends NodeHttpHandlerOptions<T>, Omit<StandardHandlerOptions<T>, 'plugins'>, RPCHandlerCodecOptions<T> {
104
74
  /**
105
75
  * Configuration for {@link CSRFGuardHandlerPlugin}, which is enabled by default for `RPCHandler` over HTTP.
@@ -117,5 +87,5 @@ declare class RPCHandler<T extends Context> extends NodeHttpHandler<T> {
117
87
  constructor(router: Router<T>, options?: NoInfer<RPCHandlerOptions<T>>);
118
88
  }
119
89
 
120
- export { BodyCompressionHandlerPlugin, BodyLimitHandlerPlugin, CompositeNodeHttpHandlerPlugin, NodeHttpHandler, RPCHandler };
121
- export type { BodyCompressionHandlerPluginOptions, BodyLimitHandlerPluginOptions, NodeHttpHandlerHandleResult, NodeHttpHandlerNodeHttpInterceptor, NodeHttpHandlerNodeHttpInterceptorOptions, NodeHttpHandlerOptions, NodeHttpHandlerPlugin, RPCHandlerOptions };
90
+ export { CompositeNodeHttpHandlerPlugin, NodeHttpHandler, RPCHandler };
91
+ export type { NodeHttpHandlerHandleResult, NodeHttpHandlerNodeHttpInterceptor, NodeHttpHandlerNodeHttpInterceptorOptions, NodeHttpHandlerOptions, NodeHttpHandlerPlugin, RPCHandlerOptions };
@@ -1,120 +1,14 @@
1
- import compression from '@orpc/interop/compression';
2
- import { toArray, sortPlugins, intercept, resolveMaybeOptionalOptions } from '@orpc/shared';
3
- import { ORPCError } from '@orpc/client';
1
+ import { sortPlugins, intercept, resolveMaybeOptionalOptions, toArray } from '@orpc/shared';
4
2
  import { toStandardLazyRequest, sendStandardResponse } from '@standardserver/node';
5
3
  import { r as resolveFriendlyStandardHandlerHandleOptions } from '../../shared/server.W91HSRkE.mjs';
6
4
  import { C as CSRFGuardHandlerPlugin } from '../../shared/server.D_QauotT.mjs';
7
5
  import { R as RPCHandlerCodec, S as StandardHandler } from '../../shared/server.DZEvIn7o.mjs';
6
+ import '@orpc/client';
8
7
  import '@standardserver/core';
9
8
  import '../../shared/server.BDeup7Ky.mjs';
10
9
  import '@orpc/contract';
11
10
  import '../../shared/server.C_osSBcd.mjs';
12
11
 
13
- class BodyCompressionHandlerPlugin {
14
- name = "~body-compression";
15
- compressionHandler;
16
- constructor(options = {}) {
17
- this.compressionHandler = compression({
18
- ...options,
19
- filter: (request, response) => {
20
- const hasContentDisposition = response.hasHeader("content-disposition");
21
- const contentType = response.getHeader("content-type")?.toString();
22
- if (!hasContentDisposition && contentType?.startsWith("text/event-stream")) {
23
- return false;
24
- }
25
- return options.filter ? options.filter(request, response) : compression.filter(request, response);
26
- }
27
- });
28
- }
29
- initNodeHttpHandlerOptions(options) {
30
- return {
31
- ...options,
32
- nodeHttpInterceptors: [
33
- async (interceptorOptions) => {
34
- let resolve;
35
- let reject;
36
- const promise = new Promise((res, rej) => {
37
- resolve = res;
38
- reject = rej;
39
- });
40
- const originalWrite = interceptorOptions.response.write;
41
- const originalEnd = interceptorOptions.response.end;
42
- const originalOn = interceptorOptions.response.on;
43
- this.compressionHandler(
44
- interceptorOptions.request,
45
- interceptorOptions.response,
46
- async (error) => {
47
- if (error) {
48
- reject(error);
49
- } else {
50
- try {
51
- resolve(await interceptorOptions.next(interceptorOptions));
52
- } catch (nextError) {
53
- reject(nextError);
54
- }
55
- }
56
- }
57
- );
58
- try {
59
- return await promise;
60
- } finally {
61
- interceptorOptions.response.write = originalWrite;
62
- interceptorOptions.response.end = originalEnd;
63
- interceptorOptions.response.on = originalOn;
64
- }
65
- },
66
- ...toArray(options.nodeHttpInterceptors)
67
- ]
68
- };
69
- }
70
- }
71
-
72
- class BodyLimitHandlerPlugin {
73
- name = "~body-limit";
74
- maxBodySize;
75
- constructor(options) {
76
- this.maxBodySize = options.maxBodySize;
77
- }
78
- initNodeHttpHandlerOptions(options) {
79
- return {
80
- ...options,
81
- nodeHttpInterceptors: [
82
- async (interceptorOptions) => {
83
- let isHeaderChecked = false;
84
- const checkHeader = () => {
85
- if (isHeaderChecked) {
86
- return;
87
- }
88
- isHeaderChecked = true;
89
- const contentLength = interceptorOptions.request.headers["content-length"];
90
- if (contentLength && Number(contentLength) > this.maxBodySize) {
91
- throw new ORPCError("PAYLOAD_TOO_LARGE");
92
- }
93
- };
94
- const originalEmit = interceptorOptions.request.emit;
95
- let currentBodySize = 0;
96
- interceptorOptions.request.emit = (event, ...args) => {
97
- if (event === "data") {
98
- checkHeader();
99
- currentBodySize += args[0]?.length ?? 0;
100
- if (currentBodySize > this.maxBodySize) {
101
- throw new ORPCError("PAYLOAD_TOO_LARGE");
102
- }
103
- }
104
- return originalEmit.call(interceptorOptions.request, event, ...args);
105
- };
106
- try {
107
- return await interceptorOptions.next(interceptorOptions);
108
- } finally {
109
- interceptorOptions.request.emit = originalEmit;
110
- }
111
- },
112
- ...toArray(options.nodeHttpInterceptors)
113
- ]
114
- };
115
- }
116
- }
117
-
118
12
  class CompositeNodeHttpHandlerPlugin {
119
13
  name = "~composite/node-http-handler";
120
14
  plugins;
@@ -176,4 +70,4 @@ class RPCHandler extends NodeHttpHandler {
176
70
  }
177
71
  }
178
72
 
179
- export { BodyCompressionHandlerPlugin, BodyLimitHandlerPlugin, CompositeNodeHttpHandlerPlugin, NodeHttpHandler, RPCHandler };
73
+ export { CompositeNodeHttpHandlerPlugin, NodeHttpHandler, RPCHandler };
@@ -30,6 +30,29 @@ interface BatchHandlerPluginOptions<T extends Context> {
30
30
  * @default {}
31
31
  */
32
32
  headers?: Value<Promisable<StandardHeaders>, [batchOptions: StandardHandlerRoutingInterceptorOptions<T>]>;
33
+ /**
34
+ * Keep-alive settings for streaming batch responses.
35
+ *
36
+ * When enabled, a zero-length length-prefixed frame is sent periodically while the
37
+ * stream is idle (no message sent for `interval` ms). Clients ignore these frames.
38
+ * Only applies to streaming mode.
39
+ *
40
+ * @default { enabled: true, interval: 15000 }
41
+ */
42
+ keepAlive?: undefined | {
43
+ /**
44
+ * If true, a keep-alive frame is sent periodically while the stream is idle.
45
+ *
46
+ * @default true
47
+ */
48
+ enabled: boolean;
49
+ /**
50
+ * Interval (in milliseconds) between keep-alive frames after the last message.
51
+ *
52
+ * @default 15000
53
+ */
54
+ interval?: number;
55
+ };
33
56
  }
34
57
  declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
35
58
  name: string;
@@ -42,6 +65,8 @@ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPl
42
65
  private readonly mapSubrequest;
43
66
  private readonly successStatus;
44
67
  private readonly headers;
68
+ private readonly keepAliveEnabled;
69
+ private readonly keepAliveInterval;
45
70
  constructor(options?: BatchHandlerPluginOptions<T>);
46
71
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
47
72
  }
@@ -123,6 +148,15 @@ declare class CSRFGuardHandlerPlugin<T extends Context> implements StandardHandl
123
148
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
124
149
  }
125
150
 
151
+ declare class RequestCompressionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
152
+ name: string;
153
+ /**
154
+ * Should decompress the original batch request body instead of sub-requests.
155
+ */
156
+ after: string[];
157
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
158
+ }
159
+
126
160
  interface RequestHeadersHandlerPluginContext {
127
161
  /**
128
162
  * Request headers as a Headers instance. This is injected by the Request Headers Plugin.
@@ -140,6 +174,72 @@ declare class RequestHeadersHandlerPlugin<T extends RequestHeadersHandlerPluginC
140
174
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
141
175
  }
142
176
 
177
+ interface RequestLimitHandlerPluginOptions {
178
+ /**
179
+ * The maximum allowed request body size in bytes.
180
+ */
181
+ maxBodySize: number;
182
+ }
183
+ /**
184
+ * Rejects requests whose body exceeds `maxBodySize`.
185
+ *
186
+ * When used with the request compression plugin, the limit applies to the
187
+ * decompressed payload rather than the compressed wire size.
188
+ *
189
+ * @see {@link https://orpc.dev/docs/plugins/request-limit Request Limit Plugin Docs}
190
+ */
191
+ declare class RequestLimitHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
192
+ name: string;
193
+ /**
194
+ * Should limit the original batch request body instead of sub-requests.
195
+ */
196
+ after: string[];
197
+ /**
198
+ * Should limit the final body size instead of the compressed one.
199
+ */
200
+ before: string[];
201
+ private readonly maxBodySize;
202
+ constructor(options: RequestLimitHandlerPluginOptions);
203
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
204
+ }
205
+
206
+ interface ResponseCompressionHandlerPluginOptions<_T extends Context> {
207
+ /**
208
+ * The compression schemes to use for response compression.
209
+ * Schemes are prioritized by their order in this array and
210
+ * only applied if the client supports them (via Accept-Encoding).
211
+ *
212
+ * @default ['gzip', 'deflate']
213
+ */
214
+ encodings?: readonly ('gzip' | 'deflate' | 'deflate-raw')[];
215
+ /**
216
+ * The minimum response size in bytes required to trigger compression.
217
+ * Responses smaller than this threshold will not be compressed to avoid overhead.
218
+ * If the response size cannot be determined, compression will still be applied.
219
+ *
220
+ * @default 1024 (1KB)
221
+ */
222
+ threshold?: number;
223
+ }
224
+ /**
225
+ * Compresses response bodies based on the client's Accept-Encoding header.
226
+ * Works at the standard handler level, so it supports all adapters.
227
+ *
228
+ * @see {@link https://orpc.dev/docs/plugins/response-compression Response Compression Plugin Docs}
229
+ */
230
+ declare class ResponseCompressionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
231
+ name: string;
232
+ /**
233
+ * Compression should be done after batching, to compress the final response.
234
+ * Compression should also be done after response headers are set, to access final headers like Content-Type and Cache-Control.
235
+ */
236
+ after: string[];
237
+ private readonly encodings;
238
+ private readonly threshold;
239
+ constructor(options?: ResponseCompressionHandlerPluginOptions<T>);
240
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
241
+ }
242
+
143
243
  interface ResponseHeadersHandlerPluginContext {
144
244
  /**
145
245
  * Response headers as a Headers instance. This is injected by the Response Headers Plugin.
@@ -193,5 +293,5 @@ declare class RethrowHandlerPlugin<T extends Context> implements StandardHandler
193
293
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
194
294
  }
195
295
 
196
- export { BatchHandlerPlugin, CORSHandlerPlugin, CSRFGuardHandlerPlugin, RequestHeadersHandlerPlugin, ResponseHeadersHandlerPlugin, RethrowHandlerPlugin };
197
- export type { BatchHandlerPluginOptions, CORSHandlerPluginOptions, RequestHeadersHandlerPluginContext, ResponseHeadersHandlerPluginContext, RethrowHandlerPluginOptions };
296
+ export { BatchHandlerPlugin, CORSHandlerPlugin, CSRFGuardHandlerPlugin, RequestCompressionHandlerPlugin, RequestHeadersHandlerPlugin, RequestLimitHandlerPlugin, ResponseCompressionHandlerPlugin, ResponseHeadersHandlerPlugin, RethrowHandlerPlugin };
297
+ export type { BatchHandlerPluginOptions, CORSHandlerPluginOptions, RequestHeadersHandlerPluginContext, RequestLimitHandlerPluginOptions, ResponseCompressionHandlerPluginOptions, ResponseHeadersHandlerPluginContext, RethrowHandlerPluginOptions };
@@ -30,6 +30,29 @@ interface BatchHandlerPluginOptions<T extends Context> {
30
30
  * @default {}
31
31
  */
32
32
  headers?: Value<Promisable<StandardHeaders>, [batchOptions: StandardHandlerRoutingInterceptorOptions<T>]>;
33
+ /**
34
+ * Keep-alive settings for streaming batch responses.
35
+ *
36
+ * When enabled, a zero-length length-prefixed frame is sent periodically while the
37
+ * stream is idle (no message sent for `interval` ms). Clients ignore these frames.
38
+ * Only applies to streaming mode.
39
+ *
40
+ * @default { enabled: true, interval: 15000 }
41
+ */
42
+ keepAlive?: undefined | {
43
+ /**
44
+ * If true, a keep-alive frame is sent periodically while the stream is idle.
45
+ *
46
+ * @default true
47
+ */
48
+ enabled: boolean;
49
+ /**
50
+ * Interval (in milliseconds) between keep-alive frames after the last message.
51
+ *
52
+ * @default 15000
53
+ */
54
+ interval?: number;
55
+ };
33
56
  }
34
57
  declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
35
58
  name: string;
@@ -42,6 +65,8 @@ declare class BatchHandlerPlugin<T extends Context> implements StandardHandlerPl
42
65
  private readonly mapSubrequest;
43
66
  private readonly successStatus;
44
67
  private readonly headers;
68
+ private readonly keepAliveEnabled;
69
+ private readonly keepAliveInterval;
45
70
  constructor(options?: BatchHandlerPluginOptions<T>);
46
71
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
47
72
  }
@@ -123,6 +148,15 @@ declare class CSRFGuardHandlerPlugin<T extends Context> implements StandardHandl
123
148
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
124
149
  }
125
150
 
151
+ declare class RequestCompressionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
152
+ name: string;
153
+ /**
154
+ * Should decompress the original batch request body instead of sub-requests.
155
+ */
156
+ after: string[];
157
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
158
+ }
159
+
126
160
  interface RequestHeadersHandlerPluginContext {
127
161
  /**
128
162
  * Request headers as a Headers instance. This is injected by the Request Headers Plugin.
@@ -140,6 +174,72 @@ declare class RequestHeadersHandlerPlugin<T extends RequestHeadersHandlerPluginC
140
174
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
141
175
  }
142
176
 
177
+ interface RequestLimitHandlerPluginOptions {
178
+ /**
179
+ * The maximum allowed request body size in bytes.
180
+ */
181
+ maxBodySize: number;
182
+ }
183
+ /**
184
+ * Rejects requests whose body exceeds `maxBodySize`.
185
+ *
186
+ * When used with the request compression plugin, the limit applies to the
187
+ * decompressed payload rather than the compressed wire size.
188
+ *
189
+ * @see {@link https://orpc.dev/docs/plugins/request-limit Request Limit Plugin Docs}
190
+ */
191
+ declare class RequestLimitHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
192
+ name: string;
193
+ /**
194
+ * Should limit the original batch request body instead of sub-requests.
195
+ */
196
+ after: string[];
197
+ /**
198
+ * Should limit the final body size instead of the compressed one.
199
+ */
200
+ before: string[];
201
+ private readonly maxBodySize;
202
+ constructor(options: RequestLimitHandlerPluginOptions);
203
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
204
+ }
205
+
206
+ interface ResponseCompressionHandlerPluginOptions<_T extends Context> {
207
+ /**
208
+ * The compression schemes to use for response compression.
209
+ * Schemes are prioritized by their order in this array and
210
+ * only applied if the client supports them (via Accept-Encoding).
211
+ *
212
+ * @default ['gzip', 'deflate']
213
+ */
214
+ encodings?: readonly ('gzip' | 'deflate' | 'deflate-raw')[];
215
+ /**
216
+ * The minimum response size in bytes required to trigger compression.
217
+ * Responses smaller than this threshold will not be compressed to avoid overhead.
218
+ * If the response size cannot be determined, compression will still be applied.
219
+ *
220
+ * @default 1024 (1KB)
221
+ */
222
+ threshold?: number;
223
+ }
224
+ /**
225
+ * Compresses response bodies based on the client's Accept-Encoding header.
226
+ * Works at the standard handler level, so it supports all adapters.
227
+ *
228
+ * @see {@link https://orpc.dev/docs/plugins/response-compression Response Compression Plugin Docs}
229
+ */
230
+ declare class ResponseCompressionHandlerPlugin<T extends Context> implements StandardHandlerPlugin<T> {
231
+ name: string;
232
+ /**
233
+ * Compression should be done after batching, to compress the final response.
234
+ * Compression should also be done after response headers are set, to access final headers like Content-Type and Cache-Control.
235
+ */
236
+ after: string[];
237
+ private readonly encodings;
238
+ private readonly threshold;
239
+ constructor(options?: ResponseCompressionHandlerPluginOptions<T>);
240
+ init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
241
+ }
242
+
143
243
  interface ResponseHeadersHandlerPluginContext {
144
244
  /**
145
245
  * Response headers as a Headers instance. This is injected by the Response Headers Plugin.
@@ -193,5 +293,5 @@ declare class RethrowHandlerPlugin<T extends Context> implements StandardHandler
193
293
  init(options: StandardHandlerOptions<T>): StandardHandlerOptions<T>;
194
294
  }
195
295
 
196
- export { BatchHandlerPlugin, CORSHandlerPlugin, CSRFGuardHandlerPlugin, RequestHeadersHandlerPlugin, ResponseHeadersHandlerPlugin, RethrowHandlerPlugin };
197
- export type { BatchHandlerPluginOptions, CORSHandlerPluginOptions, RequestHeadersHandlerPluginContext, ResponseHeadersHandlerPluginContext, RethrowHandlerPluginOptions };
296
+ export { BatchHandlerPlugin, CORSHandlerPlugin, CSRFGuardHandlerPlugin, RequestCompressionHandlerPlugin, RequestHeadersHandlerPlugin, RequestLimitHandlerPlugin, ResponseCompressionHandlerPlugin, ResponseHeadersHandlerPlugin, RethrowHandlerPlugin };
297
+ export type { BatchHandlerPluginOptions, CORSHandlerPluginOptions, RequestHeadersHandlerPluginContext, RequestLimitHandlerPluginOptions, ResponseCompressionHandlerPluginOptions, ResponseHeadersHandlerPluginContext, RethrowHandlerPluginOptions };
@@ -1,9 +1,9 @@
1
- import { toArray, value } from '@orpc/shared';
2
- import { flattenStandardHeader, parseStandardUrl, mergeStandardHeaders } from '@standardserver/core';
1
+ import { toArray, value, isCompressibleContentType, isAsyncIteratorObject, stringifyJSON } from '@orpc/shared';
2
+ import { flattenStandardHeader, parseStandardUrl, generateContentDisposition, mergeStandardHeaders } from '@standardserver/core';
3
3
  import { isClientPeerSendMessage, ServerPeer, encodePeerMessage } from '@standardserver/peer';
4
4
  export { C as CSRFGuardHandlerPlugin } from '../shared/server.D_QauotT.mjs';
5
- import { toFetchHeaders, toStandardHeaders } from '@standardserver/fetch';
6
- import '@orpc/client';
5
+ import { toFetchHeaders, toStandardBody, toStandardHeaders } from '@standardserver/fetch';
6
+ import { ORPCError } from '@orpc/client';
7
7
 
8
8
  class BatchHandlerPlugin {
9
9
  name = "~batch";
@@ -16,6 +16,8 @@ class BatchHandlerPlugin {
16
16
  mapSubrequest;
17
17
  successStatus;
18
18
  headers;
19
+ keepAliveEnabled;
20
+ keepAliveInterval;
19
21
  constructor(options = {}) {
20
22
  this.maxSize = options.maxSize ?? 10;
21
23
  this.mapSubrequest = options.mapSubrequest ?? ((subRequest, { request: batchRequest }) => ({
@@ -29,6 +31,8 @@ class BatchHandlerPlugin {
29
31
  }));
30
32
  this.successStatus = options.successStatus ?? 207;
31
33
  this.headers = options.headers ?? {};
34
+ this.keepAliveEnabled = options.keepAlive?.enabled ?? true;
35
+ this.keepAliveInterval = options.keepAlive?.interval ?? 15e3;
32
36
  }
33
37
  init(options) {
34
38
  const routingInterceptor = async (interceptorOptions) => {
@@ -127,9 +131,35 @@ class BatchHandlerPlugin {
127
131
  };
128
132
  }
129
133
  let streamController;
134
+ let keepAliveTimer;
135
+ const clearKeepAlive = () => {
136
+ if (keepAliveTimer !== void 0) {
137
+ clearInterval(keepAliveTimer);
138
+ keepAliveTimer = void 0;
139
+ }
140
+ };
141
+ const scheduleKeepAlive = () => {
142
+ if (!this.keepAliveEnabled) {
143
+ return;
144
+ }
145
+ clearKeepAlive();
146
+ keepAliveTimer = setInterval(() => {
147
+ try {
148
+ const lengthBuffer = new ArrayBuffer(4);
149
+ new DataView(lengthBuffer).setUint32(0, 0, false);
150
+ streamController.enqueue(new Uint8Array(lengthBuffer));
151
+ } catch {
152
+ clearKeepAlive();
153
+ }
154
+ }, this.keepAliveInterval);
155
+ };
130
156
  const stream = new ReadableStream({
131
157
  start(controller) {
132
158
  streamController = controller;
159
+ scheduleKeepAlive();
160
+ },
161
+ cancel() {
162
+ clearKeepAlive();
133
163
  }
134
164
  });
135
165
  const peer = new ServerPeer(async (message) => {
@@ -139,11 +169,14 @@ class BatchHandlerPlugin {
139
169
  new DataView(lengthBuffer).setUint32(0, bytes.byteLength, false);
140
170
  streamController.enqueue(new Uint8Array(lengthBuffer));
141
171
  streamController.enqueue(bytes);
172
+ scheduleKeepAlive();
142
173
  });
143
174
  Promise.all(messages.map((msg) => peer.message(msg, handleIndividualRequest))).then(async () => {
175
+ clearKeepAlive();
144
176
  streamController.close();
145
177
  await peer.close();
146
178
  }).catch(async (error) => {
179
+ clearKeepAlive();
147
180
  streamController.error(error);
148
181
  await peer.close(error);
149
182
  });
@@ -193,7 +226,10 @@ class CORSHandlerPlugin {
193
226
  if (allowedOrigins.includes(origin)) {
194
227
  resHeaders["access-control-allow-origin"] = origin;
195
228
  }
196
- resHeaders.vary = interceptorOptions.request.headers.vary ?? "origin";
229
+ const existingVary = flattenStandardHeader(resHeaders.vary);
230
+ if (!existingVary?.split(",").some((v) => v.trim().toLowerCase() === "origin")) {
231
+ resHeaders.vary = existingVary ? `${existingVary}, Origin` : "Origin";
232
+ }
197
233
  }
198
234
  const allowedTimingOrigins = toArray(await value(this.options.timingOrigin, origin, interceptorOptions));
199
235
  if (allowedTimingOrigins.includes("*")) {
@@ -244,6 +280,69 @@ class CORSHandlerPlugin {
244
280
  }
245
281
  }
246
282
 
283
+ class RequestCompressionHandlerPlugin {
284
+ name = "~request-compression";
285
+ /**
286
+ * Should decompress the original batch request body instead of sub-requests.
287
+ */
288
+ after = ["~batch"];
289
+ init(options) {
290
+ const routingInterceptor = async ({ next, ...interceptorOptions }) => {
291
+ const encodings = parseContentEncodings(
292
+ flattenStandardHeader(interceptorOptions.request.headers["content-encoding"])
293
+ );
294
+ if (encodings.length === 0 || !encodings.every(isSupportedEncoding)) {
295
+ return next();
296
+ }
297
+ const decompressedHeaders = {
298
+ ...interceptorOptions.request.headers,
299
+ "content-length": void 0,
300
+ "content-encoding": void 0
301
+ };
302
+ return next({
303
+ ...interceptorOptions,
304
+ request: {
305
+ ...interceptorOptions.request,
306
+ headers: decompressedHeaders,
307
+ async resolveBody(hint) {
308
+ const stream = await interceptorOptions.request.resolveBody("octet-stream");
309
+ if (!(stream instanceof ReadableStream)) {
310
+ return stream;
311
+ }
312
+ let decompressedStream = stream;
313
+ for (let i = encodings.length - 1; i >= 0; i--) {
314
+ decompressedStream = decompressedStream.pipeThrough(
315
+ new DecompressionStream(encodings[i])
316
+ );
317
+ }
318
+ const response = new Response(decompressedStream, {
319
+ headers: toFetchHeaders(decompressedHeaders)
320
+ });
321
+ return toStandardBody(response, { hint });
322
+ }
323
+ }
324
+ });
325
+ };
326
+ return {
327
+ ...options,
328
+ routingInterceptors: [
329
+ routingInterceptor,
330
+ ...toArray(options.routingInterceptors)
331
+ ]
332
+ };
333
+ }
334
+ }
335
+ const SUPPORTED_ENCODINGS = ["gzip", "deflate", "deflate-raw"];
336
+ function isSupportedEncoding(encoding) {
337
+ return SUPPORTED_ENCODINGS.includes(encoding);
338
+ }
339
+ function parseContentEncodings(header) {
340
+ if (header === void 0) {
341
+ return [];
342
+ }
343
+ return header.split(",").map((part) => part.trim().toLowerCase());
344
+ }
345
+
247
346
  class RequestHeadersHandlerPlugin {
248
347
  name = "~request-headers";
249
348
  init(options) {
@@ -266,6 +365,243 @@ class RequestHeadersHandlerPlugin {
266
365
  }
267
366
  }
268
367
 
368
+ class RequestLimitHandlerPlugin {
369
+ name = "~request-limit";
370
+ /**
371
+ * Should limit the original batch request body instead of sub-requests.
372
+ */
373
+ after = ["~batch"];
374
+ /**
375
+ * Should limit the final body size instead of the compressed one.
376
+ */
377
+ before = ["~request-compression"];
378
+ maxBodySize;
379
+ constructor(options) {
380
+ this.maxBodySize = options.maxBodySize;
381
+ }
382
+ init(options) {
383
+ const maxBodySize = this.maxBodySize;
384
+ const routingInterceptor = async ({ next, ...interceptorOptions }) => {
385
+ return next({
386
+ ...interceptorOptions,
387
+ request: {
388
+ ...interceptorOptions.request,
389
+ async resolveBody(hint) {
390
+ const contentLength = Number(
391
+ flattenStandardHeader(interceptorOptions.request.headers["content-length"])
392
+ );
393
+ if (Number.isFinite(contentLength) && contentLength > maxBodySize) {
394
+ throw new ORPCError("PAYLOAD_TOO_LARGE");
395
+ }
396
+ const stream = await interceptorOptions.request.resolveBody("octet-stream");
397
+ if (!(stream instanceof ReadableStream)) {
398
+ return stream;
399
+ }
400
+ let currentBodySize = 0;
401
+ const limitedStream = stream.pipeThrough(
402
+ new TransformStream({
403
+ transform(chunk, controller) {
404
+ currentBodySize += chunk.byteLength;
405
+ if (currentBodySize > maxBodySize) {
406
+ controller.error(new ORPCError("PAYLOAD_TOO_LARGE"));
407
+ return;
408
+ }
409
+ controller.enqueue(chunk);
410
+ }
411
+ })
412
+ );
413
+ const response = new Response(limitedStream, {
414
+ headers: toFetchHeaders(interceptorOptions.request.headers)
415
+ });
416
+ return toStandardBody(response, { hint });
417
+ }
418
+ }
419
+ });
420
+ };
421
+ return {
422
+ ...options,
423
+ routingInterceptors: [
424
+ routingInterceptor,
425
+ ...toArray(options.routingInterceptors)
426
+ ]
427
+ };
428
+ }
429
+ }
430
+
431
+ const AVG_BYTES_PER_CHAR = 1.2;
432
+ class ResponseCompressionHandlerPlugin {
433
+ name = "~response-compression";
434
+ /**
435
+ * Compression should be done after batching, to compress the final response.
436
+ * Compression should also be done after response headers are set, to access final headers like Content-Type and Cache-Control.
437
+ */
438
+ after = ["~batch", "~response-headers"];
439
+ encodings;
440
+ threshold;
441
+ constructor(options = {}) {
442
+ this.encodings = options.encodings ?? ["gzip", "deflate"];
443
+ this.threshold = options.threshold ?? 1024;
444
+ }
445
+ init(options) {
446
+ const routingInterceptor = async ({ next, ...interceptorOptions }) => {
447
+ const result = await next();
448
+ if (!result.matched) {
449
+ return result;
450
+ }
451
+ const response = result.response;
452
+ const contentEncoding = flattenStandardHeader(response.headers["content-encoding"])?.trim()?.toLowerCase();
453
+ if (contentEncoding !== void 0) {
454
+ return result;
455
+ }
456
+ if (isNoTransformCacheControl(flattenStandardHeader(response.headers["cache-control"]))) {
457
+ return result;
458
+ }
459
+ const acceptEncodings = parseAcceptEncodings(
460
+ flattenStandardHeader(interceptorOptions.request.headers["accept-encoding"])
461
+ );
462
+ const encoding = this.encodings.find((enc) => acceptEncodings.includes(enc));
463
+ if (encoding === void 0) {
464
+ return result;
465
+ }
466
+ const body = response.body;
467
+ const headers = response.headers;
468
+ if (body instanceof ReadableStream) {
469
+ const contentLength = Number(flattenStandardHeader(headers["content-length"]));
470
+ if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) && isCompressibleContentType(flattenStandardHeader(headers["content-type"]))) {
471
+ return {
472
+ ...result,
473
+ response: {
474
+ ...response,
475
+ body: body.pipeThrough(new CompressionStream(encoding)),
476
+ headers: {
477
+ ...headers,
478
+ "standard-server": "octet-stream",
479
+ "content-length": [],
480
+ "content-encoding": encoding
481
+ }
482
+ }
483
+ };
484
+ }
485
+ } else if (body instanceof Blob) {
486
+ if ((!Number.isFinite(body.size) || body.size >= this.threshold) && isCompressibleContentType(body.type)) {
487
+ const contentDisposition = headers["content-disposition"] ?? generateContentDisposition(
488
+ body instanceof File ? body.name : "blob"
489
+ );
490
+ return {
491
+ ...result,
492
+ response: {
493
+ ...response,
494
+ body: body.stream().pipeThrough(new CompressionStream(encoding)),
495
+ headers: {
496
+ ...headers,
497
+ "standard-server": "file",
498
+ "content-type": body.type,
499
+ "content-length": [],
500
+ "content-disposition": contentDisposition,
501
+ "content-encoding": encoding
502
+ }
503
+ }
504
+ };
505
+ }
506
+ } else if (body instanceof FormData) {
507
+ const PART_OVERHEAD = 64;
508
+ let contentLength = 0;
509
+ for (const [key, value] of body) {
510
+ contentLength += PART_OVERHEAD + key.length;
511
+ if (value instanceof Blob) {
512
+ if (!Number.isFinite(value.size)) {
513
+ if (!isCompressibleContentType(value.type)) {
514
+ contentLength = -Infinity;
515
+ break;
516
+ }
517
+ contentLength = Infinity;
518
+ } else {
519
+ contentLength += isCompressibleContentType(value.type) ? value.size : -value.size;
520
+ }
521
+ } else {
522
+ contentLength += value.length * AVG_BYTES_PER_CHAR;
523
+ }
524
+ }
525
+ if (contentLength >= this.threshold) {
526
+ const res = new Response(body);
527
+ const compressedStream = res.body.pipeThrough(new CompressionStream(encoding));
528
+ return {
529
+ ...result,
530
+ response: {
531
+ ...response,
532
+ body: compressedStream,
533
+ headers: {
534
+ ...headers,
535
+ "standard-server": [],
536
+ "content-type": res.headers.get("content-type"),
537
+ "content-length": [],
538
+ "content-encoding": encoding
539
+ }
540
+ }
541
+ };
542
+ }
543
+ } else if (body instanceof URLSearchParams) {
544
+ const string = body.toString();
545
+ if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
546
+ return {
547
+ ...result,
548
+ response: {
549
+ ...response,
550
+ body: new Blob([string]).stream().pipeThrough(new CompressionStream(encoding)),
551
+ headers: {
552
+ ...headers,
553
+ "standard-server": [],
554
+ "content-type": "application/x-www-form-urlencoded",
555
+ "content-length": [],
556
+ "content-encoding": encoding
557
+ }
558
+ }
559
+ };
560
+ }
561
+ } else if (body !== void 0 && !isAsyncIteratorObject(body)) {
562
+ const string = stringifyJSON(body);
563
+ if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
564
+ return {
565
+ ...result,
566
+ response: {
567
+ ...response,
568
+ body: new Blob([string]).stream().pipeThrough(new CompressionStream(encoding)),
569
+ headers: {
570
+ ...headers,
571
+ "standard-server": [],
572
+ "content-type": "application/json",
573
+ "content-length": [],
574
+ "content-encoding": encoding
575
+ }
576
+ }
577
+ };
578
+ }
579
+ }
580
+ return result;
581
+ };
582
+ return {
583
+ ...options,
584
+ routingInterceptors: [
585
+ routingInterceptor,
586
+ ...toArray(options.routingInterceptors)
587
+ ]
588
+ };
589
+ }
590
+ }
591
+ function parseAcceptEncodings(header) {
592
+ if (header === void 0) {
593
+ return [];
594
+ }
595
+ return header.split(",").map((part) => part.trim().split(";")[0].trim().toLowerCase()).filter(Boolean);
596
+ }
597
+ const CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
598
+ function isNoTransformCacheControl(cacheControl) {
599
+ if (cacheControl === void 0) {
600
+ return false;
601
+ }
602
+ return CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl);
603
+ }
604
+
269
605
  class ResponseHeadersHandlerPlugin {
270
606
  name = "~response-headers";
271
607
  /**
@@ -354,4 +690,4 @@ class RethrowHandlerPlugin {
354
690
  }
355
691
  }
356
692
 
357
- export { BatchHandlerPlugin, CORSHandlerPlugin, RequestHeadersHandlerPlugin, ResponseHeadersHandlerPlugin, RethrowHandlerPlugin };
693
+ export { BatchHandlerPlugin, CORSHandlerPlugin, RequestCompressionHandlerPlugin, RequestHeadersHandlerPlugin, RequestLimitHandlerPlugin, ResponseCompressionHandlerPlugin, ResponseHeadersHandlerPlugin, RethrowHandlerPlugin };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/server",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.15",
4
+ "version": "2.0.0-beta.17",
5
5
  "license": "MIT",
6
6
  "homepage": "https://orpc.dev",
7
7
  "repository": {
@@ -85,15 +85,14 @@
85
85
  }
86
86
  },
87
87
  "dependencies": {
88
- "@standardserver/core": "^0.0.32",
89
- "@standardserver/fetch": "^0.0.32",
90
- "@standardserver/node": "^0.0.32",
91
- "@standardserver/peer": "^0.0.32",
88
+ "@standardserver/core": "^0.4.2",
89
+ "@standardserver/fetch": "^0.4.2",
90
+ "@standardserver/node": "^0.4.2",
91
+ "@standardserver/peer": "^0.4.2",
92
92
  "cookie": "^2.0.1",
93
- "@orpc/client": "2.0.0-beta.15",
94
- "@orpc/contract": "2.0.0-beta.15",
95
- "@orpc/interop": "2.0.0-beta.15",
96
- "@orpc/shared": "2.0.0-beta.15"
93
+ "@orpc/client": "2.0.0-beta.17",
94
+ "@orpc/contract": "2.0.0-beta.17",
95
+ "@orpc/shared": "2.0.0-beta.17"
97
96
  },
98
97
  "devDependencies": {
99
98
  "crossws": "^0.4.6",