<commit_before>var assert = require('assert');
var _ = require('lodash');
var RadDog = require('./dist/raddog');

describe('single item radix trie _operations', function(){
	before(function(done) {
		dog = new RadDog('uid', 'title');
		done();
	});
	it('should _lookup "sweater" as null', function() { assert.equal(dog._lookup('sweater'), null); });
	it('should _insert "sweater"', function() {
		var path;
		dog._insert('sweater', 'sweater-uid');
		assert.ok(dog.index.sweater);
		path = dog._lookup('sweater');
		assert.equal(path[0].node, dog.index);
		assert.equal(path[1].node, dog.index.sweater);
		assert.equal(dog.index[' count'], 1);
		assert.equal(dog.index[' items'].length, 0);
		assert.equal(dog.index.sweater[' count'], 1);
		assert.equal(dog.index.sweater[' items'].length, 1);
		assert.equal(dog.index.sweater[' items'][0], 'sweater-uid');
	});
	it('should _delete "sweater"', function() {
		dog._delete('sweater', 'sweater-uid');
		assert.equal(dog._lookup('sweater'), null);
		assert.equal(dog.index[' count'], 0);
		assert.equal(dog.index[' items'].length, 0);
	});
});

describe('multiple item radix trie _operations', function(){
	before(function(done) {
		dog = new RadDog('uid', 'title');
		done();
	});
	it('should _insert "dog", "dot", "doggy", "dock"', function() {
		var path;
		dog._insert('dog', 'dog-uid');
		dog._insert('dot', 'dot-uid');
		dog._insert('doggy', 'doggy-uid');
		dog._insert('dock', 'dock-uid');
		// "do" prefix should be split
		path = dog._lookup('dog');
		assert.equal(path.length, 3);
		path = dog._lookup('dot', 'dot-uid');
		assert.equal(path.length, 3);
		path = dog._lookup('doggy', 'doggy-uid');
		assert.equal(path.length, 4);
		path = dog._lookup('dock', 'dock-uid');
		assert.equal(path.length, 3);
	});
	it('should _delete "dog" and collapse', function() {
		dog._delete('dog', 'dog-uid');
		path = dog._lookup('doggy', 'doggy-uid');
		assert.equal(path.length, 3);
	});
});

describe('multiple item radix trie _operations', function(){
	before(function(done) {
		dog = new RadDog('uid', 'title');
		dog.insert({title:'nike roshe', uid: 'nike roshe uid'});
		dog.insert({title:'nike dunk high', uid: 'nike dunk womens uid'});
		dog.insert({title:'NIKE dunk high', uid: 'nike dunk mens uid'});
		dog.insert({title:'nike dunk sb low', uid: 'nike dunk mens uid'});
		dog.insert({title:'nike air force one', uid: 'nike air force one uid'});
		dog.insert({title:'nike freeruns', uid: 'nike freeruns uid'});
		dog.insert({title:'nike floaters', uid: 'nike floaters uid'});
		dog.insert({title:'nike flow', uid: 'nike flow uid'});
		done();
	});
	it('should find nike roshe item', function() {
		var cursor = dog.search('nike roshe');
		var item = cursor.next();
		assert.equal(item.uid, 'nike roshe uid');
	});
	it('should be able to assign two uids to one title', function() {
		var cursor = dog.search('nike dunk high');
		var item = cursor.next();
		assert.equal(cursor.end, false);
		var uid1 = item.uid;
		item = cursor.next();
		assert.notEqual(uid1, item.uid);
		item = cursor.next();
		assert.equal(cursor.end, true);
		assert.equal(item, null);
	});

});
<commit_msg>Added another test<commit_after>var assert = require('assert');
var _ = require('lodash');
var RadDog = require('./dist/raddog');

describe('single item radix trie _operations', function(){
	before(function(done) {
		dog = new RadDog('uid', 'title');
		done();
	});
	it('should _lookup "sweater" as null', function() { assert.equal(dog._lookup('sweater'), null); });
	it('should _insert "sweater"', function() {
		var path;
		dog._insert('sweater', 'sweater-uid');
		assert.ok(dog.index.sweater);
		path = dog._lookup('sweater');
		assert.equal(path[0].node, dog.index);
		assert.equal(path[1].node, dog.index.sweater);
		assert.equal(dog.index[' count'], 1);
		assert.equal(dog.index[' items'].length, 0);
		assert.equal(dog.index.sweater[' count'], 1);
		assert.equal(dog.index.sweater[' items'].length, 1);
		assert.equal(dog.index.sweater[' items'][0], 'sweater-uid');
	});
	it('should _delete "sweater"', function() {
		dog._delete('sweater', 'sweater-uid');
		assert.equal(dog._lookup('sweater'), null);
		assert.equal(dog.index[' count'], 0);
		assert.equal(dog.index[' items'].length, 0);
	});
});

describe('multiple item radix trie _operations', function(){
	before(function(done) {
		dog = new RadDog('uid', 'title');
		done();
	});
	it('should _insert "dog", "dot", "doggy", "dock"', function() {
		var path;
		dog._insert('dog', 'dog-uid');
		dog._insert('dot', 'dot-uid');
		dog._insert('doggy', 'doggy-uid');
		dog._insert('dock', 'dock-uid');
		// "do" prefix should be split
		path = dog._lookup('dog');
		assert.equal(path.length, 3);
		path = dog._lookup('dot', 'dot-uid');
		assert.equal(path.length, 3);
		path = dog._lookup('doggy', 'doggy-uid');
		assert.equal(path.length, 4);
		path = dog._lookup('dock', 'dock-uid');
		assert.equal(path.length, 3);
	});
	it('should _delete "dog" and collapse', function() {
		dog._delete('dog', 'dog-uid');
		path = dog._lookup('doggy', 'doggy-uid');
		assert.equal(path.length, 3);
	});
});

