<commit_before>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var files = [
  ['firefox', function() { return navigator.userAgent.indexOf('Firefox') != -1; }],
  'stdlib',
  'io',
  'writer',
  'socket',
  'hash',
  'base64',
  'encodings',
  'utf8',
  'parse',
  'event',
  'JSONUtil',
  'XMLUtil',
  'context',
  'FOAM',
  'JSONParser',
  'TemplateUtil',
  // To use FO, uncomment the next line
  // and comment out all lines from FObject to mm6Prototbuf
  // inclusively
//  'experimental/fo',
//  'experimental/protobuffeatures',
  'FObject',
  'BootstrapModel',
  'mm1Model',
  'mm2Property',
  'mm3Types',
  'mm4Method',
  'mm5Misc',
  'mm6Protobuf',
  'value',
  'view',
  'layout',
  'daoView',
  'ChoiceView',
  'DetailView',
  'TableView',
  'cview',
  'cview2',
  'RichTextView',
  'listchoiceview',
  'scroll',
  'mlang',
  'QueryParser',
  'search',
  'async',
  'oam',
  'visitor',
  'messaging',
  'dao',
  'arrayDAO',
  'ClientDAO',
  'diff',
  'SplitDAO',
  'index',
  'StackView',
  'MementoMgr',
  'DAOController',
  'ThreePaneController',
  'experimental/protobufparser',
  'experimental/protobuf',
  // remove below here
  'models',
  'touch',
  'glang',
  'oauth',
  '../apps/mailreader/view',
  '../apps/mailreader/email',
  'turntable'
];
<commit_msg>Add lib/email/email to FOAMmodels since lots of demos expect EMail to already be defined.<commit_after>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var files = [
  ['firefox', function() { return navigator.userAgent.indexOf('Firefox') != -1; }],
  'stdlib',
  'io',
  'writer',
  'socket',
  'hash',
  'base64',
  'encodings',
  'utf8',
  'parse',
  'event',
  'JSONUtil',
  'XMLUtil',
  'context',
  'FOAM',
  'JSONParser',
  'TemplateUtil',
  // To use FO, uncomment the next line
  // and comment out all lines from FObject to mm6Prototbuf
  // inclusively
//  'experimental/fo',
//  'experimental/protobuffeatures',
  'FObject',
  'BootstrapModel',
  'mm1Model',
  'mm2Property',
  'mm3Types',
  'mm4Method',
  'mm5Misc',
  'mm6Protobuf',
  'value',
  'view',
  'layout',
  'daoView',
  'ChoiceView',
  'DetailView',
  'TableView',
  'cview',
  'cview2',
  'RichTextView',
  'listchoiceview',
  'scroll',
  'mlang',
  'QueryParser',
  'search',
  'async',
  'oam',
  'visitor',
  'messaging',
  'dao',
  'arrayDAO',
  'ClientDAO',
  'diff',
  'SplitDAO',
  'index',
  'StackView',
  'MementoMgr',
  'DAOController',
  'ThreePaneController',
  'experimental/protobufparser',
  'experimental/protobuf',
  // remove below here
  'models',
  'touch',
  'glang',
  'oauth',
  '../apps/mailreader/view',
  '../apps/mailreader/email',
  '../lib/email/email',
  'turntable'
];
<|endoftext|>


<commit_before>'use strict';

