import express from 'express' ; import { existsSync } from 'fs' ; import next from 'next' ; import { join } from 'path' ; import { getPluginConfig } from './utils' ; import isPromise from 'is-promise' ; import { Loader } from './Loader' ; import { coreLogger } from '@tiejs/logger' ; import chalk from 'chalk' ; import { Container , Application } from '@tiejs/common' ; import http from 'http' ; import { Config } from './types' ; export function createApp ( config = { } as Config ) { const t0 = Date . now ( ) ; const app = ( express ( ) as any ) as Application ; const isProd = process . env . NODE_ENV === 'production' ; const baseDir = process . cwd ( ) ; const isEnableNextJS = ( ) => { return existsSync ( join ( baseDir , 'pages' ) ) || existsSync ( join ( baseDir , 'src' , 'pages' ) ) ; } ; app . baseDir = baseDir ; app . config = { enableNextJS : isEnableNextJS ( ) , ... config , port : config . port || 3000 , plugins : getPluginConfig ( config . plugins ) , nextApp : next ( { dev : ! isProd } ) , } ; app . bootstrap = async ( ) => { if ( app . config . enableNextJS ) { await app . config . nextApp . prepare ( ) ; } const t1 = Date . now ( ) ; const time = ( t1 - t0 ) / 1000 ; const { port } = app . config ; const server = http . createServer ( app ) ; Container . set ( 'TIE_APP' , app ) ; Container . set ( 'TIE_SERVER' , server ) ; await new Loader ( app as any ) . init ( ) ; for ( const item of app . pluginStore ) { if ( ! item . serverDidCreate ) continue ; const result = item . serverDidCreate . call ( item . instance , app , server ) ; if ( isPromise ( result ) ) await result ; } server . listen ( port , async ( ) => { const msg = `Tie server started on ${ chalk . cyan ( `http://127.0.0.1:${ port }` ) } (${ time }s)` ; coreLogger . info ( msg ) ; for ( const item of app . pluginStore ) { if ( ! item . serverDidListen ) continue ; const result = item . serverDidListen . call ( item . instance , app , server ) ; if ( isPromise ( result ) ) await result ; } } ) ; } ; return app ; }