import * as _faasjs_func from '@faasjs/func'; import { IncomingMessage, ServerResponse, Server as Server$1 } from 'node:http'; import { Logger } from '@faasjs/logger'; type MiddlewareEvent = { body: any; raw: { request: IncomingMessage; response: ServerResponse; }; }; type MiddlewareContext = { logger: Logger; }; type Middleware = (request: IncomingMessage & { body?: any; }, response: ServerResponse, context: MiddlewareContext) => void | Promise; /** * Apply a middleware function to handle incoming requests. * * @param handler - The middleware function to handle the request and response. * @returns A function that processes the event and applies the middleware. * * @example * ```typescript * import { useMiddleware } from '@faasjs/server' * * export const func = useMiddleware((request, response, logger) => { * response.setHeader('X-Hello', 'World') * response.end('Hello, World!') * logger.info('Hello, World!') * }) * ``` */ declare function useMiddleware(handler: Middleware): Promise<_faasjs_func.Func>; /** * Apply an array of middleware functions to an event. * * @param {Middleware[]} handlers - An array of middleware functions to be applied. * @returns {Promise} A promise that resolves when all middleware functions have been applied. * * @example * ```typescript * import { useMiddlewares } from '@faasjs/server' * * export const func = useMiddlewares([ * (request, response) => { * if (request.url === '/hi') return * response.end('Hello, World!') * }, * (request, response) => { * if (request.url === '/hello') return * response.end('Hi, World!') * } * ]) * ``` */ declare function useMiddlewares(handlers: Middleware[]): Promise<_faasjs_func.Func>; type StaticHandlerOptions = { root: string; /** * Not found handler. * * If set to `true`, the middleware will respond with a default 404 status code. * If set to a string as a fallback path, the middleware will respond with the file at that path. * If set to a function, the middleware will call the function with the request, response, and logger. * If set to `false`, the middleware will do nothing. * * @default false */ notFound?: Middleware | boolean | string; /** * Cache static files. * If set to `true`, the middleware will cache static files. * If set to a string, the middleware will cache static files with the specified key. * If set to `false`, the middleware will not cache static files. * * @default true */ cache?: boolean | string; /** * Strip prefix from the URL. * * @example * ```typescript * import { useMiddleware, staticHandler } from '@faasjs/server' * * export const func = useMiddleware(staticHandler({ root: __dirname + '/public', stripPrefix: '/public' })) // /public/index.html -> /index.html * ``` */ stripPrefix?: string | RegExp; }; /** * Middleware to handle static file requests. * * @param {StaticHandlerOptions} options - Options for the static handler. * @returns {Middleware} The middleware function. * * The middleware resolves the requested URL to a file path within the specified root directory. * If the file exists, it reads the file content and sends it in the response. * If the file does not exist, it does nothing. * * @example * ```typescript * import { useMiddleware, staticHandler } from '@faasjs/server' * * export const func = useMiddleware(staticHandler({ root: __dirname + '/public' })) * ``` */ declare function staticHandler(options: StaticHandlerOptions): Middleware; type ServerHandlerOptions = { requestedAt?: number; filepath?: string; }; declare function getAll(): Server[]; declare function closeAll(): Promise; /** * Options for configuring the server. */ /** * Configuration options for the server. */ type ServerOptions = { /** * The port on which the server will listen. Defaults to `3000` if not provided. * * @default 3000 */ port?: number; /** * Callback function that is invoked when the server starts. * * This function is executed asynchronously and will not interrupt the server * if an error occurs during its execution. * * @param context - An object containing the logger instance. * * @example * ```typescript * const server = new Server(process.cwd(), { * onStart: async ({ logger }) => { * logger.info('Server started'); * } * }); * ``` */ onStart?: (context: { logger: Logger; }) => Promise; /** * Callback function that is invoked when an error occurs. * * This function is executed asynchronously and allows handling of errors * that occur during server operation. * * @param error - The error that occurred. * @param context - An object containing the logger instance. * * @example * ```typescript * const server = new Server(process.cwd(), { * onError: async (error, { logger }) => { * logger.error(error); * } * }); * ``` */ onError?: (error: Error, context: { logger: Logger; }) => Promise; /** * Callback function that is invoked when the server is closed. * * This function is executed asynchronously and can be used to perform * cleanup tasks or log server shutdown events. * * @param context - An object containing the logger instance. * * @example * ```typescript * const server = new Server(process.cwd(), { * onClose: async ({ logger }) => { * logger.info('Server closed'); * } * }); * ``` */ onClose?: (context: { logger: Logger; }) => Promise; /** * Callback function that is invoked before handling each request. * * This function is executed asynchronously before the main request handling logic. * It can be used for request preprocessing, authentication, logging, etc. * * @param req - The incoming HTTP request object. * @param res - The server response object. * * @example * ```typescript * const server = new Server(process.cwd(), { * beforeHandle: async (req, res) => { * console.log(`Processing ${req.method} request to ${req.url}`) * * if (req.method !== 'POST') * res.writeHead(405, { 'Allow': 'POST' }) // If you write response, it will finish the request * } * }); * ``` */ beforeHandle?: Middleware; }; /** * FaasJS Server. * * @param {string} root The root path of the server. * @param {ServerOptions} opts The options of the server. * @returns {Server} * @example * ```ts * import { Server } from '@faasjs/server' * * const server = new Server(process.cwd(), { * port: 8080, * }) * * server.listen() * ``` */ declare class Server { readonly root: string; readonly logger: Logger; readonly options: ServerOptions; protected closed: boolean; private activeRequests; private cachedFuncs; private onError; private server; private sockets; constructor(root: string, opts?: ServerOptions); handle(req: IncomingMessage, res: ServerResponse, options?: ServerHandlerOptions): Promise; /** * Start server. * @returns {Server} */ listen(): Server$1; /** * Close server. */ close(): Promise; /** * Middleware function to handle incoming HTTP requests. * * @param req - The incoming HTTP request object. * @param res - The server response object. * @param next - A callback function to pass control to the next middleware. * @returns A promise that resolves when the middleware processing is complete. */ middleware(req: IncomingMessage, res: ServerResponse, next: () => void): Promise; private getFilePath; private handleOptionRequest; } export { type Middleware, type MiddlewareContext, type MiddlewareEvent, Server, type ServerHandlerOptions, type ServerOptions, type StaticHandlerOptions, closeAll, getAll, staticHandler, useMiddleware, useMiddlewares };