<commit_before>var fs = require('fs');
var kss = require('kss');
var kssJadeGenerator = require('kss-jade-generator');
var path = require('path');
var assign = require('object-assign');
var through = require('through');
var PluginError = require('gulp-util').PluginError;

var PLUGIN_NAME = 'gulp-kss-jade';

module.exports = function(opt) {

  var firstFile = null;
  var buffer = [];
  var cache = {partial: {}};
  var templatePath;
  var template;
  var homepage;
  var destination = null;
  var source = null;
  var defaults = {
    templatePath: null,
    template: null,
    mask: {},
    markdown: true,
    multiline: true,
    typos: false,
    custom: [],
    helpers: '',
    css: [],
    js: [],
  };

  opt = assign(defaults, opt);
  opt.templatePath ?
    templatePath = path.resolve(process.cwd() + '/' + opt.templatePath) :
    new PluginError(PLUGIN_NAME,  'No templatePath provided. Please provide a templatePath.');

  opt.template ?
    template = fs.readFileSync(templatePath + '/' + opt.template, 'utf8') :
    new PluginError(PLUGIN_NAME,  'No template provided. Please provide a template.');

  opt.destination ?
    destination = path.resolve(process.cwd() + '/' + opt.destination) :
    new PluginError(PLUGIN_NAME,  'No destination provided. Please provide a destination.');

  opt.homepage ?
    homepage = opt.homepage :
    new PluginError(PLUGIN_NAME,  'No homepage provided. Please provide a homepage.');

  opt.source && Array.isArray(opt.source) ?
    source = opt.source.map((src) => path.resolve(process.cwd() + '/' + src)) :
    new PluginError(PLUGIN_NAME,  'No source provided. Please provide a source.');

  /* Is called for each file and writes all files to buffer */
  function bufferContents(file) {
    if (file.isNull()) return; // ignore
    if (file.isStream()) return new PluginError(PLUGIN_NAME,  'Streaming not supported');

    if (!firstFile) firstFile = file;
    buffer.push(file.contents.toString('utf8'));
  }

  function processKss() {
    var _this = this;

    kss.parse(buffer, opt, function(err, styleguide) {
      err ? new PluginError(PLUGIN_NAME,  'Streaming not supported') : 0;

      kssJadeGenerator.init({
        source: source,
        destination: destination,
        template: template,
        templatePath: templatePath,
        homepage: homepage,
        helpers: [],
        css: [],
        js: [],
      });

      kssJadeGenerator.generate(styleguide);

    });
  }

  return through(bufferContents, processKss);
};
<commit_msg>update<commit_after>var fs = require('fs');
var kss = require('kss');
var kssJadeGenerator = require('kss-jade-generator');
var path = require('path');
var assign = require('object-assign');
var through = require('through');
var PluginError = require('gulp-util').PluginError;

var PLUGIN_NAME = 'gulp-kss-jade';

module.exports = function(opt) {

  var firstFile = null;
  var buffer = [];
  var cache = {partial: {}};
  var templatePath;
  var template;
  var homepage;
  var destination = null;
  var source = null;
  var defaults = {
    templatePath: null,
    template: null,
    mask: {},
    markdown: true,
    multiline: true,
    typos: false,
    custom: [],
    helpers: '',
    css: [],
    js: [],
  };

  opt = assign(defaults, opt);
  opt.templatePath ?
    templatePath = path.resolve(process.cwd() + '/' + opt.templatePath) :
    new PluginError(PLUGIN_NAME,  'No templatePath provided. Please provide a templatePath.');

  opt.template ?
    template = fs.readFileSync(templatePath + '/' + opt.template, 'utf8') :
    new PluginError(PLUGIN_NAME,  'No template provided. Please provide a template.');

  opt.destination ?
    destination = path.resolve(process.cwd() + '/' + opt.destination) :
    new PluginError(PLUGIN_NAME,  'No destination provided. Please provide a destination.');

  opt.homepage ?
    homepage = opt.homepage :
    new PluginError(PLUGIN_NAME,  'No homepage provided. Please provide a homepage.');

  opt.source && Array.isArray(opt.source) ?
    source = opt.source.map((src) => path.resolve(process.cwd() + '/' + src)) :
    new PluginError(PLUGIN_NAME,  'No source provided. Please provide a source.');

  /* Is called for each file and writes all files to buffer */
  function bufferContents(file, enc, cb) {
    if (file.isNull()) return; // ignore
    if (file.isStream()) return new PluginError(PLUGIN_NAME,  'Streaming not supported');

    if (!firstFile) firstFile = file;
    buffer.push(file.contents.toString('utf8'));
  }

  function processKss(file, enc, cb) {
    var _this = this;

    kss.parse(buffer, opt, function(err, styleguide) {
      err ? new PluginError(PLUGIN_NAME,  'Streaming not supported') : 0;

      kssJadeGenerator.init({
        source: source,
        destination: destination,
        template: template,
        templatePath: templatePath,
        homepage: homepage,
        helpers: [],
        css: [],
        js: [],
      });

      kssJadeGenerator.generate(styleguide);
      cb();
    });
  }

  return through(bufferContents, processKss);
};
<|endoftext|>


<commit_before>/* eslint-env jest */

'use strict'

const Vue = require('vue/dist/vue.js')
const VueRx = require('../dist/vue-rx.js')

// library
const Observable = require('rxjs/Observable').Observable
const Subject = require('rxjs/Subject').Subject
const Subscription = require('rxjs/Subscription').Subscription
require('rxjs/add/observable/fromEvent')
require('rxjs/add/operator/share')

// user
require('rxjs/add/operator/map')
require('rxjs/add/operator/startWith')
require('rxjs/add/operator/scan')
require('rxjs/add/operator/pluck')
require('rxjs/add/operator/merge')

const miniRx = {
  Observable,
  Subscription,
  Subject
}

Vue.config.productionTip = false
Vue.use(VueRx, miniRx)

const nextTick = Vue.nextTick

function mock () {
  let observer
  const observable = Observable.create(_observer => {
    observer = _observer
  })
  return {
    ob: observable,
    next: val => observer.next(val)
  }
}

function trigger (target, event) {
  var e = document.createEvent('HTMLEvents')
  e.initEvent(event, true, true)
  target.dispatchEvent(e)
}

function click (target) {
  trigger(target, 'click')
}

test('expose $observables', () => {
  const { ob, next } = mock()

  const vm = new Vue({
    subscriptions: {
      hello: ob.startWith(0)
    }
  })

  const results = []
  vm.$observables.hello.subscribe(val => {
    results.push(val)
  })

  next(1)
  next(2)
  next(3)
  expect(results).toEqual([0, 1, 2, 3])
})

test('bind subscriptions to render', done => {
  const { ob, next } = mock()

  const vm = new Vue({
    subscriptions: {
      hello: ob.startWith('foo')
    },
    render (h) {
      return h('div', this.hello)
    }
  }).$mount()

  expect(vm.$el.textContent).toBe('foo')

  next('bar')
  nextTick(() => {
    expect(vm.$el.textContent).toBe('bar')
    done()
  })
})

test('subscriptions() has access to component state', () => {
  const { ob } = mock()

  const vm = new Vue({
    data: {
      foo: 'FOO'
    },
    props: ['bar'],
    propsData: {
      bar: 'BAR'
    },
    subscriptions () {
      return {
        hello: ob.startWith(this.foo + this.bar)
      }
    },
    render (h) {
      return h('div', this.hello)
    }
  }).$mount()

  expect(vm.$el.textContent).toBe('FOOBAR')
})

test('v-stream directive (basic)', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <button v-stream:click="click$">+</button>

    `,
    domStreams: ['click$'],
    subscriptions () {
      return {
        count: this.click$.map(() => 1)
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    done()
  })
})

test('v-stream directive (with .native modify)', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <my-button v-stream:click.native="clickNative$">+</my-button>
        <my-button v-stream:click="click$">-</my-button>

    `,
    components: {
      myButton: {
        template: '<button>MyButton</button>'
      }
    },
    domStreams: ['clickNative$', 'click$'],
    subscriptions () {
      return {
        count: this.click$.map(() => -1)
          .merge(this.clickNative$.map(() => 1))
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    done()
  })
})

