<commit_before>define(['./semver'], function(semver) {
  return {
    loadedCache: {},
    getVersionNum: function(name, callback) {
      var hashIndex = name.lastIndexOf('#');
      var moduleName = name.substr(0, hashIndex);
      var versionRange = name.substr(hashIndex + 1);

      var loadedCache = this.loadedCache;

      if (!semver.validRange(versionRange))
        throw moduleName + '#' + versionRange + ' has an invalid version range.';

      // load the version ranges for the given moduleName
      req([moduleName], function(supportedVersions) {
        // first check if we have any loaded versions for this module
        if (loadedCache[moduleName]) {
          for (var v in loadedCache[moduleName])
            if (semver.satisfies(v, version))
              return callback(v);
        }

        // no supported loaded version - need to load a version
        callback(semver.maxSatisfying(supportedVersions, version));

      }, function(err) {
        throw 'You need to provide a "' + moduleName + '" module providing the version array.';
      });
    },
    load: function(name, req, load, config) {
      this.getVersionNum(name, function(version) {
        // load from the expected filename convention
        req([moduleName + '-' + version], function(m) {
          loadedCache[moduleName] = loadedCache[moduleName] || {};
          loadedCache[moduleName][loadVersion] = true;
          load(m);
        });
      });
    },
    write: function(pluginName, name, write) {
      this.getVersionNum(name, function(version) {
        write.asModule(pluginName + '!' + moduleName, "define(['" + name + '-' + version + "'], function(m){ return m; });")
      });
    }
  };
});<commit_msg>minor corrections<commit_after>define(['./semver'], function(semver) {
  return {
    loadedVersions: {},
    getVersionNum: function(name, callback) {
      var hashIndex = name.lastIndexOf('#');
      var moduleName = name.substr(0, hashIndex);
      var versionRange = name.substr(hashIndex + 1);

      var loadedCache = this.loadedVersions;

      if (!semver.validRange(versionRange))
        throw moduleName + '#' + versionRange + ' has an invalid version range.';

      // load the version ranges for the given moduleName
      req([moduleName], function(supportedVersions) {
        // first check if we have any loaded versions for this module
        if (loadedVersions[moduleName]) {
          for (var v in loadedVersions[moduleName])
            if (semver.satisfies(v, version))
              return callback(v);
        }

        // no supported loaded version - need to load a version
        callback(semver.maxSatisfying(supportedVersions, version));

      }, function(err) {
        throw 'You need to provide a "' + moduleName + '" module providing the version array.';
      });
    },
    load: function(name, req, load, config) {
      var loadedVersions = this.loadedVersions;
      this.getVersionNum(name, function(version) {
        // load from the expected filename convention
        req([moduleName + '-' + version], function(m) {
          loadedVersions[moduleName] = loadedVersions[moduleName] || {};
          loadedVersions[moduleName][loadVersion] = true;
          load(m);
        });
      });
    },
    write: function(pluginName, name, write) {
      this.getVersionNum(name, function(version) {
        write.asModule(pluginName + '!' + moduleName, "define(['" + name + '-' + version + "'], function(m){ return m; });")
      });
    }
  };
});<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Feb 01 2016 22:48:23 GMT-0500 (EST)

module.exports = function(config) {
	var configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ['mocha', 'requirejs'],

		// list of files / patterns to load in the browser
		files: [
			// '../test/helper/Test.js',
			'test/karmaTest.js',
			{pattern: 'test/*/*.js', included: false},
			{pattern: 'examples/*.html', included: false},
			{pattern: 'examples/scripts/*.js', included: false},
			{pattern: 'examples/style/*.css', included: false},
			{pattern: 'examples/audio/*/*.mp3', included: false},
			{pattern: 'examples/audio/*.mp3', included: false},
			{pattern: 'examples/audio/*/*.png', included: false},
			{pattern: 'build/*.js', included: false},
			{pattern: 'test/audio/*', included: false},
			{pattern: 'Tone/*/*.js', included: false},
			],

		// list of files to exclude
		exclude: [],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'Tone/!(shim)/*.js': ['coverage']
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['dots', 'coverage'],

		coverageReporter: {
			type : 'lcov',
			dir : 'test/coverage/'
		},

		//plugins
		plugins : [
		'karma-coverage',
		'karma-mocha',
		'karma-requirejs',
		'karma-chrome-launcher',
		'karma-firefox-launcher'
		],

		client: {
			mocha: {
				reporter: 'html', // change Karma's debug.html to the mocha web reporter
				ui: 'bdd'
			}
		},

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// set the inactivity level to longer
		browserNoActivityTimeout : 40000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		// browsers: ['HeadlessChrome', 'HeadlessFirefox'],
		browsers: ['HeadlessChrome'],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: false,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: process.env.TRAVIS ? 1 : Infinity,
		// concurrency: Infinity,

		//custom launcher for travis
		customLaunchers: {
			HeadlessChrome: {
				base: 'ChromeHeadless',
				flags: ['--no-sandbox', '--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream']
			},
			HeadlessFirefox: {
		        base: 'Firefox',
				flags: [ '-headless' ],
		        prefs: {
		            'media.navigator.permission.disabled': true,
					'focusmanager.testmode': true
		        }
		    }
		}
	};

	config.set(configuration);
};
<commit_msg>running tests on headless FF<commit_after>// Karma configuration
// Generated on Mon Feb 01 2016 22:48:23 GMT-0500 (EST)

module.exports = function(config) {
	var configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: ['mocha', 'requirejs'],

		// list of files / patterns to load in the browser
		files: [
			// '../test/helper/Test.js',
			'test/karmaTest.js',
			{pattern: 'test/*/*.js', included: false},
			{pattern: 'examples/*.html', included: false},
			{pattern: 'examples/scripts/*.js', included: false},
			{pattern: 'examples/style/*.css', included: false},
			{pattern: 'examples/audio/*/*.mp3', included: false},
			{pattern: 'examples/audio/*.mp3', included: false},
			{pattern: 'examples/audio/*/*.png', included: false},
			{pattern: 'build/*.js', included: false},
			{pattern: 'test/audio/*', included: false},
			{pattern: 'Tone/*/*.js', included: false},
			],

		// list of files to exclude
		exclude: [],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'Tone/!(shim)/*.js': ['coverage']
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['dots', 'coverage'],

		coverageReporter: {
			type : 'lcov',
			dir : 'test/coverage/'
		},

		//plugins
		plugins : [
		'karma-coverage',
		'karma-mocha',
		'karma-requirejs',
		'karma-chrome-launcher',
		'karma-firefox-launcher'
		],

		client: {
			mocha: {
				reporter: 'html', // change Karma's debug.html to the mocha web reporter
				ui: 'bdd'
			}
		},

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// set the inactivity level to longer
		browserNoActivityTimeout : 40000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: ['HeadlessFirefox', 'HeadlessChrome'],
		// browsers: ['HeadlessChrome'],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: false,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: process.env.TRAVIS ? 1 : Infinity,
		// concurrency: Infinity,

		//custom launcher for travis
		customLaunchers: {
			HeadlessChrome: {
				base: 'ChromeHeadless',
				flags: ['--no-sandbox', '--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream']
			},
			HeadlessFirefox: {
		        base: 'Firefox',
				flags: [ '-headless' ],
		        prefs: {
		            'media.navigator.permission.disabled': true,
					'focusmanager.testmode': true
		        }
		    }
		}
	};

	config.set(configuration);
};
<|endoftext|>


<commit_before><commit_msg>added boilerplate for spec file<commit_after>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow, render, mount } from 'enzyme';
import chai from 'chai';
import sinon from 'sinon';

import Form from '../Form';

const expect = chai.expect;

