<commit_before>var expect = require("expect.js")

describe("macro hygiene", function() {

  it("should work for or macro", function() {

    macro or {
      case ($x:expr, $y:expr) => {
        (function($tmp) {
          return $tmp ? $tmp : $y;
        })($x);
      }
    }

    (function($tmp) {
      var z = or(false, $tmp)
      expect(z).to.be("ok");
    })("ok");

  });

  it("should work for a binding outside of the macro def", function() {

    var z = (function(x) {

      macro m {
        case ($ignore:ident) => {
          x
        }
      }

      return (function (x) {
        return m(_) + x;
      })(22)

    })(1);
    expect(z).to.be(23)
  });

  it("should not rename object idents if they are the same as vars", function() {
    var o = (function (x) {
      return {
        x: x
      }
    })(42)

    expect(o.x).to.be(42);
  });

  it("should not rename object dot accesses", function() {
    var n = (function (o, x) {
      return o.x;
    })({x: 42})

    expect(n).to.be(42)
  });

  it("should do the correct renaming without macros for vars", function() {
    var z = (function() {
      var x = 42;
      return (function() {
        var y = x;
        var x = "foo"
        return y
      })();
    })();
    expect(z).to.be(undefined)
  });

  it("should do the correct renaming without macros for vars and params", function() {
    var z = (function() {
      return (function(x) {
        var y = x;
        var x = "foo"
        return y
      })(42);
    })();
    expect(z).to.be(42)
  });

  it("should do the correct renaming with macros for vars", function() {
    macro m {
      case () => { var x = 5; }
    }
    var z = (function(x) {
      var y = x;
      m();
      return y;
    })("foo")
    expect(z).to.be("foo")
  });

  // it("should work for vars with hoisting", function() {
  //   macro m {
  //     case $x:lit => {
  //       var tmp = $x;
  //     }
  //   }

  //   var tmp = "outer"
  //   m "inner"
  //   expect(tmp).to.be("outer");

  // });

  // it("should work for vars with hoisting and params", function() {
  //   function f(tmp) {
  //     macro m {
  //       case $x:lit => {
  //         var tmp = $x;
  //       }
  //     }

  //     var tmp = "outer"
  //     m "inner"
  //     expect(tmp).to.be("outer");
  //   }

  //   f("call")

  // });

  it("should work for var with nested function", function() {
    macro m {
      case $x:lit => {
        var tmp = $x;
      }
    }
    function f() {
      var tmp = "outer"
      m "inner"
      expect(tmp).to.be("outer");
    }
    f();
  });

  // todo this test needs a better api (syntax-case?)

  // it("should work for another variant of hygiene", function() {
  //   (function(x) {

  //     macro n {
  //       case ($stx:lit) => {
  //         function(x) {
  //           // want a way to distinguish between the two versions of x
  //           return x + x
  //         }
  //       }
  //     }

  //   })(42);
  // });

  // it("should work for the or macro with var", function() {
  //   macro or {
  //     case ($x:expr, $y:expr) => {
  //       (function() {
  //         var $tmp = $x;
  //         return $tmp ? $tmp : $y;
  //       })();
  //     }
  //   }

  //   var $tmp = "ok"
  //   var z = or(false, $tmp);
  //   expect(z).to.be("ok");
  // });

});
<commit_msg>var hygiene tests (failing)<commit_after>var expect = require("expect.js")

describe("macro hygiene", function() {

  it("should work for or macro", function() {

    macro or {
      case ($x:expr, $y:expr) => {
        (function($tmp) {
          return $tmp ? $tmp : $y;
        })($x);
      }
    }

    (function($tmp) {
      var z = or(false, $tmp)
      expect(z).to.be("ok");
    })("ok");

  });

  it("should work for a binding outside of the macro def", function() {

    var z = (function(x) {

      macro m {
        case ($ignore:ident) => {
          x
        }
      }

      return (function (x) {
        return m(_) + x;
      })(22)

    })(1);
    expect(z).to.be(23)
  });

  it("should not rename object idents if they are the same as vars", function() {
    var o = (function (x) {
      return {
        x: x
      }
    })(42)

    expect(o.x).to.be(42);
  });

  it("should not rename object dot accesses", function() {
    var n = (function (o, x) {
      return o.x;
    })({x: 42})

    expect(n).to.be(42)
  });

  it("should do the correct renaming without macros for vars", function() {
    var z = (function() {
      var x = 42;
      return (function() {
        var y = x;
        var x = "foo"
        return y
      })();
    })();
    expect(z).to.be(undefined)
  });

  it("should do the correct renaming without macros for vars and params", function() {
    var z = (function() {
      return (function(x) {
        var y = x;
        var x = "foo"
        return y
      })(42);
    })();
    expect(z).to.be(42)
  });

  it("should do the correct renaming with macros for vars", function() {
    macro m {
      case () => { var x = 5; }
    }
    var z = (function(x) {
      var y = x;
      m();
      return y;
    })("foo")
    expect(z).to.be("foo")
  });

  it("should work for vars with hoisting", function() {
    macro m {
      case $x:lit => {
        var tmp = $x;
      }
    }

    var tmp = "outer"
    m "inner"
    expect(tmp).to.be("outer");

  });

  it("should work for vars with hoisting and params", function() {
    function f(tmp) {
      macro m {
        case $x:lit => {
          var tmp = $x;
        }
      }

      var tmp = "outer"
      m "inner"
      expect(tmp).to.be("outer");
    }

    f("call")

  });

  it("should work for var with nested function", function() {
    macro m {
      case $x:lit => {
        var tmp = $x;
      }
    }
    function f() {
      var tmp = "outer"
      m "inner"
      expect(tmp).to.be("outer");
    }
    f();
  });

  // todo this test needs a better api (syntax-case?)

  // it("should work for another variant of hygiene", function() {
  //   (function(x) {

  //     macro n {
  //       case ($stx:lit) => {
  //         function(x) {
  //           // want a way to distinguish between the two versions of x
  //           return x + x
  //         }
  //       }
  //     }

  //   })(42);
  // });

  // it("should work for the or macro with var", function() {
  //   macro or {
  //     case ($x:expr, $y:expr) => {
  //       (function() {
  //         var $tmp = $x;
  //         return $tmp ? $tmp : $y;
  //       })();
  //     }
  //   }

  //   var $tmp = "ok"
  //   var z = or(false, $tmp);
  //   expect(z).to.be("ok");
  // });

});
<|endoftext|>


<commit_before>import Ember from 'ember';
import emberRequire from './ext-require';

const EmberView = emberRequire('ember-views/views/view');
const RoutingService = emberRequire('ember-routing/services/routing');
const Engine = emberRequire('ember-application/system/engine');

const {
  SelectView,
  OutletView,
  TextField,
  TextArea,
  Checkbox,
  ContainerDebugAdapter,
  ComponentLookup,
  LinkComponent
} = Ember;

Engine.reopen({
  buildRegistry() {
    let namespace = this;
    let registry = this._super(...arguments);

    if (!(this instanceof Ember.Application)) {
      registry.optionsForType('component', { singleton: false });
      registry.optionsForType('view', { singleton: false });
      registry.optionsForType('template', { instantiate: false });

      registry.register('application:main', namespace, { instantiate: false });

      registry.register('controller:basic', Ember.Controller, { instantiate: false });

      // registry.register('renderer:-dom', { create() { return new Renderer(new DOMHelper()); } });

      registry.injection('view', 'renderer', 'renderer:-dom');

      if (Ember.ENV._ENABLE_LEGACY_VIEW_SUPPORT) {
        registry.register('view:select', SelectView);
      }
      registry.register('view:-outlet', OutletView);

      //registry.register('-view-registry:main', { create() { return {}; } });

      registry.injection('view', '_viewRegistry', '-view-registry:main');

      registry.register('view:toplevel', EmberView.extend());

      // registry.register('route:basic', Route, { instantiate: false });
      // registry.register('event_dispatcher:main', EventDispatcher);

      // registry.injection('router:main', 'namespace', 'application:main');
      registry.injection('view:-outlet', 'namespace', 'application:main');

      // registry.register('location:auto', AutoLocation);
      // registry.register('location:hash', HashLocation);
      // registry.register('location:history', HistoryLocation);
      // registry.register('location:none', NoneLocation);

      registry.injection('controller', 'target', 'router:main');
      registry.injection('controller', 'namespace', 'application:main');

      // registry.register('-bucket-cache:main', BucketCache);
      registry.injection('router', '_bucketCache', '-bucket-cache:main');
      registry.injection('route', '_bucketCache', '-bucket-cache:main');
      registry.injection('controller', '_bucketCache', '-bucket-cache:main');

      registry.injection('route', 'router', 'router:main');

      registry.register('component:-text-field', TextField);
      registry.register('component:-text-area', TextArea);
      registry.register('component:-checkbox', Checkbox);
      // registry.register('view:-legacy-each', LegacyEachView);
      registry.register('component:link-to', LinkComponent);

      // Register the routing service...
      registry.register('service:-routing', RoutingService);
      // Then inject the app router into it
      registry.injection('service:-routing', 'router', 'router:main');

      // DEBUGGING
      registry.register('resolver-for-debugging:main', registry.resolver, { instantiate: false });
      registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
      registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
      // Custom resolver authors may want to register their own ContainerDebugAdapter with this key

      registry.register('container-debug-adapter:main', ContainerDebugAdapter);

      registry.register('component-lookup:main', ComponentLookup);
    }

    return registry;
  }
});
<commit_msg>Fix error when legacy view support is on.<commit_after>import Ember from 'ember';
import emberRequire from './ext-require';

const SelectView = emberRequire('ember-views/views/select');
const EmberView = emberRequire('ember-views/views/view');
const RoutingService = emberRequire('ember-routing/services/routing');
const Engine = emberRequire('ember-application/system/engine');

