/* eslint no-unused-vars: 0 */ /* eslint no-undef: 0 */ /* eslint space-infix-ops: 0 */ /// import * as ajv from 'ajv' import * as http from 'http' import * as http2 from 'http2' import * as https from 'https' import * as LightMyRequest from 'light-my-request' declare function fastify< HttpServer extends (http.Server | http2.Http2Server) = http.Server, HttpRequest extends (http.IncomingMessage | http2.Http2ServerRequest) = http.IncomingMessage, HttpResponse extends (http.ServerResponse | http2.Http2ServerResponse) = http.ServerResponse >(opts?: fastify.ServerOptions): fastify.FastifyInstance; declare function fastify(opts?: fastify.ServerOptionsAsHttp): fastify.FastifyInstance; declare function fastify(opts?: fastify.ServerOptionsAsSecureHttp): fastify.FastifyInstance; declare function fastify(opts?: fastify.ServerOptionsAsHttp2): fastify.FastifyInstance; declare function fastify(opts?: fastify.ServerOptionsAsSecureHttp2): fastify.FastifyInstance; // eslint-disable-next-line no-redeclare declare namespace fastify { type Plugin = PluginInstance extends () => Promise ? ((instance: FastifyInstance< HttpServer, HttpRequest, HttpResponse >, options: Options) => Promise) : (instance: FastifyInstance, options: Options, callback: (err?: FastifyError) => void) => void; type Middleware < HttpServer, HttpRequest, HttpResponse > = (this: FastifyInstance, req: HttpRequest, res: HttpResponse, callback: (err?: FastifyError) => void) => void type DefaultQuery = { [k: string]: any } type DefaultParams = { [k: string]: any } type DefaultHeaders = { [k: string]: any } type DefaultBody = any type HTTPMethod = 'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' | 'OPTIONS' // // Keep the original name of the interfaces to avoid braking change interface HTTPInjectOptions extends LightMyRequest.InjectOptions {} interface HTTPInjectResponse extends LightMyRequest.Response {} interface ValidationResult { keyword: string; dataPath: string; schemaPath: string; params: { [type: string]: string; }, message: string; } /** * Fastify custom error */ interface FastifyError extends Error { statusCode?: number; /** * Validation errors */ validation?: Array; } interface Logger { fatal(msg: string, ...args: any[]): void; fatal(obj: {}, msg?: string, ...args: any[]): void; error(msg: string, ...args: any[]): void; error(obj: {}, msg?: string, ...args: any[]): void; warn(msg: string, ...args: any[]): void; warn(obj: {}, msg?: string, ...args: any[]): void; info(msg: string, ...args: any[]): void; info(obj: {}, msg?: string, ...args: any[]): void; debug(msg: string, ...args: any[]): void; debug(obj: {}, msg?: string, ...args: any[]): void; trace(msg: string, ...args: any[]): void; trace(obj: {}, msg?: string, ...args: any[]): void; } type FastifyMiddleware< HttpServer = http.Server, HttpRequest = http.IncomingMessage, HttpResponse = http.ServerResponse, Query = DefaultQuery, Params = DefaultParams, Headers = DefaultHeaders, Body = DefaultBody > = ( this: FastifyInstance, req: FastifyRequest, reply: FastifyReply, done: (err?: Error) => void, ) => void | Promise type FastifyMiddlewareWithPayload< HttpServer = http.Server, HttpRequest = http.IncomingMessage, HttpResponse = http.ServerResponse, Query = DefaultQuery, Params = DefaultParams, Headers = DefaultHeaders, Body = DefaultBody > = ( this: FastifyInstance, req: FastifyRequest, reply: FastifyReply, payload: any, done: (err?: Error, value?: any) => void, ) => void | Promise type RequestHandler< HttpRequest = http.IncomingMessage, HttpResponse = http.ServerResponse, Query = DefaultQuery, Params = DefaultParams, Headers = DefaultHeaders, Body = DefaultBody > = ( this: FastifyInstance, request: FastifyRequest, reply: FastifyReply, ) => void | Promise type SchemaCompiler = (schema: Object) => Function type SchemaResolver = (ref: string) => Object type BodyParser = | ((req: HttpRequest, rawBody: RawBody, done: (err: Error | null, body?: any) => void) => void) | ((req: HttpRequest, rawBody: RawBody) => Promise) type ContentTypeParser = | ((req: HttpRequest, done: (err: Error | null, body?: any) => void) => void) | ((req: HttpRequest) => Promise) interface FastifyContext { config: any } /** * fastify's wrapped version of node.js IncomingMessage */ interface FastifyRequest< HttpRequest = http.IncomingMessage, Query = DefaultQuery, Params = DefaultParams, Headers = DefaultHeaders, Body = DefaultBody > { query: Query params: Params headers: Headers body: Body id: any ip: string ips: string[] hostname: string raw: HttpRequest req: HttpRequest log: Logger } /** * Response object that is used to build and send a http response */ interface FastifyReply { code(statusCode: number): FastifyReply status(statusCode: number): FastifyReply header(name: string, value: any): FastifyReply headers(headers: { [key: string]: any }): FastifyReply getHeader(name: string): string | undefined hasHeader(name: string): boolean removeHeader(name: string): FastifyReply callNotFound(): void getResponseTime(): number type(contentType: string): FastifyReply redirect(url: string): FastifyReply redirect(statusCode: number, url: string): FastifyReply serialize(payload: any): string serializer(fn: Function): FastifyReply send(payload?: T): FastifyReply sent: boolean res: HttpResponse context: FastifyContext request: FastifyRequest } type TrustProxyFunction = (addr: string, index: number) => boolean type ServerFactoryHandlerFunction = (request: http.IncomingMessage | http2.Http2ServerRequest, response: http.ServerResponse | http2.Http2ServerResponse) => void type ServerFactoryFunction = (handler: ServerFactoryHandlerFunction, options: ServerOptions) => http.Server | http2.Http2Server interface ServerOptions { caseSensitive?: boolean, ignoreTrailingSlash?: boolean, bodyLimit?: number, pluginTimeout?: number, disableRequestLogging?: boolean, onProtoPoisoning?: 'error' | 'remove' | 'ignore', onConstructorPoisoning?: 'error' | 'remove' | 'ignore', logger?: any, trustProxy?: string | number | boolean | Array | TrustProxyFunction, maxParamLength?: number, querystringParser?: (str: string) => { [key: string]: string | string[] }, versioning? : { storage() : { get(version: String) : Function | null, set(version: String, store: Function) : void, del(version: String) : void, empty() : void }, deriveVersion(req: Object, ctx?: Context) : String, }, modifyCoreObjects?: boolean, return503OnClosing?: boolean, genReqId?: (req: FastifyRequest) => number | string, requestIdHeader?: string, requestIdLogLabel?: string, serverFactory?: ServerFactoryFunction, ajv?: { customOptions?: ajv.Options, plugins?: Array|String> } } interface ServerOptionsAsSecure extends ServerOptions { https: http2.SecureServerOptions } interface ServerOptionsAsHttp extends ServerOptions { http2?: false } interface ServerOptionsAsSecureHttp extends ServerOptionsAsHttp, ServerOptionsAsSecure {} interface ServerOptionsAsHttp2 extends ServerOptions { http2: true } interface ServerOptionsAsSecureHttp2 extends ServerOptionsAsHttp2, ServerOptionsAsSecure {} // TODO - define/import JSONSchema types type JSONSchema = Object interface RouteSchema { body?: JSONSchema querystring?: JSONSchema params?: JSONSchema headers?: JSONSchema response?: { [code: number]: JSONSchema, [code: string]: JSONSchema } } /** * Optional configuration parameters for the route being created */ interface RouteShorthandOptions< HttpServer = http.Server, HttpRequest = http.IncomingMessage, HttpResponse = http.ServerResponse, Query = DefaultQuery, Params = DefaultParams, Headers = DefaultHeaders, Body = DefaultBody > { schema?: RouteSchema attachValidation?: boolean onSend?: | FastifyMiddlewareWithPayload | Array> onRequest?: | FastifyMiddleware | Array> onResponse?: | FastifyMiddleware | Array> preParsing?: | FastifyMiddleware | Array> preValidation?: | FastifyMiddleware | Array> preHandler?: | FastifyMiddleware | Array> preSerialization?: FastifyMiddlewareWithPayload | Array> handler?: RequestHandler schemaCompiler?: SchemaCompiler bodyLimit?: number logLevel?: string logSerializers?: Object config?: any version?: string prefixTrailingSlash?: 'slash' | 'no-slash' | 'both' } /** * Route configuration options such as "url" and "method" */ interface RouteOptions< HttpServer = http.Server, HttpRequest = http.IncomingMessage, HttpResponse = http.ServerResponse, Query = DefaultQuery, Params = DefaultParams, Headers = DefaultHeaders, Body = DefaultBody > extends RouteShorthandOptions { method: HTTPMethod | HTTPMethod[] url: string handler: RequestHandler } /** * Register options */ interface RegisterOptions { [key: string]: any, prefix?: string, logSerializers?: Object } /** * Server listen options */ interface ListenOptions { port?: number; host?: string; backlog?: number; path?: string; exclusive?: boolean; readableAll?: boolean; writableAll?: boolean; /** * @default false */ ipv6Only?: boolean; } /** * Represents the fastify instance created by the factory function the module exports. */ interface FastifyInstance { server: HttpServer log: Logger schemaCompiler: SchemaCompiler /** * Adds a route to the server */ route( opts: RouteOptions, ): FastifyInstance /** * Defines a GET route with the given mount path, options, and handler */ get( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a GET route with the given mount path and handler */ get( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a PUT route with the given mount path, options, and handler */ put( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a PUT route with the given mount path and handler */ put( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a PATCH route with the given mount path, options, and handler */ patch( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a PATCH route with the given mount path and handler */ patch( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a POST route with the given mount path, options, and handler */ post( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a POST route with the given mount path and handler */ post( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a HEAD route with the given mount path, options, and handler */ head( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a HEAD route with the given mount path and handler */ head( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a DELETE route with the given mount path, options, and handler */ delete( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a DELETE route with the given mount path and handler */ delete( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a OPTIONS route with the given mount path, options, and handler */ options( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a OPTIONS route with the given mount path and handler */ options( url: string, handler: RequestHandler, ): FastifyInstance /** * Defines a route for all the supported methods with the given mount path, options, and handler */ all( url: string, opts: RouteShorthandOptions, handler?: RequestHandler, ): FastifyInstance /** * Defines a route for all the supported methods with the given mount path and handler */ all( url: string, handler: RequestHandler, ): FastifyInstance /** * Starts the server on the given port after all the plugins are loaded, * internally waits for the .ready() event. The callback is the same as the * Node core. */ listen(callback: (err: Error, address: string) => void): void listen(port: number, callback: (err: Error, address: string) => void): void listen(port: number, address: string, callback: (err: Error, address: string) => void): void listen(port: number, address: string, backlog: number, callback: (err: Error, address: string) => void): void listen(options: ListenOptions, callback: (err: Error, address: string) => void): void listen(sockFile: string, callback: (err: Error, address: string) => void): void listen(port: number, address?: string, backlog?: number): Promise listen(sockFile: string): Promise listen(options: ListenOptions): Promise /** * Registers a listener function that is invoked when all the plugins have * been loaded. It receives an error parameter if something went wrong. */ ready(): Promise> ready(readyListener: (err: Error) => void): void ready(readyListener: (err: Error, done: Function) => void): void ready(readyListener: (err: Error, context: FastifyInstance, done: Function) => void): void /** * Call this function to close the server instance and run the "onClose" callback */ close(closeListener: () => void): void close(): Promise /** * Apply the given middleware to all incoming requests */ use(middleware: Middleware): void /** * Apply the given middleware to routes matching the given path */ use(path: string, middleware: Middleware): void /** * Apply the given middleware to routes matching the given multiple path */ use(path: string[], middleware: Middleware): void /** * Registers a plugin */ register, PluginInstance extends Function>(plugin: Plugin, options?: Options): FastifyInstance /** * `Register a callback that will be executed just after a register. * It can take up to three parameters */ after(afterListener: (err: Error) => void): void after(afterListener: (err: Error, done: Function) => void): void after(afterListener: (err: Error, context: FastifyInstance, done: Function) => void): void /** * Decorate this fastify instance with new properties. Throws an execption if * you attempt to add the same decorator name twice */ decorate(name: string, decoration: any, dependencies?: Array): FastifyInstance /** * Decorate reply objects with new properties. Throws an execption if * you attempt to add the same decorator name twice */ decorateReply(name: string, decoration: any, dependencies?: Array): FastifyInstance /** * Decorate request objects with new properties. Throws an execption if * you attempt to add the same decorator name twice */ decorateRequest(name: string, decoration: any, dependencies?: Array): FastifyInstance /** * Determines if the given named decorator is available */ hasDecorator(name: string): boolean /** * Determines if the given named request decorator is available */ hasRequestDecorator(name: string): boolean /** * Determines if the given named reply decorator is available */ hasReplyDecorator(name: string): boolean /** * Add a hook that is triggered when a request is initially received */ addHook(name: 'onRequest', hook: FastifyMiddleware): FastifyInstance /** * Add a hook that is triggered after the onRequest hook and middlewares, but before body parsing */ addHook(name: 'preParsing', hook: FastifyMiddleware): FastifyInstance /** * Add a hook that is triggered after the onRequest, middlewares, and body parsing, but before the validation */ addHook(name: 'preValidation', hook: FastifyMiddleware): FastifyInstance /** * Hook that is fired after a request is processed, but before the response is serialized * hook */ addHook(name: 'preSerialization', hook: FastifyMiddlewareWithPayload): FastifyInstance /** * Hook that is fired before a request is processed, but after the "preValidation" * hook */ addHook(name: 'preHandler', hook: FastifyMiddleware): FastifyInstance /** * Hook that is fired after a request is processed, but before the "onResponse" * hook */ addHook(name: 'onSend', hook: (this: FastifyInstance, req: FastifyRequest, reply: FastifyReply, payload: any, done: (err?: Error, value?: any) => void) => void): FastifyInstance /** * Hook that is fired if `reply.send` is invoked with an Error */ addHook(name: 'onError', hook: (this: FastifyInstance, req: FastifyRequest, reply: FastifyReply, error: FastifyError, done: () => void) => void): FastifyInstance /** * Hook that is called when a response is about to be sent to a client */ addHook(name: 'onResponse', hook: FastifyMiddleware): FastifyInstance /** * Adds a hook that is triggered when server.close is called. Useful for closing connections * and performing cleanup tasks */ addHook(name: 'onClose', hook: (instance: FastifyInstance, done: () => void) => void): FastifyInstance /** * Adds a hook that is triggered when a new route is registered. Listeners are passed a * routeOptions object as the sole parameter. * The interface is synchronous, and, as such, the listeners do not get passed a callback. */ addHook(name: 'onRoute', hook: (opts: RouteOptions & { path: string, prefix: string }) => void): FastifyInstance /** * Adds a hook that is triggered when Fastify a new plugin is being registered. * This hook can be useful if you are developing a plugin that needs to use the encapsulation functionality of Fastify. * The interface is synchronous, and, as such, the listeners do not get passed a callback. */ addHook(name: 'onRegister', hook: (instance: FastifyInstance) => void): FastifyInstance /** * Useful for testing http requests without running a sever */ inject(opts: HTTPInjectOptions | string, cb: (err: Error, res: HTTPInjectResponse) => void): void /** * Useful for testing http requests without running a sever */ inject(opts: HTTPInjectOptions | string): Promise /** * Useful for testing http requests without running a sever */ inject(): LightMyRequest.Chain; /** * Set the 404 handler */ setNotFoundHandler(handler: (this: FastifyInstance, request: FastifyRequest, reply: FastifyReply) => void): void /** * Set a function that will be called whenever an error happens */ setErrorHandler(handler: (error: E, request: FastifyRequest, reply: FastifyReply) => void): void /** * Set a function that will be called whenever an error happens */ setReplySerializer(handler: (payload: string | object | Buffer | NodeJS.ReadableStream, statusCode: number) => string): void /** * Set the schema compiler for all routes. */ setSchemaCompiler(schemaCompiler: SchemaCompiler): FastifyInstance /** * Set the schema resolver to find the `$ref` schema object */ setSchemaResolver(schemaResolver: SchemaResolver): FastifyInstance /** * Create a shared schema */ addSchema(schema: object): FastifyInstance /** * Get all shared schemas */ getSchemas(): {[shemaId: string]: Object} /** * Add a content type parser */ addContentTypeParser(contentType: string | string[], opts: { bodyLimit?: number }, parser: ContentTypeParser): void addContentTypeParser(contentType: string | string[], opts: { parseAs: 'string'; bodyLimit?: number }, parser: BodyParser): void addContentTypeParser(contentType: string | string[], opts: { parseAs: 'buffer'; bodyLimit?: number }, parser: BodyParser): void addContentTypeParser(contentType: string | string[], parser: ContentTypeParser): void /** * Check if a parser for the specified content type exists */ hasContentTypeParser(contentType: string): boolean; /** * Prints the representation of the internal radix tree used by the router */ printRoutes(): string } } export = fastify;