@fastify/compress 5.0.0

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.
@@ -0,0 +1,13 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "monthly"
7
+ open-pull-requests-limit: 10
8
+
9
+ - package-ecosystem: "npm"
10
+ directory: "/"
11
+ schedule:
12
+ interval: "weekly"
13
+ open-pull-requests-limit: 10
@@ -0,0 +1,21 @@
1
+ # Number of days of inactivity before an issue becomes stale
2
+ daysUntilStale: 15
3
+ # Number of days of inactivity before a stale issue is closed
4
+ daysUntilClose: 7
5
+ # Issues with these labels will never be considered stale
6
+ exemptLabels:
7
+ - "discussion"
8
+ - "feature request"
9
+ - "bug"
10
+ - "help wanted"
11
+ - "plugin suggestion"
12
+ - "good first issue"
13
+ # Label to use when marking an issue as stale
14
+ staleLabel: stale
15
+ # Comment to post when marking an issue as stale. Set to `false` to disable
16
+ markComment: >
17
+ This issue has been automatically marked as stale because it has not had
18
+ recent activity. It will be closed if no further activity occurs. Thank you
19
+ for your contributions.
20
+ # Comment to post when closing a stale issue. Set to `false` to disable
21
+ closeComment: false
@@ -0,0 +1,47 @@
1
+ name: CI
2
+ 'on':
3
+ push:
4
+ paths-ignore:
5
+ - docs/**
6
+ - '*.md'
7
+ pull_request:
8
+ paths-ignore:
9
+ - docs/**
10
+ - '*.md'
11
+ jobs:
12
+ test:
13
+ runs-on: ${{ matrix.os }}
14
+ strategy:
15
+ matrix:
16
+ node-version:
17
+ - 10
18
+ - 12
19
+ - 14
20
+ - 16
21
+ - 17
22
+ os:
23
+ - macos-latest
24
+ - ubuntu-latest
25
+ - windows-latest
26
+ steps:
27
+ - uses: actions/checkout@v3
28
+ - name: Use Node.js
29
+ uses: actions/setup-node@v3
30
+ with:
31
+ node-version: ${{ matrix.node-version }}
32
+ - name: Install Dependencies
33
+ run: |
34
+ npm install --ignore-scripts
35
+ - name: Run Tests
36
+ run: |
37
+ npm test
38
+ automerge:
39
+ needs: test
40
+ runs-on: ubuntu-latest
41
+ permissions:
42
+ pull-requests: write
43
+ contents: write
44
+ steps:
45
+ - uses: fastify/github-action-merge-dependabot@v3
46
+ with:
47
+ github-token: ${{ secrets.GITHUB_TOKEN }}
package/.taprc ADDED
@@ -0,0 +1,6 @@
1
+ ts: false
2
+ jsx: false
3
+ flow: false
4
+ coverage: true
5
+ check-coverage: true
6
+ 100: true
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Fastify
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,310 @@
1
+ # fastify-compress
2
+
3
+ ![CI](https://github.com/fastify/fastify-compress/workflows/CI/badge.svg)
4
+ [![NPM version](https://img.shields.io/npm/v/fastify-compress.svg?style=flat)](https://www.npmjs.com/package/fastify-compress)
5
+ [![Known Vulnerabilities](https://snyk.io/test/github/fastify/fastify-compress/badge.svg)](https://snyk.io/test/github/fastify/fastify-compress)
6
+ [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
7
+
8
+ Adds compression utils to [the Fastify `reply` object](https://www.fastify.io/docs/latest/Reference/Reply/#reply) and a hook to decompress requests payloads.
9
+ Supports `gzip`, `deflate`, and `brotli`.
10
+
11
+ > **Important note:** since `fastify-compress` version 4.x payloads that are compressed using the `zip` algorithm are not automatically uncompressed anymore. `fastify-compress` main feature is to provide response compression mechanism to your server, however the `zip` format does not appear in the [IANA maintained Table of Content Encodings](https://www.iana.org/assignments/http-parameters/http-parameters.xml#content-coding) and thus such behavior was out of the scope of this plugin.
12
+
13
+ ## Install
14
+ ```
15
+ npm i fastify-compress
16
+ ```
17
+
18
+ ## Usage - Compress replies
19
+
20
+ This plugin adds two functionalities to Fastify: a compress utility and a global compression hook.
21
+
22
+ Currently, the following encoding tokens are supported, using the first acceptable token in this order:
23
+
24
+ 1. `br`
25
+ 2. `gzip`
26
+ 3. `deflate`
27
+ 4. `*` (no preference — `fastify-compress` will use `gzip`)
28
+ 5. `identity` (no compression)
29
+
30
+ If an unsupported encoding is received or if the `'accept-encoding'` header is missing, it will not compress the payload. If an unsupported encoding is received and you would like to return an error, provide an `onUnsupportedEncoding` option.
31
+
32
+ The plugin automatically decides if a payload should be compressed based on its `content-type`; if no content type is present, it will assume `application/json`.
33
+
34
+ ### Global hook
35
+ The global compression hook is enabled by default. To disable it, pass the option `{ global: false }`:
36
+ ```javascript
37
+ fastify.register(
38
+ require('fastify-compress'),
39
+ { global: false }
40
+ )
41
+ ```
42
+ Remember that thanks to the Fastify encapsulation model, you can set a global compression, but run it only in a subset of routes if you wrap them inside a plugin.
43
+
44
+ Important note! If you are using `fastify-compress` plugin together with `fastify-static` plugin, you must register the `fastify-compress` (with *global hook*) **before** registering `fastify-static`.
45
+
46
+ ### Per Route options
47
+ You can specify different options for compression per route by passing in the `compress` options on the route's configuration.
48
+ ```javascript
49
+ fastify.register(
50
+ require('fastify-compress'),
51
+ { global: false }
52
+ )
53
+
54
+ // only compress if the payload is above a certain size and use brotli
55
+ fastify.get('/custom-route', {
56
+ compress: {
57
+ inflateIfDeflated: true,
58
+ threshold: 128,
59
+ zlib: {
60
+ createBrotliCompress: () => createYourCustomBrotliCompress(),
61
+ createGzip: () => createYourCustomGzip(),
62
+ createDeflate: () => createYourCustomDeflate()
63
+ }
64
+ }, (req, reply) => {
65
+ // ...
66
+ })
67
+ ```
68
+
69
+ Note: Setting `compress = false` on any route will disable compression on the route even if global compression is enabled.
70
+
71
+ ### `reply.compress`
72
+ This plugin adds a `compress` method to `reply` that accepts a stream or a string, and compresses it based on the `accept-encoding` header. If a JS object is passed in, it will be stringified to JSON.
73
+ Note that the compress method is configured with either the per route parameters if the route has a custom configuration or with the global parameters if the the route has no custom parameters but
74
+ the plugin was defined as global.
75
+
76
+ ```javascript
77
+ const fs = require('fs')
78
+ const fastify = require('fastify')()
79
+
80
+ fastify.register(require('fastify-compress'), { global: false })
81
+
82
+ fastify.get('/', (req, reply) => {
83
+ reply
84
+ .type('text/plain')
85
+ .compress(fs.createReadStream('./package.json'))
86
+ })
87
+
88
+ fastify.listen(3000, function (err) {
89
+ if (err) throw err
90
+ console.log(`server listening on ${fastify.server.address().port}`)
91
+ })
92
+ ```
93
+
94
+ ## Compress Options
95
+
96
+ ### threshold
97
+ The minimum byte size for a response to be compressed. Defaults to `1024`.
98
+ ```javascript
99
+ fastify.register(
100
+ require('fastify-compress'),
101
+ { threshold: 2048 }
102
+ )
103
+ ```
104
+ ### customTypes
105
+ [mime-db](https://github.com/jshttp/mime-db) is used to determine if a `content-type` should be compressed. You can compress additional content types via regular expression.
106
+ ```javascript
107
+ fastify.register(
108
+ require('fastify-compress'),
109
+ { customTypes: /x-protobuf$/ }
110
+ )
111
+ ```
112
+
113
+ ### onUnsupportedEncoding
114
+ When the encoding is not supported, a custom error response can be sent in place of the uncompressed payload by setting the `onUnsupportedEncoding(encoding, request, reply)` option to be a function that can modify the reply and return a `string | Buffer | Stream | Error` payload.
115
+ ```javascript
116
+ fastify.register(
117
+ require('fastify-compress'),
118
+ {
119
+ onUnsupportedEncoding: (encoding, request, reply) => {
120
+ reply.code(406)
121
+ return 'We do not support the ' + encoding + ' encoding.'
122
+ }
123
+ }
124
+ )
125
+ ```
126
+
127
+ ### Disable compression by header
128
+ You can selectively disable response compression by using the `x-no-compression` header in the request.
129
+
130
+ ### Inflate pre-compressed bodies for clients that do not support compression
131
+ Optional feature to inflate pre-compressed data if the client does not include one of the supported compression types in its `accept-encoding` header.
132
+ ```javascript
133
+ fastify.register(
134
+ require('fastify-compress'),
135
+ { inflateIfDeflated: true }
136
+ )
137
+
138
+ fastify.get('/file', (req, reply) =>
139
+ // will inflate the file on the way out for clients
140
+ // that indicate they do not support compression
141
+ reply.send(fs.createReadStream('./file.gz')))
142
+ ```
143
+
144
+ ### Customize encoding priority
145
+
146
+ By default, `fastify-compress` prioritizes compression as described [at the beginning of §Usage - Compress replies](#usage). You can change that by passing an array of compression tokens to the `encodings` option:
147
+
148
+ ```javascript
149
+ fastify.register(
150
+ require('fastify-compress'),
151
+ // Only support gzip and deflate, and prefer deflate to gzip
152
+ { encodings: ['deflate', 'gzip'] }
153
+ )
154
+ ```
155
+
156
+ ### brotliOptions and zlibOptions
157
+
158
+ You can tune compression by setting the `brotliOptions` and `zlibOptions` properties. These properties are passed directly to native node `zlib` methods, so they should match the corresponding [class](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) [definitions](https://nodejs.org/api/zlib.html#zlib_class_options).
159
+
160
+ ```javascript
161
+ server.register(fastifyCompress, {
162
+ brotliOptions: {
163
+ params: {
164
+ [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, // useful for APIs that primarily return text
165
+ [zlib.constants.BROTLI_PARAM_QUALITY]: 4, // default is 11, max is 11, min is 0
166
+ },
167
+ },
168
+ zlibOptions: {
169
+ level: 9, // default is 9, max is 9, min is 0
170
+ }
171
+ });
172
+ ```
173
+
174
+ ### Manage `Content-Length` header removal with removeContentLengthHeader
175
+ By default, `fastify-compress` removes the reply `Content-Length` header. You can change that by setting the `removeContentLengthHeader` to `false` either on a global scope or on a route specific scope.
176
+
177
+ ```javascript
178
+ // Global plugin scope
179
+ server.register(fastifyCompress, { global: true, removeContentLengthHeader: false });
180
+
181
+ // Route specific scope
182
+ fastify.get('/file', {
183
+ compress: { removeContentLengthHeader: false }
184
+ }, (req, reply) =>
185
+ reply.compress(fs.createReadStream('./file.gz'))
186
+ )
187
+ ```
188
+
189
+ ## Usage - Decompress request payloads
190
+
191
+ This plugin adds a `preParsing` hook that decompress the request payload according to the `content-encoding` request header.
192
+
193
+ Currently, the following encoding tokens are supported:
194
+
195
+ 1. `br`
196
+ 2. `gzip`
197
+ 3. `deflate`
198
+
199
+ If an unsupported encoding or and invalid payload is received, the plugin will throw an error.
200
+
201
+ If the request header is missing, the plugin will not do anything and yield to the next hook.
202
+
203
+ ### Global hook
204
+
205
+ The global request decompression hook is enabled by default. To disable it, pass the option `{ global: false }`:
206
+ ```javascript
207
+ fastify.register(
208
+ require('fastify-compress'),
209
+ { global: false }
210
+ )
211
+ ```
212
+
213
+ Remember that thanks to the Fastify encapsulation model, you can set a global decompression, but run it only in a subset of routes if you wrap them inside a plugin.
214
+
215
+ ### Per Route options
216
+
217
+ You can specify different options for decompression per route by passing in the `decompress` options on the route's configuration.
218
+ ```javascript
219
+ fastify.register(
220
+ require('fastify-compress'),
221
+ { global: false }
222
+ )
223
+
224
+ // Always decompress using gzip
225
+ fastify.get('/custom-route', {
226
+ decompress: {
227
+ forceRequestEncoding: 'gzip',
228
+ zlib: {
229
+ createBrotliDecompress: () => createYourCustomBrotliDecompress(),
230
+ createGunzip: () => createYourCustomGunzip(),
231
+ createInflate: () => createYourCustomInflate()
232
+ }
233
+ }
234
+ }, (req, reply) => {
235
+ // ...
236
+ })
237
+ ```
238
+
239
+ ### requestEncodings
240
+
241
+ By default, `fastify-compress` accepts all encodings specified [at the beginning of §Usage - Decompress request payloads](#usage). You can change that by passing an array of compression tokens to the `requestEncodings` option:
242
+
243
+ ```javascript
244
+ fastify.register(
245
+ require('fastify-compress'),
246
+ // Only support gzip
247
+ { requestEncodings: ['gzip'] }
248
+ )
249
+ ```
250
+
251
+ ### forceRequestEncoding
252
+
253
+ By default, `fastify-compress` chooses the decompressing algorithm by looking at the `content-encoding` header, if present.
254
+
255
+ You can force one algorithm and ignore the header at all by providing the `forceRequestEncoding` option.
256
+
257
+ Note that if the request payload is not compressed, `fastify-compress` will try to decompress, resulting in an error.
258
+
259
+ ### onUnsupportedRequestEncoding
260
+
261
+ When the request payload encoding is not supported, you can customize the response error by setting the `onUnsupportedEncoding(request, encoding)` option to be a function that returns an error.
262
+
263
+ ```javascript
264
+ fastify.register(
265
+ require('fastify-compress'),
266
+ {
267
+  onUnsupportedRequestEncoding: (request, encoding) => {
268
+ return {
269
+ statusCode: 415,
270
+ code: 'UNSUPPORTED',
271
+ error: 'Unsupported Media Type',
272
+ message: 'We do not support the ' + encoding + ' encoding.'
273
+ }
274
+ }
275
+ }
276
+ )
277
+ ```
278
+
279
+ ### onInvalidRequestPayload
280
+
281
+ When the request payload cannot be decompressed using the detected algorithm, you can customize the response error setting the `onInvalidRequestPayload(request, encoding)` option to be a function that returns an error.
282
+
283
+ ```javascript
284
+ fastify.register(
285
+ require('fastify-compress'),
286
+ {
287
+ onInvalidRequestPayload: (request, encoding, error) => {
288
+ return {
289
+ statusCode: 400,
290
+ code: 'BAD_REQUEST',
291
+ error: 'Bad Request',
292
+ message: 'This is not a valid ' + encoding + ' encoded payload: ' + error.message
293
+ }
294
+ }
295
+ }
296
+ )
297
+ ```
298
+
299
+ ## Note
300
+ Please note that in large-scale scenarios, you should use a proxy like Nginx to handle response compression.
301
+
302
+ ## Acknowledgements
303
+
304
+ Past sponsors:
305
+
306
+ - [LetzDoIt](http://www.letzdoitapp.com/)
307
+
308
+ ## License
309
+
310
+ Licensed under [MIT](./LICENSE).
package/index.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import {
2
+ FastifyPluginCallback,
3
+ FastifyReply,
4
+ FastifyRequest,
5
+ RawServerBase,
6
+ RawServerDefault
7
+ } from 'fastify'
8
+ import * as fastify from 'fastify'
9
+ import { Input, InputObject } from 'into-stream'
10
+ import { Stream } from 'stream'
11
+ import { BrotliOptions, ZlibOptions } from 'zlib'
12
+
13
+ type EncodingToken = 'br' | 'deflate' | 'gzip' | 'identity';
14
+
15
+ export interface FastifyCompressOptions {
16
+ brotliOptions?: BrotliOptions;
17
+ customTypes?: RegExp;
18
+ encodings?: EncodingToken[];
19
+ forceRequestEncoding?: EncodingToken;
20
+ global?: boolean;
21
+ inflateIfDeflated?: boolean;
22
+ onInvalidRequestPayload?: (encoding: string, request: FastifyRequest, error: Error) => Error | undefined | null;
23
+ onUnsupportedEncoding?: (encoding: string, request: FastifyRequest, reply: FastifyReply) => string | Buffer | Stream;
24
+ onUnsupportedRequestEncoding?: (encoding: string, request: FastifyRequest, reply: FastifyReply) => Error | undefined | null;
25
+ removeContentLengthHeader?: boolean;
26
+ requestEncodings?: EncodingToken[];
27
+ threshold?: number;
28
+ zlib?: unknown;
29
+ zlibOptions?: ZlibOptions;
30
+ }
31
+
32
+ interface RouteCompressOptions extends Pick<FastifyCompressOptions,
33
+ | 'brotliOptions'
34
+ | 'customTypes'
35
+ | 'encodings'
36
+ | 'inflateIfDeflated'
37
+ | 'onUnsupportedEncoding'
38
+ | 'removeContentLengthHeader'
39
+ | 'threshold'
40
+ | 'zlib'
41
+ | 'zlibOptions'
42
+ > {}
43
+
44
+ interface RouteDecompressOptions extends Pick<FastifyCompressOptions,
45
+ | 'forceRequestEncoding'
46
+ | 'onInvalidRequestPayload'
47
+ | 'onUnsupportedRequestEncoding'
48
+ | 'requestEncodings'
49
+ | 'zlib'
50
+ > {}
51
+
52
+ interface FastifyCompressRouteOptions {
53
+ compress?: RouteCompressOptions | false;
54
+ decompress?: RouteDecompressOptions | false;
55
+ }
56
+
57
+ export interface RouteOptions extends fastify.RouteOptions, FastifyCompressRouteOptions {}
58
+
59
+ export interface RoutesConfigCompressOptions {
60
+ /** @deprecated `config.compress` is deprecated, use `compress` shorthand option instead */
61
+ compress?: RouteCompressOptions | false;
62
+ /** @deprecated `config.decompress` is deprecated, use `decompress` shorthand option instead */
63
+ decompress?: RouteDecompressOptions | false;
64
+ }
65
+
66
+ declare module 'fastify' {
67
+ export interface FastifyContextConfig extends RoutesConfigCompressOptions {}
68
+
69
+ export interface RouteShorthandOptions<
70
+ RawServer extends RawServerBase = RawServerDefault
71
+ > extends FastifyCompressRouteOptions {}
72
+
73
+ interface FastifyReply {
74
+ compress(input: Stream | Input | InputObject): void;
75
+ }
76
+
77
+ export interface RouteOptions extends FastifyCompressRouteOptions {}
78
+ }
79
+
80
+ declare const fastifyCompress: FastifyPluginCallback<FastifyCompressOptions>
81
+ export default fastifyCompress