const {
  OutletView,
  TextField,
  TextArea,
  Checkbox,
  ContainerDebugAdapter,
  ComponentLookup,
  LinkComponent
} = Ember;

Engine.reopen({
  buildRegistry() {
    let namespace = this;
    let registry = this._super(...arguments);

    if (!(this instanceof Ember.Application)) {
      registry.optionsForType('component', { singleton: false });
      registry.optionsForType('view', { singleton: false });
      registry.optionsForType('template', { instantiate: false });

      registry.register('application:main', namespace, { instantiate: false });

      registry.register('controller:basic', Ember.Controller, { instantiate: false });

      // registry.register('renderer:-dom', { create() { return new Renderer(new DOMHelper()); } });

      registry.injection('view', 'renderer', 'renderer:-dom');

      if (Ember.ENV._ENABLE_LEGACY_VIEW_SUPPORT) {
        registry.register('view:select', SelectView);
      }
      registry.register('view:-outlet', OutletView);

      //registry.register('-view-registry:main', { create() { return {}; } });

      registry.injection('view', '_viewRegistry', '-view-registry:main');

      registry.register('view:toplevel', EmberView.extend());

      // registry.register('route:basic', Route, { instantiate: false });
      // registry.register('event_dispatcher:main', EventDispatcher);

      // registry.injection('router:main', 'namespace', 'application:main');
      registry.injection('view:-outlet', 'namespace', 'application:main');

      // registry.register('location:auto', AutoLocation);
      // registry.register('location:hash', HashLocation);
      // registry.register('location:history', HistoryLocation);
      // registry.register('location:none', NoneLocation);

      registry.injection('controller', 'target', 'router:main');
      registry.injection('controller', 'namespace', 'application:main');

      // registry.register('-bucket-cache:main', BucketCache);
      registry.injection('router', '_bucketCache', '-bucket-cache:main');
      registry.injection('route', '_bucketCache', '-bucket-cache:main');
      registry.injection('controller', '_bucketCache', '-bucket-cache:main');

      registry.injection('route', 'router', 'router:main');

      registry.register('component:-text-field', TextField);
      registry.register('component:-text-area', TextArea);
      registry.register('component:-checkbox', Checkbox);
      // registry.register('view:-legacy-each', LegacyEachView);
      registry.register('component:link-to', LinkComponent);

      // Register the routing service...
      registry.register('service:-routing', RoutingService);
      // Then inject the app router into it
      registry.injection('service:-routing', 'router', 'router:main');

      // DEBUGGING
      registry.register('resolver-for-debugging:main', registry.resolver, { instantiate: false });
      registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
      registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
      // Custom resolver authors may want to register their own ContainerDebugAdapter with this key

      registry.register('container-debug-adapter:main', ContainerDebugAdapter);

      registry.register('component-lookup:main', ComponentLookup);
    }

    return registry;
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from 'ember-cli-onedata-common/templates/components/one-icon';

const {computed} = Ember;

/**
 * Inserts a icon from oneicons font.
 * Typical usage: ``{{one-icon icon='home'}}``
 * @module components/one-icon
 * @author Jakub Liput
 * @copyright (C) 2016 ACK CYFRONET AGH
 * @license This software is released under the MIT license cited in 'LICENSE.txt'.
 */
export default Ember.Component.extend({
  layout,

  tagName: 'span',
  classNames: ['one-icon'],
  classNameBindings: ['iconClass'],

  // defaults
  icon: 'checkbox-x',
  color: '',
  addClass: '',

  iconClass: computed('icon', function() {
    return `oneicon-${this.get('icon')}`;
  }),
});
<commit_msg>VFS-2417 Fixing issues with new one-icon<commit_after>import Ember from 'ember';
import layout from 'ember-cli-onedata-common/templates/components/one-icon';

const {computed} = Ember;

/**
 * Inserts a icon from oneicons font.
 * Typical usage: ``{{one-icon icon='home'}}``
 * @module components/one-icon
 * @author Jakub Liput
 * @copyright (C) 2016 ACK CYFRONET AGH
 * @license This software is released under the MIT license cited in 'LICENSE.txt'.
 */
export default Ember.Component.extend({
  layout,

  tagName: 'span',
  classNames: ['one-icon', 'oneicon'],
  classNameBindings: ['iconClass'],

  // defaults
  icon: 'checkbox-x',
  color: '',
  addClass: '',

  iconClass: computed('icon', function() {
    return `oneicon-${this.get('icon')}`;
  }),
});
<|endoftext|>


<commit_before>import Ember from 'ember';

const map = new Map();

export default Ember.Mixin.create({
  setParam(name, value) {
    if (map.has(name)) {
      map.get(name).value = value;
      this.callCbs(name);
    } else {
      map.set(name, {
        value,
        cbs: []
      });
    }
  },

  getParam(name) {
  	var item = map.get(name);
    return item ? item.value : undefined;
  },

  subscribe(name, cb) {
    if (map.has(name)) {
      let item = map.get(name);
      item.cbs.push(cb);
    } else {
    	map.set(name, {
				value: undefined,
        cbs: [cb]
      });
    }
  },

  autoSubscribe(context) {
  	if (!context || !context.queryParams) {
    	return;
    }

    let keys = context.queryParams.reduce((all, item) => {
    	if (typeof item === 'string') {
      	all.push(item);
      } else if (typeof item === 'object') {
      	all = all.concat(Object.keys(item));
      }

      return all;
    }, []);
    let update = (name, val) => {
      Ember.run(context, 'set', name, val);
    };

    keys.forEach(key => this.subscribe(key, update));
  },

  callCbs(name) {
  	if (map.has(name)) {
      let item = map.get(name);
      item.cbs.forEach(cb => cb(name, item.value));
    }
  }
});
<commit_msg>Do not call callbacks on a destroyed object.<commit_after>import Ember from 'ember';

const map = new Map();

export default Ember.Mixin.create({
  setParam(name, value) {
    if (map.has(name)) {
      map.get(name).value = value;
      this.callCbs(name);
    } else {
      map.set(name, {
        value,
        cbs: []
      });
    }
  },

  getParam(name) {
  	var item = map.get(name);
    return item ? item.value : undefined;
  },

  subscribe(name, cb) {
    if (map.has(name)) {
      let item = map.get(name);
      item.cbs.push(cb);
    } else {
    	map.set(name, {
				value: undefined,
        cbs: [cb]
      });
    }
  },

  autoSubscribe(context) {
  	if (!context || !context.queryParams) {
    	return;
    }

    let keys = context.queryParams.reduce((all, item) => {
    	if (typeof item === 'string') {
      	all.push(item);
      } else if (typeof item === 'object') {
      	all = all.concat(Object.keys(item));
      }

      return all;
    }, []);
    let update = (name, val) => {
      if (context.isDestroyed || context.isDestroying) {
        return;
      }

      Ember.run(context, 'set', name, val);
    };

    keys.forEach(key => this.subscribe(key, update));
  },

  callCbs(name) {
  	if (map.has(name)) {
      let item = map.get(name);
      item.cbs.forEach(cb => cb(name, item.value));
    }
  }
});
<|endoftext|>


<commit_before>/* globals plupload */
import Ember from "ember";
import File from "./file";
import trim from "./trim";
import computed from './computed';

const get = Ember.get;
const set = Ember.set;
const bool = Ember.computed.bool;
const bind = Ember.run.bind;
const copy = Ember.copy;
const merge = Ember.merge;

var summation = function (target, key) {
  return target.reduce(function (E, obj) {
    return E + get(obj, key);
  }, 0);
};

/**

  @namespace ember-plupload
  @class UploadQueue
  @extend Ember.ArrayProxy
 */
export default Ember.ArrayProxy.extend({

  name: null,

  uploading: bool('length'),

  queues: null,

  init: function () {
    set(this, 'queues', Ember.A([]));
    set(this, 'orphanedQueues', Ember.A([]));

    set(this, 'content', Ember.A([]));
    this._super();
  },

  configure: function (config = {}) {
    var uploader = new plupload.Uploader(config);

    uploader.bind('FilesAdded',     bind(this, 'filesAdded'));
    uploader.bind('FilesRemoved',   bind(this, 'filesRemoved'));
    uploader.bind('BeforeUpload',   bind(this, 'configureUpload'));
    uploader.bind('UploadProgress', bind(this, 'progressDidChange'));
    uploader.bind('FileUploaded',   bind(this, 'fileUploaded'));
    uploader.bind('UploadComplete', bind(this, 'uploadComplete'));
    uploader.bind('Error',          bind(this, 'onError'));

    get(this, 'queues').pushObject(uploader);

    // Set browse_button and drop_element as
    // references to the buttons so mOxie doesn't
    // get confused when the dom might be detached
    uploader.settings.browse_button = [config.browse_button];
    uploader.settings.drop_element = [config.drop_element];

    let settings = copy(uploader.settings);
    delete settings.url;
    set(this, 'settings', settings);

    uploader.init();
    return uploader;
  },

  /**
    Orphan the active plupload object so
    we garbage collect the queues.
   */
  orphan: function () {
    var orphans = get(this, 'orphanedQueues');
    var activeQueues = get(this, 'queues').filter(function (queue) {
      return orphans.indexOf(queue) === -1;
    });
    var queue = get(Ember.A(activeQueues), 'lastObject');
    if (get(queue, 'total.queued') > 0) {
      orphans.pushObject(queue);
    } else {
      this.garbageCollectUploader(queue);
    }
  },

  destroy: function () {
    this._super();
    get(this, 'queues').invoke('unbindAll');
    set(this, 'content', Ember.A([]));
    set(this, 'queues', null);
  },

  refresh: function () {
    get(this, 'queues').invoke('refresh');
  },

  progress: computed({
    get() {
      const queues        = get(this, 'queues');
      const totalSize     = summation(queues, 'total.size');
      const totalUploaded = summation(queues, 'total.loaded');
      const percent       = totalUploaded / totalSize || 0;

      return Math.floor(percent * 100);
    }
  }),

  filesAdded: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = File.create({
        uploader: uploader,
        file: files[i]
      });

      this.pushObject(file);
      get(this, 'target').sendAction('when-queued', file, {
        name: get(this, 'name'),
        uploader: uploader,
        queue: this
      });
    }
  },

  filesRemoved: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = this.findProperty('id', files[i].id);
      if (file) {
        this.removeObject(file);
      }
    }
  },

  configureUpload: function (uploader, file) {
    file = this.findProperty('id', file.id);
    // Reset settings for merging
    uploader.settings = copy(get(this, 'settings'));
    merge(uploader.settings, file.settings);

    this.progressDidChange(uploader, file);
  },

  progressDidChange: function (uploader, file) {
    file = this.findProperty('id', file.id);
    if (file) {
      file.notifyPropertyChange('progress');
    }

    this.notifyPropertyChange('progress');
  },

  parseResponse: function (response) {
    var body = trim(response.response);
    var rawHeaders = Ember.A(response.responseHeaders.split(/\n|\r/)).without('');
    var headers = rawHeaders.reduce(function (headers, header) {
      var parts = header.split(/^([A-Za-z_-]*:)/);
      if (parts.length > 0){
        headers[parts[1].slice(0, -1)] = trim(parts[2]);
      }
      return headers;
    }, {});

    var contentType = (headers['Content-Type'] || '').split(';');
    // Parse body according to the Content-Type received by the server
    if (contentType.indexOf('text/html') !== -1) {
      body = Ember.$.parseHTML(body);
    } else if (contentType.indexOf('text/xml') !== -1) {
      body = Ember.$.parseXML(body);
    } else if (contentType.indexOf('application/json') !== -1 ||
               contentType.indexOf('text/javascript') !== -1 ||
               contentType.indexOf('application/javascript') !== -1) {
      body = Ember.$.parseJSON(body);
    }

    return {
      status: response.status,
      body: body,
      headers: headers
    };
  },

  fileUploaded: function (uploader, file, response) {
    var results = this.parseResponse(response);
    file = this.findProperty('id', file.id);
    if (file) {
      this.removeObject(file);
    }

    // NOTE: Plupload calls UploadProgress upon triggering FileUploaded,
    //       so we don't need to trigger a progress event
    if (results.status === 204 ||
        results.status === 200 ||
        results.status === 201) {
      file._deferred.resolve(results);
    } else {
      file._deferred.reject(results);
    }

    // Notify plupload that our browse_button may have
    // changed locations
    Ember.run.later(uploader, 'refresh', 750);
  },

  garbageCollectUploader: function (uploader) {
    get(this, 'queues').removeObject(uploader);
    get(this, 'orphanedQueues').removeObject(uploader);
    this.filterProperty('uploader', uploader).invoke('destroy');
    uploader.unbindAll();
  },

  uploadComplete: function (uploader) {
    // Notify plupload that our browse_button may have
    // changed locations
    Ember.run.later(uploader, 'refresh', 750);
    this.notifyPropertyChange('progress');

    // Clean up the orphaned uploader and its files
    if (get(this, 'orphanedQueues').indexOf(uploader) !== -1) {
      this.garbageCollectUploader(uploader);
    }
  },

  onError: function (uploader, error) {
    if (error.file) {
      var file = this.findProperty('id', error.file.id);
      if (file == null) {
        file = File.create({
          uploader: uploader,
          file: file
        });
      }

      set(file, 'error', error);

      if (file._deferred) {
        file._deferred.reject(error);

      // This happended before the file got queued,
      // So we need to stub out `upload` and trigger
      // the queued event
      } else {
        file.upload = file.read = function () {
          Ember.run.debounce(uploader, 'refresh', 750);
          return Ember.RSVP.reject(error, `File: '${error.file.id}' ${error.message}`);
        };
        file.isDestroyed = true;

        get(this, 'target').sendAction('when-queued', file, {
          name: get(this, 'name'),
          uploader: uploader,
          queue: this
        });
      }
      this.notifyPropertyChange('length');
      Ember.run.debounce(uploader, 'refresh', 750);
    } else {
      set(this, 'error', error);
    }
  }
});
<commit_msg>Check for lower case content-type header<commit_after>/* globals plupload */
import Ember from "ember";
import File from "./file";
import trim from "./trim";
import computed from './computed';

