fastify 4.10.2 → 4.12.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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2016-2022 The Fastify Team
3
+ Copyright (c) 2016-2023 The Fastify Team
4
4
 
5
5
  The Fastify team members are listed at https://github.com/fastify/fastify#team
6
6
  and in the README file.
package/README.md CHANGED
@@ -289,8 +289,6 @@ listed in alphabetical order.
289
289
  ### Fastify Core team
290
290
  * [__Tommaso Allevi__](https://github.com/allevo),
291
291
  <https://twitter.com/allevitommaso>, <https://www.npmjs.com/~allevo>
292
- * [__Ethan Arrowood__](https://github.com/Ethan-Arrowood/),
293
- <https://twitter.com/arrowoodtech>, <https://www.npmjs.com/~ethan_arrowood>
294
292
  * [__Harry Brundage__](https://github.com/airhorns/),
295
293
  <https://twitter.com/harrybrundage>, <https://www.npmjs.com/~airhorns>
296
294
  * [__David Mark Clements__](https://github.com/davidmarkclements),
@@ -362,6 +360,8 @@ to join this group by Lead Maintainers.
362
360
  <https://twitter.com/cemremengu>, <https://www.npmjs.com/~cemremengu>
363
361
  * [__Nathan Woltman__](https://github.com/nwoltman),
364
362
  <https://twitter.com/NathanWoltman>, <https://www.npmjs.com/~nwoltman>
363
+ * [__Ethan Arrowood__](https://github.com/Ethan-Arrowood/),
364
+ <https://twitter.com/arrowoodtech>, <https://www.npmjs.com/~ethan_arrowood>
365
365
 
366
366
  ## Hosted by
367
367
 
@@ -220,6 +220,10 @@ section.
220
220
  plugin to authenticate HTTP requests based on api key and signature
221
221
  - [`fastify-appwrite`](https://github.com/Dev-Manny/fastify-appwrite) Fastify
222
222
  Plugin for interacting with Appwrite server.
223
+ - [`fastify-at-mysql`](https://github.com/mateonunez/fastify-at-mysql) Fastify
224
+ MySQL plugin with auto SQL injection attack prevention.
225
+ - [`fastify-at-postgres`](https://github.com/mateonunez/fastify-at-postgres) Fastify
226
+ Postgres plugin with auto SQL injection attack prevention.
223
227
  - [`fastify-auth0-verify`](https://github.com/nearform/fastify-auth0-verify):
224
228
  Auth0 verification plugin for Fastify, internally uses
225
229
  [fastify-jwt](https://npm.im/fastify-jwt) and
@@ -362,6 +366,9 @@ section.
362
366
  - [`fastify-influxdb`](https://github.com/alex-ppg/fastify-influxdb) Fastify
363
367
  InfluxDB plugin connecting to an InfluxDB instance via the Influx default
364
368
  package.
369
+ - [`fastify-ip`](https://github.com/metcoder95/fastify-ip) A plugin
370
+ for Fastify that allows you to infer a request ID by a
371
+ given set of custom Request headers.
365
372
  - [`fastify-jwt-authz`](https://github.com/Ethan-Arrowood/fastify-jwt-authz) JWT
366
373
  user scope verifier.
367
374
  - [`fastify-jwt-webapp`](https://github.com/charlesread/fastify-jwt-webapp) JWT
@@ -387,6 +394,9 @@ section.
387
394
  - [`fastify-lured`](https://github.com/lependu/fastify-lured) Plugin to load lua
388
395
  scripts with [fastify-redis](https://github.com/fastify/fastify-redis) and
389
396
  [lured](https://github.com/enobufs/lured).
397
+ - [`fastify-lyra`](https://github.com/mateonunez/fastify-lyra)
398
+ A plugin to implement [Lyra](https://github.com/LyraSearch/lyra) search engine
399
+ on Fastify.
390
400
  - [`fastify-mailer`](https://github.com/coopflow/fastify-mailer) Plugin to
391
401
  initialize and encapsulate [Nodemailer](https://nodemailer.com)'s transporters
392
402
  instances in Fastify.
@@ -467,6 +477,8 @@ section.
467
477
  - [`fastify-postgraphile`](https://github.com/alemagio/fastify-postgraphile)
468
478
  Plugin to integrate [PostGraphile](https://www.graphile.org/postgraphile/) in
469
479
  a Fastify project.
480
+ - [`fastify-postgres-dot-js`](https://github.com/kylerush/fastify-postgresjs) Fastify
481
+ PostgreSQL connection plugin that uses [Postgres.js](https://github.com/porsager/postgres).
470
482
  - [`fastify-prettier`](https://github.com/hsynlms/fastify-prettier) A Fastify
471
483
  plugin that uses [prettier](https://github.com/prettier/prettier) under the
472
484
  hood to beautify outgoing responses and/or other things in the Fastify server.
@@ -565,6 +577,8 @@ section.
565
577
  for [zod](https://github.com/colinhacks/zod).
566
578
  - [`fastify-typeorm-plugin`](https://github.com/inthepocket/fastify-typeorm-plugin)
567
579
  Fastify plugin to work with TypeORM.
580
+ - [`fastify-user-agent`](https://github.com/Eomm/fastify-user-agent) parses your
581
+ request's `user-agent` header.
568
582
  - [`fastify-vhost`](https://github.com/patrickpissurno/fastify-vhost) Proxy
569
583
  subdomain HTTP requests to another server (useful if you want to point
570
584
  multiple subdomains to the same IP address, while running different servers on
@@ -39,6 +39,11 @@ const res = await fastify.inject('/encapsulated')
39
39
  console.log(res.json().message) // 'wrapped'
40
40
  ```
41
41
 
42
+ >The root error handler is Fastify’s generic error handler.
43
+ >This error handler will use the headers and status code in the Error object,
44
+ >if they exist. **The headers and status code will not be automatically set if
45
+ >a custom error handler is provided**.
46
+
42
47
  ### Removed `app.use()` ([#3506](https://github.com/fastify/fastify/pull/3506))
43
48
 
44
49
  With v4 of Fastify, `app.use()` has been removed and the use of middleware is
@@ -112,6 +112,9 @@ fastify.setErrorHandler(function (error, request, reply) {
112
112
  this.log.error(error)
113
113
  // Send error response
114
114
  reply.status(500).send({ ok: false })
115
+ } else {
116
+ // fastify will use parent error handler to handle this
117
+ reply.send(error)
115
118
  }
116
119
  })
117
120
 
@@ -382,4 +385,4 @@ Impossible to load plugin because the parent (mapped directly from `avvio`)
382
385
  <a name="FST_ERR_PLUGIN_TIMEOUT"></a>
383
386
  #### FST_ERR_PLUGIN_TIMEOUT
384
387
 
385
- Plugin did not start in time. Default timeout (in millis): `10000`
388
+ Plugin did not start in time. Default timeout (in millis): `10000`
@@ -674,6 +674,15 @@ fastify.get('/streams', function (request, reply) {
674
674
  reply.send(stream)
675
675
  })
676
676
  ```
677
+ When using async-await you will need to return or await the reply object:
678
+ ```js
679
+ fastify.get('/streams', async function (request, reply) {
680
+ const fs = require('fs')
681
+ const stream = fs.createReadStream('some-file', 'utf8')
682
+ reply.header('Content-Type', 'application/octet-stream')
683
+ return reply.send(stream)
684
+ })
685
+ ```
677
686
 
678
687
  #### Buffers
679
688
  <a id="send-buffers"></a>
@@ -689,6 +698,16 @@ fastify.get('/streams', function (request, reply) {
689
698
  })
690
699
  ```
691
700
 
701
+ When using async-await you will need to return or await the reply object:
702
+ ```js
703
+ const fs = require('fs')
704
+ fastify.get('/streams', async function (request, reply) {
705
+ fs.readFile('some-file', (err, fileBuffer) => {
706
+ reply.send(err || fileBuffer)
707
+ })
708
+ return reply
709
+ })
710
+ ```
692
711
  #### Errors
693
712
  <a id="errors"></a>
694
713
 
@@ -1011,6 +1011,9 @@ Note that the array contains the `fastify.server.address()` too.
1011
1011
  #### getDefaultRoute
1012
1012
  <a id="getDefaultRoute"></a>
1013
1013
 
1014
+ **Notice**: this method is deprecated and should be removed in the next Fastify
1015
+ major version.
1016
+
1014
1017
  The `defaultRoute` handler handles requests that do not match any URL specified
1015
1018
  by your Fastify application. This defaults to the 404 handler, but can be
1016
1019
  overridden with [setDefaultRoute](#setdefaultroute). Method to get the
@@ -1023,14 +1026,25 @@ const defaultRoute = fastify.getDefaultRoute()
1023
1026
  #### setDefaultRoute
1024
1027
  <a id="setDefaultRoute"></a>
1025
1028
 
1026
- **Note**: The default 404 handler, or one set using `setNotFoundHandler`, will
1027
- never trigger if the default route is overridden. This sets the handler for the
1029
+ **Notice**: this method is deprecated and should be removed in the next Fastify
1030
+ major version. Please, consider to use `setNotFoundHandler` or a wildcard
1031
+ matching route.
1032
+
1033
+ The default 404 handler, or one set using `setNotFoundHandler`, will
1034
+ never trigger if the default route is overridden. This sets the handler for the
1028
1035
  Fastify application, not just the current instance context. Use
1029
1036
  [setNotFoundHandler](#setnotfoundhandler) if you want to customize 404 handling
1030
- instead. Method to set the `defaultRoute` for the server:
1037
+ instead.
1038
+
1039
+ This method sets the `defaultRoute` for the server. Note that, its purpose is
1040
+ to interact with the underlying raw requests. Unlike other Fastify handlers, the
1041
+ arguments received are of type [RawRequest](./TypeScript.md#rawrequest) and
1042
+ [RawReply](./TypeScript.md#rawreply) respectively.
1031
1043
 
1032
1044
  ```js
1033
1045
  const defaultRoute = function (req, res) {
1046
+ // req = RawRequest
1047
+ // res = RawReply
1034
1048
  res.end('hello world')
1035
1049
  }
1036
1050
 
@@ -1670,7 +1684,7 @@ information.
1670
1684
  `fastify.defaultTextParser()` can be used to parse content as plain text.
1671
1685
 
1672
1686
  ```js
1673
- fastify.addContentTypeParser('text/json', { asString: true }, fastify.defaultTextParser())
1687
+ fastify.addContentTypeParser('text/json', { asString: true }, fastify.defaultTextParser)
1674
1688
  ```
1675
1689
 
1676
1690
  #### errorHandler
package/fastify.d.ts CHANGED
@@ -1,26 +1,190 @@
1
1
  import * as http from 'http'
2
2
  import * as http2 from 'http2'
3
3
  import * as https from 'https'
4
- import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
4
+ import { Socket } from 'net'
5
5
 
6
- import { FastifyRequest, RequestGenericInterface } from './types/request'
7
- import { RawServerBase, RawServerDefault, RawRequestDefaultExpression, RawReplyDefaultExpression } from './types/utils'
8
- import { FastifyBaseLogger, FastifyLoggerInstance, FastifyLoggerOptions, PinoLoggerOptions } from './types/logger'
9
- import { FastifyInstance } from './types/instance'
10
- import { FastifyServerFactory } from './types/serverFactory'
11
- import { Options as AjvOptions } from '@fastify/ajv-compiler'
12
- import { Options as FJSOptions } from '@fastify/fast-json-stringify-compiler'
6
+ import { Options as AjvOptions, ValidatorCompiler } from '@fastify/ajv-compiler'
13
7
  import { FastifyError } from '@fastify/error'
8
+ import { Options as FJSOptions, SerializerCompiler } from '@fastify/fast-json-stringify-compiler'
9
+ import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
10
+ import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
11
+
12
+ import { FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction } from './types/content-type-parser'
13
+ import { FastifyContext, FastifyContextConfig } from './types/context'
14
+ import { FastifyErrorCodes } from './types/errors'
15
+ import { DoneFuncWithErrOrRes, HookHandlerDoneFunction, RequestPayload, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onRegisterHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler } from './types/hooks'
16
+ import { FastifyListenOptions, FastifyInstance, PrintRoutesOptions } from './types/instance'
17
+ import { FastifyBaseLogger, FastifyLoggerInstance, FastifyLoggerOptions, PinoLoggerOptions, FastifyLogFn, LogLevel } from './types/logger'
18
+ import { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
19
+ import { FastifyRegister, FastifyRegisterOptions, RegisterOptions } from './types/register'
14
20
  import { FastifyReply } from './types/reply'
15
- import { FastifySchemaValidationError } from './types/schema'
16
- import { ConstructorAction, ProtoAction } from "./types/content-type-parser";
17
- import { Socket } from 'net'
18
- import { ValidatorCompiler } from '@fastify/ajv-compiler'
19
- import { SerializerCompiler } from '@fastify/fast-json-stringify-compiler'
20
- import { FastifySchema } from './types/schema'
21
- import { FastifyContextConfig } from './types/context'
21
+ import { FastifyRequest, RequestGenericInterface } from './types/request'
22
+ import { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface } from './types/route'
23
+ import { FastifySchema, FastifySchemaCompiler, FastifySchemaValidationError } from './types/schema'
24
+ import { FastifyServerFactory, FastifyServerFactoryHandler } from './types/serverFactory'
22
25
  import { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
23
- import { FastifyErrorCodes } from './types/errors'
26
+ import { HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault } from './types/utils'
27
+
28
+ declare module '@fastify/error' {
29
+ interface FastifyError {
30
+ validation?: fastify.ValidationResult[];
31
+ validationContext?: 'body' | 'headers' | 'parameters' | 'querystring';
32
+ }
33
+ }
34
+
35
+ type Fastify = typeof fastify
36
+
37
+ declare namespace fastify {
38
+ export const errorCodes: FastifyErrorCodes;
39
+
40
+ export type FastifyHttp2SecureOptions<
41
+ Server extends http2.Http2SecureServer,
42
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
43
+ > = FastifyServerOptions<Server, Logger> & {
44
+ http2: true,
45
+ https: http2.SecureServerOptions,
46
+ http2SessionTimeout?: number
47
+ }
48
+
49
+ export type FastifyHttp2Options<
50
+ Server extends http2.Http2Server,
51
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
52
+ > = FastifyServerOptions<Server, Logger> & {
53
+ http2: true,
54
+ http2SessionTimeout?: number
55
+ }
56
+
57
+ export type FastifyHttpsOptions<
58
+ Server extends https.Server,
59
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
60
+ > = FastifyServerOptions<Server, Logger> & {
61
+ https: https.ServerOptions | null
62
+ }
63
+
64
+ type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
65
+
66
+ export interface ConnectionError extends Error {
67
+ code: string,
68
+ bytesParsed: number,
69
+ rawPacket: {
70
+ type: string,
71
+ data: number[]
72
+ }
73
+ }
74
+
75
+ type TrustProxyFunction = (address: string, hop: number) => boolean
76
+
77
+ /**
78
+ * Options for a fastify server instance. Utilizes conditional logic on the generic server parameter to enforce certain https and http2
79
+ */
80
+ export type FastifyServerOptions<
81
+ RawServer extends RawServerBase = RawServerDefault,
82
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
83
+ > = {
84
+ ignoreTrailingSlash?: boolean,
85
+ ignoreDuplicateSlashes?: boolean,
86
+ connectionTimeout?: number,
87
+ keepAliveTimeout?: number,
88
+ maxRequestsPerSocket?: number,
89
+ forceCloseConnections?: boolean | 'idle',
90
+ requestTimeout?: number,
91
+ pluginTimeout?: number,
92
+ bodyLimit?: number,
93
+ maxParamLength?: number,
94
+ disableRequestLogging?: boolean,
95
+ exposeHeadRoutes?: boolean,
96
+ onProtoPoisoning?: ProtoAction,
97
+ onConstructorPoisoning?: ConstructorAction,
98
+ logger?: boolean | FastifyLoggerOptions<RawServer> & PinoLoggerOptions | Logger,
99
+ serializerOpts?: FJSOptions | Record<string, unknown>,
100
+ serverFactory?: FastifyServerFactory<RawServer>,
101
+ caseSensitive?: boolean,
102
+ requestIdHeader?: string | false,
103
+ requestIdLogLabel?: string;
104
+ jsonShorthand?: boolean;
105
+ genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>) => string,
106
+ trustProxy?: boolean | string | string[] | number | TrustProxyFunction,
107
+ querystringParser?: (str: string) => { [key: string]: unknown },
108
+ /**
109
+ * @deprecated Prefer using the `constraints.version` property
110
+ */
111
+ versioning?: {
112
+ storage(): {
113
+ get(version: string): string | null,
114
+ set(version: string, store: Function): void
115
+ del(version: string): void,
116
+ empty(): void
117
+ },
118
+ deriveVersion<Context>(req: Object, ctx?: Context): string // not a fan of using Object here. Also what is Context? Can either of these be better defined?
119
+ },
120
+ constraints?: {
121
+ [name: string]: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>,
122
+ },
123
+ schemaController?: {
124
+ bucket?: (parentSchemas?: unknown) => {
125
+ add(schema: unknown): FastifyInstance;
126
+ getSchema(schemaId: string): unknown;
127
+ getSchemas(): Record<string, unknown>;
128
+ };
129
+ compilersFactory?: {
130
+ buildValidator?: ValidatorCompiler;
131
+ buildSerializer?: SerializerCompiler;
132
+ };
133
+ };
134
+ return503OnClosing?: boolean,
135
+ ajv?: {
136
+ customOptions?: AjvOptions,
137
+ plugins?: (Function | [Function, unknown])[]
138
+ },
139
+ frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema>(
140
+ error: FastifyError,
141
+ req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>,
142
+ res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, RequestGeneric, FastifyContextConfig, SchemaCompiler, TypeProvider>
143
+ ) => void,
144
+ rewriteUrl?: (req: RawRequestDefaultExpression<RawServer>) => string,
145
+ schemaErrorFormatter?: (errors: FastifySchemaValidationError[], dataVar: string) => Error,
146
+ /**
147
+ * listener to error events emitted by client connections
148
+ */
149
+ clientErrorHandler?: (error: ConnectionError, socket: Socket) => void
150
+ }
151
+
152
+ export interface ValidationResult {
153
+ keyword: string;
154
+ instancePath: string;
155
+ schemaPath: string;
156
+ params: Record<string, string | string[]>;
157
+ message?: string;
158
+ }
159
+
160
+ /* Export additional types */
161
+ export type {
162
+ LightMyRequestChain, InjectOptions, LightMyRequestResponse, LightMyRequestCallback, // 'light-my-request'
163
+ FastifyRequest, RequestGenericInterface, // './types/request'
164
+ FastifyReply, // './types/reply'
165
+ FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin, // './types/plugin'
166
+ FastifyListenOptions, FastifyInstance, PrintRoutesOptions, // './types/instance'
167
+ FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel, // './types/logger'
168
+ FastifyContext, FastifyContextConfig, // './types/context'
169
+ RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface, // './types/route'
170
+ FastifyRegister, FastifyRegisterOptions, RegisterOptions, // './types/register'
171
+ FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction, // './types/content-type-parser'
172
+ FastifyError, // '@fastify/error'
173
+ FastifySchema, FastifySchemaCompiler, // './types/schema'
174
+ HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault, // './types/utils'
175
+ DoneFuncWithErrOrRes, HookHandlerDoneFunction, RequestPayload, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onRegisterHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler, // './types/hooks'
176
+ FastifyServerFactory, FastifyServerFactoryHandler, // './types/serverFactory'
177
+ FastifyTypeProvider, FastifyTypeProviderDefault, // './types/type-provider'
178
+ FastifyErrorCodes, // './types/errors'
179
+ }
180
+ // named export
181
+ // import { plugin } from 'plugin'
182
+ // const { plugin } = require('plugin')
183
+ export const fastify: Fastify
184
+ // default export
185
+ // import plugin from 'plugin'
186
+ export { fastify as default }
187
+ }
24
188
 
25
189
  /**
26
190
  * Fastify factory function for the standard fastify http, https, or http2 server instance.
@@ -34,183 +198,34 @@ declare function fastify<
34
198
  Server extends http2.Http2SecureServer,
35
199
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
36
200
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
37
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
201
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
38
202
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
39
- >(opts: FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
203
+ >(opts: fastify.FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
40
204
 
41
205
  declare function fastify<
42
206
  Server extends http2.Http2Server,
43
207
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
44
208
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
45
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
209
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
46
210
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
47
- >(opts: FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
211
+ >(opts: fastify.FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
48
212
 
49
213
  declare function fastify<
50
214
  Server extends https.Server,
51
215
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
52
216
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
53
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
217
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
54
218
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
55
- >(opts: FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
219
+ >(opts: fastify.FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
56
220
 
57
221
  declare function fastify<
58
222
  Server extends http.Server,
59
223
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
60
224
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
61
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
225
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
62
226
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
63
- >(opts?: FastifyServerOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
64
-
65
- declare namespace fastify {
66
- export const errorCodes: FastifyErrorCodes;
67
- }
68
-
69
- export default fastify
70
-
71
- export type FastifyHttp2SecureOptions<
72
- Server extends http2.Http2SecureServer,
73
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
74
- > = FastifyServerOptions<Server, Logger> & {
75
- http2: true,
76
- https: http2.SecureServerOptions,
77
- http2SessionTimeout?: number
78
- }
79
-
80
- export type FastifyHttp2Options<
81
- Server extends http2.Http2Server,
82
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
83
- > = FastifyServerOptions<Server, Logger> & {
84
- http2: true,
85
- http2SessionTimeout?: number
86
- }
87
-
88
- export type FastifyHttpsOptions<
89
- Server extends https.Server,
90
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
91
- > = FastifyServerOptions<Server, Logger> & {
92
- https: https.ServerOptions | null
93
- }
94
-
95
- type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
96
-
97
- export interface ConnectionError extends Error {
98
- code: string,
99
- bytesParsed: number,
100
- rawPacket: {
101
- type: string,
102
- data: number[]
103
- }
104
- }
105
-
106
- /**
107
- * Options for a fastify server instance. Utilizes conditional logic on the generic server parameter to enforce certain https and http2
108
- */
109
- export type FastifyServerOptions<
110
- RawServer extends RawServerBase = RawServerDefault,
111
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
112
- > = {
113
- ignoreTrailingSlash?: boolean,
114
- ignoreDuplicateSlashes?: boolean,
115
- connectionTimeout?: number,
116
- keepAliveTimeout?: number,
117
- maxRequestsPerSocket?: number,
118
- forceCloseConnections?: boolean | 'idle',
119
- requestTimeout?: number,
120
- pluginTimeout?: number,
121
- bodyLimit?: number,
122
- maxParamLength?: number,
123
- disableRequestLogging?: boolean,
124
- exposeHeadRoutes?: boolean,
125
- onProtoPoisoning?: ProtoAction,
126
- onConstructorPoisoning?: ConstructorAction,
127
- logger?: boolean | FastifyLoggerOptions<RawServer> & PinoLoggerOptions | Logger,
128
- serializerOpts?: FJSOptions | Record<string, unknown>,
129
- serverFactory?: FastifyServerFactory<RawServer>,
130
- caseSensitive?: boolean,
131
- requestIdHeader?: string | false,
132
- requestIdLogLabel?: string;
133
- jsonShorthand?: boolean;
134
- genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>) => string,
135
- trustProxy?: boolean | string | string[] | number | TrustProxyFunction,
136
- querystringParser?: (str: string) => { [key: string]: unknown },
137
- /**
138
- * @deprecated Prefer using the `constraints.version` property
139
- */
140
- versioning?: {
141
- storage(): {
142
- get(version: string): string | null,
143
- set(version: string, store: Function): void
144
- del(version: string): void,
145
- empty(): void
146
- },
147
- deriveVersion<Context>(req: Object, ctx?: Context): string // not a fan of using Object here. Also what is Context? Can either of these be better defined?
148
- },
149
- constraints?: {
150
- [name: string]: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>,
151
- },
152
- schemaController?: {
153
- bucket?: (parentSchemas?: unknown) => {
154
- add(schema: unknown): FastifyInstance;
155
- getSchema(schemaId: string): unknown;
156
- getSchemas(): Record<string, unknown>;
157
- };
158
- compilersFactory?: {
159
- buildValidator?: ValidatorCompiler;
160
- buildSerializer?: SerializerCompiler;
161
- };
162
- };
163
- return503OnClosing?: boolean,
164
- ajv?: {
165
- customOptions?: AjvOptions,
166
- plugins?: (Function | [Function, unknown])[]
167
- },
168
- frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema>(
169
- error: FastifyError,
170
- req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>,
171
- res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, RequestGeneric, FastifyContextConfig, SchemaCompiler, TypeProvider>
172
- ) => void,
173
- rewriteUrl?: (req: RawRequestDefaultExpression<RawServer>) => string,
174
- schemaErrorFormatter?: (errors: FastifySchemaValidationError[], dataVar: string) => Error,
175
- /**
176
- * listener to error events emitted by client connections
177
- */
178
- clientErrorHandler?: (error: ConnectionError, socket: Socket) => void
179
- }
180
-
181
- type TrustProxyFunction = (address: string, hop: number) => boolean
182
-
183
- declare module '@fastify/error' {
184
- interface FastifyError {
185
- validation?: ValidationResult[];
186
- validationContext?: 'body' | 'headers' | 'parameters' | 'querystring';
187
- }
188
- }
189
-
190
- export interface ValidationResult {
191
- keyword: string;
192
- instancePath: string;
193
- schemaPath: string;
194
- params: Record<string, string | string[]>;
195
- message?: string;
196
- }
227
+ >(opts?: fastify.FastifyServerOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
197
228
 
198
- /* Export all additional types */
199
- export type { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
200
- export { FastifyRequest, RequestGenericInterface } from './types/request'
201
- export { FastifyReply } from './types/reply'
202
- export { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
203
- export { FastifyListenOptions, FastifyInstance, PrintRoutesOptions } from './types/instance'
204
- export { FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel } from './types/logger'
205
- export { FastifyContext, FastifyContextConfig } from './types/context'
206
- export { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface } from './types/route'
207
- export * from './types/register'
208
- export { FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction } from './types/content-type-parser'
209
- export { FastifyError } from '@fastify/error'
210
- export { FastifySchema, FastifySchemaCompiler } from './types/schema'
211
- export { HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault } from './types/utils'
212
- export * from './types/hooks'
213
- export { FastifyServerFactory, FastifyServerFactoryHandler } from './types/serverFactory'
214
- export { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
215
- export { FastifyErrorCodes } from './types/errors'
216
- export { fastify }
229
+ // CJS export
230
+ // const fastify = require('fastify')
231
+ export = fastify
package/fastify.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const VERSION = '4.10.2'
3
+ const VERSION = '4.12.0'
4
4
 
5
5
  const Avvio = require('avvio')
6
6
  const http = require('http')
@@ -2,9 +2,7 @@
2
2
 
3
3
  const { AsyncResource } = require('async_hooks')
4
4
  const lru = require('tiny-lru').lru
5
- // TODO: find more perforamant solution
6
- const { parse: parseContentType } = require('content-type')
7
-
5
+ const { safeParse: safeParseContentType, defaultContentType } = require('fast-content-type-parse')
8
6
  const secureJson = require('secure-json-parse')
9
7
  const {
10
8
  kDefaultJsonParse,
@@ -70,6 +68,7 @@ ContentTypeParser.prototype.add = function (contentType, opts, parserFn) {
70
68
  if (contentTypeIsString) {
71
69
  this.parserList.unshift(new ParserListItem(contentType))
72
70
  } else {
71
+ contentType.isEssence = contentType.source.indexOf(';') === -1
73
72
  this.parserRegExpList.unshift(contentType)
74
73
  }
75
74
  this.customParsers.set(contentType.toString(), parser)
@@ -103,7 +102,7 @@ ContentTypeParser.prototype.getParser = function (contentType) {
103
102
 
104
103
  // dummyContentType always the same object
105
104
  // we can use === for the comparsion and return early
106
- if (parsed === dummyContentType) {
105
+ if (parsed === defaultContentType) {
107
106
  return this.customParsers.get('')
108
107
  }
109
108
 
@@ -307,6 +306,7 @@ function buildContentTypeParser (c) {
307
306
  contentTypeParser[kDefaultJsonParse] = c[kDefaultJsonParse]
308
307
  contentTypeParser.customParsers = new Map(c.customParsers.entries())
309
308
  contentTypeParser.parserList = c.parserList.slice()
309
+ contentTypeParser.parserRegExpList = c.parserRegExpList.slice()
310
310
  return contentTypeParser
311
311
  }
312
312
 
@@ -358,17 +358,6 @@ function removeAllContentTypeParsers () {
358
358
  this[kContentTypeParser].removeAll()
359
359
  }
360
360
 
361
- // dummy here to prevent repeated object creation
362
- const dummyContentType = { type: '', parameters: Object.create(null) }
363
-
364
- function safeParseContentType (contentType) {
365
- try {
366
- return parseContentType(contentType)
367
- } catch (err) {
368
- return dummyContentType
369
- }
370
- }
371
-
372
361
  function compareContentType (contentType, parserListItem) {
373
362
  if (parserListItem.isEssence) {
374
363
  // we do essence check
@@ -389,7 +378,7 @@ function compareContentType (contentType, parserListItem) {
389
378
  }
390
379
 
391
380
  function compareRegExpContentType (contentType, essenceMIMEType, regexp) {
392
- if (regexp.source.indexOf(';') === -1) {
381
+ if (regexp.isEssence) {
393
382
  // we do essence check
394
383
  return regexp.test(essenceMIMEType)
395
384
  } else {
@@ -5,6 +5,9 @@
5
5
 
6
6
 
7
7
 
8
+ // eslint-disable-next-line
9
+ const STR_ESCAPE = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/
10
+
8
11
  class Serializer {
9
12
  constructor (options = {}) {
10
13
  switch (options.rounding) {
@@ -99,6 +102,11 @@ class Serializer {
99
102
  str = str.toString()
100
103
  }
101
104
 
105
+ // Fast escape chars check
106
+ if (!STR_ESCAPE.test(str)) {
107
+ return quotes + str + quotes
108
+ }
109
+
102
110
  if (str.length < 42) {
103
111
  return this.asStringSmall(str)
104
112
  } else {
package/lib/route.js CHANGED
@@ -89,9 +89,11 @@ function buildRouting (options) {
89
89
  hasRoute,
90
90
  prepareRoute,
91
91
  getDefaultRoute: function () {
92
+ warning.emit('FSTDEP014')
92
93
  return router.defaultRoute
93
94
  },
94
95
  setDefaultRoute: function (defaultRoute) {
96
+ warning.emit('FSTDEP014')
95
97
  if (typeof defaultRoute !== 'function') {
96
98
  throw new FST_ERR_DEFAULT_ROUTE_INVALID_TYPE()
97
99
  }
package/lib/warnings.js CHANGED
@@ -25,4 +25,6 @@ warning.create('FastifyDeprecation', 'FSTDEP012', 'Request#context property acce
25
25
 
26
26
  warning.create('FastifyDeprecation', 'FSTDEP013', 'Direct return of "trailers" function is deprecated. Please use "callback" or "async-await" for return value. The support of direct return will removed in `fastify@5`.')
27
27
 
28
+ warning.create('FastifyDeprecation', 'FSTDEP014', 'You are trying to set/access the default route. This property is deprecated. Please, use setNotFoundHandler if you want to custom a 404 handler or the wildcard (*) to match all routes.')
29
+
28
30
  module.exports = warning
@@ -35,7 +35,13 @@ function wrapThenable (thenable, reply) {
35
35
  }
36
36
 
37
37
  reply[kReplyIsError] = true
38
- reply.send(err)
38
+
39
+ // try-catch allow to re-throw error in error handler for async handler
40
+ try {
41
+ reply.send(err)
42
+ } catch (err) {
43
+ reply.send(err)
44
+ }
39
45
  })
40
46
  }
41
47
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fastify",
3
- "version": "4.10.2",
3
+ "version": "4.12.0",
4
4
  "description": "Fast and low overhead web framework, for Node.js",
5
5
  "main": "fastify.js",
6
6
  "type": "commonjs",
@@ -154,7 +154,7 @@
154
154
  "json-schema-to-ts": "^2.5.5",
155
155
  "JSONStream": "^1.3.5",
156
156
  "license-checker": "^25.0.1",
157
- "markdownlint-cli2": "^0.5.1",
157
+ "markdownlint-cli2": "^0.6.0",
158
158
  "proxyquire": "^2.1.3",
159
159
  "pump": "^3.0.0",
160
160
  "self-cert": "^2.0.0",
@@ -164,7 +164,7 @@
164
164
  "split2": "^4.1.0",
165
165
  "standard": "^17.0.0",
166
166
  "tap": "^16.3.0",
167
- "tsd": "^0.24.1",
167
+ "tsd": "^0.25.0",
168
168
  "typescript": "^4.8.3",
169
169
  "undici": "^5.10.0",
170
170
  "vary": "^1.1.2",
@@ -176,7 +176,7 @@
176
176
  "@fastify/fast-json-stringify-compiler": "^4.1.0",
177
177
  "abstract-logging": "^2.0.1",
178
178
  "avvio": "^8.2.0",
179
- "content-type": "^1.0.4",
179
+ "fast-content-type-parse": "^1.0.0",
180
180
  "find-my-way": "^7.3.0",
181
181
  "light-my-request": "^5.6.1",
182
182
  "pino": "^8.5.0",
@@ -36,7 +36,7 @@ test('Should return 503 while closing - pipelining', async t => {
36
36
  await instance.close()
37
37
  })
38
38
 
39
- const isV19plus = semver.satisfies(process.version, '>= v19.0.0')
39
+ const isV19plus = semver.gte(process.version, '19.0.0')
40
40
  test('Should not return 503 while closing - pipelining - return503OnClosing: false, skip Node >= v19.x', { skip: isV19plus }, async t => {
41
41
  const fastify = Fastify({
42
42
  return503OnClosing: false,
@@ -203,7 +203,7 @@ test('Should return error while closing (callback) - injection', t => {
203
203
  })
204
204
  })
205
205
 
206
- const isV19plus = semver.satisfies(process.version, '>= v19.0.0')
206
+ const isV19plus = semver.gte(process.version, '19.0.0')
207
207
  t.test('Current opened connection should continue to work after closing and return "connection: close" header - return503OnClosing: false, skip Node >= v19.x', { skip: isV19plus }, t => {
208
208
  const fastify = Fastify({
209
209
  return503OnClosing: false,
@@ -609,3 +609,46 @@ test('content-type fail when parameters not match - regexp', async t => {
609
609
 
610
610
  t.same(response.statusCode, 415)
611
611
  })
612
+
613
+ // Refs: https://github.com/fastify/fastify/issues/4495
614
+ test('content-type regexp list should be cloned when plugin override', async t => {
615
+ t.plan(6)
616
+
617
+ const fastify = Fastify()
618
+
619
+ fastify.addContentTypeParser(/^image\/.*/, { parseAs: 'buffer' }, (req, payload, done) => {
620
+ done(null, payload)
621
+ })
622
+
623
+ fastify.register(function plugin (fastify, options, done) {
624
+ fastify.post('/', function (request, reply) {
625
+ reply.type(request.headers['content-type']).send(request.body)
626
+ })
627
+
628
+ done()
629
+ })
630
+
631
+ {
632
+ const { payload, headers, statusCode } = await fastify.inject({
633
+ method: 'POST',
634
+ path: '/',
635
+ payload: 'jpeg',
636
+ headers: { 'content-type': 'image/jpeg' }
637
+ })
638
+ t.same(statusCode, 200)
639
+ t.same(headers['content-type'], 'image/jpeg')
640
+ t.same(payload, 'jpeg')
641
+ }
642
+
643
+ {
644
+ const { payload, headers, statusCode } = await fastify.inject({
645
+ method: 'POST',
646
+ path: '/',
647
+ payload: 'png',
648
+ headers: { 'content-type': 'image/png' }
649
+ })
650
+ t.same(statusCode, 200)
651
+ t.same(headers['content-type'], 'image/png')
652
+ t.same(payload, 'png')
653
+ }
654
+ })
@@ -3,6 +3,51 @@
3
3
  const t = require('tap')
4
4
  const test = t.test
5
5
  const Fastify = require('..')
6
+ const warning = require('../lib/warnings')
7
+
8
+ // Silence the standard warning logs. We will test the messages explicitly.
9
+ process.removeAllListeners('warning')
10
+
11
+ test('setDefaultRoute should emit a deprecation warning', t => {
12
+ t.plan(2)
13
+
14
+ const fastify = Fastify()
15
+ const defaultRoute = (req, res) => {
16
+ res.end('hello from defaultRoute')
17
+ }
18
+
19
+ process.on('warning', onWarning)
20
+ function onWarning (warning) {
21
+ t.equal(warning.name, 'FastifyDeprecation')
22
+ t.equal(warning.code, 'FSTDEP014')
23
+ }
24
+
25
+ t.teardown(() => {
26
+ process.removeListener('warning', onWarning)
27
+ warning.emitted.set('FSTDEP014', false)
28
+ })
29
+
30
+ fastify.setDefaultRoute(defaultRoute)
31
+ })
32
+
33
+ test('getDefaultRoute should emit a deprecation warning', t => {
34
+ t.plan(2)
35
+
36
+ const fastify = Fastify()
37
+
38
+ process.on('warning', onWarning)
39
+ function onWarning (warning) {
40
+ t.equal(warning.name, 'FastifyDeprecation')
41
+ t.equal(warning.code, 'FSTDEP014')
42
+ }
43
+
44
+ t.teardown(() => {
45
+ process.removeListener('warning', onWarning)
46
+ warning.emitted.set('FSTDEP014', false)
47
+ })
48
+
49
+ fastify.getDefaultRoute()
50
+ })
6
51
 
7
52
  test('should fail if defaultRoute is not a function', t => {
8
53
  t.plan(1)
@@ -514,6 +514,34 @@ test('error thrown by custom error handler routes to default error handler', t =
514
514
  })
515
515
  })
516
516
 
517
+ // Refs: https://github.com/fastify/fastify/pull/4484#issuecomment-1367301750
518
+ test('allow re-thrown error to default error handler when route handler is async and error handler is sync', t => {
519
+ t.plan(4)
520
+ const fastify = Fastify()
521
+
522
+ fastify.setErrorHandler(function (error) {
523
+ t.equal(error.message, 'kaboom')
524
+ throw Error('kabong')
525
+ })
526
+
527
+ fastify.get('/', async function () {
528
+ throw Error('kaboom')
529
+ })
530
+
531
+ fastify.inject({
532
+ url: '/',
533
+ method: 'GET'
534
+ }, (err, res) => {
535
+ t.error(err)
536
+ t.equal(res.statusCode, 500)
537
+ t.same(JSON.parse(res.payload), {
538
+ error: statusCodes['500'],
539
+ message: 'kabong',
540
+ statusCode: 500
541
+ })
542
+ })
543
+ })
544
+
517
545
  // Issue 2078 https://github.com/fastify/fastify/issues/2078
518
546
  // Supported error code list: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
519
547
  const invalidErrorCodes = [
@@ -12,6 +12,7 @@ import { FastifyReply } from '../../types/reply'
12
12
  import { FastifyRequest } from '../../types/request'
13
13
  import { DefaultRoute } from '../../types/route'
14
14
  import { FastifySchemaControllerOptions, FastifySchemaCompiler, FastifySerializerCompiler } from '../../types/schema'
15
+ import { AddressInfo } from 'net'
15
16
 
16
17
  const server = fastify()
17
18
 
@@ -26,6 +27,7 @@ expectAssignable<FastifyInstance>(server.addSchema({
26
27
  }))
27
28
 
28
29
  expectType<Record<string, unknown>>(server.getSchemas())
30
+ expectType<AddressInfo[]>(server.addresses())
29
31
  expectType<unknown>(server.getSchema('SchemaId'))
30
32
  expectType<string>(server.printRoutes())
31
33
  expectType<string>(server.printPlugins())
@@ -123,6 +123,21 @@ const serverAutoInferredFileOption = fastify({
123
123
 
124
124
  expectType<FastifyBaseLogger>(serverAutoInferredFileOption.log)
125
125
 
126
+ const serverAutoInferredSerializerResponseObjectOption = fastify({
127
+ logger: {
128
+ serializers: {
129
+ res (ServerResponse) {
130
+ expectType<FastifyReply>(ServerResponse)
131
+ return {
132
+ status: '200'
133
+ }
134
+ }
135
+ }
136
+ }
137
+ })
138
+
139
+ expectType<FastifyBaseLogger>(serverAutoInferredSerializerResponseObjectOption.log)
140
+
126
141
  const serverAutoInferredSerializerObjectOption = fastify({
127
142
  logger: {
128
143
  serializers: {
@@ -101,3 +101,46 @@ expectAssignable<ServerWithTypeProvider>(serverWithTypeProvider.register(async (
101
101
  expectAssignable<ServerWithTypeProvider>(serverWithTypeProvider.register(async (instance: ServerWithTypeProvider) => {
102
102
  expectAssignable<ServerWithTypeProvider>(instance)
103
103
  }))
104
+
105
+ // With Type Provider and logger
106
+ const customLogger = {
107
+ level: 'info',
108
+ info: () => { },
109
+ warn: () => { },
110
+ error: () => { },
111
+ fatal: () => { },
112
+ trace: () => { },
113
+ debug: () => { },
114
+ child: () => customLogger,
115
+ silent: () => { }
116
+ }
117
+ const serverWithTypeProviderAndLogger = fastify({
118
+ logger: customLogger
119
+ }).withTypeProvider<TestTypeProvider>()
120
+ type ServerWithTypeProviderAndLogger = FastifyInstance<Server, IncomingMessage, ServerResponse, typeof customLogger, TestTypeProvider>
121
+ const testPluginWithTypeProviderAndLogger: FastifyPluginCallback<TestOptions, RawServerDefault, TestTypeProvider, typeof customLogger> = function (instance, opts, done) { }
122
+ const testPluginWithTypeProviderAndLoggerAsync: FastifyPluginAsync<TestOptions, RawServerDefault, TestTypeProvider, typeof customLogger> = async function (instance, opts) { }
123
+ const testPluginWithTypeProviderAndLoggerWithType = (instance: ServerWithTypeProviderAndLogger, opts: FastifyPluginOptions, done: (error?: FastifyError) => void) => { }
124
+ const testPluginWithTypeProviderAndLoggerWithTypeAsync = async (instance: ServerWithTypeProviderAndLogger, opts: FastifyPluginOptions) => { }
125
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginCallback))
126
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginAsync))
127
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginOpts))
128
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginOptsAsync))
129
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginOptsWithType))
130
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginOptsWithTypeAsync))
131
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginWithTypeProviderAndLogger))
132
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginWithTypeProviderAndLoggerAsync))
133
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginWithTypeProviderAndLoggerWithType))
134
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(testPluginWithTypeProviderAndLoggerWithTypeAsync))
135
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register((instance) => {
136
+ expectAssignable<FastifyInstance>(instance)
137
+ }))
138
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register((instance: ServerWithTypeProviderAndLogger) => {
139
+ expectAssignable<ServerWithTypeProviderAndLogger>(instance)
140
+ }))
141
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(async (instance) => {
142
+ expectAssignable<FastifyInstance>(instance)
143
+ }))
144
+ expectAssignable<ServerWithTypeProviderAndLogger>(serverWithTypeProviderAndLogger.register(async (instance: ServerWithTypeProviderAndLogger) => {
145
+ expectAssignable<ServerWithTypeProviderAndLogger>(instance)
146
+ }))
@@ -21,6 +21,7 @@ import {
21
21
  FastifyTypeProviderDefault
22
22
  } from './type-provider'
23
23
  import { ContextConfigDefault, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault } from './utils'
24
+ import { AddressInfo } from 'net'
24
25
 
25
26
  export interface PrintRoutesOptions {
26
27
  includeMeta?: boolean | (string | symbol)[]
@@ -92,6 +93,7 @@ export interface FastifyInstance<
92
93
  version: string;
93
94
  log: Logger;
94
95
 
96
+ addresses(): AddressInfo[]
95
97
  withTypeProvider<Provider extends FastifyTypeProvider>(): FastifyInstance<RawServer, RawRequest, RawReply, Logger, Provider>;
96
98
 
97
99
  addSchema(schema: unknown): FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>;
package/types/logger.d.ts CHANGED
@@ -60,7 +60,7 @@ export interface FastifyLoggerOptions<
60
60
  [key: string]: unknown;
61
61
  };
62
62
  res?: (res: RawReply) => {
63
- statusCode: string | number;
63
+ statusCode?: string | number;
64
64
  [key: string]: unknown;
65
65
  };
66
66
  };
package/types/plugin.d.ts CHANGED
@@ -10,8 +10,13 @@ export type FastifyPluginOptions = Record<string, any>
10
10
  *
11
11
  * Fastify allows the user to extend its functionalities with plugins. A plugin can be a set of routes, a server decorator or whatever. To activate plugins, use the `fastify.register()` method.
12
12
  */
13
- export type FastifyPluginCallback<Options extends FastifyPluginOptions = Record<never, never>, Server extends RawServerBase = RawServerDefault, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault> = (
14
- instance: FastifyInstance<Server, RawRequestDefaultExpression<Server>, RawReplyDefaultExpression<Server>, FastifyBaseLogger, TypeProvider>,
13
+ export type FastifyPluginCallback<
14
+ Options extends FastifyPluginOptions = Record<never, never>,
15
+ Server extends RawServerBase = RawServerDefault,
16
+ TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
17
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
18
+ > = (
19
+ instance: FastifyInstance<Server, RawRequestDefaultExpression<Server>, RawReplyDefaultExpression<Server>, Logger, TypeProvider>,
15
20
  opts: Options,
16
21
  done: (err?: Error) => void
17
22
  ) => void
@@ -25,8 +30,9 @@ export type FastifyPluginAsync<
25
30
  Options extends FastifyPluginOptions = Record<never, never>,
26
31
  Server extends RawServerBase = RawServerDefault,
27
32
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
33
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
28
34
  > = (
29
- instance: FastifyInstance<Server, RawRequestDefaultExpression<Server>, RawReplyDefaultExpression<Server>, FastifyBaseLogger, TypeProvider>,
35
+ instance: FastifyInstance<Server, RawRequestDefaultExpression<Server>, RawReplyDefaultExpression<Server>, Logger, TypeProvider>,
30
36
  opts: Options
31
37
  ) => Promise<void>;
32
38
 
@@ -2,7 +2,7 @@ import { FastifyPluginOptions, FastifyPluginCallback, FastifyPluginAsync } from
2
2
  import { LogLevel } from './logger'
3
3
  import { FastifyInstance } from './instance'
4
4
  import { RawServerBase } from './utils'
5
- import { FastifyTypeProvider, RawServerDefault } from '../fastify'
5
+ import { FastifyBaseLogger, FastifyTypeProvider, RawServerDefault } from '../fastify'
6
6
 
7
7
  export interface RegisterOptions {
8
8
  prefix?: string;
@@ -17,17 +17,17 @@ export type FastifyRegisterOptions<Options> = (RegisterOptions & Options) | ((in
17
17
  *
18
18
  * Function for adding a plugin to fastify. The options are inferred from the passed in FastifyPlugin parameter.
19
19
  */
20
- export interface FastifyRegister<T = void, RawServer extends RawServerBase = RawServerDefault, TypeProviderDefault extends FastifyTypeProvider = FastifyTypeProvider> {
21
- <Options extends FastifyPluginOptions, Server extends RawServerBase = RawServer, TypeProvider extends FastifyTypeProvider = TypeProviderDefault>(
22
- plugin: FastifyPluginCallback<Options, Server, TypeProvider>,
20
+ export interface FastifyRegister<T = void, RawServer extends RawServerBase = RawServerDefault, TypeProviderDefault extends FastifyTypeProvider = FastifyTypeProvider, LoggerDefault extends FastifyBaseLogger = FastifyBaseLogger> {
21
+ <Options extends FastifyPluginOptions, Server extends RawServerBase = RawServer, TypeProvider extends FastifyTypeProvider = TypeProviderDefault, Logger extends FastifyBaseLogger = LoggerDefault>(
22
+ plugin: FastifyPluginCallback<Options, Server, TypeProvider, Logger>,
23
23
  opts?: FastifyRegisterOptions<Options>
24
24
  ): T;
25
- <Options extends FastifyPluginOptions, Server extends RawServerBase = RawServer, TypeProvider extends FastifyTypeProvider = TypeProviderDefault>(
26
- plugin: FastifyPluginAsync<Options, Server, TypeProvider>,
25
+ <Options extends FastifyPluginOptions, Server extends RawServerBase = RawServer, TypeProvider extends FastifyTypeProvider = TypeProviderDefault, Logger extends FastifyBaseLogger = LoggerDefault>(
26
+ plugin: FastifyPluginAsync<Options, Server, TypeProvider, Logger>,
27
27
  opts?: FastifyRegisterOptions<Options>
28
28
  ): T;
29
- <Options extends FastifyPluginOptions, Server extends RawServerBase = RawServer, TypeProvider extends FastifyTypeProvider = TypeProviderDefault>(
30
- plugin: FastifyPluginCallback<Options, Server, TypeProvider> | FastifyPluginAsync<Options, Server, TypeProvider> | Promise<{ default: FastifyPluginCallback<Options, Server, TypeProvider> }> | Promise<{ default: FastifyPluginAsync<Options, Server, TypeProvider> }>,
29
+ <Options extends FastifyPluginOptions, Server extends RawServerBase = RawServer, TypeProvider extends FastifyTypeProvider = TypeProviderDefault, Logger extends FastifyBaseLogger = LoggerDefault>(
30
+ plugin: FastifyPluginCallback<Options, Server, TypeProvider, Logger> | FastifyPluginAsync<Options, Server, TypeProvider, Logger> | Promise<{ default: FastifyPluginCallback<Options, Server, TypeProvider, Logger> }> | Promise<{ default: FastifyPluginAsync<Options, Server, TypeProvider, Logger> }>,
31
31
  opts?: FastifyRegisterOptions<Options>
32
32
  ): T;
33
33
  }