/* eslint-disable no-unused-vars */
const debug = (component) => {
    console.info('------------------------------------------------------------');
    console.info(component.debug());
    console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */
<|endoftext|>


<commit_before>/**
 * @module test/index.spec
 */
'use strict';

var Code = require('code');
var Lab = require('lab');
var rewire = require('rewire');
var sinon = require('sinon');

var Hermes = rewire('../index');

var connectionOpts = require('./fixtures/connection-opts');
var mockChannel = require('./fixtures/mock-channel');

var lab = exports.lab = Lab.script();

var after = lab.after;
var afterEach = lab.afterEach;
var before = lab.before;
var beforeEach = lab.beforeEach;
var describe = lab.describe;
var expect = Code.expect;
var it = lab.it;

describe('hermes', function () {
  var HermesClass = Hermes.__get__('Hermes');

  it('should throw an exception if not supplied correct opts', function (done) {
    var throws = function () {
      return Hermes.hermesSingletonFactory({});
    };
    expect(throws).to.throw();
    done();
  });

  it('should initiate a connection to a rabbitmq server on instantiate', function (done) {
    var hermesAmqplib = Hermes.__get__('amqplib');
    sinon.stub(hermesAmqplib, 'connect', function (url) {
      expect(url).to.be.a.string();
      expect(url).to.equal('amqp://tom:harry@bobsburgers.net:1111');
      hermesAmqplib.connect.restore();
      done();
    });
    var hermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
  });

  it('should correctly construct connection url string without a specified port', function (done) {
    var hermesAmqplib = Hermes.__get__('amqplib');
    sinon.stub(hermesAmqplib, 'connect', function (url) {
      expect(url).to.be.a.string();
      expect(url).to.equal('amqp://tom:harry@bobsburgers.net');
      hermesAmqplib.connect.restore();
      done();
    });
    var hermes = new HermesClass(connectionOpts.noSpecPort);
  });

  describe('pre-connect and post-connect functionality', function () {
    var TEST_QUEUE = 'test-queue';
    var channel;
    var connectFinish;
    var hermes;
    var hermesAmqplib;
    var originalQueues;

    beforeEach(function (done) {
      originalQueues = Hermes.__get__('queues')
      Hermes.__set__('queues', [TEST_QUEUE]);

      hermesAmqplib = Hermes.__get__('amqplib');
      // connectFinish allow testing pre-post connected states
      sinon.stub(hermesAmqplib, 'connect', function (url, cb) {
        connectFinish = function () {
          cb(null, {
            createChannel: function (cb) {
              channel = mockChannel();
              cb(null, channel);
            }
          });
        };
      });
      hermes = new HermesClass(connectionOpts.standard);
      done();
    });

    afterEach(function (done) {
      hermesAmqplib.connect.restore();
      Hermes.__set__('queues', originalQueues);
      done();
    });

    it('should automatically queue subscribe invokations until connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var subscribeCB = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, subscribeCB);
      expect(hermes.subscribeQueue).to.have.length(1);
      // simulate connection complete
      connectFinish();
      // all queued subscribe jobs are complete
      expect(hermes.subscribeQueue).to.have.length(0);
      done();
    });

    it('should automatically queue publish invokations until connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var testData = {foo: 'bar'};
      hermes.publish(TEST_QUEUE, testData);
      expect(hermes.publishQueue).to.have.length(1);
      // simulate connection complete
      connectFinish();
      // all queued subscribe jobs are complete
      expect(hermes.publishQueue).to.have.length(0);
      done();
    });

    it('should not queue publish invokations if already connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      connectFinish();
      // connected...
      var testData = {foo: 'bar'};
      expect(hermes.publishQueue).to.have.length(0);
      hermes.publish(TEST_QUEUE, testData);
      expect(hermes.publishQueue).to.have.length(0);
      expect(channel.sendToQueue.callCount).to.equal(1);
      expect(channel.sendToQueue.args[0][0]).to.equal(TEST_QUEUE);
      expect(channel.sendToQueue.args[0][1].toString())
        .to.equal(new Buffer(JSON.stringify(testData)).toString());
      done();
    });

    it('should not queue subscribe invokations if already connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      connectFinish();
      // connected...
      var subscribeCB = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, subscribeCB);
      expect(hermes.subscribeQueue).to.have.length(0);
      expect(channel.consume.callCount).to.equal(1);
      expect(channel.consume.args[0][0]).to.equal(TEST_QUEUE);
      done();
    });

    it('should remove workers from subscribe queue on unsubscribe if not yet connected', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var worker = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, worker);
      expect(hermes.subscribeQueue).to.have.length(1);
      // only has consumerTag if registered w/ rabbitmq
      expect(Object.keys(hermes.consumerTags)).to.have.length(0);
      hermes.unsubscribe(TEST_QUEUE, worker);
      expect(hermes.subscribeQueue).to.have.length(0);
      expect(Object.keys(hermes.consumerTags)).to.have.length(0);
      done();
    });

    it('should unsubscribe workers from rabbitmq', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var worker = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, worker);
      expect(hermes.subscribeQueue).to.have.length(1);
      connectFinish();
      // connected...
      expect(hermes.subscribeQueue).to.have.length(0);
      expect(Object.keys(hermes.consumerTags)).to.have.length(1);
      hermes.unsubscribe(TEST_QUEUE, worker);
      expect(Object.keys(hermes.consumerTags)).to.have.length(0);
      done();
    });

  });
});
<commit_msg>additional assertions<commit_after>/**
 * @module test/index.spec
 */
'use strict';

var Code = require('code');
var Lab = require('lab');
var rewire = require('rewire');
var sinon = require('sinon');

var Hermes = rewire('../index');

var connectionOpts = require('./fixtures/connection-opts');
var mockChannel = require('./fixtures/mock-channel');

var lab = exports.lab = Lab.script();

var after = lab.after;
var afterEach = lab.afterEach;
var before = lab.before;
var beforeEach = lab.beforeEach;
var describe = lab.describe;
var expect = Code.expect;
var it = lab.it;

describe('hermes', function () {
  var HermesClass = Hermes.__get__('Hermes');

  it('should throw an exception if not supplied correct opts', function (done) {
    var throws = function () {
      return Hermes.hermesSingletonFactory({});
    };
    expect(throws).to.throw();
    done();
  });

  it('should initiate a connection to a rabbitmq server on instantiate', function (done) {
    var hermesAmqplib = Hermes.__get__('amqplib');
    sinon.stub(hermesAmqplib, 'connect', function (url) {
      expect(url).to.be.a.string();
      expect(url).to.equal('amqp://tom:harry@bobsburgers.net:1111');
      hermesAmqplib.connect.restore();
      done();
    });
    var hermes = Hermes.hermesSingletonFactory(connectionOpts.standard);
  });

  it('should correctly construct connection url string without a specified port', function (done) {
    var hermesAmqplib = Hermes.__get__('amqplib');
    sinon.stub(hermesAmqplib, 'connect', function (url) {
      expect(url).to.be.a.string();
      expect(url).to.equal('amqp://tom:harry@bobsburgers.net');
      hermesAmqplib.connect.restore();
      done();
    });
    var hermes = new HermesClass(connectionOpts.noSpecPort);
  });

  describe('pre-connect and post-connect functionality', function () {
    var TEST_QUEUE = 'test-queue';
    var channel;
    var connectFinish;
    var hermes;
    var hermesAmqplib;
    var originalQueues;

    beforeEach(function (done) {
      originalQueues = Hermes.__get__('queues')
      Hermes.__set__('queues', [TEST_QUEUE]);

      hermesAmqplib = Hermes.__get__('amqplib');
      // connectFinish allow testing pre-post connected states
      sinon.stub(hermesAmqplib, 'connect', function (url, cb) {
        connectFinish = function () {
          cb(null, {
            createChannel: function (cb) {
              channel = mockChannel();
              cb(null, channel);
            }
          });
        };
      });
      hermes = new HermesClass(connectionOpts.standard);
      done();
    });

    afterEach(function (done) {
      hermesAmqplib.connect.restore();
      Hermes.__set__('queues', originalQueues);
      done();
    });

    it('should automatically queue subscribe invokations until connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var subscribeCB = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, subscribeCB);
      expect(hermes.subscribeQueue).to.have.length(1);
      // simulate connection complete
      connectFinish();
      // all queued subscribe jobs are complete
      expect(hermes.subscribeQueue).to.have.length(0);
      done();
    });

    it('should automatically queue publish invokations until connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var testData = {foo: 'bar'};
      hermes.publish(TEST_QUEUE, testData);
      expect(hermes.publishQueue).to.have.length(1);
      // simulate connection complete
      connectFinish();
      // all queued subscribe jobs are complete
      expect(hermes.publishQueue).to.have.length(0);
      done();
    });

    it('should not queue publish invokations if already connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      connectFinish();
      // connected...
      var testData = {foo: 'bar'};
      expect(hermes.publishQueue).to.have.length(0);
      hermes.publish(TEST_QUEUE, testData);
      expect(hermes.publishQueue).to.have.length(0);
      expect(channel.sendToQueue.callCount).to.equal(1);
      expect(channel.sendToQueue.args[0][0]).to.equal(TEST_QUEUE);
      expect(channel.sendToQueue.args[0][1].toString())
        .to.equal(new Buffer(JSON.stringify(testData)).toString());
      done();
    });

    it('should not queue subscribe invokations if already connected to RabbitMQ server', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      connectFinish();
      // connected...
      var subscribeCB = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, subscribeCB);
      expect(hermes.subscribeQueue).to.have.length(0);
      expect(channel.consume.callCount).to.equal(1);
      expect(channel.consume.args[0][0]).to.equal(TEST_QUEUE);
      done();
    });

    it('should remove workers from subscribe queue on unsubscribe if not yet connected', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var worker = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, worker);
      expect(hermes.subscribeQueue).to.have.length(1);
      // only has consumerTag if registered w/ rabbitmq
      expect(Object.keys(hermes.consumerTags)).to.have.length(0);
      hermes.unsubscribe(TEST_QUEUE, worker);
      expect(hermes.subscribeQueue).to.have.length(0);
      expect(Object.keys(hermes.consumerTags)).to.have.length(0);
      done();
    });

    it('should unsubscribe workers from rabbitmq', function (done) {
      expect(hermesAmqplib.connect.callCount).to.equal(1);
      // not yet connected...
      var worker = function (data, done) {};
      hermes.subscribe(TEST_QUEUE, worker);
      expect(hermes.subscribeQueue).to.have.length(1);
      connectFinish();
      // connected...
      expect(hermes.subscribeQueue).to.have.length(0);
      expect(Object.keys(hermes.consumerTags)).to.have.length(1);
      var consumerTag = Object.keys(hermes.consumerTags)[0];
      hermes.unsubscribe(TEST_QUEUE, worker);
      expect(Object.keys(hermes.consumerTags)).to.have.length(0);
      expect(channel.cancel.callCount).to.equal(1);
      expect(channel.cancel.args[0][0]).to.equal(consumerTag);
      done();
    });

  });
});
<|endoftext|>


<commit_before>// import articlesReducer from 'redux/modules/articlesModule';
// import { expect } from 'chai';