const get = Ember.get;
const set = Ember.set;
const bool = Ember.computed.bool;
const bind = Ember.run.bind;
const copy = Ember.copy;
const merge = Ember.merge;

var summation = function (target, key) {
  return target.reduce(function (E, obj) {
    return E + get(obj, key);
  }, 0);
};

/**

  @namespace ember-plupload
  @class UploadQueue
  @extend Ember.ArrayProxy
 */
export default Ember.ArrayProxy.extend({

  name: null,

  uploading: bool('length'),

  queues: null,

  init: function () {
    set(this, 'queues', Ember.A([]));
    set(this, 'orphanedQueues', Ember.A([]));

    set(this, 'content', Ember.A([]));
    this._super();
  },

  configure: function (config = {}) {
    var uploader = new plupload.Uploader(config);

    uploader.bind('FilesAdded',     bind(this, 'filesAdded'));
    uploader.bind('FilesRemoved',   bind(this, 'filesRemoved'));
    uploader.bind('BeforeUpload',   bind(this, 'configureUpload'));
    uploader.bind('UploadProgress', bind(this, 'progressDidChange'));
    uploader.bind('FileUploaded',   bind(this, 'fileUploaded'));
    uploader.bind('UploadComplete', bind(this, 'uploadComplete'));
    uploader.bind('Error',          bind(this, 'onError'));

    get(this, 'queues').pushObject(uploader);

    // Set browse_button and drop_element as
    // references to the buttons so mOxie doesn't
    // get confused when the dom might be detached
    uploader.settings.browse_button = [config.browse_button];
    uploader.settings.drop_element = [config.drop_element];

    let settings = copy(uploader.settings);
    delete settings.url;
    set(this, 'settings', settings);

    uploader.init();
    return uploader;
  },

  /**
    Orphan the active plupload object so
    we garbage collect the queues.
   */
  orphan: function () {
    var orphans = get(this, 'orphanedQueues');
    var activeQueues = get(this, 'queues').filter(function (queue) {
      return orphans.indexOf(queue) === -1;
    });
    var queue = get(Ember.A(activeQueues), 'lastObject');
    if (get(queue, 'total.queued') > 0) {
      orphans.pushObject(queue);
    } else {
      this.garbageCollectUploader(queue);
    }
  },

  destroy: function () {
    this._super();
    get(this, 'queues').invoke('unbindAll');
    set(this, 'content', Ember.A([]));
    set(this, 'queues', null);
  },

  refresh: function () {
    get(this, 'queues').invoke('refresh');
  },

  progress: computed({
    get() {
      const queues        = get(this, 'queues');
      const totalSize     = summation(queues, 'total.size');
      const totalUploaded = summation(queues, 'total.loaded');
      const percent       = totalUploaded / totalSize || 0;

      return Math.floor(percent * 100);
    }
  }),

  filesAdded: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = File.create({
        uploader: uploader,
        file: files[i]
      });

      this.pushObject(file);
      get(this, 'target').sendAction('when-queued', file, {
        name: get(this, 'name'),
        uploader: uploader,
        queue: this
      });
    }
  },

  filesRemoved: function (uploader, files) {
    for (var i = 0, len = files.length; i < len; i++) {
      var file = this.findProperty('id', files[i].id);
      if (file) {
        this.removeObject(file);
      }
    }
  },

  configureUpload: function (uploader, file) {
    file = this.findProperty('id', file.id);
    // Reset settings for merging
    uploader.settings = copy(get(this, 'settings'));
    merge(uploader.settings, file.settings);

    this.progressDidChange(uploader, file);
  },

  progressDidChange: function (uploader, file) {
    file = this.findProperty('id', file.id);
    if (file) {
      file.notifyPropertyChange('progress');
    }

    this.notifyPropertyChange('progress');
  },

  parseResponse: function (response) {
    var body = trim(response.response);
    var rawHeaders = Ember.A(response.responseHeaders.split(/\n|\r/)).without('');
    var headers = rawHeaders.reduce(function (headers, header) {
      var parts = header.split(/^([A-Za-z_-]*:)/);
      if (parts.length > 0){
        headers[parts[1].slice(0, -1)] = trim(parts[2]);
      }
      return headers;
    }, {});

    var contentType = (headers['Content-Type'] || headers['content-type'] || '').split(';');
    // Parse body according to the Content-Type received by the server
    if (contentType.indexOf('text/html') !== -1) {
      body = Ember.$.parseHTML(body);
    } else if (contentType.indexOf('text/xml') !== -1) {
      body = Ember.$.parseXML(body);
    } else if (contentType.indexOf('application/json') !== -1 ||
               contentType.indexOf('text/javascript') !== -1 ||
               contentType.indexOf('application/javascript') !== -1) {
      body = Ember.$.parseJSON(body);
    }

    return {
      status: response.status,
      body: body,
      headers: headers
    };
  },

  fileUploaded: function (uploader, file, response) {
    var results = this.parseResponse(response);
    file = this.findProperty('id', file.id);
    if (file) {
      this.removeObject(file);
    }

    // NOTE: Plupload calls UploadProgress upon triggering FileUploaded,
    //       so we don't need to trigger a progress event
    if (results.status === 204 ||
        results.status === 200 ||
        results.status === 201) {
      file._deferred.resolve(results);
    } else {
      file._deferred.reject(results);
    }

    // Notify plupload that our browse_button may have
    // changed locations
    Ember.run.later(uploader, 'refresh', 750);
  },

  garbageCollectUploader: function (uploader) {
    get(this, 'queues').removeObject(uploader);
    get(this, 'orphanedQueues').removeObject(uploader);
    this.filterProperty('uploader', uploader).invoke('destroy');
    uploader.unbindAll();
  },

  uploadComplete: function (uploader) {
    // Notify plupload that our browse_button may have
    // changed locations
    Ember.run.later(uploader, 'refresh', 750);
    this.notifyPropertyChange('progress');

    // Clean up the orphaned uploader and its files
    if (get(this, 'orphanedQueues').indexOf(uploader) !== -1) {
      this.garbageCollectUploader(uploader);
    }
  },

  onError: function (uploader, error) {
    if (error.file) {
      var file = this.findProperty('id', error.file.id);
      if (file == null) {
        file = File.create({
          uploader: uploader,
          file: file
        });
      }

      set(file, 'error', error);

      if (file._deferred) {
        file._deferred.reject(error);

      // This happended before the file got queued,
      // So we need to stub out `upload` and trigger
      // the queued event
      } else {
        file.upload = file.read = function () {
          Ember.run.debounce(uploader, 'refresh', 750);
          return Ember.RSVP.reject(error, `File: '${error.file.id}' ${error.message}`);
        };
        file.isDestroyed = true;

        get(this, 'target').sendAction('when-queued', file, {
          name: get(this, 'name'),
          uploader: uploader,
          queue: this
        });
      }
      this.notifyPropertyChange('length');
      Ember.run.debounce(uploader, 'refresh', 750);
    } else {
      set(this, 'error', error);
    }
  }
});
<|endoftext|>


