UNPKG

@hp4k1h5/terminordle

Version:

> multiplayer [wordle](https://www.powerlanguage.co.uk/wordle/) clone in your terminal

88 lines (87 loc) 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createWS = exports.requestSession = void 0; const ws_1 = require("ws"); const chalk = require("chalk"); const session_1 = require("./session"); const cli_1 = require("../../cli"); const repl_1 = require("../../cli/repl"); const msg_1 = require("./msg"); var session_2 = require("./session"); Object.defineProperty(exports, "requestSession", { enumerable: true, get: function () { return session_2.requestSession; } }); const msgTypeToFn = { user_id: setUserId, session_id: setSessionId, info, again: session_1.again, error, guess: session_1.guess, }; function error(ws, data) { // TODO: console.error('error from server', data); } function info(cnx, message, color = cli_1.MsgColors.green) { if (typeof message.content === 'string') { cli_1.display.alterMessage(message.content, color); let replace = false; if (repl_1.rl.getCursorPos().cols) replace = true; if (replace) repl_1.rl.write(null, { ctrl: true, name: 'u' }); cli_1.display.print(); if (replace) repl_1.rl.write(null, { ctrl: true, name: 'y' }); } } function setUserId(cnx, message) { if (!message || typeof message.content !== 'string') { return; } cnx.user_id = message.content; cli_1.display.screen.splice((0, cli_1.infoIndex)(), 0, `${chalk.cyanBright('user id: ')} ${cnx.user_id}`); cli_1.display.print(); } function setSessionId(cnx, message) { if (cnx.session_id) return; cnx.session_id = message.session_id; cli_1.display.alterMessage('type a guess and hit enter ', cli_1.MsgColors.bold); cli_1.display.screen.splice((0, cli_1.infoIndex)() - 1, 0, `${chalk.blueBright('session id:')} ${cnx.session_id}`); cli_1.display.print(); } function createWS(url) { if (!/^wss?:\/\//.test(url)) { url = 'ws://' + url; } console.log(chalk.bgBlueBright(`connecting to ${url}`)); return new Promise(keep => { const ws = new ws_1.WebSocket(url); ws.on('open', function () { keep(ws); }); ws.on('message', async function (data) { let message; try { message = (0, msg_1.validateMsg)(ws, data); } catch (e) { return; } try { await msgTypeToFn[message.type](ws, message); } catch (e) { console.error('action error', message, e); // TODO: } }); ws.on('error', function (data) { console.error('received: %s', data); // TODO: return; }); ws.on('close', function () { process.exit(0); }); }); } exports.createWS = createWS;