describe('multiple item radix trie _operations', function(){
	before(function(done) {
		dog = new RadDog('uid', 'title');
		dog.insert({title:'nike roshe', uid: 'nike roshe uid'});
		dog.insert({title:'nike dunk high', uid: 'nike dunk womens uid'});
		dog.insert({title:'nike dunk sb low', uid: 'nike dunk mens uid'});
		dog.insert({title:'NIKE dunk high', uid: 'nike dunk mens uid'});
		dog.insert({title:'nike air force one', uid: 'nike air force one uid'});
		dog.insert({title:'nike freeruns', uid: 'nike freeruns uid'});
		dog.insert({title:'nike floaters', uid: 'nike floaters uid'});
		dog.insert({title:'nike flow', uid: 'nike flow uid'});
		done();
	});
	it('should find nike roshe item', function() {
		var cursor = dog.search('nike roshe');
		var item = cursor.next();
		assert.equal(item.uid, 'nike roshe uid');
	});
	it('should be able to assign two uids to one title', function() {
		var cursor = dog.search('nike dunk high');
		var item = cursor.next();
		assert.equal(cursor.end, false);
		var uid1 = item.uid;
		item = cursor.next();
		assert.notEqual(uid1, item.uid);
		item = cursor.next();
		assert.equal(cursor.end, true);
		assert.equal(item, null);
	});
	it('should be able to do partial searches', function() {
		var cursor = dog.search('nike f');
		var item = cursor.next();
		var uid1 = item.uid;
		var title1 = item.title;
		item = cursor.next();
		assert.notEqual(uid1, item.uid);
		assert.notEqual(title1, item.title);
		var uid2 = item.uid;
		var title2 = item.title;
		item = cursor.next();
		assert.notEqual(uid1, item.uid);
		assert.notEqual(title1, item.title);
		assert.notEqual(uid2, item.uid);
		assert.notEqual(title2, item.title);
		item = cursor.next();
		item = cursor.next();
		assert.equal(cursor.end, true);
		assert.equal(item, null);
	});

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import {
    Checkbox,
    ControlLabel,
    FormControl,
    FormGroup,
    Radio
} from 'react-bootstrap';

class ExportOptions extends Component {
    render() {
        const {checkboxes, radios, separators, handleCheckboxChange, handleSeparatorChange} = this.props;

        return (

                <FormGroup>
                    <Checkbox inline
                        checked={checkboxes.location}
                        onChange={handleCheckboxChange}
                        value="location">
                        Include Location
                    </Checkbox>
                </FormGroup>
                <FormGroup>
                    <Checkbox inline
                        checked={checkboxes.date}
                        onChange={handleCheckboxChange}
                        value="date">
                        Include Date
                    </Checkbox>
                </FormGroup>

                <FormGroup>
                    <ControlLabel>Book Title Separator</ControlLabel>
                    <FormControl
                        type="text"
                        name="title"
                        value={separators.title}
                        onChange={handleSeparatorChange}
                    />
                </FormGroup>
                <FormGroup>
                    <ControlLabel>Clip Separator</ControlLabel>
                    <Radio name="clipSeparator"
                           checked={radios.separator === "none"}>None</Radio>
                    <Radio name="clipSeparator"
                           checked={radios.separator === "text"}>Text
                        <FormControl
                            type="text"
                            name="clip"
                            value={separators.clip}
                            onChange={handleSeparatorChange}
                        />
                    </Radio>
                    <Radio name="clipSeparator"
                           checked={radios.separator === "eol"}
                           onChange={handleRadioChange}
                           value="eol">Extra Line</Radio>

                </FormGroup>

        );
    }
}

ExportOptions.propTypes = {
    checkboxes:React.PropTypes.object,
    separators:React.PropTypes.object,
    handleCheckboxChange:React.PropTypes.func,
    handleSeparatorChange:React.PropTypes.func
};
export default ExportOptions;<commit_msg>Fixed the radios display for the clip separator.<commit_after>import React, { Component } from 'react';

import {
    Checkbox,
    ControlLabel,
    FormControl,
    FormGroup,
    Radio
} from 'react-bootstrap';

class ExportOptions extends Component {
    render() {
        const {checkboxes, radios, separators, handleCheckboxChange, handleRadioChange, handleSeparatorChange} = this.props;

        return (

                <FormGroup>
                    <Checkbox inline
                        checked={checkboxes.location}
                        onChange={handleCheckboxChange}
                        value="location">
                        Include Location
                    </Checkbox>
                </FormGroup>
                <FormGroup>
                    <Checkbox inline
                        checked={checkboxes.date}
                        onChange={handleCheckboxChange}
                        value="date">
                        Include Date
                    </Checkbox>
                </FormGroup>

                <FormGroup>
                    <ControlLabel>Book Title Separator</ControlLabel>
                    <FormControl
                        type="text"
                        name="title"
                        value={separators.title}
                        onChange={handleSeparatorChange}
                    />
                </FormGroup>
                <FormGroup>
                    <ControlLabel>Clip Separator</ControlLabel>
                    <Radio name="clip_separator"
                           checked={(radios.clip_separator === "none")}
                           onChange={handleRadioChange}
                           value="none">None</Radio>
                    <Radio name="clip_separator"
                           checked={(radios.clip_separator === "text")}
                           onChange={handleRadioChange}
                           value="text">Text
                        <FormControl
                            type="text"
                            name="clip"
                            disabled={!(radios.clip_separator === "text")}
                            value={separators.clip}
                            onChange={handleSeparatorChange}
                        />
                    </Radio>
                    <Radio name="clip_separator"
                           checked={(radios.clip_separator === "eol")}
                           onChange={handleRadioChange}
                           value="eol">Extra Line</Radio>

                </FormGroup>

        );
    }
}

ExportOptions.propTypes = {
    checkboxes:React.PropTypes.object,
    separators:React.PropTypes.object,
    handleCheckboxChange:React.PropTypes.func,
    handleSeparatorChange:React.PropTypes.func
};
export default ExportOptions;<|endoftext|>


<commit_before>var base = require('./');
var _ = require('lodash');
var assert = require('assert');
_.forIn(base, function(module, name) {
  console.log('Loading: ' + name);
   assert(module, 'Failed to load: ' + name);
});
console.log('WOOHOO! All of the modules import correctly.');
console.log('This is the only test we need for this package.');
<commit_msg>Add test to help ensure packages are versioned properly<commit_after>var base = require('./');
var _ = require('lodash');
var assert = require('assert');
var pack = require('./package.json');
var exec = require('child_process');

// First we test to see if all of the packages are
// importable safely.
_.forIn(base, function(module, name) {
  console.log('Loading: ' + name);
   assert(module, 'Failed to load: ' + name);
});
console.log('WOOHOO! All of the modules import correctly.');

// Now we check to see if a release is tagged correctly
// (If there is a releast at this revision at all)
var tag = exec.execSync('git tag -l --contains HEAD').toString().trim();
if (tag === '') {
  console.log('No git tag, no need to check release tag!');
} else {
  assert.equal('v' + pack.version, tag);
}

console.log('All tests passed.');
<|endoftext|>


<commit_before>/*
 * This script introduces a class representing a Gearman job server
 * and knowledge about protocol to communicate with it.
 *
 * (C) 2013 Vaclav Sykora
 * Apache License, Version 2.0, http://www.apache.org/licenses/
 *
 */

var net      = require('net'),
    util     = require('util'),
    winston  = require('winston'),
    Job      = require('./job').Job,
    common   = require('./common');

var JobServer = exports.JobServer = function (options) {
    // static logger
    if (JobServer.logger === undefined) {
        JobServer.logger = winston.loggers.get('JobServer');
    }
    // static register of all job servers

    options = options || {};

    // VALIDATION
    var pattern = { host: 'mandatory', port: 'mandatory' };
    var returned = common.verifyOptions(options, pattern);
    if (returned instanceof Error) { return returned; }

    this.host = options.host;
    this.port = options.port;

    this.connected = false;
    this.jobsWaiting4Created = []; // submited jobs waiting for JOB_CREATED response
    this.jobsWaiting4Complete = {}; // jobs with ID waiting for WORK_COMPLETE
};

/**
 * Method to establish a socket connection to a job server.
 * *callback(err)* called as
 *     * error callback when connection failed
 *     * success callback if connection opened, err=undefined
 */
JobServer.prototype.connect = function (callback) {
    var self = this;
    var eventNames;

    if (!(callback instanceof Function)) { return new Error('invalid callback (not a function)'); }

    if (this.connected) {
        callback();
    } else {
        this.socket = net.createConnection(this.port, this.host);

        // fallback event registration, only for debugging purposes
        eventNames = [ 'end', 'close', 'timeout', 'drain' ];
        eventNames.forEach(function (name) {
            self.socket.on(name, function() {
                JobServer.logger.log('warn', 'unhandled event, name=%s', name);
            });
        });

        // emitted when a socket connection is successfully established
        this.socket.on('connect', function () {
            self.socket.setKeepAlive(true);
            self.connected = true;
            JobServer.logger.log('debug', 'connection established: ', self.toString('minimal'));
            callback();
        });

        // emitted when an error occurs
        this.socket.on('error', function (err) {
            self.socket.destroy();
            delete self.socket;
            self.connected = false;
            JobServer.logger.log('error', 'socket error', err);
            callback(err);
        });

        this.socket.on('data', function (chunk) {
            JobServer.logger.log('verbose', 'received packet, len=' + chunk.length);
            JobServer.logger.log('verbose', 'data: %s', common.bufferAsHex(chunk));

            self.processData(chunk);
        });
    }

    return this.socket;
};

JobServer.prototype.disconnect = function () {
    var i, eventNames;

    this.connected = false;
    if (this.client) { // bidirectional association management
        this.client.emit('disconnect');
        delete this.client;
    }

    // clear buffered jobs #1
    for (i = 0; i < this.jobsWaiting4Created.length; i ++) {
        this.jobsWaiting4Created[i].abort();
    }
    this.jobsWaiting4Created.length = 0;
    // clear buffered jobs #2
    for (i in this.jobsWaiting4Complete) {
        if (this.jobsWaiting4Complete.hasOwnProperty(i)) {
            this.jobsWaiting4Complete[i].abort();
            delete this.jobsWaiting4Complete[i];
        }
    }

    // remove listeners from socket
    eventNames = [ 'connect', 'data', 'error', 'end', 'close', 'timeout', 'drain' ];
    for (i = 0; i < eventNames.length; i ++) {
        this.socket.removeAllListeners(eventNames[i]);
    }

    if (this.socket) {
        this.socket.end();
        delete this.socket;
    }
    JobServer.logger.log('debug', 'connection closed: ', this.toString('minimal'));
};

/**
 * Submits given job to job server.
 *
 * *callback(err)* called as
 *     * error callback when anything goes wrong
 *     * success callback when the job sent/submited over socket, err=undefined
 */
JobServer.prototype.submit = function (job, callback) {
    if (!this.connected) {
        callback(new Error('unconnected job server asked to send data'));
        return;
    }

    this.socket.write(job.encode(), job.encoding);
    job.processing = true;
    this.jobsWaiting4Created.push(job); // add to queue of submited jobs waiting for confirmation
    job.jobServer = this; // bidirectional association management
    JobServer.logger.log('debug', 'job submited, name=%s, type=%d', job.name, job.getPacketType());
    callback();
};

JobServer.prototype.getStatus = function (job, callback) {
    if (!this.connected) {
        callback(new Error('unconnected job server asked to submit a job'));
        return;
    }
}

JobServer.prototype.processData = function (chunk, callback) {
    if (!this.connected) {
        JobServer.logger.log('warn', 'trying to process data from disconnected job server (disconnect before all packet received?)');
        return;
    }

    if (chunk.readUInt32BE(0) != 0x00524553) { // \0RES
        // OUT OF SYNC!
        this._unrecoverableError('out of sync with server');
        return;
    }

    var jobId, job;
    var proceed = 12;

    var packetType = chunk.readUInt32BE(4);
    // response needs to be 12 bytes + body length (job handle + payload)
    var packetLength = chunk.readUInt32BE(8);

    switch (packetType) {
    case Job.PACKET_TYPES.JOB_CREATED:
        jobId = Job.getJobId(chunk, 12, 12 + packetLength);

        // remove it from queue of jobs waiting for JOB_CREATED
        if (this.jobsWaiting4Created.length === 0) {
            this._unrecoverableError('empty stack of job waiting 4 status CREATED');
            return;
        }
        job = this.jobsWaiting4Created.pop();

        job.id = jobId;

        // and put it into hash of created jobs
        this.jobsWaiting4Complete[jobId] = job;

        proceed += packetLength;
        JobServer.logger.log('verbose', 'job created, jobId=%s', jobId);
        if (this.jobsWaiting4Created.length === 0) {
            JobServer.logger.log('debug', 'no more a job waiting for state CREATED');
            if (this.client) { this.client.emit('done'); } // trigger event
        }

        job.emit('created'); // trigger event
        break;

    case Job.PACKET_TYPES.WORK_COMPLETE:
        // skip job handle => find next NULL
        var next0 = 12
        for (; next0 < chunk.length; next0 ++) {
            if (chunk.readUInt8(next0) == 0) {
                break;
            }
        }
        jobId = Job.getJobId(chunk, 12, next0);
        if (!this.jobsWaiting4Complete.hasOwnProperty(jobId)) {
            this._unrecoverableError('work complete, but unknown job, jobId=' + jobId);
            return;
        }
        job = this.jobsWaiting4Complete[jobId];
        job.processing = false;
        delete this.jobsWaiting4Complete[jobId]; // remove it from hash of created jobs

        JobServer.logger.log('verbose', 'work complete, jobId=%s', jobId);
        next0 ++;
        job.response = chunk.toString(job.encoding, next0, 12 + packetLength);

        proceed += packetLength;

        job.emit('complete'); // trigger event
        break;

    default:
        JobServer.logger.log('warn', 'unknown packet, type=%d', packetType);
        proceed = chunk.length; // stop processing of rest of the chunk
    }

    // recursive approach when more packets in buffer
    if (proceed < chunk.length) {
        this.processData(chunk.slice(proceed));
    }
}

/**
 * Gets an unique identifier of job server represented by the URL address.
 */
JobServer.prototype.getId = function() {
    return this.host + ':' + this.port;
}

/**
 * Returns a human readable string representation of the object.
 */
JobServer.prototype.toString = function (how) { // #unit: not needed
    if (how == 'minimal') {
        return 'host=' + this.host + ', port=' + this.port;
    }
    return 'JobServer(' + this.toString('minimal') + ')';
}

JobServer.prototype._unrecoverableError = function (msg) { // #unit: not needed
    JobServer.logger.log('error', msg);
    if (this.client) {
        this.client.emit('error', new Error(msg)); // trigger event
    }
}<commit_msg>working on JobServer#processResponse for STATUS_RES<commit_after>/*
 * This script introduces a class representing a Gearman job server
 * and knowledge about protocol to communicate with it.
 *
 * (C) 2013 Vaclav Sykora
 * Apache License, Version 2.0, http://www.apache.org/licenses/
 *
 */

var net      = require('net'),
    util     = require('util'),
    winston  = require('winston'),
    Job      = require('./job').Job,
    common   = require('./common');

var JobServer = exports.JobServer = function (options) {
    // static logger
    if (JobServer.logger === undefined) {
        JobServer.logger = winston.loggers.get('JobServer');
    }
    // static register of all job servers

    options = options || {};

    // VALIDATION
    var pattern = { host: 'mandatory', port: 'mandatory' };
    var returned = common.verifyOptions(options, pattern);
    if (returned instanceof Error) { return returned; }

    this.host = options.host;
    this.port = options.port;

    this.connected = false;
    this.jobsWaiting4Created = []; // submited jobs waiting for JOB_CREATED response
    this.jobsWaiting4Complete = {}; // jobs with ID waiting for WORK_COMPLETE
};

/**
 * Method to establish a socket connection to a job server.
 * *callback(err)* called as
 *     * error callback when connection failed
 *     * success callback if connection opened, err=undefined
 */
JobServer.prototype.connect = function (callback) {
    var self = this;
    var eventNames;

    if (!(callback instanceof Function)) { return new Error('invalid callback (not a function)'); }

    if (this.connected) {
        callback();
    } else {
        this.socket = net.createConnection(this.port, this.host);

        // fallback event registration, only for debugging purposes
        eventNames = [ 'end', 'close', 'timeout', 'drain' ];
        eventNames.forEach(function (name) {
            self.socket.on(name, function() {
                JobServer.logger.log('warn', 'unhandled event, name=%s', name);
            });
        });

        // emitted when a socket connection is successfully established
        this.socket.on('connect', function () {
            self.socket.setKeepAlive(true);
            self.connected = true;
            JobServer.logger.log('debug', 'connection established: ', self.toString('minimal'));
            callback();
        });

        // emitted when an error occurs
        this.socket.on('error', function (err) {
            self.socket.destroy();
            delete self.socket;
            self.connected = false;
            JobServer.logger.log('error', 'socket error', err);
            callback(err);
        });

        this.socket.on('data', function (chunk) {
            JobServer.logger.log('verbose', 'received packet, len=' + chunk.length);
            JobServer.logger.log('verbose', 'data: %s', common.bufferAsHex(chunk));

            self.processData(chunk);
        });
    }

    return this.socket;
};

JobServer.prototype.disconnect = function () {
    var i, eventNames;

    this.connected = false;
    if (this.client) { // bidirectional association management
        this.client.emit('disconnect');
        delete this.client;
    }

    // clear buffered jobs #1
    for (i = 0; i < this.jobsWaiting4Created.length; i ++) {
        this.jobsWaiting4Created[i].abort();
    }
    this.jobsWaiting4Created.length = 0;
    // clear buffered jobs #2
    for (i in this.jobsWaiting4Complete) {
        if (this.jobsWaiting4Complete.hasOwnProperty(i)) {
            this.jobsWaiting4Complete[i].abort();
            delete this.jobsWaiting4Complete[i];
        }
    }

    // remove listeners from socket
    eventNames = [ 'connect', 'data', 'error', 'end', 'close', 'timeout', 'drain' ];
    for (i = 0; i < eventNames.length; i ++) {
        this.socket.removeAllListeners(eventNames[i]);
    }

    if (this.socket) {
        this.socket.end();
        delete this.socket;
    }
    JobServer.logger.log('debug', 'connection closed: ', this.toString('minimal'));
};

/**
 * Submits given job to job server.
 *
 * *callback(err)* called as
 *     * error callback when anything goes wrong
 *     * success callback when the job sent/submited over socket, err=undefined
 */
JobServer.prototype.submit = function (job, callback) {
    if (!this.connected) {
        callback(new Error('unconnected job server asked to send data'));
        return;
    }

    this.socket.write(job.encode(), job.encoding);
    job.processing = true;
    this.jobsWaiting4Created.push(job); // add to queue of submited jobs waiting for confirmation
    job.jobServer = this; // bidirectional association management
    JobServer.logger.log('debug', 'job submited, name=%s, type=%d', job.name, job.getPacketType());
    callback();
};

JobServer.prototype.getStatus = function (job, callback) {
    if (!this.connected) {
        callback(new Error('unconnected job server asked to submit a job'));
        return;
    }
}

JobServer.prototype.processData = function (chunk, callback) {
    if (!this.connected) {
        JobServer.logger.log('warn', 'trying to process data from disconnected job server (disconnect before all packet received?)');
        return;
    }

    if (chunk.readUInt32BE(0) != 0x00524553) { // \0RES
        // OUT OF SYNC!
        this._unrecoverableError('out of sync with server');
        return;
    }

    var jobId, job;
    var proceed = 12;

    var packetType = chunk.readUInt32BE(4);
    // response needs to be 12 bytes + body length (job handle + payload)
    var packetLength = chunk.readUInt32BE(8);

    switch (packetType) {
    case Job.PACKET_TYPES.JOB_CREATED:
        jobId = Job.getJobId(chunk, 12, 12 + packetLength);

        // remove it from queue of jobs waiting for JOB_CREATED
        if (this.jobsWaiting4Created.length === 0) {
            this._unrecoverableError('empty stack of job waiting 4 status CREATED');
            return;
        }
        job = this.jobsWaiting4Created.pop();

        job.id = jobId;

        // and put it into hash of created jobs
        this.jobsWaiting4Complete[jobId] = job;

        proceed += packetLength;
        JobServer.logger.log('verbose', 'job created, jobId=%s', jobId);
        if (this.jobsWaiting4Created.length === 0) {
            JobServer.logger.log('debug', 'no more a job waiting for state CREATED');
            if (this.client) { this.client.emit('done'); } // trigger event
        }

        job.emit('created'); // trigger event
        break;

    case Job.PACKET_TYPES.WORK_COMPLETE:
        // skip job handle => find next NULL
        var next0 = 12
        for (; next0 < chunk.length; next0 ++) {
            if (chunk.readUInt8(next0) == 0) {
                break;
            }
        }
        jobId = Job.getJobId(chunk, 12, next0);
        if (!this.jobsWaiting4Complete.hasOwnProperty(jobId)) {
            this._unrecoverableError('work complete, but unknown job, jobId=' + jobId);
            return;
        }
        job = this.jobsWaiting4Complete[jobId];
        job.processing = false;
        delete this.jobsWaiting4Complete[jobId]; // remove it from hash of created jobs

        JobServer.logger.log('verbose', 'work complete, jobId=%s', jobId);
        next0 ++;
        job.response = chunk.toString(job.encoding, next0, 12 + packetLength);

        proceed += packetLength;

        job.emit('complete'); // trigger event
        break;

    case Job.PACKET_TYPES.STATUS_RES:
        var next0 = 12
        for (; next0 < chunk.length; next0 ++) {
            if (chunk.readUInt8(next0) == 0) {
                break;
            }
        }
        jobId = Job.getJobId(chunk, 12, next0);
        next0 ++;
        var knownStatus = String.fromCharCode(chunk.readUInt8(next0));
console.log('next0 ' + (typeof knownStatus));
        next0 += 2;
        var runningStatus = String.fromCharCode(chunk.readUInt8(next0));
        next0 += 2;
        var percent = String.fromCharCode(chunk.readUInt8(next0));
console.log('STATUS ' + jobId + ', knownStatus=' + knownStatus + ", runningStatus=" + runningStatus + ', percent=' + percent);
        break;

    default:
        JobServer.logger.log('warn', 'unknown packet, type=%d', packetType);
        proceed = chunk.length; // stop processing of rest of the chunk
    }

    // recursive approach when more packets in buffer
    if (proceed < chunk.length) {
        this.processData(chunk.slice(proceed));
    }
}

/**
 * Gets an unique identifier of job server represented by the URL address.
 */
JobServer.prototype.getId = function() {
    return this.host + ':' + this.port;
}

/**
 * Returns a human readable string representation of the object.
 */
JobServer.prototype.toString = function (how) { // #unit: not needed
    if (how == 'minimal') {
        return 'host=' + this.host + ', port=' + this.port;
    }
    return 'JobServer(' + this.toString('minimal') + ')';
}

JobServer.prototype._unrecoverableError = function (msg) { // #unit: not needed
    JobServer.logger.log('error', msg);
    if (this.client) {
        this.client.emit('error', new Error(msg)); // trigger event
    }
}<|endoftext|>


<commit_before>export class WebSocketService {
	constructor($rootScope, $log, $websocket, appConfig, toastr, _) {
		'ngInject';

		this.$log = $log;
		this.$rootScope = $rootScope;
		this.$websocket = $websocket;

		this._ = _;
		this.toastr = toastr;

		this.host = `${appConfig.host}:3000`;
		this.options = {
			maxTimeout: 60 * 1000,
			reconnectIfNotNormalClose: true
		};

		this.$log.debug('constructor()', this);
	}

	close() {
		this.$ws.close();
	}

	connect() {
		this.$ws = this.$websocket(`ws://${this.host}`, this.options);

		this.$log.debug('ws', this.$ws);

		this.$ws.onClose(this.onClose.bind(this));
		this.$ws.onError(this.onError.bind(this));
		this.$ws.onMessage(this.onMessage.bind(this));
	}

	getStatus() {
		return this.$ws.readyState;
	}

	onClose(data) {
		this.$log.error('onClose()', data);

		this.$rootScope.$broadcast('websocket:global:close', data);
	}

	onError(msg) {
		this.toastr.error('websocket:error', msg);

		this.$rootScope.$broadcast('websocket:error', msg);
	}

	onMessage(msg) {
		var data = JSON.parse(msg.data),
			action = data.action || 'none',
			type = data.type || 'global';

		this.$log.debug('onMessage()', data, type, action, this);

		if (data.nuts) {
			data = data.nuts;
		}

		this.$rootScope.$broadcast('websocket:message', msg);
		this.$rootScope.$broadcast(`websocket:${type}:${action}`, data);
	}

	send(msg) {
		var message = typeof msg === 'object' ? JSON.stringify(msg) : msg;

		this.$log.debug('send()', message, this);

		this.$ws.send(msg);
	}
}
<commit_msg>Add object to store WebSocket status codes<commit_after>export class WebSocketService {
	constructor($rootScope, $log, $websocket, appConfig, toastr, _) {
		'ngInject';

		this.$log = $log;
		this.$rootScope = $rootScope;
		this.$websocket = $websocket;

		this._ = _;
		this.toastr = toastr;

		this.host = `${appConfig.host}:3000`;
		this.options = {
			maxTimeout: 60 * 1000,
			reconnectIfNotNormalClose: true
		};

		this.$ws = null;

		this.STATUS = {
			CONNECTING: 0,
			OPEN: 1,
			CLOSING: 2,
			CLOSED: 3
		}

		this.$log.debug('constructor()', this);
	}

	close() {
		this.$ws.close();
	}

	connect() {
		this.$ws = this.$websocket(`ws://${this.host}`, this.options);

		this.$log.debug('ws', this.$ws);

		this.$ws.onClose(this.onClose.bind(this));
		this.$ws.onError(this.onError.bind(this));
		this.$ws.onMessage(this.onMessage.bind(this));
	}

	getStatus() {
		return this.$ws.readyState;
	}

	onClose(data) {
		this.$log.error('onClose()', data);

		this.$rootScope.$broadcast('websocket:global:close', data);
	}

	onError(msg) {
		this.toastr.error('websocket:error', msg);

		this.$rootScope.$broadcast('websocket:error', msg);
	}

	onMessage(msg) {
		var data = JSON.parse(msg.data),
			action = data.action || 'none',
			type = data.type || 'global';

		this.$log.debug('onMessage()', data, type, action, this);

		if (data.nuts) {
			data = data.nuts;
		}

		this.$rootScope.$broadcast('websocket:message', msg);
		this.$rootScope.$broadcast(`websocket:${type}:${action}`, data);
	}

	send(msg) {
		var message = typeof msg === 'object' ? JSON.stringify(msg) : msg;

		this.$log.debug('send()', message, this);

		this.$ws.send(msg);
	}
}
<|endoftext|>


<commit_before>var util = require('util');
var path = require('path');
var inquirer = require('inquirer');
var sb_utils = require('../../smartblocks');
var fs = require('fs');
var Handlebars = require('handlebars');
var async = require('async');
var colors = require('colors');
var ncp = require('ncp');
var os = require('os');
Handlebars.registerHelper("foreach", function (arr, options) {
    if (options.inverse && !arr.length)
        return options.inverse(this);

    return arr.map(function (item, index) {
        item.$index = index;
        item.$first = index === 0;
        item.$last = index === arr.length - 1;
        item.$notlast = !item.$last;
        return options.fn(item);
    }).join('');
});

module.exports = {
    run: function () {

        var prompts = [];
        var block_chooser = {
            type: 'list',
            name: 'block_name',
            choices: [],
            message: 'In which block do you want to create your app?'
        };
        var block_names = sb_utils.getBlocks();

        for (var k in block_names) {
            block_chooser.choices.push(block_names[k]);
        }
        prompts.push(block_chooser);

        var created = {};
        inquirer.prompt(prompts, function (answers) {
            var block_path = path.join(process.cwd(), 'blocks', answers.block_name);

            var prompts2 = [];

            var available_apps = fs.readdirSync(path.join(process.cwd(), 'blocks', answers.block_name, 'frontend', 'apps'));
            var array = [];
            for (var k in available_apps) {
                if (available_apps[k] !== 'empty') {
                    array.push(available_apps[k]);
                }
            }
            available_apps = array;

            if (available_apps.length > 0) {

                var name_chooser = {
                    name: 'app_name',
                    message: 'In what app do you want to add this view?',
                    type: 'list',
                    choices: available_apps
                };

                prompts2.push(name_chooser);

                var view_name_chooser = {
                    name: 'view_name',
                    message: 'What will be the name of the view?',
                    validate: function (input) {
                        return typeof input === 'string' && input.indexOf(/\s/) === -1 && input !== '';
                    }
                };

                prompts2.push(view_name_chooser);
                inquirer.prompt(prompts2, function (answers2) {
                    async.parallel([
                        function (cb) {
                            //view generation
                            fs.readFile(path.join(__dirname, '..', 'templates', 'frontend', 'view.template'), 'UTF-8', function (err, data) {
                                var template = Handlebars.compile(data);
                                var context = {
                                    name: answers2.view_name
                                };
                                var output = template(context);
                                fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'views', answers2.view_name + '.js'), output, function (err) {
                                    if (!err) {
                                        created.view = true;
                                    }
                                    cb();
                                });
                            });
                        },
                        function (cb) {
                            //style generation
                            fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'style', answers2.view_name + '.less'), '.nothing {}', function (err) {
                                if (!err) {
                                    created.style = true;
                                }
                                cb();
                            });
                        },
                        function (cb) {
                            //template generation
                            fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'templates', answers2.view_name + '.html'), '', function (err) {
                                if (!err) {
                                    created.template = true;
                                }
                                cb();
                            });
                        },
                        function (cb) {
                            fs.readFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'style', 'main.less'), 'UTF-8', function (err, data) {
                                if (!err) {
                                    console.log(data);
                                    var updated = data + os.EOL + '@import "' + answers2.view_name + '";';
                                    if (updated !== data) {
                                        fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'style', 'main.less'), updated, function (err) {
                                            if (!err) {
                                                created.style_link = true;
                                            }
                                            cb();
                                        });
                                    } else {
                                        cb();
                                    }
                                } else {
                                    cb();
                                }
                            });
                        }
                    ], function () {
                        console.log('The generation is done. Here\'s how it went :'.yellow);

                        if (created.view) {
                            console.log('The Backbone view was successfully created.'.green);
                        } else {
                            console.log('The Backbone view could not be created.'.red);
                        }

                        if (created.style) {
                            console.log('The style file was successfully created.'.green);
                        } else {
                            console.log('The style file could not be created.'.red);
                        }

                        if (created.template) {
                            console.log('The template was successfully created.'.green);
                        } else {
                            console.log('The template view could not be created.'.red);
                        }

                        if (created.style_link) {
                            console.log('The link to the style file was successfully created.'.green);
                        } else {
                            console.log('Warning: The link to the style file could not be created.'.yellow);
                        }
                    });

                });
            }
        });

    }
};
<commit_msg>~ removed console log<commit_after>var util = require('util');
var path = require('path');
var inquirer = require('inquirer');
var sb_utils = require('../../smartblocks');
var fs = require('fs');
var Handlebars = require('handlebars');
var async = require('async');
var colors = require('colors');
var ncp = require('ncp');
var os = require('os');
Handlebars.registerHelper("foreach", function (arr, options) {
    if (options.inverse && !arr.length)
        return options.inverse(this);

    return arr.map(function (item, index) {
        item.$index = index;
        item.$first = index === 0;
        item.$last = index === arr.length - 1;
        item.$notlast = !item.$last;
        return options.fn(item);
    }).join('');
});

