import VM from 'vm' ; import { Window } from 'happy-dom' ; import HappyDOMServerRenderer from '../renderer/HappyDOMServerRenderer' ; import HappyDOMServerRenderResult from '../renderer/HappyDOMServerRenderResult' ; /**
 * This class is used for rendering a script server side.
 */ export default class HappyDOMContext { private window : Window = new Window ( ) ; param options param options . html param options . scripts param options . url param options . customElements param options . customElements . openShadowRoots param options . customElements . extractCSS param options . customElements . scopeCSS param options . customElements . applyCSSToHead param options . evaluateScripts param options . customElements . addCSSToHead returns public async render ( { html = null , scripts = null , url = null , evaluateScripts = false , customElements = { openShadowRoots : false , extractCSS : false , scopeCSS : false , addCSSToHead : false } } ) { return new Promise ( ( resolve , reject ) => { VM . createContext ( this . window ) ; VM . runInContext ( 'window.Function = (() => {}).constructor;' , this . window ) ; const window = this . window ; const document = this . window . document ; const renderer = new HappyDOMServerRenderer ( { openShadowRoots : customElements . openShadowRoots , extractCSS : customElements . extractCSS || customElements . addCSSToHead , scopeCSS : customElements . scopeCSS } ) ; if ( ! evaluateScripts ) { global . eval = ( ) => { } ; } window . happyDOM . whenAsyncComplete ( ) . then ( ( ) => { if ( customElements . addCSSToHead ) { resolve ( this . getResultWithCssAddedToHead ( renderer . render ( document ) ) ) ; } else { resolve ( renderer . render ( document ) ) ; } } ) . catch ( reject ) ; if ( url ) { window . location . href = url ; } if ( scripts ) { for ( const script of scripts ) { script . runInContext ( this . window ) ; } } document . open ( ) ; document . write ( html ) ; document . close ( ) ; } ) ; } /**
     * Disposes the render.
     */ public dispose ( ) { this . window . happyDOM . cancelAsync ( ) ; } param result returns private getResultWithCssAddedToHead ( result ) { const styleTag = `
			<style>
				${ result . css . join ( '\n' ) }
			</style>
		` . trim ( ) ; return { html : result . html . replace ( '</head>' , `${ styleTag }</head>` ) , css : result . css } ; } }