UNPKG

phaser-game-server

Version:

an express.js server that creates a socket.io connection and loads the phaser-game-server-engine

142 lines 5.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GameServer = void 0; const fs = require("fs"); const http = require("http"); const path = require("path"); const jsdom_1 = require("jsdom"); const socket_io_1 = require("socket.io"); const express = require('express'); const datauri = require('datauri/parser'); class GameServer { constructor(config) { config = Object.assign(Object.assign({}, GameServer.DEFAULT_CONFIG), config !== null && config !== void 0 ? config : this._loadConfig()); this.port = config.port; this.allowedCorsOrigin = config.allowedCorsOrigin; this.serverRoot = this._validateServerRoot(config.serverRoot); this.scripts = this._validateScripts(...config.scripts); this.html = `<!DOCTYPE html> <html> <head> <meta charset="utf-8"> ${this.scripts.map(s => '<script defer="defer" src="' + s + '"></script>').join('\n')} </head> <body /> </html>`; this.index = path.join(this.serverRoot, 'index.html'); fs.writeFileSync(this.index, this.html); this._parser = new datauri(); this._app = express(); this._app.use(express.static(this.serverRoot)); this._app.get('/', (req, res) => { res.send(this.index); }); this._app.get('/status', (req, res) => { res.sendStatus(200); }); this._server = http.createServer(this._app); this._io = new socket_io_1.Server(this._server, { cors: { origin: `${this.allowedCorsOrigin}`, methods: ["GET", "POST"] } }); } /** * loads the virtual DOM hosting the game-engine scripts and starts the ExpressJs * server listening on the port specified in the `server.config.json` file * or 8081 by default for `socket.io` connections used to send / receive * messages to / from game engine clients */ startGameEngine() { const virtualConsole = new jsdom_1.VirtualConsole(); virtualConsole.sendTo(console, { omitJSDOMErrors: false }); try { jsdom_1.JSDOM.fromFile(this.index, { runScripts: "dangerously", resources: "usable", pretendToBeVisual: true, virtualConsole: virtualConsole }).then(dom => { console.debug('Virtual DOM loaded...', dom.serialize()); dom.window.URL.createObjectURL = (blob) => { var _a; if (blob) { return (_a = this._parser.format(blob.type, blob[Object.getOwnPropertySymbols(blob)[0]]._buffer).content) !== null && _a !== void 0 ? _a : ''; } return ''; }; dom.window.URL.revokeObjectURL = (objectURL) => { }; dom.window.gameEngineReady = () => { console.debug('Game Engine is ready'); this._server.listen(8081, () => { var _a; console.info(`Game Server Listening on ${(_a = this._server.address()) === null || _a === void 0 ? void 0 : _a['port']}`); }); dom.window.io = this._io; dom.window.gameEngineReady = null; // prevent re-entry }; }); } catch (e) { console.error('error starting game-server: ', e); } } _loadConfig() { let config = {}; const configPath = path.join(process.cwd(), 'server.config.json'); if (fs.existsSync(configPath)) { try { const file = fs.readFileSync(configPath, { encoding: 'utf-8' }); const parsed = JSON.parse(file); config = parsed; } catch (e) { console.warn('unable to load configuration due to:', e); } } return config; } _validateServerRoot(serverRoot) { let absoluteRoot; if (path.isAbsolute(serverRoot)) { absoluteRoot = serverRoot; } else { absoluteRoot = path.join(process.cwd(), serverRoot); } if (!fs.existsSync(absoluteRoot)) { throw `specified 'serverRoot' of '${absoluteRoot}' could not be found`; } return absoluteRoot; } _validateScripts(...scripts) { const fullPaths = new Array(); scripts.forEach(s => { let maybeExists; if (path.isAbsolute(s)) { maybeExists = s; } else { maybeExists = path.join(this.serverRoot, s); } if (fs.existsSync(maybeExists)) { fullPaths.push(s); } else { throw `unable to locate script at: ${maybeExists}`; } }); return fullPaths; } } exports.GameServer = GameServer; GameServer.DEFAULT_CONFIG = { port: 8081, allowedCorsOrigin: '*', scripts: new Array(), serverRoot: path.join(process.cwd(), 'dist') }; //# sourceMappingURL=game-server.js.map