<commit_before>var task = function (gulp, config) {
    'use strict';

    // Registers gulp task
    gulp.task('shared-libs', ['views', 'revParse'], function () {
      var gulpif = require('gulp-if');
      var gutil = require('gulp-util');
      var sourcemaps = require('gulp-sourcemaps');
      var source = require('vinyl-source-stream');
      var buffer = require('vinyl-buffer');
      var browserify = require('browserify');
      var uglify = require('gulp-uglify');
      var errorHandler = require('npdc-gulp/util/errorHandler')({plugin: 'browserify', verbose: true});
      var resolutions = require('browserify-resolutions');
      var rename = require('gulp-rename');

      var app = config.pkg.main;
      var bundle;

      var bundler = browserify({
          // Our app main
          entries: [app],
          // Enable source maps
          debug: true
      }).plugin(resolutions, ['angular']);

      bundler.on('log', gutil.log);

      var templateCache = '/tmp/npdc-gulp/' + config.name + '/templates.js';
      gutil.log("templateCache", templateCache);
      bundler.add(templateCache);

      bundler.require([{file: './' + app, expose: 'npdc-common'}, 'angular']);

      bundle = function (ids) {
          var bundleName = config.pkgname + '-' + config.version().split('.')[0] + '.js';
          gutil.log('Bundling', ids instanceof Array ? ids : '');

          // Browseriy
          return bundler.bundle()
            // log errors if they happen
            .on('error', errorHandler)
            .pipe(source(bundleName))
            .pipe(buffer())
            .pipe(sourcemaps.init({loadMaps: true}))
            .pipe(gulpif(global.isProd, uglify({ compress: { drop_console: true } })))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(config.dist.sharedAssets))
            .pipe(rename(config.pkgname + '-' + global.ref + '-latest.js'))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(config.dist.sharedAssets));
      };

      return bundle();
    });
};

module.exports = task;
<commit_msg>Build patch, minor and major version of shared library<commit_after>var task = function (gulp, config) {
    'use strict';

    // Registers gulp task
    gulp.task('shared-libs', ['views', 'revParse'], function () {
      var gulpif = require('gulp-if');
      var gutil = require('gulp-util');
      var sourcemaps = require('gulp-sourcemaps');
      var source = require('vinyl-source-stream');
      var buffer = require('vinyl-buffer');
      var browserify = require('browserify');
      var uglify = require('gulp-uglify');
      var errorHandler = require('npdc-gulp/util/errorHandler')({plugin: 'browserify', verbose: true});
      var resolutions = require('browserify-resolutions');
      var rename = require('gulp-rename');

      var app = config.pkg.main;
      var bundle;

      var bundler = browserify({
          // Our app main
          entries: [app],
          // Enable source maps
          debug: true
      }).plugin(resolutions, ['angular']);

      bundler.on('log', gutil.log);

      var templateCache = '/tmp/npdc-gulp/' + config.name + '/templates.js';
      gutil.log("templateCache", templateCache);
      bundler.add(templateCache);

      bundler.require([{file: './' + app, expose: 'npdc-common'}, 'angular']);

      var fullVersion = function () {
        return config.pkgname + '-' + config.version() + '.js';
      }

      var minorVersion = function () {
        return config.pkgname + '-' + config.version().split('.').slice(0,2).join('.') + '.js';
      }

      var majorVersion = function () {
        return config.pkgname + '-' + config.version().split('.')[0] + '.js';
      }

      bundle = function (ids) {
          var bundleName = fullVersion();
          gutil.log('Bundling', ids instanceof Array ? ids : '');

          // Browseriy
          return bundler.bundle()
            // log errors if they happen
            .on('error', errorHandler)
            .pipe(source(bundleName))
            .pipe(buffer())
            .pipe(sourcemaps.init({loadMaps: true}))
            .pipe(gulpif(global.isProd, uglify({ compress: { drop_console: true } })))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(config.dist.sharedAssets)) // FULL VERSION
            .pipe(rename(minorVersion()))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(config.dist.sharedAssets))
            .pipe(rename(majorVersion()))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(config.dist.sharedAssets))
            .pipe(rename(config.pkgname + '-' + global.ref + '-latest.js'))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(config.dist.sharedAssets));
      };

      return bundle();
    });
};

module.exports = task;
<|endoftext|>


<commit_before>/**
 * Created by Kane on 15/8/2.
 */
var path = require('path');
var request = require('supertest');
var rewire = require('rewire');
var express = require('express');
var bodyParser = require('body-parser');

var push = rewire('../controller/push');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

require('../db');

describe('contoller/push.js', function() {

  describe('module.exports()', function() {
    app.post('/alpha', push);

    var _update_repo = push.__get__('update_repo');

    afterEach(function() {
      push.__set__('update_repo', _update_repo);
    });

    var push_data = {
      ref: 'refs/heads/master',
      commits: [{
        id: '5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb',
        message: 'hi',
        url: 'http://localhost:3000/unknwon/macaron/commit/5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb',
        author: {
          "name": "Unknwon",
          "email": "joe2010xtmf@163.com",
          "username": "Unknwon"
        }
      }],
      "repository": {
        "id": 1,
        "name": "macaron",
        "url": "http://localhost:3000/unknwon/macaron",
        "description": "描述",
        "website": "http://guluabc.com",
        "watchers": 1,
        "owner": {
          "name": "k",
          "email": "k@163.com",
          "username": "K"
        },
        "private": false
      },
      "pusher": {
        "name": "Unknwon",
        "email": "joe2010xtmf@163.com",
        "username": "unknwon"
      },
      "before": "f22f45d79a2ff050f0250a7df41f4944e6591853",
      "after": "5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb",
      "compare_url": "http://localhost:3000/unknwon/macaron/compare/f22f45d79a2ff050f0250a7df41f4944e6591853...5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb"
    };

    it('should create repo & deployment when push event trigger with new repo', function(done) {
      request(app)
        .post('/alpha')
        .set('Content-Type', 'application/json')
        .send(JSON.stringify(push_data))
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .expect(200, {
          msg: 'Push 处理成功'
        }, done);
    });

    it('should throw error when update repo failed', function(done) {
      var err = new Error('update_repo error');
      var update_repo = function() {
        throw err;
      };

      push.__set__('update_repo', update_repo);

      request(app)
        .post('/alpha')
        .set('Content-Type', 'application/json')
        .send(JSON.stringify(push_data))
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .expect(500, {
          msg: 'Push 事件处理失败:' + err.message
        }, done);
    });
  });
});<commit_msg>push test<commit_after>/**
 * Created by Kane on 15/8/2.
 */
var path = require('path');
var request = require('supertest');
var rewire = require('rewire');
var express = require('express');
var bodyParser = require('body-parser');

var push = rewire('../controller/push');
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

require('../db');

describe('contoller/push.js', function() {
  describe('module.exports()', function() {
    app.post('/alpha', push);

    var push_data = {
      ref: 'refs/heads/master',
      commits: [{
        id: '5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb',
        message: 'hi',
        url: 'http://localhost:3000/unknwon/macaron/commit/5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb',
        author: {
          "name": "Unknwon",
          "email": "joe2010xtmf@163.com",
          "username": "Unknwon"
        }
      }],
      "repository": {
        "id": 1,
        "name": "macaron",
        "url": "http://localhost:3000/unknwon/macaron",
        "description": "描述",
        "website": "http://guluabc.com",
        "watchers": 1,
        "owner": {
          "name": "k",
          "email": "k@163.com",
          "username": "K"
        },
        "private": false
      },
      "pusher": {
        "name": "Unknwon",
        "email": "joe2010xtmf@163.com",
        "username": "unknwon"
      },
      "before": "f22f45d79a2ff050f0250a7df41f4944e6591853",
      "after": "5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb",
      "compare_url": "http://localhost:3000/unknwon/macaron/compare/f22f45d79a2ff050f0250a7df41f4944e6591853...5f69e7cedd45fcce5ea8f3116e9e20f15e90dafb"
    };

    function trigger_push() {
      return request(app)
        .post('/alpha')
        .set('Content-Type', 'application/json')
        .send(JSON.stringify(push_data))
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/);
    }

    function throw_err(err) {
      return function() {
        throw err;
      }
    }

    var _update_repo = push.__get__('update_repo');
    var _build_deploy_data = push.__get__('build_deploy_data');
    var _update_deployment = push.__get__('update_deployment');

    afterEach(function() {
      push.__set__('update_repo', _update_repo);
      push.__set__('build_deploy_data', _build_deploy_data);
      push.__set__('update_deployment', _update_deployment);
    });

    it('should create repo & deployment when push event trigger with new repo', function(done) {
      trigger_push()
        .expect(200, {
          msg: 'Push 处理成功'
        }, done);
    });

    it('should throw error when update repo failed', function(done) {
      var err = new Error('update_repo error');
      push.__set__('update_repo', throw_err(err));

      trigger_push()
        .expect(500, {
          msg: 'Push 事件处理失败:' + err.message
        }, done);
    });

    it('should throw error when build_deploy_data failed', function(done) {
      var err = new Error('build_deploy_data error');
      push.__set__('build_deploy_data', throw_err(err));

      trigger_push()
        .expect(500, {
          msg: 'Push 事件处理失败:' + err.message
        }, done);
    });

    it('should throw error when update_deployment failed', function(done) {
      var err = new Error('update_deployment error');
      push.__set__('update_deployment', throw_err(err));

      trigger_push()
        .expect(500, {
          msg: 'Push 事件处理失败:' + err.message
        }, done);
    });
  });
});<|endoftext|>


<commit_before>/* global describe, it*/
/* jslint node: true, esnext: true */

"use strict";

const chai = require('chai');
chai.use(require("chai-as-promised"));
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();
const request = require('supertest');
const kronos = require('../lib/manager.js');

let testPort = 12345;