module.exports = {
    run: function () {

        var prompts = [];
        var block_chooser = {
            type: 'list',
            name: 'block_name',
            choices: [],
            message: 'In which block do you want to create your app?'
        };
        var block_names = sb_utils.getBlocks();

        for (var k in block_names) {
            block_chooser.choices.push(block_names[k]);
        }
        prompts.push(block_chooser);

        var created = {};
        inquirer.prompt(prompts, function (answers) {
            var block_path = path.join(process.cwd(), 'blocks', answers.block_name);

            var prompts2 = [];

            var available_apps = fs.readdirSync(path.join(process.cwd(), 'blocks', answers.block_name, 'frontend', 'apps'));
            var array = [];
            for (var k in available_apps) {
                if (available_apps[k] !== 'empty') {
                    array.push(available_apps[k]);
                }
            }
            available_apps = array;

            if (available_apps.length > 0) {

                var name_chooser = {
                    name: 'app_name',
                    message: 'In what app do you want to add this view?',
                    type: 'list',
                    choices: available_apps
                };

                prompts2.push(name_chooser);

                var view_name_chooser = {
                    name: 'view_name',
                    message: 'What will be the name of the view?',
                    validate: function (input) {
                        return typeof input === 'string' && input.indexOf(/\s/) === -1 && input !== '';
                    }
                };

                prompts2.push(view_name_chooser);
                inquirer.prompt(prompts2, function (answers2) {
                    async.parallel([
                        function (cb) {
                            //view generation
                            fs.readFile(path.join(__dirname, '..', 'templates', 'frontend', 'view.template'), 'UTF-8', function (err, data) {
                                var template = Handlebars.compile(data);
                                var context = {
                                    name: answers2.view_name
                                };
                                var output = template(context);
                                fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'views', answers2.view_name + '.js'), output, function (err) {
                                    if (!err) {
                                        created.view = true;
                                    }
                                    cb();
                                });
                            });
                        },
                        function (cb) {
                            //style generation
                            fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'style', answers2.view_name + '.less'), '.nothing {}', function (err) {
                                if (!err) {
                                    created.style = true;
                                }
                                cb();
                            });
                        },
                        function (cb) {
                            //template generation
                            fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'templates', answers2.view_name + '.html'), '', function (err) {
                                if (!err) {
                                    created.template = true;
                                }
                                cb();
                            });
                        },
                        function (cb) {
                            fs.readFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'style', 'main.less'), 'UTF-8', function (err, data) {
                                if (!err) {
                                    var updated = data + os.EOL + '@import "' + answers2.view_name + '";';
                                    if (updated !== data) {
                                        fs.writeFile(path.join(block_path, 'frontend', 'apps', answers2.app_name, 'style', 'main.less'), updated, function (err) {
                                            if (!err) {
                                                created.style_link = true;
                                            }
                                            cb();
                                        });
                                    } else {
                                        cb();
                                    }
                                } else {
                                    cb();
                                }
                            });
                        }
                    ], function () {
                        console.log('The generation is done. Here\'s how it went :'.yellow);

                        if (created.view) {
                            console.log('The Backbone view was successfully created.'.green);
                        } else {
                            console.log('The Backbone view could not be created.'.red);
                        }

                        if (created.style) {
                            console.log('The style file was successfully created.'.green);
                        } else {
                            console.log('The style file could not be created.'.red);
                        }

                        if (created.template) {
                            console.log('The template was successfully created.'.green);
                        } else {
                            console.log('The template view could not be created.'.red);
                        }

                        if (created.style_link) {
                            console.log('The link to the style file was successfully created.'.green);
                        } else {
                            console.log('Warning: The link to the style file could not be created.'.yellow);
                        }
                    });

                });
            }
        });

    }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
