<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  /////////////////////////////////////////////////////////////////////////////
  // OptionsPage class:

  /**
   * Base class for options page.
   * @constructor
   * @param {string} name Options page name, also defines id of the div element
   *     containing the options view and the name of options page navigation bar
   *     item as name+'PageNav'.
   * @param {string} title Options page title, used for navigation bar
   * @extends {EventTarget}
   */
  function OptionsPage(name, title, pageDivName) {
    this.name = name;
    this.title = title;
    this.pageDivName = pageDivName;
    this.pageDiv = $(this.pageDivName);
    this.tab = null;
    this.managed = false;
  }

  /**
   * Main level option pages.
   * @protected
   */
  OptionsPage.registeredPages = {};

  /**
   * Pages which are nested under a main level page.
   * @protected
   */
  OptionsPage.registeredSubPages = {};

  /**
   * Pages which are meant to behave like modal dialogs.
   * @protected
   */
  OptionsPage.registeredOverlayPages = {};

  /**
   * Whether or not |initialize| has been called.
   * @private
   */
  OptionsPage.initialized_ = false;

  /**
   * Shows a registered page. This handles both top-level pages and sub-pages.
   * @param {string} pageName Page name.
   */
  OptionsPage.showPageByName = function(pageName) {
    // Notify main pages if they will be hidden.
    for (var name in this.registeredPages) {
      var page = this.registeredPages[name];
      if (name != pageName && page.willHidePage)
        page.willHidePage();
    }

    // Update the visibility attribute for main pages.
    for (var name in this.registeredPages) {
      var page = this.registeredPages[name];
      page.visible = name == pageName;
    }

    // Update the visibility attribute for sub-pages.
    for (var name in this.registeredSubPages) {
      var pageInfo = this.registeredSubPages[name];
      var match = name == pageName;
      if (match)
        pageInfo.parentPage.visible = true;
      pageInfo.page.visible = match;
    }

    // Notify main pages if they were shown.
    for (var name in this.registeredPages) {
      var page = this.registeredPages[name];
      if (name == pageName && page.didShowPage)
        page.didShowPage();
    }
  };

  /**
   * Called on load. Dispatch the URL hash to the given page's handleHash
   * function.
   * @param {string} pageName The string name of the (registered) options page.
   * @param {string} hash The value of the hash component of the URL.
   */
  OptionsPage.handleHashForPage = function(pageName, hash) {
    var page = this.registeredPages[pageName];
    if (!page) {
      page = this.registeredSubPages[pageName].page;
    }
    page.handleHash(hash);
  };

  /**
   * Shows a registered Overlay page.
   * @param {string} overlayName Page name.
   */
  OptionsPage.showOverlay = function(overlayName) {
    if (this.registeredOverlayPages[overlayName]) {
      this.registeredOverlayPages[overlayName].visible = true;
    }
  };

  /**
   * Clears overlays (i.e. hide all overlays).
   */
  OptionsPage.clearOverlays = function() {
     for (var name in this.registeredOverlayPages) {
       var page = this.registeredOverlayPages[name];
       page.visible = false;
     }
  };

  /**
   * Handle 'keydown' events.
   * @param {Event} e Key event.
   * @private
   */
  OptionsPage.onKeyDown_ = function(e) {
    if (e.keyCode == 27) { // Esc
      this.clearOverlays();
    }
  };

  /**
   * Closes any currently-open subpage.
   */
  OptionsPage.closeSubPage = function() {
    for (var name in this.registeredSubPages) {
      var pageInfo = this.registeredSubPages[name];
      if (pageInfo.page.visible) {
        pageInfo.page.visible = false;
        // Since the managed pref banner lives outside the overlay, and the
        // parent is not changing visibility, update the banner explicitly.
        pageInfo.parentPage.updateManagedBannerVisibility();
      }
    }
  };

  /**
  * Shows the tab contents for the given navigation tab.
  * @param {!Element} tab The tab that the user clicked.
  */
  OptionsPage.showTab = function(tab) {
    // Search parents until we find a tab, or the nav bar itself. This allows
    // tabs to have child nodes, e.g. labels in separately-styled spans.
    while (tab && !tab.classList.contains('subpages-nav-tabs') &&
           !tab.classList.contains('inactive-tab')) {
      tab = tab.parentNode;
    }
    if (!tab || !tab.classList.contains('inactive-tab'))
      return;

    if (this.activeNavTab != null) {
      this.activeNavTab.classList.remove('active-tab');
      $(this.activeNavTab.getAttribute('tab-contents')).classList.
          remove('active-tab-contents');
    }

    tab.classList.add('active-tab');
    $(tab.getAttribute('tab-contents')).classList.add('active-tab-contents');
    this.activeNavTab = tab;
  };

  /**
   * Registers new options page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.register = function(page) {
    this.registeredPages[page.name] = page;
    // Create and add new page <li> element to navbar.
    var pageNav = document.createElement('li');
    pageNav.id = page.name + 'PageNav';
    pageNav.className = 'navbar-item';
    pageNav.setAttribute('pageName', page.name);
    pageNav.textContent = page.title;
    pageNav.tabIndex = 0;
    pageNav.onclick = function(event) {
      OptionsPage.showPageByName(this.getAttribute('pageName'));
    };
    pageNav.onkeypress = function(event) {
      // Enter or space
      if (event.keyCode == 13 || event.keyCode == 32) {
        OptionsPage.showPageByName(this.getAttribute('pageName'));
      }
    };
    var navbar = $('navbar');
    navbar.appendChild(pageNav);
    page.tab = pageNav;
    page.initializePage();
  };

  /**
   * Registers a new Sub tab page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.registerSubPage = function(subPage, parentPage) {
    this.registeredSubPages[subPage.name] = {
        page: subPage, parentPage: parentPage };
    subPage.tab = undefined;
    subPage.isSubPageSheet = true;
    subPage.initializePage();
  };

  /**
   * Registers a new Overlay page.
   * @param {OptionsPage} page Page to register, must be a class derived from
   * OptionsPage.
   */
  OptionsPage.registerOverlay = function(page) {
    this.registeredOverlayPages[page.name] = page;
    page.tab = undefined;
    page.isOverlay = true;
    page.initializePage();
  };

  /**
   * Callback for window.onpopstate.
   * @param {Object} data State data pushed into history.
   */
  OptionsPage.setState = function(data) {
    if (data && data.pageName) {
      this.showPageByName(data.pageName);
    }
  };

  /**
   * Initializes the complete options page.  This will cause
   * all C++ handlers to be invoked to do final setup.
   */
  OptionsPage.initialize = function() {
    chrome.send('coreOptionsInitialize');
    this.initialized_ = true;

    // Set up the overlay sheet. Clicks on the visible part of the parent page
    // should close the overlay, not fall through to the parent page.
    $('subpage-sheet-container').onclick = function(event) {
      if (!$('subpage-sheet').contains(event.target))
        this.closeSubPage();
      event.stopPropagation();
    }
  };

  /**
   * Re-initializes the C++ handlers if necessary. This is called if the
   * handlers are torn down and recreated but the DOM may not have been (in
   * which case |initialize| won't be called again). If |initialize| hasn't been
   * called, this does nothing (since it will be later, once the DOM has
   * finished loading).
   */
  OptionsPage.reinitializeCore = function() {
    if (this.initialized_)
      chrome.send('coreOptionsInitialize');
  }

  OptionsPage.prototype = {
    __proto__: cr.EventTarget.prototype,

    /**
     * Initializes page content.
     */
    initializePage: function() {},

    /**
     * Sets managed banner visibility state.
     */
    setManagedBannerVisibility: function(visible) {
      this.managed = visible;
      if (this.visible) {
        this.updateManagedBannerVisibility();
      }
    },

    /**
     * Updates managed banner visibility state.
     */
    updateManagedBannerVisibility: function() {
      if (this.managed) {
        $('managed-prefs-banner').classList.remove('hidden');
      } else {
        $('managed-prefs-banner').classList.add('hidden');
      }
    },

    /**
     * Gets page visibility state.
     */
    get visible() {
      var page = $(this.pageDivName);
      return page && page.ownerDocument.defaultView.getComputedStyle(
          page).display == 'block';
    },

    /**
     * Sets page visibility.
     */
    set visible(visible) {
      if ((this.visible && visible) || (!this.visible && !visible))
        return;

      if (visible) {
        this.pageDiv.classList.remove('hidden');
        if (this.isOverlay) {
          $('overlay').classList.remove('hidden');
          document.addEventListener('keydown', OptionsPage.onKeyDown_);
        } else {
          if (this.isSubPageSheet)
            $('subpage-sheet-container').classList.remove('hidden');

          this.updateManagedBannerVisibility();

          // Recent webkit change no longer allows url change from "chrome://".
          window.history.pushState({pageName: this.name}, this.title);
        }
        if (this.tab) {
          this.tab.classList.add('navbar-item-selected');
        }
      } else {
        this.pageDiv.classList.add('hidden');
        if (this.isOverlay) {
          $('overlay').classList.add('hidden');
          document.removeEventListener('keydown', OptionsPage.onKeyDown_);
        } else if (this.isSubPageSheet) {
          $('subpage-sheet-container').classList.add('hidden');
        }
        if (this.tab) {
          this.tab.classList.remove('navbar-item-selected');
        }
      }

      cr.dispatchPropertyChange(this, 'visible', visible, !visible);
    },

    /**
     * Handles a hash value in the URL (such as bar in
     * chrome://options/foo#bar). Called on page load. By default, this shows
     * an overlay that matches the hash name, but can be overriden by individual
     * OptionsPage subclasses to get other behavior.
     * @param {string} hash The hash value.
     */
    handleHash: function(hash) {
      OptionsPage.showOverlay(hash);
    },
  };

  // Export
  return {
    OptionsPage: OptionsPage
  };

});
<commit_msg>DOMUI Prefs: Fix closing subpages by clicking to the left<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  /////////////////////////////////////////////////////////////////////////////
  // OptionsPage class:

  /**
   * Base class for options page.
   * @constructor
   * @param {string} name Options page name, also defines id of the div element
   *     containing the options view and the name of options page navigation bar
   *     item as name+'PageNav'.
   * @param {string} title Options page title, used for navigation bar
   * @extends {EventTarget}
   */
  function OptionsPage(name, title, pageDivName) {
    this.name = name;
    this.title = title;
    this.pageDivName = pageDivName;
    this.pageDiv = $(this.pageDivName);
    this.tab = null;
    this.managed = false;
  }

  /**
   * Main level option pages.
   * @protected
   */
  OptionsPage.registeredPages = {};

  /**
   * Pages which are nested under a main level page.
   * @protected
   */
  OptionsPage.registeredSubPages = {};

  /**
   * Pages which are meant to behave like modal dialogs.
   * @protected
   */
  OptionsPage.registeredOverlayPages = {};

  /**
   * Whether or not |initialize| has been called.
   * @private
   */
  OptionsPage.initialized_ = false;

  /**
   * Shows a registered page. This handles both top-level pages and sub-pages.
   * @param {string} pageName Page name.
   */
  OptionsPage.showPageByName = function(pageName) {
    // Notify main pages if they will be hidden.
    for (var name in this.registeredPages) {
      var page = this.registeredPages[name];
      if (name != pageName && page.willHidePage)
        page.willHidePage();
    }

    // Update the visibility attribute for main pages.
    for (var name in this.registeredPages) {
      var page = this.registeredPages[name];
      page.visible = name == pageName;
    }

    // Update the visibility attribute for sub-pages.
    for (var name in this.registeredSubPages) {
      var pageInfo = this.registeredSubPages[name];
      var match = name == pageName;
      if (match)
        pageInfo.parentPage.visible = true;
      pageInfo.page.visible = match;
    }

    // Notify main pages if they were shown.
    for (var name in this.registeredPages) {
      var page = this.registeredPages[name];
      if (name == pageName && page.didShowPage)
        page.didShowPage();
    }
  };

  /**
   * Called on load. Dispatch the URL hash to the given page's handleHash
   * function.
   * @param {string} pageName The string name of the (registered) options page.
   * @param {string} hash The value of the hash component of the URL.
   */
  OptionsPage.handleHashForPage = function(pageName, hash) {
    var page = this.registeredPages[pageName];
    if (!page) {
      page = this.registeredSubPages[pageName].page;
    }
    page.handleHash(hash);
  };

  /**
   * Shows a registered Overlay page.
   * @param {string} overlayName Page name.
   */
  OptionsPage.showOverlay = function(overlayName) {
    if (this.registeredOverlayPages[overlayName]) {
      this.registeredOverlayPages[overlayName].visible = true;
    }
  };

  /**
   * Clears overlays (i.e. hide all overlays).
   */
  OptionsPage.clearOverlays = function() {
     for (var name in this.registeredOverlayPages) {
       var page = this.registeredOverlayPages[name];
       page.visible = false;
     }
  };

  /**
   * Handle 'keydown' events.
   * @param {Event} e Key event.
   * @private
   */
  OptionsPage.onKeyDown_ = function(e) {
    if (e.keyCode == 27) { // Esc
      this.clearOverlays();
    }
  };

  /**
   * Closes any currently-open subpage.
   */
  OptionsPage.closeSubPage = function() {
    for (var name in this.registeredSubPages) {
      var pageInfo = this.registeredSubPages[name];
      if (pageInfo.page.visible) {
        pageInfo.page.visible = false;
        // Since the managed pref banner lives outside the overlay, and the
        // parent is not changing visibility, update the banner explicitly.
        pageInfo.parentPage.updateManagedBannerVisibility();
      }
    }
  };

  /**
  * Shows the tab contents for the given navigation tab.
  * @param {!Element} tab The tab that the user clicked.
  */
  OptionsPage.showTab = function(tab) {
    // Search parents until we find a tab, or the nav bar itself. This allows
    // tabs to have child nodes, e.g. labels in separately-styled spans.
    while (tab && !tab.classList.contains('subpages-nav-tabs') &&
           !tab.classList.contains('inactive-tab')) {
      tab = tab.parentNode;
    }
    if (!tab || !tab.classList.contains('inactive-tab'))
      return;

    if (this.activeNavTab != null) {
      this.activeNavTab.classList.remove('active-tab');
      $(this.activeNavTab.getAttribute('tab-contents')).classList.
          remove('active-tab-contents');
    }

    tab.classList.add('active-tab');
    $(tab.getAttribute('tab-contents')).classList.add('active-tab-contents');
    this.activeNavTab = tab;
  };

  /**
   * Registers new options page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.register = function(page) {
    this.registeredPages[page.name] = page;
    // Create and add new page <li> element to navbar.
    var pageNav = document.createElement('li');
    pageNav.id = page.name + 'PageNav';
    pageNav.className = 'navbar-item';
    pageNav.setAttribute('pageName', page.name);
    pageNav.textContent = page.title;
    pageNav.tabIndex = 0;
    pageNav.onclick = function(event) {
      OptionsPage.showPageByName(this.getAttribute('pageName'));
    };
    pageNav.onkeypress = function(event) {
      // Enter or space
      if (event.keyCode == 13 || event.keyCode == 32) {
        OptionsPage.showPageByName(this.getAttribute('pageName'));
      }
    };
    var navbar = $('navbar');
    navbar.appendChild(pageNav);
    page.tab = pageNav;
    page.initializePage();
  };

  /**
   * Registers a new Sub tab page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.registerSubPage = function(subPage, parentPage) {
    this.registeredSubPages[subPage.name] = {
        page: subPage, parentPage: parentPage };
    subPage.tab = undefined;
    subPage.isSubPageSheet = true;
    subPage.initializePage();
  };

  /**
   * Registers a new Overlay page.
   * @param {OptionsPage} page Page to register, must be a class derived from
   * OptionsPage.
   */
  OptionsPage.registerOverlay = function(page) {
    this.registeredOverlayPages[page.name] = page;
    page.tab = undefined;
    page.isOverlay = true;
    page.initializePage();
  };

  /**
   * Callback for window.onpopstate.
   * @param {Object} data State data pushed into history.
   */
  OptionsPage.setState = function(data) {
    if (data && data.pageName) {
      this.showPageByName(data.pageName);
    }
  };

  /**
   * Initializes the complete options page.  This will cause
   * all C++ handlers to be invoked to do final setup.
   */
  OptionsPage.initialize = function() {
    chrome.send('coreOptionsInitialize');
    this.initialized_ = true;

    // Set up the overlay sheet. Clicks on the visible part of the parent page
    // should close the overlay, not fall through to the parent page.
    var self = this;
    $('subpage-sheet-container').onclick = function(event) {
      if (!$('subpage-sheet').contains(event.target))
        self.closeSubPage();
      event.stopPropagation();
    }
  };

  /**
   * Re-initializes the C++ handlers if necessary. This is called if the
   * handlers are torn down and recreated but the DOM may not have been (in
   * which case |initialize| won't be called again). If |initialize| hasn't been
   * called, this does nothing (since it will be later, once the DOM has
   * finished loading).
   */
  OptionsPage.reinitializeCore = function() {
    if (this.initialized_)
      chrome.send('coreOptionsInitialize');
  }

  OptionsPage.prototype = {
    __proto__: cr.EventTarget.prototype,

    /**
     * Initializes page content.
     */
    initializePage: function() {},

    /**
     * Sets managed banner visibility state.
     */
    setManagedBannerVisibility: function(visible) {
      this.managed = visible;
      if (this.visible) {
        this.updateManagedBannerVisibility();
      }
    },

    /**
     * Updates managed banner visibility state.
     */
    updateManagedBannerVisibility: function() {
      if (this.managed) {
        $('managed-prefs-banner').classList.remove('hidden');
      } else {
        $('managed-prefs-banner').classList.add('hidden');
      }
    },

    /**
     * Gets page visibility state.
     */
    get visible() {
      var page = $(this.pageDivName);
      return page && page.ownerDocument.defaultView.getComputedStyle(
          page).display == 'block';
    },

    /**
     * Sets page visibility.
     */
    set visible(visible) {
      if ((this.visible && visible) || (!this.visible && !visible))
        return;

      if (visible) {
        this.pageDiv.classList.remove('hidden');
        if (this.isOverlay) {
          $('overlay').classList.remove('hidden');
          document.addEventListener('keydown', OptionsPage.onKeyDown_);
        } else {
          if (this.isSubPageSheet)
            $('subpage-sheet-container').classList.remove('hidden');

          this.updateManagedBannerVisibility();

          // Recent webkit change no longer allows url change from "chrome://".
          window.history.pushState({pageName: this.name}, this.title);
        }
        if (this.tab) {
          this.tab.classList.add('navbar-item-selected');
        }
      } else {
        this.pageDiv.classList.add('hidden');
        if (this.isOverlay) {
          $('overlay').classList.add('hidden');
          document.removeEventListener('keydown', OptionsPage.onKeyDown_);
        } else if (this.isSubPageSheet) {
          $('subpage-sheet-container').classList.add('hidden');
        }
        if (this.tab) {
          this.tab.classList.remove('navbar-item-selected');
        }
      }

      cr.dispatchPropertyChange(this, 'visible', visible, !visible);
    },

    /**
     * Handles a hash value in the URL (such as bar in
     * chrome://options/foo#bar). Called on page load. By default, this shows
     * an overlay that matches the hash name, but can be overriden by individual
     * OptionsPage subclasses to get other behavior.
     * @param {string} hash The hash value.
     */
    handleHash: function(hash) {
      OptionsPage.showOverlay(hash);
    },
  };

  // Export
  return {
    OptionsPage: OptionsPage
  };

});
<|endoftext|>