describe('service manager REST', function () {
  let url;

  const flowDecl = {
    "flow1": {
      "steps": {
        "s1": {
          "type": "kronos-copy",
          "config": {
            "key1": "value1"
          },
          "endpoints": {
            "in": "stdin",
            "out": "stdout"
          }
        }
      }
    }
  };

  function shutdownManager (manager,done) {
    return function() {
      manager.shutdown().then(function () {
        done();
      });
    };
  }

  function initManager() {
    return kronos.manager({
      flows: flowDecl,
      port: testPort
    });
  }

  describe('health', function () {
    url = '/health';
    it(`GET ${url}`, function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get(url)
          //.expect('Content-Type', /json/)
          .expect(200, shutdownManager(manager,done));
      });
    });
  });

  describe('state', function () {
    url = '/state';
    it(`GET ${url}`, function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get(url)
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200, shutdownManager(manager,done));
      });
    });
  });

  describe('flows', function () {
    url = '/flows';
    it(`GET ${url}`, function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get(url)
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(function(res) {
            const flow = JSON.parse(res.text);
            //expect(flow.name === 'xflow1');
            console.log(`RES: ${flow.name}`);
            if (flow.name !== 'flow1') throw new Error("flow flow1 missing");
            return undefined;
          })
          .expect(200, shutdownManager(manager,done));
      });
    });
    url = '/flows/flow1';
    it(`GET ${url}`, function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get(url)
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200, shutdownManager(manager,done));
      });
    });
  });
});
<commit_msg>test: test assertions are now beeing considered<commit_after>/* global describe, it*/
/* jslint node: true, esnext: true */

"use strict";

const chai = require('chai');
chai.use(require("chai-as-promised"));
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();
const request = require('supertest');
const kronos = require('../lib/manager.js');

let testPort = 12345;

describe('service manager REST', function () {
  const flowDecl = {
    "flow1": {
      "steps": {
        "s1": {
          "type": "kronos-copy",
          "config": {
            "key1": "value1"
          },
          "endpoints": {
            "in": "stdin",
            "out": "stdout"
          }
        }
      }
    }
  };

  function shutdownManager (manager,done) {
    return function(error,result) {
      manager.shutdown().then(function () {
        if(error) { return done(error); }
        else done();
      });
    };
  }

  function initManager() {
    return kronos.manager({
      flows: flowDecl,
      port: testPort
    });
  }

  describe('health', function () {
    it('GET /health', function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get('/health')
          .expect(200)
          .expect(function(res) {
            if (res.text !== 'OK') throw Error("not OK");
          })
          .end(shutdownManager(manager,done));
      });
    });
  });

  describe('state', function () {
    it('GET /state', function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get('/state')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .expect(function(res) {
            const response = JSON.parse(res.text);
            if (!response.uptime > 0) throw Error("uptime > 0 ?");
          })
          .end(shutdownManager(manager,done));
      });
    });
  });

  describe('flows', function () {
    it('GET /flows', function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get('/flows')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(function(res) {
            const response = JSON.parse(res.text);
            //console.log(`RES: ${JSON.stringify(response)}`);
            if (response[0].name !== 'flow1') throw Error("flow flow1 missing");
          })
          .expect(200)
          .end(shutdownManager(manager,done));
      });
    });
    it('GET /flows/flow1', function (done) {
      initManager().then(function (manager) {
        request(manager.app.listen())
          .get('/flows/flow1')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .expect(function(res) {
            const response = JSON.parse(res.text);
            if (response.name !== 'flow1') throw Error("flow flow1 missing");
          })
          .end(shutdownManager(manager,done));
      });
    });
  });
});
<|endoftext|>


<commit_before>module.exports = {
  // regex or string; artist/song get split around this match (default='-')
  delimiter: '-',
  // bool; whether artist is on left side of delimiter (default=true)
  artistFirst: true,
  // string; override Artist for songs in this file's scope (default='')
  artist: '',

  // each stage is configured with regexes and/or strings and
  // simply removes matches by default (repl=''); use an array
  // to pass a replacement param/string, e.g. [find, repl]
  replacements: {
    // applied to input string before split to Artist/Title
    preSplit: [
      // at least 2 word chars followed by at least 3 digits
      /\D{2,}[^\s]\d{3,}/i,
      // track numbers
      /^[\d\-.\s]+/,
      // remove text between (), [], or {}
      /[([{].*[)\]}]/ig,
    ],
    // applied to both Artist and Title after split
    postSplit: [
      // correct for "..., The"
      [/(.*)(, The)$/i, 'The $1'],
    ],
    // applied to Artist after split
    artist: [
      // Last, First [Middle] -> First [Middle] Last
      [/^(\w+?), ?(\w* ?\w*.?)$/ig, '$2 $1'],
    ],
    // applied to Title after split
    title: [
    ],
  }
}
<commit_msg>Tweak filename parser regex<commit_after>module.exports = {
  // regex or string; artist/song get split around this match (default='-')
  delimiter: '-',
  // bool; whether artist is on left side of delimiter (default=true)
  artistFirst: true,
  // string; override Artist for songs in this file's scope (default='')
  artist: '',

  // each stage is configured with regexes and/or strings and
  // simply removes matches by default (repl=''); use an array
  // to pass a replacement param/string, e.g. [find, repl]
  replacements: {
    // applied to input string before split to Artist/Title
    preSplit: [
      // at least 2 non-digits followed by at least 3 digits
      /\D{2,}\d{3,}/i,
      // track numbers
      /^[\d\-.\s]+/,
      // remove text between (), [], or {}
      /[([{].*[)\]}]/ig,
    ],
    // applied to both Artist and Title after split
    postSplit: [
      // correct for "..., The"
      [/(.*)(, The)$/i, 'The $1'],
    ],
    // applied to Artist after split
    artist: [
      // Last, First [Middle] -> First [Middle] Last
      [/^(\w+?), ?(\w* ?\w*.?)$/ig, '$2 $1'],
    ],
    // applied to Title after split
    title: [
    ],
  }
}
<|endoftext|>


<commit_before>var sinon = require('sinon'),
    expect = require('chai').expect,
    server = require('../index'),
    util   = require('util'),
    path = require("path"),
    request = require('request');

server.init({
  port: 8888,
  tplDir: path.join(__dirname, '../templates')
})
server.start();

describe("create_object test", function () {

  it('simple test', function() {
    var obj = {};
    server.create_object(obj, ['a', 'b']);
    expect( obj ).to.have.deep.property('a');
  });

  it('complicated test', function() {
    var obj = {};
    server.create_object(obj, ['a','b','c','d'], 1);
    expect(obj).to.have.deep.property('a.b.c.d');
  });

  it('able to work with duplicate keys', function() {
    var obj = {b:{b:{b:'c'}}};
    server.create_object(obj, ['a', 'b']);
    server.create_object(obj, ['b', 'a']);
    expect(obj).to.have.deep.property('a.b');
    expect(obj).to.have.deep.property('b.b.b', 'c');
    expect(obj).to.have.deep.property('b.a');
  });

  it('very simple', function() {
    var obj = {};
    server.create_object(obj, ['a']);
    expect(obj).to.have.deep.property('a');
  });

});

describe("simple URL GET", function () {
  var testurl = "http://localhost:8888/test1";

  it("responds to ping", function(done) {
    request(testurl, function(error, response, body) {
      expect(response.statusCode).to.eq(200);
      expect(body).to.eq('{"a":{"b":"123"}}');
      done();
    });
  });
});
<commit_msg>update tests<commit_after>var sinon = require('sinon'),
    expect = require('chai').expect,
    server = require('../index'),
    util   = require('util'),
    path = require("path"),
    request = require('request');

server.init({
  port: 8888,
  tplDir: path.join(__dirname, '../templates')
})
var s = server.start();

describe("create_object test", function () {

  it('simple test', function() {
    var obj = {};
    server.create_object(obj, ['a', 'b']);
    expect( obj ).to.have.deep.property('a');
  });

  it('complicated test', function() {
    var obj = {};
    server.create_object(obj, ['a','b','c','d'], 1);
    expect(obj).to.have.deep.property('a.b.c.d');
  });

  it('able to work with duplicate keys', function() {
    var obj = {b:{b:{b:'c'}}};
    server.create_object(obj, ['a', 'b']);
    server.create_object(obj, ['b', 'a']);
    expect(obj).to.have.deep.property('a.b');
    expect(obj).to.have.deep.property('b.b.b', 'c');
    expect(obj).to.have.deep.property('b.a');
  });

  it('very simple', function() {
    var obj = {};
    server.create_object(obj, ['a']);
    expect(obj).to.have.deep.property('a');
  });

});

describe("simple URL GET", function () {
  var testurl = "http://localhost:8888/test1";

  it("responds to ping", function(done) {
    request(testurl, function(error, response, body) {
      expect(response.statusCode).to.eq(200);
      expect(body).to.eq('{"a":{"b":"123"}}');
      done();
    });
  });
});

after(function(){
  server.closeAll();
});
<|endoftext|>


<commit_before>// Retrive data for all steps of all files
// (map db data into meta objects for our needs)

'use strict';

var aFrom                         = require('es5-ext/array/from')
  , forEach                       = require('es5-ext/object/for-each')
  , capitalize                    = require('es5-ext/string/#/capitalize')
  , includes                      = require('es5-ext/string/#/contains')
  , Set                           = require('es6-set')
  , Map                           = require('es6-map')
  , deferred                      = require('deferred')
  , memoize                       = require('memoizee')
  , unserializeValue              = require('dbjs/_setup/unserialize/value')
  , resolveKeyPath                = require('dbjs/_setup/utils/resolve-key-path')
  , debugLoad                     = require('debug-ext')('load', 6)
  , humanize                      = require('debug-ext').humanize
  , resolveProcessingStepFullPath = require('../../utils/resolve-processing-step-full-path')
  , toDateInTz                    = require('../../utils/to-date-in-time-zone')
  , timeZone                      = require('../../db').timeZone;

var re = new RegExp('^processingSteps\\/map\\/([a-zA-Z0-9]+' +
	'(?:\\/steps\\/map\\/[a-zA-Z0-9]+)*)\\/([a-z0-9A-Z\\/]+)$');