// describe('articlesReducer', () => {
//   const initialState = {
//     // Loading all articles
//     all: [],
//     loadingArticles: false,
//     articlesLoaded: false,
//     loadArticlesError: '',
//     // Adding new article
//     addingArticle: false,
//     articleAdded: null, // (Number) ID of an article that was just added
//     addArticleError: '',
//     // Editing article
//     editingArticle: false,
//     articleEdited: false,
//     editArticleError: '',
//     // Removing a article
//     removingArticle: null, // (Number) ID of an article being removed
//     articleRemoved: false,
//     removeArticleError: ''
//   }

//   const mockMessages = {
//     message: [ { id: 29,
//       title: 'Lorem dolor',
//       content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce egestas pellentesque tellus. Phasellus vitae urna sit amet purus fermentum consectetur. Vestibulum sed dapibus metus. Etiam commodo pulvinar porttitor. Proin ac dui justo. In lacus ex, varius vitae erat in, ullamcorper hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
//       createdAt: '2017-03-31T15:54:06.801Z',
//       updatedAt: '2017-04-05T19:17:40.671Z' },
//       { id: 23,
//       title: 'Test article',
//       content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce egestas pellentesque tellus. Phasellus vitae urna sit amet purus fermentum consectetur. Vestibulum sed dapibus metus. Etiam commodo pulvinar porttitor. Proin ac dui justo. In lacus ex, varius vitae erat in, ullamcorper hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
//       createdAt: '2017-03-30T15:29:22.612Z',
//       updatedAt: '2017-04-05T19:17:51.893Z' },
//       { id: 26,
//       title: 'Lorem ipsum',
//       content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce egestas pellentesque tellus. Phasellus vitae urna sit amet purus fermentum consectetur. Vestibulum sed dapibus metus. Etiam commodo pulvinar porttitor. Proin ac dui justo. In lacus ex, varius vitae erat in, ullamcorper hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
//       createdAt: '2017-03-31T08:58:50.830Z',
//       updatedAt: '2017-04-05T19:56:00.137Z' },
//       { id: 30,
//       title: 'updated test title',
//       content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"updated test content 123\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
//       createdAt: '2017-04-05T12:22:46.389Z',
//       updatedAt: '2017-04-05T20:19:18.979Z' },
//       { id: 31,
//       title: 'Test 1',
//       content: '"{\\"nodes\\":[{\\"kind\\":\\"block\\",\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"text\\":\\"Content...\\"}]}]}]}"',
//       createdAt: '2017-04-06T14:05:44.482Z',
//       updatedAt: '2017-04-06T14:05:44.482Z' },
//       { id: 32,
//       title: 'Test 2',
//       content: '"{\\"nodes\\":[{\\"kind\\":\\"block\\",\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"text\\":\\"Content...\\"}]}]}]}"',
//       createdAt: '2017-04-06T14:06:03.450Z',
//       updatedAt: '2017-04-06T14:06:03.450Z' },
//       { id: 33,
//       title: 'Test 3',
//       content: '"{\\"nodes\\":[{\\"kind\\":\\"block\\",\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"text\\":\\"Content...\\"}]}]}]}"',
//       createdAt: '2017-04-06T14:06:19.233Z',
//       updatedAt: '2017-04-06T14:06:19.233Z' }
//     ]
//   }
//   // it('should return initial state', () => {
//   //   expect(
//   //     articlesReducer(undefined, {})
//   //   ).to.equal(
//   //   {
//   //     // Loading all articles
//   //     all: [],
//   //     loadingArticles: false,
//   //     articlesLoaded: false,
//   //     loadArticlesError: '',
//   //     // Adding new article
//   //     addingArticle: false,
//   //     articleAdded: null, // (Number) ID of an article that was just added
//   //     addArticleError: '',
//   //     // Editing article
//   //     editingArticle: false,
//   //     articleEdited: false,
//   //     editArticleError: '',
//   //     // Removing a article
//   //     removingArticle: null, // (Number) ID of an article being removed
//   //     articleRemoved: false,
//   //     removeArticleError: ''
//   //   }
//   //   )
//   // })

//   it('should handle LOAD_ARTICLES_REQUEST', () => {
//     const result = articlesReducer(initialState, { type: 'LOAD_ARTICLES_REQUEST'})
//     expect(result.articlesLoaded).to.equal(false)
//     expect(result.loadingArticles).to.equal(true)
//     expect(result.loadArticlesError).to.equal(null)
//   })

//   it('should handle LOAD_ARTICLES_SUCCESS', () => {
//     const result = articlesReducer(initialState, { type: 'LOAD_ARTICLES_SUCCESS', result: mockMessages })
//     expect(result.all.length).to.equal(7)
//     expect(result.loadingArticles).to.equal(false)
//     expect(result.articlesLoaded).to.equal(true)
//   })

//   it('should handle LOAD_ARTICLES_FAIL', () => {
//     const result = articlesReducer(initialState, { type: 'LOAD_ARTICLES_FAIL', error: { message: `test error` } })
//     expect(result.loadingArticles).to.equal(false)
//     expect(result.articlesLoaded).to.equal(false)
//     expect(result.loadArticlesError).to.equal(`Error while loading articles: test error`)
//   })
// })<commit_msg>fix articlesModule tests<commit_after>import articlesReducer from 'redux/modules/articlesModule';
import { expect } from 'chai';

describe('articlesReducer', () => {
  const initialState = {
    // Loading all articles
    all: [],
    loadingArticles: false,
    articlesLoaded: false,
    loadArticlesError: '',
    // Adding new article
    addingArticle: false,
    articleAdded: null, // (Number) ID of an article that was just added
    addArticleError: '',
    // Editing article
    editingArticle: false,
    articleEdited: false,
    editArticleError: '',
    // Removing a article
    removingArticle: null, // (Number) ID of an article being removed
    articleRemoved: false,
    removeArticleError: ''
  }

  const mockMessages = {
    message: [ { id: 29,
      title: 'Lorem dolor',
      content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce egestas pellentesque tellus. Phasellus vitae urna sit amet purus fermentum consectetur. Vestibulum sed dapibus metus. Etiam commodo pulvinar porttitor. Proin ac dui justo. In lacus ex, varius vitae erat in, ullamcorper hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
      createdAt: '2017-03-31T15:54:06.801Z',
      updatedAt: '2017-04-05T19:17:40.671Z' },
      { id: 23,
      title: 'Test article',
      content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce egestas pellentesque tellus. Phasellus vitae urna sit amet purus fermentum consectetur. Vestibulum sed dapibus metus. Etiam commodo pulvinar porttitor. Proin ac dui justo. In lacus ex, varius vitae erat in, ullamcorper hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
      createdAt: '2017-03-30T15:29:22.612Z',
      updatedAt: '2017-04-05T19:17:51.893Z' },
      { id: 26,
      title: 'Lorem ipsum',
      content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce egestas pellentesque tellus. Phasellus vitae urna sit amet purus fermentum consectetur. Vestibulum sed dapibus metus. Etiam commodo pulvinar porttitor. Proin ac dui justo. In lacus ex, varius vitae erat in, ullamcorper hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
      createdAt: '2017-03-31T08:58:50.830Z',
      updatedAt: '2017-04-05T19:56:00.137Z' },
      { id: 30,
      title: 'updated test title',
      content: '"{\\"document\\":{\\"data\\":{},\\"kind\\":\\"document\\",\\"nodes\\":[{\\"data\\":{},\\"kind\\":\\"block\\",\\"isVoid\\":false,\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"kind\\":\\"range\\",\\"text\\":\\"updated test content 123\\",\\"marks\\":[]}]}]}]},\\"kind\\":\\"state\\"}"',
      createdAt: '2017-04-05T12:22:46.389Z',
      updatedAt: '2017-04-05T20:19:18.979Z' },
      { id: 31,
      title: 'Test 1',
      content: '"{\\"nodes\\":[{\\"kind\\":\\"block\\",\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"text\\":\\"Content...\\"}]}]}]}"',
      createdAt: '2017-04-06T14:05:44.482Z',
      updatedAt: '2017-04-06T14:05:44.482Z' },
      { id: 32,
      title: 'Test 2',
      content: '"{\\"nodes\\":[{\\"kind\\":\\"block\\",\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"text\\":\\"Content...\\"}]}]}]}"',
      createdAt: '2017-04-06T14:06:03.450Z',
      updatedAt: '2017-04-06T14:06:03.450Z' },
      { id: 33,
      title: 'Test 3',
      content: '"{\\"nodes\\":[{\\"kind\\":\\"block\\",\\"type\\":\\"paragraph\\",\\"nodes\\":[{\\"kind\\":\\"text\\",\\"ranges\\":[{\\"text\\":\\"Content...\\"}]}]}]}"',
      createdAt: '2017-04-06T14:06:19.233Z',
      updatedAt: '2017-04-06T14:06:19.233Z' }
    ]
  }
  // it('should return initial state', () => {
  //   expect(
  //     articlesReducer(undefined, {})
  //   ).to.equal(
  //   {
  //     // Loading all articles
  //     all: [],
  //     loadingArticles: false,
  //     articlesLoaded: false,
  //     loadArticlesError: '',
  //     // Adding new article
  //     addingArticle: false,
  //     articleAdded: null, // (Number) ID of an article that was just added
  //     addArticleError: '',
  //     // Editing article
  //     editingArticle: false,
  //     articleEdited: false,
  //     editArticleError: '',
  //     // Removing a article
  //     removingArticle: null, // (Number) ID of an article being removed
  //     articleRemoved: false,
  //     removeArticleError: ''
  //   }
  //   )
  // })

  it('should handle LOAD_ARTICLES_REQUEST', () => {
    const result = articlesReducer(initialState, { type: 'LOAD_ARTICLES_REQUEST'})
    expect(result.articlesLoaded).to.equal(false)
    expect(result.loadingArticles).to.equal(true)
    expect(result.loadArticlesError).to.equal(false)
  })

  it('should handle LOAD_ARTICLES_SUCCESS', () => {
    const result = articlesReducer(initialState, { type: 'LOAD_ARTICLES_SUCCESS', result: mockMessages })
    expect(result.all.length).to.equal(7)
    expect(result.loadingArticles).to.equal(false)
    expect(result.articlesLoaded).to.equal(true)
  })

  it('should handle LOAD_ARTICLES_FAIL', () => {
    const result = articlesReducer(initialState, { type: 'LOAD_ARTICLES_FAIL', error: { message: `test error` } })
    expect(result.loadingArticles).to.equal(false)
    expect(result.articlesLoaded).to.equal(false)
    expect(result.loadArticlesError).to.equal(true)
  })
})<|endoftext|>