<commit_before>var should = require('should'),
    stream = require('stream'),
    CLI    = require('../lib/CLI.js');

//not exactly cool tests.. but still..
describe('CLI Tool', function () {
  var optimist = {}, argv = {},
    _log, _error, CLI_error;

  _log = console.log;
  _error = console.error;
  CLI_error = CLI.prototype.error;

  beforeEach(function () {
    optimist = {};
    argv = {};
  });

  afterEach(function () {
    console.log = _log;
    console.error = _error;
    CLI.prototype.error = CLI_error;
  });

  it('should call showHelp if -h is passed', function (done) {
    argv = { h : true, help : true };
    optimist.showHelp = done;

    new CLI(argv, optimist);
  });

  it('should use stdin and stdout for input/output if files are not provided', function () {
    var cli = new CLI(argv, optimist);

    should(cli).have.property('in',  process.stdin);
    should(cli).have.property('out', process.stdout);
  });

  it('should call list if -l is passed', function (done) {
    var _list = CLI.prototype.list, cli;

    argv = { list : true };

    CLI.prototype.list = function () {
      done();
    };

    cli = new CLI(argv, optimist);

    CLI.prototype.list = _list;
  });

  it('should return appropriate message if -l passed', function (done) {
    var cli = new CLI(argv, optimist);

    console.log = function (str) {
      console.log = _log;
      str.match('xist of languages:').should.be.an.instanceOf(Array);
    };

    cli.list().then(function () {
      done();
    })
    .fail(function (error) {
      done(error);
    });
  });

  it('should return error if file not found', function (done) {
    argv = { file : 'filethat!@#$%\n^CantExist' };

    CLI.prototype.error = function (error) {
      var notFoundExp = /not found/

      notFoundExp.test(error).should.equal(true);
      done();
    };

    var cli = new CLI(argv, optimist);
  });

  it('should return error if output file exists', function (done) {
    argv = { output : 'test/file' };

    CLI.prototype.error = function (error) {
      var fileExistsExp = /already exists/

      fileExistsExp.test(error).should.equal(true);
      done();
    };

    var cli = new CLI(argv, optimist);
  });

  it('should have in parameter as ReadableStream', function () {
    argv = { file : 'test/file', depth : 0 };

    var cli = new CLI(argv, optimist);
    should(cli).have.property('in').and.be.an.instanceOf(stream.Readable);
  });

  it('should fail if output file can\'t be created', function (done) {
    CLI.prototype.error = function (error) {
      error.match('Could not write to file').should.be.an.instanceOf(Array);
      done();
    };

    argv = { output : 'nosuchDir/file' };
    new CLI(argv, optimist);
  });

  it('should exit process if error occurs', function (done) {
    var _exit = process.exit,
      errStr = 'error',
      errCode = 1;

    console.error = function () {};
    process.exit  = function (ecode) {
      if (errCode === ecode) {
        done();
      }
    };

    var cli = new CLI(argv, optimist);
    cli.error(errStr, errCode);

    process.exit = _exit;
  });
});
<commit_msg>Fix -l test<commit_after>var should = require('should'),
    stream = require('stream'),
    CLI    = require('../lib/CLI.js');