module.exports = exports = memoize(function (driver, processingStepsMeta) {
	var storageStepsMap = new Map(), stepShortPathMap = new Map()
	  , serviceFullShortNameMap = new Map()
	  , startTime = Date.now();

	var result = { steps: Object.create(null), businessProcesses: Object.create(null) };

	forEach(processingStepsMeta, function (meta, stepShortPath) {
		var stepPath = resolveProcessingStepFullPath(stepShortPath);
		stepShortPathMap.set(stepPath, stepShortPath);
		meta._services.forEach(function (serviceName) {
			var serviceFullName = 'businessProcess' + capitalize.call(serviceName)
			  , storage = driver.getStorage(serviceFullName);
			serviceFullShortNameMap.set(serviceFullName, serviceName);
			if (!storageStepsMap.has(storage)) storageStepsMap.set(storage, new Set());
			storageStepsMap.get(storage).add(stepPath);
		});

		result.steps[stepShortPath] = Object.create(null);
	});

	return deferred.map(aFrom(storageStepsMap), function (data) {
		var storage = data[0], stepPaths = data[1]
		  , serviceName = serviceFullShortNameMap.get(storage.name);

		var initStepDataset = function (stepPath, businessProcessId) {
			var stepShortPath = stepShortPathMap.get(stepPath);
			if (!result.steps[stepShortPath][businessProcessId]) {
				result.steps[stepShortPath][businessProcessId] = {
					stepFullPath: 'processingSteps/map/' + stepPath
				};
			}
			return result.steps[stepShortPath][businessProcessId];
		};
		var initBpDataset = function (businessProcessId) {
			if (!result.businessProcesses[businessProcessId]) {
				result.businessProcesses[businessProcessId] = { serviceName: serviceName };
			}
			return result.businessProcesses[businessProcessId];
		};

		// Listen for new records
		stepPaths.forEach(function (stepPath) {
			// Status
			forEach(exports.stepMetaMap, function (meta, stepKeyPath) {
				storage.on('key:processingSteps/map/' + stepPath + '/' + stepKeyPath, function (event) {
					if (event.type !== (meta.type || 'direct')) return;
					if (!meta.validate(event.data)) meta.delete(initStepDataset(stepPath, event.ownerId));
					else meta.set(initStepDataset(stepPath, event.ownerId), event.data);
				});
			});
		});
		forEach(exports.businessProcessMetaMap, function (meta, keyPath) {
			storage.on('key:' + keyPath, function (event) {
				if (event.type !== (meta.type || 'direct')) return;
				if (!meta.validate(event.data)) meta.delete(initBpDataset(event.ownerId));
				else meta.set(initBpDataset(event.ownerId), event.data);
			});
		});

		// Get current records
		return deferred(
			storage.search(function (id, record) {
				var bpId = id.slice('/', 1)[0], stepPath, stepKeyPath, meta, keyPath, multiItemValue, path;
				if (bpId === id) return;
				if (includes.call(id, '*')) {
					keyPath = resolveKeyPath(id);
					path = bpId + '/' + keyPath;
					if (path !== id) multiItemValue = id.slice(path.length + 1);
				} else {
					keyPath = id.slice(bpId.length + 1);
				}
				meta = exports.businessProcessMetaMap[keyPath];
				if (meta) {
					if (meta.type && (meta.type !== 'direct')) return;
					if (multiItemValue && !meta.multiple) return;
					if (!meta.validate(record, multiItemValue)) return;
					meta.set(initBpDataset(bpId), record, multiItemValue);
				}
				var match = keyPath.match(re);
				if (!match) return;
				stepPath = match[2];
				if (!stepPaths.has(stepPath)) return;
				stepKeyPath = match[3];
				meta = exports.stepMetaMap[stepKeyPath];
				if (!meta) return;
				if (meta.type && (meta.type !== 'direct')) return;
				if (multiItemValue && !meta.multiple) return;
				if (!meta.validate(record, multiItemValue)) return;
				meta.set(initStepDataset(stepPath, bpId), record, multiItemValue);
			}),
			deferred.map(Object.keys(exports.businessProcessMetaMap), function (keyPath) {
				var meta = exports.businessProcessMetaMap[keyPath];
				if (meta.type !== 'computed') return;
				return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
					if (!meta.validate(record)) return;
					meta.set(initBpDataset(id.split('/', 1)[0]), record);
				});
			}),
			deferred.map(aFrom(stepPaths), function (stepPath) {
				return deferred.map(Object.keys(exports.stepMetaMap), function (stepPropKeyPath) {
					var meta = exports.stepMetaMap[stepPropKeyPath];
					if (meta.type !== 'computed') return;
					var keyPath = 'processingSteps/map/' + stepPath + '/' + stepPropKeyPath;
					return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
						if (!meta.validate(record)) return;
						meta.set(initStepDataset(stepPath, id.split('/', 1)[0]), record);
					});
				});
			})
		);
	})(result).aside(function () {
		debugLoad('business process db data (in %s)', humanize(Date.now() - startTime));
	});

}, { length: 0 });

// Map of all properties to be mapped to result with corresponding instructions
exports.stepMetaMap = {
	correctionTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.correctionTime = unserializeValue(record.value); },
		delete: function (data) { delete data.correctionTime; }
	},
	isReady: {
		type: 'computed',
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.pendingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
		},
		delete: function (data) { delete data.pendingDate; }
	},
	processingTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.processingTime = unserializeValue(record.value); },
		delete: function (data) { delete data.processingTime; }
	},
	processor: {
		validate: function (record) { return (record.value[0] === '7'); },
		set: function (data, record) { data.processor = record.value.slice(1); },
		delete: function (data) { delete data.processor; }
	},
	status: {
		validate: function (record) {
			return ((record.value === '3approved') || (record.value === '3rejected'));
		},
		set: function (data, record) {
			data.processingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
		},
		delete: function (data) { delete data.processingDate; }
	}
};

exports.businessProcessMetaMap = {
	isApproved: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.approvedDateTime = new Date(record.stamp / 1000);
			data.approvedDate = toDateInTz(data.approvedDateTime, timeZone);
		},
		delete: function (data) {
			delete data.approvedDateTime;
			delete data.approvedDate;
		}
	},
	isSubmitted: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.submissionDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) { delete data.submissionDateTime; }
	},
	status: {
		validate: function (record) { return (record.value[0] === '3'); },
		set: function (data, record) { data.status = record.value.slice(1); },
		delete: function (data) { delete data.status; }
	}
};
<commit_msg>Gather 'registrations' data<commit_after>// Retrive data for all steps of all files
// (map db data into meta objects for our needs)

'use strict';

var aFrom                         = require('es5-ext/array/from')
  , forEach                       = require('es5-ext/object/for-each')
  , capitalize                    = require('es5-ext/string/#/capitalize')
  , includes                      = require('es5-ext/string/#/contains')
  , Set                           = require('es6-set')
  , Map                           = require('es6-map')
  , deferred                      = require('deferred')
  , memoize                       = require('memoizee')
  , unserializeValue              = require('dbjs/_setup/unserialize/value')
  , resolveKeyPath                = require('dbjs/_setup/utils/resolve-key-path')
  , resolveEventKeys              = require('dbjs-persistence/lib/resolve-event-keys')
  , debugLoad                     = require('debug-ext')('load', 6)
  , humanize                      = require('debug-ext').humanize
  , resolveProcessingStepFullPath = require('../../utils/resolve-processing-step-full-path')
  , toDateInTz                    = require('../../utils/to-date-in-time-zone')
  , timeZone                      = require('../../db').timeZone;

var re = new RegExp('^processingSteps\\/map\\/([a-zA-Z0-9]+' +
	'(?:\\/steps\\/map\\/[a-zA-Z0-9]+)*)\\/([a-z0-9A-Z\\/]+)$');

module.exports = exports = memoize(function (driver, processingStepsMeta) {
	var storageStepsMap = new Map(), stepShortPathMap = new Map()
	  , serviceFullShortNameMap = new Map()
	  , startTime = Date.now();

	var result = { steps: Object.create(null), businessProcesses: Object.create(null) };

	forEach(processingStepsMeta, function (meta, stepShortPath) {
		var stepPath = resolveProcessingStepFullPath(stepShortPath);
		stepShortPathMap.set(stepPath, stepShortPath);
		meta._services.forEach(function (serviceName) {
			var serviceFullName = 'businessProcess' + capitalize.call(serviceName)
			  , storage = driver.getStorage(serviceFullName);
			serviceFullShortNameMap.set(serviceFullName, serviceName);
			if (!storageStepsMap.has(storage)) storageStepsMap.set(storage, new Set());
			storageStepsMap.get(storage).add(stepPath);
		});

		result.steps[stepShortPath] = Object.create(null);
	});

	return deferred.map(aFrom(storageStepsMap), function (data) {
		var storage = data[0], stepPaths = data[1]
		  , serviceName = serviceFullShortNameMap.get(storage.name);

		var initStepDataset = function (stepPath, businessProcessId) {
			var stepShortPath = stepShortPathMap.get(stepPath);
			if (!result.steps[stepShortPath][businessProcessId]) {
				result.steps[stepShortPath][businessProcessId] = {
					stepFullPath: 'processingSteps/map/' + stepPath
				};
			}
			return result.steps[stepShortPath][businessProcessId];
		};
		var initBpDataset = function (businessProcessId) {
			if (!result.businessProcesses[businessProcessId]) {
				result.businessProcesses[businessProcessId] = { serviceName: serviceName };
			}
			return result.businessProcesses[businessProcessId];
		};

		// Listen for new records
		stepPaths.forEach(function (stepPath) {
			// Status
			forEach(exports.stepMetaMap, function (meta, stepKeyPath) {
				storage.on('key:processingSteps/map/' + stepPath + '/' + stepKeyPath, function (event) {
					if (event.type !== (meta.type || 'direct')) return;
					if (!meta.validate(event.data)) meta.delete(initStepDataset(stepPath, event.ownerId));
					else meta.set(initStepDataset(stepPath, event.ownerId), event.data);
				});
			});
		});
		forEach(exports.businessProcessMetaMap, function (meta, keyPath) {
			storage.on('key:' + keyPath, function (event) {
				if (event.type !== (meta.type || 'direct')) return;
				if (!meta.validate(event.data)) meta.delete(initBpDataset(event.ownerId));
				else meta.set(initBpDataset(event.ownerId), event.data);
			});
		});

		// Get current records
		return deferred(
			storage.search(function (id, record) {
				var bpId = id.slice('/', 1)[0], stepPath, stepKeyPath, meta, keyPath, multiItemValue, path;
				if (bpId === id) return;
				if (includes.call(id, '*')) {
					keyPath = resolveKeyPath(id);
					path = bpId + '/' + keyPath;
					if (path !== id) multiItemValue = id.slice(path.length + 1);
				} else {
					keyPath = id.slice(bpId.length + 1);
				}
				meta = exports.businessProcessMetaMap[keyPath];
				if (meta) {
					if (meta.type && (meta.type !== 'direct')) return;
					if (multiItemValue && !meta.multiple) return;
					if (!meta.validate(record, multiItemValue)) return;
					meta.set(initBpDataset(bpId), record, multiItemValue);
				}
				var match = keyPath.match(re);
				if (!match) return;
				stepPath = match[2];
				if (!stepPaths.has(stepPath)) return;
				stepKeyPath = match[3];
				meta = exports.stepMetaMap[stepKeyPath];
				if (!meta) return;
				if (meta.type && (meta.type !== 'direct')) return;
				if (multiItemValue && !meta.multiple) return;
				if (!meta.validate(record, multiItemValue)) return;
				meta.set(initStepDataset(stepPath, bpId), record, multiItemValue);
			}),
			deferred.map(Object.keys(exports.businessProcessMetaMap), function (keyPath) {
				var meta = exports.businessProcessMetaMap[keyPath];
				if (meta.type !== 'computed') return;
				return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
					if (!meta.validate(record)) return;
					meta.set(initBpDataset(id.split('/', 1)[0]), record);
				});
			}),
			deferred.map(aFrom(stepPaths), function (stepPath) {
				return deferred.map(Object.keys(exports.stepMetaMap), function (stepPropKeyPath) {
					var meta = exports.stepMetaMap[stepPropKeyPath];
					if (meta.type !== 'computed') return;
					var keyPath = 'processingSteps/map/' + stepPath + '/' + stepPropKeyPath;
					return storage.searchComputed({ keyPath: keyPath }, function (id, record) {
						if (!meta.validate(record)) return;
						meta.set(initStepDataset(stepPath, id.split('/', 1)[0]), record);
					});
				});
			})
		);
	})(result).aside(function () {
		debugLoad('business process db data (in %s)', humanize(Date.now() - startTime));
	});

}, { length: 0 });