<commit_before>var gulp = require('gulp');
var less = require('gulp-less');
var lesshint = require('gulp-lesshint');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var cached = require('gulp-cached');
var watch = require('gulp-watch');
var runSequence = require('run-sequence');
var mergeStream = require('merge-stream');
var config = require('./../config');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('less', function () {

	return mergeStream(config.global.resources.map( function(currentResource) {
		return gulp.src([
			config.global.src + currentResource + '/less/**/*.less',
			'!' + config.global.src + currentResource + '/less/**/_*.less'
		])
			.pipe(sourcemaps.init())
			.pipe(less().on('error', less.logError))
			.pipe(postcss([
				autoprefixer(config.autoprefixer)
			]))
			.pipe(sourcemaps.write('.'))
			.pipe(gulp.dest(config.global.dev + currentResource + '/css'));
	}));
});

gulp.task('lint:less', function() {
  if (config.global.tasks.linting) {
    return mergeStream(config.global.resources.map( function(currentResource) {
      return gulp.src(config.global.src + currentResource.replace('/','') + '/less/**/*.less')
				.pipe(cached('less'))
				.pipe(lesshint({}))
				.pipe(lesshint.reporter()) // Leave empty to use the default, "stylish"
				.pipe(lesshint.failOnError()); // Use this to fail the task on lint errors
    }));
  }
});

gulp.task('watch:less', function () {

	config.global.resources.forEach(function(currentResource) {
		watch([
			config.global.src + currentResource + '/css/**/*.less'
		], function () {
			runSequence(
				['lint:less'],
				['less']
			);
		});
	});

});
<commit_msg>fix gulp task lint:less<commit_after>var gulp = require('gulp');
var less = require('gulp-less');
var path = require('path');
var lesshint = require('gulp-lesshint');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var cached = require('gulp-cached');
var watch = require('gulp-watch');
var runSequence = require('run-sequence');
var mergeStream = require('merge-stream');
var config = require('./../config');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('less', function () {

	return mergeStream(config.global.resources.map( function(currentResource) {
		return gulp.src([
			config.global.src + currentResource + '/less/**/*.less',
			'!' + config.global.src + currentResource + '/less/**/_*.less'
		])
			.pipe(sourcemaps.init())
			.pipe(less({
        paths: [ path.join(__dirname, 'less', 'includes') ]
      }))
			.pipe(postcss([
				autoprefixer(config.autoprefixer)
			]))
			.pipe(sourcemaps.write('.'))
			.pipe(gulp.dest(config.global.dev + currentResource + '/css'));
	}));
});

gulp.task('lint:less', function() {
  if (config.global.tasks.linting) {
    return mergeStream(config.global.resources.map( function(currentResource) {
      return gulp.src(config.global.src + currentResource.replace('/','') + '/less/**/*.less')
				.pipe(cached('less'))
				.pipe(lesshint({}))
				.pipe(lesshint.reporter()) // Leave empty to use the default, "stylish"
				.pipe(lesshint.failOnError()); // Use this to fail the task on lint errors
    }));
  }
});

gulp.task('watch:less', function () {

	config.global.resources.forEach(function(currentResource) {
		watch([
			config.global.src + currentResource + '/css/**/*.less'
		], function () {
			runSequence(
				['lint:less'],
				['less']
			);
		});
	});

});
<|endoftext|>


<commit_before>import { test } from 'tap'
import React from 'react'
import { shallow } from 'enzyme'
import JSONTree from 'react-json-tree'

import PropsViewer from '../src'

test('props-viewer should generate a component', (t) => {
  const Robot = PropsViewer('Robot')

  t.equal(typeof Robot, 'function')
  t.equal(Robot.length, 1)
  t.equal(Robot.displayName, 'Robot')
  t.end()
})

test('shallow', (t) => {
  const Robot = PropsViewer('Robot')
  const props = {
    ava: 43
  }

  const wrapper = shallow(<Robot {...props} />)

  t.equal(wrapper.contains(Robot), true)
  t.equal(wrapper.contains(<JSONTree data={props} />), true)
  t.end()
})

test('props-viewer should throw when name is not a string', (t) => {
  t.throws(() => PropsViewer(), 'expected name to be a string')
  t.throws(() => PropsViewer(43), 'expected name to be a string')
  t.end()
})
<commit_msg>test(index): adapt to enzyme 3.0 API usage<commit_after>import { test } from 'tap'
import React from 'react'
import Enzyme, { shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-15'
import JSONTree from 'react-json-tree'

import PropsViewer from '../src'

Enzyme.configure({ adapter: new Adapter() })

test('props-viewer should generate a component', (t) => {
  const Robot = PropsViewer('Robot')

  t.equal(typeof Robot, 'function')
  t.equal(Robot.length, 1)
  t.equal(Robot.displayName, 'Robot')
  t.end()
})

test('shallow', (t) => {
  const Robot = PropsViewer('Robot')
  const props = {
    ava: 43
  }

  const wrapper = shallow(<Robot {...props} />)

  t.equal(wrapper.contains(Robot), true)
  t.equal(wrapper.contains(<JSONTree data={props} />), true)
  t.end()
})

test('props-viewer should throw when name is not a string', (t) => {
  t.throws(() => PropsViewer(), 'expected name to be a string')
  t.throws(() => PropsViewer(43), 'expected name to be a string')
  t.end()
})
<|endoftext|>


<commit_before>import React from 'react';
import Highlight, { defaultProps } from 'prism-react-renderer';
import customTheme from 'prism-react-renderer/themes/vsDark';

const InlineCode = ({ children, className, additionalPreClasses, theme }) => {
  className = className ? className : '';
  const language = className.replace(/language-/, '');
  return (
    <Highlight
      {...defaultProps}
      code={children}
      language={language}
      theme={theme || customTheme}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre
          className={`docs-code sprk-u-Measure ${className} ${additionalPreClasses}`}
          style={{ ...style }}
        >
          {tokens.map((line, i) => (

              {line.map((token, key) => (

              ))}

          ))}

      )}
    </Highlight>
  );
};

export default InlineCode;
<commit_msg>prism theme<commit_after>import React from 'react';
import Highlight, { defaultProps } from 'prism-react-renderer';
import customTheme from 'prism-react-renderer/themes/duotoneDark';

const InlineCode = ({ children, className, additionalPreClasses, theme }) => {
  className = className ? className : '';
  const language = className.replace(/language-/, '');
  return (
    <Highlight
      {...defaultProps}
      code={children}
      language={language}
      theme={theme || customTheme}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre
          className={`docs-code sprk-u-Measure ${className} ${additionalPreClasses}`}
          style={{ ...style }}
        >
          {tokens.map((line, i) => (

              {line.map((token, key) => (

              ))}

          ))}

      )}
    </Highlight>
  );
};

export default InlineCode;
<|endoftext|>


<commit_before>var gulp         = require('gulp');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var postcss      = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var mqpacker     = require('css-mqpacker');
var config       = require('../config');

var processors = [
    autoprefixer({
        browsers: ['last 4 versions'],
        cascade: false
    }),
    mqpacker({
        sort: sortMediaQueries
    })
];

gulp.task('sass', function() {
    return gulp
        .src(config.src.sass + '/*.{sass,scss}')
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: config.production ? 'compact' : 'expanded', // nested, expanded, compact, compressed
            precision: 5
        }))
        .on('error', config.errorHandler)
        .pipe(postcss(processors))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(config.dest.css));
});

gulp.task('sass:watch', function() {
    gulp.watch(config.src.sass + '/**/*.{sass,scss}', ['sass']);
});

function isMax(mq) {
    return /max-width/.test(mq);
}

function isMin(mq) {
    return /min-width/.test(mq);
}

function sortMediaQueries(a, b) {
    A = a.replace(/\D/g, '');
    B = b.replace(/\D/g, '');

    if (isMax(a) && isMax(b)) {
        return B - A;
    } else if (isMin(a) && isMin(b)) {
        return A - B;
    } else if (isMax(a) && isMin(b)) {
        return 1;
    } else if (isMin(a) && isMax(b)) {
        return -1;
    }

    return 1;
}
<commit_msg>sassLint add to sass.js<commit_after>var gulp         = require('gulp');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var postcss      = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var mqpacker     = require('css-mqpacker');
var config       = require('../config');
var sassLint     = require('gulp-sass-lint');

var processors = [
    autoprefixer({
        browsers: ['last 4 versions'],
        cascade: false
    }),
    mqpacker({
        sort: sortMediaQueries
    })
];