describe('Date Directives spec,', function() {

  var compileElement, scope, elem, DateUtil;

  beforeEach(function() {
    angular.mock.module('ngFormLib.controls.formDate');

    inject(function(_$compile_, $rootScope, _DateUtil_) {
      scope = $rootScope.$new();
      compileElement = function(html) {
        return _$compile_(html)(scope);
      };
      DateUtil = _DateUtil_;
    });
  });

  describe('formDateFormat', function() {

    function testDate(element, testData) {

      scope.$digest();

      var inputElem = element.find('input');

      // Initially it is blank
      expect(inputElem.val()).toEqual('');
      expect(inputElem.hasClass('ng-dirty')).toEqual(false);
      expect(inputElem.hasClass('ng-invalid-date')).toEqual(false);

      for (var i = 0; i < testData.length; i++) {
        inputElem.val(testData[i].input).triggerHandler('change');
        //scope.$digest();

        expect(inputElem.val()).toEqual(testData[i].output);

        for (var c = 0; c < testData[i].expectedClasses.length; c++) {
          //console.log(inputElem[0].outerHTML);
          expect(inputElem.hasClass(testData[i].expectedClasses[c])).toEqual(true);
        }
      }
    }

    it('should validate an ordinary input field which must be a date, no other restrictions', function() {
      var testData = [
        {input: '02',         output: '02',         expectedClasses: ['ng-invalid', 'ng-invalid-date'], desc: 'Partial date'},
        {input: '02/01/1900', output: '02/01/1900', expectedClasses: ['ng-valid'],                      desc: 'Old valid date'},
        {input: '',           output: '',           expectedClasses: ['ng-valid'],                      desc: 'Blank date'},
        {input: '29/02/2000', output: '29/02/2000', expectedClasses: ['ng-valid'],                      desc: 'Is a leap year'},
        {input: '29/02/1900', output: '29/02/1900', expectedClasses: ['ng-invalid', 'ng-invalid-date'], desc: 'Not leap year'},
        {input: '29/02/2012', output: '29/02/2012', expectedClasses: ['ng-valid'],                      desc: 'Is a leap year'},
        {input: '29/02/2013', output: '29/02/2013', expectedClasses: ['ng-invalid', 'ng-invalid-date'], desc: 'Not leap year'},
        {input: '31122015',   output: '31122015',   expectedClasses: ['ng-valid'],                      desc: 'String of 8 digits accepted??'}
      ];

      var element = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" form-date-format></form>');
      testDate(element, testData);
    });

    it('should validate an ordinary input field which must be a date, with a min and max date restriction', function() {
      var testData = [
        {input: '02',         output: '02',         expectedClasses: ['ng-invalid', 'ng-invalid-date'],     desc: 'Partial date'},
        {input: '31/12/1999', output: '31/12/1999', expectedClasses: ['ng-invalid', 'ng-invalid-min-date'], desc: 'Date too small'},
        {input: '',           output: '',           expectedClasses: ['ng-valid'],                          desc: 'Blank date'},
        {input: '01/01/2011', output: '01/01/2011', expectedClasses: ['ng-invalid', 'ng-invalid-max-date'], desc: 'Date too large'},
        {input: '01/01/2000', output: '01/01/2000', expectedClasses: ['ng-valid'],                          desc: 'Min boundary date'},
        {input: '01/01/2005', output: '01/01/2005', expectedClasses: ['ng-valid'],                          desc: 'Somewehere in the middle'},
        {input: '31/12/2010', output: '31/12/2010', expectedClasses: ['ng-valid'],                          desc: 'Max boundary date'}
      ];

      var element = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" min-date="01/01/2000" max-date="31/12/2010" form-date-format></form>');
      testDate(element, testData);
    });

    it('should validate an ordinary input field which must be a date, with max date restriction of "today"', function() {
      var today = DateUtil.getToday();
      var tomorrow = DateUtil.dateAdd(today, 1);
      var yesterday = DateUtil.dateAdd(today, -1);
      var testData = [
        {input: today, output: today,         expectedClasses: ['ng-valid'],                          desc: 'Max date boundary'},
        {input: tomorrow, output: tomorrow,   expectedClasses: ['ng-invalid', 'ng-invalid-max-date'], desc: 'Over max date'},
        {input: yesterday, output: yesterday, expectedClasses: ['ng-valid'],                          desc: 'Below max date'}
      ];

      var element = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" max-date="today" form-date-format></form>');
      testDate(element, testData);
    });

    it('should eval the dateChange attribute when the date is valid', function() {
      scope.callback = jasmine.createSpy('callback');
      elem = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" date-change="callback()" form-date-format></form>');

      scope.$digest();
      var inputElem = elem.find('input');

      expect(scope.callback.calls.count()).toEqual(0);

      // We send a change event, so we should call the callback function
      inputElem.val('').triggerHandler('change');
      expect(inputElem.hasClass('ng-valid')).toEqual(true);
      expect(scope.callback.calls.count()).toEqual(1);

      // Make the date invalid, should not trigger a call
      inputElem.val('xyz').triggerHandler('change');
      expect(inputElem.hasClass('ng-invalid')).toEqual(true);
      expect(scope.callback.calls.count()).toEqual(1);

      // valid date should trigger callback
      inputElem.val('01/01/1976').triggerHandler('change');
      expect(inputElem.hasClass('ng-valid')).toEqual(true);
      expect(scope.callback.calls.count()).toEqual(2);
    });
  });

  describe('formDateInput', function() {

    it('should create a date input', function() {
      elem = compileElement('<form name="frm"><form-date ff-ng-model="scope.date" label="frm-date" uid="frm-date" name="frm-date"></form-date></form>');
      scope.$digest();

      expect(elem.html()).toEqual('
' +
        'frm-date' +
        '
<input type="text" class="form-control ng-pristine ng-valid ng-valid-required" maxlength="10" placeholder="dd/mm/yyyy" bs-datepicker="" form-date-format="" mask-date-digits="" id="frm-date" name="frm-date" ng-model="scope.date" ng-required="false" aria-required="false">
' +
        '
');
    });

    it('should throw an error if any of the label, id and name attributes are missing', function() {
      var controlName = 'formDate', directiveName = 'form-date';
      //var errorNoNameOrId = 'All ' + controlName + ' components MUST have a uid and name attribute, and the directive MUST exist inside a <form> for errors to appear';
      var errorNoLabel = 'The ' + controlName + ' component requires a label attribute.';
      var exceptionFn = function(html) {
        compileElement(html);
        scope.$digest();
      };

      var testData = [
        {html: '<' + directiveName + ' label="" uid="b" name="c"></' + directiveName + '>', expected: errorNoLabel}
      ];

      testData.forEach(function(testData) {
        expect(function() {exceptionFn(testData.html);}).toThrow(new Error(testData.expected));
      });
    });
  });

});
<commit_msg>Add ng-valid-maxlength and ng-untouched to pass test<commit_after>'use strict';

describe('Date Directives spec,', function() {

  var compileElement, scope, elem, DateUtil;

  beforeEach(function() {
    angular.mock.module('ngFormLib.controls.formDate');

    inject(function(_$compile_, $rootScope, _DateUtil_) {
      scope = $rootScope.$new();
      compileElement = function(html) {
        return _$compile_(html)(scope);
      };
      DateUtil = _DateUtil_;
    });
  });

  describe('formDateFormat', function() {

    function testDate(element, testData) {

      scope.$digest();

      var inputElem = element.find('input');

      // Initially it is blank
      expect(inputElem.val()).toEqual('');
      expect(inputElem.hasClass('ng-dirty')).toEqual(false);
      expect(inputElem.hasClass('ng-invalid-date')).toEqual(false);

      for (var i = 0; i < testData.length; i++) {
        inputElem.val(testData[i].input).triggerHandler('change');
        //scope.$digest();

        expect(inputElem.val()).toEqual(testData[i].output);

        for (var c = 0; c < testData[i].expectedClasses.length; c++) {
          //console.log(inputElem[0].outerHTML);
          expect(inputElem.hasClass(testData[i].expectedClasses[c])).toEqual(true);
        }
      }
    }

    it('should validate an ordinary input field which must be a date, no other restrictions', function() {
      var testData = [
        {input: '02',         output: '02',         expectedClasses: ['ng-invalid', 'ng-invalid-date'], desc: 'Partial date'},
        {input: '02/01/1900', output: '02/01/1900', expectedClasses: ['ng-valid'],                      desc: 'Old valid date'},
        {input: '',           output: '',           expectedClasses: ['ng-valid'],                      desc: 'Blank date'},
        {input: '29/02/2000', output: '29/02/2000', expectedClasses: ['ng-valid'],                      desc: 'Is a leap year'},
        {input: '29/02/1900', output: '29/02/1900', expectedClasses: ['ng-invalid', 'ng-invalid-date'], desc: 'Not leap year'},
        {input: '29/02/2012', output: '29/02/2012', expectedClasses: ['ng-valid'],                      desc: 'Is a leap year'},
        {input: '29/02/2013', output: '29/02/2013', expectedClasses: ['ng-invalid', 'ng-invalid-date'], desc: 'Not leap year'},
        {input: '31122015',   output: '31122015',   expectedClasses: ['ng-valid'],                      desc: 'String of 8 digits accepted??'}
      ];

      var element = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" form-date-format></form>');
      testDate(element, testData);
    });

    it('should validate an ordinary input field which must be a date, with a min and max date restriction', function() {
      var testData = [
        {input: '02',         output: '02',         expectedClasses: ['ng-invalid', 'ng-invalid-date'],     desc: 'Partial date'},
        {input: '31/12/1999', output: '31/12/1999', expectedClasses: ['ng-invalid', 'ng-invalid-min-date'], desc: 'Date too small'},
        {input: '',           output: '',           expectedClasses: ['ng-valid'],                          desc: 'Blank date'},
        {input: '01/01/2011', output: '01/01/2011', expectedClasses: ['ng-invalid', 'ng-invalid-max-date'], desc: 'Date too large'},
        {input: '01/01/2000', output: '01/01/2000', expectedClasses: ['ng-valid'],                          desc: 'Min boundary date'},
        {input: '01/01/2005', output: '01/01/2005', expectedClasses: ['ng-valid'],                          desc: 'Somewehere in the middle'},
        {input: '31/12/2010', output: '31/12/2010', expectedClasses: ['ng-valid'],                          desc: 'Max boundary date'}
      ];

      var element = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" min-date="01/01/2000" max-date="31/12/2010" form-date-format></form>');
      testDate(element, testData);
    });

    it('should validate an ordinary input field which must be a date, with max date restriction of "today"', function() {
      var today = DateUtil.getToday();
      var tomorrow = DateUtil.dateAdd(today, 1);
      var yesterday = DateUtil.dateAdd(today, -1);
      var testData = [
        {input: today, output: today,         expectedClasses: ['ng-valid'],                          desc: 'Max date boundary'},
        {input: tomorrow, output: tomorrow,   expectedClasses: ['ng-invalid', 'ng-invalid-max-date'], desc: 'Over max date'},
        {input: yesterday, output: yesterday, expectedClasses: ['ng-valid'],                          desc: 'Below max date'}
      ];

      var element = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" max-date="today" form-date-format></form>');
      testDate(element, testData);
    });

    it('should eval the dateChange attribute when the date is valid', function() {
      scope.callback = jasmine.createSpy('callback');
      elem = compileElement('<form name="frm"><input type="text" name="startDate" ng-model="startDate" date-change="callback()" form-date-format></form>');

      scope.$digest();
      var inputElem = elem.find('input');

      expect(scope.callback.calls.count()).toEqual(0);

      // We send a change event, so we should call the callback function
      inputElem.val('').triggerHandler('change');
      expect(inputElem.hasClass('ng-valid')).toEqual(true);
      expect(scope.callback.calls.count()).toEqual(1);

      // Make the date invalid, should not trigger a call
      inputElem.val('xyz').triggerHandler('change');
      expect(inputElem.hasClass('ng-invalid')).toEqual(true);
      expect(scope.callback.calls.count()).toEqual(1);

      // valid date should trigger callback
      inputElem.val('01/01/1976').triggerHandler('change');
      expect(inputElem.hasClass('ng-valid')).toEqual(true);
      expect(scope.callback.calls.count()).toEqual(2);
    });
  });

  describe('formDateInput', function() {

    it('should create a date input', function() {
      elem = compileElement('<form name="frm"><form-date ff-ng-model="scope.date" label="frm-date" uid="frm-date" name="frm-date"></form-date></form>');
      scope.$digest();

      expect(elem.html()).toEqual('
' +
        'frm-date' +
        '
<input type="text" class="form-control ng-pristine ng-untouched ng-valid ng-valid-maxlength ng-valid-required" maxlength="10" placeholder="dd/mm/yyyy" bs-datepicker="" form-date-format="" mask-date-digits="" id="frm-date" name="frm-date" ng-model="scope.date" ng-required="false" aria-required="false">
' +
        '
');
    });

    it('should throw an error if any of the label, id and name attributes are missing', function() {
      var controlName = 'formDate', directiveName = 'form-date';
      //var errorNoNameOrId = 'All ' + controlName + ' components MUST have a uid and name attribute, and the directive MUST exist inside a <form> for errors to appear';
      var errorNoLabel = 'The ' + controlName + ' component requires a label attribute.';
      var exceptionFn = function(html) {
        compileElement(html);
        scope.$digest();
      };

      var testData = [
        {html: '<' + directiveName + ' label="" uid="b" name="c"></' + directiveName + '>', expected: errorNoLabel}
      ];

      testData.forEach(function(testData) {
        expect(function() {exceptionFn(testData.html);}).toThrow(new Error(testData.expected));
      });
    });
  });

});
<|endoftext|>


<commit_before>define(['SocketIO', 'Scene'], function(io, scene) {
    return {
        init: function() {
            var _this = this;

            this.socket = io.connect();

            this.players = {
                me: {
                    name: 'YO',
                    position: new THREE.Vector3(),
                },
                others: {},
            };

            this.socket.on('connect', function() {
                _this.players.me.id = this.id;
                _this.socket.emit('register', _this.players.me);
            });

            this.socket.on('other connect', function(other) {
                _this.players.others[other.id] = other;
                _this.addPlayerAvatar(other);
            });

            this.socket.on('other disconnect', function(id) {
                var player = _this.players.others[id];
                delete self.players.others[id];
                _this.removePlayerAvatar(player);
            });

            this.socket.on('other change', function(data) {
                var player = self.players.others[data.id];
                if (player) {
                    player.position = data.position;
                    player.mesh.position.copy(data.position);
                }
            });
        },

        removePlayerAvatar: function(player) {
            scene.getScene().remove(player.mesh);
        },

        addPlayerAvatar: function(player) {
            var geometry = new THREE.BoxGeometry(40, 40, 40);

            var texture = THREE.ImageUtils.loadTexture('client/assets/img/grass.jpg');

            // texture.anisotropy = Metavrse.renderer.getMaxAnisotropy();
            var material = new THREE.MeshBasicMaterial({map: texture});

            mesh = new THREE.Mesh(geometry, material);
            mesh.position = player.position;

            player.mesh = mesh;

            scene.getScene().add(mesh);
        },

        playerMoved: function(position) {
            this.players.me.position = position;
            this.socket.emit('change', this.players.me);
        },
    };
});
<commit_msg>self to _this fix<commit_after>define(['SocketIO', 'Scene'], function(io, scene) {
    return {
        init: function() {
            var _this = this;

            this.socket = io.connect();

            this.players = {
                me: {
                    name: 'YO',
                    position: new THREE.Vector3(),
                },
                others: {},
            };

            this.socket.on('connect', function() {
                _this.players.me.id = this.id;
                _this.socket.emit('register', _this.players.me);
            });

            this.socket.on('other connect', function(other) {
                _this.players.others[other.id] = other;
                _this.addPlayerAvatar(other);
            });

            this.socket.on('other disconnect', function(id) {
                var player = _this.players.others[id];
                delete _this.players.others[id];
                _this.removePlayerAvatar(player);
            });

            this.socket.on('other change', function(data) {
                var player = _this.players.others[data.id];
                if (player) {
                    player.position = data.position;
                    player.mesh.position.copy(data.position);
                }
            });
        },

        removePlayerAvatar: function(player) {
            scene.getScene().remove(player.mesh);
        },

        addPlayerAvatar: function(player) {
            var geometry = new THREE.BoxGeometry(40, 40, 40);

            var texture = THREE.ImageUtils.loadTexture('client/assets/img/grass.jpg');

            // texture.anisotropy = Metavrse.renderer.getMaxAnisotropy();
            var material = new THREE.MeshBasicMaterial({map: texture});

            mesh = new THREE.Mesh(geometry, material);
            mesh.position = player.position;

            player.mesh = mesh;

            scene.getScene().add(mesh);
        },

        playerMoved: function(position) {
            this.players.me.position = position;
            this.socket.emit('change', this.players.me);
        },
    };
});
<|endoftext|>


<commit_before>var Emitter = require( 'events' ).EventEmitter
var inherit = require( 'bloodline' )
var Inspector = require( 'inspector' )
var URL = require( 'url' )
var path = require( 'path' )
var log = require( 'debug' )( 'ZEUGBERG:CHROME' )
var async = require( 'async' )

/**
 * Chrome/Window Frame
 * @return {Chrome}
 */
function Chrome( options ) {

  if( !(this instanceof Chrome) )
    return new Chrome( options )

  Emitter.call( this )

  this.frame = null
  this.devTools = null
  this.inspector = null

  this._isResizing = null

}

Chrome.setTimeout = global.setTimeout.bind( global )
Chrome.clearTimeout = global.clearTimeout.bind( global )

/**
 * Options for Window.open()
 * @type {Object}
 */
Chrome.options = {
  frame: false,
  toolbar: false,
  width: 1024,
  height: 768,
}

/**
 * Chrome prototype
 * @type {Object}
 */
Chrome.prototype = {

  constructor: Chrome,

  get location() {
    if( this.frame != null )
      return this.frame.window.location.href
  },

  set location( value ) {
    if( this.frame != null )
      this.frame.window.location.href = value
    // TODO:
    // - [ ] Handle relative paths
  },

  attachEvents: function() {

    this.frame.on( 'loading', this.onLoading.bind( this ) )
    this.frame.on( 'loaded', this.onLoaded.bind( this ) )
    this.frame.on( 'document-start', this.onDocumentStart.bind( this ) )
    this.frame.on( 'document-end', this.onDocumentEnd.bind( this ) )
    this.frame.on( 'devtools-opened', this.onDevToolsOpened.bind( this ) )
    this.frame.on( 'devtools-closed', this.onDevToolsClosed.bind( this ) )
    this.frame.on( 'resize', this.onResize.bind( this ) )
    this.frame.on( 'capturepagedone', this.onCapturePage.bind( this ) )
    this.frame.on( 'new-win-policy', this.onNewWinPolicy.bind( this ) )
    this.frame.on( 'close', this.onClose.bind( this ) )
    this.frame.on( 'closed', this.onClosed.bind( this ) )

    return this

  },

  attachWindowEvents: function() {
    with( this.frame.window ) {
      addEventListener( 'DOMContentLoaded', this.onDOMContentLoaded.bind( this ) )
      addEventListener( 'load', this.onLoad.bind( this ) )
    }
  },

  attachDebugger: function() {

    if( this.devTools != null )
      return this

    this.devTools = this.frame.showDevTools()
    this.devTools.show( global.argv.debug )

    return this

  },

  attachInspector: function( location, filename ) {

    var self = this
    var remotePort = 9222

    var inspector = this.inspector = new Inspector(
      remotePort, location.hostname, filename,
      function() {
        log( 'INSPECTOR:ATTACHED' )
        self.emit( 'inspector:attached' )
        async.parallel([
          function( done ) { inspector.Network.enable( done ) },
          function( done ) { inspector.Page.enable( done ) },
          function( done ) { inspector.Profiler.enable( done ) },
        ], function( error, results ) {
          if( error != null ) {
            self.emit( 'error', error )
            return
          }
          log( 'INSPECTOR:ENABLED' )
          self.emit( 'inspector:enabled' )
        })
      }
    )

    this.inspector.on( 'error', function( error ) {
      log( 'INSPECTOR:ERROR', error )
      self.emit( 'error', error )
    })

    // Listen for network events, and pick the first
    // document type response after 'loading' event,
    // as it's the page's navigation response
    this.once( 'inspector:enabled', function() {
      this.inspector.Network.on( 'responseReceived', function( event ) {
        if( self.loading && event.type === 'Document' ) {
          self.emit( 'response', event.response )
        }
      })
    })

    // TODO:
    // - [ ] set up HAR recording
    // - [ ] set up JS/CPU profiling

  },

  onLoading: function() {
    this.loading = true
    log( 'LOADING' )
  },

  onDOMContentLoaded: function() {
    log( 'DOMCONTENTLOADED' )
  },

  onLoad: function() {
    log( 'LOAD' )
  },

  onLoaded: function() {
    this.loading = false
    log( 'LOADED' )
    this.emit( 'loaded' )
  },

  onDocumentStart: function() {
    log( 'DOCUMENT:START' )
    this.attachDebugger()
    this.attachWindowEvents()
    this.emit( 'attachEvents' )
  },

  onDocumentEnd: function() {
    log( 'DOCUMENT:END' )
  },

  onDevToolsOpened: function( url ) {

    log( 'DEVTOOLS:OPENED', url )

    var self = this
    var location = URL.parse( url, true )
    var dirname = path.join( __dirname, '..' )
    var filename = 'file://' + dirname + '/about:blank'

    this.attachInspector( location, filename )

  },

  onDevToolsClosed: function() {
    log( 'DEVTOOLS:CLOSED' )
    // Remove the ref to the closed window
    this.devTools = null
    // TODO:
    // - [ ] shutdown the inspector
  },

  onResize: function( width, height ) {
    log( 'RESIZE', width, height )
    var self = this
    Chrome.clearTimeout( this._isResizing )
    this._isResizing = Chrome.setTimeout( function() {
      window.requestAnimationFrame( function() {
        process.nextTick( function() {
          log( 'RESIZED' )
          self.emit( 'resized' )
        })
      })
    }, 200 )
  },

  onCapturePage: function() {
    log( 'CAPTURE_PAGE' )
  },

  // Emitted when a new window is requested from this window
  // or a child iframe, e.g. user clicks a link with _blank target.
  onNewWinPolicy: function( frame, url, policy ) {
    log( 'NEW_WIN_POLICY', url )
    // Force the new (popup) window
    // to open in the current window
    // See nw.js wiki for details
    policy.forceCurrent()
    // NOTE: .forceCurrent() would prematurely terminate a test
    // if the opened frame calls window.close() on itself
    // TODO:
    // - [ ] Handle popups properly
  },

  onClose: function() {
    log( 'CLOSE' )
    // Don't leave any unattached
    // DevTools windows behind
    if( this.devTools != null )
      this.devTools.close( true )
    // Enforce close
    // (without 'true' it will loop endlessly,
    // calling 'onClose' over and over)
    this.close( true )
  },

  onClosed: function() {
    log( 'CLOSED' )
  },

  open: function( path ) {

    if( this.frame != null )
      return this

    var GUI = window.require( 'nw.gui' )
    var location = path || 'about:blank'

    this.frame = GUI.Window.open( location, Chrome.options )
    this.frame.show( global.argv.debug )
    this.attachEvents()

    return this

  },

  close: function( force ) {

    if( this.frame == null )
      return this

    this.frame.close( force )
    this.frame = null

    return this

  },

}

inherit( Chrome, Emitter )
// Exports
module.exports = Chrome
<commit_msg>Updated lib/chrome: Removed Inspector.Profiler<commit_after>var Emitter = require( 'events' ).EventEmitter
var inherit = require( 'bloodline' )
var Inspector = require( 'inspector' )
var URL = require( 'url' )
var path = require( 'path' )
var log = require( 'debug' )( 'ZEUGBERG:CHROME' )
var async = require( 'async' )

/**
 * Chrome/Window Frame
 * @return {Chrome}
 */
function Chrome( options ) {

  if( !(this instanceof Chrome) )
    return new Chrome( options )

  Emitter.call( this )

  this.frame = null
  this.devTools = null
  this.inspector = null

  this._isResizing = null

}

Chrome.setTimeout = global.setTimeout.bind( global )
Chrome.clearTimeout = global.clearTimeout.bind( global )

/**
 * Options for Window.open()
 * @type {Object}
 */
Chrome.options = {
  frame: false,
  toolbar: false,
  width: 1024,
  height: 768,
}

/**
 * Chrome prototype
 * @type {Object}
 */
Chrome.prototype = {

  constructor: Chrome,

  get location() {
    if( this.frame != null )
      return this.frame.window.location.href
  },

  set location( value ) {
    if( this.frame != null )
      this.frame.window.location.href = value
    // TODO:
    // - [ ] Handle relative paths
  },

  attachEvents: function() {

    this.frame.on( 'loading', this.onLoading.bind( this ) )
    this.frame.on( 'loaded', this.onLoaded.bind( this ) )
    this.frame.on( 'document-start', this.onDocumentStart.bind( this ) )
    this.frame.on( 'document-end', this.onDocumentEnd.bind( this ) )
    this.frame.on( 'devtools-opened', this.onDevToolsOpened.bind( this ) )
    this.frame.on( 'devtools-closed', this.onDevToolsClosed.bind( this ) )
    this.frame.on( 'resize', this.onResize.bind( this ) )
    this.frame.on( 'capturepagedone', this.onCapturePage.bind( this ) )
    this.frame.on( 'new-win-policy', this.onNewWinPolicy.bind( this ) )
    this.frame.on( 'close', this.onClose.bind( this ) )
    this.frame.on( 'closed', this.onClosed.bind( this ) )

    return this

  },

  attachWindowEvents: function() {
    with( this.frame.window ) {
      addEventListener( 'DOMContentLoaded', this.onDOMContentLoaded.bind( this ) )
      addEventListener( 'load', this.onLoad.bind( this ) )
    }
  },

  attachDebugger: function() {

    if( this.devTools != null )
      return this

    this.devTools = this.frame.showDevTools()
    this.devTools.show( global.argv.debug )

    return this

  },

  attachInspector: function( location, filename ) {

    var self = this
    var remotePort = 9222

    var inspector = this.inspector = new Inspector(
      remotePort, location.hostname, filename,
      function() {
        log( 'INSPECTOR:ATTACHED' )
        self.emit( 'inspector:attached' )
        async.parallel([
          function( done ) { inspector.Network.enable( done ) },
          function( done ) { inspector.Page.enable( done ) },
        ], function( error, results ) {
          if( error != null ) {
            self.emit( 'error', error )
            return
          }
          log( 'INSPECTOR:ENABLED' )
          self.emit( 'inspector:enabled' )
        })
      }
    )

    this.inspector.on( 'error', function( error ) {
      log( 'INSPECTOR:ERROR', error )
      self.emit( 'error', error )
    })

    // Listen for network events, and pick the first
    // document type response after 'loading' event,
    // as it's the page's navigation response
    this.once( 'inspector:enabled', function() {
      this.inspector.Network.on( 'responseReceived', function( event ) {
        if( self.loading && event.type === 'Document' ) {
          self.emit( 'response', event.response )
        }
      })
    })

    // TODO:
    // - [ ] set up HAR recording
    // - [ ] set up JS/CPU profiling

  },

  onLoading: function() {
    this.loading = true
    log( 'LOADING' )
  },

  onDOMContentLoaded: function() {
    log( 'DOMCONTENTLOADED' )
  },

  onLoad: function() {
    log( 'LOAD' )
  },

  onLoaded: function() {
    this.loading = false
    log( 'LOADED' )
    this.emit( 'loaded' )
  },

  onDocumentStart: function() {
    log( 'DOCUMENT:START' )
    this.attachDebugger()
    this.attachWindowEvents()
    this.emit( 'attachEvents' )
  },

  onDocumentEnd: function() {
    log( 'DOCUMENT:END' )
  },

  onDevToolsOpened: function( url ) {

    log( 'DEVTOOLS:OPENED', url )

    var self = this
    var location = URL.parse( url, true )
    var dirname = path.join( __dirname, '..' )
    var filename = 'file://' + dirname + '/about:blank'

    this.attachInspector( location, filename )

  },

  onDevToolsClosed: function() {
    log( 'DEVTOOLS:CLOSED' )
    // Remove the ref to the closed window
    this.devTools = null
    // TODO:
    // - [ ] shutdown the inspector
  },

  onResize: function( width, height ) {
    log( 'RESIZE', width, height )
    var self = this
    Chrome.clearTimeout( this._isResizing )
    this._isResizing = Chrome.setTimeout( function() {
      window.requestAnimationFrame( function() {
        process.nextTick( function() {
          log( 'RESIZED' )
          self.emit( 'resized' )
        })
      })
    }, 200 )
  },

  onCapturePage: function() {
    log( 'CAPTURE_PAGE' )
  },

  // Emitted when a new window is requested from this window
  // or a child iframe, e.g. user clicks a link with _blank target.
  onNewWinPolicy: function( frame, url, policy ) {
    log( 'NEW_WIN_POLICY', url )
    // Force the new (popup) window
    // to open in the current window
    // See nw.js wiki for details
    policy.forceCurrent()
    // NOTE: .forceCurrent() would prematurely terminate a test
    // if the opened frame calls window.close() on itself
    // TODO:
    // - [ ] Handle popups properly
  },

  onClose: function() {
    log( 'CLOSE' )
    // Don't leave any unattached
    // DevTools windows behind
    if( this.devTools != null )
      this.devTools.close( true )
    // Enforce close
    // (without 'true' it will loop endlessly,
    // calling 'onClose' over and over)
    this.close( true )
  },

  onClosed: function() {
    log( 'CLOSED' )
  },

  open: function( path ) {

    if( this.frame != null )
      return this

    var GUI = window.require( 'nw.gui' )
    var location = path || 'about:blank'

    this.frame = GUI.Window.open( location, Chrome.options )
    this.frame.show( global.argv.debug )
    this.attachEvents()

    return this

  },

  close: function( force ) {

    if( this.frame == null )
      return this

    this.frame.close( force )
    this.frame = null

    return this

  },

}

inherit( Chrome, Emitter )
// Exports
module.exports = Chrome
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BSchema = new Schema({
    surname: {type:String,required:true,index:true,list:{}}, // this field appears in a listing and the default edit form header
    forename:  {type: String, list:true, index:true},        // this field appears in a listing and the default edit form header
    address: {
        line1: {type: String, form:{label: 'Address'}},      // this label overrides the one generated from the field name
        line2: {type: String, form:{label: null}},           // null label - gives a blank label
        line3: {type: String, form:{label: null}},
        town: {type: String, form:{label: 'Town'}},
        postcode: {type: String, form:{label: 'Postcode', help:'Enter your postcode or zip code'}},  // help displays on the line under the control
        country: {type: String, form:{label:"Country", hidden:true}}
    },
    // The email field is indexed, but the noSearch property means the index is not used in the searchBox searches
    // The field has a custom directive (which is defined in /app/js/directives/bespoke-field.js)
    email: {type: String, index:true, noSearch: true, form:{directive: 'email-field'}},
    weight: {type : Number, form:{label:"Weight (lbs)"}},    // this label overrides the one generated from the field name
    dateOfBirth: Date,
    accepted: {type: Boolean, required: true, form:{helpInline: 'Did we take them?'}, list:{}},   // helpInline displays to the right of the input control
    interviewScore:{type:Number,form:{hidden:true},list:{}},  // this field does not appear on the form or listings, even though list is defined - not sure about this
    freeText: {type: String, form:{type: 'textarea', rows:5, help:'There is some validation on this field to ensure that the word "rude" is not entered.  Try it to see the record level error handling.'}}
});

BSchema.pre('save', function(next) {
    // Check for rude words (well, the word "rude", actually) to show an error

    if (this.freeText.indexOf('rude') !== -1) {
        return next(new Error("Wash your mouth!  You must not use rude words."));
    }
    return next();
});

var B = mongoose.model('B', BSchema);

// Alternative form schemas can be defined as shown below
BSchema.statics.form = function(layout) {
    var formSchema = '';
    switch (layout) {
        case 'justnameandpostcode' :
            // the object overrides the form object in the schema
            formSchema = {
                surname:{label:"Family Name"},
                "address.postcode":{},
                "address.country": {}   // fields that are hidden by default but specified in the override schema are not hidden
            };
            break;
    }
    return formSchema;
};

BSchema.statics.findAccepted = function(req,cb) {
    // Only show the accepted items
    cb(null, B.find().where('accepted', true));
};

module.exports = {
    model : B,                                  // pass the mode in an object if you want to add options
    findFunc: BSchema.statics.findAccepted      // this can be used to 'pre' filter selections.
                                                // A common use case is to restrict a user to only see their own records
                                                // as described in https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/TiR5OXR9mAM
};
<commit_msg>Slight improvements to documentation<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BSchema = new Schema({
    surname: {type:String,required:true,index:true,list:{}}, // this field appears in a listing and the default edit form header
    forename:  {type: String, list:true, index:true},        // this field appears in a listing and the default edit form header
    address: {
        line1: {type: String, form:{label: 'Address'}},      // this label overrides the one generated from the field name
        line2: {type: String, form:{label: null}},           // null label - gives a blank label
        line3: {type: String, form:{label: null}},
        town: {type: String, form:{label: 'Town'}},
        postcode: {type: String, form:{label: 'Postcode', help:'Enter your postcode or zip code'}},  // help displays on the line under the control
        country: {type: String, form:{label:"Country", hidden:true}}
    },

    // The email field is indexed, but the noSearch property means the index is not used in the searchBox searches
    // A use case for this would be an index that is used in reports for grouping which has no meaning in a search.
    //
    // The field has a custom directive (which is defined in /app/js/directives/bespoke-field.js)
    email: {type: String, index:true, noSearch: true, form:{directive: 'email-field'}},

    weight: {type : Number, form:{label:"Weight (lbs)"}},    // this label overrides the one generated from the field name
    dateOfBirth: Date,
    accepted: {type: Boolean, required: true, form:{helpInline: 'Did we take them?'}, list:{}},   // helpInline displays to the right of the input control
    interviewScore:{type:Number,form:{hidden:true},list:{}},  // this field does not appear on the form or listings, even though list is defined - not sure about this
    freeText: {type: String, form:{type: 'textarea', rows:5, help:'There is some validation on this field to ensure that the word "rude" is not entered.  Try it to see the record level error handling.'}}
});

BSchema.pre('save', function(next) {
    // Check for rude words (well, the word "rude", actually) to show an error

    if (this.freeText.indexOf('rude') !== -1) {
        return next(new Error("Wash your mouth!  You must not use rude words."));
    }
    return next();
});

var B = mongoose.model('B', BSchema);

// Alternative form schemas can be defined as shown below
BSchema.statics.form = function(layout) {
    var formSchema = '';
    switch (layout) {
        case 'justnameandpostcode' :
            // the object overrides the form object in the schema
            formSchema = {
                surname:{label:"Family Name"},
                "address.postcode":{},
                "address.country": {}   // fields that are hidden by default but specified in the override schema are not hidden
            };
            break;
    }
    return formSchema;
};

BSchema.statics.findAccepted = function(req,cb) {
    // Only show the accepted items
    cb(null, B.find().where('accepted', true));
};

module.exports = {
    model : B,                                  // pass the mode in an object if you want to add options
    findFunc: BSchema.statics.findAccepted      // this can be used to 'pre' filter selections.
                                                // A common use case is to restrict a user to only see their own records
                                                // as described in https://groups.google.com/forum/?fromgroups=#!topic/mongoose-orm/TiR5OXR9mAM
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Handles notifications and subscriptions for store
 * @nameSpace NotificationManager
 */
var notificationManager = {};
(function () {

    var log = new Log('notificationManager');
    //noinspection JSUnresolvedVariable
    var StoreNotificationService = Packages.org.wso2.carbon.store.notifications.service.StoreNotificationService;
    var storeNotifier = new StoreNotificationService();

    /**
     * Notify triggered event
     * @param eventName event that is triggered
     * @param assetType type of the asset event triggered on
     * @param assetName name of the asset event triggered on
     * @param message message to be sent in the notification
     * @param path path of the resource the event occured
     * @param user logged in user
     */
    notificationManager.notifyEvent = function (eventName, assetType, assetName, message, path, user) {
        var isSuccessful;
        var emailContent = generateEmail(assetType, assetName, message, eventName);
        try {
            storeNotifier.notifyEvent(eventName, emailContent, path, user);
            isSuccessful = true;
        } catch (e) {
            log.error('Notifying the event ' + eventName + 'failed for ' + eventName);
            isSuccessful = false;
        }
        return isSuccessful;
    };

    /**
     * Subscribe for an event
     * @param tenantId logged in user
     * @param resourcePath path of the resource subscribing to
     * @param endpoint method of notification (user, role or email)
     * @param eventName event subscribing for
     */
    notificationManager.subscribeToEvent = function (tenantId, resourcePath, endpoint, eventName) {
        var isSuccessful;
        try {
            storeNotifier.subscribeToEvent(tenantId, resourcePath, endpoint, eventName);
            isSuccessful = true;
        } catch (e) {
            log.error('Subscribing to asset on ' + resourcePath + ' failed for ' + eventName);
            isSuccessful = false;
        }
        return isSuccessful;
    };

    /**
     * Remove subscription
     * @param resourcePath path of the resource subscribed to
     * @param eventName event subscribed for
     * @param endpoint method of notification
     */
    notificationManager.unsubscribe = function (resourcePath, eventName, endpoint) {
        storeNotifier.unsubscribe(resourcePath, eventName, endpoint);
    };

    /**
     * Get all the event types
     * @returns event types
     */
    notificationManager.getEventTypes = function () {
        return storeNotifier.getEventTypes();
    };

    /**
     * Get all subscriptions
     * @returns list of subscriptions
     */
    notificationManager.getAllSubscriptions = function () {
        try {
            return storeNotifier.getAllSubscriptions();
        } catch (e) {
            log.error("Retrieving subscription list failed");
            return null;
        }
    };

    /**
     * Generates an email message containing details of an event
     * @param assetType type of the asset event triggered on
     * @param assetName name of the asset event triggered on
     * @param msg message to send in the email
     * @param eventName name of the triggered event
     * @return content of the email
     */
    var generateEmail = function (assetType, assetName, msg, eventName) {

        var stringAssetName = stringify(assetName);
        var stringAssetType = stringify(assetType);
        var stringMsg = stringify(msg);

        var email_temp;
        if (eventName == storeConstants.LC_STATE_CHANGE_EVENT) {
            email_temp = storeConstants.EMAIL_TEMPLATE_LC;
        } else if (eventName == storeConstants.ASSET_UPDATE_EVENT) {
            email_temp = storeConstants.EMAIL_TEMPLATE_UPDATE;
        } else if (eventName == storeConstants.VERSION_CREATED_EVENT) {
            email_temp = storeConstants.EMAIL_TEMPLATE_VERSION;
        } else {
            email_temp = storeConstants.EMAIL_TEMPLATE_DEFAULT;
        }

        message = new JaggeryParser().parse(email_temp).toString();

        //evaluating the template in Jaggery //TODO improve template evaluation to support custom templates
        var templateScript = '(function() { var result = ""; var assetName=' + stringAssetName + '; var msg =' + stringMsg + '; var assetType =' + stringAssetType +
            '; print = function(text) { if(typeof text === "object") {result += stringify(text);} else {result += text;} };' + message + ' return result;}())';

        return eval(templateScript);
    }

}());<commit_msg>Fixing error logs according to new logging in jaggery<commit_after>/*
 * Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Handles notifications and subscriptions for store
 * @nameSpace NotificationManager
 */
var notificationManager = {};
(function () {

    var log = new Log('notificationManager');
    //noinspection JSUnresolvedVariable
    var StoreNotificationService = Packages.org.wso2.carbon.store.notifications.service.StoreNotificationService;
    var storeNotifier = new StoreNotificationService();

    /**
     * Notify triggered event
     * @param eventName event that is triggered
     * @param assetType type of the asset event triggered on
     * @param assetName name of the asset event triggered on
     * @param message message to be sent in the notification
     * @param path path of the resource the event occured
     * @param user logged in user
     */
    notificationManager.notifyEvent = function (eventName, assetType, assetName, message, path, user) {
        var isSuccessful;
        var emailContent = generateEmail(assetType, assetName, message, eventName);
        try {
            storeNotifier.notifyEvent(eventName, emailContent, path, user);
            isSuccessful = true;
        } catch (e) {
            log.error('Notifying the event ' + eventName + 'failed for ' + eventName, e);
            isSuccessful = false;
        }
        return isSuccessful;
    };

    /**
     * Subscribe for an event
     * @param tenantId logged in user
     * @param resourcePath path of the resource subscribing to
     * @param endpoint method of notification (user, role or email)
     * @param eventName event subscribing for
     */
    notificationManager.subscribeToEvent = function (tenantId, resourcePath, endpoint, eventName) {
        var isSuccessful;
        try {
            storeNotifier.subscribeToEvent(tenantId, resourcePath, endpoint, eventName);
            isSuccessful = true;
        } catch (e) {
            log.error('Subscribing to asset on ' + resourcePath + ' failed for ' + eventName, e);
            isSuccessful = false;
        }
        return isSuccessful;
    };

    /**
     * Remove subscription
     * @param resourcePath path of the resource subscribed to
     * @param eventName event subscribed for
     * @param endpoint method of notification
     */
    notificationManager.unsubscribe = function (resourcePath, eventName, endpoint) {
        storeNotifier.unsubscribe(resourcePath, eventName, endpoint);
    };

    /**
     * Get all the event types
     * @returns event types
     */
    notificationManager.getEventTypes = function () {
        return storeNotifier.getEventTypes();
    };

    /**
     * Get all subscriptions
     * @returns list of subscriptions
     */
    notificationManager.getAllSubscriptions = function () {
        try {
            return storeNotifier.getAllSubscriptions();
        } catch (e) {
            log.error("Retrieving subscription list failed", e);
            return null;
        }
    };

    /**
     * Generates an email message containing details of an event
     * @param assetType type of the asset event triggered on
     * @param assetName name of the asset event triggered on
     * @param msg message to send in the email
     * @param eventName name of the triggered event
     * @return content of the email
     */
    var generateEmail = function (assetType, assetName, msg, eventName) {

        var stringAssetName = stringify(assetName);
        var stringAssetType = stringify(assetType);
        var stringMsg = stringify(msg);

        var email_temp;
        if (eventName == storeConstants.LC_STATE_CHANGE_EVENT) {
            email_temp = storeConstants.EMAIL_TEMPLATE_LC;
        } else if (eventName == storeConstants.ASSET_UPDATE_EVENT) {
            email_temp = storeConstants.EMAIL_TEMPLATE_UPDATE;
        } else if (eventName == storeConstants.VERSION_CREATED_EVENT) {
            email_temp = storeConstants.EMAIL_TEMPLATE_VERSION;
        } else {
            email_temp = storeConstants.EMAIL_TEMPLATE_DEFAULT;
        }

        message = new JaggeryParser().parse(email_temp).toString();

        //evaluating the template in Jaggery //TODO improve template evaluation to support custom templates
        var templateScript = '(function() { var result = ""; var assetName=' + stringAssetName + '; var msg =' + stringMsg + '; var assetType =' + stringAssetType +
            '; print = function(text) { if(typeof text === "object") {result += stringify(text);} else {result += text;} };' + message + ' return result;}())';

        return eval(templateScript);
    }

}());<|endoftext|>


<commit_before>// if node
var Stream = require('stream').Stream;
var EventEmitter = require('events').EventEmitter;
var BufferReadStream = require('streamers').BufferReadStream;
var WebSocket = require('streamws');

var util = require('./util');
var BinaryStream = require('./stream').BinaryStream;

// end node

function BinaryClient(socket, options) {
  if (!(this instanceof BinaryClient)) return new BinaryClient(socket, options);

  EventEmitter.call(this);

  var self = this;

  this._options = util.extend({
    chunkSize: 40960
  }, options);

  this.streams = {};

  if(typeof socket === 'string') {
    this._nextId = 0;
    this._socket = new WebSocket(socket);
  } else {
    // Use odd numbered ids for server originated streams
    this._nextId = 1;
    this._socket = socket;
  }

  this._socket.binaryType = 'arraybuffer';

  this._socket.addEventListener('open', function(){
    self.emit('open');
  });
  // if node
  this._socket.on('drain', function(){
    var ids = Object.keys(self.streams);
    for (var i = 0, ii = ids.length; i < ii; i++) {
      self.streams[ids[i]]._onDrain();
    }
  });
  // end node
  this._socket.addEventListener('error', function(error){
    var ids = Object.keys(self.streams);
    for (var i = 0, ii = ids.length; i < ii; i++) {
      self.streams[ids[i]]._onError(error);
    }
    self.emit('error', error);
  });
  this._socket.addEventListener('close', function(code, message){
    var ids = Object.keys(self.streams);
    for (var i = 0, ii = ids.length; i < ii; i++) {
      self.streams[ids[i]]._onClose();
    }
    self.emit('close', code, message);
  });
  this._socket.addEventListener('message', function(data, flags){
    util.setZeroTimeout(function(){

      // Message format
      // [type, payload, bonus ]
      //
      // Reserved
      // [ 0  , X , X ]
      //
      //
      // New stream
      // [ 1  , Meta , new streamId ]
      //
      //
      // Data
      // [ 2  , Data , streamId ]
      //
      //
      // Pause
      // [ 3  , null , streamId ]
      //
      //
      // Resume
      // [ 4  , null , streamId ]
      //
      //
      // End
      // [ 5  , null , streamId ]
      //
      //
      // Close
      // [ 6  , null , streamId ]
      //

      data = data.data;

      try {
          data = util.unpack(data);
      } catch (ex) {
          return self.emit('error', new Error('Received unparsable message: ' + ex));
      }
      if (!(data instanceof Array))
          return self.emit('error', new Error('Received non-array message'));
      if (data.length != 3)
          return self.emit('error', new Error('Received message with wrong part count: ' + data.length));
      if ('number' != typeof data[0])
          return self.emit('error', new Error('Received message with non-number type: ' + data[0]));

      switch(data[0]) {
        case 0:
          // Reserved
          break;
        case 1:
          var meta = data[1];
          var streamId = data[2];
          var binaryStream = self._receiveStream(streamId);
          self.emit('stream', binaryStream, meta);
          break;
        case 2:
          var payload = data[1];
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onData(payload);
          } else {
            self.emit('error', new Error('Received `data` message for unknown stream: ' + streamId));
          }
          break;
        case 3:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onPause();
          } else {
            self.emit('error', new Error('Received `pause` message for unknown stream: ' + streamId));
          }
          break;
        case 4:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onResume();
          } else {
            self.emit('error', new Error('Received `resume` message for unknown stream: ' + streamId));
          }
          break;
        case 5:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onEnd();
          } else {
            self.emit('error', new Error('Received `end` message for unknown stream: ' + streamId));
          }
          break;
        case 6:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onClose();
          } else {
            self.emit('error', new Error('Received `close` message for unknown stream: ' + streamId));
          }
          break;
        default:
          self.emit('error', new Error('Unrecognized message type received: ' + data[0]));
      }
    });
  });
}