// Map of all properties to be mapped to result with corresponding instructions
exports.stepMetaMap = {
	correctionTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.correctionTime = unserializeValue(record.value); },
		delete: function (data) { delete data.correctionTime; }
	},
	isReady: {
		type: 'computed',
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.pendingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
		},
		delete: function (data) { delete data.pendingDate; }
	},
	processingTime: {
		validate: function (record) { return (record.value[0] === '2'); },
		set: function (data, record) { data.processingTime = unserializeValue(record.value); },
		delete: function (data) { delete data.processingTime; }
	},
	processor: {
		validate: function (record) { return (record.value[0] === '7'); },
		set: function (data, record) { data.processor = record.value.slice(1); },
		delete: function (data) { delete data.processor; }
	},
	status: {
		validate: function (record) {
			return ((record.value === '3approved') || (record.value === '3rejected'));
		},
		set: function (data, record) {
			data.processingDate = toDateInTz(new Date(record.stamp / 1000), timeZone);
		},
		delete: function (data) { delete data.processingDate; }
	}
};

exports.businessProcessMetaMap = {
	isApproved: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.approvedDateTime = new Date(record.stamp / 1000);
			data.approvedDate = toDateInTz(data.approvedDateTime, timeZone);
		},
		delete: function (data) {
			delete data.approvedDateTime;
			delete data.approvedDate;
		}
	},
	isSubmitted: {
		validate: function (record) { return (record.value === '11'); },
		set: function (data, record) {
			data.submissionDateTime = new Date(record.stamp / 1000);
		},
		delete: function (data) { delete data.submissionDateTime; }
	},
	'registrations/requested': {
		type: 'computed',
		validate: function (record) { return record.value[0] === '['; },
		set: function (data, record) {
			data.registrations = new Set(resolveEventKeys(JSON.parse(record.value)).map(function (value) {
				return value.slice(value.lastIndexOf('/') + 1);
			}));
		},
		delete: function (data) {
			delete data.registrations;
		}
	},
	status: {
		validate: function (record) { return (record.value[0] === '3'); },
		set: function (data, record) { data.status = record.value.slice(1); },
		delete: function (data) { delete data.status; }
	}
};
<|endoftext|>


<commit_before>import React from 'react';
import cx from 'classnames';
import { Router, Route, Link } from 'react-router'

class Header extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    //this.loadCarbonAds();
    //this.renderConnectedDots();
  }

  loadCarbonAds() {
    let carbonAdsContainer = this.refs.carbonAds;
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=sahatyalkabovcom';
    script.id = '_carbonads_js';
    carbonAdsContainer.appendChild(script);
  }

  renderConnectedDots() {
    let canvas = this.refs.connectedDots;
    let ctx = canvas.getContext('2d');
    let colorDot = '#fff';
    let color = '#fff';

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    canvas.style.display = 'block';
    ctx.fillStyle = colorDot;
    ctx.lineWidth = .1;
    ctx.strokeStyle = color;

    var mousePosition = {
      x: 30 * canvas.width / 100,
      y: 30 * canvas.height / 100
    };

    var dots = {
      nb: 350,
      distance: 60,
      d_radius: 100,
      array: []
    };

    function Dot() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;

      this.vx = -.5 + Math.random();
      this.vy = -.5 + Math.random();

      this.radius = Math.random();
    }

    Dot.prototype = {
      create: function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        ctx.fill();
      },

      animate: function() {

        for (let i = 0; i < dots.nb; i++) {

          var dot = dots.array[i];

          if (dot.y < 0 || dot.y > canvas.height) {
            dot.vx = dot.vx;
            dot.vy = -dot.vy;
          }
          else if (dot.x < 0 || dot.x > canvas.width) {
            dot.vx = -dot.vx;
            dot.vy = dot.vy;
          }
          dot.x += dot.vx;
          dot.y += dot.vy;
        }
      },

      line: function() {
        for (let i = 0; i < dots.nb; i++) {
          for (let j = 0; j < dots.nb; j++) {
            var i_dot = dots.array[i];
            var j_dot = dots.array[j];

            if ((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > -dots.distance && (i_dot.y - j_dot.y) > -dots.distance) {
              if ((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > -dots.d_radius && (i_dot.y - mousePosition.y) > -dots.d_radius) {
                ctx.beginPath();
                ctx.moveTo(i_dot.x, i_dot.y);
                ctx.lineTo(j_dot.x, j_dot.y);
                ctx.stroke();
                ctx.closePath();
              }
            }
          }
        }
      }
    };

    function createDots() {
      let dot;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      for (let i = 0; i < dots.nb; i++) {
        dots.array.push(new Dot());
        dot = dots.array[i];

        dot.create();
      }

      dot.line();
      dot.animate();
    }

    window.onmousemove = function(parameter) {
      mousePosition.x = parameter.pageX;
      mousePosition.y = parameter.pageY;
    };

    mousePosition.x = window.innerWidth / 2;
    mousePosition.y = window.innerHeight / 2;

    setInterval(createDots, 1000 / 30);
  }

  render() {
    return (

        <canvas ref="connectedDots"/>

Bug Reports

Contributing

Mega Boilerplate

            Simple and easy to use hand-crafted starter kits.

Demo 1

Demo 2

Demo 3

Demo 4

            Don't forget to  on GitHub if you liked this project!

    );
  }
}

export default Header;
<commit_msg>Updated header links<commit_after>import React from 'react';
import cx from 'classnames';
import { Router, Route, Link } from 'react-router'

class Header extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    //this.loadCarbonAds();
    //this.renderConnectedDots();
  }

  loadCarbonAds() {
    let carbonAdsContainer = this.refs.carbonAds;
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=sahatyalkabovcom';
    script.id = '_carbonads_js';
    carbonAdsContainer.appendChild(script);
  }

  renderConnectedDots() {
    let canvas = this.refs.connectedDots;
    let ctx = canvas.getContext('2d');
    let colorDot = '#fff';
    let color = '#fff';

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    canvas.style.display = 'block';
    ctx.fillStyle = colorDot;
    ctx.lineWidth = .1;
    ctx.strokeStyle = color;

    var mousePosition = {
      x: 30 * canvas.width / 100,
      y: 30 * canvas.height / 100
    };

    var dots = {
      nb: 350,
      distance: 60,
      d_radius: 100,
      array: []
    };

    function Dot() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;

      this.vx = -.5 + Math.random();
      this.vy = -.5 + Math.random();

      this.radius = Math.random();
    }

    Dot.prototype = {
      create: function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        ctx.fill();
      },

      animate: function() {

        for (let i = 0; i < dots.nb; i++) {

          var dot = dots.array[i];

          if (dot.y < 0 || dot.y > canvas.height) {
            dot.vx = dot.vx;
            dot.vy = -dot.vy;
          }
          else if (dot.x < 0 || dot.x > canvas.width) {
            dot.vx = -dot.vx;
            dot.vy = dot.vy;
          }
          dot.x += dot.vx;
          dot.y += dot.vy;
        }
      },

      line: function() {
        for (let i = 0; i < dots.nb; i++) {
          for (let j = 0; j < dots.nb; j++) {
            var i_dot = dots.array[i];
            var j_dot = dots.array[j];

            if ((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > -dots.distance && (i_dot.y - j_dot.y) > -dots.distance) {
              if ((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > -dots.d_radius && (i_dot.y - mousePosition.y) > -dots.d_radius) {
                ctx.beginPath();
                ctx.moveTo(i_dot.x, i_dot.y);
                ctx.lineTo(j_dot.x, j_dot.y);
                ctx.stroke();
                ctx.closePath();
              }
            }
          }
        }
      }
    };

    function createDots() {
      let dot;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      for (let i = 0; i < dots.nb; i++) {
        dots.array.push(new Dot());
        dot = dots.array[i];

        dot.create();
      }

      dot.line();
      dot.animate();
    }

    window.onmousemove = function(parameter) {
      mousePosition.x = parameter.pageX;
      mousePosition.y = parameter.pageY;
    };

    mousePosition.x = window.innerWidth / 2;
    mousePosition.y = window.innerHeight / 2;

    setInterval(createDots, 1000 / 30);
  }

  render() {
    return (

        <canvas ref="connectedDots"/>

Bug Reports

Contributing

Mega Boilerplate

            Simple and easy to use hand-crafted starter kits.

Demo 1

Demo 2

Demo 3

Demo 4

            Don't forget to  on GitHub if you liked this project!

    );
  }
}

export default Header;
<|endoftext|>


<commit_before>"use strict";

var ViewPortCreator = Class.extend({
  init: function() {
    this.trajectoryCalculator = new TrajectoryCalculator();
  },

  getColumnsInRange: function(scrollLocation, playerLocation, column) {
    return _.map(column.findAllNearby(playerLocation.col), function(col) {
      return col - scrollLocation;
    });
  },

  shiftTrajectoriesForViewPort: function(scrollLocation, trajectories) {
    var newTrajectories = [];
    for (var i=0; i<trajectories.length; i++) {
      newTrajectories.push(this.shiftArrayForViewPort(scrollLocation, trajectories[i]));
    }

    return newTrajectories;
  },

  shiftArrayForViewPort: function(scrollLocation, array) {
    var newArray = [];
    for (var i=0; i<array.length; i++) {
      newArray.push(this.shiftForViewPort(scrollLocation, array[i]));
    }

    return newArray;
  },

  shiftForViewPort: function(scrollLocation, point) {
    return pointRowCol(point.row, point.col - scrollLocation);
  },

  create: function(scrollLocation, playerLocation, topColumn, bottomColumn, collided, gameOver, points) {
    var viewPort = {
      playerLocation: this.shiftForViewPort(scrollLocation, playerLocation),
      trajectory: this.shiftTrajectoriesForViewPort(
        scrollLocation,
        this.trajectoryCalculator.getTrajectories(playerLocation)),
      topColumns: this.getColumnsInRange(scrollLocation, playerLocation, topColumn),
      bottomColumns: this.getColumnsInRange(scrollLocation, playerLocation, bottomColumn),
      collided: collided,
      gameOver: gameOver,
      points: points,
    };

    return viewPort;
  },

});<commit_msg>refactor: change method names<commit_after>"use strict";