<commit_before>var through2 = require('through2')
var mbstream = require('multibuffer-stream')
var buff = require('multibuffer')
var bops = require('bops')
var concat = require('concat-stream')
var os = require('os')
var protobuf = require('protocol-buffers')
var json = require('json-protobuf-encoding')
var ndjson = require('ndjson')

var proto = function(sch) {
  return protobuf(sch, {encodings:{json:json()}}).Row
}

module.exports.readStreamBuff = function(test, common) {
  test('readStream returns all buff rows', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ columns: ['num'], protobuf: true, quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.num })
          t.equals(JSON.stringify(nums.sort()), JSON.stringify(results.sort()), 'matches')
          done()
        }))
      })

      var packStream = mbstream.packStream()
      packStream.pipe(ws)
      var schema = proto('message Row { optional json num = 1; }')

      // create a bunch of single cell buff rows with incrementing integers in them
      for (var i = 0; i < 1000; i++) {
        packStream.write(schema.encode({num:i+''}))
        nums.push(i + '')
      }
      packStream.end()
    })
  })
}

module.exports.readStreamBuffPrimaryKey = function(test, common) {
  test('readStream returns all buff rows w/ custom primary key', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ columns: ['num'], primary: 'num', protobuf: true, quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.num })
          t.equals(JSON.stringify(nums.sort()), JSON.stringify(results.sort()), 'matches')
          done()
        }))
      })

      var packStream = mbstream.packStream()
      packStream.pipe(ws)

      var schema = proto('message Row { optional json num = 1; }')

      // create a bunch of single cell buff rows with incrementing integers in them
      for (var i = 0; i < 1000; i++) {
        packStream.write(schema.encode({num:i+''}))
        nums.push(i + '')
      }

      packStream.end()
    })
  })
}

module.exports.readStreamCsvPrimaryKey = function(test, common) {
  test('readStream returns all csv rows w/ custom primary key', function(t) {
    var expected = ['1', '10', '100']
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, primary: 'a', quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.key })
          t.equals(JSON.stringify(results.sort()), JSON.stringify(expected.sort()), 'matches')
          done()
        }))
      })

      ws.write(bops.from('a,b,c\n1,1,1\n10,1,1\n100,1,1'))
      ws.end()
    })
  })
}

module.exports.readStreamNdjPrimaryKey = function(test, common) {
  test('readStream returns all ndjson rows w/ custom primary key', function(t) {
    var expected = ['1', '10', '100']
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ json: true, primary: 'a', quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.key })
          t.equals(JSON.stringify(results.sort()), JSON.stringify(expected.sort()), 'order matches')
          done()
        }))
      })

      ws.write(bops.from(JSON.stringify({"a": "1", "b": "foo"}) + os.EOL))
      ws.write(bops.from(JSON.stringify({"a": "10", "b": "foo"}) + os.EOL))
      ws.write(bops.from(JSON.stringify({"a": "100", "b": "foo"})))
      ws.end()
    })
  })
}

module.exports.getChanges = function(test, common) {
  test('getChanges', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, quiet: true })

      ws.on('finish', function() {
        dat.createChangesReadStream({data: true}).pipe(concat(function(data) {
          var changes = data.map(function(r) { return r.change })
          t.equal(JSON.stringify(changes), JSON.stringify([1,2,3,4,5,6]) , 'ordered changes 1 - 6 exist') // 5 rows + 1 schema
          t.equal(!!data[0].value, true)
          done()
        }))
      })

      ws.write(bops.from('a,b,c\n10,1,1\n100,1,1\n1,1,1\n1,1,1\n1,1,1'))
      ws.end()
    })
  })
}

module.exports.changesStream = function(test, common) {
  test('simple put should trigger a change', function(t) {
    common.getDat(t, function(dat, done) {
      var changes = dat.createChangesReadStream({ live: true, data: true, decode: true })
      var gotChange = false
      setTimeout(function() {
        if (gotChange) return
        t.false(true, 'timeout')
        setImmediate(done)
      }, 1000)

      changes.pipe(through2({objectMode: true}, function(obj, enc, next) {
        if (obj.subset) return next()
        changes.destroy()
        t.equal(obj.value.foo, "bar")
        gotChange = true
        setImmediate(done)
      }))

      dat.put({"foo": "bar"}, function(err, doc) {
        if (err) throw err
      })
    })
  })
}

module.exports.changesStreamTail = function(test, common) {
  test('createChangesStream tail:true', function(t) {
    common.getDat(t, function(dat, done) {

      dat.put({"foo": "old"}, function(err) {
        t.notOk(err, 'should not err')

        var changes = dat.createChangesReadStream({ live: true, tail: true, data: true, decode: true })
        var gotChange = false
        setTimeout(function() {
          if (gotChange) return
          t.false(true, 'timeout')
          setImmediate(done)
        }, 1000)

        changes.pipe(through2({objectMode: true}, function(obj, enc, next) {
          if (obj.subset) return next()
          changes.destroy()
          t.equal(obj.value.foo, "new", 'should only get new row, not old row')
          gotChange = true
          setImmediate(done)
        }))

        dat.put({"foo": "new"}, function(err) {
          t.notOk(err, 'should not err')
        })
      })

    })
  })
}

module.exports.changesStreamTailNum = function(test, common) {
  test('createChangesStream tail:1', function(t) {
    common.getDat(t, function(dat, done) {

      var ws = dat.createWriteStream({quiet: true})

      ws.on('error', function(err) {
        t.notOk(err)
        setImmediate(done)
      })

      ws.on('finish', function() {
        var changes = dat.createChangesReadStream({ live: true, tail: 1, data: true, decode: true })

        var gotChange = false
        setTimeout(function() {
          if (gotChange) return
          t.false(true, 'timeout')
          setImmediate(done)
        }, 1000)

        changes.pipe(through2({objectMode: true}, function(obj, enc, next) {
          if (obj.subset) return next()
          changes.destroy()
          t.equal(obj.value.foo, "taco", 'should only get 1 newest row, not older rows')
          gotChange = true
          setImmediate(done)
          next()
        }))
      })

      ws.write({'foo': 'bar'})
      ws.write({'foo': 'baz'})
      ws.write({'foo': 'taco'})
      ws.end()

    })
  })
}

module.exports.createReadStream = function(test, common) {
  test('createReadStream', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, quiet: true })

      ws.on('finish', function() {
        var readStream = dat.createReadStream()
        readStream.pipe(concat(function(rows) {
          t.equal(rows.length, 5, '5 rows')
          done()
        }))
      })

      ws.write(bops.from('a,b,c\n10,1,1\n100,1,1\n1,1,1\n1,1,1\n1,1,1'))
      ws.end()
    })
  })
}

module.exports.createReadStreamStartEndKeys = function(test, common) {
  test('createReadStream w/ start + end keys', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, primary: 'a', quiet: true })

      ws.on('finish', function() {
        var readStream = dat.createReadStream({ start: '2', end: '4'})
        readStream.pipe(concat(function(rows) {
          t.equal(rows.length, 3, '3 rows')
          t.equal(rows[0].a, '2')
          t.equal(rows[1].a, '3')
          t.equal(rows[2].a, '4')
          done()
        }))
      })

      ws.write(bops.from('a\n1\n2\n3\n4\n5'))
      ws.end()
    })
  })
}

