/*
frontend "connector"
332997
function askFrontendProp(who, propName, params, frontendConnectorRequestID)
    {
        that.send({
            "a": "fp",
            "t": propName,
            "w": who,
            "p": params,
            "r": frontendConnectorRequestID
        });
    }
982693
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$persist=false)
	{
		if (!function_exists('ibase_pconnect')) return null;
		if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
		$fn = ($persist) ? 'ibase_pconnect':'ibase_connect';
		if ($this->role)
			$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
					$this->charSet,$this->buffers,$this->dialect,$this->role);
		else
			$this->_connectionID = $fn($argHostname,$argUsername,$argPassword,
					$this->charSet,$this->buffers,$this->dialect);

		if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
			$this->replaceQuote = "''";
		}
		if ($this->_connectionID === false) {
			$this->_handleerror();
			return false;
		}

		// PHP5 change.
		if (function_exists('ibase_timefmt')) {
			ibase_timefmt($this->ibase_datefmt,IBASE_DATE );
			if ($this->dialect == 1) {
				ibase_timefmt($this->ibase_datefmt,IBASE_TIMESTAMP );
			}
			else {
				ibase_timefmt($this->ibase_timestampfmt,IBASE_TIMESTAMP );
			}
			ibase_timefmt($this->ibase_timefmt,IBASE_TIME );

		} else {
			ini_set("ibase.timestampformat", $this->ibase_timestampfmt);
			ini_set("ibase.dateformat", $this->ibase_datefmt);
			ini_set("ibase.timeformat", $this->ibase_timefmt);
		}
		return true;
	}
204643
@Override
    public ApplicationDescriptor connectorModule(String uri) {
        model.createChild("module").createChild("connector").text(uri);
        return this;
    }
203225
function connect() {
	// detect type of each argument
	for (var i = 0; i < arguments.length; i++) {
		if (arguments[i].constructor.name === 'Mongoose') {
			// detected Mongoose
			this.mongoose = arguments[i];
		} else if (arguments[i].name === 'app') {
			// detected Express app
			this.app = arguments[i];
		}
	}
	return this;
}
144519
function connect(options) {
  // Default driver is MySQL.
  activeBackend = options.driver || 'mysql';

  // Save the connection options for later use.
  connectionOptions = options;

  if (activeBackend === 'mysql') {
    // Save a reference to the MySQL client object for later use.
    activeDb = mysql.createClient(options);

    if (activeDb !== null) {
      activeDb.on('error', function (err) {
        console.log(err);
      });
    }
  }

  return activeDb;
}
215276
function connect(Composed) {
  return (function (superclass) {
    function Connect(props) {
      superclass.call(this, props);
      this.state = getState();
      this.onChange = this.onChange.bind(this);
    }

    if ( superclass ) Connect.__proto__ = superclass;
    Connect.prototype = Object.create( superclass && superclass.prototype );
    Connect.prototype.constructor = Connect;

    Connect.prototype.componentDidMount = function componentDidMount () {
      this.token = subscribe(this.onChange);
    };

    Connect.prototype.componentWillUnmount = function componentWillUnmount () {
      if (typeof this.token === "function") {
        this.token();
      }
    };

    Connect.prototype.onChange = function onChange (state) {
      this.setState(state);
    };

    Connect.prototype.render = function render () {
      return React.createElement(Composed, Object.assign({}, this.state, this.props));
    };

    return Connect;
  }(React__default.PureComponent));
}
1057366
function createConnect() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$connectHOC = _ref.connectHOC,
      connectHOC = _ref$connectHOC === undefined ? __WEBPACK_IMPORTED_MODULE_0__components_connectAdvanced__["a" /* default */] : _ref$connectHOC,
      _ref$mapStateToPropsF = _ref.mapStateToPropsFactories,
      mapStateToPropsFactories = _ref$mapStateToPropsF === undefined ? __WEBPACK_IMPORTED_MODULE_3__mapStateToProps__["a" /* default */] : _ref$mapStateToPropsF,
      _ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories,
      mapDispatchToPropsFactories = _ref$mapDispatchToPro === undefined ? __WEBPACK_IMPORTED_MODULE_2__mapDispatchToProps__["a" /* default */] : _ref$mapDispatchToPro,
      _ref$mergePropsFactor = _ref.mergePropsFactories,
      mergePropsFactories = _ref$mergePropsFactor === undefined ? __WEBPACK_IMPORTED_MODULE_4__mergeProps__["a" /* default */] : _ref$mergePropsFactor,
      _ref$selectorFactory = _ref.selectorFactory,
      selectorFactory = _ref$selectorFactory === undefined ? __WEBPACK_IMPORTED_MODULE_5__selectorFactory__["a" /* default */] : _ref$selectorFactory;

  return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
    var _ref2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
        _ref2$pure = _ref2.pure,
        pure = _ref2$pure === undefined ? true : _ref2$pure,
        _ref2$areStatesEqual = _ref2.areStatesEqual,
        areStatesEqual = _ref2$areStatesEqual === undefined ? strictEqual : _ref2$areStatesEqual,
        _ref2$areOwnPropsEqua = _ref2.areOwnPropsEqual,
        areOwnPropsEqual = _ref2$areOwnPropsEqua === undefined ? __WEBPACK_IMPORTED_MODULE_1__utils_shallowEqual__["a" /* default */] : _ref2$areOwnPropsEqua,
        _ref2$areStatePropsEq = _ref2.areStatePropsEqual,
        areStatePropsEqual = _ref2$areStatePropsEq === undefined ? __WEBPACK_IMPORTED_MODULE_1__utils_shallowEqual__["a" /* default */] : _ref2$areStatePropsEq,
        _ref2$areMergedPropsE = _ref2.areMergedPropsEqual,
        areMergedPropsEqual = _ref2$areMergedPropsE === undefined ? __WEBPACK_IMPORTED_MODULE_1__utils_shallowEqual__["a" /* default */] : _ref2$areMergedPropsE,
        extraOptions = _objectWithoutProperties(_ref2, ['pure', 'areStatesEqual', 'areOwnPropsEqual', 'areStatePropsEqual', 'areMergedPropsEqual']);

    var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps');
    var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps');
    var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps');

    return connectHOC(selectorFactory, _extends({
      // used in error messages
      methodName: 'connect',

      // used to compute Connect's displayName from the wrapped component's displayName.
      getDisplayName: function getDisplayName(name) {
        return 'Connect(' + name + ')';
      },

      // if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
      shouldHandleStateChanges: Boolean(mapStateToProps),

      // passed through to selectorFactory
      initMapStateToProps: initMapStateToProps,
      initMapDispatchToProps: initMapDispatchToProps,
      initMergeProps: initMergeProps,
      pure: pure,
      areStatesEqual: areStatesEqual,
      areOwnPropsEqual: areOwnPropsEqual,
      areStatePropsEqual: areStatePropsEqual,
      areMergedPropsEqual: areMergedPropsEqual

    }, extraOptions));
  };
}
860794
function connect(connector){
    return connector.connect().then(function() {
    	// Set time
    	date = new Date();

        // If we are here, we are connected
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Connected to: '+ connector.endpoint.host +'</p>');
    	
        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to errors</p>');

        // Subscribe to errors channel
        nem.com.websockets.subscribe.errors(connector, function(res){
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received error</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to new blocks</p>');

        // Subscribe to new blocks channel
        nem.com.websockets.subscribe.chain.blocks(connector, function(res){
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received a new block</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to recent transactions</p>');

        // Subscribe to recent transactions channel
        nem.com.websockets.subscribe.account.transactions.recent(connector, function(res){
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received recent transactions</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to account data of '+ connector.address +'</p>');

        // Subscribe to account data channel
        nem.com.websockets.subscribe.account.data(connector, function(res) {
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received account data</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to unconfirmed transactions of '+ connector.address +'</p>');

        // Subscribe to unconfirmed transactions channel
        nem.com.websockets.subscribe.account.transactions.unconfirmed(connector, function(res) {
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received unconfirmed transaction</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Subscribing to confirmed transactions of '+ connector.address +'</p>');

        // Subscribe to confirmed transactions channel
        nem.com.websockets.subscribe.account.transactions.confirmed(connector, function(res) {
            // Set time
            date = new Date();
            // Show event
            $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Received confirmed transaction</p>');
            // Show data
            $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(res) +'</pre>');
        });
        
        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Requesting account data of '+ connector.address +'</p>');

        // Request account data
        nem.com.websockets.requests.account.data(connector);

        // Show event
    	$('#stream').append('<p><b>'+ date.toLocaleString()+':</b> Requesting recent transactions of '+ connector.address +'</p>');
        
        // Request recent transactions
        nem.com.websockets.requests.account.transactions.recent(connector);

    }, function(err) {
        // Set time
        date = new Date();
        // Show event
        $('#stream').append('<p><b>'+ date.toLocaleString()+':</b> An error occured</p>');
        // Show data
        $('#stream').append('<p><b>'+ date.toLocaleString()+': <pre>' + JSON.stringify(err) +'</pre>');
        // Try to reconnect
        reconnect();
    });
}
188512
function OpenConnection(connection) {
    let base = new pg.Client({
        host: connection.Hostname || 'localhost',
        port: parseInt(connection.Port) || 5432,
        user: connection.Username,
        password: connection.Password,
        database: connection.Database
    });
    base.connect();
    return new PostgreSQL(base);
}
163494
function Connection(options) {
  //*****************************************************************
  // public API functions
  //*****************************************************************

  /**
   * Connect event
   *
   * @returns {Promise} promise
   */
  this.connect = () => {
    switch (_status) {
      case Status.NOT_CONNECTED:
        _status = Status.CONNECTING;
        return new Promise(function(resolve, reject) {
          _registerHandshakeCmd(resolve, reject);
        });

      case Status.CLOSING:
      case Status.CLOSED:
        return Promise.reject(
          Errors.createError(
            'Connection closed',
            true,
            info,
            '08S01',
            Errors.ER_CONNECTION_ALREADY_CLOSED
          )
        );

      case Status.CONNECTING:
      case Status.AUTHENTICATING:
        return Promise.reject(
          Errors.createError(
            'Connection is already connecting',
            true,
            info,
            '08S01',
            Errors.ER_ALREADY_CONNECTING
          )
        );
    }
    //status Connected
    return Promise.resolve(this);
  };

  /**
   * Permit to change user during connection.
   * All user variables will be reset, Prepare commands will be released.
   * !!! mysql has a bug when CONNECT_ATTRS capability is set, that is default !!!!
   *
   * @param options   connection options
   * @returns {Promise} promise
   */
  this.changeUser = options => {
    if (!info.isMariaDB()) {
      return Promise.reject(
        Errors.createError(
          'method changeUser not available for MySQL server due to Bug #83472',
          false,
          info,
          '0A000',
          Errors.ER_MYSQL_CHANGE_USER_BUG
        )
      );
    }

    return new Promise(function(resolve, reject) {
      _addCommand(
        new ChangeUser(
          options,
          resolve,
          _authFailHandler.bind(this, reject),
          _addCommand.bind(this)
        )
      );
    });
  };

  /**
   * Start transaction
   *
   * @returns {Promise} promise
   */
  this.beginTransaction = () => {
    return this.query('START TRANSACTION');
  };

  /**
   * Commit a transaction.
   *
   * @returns {Promise} command if commit was needed only
   */
  this.commit = () => {
    return _changeTransaction('COMMIT');
  };

  /**
   * Roll back a transaction.
   *
   * @returns {Promise} promise
   */
  this.rollback = () => {
    return _changeTransaction('ROLLBACK');
  };

  /**
   * Execute query using text protocol.
   *
   * @param sql     sql parameter Object can be used to supersede default option.
   *                Object must then have sql property.
   * @param values  object / array of placeholder values (not mandatory)
   * @returns {Promise} promise
   */
  this.query = (sql, values) => {
    let _cmdOpt, _sql;
    if (typeof sql === 'object') {
      _cmdOpt = sql;
      _sql = _cmdOpt.sql;
    } else {
      _sql = sql;
    }

    return new Promise(function(resolve, reject) {
      const cmd = new Query(resolve, reject, _cmdOpt, opts, _sql, values);
      if (opts.trace) Error.captureStackTrace(cmd);
      _addCommand(cmd);
    });
  };

  /**
   * Execute batch using text protocol.
   *
   * @param sql     sql parameter Object can be used to supersede default option.
   *                Object must then have sql property.
   * @param initialValues  object / array of placeholder values (not mandatory)
   * @returns {Promise} promise
   */
  this.batch = (sql, initialValues) => {
    let _options, _sql;
    if (typeof sql === 'object') {
      _options = sql;
      _sql = _options.sql;
    } else {
      _sql = sql;
    }

    return new Promise(function(resolve, reject) {
      let useBulk = canUseBulk(initialValues);

      const cmd = useBulk
        ? new BatchBulk(resolve, reject, _options, opts, _sql, initialValues)
        : new BatchRewrite(
            resolve,
            reject,
            _options,
            opts,
            _sql,
            initialValues
          );
      if (opts.trace) Error.captureStackTrace(cmd);
      _addCommand(cmd);
    });
  };

  /**
   * Execute query returning a Readable Object that will emit columns/data/end/error events
   * to permit streaming big result-set
   *
   * @param sql     sql parameter Object can be used to supersede default option.
   *                Object must then have sql property.
   * @param values  object / array of placeholder values (not mandatory)
   * @returns {Readable}
   */
  this.queryStream = (sql, values) => {
    let _cmdOpt, _sql;
    if (typeof sql === 'object') {
      _cmdOpt = sql;
      _sql = _cmdOpt.sql;
    } else {
      _sql = sql;
    }

    const cmd = new Stream(_cmdOpt, opts, _sql, values, _socket);
    if (opts.trace) Error.captureStackTrace(cmd);
    _addCommand(cmd);
    return cmd.inStream;
  };

  /**
   * Send an empty MySQL packet to ensure connection is active, and reset @@wait_timeout
   *
   * @returns {Promise} promise
   */
  this.ping = () => {
    return new Promise(function(resolve, reject) {
      return _addCommand(new Ping(resolve, reject));
    });
  };

  /**
   * Send a reset command that will
   * - rollback any open transaction
   * - reset transaction isolation level
   * - reset session variables
   * - delete user variables
   * - remove temporary tables
   * - remove all PREPARE statement
   *
   * @returns {Promise} promise
   */
  this.reset = () => {
    if (
      (info.isMariaDB() && info.hasMinVersion(10, 2, 4)) ||
      (!info.isMariaDB() && info.hasMinVersion(5, 7, 3))
    ) {
      return new Promise(function(resolve, reject) {
        return _addCommand(new Reset(resolve, reject));
      });
    }
    return Promise.reject(
      new Error(
        'Reset command not permitted for server ' + this.info.serverVersion
      )
    );
  };

  /**
   * Indicates the state of the connection as the driver knows it
   * @returns {boolean}
   */
  this.isValid = () => {
    return _status === Status.CONNECTED;
  };

  /**
   * Terminate connection gracefully.
   *
   * @returns {Promise} promise
   */
  this.end = () => {
    _addCommand = _addCommandDisabled;
    clearTimeout(_timeout);

    if (
      _status !== Status.CLOSING &&
      _status !== Status.CLOSED &&
      _status !== Status.NOT_CONNECTED
    ) {
      _status = Status.CLOSING;
      return new Promise(function(resolve, reject) {
        const ended = () => {
          _status = Status.CLOSED;
          _socket.destroy();
          _socket.unref();
          _clear();
          _receiveQueue.clear();
          resolve();
        };
        const quitCmd = new Quit(ended, ended);
        _sendQueue.push(quitCmd);
        _receiveQueue.push(quitCmd);
        if (_sendQueue.length === 1) {
          process.nextTick(_nextSendCmd.bind(this));
        }
      });
    }
    return Promise.resolve();
  };

  /**
   * Alias for destroy.
   */
  this.close = function() {
    this.destroy();
  };

  /**
   * Force connection termination by closing the underlying socket and killing server process if any.
   */
  this.destroy = () => {
    _addCommand = _addCommandDisabled;
    clearTimeout(_timeout);
    if (_status !== Status.CLOSING && _status !== Status.CLOSED) {
      _status = Status.CLOSING;
      _sendQueue.clear();
      if (_receiveQueue.length > 0) {
        //socket is closed, but server may still be processing a huge select
        //only possibility is to kill process by another thread
        //TODO reuse a pool connection to avoid connection creation
        const self = this;
        const killCon = new Connection(opts);
        killCon
          .connect()
          .then(() => {
            //*************************************************
            //kill connection
            //*************************************************
            const killResHandler = () => {
              const destroyError = Errors.createError(
                'Connection destroyed, command was killed',
                true,
                info,
                '08S01',
                Errors.ER_CMD_NOT_EXECUTED_DESTROYED
              );
              socketErrorDispatchToQueries(destroyError);
              process.nextTick(() => {
                if (_socket) _socket.destroy();
              });
              _status = Status.CLOSED;
              killCon.end().catch(() => {});
            };

            killCon
              .query('KILL ' + info.threadId)
              .then(killResHandler)
              .catch(killResHandler);
          })
          .catch(err => {
            //*************************************************
            //failing to create a kill connection, end normally
            //*************************************************
            const ended = () => {
              let sock = _socket;
              _clear();
              _status = Status.CLOSED;
              setImmediate(resolve);
              sock.destroy();
              _receiveQueue.clear();
            };
            const quitCmd = new Quit(ended, ended);
            _sendQueue.push(quitCmd);
            _receiveQueue.push(quitCmd);
            if (_sendQueue.length === 1) {
              process.nextTick(_nextSendCmd.bind(self));
            }
          });
      } else {
        _status = Status.CLOSED;
        _socket.destroy();
      }
    }
    _clear();
  };

  this.pause = () => {
    _socket.pause();
  };

  this.resume = () => {
    _socket.resume();
  };

  this.escape = value => {
    throw Errors.createError(
      '"Connection.escape intentionally not implemented. please use Connection.query(sql, values), it will be more secure and faster',
      false,
      info,
      '0A000',
      Errors.ER_NOT_IMPLEMENTED_ESCAPE
    );
  };

  this.escapeId = value => {
    throw Errors.createError(
      '"Connection.escapeId intentionally not implemented. please use Connection.query(sql, values), it will be more secure and faster',
      false,
      info,
      '0A000',
      Errors.ER_NOT_IMPLEMENTED_ESCAPEID
    );
  };

  this.format = (sql, values) => {
    throw Errors.createError(
      '"Connection.format intentionally not implemented. please use Connection.query(sql, values), it will be more secure and faster',
      false,
      info,
      '0A000',
      Errors.ER_NOT_IMPLEMENTED_FORMAT
    );
  };

  //*****************************************************************
  // additional public methods
  //*****************************************************************

  /**
   * return current connected server version information.
   *
   * @returns {*}
   */
  this.serverVersion = () => {
    if (!info.serverVersion)
      throw new Error(
        'cannot know if server information until connection is established'
      );
    return info.serverVersion.raw;
  };

  /**
   * Change option "debug" during connection.
   * @param val   debug value
   */
  this.debug = val => {
    opts.debug = val;
  };

  this.debugCompress = val => {
    opts.debugCompress = val;
  };

  //*****************************************************************
  // internal public testing methods
  //*****************************************************************

  function TestMethods() {}
  TestMethods.prototype.getCollation = () => {
    return opts.collation;
  };

  TestMethods.prototype.getSocket = () => {
    return _socket;
  };

  this.__tests = new TestMethods();

  //*****************************************************************
  // internal methods
  //*****************************************************************

  this._status = () => {
    return _status;
  };

  /**
   * Execute query using text protocol with callback emit columns/data/end/error
   * events to permit streaming big result-set
   *
   * @param sql     sql parameter Object can be used to supersede default option.
   *                Object must then have sql property.
   * @param values  object / array of placeholder values (not mandatory)
   * @param cb      callback
   * @returns {Query} query
   */
  this._queryCallback = (sql, values, cb) => {
    let _cmdOpts, _sql, _values;
    let _cb = cb;
    if (typeof sql === 'object') {
      _cmdOpts = sql;
      _sql = _cmdOpts.sql;
    } else {
      _sql = sql;
    }

    if (typeof values === 'function') {
      _cb = values;
    } else if (values !== undefined) {
      _values = values;
    }

    let cmd;
    if (_cb) {
      const resolve = rows => {
        const meta = rows.meta;
        delete rows.meta;
        _cb(null, rows, meta);
      };
      cmd = new Query(resolve, _cb, _cmdOpts, opts, _sql, _values);
    } else {
      cmd = new Query(() => {}, () => {}, _cmdOpts, opts, _sql, _values);
    }
    cmd.handleNewRows = row => {
      cmd._rows[cmd._responseIndex].push(row);
      cmd.emit('data', row);
    };

    if (opts.trace) Error.captureStackTrace(cmd);
    _addCommand(cmd);
    return cmd;
  };

  /**
   * Execute a batch using text protocol with callback emit columns/data/end/error
   * events to permit streaming big result-set
   *
   * @param sql     sql parameter Object can be used to supersede default option.
   *                Object must then have sql property.
   * @param values  object / array of placeholder values (not mandatory)
   * @param cb      callback
   * @returns {Query} query
   */
  this._batchCallback = (sql, values, cb) => {
    let _cmdOpts, _sql, _values;
    let _cb = cb;
    if (typeof sql === 'object') {
      _cmdOpts = sql;
      _sql = _cmdOpts.sql;
    } else {
      _sql = sql;
    }

    if (typeof values === 'function') {
      _cb = values;
    } else if (values !== undefined) {
      _values = values;
    }

    let cmd;

    let useBulk = canUseBulk(_values);

    const fct = useBulk ? BatchBulk : BatchRewrite;

    if (_cb) {
      const resolve = rows => {
        const meta = rows.meta;
        delete rows.meta;
        _cb(null, rows, meta);
      };
      cmd = new fct(resolve, _cb, _cmdOpts, opts, _sql, _values);
    } else {
      cmd = new fct(() => {}, () => {}, _cmdOpts, opts, _sql, _values);
    }
    cmd.handleNewRows = row => {
      cmd._rows[cmd._responseIndex].push(row);
      cmd.emit('data', row);
    };

    if (opts.trace) Error.captureStackTrace(cmd);
    _addCommand(cmd);
    return cmd;
  };

  /**
   * Use Batch rewrite or MariaDB bulk protocol.
   *
   * @param _values current batch values
   * @return {boolean} indicating if must use rewrite or bulk
   */
  const canUseBulk = _values => {
    let useBulk = info.isMariaDB() && info.hasMinVersion(10, 2, 7) && opts.bulk;
    if (useBulk) {
      //ensure that there is no stream object
      if (_values !== undefined) {
        const values = Array.isArray(_values) ? _values : [_values];
        const paramLen = Array.isArray(values[0]) ? values[0].length : 1;
        if (!opts.namedPlaceholders) {
          for (let r = 0; r < values.length; r++) {
            let row = values[r];
            if (!Array.isArray(row)) row = [row];
            if (paramLen !== row.length) {
              useBulk = false;
              break;
            }
            for (let j = 0; j < paramLen; j++) {
              const val = row[j];
              if (
                val !== null &&
                typeof val === 'object' &&
                typeof val.pipe === 'function' &&
                typeof val.read === 'function'
              ) {
                useBulk = false;
                break;
              }
            }
            if (!useBulk) break;
          }
        } else {
          for (let r = 0; r < values.length; r++) {
            let row = values[r];
            const keys = Object.keys(row);
            for (let j = 0; j < keys.length; j++) {
              const val = row[keys[j]];
              if (
                val !== null &&
                typeof val === 'object' &&
                typeof val.pipe === 'function' &&
                typeof val.read === 'function'
              ) {
                useBulk = false;
                break;
              }
            }
            if (!useBulk) break;
          }
        }
      }
    }
    return useBulk;
  };

  /**
   * Add handshake command to queue.
   *
   * @private
   */
  const _registerHandshakeCmd = (resolve, rejected) => {
    const _authFail = _authFailHandler.bind(this, rejected);
    const _authSucceed = _authSucceedHandler.bind(this, resolve, _authFail);

    const handshake = new Handshake(
      _authSucceed,
      _authFail,
      _createSecureContext.bind(this, _authFail),
      _addCommand.bind(this),
      _getSocket
    );
    Error.captureStackTrace(handshake);

    handshake.once('end', () => {
      process.nextTick(_nextSendCmd);
    });

    _receiveQueue.push(handshake);
    _initSocket(_authFail);
  };

  const _executeSessionVariableQuery = () => {
    if (opts.sessionVariables) {
      const values = [];
      let sessionQuery = 'set ';
      let keys = Object.keys(opts.sessionVariables);
      if (keys.length > 0) {
        return new Promise(function(resolve, reject) {
          for (let k = 0; k < keys.length; ++k) {
            sessionQuery +=
              (k !== 0 ? ',' : '') +
              '@@' +
              keys[k].replace(/[^a-z0-9_]/gi, '') +
              '=?';
            values.push(opts.sessionVariables[keys[k]]);
          }
          const errorHandling = initialErr => {
            reject(
              Errors.createError(
                'Error setting session variable (value ' +
                  JSON.stringify(opts.sessionVariables) +
                  '). Error: ' +
                  initialErr.message,
                true,
                info,
                '08S01',
                Errors.ER_SETTING_SESSION_ERROR,
                null
              )
            );
          };
          const cmd = new Query(
            resolve,
            errorHandling,
            null,
            opts,
            sessionQuery,
            values
          );
          if (opts.trace) Error.captureStackTrace(cmd);
          _addCommand(cmd);
        });
      }
    }
    return Promise.resolve();
  };

  /**
   * Asking server timezone if not set
   * @returns {Promise<void>|Promise<T | never>}
   * @private
   */
  const _checkServerTimezone = () => {
    if (opts.timezone === 'local' || opts.tz) {
      return Promise.resolve();
    }
    return this.query('SELECT @@system_time_zone stz, @@time_zone tz').then(
      res => {
        const serverTimezone = res[0].tz === 'SYSTEM' ? res[0].stz : res[0].tz;
        const serverZone = moment.tz.zone(serverTimezone);
        if (serverZone) {
          if (serverTimezone === moment.tz.guess()) {
            //db server and client use same timezone, avoid any conversion
            opts.tz = null;
          } else {
            opts.tz = moment.tz.setDefault(serverTimezone);
          }
        } else {
          return Promise.reject(
            Errors.createError(
              "Automatic timezone setting fails. Server timezone '" +
                serverTimezone +
                "' does't have a corresponding IANA timezone. Option timezone must be set according to server timezone",
              true,
              info,
              '08S01',
              Errors.ER_WRONG_AUTO_TIMEZONE
            )
          );
        }
        return Promise.resolve();
      }
    );
  };

  const _executeInitQuery = () => {
    if (opts.initSql) {
      const initialArr = Array.isArray(opts.initSql)
        ? opts.initSql
        : [opts.initSql];
      const initialPromises = [];
      initialArr.forEach(sql => {
        initialPromises.push(
          new Promise(function(resolve, reject) {
            const errorHandling = initialErr => {
              reject(
                Errors.createError(
                  'Error executing initial sql command: ' + initialErr.message,
                  true,
                  info,
                  '08S01',
                  Errors.ER_INITIAL_SQL_ERROR,
                  null
                )
              );
            };
            const cmd = new Query(
              resolve,
              errorHandling,
              null,
              opts,
              sql,
              null
            );
            if (opts.trace) Error.captureStackTrace(cmd);
            _addCommand(cmd);
          })
        );
      });
      return Promise.all(initialPromises);
    }
    return Promise.resolve();
  };

  const _getSocket = () => {
    return _socket;
  };

  /**
   * Initialize socket and associate events.
   * @private
   */
  const _initSocket = authFailHandler => {
    if (opts.socketPath) {
      _socket = Net.connect(opts.socketPath);
    } else {
      _socket = Net.connect(opts.port, opts.host);
    }

    if (opts.connectTimeout) {
      _timeout = setTimeout(
        _connectTimeoutReached,
        opts.connectTimeout,
        authFailHandler
      );
    }

    const _socketError = _socketErrorHandler.bind(this, authFailHandler);

    _socket.on('data', _in.onData.bind(_in));
    _socket.on('error', _socketError);
    _socket.on('end', _socketError);
    _socket.on(
      'connect',
      function() {
        clearTimeout(_timeout);
        if (_status === Status.CONNECTING) {
          _status = Status.AUTHENTICATING;
          _socketConnected = true;
          _socket.setTimeout(
            opts.socketTimeout,
            _socketTimeoutReached.bind(this, authFailHandler)
          );
          _socket.setNoDelay(true);
        }
      }.bind(this)
    );

    _socket.writeBuf = _socket.write;
    _socket.flush = () => {};
    _out.setStream(_socket);
  };

  /**
   * Authentication success result handler.
   *
   * @private
   */
  const _authSucceedHandler = (resolve, rejected) => {
    //enable packet compression according to option
    if (opts.logPackets) info.enableLogPacket();
    if (opts.compress) {
      if (info.serverCapabilities & Capabilities.COMPRESS) {
        _out.setStream(new CompressionOutputStream(_socket, opts, info));
        _in = new CompressionInputStream(_in, _receiveQueue, opts, info);
        _socket.removeAllListeners('data');
        _socket.on('data', _in.onData.bind(_in));
      } else {
        console.error(
          "connection is configured to use packet compression, but the server doesn't have this capability"
        );
      }
    }

    if (opts.pipelining) {
      _addCommand = _addCommandEnablePipeline;
      const commands = _receiveQueue.toArray();
      commands.forEach(cmd => {
        const listeners = cmd.listeners('end');
        cmd.removeListener('end', listeners[0]);
        cmd.once('send_end', () => {
          setImmediate(_nextSendCmd);
        });
      });
    }

    const errorInitialQueries = err => {
      if (!err.fatal) this.end().catch(err => {});
      process.nextTick(rejected, err);
    };

    _executeSessionVariableQuery()
      .then(() => {
        return _checkServerTimezone();
      })
      .then(() => {
        return _executeInitQuery();
      })
      .then(() => {
        _status = Status.CONNECTED;
        process.nextTick(resolve, this);
      })
      .catch(errorInitialQueries);
  };

  /**
   * Authentication failed result handler.
   *
   * @private
   */
  const _authFailHandler = (reject, err) => {
    process.nextTick(reject, err);
    //remove handshake command
    _receiveQueue.shift();

    _fatalError(err, true);
  };

  /**
   * Create TLS socket and associate events.
   *
   * @param rejected  rejected function when error
   * @param callback  callback function when done
   * @private
   */
  const _createSecureContext = (rejected, callback) => {
    const _socketError = _socketErrorHandler.bind(this, rejected);
    const sslOption = Object.assign({}, opts.ssl, {
      servername: opts.host,
      socket: _socket
    });

    try {
      const secureSocket = tls.connect(sslOption, callback);

      secureSocket.on('data', _in.onData.bind(_in));
      secureSocket.on('error', _socketError);
      secureSocket.on('end', _socketError);
      secureSocket.writeBuf = secureSocket.write;
      secureSocket.flush = () => {};

      _socket.removeAllListeners('data');
      _socket = secureSocket;

      _out.setStream(secureSocket);
    } catch (err) {
      _socketError(err);
    }
  };

  /**
   * Handle packet when no packet is expected.
   * (there can be an ERROR packet send by server/proxy to inform that connection is ending).
   *
   * @param packet  packet
   * @private
   */
  const _unexpectedPacket = function(packet) {
    if (packet && packet.peek() === 0xff) {
      //can receive unexpected error packet from server/proxy
      //to inform that connection is closed (usually by timeout)
      let err = packet.readError(info);
      if (
        err.fatal &&
        (_status !== Status.CLOSING && _status !== Status.CLOSED)
      ) {
        this.emit('error', err);
        this.end();
      }
    } else if (_status !== Status.CLOSING && _status !== Status.CLOSED) {
      this.emit(
        'error',
        Errors.createError(
          'receiving packet from server without active commands\n' +
            'conn:' +
            (info.threadId ? info.threadId : -1) +
            '(' +
            packet.pos +
            ',' +
            packet.end +
            ')\n' +
            Utils.log(opts, packet.buf, packet.pos, packet.end),
          true,
          info,
          '08S01',
          Errors.ER_UNEXPECTED_PACKET
        )
      );
      this.destroy();
    }
  };

  /**
   * Change transaction state.
   *
   * @param sql sql
   * @returns {Promise} promise
   * @private
   */
  const _changeTransaction = sql => {
    //if command in progress, driver cannot rely on status and must execute query
    if (_status === Status.CLOSING || _status === Status.CLOSED) {
      return Promise.reject(
        Errors.createError(
          'Cannot execute new commands: connection closed\nsql: ' + sql,
          true,
          info,
          '08S01',
          Errors.ER_CMD_CONNECTION_CLOSED
        )
      );
    }

    //Command in progress => must execute query
    //or if no command in progress, can rely on status to know if query is needed
    if (
      _receiveQueue.peekFront() ||
      info.status & ServerStatus.STATUS_IN_TRANS
    ) {
      return new Promise(function(resolve, reject) {
        const cmd = new Query(resolve, reject, null, opts, sql, null);
        if (opts.trace) Error.captureStackTrace(cmd);
        _addCommand(cmd);
      });
    }
    return Promise.resolve();
  };

  /**
   * Handle connection timeout.
   *
   * @private
   */
  const _connectTimeoutReached = function(authFailHandler) {
    _timeout = null;
    const handshake = _receiveQueue.peekFront();
    authFailHandler(
      Errors.createError(
        'Connection timeout',
        true,
        info,
        '08S01',
        Errors.ER_CONNECTION_TIMEOUT,
        handshake ? handshake.stack : null
      )
    );
  };

  /**
   * Handle socket timeout.
   *
   * @private
   */
  const _socketTimeoutReached = function() {
    const err = Errors.createError(
      'socket timeout',
      true,
      info,
      '08S01',
      Errors.ER_SOCKET_TIMEOUT
    );
    const packetMsgs = info.getLastPackets();
    if (packetMsgs !== '') {
      err.message = err.message + '\nlast received packets:\n' + packetMsgs;
    }
    _fatalError(err, true);
  };

  /**
   * Add command to command sending and receiving queue.
   *
   * @param cmd         command
   * @returns {*}       current command
   * @private
   */
  const _addCommandEnable = cmd => {
    cmd.once('end', () => {
      setImmediate(_nextSendCmd);
    });

    //send immediately only if no current active receiver
    if (_sendQueue.isEmpty() && _status === Status.CONNECTED) {
      if (_receiveQueue.peekFront()) {
        _receiveQueue.push(cmd);
        _sendQueue.push(cmd);
        return cmd;
      }

      _receiveQueue.push(cmd);
      cmd.start(_out, opts, info);
    } else {
      _receiveQueue.push(cmd);
      _sendQueue.push(cmd);
    }
    return cmd;
  };

  /**
   * Add command to command sending and receiving queue using pipelining
   *
   * @param cmd         command
   * @returns {*}       current command
   * @private
   */
  const _addCommandEnablePipeline = cmd => {
    cmd.once('send_end', () => {
      setImmediate(_nextSendCmd);
    });

    _receiveQueue.push(cmd);
    if (_sendQueue.isEmpty()) {
      cmd.start(_out, opts, info);
      if (cmd.sending) {
        _sendQueue.push(cmd);
        cmd.prependOnceListener('send_end', () => {
          _sendQueue.shift();
        });
      }
    } else {
      _sendQueue.push(cmd);
    }
    return cmd;
  };

  /**
   * Replacing command when connection is closing or closed to send a proper error message.
   *
   * @param cmd         command
   * @private
   */
  const _addCommandDisabled = cmd => {
    cmd.throwNewError(
      'Cannot execute new commands: connection closed\n' + cmd.displaySql(),
      true,
      info,
      '08S01',
      Errors.ER_CMD_CONNECTION_CLOSED
    );
  };

  /**
   * Handle socket error.
   *
   * @param authFailHandler   authentication handler
   * @param err               socket error
   * @private
   */
  const _socketErrorHandler = function(authFailHandler, err) {
    if (_status === Status.CLOSING || _status === Status.CLOSED) return;

    _socket.writeBuf = () => {};
    _socket.flush = () => {};

    //socket has been ended without error
    if (!err) {
      err = Errors.createError(
        'socket has unexpectedly been closed',
        true,
        info,
        '08S01',
        Errors.ER_SOCKET_UNEXPECTED_CLOSE
      );
    } else {
      err.fatal = true;
      this.sqlState = 'HY000';
    }

    const packetMsgs = info.getLastPackets();
    if (packetMsgs !== '') {
      err.message += '\nlast received packets:\n' + packetMsgs;
    }

    switch (_status) {
      case Status.CONNECTING:
      case Status.AUTHENTICATING:
        const currentCmd = _receiveQueue.peekFront();
        if (currentCmd && currentCmd.stack && err) {
          err.stack +=
            '\n From event:\n' +
            currentCmd.stack.substring(currentCmd.stack.indexOf('\n') + 1);
        }
        authFailHandler(err);
        break;

      default:
        _fatalError(err, false);
    }
  };

  /**
   * Fatal unexpected error : closing connection, and throw exception.
   *
   * @param self    current connection
   * @private
   */
  const _fatalErrorHandler = function(self) {
    return function(err, avoidThrowError) {
      if (_status === Status.CLOSING || _status === Status.CLOSED) {
        socketErrorDispatchToQueries(err);
        return;
      }
      const mustThrowError = _status !== Status.CONNECTING;
      _status = Status.CLOSING;

      //prevent executing new commands
      _addCommand = _addCommandDisabled;

      if (_socket) {
        _socket.removeAllListeners('error');
        _socket.removeAllListeners('timeout');
        _socket.removeAllListeners('close');
        _socket.removeAllListeners('data');
        if (!_socket.destroyed) _socket.destroy();
        _socket = undefined;
      }
      _status = Status.CLOSED;

      const errorThrownByCmd = socketErrorDispatchToQueries(err);
      if (mustThrowError) {
        if (self.listenerCount('error') > 0) {
          self.emit('error', err);
          self.emit('end');
          _clear();
        } else {
          self.emit('end');
          _clear();
          //error will be thrown if no error listener and no command did throw the exception
          if (!avoidThrowError && !errorThrownByCmd) throw err;
        }
      } else {
        _clear();
      }
    };
  };

  /**
   * Dispatch fatal error to current running queries.
   *
   * @param err        the fatal error
   * @return {boolean} return if error has been relayed to queries
   */
  const socketErrorDispatchToQueries = err => {
    let receiveCmd;
    let errorThrownByCmd = false;
    while ((receiveCmd = _receiveQueue.shift())) {
      if (receiveCmd && receiveCmd.onPacketReceive) {
        errorThrownByCmd = true;
        setImmediate(receiveCmd.throwError.bind(receiveCmd), err, info);
      }
    }
    return errorThrownByCmd;
  };

  /**
   * Will send next command in queue if any.
   *
   * @private
   */
  const _nextSendCmd = () => {
    let sendCmd;
    if ((sendCmd = _sendQueue.shift())) {
      if (sendCmd.sending) {
        _sendQueue.unshift(sendCmd);
      } else {
        sendCmd.start(_out, opts, info);
        if (sendCmd.sending) {
          sendCmd.prependOnceListener('send_end', () => {
            _sendQueue.shift();
          });
          _sendQueue.unshift(sendCmd);
        }
      }
    }
  };

  /**
   * Clearing connection variables when ending.
   *
   * @private
   */
  const _clear = () => {
    _sendQueue.clear();
    _out = undefined;
    _socket = undefined;
  };

  //*****************************************************************
  // internal variables
  //*****************************************************************

  EventEmitter.call(this);
  const opts = Object.assign({}, options);
  const info = new ConnectionInformation();
  const _sendQueue = new Queue();
  const _receiveQueue = new Queue();
  let _status = Status.NOT_CONNECTED;
  let _socketConnected = false;
  let _socket = null;
  let _timeout = null;
  let _addCommand = _addCommandEnable;
  const _fatalError = _fatalErrorHandler(this);
  let _out = new PacketOutputStream(opts, info);
  let _in = new PacketInputStream(
    _unexpectedPacket.bind(this),
    _receiveQueue,
    _out,
    opts,
    info
  );

  //add alias threadId for mysql/mysql2 compatibility
  Object.defineProperty(this, 'threadId', {
    get() {
      return info ? info.threadId : undefined;
    }
  });
  Object.defineProperty(this, 'info', {
    get() {
      return info;
    }
  });
}
675780
async function getFrontendData(file) {
  const localPath = path.join(macros.PUBLIC_DIR, file);
  const exists = await fs.exists(localPath);

  // Exists locally, great
  if (exists) {
    const body = await fs.readFile(localPath);
    return JSON.parse(body);
  }

  macros.log('Downloading ', file, ' from searchneu.com becaues it does not exist locally.');

  // Download from https://searchneu.com
  // Note this goes through the local request cache
  let resp;
  try {
    resp = await request.get(`https://searchneu.com/data/v${macros.schemaVersion}/${file}`);
  } catch (e) {
    macros.error('Unable to load frontend data from locally or from searchneu.com!', file, e);
    return null;
  }

  await mkdirp(path.dirname(localPath));

  let data;

  try {
    data = JSON.parse(resp.body);
  } catch (e) {
    macros.log('Could not download term', file, 'from server!');
    macros.log('Probably going to crash');
    return null;
  }

  // Save that locally
  await fs.writeFile(localPath, resp.body);

  return data;
}
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
588197
function updateServicesJS(newFileName) {

  console.log(" 🔰  updating: ".cyan + "components.js".white);

  if (process.cwd().includes('client/app/services') === false) {
    process.chdir(`./client/app/services`);
  }

  if (process.cwd().includes(`client/app/services/${newFileName}`) === true) {
    process.chdir('..');
  }

  componentsArray = [];
  genArr = [];


  // sync with updates
  fs.readdir(process.cwd(), function (err, items) {
    genArr = items;
    generateDirectArray(genArr);
  });


  function generateDirectArray(items) {
    for (var i = 0; i < items.length; i++) {
      if (isDirectory(items[i])) {
      } else {
        componentsArray.push(items[i]);
      }
    }
    importStringGenerator();
  }

  function isDirectory(inputString) {
    var str = inputString;
    var patt = new RegExp("[.]");
    var res = patt.test(str);
    return res;
  }

  function importStringGenerator() {

    genString = "";
    for (var i = 0; i < componentsArray.length; i++) {
      genString = genString + `import ${componentsArray[i]}Service from './${componentsArray[i]}/${componentsArray[i]}';\r`
    }

    listString = "";
    for (var i = 0; i < componentsArray.length; i++) {

      // check if last in list in order to not include comma
      if (i === (componentsArray.length - 1)) {
        listString = listString + `  .service('${componentsArray[i]}Service', ${componentsArray[i]}Service);` + `\r`
      } else {
        listString = listString + `  .service('${componentsArray[i]}Service', ${componentsArray[i]}Service)` + `\r`
      }
    }


    fs.writeFile("services.js", `import angular from 'angular';
${genString}

const ServicesModule = angular.module('app.services', [])
${listString}

export default ServicesModule;`, function (err) {
      if (err) {
        return console.log(` ❌  failed to update due to error:  ${err}`);
      }
      console.log(" 🔰  updated: ".cyan + "services.js".white);
    });
  }
}
1322580
function connect (conf) {
  // Instantiating API client, this is the one that will be passed to other methods
  var client = new Client();

  if (conf["my-host.token"]) {
    // Authorize client
    client.setToken(conf["my-host.token"]);
    // Check token…
    return checkToken(client)
      .then(null, function () {
        // …and create a new one if it failed
        console.error("Existing token is invalid");
        return createToken(client);
      });
  } else {
    // No token found: create new one
    return createToken(client);
  }
}
1206338
function _connect(nodeOrId, event, eventHandler) {
		var node = lib.node(nodeOrId);
		if (node) {
			node.addEventListener(event, eventHandler, false);
		}
	}
1223468
function ElementsEventHandler(socket) {
  var _this = this;
  //Call EventEmmiter _contructor_
  events.EventEmitter.call(this);
  this.socket = socket;

  // On every message event received by socket we get
  // an message event object like {event:, data:} 
  // we emit  a local event through an EventEmitter interface
  // with .event as event type and .data as
  // event data;
  this.socket.on('message', function(message, callback) {
    debug("Forwarding frontend message '%s', with data %j", message.event, message.data);
    if (message.event !== undefined) {
      _this.emit(message.event, message.data);
      if (typeof callback === 'function') {
        callback();
      }
    }
    if (message.event === "userinput" && message.scope !== undefined) {
      debug("userinput received: %s", JSON.stringify(message));
      _this.emit(message.scope, message.data);
    }
  });
  this.socket.on("disconnect", function() {
    delete(this.socket);
    _this.emit("disconnect");
  });
}
1201780
function (backend) {

    backend.Debug (4, "MySQL creating connection [%s]", backend.uid);
    backend.base = mysql.createConnection(backend.opts);
    backend.count ++;
      
    // register event for asynchronous server errors
    backend.base.on('error', function(err) {
        backend.Debug (1, "MySQL server error=[%s]", err);
        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
             backend.Debug (4, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
             
        } else { 
            throw err;  // server variable configures this)
        };
    });
    
    // force an initial connectiion at object construction time
    backend.base.connect (function(err) {
        if (err) {
             backend.Debug (4, "MySQL connection fail [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
            
        } else {
            backend.Debug (5,"MySQL Connect Done [%s]",  backend.uid);
        }
    });
}