var ViewPortCreator = Class.extend({
  init: function() {
    this.trajectoryCalculator = new TrajectoryCalculator();
  },

  findPillarsInViewPort: function(scrollLocation, playerLocation, column) {
    return _.map(column.findAllNearby(playerLocation.col), function(col) {
      return col - scrollLocation;
    });
  },

  shiftTrajectoriesForViewPort: function(scrollLocation, trajectories) {
    //refactor out these awful temp arrays when I switch out from underscore to lo-dash
    var newTrajectories = [];
    for (var i=0; i<trajectories.length; i++) {
      var newTrajectory = [];

      for (var j=0; j<trajectories[i].length; j++) {
        newTrajectory.push(this.shiftLocationForViewPort(scrollLocation, trajectories[i][j]));
      }

      newTrajectories.push(newTrajectory);
    }

    return newTrajectories;
  },

  shiftLocationForViewPort: function(scrollLocation, point) {
    return pointRowCol(point.row, point.col - scrollLocation);
  },

  create: function(scrollLocation, playerLocation, topColumn, bottomColumn, collided, gameOver, points) {
    var viewPort = {
      playerLocation: this.shiftLocationForViewPort(scrollLocation, playerLocation),
      trajectory: this.shiftTrajectoriesForViewPort(
        scrollLocation,
        this.trajectoryCalculator.getTrajectories(playerLocation)),
      topColumns: this.findPillarsInViewPort(scrollLocation, playerLocation, topColumn),
      bottomColumns: this.findPillarsInViewPort(scrollLocation, playerLocation, bottomColumn),
      collided: collided,
      gameOver: gameOver,
      points: points,
    };

    return viewPort;
  },
});<|endoftext|>


<commit_before><commit_msg>Included check for non valid first arg.<commit_after><|endoftext|>


<commit_before>const path = require('path');
const istanbul = require('rollup-plugin-istanbul');

const baseConfig = require('./karma.base');

function getBuild() {
  let id = `LIGHTY - TRAVIS #${process.env.TRAVIS_BUILD_NUMBER}`;

  id += ` (Branch: ${process.env.TRAVIS_BRANCH}`;

  if (process.env.TRAVIS_PULL_REQUEST !== 'false') {
    id += ` | PR: ${process.env.TRAVIS_PULL_REQUEST}`;
  }

  id += ')';

  return id;
}

function getTunnel() {
  return process.env.TRAVIS_JOB_NUMBER;
}

module.exports = function karma(config) {
  const sauceBrowsers = {
    // Chrome (last 3 versions)

    sl_chrome_54: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '54.0',
      platform: 'Windows 10',
    },

    sl_chrome_53: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '53.0',
      platform: 'Windows 10',
    },

    sl_chrome_52: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '52.0',
      platform: 'Windows 10',
    },

    // Firefox (last 3 versions)

    sl_firefox_50: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '50.0',
      platform: 'Windows 10',
    },

    sl_firefox_49: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '49.0',
      platform: 'Windows 10',
    },

    sl_firefox_48: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '48.0',
      platform: 'Windows 10',
    },

    // Edge

    sl_edge_14: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      version: '14.14393',
      platform: 'Windows 10',
    },

    sl_edge_13: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      version: '13.10586',
      platform: 'Windows 10',
    },

    // Internet Explorer (last 3 versions)

    sl_ie_11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '11.103',
      platform: 'Windows 10',
    },

    sl_ie_10: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '10.0',
      platform: 'Windows 8',
    },

    sl_ie_9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '9.0',
      platform: 'Windows 7',
    },

    // Safari (last 3 versions)

    sl_safari_10: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '10.0',
      platform: 'OS X 10.11',
    },

    sl_safari_9: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '9.0',
      platform: 'OS X 10.11',
    },

    sl_safari_8: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '8.0',
      platform: 'OS X 10.10',
    },

    // iOS (last 3 major versions)

    sl_ios_10: {
      base: 'SauceLabs',
      browserName: 'Safari',
      appiumVersion: '1.6.3',
      deviceName: 'iPhone Simulator',
      deviceOrientation: 'portrait',
      platformVersion: '10.0',
      platformName: 'iOS',
    },

    sl_ios_9: {
      base: 'SauceLabs',
      browserName: 'Safari',
      appiumVersion: '1.6.3',
      deviceName: 'iPhone Simulator',
      deviceOrientation: 'portrait',
      platformVersion: '9.3',
      platformName: 'iOS',
    },

    sl_ios_8: {
      base: 'SauceLabs',
      browserName: 'Safari',
      appiumVersion: '1.6.3',
      deviceName: 'iPhone Simulator',
      deviceOrientation: 'portrait',
      platformVersion: '8.4',
      platformName: 'iOS',
    },
  };

  Object.assign(baseConfig, {
    sauceLabs: {
      testName: 'lighty',
      build: getBuild(),
      tunnelIdentifier: getTunnel(),
      recordVideo: false,
      recordScreenshots: false,
      startConnect: false,
    },

    customLaunchers: sauceBrowsers,

    browsers: Object.keys(sauceBrowsers),

    reporters: ['dots', 'coverage', 'coveralls', 'saucelabs'],

    coverageReporter: {
      dir: path.join(__dirname, '../', 'coverage'),
      reporters: [
        { type: 'text' },
        { type: 'lcov' },
      ],
    },

    concurrency: 1,
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 1,
    browserNoActivityTimeout: 4 * 60 * 1000,
    captureTimeout: 0,

    singleRun: true,
  });

  baseConfig.rollupPreprocessor.plugins.splice(1, 1, istanbul({
    exclude: ['node_modules/**/*.js', 'spec/**/*.js'],
  }));

  baseConfig.plugins.push(
    'karma-sauce-launcher',
    'karma-coverage',
    'karma-coveralls'
  );

  config.set(baseConfig);
};
<commit_msg>Update and extend browsers list for CI tests<commit_after>const path = require('path');
const istanbul = require('rollup-plugin-istanbul');

const baseConfig = require('./karma.base');

function getBuild() {
  let id = `LIGHTY - TRAVIS #${process.env.TRAVIS_BUILD_NUMBER}`;

  id += ` (Branch: ${process.env.TRAVIS_BRANCH}`;

  if (process.env.TRAVIS_PULL_REQUEST !== 'false') {
    id += ` | PR: ${process.env.TRAVIS_PULL_REQUEST}`;
  }

  id += ')';

  return id;
}

function getTunnel() {
  return process.env.TRAVIS_JOB_NUMBER;
}

module.exports = function karma(config) {
  const sauceBrowsers = {
    // Chrome (last 3 versions and 3 old versions)

    sl_chrome_57: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '57.0',
      platform: 'Windows 10',
    },

    sl_chrome_56: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '56.0',
      platform: 'Windows 10',
    },

    sl_chrome_55: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '55.0',
      platform: 'Windows 10',
    },

    sl_chrome_51: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '51.0',
      platform: 'Windows 10',
    },

    sl_chrome_40: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '40.0',
      platform: 'Windows 10',
    },

    sl_chrome_30: {
      base: 'SauceLabs',
      browserName: 'chrome',
      version: '30.0',
      platform: 'Windows 10',
    },

    // Firefox (last 3 versions and 3 old versions)

    sl_firefox_52: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '52.0',
      platform: 'Windows 10',
    },

    sl_firefox_51: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '51.0',
      platform: 'Windows 10',
    },

    sl_firefox_50: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '50.0',
      platform: 'Windows 10',
    },

    sl_firefox_40: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '40.0',
      platform: 'Windows 10',
    },

    sl_firefox_33: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '33.0',
      platform: 'Windows 10',
    },

    sl_firefox_20: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '20.0',
      platform: 'Windows 10',
    },

    // Edge

    sl_edge_14: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      version: '14.14393',
      platform: 'Windows 10',
    },

    sl_edge_13: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      version: '13.10586',
      platform: 'Windows 10',
    },

    // Internet Explorer (last 3 versions)

    sl_ie_11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '11.103',
      platform: 'Windows 10',
    },

    sl_ie_10: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '10.0',
      platform: 'Windows 8',
    },

    sl_ie_9: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      version: '9.0',
      platform: 'Windows 7',
    },

    // Safari (last 6 versions)

    sl_safari_10: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '10.0',
      platform: 'OS X 10.12',
    },

    sl_safari_9: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '9.0',
      platform: 'OS X 10.11',
    },

    sl_safari_8: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '8.0',
      platform: 'OS X 10.10',
    },

    sl_safari_7: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '7.0',
      platform: 'OS X 10.9',
    },

    sl_safari_6: {
      base: 'SauceLabs',
      browserName: 'Safari',
      version: '6.0',
      platform: 'OS X 10.8',
    },

    // iOS (last 3 major versions)

    sl_ios_10: {
      base: 'SauceLabs',
      browserName: 'Safari',
      appiumVersion: '1.6.4',
      deviceName: 'iPhone Simulator',
      deviceOrientation: 'portrait',
      platformVersion: '10.2',
      platformName: 'iOS',
    },

    sl_ios_9: {
      base: 'SauceLabs',
      browserName: 'Safari',
      appiumVersion: '1.6.4',
      deviceName: 'iPhone Simulator',
      deviceOrientation: 'portrait',
      platformVersion: '9.3',
      platformName: 'iOS',
    },

    sl_ios_8: {
      base: 'SauceLabs',
      browserName: 'Safari',
      appiumVersion: '1.6.4',
      deviceName: 'iPhone Simulator',
      deviceOrientation: 'portrait',
      platformVersion: '8.4',
      platformName: 'iOS',
    },
  };

  Object.assign(baseConfig, {
    sauceLabs: {
      testName: 'lighty',
      build: getBuild(),
      tunnelIdentifier: getTunnel(),
      recordVideo: false,
      recordScreenshots: false,
      startConnect: false,
    },

    customLaunchers: sauceBrowsers,

    browsers: Object.keys(sauceBrowsers),

    reporters: ['dots', 'coverage', 'coveralls', 'saucelabs'],

    coverageReporter: {
      dir: path.join(__dirname, '../', 'coverage'),
      reporters: [
        { type: 'text' },
        { type: 'lcov' },
      ],
    },

    concurrency: 1,
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 1,
    browserNoActivityTimeout: 4 * 60 * 1000,
    captureTimeout: 0,

    singleRun: true,
  });

  baseConfig.rollupPreprocessor.plugins.splice(1, 1, istanbul({
    exclude: ['node_modules/**/*.js', 'spec/**/*.js'],
  }));

  baseConfig.plugins.push(
    'karma-sauce-launcher',
    'karma-coverage',
    'karma-coveralls'
  );

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