module.exports.createReadStreamFormats = function (test, common) {
  test('createReadStream json', function (t) {
    common.getDat(t, function (dat, done) {
      var ws = dat.createWriteStream({primary: 'a', quiet: true})
      ws.on('finish', csvFormat)
      ws.write({a: 1})
      ws.write({a: 2})
      ws.write({a: 3})
      ws.end()

      function csvFormat() {
        var rs = dat.createReadStream({ csv: true })
        rs.pipe(concat(function(data) {
          var rows = data.split('\n')
          t.equal(rows[0].split(',').length, 3, 'csv header')
          t.equal(rows[1].split(',').length, 3, 'csv first row')
          t.equal(rows.length, 5, 'csv length')
          jsonStyleObject()
        }))
      }

      function jsonStyleObject() {
        var rs = dat.createReadStream({format: 'json'})
        rs.pipe(concat(function (data) {
          var json = JSON.parse(data)
          t.equals(json.rows.length, 3, 'json object style length')
          t.equals(json.rows[0].a, 1, 'json object style data')
          t.equals(Object.keys(json.rows[0]).length, 3, 'json object style keys')
          jsonStyleArray()
        }))
      }

      function jsonStyleArray() {
        var rs = dat.createReadStream({format: 'json', style: 'array'})
        rs.pipe(concat(function (data) {
          var json = JSON.parse(data)
          t.equals(json.length, 3, 'json array style length')
          t.equals(json[0].a, 1, 'json array style data')
          t.equals(Object.keys(json[0]).length, 3, 'json object style keys')
          ndjsonFormat()
        }))
      }

      function ndjsonFormat() {
        var rs = dat.createReadStream({format: 'ndjson'})
        rs.pipe(ndjson.parse()).pipe(concat(function (json) {
          t.equals(json.length, 3, 'ndjson length')
          t.equals(json[0].a, 1, 'ndjson first row data')
          t.equals(Object.keys(json[0]).length, 3, 'ndjson first row keys')
          sseFormat()
        }))
      }

      function sseFormat() {
        var rs = dat.createReadStream({format: 'sse'})
        rs.pipe(concat(function (data) {
          var rows = data.split('\n\n')
          t.equals(rows.length, 4, 'sse length')
          var row = rows[0].split('event: data\ndata: ')
          t.equals(row.length, 2, 'sse header')
          var json = {}
          try { json = JSON.parse(row[1]) } catch(e) { t.fail(e.message)}
          t.equals(json.a, 1, 'sse first row data')
          t.equals(Object.keys(json).length, 3, 'sse first row keys')
          done()
        }))
      }

    })
  })
}

module.exports.createReadStreamNDJSON = function (test, common) {
  test('createReadStream ndjson', function (t) {
    common.getDat(t, function (dat, done) {

    })
  })
}

module.exports.createVersionStream = function(test, common) {
  test('createVersionStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put("foo", {"baz": "bar"}, function(err, doc) {
        t.false(err)
        var ver1 = doc.version
        doc.pizza = 'taco'
        dat.put(doc, function(err, doc) {
          t.false(err)
          // put some data before and after to make sure they dont get returned too
          dat.put("abc", {'bar': 'baz'}, function(err) {
            t.false(err)
            dat.put("xyz", {'bar': 'baz'}, function(err) {
              t.false(err)
              readVersions()
            })
          })
        })
      })

      function readVersions() {
        dat.createVersionStream('foo').pipe(concat(function(versions) {
          t.equal(versions.length, 2, '2 versions')
          var v1 = versions[0] || {version: ""}
          var v2 = versions[1] || {version: ""}
          t.equal(v1.version, 1)
          t.equal(v2.version, 2)
          t.equal(v1.pizza, null, 'version 1')
          t.equal(v2.pizza, 'taco', 'version 2')
          setImmediate(done)
        }))
      }
    })
  })
}

module.exports.all = function (test, common) {
  module.exports.readStreamBuff(test, common)
  module.exports.readStreamBuffPrimaryKey(test, common)
  module.exports.readStreamCsvPrimaryKey(test, common)
  module.exports.readStreamNdjPrimaryKey(test, common)
  module.exports.getChanges(test, common)
  module.exports.changesStream(test, common)
  module.exports.changesStreamTail(test, common)
  module.exports.changesStreamTailNum(test, common)
  module.exports.createReadStream(test, common)
  module.exports.createReadStreamStartEndKeys(test, common)
  module.exports.createReadStreamFormats(test, common)
  module.exports.createVersionStream(test, common)
}
<commit_msg>removed unused test<commit_after>var through2 = require('through2')
var mbstream = require('multibuffer-stream')
var buff = require('multibuffer')
var bops = require('bops')
var concat = require('concat-stream')
var os = require('os')
var protobuf = require('protocol-buffers')
var json = require('json-protobuf-encoding')
var ndjson = require('ndjson')

var proto = function(sch) {
  return protobuf(sch, {encodings:{json:json()}}).Row
}

module.exports.readStreamBuff = function(test, common) {
  test('readStream returns all buff rows', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ columns: ['num'], protobuf: true, quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.num })
          t.equals(JSON.stringify(nums.sort()), JSON.stringify(results.sort()), 'matches')
          done()
        }))
      })

      var packStream = mbstream.packStream()
      packStream.pipe(ws)
      var schema = proto('message Row { optional json num = 1; }')

      // create a bunch of single cell buff rows with incrementing integers in them
      for (var i = 0; i < 1000; i++) {
        packStream.write(schema.encode({num:i+''}))
        nums.push(i + '')
      }
      packStream.end()
    })
  })
}

module.exports.readStreamBuffPrimaryKey = function(test, common) {
  test('readStream returns all buff rows w/ custom primary key', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ columns: ['num'], primary: 'num', protobuf: true, quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.num })
          t.equals(JSON.stringify(nums.sort()), JSON.stringify(results.sort()), 'matches')
          done()
        }))
      })

      var packStream = mbstream.packStream()
      packStream.pipe(ws)

      var schema = proto('message Row { optional json num = 1; }')

      // create a bunch of single cell buff rows with incrementing integers in them
      for (var i = 0; i < 1000; i++) {
        packStream.write(schema.encode({num:i+''}))
        nums.push(i + '')
      }

      packStream.end()
    })
  })
}

module.exports.readStreamCsvPrimaryKey = function(test, common) {
  test('readStream returns all csv rows w/ custom primary key', function(t) {
    var expected = ['1', '10', '100']
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, primary: 'a', quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.key })
          t.equals(JSON.stringify(results.sort()), JSON.stringify(expected.sort()), 'matches')
          done()
        }))
      })

      ws.write(bops.from('a,b,c\n1,1,1\n10,1,1\n100,1,1'))
      ws.end()
    })
  })
}

module.exports.readStreamNdjPrimaryKey = function(test, common) {
  test('readStream returns all ndjson rows w/ custom primary key', function(t) {
    var expected = ['1', '10', '100']
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ json: true, primary: 'a', quiet: true })
      var nums = []

      ws.on('finish', function() {
        dat.createReadStream().pipe(concat(function(data) {
          var results = data.map(function(r) { return r.key })
          t.equals(JSON.stringify(results.sort()), JSON.stringify(expected.sort()), 'order matches')
          done()
        }))
      })

      ws.write(bops.from(JSON.stringify({"a": "1", "b": "foo"}) + os.EOL))
      ws.write(bops.from(JSON.stringify({"a": "10", "b": "foo"}) + os.EOL))
      ws.write(bops.from(JSON.stringify({"a": "100", "b": "foo"})))
      ws.end()
    })
  })
}

module.exports.getChanges = function(test, common) {
  test('getChanges', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, quiet: true })

      ws.on('finish', function() {
        dat.createChangesReadStream({data: true}).pipe(concat(function(data) {
          var changes = data.map(function(r) { return r.change })
          t.equal(JSON.stringify(changes), JSON.stringify([1,2,3,4,5,6]) , 'ordered changes 1 - 6 exist') // 5 rows + 1 schema
          t.equal(!!data[0].value, true)
          done()
        }))
      })

      ws.write(bops.from('a,b,c\n10,1,1\n100,1,1\n1,1,1\n1,1,1\n1,1,1'))
      ws.end()
    })
  })
}

module.exports.changesStream = function(test, common) {
  test('simple put should trigger a change', function(t) {
    common.getDat(t, function(dat, done) {
      var changes = dat.createChangesReadStream({ live: true, data: true, decode: true })
      var gotChange = false
      setTimeout(function() {
        if (gotChange) return
        t.false(true, 'timeout')
        setImmediate(done)
      }, 1000)

      changes.pipe(through2({objectMode: true}, function(obj, enc, next) {
        if (obj.subset) return next()
        changes.destroy()
        t.equal(obj.value.foo, "bar")
        gotChange = true
        setImmediate(done)
      }))

      dat.put({"foo": "bar"}, function(err, doc) {
        if (err) throw err
      })
    })
  })
}

module.exports.changesStreamTail = function(test, common) {
  test('createChangesStream tail:true', function(t) {
    common.getDat(t, function(dat, done) {

      dat.put({"foo": "old"}, function(err) {
        t.notOk(err, 'should not err')

        var changes = dat.createChangesReadStream({ live: true, tail: true, data: true, decode: true })
        var gotChange = false
        setTimeout(function() {
          if (gotChange) return
          t.false(true, 'timeout')
          setImmediate(done)
        }, 1000)

        changes.pipe(through2({objectMode: true}, function(obj, enc, next) {
          if (obj.subset) return next()
          changes.destroy()
          t.equal(obj.value.foo, "new", 'should only get new row, not old row')
          gotChange = true
          setImmediate(done)
        }))

        dat.put({"foo": "new"}, function(err) {
          t.notOk(err, 'should not err')
        })
      })

    })
  })
}

module.exports.changesStreamTailNum = function(test, common) {
  test('createChangesStream tail:1', function(t) {
    common.getDat(t, function(dat, done) {

      var ws = dat.createWriteStream({quiet: true})

      ws.on('error', function(err) {
        t.notOk(err)
        setImmediate(done)
      })

      ws.on('finish', function() {
        var changes = dat.createChangesReadStream({ live: true, tail: 1, data: true, decode: true })

        var gotChange = false
        setTimeout(function() {
          if (gotChange) return
          t.false(true, 'timeout')
          setImmediate(done)
        }, 1000)

        changes.pipe(through2({objectMode: true}, function(obj, enc, next) {
          if (obj.subset) return next()
          changes.destroy()
          t.equal(obj.value.foo, "taco", 'should only get 1 newest row, not older rows')
          gotChange = true
          setImmediate(done)
          next()
        }))
      })

      ws.write({'foo': 'bar'})
      ws.write({'foo': 'baz'})
      ws.write({'foo': 'taco'})
      ws.end()

    })
  })
}