let path = require('path'),
    Map = require('./index'),
    World = Map.World;

let home = process.env["HOME"];
let saves = path.join(home, "Library", "Application Support", "minecraft", "saves");
let worldName = "First World";
let worldPath = path.join(saves, worldName);

let world = new World(worldPath);
let position = { x: 119, y: 63, z: 118 };
let region = world.getRegion(position);
let chunk = region.getChunkContainingPosition(position);

console.log(chunk);
<commit_msg>Return the block type and data for a given position<commit_after>#!/usr/bin/env node
let path = require('path'),
    Map = require('./index'),
    World = Map.World,
    printTag = require('kld-nbt').printTag;

let home = process.env["HOME"];
let saves = path.join(home, "Library", "Application Support", "minecraft", "saves");
let worldName = "First World";
let worldPath = path.join(saves, worldName);

let world = new World(worldPath);
let position = { x: 119, y: 62, z: 118 };
let region = world.getRegion(position);
let chunk = region.getChunkContainingPosition(position);

// printTag(chunk.data);

let blockType = chunk.getBlockType(position);

console.log(blockType);
<|endoftext|>


<commit_before>export class WebsocketService {
	constructor($log, _) {
		'ngInject';

		this._ = _;
		this.$log = $log;

		this.$log.info('constructor()', this);

		this.host = 'localhost:1337';

		// if user is running mozilla then use it's built-in WebSocket
		window.WebSocket = window.WebSocket || window.MozWebSocket;

		this.connection = new WebSocket(`ws://${this.host}`);

		this.$log.info('connection', this.connection);

		this.connection.onmessage = this.onMessage;
	}

	send(obj) {
		var message = typeof obj === 'object' ? JSON.stringify(obj) : obj;

		this.$log.info('send(obj)', message);

		this.connection.send(message);
	}

	onMessage() {
		this.$log.info('onMessage()', arguments);
	}
}
<commit_msg>Update WebSocketService so it can respond to new players properly<commit_after>export class WebSocketService {
	constructor($rootScope, $log, appConfig, toastr, _) {
		'ngInject';

		this.$log = $log;
		this.$rootScope = $rootScope;

		this._ = _;
		this.toastr = toastr;

		this.host = `${appConfig.localhost}:1337`;

		// if user is running mozilla then use it's built-in WebSocket
		this.WebSocket = (window.WebSocket || window.MozWebSocket);

		this.connection = new this.WebSocket(`ws://${this.host}`);

		this.$log.info('connection', this.connection);

		this.connection.onmessage = this.onMessage.bind(this);

		this.$log.info('constructor()', this);
	}

	send(obj) {
		var message = typeof obj === 'object' ? JSON.stringify(obj) : obj;

		this.$log.info('send(obj)', message);

		this.connection.send(message);
	}

	// TODO: Watch for a message coming back from any service using the websocketService
	onMessage(msg) {
		var data = JSON.parse(msg.data),
			action = data.action || 'none',
			type = data.type || 'global',
			broadcast;

		this.$log.info('onMessage()', data, type, action, this);

		if (type === 'player') {
			switch(action) {
				case 'create':
					data = data.nuts;
					break;
				default:
					break;
			}
		}

		//--- TESTING ONLY ---//
		this.toastr.info(JSON.stringify(data), `websocket:${type}:${action}`);

		this.$rootScope.$broadcast('websocket', msg);
		this.$rootScope.$broadcast(`websocket:${type}:${action}`, data);
	}
}
<|endoftext|>


<commit_before>var async = require('async');

var NobleDevice = require('./index');

var TestDevice = function(peripheral) {
  NobleDevice.call(this, peripheral);
};

NobleDevice.Util.inherits(TestDevice, NobleDevice);