test('v-stream directive (with data)', done => {
  const vm = new Vue({
    data: {
      delta: -1
    },
    template: `

        {{ count }}
        <button v-stream:click="{ subject: click$, data: delta }">+</button>

    `,
    domStreams: ['click$'],
    subscriptions () {
      return {
        count: this.click$.pluck('data')
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('-1')
    vm.delta = 1
    nextTick(() => {
      click(vm.$el.querySelector('button'))
      nextTick(() => {
        expect(vm.$el.querySelector('span').textContent).toBe('0')
        done()
      })
    })
  })
})

test('v-stream directive (multiple bindings on same node)', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <button
          v-stream:click="{ subject: plus$, data: 1 }"
          v-stream:keyup="{ subject: plus$, data: -1 }">+</button>

    `,
    domStreams: ['plus$'],
    subscriptions () {
      return {
        count: this.plus$.pluck('data')
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    trigger(vm.$el.querySelector('button'), 'keyup')
    nextTick(() => {
      expect(vm.$el.querySelector('span').textContent).toBe('0')
      done()
    })
  })
})

test('$fromDOMEvent()', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <button>+</button>

    `,
    subscriptions () {
      const click$ = this.$fromDOMEvent('button', 'click')
      return {
        count: click$.map(() => 1)
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  document.body.appendChild(vm.$el)
  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    done()
  })
})

test('$watchAsObservable()', done => {
  const vm = new Vue({
    data: {
      count: 0
    }
  })

  const results = []
  vm.$watchAsObservable('count').subscribe(change => {
    results.push(change)
  })

  vm.count++
  nextTick(() => {
    expect(results).toEqual([{ newValue: 1, oldValue: 0 }])
    vm.count++
    nextTick(() => {
      expect(results).toEqual([
        { newValue: 1, oldValue: 0 },
        { newValue: 2, oldValue: 1 }
      ])
      done()
    })
  })
})

test('$subscribeTo()', () => {
  const { ob, next } = mock()
  const results = []
  const vm = new Vue({
    created () {
      this.$subscribeTo(ob, count => {
        results.push(count)
      })
    }
  })

  next(1)
  expect(results).toEqual([1])

  vm.$destroy()
  next(2)
  expect(results).toEqual([1]) // should not trigger anymore
})

test('$eventToObservable()', done => {
  let calls = 0
  const vm = new Vue({
    created () {
      this.$eventToObservable('ping')
        .subscribe(function (event) {
          expect(event.name).toEqual('ping')
          expect(event.msg).toEqual('ping message')
          calls++
        })
    }
  })
  vm.$emit('ping', 'ping message')

  nextTick(() => {
    vm.$destroy()
    // Should not emit
    vm.$emit('pong', 'pong message')
    expect(calls).toEqual(1)
    done()
  })
})

test('$eventToObservable() with lifecycle hooks', done => {
  const vm = new Vue({
    created () {
      this.$eventToObservable('hook:beforeDestroy')
        .subscribe(function (event) {
          done(event)
        })
    }
  })
  nextTick(() => {
    vm.$destroy()
  })
})

test('$createObservableMethod() with no context', done => {
  const vm = new Vue({
    created () {
      this.$createObservableMethod('add')
        .subscribe(function (param) {
          expect(param).toEqual('hola')
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('hola')
  })
})

test('$createObservableMethod() with muli params & context', done => {
  const vm = new Vue({
    created () {
      this.$createObservableMethod('add', true)
        .subscribe(function (param) {
          expect(param[0]).toEqual('hola')
          expect(param[1]).toEqual('mundo')
          expect(param[2]).toEqual(vm)
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('hola', 'mundo')
  })
})

test('observableMethods mixin', done => {
  const vm = new Vue({
    observableMethods: ['add'],
    created () {
      this.add$
        .subscribe(function (param) {
          expect(param[0]).toEqual('Qué')
          expect(param[1]).toEqual('tal')
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('Qué', 'tal')
  })
})

test('observableMethods mixin', done => {
  const vm = new Vue({
    observableMethods: { 'add': 'plus$' },
    created () {
      this.plus$
        .subscribe(function (param) {
          expect(param[0]).toEqual('Qué')
          expect(param[1]).toEqual('tal')
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('Qué', 'tal')
  })
})
<commit_msg>fix(test):  make test in .native modifier more accurate<commit_after>/* eslint-env jest */

'use strict'

const Vue = require('vue/dist/vue.js')
const VueRx = require('../dist/vue-rx.js')

// library
const Observable = require('rxjs/Observable').Observable
const Subject = require('rxjs/Subject').Subject
const Subscription = require('rxjs/Subscription').Subscription
require('rxjs/add/observable/fromEvent')
require('rxjs/add/operator/share')

// user
require('rxjs/add/operator/map')
require('rxjs/add/operator/startWith')
require('rxjs/add/operator/scan')
require('rxjs/add/operator/pluck')
require('rxjs/add/operator/merge')
require('rxjs/add/operator/filter')

const miniRx = {
  Observable,
  Subscription,
  Subject
}

Vue.config.productionTip = false
Vue.use(VueRx, miniRx)

const nextTick = Vue.nextTick

function mock () {
  let observer
  const observable = Observable.create(_observer => {
    observer = _observer
  })
  return {
    ob: observable,
    next: val => observer.next(val)
  }
}

function trigger (target, event) {
  var e = document.createEvent('HTMLEvents')
  e.initEvent(event, true, true)
  target.dispatchEvent(e)
}

function click (target) {
  trigger(target, 'click')
}

test('expose $observables', () => {
  const { ob, next } = mock()

  const vm = new Vue({
    subscriptions: {
      hello: ob.startWith(0)
    }
  })

  const results = []
  vm.$observables.hello.subscribe(val => {
    results.push(val)
  })

  next(1)
  next(2)
  next(3)
  expect(results).toEqual([0, 1, 2, 3])
})

test('bind subscriptions to render', done => {
  const { ob, next } = mock()

  const vm = new Vue({
    subscriptions: {
      hello: ob.startWith('foo')
    },
    render (h) {
      return h('div', this.hello)
    }
  }).$mount()

  expect(vm.$el.textContent).toBe('foo')

  next('bar')
  nextTick(() => {
    expect(vm.$el.textContent).toBe('bar')
    done()
  })
})

test('subscriptions() has access to component state', () => {
  const { ob } = mock()

  const vm = new Vue({
    data: {
      foo: 'FOO'
    },
    props: ['bar'],
    propsData: {
      bar: 'BAR'
    },
    subscriptions () {
      return {
        hello: ob.startWith(this.foo + this.bar)
      }
    },
    render (h) {
      return h('div', this.hello)
    }
  }).$mount()

  expect(vm.$el.textContent).toBe('FOOBAR')
})

test('v-stream directive (basic)', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <button v-stream:click="click$">+</button>

    `,
    domStreams: ['click$'],
    subscriptions () {
      return {
        count: this.click$.map(() => 1)
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    done()
  })
})

test('v-stream directive (with .native modify)', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <my-button id="btn-native" v-stream:click.native="clickNative$">+</my-button>
        <my-button id="btn" v-stream:click="click$">-</my-button>

    `,
    components: {
      myButton: {
        template: '<button>MyButton</button>'
      }
    },
    domStreams: ['clickNative$', 'click$'],
    subscriptions () {
      return {
        count: this.clickNative$
          .filter(e => e.event.target && e.event.target.id === 'btn-native')
          .map(() => 1)
          .merge(this.click$.map(() => -1))
          .merge()
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('#btn-native'))
  click(vm.$el.querySelector('#btn'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    done()
  })
})

test('v-stream directive (with data)', done => {
  const vm = new Vue({
    data: {
      delta: -1
    },
    template: `

        {{ count }}
        <button v-stream:click="{ subject: click$, data: delta }">+</button>

    `,
    domStreams: ['click$'],
    subscriptions () {
      return {
        count: this.click$.pluck('data')
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('-1')
    vm.delta = 1
    nextTick(() => {
      click(vm.$el.querySelector('button'))
      nextTick(() => {
        expect(vm.$el.querySelector('span').textContent).toBe('0')
        done()
      })
    })
  })
})

test('v-stream directive (multiple bindings on same node)', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <button
          v-stream:click="{ subject: plus$, data: 1 }"
          v-stream:keyup="{ subject: plus$, data: -1 }">+</button>

    `,
    domStreams: ['plus$'],
    subscriptions () {
      return {
        count: this.plus$.pluck('data')
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    trigger(vm.$el.querySelector('button'), 'keyup')
    nextTick(() => {
      expect(vm.$el.querySelector('span').textContent).toBe('0')
      done()
    })
  })
})

test('$fromDOMEvent()', done => {
  const vm = new Vue({
    template: `

        {{ count }}
        <button>+</button>

    `,
    subscriptions () {
      const click$ = this.$fromDOMEvent('button', 'click')
      return {
        count: click$.map(() => 1)
          .startWith(0)
          .scan((total, change) => total + change)
      }
    }
  }).$mount()

  document.body.appendChild(vm.$el)
  expect(vm.$el.querySelector('span').textContent).toBe('0')
  click(vm.$el.querySelector('button'))
  nextTick(() => {
    expect(vm.$el.querySelector('span').textContent).toBe('1')
    done()
  })
})

test('$watchAsObservable()', done => {
  const vm = new Vue({
    data: {
      count: 0
    }
  })

  const results = []
  vm.$watchAsObservable('count').subscribe(change => {
    results.push(change)
  })

  vm.count++
  nextTick(() => {
    expect(results).toEqual([{ newValue: 1, oldValue: 0 }])
    vm.count++
    nextTick(() => {
      expect(results).toEqual([
        { newValue: 1, oldValue: 0 },
        { newValue: 2, oldValue: 1 }
      ])
      done()
    })
  })
})

test('$subscribeTo()', () => {
  const { ob, next } = mock()
  const results = []
  const vm = new Vue({
    created () {
      this.$subscribeTo(ob, count => {
        results.push(count)
      })
    }
  })

  next(1)
  expect(results).toEqual([1])

  vm.$destroy()
  next(2)
  expect(results).toEqual([1]) // should not trigger anymore
})

test('$eventToObservable()', done => {
  let calls = 0
  const vm = new Vue({
    created () {
      this.$eventToObservable('ping')
        .subscribe(function (event) {
          expect(event.name).toEqual('ping')
          expect(event.msg).toEqual('ping message')
          calls++
        })
    }
  })
  vm.$emit('ping', 'ping message')

  nextTick(() => {
    vm.$destroy()
    // Should not emit
    vm.$emit('pong', 'pong message')
    expect(calls).toEqual(1)
    done()
  })
})

test('$eventToObservable() with lifecycle hooks', done => {
  const vm = new Vue({
    created () {
      this.$eventToObservable('hook:beforeDestroy')
        .subscribe(function (event) {
          done(event)
        })
    }
  })
  nextTick(() => {
    vm.$destroy()
  })
})

test('$createObservableMethod() with no context', done => {
  const vm = new Vue({
    created () {
      this.$createObservableMethod('add')
        .subscribe(function (param) {
          expect(param).toEqual('hola')
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('hola')
  })
})

test('$createObservableMethod() with muli params & context', done => {
  const vm = new Vue({
    created () {
      this.$createObservableMethod('add', true)
        .subscribe(function (param) {
          expect(param[0]).toEqual('hola')
          expect(param[1]).toEqual('mundo')
          expect(param[2]).toEqual(vm)
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('hola', 'mundo')
  })
})

test('observableMethods mixin', done => {
  const vm = new Vue({
    observableMethods: ['add'],
    created () {
      this.add$
        .subscribe(function (param) {
          expect(param[0]).toEqual('Qué')
          expect(param[1]).toEqual('tal')
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('Qué', 'tal')
  })
})

test('observableMethods mixin', done => {
  const vm = new Vue({
    observableMethods: { 'add': 'plus$' },
    created () {
      this.plus$
        .subscribe(function (param) {
          expect(param[0]).toEqual('Qué')
          expect(param[1]).toEqual('tal')
          done(param)
        })
    }
  })
  nextTick(() => {
    vm.add('Qué', 'tal')
  })
})
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var dart2jsaas = require('dart2jsaas');

var format = require('util').format;
var areEqual = require('./util').areEqual;
var random = function() {
  return Math.round(Math.random() * 10000);
};

var DART_ADAPTER_TPL = fs.readFileSync(__dirname + '/../static/adapter.dart.tmpl').toString();
var TEMP_DIR = process.env.TMPDIR || process.env.TMP || process.env.TEMP || '/tmp';
var DART_IMPORT = 'import "%s" as %s;';

var initDartUnittest = function(emitter, /* config.files */ files, /* config.basePath */ basePath,
  /* config.karmaDartImports */ customImports, /* config.hostname */ hostname, /* config.port */ port,
  logger, customFileHandlers) {

  var log = logger.create('dart');

  var dart2js = dart2jsaas.setupSystem({
    fetcherBaseUrl: 'http://' + hostname + ':' + port + '/base/'
  });

  customFileHandlers.push({
    urlRegex: /.*dart.js(\?[0-9]*)?$/,
    handler: function(request, response, fa, fb, basePath) {
      var base = '/base/';
      dart2js(request.url.replace(base, '').replace(/\.js(\?[0-9]*)?$/, '')).then(function(outjs) {
        response.writeHead(200);
        response.end(outjs);
      });
    }
  });

  customFileHandlers.push({
    urlRegex: /^\/packages\/.*$/,
    handler: function(request, response, fa, fb, basePath) {
      var url = request.url;
      var path = url.indexOf('?') > -1 ? url.substring(0, url.indexOf('?')) : url;
      var contets = fs.readFileSync(basePath + path);
      response.writeHead(200);
      response.end(contets);
    }
  });

  // include the adapter.js
  files.unshift({pattern: __dirname + '/adapter.js', included: true, served: true, watched: false});

  var adapterImports = {
    unittest: 'package:unittest/unittest.dart',
    js: 'package:js/js.dart'
  };

  if (customImports) {
    Object.keys(customImports).forEach(function(library) {
      adapterImports[library] = customImports[library];
    });
  }

  var adapterImportsCode = Object.keys(adapterImports).map(function(library) {
    return format(DART_IMPORT, adapterImports[library], library);
  }).join('\n');

  var randomUid = random();

  var dartAdapterFile = {
    path: '/__adapter_dart_unittest.dart',
    contentPath: path.normalize(TEMP_DIR + '/karma-dart-adapter-' + randomUid + '.dart'),
    isUrl: true,
    mtime: new Date()
  };

  var previousDartTestFiles = [];

  emitter.on('file_list_modified', function(filesPromise) {
    filesPromise.then(function(files) {
      var dartTestFiles = [];
      var dartTestFilePaths = [];
      var includedFiles = [dartAdapterFile];

      // All *.dart included files are considered to be test libraries.
      files.included.forEach(function(file) {
        if (path.extname(file.path) === '.dart') {
          dartTestFiles.push(file);
          dartTestFilePaths.push(file.path);
        } else {
          includedFiles.push(file);
        }
      });

      // filtered (without dart test files, the adapter will include them)
      files.included = includedFiles;
      files.served.push(dartAdapterFile);

      // Did the list of included test files changed ?
      // If so, update the adapter files, which contains all the imports.
      if (!areEqual(previousDartTestFiles, dartTestFilePaths)) {
        log.debug('List of dart files changed, updating the list of imports.');

        var testImports = [];
        var mainCalls = [];
        dartTestFiles.forEach(function(dartFile, index) {
          var filePath = dartFile.path;
          if (filePath.indexOf(basePath) === 0) {
            filePath = '/base/' + filePath.substr(basePath.length + 1);
          } else {
            filePath = 'absolute' + filePath;
          }
          testImports.push(format(DART_IMPORT, filePath, 'test_' + index));
          mainCalls.push(format('  test_%s.main();', index));
        });

        // TODO(vojta): skip this writeFileSync() once we can use in-memory cache (file.content)
        fs.writeFileSync(dartAdapterFile.contentPath, DART_ADAPTER_TPL
            .replace('/*%ADAPTER_IMPORTS%*/', adapterImportsCode)
            .replace('/*%TEST_IMPORTS%*/', testImports.join('\n'))
            .replace('/*%TEST_MAIN_CALLS%*/', mainCalls.join('\n')));

        dartAdapterFile.mtime = new Date();
        previousDartTestFiles = dartTestFilePaths;
      }
    });
  });
};

module.exports = {
  'framework:dart-unittest': ['factory', initDartUnittest]
};
<commit_msg>Update dart2jsaas loader to support Dart SDK 8.5<commit_after>var path = require('path');
var fs = require('fs');
var dart2jsaas = require('dart2jsaas');

var format = require('util').format;
var areEqual = require('./util').areEqual;
var random = function() {
  return Math.round(Math.random() * 10000);
};

var DART_ADAPTER_TPL = fs.readFileSync(__dirname + '/../static/adapter.dart.tmpl').toString();
var TEMP_DIR = process.env.TMPDIR || process.env.TMP || process.env.TEMP || '/tmp';
var DART_IMPORT = 'import "%s" as %s;';

var initDartUnittest = function(emitter, /* config.files */ files, /* config.basePath */ basePath,
  /* config.karmaDartImports */ customImports, /* config.hostname */ hostname, /* config.port */ port,
  logger, customFileHandlers) {

  var log = logger.create('dart');

  var dart2js = dart2jsaas.setupSystem({
    fetcherBaseUrl: 'http://' + hostname + ':' + port + '/'
  });

  customFileHandlers.push({
    urlRegex: /.*dart.js(\?[0-9]*)?$/,
    handler: function(request, response, fa, fb, basePath) {
      var url = request.url.substr(1);  // Drop the leading slash.

      dart2js(url.replace(/\.js(\?[0-9]*)?$/, '')).then(function(outjs) {
        response.writeHead(200);
        response.end(outjs);
      });
    }
  });

  customFileHandlers.push({
    urlRegex: /^\/packages\/.*$/,
    handler: function(request, response, fa, fb, basePath) {
      var url = request.url;
      var path = url.indexOf('?') > -1 ? url.substring(0, url.indexOf('?')) : url;
      var contets = fs.readFileSync(basePath + path);
      response.writeHead(200);
      response.end(contets);
    }
  });

  // include the adapter.js
  files.unshift({pattern: __dirname + '/adapter.js', included: true, served: true, watched: false});

  var adapterImports = {
    unittest: 'package:unittest/unittest.dart',
    js: 'package:js/js.dart'
  };

  if (customImports) {
    Object.keys(customImports).forEach(function(library) {
      adapterImports[library] = customImports[library];
    });
  }

  var adapterImportsCode = Object.keys(adapterImports).map(function(library) {
    return format(DART_IMPORT, adapterImports[library], library);
  }).join('\n');

  var randomUid = random();

  var dartAdapterFile = {
    path: '/__adapter_dart_unittest.dart',
    contentPath: path.normalize(TEMP_DIR + '/karma-dart-adapter-' + randomUid + '.dart'),
    isUrl: true,
    mtime: new Date()
  };

  var previousDartTestFiles = [];

  emitter.on('file_list_modified', function(filesPromise) {
    filesPromise.then(function(files) {
      var dartTestFiles = [];
      var dartTestFilePaths = [];
      var includedFiles = [dartAdapterFile];

      // All *.dart included files are considered to be test libraries.
      files.included.forEach(function(file) {
        if (path.extname(file.path) === '.dart') {
          dartTestFiles.push(file);
          dartTestFilePaths.push(file.path);
        } else {
          includedFiles.push(file);
        }
      });

      // filtered (without dart test files, the adapter will include them)
      files.included = includedFiles;
      files.served.push(dartAdapterFile);

      // Did the list of included test files changed ?
      // If so, update the adapter files, which contains all the imports.
      if (!areEqual(previousDartTestFiles, dartTestFilePaths)) {
        log.debug('List of dart files changed, updating the list of imports.');

        var testImports = [];
        var mainCalls = [];
        dartTestFiles.forEach(function(dartFile, index) {
          var filePath = dartFile.path;
          if (filePath.indexOf(basePath) === 0) {
            filePath = 'base/' + filePath.substr(basePath.length + 1);
          } else {
            filePath = 'absolute' + filePath;
          }
          testImports.push(format(DART_IMPORT, filePath, 'test_' + index));
          mainCalls.push(format('  test_%s.main();', index));
        });

        // TODO(vojta): skip this writeFileSync() once we can use in-memory cache (file.content)
        fs.writeFileSync(dartAdapterFile.contentPath, DART_ADAPTER_TPL
            .replace('/*%ADAPTER_IMPORTS%*/', adapterImportsCode)
            .replace('/*%TEST_IMPORTS%*/', testImports.join('\n'))
            .replace('/*%TEST_MAIN_CALLS%*/', mainCalls.join('\n')));

        dartAdapterFile.mtime = new Date();
        previousDartTestFiles = dartTestFilePaths;
      }
    });
  });
};

module.exports = {
  'framework:dart-unittest': ['factory', initDartUnittest]
};
<|endoftext|>


<commit_before>import React from 'react';
import {createRenderer} from 'react-addons-test-utils';
import assert from 'assert';

describe('streamComponent', function () {
	const streamComponent = require('../src').streamComponent;
	const shallowRenderer = createRenderer();

	it('should return a valid React component', function () {
		const Streamable = streamComponent('button', ['onClick']);
		shallowRenderer.render(<Streamable />);
		const result = shallowRenderer.getRenderOutput();

		assert.strictEqual(result.type, 'button', "is a button component");
	});

	it('should have an __eventStream property', function () {
		const Streamable = streamComponent('button', ['onClick']);
		assert.strictEqual(!!Streamable.__eventStream, true, "has __eventStream");
	});

	it('should have an onClick event handler', function () {
		const Streamable = streamComponent('button', ['onClick']);
		shallowRenderer.render(<Streamable />);
		const result = shallowRenderer.getRenderOutput();
		assert.strictEqual(!!result.props.onClick, true, "has onClick");
	});

	it('should emit a value on __eventStream when an event is triggered', function () {
		const Streamable = streamComponent('button', ['onClick']);
		shallowRenderer.render(<Streamable />);
		const result = shallowRenderer.getRenderOutput();

		Streamable.__eventStream.onValue((e) =>
			assert.deepEqual(e, { event: 'onClick', e: 'test event' }, "onClick")
		);
		result.props.onClick('test event');
	});
});

describe('getStream', function () {
	const getStream = require('../src').getStream;
	it('should return the __eventStream property set on an object', function () {
		const obj = {
			__eventStream: true
		};

		assert.strictEqual(getStream(obj), true, "__eventStream property");
	});
});
<commit_msg>test getStream -> fromComponent<commit_after>import React from 'react';
import {createRenderer} from 'react-addons-test-utils';
import assert from 'assert';

describe('streamComponent', function () {
	const streamComponent = require('../src').streamComponent;
	const shallowRenderer = createRenderer();

	it('should return a valid React component', function () {
		const Streamable = streamComponent('button', ['onClick']);
		shallowRenderer.render(<Streamable />);
		const result = shallowRenderer.getRenderOutput();

		assert.strictEqual(result.type, 'button', "is a button component");
	});

	it('should have an __eventStream property', function () {
		const Streamable = streamComponent('button', ['onClick']);
		assert.strictEqual(!!Streamable.__eventStream, true, "has __eventStream");
	});

	it('should have an onClick event handler', function () {
		const Streamable = streamComponent('button', ['onClick']);
		shallowRenderer.render(<Streamable />);
		const result = shallowRenderer.getRenderOutput();
		assert.strictEqual(!!result.props.onClick, true, "has onClick");
	});

	it('should emit a value on __eventStream when an event is triggered', function () {
		const Streamable = streamComponent('button', ['onClick']);
		shallowRenderer.render(<Streamable />);
		const result = shallowRenderer.getRenderOutput();

		Streamable.__eventStream.onValue((e) =>
			assert.deepEqual(e, { event: 'onClick', e: 'test event' }, "onClick")
		);
		result.props.onClick('test event');
	});
});

describe('fromComponent', function () {
	const fromComponent = require('../src').fromComponent;
	it('should return the __eventStream property set on an object', function () {
		const obj = {
			__eventStream: true
		};

		assert.strictEqual(fromComponent(obj), true, "__eventStream property");
	});
});
<|endoftext|>


<commit_before>
	/*Declaration of global variables.*/

	//The variables request and url are used in ajax functions
	var request,url;
	//Value=1 indicates 'SpecimenRequests' tab and value=2 indicates 'ArrayRequests' tab
	var pageDisplayed=1;

	/**
	 * This funciton is called on click of 'Create Array' button in the ArrayRequests.jsp.It redirects to SpecimenArray.jsp
	 */
	function gotoCreateArrayPage(arrayRowCounter)
	{
		var id  = "defineArrayName_" + arrayRowCounter;
		var arrayName = document.getElementById(id).value;
		var queryString = "?array=" + arrayName + "&operation=add&id=";
		var action = "CreateDefinedArray.do" + queryString;
		document.forms[0].action = action ;
	    document.forms[0].submit();
	}

	/**
	 * This function submits the form.(That is,data from both the RequestDetails.jsp and ArrayRequests.jsp)
	 */
	function submitPage()
	{
		document.forms[0].submit();
	}

	/**
	 * Function updateAllStatus() constructs the request url alongwith the required query string and calls the sendRequestForUpdateStatus() function.
	 * This is called to update statuses of the order items.
	 */
	function updateAllStatus()
	{
		var selectNext = document.getElementById('nextStatusId');
		selectedNextValue = selectNext.value;
		//Send request only if dropdown value is changed.
		if(selectNext.selectedIndex != 0 )
		{
			//Construst URL to send the request
			var queryString = "updateValue=" + selectedNextValue;
			url = "UpdateStatus.do?"+queryString;
			sendRequestForUpdateStatus();
		}
	}

	/**
	 * Function sendRequest() sends the GET request to the server.
	 */
	function sendRequestForUpdateStatus()
	{
		//Obtain XMLHttpRequest object
		request = newXMLHTTPReq();
		if(request)
		{
			//To update status of orderitems in Specimen Requests tab page
			if(pageDisplayed == 1)
			{
				request.onreadystatechange = handleResponse;
			}
			//To update status of defined array and existing array in Array Requests tab page
			else
			{
				request.onreadystatechange = handleResponseForArray;
			}
			try
			{
				request.open("GET", url, true);
				request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				request.send("");
			}
			catch(e)
			{}
		}
	}

	/**
	 * This function assigns the response to the select element in the ArrayRequests page
	 * (for defined arrays and existing arrays) when the response is ready.
	 */
	function handleResponseForArray()
	{
		if(request.readyState == 4)
		{
		   //Response is ready
			if(request.status == 200)
			{
				/* ',' seperates statuses of all defined arrays from existing arrays.
				 * The length of responseStringArray would be always 2.
				 * The first element of the array contains response string of the defined array statuses.
				 * The second element of the array contains response string of the existing array statuses.
				 */
				responseStringArray = parseResponseText(',');

				var selectId="";

				//Change status for Defined Arrays
				if(document.getElementById("definedArrayRows") != null)
					var num_rows_definedArray = document.getElementById("definedArrayRows").value;

				//Change status for Existing Arrays
				if(document.getElementById("numOfExistingArrays") != null)
					var num_rows_existingArray = document.getElementById("numOfExistingArrays").value;

				//';' seperates status of individual orderitems in the definedarrays
				definedArrayResponseStringArray = responseStringArray[0].split(';');

				//Set new values in the options
				setNewStatusValuesInOptionsArray("array_",num_rows_definedArray,definedArrayResponseStringArray);

				//Change status for Existing Arrays
				if(responseStringArray.length == 2)
				{
					//';' seperates status of indivudual existing arrays
					existingArrayResponseStringArray = responseStringArray[1].split(';');

					//Set new values in the options
					setNewStatusValuesInOptionsArray("existingArray_",num_rows_existingArray,existingArrayResponseStringArray);
				}
			}//End if(request.status == 200)
		}//End if(request.readyState == 4)
	}

	/**
	 * handleResponse() assigns the response to the select element when the response is ready and there is no error in the response.
	 */
	function handleResponse()
	{
		if(request.readyState == 4)
		{
			//Response is ready
			if(request.status == 200)
			{
				responseStringArray = parseResponseText(';');

				var tbodyId = document.getElementById('tbody');
				var num_rows = tbodyId.rows.length;				//responseStringArray.length==rows.length
				var selectId="";

				//Set new values in the options
				setNewStatusValuesInOptionsArray("select_",num_rows,responseStringArray);
			}//End if(request.status == 200)
		}//End if(request.readyState == 4)
	}

	/**
	 * Added by Ashish to update quantity for selected derived biospecimens.
	 */
	var id;
	function handleResponseForQty()
	{
		if(request.readyState == 4)
		{
			//Response is ready
			if(request.status == 200)
			{
				/* Response contains required output.
				 * Get the response from server.
				 */
				var responseString = request.responseText;
				var divId = "avaiQty" +id;
				document.getElementById(divId).innerHTML = responseString;
			}//End if(request.status == 200)
		}//End if(request.readyState == 4)
	}

	/**
	 *  This function updates the quantity for selected derived biospecimens (Added by Ashish)
	 */
	function updateQuantity(requestForId)
	{
		var sendRequestFor = 'updateQty';
		id = requestForId.substring(10);
		var selectNext = document.getElementById(requestForId);
		selectedNextValue = selectNext.value;
		//Construst URL to send the request
		var queryString = "selectedSpecimen=" + selectedNextValue+"&finalSpecimenListId=" + id;
		url = "UpdateQuantity.do?"+queryString;
		sendRequestForQuantity();
	}

	/**
	 * This function sends 'GET' request to the server for updating quantity (Added by Ashish)
	 */
	function sendRequestForQuantity()
	{
		request = newXMLHTTPReq();

		if(request)
		{
			request.onreadystatechange = handleResponseForQty;
			try
			{
				request.open("GET", url, true);
				request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				request.send("");
			}
			catch(e)
			{}
		}
	}

	/**
	 * Thisfunction expand/collapses block for rows in the Existing Array(ArrayRequests.jsp)
	 */
	function expandArrayBlock()
	{
		switchObj = document.getElementById('switchExistingArray');
		tbodyObj = document.getElementById('existingArrayId');
		switchBlock(switchObj,tbodyObj);
	}

	/**
	 * This function expand/collapses block for individual orderitems defined in an array(ArrayRequests.jsp)
	 */
	function expandOrderItemsInArray(rowid,arrayId)
	{
		var switchObj = document.getElementById('switchdefineArray' + rowid + '_array' + arrayId);
		var dataObj = document.getElementById('dataDefinedArray' + rowid + '_array' + arrayId);
		switchBlock(switchObj,dataObj);
	}

	/**
	 * This function expand/collapses block for individual orderitems defined in orderlist in RequestDetails.jsp
	 */
	function switchOrderList(rowid)
	{
		switchObj = document.getElementById('switch'+rowid);
		dataObj = document.getElementById('data'+rowid);
		switchBlock(switchObj,dataObj);
	}

	/**
	 * This function switches the block in the deifned arrays row
	 */
	function switchDefinedArrayBlock(rowid)
	{
		switchObj = document.getElementById('switchArray' + rowid);
		dataObj = document.getElementById('dataArray' + rowid);
		arrayHeaderObj = document.getElementById('headerArray' + rowid);
		btnCreateArrayObj = document.getElementById('btnCreateArray' + rowid);

		if(dataObj.style.display != 'none') //Clicked on - image
		{
			dataObj.style.display = 'none';
			arrayHeaderObj.style.display = 'none';
			btnCreateArrayObj.style.display = 'none';
			switchObj.innerHTML = '';
		}
		else
		{
			if(navigator.appName == "Microsoft Internet Explorer")
			{
				dataObj.style.display = 'block';
				arrayHeaderObj.style.display = 'block';
				btnCreateArrayObj.style.display = 'block';
			}
			else
			{
				dataObj.style.display = 'table-row';
				arrayHeaderObj.style.display = 'table-row';
				btnCreateArrayObj.style.display = 'table-row';
			}
			switchObj.innerHTML = '';
		}
	}

	/**
	 * This function switches the tab to SpecimenRequest Page (i.e,ArrayRequests.jsp)
	 */
	function gotoArrayRequestTab()
	{
		document.getElementById("tabIndexId").value=2;
		pageDisplayed=2;
		//Hide the table containing biospecimen  order items
		document.getElementById('table3_specimenDataTab').style.display="none";

		if(navigator.appName == "Microsoft Internet Explorer")
		{
			//Display the table containing ArrayRequests.jsp
			document.getElementById('table5_arrayDataTable').style.display="block";
			expandTableForIE();
		}
		else
		{
			//Display the table containing ArrayRequests.jsp
			document.getElementById('table5_arrayDataTable').style.display="table-row";
			expandTableForOtherBrowsers();
		}
		changeCssForTab('arrayRequestTab','specimenRequestTab');
	}

	/**
	 * This function switches the tab to SpecimenRequest Page (i.e, RequestDetails.jsp)
	 */
	function gotoSpecimenRequestTab()
	{
		document.getElementById("tabIndexId").value=1;
		pageDisplayed=1;
		//Hide the table containing ArrayRequests.jsp
		document.getElementById('table5_arrayDataTable').style.display="none";
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			//Display the table containing the data of RequestDetails.jsp
			document.getElementById('table3_specimenDataTab').style.display="block";
			expandTableForIE();
		}
		else
		{
			//Display the table containing the data of RequestDetails.jsp
			document.getElementById('table3_specimenDataTab').style.display="table-row";
			expandTableForOtherBrowsers();
		}
		changeCssForTab('specimenRequestTab','arrayRequestTab');
	}

	/**
	 * This function expands tables on both tabbed pages(i.e,Specimen Requests tab and Array Requests tab)
	 * when displayed on Microsoft IE browser
	 */
	function expandTableForIE()
	{
		//Display other tables required for both the tabbed pages
		document.getElementById('table4_pageFooter').style.display="block";
		document.getElementById('table2_TabPage').style.display="block";
		document.getElementById('table1_OrderRequestHeader').style.display="block";
	}

	/**
	 * This funciton expands tables on both tabbed pages(i.e,Specimen Requests tab and Array Requests tab)
	 * when displayed on Mozilla/NetScape or other browsers
	 */
	function expandTableForOtherBrowsers()
	{
		//Display other tables required for both the tabbed pages
		document.getElementById('table4_pageFooter').style.display="table-row";
		document.getElementById('table2_TabPage').style.display="table-row";
		document.getElementById('table1_OrderRequestHeader').style.display="table-row";
	}

	/**
	 * This function changes the css of the tab depending upon whether 'Specimen Requests' or 'Array Requests' tab
	 * was selected.
	 */
	function changeCssForTab(strSelectedTab,strUnSelectedTab)
	{
		var selectedTab = document.getElementById(strSelectedTab);
		var unSelectedTab = document.getElementById(strUnSelectedTab);

		selectedTab.onmouseover=null;
		selectedTab.onmouseout=null;
		selectedTab.className="tabMenuItemSelected";

		unSelectedTab.onmouseover=function() { changeMenuStyle(this,'tabMenuItemOver'),showCursor();};
		unSelectedTab.onmouseout=function() {changeMenuStyle(this,'tabMenuItem'),hideCursor();};
		unSelectedTab.className="tabMenuItem";
	}

	/**
	 * This function obtains responsetext from the request object and parses it with the given delimiter and returns a string array
	 */
	function parseResponseText(delimiter)
	{
		//Response contains required output.
		var responseString = request.responseText;
		var responseStringArray = new Array();

		//Get array values for each row.
		responseStringArray = responseString.split(delimiter);
		return responseStringArray;
	}

	/**
	 * This function sets the new status values in the options array
	 */
	function setNewStatusValuesInOptionsArray(strElement,rowCount,responseStringArray)
	{
		for(var counter=0;counter<rowCount;counter++)
		{
			strSelectElementId = strElement + counter;
			selectElementId = document.getElementById(strSelectElementId);
			optionStringArray = responseStringArray[counter].split('||');

			for(var x=0;x<optionStringArray.length-1;x++)
			{
				optionStrings = optionStringArray[x].split('|');
				//Set the text/value pair in options.
				selectElementId.options[x] = new Option(optionStrings[0],optionStrings[1]);
			}
		}
	}

	/**
	 * This function switches the block when clicked on +/- image
	 */
	function switchBlock(switchObj,dataObj)
	{
		if(dataObj.style.display != 'none') //Clicked on - image
		{
			dataObj.style.display = 'none';
			switchObj.innerHTML = '';
		}
		else  							   //Clicked on + image
		{
			if(navigator.appName == "Microsoft Internet Explorer")
				dataObj.style.display = 'block';
			else
				dataObj.style.display = 'table-row';

			switchObj.innerHTML = '';
		}
	}
<commit_msg>bug 4991<commit_after>
	/*Declaration of global variables.*/

	//The variables request and url are used in ajax functions
	var request,url;
	//Value=1 indicates 'SpecimenRequests' tab and value=2 indicates 'ArrayRequests' tab
	var pageDisplayed=1;

	/**
	 * This funciton is called on click of 'Create Array' button in the ArrayRequests.jsp.It redirects to SpecimenArray.jsp
	 */
	function gotoCreateArrayPage(arrayRowCounter)
	{
		var id  = "defineArrayName_" + arrayRowCounter;
		var arrayName = document.getElementById(id).value;
		var queryString = "?array=" + arrayName + "&operation=add&id=";
		var action = "CreateDefinedArray.do" + queryString;
		document.forms[0].action = action ;
	    document.forms[0].submit();
	}

	/**
	 * This function submits the form.(That is,data from both the RequestDetails.jsp and ArrayRequests.jsp)
	 */
	function submitPage()
	{
		document.forms[0].submit();
	}

	/**
	 * Function updateAllStatus() constructs the request url alongwith the required query string and calls the sendRequestForUpdateStatus() function.
	 * This is called to update statuses of the order items.
	 */
	function updateAllStatus()
	{
		var selectNext = document.getElementById('nextStatusId');
		selectedNextValue = selectNext.value;
		//Send request only if dropdown value is changed.
		if(selectNext.selectedIndex != 0 )
		{
			//Construst URL to send the request
			var queryString = "updateValue=" + selectedNextValue;
			url = "UpdateStatus.do?"+queryString;
			sendRequestForUpdateStatus();
		}
	}

	/**
	 * Function sendRequest() sends the GET request to the server.
	 */
	function sendRequestForUpdateStatus()
	{
		//Obtain XMLHttpRequest object
		request = newXMLHTTPReq();
		if(request)
		{
			//To update status of orderitems in Specimen Requests tab page
			if(pageDisplayed == 1)
			{
				request.onreadystatechange = handleResponse;
			}
			//To update status of defined array and existing array in Array Requests tab page
			else
			{
				request.onreadystatechange = handleResponseForArray;
			}
			try
			{
				request.open("GET", url, true);
				request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				request.send("");
			}
			catch(e)
			{}
		}
	}

	/**
	 * This function assigns the response to the select element in the ArrayRequests page
	 * (for defined arrays and existing arrays) when the response is ready.
	 */
	function handleResponseForArray()
	{
		if(request.readyState == 4)
		{
		   //Response is ready
			if(request.status == 200)
			{
				/* ',' seperates statuses of all defined arrays from existing arrays.
				 * The length of responseStringArray would be always 2.
				 * The first element of the array contains response string of the defined array statuses.
				 * The second element of the array contains response string of the existing array statuses.
				 */
				responseStringArray = parseResponseText(',');

				var selectId="";

				//Change status for Defined Arrays
				if(document.getElementById("definedArrayRows") != null)
					var num_rows_definedArray = document.getElementById("definedArrayRows").value;

				//Change status for Existing Arrays
				if(document.getElementById("numOfExistingArrays") != null)
					var num_rows_existingArray = document.getElementById("numOfExistingArrays").value;

				//';' seperates status of individual orderitems in the definedarrays
				definedArrayResponseStringArray = responseStringArray[0].split(';');

				//Set new values in the options
				setNewStatusValuesInOptionsArray("array_",num_rows_definedArray,definedArrayResponseStringArray);

				//Change status for Existing Arrays
				if(responseStringArray.length == 2)
				{
					//';' seperates status of indivudual existing arrays
					existingArrayResponseStringArray = responseStringArray[1].split(';');

					//Set new values in the options
					setNewStatusValuesInOptionsArray("existingArray_",num_rows_existingArray,existingArrayResponseStringArray);
				}
			}//End if(request.status == 200)
		}//End if(request.readyState == 4)
	}

	/**
	 * handleResponse() assigns the response to the select element when the response is ready and there is no error in the response.
	 */
	function handleResponse()
	{
		if(request.readyState == 4)
		{
			//Response is ready
			if(request.status == 200)
			{
				responseStringArray = parseResponseText(';');

				var tbodyId = document.getElementById('tbody');
				var num_rows = tbodyId.rows.length;				//responseStringArray.length==rows.length
				var selectId="";

				//Set new values in the options
				setNewStatusValuesInOptionsArray("select_",num_rows,responseStringArray);
			}//End if(request.status == 200)
		}//End if(request.readyState == 4)
	}

	/**
	 * Added by Ashish to update quantity for selected derived biospecimens.
	 */
	var id;
	function handleResponseForQty()
	{
		if(request.readyState == 4)
		{
			//Response is ready
			if(request.status == 200)
			{
				/* Response contains required output.
				 * Get the response from server.
				 */
				var responseString = request.responseText;
				var divId = "avaiQty" +id;
				document.getElementById(divId).innerHTML = responseString;
			}//End if(request.status == 200)
		}//End if(request.readyState == 4)
	}

	/**
	 *  This function updates the quantity for selected derived biospecimens (Added by Ashish)
	 */
	function updateQuantity(requestForId)
	{
		var sendRequestFor = 'updateQty';
		id = requestForId.substring(10);
		var selectNext = document.getElementById(requestForId);
		selectedNextValue = selectNext.value;
		//Construst URL to send the request
		var queryString = "selectedSpecimen=" + selectedNextValue+"&finalSpecimenListId=" + id;
		url = "UpdateQuantity.do?"+queryString;
		sendRequestForQuantity();
	}

	/**
	 * This function sends 'GET' request to the server for updating quantity (Added by Ashish)
	 */
	function sendRequestForQuantity()
	{
		request = newXMLHTTPReq();

		if(request)
		{
			request.onreadystatechange = handleResponseForQty;
			try
			{
				request.open("GET", url, true);
				request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				request.send("");
			}
			catch(e)
			{}
		}
	}

	/**
	 * Thisfunction expand/collapses block for rows in the Existing Array(ArrayRequests.jsp)
	 */
	function expandArrayBlock()
	{
		switchObj = document.getElementById('switchExistingArray');
		tbodyObj = document.getElementById('existingArrayId');
		switchBlock(switchObj,tbodyObj);
	}

	/**
	 * This function expand/collapses block for individual orderitems defined in an array(ArrayRequests.jsp)
	 */
	function expandOrderItemsInArray(rowid,arrayId)
	{
		var switchObj = document.getElementById('switchdefineArray' + rowid + '_array' + arrayId);
		var dataObj = document.getElementById('dataDefinedArray' + rowid + '_array' + arrayId);
		switchBlock(switchObj,dataObj);
	}

	/**
	 * This function expand/collapses block for individual orderitems defined in orderlist in RequestDetails.jsp
	 */
	function switchOrderList(rowid)
	{
		switchObj = document.getElementById('switch'+rowid);
		dataObj = document.getElementById('data'+rowid);
		switchBlock(switchObj,dataObj);
	}

	/**
	 * This function switches the block in the deifned arrays row
	 */
	function switchDefinedArrayBlock(rowid)
	{
		switchObj = document.getElementById('switchArray' + rowid);
		dataObj = document.getElementById('dataArray' + rowid);
		arrayHeaderObj = document.getElementById('headerArray' + rowid);
		btnCreateArrayObj = document.getElementById('btnCreateArray' + rowid);

		if(dataObj.style.display != 'none') //Clicked on - image
		{
			dataObj.style.display = 'none';
			arrayHeaderObj.style.display = 'none';
			btnCreateArrayObj.style.display = 'none';
			switchObj.innerHTML = '';
		}
		else
		{
			if(navigator.appName == "Microsoft Internet Explorer")
			{
				dataObj.style.display = 'block';
				arrayHeaderObj.style.display = 'block';
				btnCreateArrayObj.style.display = 'block';
			}
			else
			{
				dataObj.style.display = 'table-row';
				arrayHeaderObj.style.display = 'table-row';
				btnCreateArrayObj.style.display = 'table-row';
			}
			switchObj.innerHTML = '';
		}
	}

	/**
	 * This function switches the tab to SpecimenRequest Page (i.e,ArrayRequests.jsp)
	 */
	function gotoArrayRequestTab()
	{
		document.getElementById("tabIndexId").value=2;
		pageDisplayed=2;
		//Hide the table containing biospecimen  order items
		document.getElementById('table3_specimenDataTab').style.display="none";

		if(navigator.appName == "Microsoft Internet Explorer")
		{
			//Display the table containing ArrayRequests.jsp
			document.getElementById('table5_arrayDataTable').style.display="block";
			expandTableForIE();
		}
		else
		{
			//Display the table containing ArrayRequests.jsp
			document.getElementById('table5_arrayDataTable').style.display="table-row";
			expandTableForOtherBrowsers();
		}
		changeCssForTab('arrayRequestTab','specimenRequestTab');
	}

	/**
	 * This function switches the tab to SpecimenRequest Page (i.e, RequestDetails.jsp)
	 */
	function gotoSpecimenRequestTab()
	{
		document.getElementById("tabIndexId").value=1;
		pageDisplayed=1;
		//Hide the table containing ArrayRequests.jsp
		document.getElementById('table5_arrayDataTable').style.display="none";
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			//Display the table containing the data of RequestDetails.jsp
			document.getElementById('table3_specimenDataTab').style.display="block";
			expandTableForIE();
		}
		else
		{
			//Display the table containing the data of RequestDetails.jsp
			document.getElementById('table3_specimenDataTab').style.display="table-row";
			expandTableForOtherBrowsers();
		}
		changeCssForTab('specimenRequestTab','arrayRequestTab');
	}

	/**
	 * This function expands tables on both tabbed pages(i.e,Specimen Requests tab and Array Requests tab)
	 * when displayed on Microsoft IE browser
	 */
	function expandTableForIE()
	{
		//Display other tables required for both the tabbed pages
		document.getElementById('table4_pageFooter').style.display="block";
		document.getElementById('table2_TabPage').style.display="block";
		document.getElementById('table1_OrderRequestHeader').style.display="block";
	}

	/**
	 * This funciton expands tables on both tabbed pages(i.e,Specimen Requests tab and Array Requests tab)
	 * when displayed on Mozilla/NetScape or other browsers
	 */
	function expandTableForOtherBrowsers()
	{
		//Display other tables required for both the tabbed pages
		document.getElementById('table4_pageFooter').style.display="table-row";
		document.getElementById('table2_TabPage').style.display="table-row";
		document.getElementById('table1_OrderRequestHeader').style.display="table-row";
	}

	/**
	 * This function changes the css of the tab depending upon whether 'Specimen Requests' or 'Array Requests' tab
	 * was selected.
	 */
	function changeCssForTab(strSelectedTab,strUnSelectedTab)
	{
		var selectedTab = document.getElementById(strSelectedTab);
		var unSelectedTab = document.getElementById(strUnSelectedTab);

		selectedTab.onmouseover=null;
		selectedTab.onmouseout=null;
		selectedTab.className="tabMenuItemSelected";

		unSelectedTab.onmouseover=function() { changeMenuStyle(this,'tabMenuItemOver'),showCursor();};
		unSelectedTab.onmouseout=function() {changeMenuStyle(this,'tabMenuItem'),hideCursor();};
		unSelectedTab.className="tabMenuItem";
	}

	/**
	 * This function obtains responsetext from the request object and parses it with the given delimiter and returns a string array
	 */
	function parseResponseText(delimiter)
	{
		//Response contains required output.
		var responseString = request.responseText;
		var responseStringArray = new Array();

		//Get array values for each row.
		responseStringArray = responseString.split(delimiter);
		return responseStringArray;
	}

	/**
	 * This function sets the new status values in the options array
	 */
	function setNewStatusValuesInOptionsArray(strElement,rowCount,responseStringArray)
	{
		for(var counter=0;counter<rowCount;counter++)
		{
			strSelectElementId = strElement + counter;
			selectElementId = document.getElementById(strSelectElementId);
			if(selectElementId != null)
			{
				optionStringArray = responseStringArray[counter].split('||');

				for(var x=0;x<optionStringArray.length-1;x++)
				{
					optionStrings = optionStringArray[x].split('|');
					//Set the text/value pair in options.
					selectElementId.options[x] = new Option(optionStrings[0],optionStrings[1]);
				}
			}
		}
	}

	/**
	 * This function switches the block when clicked on +/- image
	 */
	function switchBlock(switchObj,dataObj)
	{
		if(dataObj.style.display != 'none') //Clicked on - image
		{
			dataObj.style.display = 'none';
			switchObj.innerHTML = '';
		}
		else  							   //Clicked on + image
		{
			if(navigator.appName == "Microsoft Internet Explorer")
				dataObj.style.display = 'block';
			else
				dataObj.style.display = 'table-row';

			switchObj.innerHTML = '';
		}
	}
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');

var VERSION = '0.6.0';
var BASE = 'https://github.com/facebook/flow/releases/download/v' + VERSION + '/';

module.exports = new BinWrapper()
	.src(BASE + 'flow-osx-v' + VERSION + '.zip', 'darwin')
	.src(BASE + 'flow-linux64-v' + VERSION + '.zip', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use('flow');
<commit_msg>Update binary to v0.7.0<commit_after>'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');

var VERSION = '0.7.0';
var BASE = 'https://github.com/facebook/flow/releases/download/v' + VERSION + '/';

module.exports = new BinWrapper()
	.src(BASE + 'flow-osx-v' + VERSION + '.zip', 'darwin')
	.src(BASE + 'flow-linux64-v' + VERSION + '.zip', 'linux', 'x64')
	.dest(path.join(__dirname, '../vendor'))
	.use('flow');
<|endoftext|>


<commit_before>var test = require('tape');
var webpack = require('../');
var path = require('path');
var fs = require('vinyl-fs');
var named = require('vinyl-named');

var base = path.resolve(__dirname, 'fixtures');

test('streams output assets', function (t) {
  t.plan(3);
  var entry = fs.src('test/fixtures/entry.js');
  var stream = webpack({
    config: {
      mode: 'development',
      output: {
        filename: 'bundle.js'
      }
    },
    quiet: true
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case '0.bundle.js':
        t.ok(/var chunk = true;/i.test(contents), 'should contain "var chunk = true;"');
        break;
    }
  });
  entry.pipe(stream);
});

test('multiple entry points', function (t) {
  t.plan(3);
  var stream = webpack({
    config: {
      mode: 'development',
      entry: {
        'one': path.join(base, 'entry.js'),
        'two': path.join(base, 'anotherentrypoint.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    },
    quiet: true
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'one.bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'two.bundle.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });
  stream.end();
});

test('subsequent runs served from cache', function (t) {
  t.plan(4);

  var config = {
    entry: {
      'one': path.join(base, 'entry.js'),
      'two': path.join(base, 'anotherentrypoint.js')
    },
    output: {
      filename: '[name].bundle.js'
    },
    quiet: true
  };

  var stream = webpack(config);
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'one.bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'two.bundle.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });

  stream.on('end', function () {
    var cachedStream = webpack(config);
    var data = null;

    cachedStream.on('data', function (file) {
      data = file;
    });

    cachedStream.on('end', function () {
      t.ok(data === null, 'should not write any output');
    });
  });

  stream.end();
});

test('stream multiple entry points', function (t) {
  t.plan(3);
  var entries = fs.src(['test/fixtures/entry.js', 'test/fixtures/anotherentrypoint.js']);
  var stream = webpack({
    config: {
      mode: 'development'
    },
    quiet: true
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'entry.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'anotherentrypoint.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });
  entries.pipe(named()).pipe(stream);
});

test('empty input stream', function (t) {
  t.plan(1);

  var entry = fs.src('test/path/to/nothing', { allowEmpty: true });
  var stream = webpack({
    config: {},
    quiet: true
  });
  var data = null;

  stream.on('data', function (file) {
    data = file;
  });

  stream.on('end', function () {
    t.ok(data === null, 'should not write any output');
  });

  entry.pipe(named()).pipe(stream);
});

test('multi-compile', function (t) {
  t.plan(3);

  var stream = webpack({
    quiet: true,
    config: [{
      mode: 'development',
      entry: {
        'one': path.join(base, 'entry.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    }, {
      mode: 'development',
      entry: {
        'two': path.join(base, 'anotherentrypoint.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    }]
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'one.bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'two.bundle.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });
  stream.end();
});

test('no options', function (t) {
  t.plan(1);
  var stream = webpack();
  stream.on('end', function () {
    t.ok(true, 'ended without error');
  });
  stream.end();
});

test('error formatting', function (t) {
  t.plan(2);
  // TODO: Fix this to test to rely less on large string outputs as those can change
  // and still be ok.
  var expectedMessage = '\x1b[31mError\x1b[39m in plugin "\x1b[36mwebpack-stream\x1b[39m"\nMessage:\n    ./test/fixtures/entry.js\nModule Error (from ./test/fak';
  var entry = fs.src('test/fixtures/entry.js');
  var stream = webpack({
    quiet: true,
    config: {
      module: {
        rules: [
          {
            test: /\.js$/,
            enforce: 'pre',
            use: './test/fake-error-loader'
          }
        ]
      }
    }
  });
  stream.on('error', function (err) {
    t.equal(err.toString().slice(0, expectedMessage.length), expectedMessage, 'error message');
  });
  stream.on('compilation-error', function (err) {
    t.equal(err.toString().slice(0, expectedMessage.length), expectedMessage, 'compilation-error message');
  });
  entry.pipe(stream);
});
<commit_msg>Fix test for newer webpack<commit_after>var test = require('tape');
var webpack = require('../');
var path = require('path');
var fs = require('vinyl-fs');
var named = require('vinyl-named');

var base = path.resolve(__dirname, 'fixtures');

test('streams output assets', function (t) {
  t.plan(3);
  var entry = fs.src('test/fixtures/entry.js');
  var stream = webpack({
    config: {
      mode: 'development',
      output: {
        filename: 'bundle.js'
      }
    },
    quiet: true
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case '0.bundle.js':
        t.ok(/var chunk = true;/i.test(contents), 'should contain "var chunk = true;"');
        break;
    }
  });
  entry.pipe(stream);
});

test('multiple entry points', function (t) {
  t.plan(3);
  var stream = webpack({
    config: {
      mode: 'development',
      entry: {
        'one': path.join(base, 'entry.js'),
        'two': path.join(base, 'anotherentrypoint.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    },
    quiet: true
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'one.bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'two.bundle.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });
  stream.end();
});

test('subsequent runs served from cache', function (t) {
  t.plan(4);

  var config = {
    config: {
      mode: 'development',
      entry: {
        'one': path.join(base, 'entry.js'),
        'two': path.join(base, 'anotherentrypoint.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    },
    quiet: true
  };

  var stream = webpack(config);
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'one.bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'two.bundle.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });

  stream.on('end', function () {
    var cachedStream = webpack(config);
    var data = null;

    cachedStream.on('data', function (file) {
      data = file;
    });

    cachedStream.on('end', function () {
      t.ok(data === null, 'should not write any output');
    });
  });

  stream.end();
});

test('stream multiple entry points', function (t) {
  t.plan(3);
  var entries = fs.src(['test/fixtures/entry.js', 'test/fixtures/anotherentrypoint.js']);
  var stream = webpack({
    config: {
      mode: 'development'
    },
    quiet: true
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'entry.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'anotherentrypoint.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });
  entries.pipe(named()).pipe(stream);
});

test('empty input stream', function (t) {
  t.plan(1);

  var entry = fs.src('test/path/to/nothing', { allowEmpty: true });
  var stream = webpack({
    config: {},
    quiet: true
  });
  var data = null;

  stream.on('data', function (file) {
    data = file;
  });

  stream.on('end', function () {
    t.ok(data === null, 'should not write any output');
  });

  entry.pipe(named()).pipe(stream);
});

test('multi-compile', function (t) {
  t.plan(3);

  var stream = webpack({
    quiet: true,
    config: [{
      mode: 'development',
      entry: {
        'one': path.join(base, 'entry.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    }, {
      mode: 'development',
      entry: {
        'two': path.join(base, 'anotherentrypoint.js')
      },
      output: {
        filename: '[name].bundle.js'
      }
    }]
  });
  stream.on('data', function (file) {
    var basename = path.basename(file.path);
    var contents = file.contents.toString();
    switch (basename) {
      case 'one.bundle.js':
        t.ok(/__webpack_require__/i.test(contents), 'should contain "__webpack_require__"');
        t.ok(/var one = true;/i.test(contents), 'should contain "var one = true;"');
        break;
      case 'two.bundle.js':
        t.ok(/var anotherentrypoint = true;/i.test(contents), 'should contain "var anotherentrypoint = true;"');
        break;
    }
  });
  stream.end();
});

test('no options', function (t) {
  t.plan(1);
  var stream = webpack();
  stream.on('end', function () {
    t.ok(true, 'ended without error');
  });
  stream.end();
});

test('error formatting', function (t) {
  t.plan(2);
  // TODO: Fix this to test to rely less on large string outputs as those can change
  // and still be ok.
  var expectedMessage = '\x1b[31mError\x1b[39m in plugin "\x1b[36mwebpack-stream\x1b[39m"\nMessage:\n    ./test/fixtures/entry.js\nModule Error (from ./test/fak';
  var entry = fs.src('test/fixtures/entry.js');
  var stream = webpack({
    quiet: true,
    config: {
      module: {
        rules: [
          {
            test: /\.js$/,
            enforce: 'pre',
            use: './test/fake-error-loader'
          }
        ]
      }
    }
  });
  stream.on('error', function (err) {
    t.equal(err.toString().slice(0, expectedMessage.length), expectedMessage, 'error message');
  });
  stream.on('compilation-error', function (err) {
    t.equal(err.toString().slice(0, expectedMessage.length), expectedMessage, 'compilation-error message');
  });
  entry.pipe(stream);
});
<|endoftext|>


<commit_before>module.exports = function (source, target) {
  target = target || window.parent
  source = source || window.parent.document.URL
  window.console = {
    log: function (msg) { target.postMessage({type: 'log', data: maybeStringify(msg)}, source) },
    warn: function (msg) { target.postMessage({type: 'warn', data: maybeStringify(msg)}, source) },
    error: function (err) { target.postMessage(maybeStringify(err), source) }
  }

  window.onerror = function (error, url, line, column, errObj) {
    console.error({type: 'error', data: maybeStringify(error)})
  }
}

function maybeStringify (msg) {
  return typeof msg === 'object' ? JSON.stringify(msg) : msg
}
<commit_msg>minor update<commit_after>module.exports = function (source, target) {
  target = target || window.parent
  source = source || window.parent.document.URL
  window.console = {
    log: function (msg) { target.postMessage({type: 'log', data: maybeStringify(msg)}, source) },
    warn: function (msg) { target.postMessage({type: 'warn', data: maybeStringify(msg)}, source) },
    error: function (err) { target.postMessage({type: 'error', data: maybeStringify(err.message)}, source) }
  }

  window.onerror = function (error, url, line, column, errObj) {
    console.error(error)
  }
}

function maybeStringify (msg) {
  return typeof msg === 'object' ? JSON.stringify(msg) : msg
}
<|endoftext|>


<commit_before>
var assert = require('assert');
var request = require('request');

var _baseUrl = 'http://localhost:3000';

describe('Routes test', function()
{
  it('/index', function(done) {
    request.get(_baseUrl+'/', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/ajax', function(done) {
    request.get(_baseUrl+'/ajax', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/mail', function(done) {
    request.get(_baseUrl+'/mail', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/pin', function(done) {
    request.get(_baseUrl+'/pin', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/id', function(done) {
    request.get(_baseUrl+'/id=5', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      assert.equal(body, 5);
      done();
    });
  });

  it('/hello', function(done) {
    request.get(_baseUrl+'/hello?name=aaa&last=bbb', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      assert.equal(body, 'Hello aaa bbb');
      done();
    });
  });

  it('/notFound', function(done) {
    request.get(_baseUrl+'/notFound', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 404);
      done();
    });
  });

});
<commit_msg>add correcect/incorrect routes test<commit_after>
var assert = require('assert');
var request = require('request');

var _baseUrl = 'http://localhost:3000';

describe('Routes test', function()
{
  it('/index', function(done) {
    request.get(_baseUrl+'/', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/ajax', function(done) {
    request.get(_baseUrl+'/ajax', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/mail', function(done) {
    request.get(_baseUrl+'/mail', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/pin', function(done) {
    request.get(_baseUrl+'/pin', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      done();
    });
  });

  it('/id (correct)', function(done) {
    request.get(_baseUrl+'/id=5', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      assert.equal(body, 5);
      done();
    });
  });

  it('/id (void)', function(done) {
    request.get(_baseUrl+'/id', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 404);
      done();
    });
  });

  it('/id (string)', function(done) {
    request.get(_baseUrl+'/id=aaa', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 404);
      done();
    });
  });

  it('/hello (correct)', function(done) {
    request.get(_baseUrl+'/hello?name=aaa&last=bbb', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      assert.equal(body, 'Hello aaa bbb');
      done();
    });
  });

  it('/hello (void)', function(done) {
    request.get(_baseUrl+'/hello', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 200);
      assert.equal(body, 'Hello !not set! !not set!');
      done();
    });
  });

  it('/notFound or 404', function(done) {
    request.get(_baseUrl+'/notFound', function(err, res, body) {
      assert.equal(err, null);
      assert.equal(res.statusCode , 404);
      done();
    });
  });

});
<|endoftext|>


<commit_before>var Game = require("./public/js/engine");
var Bot = require("./bots");
var util = require("./utils");
var settings = require("./settings");
var Player = require("./public/js/player");
/*
 * @constructor
 * @this {Room}
 */
function Room(gametype) {
    this.id = util.nextRoomId();
    //TODO: replace with uuid?
    this.openIds = [];
    //list of removed player ids, for grid replacement
    this.players = this.dummyPlayers();
    //list of player objects
    this.banned = [];
    this.board = this.getBoard(gametype);
    this.game = new Game(this.players, this.board);
    console.log(this.game.grid);
    this.admin = undefined;
    //player
    this.turn = 0;
    //player index
    this.isPublic = true;
    //for private games, change to false
    this.started = false;
    //for new rooms, change on hit 3 players
}

Room.prototype.dummyPlayers = function() {
    var dummies = [];
    for (var i = 1; i < 4; i++) {
        var id = i;
        var dummy = new Player(id, {
            emit : function() {
            }
        });
        dummy.removed = true;
        dummies.push(dummy);
        this.openIds.push(id);
    }
    return dummies;
}
/*
 * @param {id} id
 * @return {Player}
 */
Room.prototype.getPlayer = function(id) {
    for (var i in this.players) {
        var player = this.players[i];
        if (player.id === id) {
            return player;
        }
    }
}

Room.prototype.getPlayerIndex = function(id) {
    return this.players.indexOf(this.getPlayer(id));
}

Room.prototype.currentPlayerId = function() {
    return this.players[this.turn].id;
}
/*
 * TODO: do this more efficiently (perhaps using map/clone)
 * @return {list: {players}}
 * {players} = {id, score, bot, removed}
 */
Room.prototype.publicPlayerList = function() {//send only select information to clients
    var playerList = [];
    for (var i in this.players) {
        var p = this.players[i];
        var player = {
            id : p.id,
            //color : p.color,
            //color is now based on index in player list
            score : p.score,
            bot : p.bot,
            removed : p.removed
        }
        playerList.push(player);
    }
    return playerList;
}
/*
 * @param {string} target
 * @param {Object} data
 */
Room.prototype.update = function(target, data) {
    this.sendAll("update", {
        target : target,
        data : data
    });
}

Room.prototype.playerCount = function() {
    var cnt = 0;
    for (var i = 0; i < this.players.length; i++) {
        if (!this.players[i].removed) {//check if player has been removed from game
            cnt++;
        }
    }
    return cnt;
}
/*
 * 2 cases, either a game has started and we need to replace a removed player, or were still adding players
 * @param {player} player
 * @param {callback} callback
 */
Room.prototype.add = function(player, callback) {
    if (this.openIds.length >= 1 && this.banned.indexOf(player) === -1) {

        //user left the game, and is now returning
        if (this.openIds.indexOf(player.id) !== -1) {
            var openId = this.openIds.splice(this.openIds.indexOf(player.id),1)[0];
            player.removed = false;
        } else {
            var openId = this.openIds.shift();
        }
        var slot = this.getPlayerIndex(openId);
        if (slot === -1) {
            util.log("no slot")
            return;
        }

        //replace open space with new player
        console.log("previous: " + openId + ", new: " + player.id);
        this.game.replacePlayer(openId, player.id);

        this.players[slot] = player;
        this.setScores();
        this.update("grid", this.game.grid);

        this.update("players", this.publicPlayerList());
        var playerSocket = player.socket;

        playerSocket.emit("update", {
            target : "room",
            data : this.id
        })
        playerSocket.emit("update", {
            target : "me",
            data : player.id
        });
        playerSocket.emit("update", {
            target : "board",
            data : this.board
        });

        if (callback) {
            callback(this);
        }

        if (this.isPublic && !this.started) {
            //have enough people, public game, and havent started yet
            this.newGame();
        }
        this.update("gameState", this.gameState());
    }
}
/*
 * @param {player} player
 */
Room.prototype.remove = function(player) {
    var index = this.getPlayerIndex(player.id);
    if (index !== -1) {
        util.log("remvoed player")
        this.openIds.push(this.players[index].id);
        //this.players[index] = this.removedPlayer();
        this.players[index].removed = true;
        //dont actually remove player
        this.update("gameState", this.gameState());
        this.update("players", this.publicPlayerList());
    }
}
/*
 * @param {string} name
 * @param {Object} data
 */
Room.prototype.sendAll = function(name, data) {//send to all players
    for (var i in this.players) {
        this.players[i].socket.emit(name, data);
    }
}
/*
 * @param {move} data
 * @param {player} player
 * {move} = {start:{Position}, end:{Position}}
 */
Room.prototype.move = function(data, player) {
    if (player.id !== this.currentPlayerId()) {
        util.log("tried to move, but not your turn");
        return;
    }
    var valid = this.game.validateMove(data.start, data.end, player.id);
    if (!valid) {
        var d = data;
        d.id = player.id;
        util.log("bad move", d);
        return;
    }

    var scoreDiff = this.game.move(data.start, data.end);
    this.mergeScores(scoreDiff);
    this.sendAll("move", data);

    if (this.game.gameEnded()) {
        // TODO: Game ends here
        util.log("game ended");
    }

    this.turn = ++this.turn % 3;
    this.update("gameState", this.gameState());

    this.botMove();
}
/*
 * @param {dict} scores {id: scoreDiff}
 */
Room.prototype.mergeScores = function(scoreDiff) {
    var scoreDiff = scoreDiff
    for (var s in scoreDiff) {
        if (this.getPlayer(s)) {
            this.getPlayer(s).score += scoreDiff[s];
        }
    }
}
/*
 * re-sets score based on board values
 */
Room.prototype.setScores = function() {
    var scores = this.game.getScores();
    for (var s in scores) {
        if (this.getPlayer(s)) {
            this.getPlayer(s).score = scores[s];
        }
    }
}

Room.prototype.addBot = function() {
    util.log("adding bot");
    this.add(new Bot(this.board));
    this.botMove();
}

Room.prototype.botMove = function() {
    var curPlayer = this.players[this.turn];
    if (curPlayer.bot) {
        var move = curPlayer.nextMove(util.deepCopy(this.game.grid));
        this.move(move, curPlayer);
    }

}

Room.prototype.kick = function(target) {
    this.remove(target);
}

Room.prototype.ban = function(target) {
    this.kick(target);
    this.banned.push(target);
}

Room.prototype.adminStart = function() {
    if (!this.isPublic) {
        this.isPublic = true;
        this.update("gameState", this.gameState())
    }
}

Room.prototype.getBoard = function(board) {
    var boards = {
        "classic" : './resources/boards/original.json',
        "pointcontrol" : './resources/boards/pointcontrol.json',
    }
    return boards[board] ? require(boards[board]) : require(boards["classic"]);
}
//only call this with 3 players in players list
Room.prototype.newGame = function() {
    this.started = true;
    //this.game.newGame();
    this.setScores(this.game.getScores());
    this.turn = 0;
    this.update("gameState", this.gameState());
    this.update("players", this.publicPlayerList());
    this.update("board", this.board);
    this.update("grid", this.game.grid);
}
/*
 * TODO: make more efficient
 * @return {gameState}
 * {gameState} = {isPublic: boolean, playing: {boolean}, turn: {number}}
 */
Room.prototype.gameState = function() {
    var state = {
        isPublic : this.isPublic,
        turn : this.turn
    }
    return state;
}

Room.prototype.setAdmin = function(playerId) {
    this.admin = playerId;
}

Room.prototype.privatize = function() {
    this.isPublic = false;
}

module.exports = Room;

<commit_msg>fixed joining bug<commit_after>var Game = require("./public/js/engine");
var Bot = require("./bots");
var util = require("./utils");
var settings = require("./settings");
var Player = require("./public/js/player");
/*
 * @constructor
 * @this {Room}
 */
function Room(gametype) {
    this.id = util.nextRoomId();
    //TODO: replace with uuid?
    this.openIds = [];
    //list of removed player ids, for grid replacement
    this.players = this.dummyPlayers();
    //list of player objects
    this.banned = [];
    this.board = this.getBoard(gametype);
    this.game = new Game(this.players, this.board);
    console.log(this.game.grid);
    this.admin = undefined;
    //player
    this.turn = 0;
    //player index
    this.isPublic = true;
    //for private games, change to false
    this.started = false;
    //for new rooms, change on hit 3 players
}

Room.prototype.dummyPlayers = function() {
    var dummies = [];
    for (var i = 1; i < 4; i++) {
        var id = i;
        var dummy = new Player(id, {
            emit : function() {
            }
        });
        dummy.removed = true;
        dummies.push(dummy);
        this.openIds.push(id);
    }
    return dummies;
}
/*
 * @param {id} id
 * @return {Player}
 */
Room.prototype.getPlayer = function(id) {
    for (var i in this.players) {
        var player = this.players[i];
        if (player.id === id) {
            return player;
        }
    }
}

Room.prototype.getPlayerIndex = function(id) {
    return this.players.indexOf(this.getPlayer(id));
}

Room.prototype.currentPlayerId = function() {
    return this.players[this.turn].id;
}
/*
 * TODO: do this more efficiently (perhaps using map/clone)
 * @return {list: {players}}
 * {players} = {id, score, bot, removed}
 */
Room.prototype.publicPlayerList = function() {//send only select information to clients
    var playerList = [];
    for (var i in this.players) {
        var p = this.players[i];
        var player = {
            id : p.id,
            //color : p.color,
            //color is now based on index in player list
            score : p.score,
            bot : p.bot,
            removed : p.removed
        }
        playerList.push(player);
    }
    return playerList;
}
/*
 * @param {string} target
 * @param {Object} data
 */
Room.prototype.update = function(target, data) {
    this.sendAll("update", {
        target : target,
        data : data
    });
}

Room.prototype.playerCount = function() {
    var cnt = 0;
    for (var i = 0; i < this.players.length; i++) {
        if (!this.players[i].removed) {//check if player has been removed from game
            cnt++;
        }
    }
    return cnt;
}
/*
 * 2 cases, either a game has started and we need to replace a removed player, or were still adding players
 * @param {player} player
 * @param {callback} callback
 */
Room.prototype.add = function(player, callback) {
    if (this.openIds.length >= 1 && this.banned.indexOf(player) === -1) {
        //detect if player is trying to join more than once
        if(this.getPlayer(player.id) && !this.getPlayer(player.id).removed){
            return;
        }
        //user left the game, and is now returning
        if (this.openIds.indexOf(player.id) !== -1) {
            var openId = this.openIds.splice(this.openIds.indexOf(player.id),1)[0];
            player.removed = false;
        } else {
            var openId = this.openIds.shift();
        }
        var slot = this.getPlayerIndex(openId);
        if (slot === -1) {
            util.log("no slot")
            return;
        }

        //replace open space with new player
        console.log("previous: " + openId + ", new: " + player.id);
        this.game.replacePlayer(openId, player.id);

        this.players[slot] = player;
        this.setScores();
        this.update("grid", this.game.grid);

        this.update("players", this.publicPlayerList());
        var playerSocket = player.socket;

        playerSocket.emit("update", {
            target : "room",
            data : this.id
        })
        playerSocket.emit("update", {
            target : "me",
            data : player.id
        });
        playerSocket.emit("update", {
            target : "board",
            data : this.board
        });

        if (callback) {
            callback(this);
        }

        if (this.isPublic && !this.started) {
            //have enough people, public game, and havent started yet
            this.newGame();
        }
        this.update("gameState", this.gameState());
    }
}
/*
 * @param {player} player
 */
Room.prototype.remove = function(player) {
    var index = this.getPlayerIndex(player.id);
    if (index !== -1) {
        util.log("remvoed player")
        this.openIds.push(this.players[index].id);
        //this.players[index] = this.removedPlayer();
        this.players[index].removed = true;
        //dont actually remove player
        this.update("gameState", this.gameState());
        this.update("players", this.publicPlayerList());
    }
}
/*
 * @param {string} name
 * @param {Object} data
 */
Room.prototype.sendAll = function(name, data) {//send to all players
    for (var i in this.players) {
        this.players[i].socket.emit(name, data);
    }
}
/*
 * @param {move} data
 * @param {player} player
 * {move} = {start:{Position}, end:{Position}}
 */
Room.prototype.move = function(data, player) {
    if (player.id !== this.currentPlayerId()) {
        util.log("tried to move, but not your turn");
        return;
    }
    var valid = this.game.validateMove(data.start, data.end, player.id);
    if (!valid) {
        var d = data;
        d.id = player.id;
        util.log("bad move", d);
        return;
    }

    var scoreDiff = this.game.move(data.start, data.end);
    this.mergeScores(scoreDiff);
    this.sendAll("move", data);

    if (this.game.gameEnded()) {
        // TODO: Game ends here
        util.log("game ended");
    }

    this.turn = ++this.turn % 3;
    this.update("gameState", this.gameState());

    this.botMove();
}
/*
 * @param {dict} scores {id: scoreDiff}
 */
Room.prototype.mergeScores = function(scoreDiff) {
    var scoreDiff = scoreDiff
    for (var s in scoreDiff) {
        if (this.getPlayer(s)) {
            this.getPlayer(s).score += scoreDiff[s];
        }
    }
}
/*
 * re-sets score based on board values
 */
Room.prototype.setScores = function() {
    var scores = this.game.getScores();
    for (var s in scores) {
        if (this.getPlayer(s)) {
            this.getPlayer(s).score = scores[s];
        }
    }
}

Room.prototype.addBot = function() {
    util.log("adding bot");
    this.add(new Bot(this.board));
    this.botMove();
}

Room.prototype.botMove = function() {
    var curPlayer = this.players[this.turn];
    if (curPlayer.bot) {
        var move = curPlayer.nextMove(util.deepCopy(this.game.grid));
        this.move(move, curPlayer);
    }

}

Room.prototype.kick = function(target) {
    this.remove(target);
}

Room.prototype.ban = function(target) {
    this.kick(target);
    this.banned.push(target);
}

Room.prototype.adminStart = function() {
    if (!this.isPublic) {
        this.isPublic = true;
        this.update("gameState", this.gameState())
    }
}

Room.prototype.getBoard = function(board) {
    var boards = {
        "classic" : './resources/boards/original.json',
        "pointcontrol" : './resources/boards/pointcontrol.json',
    }
    return boards[board] ? require(boards[board]) : require(boards["classic"]);
}
//only call this with 3 players in players list
Room.prototype.newGame = function() {
    this.started = true;
    //this.game.newGame();
    this.setScores(this.game.getScores());
    this.turn = 0;
    this.update("gameState", this.gameState());
    this.update("players", this.publicPlayerList());
    this.update("board", this.board);
    this.update("grid", this.game.grid);
}
/*
 * TODO: make more efficient
 * @return {gameState}
 * {gameState} = {isPublic: boolean, playing: {boolean}, turn: {number}}
 */
Room.prototype.gameState = function() {
    var state = {
        isPublic : this.isPublic,
        turn : this.turn
    }
    return state;
}

Room.prototype.setAdmin = function(playerId) {
    this.admin = playerId;
}

Room.prototype.privatize = function() {
    this.isPublic = false;
}

module.exports = Room;

<|endoftext|>