<commit_before>/* eslint-env mocha */
var shared = require("./shared");

var expect = shared.expect;
var samples = shared.samples;
var expectImmutableEqual = shared.expectImmutableEqual;
var expectNotImmutableEqual = shared.expectNotImmutableEqual;

var Immutable = require('immutable');

var transit = require('../');

describe('transit', function() {
  samples.get('Immutable').forEach(function(data, desc) {
    describe(desc + " - " + data.inspect(), function() {
      it('should encode to JSON', function() {
        var json = transit.toJSON(data);
        expect(json).to.be.a('string');
        expect(JSON.parse(json)).to.not.eql(null);
      });
      it('should round-trip', function() {
        var roundTrip = transit.fromJSON(transit.toJSON(data));
        expect(roundTrip).to.be.an('object');
        expectImmutableEqual(roundTrip, data);
        expect(roundTrip).to.be.an.instanceOf(data.constructor);
      });
    });
  });

  samples.get('JS').forEach(function(data, desc) {
    describe(desc + " - " + JSON.stringify(data), function() {
      it('should encode to JSON', function() {
        var json = transit.toJSON(data);
        expect(json).to.be.a('string');
        expect(JSON.parse(json)).to.not.eql(null);
      });
      it('should round-trip', function() {
        var roundTrip = transit.fromJSON(transit.toJSON(data));
        expectImmutableEqual(roundTrip, data);
      });
    });
  });

  it('should ignore functions', function() {
    var input = Immutable.Map({ a: function abc(){} });
    var result = transit.fromJSON(transit.toJSON(input));
    expect(result.get('a')).to.eql(null);
  });

  describe('Records', function() {
    var FooRecord = Immutable.Record({
      a: 1,
      b: 2,
    }, 'foo');

    var BarRecord = Immutable.Record({
      c: '1',
      d: '2'
    }, 'bar');

    var NamelessRecord = Immutable.Record({});

    var ClassyBase = Immutable.Record({name: 'lindsey'}, 'ClassyRecord');
    function ClassyRecord(values) { ClassyBase.call(this, values); }
    ClassyRecord.prototype = Object.create(ClassyBase.prototype);
    ClassyRecord.prototype.constructor = ClassyRecord;

    var recordTransit = transit.withRecords([FooRecord, BarRecord]);

    it('should ensure maps and records compare differently', function() {
      expectNotImmutableEqual(new FooRecord(), Immutable.Map({a: 1, b: 2}));
    });

    it('should round-trip simple records', function() {
      var data = Immutable.Map({
        myFoo: new FooRecord(),
        myBar: new BarRecord()
      });

      var roundTrip = recordTransit.fromJSON(recordTransit.toJSON(data));
      expectImmutableEqual(data, roundTrip);

      expect(roundTrip.get('myFoo').a).to.eql(1);
      expect(roundTrip.get('myFoo').b).to.eql(2);

      expect(roundTrip.get('myBar').c).to.eql('1');
      expect(roundTrip.get('myBar').d).to.eql('2');
    });

    it('should round-trip complex nested records', function() {
      var data = Immutable.Map({
        foo: new FooRecord({
          b: Immutable.List.of(BarRecord(), BarRecord({c: 22}))
        }),
        bar: new BarRecord()
      });

      var roundTrip = recordTransit.fromJSON(recordTransit.toJSON(data));
      expectImmutableEqual(data, roundTrip);
    });

    it('should serialize unspecified Record as a Map', function() {
      var data = Immutable.Map({
        myFoo: new FooRecord(),
        myBar: new BarRecord()
      });

      var oneRecordTransit = transit.withRecords([FooRecord]);
      var roundTripOneRecord = oneRecordTransit.fromJSON(
                                oneRecordTransit.toJSON(data));

      expectImmutableEqual(roundTripOneRecord, Immutable.fromJS({
        myFoo: new FooRecord(),
        myBar: {c: '1', d: '2'}
      }));

      var roundTripWithoutRecords = transit.fromJSON(transit.toJSON(data));

      expectImmutableEqual(roundTripWithoutRecords, Immutable.fromJS({
        myFoo: {a: 1, b: 2},
        myBar: {c: '1', d: '2'}
      }));
    });

    it('should roundtrip ES6-class-style records', function() {
      var data = new ClassyRecord({name: 'jon'});

      var classyTransit = transit.withRecords([ClassyRecord]);
      var roundTrip = classyTransit.fromJSON(classyTransit.toJSON(data));

      expectImmutableEqual(data, roundTrip);
    });

    it('throws an error when it is passed a record with no name', function() {
      expect(function() {
        transit.withRecords([NamelessRecord]);
      }).to.throw();
    });

    it('throws an error when it reads an unknown record type', function() {
      var input = new FooRecord();

      var json = recordTransit.toJSON(input);

      var emptyRecordTransit = transit.withRecords([]);

      expect(function() {
        emptyRecordTransit.fromJSON(json);
      }).to.throw();
    });

    it('throws an error if two records have the same name', function() {
      var R1 = Immutable.Record({}, 'R1');
      var R1_2 = Immutable.Record({}, 'R1');

      expect(function() {
        transit.withRecords([R1, R1_2]);
      }).to.throw();
    });

    it('should not throw an error with custom error-handler', function() {
      var input = new FooRecord();

      var json = recordTransit.toJSON(input);

      var emptyRecordTransit = transit.withRecords([], function() {
        return null;
      });

      expect(function() {
        emptyRecordTransit.fromJSON(json);
      }).to.not.throw();
    });

    it('should deserializing a FooRecord to BarRecord', function() {
      var input = new FooRecord({a: '3', b: '4'});

      var json = recordTransit.toJSON(input);

      var emptyRecordTransit = transit.withRecords([], function(n, v) {
        switch (n) {
        case 'foo':
          return new BarRecord({c: v.a, d: v.b});
        default:
          return null;
        }
      });
      var result = emptyRecordTransit.fromJSON(json);

      expect(result).to.be.an.instanceof(BarRecord);
      expect(result.c).to.eql('3');
      expect(result.d).to.eql('4');
    });
  });

  describe('.withFilter(predicate)', function(){
    var filterFunction = function(val, key) {
      return key[0] !== '_';
    };
    var filter = transit.withFilter(filterFunction);

    it('can ignore Map entries', function() {
      var input = Immutable.Map({
        a: 'foo', _b: 'bar', c: Immutable.Map({d: 'deep', _e: 'hide'})
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.get('a')).to.eql('foo');
      expect(result.get('_b')).to.eql(undefined);
      expect(result.size).to.eql(2);
      expect(result.getIn(['c', 'd'])).to.eql('deep');
      expect(result.getIn(['c', '_e'])).to.eql(undefined);
      expect(result.getIn(['c']).size).to.eql(1);
    });

    it('can ignore OrderedMap entries', function() {
      var input = Immutable.OrderedMap()
        .set('a', 'baz').set('_b', 'bar')
        .set('c', Immutable.OrderedMap({d: 'deep', _e: 'hide'}));
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.get('a')).to.eql('baz');
      expect(result.get('_b')).to.eql(undefined);
      expect(result.size).to.eql(2);
      expect(result.getIn(['c', 'd'])).to.eql('deep');
      expect(result.getIn(['c', '_e'])).to.eql(undefined);
      expect(result.getIn(['c']).size).to.eql(1);
    });

    it('can ignore Set entries', function() {
      var input = Immutable.OrderedSet.of(1, 2, 3, 3, 'a');
      filter = transit.withFilter(function(val) {
        return typeof val === 'number';
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(3);
    });

    it('can ignore OrderedSet entries', function() {
      var input = Immutable.Set.of(1, 2, 3, 3, 'a');
      filter = transit.withFilter(function(val) {
        return typeof val === 'number';
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(3);
    });

    it('can ignore List entries', function() {
      var input = Immutable.List.of(1, 2, 3, 3, 'a');
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(4);
    });

    it('can ignore Maps nested in Records', function() {
      var MyRecord = Immutable.Record({
        a: null,
        _b: 'bar'
      }, 'myRecord');

      var input = new MyRecord({a: Immutable.Map({_c: 1, d: 2}), _b: 'baz' });
      var recordFilter = transit
                          .withRecords([MyRecord])
                          .withFilter(filterFunction);

      var result = recordFilter.fromJSON(recordFilter.toJSON(input));

      expect(result.getIn(['a', 'd'])).to.eql(2);
      expect(result.getIn(['a', '_c'])).to.eql(undefined);
      expect(result.get('a').size).to.eql(1);
      expect(result.get('_b')).to.eql('baz');
    });

    it('should use missing-record-handler combined with filter', function() {
      var FooRecord = Immutable.Record({
        a: 1,
        b: 2,
      }, 'foo');

      var BarRecord = Immutable.Record({
        c: '1',
        d: '2'
      }, 'bar');

      var input = new Immutable.Map({
        _bar: new BarRecord(),
        foo: new FooRecord({
          a: 3,
          b: 4
        })
      });

      var missingRecordHandler = function(n, v) {
        switch (n) {
        case 'foo':
          return new BarRecord({c: v.a, d: v.b});
        default:
          return null;
        }
      };

      var recordFilter = transit
                          .withRecords([FooRecord, BarRecord])
                          .withFilter(filterFunction);
      var json = recordFilter.toJSON(input);
      recordFilter = transit
                      .withRecords([BarRecord], missingRecordHandler)
                      .withFilter(filterFunction);

      var result = recordFilter.fromJSON(json);

      expect(result.get('foo').c).to.eql(3);
      expect(result.get('foo').d).to.eql(4);
      expect(result.get('_bar')).to.eql(undefined);
    });

  });

  describe("withExtraHandlers", function() {
    function Point2d(x, y) { this.x = x; this.y = y; }
    function Point3d(x, y, z) { this.x = x; this.y = y; this.z = z; }
    var transitX;
    before(function() {
      transitX = transit.withExtraHandlers([
        {
          tag: "2d", class: Point2d,
          write: function(val) { return [val.x, val.y]; },
          read: function(rep) { return new Point2d(rep[0], rep[1]); }
        },
        {
          tag: "3d", class: Point3d,
          write: function(val) { return {x: val.x, y: val.y, z: val.z}; },
          read: function(rep) { return new Point3d(rep.x, rep.y, rep.z); }
        }
      ]);
    });
    var value = Immutable.Map.of(
      123, new Point2d(3, 5),
      "co-ords", Immutable.List.of(new Point3d(1, 2, 3), new Point3d(4, 5, 6))
    );

    it('should encode into json', function() {
      var json = transitX.toJSON(value);
      expect(json).to.be.a('string');
      expect(JSON.parse(json)).to.not.eql(null);
    });
    it('should round-trip', function() {
      var roundTrip = transitX.fromJSON(transitX.toJSON(value));
      expect(roundTrip).to.be.an.instanceof(Immutable.Map);

      var point2 = roundTrip.get(123);
      expect(point2).to.be.an.instanceof(Point2d);
      expect(point2).to.have.property("x", 3);
      expect(point2).to.have.property("y", 5);

      var point3a = roundTrip.getIn(["co-ords", 0]);
      expect(point3a).to.be.an.instanceof(Point3d);
      expect(point3a).to.have.property("x", 1);
      expect(point3a).to.have.property("y", 2);
      expect(point3a).to.have.property("z", 3);

      var point3b = roundTrip.getIn(["co-ords", 1]);
      expect(point3b).to.be.an.instanceof(Point3d);
      expect(point3b).to.have.property("x", 4);
      expect(point3b).to.have.property("y", 5);
      expect(point3b).to.have.property("z", 6);
    });

    describe("argument checking", function() {
      function makeExtra(override) {
        function ABC() {}
        var extra = {
          tag: "abc", class: ABC,
          read: function(rep) { return ABC(rep); },
          write: function(v) { return v * 0; }
        };
        Object.keys(override || {}).forEach(function(key) {
          extra[key] = override[key];
        });
        return extra;
      }
      it("should check for non-array", function() {
        expect(function() {
          transit.withExtraHandlers({});
        }).to.throw();
      });
      it("should check for string tag", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra(),
            makeExtra({tag: 123})
          ]);
        }).to.throw();
      });
      it("should check for class function", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra({class: "blah"})
          ]);
        }).to.throw();
      });
      it("should check for write function", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra({write: [1, 2, 3]})
          ]);
        }).to.throw();
      });
      it("should check for read function", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra({read: {nope: "not this"}})
          ]);
        }).to.throw();
      });
    });
  });

  describe('Unknown Input', function() {
    it('fails when an unrecognized object is passed', function() {
      var MyObject = function() {};
      var MyObjectInstance = new MyObject();

      expect(function() {
        transit.toJSON(MyObjectInstance);
      }).to.throw();
    });
  });

});
<commit_msg>Wrote test to check filtering of stack deserialisation.<commit_after>/* eslint-env mocha */
var shared = require("./shared");