TestDevice.discover(function(testDevice) {
  console.log('found ' + testDevice.uuid);

  testDevice.on('disconnect', function() {
    console.log('disconnected!');
    process.exit(0);
  });

  async.series([
      function(callback) {
        console.log('connect');
        testDevice.connect(callback);
      },
      function(callback) {
        console.log('discoverServicesAndCharacteristics');
        testDevice.discoverServicesAndCharacteristics(callback);
      },
      function(callback) {
        console.log('readDeviceName');
        testDevice.readDeviceName(function(error, deviceName) {
          console.log('\tdevice name = ' + deviceName);
          callback();
        });
      },
      function(callback) {
        console.log('disconnect');
        testDevice.disconnect(callback);
      }
    ]
  );
});<commit_msg>- update test.js to use .id instead of .uuid<commit_after>var async = require('async');

var NobleDevice = require('./index');

var TestDevice = function(peripheral) {
  NobleDevice.call(this, peripheral);
};

NobleDevice.Util.inherits(TestDevice, NobleDevice);

TestDevice.discover(function(testDevice) {
  console.log('found ' + testDevice.id);

  testDevice.on('disconnect', function() {
    console.log('disconnected!');
    process.exit(0);
  });

  async.series([
      function(callback) {
        console.log('connect');
        testDevice.connect(callback);
      },
      function(callback) {
        console.log('discoverServicesAndCharacteristics');
        testDevice.discoverServicesAndCharacteristics(callback);
      },
      function(callback) {
        console.log('readDeviceName');
        testDevice.readDeviceName(function(error, deviceName) {
          console.log('\tdevice name = ' + deviceName);
          callback();
        });
      },
      function(callback) {
        console.log('disconnect');
        testDevice.disconnect(callback);
      }
    ]
  );
});<|endoftext|>


<commit_before>/**
 * mukla <https://github.com/tunnckoCore/mukla>
 *
 * Copyright (c) 2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

var ms = require('pretty-hrtime');
var assert = require('assert');
var mukla = require('./index');

mukla.once('start', function(stats) {
  if (stats.init) return;
  console.log()
  mukla.removeAllListeners('start')
})
mukla.on('error', function _muklaError(storage) {
  this.failing++;
  storage.title = storage.name;
  this.emit('fail', storage);
  this.emit('test end', storage);
});
mukla.on('stop', function _muklaTestEnd(storage) {
  this.passing++;
  storage.title = storage.name;
  this.emit('pass', storage);
  this.emit('test end', storage);
});
mukla.on('start', function _muklaError(storage) {
  this.tests++;
  storage.title = storage.name;
  this.emit('test', storage);
});
mukla.on('suite', function(suite) {
   console.log('# suite:', suite.title);
});
mukla.on('suite end', function(suite) {
   console.log('# suite end:', suite.title);
});
mukla.on('pass', function(test) {
  console.log('  ok %s (%s)', test.title, test.duration);
});
mukla.on('fail', function(test) {
  console.log('  not ok %s (%s)', test.title, test.duration);
});
mukla.once('end', function(stats) {
  console.log();
  console.log('\u001b[32mpassing', stats.passing + '\u001b[39m');
  console.log('\u001b[31mfailing', stats.failing + '\u001b[39m');
  console.log('----------');
  console.log('\u001b[90mtotal  ', stats.tests + '\u001b[39m');
});

// var describe = mukla.describe;
// var it = mukla.it;

mukla.describe('mukla:', function() {
  mukla.it('test 1', function(done) {
    assert.strictEqual(typeof 123, 'function');
    done();
  });
  mukla.it('test 2', function(done) {
    assert.strictEqual(typeof 2134234, 'function');
    done();
  });
});
// describe('mukla:', function() {
//   it('test 1', function(done) {
//     assert.strictEqual(typeof done, 'function');
//     done();
//   });
//   it('test 2', function(done) {
//     assert.strictEqual(typeof mukla.it, 'function');
//     done();
//   });
// });
<commit_msg>update reporter<commit_after>/**
 * mukla <https://github.com/tunnckoCore/mukla>
 *
 * Copyright (c) 2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

var ms = require('pretty-hrtime');
var assert = require('assert');
var mukla = require('./index');

mukla.once('start', function(stats) {
  if (stats.init) return;
  mukla.removeAllListeners('start')
})
mukla.on('error', function _muklaError(storage) {
  this.tests++;
  this.failing++;
  storage.title = storage.name;
  this.emit('fail', storage);
  this.emit('test end', storage);
});
mukla.on('stop', function _muklaTestEnd(storage) {
  this.tests++;
  this.passing++;
  storage.title = storage.name;
  this.emit('pass', storage);
  this.emit('test end', storage);
});
mukla.on('suite', function(suite) {
  console.log()
  console.log('# suite:', suite.title);
});
mukla.on('suite end', function() {
  console.log('# suite end');
});
mukla.on('pass', function(test) {
  var ms = test.duration[1].toString();
  console.log('# %s ok %s (%s)', test.uid+1, test.title, ms.slice(0, ms.length - 6) + 'ms');
});
mukla.on('fail', function(test) {
  var ms = test.duration[1].toString();
  console.log('# %s ok %s (%s)', test.uid+1, test.title, ms.slice(0, ms.length - 6) + 'ms');
});
mukla.once('end', function(stats) {
  console.log();
  console.log('\u001b[32mpassing', stats.passing + '\u001b[39m');
  console.log('\u001b[31mfailing', stats.failing + '\u001b[39m');
  console.log('----------');
  console.log('\u001b[90mtotal  ', stats.tests + '\u001b[39m');
});

// var describe = mukla.describe;
// var it = mukla.it;

mukla.describe('mukla:', function() {
  mukla.it('test 1', function(done) {
    assert.strictEqual(typeof 123, 'function');
    done();
  });
  mukla.it('test 2', function(done) {
    assert.strictEqual(typeof 2134234, 'function');
    done();
  });
});
// describe('mukla:', function() {
//   it('test 1', function(done) {
//     assert.strictEqual(typeof done, 'function');
//     done();
//   });
//   it('test 2', function(done) {
//     assert.strictEqual(typeof mukla.it, 'function');
//     done();
//   });
// });
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');
var aesgcm = require('./');
var stream = require('stream');
var util = require('util');

test('basic', function(t) {
  t.plan(1);
  var config = {
    key: aesgcm.createKeyBuffer()
  };

  var encrypt = aesgcm.encrypt(config);
  var decrypt = aesgcm.decrypt(config);

  var data = [
    'Everything that is written into the stream will be encrypted.\n',
    'But because GCM creates a MAC based on ALL the cipher text,\n',
    'it\'s necessary to explicitly call end when writing to the stream.\n',
    'Otherwise you won\'t be able to authenticate and decrypt the data.\n',
    'The decrypter relies on the first 12 bytes of the cipher text being the nonce,\n',
    'and the last 16 bytes of the cipherText being the MAC;\n',
    'which is only generated and sent on flush.\n'
  ];

  var outData = [];
  encrypt.pipe(decrypt).on('data', function(d) {
    outData.push(d.toString());
  }).on('finish', function() {
    t.equals(data.join(''), outData.join(''));
  }).on('error', function(e) {
    t.error(e);
  });
  data.forEach(function(s) {
    encrypt.write(s);
  });
  encrypt.end();
});

test('mixed up chunks', function(t) {
  t.plan(1);
  var config = {
    key: aesgcm.createKeyBuffer()
  };

  var encrypt = aesgcm.encrypt(config);
  var decrypt = aesgcm.decrypt(config);

  var data = [
    'Everything that is written into the stream will be encrypted.\n',
    'But it will be held in memory as encrypted cipher text.\n',
    'It won\'t continue to be streamed until end is called or triggered.\n',
    'That\'s because GCM creates a MAC based on ALL the cipher text.\n',
    'Authentication requires the MAC and Nonce BEFORE decryption begins.\n',
    'That\'s why the first 28 bytes from encrypt are the Nonce and MAC.\n'
  ];
  var outData = [];
  encrypt.pipe(new MixingStream()).pipe(decrypt).on('data', function(d) {
    outData.push(d.toString());
  }).on('finish', function() {
    t.equals(data.join(''), outData.join(''));
  }).on('error', function(e) {
    t.error(e);
  });
  data.forEach(function(s) {
    encrypt.write(s);
  });
  encrypt.end();
});
test('incorect tag', function(t) {
  t.plan(2);
  var config = {
    key: aesgcm.createKeyBuffer()
  };

  var encrypt = aesgcm.encrypt(config);
  var decrypt = aesgcm.decrypt(config);

  var data = [
    'Everything that is written into the stream will be encrypted.\n',
    'But it will be held in memory as encrypted cipher text.\n',
    'It won\'t continue to be streamed until end is called or triggered.\n',
    'That\'s because GCM creates a MAC based on ALL the cipher text.\n',
    'Authentication requires the MAC and Nonce BEFORE decryption begins.\n',
    'That\'s why the first 28 bytes from encrypt are the Nonce and MAC.\n'
  ];
  var outData = [];
  function onError (e) {
    t.error(e);
  }
  encrypt.pipe(new MixingStream(true)).pipe(decrypt).on('data', function(d) {
    outData.push(d.toString());
  }).on('finish', function() {
    t.notEqual(data.join(''), outData.join(''));
  }).on('error', onError);
  data.forEach(function(s) {
    encrypt.write(s);
  });
  decrypt.removeListener('error', onError);
  decrypt.on('error', function(e) {
    t.ok(e, 'throws');
  });
  encrypt.end();
});

function MixingStream(evil) {
  stream.Transform.call(this);
  this.previous = null;
  this.evil = !!evil;
}
util.inherits(MixingStream, stream.Transform);
MixingStream.prototype._transform = function(chunk, _, next) {
  var previous = this.previous;
  var mid = ~~(chunk.length / 2);
  var start = chunk.slice(0, mid);
  var end = chunk.slice(mid);
  this.previous = end;
  if (previous) {
    this.push(Buffer.concat([previous, start]))
  } else {
    this.push(start);
  }
  next();
}

MixingStream.prototype._flush = function(next) {
  if (this.previous) {
    if (this.evil) {
      this.previous[0] = ~this.previous[0];
    }
    this.push(this.previous);
  }
  next();
};
<commit_msg>Fix jshint errors in test file<commit_after>'use strict';

var test = require('tape');
var aesgcm = require('./');
var stream = require('stream');
var util = require('util');

test('basic', function(t) {
  t.plan(1);
  var config = {
    key: aesgcm.createKeyBuffer()
  };

  var encrypt = aesgcm.encrypt(config);
  var decrypt = aesgcm.decrypt(config);

  var data = [
    'Everything that is written into the stream will be encrypted.\n',
    'But because GCM creates a MAC based on ALL the cipher text,\n',
    'it\'s necessary to explicitly call end when writing to the stream.\n',
    'Otherwise you won\'t be able to authenticate and decrypt the data.\n',
    'The decrypter relies on the first 12 bytes of the cipher text being the nonce,\n',
    'and the last 16 bytes of the cipherText being the MAC;\n',
    'which is only generated and sent on flush.\n'
  ];

  var outData = [];
  encrypt.pipe(decrypt).on('data', function(d) {
    outData.push(d.toString());
  }).on('finish', function() {
    t.equals(data.join(''), outData.join(''));
  }).on('error', function(e) {
    t.error(e);
  });
  data.forEach(function(s) {
    encrypt.write(s);
  });
  encrypt.end();
});

test('mixed up chunks', function(t) {
  t.plan(1);
  var config = {
    key: aesgcm.createKeyBuffer()
  };

  var encrypt = aesgcm.encrypt(config);
  var decrypt = aesgcm.decrypt(config);

  var data = [
    'Everything that is written into the stream will be encrypted.\n',
    'But it will be held in memory as encrypted cipher text.\n',
    'It won\'t continue to be streamed until end is called or triggered.\n',
    'That\'s because GCM creates a MAC based on ALL the cipher text.\n',
    'Authentication requires the MAC and Nonce BEFORE decryption begins.\n',
    'That\'s why the first 28 bytes from encrypt are the Nonce and MAC.\n'
  ];
  var outData = [];
  encrypt.pipe(new MixingStream()).pipe(decrypt).on('data', function(d) {
    outData.push(d.toString());
  }).on('finish', function() {
    t.equals(data.join(''), outData.join(''));
  }).on('error', function(e) {
    t.error(e);
  });
  data.forEach(function(s) {
    encrypt.write(s);
  });
  encrypt.end();
});
test('incorect tag', function(t) {
  t.plan(2);
  var config = {
    key: aesgcm.createKeyBuffer()
  };

  var encrypt = aesgcm.encrypt(config);
  var decrypt = aesgcm.decrypt(config);

  var data = [
    'Everything that is written into the stream will be encrypted.\n',
    'But it will be held in memory as encrypted cipher text.\n',
    'It won\'t continue to be streamed until end is called or triggered.\n',
    'That\'s because GCM creates a MAC based on ALL the cipher text.\n',
    'Authentication requires the MAC and Nonce BEFORE decryption begins.\n',
    'That\'s why the first 28 bytes from encrypt are the Nonce and MAC.\n'
  ];
  var outData = [];
  function onError (e) {
    t.error(e);
  }
  encrypt.pipe(new MixingStream(true)).pipe(decrypt).on('data', function(d) {
    outData.push(d.toString());
  }).on('finish', function() {
    t.notEqual(data.join(''), outData.join(''));
  }).on('error', onError);
  data.forEach(function(s) {
    encrypt.write(s);
  });
  decrypt.removeListener('error', onError);
  decrypt.on('error', function(e) {
    t.ok(e, 'throws');
  });
  encrypt.end();
});

function MixingStream(evil) {
  stream.Transform.call(this);
  this.previous = null;
  this.evil = !!evil;
}
util.inherits(MixingStream, stream.Transform);
MixingStream.prototype._transform = function(chunk, _, next) {
  var previous = this.previous;
  var mid = ~~(chunk.length / 2);
  var start = chunk.slice(0, mid);
  var end = chunk.slice(mid);
  this.previous = end;
  if (previous) {
    this.push(Buffer.concat([previous, start]));
  } else {
    this.push(start);
  }
  next();
};

MixingStream.prototype._flush = function(next) {
  if (this.previous) {
    if (this.evil) {
      this.previous[0] = ~this.previous[0];
    }
    this.push(this.previous);
  }
  next();
};
<|endoftext|>


<commit_before>/* istanbul ignore file */
/* eslint-disable camelcase */
const delay = require('mocker-api/lib/delay');