//not exactly cool tests.. but still..
describe('CLI Tool', function () {
  var optimist = {}, argv = {},
    _log, _error, CLI_error;

  _log = console.log;
  _error = console.error;
  CLI_error = CLI.prototype.error;

  beforeEach(function () {
    optimist = {};
    argv = {};
  });

  afterEach(function () {
    console.log = _log;
    console.error = _error;
    CLI.prototype.error = CLI_error;
  });

  it('should call showHelp if -h is passed', function (done) {
    argv = { h : true, help : true };
    optimist.showHelp = done;

    new CLI(argv, optimist);
  });

  it('should use stdin and stdout for input/output if files are not provided', function () {
    var cli = new CLI(argv, optimist);

    should(cli).have.property('in',  process.stdin);
    should(cli).have.property('out', process.stdout);
  });

  it('should call list if -l is passed', function (done) {
    var _list = CLI.prototype.list, cli;

    argv = { list : true };

    CLI.prototype.list = function () {
      done();
    };

    cli = new CLI(argv, optimist);

    CLI.prototype.list = _list;
  });

  it('should return appropriate message if -l passed', function (done) {
    var cli = new CLI(argv, optimist);

    console.log = function (str) {
      console.log = _log;
      str.match('List of languages:').should.be.an.instanceOf(Array);
    };

    cli.list().then(function () {
      done();
    })
    .fail(function (error) {
      done(error);
    });
  });

  it('should return error if file not found', function (done) {
    argv = { file : 'filethat!@#$%\n^CantExist' };

    CLI.prototype.error = function (error) {
      var notFoundExp = /not found/

      notFoundExp.test(error).should.equal(true);
      done();
    };

    var cli = new CLI(argv, optimist);
  });

  it('should return error if output file exists', function (done) {
    argv = { output : 'test/file' };

    CLI.prototype.error = function (error) {
      var fileExistsExp = /already exists/

      fileExistsExp.test(error).should.equal(true);
      done();
    };

    var cli = new CLI(argv, optimist);
  });

  it('should have in parameter as ReadableStream', function () {
    argv = { file : 'test/file', depth : 0 };

    var cli = new CLI(argv, optimist);
    should(cli).have.property('in').and.be.an.instanceOf(stream.Readable);
  });

  it('should fail if output file can\'t be created', function (done) {
    CLI.prototype.error = function (error) {
      error.match('Could not write to file').should.be.an.instanceOf(Array);
      done();
    };

    argv = { output : 'nosuchDir/file' };
    new CLI(argv, optimist);
  });

  it('should exit process if error occurs', function (done) {
    var _exit = process.exit,
      errStr = 'error',
      errCode = 1;

    console.error = function () {};
    process.exit  = function (ecode) {
      if (errCode === ecode) {
        done();
      }
    };

    var cli = new CLI(argv, optimist);
    cli.error(errStr, errCode);

    process.exit = _exit;
  });
});
<|endoftext|>


<commit_before>/*global require */
var api = require('../js/api');
var response = require('./fixtures/article/1.json');
var secondResponse = require('./fixtures/article/2.json');
var utils = require('./utils');
var should = require('should');
var _ = require('lodash');
var sinon = require('sinon');
var EnvConfig = require('../js/config');

describe("api utilities", function() {
  describe("_success", function() {
    var self;
    beforeEach(function() {
        self = new Object;
        self.resolve = sinon.spy();
        self.reject = sinon.spy();
        self.callback = sinon.spy();
    });
    it("statusText OK callback success", function(){
      self.success = api._success(self.resolve,
        self.reject, self.callback);
      self.success.should.be.a.Function;
    });
    it("statusText OK callback success", function(){
      self.success = api._success(self.resolve,
        self.reject, self.callback);
      self.success.should.be.a.Function;
      var result = { statusText: "OK" };
      self.success('', result, '');
      self.callback.should.have.property('called', true);
      self.resolve.should.have.property('called', true);
      self.reject.should.have.property('called', false);
    });
    it("statusText OK callback fail", function(){
      self.callback = sinon.spy(function() {
        throw new Error("test");
      });
      self.success = api._success(self.resolve,
        self.reject, self.callback);
      var result = { statusText: "OK" };
      self.success('', result, '');
      self.callback.should.have.property('called', true);
      self.reject.should.have.property('called', true);
      self.resolve.should.have.property('called', false);
    });
  });
  describe("_promise_request", function() {
    it("calls onRejected when request fails", function(done) {
      var url = EnvConfig.MIRRORS_URL + 'test/';
      var callback = sinon.spy();
      var success = sinon.spy();
      var fail = function() {
        callback.should.have.property('called', false);
        success.should.have.property('called', false);
        done();
      };
      api._promise_request({
        'url': url,
        'timeout': 1
        }, callback).then(success, fail);
    });
    before(function(done) {
      slug = 'test';
      server = utils.mock_component(slug, response);
      done();
    });
    after(function(done) {
      server.restore();
      done();
    });
    it("callback runs before promise succeeds", function(done) {
      var url = EnvConfig.MIRRORS_URL + 'component/' + slug + '/';
      var callback = sinon.spy();
      var fail = sinon.spy();
      var success = function() {
        callback.should.have.property('calledOnce', true);
        callback.calledWithExactly(response);
        fail.should.have.property('called', false);
        done();
      };
      api._promise_request(url, callback).then(success, fail);
    });
  });
});

describe("component api", function() {
  describe("constructor", function() {
    it("builds if data given to it", function(done) {
      var component = new api.Component('test', response);
      component.slug.should.eql(response.slug);
      component.metadata.should.have.keys(_.keys(response.metadata));
      done();
    });
    it("keeps object boundries", function(done) {
      var drones = new api.Component('drones', response);
      var iceStore = new api.Component('ice', secondResponse);
      drones.slug.should.not.eql(iceStore.slug);
      drones.attributes.should.not.eql(iceStore.attributes);
      drones.metadata.should.not.eql(iceStore.metadata);
      done();
    });
  });
  describe("get", function() {
    var server;
    var slug;
    before(function(done) {
      slug = 'test';
      server = utils.mock_component(slug, response);
      done();
    });
    after(function(done) {
      server.restore();
      done();
    });
    it("returns data from mirrors", function(done) {
      var callback = function(data) {
        should.exist(data);
        data.should.have.property('slug', slug);
      };
      var component = new api.Component(slug);
      component.get(callback).then(function() {
        should(component).have.property('metadata');
        should(component).have.property('attributes');
        should(component).have.property('data');
        done();
      });
    });
  });
});

describe("data api", function() {
  describe("get", function() {
    it("returns data from mirrors", function(done) {
      var slug = 'test';
      var server = utils.mock_component(slug, {}, {
        'content-type': 'text/x-markdown',
        'response': 'DATA'
      });
      var callback = function(data) {
        server.restore();
        should.exist(data);
        data.should.be.exactly('DATA');
      };
      var data_uri = '/mirrors/component/' + slug +'/data';
      var data = new api.Data(data_uri);
      data.get(callback).then(function() {
        done();
      });
    });
    it("should redirect to mirrors when unauthorized", function(done) {
      var slug = 'unauthorized_check';
      var server = utils.mock_unauthorized(slug);
      var component = new api.Component(slug);
        //overwrite function that changes document location
      var redirect = api.logInRedirect;
      api.logInRedirect = function() {
        true.should.be.ok;
        api.logInRedirect = redirect;
        server.restore();
        done();
      };
      component.get();
    });
  });
});
<commit_msg>more _succes tests<commit_after>/*global require */
var api = require('../js/api');
var response = require('./fixtures/article/1.json');
var secondResponse = require('./fixtures/article/2.json');
var utils = require('./utils');
var should = require('should');
var _ = require('lodash');
var sinon = require('sinon');
var EnvConfig = require('../js/config');

describe("api utilities", function() {
  describe("_success", function() {
    var self;
    beforeEach(function() {
      self = new Object;
      self.resolve = sinon.spy();
      self.reject = sinon.spy();
      self.callback = sinon.spy();
      self.success = api._success(self.resolve,
        self.reject, self.callback);
    });
    it("returns a function", function(){
      self.success.should.be.a.Function;
    });
    it("statusText OK callback success", function(){
      var result = { statusText: "OK" };
      self.success('', result, '');
      self.callback.should.have.property('called', true);
      self.resolve.should.have.property('called', true);
      self.reject.should.have.property('called', false);
    });
    it("statusText OK callback fail", function(){
      self.callback = sinon.spy(function() {
        throw new Error("test");
      });
      self.success = api._success(self.resolve,
        self.reject, self.callback);
      var result = { statusText: "OK" };
      self.success('', result, '');
      self.callback.should.have.property('called', true);
      self.reject.should.have.property('called', true);
      self.resolve.should.have.property('called', false);
    });
  });
  describe("_promise_request", function() {
    it("calls onRejected when request fails", function(done) {
      var url = EnvConfig.MIRRORS_URL + 'test/';
      var callback = sinon.spy();
      var success = sinon.spy();
      var fail = function() {
        callback.should.have.property('called', false);
        success.should.have.property('called', false);
        done();
      };
      api._promise_request({
        'url': url,
        'timeout': 1
        }, callback).then(success, fail);
    });
    before(function(done) {
      slug = 'test';
      server = utils.mock_component(slug, response);
      done();
    });
    after(function(done) {
      server.restore();
      done();
    });
    it("callback runs before promise succeeds", function(done) {
      var url = EnvConfig.MIRRORS_URL + 'component/' + slug + '/';
      var callback = sinon.spy();
      var fail = sinon.spy();
      var success = function() {
        callback.should.have.property('calledOnce', true);
        callback.calledWithExactly(response);
        fail.should.have.property('called', false);
        done();
      };
      api._promise_request(url, callback).then(success, fail);
    });
  });
});

describe("component api", function() {
  describe("constructor", function() {
    it("builds if data given to it", function(done) {
      var component = new api.Component('test', response);
      component.slug.should.eql(response.slug);
      component.metadata.should.have.keys(_.keys(response.metadata));
      done();
    });
    it("keeps object boundries", function(done) {
      var drones = new api.Component('drones', response);
      var iceStore = new api.Component('ice', secondResponse);
      drones.slug.should.not.eql(iceStore.slug);
      drones.attributes.should.not.eql(iceStore.attributes);
      drones.metadata.should.not.eql(iceStore.metadata);
      done();
    });
  });
  describe("get", function() {
    var server;
    var slug;
    before(function(done) {
      slug = 'test';
      server = utils.mock_component(slug, response);
      done();
    });
    after(function(done) {
      server.restore();
      done();
    });
    it("returns data from mirrors", function(done) {
      var callback = function(data) {
        should.exist(data);
        data.should.have.property('slug', slug);
      };
      var component = new api.Component(slug);
      component.get(callback).then(function() {
        should(component).have.property('metadata');
        should(component).have.property('attributes');
        should(component).have.property('data');
        done();
      });
    });
  });
});

describe("data api", function() {
  describe("get", function() {
    it("returns data from mirrors", function(done) {
      var slug = 'test';
      var server = utils.mock_component(slug, {}, {
        'content-type': 'text/x-markdown',
        'response': 'DATA'
      });
      var callback = function(data) {
        server.restore();
        should.exist(data);
        data.should.be.exactly('DATA');
      };
      var data_uri = '/mirrors/component/' + slug +'/data';
      var data = new api.Data(data_uri);
      data.get(callback).then(function() {
        done();
      });
    });
    it("should redirect to mirrors when unauthorized", function(done) {
      var slug = 'unauthorized_check';
      var server = utils.mock_unauthorized(slug);
      var component = new api.Component(slug);
        //overwrite function that changes document location
      var redirect = api.logInRedirect;
      api.logInRedirect = function() {
        true.should.be.ok;
        api.logInRedirect = redirect;
        server.restore();
        done();
      };
      component.get();
    });
  });
});
<|endoftext|>