var expect = shared.expect;
var samples = shared.samples;
var expectImmutableEqual = shared.expectImmutableEqual;
var expectNotImmutableEqual = shared.expectNotImmutableEqual;

var Immutable = require('immutable');

var transit = require('../');

describe('transit', function() {
  samples.get('Immutable').forEach(function(data, desc) {
    describe(desc + " - " + data.inspect(), function() {
      it('should encode to JSON', function() {
        var json = transit.toJSON(data);
        expect(json).to.be.a('string');
        expect(JSON.parse(json)).to.not.eql(null);
      });
      it('should round-trip', function() {
        var roundTrip = transit.fromJSON(transit.toJSON(data));
        expect(roundTrip).to.be.an('object');
        expectImmutableEqual(roundTrip, data);
        expect(roundTrip).to.be.an.instanceOf(data.constructor);
      });
    });
  });

  samples.get('JS').forEach(function(data, desc) {
    describe(desc + " - " + JSON.stringify(data), function() {
      it('should encode to JSON', function() {
        var json = transit.toJSON(data);
        expect(json).to.be.a('string');
        expect(JSON.parse(json)).to.not.eql(null);
      });
      it('should round-trip', function() {
        var roundTrip = transit.fromJSON(transit.toJSON(data));
        expectImmutableEqual(roundTrip, data);
      });
    });
  });

  it('should ignore functions', function() {
    var input = Immutable.Map({ a: function abc(){} });
    var result = transit.fromJSON(transit.toJSON(input));
    expect(result.get('a')).to.eql(null);
  });

  describe('Records', function() {
    var FooRecord = Immutable.Record({
      a: 1,
      b: 2,
    }, 'foo');

    var BarRecord = Immutable.Record({
      c: '1',
      d: '2'
    }, 'bar');

    var NamelessRecord = Immutable.Record({});

    var ClassyBase = Immutable.Record({name: 'lindsey'}, 'ClassyRecord');
    function ClassyRecord(values) { ClassyBase.call(this, values); }
    ClassyRecord.prototype = Object.create(ClassyBase.prototype);
    ClassyRecord.prototype.constructor = ClassyRecord;

    var recordTransit = transit.withRecords([FooRecord, BarRecord]);

    it('should ensure maps and records compare differently', function() {
      expectNotImmutableEqual(new FooRecord(), Immutable.Map({a: 1, b: 2}));
    });

    it('should round-trip simple records', function() {
      var data = Immutable.Map({
        myFoo: new FooRecord(),
        myBar: new BarRecord()
      });

      var roundTrip = recordTransit.fromJSON(recordTransit.toJSON(data));
      expectImmutableEqual(data, roundTrip);

      expect(roundTrip.get('myFoo').a).to.eql(1);
      expect(roundTrip.get('myFoo').b).to.eql(2);

      expect(roundTrip.get('myBar').c).to.eql('1');
      expect(roundTrip.get('myBar').d).to.eql('2');
    });

    it('should round-trip complex nested records', function() {
      var data = Immutable.Map({
        foo: new FooRecord({
          b: Immutable.List.of(BarRecord(), BarRecord({c: 22}))
        }),
        bar: new BarRecord()
      });

      var roundTrip = recordTransit.fromJSON(recordTransit.toJSON(data));
      expectImmutableEqual(data, roundTrip);
    });

    it('should serialize unspecified Record as a Map', function() {
      var data = Immutable.Map({
        myFoo: new FooRecord(),
        myBar: new BarRecord()
      });

      var oneRecordTransit = transit.withRecords([FooRecord]);
      var roundTripOneRecord = oneRecordTransit.fromJSON(
                                oneRecordTransit.toJSON(data));

      expectImmutableEqual(roundTripOneRecord, Immutable.fromJS({
        myFoo: new FooRecord(),
        myBar: {c: '1', d: '2'}
      }));

      var roundTripWithoutRecords = transit.fromJSON(transit.toJSON(data));

      expectImmutableEqual(roundTripWithoutRecords, Immutable.fromJS({
        myFoo: {a: 1, b: 2},
        myBar: {c: '1', d: '2'}
      }));
    });

    it('should roundtrip ES6-class-style records', function() {
      var data = new ClassyRecord({name: 'jon'});

      var classyTransit = transit.withRecords([ClassyRecord]);
      var roundTrip = classyTransit.fromJSON(classyTransit.toJSON(data));

      expectImmutableEqual(data, roundTrip);
    });

    it('throws an error when it is passed a record with no name', function() {
      expect(function() {
        transit.withRecords([NamelessRecord]);
      }).to.throw();
    });

    it('throws an error when it reads an unknown record type', function() {
      var input = new FooRecord();

      var json = recordTransit.toJSON(input);

      var emptyRecordTransit = transit.withRecords([]);

      expect(function() {
        emptyRecordTransit.fromJSON(json);
      }).to.throw();
    });

    it('throws an error if two records have the same name', function() {
      var R1 = Immutable.Record({}, 'R1');
      var R1_2 = Immutable.Record({}, 'R1');

      expect(function() {
        transit.withRecords([R1, R1_2]);
      }).to.throw();
    });

    it('should not throw an error with custom error-handler', function() {
      var input = new FooRecord();

      var json = recordTransit.toJSON(input);

      var emptyRecordTransit = transit.withRecords([], function() {
        return null;
      });

      expect(function() {
        emptyRecordTransit.fromJSON(json);
      }).to.not.throw();
    });

    it('should deserializing a FooRecord to BarRecord', function() {
      var input = new FooRecord({a: '3', b: '4'});

      var json = recordTransit.toJSON(input);

      var emptyRecordTransit = transit.withRecords([], function(n, v) {
        switch (n) {
        case 'foo':
          return new BarRecord({c: v.a, d: v.b});
        default:
          return null;
        }
      });
      var result = emptyRecordTransit.fromJSON(json);

      expect(result).to.be.an.instanceof(BarRecord);
      expect(result.c).to.eql('3');
      expect(result.d).to.eql('4');
    });
  });

  describe('.withFilter(predicate)', function(){
    var filterFunction = function(val, key) {
      return key[0] !== '_';
    };
    var filter = transit.withFilter(filterFunction);

    it('can ignore Map entries', function() {
      var input = Immutable.Map({
        a: 'foo', _b: 'bar', c: Immutable.Map({d: 'deep', _e: 'hide'})
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.get('a')).to.eql('foo');
      expect(result.get('_b')).to.eql(undefined);
      expect(result.size).to.eql(2);
      expect(result.getIn(['c', 'd'])).to.eql('deep');
      expect(result.getIn(['c', '_e'])).to.eql(undefined);
      expect(result.getIn(['c']).size).to.eql(1);
    });

    it('can ignore OrderedMap entries', function() {
      var input = Immutable.OrderedMap()
        .set('a', 'baz').set('_b', 'bar')
        .set('c', Immutable.OrderedMap({d: 'deep', _e: 'hide'}));
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.get('a')).to.eql('baz');
      expect(result.get('_b')).to.eql(undefined);
      expect(result.size).to.eql(2);
      expect(result.getIn(['c', 'd'])).to.eql('deep');
      expect(result.getIn(['c', '_e'])).to.eql(undefined);
      expect(result.getIn(['c']).size).to.eql(1);
    });

    it('can ignore Set entries', function() {
      var input = Immutable.OrderedSet.of(1, 2, 3, 3, 'a');
      filter = transit.withFilter(function(val) {
        return typeof val === 'number';
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(3);
    });

    it('can ignore Stack entries', function() {
      var input = Immutable.Stack.of(1, 2, 3, 'a');
      filter = transit.withFilter(function(val) {
        return typeof val === 'number';
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(3);
    });

    it('can ignore OrderedSet entries', function() {
      var input = Immutable.Set.of(1, 2, 3, 3, 'a');
      filter = transit.withFilter(function(val) {
        return typeof val === 'number';
      });
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(3);
    });

    it('can ignore List entries', function() {
      var input = Immutable.List.of(1, 2, 3, 3, 'a');
      var result = filter.fromJSON(filter.toJSON(input));
      expect(result.includes('a')).to.eql(false);
      expect(result.size).to.eql(4);
    });

    it('can ignore Maps nested in Records', function() {
      var MyRecord = Immutable.Record({
        a: null,
        _b: 'bar'
      }, 'myRecord');

      var input = new MyRecord({a: Immutable.Map({_c: 1, d: 2}), _b: 'baz' });
      var recordFilter = transit
                          .withRecords([MyRecord])
                          .withFilter(filterFunction);

      var result = recordFilter.fromJSON(recordFilter.toJSON(input));

      expect(result.getIn(['a', 'd'])).to.eql(2);
      expect(result.getIn(['a', '_c'])).to.eql(undefined);
      expect(result.get('a').size).to.eql(1);
      expect(result.get('_b')).to.eql('baz');
    });

    it('should use missing-record-handler combined with filter', function() {
      var FooRecord = Immutable.Record({
        a: 1,
        b: 2,
      }, 'foo');

      var BarRecord = Immutable.Record({
        c: '1',
        d: '2'
      }, 'bar');

      var input = new Immutable.Map({
        _bar: new BarRecord(),
        foo: new FooRecord({
          a: 3,
          b: 4
        })
      });

      var missingRecordHandler = function(n, v) {
        switch (n) {
        case 'foo':
          return new BarRecord({c: v.a, d: v.b});
        default:
          return null;
        }
      };

      var recordFilter = transit
                          .withRecords([FooRecord, BarRecord])
                          .withFilter(filterFunction);
      var json = recordFilter.toJSON(input);
      recordFilter = transit
                      .withRecords([BarRecord], missingRecordHandler)
                      .withFilter(filterFunction);

      var result = recordFilter.fromJSON(json);

      expect(result.get('foo').c).to.eql(3);
      expect(result.get('foo').d).to.eql(4);
      expect(result.get('_bar')).to.eql(undefined);
    });

  });

  describe("withExtraHandlers", function() {
    function Point2d(x, y) { this.x = x; this.y = y; }
    function Point3d(x, y, z) { this.x = x; this.y = y; this.z = z; }
    var transitX;
    before(function() {
      transitX = transit.withExtraHandlers([
        {
          tag: "2d", class: Point2d,
          write: function(val) { return [val.x, val.y]; },
          read: function(rep) { return new Point2d(rep[0], rep[1]); }
        },
        {
          tag: "3d", class: Point3d,
          write: function(val) { return {x: val.x, y: val.y, z: val.z}; },
          read: function(rep) { return new Point3d(rep.x, rep.y, rep.z); }
        }
      ]);
    });
    var value = Immutable.Map.of(
      123, new Point2d(3, 5),
      "co-ords", Immutable.List.of(new Point3d(1, 2, 3), new Point3d(4, 5, 6))
    );

    it('should encode into json', function() {
      var json = transitX.toJSON(value);
      expect(json).to.be.a('string');
      expect(JSON.parse(json)).to.not.eql(null);
    });
    it('should round-trip', function() {
      var roundTrip = transitX.fromJSON(transitX.toJSON(value));
      expect(roundTrip).to.be.an.instanceof(Immutable.Map);

      var point2 = roundTrip.get(123);
      expect(point2).to.be.an.instanceof(Point2d);
      expect(point2).to.have.property("x", 3);
      expect(point2).to.have.property("y", 5);

      var point3a = roundTrip.getIn(["co-ords", 0]);
      expect(point3a).to.be.an.instanceof(Point3d);
      expect(point3a).to.have.property("x", 1);
      expect(point3a).to.have.property("y", 2);
      expect(point3a).to.have.property("z", 3);

      var point3b = roundTrip.getIn(["co-ords", 1]);
      expect(point3b).to.be.an.instanceof(Point3d);
      expect(point3b).to.have.property("x", 4);
      expect(point3b).to.have.property("y", 5);
      expect(point3b).to.have.property("z", 6);
    });

    describe("argument checking", function() {
      function makeExtra(override) {
        function ABC() {}
        var extra = {
          tag: "abc", class: ABC,
          read: function(rep) { return ABC(rep); },
          write: function(v) { return v * 0; }
        };
        Object.keys(override || {}).forEach(function(key) {
          extra[key] = override[key];
        });
        return extra;
      }
      it("should check for non-array", function() {
        expect(function() {
          transit.withExtraHandlers({});
        }).to.throw();
      });
      it("should check for string tag", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra(),
            makeExtra({tag: 123})
          ]);
        }).to.throw();
      });
      it("should check for class function", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra({class: "blah"})
          ]);
        }).to.throw();
      });
      it("should check for write function", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra({write: [1, 2, 3]})
          ]);
        }).to.throw();
      });
      it("should check for read function", function() {
        expect(function() {
          transit.withExtraHandlers([
            makeExtra({read: {nope: "not this"}})
          ]);
        }).to.throw();
      });
    });
  });

  describe('Unknown Input', function() {
    it('fails when an unrecognized object is passed', function() {
      var MyObject = function() {};
      var MyObjectInstance = new MyObject();

      expect(function() {
        transit.toJSON(MyObjectInstance);
      }).to.throw();
    });
  });

});
<|endoftext|>


