import { Context } from 'midway' ; import { getVersion , ReadableString } from './utils' ; import { renderLayout } from './renderLayout' ; import { useCdn } from './useCdn' ; import { Config } from './interface/config' ; import { Global } from './interface/global' ; const mergeStream = require ( 'merge-stream' ) ; declare const global ; const renderToStream = async ( ctx , config ) => { const csr = ctx . request ?. query ?. csr ? ctx . request . query . csr : false ; if ( config . type !== 'ssr' || csr ) { const stream = await renderLayout ( ctx , config ) ; const doctypeStream = new ReadableString ( '<!DOCTYPE html>' ) ; return mergeStream ( doctypeStream , stream ) ; } const { useCDN , serverJs , baseDir , isRax , useReactToString } = config ; const BASE_DIR = baseDir || process . cwd ( ) ; const isLocal = process . env . NODE_ENV === 'development' || config . env === 'local' ; let SEVER_JS = serverJs ; if ( useCDN && typeof serverJs === 'string' ) { const version = getVersion ( serverJs ) ; const filename = `serverBundle${ version }` ; SEVER_JS = await useCdn ( serverJs , isLocal , filename ) ; } if ( isLocal && typeof SEVER_JS === 'string' ) { delete require . cache [ SEVER_JS ] ; } if ( ! global . renderToNodeStream ) { if ( useReactToString ) { global . renderToNodeStream = require ( BASE_DIR + '/node_modules/react-dom/server' ) . renderToString ; } else { global . renderToNodeStream = isRax ? require ( BASE_DIR + '/node_modules/rax-server-renderer' ) . renderToString : require ( BASE_DIR + '/node_modules/react-dom/server' ) . renderToNodeStream ; } } const serverComponent = typeof SEVER_JS === 'string' ? await require ( SEVER_JS ) . default ( ctx ) : await SEVER_JS ( ctx ) ; const stream = isRax ? global . renderToNodeStream ( serverComponent , { defaultUnit : 'rpx' } ) : global . renderToNodeStream ( serverComponent ) ; if ( useReactToString || isRax ) { return '<!DOCTYPE html>' + stream ; } else { const doctypeStream = new ReadableString ( '<!DOCTYPE html>' ) ; return mergeStream ( doctypeStream , stream ) ; } } ; export default renderToStream ;