import { Environment, ProcessedDatabucket, ServerEvents, ServerOptions } from '@mockoon/commons'; import type { RequestListener } from 'http'; import TypedEmitter from 'typed-emitter'; declare const MockoonServer_base: new () => TypedEmitter; /** * Create a server instance from an Environment object. * * Extends an EventEmitter. * * ⚠️ The function listenServerEvents must be used to listen to server events * and avoid the EventEmitter to throw errors due to the lack of listeners. * * Example: * * ``` * const server = new MockoonServer(environment); * const logger = createLoggerInstance(); * listenServerEvents(server, environment, logger, false); * * // or ate least listen to the error event * server.on('error', (errorCode, originalError) => {}); * ``` */ export declare class MockoonServer extends MockoonServer_base { private environment; private adminApiAuthToken; private adminApiAuthTokenIsAutoGenerated; private serverInstance; private webSocketServers; private tlsOptions; private processedDatabuckets; private requestNumbers; private globalVariables; private options; private transactionLogs; private effectiveRestRoutes; private effectiveWebSocketRoutes; private maxRequestBodySize; constructor(environment: Environment, options?: Partial); /** * Start a server */ start(): void; /** * Kill the server */ stop(): void; getAdminApiAuthToken(): string; isAdminApiEnabled(): boolean; isAdminApiAuthTokenAutoGenerated(): boolean; /** * Create a request listener */ createRequestListener(): RequestListener; /** * Return a processed databucket by name, id, or uuid * * @param identifier */ getProcessedDatabucket(identifier: string): ProcessedDatabucket | undefined; /** * Method that can be used to update the server's environment and * the disabled routes. * * It will recompute the effective route list to be used later during * request handling. * * @param environment */ updateEnvironment(environment: Environment): void; /** * Method to update the list of disabled routes without restarting the server. */ updateDisabledRoutes(disabledRoutes: string[]): void; /** * ### Middleware ### * Remove the Expect: 100-continue header. * Express will always respond with 100 Continue if the header is present. * * However, http-proxy-middleware hang (onProxyReq is not triggered) if the header is present. * See https://github.com/http-party/node-http-proxy/issues/1219 * A workaround would be to remove it and re-add it in the onProxyReq function, * but it's probably better to just remove it. * * @param request * @param response * @param next */ private removeExpectHeader; /** * ### Middleware ### * Emit the SERVER_ENTERING_REQUEST event * * @param request * @param response * @param next */ private emitEvent; /** * ### Middleware ### * Add global latency to the mock server * * @param request * @param response * @param next */ private delayResponse; /** * ### Middleware ### * Remove duplicate slashes in entering call paths * * @param request * @param response * @param next */ private deduplicateRequestSlashes; /** * Process the raw body and parse it if needed * * @param request * @param next * @param rawBody * @param requestContentType */ private processRawBody; /** * ### Middleware ### * Parse entering request body * * @param request * @param response * @param next */ private parseBody; /** * ### Middleware ### * Emit an event when response emit the 'close' event * * @param request * @param response * @param next */ private logRequest; /** * ### Middleware ### * Add environment headers & proxy headers to the response * * @param request * @param response * @param next */ private setResponseHeaders; /** * Create a wildcard REST route that will handle all HTTP routes * We do it this way to be able to support dynamic route additions / deletions * * Note on performances: the path matching is done at runtime using path-to-regexp. * We tested the overhead of not caching the matchers with up to 10 000 routes, and it is * negligible (some extra milliseconds). We will reevaluate if any performance issue arises. * * @param server - server on which attach routes */ private createRestRoutes; /** * Creates websocket routes from the given set of routes. * */ private createWebsocketRoutes; /** * Creates a single websocket route and adds it to the servers array. * * @param wsRoute */ private createWebsocketRoute; /** * Registers the upgrade event handler for WebSocket connections. * This is attached to the server instance only once. */ private registerWebSocketUpgradeHandler; private webSocketUpgradeHandler; /** * Creates a handler for a web socket connection received, if only any * of route is matched. * * @param webSocketServer * @param routeFor * @returns */ private createWebSocketConnectionHandler; /** * Derive final delivery content for websocket response. * * If no content is returned, that means the relevant content has been served, * or a failure has occurred. These scenarios can happen with file body type * and should be handled properly by the callers. * * @param socket * @param route * @param enabledRouteResponse * @param request * @param data */ private deriveFinalResponseContentForWebSockets; private handleBroadcastResponse; /** * Handle streaming websocket responses. * * @param socket * @param route * @param request * @param baseErrorMeta */ private handleOneToOneStreamingResponses; /** * Sends given response data to the socket client. * * @param client * @param content * @param errorMetaData */ private serveWsResponse; private routeHandler; private setRouteMetadataHeaders; private executeCallbacks; /** * Parse the body templating and send it as the response body * * @param routeResponse * @param request * @param response */ private serveBody; /** * Send a file as response body. * Revert to sendBody if file is not found. * * @param routeResponse * @param routeContentType * @param request * @param response */ private sendFile; /** * Always answer with status 200 to CORS pre flight OPTIONS requests if option activated. * /!\ Must be called after the routes creation otherwise it will intercept all user defined OPTIONS routes. * * @param server - express instance */ private setCors; /** * Add catch-all proxy if enabled. * Restream the body to the proxied API because it already has been * intercepted by the body parser. * * @param server - server on which to launch the proxy */ private enableProxy; /** * ### Middleware ### * Catch all error handler * http://expressjs.com/en/guide/error-handling.html#catching-errors * * @param server - server on which to log the response */ private errorHandler; /** * Set the provided headers on the target. Use different headers accessors * depending on the type of target: * express.Response/http.OutgoingMessage/http.IncomingMessage * Use the source in the template parsing of each header value. * * @param headers * @param target * @param request */ private setHeaders; /** * If header already has a value, concatenate the values into an array * * @param currentValue * @param newValue * @returns */ private appendHeaderValue; /** * Verify a header validity and parse its content, if templating is used * * @param header * @param request * @returns */ private parseHeader; /** * Send an error with text/plain content type, the provided message and status code. * Status is optional. No status will default to the one defined by the user, allowing for maximum customization. * * @param response * @param errorMessage * @param status */ private sendError; /** * Emit callback invoked event. * * @param res * @param callback * @param url * @param requestBody * @param requestHeaders */ private emitCallbackInvoked; /** * Fetch the updated route as some parameters can be applied without a restart (latency, headers, etc) * * @param routeUUID */ private getRefreshedRoute; /** * Build the secure context options * - if custom cert are provided load them * - if not, use default TLS cert (self-signed) * * @returns */ private buildTLSOptions; /** * Emit an event with the processed databuckets. * Remove the value from the processed databuckets to avoid sending * too much data to the client. */ private emitProcessedDatabuckets; /** * Set response properties from the locals object. * Currently supports the statusCode that can be set using templating helper. * * @param response */ private applyResponseLocals; /** * Parse file paths and prevent path traversal * * If the path is absolute, it must stay within its original static base * (before the first {{...}}) * If the path is relative, it must stay within the environment base directory * * @param filePath * @param request * @returns */ private getSafeFilePath; /** * List the routes from the environment, folders and disabled routes */ private computeEffectiveRestRoutes; /** * List the WebSocket routes from the environment, folders and disabled routes * * @returns */ private computeEffectiveWebSocketRoutes; /** * Regenerates WebSocket routes by detecting changes and stopping/starting servers accordingly. * * @param previousWsRoutes Previous set of WebSocket routes * @param newWsRoutes New set of WebSocket routes */ private regenerateWebSocketRoutes; /** * Close the WebSocket server associated with the provided route. * Also, close all client connections as close() does not do it by default * * @param route */ private closeWsServer; /** * Close all WebSocket servers and client connections. Used when stopping the server or when * all WebSocket routes are deleted. */ private closeWsServers; } export {};