<commit_before>var should     = require('should'),
    dirEqual   = require('assert-dir-equal'),
    rm         = require('rimraf').sync,
    path       = require('path'),
    Metalsmith = require('metalsmith');

require('mocha');

function msFactory(dir, plugins, done) {

    var ms = Metalsmith(path.join(__dirname, 'fixtures/src'));

    ms.source(dir);

    ms.clean(false);

    //each(plugins, function(plugin) {
        //ms.use(plugin.fn(plugin.opts));
    //});
    console.log(Object.keys(plugins));
    plugins.forEach(function(plugin) {
      ms.use(plugin.fn(plugin.opts));
    });

    ms.destination('../../tmp');

    ms.build(function(err) {
        if (err) { throw err; }
        done();
    });
}

describe('metalsmith flexible shortcodes', function() {

    beforeEach(function() {
        rm(path.join(__dirname, 'tmp'));
    });

    it('simple self closing shortcodes', function(done) {
        msFactory('simple-self-closing', [{
            opts: {
                shortcodes: {
                    makro: function() {
                        return 'I\'m replaced :)';
                    }
                }
            },
            fn: require('..')
        },
        {
            opts: {},
            fn: require('metalsmith-markdown')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/simple-self-closing'));
            done();
        });
    });

    it('simple enclosing shortcodes', function(done) {
        msFactory('simple-enclosing', [{
            opts: {
                gfm: true
            },
            fn: require('metalsmith-markdown')
        },
        {
            opts: {
                shortcodes: {
                    div: function(str) {
                        return '
\n' + str + '\n
';
                    }
                },
                clean: true
            },
            fn: require('..')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/simple-enclosing'));
            done();
        });
    });

    it('use file metadata', function(done) {
        msFactory('metadata-file', [{
            opts: {
                shortcodes: {
                    'var': function(str, params, data) {
                        for (var name in params) {
                            return data[name];
                        }
                    }
                },
                clean: true
            },
            fn: require('..')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/metadata-file'));
            done();
        });
    });

    it('use global metadata', function(done) {
        msFactory('metadata-global', [{
            opts: {},
            fn: function() {
                return function(files, metalsmith, done) {
                    metalsmith.metadata({
                        globalTest: 'Hello'
                    });
                    done();
                };
            }
        },
        {
            opts: {
                shortcodes: {
                    'var': function(str, params, data) {
                        for (var name in params) {
                            return data[name];
                        }
                    }
                },
                clean: true
            },
            fn: require('..')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/metadata-file'));
            done();
        });
    });

});
<commit_msg>Remove old code and dev logging<commit_after>var should     = require('should'),
    dirEqual   = require('assert-dir-equal'),
    rm         = require('rimraf').sync,
    path       = require('path'),
    Metalsmith = require('metalsmith');

require('mocha');

function msFactory(dir, plugins, done) {

    var ms = Metalsmith(path.join(__dirname, 'fixtures/src'));

    ms.source(dir);

    ms.clean(false);

    plugins.forEach(function(plugin) {
      ms.use(plugin.fn(plugin.opts));
    });

    ms.destination('../../tmp');

    ms.build(function(err) {
        if (err) { throw err; }
        done();
    });
}

describe('metalsmith flexible shortcodes', function() {

    beforeEach(function() {
        rm(path.join(__dirname, 'tmp'));
    });

    it('simple self closing shortcodes', function(done) {
        msFactory('simple-self-closing', [{
            opts: {
                shortcodes: {
                    makro: function() {
                        return 'I\'m replaced :)';
                    }
                }
            },
            fn: require('..')
        },
        {
            opts: {},
            fn: require('metalsmith-markdown')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/simple-self-closing'));
            done();
        });
    });

    it('simple enclosing shortcodes', function(done) {
        msFactory('simple-enclosing', [{
            opts: {
                gfm: true
            },
            fn: require('metalsmith-markdown')
        },
        {
            opts: {
                shortcodes: {
                    div: function(str) {
                        return '
\n' + str + '\n
';
                    }
                },
                clean: true
            },
            fn: require('..')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/simple-enclosing'));
            done();
        });
    });

    it('use file metadata', function(done) {
        msFactory('metadata-file', [{
            opts: {
                shortcodes: {
                    'var': function(str, params, data) {
                        for (var name in params) {
                            return data[name];
                        }
                    }
                },
                clean: true
            },
            fn: require('..')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/metadata-file'));
            done();
        });
    });

    it('use global metadata', function(done) {
        msFactory('metadata-global', [{
            opts: {},
            fn: function() {
                return function(files, metalsmith, done) {
                    metalsmith.metadata({
                        globalTest: 'Hello'
                    });
                    done();
                };
            }
        },
        {
            opts: {
                shortcodes: {
                    'var': function(str, params, data) {
                        for (var name in params) {
                            return data[name];
                        }
                    }
                },
                clean: true
            },
            fn: require('..')
        }], function() {
            dirEqual(path.join(__dirname, 'tmp'), path.join(__dirname, 'fixtures/expected/metadata-file'));
            done();
        });
    });

});
<|endoftext|>