UNPKG

13.7 kBTypeScriptView Raw
1import * as http from 'http'
2import * as http2 from 'http2'
3import * as https from 'https'
4import { Socket } from 'net'
5
6import { Options as AjvOptions, ValidatorFactory } from '@fastify/ajv-compiler'
7import { FastifyError } from '@fastify/error'
8import { Options as FJSOptions, SerializerFactory } from '@fastify/fast-json-stringify-compiler'
9import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
10import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
11
12import { FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction } from './types/content-type-parser'
13import { FastifyRequestContext, FastifyContextConfig, FastifyReplyContext } from './types/context'
14import { FastifyErrorCodes } from './types/errors'
15import { DoneFuncWithErrOrRes, HookHandlerDoneFunction, RequestPayload, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onListenAsyncHookHandler, onListenHookHandler, onRegisterHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler, onRequestAbortHookHandler, onRequestAbortAsyncHookHandler, preCloseAsyncHookHandler, preCloseHookHandler } from './types/hooks'
16import { FastifyListenOptions, FastifyInstance, PrintRoutesOptions } from './types/instance'
17import { FastifyBaseLogger, FastifyLoggerInstance, FastifyLoggerOptions, PinoLoggerOptions, FastifyLogFn, LogLevel } from './types/logger'
18import { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
19import { FastifyRegister, FastifyRegisterOptions, RegisterOptions } from './types/register'
20import { FastifyReply } from './types/reply'
21import { FastifyRequest, RequestGenericInterface } from './types/request'
22import { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface } from './types/route'
23import { FastifySchema, FastifySchemaCompiler, FastifySchemaValidationError, SchemaErrorDataVar, SchemaErrorFormatter } from './types/schema'
24import { FastifyServerFactory, FastifyServerFactoryHandler } from './types/serverFactory'
25import { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
26import { HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault } from './types/utils'
27
28declare module '@fastify/error' {
29 interface FastifyError {
30 validationContext?: SchemaErrorDataVar;
31 validation?: FastifySchemaValidationError[];
32 }
33}
34
35type Fastify = typeof fastify
36
37declare 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 export type FastifyHttpOptions<
65 Server extends http.Server,
66 Logger extends FastifyBaseLogger = FastifyBaseLogger
67 > = FastifyServerOptions<Server, Logger> & {
68 http?: http.ServerOptions | null
69 }
70
71 type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
72
73 export interface ConnectionError extends Error {
74 code: string,
75 bytesParsed: number,
76 rawPacket: {
77 type: string,
78 data: number[]
79 }
80 }
81
82 type TrustProxyFunction = (address: string, hop: number) => boolean
83
84 /**
85 * Options for a fastify server instance. Utilizes conditional logic on the generic server parameter to enforce certain https and http2
86 */
87 export type FastifyServerOptions<
88 RawServer extends RawServerBase = RawServerDefault,
89 Logger extends FastifyBaseLogger = FastifyBaseLogger
90 > = {
91 ignoreTrailingSlash?: boolean,
92 ignoreDuplicateSlashes?: boolean,
93 connectionTimeout?: number,
94 keepAliveTimeout?: number,
95 maxRequestsPerSocket?: number,
96 forceCloseConnections?: boolean | 'idle',
97 requestTimeout?: number,
98 pluginTimeout?: number,
99 bodyLimit?: number,
100 maxParamLength?: number,
101 disableRequestLogging?: boolean,
102 exposeHeadRoutes?: boolean,
103 onProtoPoisoning?: ProtoAction,
104 onConstructorPoisoning?: ConstructorAction,
105 logger?: boolean | FastifyLoggerOptions<RawServer> & PinoLoggerOptions | Logger,
106 serializerOpts?: FJSOptions | Record<string, unknown>,
107 serverFactory?: FastifyServerFactory<RawServer>,
108 caseSensitive?: boolean,
109 allowUnsafeRegex?: boolean,
110 requestIdHeader?: string | false,
111 requestIdLogLabel?: string;
112 useSemicolonDelimiter?: boolean,
113 jsonShorthand?: boolean;
114 genReqId?: (req: RawRequestDefaultExpression<RawServer>) => string,
115 trustProxy?: boolean | string | string[] | number | TrustProxyFunction,
116 querystringParser?: (str: string) => { [key: string]: unknown },
117 /**
118 * @deprecated Prefer using the `constraints.version` property
119 */
120 versioning?: {
121 storage(): {
122 get(version: string): string | null,
123 set(version: string, store: Function): void
124 del(version: string): void,
125 empty(): void
126 },
127 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?
128 },
129 constraints?: {
130 [name: string]: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>,
131 },
132 schemaController?: {
133 bucket?: (parentSchemas?: unknown) => {
134 add(schema: unknown): FastifyInstance;
135 getSchema(schemaId: string): unknown;
136 getSchemas(): Record<string, unknown>;
137 };
138 compilersFactory?: {
139 buildValidator?: ValidatorFactory;
140 buildSerializer?: SerializerFactory;
141 };
142 };
143 return503OnClosing?: boolean,
144 ajv?: {
145 customOptions?: AjvOptions,
146 plugins?: (Function | [Function, unknown])[]
147 },
148 frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema>(
149 error: FastifyError,
150 req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>,
151 res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, RequestGeneric, FastifyContextConfig, SchemaCompiler, TypeProvider>
152 ) => void,
153 rewriteUrl?: (
154 // The RawRequestDefaultExpression, RawReplyDefaultExpression, and FastifyTypeProviderDefault parameters
155 // should be narrowed further but those generic parameters are not passed to this FastifyServerOptions type
156 this: FastifyInstance<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, Logger, FastifyTypeProviderDefault>,
157 req: RawRequestDefaultExpression<RawServer>
158 ) => string,
159 schemaErrorFormatter?: SchemaErrorFormatter,
160 /**
161 * listener to error events emitted by client connections
162 */
163 clientErrorHandler?: (error: ConnectionError, socket: Socket) => void,
164 }
165
166 /**
167 * @deprecated use {@link FastifySchemaValidationError}
168 */
169 export type ValidationResult = FastifySchemaValidationError;
170
171 /* Export additional types */
172 export type {
173 LightMyRequestChain, InjectOptions, LightMyRequestResponse, LightMyRequestCallback, // 'light-my-request'
174 FastifyRequest, RequestGenericInterface, // './types/request'
175 FastifyReply, // './types/reply'
176 FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin, // './types/plugin'
177 FastifyListenOptions, FastifyInstance, PrintRoutesOptions, // './types/instance'
178 FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel, // './types/logger'
179 FastifyRequestContext, FastifyContextConfig, FastifyReplyContext, // './types/context'
180 RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface, // './types/route'
181 FastifyRegister, FastifyRegisterOptions, RegisterOptions, // './types/register'
182 FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction, // './types/content-type-parser'
183 FastifyError, // '@fastify/error'
184 FastifySchema, FastifySchemaCompiler, // './types/schema'
185 HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault, // './types/utils'
186 DoneFuncWithErrOrRes, HookHandlerDoneFunction, RequestPayload, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onListenAsyncHookHandler, onListenHookHandler, onRegisterHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler, onRequestAbortHookHandler, onRequestAbortAsyncHookHandler, preCloseAsyncHookHandler, preCloseHookHandler, // './types/hooks'
187 FastifyServerFactory, FastifyServerFactoryHandler, // './types/serverFactory'
188 FastifyTypeProvider, FastifyTypeProviderDefault, // './types/type-provider'
189 FastifyErrorCodes, // './types/errors'
190 }
191 // named export
192 // import { plugin } from 'plugin'
193 // const { plugin } = require('plugin')
194 export const fastify: Fastify
195 // default export
196 // import plugin from 'plugin'
197 export { fastify as default }
198}
199
200/**
201 * Fastify factory function for the standard fastify http, https, or http2 server instance.
202 *
203 * The default function utilizes http
204 *
205 * @param opts Fastify server options
206 * @returns Fastify server instance
207 */
208declare function fastify<
209 Server extends http2.Http2SecureServer,
210 Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
211 Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
212 Logger extends FastifyBaseLogger = FastifyBaseLogger,
213 TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
214>(opts: fastify.FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
215
216declare function fastify<
217 Server extends http2.Http2Server,
218 Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
219 Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
220 Logger extends FastifyBaseLogger = FastifyBaseLogger,
221 TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
222>(opts: fastify.FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
223
224declare function fastify<
225 Server extends https.Server,
226 Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
227 Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
228 Logger extends FastifyBaseLogger = FastifyBaseLogger,
229 TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
230>(opts: fastify.FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
231
232declare function fastify<
233 Server extends http.Server,
234 Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
235 Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
236 Logger extends FastifyBaseLogger = FastifyBaseLogger,
237 TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
238>(opts?: fastify.FastifyHttpOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
239
240// CJS export
241// const fastify = require('fastify')
242export = fastify
243
\No newline at end of file