import * as fs from 'fs' ; import * as http from 'http' ; import * as https from 'https' ; import { ServerOptions } from 'https' ; import * as Koa from 'koa' ; import * as Router from 'koa-router' ; import * as path from 'path' ; import { UserConfigs } from './config' ; import { ExtensionManager } from './extension/extension' ; import { ResourcePackManager } from './resourcepack/resourcepack' ; import { getRemoteOrCachedFile , isPath } from './utils' ; const serverOptions = { key : fs . readFileSync ( path . join ( __dirname , 'certificate/key.pem' ) ) , cert : fs . readFileSync ( path . join ( __dirname , 'certificate/cert.crt' ) ) } ; Object . freeze ( serverOptions ) ; export function LoadServer ( ) { const router = new Router ( ) ; const server = new Koa ( ) ; ResourcePackManager . register ( server , router ) ; ExtensionManager . register ( server , router ) ; server . use ( router . routes ( ) ) ; server . use ( async ( ctx ) => { const isRoutePath = isPath ( ctx . request . originalUrl ) ; const resp = await getRemoteOrCachedFile ( ctx . request . originalUrl ) ; ctx . res . statusCode = resp . code ; ctx . body = isRoutePath ? resp . data . toString ( 'utf-8' ) : resp . data ; } ) ; httpServer = http . createServer ( server . callback ( ) ) ; httpsServer = https . createServer ( serverOptions , server . callback ( ) ) ; } export function CloseServer ( ) { if ( httpServer || httpsServer ) { UserConfigs . userData . useHttpServer ? httpServer . close ( ) : httpsServer . close ( ) ; httpServer = undefined ; httpsServer = undefined ; } } export function ListenServer ( port ) { if ( UserConfigs . userData . useHttpServer ) { httpServer . listen ( port ) ; httpServer . on ( 'error' , err => { if ( err . name === 'EADDRINUSE' ) { httpServer . close ( ) ; httpServer . listen ( 0 ) ; } } ) ; } else { httpsServer . listen ( port ) ; httpsServer . on ( 'error' , err => { if ( err . code === 'EADDRINUSE' ) { httpsServer . close ( ) ; httpsServer . listen ( 0 ) ; } } ) ; } } export let httpServer ; export let httpsServer ;