gulp.task('sass', function() {
    return gulp
        .src(config.src.sass + '/*.{sass,scss}')
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: config.production ? 'compact' : 'expanded', // nested, expanded, compact, compressed
            precision: 5
        }))
        .on('error', config.errorHandler)
        .pipe(postcss(processors))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(config.dest.css));
});

gulp.task('sass:watch', function() {
    gulp.watch(config.src.sass + '/**/*.{sass,scss}', ['sass']);
});

function isMax(mq) {
    return /max-width/.test(mq);
}

function isMin(mq) {
    return /min-width/.test(mq);
}

function sortMediaQueries(a, b) {
    A = a.replace(/\D/g, '');
    B = b.replace(/\D/g, '');

    if (isMax(a) && isMax(b)) {
        return B - A;
    } else if (isMin(a) && isMin(b)) {
        return A - B;
    } else if (isMax(a) && isMin(b)) {
        return 1;
    } else if (isMin(a) && isMax(b)) {
        return -1;
    }

    return 1;
}

gulp.task('sassLint', function() {

    return gulp.src('src/sass/**/*.s+(a|c)ss')
        .pipe(sassLint())
        .pipe(sassLint.format())
        .pipe(sassLint.failOnError())

});
<|endoftext|>


<commit_before>;( function () {

	function X ( window ) {

		var x = {};

		x.detector = {

			detect: function ( options ) {

				if ( options.type = "default" ) {

					var selector = options.selector;
					var callback = options.callback;
					var element_arr = window.document.querySelectorAll( selector );

					for ( var i = 0; i < element_arr.length; i++ ) {

						if ( element_arr[ 0 ].dataset.detected !== "1" ) {

							element_arr[ 0 ].dataset.detected = "1";
							callback( element_arr[ 0 ] );

						};

					};

					var observer = new MutationObserver( function ( records ) {

						var element_arr = window.document.querySelectorAll( selector );

						if ( element_arr ) {

							for ( var i = 0; i < element_arr.length; i++ ) {

								if ( element_arr[ i ].dataset.detected !== "1" ) {

									element_arr[ i ].dataset.detected = "1";
									callback( element_arr[ i ] );

								};

							};

						};

					});

					observer.observe( window.document, { childList: true, subtree: true } );

				} else if ( options.type = "one_time_promise" ) {

					return new Promise( function ( resolve ) {

						var element = window.document.querySelector( options.selector );

						if ( element ) {

							resolve( element );

						} else {

							var observer = new MutationObserver( function () {

								var element = window.document.querySelector( selector );

								if ( element ) {

									resolve( element );
									observer.disconnect( window.document );

								};

							})

							observer.observe( window.document, { childList: true, subtree: true } );

						};

					});

				};

			},

		};

		x.storage = {

			get: function ( path ) {

				var path_arr = path.split( "." );
				var current_object;

				return new Promise ( function ( resolve ) {

					window.chrome.storage.local.get( null, function ( items ) {

						current_object = items;

						for ( var i = 0; i < path_arr.length; i++ ) {

							if ( typeof current_object[ path_arr[ i ] ] !== undefined ) {

								current_object = current_object[ path_arr[ i ] ];

							} else {

								resolve( undefined );
								break;

							};

						};

						resolve( current_object );

					});

				});

			},

			set: function ( path, value ) {

				var path_arr = path.split( "." );
				var current_object;
				var success;

				return new Promise ( function ( resolve ) {

					window.chrome.storage.local.get( null, function ( items ) {

						current_object = items;

						for ( var i = 0; i < path_arr.length; i++ ) {

							if ( i === path_arr.length - 1 ) {

								current_object[ path_arr[ i ] ] = value;

							} else if ( typeof current_object[ path_arr[ i ] ] !== undefined ) {

								current_object = current_object[ path_arr[ i ] ];

							} else {

								resolve( false );
								break;

							};

						};

						window.chrome.storage.local.set( items, resolve.bind( this, true ) );

					});

				});

			},

		};

		x.hub = {

			send: function () {

			},

			listen: function () {

			},

			send_runtime_message_rq_to_rs: function ( rq ) {

				window.chrome.runtime.sendMessage( rq );

			},

			send_tab_message_rq_to_rs: function ( req, conv ) {

				if ( req.all_tabs_flag ) {

					window.chrome.tabs.query( {}, function ( tab_arr ) {

						tab_arr.forEach( function ( tab ) {

							window.chrome.tabs.sendMessage( tab.id, req );

						});

					});

				} else {

					return new Promise( function ( resolve ) {

						window.chrome.tabs.sendMessage( req.tab_id, req, resolve );

					});

				};

			},

		};

		x.util = {

			text_to_json: function ( text ) {

				try {

					return JSON.parse( text );

				} catch ( e ) {

					return

				};

			},

		};

		x.ajax = {

			fetch: function ( rq, conv ) {

				var headers = new Headers( rq.headers || {} );

				if ( rq.method === "get_json" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()
						.then( function ( text ) {

							return conv( "text", "json", text );

						});

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "get_doc" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()
						.then( function ( text ) {

							return conv( "text", "doc", text );

						});

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "get_blob" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.blob()

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "get_text" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "post_json_get_json" ) {

					headers.append( "Content-Type", "application/json" );

					return window.fetch( rq.url, {

						method: "POST",
						credentials: "include",
						body: JSON.stringify( rq.body ),
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()
						.then( function ( text ) {

							return conv( "text", "json", text );

						});

					})
					.catch( function ( response ) {

						return null;

					});

				};

			},

			http_rq_to_rs: function ( request, conv ) {

				var body;

				if ( request.method === "POST" && request.content_type === "application/x-www-form-urlencoded" ) {

					body = conv( "obj", "form_data", request.body );

				} else if ( request.method === "POST" && request.content_type === "application/json" ) {

					body = JSON.stringify( request.body );

				};

				return window.fetch( request.url, {
					method: request.method,
					credentials: "include",
					headers: new Headers({
						"Content-Type": request.content_type,
						"Accept": request.accept,
					}),
					body: body,
				})
				.then( function ( r ) {

					return r.text()
					.then( function ( text ) {

						return {
							head: {
								error: false,
								code: 0,
								http_req: request,
								status: r.status,
								headers: r.headers,
							},
							body: {
								text: text,
							},
						};

					});

				})
				.catch( function ( response ) {

					return {
						head: {
							error: true,
							code: 1,
							http_req: request,
						},
					};

				});

			},

			obj_to_form_data: function ( obj ) {

				return Object.keys( obj ).map( function ( name ) {

					return encodeURIComponent( name ) + "=" + encodeURIComponent( obj[ name ] );

				}).join( "&" );

			},

			xhr_rq_to_rs: function ( rq, conv ) {

				return new Promise( function ( resolve ) {

					// define event listeners

						function readystatechange_listener () {

							if ( this.readyState === 4 ) {

								if ( this.status === 200 ) {

									resolve({

										error: false,
										response: this.response,

									});

								} else {

									resolve({

										error: true,
										response: this.response,

									});

								};

							};

						};

						function timeout_listener () {

						};

						function load_listener () {

							if ( this.status === 200 ) {

								resolve({

									error: false,
									response: this.response,

								});

							} else {

								resolve({

									error: true,

								});

							}

						};

						function error_listener () {

							resolve({

								error: true,

							});

						};

					// init

						var xhr = new XMLHttpRequest();
						xhr.open( rq.method, rq.url, true );

					// set timeout

						if ( rq.timeout ) {

							xhr.timeout = rq.timeout;

						};

					// set response type

						xhr.responseType = rq.response_type || "text";

					// set headers

						if ( rq.headers ) {

							Object.keys( rq.headers ).forEach( function ( key ) { xhr.setRequestHeader( key, rq.headers[ key ] ) } );

						};

						if ( rq.rq_body_type === "json" ) {

							xhr.setRequestHeader( "Content-Type", "application/json" );

						};

					// register listeners

						xhr.addEventListener( "load", load_listener );
						xhr.addEventListener( "error", error_listener );
						xhr.addEventListener( "timeout", timeout_listener );
						// xhr.addEventListener( "readystatechange", readystatechange_listener );

					// define request body

						if ( rq.rq_body_type === "json" ) {

							var rq_body = JSON.stringify( rq.rq_body );

						} else if ( rq.rq_body_type === "form_data" ) {

							var rq_body = new FormData();

							Object.keys( rq.rq_body ).forEach( function ( key ) {

								rq_body.append( key, rq.rq_body[ key ] );

							});

						} else {

							var rq_body = null;

						};

					// send

						xhr.send( rq_body );

				});

			},

		};

		return x;

	};

	( function ( window ) {

		window.x = new X( window );

	} ( window ) );

} () );<commit_msg>1.0.0<commit_after>// 1.0.0