<commit_before>// router tests...

var expect = require('expect.js');

process.env.THREESCALE_PROVIDER_KEY='dummykey';
var apiRouter = require('../routes/api.js');

describe('API router tests', function() {
  it('router should be valid', function(){
      expect(apiRouter).to.be.ok();
			expect(apiRouter.get).to.be.an('function');
  });

  it('dummy - check some syntax of expect.js', function(done) {
    var f = function(){};
    expect(f).to.be.an('function');
    expect(f.doesnotexist).to.not.be.an('function'); // should fail
    expect(f.bind).to.be.an('function'); // Function.prototype.bind()
		done();
  })

});

<commit_msg>added simple middleware test<commit_after>// router tests...

var expect = require('expect.js');

process.env.THREESCALE_PROVIDER_KEY='dummykey';
var apiRouter = require('../routes/api');
var ts = require('../util/threescale');

describe('API router tests', function() {
  it('router should be valid', function(done){
      expect(apiRouter).to.be.ok();
			expect(apiRouter.get).to.be.an('function');
			done();
  });

  it('threescale middleware tests', function(done) {
    expect(ts).to.be.an('function');
		done();
  })

});

<|endoftext|>


<commit_before>const Vec3 = require('vec3').Vec3

module.exports.player = function (player, serv) {
  player.changeBlock = async (position, blockType, blockData) => {
    serv.players
      .filter(p => p.world === player.world && player !== p)
      .forEach(p => p.sendBlock(position, blockType, blockData))

    await player.world.setBlockType(position, blockType)
    await player.world.setBlockData(position, blockData)
  }

  player.sendBlock = (position, blockType, blockData) => // Call from player.setBlock unless you want "local" fake blocks
    player.behavior('sendBlock', {
      position: position,
      blockType: blockType,
      blockData: blockData
    }, ({ position, blockType, blockData }) => {
      player._client.write('block_change', {
        location: position,
        type: blockType << 4 | blockData
      })
    })

  player.setBlock = (position, blockType, blockData) => serv.setBlock(player.world, position, blockType, blockData)

  player.sendBlockAction = (position, actionId, actionParam, blockType) => {
    if (!blockType) {
      const location = new Vec3(position.x, position.y, position.z)
      blockType = player.world.getBlockType(location)
    }

    player.behavior('sendBlockAction', {
      position: position,
      blockType: blockType,
      actionId: actionId,
      actionParam: actionParam
    }, ({ position, blockType, actionId, actionParam }) => {
      player._client.write('block_action', {
        location: position,
        actionId: actionId,
        actionParam: actionParam,
        blockId: blockType
      })
    })
  }

  player.setBlockAction = (position, byte1, byte2) => serv.setBlockAction(player.world, position, byte1, byte2)

  player.commands.add({
    base: 'setblock',
    info: 'set a block at a position',
    usage: '/setblock <x> <y> <z> <id> [data]',
    op: true,
    parse (str) {
      const results = str.match(/^(~|~?-?[0-9]+) (~|~?-?[0-9]+) (~|~?-?[0-9]+) ([0-9]{1,3})(?: ([0-9]{1,3}))?/)
      if (!results) return false
      return results
    },
    action (params) {
      let res = params.slice(1, 4)
      res = res.map((val, i) => serv.posFromString(val, player.position[['x', 'y', 'z'][i]]))
      player.setBlock(new Vec3(res[0], res[1], res[2]).floored(), params[4], params[5] || 0)
    }
  })
}
<commit_msg>Fix player.setBlockAction arguments inconsistency<commit_after>const Vec3 = require('vec3').Vec3

module.exports.player = function (player, serv) {
  player.changeBlock = async (position, blockType, blockData) => {
    serv.players
      .filter(p => p.world === player.world && player !== p)
      .forEach(p => p.sendBlock(position, blockType, blockData))

    await player.world.setBlockType(position, blockType)
    await player.world.setBlockData(position, blockData)
  }

  player.sendBlock = (position, blockType, blockData) => // Call from player.setBlock unless you want "local" fake blocks
    player.behavior('sendBlock', {
      position: position,
      blockType: blockType,
      blockData: blockData
    }, ({ position, blockType, blockData }) => {
      player._client.write('block_change', {
        location: position,
        type: blockType << 4 | blockData
      })
    })

  player.setBlock = (position, blockType, blockData) => serv.setBlock(player.world, position, blockType, blockData)

  player.sendBlockAction = (position, actionId, actionParam, blockType) => {
    if (!blockType) {
      const location = new Vec3(position.x, position.y, position.z)
      blockType = player.world.getBlockType(location)
    }

    player.behavior('sendBlockAction', {
      position: position,
      blockType: blockType,
      actionId: actionId,
      actionParam: actionParam
    }, ({ position, blockType, actionId, actionParam }) => {
      player._client.write('block_action', {
        location: position,
        actionId: actionId,
        actionParam: actionParam,
        blockId: blockType
      })
    })
  }

  player.setBlockAction = (position, actionId, actionParam) => serv.setBlockAction(player.world, position, actionId, actionParam)

  player.commands.add({
    base: 'setblock',
    info: 'set a block at a position',
    usage: '/setblock <x> <y> <z> <id> [data]',
    op: true,
    parse (str) {
      const results = str.match(/^(~|~?-?[0-9]+) (~|~?-?[0-9]+) (~|~?-?[0-9]+) ([0-9]{1,3})(?: ([0-9]{1,3}))?/)
      if (!results) return false
      return results
    },
    action (params) {
      let res = params.slice(1, 4)
      res = res.map((val, i) => serv.posFromString(val, player.position[['x', 'y', 'z'][i]]))
      player.setBlock(new Vec3(res[0], res[1], res[2]).floored(), params[4], params[5] || 0)
    }
  })
}
<|endoftext|>


<commit_before>//
//  test/api.js
//
//  Created by Walt Zimmerman on 8/28/16.
//

"use strict";
const expect = require('chai').expect;
const supertest = require('supertest');
// Model
const User = require("../models/users");
// Pass Data
const TEST_USER_DATA_PASS = { "phone_number" : "1231234567" }
// App
const app = require('../app');
// Api
const api = supertest(app);

let TEST_USER;

let verification_code;

let auth_token;

describe(`Test to ensure the API is returning correct status codes and data`, () => {
	// Setup
	before(() => {
		TEST_USER = new User(TEST_USER_DATA_PASS);
		return TEST_USER.save().then(() => { return TEST_USER.genVerificationCode() })
	});

	it(`GET /users/:phone_number should return 401 with no authorization token`, (done) => {
		api.get('/users/1231234567')
			.expect(401, done);
	});

	it(`GET /users/:phone_number should return 200 with authorization`, (done) => {
		// Get users auth and setup for verification_code test
		TEST_USER.findBy('phone_number', "1231234567")
			.then((u) => {
				// Setup for next test
				verification_code = u.verification_code;
				auth_token = u.auth_token;
				api.get('/users/1231234567')
					.set("authorization", auth_token)
					.expect(200, done);
			})
			.catch((err) => {
				// should not reach this block
				expect(err).to.be.undefined;
				done();
			});
	});

	it(`POST /users/:phone_number/verify should return 200`, (done) => {
		api.post('/users/1231234567/verify')
			.send({ verification_code })
			.expect(200, done);
	});

	it(`POST /users/:phone_number/verify should return authorization token`, (done) => {
		api.post('/users/1231234567/verify')
			.send({ verification_code })
			.expect((res) => {
				expect(res.body).to.have.property("authorization");
				expect(res.body.authorization).to.not.be.null;
				expect(res.body.authorization).to.be.a("string");
			})
			.expect(200, done);
	})

	it(`POST /users/:phone_number/verify should return 401 with invalid verification_code`, (done) => {
		api.post('/users/1231234567/verify')
			.send({ verification_code: "NOT VALID CODE" })
			.expect(401, done);
	});

	it(`PUT /users/:phone_number should return 401 with no authorization token`, (done) => {
		api.put('/users/1231234567')
			.expect(401, done);
	});

	it(`PUT /users/:phone_number should return 202 with valid authorization token`, (done) => {
		api.put('/users/1231234567')
			.set("authorization", auth_token)
			.send({ first_name: 'SomeUpdatedUser' }) // Sending update next test we will test if the value got updated
			.expect(202, done);
	});

	it(`PUT /users/:phone_number should update user`, (done) => {
			// Grab updated user
			api
				.get('/users/1231234567')
				.set("authorization", auth_token)
				.expect((res) => {
					expect(TEST_USER.first_name).to.not.equal(res.body.first_name);
					expect(res.body.first_name).to.equal('SomeUpdatedUser');
				})
				.expect(200, done);
	});

	after(() => {
		TEST_USER.destroy();
	})
});<commit_msg>update test description<commit_after>//
//  test/api.js
//
//  Created by Walt Zimmerman on 8/28/16.
//

"use strict";
const expect = require('chai').expect;
const supertest = require('supertest');
// Model
const User = require("../models/users");
// Pass Data
const TEST_USER_DATA_PASS = { "phone_number" : "1231234567" }
// App
const app = require('../app');
// Api
const api = supertest(app);

let TEST_USER;

let verification_code;

let auth_token;

describe(`Integration Tests`, () => {
	// Setup
	before(() => {
		TEST_USER = new User(TEST_USER_DATA_PASS);
		return TEST_USER.save().then(() => { return TEST_USER.genVerificationCode() })
	});

	it(`GET /users/:phone_number should return 401 with no authorization token`, (done) => {
		api.get('/users/1231234567')
			.expect(401, done);
	});

	it(`GET /users/:phone_number should return 200 with authorization`, (done) => {
		// Get users auth and setup for verification_code test
		TEST_USER.findBy('phone_number', "1231234567")
			.then((u) => {
				// Setup for next test
				verification_code = u.verification_code;
				auth_token = u.auth_token;
				api.get('/users/1231234567')
					.set("authorization", auth_token)
					.expect(200, done);
			})
			.catch((err) => {
				// should not reach this block
				expect(err).to.be.undefined;
				done();
			});
	});

	it(`POST /users/:phone_number/verify should return 200`, (done) => {
		api.post('/users/1231234567/verify')
			.send({ verification_code })
			.expect(200, done);
	});

	it(`POST /users/:phone_number/verify should return authorization token`, (done) => {
		api.post('/users/1231234567/verify')
			.send({ verification_code })
			.expect((res) => {
				expect(res.body).to.have.property("authorization");
				expect(res.body.authorization).to.not.be.null;
				expect(res.body.authorization).to.be.a("string");
			})
			.expect(200, done);
	})

	it(`POST /users/:phone_number/verify should return 401 with invalid verification_code`, (done) => {
		api.post('/users/1231234567/verify')
			.send({ verification_code: "NOT VALID CODE" })
			.expect(401, done);
	});

	it(`PUT /users/:phone_number should return 401 with no authorization token`, (done) => {
		api.put('/users/1231234567')
			.expect(401, done);
	});

	it(`PUT /users/:phone_number should return 202 with valid authorization token`, (done) => {
		api.put('/users/1231234567')
			.set("authorization", auth_token)
			.send({ first_name: 'SomeUpdatedUser' }) // Sending update next test we will test if the value got updated
			.expect(202, done);
	});

	it(`PUT /users/:phone_number should update user`, (done) => {
			// Grab updated user
			api
				.get('/users/1231234567')
				.set("authorization", auth_token)
				.expect((res) => {
					expect(TEST_USER.first_name).to.not.equal(res.body.first_name);
					expect(res.body.first_name).to.equal('SomeUpdatedUser');
				})
				.expect(200, done);
	});

	after(() => {
		TEST_USER.destroy();
	})
});<|endoftext|>


<commit_before>/*eslint-disable react/no-danger*/
import React from "react";
import serialize from "serialize-javascript";
import process from "process";
import getAssetPath from "../getAssetPath";
import getAssetPathForFile from "../getAssetPathForFile";

const isProduction = process.env.NODE_ENV === "production";

// eslint-disable-next-line no-unused-vars
export default (config, entryPoint, headContent, assets) => {
  const tags = [];
  let key = 0;
  const assetPath = getAssetPath(config);

  if (isProduction) {
    tags.push(<link key={key++} rel="stylesheet" type="text/css" href={getAssetPathForFile(`${entryPoint}`, "styles")} />);
  }

  tags.push(
    <script key={key++} type="text/javascript" dangerouslySetInnerHTML={{__html: `window.__GS_PUBLIC_PATH__ = ${serialize(assetPath)}; window.__GS_ENVIRONMENT__ = ${serialize(process.env.NODE_ENV)}`}}></script>
  );

  const scriptPaths = {
    vendor: getAssetPathForFile("vendor", "javascript"),
    entryPoint: getAssetPathForFile(entryPoint, "javascript")
  };

  tags.push(headContent);

  tags.push(getScriptLoader(scriptPaths));

  return tags;
};

function getScriptLoader ({vendor, entryPoint}:Object) {
  // eslint-disable-next-line quotes
  const scriptLoader = `
    loadjs=function(){function n(n,e){n=n.push?n:[n];var t,r,o,c,i=[],s=n.length,h=s;for(t=function(n,t){t.length&&i.push(n),h--,h||e(i)};s--;)r=n[s],o=u[r],o?t(r,o):(c=f[r]=f[r]||[],c.push(t))}function e(n,e){if(n){var t=f[n];if(u[n]=e,t)for(;t.length;)t[0](n,e),t.splice(0,1)}}function t(n,e,t){var r,o,c=document;/\.css$/.test(n)?(r=!0,o=c.createElement("link"),o.rel="stylesheet",o.href=n):(o=c.createElement("script"),o.src=n,o.async=void 0===t||t),o.onload=o.onerror=o.onbeforeload=function(t){var c=t.type[0];if(r&&"hideFocus"in o)try{o.sheet.cssText.length||(c="e")}catch(n){c="e"}e(n,c,t.defaultPrevented)},c.head.appendChild(o)}function r(n,e,r){n=n.push?n:[n];var o,c,i=n.length,u=i,f=[];for(o=function(n,t,r){if("e"==t&&f.push(n),"b"==t){if(!r)return;f.push(n)}i--,i||e(f)},c=0;c<u;c++)t(n[c],o,r)}function o(n,t,o){var u,f;if(t&&t.trim&&(u=t),f=(u?o:t)||{},u){if(u in i)throw new Error("LoadJS");i[u]=!0}r(n,function(n){n.length?(f.error||c)(n):(f.success||c)(),e(u,n)},f.async)}var c=function(){},i={},u={},f={};return o.ready=function(e,t){return n(e,function(n){n.length?(t.error||c)(n):(t.success||c)()}),o},o.done=function(n){e(n,[])},o}();
    var maxRetries = 10;
    var vendorRetries = 0;
    var appRetries = 0;

    var loadEntryPoint = function() {
      loadjs("${entryPoint}", {
        error: function() {
          appRetries++;
          if (appRetries < maxRetries) {
            setTimeout(function() { loadEntryPoint();}, 100);
          }
          else {
            throw new Error("Failed to load ${entryPoint}");
          }
        }
      });
    };

    var loadVendorThenEntry = function() {
      loadjs("${vendor}", {
        success: loadEntryPoint,
        error: function() {
          vendorRetries++;
          if (vendorRetries < maxRetries) {
            setTimeout(function() { loadVendorThenEntry();}, 100);
          }
          else {
            throw new Error("Failed to load ${vendor}");
          }
        }
      });
    };

    document.addEventListener("DOMContentLoaded", function() {
      loadVendorThenEntry();
    });
  `;
  return <script key="script-loader" type="text/javascript" dangerouslySetInnerHTML={{__html: scriptLoader}} />;
}
<commit_msg>Bump loadjs to 3.2.0<commit_after>/*eslint-disable react/no-danger*/
import React from "react";
import serialize from "serialize-javascript";
import process from "process";
import getAssetPath from "../getAssetPath";
import getAssetPathForFile from "../getAssetPathForFile";

const isProduction = process.env.NODE_ENV === "production";

// eslint-disable-next-line no-unused-vars
export default (config, entryPoint, headContent, assets) => {
  const tags = [];
  let key = 0;
  const assetPath = getAssetPath(config);

  if (isProduction) {
    tags.push(<link key={key++} rel="stylesheet" type="text/css" href={getAssetPathForFile(`${entryPoint}`, "styles")} />);
  }

  tags.push(
    <script key={key++} type="text/javascript" dangerouslySetInnerHTML={{__html: `window.__GS_PUBLIC_PATH__ = ${serialize(assetPath)}; window.__GS_ENVIRONMENT__ = ${serialize(process.env.NODE_ENV)}`}}></script>
  );

  const scriptPaths = {
    vendor: getAssetPathForFile("vendor", "javascript"),
    entryPoint: getAssetPathForFile(entryPoint, "javascript")
  };

  tags.push(headContent);

  tags.push(getScriptLoader(scriptPaths));

  return tags;
};

function getScriptLoader ({vendor, entryPoint}:Object) {
  // eslint-disable-next-line quotes
  const scriptLoader = `
    loadjs=loadjs=function(){function e(e,n){e=e.push?e:[e];var t,r,o,i,c=[],s=e.length,h=s;for(t=function(e,t){t.length&&c.push(e),h--,h||n(c)};s--;)r=e[s],o=u[r],o?t(r,o):(i=f[r]=f[r]||[],i.push(t))}function n(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function t(e,n,r,o){var c,u,f=document,s=r.async,h=(r.numRetries||0)+1,a=r.before||i;o=o||0,/\.css$/.test(e)?(c=!0,u=f.createElement("link"),u.rel="stylesheet",u.href=e):(u=f.createElement("script"),u.src=e,u.async=void 0===s||s),u.onload=u.onerror=u.onbeforeload=function(i){var f=i.type[0];if(c&&"hideFocus"in u)try{u.sheet.cssText.length||(f="e")}catch(e){f="e"}return"e"==f&&(o+=1,o<h)?t(e,n,r,o):void n(e,f,i.defaultPrevented)},a(e,u),f.head.appendChild(u)}function r(e,n,r){e=e.push?e:[e];var o,i,c=e.length,u=c,f=[];for(o=function(e,t,r){if("e"==t&&f.push(e),"b"==t){if(!r)return;f.push(e)}c--,c||n(f)},i=0;i<u;i++)t(e[i],o,r)}function o(e,t,o){var u,f;if(t&&t.trim&&(u=t),f=(u?o:t)||{},u){if(u in c)throw new Error("LoadJS");c[u]=!0}r(e,function(e){e.length?(f.error||i)(e):(f.success||i)(),n(u,e)},f)}var i=function(){},c={},u={},f={};return o.ready=function(n,t){return e(n,function(e){e.length?(t.error||i)(e):(t.success||i)()}),o},o.done=function(e){n(e,[])},o}();

    var loadEntryPoint = function() {
      loadjs("${entryPoint}", {
        before: function(path, el) { el.crossOrigin = "anonymous"; },
        error: function() { throw new Error("Failed to load ${entryPoint}"); },
        numRetries: 10
      });
    };

    var loadVendorThenEntry = function() {
      loadjs("${vendor}", {
        before: function(path, el) { el.crossOrigin = "anonymous"; },
        success: loadEntryPoint,
        error: function() { throw new Error("Failed to load ${vendor}"); },
        numRetries: 10
      });
    };

    document.addEventListener("DOMContentLoaded", function() {
      loadVendorThenEntry();
    });
  `;
  return <script key="script-loader" type="text/javascript" dangerouslySetInnerHTML={{__html: scriptLoader}} />;
}
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Bluebird = require('bluebird');
const TechnicalError = require('../errors').TechnicalError;
const {executePromiseInBatch} = require('../tools').stream;
const QueueManager = require('../tools').QueueManager;
const LoggerFactory = require('../tools').LoggerFactory;

class ProjectionUpdater {

  constructor(eventStore, projectionStore, options) {
    this._eventStore = eventStore;
    this._projectionStore = projectionStore;
    this._options = _.defaults(options || {}, {
      log: new LoggerFactory().create(__filename),
      delayBeforeUpdateInMs: 500
    });
    this._queueManager = new QueueManager();
  }

  get projectionName() {
    throw new TechnicalError('Must be implemented');
  }

  registerToBus(eventBus) {
    _.forEach(this._eventTypes(), type => {
      eventBus.register(type, () => this._planReady());
    });
  }

  _planReady() {
    if (!this._readyPlanned) {
      this._options.log.debug('Planning ready for', this.projectionName);
      this._readyPlanned = true;
      return Bluebird.delay(this._options.delayBeforeUpdateInMs)
        .then(() => {
          delete this._readyPlanned;
          return this.ready();
        });
    }
    return Promise.resolve();
  }

  ready() {
    return this._queueManager
      .queue(this.projectionName, {limit: 1})
      .enqueue(() => this._update());
  }

  _update() {
    this._options.log.debug('Update started');
    return this._retrieveLastEventId()
      .then(eventId => {
        let stream = this._eventStore.eventsFromTypes(this._eventTypes(), eventId);
        return executePromiseInBatch(stream, event => this._handleEvent(event));
      })
      .then(() => this._options.log.debug('Update done'));
  }

  _eventTypes() {
    return _.keys(this.handlers);
  }

  _retrieveLastEventId() {
    if (!this._lastEventId) {
      return this._projectionStore.get(this.projectionName)
        .then(result => _.get(result, 'lastEventId', null));
    }
    return Promise.resolve(this._lastEventId);
  }

  _handleEvent(event) {
    return Bluebird.try(() => this.handlers[event.type](event))
      .then(() => this._newEventProcessed(event))
      .catch(rejection => {
        this._options.log.error(`Update failed on event ${event.id}`, rejection);
        return Promise.reject(rejection);
      });
  }

  _newEventProcessed(event) {
    this._lastEventId = event.id;
    return this._projectionStore.set(this.projectionName, {lastEventId: this._lastEventId});
  }

  informationFromCreationEvent(event) {
    return {_id: event.aggregateRoot.id, creationDate: event.date};
  }
}

module.exports = ProjectionUpdater;
<commit_msg>useless method removal<commit_after>'use strict';

const _ = require('lodash');
const Bluebird = require('bluebird');
const TechnicalError = require('../errors').TechnicalError;
const {executePromiseInBatch} = require('../tools').stream;
const QueueManager = require('../tools').QueueManager;
const LoggerFactory = require('../tools').LoggerFactory;

class ProjectionUpdater {

  constructor(eventStore, projectionStore, options) {
    this._eventStore = eventStore;
    this._projectionStore = projectionStore;
    this._options = _.defaults(options || {}, {
      log: new LoggerFactory().create(__filename),
      delayBeforeUpdateInMs: 500
    });
    this._queueManager = new QueueManager();
  }

  get projectionName() {
    throw new TechnicalError('Must be implemented');
  }

  registerToBus(eventBus) {
    _.forEach(this._eventTypes(), type => {
      eventBus.register(type, () => this._planReady());
    });
  }

  _planReady() {
    if (!this._readyPlanned) {
      this._options.log.debug('Planning ready for', this.projectionName);
      this._readyPlanned = true;
      return Bluebird.delay(this._options.delayBeforeUpdateInMs)
        .then(() => {
          delete this._readyPlanned;
          return this.ready();
        });
    }
    return Promise.resolve();
  }

  ready() {
    return this._queueManager
      .queue(this.projectionName, {limit: 1})
      .enqueue(() => this._update());
  }

  _update() {
    this._options.log.debug('Update started');
    return this._retrieveLastEventId()
      .then(eventId => {
        let stream = this._eventStore.eventsFromTypes(this._eventTypes(), eventId);
        return executePromiseInBatch(stream, event => this._handleEvent(event));
      })
      .then(() => this._options.log.debug('Update done'));
  }

  _eventTypes() {
    return _.keys(this.handlers);
  }

  _retrieveLastEventId() {
    if (!this._lastEventId) {
      return this._projectionStore.get(this.projectionName)
        .then(result => _.get(result, 'lastEventId', null));
    }
    return Promise.resolve(this._lastEventId);
  }

  _handleEvent(event) {
    return Bluebird.try(() => this.handlers[event.type](event))
      .then(() => this._newEventProcessed(event))
      .catch(rejection => {
        this._options.log.error(`Update failed on event ${event.id}`, rejection);
        return Promise.reject(rejection);
      });
  }

  _newEventProcessed(event) {
    this._lastEventId = event.id;
    return this._projectionStore.set(this.projectionName, {lastEventId: this._lastEventId});
  }
}

module.exports = ProjectionUpdater;
<|endoftext|>


<commit_before>import Ember from 'ember';
import DocumentsError from '../util/error';

const {
  RSVP: { defer, resolve, reject },
  assign
} = Ember;

export default class Operation {

  constructor(label, props, fn, resolve) {
    this.label = label;
    this.fn = fn;
    this.resolve = resolve;
    assign(this, props);
    this.deferred = defer();
    this.destroyed = false;
  }

  _resolve(arg) {
    return this.deferred.resolve(arg);
  }

  _reject(err) {
    return this.deferred.reject(err);
  }

  get promise() {
    return this.deferred.promise;
  }

  _invoke() {
    if(this.destroyed) {
      return reject(new DocumentsError({ error: 'internal', reason: 'operation_destroyed' }));
    }
    return this.fn(this).then(result => {
      let resolve = this.resolve;
      if(resolve) {
        return resolve(result);
      }
      return result;
    });
  }

  invoke() {
    resolve()
      .then(() => this._invoke())
      .then(arg => this._resolve(arg), err => this._reject(err));
  }

  destroy() {
    this.destroyed = true;
  }

}
<commit_msg>RSVP.resolve operation fn<commit_after>import Ember from 'ember';
import DocumentsError from '../util/error';

const {
  RSVP: { defer, resolve, reject },
  assign
} = Ember;

export default class Operation {

  constructor(label, props, fn, resolve) {
    this.label = label;
    this.fn = fn;
    this.resolve = resolve;
    assign(this, props);
    this.deferred = defer();
    this.destroyed = false;
  }

  _resolve(arg) {
    return this.deferred.resolve(arg);
  }

  _reject(err) {
    return this.deferred.reject(err);
  }

  get promise() {
    return this.deferred.promise;
  }

  _invoke() {
    if(this.destroyed) {
      return reject(new DocumentsError({ error: 'internal', reason: 'operation_destroyed' }));
    }
    return resolve(this.fn(this)).then(result => {
      if(this.resolve) {
        return this.resolve(result);
      }
      return result;
    });
  }

  invoke() {
    resolve()
      .then(() => this._invoke())
      .then(arg => this._resolve(arg), err => this._reject(err));
  }

  destroy() {
    this.destroyed = true;
  }

}
<|endoftext|>


<commit_before>/// <reference path="../declares.d.ts" />
'use strict';
define(["require", "exports"], function (require, exports) {
    exports.language = {
        displayName: 'Dylan',
        name: 'dylan',
        mimeTypes: [],
        fileExtensions: ['.dylan', '.lid', '.hdp'],
        ignoreCase: true,
        defaultToken: '',
        lineComment: '//',
        blockCommentStart: '/*',
        blockCommentEnd: '*/',
        autoClosingPairs: [
          ['{', '}'],
          ['[', ']'],
          ['(', ')'],
          ['"', '"'],
          ['\'', '\'']],
        keywords: [
            'class',
            'constant',
            'domain',
            'function',
            'generic',
            'handler',
            'let',
            'library',
            'local',
            'macro',
            'method',
            'module',
            'slot',
            'variable',
        ],
        flowKeywords: [
            'afterwards',
            'begin',
            'block',
            'case',
            'cleanup',
            'define',
            'else',
            'elseif',
            'end',
            'exception',
            'for',
            'if',
            'otherwise',
            'select',
            'unless',
            'until',
            'while',
        ],
        methodAdjectives: [
            'compiler-open',
            'inline',
            'inline-only',
            'not-inline',
            'sealed',
        ],
        classAdjectives: [
            'abstract',
            'concrete',
            'dynamic',
            'free',
            'open',
            'primary',
            'sealed',
        ],
        brackets: [
            { open: '{', close: '}', token: 'delimiter.curly' },
            { open: '[', close: ']', token: 'delimiter.bracket' },
            { open: '(', close: ')', token: 'delimiter.parenthesis' }
        ],
        tokenizer: {
            root: [
                [/\s+/, 'white'],
                { include: '@numbers' },
                [/[,;]/, 'delimiter'],
                [/[{}\[\]()]/, '@brackets'],
                [/[a-zA-Z]\w*/, {
                    cases: {
                        '@flowKeywords': 'keyword.flow',
                        '@keywords': 'keyword',
                        '@methodAdjectives': 'token.annotation',
                        '@classAdjectives': 'token.annotation',
                        '@default': 'identifier'
                    }
                }]
            ],
            numbers: [
                [/#x([abcdef]|[ABCDEF]|\d)+/, 'number.hex'],
                [/#o[01234567]+/, 'number.octal'],
                [/#b[01]+/, 'number.binary'],
                [/(\+|-)?[\d]+/, 'number.decimal'],
                [/(\+|-)?(([\d]+\.?[\d]*)|(\.[\d]+))((e|E)(\+|-)?[\d]+)?/, 'number'],
            ],
        }
    };
});
<commit_msg>String (byte and unicode) strings handled.<commit_after>/// <reference path="../declares.d.ts" />
'use strict';
define(["require", "exports"], function (require, exports) {
    exports.language = {
        displayName: 'Dylan',
        name: 'dylan',
        mimeTypes: [],
        fileExtensions: ['.dylan', '.lid', '.hdp'],
        ignoreCase: true,
        defaultToken: '',
        lineComment: '//',
        blockCommentStart: '/*',
        blockCommentEnd: '*/',
        autoClosingPairs: [
          ['{', '}'],
          ['[', ']'],
          ['(', ')'],
          ['"', '"'],
          ['\'', '\'']],
        keywords: [
            'class',
            'constant',
            'domain',
            'function',
            'generic',
            'handler',
            'let',
            'library',
            'local',
            'macro',
            'method',
            'module',
            'slot',
            'variable',
        ],
        flowKeywords: [
            'afterwards',
            'begin',
            'block',
            'case',
            'cleanup',
            'define',
            'else',
            'elseif',
            'end',
            'exception',
            'for',
            'if',
            'otherwise',
            'select',
            'unless',
            'until',
            'while',
        ],
        methodAdjectives: [
            'compiler-open',
            'inline',
            'inline-only',
            'not-inline',
            'sealed',
        ],
        classAdjectives: [
            'abstract',
            'concrete',
            'dynamic',
            'free',
            'open',
            'primary',
            'sealed',
        ],
        brackets: [
            { open: '{', close: '}', token: 'delimiter.curly' },
            { open: '[', close: ']', token: 'delimiter.bracket' },
            { open: '(', close: ')', token: 'delimiter.parenthesis' }
        ],
        escapes: /\\(?:[\\"'abefnrt0]|<[0-9A-Za-z]>)/,
        tokenizer: {
            root: [
                [/\s+/, 'white'],
                { include: '@numbers' },
                [/[,;]/, 'delimiter'],
                [/[{}\[\]()]/, '@brackets'],
                [/"([^"\\]|\\.)*$/, 'string.invalid'],
                [/"/, 'string', '@string'],
                [/'[^\\']'/, 'string'],
                [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
                [/'/, 'string.invalid'],
                [/[a-zA-Z0-9]\w*/, {
                    cases: {
                        '@flowKeywords': 'keyword.flow',
                        '@keywords': 'keyword',
                        '@methodAdjectives': 'token.annotation',
                        '@classAdjectives': 'token.annotation',
                        '@default': 'identifier'
                    }
                }]
            ],
            numbers: [
                [/#x([abcdef]|[ABCDEF]|\d)+/, 'number.hex'],
                [/#o[01234567]+/, 'number.octal'],
                [/#b[01]+/, 'number.binary'],
                [/(\+|-)?[\d]+/, 'number.decimal'],
                [/(\+|-)?(([\d]+\.?[\d]*)|(\.[\d]+))((e|E)(\+|-)?[\d]+)?/, 'number'],
            ],
            string: [
                [/[^\\"]+/, 'string'],
                [/@escapes/, 'string.escape'],
                [/\\./, 'string.escape.invalid'],
                [/"/, 'string', '@pop'],
            ],
        }
    };
});
<|endoftext|>


<commit_before>var generators = require('yeoman-generator')
var fse = require('fs-extra')
var path = require('path')

// Vars
var cwd = process.cwd()
var site_path

module.exports = generators.Base.extend({

  constructor: function () {
    generators.Base.apply(this, arguments)
    this.argument('name', {type: String, required: false})
  },

  prompting: function () {
    var done = this.async()

    if (this.name) {
      site_path = path.join(cwd, this.name)
      return done()
    }

    this.prompt({
      type: 'input',
      name: 'name',
      message: 'Your site name',
      default: 'odddrupal'
    }, function (answers) {
      site_path = path.join(cwd, answers.name)
      done()
    })
  },

  // ## Clone odddrupal

  // Clone https://github.com/oddhill/odddrupal.git.
  // And rename origin to odddrupal.
  clone: function () {
    var self = this
    var done = this.async()

    self.log('Cloning odddrupal to ' + site_path + '...')

    // Clone odddrupal to cwd
    var clone = self.spawnCommand('git', ['clone', 'https://github.com/oddhill/odddrupal.git', site_path])
    clone.on('close', function () {
      // Remove origin remote ref
      var rmRemote = self.spawnCommand('git', ['remote', 'rm', 'origin'], {cwd: site_path})
      rmRemote.on('close', function (code) {
        if (!code) {
          self.log('Done')
        } else {
          self.log('Unable to remove origin remote reference. Code: ' + code)
        }
        // Continue
        done()
      })
    })
  },

  // Rename current branch to master
  createMaster: function () {
    var self = this
    var done = this.async()
    self.log('Renaming the 7.x branch to master...')
    // Rename current local branch to master
    var rename = self.spawnCommand('git', ['branch', '-m', '7.x', 'master'], {cwd: site_path})
    rename.on('close', function () {
      self.log('Done')
      done()
    })
  },

  // ## Install odddrupal

  // Copy .htaccess.default to .htaccess.
  htaccess: function () {
    var self = this
    var done = this.async()
    fse.copy(path.join(site_path, '.htaccess.default'), path.join(site_path, '.htaccess'), function (err) {
      if (!err) {
        self.log('Copied .htaccess.default to .htaccess')
        done()
      }
    })
  },

  // Copy sites/default/settings.local.php.default to settings.local.php.
  dbSettings: function () {
    var self = this
    var done = this.async()
    fse.copy(path.join(site_path, 'sites/default/settings.local.php.default'), path.join(site_path, 'sites/default/settings.local.php'), function (err) {
      if (!err) {
        self.log('Copied settings.local.php.default to settings.local.php')
        done()
      }
    })
  },

  // Make sure the files folder (sites/all/files) is 777.
  filesChmod: function () {
    var self = this
    var done = this.async()
    fse.ensureDir(path.join(site_path, 'sites/all/files'), function (err) {
      if (!err) {
        self.log('Created files dir')
        // Make sure files folder is 777
        fse.chmod(path.join(site_path, 'sites/all/files'), '777', function () {
          self.log('Changed permissions on files dir to 777.')

          // Continue
          done()
        })
      }
    })
  },

  end: function () {
    this.log('All done!')
  }

})
<commit_msg>Removed odddrupal generator<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';

import BaseAdapter from './base-adapter';
import { SimplePredicate, ComplexPredicate, StringPredicate } from './predicate';

/**
 * Class of query adapter that translates query object into OData URL.
 *
 * @module ember-flexberry-projections
 * @namespace Query
 * @class ODataAdapter
 * @extends Query.BaseAdapter
 */
export default class ODataAdapter extends BaseAdapter {
  /**
   * @param {String} baseUrl
   * @param {EdmberData.Store} store
   * @class ODataAdapter
   * @constructor
   */
  constructor(baseUrl, store) {
    super();

    if (!baseUrl) {
      throw new Error('Base URL for OData feed is required');
    }

    if (!store) {
      throw new Error('Store is required');
    }

    this._baseUrl = baseUrl;
    this._store = store;
  }

  /**
   * Determines the pathname for a given type.
   * Additionally capitalizes the type name (requirement of Flexberry OData Server).
   *
   * @method pathForType
   * @param {String} modelName
   * @return {String} The path for a given type.
   */
  pathForType(modelName) {
    var camelized = Ember.String.camelize(modelName);
    var capitalized = Ember.String.capitalize(camelized);
    return Ember.String.pluralize(capitalized);
  }

  /**
   * Returns base part of URL for querying OData feed (without query part).
   *
   * @method getODataFullUrl
   * @param {Object} query The query for building OData URL.
   * @return {String}
   * @public
   */
  getODataBaseUrl(query) {
    let type = this.pathForType(query.modelName);
    let id = query.id ? `(${query.id})` : '';

    return `${this._baseUrl}/${type}${id}`;
  }

  /**
   * Returns query data for querying OData feed (for query part).
   *
   * @method getODataQuery
   * @param {Object} query The query for building OData URL.
   * @return {Object}
   * @public
   */
  getODataQuery(query) {
    let odataArgs = {};

    // TODO: do not use order,expand with count
    for (let k in builders) {
      if (builders.hasOwnProperty(k)) {
        let v = builders[k](query, this._store);
        if (v !== null && v !== '') {
          odataArgs[k] = v;
        }
      }
    }

    return odataArgs;
  }

  /**
   * Returns full URL for querying OData feed (base part and query part).
   *
   * @method getODataFullUrl
   * @param {Object} query The query for building OData URL.
   * @return {String}
   * @public
   */
  getODataFullUrl(query) {
    let odataArgs = this.getODataQuery(query);
    let queryArgs = [];
    Object.keys(odataArgs).forEach(k => {
      let v = odataArgs[k];
      if (v) {
        queryArgs.push(`${k}=${v}`);
      }
    });
    let queryMark = queryArgs.length > 0 ? '?' : '';
    let queryPart = queryArgs.join('&');

    return this.getODataBaseUrl(query) + queryMark + queryPart;
  }
}

var builders = {
  $filter: buildODataFilters,
  $orderby: buildODataOrderBy,
  $skip: buildODataSkip,
  $top: buildODataTop,
  $count: buildODataCount,
  $expand: buildODataExpand,
  $select: buildODataSelect
};

function buildODataSelect(query) {
  return query.select.join(',');
}

function buildODataExpand(query) {
  return query.expand.join(',');
}

function buildODataCount(query) {
  return query.count ? true : null;
}

function buildODataSkip(query) {
  return query.skip;
}

function buildODataTop(query) {
  return query.top;
}

function buildODataFilters(query, store) {
  let predicate = query.predicate;
  if (!predicate) {
    return null;
  }

  return convertPredicateToODataFilterClause(predicate, store, query.modelName);
}

function buildODataOrderBy(query) {
  if (!query.order) {
    return null;
  }

  let result = '';
  for (let i = 0; i < query.order.length; i++) {
    let property = query.order.attribute(i);
    let sep = i ? ',' : '';
    let direction = property.direction ? ` ${property.direction}` : '';
    result += `${sep}${property.name}${direction}`;
  }

  return result;
}

/**
 * Converts specified predicate into OData filter part.
 *
 * @method convertPredicateToODataFilterClause
 * @param predicate {BasePredicate} Predicate to convert.
 * @param store
 * @return {String} OData filter part.
 */
function convertPredicateToODataFilterClause(predicate, store, modelName) {
  if (predicate instanceof SimplePredicate) {
    let type = '?';
    store.modelFor(modelName).eachAttribute(function(name, meta) {
      if (name === predicate.attributeName) {
        type = meta.type;
      }
    });

    let value = type === 'string' ? `'${predicate.value}'` : predicate.value;
    return `${predicate.attributeName} ${predicate.operator} ${value}`;
  }

  if (predicate instanceof StringPredicate) {
    return `contains(${predicate.attributeName},'${predicate.containsValue}')`;
  }

  if (predicate instanceof ComplexPredicate) {
    let separator = ` ${predicate.condition} `;
    return predicate.predicates
      .map(i => convertPredicateToODataFilterClause(i, store, modelName)).join(separator);
  }

  throw new Error(`Unknown predicate '${predicate}'`);
}
<commit_msg>Use serializers for string predicates in OData<commit_after>import Ember from 'ember';

import BaseAdapter from './base-adapter';
import { SimplePredicate, ComplexPredicate, StringPredicate } from './predicate';

/**
 * Class of query adapter that translates query object into OData URL.
 *
 * @module ember-flexberry-projections
 * @namespace Query
 * @class ODataAdapter
 * @extends Query.BaseAdapter
 */
export default class ODataAdapter extends BaseAdapter {
  /**
   * @param {String} baseUrl
   * @param {EdmberData.Store} store
   * @class ODataAdapter
   * @constructor
   */
  constructor(baseUrl, store) {
    super();

    if (!baseUrl) {
      throw new Error('Base URL for OData feed is required');
    }

    if (!store) {
      throw new Error('Store is required');
    }

    this._baseUrl = baseUrl;
    this._store = store;
  }

  /**
   * Determines the pathname for a given type.
   * Additionally capitalizes the type name (requirement of Flexberry OData Server).
   *
   * @method pathForType
   * @param {String} modelName
   * @return {String} The path for a given type.
   */
  pathForType(modelName) {
    var camelized = Ember.String.camelize(modelName);
    var capitalized = Ember.String.capitalize(camelized);
    return Ember.String.pluralize(capitalized);
  }

  /**
   * Returns base part of URL for querying OData feed (without query part).
   *
   * @method getODataFullUrl
   * @param {Object} query The query for building OData URL.
   * @return {String}
   * @public
   */
  getODataBaseUrl(query) {
    let type = this.pathForType(query.modelName);
    let id = query.id ? `(${query.id})` : '';

    return `${this._baseUrl}/${type}${id}`;
  }

  /**
   * Returns query data for querying OData feed (for query part).
   *
   * @method getODataQuery
   * @param {Object} query The query for building OData URL.
   * @return {Object}
   * @public
   */
  getODataQuery(query) {
    let odataArgs = {};

    // TODO: do not use order,expand with count
    for (let k in builders) {
      if (builders.hasOwnProperty(k)) {
        let v = builders[k](query, this._store);
        if (v !== null && v !== '') {
          odataArgs[k] = v;
        }
      }
    }

    return odataArgs;
  }

  /**
   * Returns full URL for querying OData feed (base part and query part).
   *
   * @method getODataFullUrl
   * @param {Object} query The query for building OData URL.
   * @return {String}
   * @public
   */
  getODataFullUrl(query) {
    let odataArgs = this.getODataQuery(query);
    let queryArgs = [];
    Object.keys(odataArgs).forEach(k => {
      let v = odataArgs[k];
      if (v) {
        queryArgs.push(`${k}=${v}`);
      }
    });
    let queryMark = queryArgs.length > 0 ? '?' : '';
    let queryPart = queryArgs.join('&');

    return this.getODataBaseUrl(query) + queryMark + queryPart;
  }
}

var builders = {
  $filter: buildODataFilters,
  $orderby: buildODataOrderBy,
  $skip: buildODataSkip,
  $top: buildODataTop,
  $count: buildODataCount,
  $expand: buildODataExpand,
  $select: buildODataSelect
};

function buildODataSelect(query) {
  return query.select.join(',');
}

function buildODataExpand(query) {
  return query.expand.join(',');
}

function buildODataCount(query) {
  return query.count ? true : null;
}

function buildODataSkip(query) {
  return query.skip;
}

function buildODataTop(query) {
  return query.top;
}

function buildODataFilters(query, store) {
  let predicate = query.predicate;
  if (!predicate) {
    return null;
  }

  return convertPredicateToODataFilterClause(predicate, store, query.modelName);
}

function buildODataOrderBy(query) {
  if (!query.order) {
    return null;
  }

  let result = '';
  for (let i = 0; i < query.order.length; i++) {
    let property = query.order.attribute(i);
    let sep = i ? ',' : '';
    let direction = property.direction ? ` ${property.direction}` : '';
    result += `${sep}${property.name}${direction}`;
  }

  return result;
}

/**
 * Converts specified predicate into OData filter part.
 *
 * @method convertPredicateToODataFilterClause
 * @param predicate {BasePredicate} Predicate to convert.
 * @param store
 * @return {String} OData filter part.
 */
function convertPredicateToODataFilterClause(predicate, store, modelName) {
  if (predicate instanceof SimplePredicate) {
    let type = '?';
    store.modelFor(modelName).eachAttribute(function(name, meta) {
      if (name === predicate.attributeName) {
        type = meta.type;
      }
    });

    let value = type === 'string' ? `'${predicate.value}'` : predicate.value;
    return `${predicate.attributeName} ${predicate.operator} ${value}`;
  }

  if (predicate instanceof StringPredicate) {
    let serializer = store.serializerFor(modelName);
    let normalizedAttrName = serializer.keyForAttribute(predicate.attributeName);
    return `contains(${normalizedAttrName},'${predicate.containsValue}')`;
  }

  if (predicate instanceof ComplexPredicate) {
    let separator = ` ${predicate.condition} `;
    return predicate.predicates
      .map(i => convertPredicateToODataFilterClause(i, store, modelName)).join(separator);
  }

  throw new Error(`Unknown predicate '${predicate}'`);
}
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-pug-gulp-sass-bootstrap:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({someAnswer: true})
      .toPromise();
  });

  it('creates files', function () {
    assert.file([
      'dummyfile.txt'
    ]);
  });

  it('installs bootstrap', function (done) {
    helpers.mockPrompt(this.app, {
      format: 'css'
    });

    this.app.run(function () {
      assert.equal(this.bowerInstallCalls[0][0], 'bootstrap');
      done();
    }.bind(this));
  });
});
<commit_msg>change to bootstrap with Sass in test<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-pug-gulp-sass-bootstrap:app', function () {
  before(function () {
    return helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({someAnswer: true})
      .toPromise();
  });

  it('creates files', function () {
    assert.file([
      'dummyfile.txt'
    ]);
  });

  it('installs sass-bootstrap', function (done) {
    this.app.run(function () {
      assert.equal(this.bowerInstallCalls[0][0], 'bootstrap-sass-official');
      done();
    }.bind(this));
  });
});
<|endoftext|>


<commit_before>"use strict";

function convert_date_string(date_time_str) {
  // use strict ISO 8601 parsing in moment.js to avoid ambiguities
  var moment_obj =  moment(date_time_str, moment.ISO_8601, true);
  if (moment_obj.isValid) {
    return date_time_str;
  } else {
    return null;
  }
}

function make_daterange() {
   // converts the time range inputs to a format that can be
   // used by solr
   var start_val = $('input#start_time').val();
   var end_val = $('input#end_time').val();
   // TODO: add input verification on server side

   var form_button = $('form[name="datetime-selection"').find('.btn.apply');
   var btn_disabled;
   if (!start_val && !end_val) {
     var set_val = '';
     start_val_scrub = end_val_scrub = null;
       btn_disabled = true;
   } else {
     var start_val_scrub = start_val;
     var end_val_scrub = end_val;
   }

   var date_form = $('form[name="datetime-selection"]');
   var form_btn = date_form.find('.btn.apply');
   date_form.validate()
   if (date_form.valid()) {
     $('input#ext_timerange_start').val(start_val_scrub);
     $('input#ext_timerange_end').val(end_val_scrub);
     form_btn.attr('disabled', false);
   } else {
     form_btn.attr('disabled', true);
   }
}

ckan.module('ioos_theme_daterange', function($) {
    return {
        initialize: function() {
  // toggle date info popover
  $('[data-toggle="popover"]').popover({placement: 'bottom', html: true});
  var form = $(".search-form");
  $(['ext_timerange_start', 'ext_timerange_end']).each(function(index, item){
    var time_elem = $("#" + item);
    if (time_elem.length === 0) {
      $('<input type="hidden" />').attr({'id': item,
                                         'name': item}).appendTo(form);
     }
    });
    var search_params = new URLSearchParams(location.search);
    var param_start_time = search_params.get('ext_timerange_start');
    if (param_start_time !== null) {
        $('input#start_time').val(param_start_time);
    }
    var param_end_time = search_params.get('ext_timerange_end');
    if (param_end_time !== null) {
        $('input#end_time').val(param_end_time);
    }

  $('a[name="datefilter"]').daterangepicker({
    timePicker24Hour: true,
    startDate: moment().startOf('hour'),
    endDate: moment().startOf('hour').add(32, 'hour'),
    locale: {
      format: 'YYYY-MM-DDTHH:mm\\Z'
    }
  });

  // set ISO-like date on range selection
  $('a[name="datefilter"]').on('apply.daterangepicker',
                                   function(ev, picker) {
                                       $('input[name="start_time"]').val(picker.startDate.format('YYYY-MM-DDTHH:mm') + "Z");
                                       $('input[name="end_time"]').val(picker.endDate.format('YYYY-MM-DDTHH:mm') + "Z");
                                       // setting .val doesn't fire the
                                       // on change handler, so we need to
                                       // call the function directly.
                                       make_daterange();
                                   });
  $.validator.setDefaults({
    debug: true,
    success: "valid"
  });

  $.validator.addMethod("isMomentCompatible",
      function (value, element, params) {
        if (this.optional(element) || value === null || value === "*") {
          return true;
        } else {
         // use strict ISO 8601 parsing in moment.js to avoid ambiguities
         var is_valid = moment(value, ['YYYY', moment.ISO_8601],
                               true).isValid();
         if (!is_valid) {
            var date_btn = $('form[name="datetime-selection"]').find('.btn.apply');
            date_btn.attr('disabled', true);
          }
          return is_valid;
        }
      });

  var validator = $('form[name="datetime-selection"]').validate({
      rules: {
         start_time: {
             isMomentCompatible: true,
             required: false
         },
         end_time: {
             isMomentCompatible: true,
             required: false
         }
      },
     messages: {
        start_time: { isMomentCompatible: "Start time not valid" },
        end_time: { isMomentCompatible: "End time not valid" }
     }
  });

  make_daterange();

  // clear data selection on cancel
  $('a[name="datefilter"]').on('cancel.daterangepicker',
                                   function(ev, picker) {
                                       $('input[name="start_time"]').val('');
                                       $('input[name="end_time"]').val('');
                                       make_daterange();
                                   });

  $('input[name="start_time"]').on('change', make_daterange);
  $('input[name="end_time"]').on('change', make_daterange);

  // submit the updated form when the Apply button is clicked
  $(this.el).find('.btn.apply').click(function() { form.submit() });
  $('form[name="datetime-selection"]').on('reset', function() {
                                           $('input#ext_timerange_start').remove();
                                           $('input#ext_timerange_end').remove();
                                           /* semi-hack to wait until reset
                                            * event has fired by pushing
                                            * onto the event stack */
                                           window.setTimeout(function() {
                                                              make_daterange();
                                                              form.submit();
                                                             }, 0);
                                          });
    }
  }

 });
<commit_msg>Submit form on daterangepicker apply<commit_after>"use strict";

function convert_date_string(date_time_str) {
  // use strict ISO 8601 parsing in moment.js to avoid ambiguities
  var moment_obj =  moment(date_time_str, moment.ISO_8601, true);
  if (moment_obj.isValid) {
    return date_time_str;
  } else {
    return null;
  }
}

function make_daterange() {
   // converts the time range inputs to a format that can be
   // used by solr
   var start_val = $('input#start_time').val();
   var end_val = $('input#end_time').val();
   // TODO: add input verification on server side

   var form_button = $('form[name="datetime-selection"').find('.btn.apply');
   var btn_disabled;
   if (!start_val && !end_val) {
     var set_val = '';
     start_val_scrub = end_val_scrub = null;
       btn_disabled = true;
   } else {
     var start_val_scrub = start_val;
     var end_val_scrub = end_val;
   }

   var date_form = $('form[name="datetime-selection"]');
   var form_btn = date_form.find('.btn.apply');
   date_form.validate()
   if (date_form.valid()) {
     $('input#ext_timerange_start').val(start_val_scrub);
     $('input#ext_timerange_end').val(end_val_scrub);
     form_btn.attr('disabled', false);
   } else {
     form_btn.attr('disabled', true);
   }
}

ckan.module('ioos_theme_daterange', function($) {
    return {
        initialize: function() {
  // toggle date info popover
  $('[data-toggle="popover"]').popover({placement: 'bottom', html: true});
  var form = $(".search-form");
  $(['ext_timerange_start', 'ext_timerange_end']).each(function(index, item){
    var time_elem = $("#" + item);
    if (time_elem.length === 0) {
      $('<input type="hidden" />').attr({'id': item,
                                         'name': item}).appendTo(form);
     }
    });
    var search_params = new URLSearchParams(location.search);
    var param_start_time = search_params.get('ext_timerange_start');
    if (param_start_time !== null) {
        $('input#start_time').val(param_start_time);
    }
    var param_end_time = search_params.get('ext_timerange_end');
    if (param_end_time !== null) {
        $('input#end_time').val(param_end_time);
    }

  $('a[name="datefilter"]').daterangepicker({
    timePicker24Hour: true,
    startDate: moment().startOf('hour'),
    endDate: moment().startOf('hour').add(32, 'hour'),
    locale: {
      format: 'YYYY-MM-DDTHH:mm\\Z'
    }
  });

  // set ISO-like date on range selection
  $('a[name="datefilter"]').on('apply.daterangepicker',
                                   function(ev, picker) {
                                       $('input[name="start_time"]').val(picker.startDate.format('YYYY-MM-DDTHH:mm') + "Z");
                                       $('input[name="end_time"]').val(picker.endDate.format('YYYY-MM-DDTHH:mm') + "Z");
                                       /* setting .val doesn't fire the
                                        * on change handler, so we need to
                                        * call the function directly. */
                                       make_daterange();
                                       /* submit the form after selecting dates
                                        * to make behavior consistent with
                                        * other widgets */
                                       form.submit();
                                   });
  $.validator.setDefaults({
    debug: true,
    success: "valid"
  });

  $.validator.addMethod("isMomentCompatible",
      function (value, element, params) {
        if (this.optional(element) || value === null || value === "*") {
          return true;
        } else {
         // use strict ISO 8601 parsing in moment.js to avoid ambiguities
         var is_valid = moment(value, ['YYYY', moment.ISO_8601],
                               true).isValid();
         if (!is_valid) {
            var date_btn = $('form[name="datetime-selection"]').find('.btn.apply');
            date_btn.attr('disabled', true);
          }
          return is_valid;
        }
      });

  var validator = $('form[name="datetime-selection"]').validate({
      rules: {
         start_time: {
             isMomentCompatible: true,
             required: false
         },
         end_time: {
             isMomentCompatible: true,
             required: false
         }
      },
     messages: {
        start_time: { isMomentCompatible: "Start time not valid" },
        end_time: { isMomentCompatible: "End time not valid" }
     }
  });

  make_daterange();

  // clear data selection on cancel
  $('a[name="datefilter"]').on('cancel.daterangepicker',
                                   function(ev, picker) {
                                       $('input[name="start_time"]').val('');
                                       $('input[name="end_time"]').val('');
                                       make_daterange();
                                   });

  $('input[name="start_time"]').on('change', make_daterange);
  $('input[name="end_time"]').on('change', make_daterange);

  // submit the updated form when the Apply button is clicked
  $(this.el).find('.btn.apply').click(function() { form.submit() });
  $('form[name="datetime-selection"]').on('reset', function() {
                                           $('input#ext_timerange_start').remove();
                                           $('input#ext_timerange_end').remove();
                                           /* semi-hack to wait until reset
                                            * event has fired by pushing
                                            * onto the event stack */
                                           window.setTimeout(function() {
                                                              make_daterange();
                                                              form.submit();
                                                             }, 0);
                                          });
    }
  }

});
<|endoftext|>


<commit_before>
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      [1,2,3].indexOf(5).should.equal(-1);
      [1,2,3].indexOf(0).should.equal(-1);
    })

    it('should return the correct index when the value is present', function(){
      [1,2,3].indexOf(1).should.equal(0);
      [1,2,3].indexOf(2).should.equal(1);
      [1,2,3].indexOf(5).should.equal(2);
    })
  })
})
<commit_msg>fixed a test<commit_after>
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      [1,2,3].indexOf(5).should.equal(-1);
      [1,2,3].indexOf(0).should.equal(-1);
    })

    it('should return the correct index when the value is present', function(){
      [1,2,3].indexOf(1).should.equal(0);
      [1,2,3].indexOf(2).should.equal(1);
      [1,2,3].indexOf(3).should.equal(2);
    })
  })
})
<|endoftext|>