module.exports.createReadStream = function(test, common) {
  test('createReadStream', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, quiet: true })

      ws.on('finish', function() {
        var readStream = dat.createReadStream()
        readStream.pipe(concat(function(rows) {
          t.equal(rows.length, 5, '5 rows')
          done()
        }))
      })

      ws.write(bops.from('a,b,c\n10,1,1\n100,1,1\n1,1,1\n1,1,1\n1,1,1'))
      ws.end()
    })
  })
}

module.exports.createReadStreamStartEndKeys = function(test, common) {
  test('createReadStream w/ start + end keys', function(t) {
    common.getDat(t, function(dat, done) {
      var ws = dat.createWriteStream({ csv: true, primary: 'a', quiet: true })

      ws.on('finish', function() {
        var readStream = dat.createReadStream({ start: '2', end: '4'})
        readStream.pipe(concat(function(rows) {
          t.equal(rows.length, 3, '3 rows')
          t.equal(rows[0].a, '2')
          t.equal(rows[1].a, '3')
          t.equal(rows[2].a, '4')
          done()
        }))
      })

      ws.write(bops.from('a\n1\n2\n3\n4\n5'))
      ws.end()
    })
  })
}

module.exports.createReadStreamFormats = function (test, common) {
  test('createReadStream json', function (t) {
    common.getDat(t, function (dat, done) {
      var ws = dat.createWriteStream({primary: 'a', quiet: true})
      ws.on('finish', csvFormat)
      ws.write({a: 1})
      ws.write({a: 2})
      ws.write({a: 3})
      ws.end()

      function csvFormat() {
        var rs = dat.createReadStream({ csv: true })
        rs.pipe(concat(function(data) {
          var rows = data.split('\n')
          t.equal(rows[0].split(',').length, 3, 'csv header')
          t.equal(rows[1].split(',').length, 3, 'csv first row')
          t.equal(rows.length, 5, 'csv length')
          jsonStyleObject()
        }))
      }

      function jsonStyleObject() {
        var rs = dat.createReadStream({format: 'json'})
        rs.pipe(concat(function (data) {
          var json = JSON.parse(data)
          t.equals(json.rows.length, 3, 'json object style length')
          t.equals(json.rows[0].a, 1, 'json object style data')
          t.equals(Object.keys(json.rows[0]).length, 3, 'json object style keys')
          jsonStyleArray()
        }))
      }

      function jsonStyleArray() {
        var rs = dat.createReadStream({format: 'json', style: 'array'})
        rs.pipe(concat(function (data) {
          var json = JSON.parse(data)
          t.equals(json.length, 3, 'json array style length')
          t.equals(json[0].a, 1, 'json array style data')
          t.equals(Object.keys(json[0]).length, 3, 'json object style keys')
          ndjsonFormat()
        }))
      }

      function ndjsonFormat() {
        var rs = dat.createReadStream({format: 'ndjson'})
        rs.pipe(ndjson.parse()).pipe(concat(function (json) {
          t.equals(json.length, 3, 'ndjson length')
          t.equals(json[0].a, 1, 'ndjson first row data')
          t.equals(Object.keys(json[0]).length, 3, 'ndjson first row keys')
          sseFormat()
        }))
      }

      function sseFormat() {
        var rs = dat.createReadStream({format: 'sse'})
        rs.pipe(concat(function (data) {
          var rows = data.split('\n\n')
          t.equals(rows.length, 4, 'sse length')
          var row = rows[0].split('event: data\ndata: ')
          t.equals(row.length, 2, 'sse header')
          var json = {}
          try { json = JSON.parse(row[1]) } catch(e) { t.fail(e.message)}
          t.equals(json.a, 1, 'sse first row data')
          t.equals(Object.keys(json).length, 3, 'sse first row keys')
          done()
        }))
      }

    })
  })
}

module.exports.createVersionStream = function(test, common) {
  test('createVersionStream', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put("foo", {"baz": "bar"}, function(err, doc) {
        t.false(err)
        var ver1 = doc.version
        doc.pizza = 'taco'
        dat.put(doc, function(err, doc) {
          t.false(err)
          // put some data before and after to make sure they dont get returned too
          dat.put("abc", {'bar': 'baz'}, function(err) {
            t.false(err)
            dat.put("xyz", {'bar': 'baz'}, function(err) {
              t.false(err)
              readVersions()
            })
          })
        })
      })

      function readVersions() {
        dat.createVersionStream('foo').pipe(concat(function(versions) {
          t.equal(versions.length, 2, '2 versions')
          var v1 = versions[0] || {version: ""}
          var v2 = versions[1] || {version: ""}
          t.equal(v1.version, 1)
          t.equal(v2.version, 2)
          t.equal(v1.pizza, null, 'version 1')
          t.equal(v2.pizza, 'taco', 'version 2')
          setImmediate(done)
        }))
      }
    })
  })
}

module.exports.all = function (test, common) {
  module.exports.readStreamBuff(test, common)
  module.exports.readStreamBuffPrimaryKey(test, common)
  module.exports.readStreamCsvPrimaryKey(test, common)
  module.exports.readStreamNdjPrimaryKey(test, common)
  module.exports.getChanges(test, common)
  module.exports.changesStream(test, common)
  module.exports.changesStreamTail(test, common)
  module.exports.changesStreamTailNum(test, common)
  module.exports.createReadStream(test, common)
  module.exports.createReadStreamStartEndKeys(test, common)
  module.exports.createReadStreamFormats(test, common)
  module.exports.createVersionStream(test, common)
}
<|endoftext|>


<commit_before>var axios = require('../../../index');
var http = require('http');
var url = require('url');
var zlib = require('zlib');
var server;

module.exports = {
  tearDown: function (callback) {
    server.close();
    server = null;
    callback();
  },

  testTimeout: function (test) {
    server = http.createServer(function (req, res) {
      setTimeout(function () {
        res.end();
      }, 1000);
    }).listen(4444, function () {
      var success = false, failure = false;
      var error;

      axios.get('http://localhost:4444/', {
        timeout: 250
      }).then(function (res) {
        success = true;
      }).catch(function (res) {
        error = res;
        failure = true;
      });

      setTimeout(function () {
        test.equal(success, false, 'request should not succeed');
        test.equal(failure, true, 'request should fail');
        test.equal(error.code, 'ECONNABORTED');
        test.equal(error.message, 'timeout of 250ms exceeded');
        test.done();
      }, 300);
    });
  },

  testJSON: function (test) {
    var data = {
      firstName: 'Fred',
      lastName: 'Flintstone',
      emailAddr: 'fred@example.com'
    };

    server = http.createServer(function (req, res) {
      res.setHeader('Content-Type', 'application/json;charset=utf-8');
      res.end(JSON.stringify(data));
    }).listen(4444, function () {
      axios.get('http://localhost:4444/').then(function (res) {
        test.deepEqual(res.data, data);
        test.done();
      });
    });
  },

  testRedirect: function (test) {
    var str = 'test response';

    server = http.createServer(function (req, res) {
      var parsed = url.parse(req.url);

      if (parsed.pathname === '/one') {
        res.setHeader('Location', '/two');
        res.statusCode = 302;
        res.end();
      } else {
        res.end(str);
      }
    }).listen(4444, function () {
      axios.get('http://localhost:4444/one').then(function (res) {
        test.equal(res.data, str);
        test.done();
      });
    });
  },

  testTransparentGunzip: function (test) {
    var data = {
      firstName: 'Fred',
      lastName: 'Flintstone',
      emailAddr: 'fred@example.com'
    };

    zlib.gzip(JSON.stringify(data), function(err, zipped) {

      server = http.createServer(function (req, res) {
        res.setHeader('Content-Type', 'application/json;charset=utf-8');
        res.setHeader('Content-Encoding', 'gzip');
        res.end(zipped);
      }).listen(4444, function () {
        axios.get('http://localhost:4444/').then(function (res) {
          test.deepEqual(res.data, data);
          test.done();
        });
      });

    });
  },

  testUTF8: function (test) {
    var str = Array(100000).join('ж');

    server = http.createServer(function (req, res) {
      res.setHeader('Content-Type', 'text/html; charset=UTF-8');
      res.end(str);
    }).listen(4444, function () {
      axios.get('http://localhost:4444/').then(function (res) {
        test.equal(res.data, str);
        test.done();
      });
    });
  },

  testBasicAuth: function (test) {
    server = http.createServer(function (req, res) {
      console.log(req.headers);
      res.end(req.headers.authorization);
    }).listen(4444, function () {
      var user = 'foo';
      axios.get('http://' + user + '@localhost:4444/').then(function (res) {
        var base64 = new Buffer(user + ':', 'utf8').toString('base64');
        test.equal(res.data, 'Basic ' + base64);
        test.done();
      });
    });
  },
};
<commit_msg>Removing console.log<commit_after>var axios = require('../../../index');
var http = require('http');
var url = require('url');
var zlib = require('zlib');
var server;