;( function () {

	function X ( window ) {

		var x = {};

		x.detector = {

			detect: function ( options ) {

				if ( options.type = "default" ) {

					var selector = options.selector;
					var callback = options.callback;
					var element_arr = window.document.querySelectorAll( selector );

					for ( var i = 0; i < element_arr.length; i++ ) {

						if ( element_arr[ 0 ].dataset.detected !== "1" ) {

							element_arr[ 0 ].dataset.detected = "1";
							callback( element_arr[ 0 ] );

						};

					};

					var observer = new MutationObserver( function ( records ) {

						var element_arr = window.document.querySelectorAll( selector );

						if ( element_arr ) {

							for ( var i = 0; i < element_arr.length; i++ ) {

								if ( element_arr[ i ].dataset.detected !== "1" ) {

									element_arr[ i ].dataset.detected = "1";
									callback( element_arr[ i ] );

								};

							};

						};

					});

					observer.observe( window.document, { childList: true, subtree: true } );

				} else if ( options.type = "one_time_promise" ) {

					return new Promise( function ( resolve ) {

						var element = window.document.querySelector( options.selector );

						if ( element ) {

							resolve( element );

						} else {

							var observer = new MutationObserver( function () {

								var element = window.document.querySelector( selector );

								if ( element ) {

									resolve( element );
									observer.disconnect( window.document );

								};

							})

							observer.observe( window.document, { childList: true, subtree: true } );

						};

					});

				};

			},

		};

		x.storage = {

			get: function ( path ) {

				var path_arr = path.split( "." );
				var current_object;

				return new Promise ( function ( resolve ) {

					window.chrome.storage.local.get( null, function ( items ) {

						current_object = items;

						for ( var i = 0; i < path_arr.length; i++ ) {

							if ( typeof current_object[ path_arr[ i ] ] !== undefined ) {

								current_object = current_object[ path_arr[ i ] ];

							} else {

								resolve( undefined );
								break;

							};

						};

						resolve( current_object );

					});

				});

			},

			set: function ( path, value ) {

				var path_arr = path.split( "." );
				var current_object;
				var success;

				return new Promise ( function ( resolve ) {

					window.chrome.storage.local.get( null, function ( items ) {

						current_object = items;

						for ( var i = 0; i < path_arr.length; i++ ) {

							if ( i === path_arr.length - 1 ) {

								current_object[ path_arr[ i ] ] = value;

							} else if ( typeof current_object[ path_arr[ i ] ] !== undefined ) {

								current_object = current_object[ path_arr[ i ] ];

							} else {

								resolve( false );
								break;

							};

						};

						window.chrome.storage.local.set( items, resolve.bind( this, true ) );

					});

				});

			},

		};

		x.hub = {

			send: function () {

			},

			listen: function () {

			},

			send_runtime_message_rq_to_rs: function ( rq ) {

				window.chrome.runtime.sendMessage( rq );

			},

			send_tab_message_rq_to_rs: function ( req, conv ) {

				if ( req.all_tabs_flag ) {

					window.chrome.tabs.query( {}, function ( tab_arr ) {

						tab_arr.forEach( function ( tab ) {

							window.chrome.tabs.sendMessage( tab.id, req );

						});

					});

				} else {

					return new Promise( function ( resolve ) {

						window.chrome.tabs.sendMessage( req.tab_id, req, resolve );

					});

				};

			},

		};

		x.util = {

			text_to_json: function ( text ) {

				try {

					return JSON.parse( text );

				} catch ( e ) {

					return

				};

			},

		};

		x.query = {

			query: function ( rq ) {

				if ( typeof rq.method === "undefined" ) {

					var arr = rq[ 0 ];
					var obj = rq[ 1 ];
					var match_arr = [];

					for ( var i = arr.length; i--; ) {

						var match_flag = true;
						var keys = Object.keys( obj );

						for ( var j = keys.length; j--; ) {

							var key = keys[ j ];

							if ( obj[ key ] !== arr[ i ][ key ] ) {

								match_flag = false;

							};

						};

						if ( match_flag ) {

							match_arr.push( arr[ i ] );

						};

					};

					return match_arr;

				} else if ( rq.method === "remove" ) {

					for ( var i = rq.arr.length; i--; ) {

						var item = rq.arr[ i ];
						var match_bool = true;
						var q_key_arr = Object.keys( rq.q || {} );
						var nq_key_arr = Object.keys( rq.nq || {} );

						for ( var j = q_key_arr.length; j--; ) {

							if ( item[ q_key_arr[ j ] ] !== rq.q[ q_key_arr[ j ] ] ) {

								match_bool = false;

							};

						};

						for ( var j = nq_key_arr.length; j--; ) {

							if ( item[ nq_key_arr[ j ] ] === rq.q[ nq_key_arr[ j ] ] ) {

								match_bool = false;

							};

						};

						if ( match_bool === true ) {

							rq.arr.splice( i, 1 );

						};

					};

				} else if ( rq.method === "find" ) {

					var match_arr = [];

					for ( var i = rq.arr.length; i--; ) {

						var item = rq.arr[ i ];
						var match_bool = true;
						var q_key_arr = Object.keys( rq.q || {} );
						var nq_key_arr = Object.keys( rq.nq || {} );

						for ( var j = q_key_arr.length; j--; ) {

							if ( item[ q_key_arr[ j ] ] !== rq.q[ q_key_arr[ j ] ] ) {

								match_bool = false;

							};

						};

						for ( var j = nq_key_arr.length; j--; ) {

							if ( item[ nq_key_arr[ j ] ] === rq.q[ nq_key_arr[ j ] ] ) {

								match_bool = false;

							};

						};

						if ( match_bool === true ) {

							match_arr.push( rq.arr[ i ] );

						};

					};

					return match_arr;

				};

			},

		},

		x.ajax = {

			fetch: function ( rq, conv ) {

				var headers = new Headers( rq.headers || {} );

				if ( rq.method === "get_json" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()
						.then( function ( text ) {

							return conv( "text", "json", text );

						});

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "get_doc" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()
						.then( function ( text ) {

							return conv( "text", "doc", text );

						});

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "get_blob" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.blob()

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "get_text" ) {

					return window.fetch( rq.url, {

						method: "GET",
						credentials: "include",
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()

					})
					.catch( function ( response ) {

						return null;

					});

				} else if ( rq.method === "post_json_get_json" ) {

					headers.append( "Content-Type", "application/json" );

					return window.fetch( rq.url, {

						method: "POST",
						credentials: "include",
						body: JSON.stringify( rq.body ),
						headers: headers,

					})
					.then( function ( r ) {

						return r.text()
						.then( function ( text ) {

							return conv( "text", "json", text );

						});

					})
					.catch( function ( response ) {

						return null;

					});

				};

			},

			http_rq_to_rs: function ( request, conv ) {

				var body;

				if ( request.method === "POST" && request.content_type === "application/x-www-form-urlencoded" ) {

					body = conv( "obj", "form_data", request.body );

				} else if ( request.method === "POST" && request.content_type === "application/json" ) {

					body = JSON.stringify( request.body );

				};

				return window.fetch( request.url, {
					method: request.method,
					credentials: "include",
					headers: new Headers({
						"Content-Type": request.content_type,
						"Accept": request.accept,
					}),
					body: body,
				})
				.then( function ( r ) {

					return r.text()
					.then( function ( text ) {

						return {
							head: {
								error: false,
								code: 0,
								http_req: request,
								status: r.status,
								headers: r.headers,
							},
							body: {
								text: text,
							},
						};

					});

				})
				.catch( function ( response ) {

					return {
						head: {
							error: true,
							code: 1,
							http_req: request,
						},
					};

				});

			},

			obj_to_form_data: function ( obj ) {

				return Object.keys( obj ).map( function ( name ) {

					return encodeURIComponent( name ) + "=" + encodeURIComponent( obj[ name ] );

				}).join( "&" );

			},

			xhr_rq_to_rs: function ( rq, conv ) {

				return new Promise( function ( resolve ) {

					// define event listeners

						function readystatechange_listener () {

							if ( this.readyState === 4 ) {

								if ( this.status === 200 ) {

									resolve({

										error: false,
										response: this.response,

									});

								} else {

									resolve({

										error: true,
										response: this.response,

									});

								};

							};

						};

						function timeout_listener () {

						};

						function load_listener () {

							if ( this.status === 200 ) {

								resolve({

									error: false,
									response: this.response,

								});

							} else {

								resolve({

									error: true,

								});

							}

						};

						function error_listener () {

							resolve({

								error: true,

							});

						};

					// init

						var xhr = new XMLHttpRequest();
						xhr.open( rq.method, rq.url, true );

					// set timeout

						if ( rq.timeout ) {

							xhr.timeout = rq.timeout;

						};

					// set response type

						xhr.responseType = rq.response_type || "text";

					// set headers

						if ( rq.headers ) {

							Object.keys( rq.headers ).forEach( function ( key ) { xhr.setRequestHeader( key, rq.headers[ key ] ) } );

						};

						if ( rq.rq_body_type === "json" ) {

							xhr.setRequestHeader( "Content-Type", "application/json" );

						};

					// register listeners

						xhr.addEventListener( "load", load_listener );
						xhr.addEventListener( "error", error_listener );
						xhr.addEventListener( "timeout", timeout_listener );
						// xhr.addEventListener( "readystatechange", readystatechange_listener );

					// define request body

						if ( rq.rq_body_type === "json" ) {

							var rq_body = JSON.stringify( rq.rq_body );

						} else if ( rq.rq_body_type === "form_data" ) {

							var rq_body = new FormData();

							Object.keys( rq.rq_body ).forEach( function ( key ) {

								rq_body.append( key, rq.rq_body[ key ] );

							});

						} else {

							var rq_body = null;

						};

					// send

						xhr.send( rq_body );

				});

			},

		};

		x.events = {

			add_listener: function ( event_name, callback ) {

			},

		};

		return x;

	};

	( function ( window ) {

		window.x = new X( window );

	} ( window ) );

} () );<|endoftext|>


<commit_before>'use strict';

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_move(args){
    if(!chess_games[args['id']]){
        return false;
    }

    const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
    const valid_move = chess_validate(args);
    if(valid_move){
        chess_games[args['id']]['board'][args['piece-y']][args['piece-x']] = '';
        chess_games[args['id']]['board'][args['target-y']][args['target-x']] = piece;
        chess_games[args['id']]['player'] = 1 - chess_games[args['id']]['player'];
    }
    return valid_move;
}