// var
const confirmedVA = require('./var/confirmed_va.json');
const confirmedCC = require('./var/confirmed_cc.json');
const requests = require('./var/requests.json');
const messages0190 = require('./var/messages_0190.json');
const messages0038 = require('./var/messages_0038.json');
const parentFacilities = require('./var/facilities.json');
const facilities983 = require('./var/facilities_983.json');
const facilities984 = require('./var/facilities_984.json');
const facilities983A6 = require('./var/facilities_983A6.json');
const clinicList983 = require('./var/clinicList983.json');
const clinicList612 = require('./var/clinicList612.json');
const facilityDetails983 = require('./var/facility_details_983.json');
const facilityData = require('./var/facility_data.json');
const ccProviders = require('./var/cc_providers.json');
const sitesSupportingVAR = require('./var/sites-supporting-var.json');
const varSlots = require('./var/slots.json');
const cancelReasons = require('./var/cancel_reasons.json');
const requestEligibilityCriteria = require('./var/request_eligibility_criteria.json');
const directBookingEligibilityCriteria = require('./var/direct_booking_eligibility_criteria.json');
const generateMockSlots = require('./var/slots.js');

// v2
const requestsV2 = require('./v2/requests.json');
const facilitiesV2 = require('./v2/facilities.json');
const schedulingConfigurationsCC = require('./v2/scheduling_configurations_cc.json');
const schedulingConfigurations = require('./v2/scheduling_configurations.json');
const appointmentSlotsV2 = require('./v2/slots.json');
const clinicsV2 = require('./v2/clinics.json');
const confirmedV2 = require('./v2/confirmed.json');

varSlots.data[0].attributes.appointmentTimeSlot = generateMockSlots();
const mockAppts = [];
let currentMockId = 1;

const responses = {
  'GET /vaos/v0/appointments': (req, res) => {
    if (req.query.type === 'cc') {
      return res.json(confirmedCC);
    } else {
      return res.json(confirmedVA);
    }
  },
  'GET /vaos/v0/appointments/va/:id': (req, res) => {
    return res.json({
      data: confirmedVA.data.find(appt => appt.id === req.params.id),
    });
  },
  'GET /vaos/v0/appointment_requests': requests,
  'GET /vaos/v0/appointment_requests/:id': (req, res) => {
    return res.json({
      data: requests.data.find(appt => appt.id === req.params.id),
    });
  },
  'GET /vaos/v0/appointment_requests/:id/messages': (req, res) => {
    const id = req.params.id;
    if (id === '8a48912a6c2409b9016c525a4d490190') {
      return res.json(messages0190);
    }

    if (id === '8a48912a6cab0202016cb4fcaa8b0038') {
      return res.json(messages0038);
    }

    return res.json({ data: [] });
  },
  'GET /vaos/v0/facilities': parentFacilities,
  'GET /vaos/v0/systems/:id/direct_scheduling_facilities': (req, res) => {
    if (req.query.parent_code === '984') {
      return res.json(facilities984);
    } else if (req.query.parent_code === '983A6') {
      return res.json(facilities983A6);
    } else {
      return res.json(facilities983);
    }
  },
  'GET /vaos/v0/community_care/eligibility/:id': (req, res) => {
    return res.json({
      data: {
        id: req.param.id,
        type: 'cc_eligibility',
        attributes: { eligible: true },
      },
    });
  },
  'GET /vaos/v0/community_care/supported_sites': sitesSupportingVAR,
  'GET /vaos/v0/facilities/:id/visits/:type': (req, res) => {
    if (req.params.type === 'direct') {
      return res.json({
        data: {
          id: '05084676-77a1-4754-b4e7-3638cb3124e5',
          type: 'facility_visit',
          attributes: {
            durationInMonths: 24,
            hasVisitedInPastMonths: !req.params.id.startsWith('984'),
          },
        },
      });
    }

    return res.json({
      data: {
        id: '05084676-77a1-4754-b4e7-3638cb3124e5',
        type: 'facility_visit',
        attributes: {
          durationInMonths: 12,
          hasVisitedInPastMonths: !req.params.id.startsWith('984'),
        },
      },
    });
  },
  'GET /vaos/v0/facilities/limits': (req, res) => {
    const data = req.query.facility_ids.map(id => ({
      id,
      attributes: {
        numberOfRequests: id.startsWith('983') ? 0 : 1,
        requestLimit: 1,
        institutionCode: id,
      },
    }));

    return res.json({
      data,
    });
  },
  'GET /vaos/v0/facilities/:id/clinics': (req, res) => {
    if (req.params.id === '983') {
      return res.json(clinicList983);
    } else if (req.params.id.startsWith(612)) {
      return res.json(clinicList612);
    }

    return res.json({
      data: [],
    });
  },
  'GET /v1/facilities/va/:id': (req, res) => {
    const facility = facilityData.data.find(f => f.id === req.params.id);

    return res.json({
      data: facility || facilityDetails983,
    });
  },
  'GET /v1/facilities/va': facilityData,
  'GET /facilities_api/v1/ccp/provider': ccProviders,
  'GET /v1/facilities/ccp/:id': (req, res) => {
    const provider = ccProviders.data.find(p => p.id === req.params.id);
    return res.json({
      data: provider,
    });
  },
  'GET /vaos/v0/facilities/:id/available_appointments': varSlots,
  'GET /vaos/v0/facilities/:id/cancel_reasons': cancelReasons,
  'GET /vaos/v0/request_eligibility_criteria': requestEligibilityCriteria,
  'GET /vaos/v0/direct_booking_eligibility_criteria': directBookingEligibilityCriteria,
  'GET /vaos/v0/preferences': { data: { attributes: { emailAllowed: true } } },
  'PUT /vaos/v0/appointments/cancel': {},
  'POST /vaos/v0/appointment_requests': {
    data: {
      id: '8a4886886e4c8e22016e6613216d001g',
      attributes: {},
    },
  },
  'PUT /vaos/v0/appointment_requests/:id': (req, res) => {
    const requestAttributes = requests.data.find(
      item => item.id === req.params.id,
    ).attributes;

    return res.json({
      data: {
        id: req.body.id,
        attributes: {
          ...requestAttributes,
          status: 'Cancelled',
        },
      },
    });
  },
  'POST /vaos/v0/appointments': {},
  'POST /vaos/v0/appointment_requests/:id/messages': {
    data: {
      attributes: {},
    },
  },
  'PUT /vaos/v0/preferences': { data: { attributes: {} } },
  'POST /vaos/v2/appointments': (req, res) => {
    const submittedAppt = {
      id: `mock${currentMockId}`,
      attributes: {
        ...req.body,
        start: req.body.slot ? req.body.slot.start : null,
      },
    };
    currentMockId++;
    mockAppts.push(submittedAppt);
    return res.json({ data: submittedAppt });
  },
  'PUT /vaos/v2/appointments/:id': (req, res) => {
    // TODO: also check through confirmed mocks, when those exist
    const requestAttributes = requestsV2.data.find(
      item => item.id === req.params.id,
    ).attributes;

    return res.json({
      data: {
        id: req.params.id,
        attributes: {
          ...requestAttributes,
          ...req.body,
        },
      },
    });
  },
  'GET /vaos/v2/appointments': (req, res) => {
    if (req.query.statuses?.includes('proposed')) {
      return res.json(requestsV2);
    } else if (req.query.statuses?.includes('booked')) {
      return res.json(confirmedV2);
    }

    return res.json({ data: [] });
  },
  'GET /vaos/v2/appointments/:id': (req, res) => {
    const appointments = {
      data: requestsV2.data.concat(confirmedV2).concat(mockAppts),
    };
    return res.json({
      data: appointments.data.find(appt => appt.id === req.params.id),
    });
  },
  'GET /vaos/v2/scheduling/configurations': (req, res) => {
    if (req.query.cc_enabled === 'true') {
      return res.json(schedulingConfigurationsCC);
    }

    return res.json(schedulingConfigurations);
  },
  'GET /vaos/v2/facilities/:id': (req, res) => {
    return res.json({
      data: facilitiesV2.data.find(facility => facility.id === req.params.id),
    });
  },
  'GET /vaos/v2/facilities': (req, res) => {
    const ids = req.query.ids;
    const children = req.query.children;

    return res.json({
      data: facilitiesV2.data.filter(
        facility =>
          ids.includes(facility.id) ||
          (children && ids.some(id => facility.id.startsWith(id))),
      ),
    });
  },
  'GET /vaos/v2/locations/:facility_id/clinics/:clinic_id/slots': appointmentSlotsV2,
  'GET /vaos/v2/patients': (req, res) => {
    return res.json({
      data: {
        attributes: {
          hasRequiredAppointmentHistory:
            !req.query.facility_id.startsWith('984') ||
            req.query.clinical_service === 'primaryCare',
          isEligibleForNewAppointmentRequest: req.query.facility_id.startsWith(
            '983',
          ),
        },
      },
    });
  },
  'GET /vaos/v2/locations/:id/clinics': (req, res) => {
    if (req.query.clinic_ids) {
      return res.json({
        data: clinicsV2.data.filter(clinic =>
          req.query.clinic_ids.includes(clinic.id),
        ),
      });
    }

    if (req.params.id === '983') {
      return res.json(clinicsV2);
    }

    return res.json({
      data: [],
    });
  },
  'GET /v0/user': {
    data: {
      attributes: {
        profile: {
          sign_in: {
            service_name: 'idme',
          },
          email: 'fake@fake.com',
          loa: { current: 3 },
          first_name: 'Jane',
          middle_name: '',
          last_name: 'Doe',
          gender: 'F',
          birth_date: '1985-01-01',
          verified: true,
        },
        veteran_status: {
          status: 'OK',
          is_veteran: true,
          served_in_military: true,
        },
        in_progress_forms: [],
        prefills_available: ['21-526EZ'],
        services: [
          'facilities',
          'hca',
          'edu-benefits',
          'evss-claims',
          'form526',
          'user-profile',
          'health-records',
          'rx',
          'messaging',
        ],
        va_profile: {
          status: 'OK',
          birth_date: '19511118',
          family_name: 'Hunter',
          gender: 'M',
          given_names: ['Julio', 'E'],
          active_status: 'active',
          facilities: [
            {
              facility_id: '983',
              is_cerner: false,
            },
            {
              facility_id: '984',
              is_cerner: false,
            },
          ],
        },
      },
    },
    meta: { errors: null },
  },

  'OPTIONS /v0/maintenance_windows': 'OK',
  'GET /v0/maintenance_windows': { data: [] },

  'GET /v0/feature_toggles': {
    data: {
      type: 'feature_toggles',
      features: [
        { name: 'facilityLocatorShowCommunityCares', value: true },
        { name: 'profile_show_profile_2.0', value: false },
        { name: 'vaOnlineScheduling', value: true },
        { name: 'vaOnlineSchedulingCancel', value: true },
        { name: 'vaOnlineSchedulingRequests', value: true },
        { name: 'vaOnlineSchedulingCommunityCare', value: true },
        { name: 'vaOnlineSchedulingDirect', value: true },
        { name: 'vaOnlineSchedulingPast', value: true },
        { name: 'vaOnlineSchedulingExpressCare', value: true },
        { name: 'vaOnlineSchedulingFlatFacilityPage', value: true },
        { name: 'vaOnlineSchedulingUnenrolledVaccine', value: true },
        { name: 'vaGlobalDowntimeNotification', value: false },
        { name: 'vaOnlineSchedulingVAOSServiceRequests', value: true },
        { name: 'vaOnlineSchedulingVAOSServiceVAAppointments', value: true },
        { name: 'vaOnlineSchedulingFacilitiesServiceV2', value: true },
        { name: 'vaOnlineSchedulingVAOSServiceCCAppointments', value: true },
        { name: 'vaOnlineSchedulingVariantTesting', value: false },
        { name: 'vaOnlineSchedulingCCIterations', value: false },
        { name: 'ssoe', value: true },
        { name: 'ssoeInbound', value: false },
        { name: 'ssoeEbenefitsLinks', value: false },
        { name: 'edu_section_103', value: true },
        { name: 'vaViewDependentsAccess', value: false },
        { name: 'gibctEybBottomSheet', value: true },
      ],
    },
  },
};