module.exports = {
  tearDown: function (callback) {
    server.close();
    server = null;
    callback();
  },

  testTimeout: function (test) {
    server = http.createServer(function (req, res) {
      setTimeout(function () {
        res.end();
      }, 1000);
    }).listen(4444, function () {
      var success = false, failure = false;
      var error;

      axios.get('http://localhost:4444/', {
        timeout: 250
      }).then(function (res) {
        success = true;
      }).catch(function (res) {
        error = res;
        failure = true;
      });

      setTimeout(function () {
        test.equal(success, false, 'request should not succeed');
        test.equal(failure, true, 'request should fail');
        test.equal(error.code, 'ECONNABORTED');
        test.equal(error.message, 'timeout of 250ms exceeded');
        test.done();
      }, 300);
    });
  },

  testJSON: function (test) {
    var data = {
      firstName: 'Fred',
      lastName: 'Flintstone',
      emailAddr: 'fred@example.com'
    };

    server = http.createServer(function (req, res) {
      res.setHeader('Content-Type', 'application/json;charset=utf-8');
      res.end(JSON.stringify(data));
    }).listen(4444, function () {
      axios.get('http://localhost:4444/').then(function (res) {
        test.deepEqual(res.data, data);
        test.done();
      });
    });
  },

  testRedirect: function (test) {
    var str = 'test response';

    server = http.createServer(function (req, res) {
      var parsed = url.parse(req.url);

      if (parsed.pathname === '/one') {
        res.setHeader('Location', '/two');
        res.statusCode = 302;
        res.end();
      } else {
        res.end(str);
      }
    }).listen(4444, function () {
      axios.get('http://localhost:4444/one').then(function (res) {
        test.equal(res.data, str);
        test.done();
      });
    });
  },

  testTransparentGunzip: function (test) {
    var data = {
      firstName: 'Fred',
      lastName: 'Flintstone',
      emailAddr: 'fred@example.com'
    };

    zlib.gzip(JSON.stringify(data), function(err, zipped) {

      server = http.createServer(function (req, res) {
        res.setHeader('Content-Type', 'application/json;charset=utf-8');
        res.setHeader('Content-Encoding', 'gzip');
        res.end(zipped);
      }).listen(4444, function () {
        axios.get('http://localhost:4444/').then(function (res) {
          test.deepEqual(res.data, data);
          test.done();
        });
      });

    });
  },

  testUTF8: function (test) {
    var str = Array(100000).join('ж');

    server = http.createServer(function (req, res) {
      res.setHeader('Content-Type', 'text/html; charset=UTF-8');
      res.end(str);
    }).listen(4444, function () {
      axios.get('http://localhost:4444/').then(function (res) {
        test.equal(res.data, str);
        test.done();
      });
    });
  },

  testBasicAuth: function (test) {
    server = http.createServer(function (req, res) {
      res.end(req.headers.authorization);
    }).listen(4444, function () {
      var user = 'foo';
      axios.get('http://' + user + '@localhost:4444/').then(function (res) {
        var base64 = new Buffer(user + ':', 'utf8').toString('base64');
        test.equal(res.data, 'Basic ' + base64);
        test.done();
      });
    });
  },
};
<|endoftext|>


<commit_before>describe('scope module security', function () {
    var Scope = require('../../');

    describe('sensitive globals', function () {
        var scope;

        beforeEach(function () {
            scope = Scope.create();
            scope.set('expect', expect);
        });

        afterEach(function () {
            scope = null;
        });

        it('"global" must not be visible', function (done) {
            scope.exec(`
                expect(typeof global).be('undefined');
                expect(this.global).be(undefined);
            `, done);
        });

        it('"process" must not be visible', function (done) {
            scope.exec(`
                expect(typeof process).be('undefined');
                expect(this.process).be(undefined);
            `, done);
        });
    });

    describe('execution function', function () {
        var scope;

        beforeEach(function () {
            scope = Scope.create();
            scope.set('expect', expect);
        });

        afterEach(function () {
            scope = null;
        });

        it('must not provide access to `arguments` variable', function (done) {
            scope.exec(`
                expect(typeof arguments).be('undefined');
            `, done);
        });
    });
});
<commit_msg>Updated security tests to chai<commit_after>var Scope = require('../../');

describe('scope module security', function () {

    describe('sensitive globals', function () {
        var scope;

        beforeEach(function () {
            scope = Scope.create();
            scope.set('expect', expect);
        });

        afterEach(function () {
            scope = null;
        });

        it('"global" must not be visible', function (done) {
            scope.exec(`
                expect(typeof global).to.equal('undefined');
                expect(this.global).to.be.undefined;
            `, done);
        });

        it('"process" must not be visible', function (done) {
            scope.exec(`
                expect(typeof process).to.equal('undefined');
                expect(this.process).to.be.undefined;
            `, done);
        });
    });

    describe('execution function', function () {
        var scope;

        beforeEach(function () {
            scope = Scope.create();
            scope.set('expect', expect);
        });

        afterEach(function () {
            scope = null;
        });

        it('should not provide access to `arguments` variable', function (done) {
            scope.exec(`
                expect(typeof arguments).to.equal('undefined');
            `, done);
        });
    });
});
<|endoftext|>


<commit_before>module.exports = function (creep) {
    if(creep.memory.currentTarget) {
        creep.memory.currentTarget = Game.getObjectById(creep.memory.currentTarget.id);
    }

    // Aquire target
    if(!creep.memory.currentTarget || !creep.memory.currentTarget.structureType || creep.memory.currentTarget.energy === creep.memory.currentTarget.energyCapacity) {
        creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_SPAWNS, {
            filter: function(spawn) {
                    return (spawn.energy < spawn.energyCapacity);
                },
            algorithm: "astar"
        });

        if(!creep.memory.currentTarget) {
            creep.memory.currentTarget = creep.pos.findClosest(FIND_MY_STRUCTURES, {
                filter: function(structure) {
                     return (structure.structureType === STRUCTURE_EXTENSION || structure.structureType === STRUCTURE_LINK) && (structure.energy < structure.energyCapacity);
                },
                algorithm: "astar"
            });
        }
    }

    // Execute on target
    if(creep.memory.currentTarget) {
        if(creep.pos.isNearTo(creep.memory.currentTarget.pos.x, creep.memory.currentTarget.pos.y)) {
            creep.transferEnergy(Game.getObjectById(creep.memory.currentTarget.id));
        } else {
            creep.advMove(creep.memory.currentTarget);
        }
    }
};
<commit_msg>Travis Build - Deploying to build folder [ci skip]<commit_after>module.exports = function (creep) {
    var optimalStructureId;

    function isStructureAvailable(structure) {
        if(structure.energy < structure.energyCapacity && (structure.pos.room.name > creep.pos.room.name ? false : (structure.pos.room.name < creep.pos.room.name)) ) {
            optimalStructureId = structure.id;
            return true;
        }
    }

    if(creep.memory.currentTarget) {
        creep.memory.currentTarget = Game.getObjectById(creep.memory.currentTarget.id);
    }

    // Aquire target
    if(!creep.memory.currentTarget || !creep.memory.currentTarget.structureType || creep.memory.currentTarget.energy === creep.memory.currentTarget.energyCapacity) {
        if(Object.keys(Game.spawns).some(function (spawnName) {
            return isStructureAvailable(Game.spawns[spawnName]);
        })) {} else if (Memory.extensionList.some(function (extensionId) {
            return isStructureAvailable(Game.getObjectById(extensionId));
        })) {} else if (Memory.linkList.some(function (linkId) {
            return isStructureAvailable(Game.getObjectById(linkId));
        })) {}

        creep.memory.currentTarget = optimalStructureId;
    }

    // Execute on target
    if(creep.memory.currentTarget) {
        if(creep.pos.isNearTo(creep.memory.currentTarget.pos.x, creep.memory.currentTarget.pos.y)) {
            creep.transferEnergy(Game.getObjectById(creep.memory.currentTarget.id));
        } else {
            creep.advMove(creep.memory.currentTarget);
        }
    }
};
<|endoftext|>


<commit_before>/* global module, __dirname */
'use strict'

const pkg = require('./package.json')
const webpack = require('webpack')
const path = require('path')
const url = require('url')

const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin
const DedupePlugin = webpack.optimize.DedupePlugin
const DefinePlugin = webpack.DefinePlugin
const HotModuleReplacementPlugin = webpack.HotModuleReplacementPlugin
const NormalModuleReplacementPlugin = webpack.NormalModuleReplacementPlugin
const OccurenceOrderPlugin = webpack.optimize.OccurenceOrderPlugin
const UglifyJsPlugin = webpack.optimize.UglifyJsPlugin
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlPlugin = require('./scripts/webpack/html-plugin')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')

const isProduction = (process.env.NODE_ENV === 'production')
const isDevelopment = (process.env.NODE_ENV === 'development')
const isTest = (process.env.NODE_ENV === 'test')