// Required args: id
function chess_new(args){
    chess_games[args['id']] = {
      'board': [
        [chess_pieces[1][3], chess_pieces[1][1], chess_pieces[1][2], chess_pieces[1][4], chess_pieces[1][5], chess_pieces[1][2], chess_pieces[1][1], chess_pieces[1][3],],
        [chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0],],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        [chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0],],
        [chess_pieces[0][3], chess_pieces[0][1], chess_pieces[0][2], chess_pieces[0][4], chess_pieces[0][5], chess_pieces[0][2], chess_pieces[0][1], chess_pieces[0][3],],
      ],
      'player': 0,
    };
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_validate(args){
    if(!chess_games[args['id']]
      || args['piece-x'] < 0 || args['piece-x'] > 7
      || args['piece-y'] < 0 || args['piece-y'] > 7
      || args['target-x'] < 0 || args['target-x'] > 7
      || args['target-y'] < 0 || args['target-y'] > 7){
        return false;
    }

    const player = chess_games[args['id']]['player'];
    const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
    if(piece.length === 0 || !chess_pieces[player].includes(piece)){
        return false;
    }

    let valid_move = true;
    switch(piece){
        case chess_pieces[player][0]:
            console.log('pawn');
            break;
        case chess_pieces[player][1]:
            console.log('knight');
            break;
        case chess_pieces[player][2]:
            console.log('bishop');
            break;
        case chess_pieces[player][3]:
            console.log('rook');
            break;
        case chess_pieces[player][4]:
            console.log('queen');
            break;
        case chess_pieces[player][5]:
            console.log('king');
            break;
        default:
            valid_move = false;
    }
    return valid_move;
}

globalThis.chess_games = {};
globalThis.chess_pieces = [
  ['♙', '♘', '♗', '♖', '♕', '♔'],
  ['♟', '♞', '♝', '♜', '♛', '♚'],
];
<commit_msg>added basic king/pawn/rook movement<commit_after>'use strict';

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_move(args){
    if(!chess_games[args['id']]){
        return false;
    }

    const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
    const valid_move = chess_validate(args);
    if(valid_move){
        chess_games[args['id']]['board'][args['piece-y']][args['piece-x']] = '';
        chess_games[args['id']]['board'][args['target-y']][args['target-x']] = piece;
        chess_games[args['id']]['player'] = 1 - chess_games[args['id']]['player'];
    }
    return valid_move;
}

// Required args: id
function chess_new(args){
    chess_games[args['id']] = {
      'board': [
        [chess_pieces[1][3], chess_pieces[1][1], chess_pieces[1][2], chess_pieces[1][4], chess_pieces[1][5], chess_pieces[1][2], chess_pieces[1][1], chess_pieces[1][3],],
        [chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0],],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        [chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0],],
        [chess_pieces[0][3], chess_pieces[0][1], chess_pieces[0][2], chess_pieces[0][4], chess_pieces[0][5], chess_pieces[0][2], chess_pieces[0][1], chess_pieces[0][3],],
      ],
      'player': 0,
    };
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_validate(args){
    if(!chess_games[args['id']]
      || args['piece-x'] < 0 || args['piece-x'] > 7
      || args['piece-y'] < 0 || args['piece-y'] > 7
      || args['target-x'] < 0 || args['target-x'] > 7
      || args['target-y'] < 0 || args['target-y'] > 7){
        return false;
    }

    const player = chess_games[args['id']]['player'];
    const piece = chess_games[args['id']]['board'][args['piece-y']][args['piece-x']];
    if(piece.length === 0 || !chess_pieces[player].includes(piece)){
        return false;
    }

    const target_piece = chess_games[args['id']]['board'][args['target-y']][args['target-x']]
    let valid_move = true;
    switch(piece){
        // pawn
        case chess_pieces[player][0]: {
            const direction = player === 0 ? -1 : 1;

            if(args['target-x'] !== args['piece-x']){

            }else if(target_piece.length === 0){
                if(args['target-y'] !== args['piece-y'] + direction){
                    valid_move = false;
                }

            }else{
                valid_move = false;
            }

            break;
        }

        // knight
        case chess_pieces[player][1]: {
            break;
        }

        // bishop
        case chess_pieces[player][2]: {
            break;
        }

        // rook
        case chess_pieces[player][3]: {
            if(args['target-x'] !== args['piece-x'] && args['target-y'] !== args['piece-y']){
                valid_move = false;
            }

            break;
        }

        // queen
        case chess_pieces[player][4]: {
            break;
        }

        // king
        case chess_pieces[player][5]: {
            const movement_x = Math.abs(args['piece-x'] - args['target-x']);
            const movement_y = Math.abs(args['piece-y'] - args['target-y'])
            if(movement_x > 1 || movement_y > 1 || chess_pieces[player].includes(target_piece)){
                valid_move = false;
            }

            break;
        }

        default:
            valid_move = false;
    }
    return valid_move;
}

globalThis.chess_games = {};
globalThis.chess_pieces = [
  ['♙', '♘', '♗', '♖', '♕', '♔'],
  ['♟', '♞', '♝', '♜', '♛', '♚'],
];
<|endoftext|>


<commit_before>var postal = require('../');
var sets = require('simplesets');
var assert = require('assert');

describe('expand', function() {
    var expansions;
    var expansions2;
    describe('expand_address', function() {
        it('should correctly expand a US address', function() {
            expansions = new sets.Set(postal.expand.expand_address('781 Franklin Ave Crown Hts Brooklyn NY'));
            assert(expansions.has('781 franklin avenue crown heights brooklyn new york'));
        });
        it('should correctly dedupe equivalent addresses', function() {
            expansions = new sets.Set(postal.expand.expand_address('30 West Twenty-sixth Street Floor Number 7', {languages: ['en']}));
            expansions2 = new sets.Set(postal.expand.expand_address('Thirty W 26th St Fl #7', {languages: ['en']}));
            assert(expansions.intersection(expansions2).size() > 0);
        });
        it('should handle non-ASCII addresses correctly from Node', function() {
            expansions = new sets.Set(postal.expand.expand_address('Friedrichstraße 128, Berlin, Germany'));
            console.log(expansions);
            assert(expansions.has('friedrich straße 128 berlin germany'));
        });

    })
})

describe('parser', function() {
    var parsed = [];

    function has_components(parsed, components) {
        var expected = Object.keys(components).length;
        var got = 0;

        for (var i = 0; i < parsed.length; i++) {
            var el = parsed[i];
            if (components[el.component] === el.value) {
                got++;
            }
        }

        return expected === got;
    }

    describe('parse_address', function() {
        it('should parse a US address', function() {
            parsed = postal.parser.parse_address('781 Franklin Ave Crown Heights Brooklyn NYC NY 11216 USA');
            assert(has_components(parsed, {
                house_number: '781',
                road: 'franklin ave',
                suburb: 'crown heights',
                city_district: 'brooklyn',
                city: 'nyc',
                state: 'ny',
                postcode: '11216',
                country: 'usa'
            }));
        });
        it('should parse a venue and state', function() {
            parsed = postal.parser.parse_address('whole foods ny');
            assert(has_components(parsed, {
                house: 'whole foods',
                state: 'ny'
            }));
        });
        it('should parse house/apt style house_number', function() {
            parsed = postal.parser.parse_address('1917/2 Pike Drive');
            assert(has_components(parsed, {
                house_number: '1917 / 2',
                road: 'pike drive'
            }));
        });
        it('should parse different comma styles correctly', function() {
            parsed = postal.parser.parse_address('3437 warwickshire rd,pa');
            assert(has_components(parsed, {
                house_number: '3437',
                road: 'warwickshire rd',
                state: 'pa'
            }));
            parsed = postal.parser.parse_address('3437 warwickshire rd, pa');
            assert(has_components(parsed, {
                house_number: '3437',
                road: 'warwickshire rd',
                state: 'pa'
            }));
            parsed = postal.parser.parse_address('3437 warwickshire rd pa');
            assert(has_components(parsed, {
                house_number: '3437',
                road: 'warwickshire rd',
                state: 'pa'
            }));

        });

    })
})
<commit_msg>[fix] test using the new libpostal expansions<commit_after>var postal = require('../');
var sets = require('simplesets');
var assert = require('assert');

describe('expand', function() {
    var expansions;
    var expansions2;
    describe('expand_address', function() {
        it('should correctly expand a US address', function() {
            expansions = new sets.Set(postal.expand.expand_address('781 Franklin Ave Crown Hts Brooklyn NY'));
            assert(expansions.has('781 franklin avenue crown heights brooklyn new york'));
        });
        it('should correctly dedupe equivalent addresses', function() {
            expansions = new sets.Set(postal.expand.expand_address('30 West Twenty-sixth Street Floor Number 7', {languages: ['en']}));
            expansions2 = new sets.Set(postal.expand.expand_address('Thirty W 26th St Fl #7', {languages: ['en']}));
            assert(expansions.intersection(expansions2).size() > 0);
        });
        it('should handle non-ASCII addresses correctly from Node', function() {
            expansions = new sets.Set(postal.expand.expand_address('Friedrichstraße 128, Berlin, Germany'));
            console.log(expansions);
            assert(expansions.has('friedrich strasse 128 berlin germany'));
        });

    })
})