util.inherits(BinaryClient, EventEmitter);

BinaryClient.prototype.send = function(data, meta){
  var stream = this.createStream(meta);
  if(data instanceof Stream) {
    data.pipe(stream);
  } else if (util.isNode === true) {
    if(Buffer.isBuffer(data)) {
      (new BufferReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else {
      stream.write(data);
    }
  } else if (util.isNode !== true) {
    if(data.constructor == Blob || data.constructor == File) {
      (new BlobReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else if (data.constructor == ArrayBuffer) {
      var blob;
      if(binaryFeatures.useArrayBufferView) {
        data = new Uint8Array(data);
      }
      if(binaryFeatures.useBlobBuilder) {
        var builder = new BlobBuilder();
        builder.append(data);
        blob = builder.getBlob()
      } else {
        blob = new Blob([data]);
      }
      (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else if (typeof data === 'object' && 'BYTES_PER_ELEMENT' in data) {
      var blob;
      if(!binaryFeatures.useArrayBufferView) {
        // Warn
        data = data.buffer;
      }
      if(binaryFeatures.useBlobBuilder) {
        var builder = new BlobBuilder();
        builder.append(data);
        blob = builder.getBlob()
      } else {
        blob = new Blob([data]);
      }
      (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else {
      stream.write(data);
    }
  }
  return stream;
};

BinaryClient.prototype._receiveStream = function(streamId){
  var self = this;
  var binaryStream = new BinaryStream(this._socket, streamId, false);
  binaryStream.on('close', function(){
    delete self.streams[streamId];
  });
  this.streams[streamId] = binaryStream;
  return binaryStream;
};

BinaryClient.prototype.createStream = function(meta){
  if(this._socket.readyState !== WebSocket.OPEN) {
    throw new Error('Client is not yet connected or has closed');
    return;
  }
  var self = this;
  var streamId = this._nextId;
  this._nextId += 2;
  var binaryStream = new BinaryStream(this._socket, streamId, true, meta);
  binaryStream.on('close', function(){
    delete self.streams[streamId];
  });
  this.streams[streamId] = binaryStream;
  return binaryStream;
};

BinaryClient.prototype.close = BinaryClient.prototype.destroy = function(code, message) {
  this._socket.close(code, message);
};

exports.BinaryClient = BinaryClient;
<commit_msg>Fix close internal socket by removing parameters<commit_after>// if node
var Stream = require('stream').Stream;
var EventEmitter = require('events').EventEmitter;
var BufferReadStream = require('streamers').BufferReadStream;
var WebSocket = require('streamws');

var util = require('./util');
var BinaryStream = require('./stream').BinaryStream;

// end node

function BinaryClient(socket, options) {
  if (!(this instanceof BinaryClient)) return new BinaryClient(socket, options);

  EventEmitter.call(this);

  var self = this;

  this._options = util.extend({
    chunkSize: 40960
  }, options);

  this.streams = {};

  if(typeof socket === 'string') {
    this._nextId = 0;
    this._socket = new WebSocket(socket);
  } else {
    // Use odd numbered ids for server originated streams
    this._nextId = 1;
    this._socket = socket;
  }

  this._socket.binaryType = 'arraybuffer';

  this._socket.addEventListener('open', function(){
    self.emit('open');
  });
  // if node
  this._socket.on('drain', function(){
    var ids = Object.keys(self.streams);
    for (var i = 0, ii = ids.length; i < ii; i++) {
      self.streams[ids[i]]._onDrain();
    }
  });
  // end node
  this._socket.addEventListener('error', function(error){
    var ids = Object.keys(self.streams);
    for (var i = 0, ii = ids.length; i < ii; i++) {
      self.streams[ids[i]]._onError(error);
    }
    self.emit('error', error);
  });
  this._socket.addEventListener('close', function(code, message){
    var ids = Object.keys(self.streams);
    for (var i = 0, ii = ids.length; i < ii; i++) {
      self.streams[ids[i]]._onClose();
    }
    self.emit('close', code, message);
  });
  this._socket.addEventListener('message', function(data, flags){
    util.setZeroTimeout(function(){

      // Message format
      // [type, payload, bonus ]
      //
      // Reserved
      // [ 0  , X , X ]
      //
      //
      // New stream
      // [ 1  , Meta , new streamId ]
      //
      //
      // Data
      // [ 2  , Data , streamId ]
      //
      //
      // Pause
      // [ 3  , null , streamId ]
      //
      //
      // Resume
      // [ 4  , null , streamId ]
      //
      //
      // End
      // [ 5  , null , streamId ]
      //
      //
      // Close
      // [ 6  , null , streamId ]
      //

      data = data.data;

      try {
          data = util.unpack(data);
      } catch (ex) {
          return self.emit('error', new Error('Received unparsable message: ' + ex));
      }
      if (!(data instanceof Array))
          return self.emit('error', new Error('Received non-array message'));
      if (data.length != 3)
          return self.emit('error', new Error('Received message with wrong part count: ' + data.length));
      if ('number' != typeof data[0])
          return self.emit('error', new Error('Received message with non-number type: ' + data[0]));

      switch(data[0]) {
        case 0:
          // Reserved
          break;
        case 1:
          var meta = data[1];
          var streamId = data[2];
          var binaryStream = self._receiveStream(streamId);
          self.emit('stream', binaryStream, meta);
          break;
        case 2:
          var payload = data[1];
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onData(payload);
          } else {
            self.emit('error', new Error('Received `data` message for unknown stream: ' + streamId));
          }
          break;
        case 3:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onPause();
          } else {
            self.emit('error', new Error('Received `pause` message for unknown stream: ' + streamId));
          }
          break;
        case 4:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onResume();
          } else {
            self.emit('error', new Error('Received `resume` message for unknown stream: ' + streamId));
          }
          break;
        case 5:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onEnd();
          } else {
            self.emit('error', new Error('Received `end` message for unknown stream: ' + streamId));
          }
          break;
        case 6:
          var streamId = data[2];
          var binaryStream = self.streams[streamId];
          if(binaryStream) {
            binaryStream._onClose();
          } else {
            self.emit('error', new Error('Received `close` message for unknown stream: ' + streamId));
          }
          break;
        default:
          self.emit('error', new Error('Unrecognized message type received: ' + data[0]));
      }
    });
  });
}

util.inherits(BinaryClient, EventEmitter);

BinaryClient.prototype.send = function(data, meta){
  var stream = this.createStream(meta);
  if(data instanceof Stream) {
    data.pipe(stream);
  } else if (util.isNode === true) {
    if(Buffer.isBuffer(data)) {
      (new BufferReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else {
      stream.write(data);
    }
  } else if (util.isNode !== true) {
    if(data.constructor == Blob || data.constructor == File) {
      (new BlobReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else if (data.constructor == ArrayBuffer) {
      var blob;
      if(binaryFeatures.useArrayBufferView) {
        data = new Uint8Array(data);
      }
      if(binaryFeatures.useBlobBuilder) {
        var builder = new BlobBuilder();
        builder.append(data);
        blob = builder.getBlob()
      } else {
        blob = new Blob([data]);
      }
      (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else if (typeof data === 'object' && 'BYTES_PER_ELEMENT' in data) {
      var blob;
      if(!binaryFeatures.useArrayBufferView) {
        // Warn
        data = data.buffer;
      }
      if(binaryFeatures.useBlobBuilder) {
        var builder = new BlobBuilder();
        builder.append(data);
        blob = builder.getBlob()
      } else {
        blob = new Blob([data]);
      }
      (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
    } else {
      stream.write(data);
    }
  }
  return stream;
};

BinaryClient.prototype._receiveStream = function(streamId){
  var self = this;
  var binaryStream = new BinaryStream(this._socket, streamId, false);
  binaryStream.on('close', function(){
    delete self.streams[streamId];
  });
  this.streams[streamId] = binaryStream;
  return binaryStream;
};

BinaryClient.prototype.createStream = function(meta){
  if(this._socket.readyState !== WebSocket.OPEN) {
    throw new Error('Client is not yet connected or has closed');
    return;
  }
  var self = this;
  var streamId = this._nextId;
  this._nextId += 2;
  var binaryStream = new BinaryStream(this._socket, streamId, true, meta);
  binaryStream.on('close', function(){
    delete self.streams[streamId];
  });
  this.streams[streamId] = binaryStream;
  return binaryStream;
};

BinaryClient.prototype.close = BinaryClient.prototype.destroy = function() {
  this._socket.close();
};

exports.BinaryClient = BinaryClient;
<|endoftext|>


<commit_before>import { readFileSync, writeFileSync } from 'fs';
import { load as loadYaml } from 'yaml-js';

const exportConfig = `export default ${JSON.stringify(loadYaml(readFileSync('./dory.yml')))};`;
writeFileSync('./public/js/config.js', exportConfig, 'utf8');
<commit_msg>Added  to config from 'package.json' file<commit_after>import { readFileSync, writeFileSync } from 'fs';
import { load as loadYaml } from 'yaml-js';

const userConfig = loadYaml(readFileSync('./dory.yml', 'utf8'));
const version = JSON.parse(readFileSync('./package.json', 'utf8')).version;
const config = JSON.stringify({ ...userConfig, version });

const exportConfig = `export default ${config};`;
writeFileSync('./public/js/config.js', exportConfig, 'utf8');
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { Button, Card, CardBlock, CardTitle, CardSubtitle, Col, Input, Form, FormGroup, Label, Popover, PopoverTitle, PopoverContent } from 'reactstrap'
import ConfirmRejectModal from '../ConfirmRejectModal/ConfirmRejectModal'
import EditBar from '../EditBar/EditBar'
import styles from './Edit.css'

class Edit extends Component {
  constructor (props) {
    super(props)
    this.state = {
      fieldname: '',
      saveModalOpen: false,
      backModalOpen: false,
      popoverOpen: false
    }
  }

  toggleSaveModal = () => {
    this.setState({
      saveModalOpen: !this.state.saveModalOpen
    })
  }

  toggleBackModal = () => {
    this.setState({
      backModalOpen: !this.state.backModalOpen
    })
  }

  togglePopover = () => {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    })
  }

  handleSaveConfirmClick = () => {
    this.props.actions.mergeEditedToProducts()
    this.props.actions.saveAllProducts()
    this.toggleSaveModal()
  }

  handleBackConfirmClick = () => {
    this.props.actions.clearSearchInput()
    this.props.actions.changeLocation('/')
    this.toggleBackModal()
  }

  handleInputChange (event) {
    this.props.actions.updateEditedProduct(event.target.id, event.target.value)
  }

  handleFieldnameInput (event) {
    this.setState({
      fieldname: event.target.value
    })
  }

  handleCreateFieldClick = () => {
    const fieldname = this.state.fieldname
    this.props.actions.updateEditedProduct(fieldname, '')
    this.togglePopover()
    this.setState({
      fieldname: ''
    })
  }

  renderFormGroup = () => {
    return Object.keys(this.props.editedProduct).map(key => {
      const renderInputs = () => {
        switch (key) {
          case 'filename':
            return <Input
              type='text'
              id={key}
              readOnly
              value={this.props.editedProduct[key]} />

          case 'id':
            return <Input
              type='text'
              id={key}
              readOnly
              value={this.props.editedProduct[key]} />

          case 'processes':
            return <Input
              type='text'
              id={key}
              readOnly
              value={'processes array not editable'} />

          default:
            return <Input
              type='text'
              id={key}
              onKeyUp={(e) => this.handleInputChange(e)}
              placeholder={this.props.editedProduct[key]} />
        }
      }

      return (
        <FormGroup key={key} row>

            {key}

          <Col sm={8}>
            {renderInputs()}
          </Col>
        </FormGroup>
      )
    })
  }

  renderEditView = () => {
    return (

        <Card>
          <CardBlock>
            <CardTitle>{this.props.editedProduct.name}</CardTitle>
            <CardSubtitle>{this.props.editedProduct.filename}</CardSubtitle>
          </CardBlock>
          <CardBlock>
            <Form>
              {this.renderFormGroup()}
            </Form>
          </CardBlock>
          <CardBlock>

              <Col sm={2}>
                <Button
                  onClick={() => this.togglePopover()}
                  outline
                  id='addField'
                  color='warning'
                  block >
                  Add field
                </Button>
                <Popover
                  placement='top'
                  isOpen={this.state.popoverOpen}
                  target='addField'
                  toggle={this.togglePopover}>
                  <PopoverTitle>
                    Enter field name
                  </PopoverTitle>
                  <PopoverContent>
                    <Input
                      type='text'
                      onKeyUp={(e) => this.handleFieldnameInput(e)}
                      placeholder='fieldname' />
                  </PopoverContent>
                  <PopoverContent className={styles.popoverBtn}>
                    <Button
                      onClick={() => this.handleCreateFieldClick()}
                      size='sm'
                      color='success'>
                      Create field
                    </Button>
                  </PopoverContent>
                </Popover>
              </Col>
              <Col sm={3}>
                <Button
                  onClick={() => this.toggleSaveModal()}
                  outline
                  color='success'>
                  Save changes
                </Button>
                <ConfirmRejectModal
                  isOpen={this.state.saveModalOpen}
                  toggle={this.toggleSaveModal}
                  onConfirmClick={this.handleSaveConfirmClick}
                  onRejectClick={this.toggleSaveModal}
                  header='Saving will overwrite file!'
                  body={`Clicking save will overwrite ${this.props.editedProduct.filename}! Are you sure?`}
                  confirmBtnText='Save!'
                  rejectBtnText='Cancel'
                  />
              </Col>

          </CardBlock>
        </Card>

    )
  }

  render () {
    return (

        <EditBar
          actions={this.props.actions}
          filename={this.props.editedProduct.filename}
          saveModalOpen={this.state.saveModalOpen}
          backModalOpen={this.state.backModalOpen}
          toggleSaveModal={this.toggleSaveModal}
          toggleBackModal={this.toggleBackModal}
          handleSaveConfirmClick={this.handleSaveConfirmClick}
          handleBackConfirmClick={this.handleBackConfirmClick}
          handleSaveRejectClick={this.toggleSaveModal}
          handleBackRejectClick={this.toggleBackModal} />
        {this.renderEditView()}

    )
  }
}

Edit.propTypes = {
  dataDir: PropTypes.string.isRequired,
  editedProduct: PropTypes.object.isRequired,
  actions: PropTypes.object.isRequired
}

export default Edit
<commit_msg>Removes placeholders in edit view. Field values are now shown as editable text<commit_after>import React, { Component, PropTypes } from 'react'
import { Button, Card, CardBlock, CardTitle, CardSubtitle, Col, Input, Form, FormGroup, Label, Popover, PopoverTitle, PopoverContent } from 'reactstrap'
import ConfirmRejectModal from '../ConfirmRejectModal/ConfirmRejectModal'
import EditBar from '../EditBar/EditBar'
import styles from './Edit.css'

class Edit extends Component {
  static propTypes = {
    dataDir: PropTypes.string.isRequired,
    editedProduct: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired
  }

  state = {
    fieldname: '',
    saveModalOpen: false,
    backModalOpen: false,
    popoverOpen: false
  }

  toggleSaveModal = () => {
    this.setState({
      saveModalOpen: !this.state.saveModalOpen
    })
  }

  toggleBackModal = () => {
    this.setState({
      backModalOpen: !this.state.backModalOpen
    })
  }

  togglePopover = () => {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    })
  }

  handleSaveConfirmClick = () => {
    this.props.actions.mergeEditedToProducts()
    this.props.actions.saveAllProducts()
    this.toggleSaveModal()
  }

  handleBackConfirmClick = () => {
    this.props.actions.clearSearchInput()
    this.props.actions.changeLocation('/')
    this.toggleBackModal()
  }

  handleInputChange = event => {
    this.props.actions.updateEditedProduct(event.target.id, event.target.value)
  }

  handleFieldnameInput = event => {
    this.setState({
      fieldname: event.target.value
    })
  }

  handleCreateFieldClick = () => {
    const fieldname = this.state.fieldname
    this.props.actions.updateEditedProduct(fieldname, '')
    this.togglePopover()
    this.setState({
      fieldname: ''
    })
  }

  renderFormGroup = () => {
    return Object.keys(this.props.editedProduct).map(key => {
      const renderInputs = () => {
        switch (key) {
          case 'filename':
            return

          case 'validationSummary':
            return

          case 'id':
            // id is read only!
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    readOnly
                    value={this.props.editedProduct[key]} />
                </Col>

            )

          case 'processes':
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    readOnly
                    value='Processes array not editable... Sorry!' />
                </Col>

            )

          default:
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    onChange={this.handleInputChange}
                    value={this.props.editedProduct[key]} />
                </Col>

            )
        }
      }

      return (
        <FormGroup key={key} row>
          {renderInputs()}
        </FormGroup>
      )
    })
  }

  renderEditView = () => {
    return (

        <Card>
          <CardBlock>
            <CardTitle>{this.props.editedProduct.name}</CardTitle>
            <CardSubtitle>{this.props.editedProduct.filename}</CardSubtitle>
          </CardBlock>
          <CardBlock>
            <Form>
              {this.renderFormGroup()}
            </Form>
          </CardBlock>
          <CardBlock>

              <Col sm={2}>
                <Button
                  onClick={() => this.togglePopover()}
                  outline
                  id='addField'
                  color='warning'
                  block >
                  Add field
                </Button>
                <Popover
                  placement='top'
                  isOpen={this.state.popoverOpen}
                  target='addField'
                  toggle={this.togglePopover}>
                  <PopoverTitle>
                    Enter field name
                  </PopoverTitle>
                  <PopoverContent>
                    <Input
                      type='text'
                      onKeyUp={this.handleFieldnameInput}
                      placeholder='fieldname' />
                  </PopoverContent>
                  <PopoverContent className={styles.popoverBtn}>
                    <Button
                      onClick={() => this.handleCreateFieldClick()}
                      size='sm'
                      color='success'>
                      Create field
                    </Button>
                  </PopoverContent>
                </Popover>
              </Col>
              <Col sm={3}>
                <Button
                  onClick={() => this.toggleSaveModal()}
                  outline
                  color='success'>
                  Save changes
                </Button>
                <ConfirmRejectModal
                  isOpen={this.state.saveModalOpen}
                  toggle={this.toggleSaveModal}
                  onConfirmClick={this.handleSaveConfirmClick}
                  onRejectClick={this.toggleSaveModal}
                  header='Saving will overwrite file!'
                  body={`Clicking save will overwrite ${this.props.editedProduct.filename}! Are you sure?`}
                  confirmBtnText='Save!'
                  rejectBtnText='Cancel'
                  />
              </Col>

          </CardBlock>
        </Card>

    )
  }

  render () {
    return (

        <EditBar
          actions={this.props.actions}
          filename={this.props.editedProduct.filename}
          saveModalOpen={this.state.saveModalOpen}
          backModalOpen={this.state.backModalOpen}
          toggleSaveModal={this.toggleSaveModal}
          toggleBackModal={this.toggleBackModal}
          handleSaveConfirmClick={this.handleSaveConfirmClick}
          handleBackConfirmClick={this.handleBackConfirmClick}
          handleSaveRejectClick={this.toggleSaveModal}
          handleBackRejectClick={this.toggleBackModal} />
        {this.renderEditView()}

    )
  }
}

export default Edit
<|endoftext|>


<commit_before>var _         = require('underscore')
  , async     = require('async')
  , request   = require('request')
  , qs        = require('querystring')
  , defaults  = require('./defaults')
  , forms     = require('forms')
  , fields    = forms.fields;

/*
TODO

Getting options from multiple functions

Handle MFA
  have testing feature with commandline enter
  User built in funcitions like that ironio one
  Have built in convert to HTML forms
*/

/**
 * Plaid.io node client driver
 *
 * @param  {Object} config
 *   @param  {String} client_id     - Plaid.io "client_id"
 *   @param  {String} secret        - Plaid.io "secret"
 *
 */
var Client = module.exports = function (config) {

  this.initialized = false;

  if (config) this.init(config);
};

/**
 * Initializes this client.
 *
 * @param  {Object} config
 *   @param  {String} client_id     - Plaid.io "client_id"
 *   @param  {String} secret        - Plaid.io "secret"
 *
 */
Client.prototype.init = function (config) {

  if (config.secret.length<0 ||  config.client_id.length<0)
      throw new Error('plaid-node client must be initialized with a '+
                    'non-empty API "secret" and "client_id" parameter.');

  if (typeof(config.secret)!='string' ||  typeof(config.client_id)!='string')
      throw new Error('plaid-node client must be initialized with a '+
                    'non-empty API "secret" and "client_id" parameter.');

  this.secret      = config.secret;
  this.client_id   = config.client_id;
  this.config     = _.defaults(config || {}, defaults);

  this.initialized = true;
};

/**
 * Internal method to check whether the client has been initialized.
 * @private
 */
Client.prototype._checkInitialized = function () {
  if (!this.initialized)
    throw new Error('analytics-node client is not initialized. Please call ' +
                    'client.init(config).');
};

/**
 * Connect a card to the Plaid API
 *
 *
 * @param  {Object} credentials     - The credentials for that card
 *   @param  {String}   username    - id for logged in user
 *   @param  {Password} password    - key/value object of tags for the user (optional)
     ...
 *
 * @param  {Object}  options   - app provided context about the user (optional)
 *
 * @callback {Error, Object, Object}
 *
 */
Client.prototype.connect = function (credentials, type, email, options, callback) {

  this._checkInitialized();

  if (!credentials || typeof(credentials)!= 'object') {
      throw new Error('[plaid]#connect: credentials must be an object');
  }

  if(!callback && (typeof options ==='function')) {
    callback = options;
    options  = {};
  }

  if(!type || typeof(type)!='string'){
    throw new Error('[plaid]#connect: Type missing or invalid');
  }

  if(!email || typeof(email)!='string'){
    throw new Error('[plaid]#connect: Email missing or invalid');
  }

  if(!callback){
    callback = function(){};
  }

  this.options     = options;
  this.credentials = credentials;
  this.type        = type;
  this.email       = email;

  return this._exec('submit', callback);
};

Client.prototype.step = function (access_token, mfa, options, callback) {

  this._checkInitialized();

  if(!callback && typeof(options)=='function'){
    callback = options;
    options  = {};
  }

  if(!callback){
    callback = function(){};
  }

  this.options      = options;
  this.access_token = access_token;
  this.mfa          = mfa;

  return this._exec('step', callback);
};

Client.prototype.get = function(access_token, options, callback) {
  this._checkInitialized();

  if(!callback && typeof(options) == 'function') {
    callback = options;
    options = {};
  }

  this.options = options;

  this.access_token = access_token;

  return this._exec('get', callback);
}

Client.prototype.remove = function(access_token, options, callback) {
  this._checkInitialized();

  if(!callback && typeof(options) == 'function') {
    callback = options;
    options = {};
  }

  this.options = options;

  this.access_token = access_token;

  return this._exec('remove', callback);
}

Client.prototype._exec = function (method, callback){

  var uri = this.config.protocol + this.config.host + this.config.endpoint[method].route;

  var query = {
      client_id   : this.client_id
    , secret      : this.secret
    , credentials : JSON.stringify(this.credentials)
    , type        : this.type
    , email       : this.email
    , access_token: this.access_token
    , options     : JSON.stringify(this.options)
    , mfa         : this.mfa
  }

  // the login option has to be set a separate parameter
  if (this.options.login) {
    query.login = this.options.login;
  }

  uri += "?"+qs.stringify(query);

  var self = this;

  request(
    { method: this.config.endpoint[method].method
    , uri: uri
    //, qs : qs.stringify(query)
    }
  , function (error, response, body) {
      if(!response) response = {};
      if(error || response.statusCode != 200)
        return self._handleError(error, response.statusCode, body, callback);

      self.body = body;
      return self._handleSuccess(callback);

    }
  )
}

Client.prototype._handleSuccess = function(callback){
  try{
    this.body = JSON.parse(this.body);
  }catch(err){
    return callback("Couldn't parse body");
  }

  if(this.body.status === 'MFA')
    return this._handleMFA(callback);

  if(!this.body.success && (typeof this.body.mfa === 'undefined'))
    return callback(this.body.error);

  return callback(null, this.body, (this.body.mfa !== 'undefined'));
}

Client.prototype._handleError = function(error, status, body, callback){
  if(error)
    return callback(error)

  try{
    body = JSON.parse(body);
  }catch(err){
    return callback("Couldn't parse body");
  }

  return callback(body.error || "Unknown error occured", body);
}

Client.prototype._handleMFA = function(callback){

  this.config.endpoint  = '/connect/submit/step';
  this.access_token     = this.access_token   || this.body.accessToken;
  this.options.itemID   = this.options.itemID || this.body.message.itemID;

  var self = this;
  //helper
  var step = function(credentials, callback){
    if(self.options.mfaCL)
      return self._mfaCL(credentials, callback);
    return self.connect(credentials, self.type, self.email, self.options, callback);
  }
  var html = function(){
    return self._formToHTML(self.body.message.form);
  }

  this.body.message.step = step;
  if(this.body.message.form)
    this.body.message.form.html = html;
  else
    console.log(this.body.message);

  return callback(null, this.body, true)
}

/* MFA testing CL */

Client.prototype._mfaCL = function(credentials, callback){
  var readline = require('readline');
  var credentials = {};

  //Making sure there is a valid form object
  if(this.body.message.form)
    var holder = this.body.message.form;
  else{
    return console.log("Unknown message");
  }

  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  //The function that is called for every question
  var read = function(question, cbk){
    var display = question.display + ": ";
    rl.question(display, function(answer) {
      credentials[display]=answer;
      return cbk();
    });
  }

  var self = this;
  async.forEachSeries(holder, read, function(err, result){

    //Closing the readline interface
    rl.close();
    self.credentials = credentials;

    return self.connect(self.credentials, self.type, self.email, self.options, callback);
  });
}

Client.prototype._formToHTML = function(raw){
  var form = {};

  for(i in raw){
    if(raw[i].type=='text')
      form[raw[i].display]=fields.string();
  }

  var form = forms.create(form).toHTML();

  return '<form>'+form+'</form>';

}
<commit_msg>fix error code<commit_after>var _         = require('underscore')
  , async     = require('async')
  , request   = require('request')
  , qs        = require('querystring')
  , defaults  = require('./defaults')
  , forms     = require('forms')
  , fields    = forms.fields;

/*
TODO

Getting options from multiple functions

Handle MFA
  have testing feature with commandline enter
  User built in funcitions like that ironio one
  Have built in convert to HTML forms
*/

/**
 * Plaid.io node client driver
 *
 * @param  {Object} config
 *   @param  {String} client_id     - Plaid.io "client_id"
 *   @param  {String} secret        - Plaid.io "secret"
 *
 */
var Client = module.exports = function (config) {

  this.initialized = false;

  if (config) this.init(config);
};

/**
 * Initializes this client.
 *
 * @param  {Object} config
 *   @param  {String} client_id     - Plaid.io "client_id"
 *   @param  {String} secret        - Plaid.io "secret"
 *
 */
Client.prototype.init = function (config) {

  if (config.secret.length<0 ||  config.client_id.length<0)
      throw new Error('plaid-node client must be initialized with a '+
                    'non-empty API "secret" and "client_id" parameter.');

  if (typeof(config.secret)!='string' ||  typeof(config.client_id)!='string')
      throw new Error('plaid-node client must be initialized with a '+
                    'non-empty API "secret" and "client_id" parameter.');

  this.secret      = config.secret;
  this.client_id   = config.client_id;
  this.config     = _.defaults(config || {}, defaults);

  this.initialized = true;
};

/**
 * Internal method to check whether the client has been initialized.
 * @private
 */
Client.prototype._checkInitialized = function () {
  if (!this.initialized)
    throw new Error('analytics-node client is not initialized. Please call ' +
                    'client.init(config).');
};

/**
 * Connect a card to the Plaid API
 *
 *
 * @param  {Object} credentials     - The credentials for that card
 *   @param  {String}   username    - id for logged in user
 *   @param  {Password} password    - key/value object of tags for the user (optional)
     ...
 *
 * @param  {Object}  options   - app provided context about the user (optional)
 *
 * @callback {Error, Object, Object}
 *
 */
Client.prototype.connect = function (credentials, type, email, options, callback) {

  this._checkInitialized();

  if (!credentials || typeof(credentials)!= 'object') {
      throw new Error('[plaid]#connect: credentials must be an object');
  }

  if(!callback && (typeof options ==='function')) {
    callback = options;
    options  = {};
  }

  if(!type || typeof(type)!='string'){
    throw new Error('[plaid]#connect: Type missing or invalid');
  }

  if(!email || typeof(email)!='string'){
    throw new Error('[plaid]#connect: Email missing or invalid');
  }

  if(!callback){
    callback = function(){};
  }

  this.options     = options;
  this.credentials = credentials;
  this.type        = type;
  this.email       = email;

  return this._exec('submit', callback);
};

Client.prototype.step = function (access_token, mfa, options, callback) {

  this._checkInitialized();

  if(!callback && typeof(options)=='function'){
    callback = options;
    options  = {};
  }

  if(!callback){
    callback = function(){};
  }

  this.options      = options;
  this.access_token = access_token;
  this.mfa          = mfa;

  return this._exec('step', callback);
};

Client.prototype.get = function(access_token, options, callback) {
  this._checkInitialized();

  if(!callback && typeof(options) == 'function') {
    callback = options;
    options = {};
  }

  this.options = options;

  this.access_token = access_token;

  return this._exec('get', callback);
}

Client.prototype.remove = function(access_token, options, callback) {
  this._checkInitialized();

  if(!callback && typeof(options) == 'function') {
    callback = options;
    options = {};
  }

  this.options = options;

  this.access_token = access_token;

  return this._exec('remove', callback);
}

Client.prototype._exec = function (method, callback){

  var uri = this.config.protocol + this.config.host + this.config.endpoint[method].route;

  var query = {
      client_id   : this.client_id
    , secret      : this.secret
    , credentials : JSON.stringify(this.credentials)
    , type        : this.type
    , email       : this.email
    , access_token: this.access_token
    , options     : JSON.stringify(this.options)
    , mfa         : this.mfa
  }

  // the login option has to be set a separate parameter
  if (this.options.login) {
    query.login = this.options.login;
  }

  uri += "?"+qs.stringify(query);

  var self = this;

  request(
    { method: this.config.endpoint[method].method
    , uri: uri
    //, qs : qs.stringify(query)
    }
  , function (error, response, body) {
      if(!response) response = {};
      if(error || ( response.statusCode > 299 ) )
        return self._handleError(error, response.statusCode, body, callback);

      self.body = body;
      return self._handleSuccess(callback);

    }
  )
}

Client.prototype._handleSuccess = function(callback){
  try{
    this.body = JSON.parse(this.body);
  }catch(err){
    return callback("Couldn't parse body");
  }

  if(this.body.status === 'MFA')
    return this._handleMFA(callback);

  if(!this.body.success && (typeof this.body.mfa === 'undefined'))
    return callback(this.body.error);

  return callback(null, this.body, (this.body.mfa !== 'undefined'));
}

Client.prototype._handleError = function(error, status, body, callback){
  if(error)
    return callback(error)

  try{
    body = JSON.parse(body);
  }catch(err){
    return callback("Couldn't parse body");
  }

  return callback(body.error || "Unknown error occured", body);
}

Client.prototype._handleMFA = function(callback){

  this.config.endpoint  = '/connect/submit/step';
  this.access_token     = this.access_token   || this.body.accessToken;
  this.options.itemID   = this.options.itemID || this.body.message.itemID;

  var self = this;
  //helper
  var step = function(credentials, callback){
    if(self.options.mfaCL)
      return self._mfaCL(credentials, callback);
    return self.connect(credentials, self.type, self.email, self.options, callback);
  }
  var html = function(){
    return self._formToHTML(self.body.message.form);
  }

  this.body.message.step = step;
  if(this.body.message.form)
    this.body.message.form.html = html;
  else
    console.log(this.body.message);

  return callback(null, this.body, true)
}

/* MFA testing CL */

Client.prototype._mfaCL = function(credentials, callback){
  var readline = require('readline');
  var credentials = {};

  //Making sure there is a valid form object
  if(this.body.message.form)
    var holder = this.body.message.form;
  else{
    return console.log("Unknown message");
  }

  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  //The function that is called for every question
  var read = function(question, cbk){
    var display = question.display + ": ";
    rl.question(display, function(answer) {
      credentials[display]=answer;
      return cbk();
    });
  }

  var self = this;
  async.forEachSeries(holder, read, function(err, result){

    //Closing the readline interface
    rl.close();
    self.credentials = credentials;

    return self.connect(self.credentials, self.type, self.email, self.options, callback);
  });
}

Client.prototype._formToHTML = function(raw){
  var form = {};

  for(i in raw){
    if(raw[i].type=='text')
      form[raw[i].display]=fields.string();
  }

  var form = forms.create(form).toHTML();

  return '<form>'+form+'</form>';

}
<|endoftext|>