const outputFolder = 'build/'
const urlLoaderLimit = 10000
let publicPath = '/'
if (isProduction) {
	// We use "homepage" field to infer "public path" at which the app is served.
	// Webpack needs to know it to put the right

						${isProduction ?
							''
							: ''}

						${context.css ?
							`<link rel="stylesheet" href="${publicPath}${context.css}">`
							: ''}

					`,
				}
			},
			isDev: isDevelopment,
		}),

		// Ignore the "full" schema in js-yaml's module, because it brings in esprima
		// to support the !!js/function type. We don't use and have no need for it, so
		// tell webpack to ignore it.
		new NormalModuleReplacementPlugin(/schema\/default_full$/, result => {
			result.request = result.request.replace('default_full', 'default_safe')
		}),

		// DefinePlugin makes some variables available to the code.
		new DefinePlugin({
			VERSION: JSON.stringify(pkg.version),
			DEVELOPMENT: isDevelopment,
			PRODUCTION: isProduction,
			TESTING: isTest,
			// APP_BASE is used in react-router, to set its base appropriately
			// across both local dev and gh-pages.
			APP_BASE: JSON.stringify(publicPath),
			'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
		}),

		// Extract the common libraries into a single file so that the chunks
		// don't need to individually bundle them.
		new CommonsChunkPlugin({
			names: ['react', 'common'],
			filename: '[name].[hash].js',
			minChunks: Infinity,
		}),

		// Watcher doesn't work well if you mistype casing in a path so we use
		// a plugin that prints an error when you attempt to do this.
		new CaseSensitivePathsPlugin(),
	],

	module: {
		loaders: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				loaders: ['babel-loader?cacheDirectory'],
			},
			{
				test: /\.worker.js$/,
				exclude: /node_modules/,
				loaders: ['worker-loader', 'babel-loader?cacheDirectory'],
			},
			{
				test: /\.json$/,
				loaders: ['json-loader'],
			},
			{
				test: /\.(otf|eot|ttf|woff2?)$/,
				loader: 'url-loader',
				query: {limit: urlLoaderLimit},
			},
			{
				test: /\.(jpe?g|png|gif)$/,
				loader: 'url-loader',
				query: {limit: urlLoaderLimit},
			},
		],
	},

	worker: {
		output: {
			filename: '[hash].worker.js',
			chunkFilename: '[id].[hash].worker.js',
		},
	},
}

// dev specific stuff
if (isDevelopment) {
	// debugging option
	config.devtool = 'cheap-module-eval-source-map'

	// add dev server and hotloading clientside code
	config.entry.main.unshift(
		// 'react-hot-loader/patch',
		'webpack-dev-server/client?/',
		'webpack/hot/only-dev-server'
	)

	config.devServer.port = config.port
	config.devServer.host = config.hostname

	// add dev plugins
	config.plugins.push(new HotModuleReplacementPlugin())

	// Add style loaders
	config.module.loaders.push({test: /\.css$/, loaders: ['style', 'css']})
	config.module.loaders.push({test: /\.scss$/, loaders: ['style', 'css', 'sass']})

	let identName = '[path][name]·[local]·[hash:base64:5]'
	config.module.loaders.push({test: /\.module.css$/, loaders: ['style', `css?modules&localIdentName=${identName}`]})
	config.module.loaders.push({test: /\.module.scss$/, loaders: ['style', `css?modules&localIdentName=${identName}', 'sass`]})
}

else if (isTest) {
	config.module.loaders.push({test: /\.css$/, loader: 'style!css'})
	config.module.loaders.push({test: /\.module.css$/, loader: 'style!css?modules'})
	config.module.loaders.push({test: /\.scss$/, loader: 'style!css!sass'})
	config.module.loaders.push({test: /\.module.scss$/, loader: 'style!css?modules!sass'})
}

// production
else if (isProduction) {
	config.devtool = 'source-map'
	config.stats.children = false

	// minify in production
	let extractor = new ExtractTextPlugin(config.output.cssFilename, {allChunks: true})
	config.plugins = config.plugins.concat([
		new DedupePlugin(),
		new OccurenceOrderPlugin(true),
		new UglifyJsPlugin({
			compress: {
				warnings: false,
				pure_getters: true, // eslint-disable-line camelcase
				screw_ie8: true, // eslint-disable-line camelcase
				unsafe: true,
			},
			mangle: {
				screw_ie8: true, // eslint-disable-line camelcase
			},
			output: {
				comments: false,
				screw_ie8: true, // eslint-disable-line camelcase
			},
		}),
		extractor,
	])

	config.module.loaders.push({
		test: /\.css$/,
		loader: extractor.extract('style', ['css']),
	})
	config.module.loaders.push({
		test: /\.scss$/,
		loader: extractor.extract('style', ['css', 'sass']),
	})

	config.module.loaders.push({
		test: /\.module.css$/,
		loader: extractor.extract('style', ['css?modules']),
	})
	config.module.loaders.push({
		test: /\.module.scss$/,
		loader: extractor.extract('style', ['css?modules', 'sass']),
	})
}

// else {
// 	throw new Error('Unknown environment! Not development, production, nor test!')
// }
//
module.exports = config
<commit_msg>go back to eval for source map<commit_after>/* global module, __dirname */
'use strict'

const pkg = require('./package.json')
const webpack = require('webpack')
const path = require('path')
const url = require('url')

const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin
const DedupePlugin = webpack.optimize.DedupePlugin
const DefinePlugin = webpack.DefinePlugin
const HotModuleReplacementPlugin = webpack.HotModuleReplacementPlugin
const NormalModuleReplacementPlugin = webpack.NormalModuleReplacementPlugin
const OccurenceOrderPlugin = webpack.optimize.OccurenceOrderPlugin
const UglifyJsPlugin = webpack.optimize.UglifyJsPlugin
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlPlugin = require('./scripts/webpack/html-plugin')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')

const isProduction = (process.env.NODE_ENV === 'production')
const isDevelopment = (process.env.NODE_ENV === 'development')
const isTest = (process.env.NODE_ENV === 'test')

const outputFolder = 'build/'
const urlLoaderLimit = 10000
let publicPath = '/'
if (isProduction) {
	// We use "homepage" field to infer "public path" at which the app is served.
	// Webpack needs to know it to put the right

						${isProduction ?
							''
							: ''}

						${context.css ?
							`<link rel="stylesheet" href="${publicPath}${context.css}">`
							: ''}

					`,
				}
			},
			isDev: isDevelopment,
		}),

		// Ignore the "full" schema in js-yaml's module, because it brings in esprima
		// to support the !!js/function type. We don't use and have no need for it, so
		// tell webpack to ignore it.
		new NormalModuleReplacementPlugin(/schema\/default_full$/, result => {
			result.request = result.request.replace('default_full', 'default_safe')
		}),

		// DefinePlugin makes some variables available to the code.
		new DefinePlugin({
			VERSION: JSON.stringify(pkg.version),
			DEVELOPMENT: isDevelopment,
			PRODUCTION: isProduction,
			TESTING: isTest,
			// APP_BASE is used in react-router, to set its base appropriately
			// across both local dev and gh-pages.
			APP_BASE: JSON.stringify(publicPath),
			'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
		}),

		// Extract the common libraries into a single file so that the chunks
		// don't need to individually bundle them.
		new CommonsChunkPlugin({
			names: ['react', 'common'],
			filename: '[name].[hash].js',
			minChunks: Infinity,
		}),

		// Watcher doesn't work well if you mistype casing in a path so we use
		// a plugin that prints an error when you attempt to do this.
		new CaseSensitivePathsPlugin(),
	],

	module: {
		loaders: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				loaders: ['babel-loader?cacheDirectory'],
			},
			{
				test: /\.worker.js$/,
				exclude: /node_modules/,
				loaders: ['worker-loader', 'babel-loader?cacheDirectory'],
			},
			{
				test: /\.json$/,
				loaders: ['json-loader'],
			},
			{
				test: /\.(otf|eot|ttf|woff2?)$/,
				loader: 'url-loader',
				query: {limit: urlLoaderLimit},
			},
			{
				test: /\.(jpe?g|png|gif)$/,
				loader: 'url-loader',
				query: {limit: urlLoaderLimit},
			},
		],
	},

	worker: {
		output: {
			filename: '[hash].worker.js',
			chunkFilename: '[id].[hash].worker.js',
		},
	},
}

// dev specific stuff
if (isDevelopment) {
	// debugging option
	config.devtool = 'eval'

	// add dev server and hotloading clientside code
	config.entry.main.unshift(
		// 'react-hot-loader/patch',
		'webpack-dev-server/client?/',
		'webpack/hot/only-dev-server'
	)

	config.devServer.port = config.port
	config.devServer.host = config.hostname

	// add dev plugins
	config.plugins.push(new HotModuleReplacementPlugin())

	// Add style loaders
	config.module.loaders.push({test: /\.css$/, loaders: ['style', 'css']})
	config.module.loaders.push({test: /\.scss$/, loaders: ['style', 'css', 'sass']})

	let identName = '[path][name]·[local]·[hash:base64:5]'
	config.module.loaders.push({test: /\.module.css$/, loaders: ['style', `css?modules&localIdentName=${identName}`]})
	config.module.loaders.push({test: /\.module.scss$/, loaders: ['style', `css?modules&localIdentName=${identName}', 'sass`]})
}

else if (isTest) {
	config.module.loaders.push({test: /\.css$/, loader: 'style!css'})
	config.module.loaders.push({test: /\.module.css$/, loader: 'style!css?modules'})
	config.module.loaders.push({test: /\.scss$/, loader: 'style!css!sass'})
	config.module.loaders.push({test: /\.module.scss$/, loader: 'style!css?modules!sass'})
}

// production
else if (isProduction) {
	config.devtool = 'source-map'
	config.stats.children = false

	// minify in production
	let extractor = new ExtractTextPlugin(config.output.cssFilename, {allChunks: true})
	config.plugins = config.plugins.concat([
		new DedupePlugin(),
		new OccurenceOrderPlugin(true),
		new UglifyJsPlugin({
			compress: {
				warnings: false,
				pure_getters: true, // eslint-disable-line camelcase
				screw_ie8: true, // eslint-disable-line camelcase
				unsafe: true,
			},
			mangle: {
				screw_ie8: true, // eslint-disable-line camelcase
			},
			output: {
				comments: false,
				screw_ie8: true, // eslint-disable-line camelcase
			},
		}),
		extractor,
	])

	config.module.loaders.push({
		test: /\.css$/,
		loader: extractor.extract('style', ['css']),
	})
	config.module.loaders.push({
		test: /\.scss$/,
		loader: extractor.extract('style', ['css', 'sass']),
	})

	config.module.loaders.push({
		test: /\.module.css$/,
		loader: extractor.extract('style', ['css?modules']),
	})
	config.module.loaders.push({
		test: /\.module.scss$/,
		loader: extractor.extract('style', ['css?modules', 'sass']),
	})
}

// else {
// 	throw new Error('Unknown environment! Not development, production, nor test!')
// }
//
module.exports = config
<|endoftext|>