describe('parser', function() {
    var parsed = [];

    function has_components(parsed, components) {
        var expected = Object.keys(components).length;
        var got = 0;

        for (var i = 0; i < parsed.length; i++) {
            var el = parsed[i];
            if (components[el.component] === el.value) {
                got++;
            }
        }

        return expected === got;
    }

    describe('parse_address', function() {
        it('should parse a US address', function() {
            parsed = postal.parser.parse_address('781 Franklin Ave Crown Heights Brooklyn NYC NY 11216 USA');
            assert(has_components(parsed, {
                house_number: '781',
                road: 'franklin ave',
                suburb: 'crown heights',
                city_district: 'brooklyn',
                city: 'nyc',
                state: 'ny',
                postcode: '11216',
                country: 'usa'
            }));
        });
        it('should parse a venue and state', function() {
            parsed = postal.parser.parse_address('whole foods ny');
            assert(has_components(parsed, {
                house: 'whole foods',
                state: 'ny'
            }));
        });
        it('should parse house/apt style house_number', function() {
            parsed = postal.parser.parse_address('1917/2 Pike Drive');
            assert(has_components(parsed, {
                house_number: '1917 / 2',
                road: 'pike drive'
            }));
        });
        it('should parse different comma styles correctly', function() {
            parsed = postal.parser.parse_address('3437 warwickshire rd,pa');
            assert(has_components(parsed, {
                house_number: '3437',
                road: 'warwickshire rd',
                state: 'pa'
            }));
            parsed = postal.parser.parse_address('3437 warwickshire rd, pa');
            assert(has_components(parsed, {
                house_number: '3437',
                road: 'warwickshire rd',
                state: 'pa'
            }));
            parsed = postal.parser.parse_address('3437 warwickshire rd pa');
            assert(has_components(parsed, {
                house_number: '3437',
                road: 'warwickshire rd',
                state: 'pa'
            }));

        });

    })
})
<|endoftext|>


<commit_before>/* jshint -W079 */
var
  gulp = require('gulp'),
  gulpBoilerplate = require('es6-gulp-boilerplate'),
  server = require('./app');

/**
 * Here you can configure the gulp build system with custom folders, different
 * build modules, etc.
 * ------------------------------------------------------------------------- */
gulpBoilerplate.config(gulp, {
  modules: {
    // module to use to preprocess your stylesheets. default: less
    // possible values: less, sass, sassCompass, stylus, myth.
    styles: 'less'
  },
  paths: {
    src: {
      // folder home of your source files (less, js, etc). default: src/
      base: '',

      // styles sources folder. default: styles/
      styles: '',

      // scripts folder. default: scripts/
      scripts: '',

      // templates and partials folder: default: ../views/, partials/
      templates: '',
      partials: ''
    },

    out: {
      // folder destination for built bundles. default: public/
      base: '',

      // production ready styles folder. default: css/
      styles: '',

      // production ready scripts folder. default: js/
      scripts: ''
    }
  },
  // express web server to use while developing.
  // port default: 3000
  // liveReloadPort default: 35729
  server: server,
  port: null,
  liveReloadPort: null
});

/**
 * Here you can hook extra tasks as dependency for predefined tasks (insert
 * a leading '!' to remove dependencies) or add additional sources (insert a
 * leading '!' to the path to delcare sources which should be ignored).
 * ------------------------------------------------------------------------- */
gulpBoilerplate.setupTasks({
  'bundle-js': {
    deps: [],
    src: []
  },
  'bundle-js:dev': {
    deps: [],
    src: []
  },
  'lint': {
    deps: [],
    src: []
  }
});

/**
 * Add extra gulp tasks below
 * ------------------------------------------------------------------------- */
var $ = gulpBoilerplate.getPlugins();

// Check the Meesayen/es6-boilerplate repository on github for a sample usage.

/**
 * Here you plug additional watchers to gulp.
 * ------------------------------------------------------------------------- */
gulpBoilerplate.setupWatchers(function(gulp) {
  // Add wathers here.
});

/**
 * Here you can inject extra tasks into the main tasks. Those will be appendend
 * and concurrently run with other tasks.
 * ------------------------------------------------------------------------- */
gulpBoilerplate.setupMain({
  'development': [
    'publish-helpers'
  ],
  'test': [],
  'production': [
    'publish-helpers'
  ]
});
<commit_msg>Cleaned up.<commit_after>/* jshint -W079 */
var
  gulp = require('gulp'),
  gulpBoilerplate = require('es6-gulp-boilerplate'),
  server = require('./app');

/**
 * Here you can configure the gulp build system with custom folders, different
 * build modules, etc.
 * ------------------------------------------------------------------------- */
gulpBoilerplate.config(gulp, {
  modules: {
    // module to use to preprocess your stylesheets. default: less
    // possible values: less, sass, sassCompass, stylus, myth.
    styles: 'less'
  },
  paths: {
    src: {
      // folder home of your source files (less, js, etc). default: src/
      base: '',

      // styles sources folder. default: styles/
      styles: '',

      // scripts folder. default: scripts/
      scripts: '',

      // templates and partials folder: default: ../views/, partials/
      templates: '',
      partials: ''
    },

    out: {
      // folder destination for built bundles. default: public/
      base: '',

      // production ready styles folder. default: css/
      styles: '',

      // production ready scripts folder. default: js/
      scripts: ''
    }
  },
  // express web server to use while developing.
  // port default: 3000
  // liveReloadPort default: 35729
  server: server,
  port: null,
  liveReloadPort: null
});

/**
 * Here you can hook extra tasks as dependency for predefined tasks (insert
 * a leading '!' to remove dependencies) or add additional sources (insert a
 * leading '!' to the path to delcare sources which should be ignored).
 * ------------------------------------------------------------------------- */
gulpBoilerplate.setupTasks({
  'bundle-js': {
    deps: [],
    src: []
  },
  'bundle-js:dev': {
    deps: [],
    src: []
  },
  'lint': {
    deps: [],
    src: []
  }
});

/**
 * Add extra gulp tasks below
 * ------------------------------------------------------------------------- */
var $ = gulpBoilerplate.getPlugins();

// Check the Meesayen/es6-boilerplate repository on github for a sample usage.

/**
 * Here you plug additional watchers to gulp.
 * ------------------------------------------------------------------------- */
gulpBoilerplate.setupWatchers(function(gulp) {
  // Add wathers here.
});

/**
 * Here you can inject extra tasks into the main tasks. Those will be appendend
 * and concurrently run with other tasks.
 * ------------------------------------------------------------------------- */
gulpBoilerplate.setupMain({
  'development': [],
  'test': [],
  'production': []
});
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");

module.exports = React.createClass({
    displayName: 'MemberAvatar',

    propTypes: {
        member: React.PropTypes.object.isRequired,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string
    },

    getDefaultProps: function() {
        return {
            width: 40,
            height: 40,
            resizeMethod: 'crop'
        }
    },

    getInitialState: function() {
        return this._getState(this.props);
    },

    componentWillReceiveProps: function(nextProps) {
        this.setState(this._getState(nextProps));
    },

    _getState: function(props) {
        return {
            name: props.member.name,
            title: props.member.userId,
            imageUrl: Avatar.avatarUrlForMember(props.member,
                                         props.width,
                                         props.height,
                                         props.resizeMethod)
        }
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {member, ...otherProps} = this.props;

        return (
            <BaseAvatar {...otherProps} name={this.state.name} title={this.state.title}
                idName={member.userId} url={this.state.imageUrl} />
        );
    }
});
<commit_msg>add debugging to MemberAvatar to try to kick jenkins...<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");

module.exports = React.createClass({
    displayName: 'MemberAvatar',

    propTypes: {
        member: React.PropTypes.object.isRequired,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string
    },

    getDefaultProps: function() {
        return {
            width: 40,
            height: 40,
            resizeMethod: 'crop'
        }
    },

    getInitialState: function() {
        return this._getState(this.props);
    },

    componentWillReceiveProps: function(nextProps) {
        this.setState(this._getState(nextProps));
    },

    _getState: function(props) {
        if (!props.member) {
            console.error("MemberAvatar called somehow with null member");
        }
        return {
            name: props.member.name,
            title: props.member.userId,
            imageUrl: Avatar.avatarUrlForMember(props.member,
                                         props.width,
                                         props.height,
                                         props.resizeMethod)
        }
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {member, ...otherProps} = this.props;

        return (
            <BaseAvatar {...otherProps} name={this.state.name} title={this.state.title}
                idName={member.userId} url={this.state.imageUrl} />
        );
    }
});
<|endoftext|>


<commit_before>import express from 'express'
import passport from 'passport'
import {logger} from '../utils/logger'

export const authentication_router = express.Router()
authentication_router
  .get('/authentication/vk', passport.authenticate('vkontakte'))
  .get('/authentication/vk/callback', passport.authenticate('vkontakte', {
    successRedirect: '/',
    failureRedirect: '/login',
  }))
  .get('/logout', (request, response) => {
    logger.info(`user ${request.user.id} logged out of the app`)
    request.logout()

    response.redirect('/login')
  })
<commit_msg>Correct the authentication router<commit_after>import express from 'express'
import passport from 'passport'
import {logger} from '../utils/logger'

export const authentication_router = express.Router()
authentication_router
  .get('/authentication/vk', passport.authenticate('vkontakte'))
  .get('/authentication/vk/callback', passport.authenticate('vkontakte', {
    successRedirect: '/',
    failureRedirect: '/',
  }))
  .get('/logout', (request, response) => {
    logger.info(`user ${request.user.id} logged out of the app`)
    request.logout()

    response.redirect('/')
  })
<|endoftext|>