import compression from 'compression' ; import express , { Express , RequestHandler } from 'express' ; import { PathParams } from 'express-serve-static-core' ; import { AppInvocationInfoResolver , SSRMiddleware , ssrMiddleware as defaultSSRMiddleware , } from './ssrMiddleware' ; import { getDefaultAppInvocationInfoResolver } from './defaultAppInvocationInfoResolver' ; export interface RenderingHostServerOptions { default port ? : number ; default hostname ? : string ; hooks ? : { beforeSSRMiddlewareRegistered ? : ( server : Express ) => void ; beforeStaticFileMiddlewareRegistered ? : ( server : Express ) => void ; beforeServerStarted ? : ( server : Express ) => void ; afterServerStarted ? : ( server : Express ) => void ; } ; ssrMiddleware ? : SSRMiddleware ; default ssrMiddlewarePath ? : PathParams ; appInvocationInfoResolver ? : AppInvocationInfoResolver ; middlewares : { compression ? : RequestHandler ; } ; enableCompression ? : boolean ; } param { RenderingHostServerOptions } config export function startRenderingHostServer ( { port = 0 , hostname = 'localhost' , hooks = { } , middlewares = { } , enableCompression = true , ssrMiddleware , ssrMiddlewarePath , appInvocationInfoResolver : customAppInvocationInfoResolver , } ) { const server = express ( ) ; if ( enableCompression ) { const compressionMiddleware = middlewares . compression && typeof middlewares . compression === 'function' ? middlewares . compression : compression ( ) ; server . use ( compressionMiddleware ) ; } const appInvocationInfoResolver = customAppInvocationInfoResolver || getDefaultAppInvocationInfoResolver ( { } ) ; const middleware = ssrMiddleware ? ssrMiddleware ( { appInvocationInfoResolver , } ) : defaultSSRMiddleware ( { appInvocationInfoResolver , } ) ; invokeHook ( hooks . beforeSSRMiddlewareRegistered , server ) ; server . post ( ssrMiddlewarePath || '*' , middleware ) ; invokeHook ( hooks . beforeStaticFileMiddlewareRegistered , server ) ; invokeHook ( hooks . beforeServerStarted , server ) ; server . listen ( port , hostname , ( err ? ) => { if ( err ) { console . error ( err ) ; return ; } console . log ( `Starting rendering host at ${ hostname }:${ port }` ) ; invokeHook ( hooks . afterServerStarted , server ) ; } ) ; } param { Function | undefined } hook param { ... unknown } args function invokeHook ( hook , ... args ) { if ( hook && typeof hook === 'function' ) { hook ( ... args ) ; } }