New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

beam-interactive-node

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

beam-interactive-node - npm Package Compare versions

Comparing version 0.2.1 to 0.2.2

177

dist/client.js

@@ -1,12 +0,32 @@

import { EventEmitter } from 'events';
import { strRepeat, indent, bubble } from './util';
'use strict';
export default class Client extends EventEmitter {
Object.defineProperty(exports, '__esModule', {
value: true
});
constructor(options) {
super();
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _events = require('events');
var _util = require('./util');
var Client = (function (_EventEmitter) {
_inherits(Client, _EventEmitter);
function Client(options) {
var _this = this;
_classCallCheck(this, Client);
_get(Object.getPrototypeOf(Client.prototype), 'constructor', this).call(this);
this.options = Object.assign({ debug: false }, options);
this.connect = this.newConnector();
bubble('error', this.connect, this);
(0, _util.bubble)('error', this.connect, this);

@@ -16,4 +36,4 @@ // By default Node throws when errors are emitted without a listener.

// and process for uncaught error events manually.
this.on('error', err => {
if (this.listeners('error').length > 1) {
this.on('error', function (err) {
if (_this.listeners('error').length > 1) {
return;

@@ -23,3 +43,3 @@ }

/* eslint-disable no-console */
console.error(this.prettyError(err));
console.error(_this.prettyError(err));
/* eslint-enable */

@@ -29,3 +49,7 @@ });

if (this.options.debug) {
this.connect.on('raw-message', data => this.logEntry(data, true)).on('sending', data => this.logEntry(data, false));
this.connect.on('raw-message', function (data) {
return _this.logEntry(data, true);
}).on('sending', function (data) {
return _this.logEntry(data, false);
});
}

@@ -39,71 +63,90 @@ }

*/
logEntry(data, incoming) {
const now = new Date();
let message = `${ now.getHours() }:${ now.getMinutes() }:${ now.getSeconds() } ` + strRepeat(incoming ? '<' : '>', 3) + ' ';
if (Buffer.isBuffer(data)) {
message += data.toString('hex');
} else {
message += data;
_createClass(Client, [{
key: 'logEntry',
value: function logEntry(data, incoming) {
var now = new Date();
var message = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + ' ' + (0, _util.strRepeat)(incoming ? '<' : '>', 3) + ' ';
if (Buffer.isBuffer(data)) {
message += data.toString('hex');
} else {
message += data;
}
/* eslint-disable no-console */
console.log(message);
/* eslint-enable */
}
/* eslint-disable no-console */
console.log(message);
/* eslint-enable */
}
/**
* Pretty-prints a client error.
* @param {Error} err
*/
}, {
key: 'prettyError',
value: function prettyError(err) {
var divider = (0, _util.strRepeat)('-', 20) + ' ';
var output = divider + 'Uncaught error in the tetris ' + this.constructor.name + ' client.\n\n' + ' > ' + err.toString() + '\n\n' + 'Client options:\n' + (0, _util.indent)(JSON.stringify(this.options, null, ' '), 1) + '\n\n';
/**
* Pretty-prints a client error.
* @param {Error} err
*/
prettyError(err) {
const divider = strRepeat('-', 20) + ' ';
let output = divider + 'Uncaught error in the tetris ' + this.constructor.name + ' client.\n\n' + ' > ' + err.toString() + '\n\n' + 'Client options:\n' + indent(JSON.stringify(this.options, null, ' '), 1) + '\n\n';
if (err.stack) {
output += 'Stack trace: ' + err.stack + '\n\n';
}
if (err.stack) {
output += 'Stack trace: ' + err.stack + '\n\n';
if (typeof err === 'object' && Object.keys(err).length > 0) {
output += 'Error: \n' + (0, _util.indent)(JSON.stringify(err, null, ' '), 1) + '\n\n';
}
output += divider + '\n';
return output;
}
if (typeof err === 'object' && Object.keys(err).length > 0) {
output += 'Error: \n' + indent(JSON.stringify(err, null, ' '), 1) + '\n\n';
/**
* Creates and returns a new Connector based on the client options.
* @protected
* @return {Connector}
*/
}, {
key: 'newConnector',
value: function newConnector() {
throw new Error('not implemented');
}
output += divider + '\n';
/**
* Sends a packet to the underlying connection.
* @param {Object} packet
*/
}, {
key: 'send',
value: function send(packet) {
this.connect.send(packet);
}
return output;
}
/**
* Sends a packet that a responses is expected to.
* @param {Object} packet
* @param {Function} response Class of the packet response.
* @param {Function} callback
*/
}, {
key: 'call',
value: function call(packet, response, callback) {
this.connect.call(packet, response, callback);
}
/**
* Creates and returns a new Connector based on the client options.
* @protected
* @return {Connector}
*/
newConnector() {
throw new Error('not implemented');
}
/**
* Closes the client and the underlying connection.
*/
}, {
key: 'close',
value: function close() {
this.connect.close();
}
}]);
/**
* Sends a packet to the underlying connection.
* @param {Object} packet
*/
send(packet) {
this.connect.send(packet);
}
return Client;
})(_events.EventEmitter);
/**
* Sends a packet that a responses is expected to.
* @param {Object} packet
* @param {Function} response Class of the packet response.
* @param {Function} callback
*/
call(packet, response, callback) {
this.connect.call(packet, response, callback);
}
/**
* Closes the client and the underlying connection.
*/
close() {
this.connect.close();
}
}
exports['default'] = Client;
module.exports = exports['default'];

@@ -1,6 +0,27 @@

import { UnknownPacketError, UnexpectedServerResponse } from './errors';
import { EventEmitter } from 'events';
import { noop, bubble } from './util';
import makeSocket from './socketMaker';
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x3, _x4, _x5) { var _again = true; _function: while (_again) { var object = _x3, property = _x4, receiver = _x5; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x3 = parent; _x4 = property; _x5 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _errors = require('./errors');
var _events = require('events');
var _util = require('./util');
var _socketMaker = require('./socketMaker');
var _socketMaker2 = _interopRequireDefault(_socketMaker);
/**

@@ -10,4 +31,6 @@ * The Connector provides a high-level interface, implemented to interact

*/
export default class Connector extends EventEmitter {
var Connector = (function (_EventEmitter) {
_inherits(Connector, _EventEmitter);
/**

@@ -20,4 +43,7 @@ * Creates a new Connector.

*/
constructor(encode, decode, errorPacket, remote) {
super();
function Connector(encode, decode, errorPacket, remote) {
_classCallCheck(this, Connector);
_get(Object.getPrototypeOf(Connector.prototype), 'constructor', this).call(this);
this.handlers = [];

@@ -36,141 +62,179 @@ this.remote = remote;

*/
connect(callback = noop, generator = makeSocket) {
const socket = this.socket = generator(this.remote);
bubble('error', socket, this, 'bubbleOpen');
_createClass(Connector, [{
key: 'connect',
value: function connect() {
var _this = this;
socket.once('open', () => {
this.emit('connect');
callback();
});
var callback = arguments.length <= 0 || arguments[0] === undefined ? _util.noop : arguments[0];
var generator = arguments.length <= 1 || arguments[1] === undefined ? _socketMaker2['default'] : arguments[1];
socket.on('unexpected-response', (req, res) => {
callback(new UnexpectedServerResponse(`Unexpected server response ${ res.statusCode }`));
});
var socket = this.socket = generator(this.remote);
socket.on('message', data => this.doDecode(data));
}
(0, _util.bubble)('error', socket, this, 'bubbleOpen');
/**
* Attempts to decode an incoming message.
* @param {String|Buffer} data
*/
doDecode(data) {
this.emit('raw-message', data);
socket.once('open', function () {
_this.emit('connect');
callback();
});
let message;
try {
message = this.decode(data);
} catch (e) {
if (e instanceof UnknownPacketError) {
this.emit('unrecognized', e.data);
} else {
this.emit('error', e);
socket.on('unexpected-response', function (req, res) {
callback(new _errors.UnexpectedServerResponse('Unexpected server response ' + res.statusCode));
});
socket.on('message', function (data) {
return _this.doDecode(data);
});
}
/**
* Attempts to decode an incoming message.
* @param {String|Buffer} data
*/
}, {
key: 'doDecode',
value: function doDecode(data) {
this.emit('raw-message', data);
var message = undefined;
try {
message = this.decode(data);
} catch (e) {
if (e instanceof _errors.UnknownPacketError) {
this.emit('unrecognized', e.data);
} else {
this.emit('error', e);
}
return;
}
return;
this.handleIncoming(message);
}
this.handleIncoming(message);
}
/**
* Sets whether the Connector is open. This is if the Connector
* is currently connected _or trying to connection_. It's independent
* of the underlying socket connection.
* @param {Boolean} state
*/
}, {
key: 'setOpen',
value: function setOpen(state) {
this.open = state;
}
/**
* Sets whether the Connector is open. This is if the Connector
* is currently connected _or trying to connection_. It's independent
* of the underlying socket connection.
* @param {Boolean} state
*/
setOpen(state) {
this.open = state;
}
/**
* Gets the opened state of the socket.
* @return {Boolea}
*/
}, {
key: 'getOpen',
value: function getOpen() {
return this.open;
}
/**
* Gets the opened state of the socket.
* @return {Boolea}
*/
getOpen() {
return this.open;
}
/**
* Bubbles an event if the connector is open.
* @protected
* @param {String} event
* @param {...} args
*/
}, {
key: 'bubbleOpen',
value: function bubbleOpen(event) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
/**
* Bubbles an event if the connector is open.
* @protected
* @param {String} event
* @param {...} args
*/
bubbleOpen(event, ...args) {
if (this.open) this.emit(event, ...args);
}
if (this.open) this.emit.apply(this, [event].concat(args));
}
/**
* Handles an incoming message. This watches for replies from "called"
* functions before dispatching an event. Using this method, calls
* can be safely concurrent.
*
* This relies partly on the assumption that requests set first will be
* answered first (FIFO), which is currently an attribute of the Tetrisd
* server. If this ever is not the case, the protocol will be adjusted
* so that packets can be numbered.
*
* @private
*/
handleIncoming(message) {
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i](message)) {
this.handlers.splice(i, 1);
return;
/**
* Handles an incoming message. This watches for replies from "called"
* functions before dispatching an event. Using this method, calls
* can be safely concurrent.
*
* This relies partly on the assumption that requests set first will be
* answered first (FIFO), which is currently an attribute of the Tetrisd
* server. If this ever is not the case, the protocol will be adjusted
* so that packets can be numbered.
*
* @private
*/
}, {
key: 'handleIncoming',
value: function handleIncoming(message) {
for (var i = 0; i < this.handlers.length; i++) {
if (this.handlers[i](message)) {
this.handlers.splice(i, 1);
return;
}
}
this.emit('message', message);
}
this.emit('message', message);
}
/**
* Sends the packet to the server, then waits for the expected reply
* (or an error) in response.
* @param {Object} packet
* @param {Class} Expected
* @param {Function} callback
*/
}, {
key: 'call',
value: function call(packet, Expected, callback) {
var _this2 = this;
/**
* Sends the packet to the server, then waits for the expected reply
* (or an error) in response.
* @param {Object} packet
* @param {Class} Expected
* @param {Function} callback
*/
call(packet, Expected, callback) {
this.handlers.push(message => {
if (message instanceof Expected) {
callback(undefined, message);
} else if (message instanceof this.errorPacket) {
callback(message);
} else {
return false;
}
this.handlers.push(function (message) {
if (message instanceof Expected) {
callback(undefined, message);
} else if (message instanceof _this2.errorPacket) {
callback(message);
} else {
return false;
}
return true;
});
return true;
});
this.send(packet);
}
this.send(packet);
}
/**
* Sends a packet to tetrisd.
* @param {Packet} packet
*/
send(packet) {
let encoded;
try {
encoded = this.encode(packet);
} catch (e) {
return this.emit('error', e);
/**
* Sends a packet to tetrisd.
* @param {Packet} packet
*/
}, {
key: 'send',
value: function send(packet) {
var encoded = undefined;
try {
encoded = this.encode(packet);
} catch (e) {
return this.emit('error', e);
}
this.emit('sending', encoded);
this.socket.send(encoded);
}
this.emit('sending', encoded);
this.socket.send(encoded);
}
/**
* Closes the client socket.
*/
}, {
key: 'close',
value: function close() {
if (this.socket) {
this.socket.close();
this.socket = undefined;
}
}
}]);
/**
* Closes the client socket.
*/
close() {
if (this.socket) {
this.socket.close();
this.socket = undefined;
}
}
}
return Connector;
})(_events.EventEmitter);
exports['default'] = Connector;
module.exports = exports['default'];

@@ -0,13 +1,9 @@

'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function extendError(name, methods) {
/* eslint-disable no-new-func */
const Err = new Function(`
return function ${ name }(message) {
const err = new Error(message);
this.stack = err.stack;
this.message = err.message;
if (this.constructor) {
this.constructor.apply(this, arguments);
}
};
`)();
var Err = new Function('\n return function ' + name + '(message) {\n const err = new Error(message);\n this.stack = err.stack;\n this.message = err.message;\n if (this.constructor) {\n this.constructor.apply(this, arguments);\n }\n };\n ')();
/* eslint-enable */

@@ -24,9 +20,11 @@

*/
export const CodingError = extendError('CodingError');
var CodingError = extendError('CodingError');
exports.CodingError = CodingError;
/**
* This error is thrown when there is a fatal error.
*/
export const FatalCodingError = extendError('FatalCodingError');
var FatalCodingError = extendError('FatalCodingError');
exports.FatalCodingError = FatalCodingError;
/**

@@ -36,5 +34,5 @@ * Thrown when we get an packet that we don't know about.

*/
export const UnknownPacketError = extendError('UnknownPacketError', {
constructor(id, data) {
this.message = `Unknown packet ID ${ id }`;
var UnknownPacketError = extendError('UnknownPacketError', {
constructor: function constructor(id, data) {
this.message = 'Unknown packet ID ' + id;
this.data = data;

@@ -44,2 +42,3 @@ }

exports.UnknownPacketError = UnknownPacketError;
/**

@@ -49,4 +48,5 @@ * Error type thrown by util.assert. Fill since browsers don't have

*/
export const AssertionError = extendError('AssertionError');
var AssertionError = extendError('AssertionError');
exports.AssertionError = AssertionError;
/**

@@ -56,2 +56,3 @@ * Sent when we get a response that we didn't like when trying to

*/
export const UnexpectedServerResponse = extendError('UnexpectedServerResponse');
var UnexpectedServerResponse = extendError('UnexpectedServerResponse');
exports.UnexpectedServerResponse = UnexpectedServerResponse;

@@ -1,9 +0,38 @@

import Packets from './packets';
import Socket from '../connector';
import Client from '../client';
import Reporter from './reporter';
import { noop } from '../util';
'use strict';
export default class Frontend extends Client {
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _packets = require('./packets');
var _packets2 = _interopRequireDefault(_packets);
var _connector = require('../connector');
var _connector2 = _interopRequireDefault(_connector);
var _client = require('../client');
var _client2 = _interopRequireDefault(_client);
var _reporter = require('./reporter');
var _reporter2 = _interopRequireDefault(_reporter);
var _util = require('../util');
var Frontend = (function (_Client) {
_inherits(Frontend, _Client);
/**

@@ -23,75 +52,102 @@ * Creates a new Robot that interacts with the remote server.

*/
constructor(options) {
super(options);
this.reporter = new Reporter(this, this.options.reportInterval);
function Frontend(options) {
_classCallCheck(this, Frontend);
_get(Object.getPrototypeOf(Frontend.prototype), 'constructor', this).call(this, options);
this.reporter = new _reporter2['default'](this, this.options.reportInterval);
}
newConnector() {
let endpoint;
if (this.options.playbook) {
endpoint = this.options.remote + '/playbook';
} else {
endpoint = this.options.remote + '/play/' + this.options.channel;
_createClass(Frontend, [{
key: 'newConnector',
value: function newConnector() {
var _this = this;
var endpoint = undefined;
if (this.options.playbook) {
endpoint = this.options.remote + '/playbook';
} else {
endpoint = this.options.remote + '/play/' + this.options.channel;
}
var socket = new _connector2['default'](function (packet) {
return packet.encode();
}, function (data) {
return _packets2['default'].decode(data);
}, _packets2['default'].Error, endpoint);
socket.on('message', function (packet) {
_this.emit('message', packet);
_this.emit(packet.id, packet.props);
});
return socket;
}
const socket = new Socket(packet => packet.encode(), data => Packets.decode(data), Packets.Error, endpoint);
/**
* Sends a handshake packet and waits for a response from the server.
* This method should be invoked prior to any other methods being run,
* and it's expected that you'll wait for a callback before
* invoking other methods.
*
* @param {Function} callback Invoked when a handshake resolves. Iff
* it fails, it will be called with an error
* as its first argument.
*/
}, {
key: 'handshake',
value: function handshake(callback) {
var _this2 = this;
socket.on('message', packet => {
this.emit('message', packet);
this.emit(packet.id, packet.props);
});
var connect = this.connect;
return socket;
}
connect.connect(function (err) {
if (err) {
callback(err);
} else {
_this2.call(new _packets2['default'].Handshake({
id: _this2.options.user,
key: _this2.options.key
}), _packets2['default'].HandshakeACK, callback);
}
});
}
/**
* Sends a handshake packet and waits for a response from the server.
* This method should be invoked prior to any other methods being run,
* and it's expected that you'll wait for a callback before
* invoking other methods.
*
* @param {Function} callback Invoked when a handshake resolves. Iff
* it fails, it will be called with an error
* as its first argument.
*/
handshake(callback) {
const connect = this.connect;
/**
* Sends a new report with some data.
* @param {Object} data
* @param {Function} callback
*/
}, {
key: 'report',
value: function report(data) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? _util.noop : arguments[1];
connect.connect(err => {
if (err) {
callback(err);
} else {
this.call(new Packets.Handshake({
id: this.options.user,
key: this.options.key
}), Packets.HandshakeACK, callback);
this.reporter.add(data, callback);
}
/**
* Creates and returns a packet by name.
* @param {String} name
* @param {Object} [data] to populate the packet. If not passed, the
* class will be returned.
* @return {Object|Function}
*/
}], [{
key: 'Packet',
value: function Packet(name, data) {
var Packet = _packets2['default'][name];
if (Packet === undefined) {
throw new Error('Tried to instatiate unknown packet "' + name + '".');
}
});
}
/**
* Sends a new report with some data.
* @param {Object} data
* @param {Function} callback
*/
report(data, callback = noop) {
this.reporter.add(data, callback);
}
/**
* Creates and returns a packet by name.
* @param {String} name
* @param {Object} [data] to populate the packet. If not passed, the
* class will be returned.
* @return {Object|Function}
*/
static Packet(name, data) {
const Packet = Packets[name];
if (Packet === undefined) {
throw new Error(`Tried to instatiate unknown packet "${ name }".`);
return data ? new Packet(data) : Packet;
}
}]);
return data ? new Packet(data) : Packet;
}
}
return Frontend;
})(_client2['default']);
exports['default'] = Frontend;
module.exports = exports['default'];

@@ -1,62 +0,93 @@

import { FatalCodingError, UnknownPacketError } from '../errors';
import isPlain from 'lodash.isplainobject';
import { assert } from '../util';
'use strict';
const idLength = 4;
Object.defineProperty(exports, '__esModule', {
value: true
});
class BasicPacket {
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
/**
* Encodes the packet to a string to be sent over the websocket.
* @return {String}
*/
encode() {
let encoded;
if (typeof this.props.toJSON === 'function') {
encoded = this.props.toJSON();
} else if (isPlain(this.props)) {
encoded = JSON.stringify(this.props);
} else {
encoded = this.props;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
return this.id + encoded;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _errors = require('../errors');
var _lodashIsplainobject = require('lodash.isplainobject');
var _lodashIsplainobject2 = _interopRequireDefault(_lodashIsplainobject);
var _util = require('../util');
var idLength = 4;
var BasicPacket = (function () {
function BasicPacket() {
_classCallCheck(this, BasicPacket);
}
/**
* Gets a property of the packet, deeply.
* @param {String} prop
* @return {*}
*/
get(prop) {
const parts = prop.split('.');
_createClass(BasicPacket, [{
key: 'encode',
let obj = this.props;
while (parts.length && obj !== undefined && obj !== null) {
obj = obj[parts.shift()];
/**
* Encodes the packet to a string to be sent over the websocket.
* @return {String}
*/
value: function encode() {
var encoded = undefined;
if (typeof this.props.toJSON === 'function') {
encoded = this.props.toJSON();
} else if ((0, _lodashIsplainobject2['default'])(this.props)) {
encoded = JSON.stringify(this.props);
} else {
encoded = this.props;
}
return this.id + encoded;
}
return obj;
}
/**
* Gets a property of the packet, deeply.
* @param {String} prop
* @return {*}
*/
}, {
key: 'get',
value: function get(prop) {
var parts = prop.split('.');
/**
* Returns a plain object of the packet properties.
* @return {Object}
*/
toObject() {
return this.props;
}
var obj = this.props;
while (parts.length && obj !== undefined && obj !== null) {
obj = obj[parts.shift()];
}
/**
* Encodes the packet to a JSON string. This is NOT for wire transfer:
* use encode() if you need to send the packet to tetrisd.
* @return {String}
*/
toJSON() {
return JSON.stringify(this.props);
}
}
return obj;
}
/**
* Returns a plain object of the packet properties.
* @return {Object}
*/
}, {
key: 'toObject',
value: function toObject() {
return this.props;
}
/**
* Encodes the packet to a JSON string. This is NOT for wire transfer:
* use encode() if you need to send the packet to tetrisd.
* @return {String}
*/
}, {
key: 'toJSON',
value: function toJSON() {
return JSON.stringify(this.props);
}
}]);
return BasicPacket;
})();
function packet(name, id) {
assert(id.length === idLength, 'expected ID length `' + id + '` to be 4');
(0, _util.assert)(id.length === idLength, 'expected ID length `' + id + '` to be 4');

@@ -66,8 +97,3 @@ // We do a bit of eval here so that the packet is generated with

/* eslint-disable no-new-func */
const Packet = new Function(`
return function ${ name } (obj) {
this.props = obj;
this.id = '${ id }';
};
`)();
var Packet = new Function('\n return function ' + name + ' (obj) {\n this.props = obj;\n this.id = \'' + id + '\';\n };\n ')();
/* eslint-enable */

@@ -94,7 +120,7 @@

Packet.decode = function packetDecode(str) {
let parsed;
var parsed = undefined;
try {
parsed = JSON.parse(str.slice(id.length));
} catch (e) {
throw new FatalCodingError(e);
throw new _errors.FatalCodingError(e);
}

@@ -108,3 +134,3 @@

const packets = {
var packets = {
Handshake: packet('Handshake', 'hshk'),

@@ -129,7 +155,7 @@ HandshakeACK: packet('HandshakeACK', 'hack'),

if (!str || str.length < idLength) {
throw new FatalCodingError('Incomplete JSON packet.', str);
throw new _errors.FatalCodingError('Incomplete JSON packet.', str);
}
for (const key in packets) {
const p = packets[key];
for (var key in packets) {
var p = packets[key];
if (p.matches(str)) {

@@ -140,6 +166,7 @@ return p.decode(str);

throw new UnknownPacketError(str.slice(0, idLength), str);
throw new _errors.UnknownPacketError(str.slice(0, idLength), str);
}
});
export default Object.freeze(packets);
exports['default'] = Object.freeze(packets);
module.exports = exports['default'];

@@ -1,4 +0,19 @@

import Packets from './packets';
import { find, noop, addIf } from '../util';
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _packets = require('./packets');
var _packets2 = _interopRequireDefault(_packets);
var _util = require('../util');
/**

@@ -8,4 +23,5 @@ * The reporter is responsible for building report data and

*/
export default class Reporter {
var Reporter = (function () {
/**

@@ -16,3 +32,6 @@ * Creates a new Reporter.

*/
constructor(client, interval) {
function Reporter(client, interval) {
_classCallCheck(this, Reporter);
this.client = client;

@@ -28,80 +47,115 @@ this.interval = interval;

*/
add(data, callback = noop) {
this.mergeTactile(data);
this.mergeJoystick(data);
if (!this.waiting) {
const delay = this.lastSent + this.interval - Date.now();
setTimeout(() => this.runSend(), Math.max(0, delay));
this.waiting = true;
_createClass(Reporter, [{
key: 'add',
value: function add(data) {
var _this = this;
var callback = arguments.length <= 1 || arguments[1] === undefined ? _util.noop : arguments[1];
this.mergeTactile(data);
this.mergeJoystick(data);
if (!this.waiting) {
var delay = this.lastSent + this.interval - Date.now();
setTimeout(function () {
return _this.runSend();
}, Math.max(0, delay));
this.waiting = true;
}
this.queued.callbacks.push(callback);
}
this.queued.callbacks.push(callback);
}
/**
* Merges queued tactile data with that of the given report.
* @param {Object} data
*/
}, {
key: 'mergeTactile',
value: function mergeTactile(data) {
var report = this.queued.report;
/**
* Merges queued tactile data with that of the given report.
* @param {Object} data
*/
mergeTactile(data) {
const report = this.queued.report;
var _loop = function (i) {
var right = data.tactile[i];
var left = (0, _util.find)(report.tactile, function (l) {
return l.id === right.id;
});
for (let i = 0; data.tactile && i < data.tactile.length; i++) {
const right = data.tactile[i];
const left = find(report.tactile, l => l.id === right.id);
if (left !== undefined) {
left.down = (0, _util.addIf)(left.down, right.down);
left.up = (0, _util.addIf)(left.up, right.up);
} else {
report.tactile.push(right);
}
};
if (left !== undefined) {
left.down = addIf(left.down, right.down);
left.up = addIf(left.up, right.up);
} else {
report.tactile.push(right);
for (var i = 0; data.tactile && i < data.tactile.length; i++) {
_loop(i);
}
}
}
/**
* Merges queued joystick data with that of the given report.
* @param {Object} data
*/
mergeJoystick(data) {
const report = this.queued.report;
/**
* Merges queued joystick data with that of the given report.
* @param {Object} data
*/
}, {
key: 'mergeJoystick',
value: function mergeJoystick(data) {
var report = this.queued.report;
for (let i = 0; data.joystick && i < data.joystick.length; i++) {
const right = data.joystick[i];
const left = find(report.joystick, l => l.id === right.id);
var _loop2 = function (i) {
var right = data.joystick[i];
var left = (0, _util.find)(report.joystick, function (l) {
return l.id === right.id;
});
if (left !== undefined) {
left.x = (left.x + right.x) / 2;
left.y = (left.y + right.y) / 2;
} else {
report.joystick.push(right);
if (left !== undefined) {
left.x = (left.x + right.x) / 2;
left.y = (left.y + right.y) / 2;
} else {
report.joystick.push(right);
}
};
for (var i = 0; data.joystick && i < data.joystick.length; i++) {
_loop2(i);
}
}
}
/**
* Resets queued data. Should be run after reports are sent.
* @private
*/
resetQueued() {
this.queued = { report: { joystick: [], tactile: [] }, callbacks: [] };
this.lastSent = Date.now();
this.waiting = false;
}
/**
* Resets queued data. Should be run after reports are sent.
* @private
*/
}, {
key: 'resetQueued',
value: function resetQueued() {
this.queued = { report: { joystick: [], tactile: [] }, callbacks: [] };
this.lastSent = Date.now();
this.waiting = false;
}
/**
* Dispatches queued data out to the socket, and completes
* any pending callbacks.
* @private
*/
runSend() {
const q = this.queued;
this.client.send(new Packets.Report(q.report));
/**
* Dispatches queued data out to the socket, and completes
* any pending callbacks.
* @private
*/
}, {
key: 'runSend',
value: function runSend() {
var q = this.queued;
this.client.send(new _packets2['default'].Report(q.report));
for (let i = 0; i < q.callbacks.length; i++) {
q.callbacks[i]();
for (var i = 0; i < q.callbacks.length; i++) {
q.callbacks[i]();
}
this.resetQueued();
}
}]);
this.resetQueued();
}
}
return Reporter;
})();
exports['default'] = Reporter;
module.exports = exports['default'];

@@ -1,10 +0,36 @@

import Packets from './packets';
import Socket from '../connector';
import Client from '../client';
import { find } from '../util';
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _packets = require('./packets');
var _packets2 = _interopRequireDefault(_packets);
var _connector = require('../connector');
var _connector2 = _interopRequireDefault(_connector);
var _client = require('../client');
var _client2 = _interopRequireDefault(_client);
var _util = require('../util');
// Map of packet types to events that should be sent out on the robot.
const eventMap = [{ ev: 'report', obj: Packets.Report }, { ev: 'error', obj: Packets.Error }];
var eventMap = [{ ev: 'report', obj: _packets2['default'].Report }, { ev: 'error', obj: _packets2['default'].Error }];
export default class Robot extends Client {
var Robot = (function (_Client) {
_inherits(Robot, _Client);

@@ -18,41 +44,64 @@ /**

*/
constructor(options) {
super(options);
function Robot(options) {
_classCallCheck(this, Robot);
_get(Object.getPrototypeOf(Robot.prototype), 'constructor', this).call(this, options);
}
newConnector() {
const socket = new Socket(packet => packet.encode(), data => Packets.decode(data), Packets.Error, this.options.remote + '/robot');
_createClass(Robot, [{
key: 'newConnector',
value: function newConnector() {
var _this = this;
socket.on('message', message => {
const event = find(eventMap, e => message instanceof e.obj);
if (event) {
this.emit(event.ev, message);
}
});
var socket = new _connector2['default'](function (packet) {
return packet.encode();
}, function (data) {
return _packets2['default'].decode(data);
}, _packets2['default'].Error, this.options.remote + '/robot');
return socket;
}
socket.on('message', function (message) {
var event = (0, _util.find)(eventMap, function (e) {
return message instanceof e.obj;
});
if (event) {
_this.emit(event.ev, message);
}
});
/**
* Sends a handshake packet and waits for a response from the server.
* This method should be invoked prior to any other methods being run,
* and it's expected that you'll wait for a callback before
* invoking other methods.
*
* @param {Function} callback Invoked when a handshake resolves. Iff
* it fails, it will be called with an error
* as its first argument.
*/
handshake(callback) {
const connect = this.connect;
return socket;
}
connect.on('connect', () => {
this.call(new Packets.Handshake({
channel: this.options.channel,
streamKey: this.options.key
}), Packets.HandshakeACK, callback);
});
/**
* Sends a handshake packet and waits for a response from the server.
* This method should be invoked prior to any other methods being run,
* and it's expected that you'll wait for a callback before
* invoking other methods.
*
* @param {Function} callback Invoked when a handshake resolves. Iff
* it fails, it will be called with an error
* as its first argument.
*/
}, {
key: 'handshake',
value: function handshake(callback) {
var _this2 = this;
connect.connect();
}
}
var connect = this.connect;
connect.on('connect', function () {
_this2.call(new _packets2['default'].Handshake({
channel: _this2.options.channel,
streamKey: _this2.options.key
}), _packets2['default'].HandshakeACK, callback);
});
connect.connect();
}
}]);
return Robot;
})(_client2['default']);
exports['default'] = Robot;
module.exports = exports['default'];

@@ -1,10 +0,27 @@

import { FatalCodingError, UnknownPacketError } from '../errors';
import Protobuf from 'protobufjs';
import varint from 'varint';
import path from 'path';
'use strict';
const builder = Protobuf.loadProtoFile(path.join(__dirname, 'tetris.proto'));
const Packets = builder.build('tetris');
Object.defineProperty(exports, '__esModule', {
value: true
});
const idMap = {
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _errors = require('../errors');
var _protobufjs = require('protobufjs');
var _protobufjs2 = _interopRequireDefault(_protobufjs);
var _varint = require('varint');
var _varint2 = _interopRequireDefault(_varint);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var builder = _protobufjs2['default'].loadProtoFile(_path2['default'].join(__dirname, 'tetris.proto'));
var Packets = builder.build('tetris');
var idMap = {
Handshake: 0,

@@ -18,4 +35,4 @@ HandshakeACK: 1,

Object.keys(idMap).forEach(function genpacket(key) {
const Packet = Packets[key];
const id = idMap[key];
var Packet = Packets[key];
var id = idMap[key];

@@ -26,3 +43,3 @@ Packet.id = id;

Packet.prototype.encode = function encode() {
return Buffer.concat([new Buffer(varint.encode(id)), this.encodeOriginal().toBuffer()]);
return Buffer.concat([new Buffer(_varint2['default'].encode(id)), this.encodeOriginal().toBuffer()]);
};

@@ -37,10 +54,10 @@

Packet.decode = function decode(buf) {
varint.decode(buf, 0);
const offset = varint.decode.bytes;
_varint2['default'].decode(buf, 0);
var offset = _varint2['default'].decode.bytes;
let decoded;
var decoded = undefined;
try {
decoded = Packet.decodeOriginal(buf.slice(offset));
} catch (e) {
throw new FatalCodingError(e);
throw new _errors.FatalCodingError(e);
}

@@ -60,9 +77,9 @@

value: function decode(buf) {
const id = varint.decode(buf);
var id = _varint2['default'].decode(buf);
if (id === undefined) {
throw new FatalCodingError('Incomplete protobuf packet.');
throw new _errors.FatalCodingError('Incomplete protobuf packet.');
}
for (const key in idMap) {
const p = Packets[key];
for (var key in idMap) {
var p = Packets[key];
if (p.id === id) {

@@ -73,6 +90,7 @@ return p.decode(buf);

throw new UnknownPacketError(id, buf);
throw new _errors.UnknownPacketError(id, buf);
}
});
export default Packets;
exports['default'] = Packets;
module.exports = exports['default'];
// Importing this is DEPRECATED and will be removed in the future.
const packets = require('../packets');
Object.keys(packets).forEach(key => {
const p = packets[key];
'use strict';
var packets = require('../packets');
Object.keys(packets).forEach(function (key) {
var p = packets[key];
Object.defineProperty(exports, key, {
enumerable: true,
get() {
get: function get() {
/* eslint-disable no-console */

@@ -11,0 +13,0 @@ console.error('Deprecated: import \'robot/packets\', not ' + '\'robot/proto/packets\', from beam-interactive-node.');

@@ -1,5 +0,16 @@

import WebSocket from 'ws';
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = makeSocket;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _ws = require('ws');
var _ws2 = _interopRequireDefault(_ws);
// window will be undefined in node.js
const isNode = typeof window === 'undefined';
var isNode = typeof window === 'undefined';

@@ -13,3 +24,3 @@ /**

function wrapHandler(event, fn) {
return ev => {
return function (ev) {
if (event === 'message') {

@@ -24,3 +35,3 @@ return fn(ev.data);

socket.on = function on(event, listener) {
const wrapped = wrapHandler(event, listener);
var wrapped = wrapHandler(event, listener);
socket.addEventListener(event, wrapped);

@@ -30,4 +41,4 @@ };

socket.once = function once(event, listener) {
const wrapped = wrapHandler(event, listener);
socket.addEventListener(event, ev => {
var wrapped = wrapHandler(event, listener);
socket.addEventListener(event, function (ev) {
wrapped(ev);

@@ -60,8 +71,11 @@ socket.removeEventListener(event, wrapped);

*/
export default function makeSocket(remote) {
const socket = new WebSocket(remote);
function makeSocket(remote) {
var socket = new _ws2['default'](remote);
if (isNode) return wrapNode(socket);
return wrapDOM(socket);
}
}
module.exports = exports['default'];

@@ -1,5 +0,19 @@

import { AssertionError } from './errors';
'use strict';
export function noop() {}
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.noop = noop;
exports.bubble = bubble;
exports.find = find;
exports.findValue = findValue;
exports.strRepeat = strRepeat;
exports.addIf = addIf;
exports.indent = indent;
exports.assert = assert;
var _errors = require('./errors');
function noop() {}
/**

@@ -12,4 +26,13 @@ * Bubbles a certain event up from the child EventEmitter to the parent.

*/
export function bubble(event, child, parent, emit = 'emit') {
child.on(event, (...args) => parent[emit](event, ...args));
function bubble(event, child, parent) {
var emit = arguments.length <= 3 || arguments[3] === undefined ? 'emit' : arguments[3];
child.on(event, function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return parent[emit].apply(parent, [event].concat(args));
});
}

@@ -25,4 +48,5 @@

*/
export function find(array, predicate) {
for (let i = 0; i < array.length; i++) {
function find(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {

@@ -44,4 +68,5 @@ return array[i];

*/
export function findValue(obj, predicate) {
for (const key in obj) {
function findValue(obj, predicate) {
for (var key in obj) {
if (obj.hasOwnProperty(key) && predicate(key, obj[key])) {

@@ -61,5 +86,6 @@ return obj[key];

*/
export function strRepeat(str, times) {
let output = '';
for (let i = 0; i < times; i++) {
function strRepeat(str, times) {
var output = '';
for (var i = 0; i < times; i++) {
output += str;

@@ -78,3 +104,4 @@ }

*/
export function addIf(a, b) {
function addIf(a, b) {
return (a || 0) + (b || 0);

@@ -90,9 +117,12 @@ }

*/
export function indent(str, times, indenter = ' ') {
const indentation = strRepeat(indenter, times);
const feed = /\r?\n/.exec(str);
function indent(str, times) {
var indenter = arguments.length <= 2 || arguments[2] === undefined ? ' ' : arguments[2];
var indentation = strRepeat(indenter, times);
var feed = /\r?\n/.exec(str);
if (feed === null) return indentation + str;
const lines = str.split(feed[0]);
for (let i = 0; i < lines.length; i++) {
var lines = str.split(feed[0]);
for (var i = 0; i < lines.length; i++) {
lines[i] = indentation + lines[i];

@@ -110,6 +140,9 @@ }

*/
export function assert(condition, error = 'expected false to be true') {
function assert(condition) {
var error = arguments.length <= 1 || arguments[1] === undefined ? 'expected false to be true' : arguments[1];
if (!condition) {
throw new AssertionError(error);
throw new _errors.AssertionError(error);
}
}
{
"name": "beam-interactive-node",
"version": "0.2.1",
"version": "0.2.2",
"description": "This repository contains reference a implementation of a Beam Interactive robot.",

@@ -5,0 +5,0 @@ "main": "index.js",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc