UNPKG

karma-server

Version:
78 lines (66 loc) 2.41 kB
const fs = require( 'fs' ); const path = require( 'path' ); const Ynn = require( 'ynn' ); const is = require( '@lvchengbin/is' ); function cors( ctx, config ) { const origin = ctx.request.get( 'origin' ); ctx.set( 'Access-Control-Allow-Origin', origin ); if( config[ 'Access-Control-Allow-Headers' ] ) { ctx.set( 'Access-Control-Allow-Headers', config[ 'Access-Control-Allow-Headers' ] ); } } const createServer = ( config, basePath, files, logger ) => { const log = logger.create( 'server' ); config || ( config = {} ); const root = config.root ? path.resolve( basePath, config.root ) : basePath; const host = config.host || '127.0.0.1'; const ns = config.namespace || 'server'; const app = new Ynn( { root, debugging : is.undefined( config.debugging ) ? Ynn.DEBUGGING_ERROR : config.debugging, modules : config.modules || {}, logging : Ynn.LOGGING_DISABLE_ALL, static : { '/static/home.html' : config.static || root }, routers() { this.router.options( /.*/, async ctx => { cors( ctx, config ); ctx.body = {}; } ); this.router.any( '*', /.*/, async ( ctx, next ) => { try { await next(); } catch( e ) { ctx.status = e.status; } finally { cors( ctx, config ); } } ); } } ); const listen = app.listen( config.port ); const port = listen.address().port; const DECLARATION = ` ( function() { // This file is generated by karma-server. window.${ns} = window.${ns} || {}; window.${ns}.time = ${+new Date}; window.${ns}.port = ${port}; window.${ns}.host = 'http://${host}:${port}'; } )(); `; const file = path.join( __dirname, 'server-declaration.js' ); fs.writeFileSync( file, DECLARATION ); log.info( `Ynn is listening to the port: ${port}. [http://${host}:${port}]` ); files.unshift( { pattern : file, included : true, served : true, watched : false } ); }; createServer.$inject = [ 'config.server', 'config.basePath', 'config.files', 'logger' ]; module.exports = { 'framework:server' : [ 'factory', createServer ] };