module.exports = delay(responses, 1000);
<commit_msg>Fix VAOS v2 mock appointment list calls (#19030)<commit_after>/* istanbul ignore file */
/* eslint-disable camelcase */
const delay = require('mocker-api/lib/delay');

// var
const confirmedVA = require('./var/confirmed_va.json');
const confirmedCC = require('./var/confirmed_cc.json');
const requests = require('./var/requests.json');
const messages0190 = require('./var/messages_0190.json');
const messages0038 = require('./var/messages_0038.json');
const parentFacilities = require('./var/facilities.json');
const facilities983 = require('./var/facilities_983.json');
const facilities984 = require('./var/facilities_984.json');
const facilities983A6 = require('./var/facilities_983A6.json');
const clinicList983 = require('./var/clinicList983.json');
const clinicList612 = require('./var/clinicList612.json');
const facilityDetails983 = require('./var/facility_details_983.json');
const facilityData = require('./var/facility_data.json');
const ccProviders = require('./var/cc_providers.json');
const sitesSupportingVAR = require('./var/sites-supporting-var.json');
const varSlots = require('./var/slots.json');
const cancelReasons = require('./var/cancel_reasons.json');
const requestEligibilityCriteria = require('./var/request_eligibility_criteria.json');
const directBookingEligibilityCriteria = require('./var/direct_booking_eligibility_criteria.json');
const generateMockSlots = require('./var/slots.js');

// v2
const requestsV2 = require('./v2/requests.json');
const facilitiesV2 = require('./v2/facilities.json');
const schedulingConfigurationsCC = require('./v2/scheduling_configurations_cc.json');
const schedulingConfigurations = require('./v2/scheduling_configurations.json');
const appointmentSlotsV2 = require('./v2/slots.json');
const clinicsV2 = require('./v2/clinics.json');
const confirmedV2 = require('./v2/confirmed.json');

varSlots.data[0].attributes.appointmentTimeSlot = generateMockSlots();
const mockAppts = [];
let currentMockId = 1;

const responses = {
  'GET /vaos/v0/appointments': (req, res) => {
    if (req.query.type === 'cc') {
      return res.json(confirmedCC);
    } else {
      return res.json(confirmedVA);
    }
  },
  'GET /vaos/v0/appointments/va/:id': (req, res) => {
    return res.json({
      data: confirmedVA.data.find(appt => appt.id === req.params.id),
    });
  },
  'GET /vaos/v0/appointment_requests': requests,
  'GET /vaos/v0/appointment_requests/:id': (req, res) => {
    return res.json({
      data: requests.data.find(appt => appt.id === req.params.id),
    });
  },
  'GET /vaos/v0/appointment_requests/:id/messages': (req, res) => {
    const id = req.params.id;
    if (id === '8a48912a6c2409b9016c525a4d490190') {
      return res.json(messages0190);
    }

    if (id === '8a48912a6cab0202016cb4fcaa8b0038') {
      return res.json(messages0038);
    }

    return res.json({ data: [] });
  },
  'GET /vaos/v0/facilities': parentFacilities,
  'GET /vaos/v0/systems/:id/direct_scheduling_facilities': (req, res) => {
    if (req.query.parent_code === '984') {
      return res.json(facilities984);
    } else if (req.query.parent_code === '983A6') {
      return res.json(facilities983A6);
    } else {
      return res.json(facilities983);
    }
  },
  'GET /vaos/v0/community_care/eligibility/:id': (req, res) => {
    return res.json({
      data: {
        id: req.param.id,
        type: 'cc_eligibility',
        attributes: { eligible: true },
      },
    });
  },
  'GET /vaos/v0/community_care/supported_sites': sitesSupportingVAR,
  'GET /vaos/v0/facilities/:id/visits/:type': (req, res) => {
    if (req.params.type === 'direct') {
      return res.json({
        data: {
          id: '05084676-77a1-4754-b4e7-3638cb3124e5',
          type: 'facility_visit',
          attributes: {
            durationInMonths: 24,
            hasVisitedInPastMonths: !req.params.id.startsWith('984'),
          },
        },
      });
    }

    return res.json({
      data: {
        id: '05084676-77a1-4754-b4e7-3638cb3124e5',
        type: 'facility_visit',
        attributes: {
          durationInMonths: 12,
          hasVisitedInPastMonths: !req.params.id.startsWith('984'),
        },
      },
    });
  },
  'GET /vaos/v0/facilities/limits': (req, res) => {
    const data = req.query.facility_ids.map(id => ({
      id,
      attributes: {
        numberOfRequests: id.startsWith('983') ? 0 : 1,
        requestLimit: 1,
        institutionCode: id,
      },
    }));

    return res.json({
      data,
    });
  },
  'GET /vaos/v0/facilities/:id/clinics': (req, res) => {
    if (req.params.id === '983') {
      return res.json(clinicList983);
    } else if (req.params.id.startsWith(612)) {
      return res.json(clinicList612);
    }

    return res.json({
      data: [],
    });
  },
  'GET /v1/facilities/va/:id': (req, res) => {
    const facility = facilityData.data.find(f => f.id === req.params.id);

    return res.json({
      data: facility || facilityDetails983,
    });
  },
  'GET /v1/facilities/va': facilityData,
  'GET /facilities_api/v1/ccp/provider': ccProviders,
  'GET /v1/facilities/ccp/:id': (req, res) => {
    const provider = ccProviders.data.find(p => p.id === req.params.id);
    return res.json({
      data: provider,
    });
  },
  'GET /vaos/v0/facilities/:id/available_appointments': varSlots,
  'GET /vaos/v0/facilities/:id/cancel_reasons': cancelReasons,
  'GET /vaos/v0/request_eligibility_criteria': requestEligibilityCriteria,
  'GET /vaos/v0/direct_booking_eligibility_criteria': directBookingEligibilityCriteria,
  'GET /vaos/v0/preferences': { data: { attributes: { emailAllowed: true } } },
  'PUT /vaos/v0/appointments/cancel': {},
  'POST /vaos/v0/appointment_requests': {
    data: {
      id: '8a4886886e4c8e22016e6613216d001g',
      attributes: {},
    },
  },
  'PUT /vaos/v0/appointment_requests/:id': (req, res) => {
    const requestAttributes = requests.data.find(
      item => item.id === req.params.id,
    ).attributes;

    return res.json({
      data: {
        id: req.body.id,
        attributes: {
          ...requestAttributes,
          status: 'Cancelled',
        },
      },
    });
  },
  'POST /vaos/v0/appointments': {},
  'POST /vaos/v0/appointment_requests/:id/messages': {
    data: {
      attributes: {},
    },
  },
  'PUT /vaos/v0/preferences': { data: { attributes: {} } },
  'POST /vaos/v2/appointments': (req, res) => {
    const submittedAppt = {
      id: `mock${currentMockId}`,
      attributes: {
        ...req.body,
        start: req.body.slot ? req.body.slot.start : null,
      },
    };
    currentMockId++;
    mockAppts.push(submittedAppt);
    return res.json({ data: submittedAppt });
  },
  'PUT /vaos/v2/appointments/:id': (req, res) => {
    // TODO: also check through confirmed mocks, when those exist
    const appointments = requestsV2.data
      .concat(confirmedV2.data)
      .concat(mockAppts);

    const appt = appointments.find(item => item.id === req.params.id);

    return res.json({
      data: {
        id: req.params.id,
        attributes: {
          ...appt.attributes,
          ...req.body,
        },
      },
    });
  },
  'GET /vaos/v2/appointments': (req, res) => {
    if (req.query.statuses?.includes('proposed')) {
      return res.json(requestsV2);
    } else if (req.query.statuses?.includes('booked')) {
      return res.json(confirmedV2);
    }

    return res.json({ data: [] });
  },
  'GET /vaos/v2/appointments/:id': (req, res) => {
    const appointments = {
      data: requestsV2.data.concat(confirmedV2.data).concat(mockAppts),
    };
    return res.json({
      data: appointments.data.find(appt => appt.id === req.params.id),
    });
  },
  'GET /vaos/v2/scheduling/configurations': (req, res) => {
    if (req.query.cc_enabled === 'true') {
      return res.json(schedulingConfigurationsCC);
    }

    return res.json(schedulingConfigurations);
  },
  'GET /vaos/v2/facilities/:id': (req, res) => {
    return res.json({
      data: facilitiesV2.data.find(facility => facility.id === req.params.id),
    });
  },
  'GET /vaos/v2/facilities': (req, res) => {
    const ids = req.query.ids;
    const children = req.query.children;

    return res.json({
      data: facilitiesV2.data.filter(
        facility =>
          ids.includes(facility.id) ||
          (children && ids.some(id => facility.id.startsWith(id))),
      ),
    });
  },
  'GET /vaos/v2/locations/:facility_id/clinics/:clinic_id/slots': appointmentSlotsV2,
  'GET /vaos/v2/patients': (req, res) => {
    return res.json({
      data: {
        attributes: {
          hasRequiredAppointmentHistory:
            !req.query.facility_id.startsWith('984') ||
            req.query.clinical_service === 'primaryCare',
          isEligibleForNewAppointmentRequest: req.query.facility_id.startsWith(
            '983',
          ),
        },
      },
    });
  },
  'GET /vaos/v2/locations/:id/clinics': (req, res) => {
    if (req.query.clinic_ids) {
      return res.json({
        data: clinicsV2.data.filter(clinic =>
          req.query.clinic_ids.includes(clinic.id),
        ),
      });
    }

    if (req.params.id === '983') {
      return res.json(clinicsV2);
    }

    return res.json({
      data: [],
    });
  },
  'GET /v0/user': {
    data: {
      attributes: {
        profile: {
          sign_in: {
            service_name: 'idme',
          },
          email: 'fake@fake.com',
          loa: { current: 3 },
          first_name: 'Jane',
          middle_name: '',
          last_name: 'Doe',
          gender: 'F',
          birth_date: '1985-01-01',
          verified: true,
        },
        veteran_status: {
          status: 'OK',
          is_veteran: true,
          served_in_military: true,
        },
        in_progress_forms: [],
        prefills_available: ['21-526EZ'],
        services: [
          'facilities',
          'hca',
          'edu-benefits',
          'evss-claims',
          'form526',
          'user-profile',
          'health-records',
          'rx',
          'messaging',
        ],
        va_profile: {
          status: 'OK',
          birth_date: '19511118',
          family_name: 'Hunter',
          gender: 'M',
          given_names: ['Julio', 'E'],
          active_status: 'active',
          facilities: [
            {
              facility_id: '983',
              is_cerner: false,
            },
            {
              facility_id: '984',
              is_cerner: false,
            },
          ],
        },
      },
    },
    meta: { errors: null },
  },

  'OPTIONS /v0/maintenance_windows': 'OK',
  'GET /v0/maintenance_windows': { data: [] },

  'GET /v0/feature_toggles': {
    data: {
      type: 'feature_toggles',
      features: [
        { name: 'facilityLocatorShowCommunityCares', value: true },
        { name: 'profile_show_profile_2.0', value: false },
        { name: 'vaOnlineScheduling', value: true },
        { name: 'vaOnlineSchedulingCancel', value: true },
        { name: 'vaOnlineSchedulingRequests', value: true },
        { name: 'vaOnlineSchedulingCommunityCare', value: true },
        { name: 'vaOnlineSchedulingDirect', value: true },
        { name: 'vaOnlineSchedulingPast', value: true },
        { name: 'vaOnlineSchedulingExpressCare', value: true },
        { name: 'vaOnlineSchedulingFlatFacilityPage', value: true },
        { name: 'vaOnlineSchedulingUnenrolledVaccine', value: true },
        { name: 'vaGlobalDowntimeNotification', value: false },
        { name: 'vaOnlineSchedulingVAOSServiceRequests', value: true },
        { name: 'vaOnlineSchedulingVAOSServiceVAAppointments', value: true },
        { name: 'vaOnlineSchedulingFacilitiesServiceV2', value: true },
        { name: 'vaOnlineSchedulingVAOSServiceCCAppointments', value: true },
        { name: 'vaOnlineSchedulingVariantTesting', value: false },
        { name: 'vaOnlineSchedulingCCIterations', value: false },
        { name: 'ssoe', value: true },
        { name: 'ssoeInbound', value: false },
        { name: 'ssoeEbenefitsLinks', value: false },
        { name: 'edu_section_103', value: true },
        { name: 'vaViewDependentsAccess', value: false },
        { name: 'gibctEybBottomSheet', value: true },
      ],
    },
  },
};

module.exports = delay(responses, 1000);
<|endoftext|>


<commit_before>var assert = require('assert'),
    Events = require('./minivents.js');

describe('Events Constructor', function () {
  it('should return an object containing the methods used by minivents if called with new', function () {
      var bus = new Events();
      assert.equal('object', typeof bus);
  });

  it('should return an object containing the methods used by minivents if called with an empty object', function () {
      var bus = new Events();
      assert.equal('object', typeof bus);
  });

});

describe('Event busses', function () {

    it('should contain an `emit` function', function () {
      var bus = new Events();
      assert.equal('function', typeof bus.emit);
    });

    it('should contain an `off` function', function () {
      var bus = new Events();
      assert.equal('function', typeof bus.off);
    });

    it('should contain an `on` function', function () {
      var bus = new Events();
      assert.equal('function', typeof bus.on);
    });

});

describe('`on` function', function () {

  it('should not throw any exceptions when called with a string and a function', function () {
    var bus = new Events();
    try {
        bus.on('ping', function () { });
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should not throw any exceptions when called with a string, a function and an object', function () {
    var bus = new Events();
    try {
        bus.on('ping', function () { }, { });
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

});

describe('`off` function', function () {

  it('should not throw any exceptions when called with a string and a function', function () {
    var bus = new Events(),
        f = function () { };
    bus.on('ping', f);
    try {
        bus.off('ping', f);
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should not throw any exceptions when called with a function that is not registered as a callback for the specified event', function () {
    var bus = new Events();
    bus.on('ping', function () { });
    try {
        bus.off('ping', function () { });
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should not throw any exceptions when called with the name of an event that does not exist', function () {
    var bus = new Events(),
        f = function () { };
    bus.on('ping', f);
    try {
        bus.off('pong', f);
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should result in the given callback no longer being triggered', function () {
    var bus = new Events(),
        f = function () { assert.fail(undefined, undefined, 'This function must not be executed.'); };
    bus.on('ping', f);
    bus.off('ping', f);
    bus.emit('ping');
  });

});

describe('`emit` function',  function () {
    it('should result in registered callbacks being invoked',  function () {
        var bus = new Events(),
            called = 0,
            f1 = function () { called++ },
            f2 = function () { called++ },
            f3 = function () { called++ };
        bus.on('ping', f1);
        bus.on('ping', f2);
        bus.on('ping', f3);
        bus.emit('ping');
        assert(called, 3);
    });

    it('should pass all of its additional arguments to the callback',  function () {
        var bus = new Events(),
            f = function (arg0, arg1) {
              assert.equal('foo', arg0);
              assert.equal('bar', arg1);
            };
        bus.on('ping', f);
        bus.emit('ping', 'foo', 'bar');
    });

    it('should inject a callback\'s context',  function () {
        var bus = new Events(),
            ctx = { }
            f = function () { assert.equal(ctx, this); };
        bus.on('ping', f, ctx);
        bus.emit('ping');
    });

});<commit_msg>Update test.js<commit_after>var assert = require('assert'),
    Events = require('./minivents.js');

describe('Events Constructor', function () {
  it('should return an object containing the methods used by minivents if called with new', function () {
      var bus = new Events();
      assert.equal('object', typeof bus);
  });

  it('should return an object containing the methods used by minivents if called with an empty object', function () {
      var bus = new Events();
      assert.equal('object', typeof bus);
  });

});

describe('Event busses', function () {

    it('should contain an `emit` function', function () {
      var bus = new Events();
      assert.equal('function', typeof bus.emit);
    });

    it('should contain an `off` function', function () {
      var bus = new Events();
      assert.equal('function', typeof bus.off);
    });

    it('should contain an `on` function', function () {
      var bus = new Events();
      assert.equal('function', typeof bus.on);
    });

});

describe('`on` function', function () {

  it('should not throw any exceptions when called with a string and a function', function () {
    var bus = new Events();
    try {
        bus.on('ping', function () { });
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should not throw any exceptions when called with a string, a function and an object', function () {
    var bus = new Events();
    try {
        bus.on('ping', function () { }, { });
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

});

describe('`off` function', function () {

  it('should not throw any exceptions when called with a string and a function', function () {
    var bus = new Events(),
        f = function () { };
    bus.on('ping', f);
    try {
        bus.off('ping', f);
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should not throw any exceptions when called with a function that is not registered as a callback for the specified event', function () {
    var bus = new Events();
    bus.on('ping', function () { });
    try {
        bus.off('ping', function () { });
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should not throw any exceptions when called with the name of an event that does not exist', function () {
    var bus = new Events(),
        f = function () { };
    bus.on('ping', f);
    try {
        bus.off('pong', f);
    } catch (e) {
        assert.fail(undefined, e, e.toString());
    }
  });

  it('should result in the given callback no longer being triggered', function () {
    var bus = new Events(),
        f = function () { assert.fail(undefined, undefined, 'This function must not be executed.'); };
    bus.on('ping', f);
    bus.off('ping', f);
    bus.emit('ping');
  });

});

describe('`emit` function',  function () {
    it('should result in registered callbacks being invoked',  function () {
        var bus = new Events(),
            called = 0,
            f1 = function () { called++ },
            f2 = function () { called++ },
            f3 = function () { called++ };
        bus.on('ping', f1);
        bus.on('ping', f2);
        bus.on('ping', f3);
        bus.emit('ping');
        assert.equal(called, 3);
    });

    it('should pass all of its additional arguments to the callback',  function () {
        var bus = new Events(),
            f = function (arg0, arg1) {
              assert.equal('foo', arg0);
              assert.equal('bar', arg1);
            };
        bus.on('ping', f);
        bus.emit('ping', 'foo', 'bar');
    });

    it('should inject a callback\'s context',  function () {
        var bus = new Events(),
            ctx = { }
            f = function () { assert.equal(ctx, this); };
        bus.on('ping', f, ctx);
        bus.emit('ping');
    });

});
<|endoftext|>