<commit_before>const yeoman = require('yeoman-generator');
const fmtUrl = require('normalize-url');
const chalk = require('chalk');
const yosay = require('yosay');

const base = 'https://github.com/laravel';

module.exports = yeoman.generators.Base.extend({
  prompting: function() {
    const done = this.async();

    this.log(yosay(
      'Welcome to the ' + chalk.red('Fly Laravel') + ' generator!'
    ));

    const prompts = [{
      name: 'framework',
      type: 'list',
      message: 'Would you like to work with Laravel or Lumen?',
      store: true,
      choices: ['Laravel', 'Lumen']
    }, {
      name: 'username',
      message: 'What is your GitHub username?',
      store: true,
      validate: function(val) {
        return val.length > 0 ? true : 'github needed';
      }
    }, {
      name: 'website',
      message: 'What is your website?',
      store: true,
      default: function(props) {
        return 'http://github.com/' + props.username;
      }
    }, {
      name: 'proxy',
      message: 'What is this project\'s development URL?',
      store: true,
      default: function(props) {
        return 'http://homestead.app';
      }
    }, {
      type: 'confirm',
      name: 'useProcessor',
      message: 'Do you want to use a CSS preprocessor?',
      store: true,
      default: true
    }, {
      type: 'list',
      name: 'cssTool',
      message: 'Good choice! Which CSS preprocessor would you like?',
      store: true,
      choices: ['SASS', 'LESS', 'Stylus'],
      when: function (response) {
        return response.useProcessor;
      }
    }, {
      type: 'confirm',
      name: 'useXO',
      message: 'Do you want to use XO\'s ESLint settings?',
      store: true,
      default: true
    }, {
      type: 'confirm',
      name: 'useTests',
      message: 'Do you want to install a test suite?',
      store: true,
      default: true
    }, {
      type: 'list',
      name: 'testrunner',
      message: 'Great! Which test runner would you like to use?',
      choices: [ 'Ava', 'Mocha' ], // 'Karma', 'Protractor', 'Tape'
      store: true,
      when: function (response) {
        return response.useTests;
      }
    }, {
      type: 'confirm',
      name: 'travis',
      message: 'Do you want to add Travis CI?',
      store: true,
      default: true
    }, {
      type: 'confirm',
      name: 'changelog',
      message: 'Do you need a CHANGELOG file?',
      store: true,
      default: true
    }, {
      type: 'confirm',
      name: 'gitinit',
      message: 'Initialize a Git repository?',
      store: true,
      default: true
    }];

    this.prompt(prompts, function(props) {
      this.props = props;

      this.useTests = props.useTests;
      this.testrunner = props.useTests ? props.testrunner.toLowerCase() : null;
      this.cssTool = props.useProcessor ? props.cssTool.toLowerCase() : 'css';

      this.proxy = fmtUrl(props.proxy);
      this.website = fmtUrl(props.website);
      this.email = this.user.git.email();
      this.name = this.user.git.name();

      done();
    }.bind(this));
  },

  writing: function() {
    const done = this.async();
    const self = this;
    const repo = `${base}/${this.props.framework.toLowerCase()}.git`

    self.spawnCommand('git', ['clone', '--depth=1', repo, '.']).on('close', function() {
      const files = ['.git', 'package.json', '.gitignore', '.gitattributes', 'resources/assets'];
      const args  = ['-rf'].concat(files);

      self.spawnCommand('rm', args).on('close', function() {
        self.copy();
        done();
      });
    });
  },

  copy: function() {
    const done = this.async();

    this.template('LICENSE');
    // this.template('README.md');
    this.template('editorconfig', '.editorconfig');
    this.template('_package.json', 'package.json');

    // Prepare FlyFile styles' path selector
    const ext = (this.cssTool == 'sass')
      ? '{sass,scss}' : (this.cssTool == 'stylus')
      ? 'styl' : this.cssTool;

    // Copy FlyFile
    this.template('flyfile', 'flyfile.js', {
      proxy: this.proxy,
      cssTool: this.cssTool,
      cssPath: "/styles/**/*."+ext
    });

    // Copy Static Assets, no alternatives
    const statics = ['fonts', 'images', 'scripts'];
    statics.forEach(function(s) {
      this.fs.copy(
        this.templatePath('assets/'+s),
        this.destinationPath('resources/assets/'+s)
      );
    }.bind(this));

    // Copy Style Assets, based on response
    this.fs.copy(
      this.templatePath('assets/styles/'+this.cssTool),
      this.destinationPath('resources/assets/styles')
    );

    const lint = this.props.useXO ? 'eslint_xo' : 'eslint_default';
    this.template(lint, '.eslintrc');

    if (this.props.gitinit) {
      this.template('gitignore', '.gitignore');
      this.template('gitattributes', '.gitattributes');
    }

    if (this.props.useTests) {
      this.fs.copy(
        this.templatePath('tests/' + this.testrunner),
        this.destinationPath('resources/tests')
      );
    }

    if (this.props.travis) {
      this.template('_travis.yml', '.travis.yml');
    }

    if (this.props.changelog) {
      this.template('changelog.md');
    }

    done();
  },

  install: function() {
    var plugins = [];
    if (this.testrunner) plugins.push('fly-'+this.testrunner);
    if (this.props.useProcessor) plugins.push('fly-'+this.cssTool);
    if (this.props.useXO) plugins.push('eslint-config-xo');

    this.spawnCommand('composer', ['install']);

    this.installDependencies({bower: false});
    this.npmInstall(plugins, {saveDev: true});
  },

  end: function() {
    if (!this.props.gitinit) return;

    const done = this.async();
    const self = this;

    console.log('\n');
    this.spawnCommand('git', ['init']).on('close', function() {
      self.spawnCommand('git', ['add', '--all']).on('close', function() {
        self.spawnCommand('git', ['commit', '-m', 'first commit, via generator-fly-laravel 🚀']).on('close', function() {
          console.log('\n');
          done();
        });
      });
    });
  }
});
<commit_msg>dont use templateStrings, breaks node 0.12<commit_after>const yeoman = require('yeoman-generator');
const fmtUrl = require('normalize-url');
const chalk = require('chalk');
const yosay = require('yosay');

const base = 'https://github.com/laravel';

module.exports = yeoman.generators.Base.extend({
  prompting: function() {
    const done = this.async();

    this.log(yosay(
      'Welcome to the ' + chalk.red('Fly Laravel') + ' generator!'
    ));

    const prompts = [{
      name: 'framework',
      type: 'list',
      message: 'Would you like to work with Laravel or Lumen?',
      store: true,
      choices: ['Laravel', 'Lumen']
    }, {
      name: 'username',
      message: 'What is your GitHub username?',
      store: true,
      validate: function(val) {
        return val.length > 0 ? true : 'github needed';
      }
    }, {
      name: 'website',
      message: 'What is your website?',
      store: true,
      default: function(props) {
        return 'http://github.com/' + props.username;
      }
    }, {
      name: 'proxy',
      message: 'What is this project\'s development URL?',
      store: true,
      default: function(props) {
        return 'http://homestead.app';
      }
    }, {
      type: 'confirm',
      name: 'useProcessor',
      message: 'Do you want to use a CSS preprocessor?',
      store: true,
      default: true
    }, {
      type: 'list',
      name: 'cssTool',
      message: 'Good choice! Which CSS preprocessor would you like?',
      store: true,
      choices: ['SASS', 'LESS', 'Stylus'],
      when: function (response) {
        return response.useProcessor;
      }
    }, {
      type: 'confirm',
      name: 'useXO',
      message: 'Do you want to use XO\'s ESLint settings?',
      store: true,
      default: true
    }, {
      type: 'confirm',
      name: 'useTests',
      message: 'Do you want to install a test suite?',
      store: true,
      default: true
    }, {
      type: 'list',
      name: 'testrunner',
      message: 'Great! Which test runner would you like to use?',
      choices: [ 'Ava', 'Mocha' ], // 'Karma', 'Protractor', 'Tape'
      store: true,
      when: function (response) {
        return response.useTests;
      }
    }, {
      type: 'confirm',
      name: 'travis',
      message: 'Do you want to add Travis CI?',
      store: true,
      default: true
    }, {
      type: 'confirm',
      name: 'changelog',
      message: 'Do you need a CHANGELOG file?',
      store: true,
      default: true
    }, {
      type: 'confirm',
      name: 'gitinit',
      message: 'Initialize a Git repository?',
      store: true,
      default: true
    }];

    this.prompt(prompts, function(props) {
      this.props = props;

      this.useTests = props.useTests;
      this.testrunner = props.useTests ? props.testrunner.toLowerCase() : null;
      this.cssTool = props.useProcessor ? props.cssTool.toLowerCase() : 'css';

      this.proxy = fmtUrl(props.proxy);
      this.website = fmtUrl(props.website);
      this.email = this.user.git.email();
      this.name = this.user.git.name();

      done();
    }.bind(this));
  },

  writing: function() {
    const done = this.async();
    const self = this;
    const repo = base + '/' + this.props.framework.toLowerCase() + '.git';

    self.spawnCommand('git', ['clone', '--depth=1', repo, '.']).on('close', function() {
      const files = ['.git', 'package.json', '.gitignore', '.gitattributes', 'resources/assets'];
      const args  = ['-rf'].concat(files);

      self.spawnCommand('rm', args).on('close', function() {
        self.copy();
        done();
      });
    });
  },

  copy: function() {
    const done = this.async();

    this.template('LICENSE');
    // this.template('README.md');
    this.template('editorconfig', '.editorconfig');
    this.template('_package.json', 'package.json');

    // Prepare FlyFile styles' path selector
    const ext = (this.cssTool == 'sass')
      ? '{sass,scss}' : (this.cssTool == 'stylus')
      ? 'styl' : this.cssTool;

    // Copy FlyFile
    this.template('flyfile', 'flyfile.js', {
      proxy: this.proxy,
      cssTool: this.cssTool,
      cssPath: "/styles/**/*."+ext
    });

    // Copy Static Assets, no alternatives
    const statics = ['fonts', 'images', 'scripts'];
    statics.forEach(function(s) {
      this.fs.copy(
        this.templatePath('assets/'+s),
        this.destinationPath('resources/assets/'+s)
      );
    }.bind(this));

    // Copy Style Assets, based on response
    this.fs.copy(
      this.templatePath('assets/styles/'+this.cssTool),
      this.destinationPath('resources/assets/styles')
    );

    const lint = this.props.useXO ? 'eslint_xo' : 'eslint_default';
    this.template(lint, '.eslintrc');

    if (this.props.gitinit) {
      this.template('gitignore', '.gitignore');
      this.template('gitattributes', '.gitattributes');
    }

    if (this.props.useTests) {
      this.fs.copy(
        this.templatePath('tests/' + this.testrunner),
        this.destinationPath('resources/tests')
      );
    }

    if (this.props.travis) {
      this.template('_travis.yml', '.travis.yml');
    }

    if (this.props.changelog) {
      this.template('changelog.md');
    }

    done();
  },

  install: function() {
    var plugins = [];
    if (this.testrunner) plugins.push('fly-'+this.testrunner);
    if (this.props.useProcessor) plugins.push('fly-'+this.cssTool);
    if (this.props.useXO) plugins.push('eslint-config-xo');

    this.spawnCommand('composer', ['install']);

    this.installDependencies({bower: false});
    this.npmInstall(plugins, {saveDev: true});
  },

  end: function() {
    if (!this.props.gitinit) return;

    const done = this.async();
    const self = this;

    console.log('\n');
    this.spawnCommand('git', ['init']).on('close', function() {
      self.spawnCommand('git', ['add', '--all']).on('close', function() {
        self.spawnCommand('git', ['commit', '-m', 'first commit, via generator-fly-laravel 🚀']).on('close', function() {
          console.log('\n');
          done();
        });
      });
    });
  }
});
<|endoftext|>


<commit_before>/**
 * @module player
 */

import { addAccessToken } from '@itslanguage/api/communication';

/**
 * Enum for available cross origin modes.
 * @enum {string}
 * @typedef CorsMode
 * @readonly
 */
export const CORS_MODE = {
  ANONYMOUS: 'anonymous',
  USE_CREDENTIALS: 'use-credentials',
};

/**
 * Factory function to create a HTMLAudioElement.
 * If requested, it is capable of adding "access_token" to the audioUrl. For some audio an user
 * needs to be authenticated to be able to playback some audio.
 *
 * Keep in mind you need a (valid) token to be able to add it!
 *
 * @param {string} [audioUrl=false] - Provide URL to load.
 * @param {boolean} [secureLoad=false] - If true, add `access_token` to the url. But only if
 * audioUrl was also passed and you have a valid token to communicate with the backend.
 * @param {CorsMode} [crossOrigin=null] - If passed, set player.crossOrigin to this value.
 * @throws {Error} If window.Audio does not exist.
 * @returns {HTMLAudioElement}
 */
export function createPlayer(audioUrl = null, secureLoad = false, crossOrigin = null) {
  if (!Audio) {
    throw new Error('Your browser is not capable of playing audio.');
  }

  const audio = new Audio();

  if (crossOrigin) {
    switch (crossOrigin) {
      case CORS_MODE.ANONYMOUS:
        audio.crossOrigin = CORS_MODE.ANONYMOUS;
        break;
      case CORS_MODE.USE_CREDENTIALS:
        audio.crossOrigin = CORS_MODE.USE_CREDENTIALS;
        break;
      default:
        throw new Error('Invalid value for crossOrigin passed');
    }
  }

  if (audioUrl) {
    audio.src = secureLoad
      ? addAccessToken(audioUrl)
      : audioUrl;
  }

  return audio;
}

/**
 * Load a (new) url to an instance of a HTMLAudioElement. Main purpose of this function is to
 * support a way to add a new url with an "access_token". But it also works for url's in general.
 *
 * Note that this function does not follow functional programming guidelines: it will adjust a
 * property of a given param directly (aka param reassign). Unfortunately this is currently the
 * only way to (re)set an url on a given element.
 *
 * There are some alternatives that opt for not using this function:
 * 1. If you want to set an url on an already defined audio player, and you do not care or want to
 * set the 'access_token', it is better to set the url directly to the audioElm.src property
 * yourself.
 * 2. You can also use the @itslanguage/api method 'addAccessToken` to add an access token to any
 * url. That is in fact what this function uses.
 *
 * So, why we still provide this function? Only for convenience!
 *
 * @param {HTMLAudioElement} player - Instance of an Audio object to set a new url on.
 * @param {string} audioUrl - The url to set.
 * @param {boolean} [secureLoad] - If true, add `access_token` to the url.
 * @returns {boolean|string} - It will return false if it could not set an url or it will return the
 * url that has been set.
 */
export function loadAudioUrl(player, audioUrl, secureLoad = false) {
  if (!(player instanceof HTMLAudioElement) || !audioUrl) {
    return false; // nothing to do here!
  }

  // The HTMLAudioElement, or any element this object extends on, does
  // not have a proper setter for the src property. So we need to re-assign
  // it here.

  // eslint-disable-next-line no-param-reassign
  player.src = secureLoad
    ? addAccessToken(audioUrl)
    : audioUrl;

  return player.src;
}
<commit_msg>refactor(player): use proper addAccessToken<commit_after>/**
 * @module player
 */

import { communication } from '@itslanguage/api';

/**
 * Enum for available cross origin modes.
 * @enum {string}
 * @typedef CorsMode
 * @readonly
 */
export const CORS_MODE = {
  ANONYMOUS: 'anonymous',
  USE_CREDENTIALS: 'use-credentials',
};

/**
 * Factory function to create a HTMLAudioElement.
 * If requested, it is capable of adding "access_token" to the audioUrl. For some audio an user
 * needs to be authenticated to be able to playback some audio.
 *
 * Keep in mind you need a (valid) token to be able to add it!
 *
 * @param {string} [audioUrl=false] - Provide URL to load.
 * @param {boolean} [secureLoad=false] - If true, add `access_token` to the url. But only if
 * audioUrl was also passed and you have a valid token to communicate with the backend.
 * @param {CorsMode} [crossOrigin=null] - If passed, set player.crossOrigin to this value.
 * @throws {Error} If window.Audio does not exist.
 * @returns {HTMLAudioElement}
 */
export function createPlayer(audioUrl = null, secureLoad = false, crossOrigin = null) {
  if (!Audio) {
    throw new Error('Your browser is not capable of playing audio.');
  }

  const audio = new Audio();

  if (crossOrigin) {
    switch (crossOrigin) {
      case CORS_MODE.ANONYMOUS:
        audio.crossOrigin = CORS_MODE.ANONYMOUS;
        break;
      case CORS_MODE.USE_CREDENTIALS:
        audio.crossOrigin = CORS_MODE.USE_CREDENTIALS;
        break;
      default:
        throw new Error('Invalid value for crossOrigin passed');
    }
  }

  if (audioUrl) {
    audio.src = secureLoad
      ? communication.addAccessToken(audioUrl)
      : audioUrl;
  }

  return audio;
}

/**
 * Load a (new) url to an instance of a HTMLAudioElement. Main purpose of this function is to
 * support a way to add a new url with an "access_token". But it also works for url's in general.
 *
 * Note that this function does not follow functional programming guidelines: it will adjust a
 * property of a given param directly (aka param reassign). Unfortunately this is currently the
 * only way to (re)set an url on a given element.
 *
 * There are some alternatives that opt for not using this function:
 * 1. If you want to set an url on an already defined audio player, and you do not care or want to
 * set the 'access_token', it is better to set the url directly to the audioElm.src property
 * yourself.
 * 2. You can also use the @itslanguage/api method 'addAccessToken` to add an access token to any
 * url. That is in fact what this function uses.
 *
 * So, why we still provide this function? Only for convenience!
 *
 * @param {HTMLAudioElement} player - Instance of an Audio object to set a new url on.
 * @param {string} audioUrl - The url to set.
 * @param {boolean} [secureLoad] - If true, add `access_token` to the url.
 * @returns {boolean|string} - It will return false if it could not set an url or it will return the
 * url that has been set.
 */
export function loadAudioUrl(player, audioUrl, secureLoad = false) {
  if (!(player instanceof HTMLAudioElement) || !audioUrl) {
    return false; // nothing to do here!
  }

  // The HTMLAudioElement, or any element this object extends on, does
  // not have a proper setter for the src property. So we need to re-assign
  // it here.

  // eslint-disable-next-line no-param-reassign
  player.src = secureLoad
    ? communication.addAccessToken(audioUrl)
    : audioUrl;

  return player.src;
}
<|endoftext|>


<commit_before><commit_msg>✨ Slimer: expose a dummy command<commit_after>const print = (...args) => console.log(...args); // eslint-disable-line no-console

module.exports.commands = [
    {
        id: 'new',
        flags: 'new <name>',
        aliases: ['create', 'project'],
        paramsDesc: ['Name for the project folder'],
        desc: 'Start a new project',
        run: (argv) => {
            print('Will evenually run yeoman to create', argv.name);
        }
    }
];
<|endoftext|>


<commit_before>var argv = require('yargs').argv;

var credentials = require('./saucelabs');
process.env.SAUCE_USERNAME = credentials.SAUCE_USERNAME;
process.env.SAUCE_ACCESS_KEY = credentials.SAUCE_ACCESS_KEY;

var customLaunchers = {
    sl_firefox_10: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '10'
    },
    sl_firefox_24: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '24'
    },
    sl_firefox_31: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '31'
    },
    sl_chrome_26: {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '26'
    },
    sl_chrome_33: {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '33'
    },
    sl_chrome_40: {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '40'
    },
    sl_chrome_latest: {
        base: 'SauceLabs',
        browserName: 'chrome'
    },
    sl_firefox_latest: {
        base: 'SauceLabs',
        browserName: 'firefox'
    },
    sl_safari_7: {
        base: 'SauceLabs',
        browserName: 'safari',
        version: '7'
    },
    sl_safari_8: {
        base: 'SauceLabs',
        browserName: 'safari',
        version: '8'
    },
    sl_ie_11: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
    },
    sl_ie_10: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
    },
    sl_opera_latest: {
        base: 'SauceLabs',
        browserName: 'opera'
    },
    sl_opera_12: {
        base: 'SauceLabs',
        browserName: 'opera',
        version: '12'
    }
};

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],

        autoWatch: false,
        singleRun: true,

        // browsers: ['Firefox'],
        browsers: argv.sauce ? Object.keys(customLaunchers) : ['Firefox'],

        files: [
            'node_modules/bluebird/js/browser/bluebird.js',
            'node_modules/route-node/node_modules/path-parser/dist/umd/path-parser.js',
            'node_modules/route-node/dist/umd/route-node.js',
            'dist/test/constants.js',
            'dist/test/async.js',
            'dist/test/transition.js',
            'dist/test/router5.js',
            'tests/*.js'
        ],

        preprocessors: {
          'dist/test/*.js': ['coverage']
        },

        plugins: [
            'karma-jasmine',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-mocha-reporter',
            'karma-coverage',
            'karma-coveralls',
            'karma-sauce-launcher'
        ],

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

        coverageReporter: {
            dir: 'coverage',
            reporters: [
                {type: 'lcov'}
            ],
        },

        sauceLabs: {
            testName: 'router5 Unit Tests',
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
            username: process.env.SAUCE_USERNAME,
            accessKey: process.env.SAUCE_ACCESS_KEY,
            startConnect: false
        },

        customLaunchers: customLaunchers
    });
};
<commit_msg>refactor: experiment with travis / saucelabs<commit_after>var argv = require('yargs').argv;

// var credentials = require('./saucelabs');
// process.env.SAUCE_USERNAME = credentials.SAUCE_USERNAME;
// process.env.SAUCE_ACCESS_KEY = credentials.SAUCE_ACCESS_KEY;

var customLaunchers = {
    sl_firefox_10: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '10'
    },
    sl_firefox_24: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '24'
    },
    sl_firefox_31: {
        base: 'SauceLabs',
        browserName: 'firefox',
        version: '31'
    },
    sl_chrome_26: {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '26'
    },
    sl_chrome_33: {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '33'
    },
    sl_chrome_40: {
        base: 'SauceLabs',
        browserName: 'chrome',
        version: '40'
    },
    sl_chrome_latest: {
        base: 'SauceLabs',
        browserName: 'chrome'
    },
    sl_firefox_latest: {
        base: 'SauceLabs',
        browserName: 'firefox'
    },
    sl_safari_7: {
        base: 'SauceLabs',
        browserName: 'safari',
        version: '7'
    },
    sl_safari_8: {
        base: 'SauceLabs',
        browserName: 'safari',
        version: '8'
    },
    sl_ie_11: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
    },
    sl_ie_10: {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
    },
    sl_opera_latest: {
        base: 'SauceLabs',
        browserName: 'opera'
    },
    sl_opera_12: {
        base: 'SauceLabs',
        browserName: 'opera',
        version: '12'
    }
};

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],

        autoWatch: false,
        singleRun: true,

        // browsers: ['Firefox'],
        browsers: argv.sauce ? Object.keys(customLaunchers) : ['Firefox'],

        files: [
            'node_modules/bluebird/js/browser/bluebird.js',
            'node_modules/route-node/node_modules/path-parser/dist/umd/path-parser.js',
            'node_modules/route-node/dist/umd/route-node.js',
            'dist/test/constants.js',
            'dist/test/async.js',
            'dist/test/transition.js',
            'dist/test/router5.js',
            'tests/*.js'
        ],

        preprocessors: {
          'dist/test/*.js': ['coverage']
        },

        plugins: [
            'karma-jasmine',
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-mocha-reporter',
            'karma-coverage',
            'karma-coveralls',
            'karma-sauce-launcher'
        ],

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

        coverageReporter: {
            dir: 'coverage',
            reporters: [
                {type: 'lcov'}
            ],
        },

        sauceLabs: {
            testName: 'router5 Unit Tests',
            startConnect: false
        },

        customLaunchers: customLaunchers
    });
};
<|endoftext|>


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

/**
 *
 * HeatTop JS Framework
 * Dependencies: jQuery 1.7.1 or later, d3 v3 or later
 * Date: June 2013
 * Description: JS Framework that subclasses the D3 Force Directed Graph library to create
 * Heat-specific objects and relationships with the purpose of displaying
 * Stacks, Resources, and related Properties in a Resource Topology Graph.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

var container = "#heat_resource_topology";

/* NOTE: The structure/architecture of this file (lots of global variables
 *       being referenced within stand-alone functions) means that
 *       "no-use-before-define" eslint warnings will be rampant.
 *       I don't believe there's any plan to overhaul this file, so let's not
 *       clutter up our eslint output with this file's singluar-but-repeated issue.
 */
/* eslint-disable no-use-before-define */

function update(){
  node = node.data(nodes, function(d) { return d.name; });
  link = link.data(links);

  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("node_name", function(d) { return d.name; })
    .attr("node_id", function(d) { return d.instance; })
    .call(force.drag);

  nodeEnter.append("image")
    .attr("xlink:href", function(d) { return d.image; })
    .attr("id", function(d){ return "image_"+ d.name; })
    .attr("x", function(d) { return d.image_x; })
    .attr("y", function(d) { return d.image_y; })
    .attr("width", function(d) { return d.image_size; })
    .attr("height", function(d) { return d.image_size; });
  node.exit().remove();

  link.enter().insert("svg:line", "g.node")
    .attr("class", "link")
    .style("stroke-width", function(d) { return Math.sqrt(d.value); });
  link.exit().remove();
  //Setup click action for all nodes
  node.on("mouseover", function(d) {
    $("#info_box").html(d.info_box);
  });
  node.on("mouseout", function() {
    $("#info_box").html('');
  });

  force.start();
}

function tick() {
  link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

  node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}

function set_in_progress(stack, nodes) {
  if (stack.in_progress === true) { in_progress = true; }
  for (var i = 0; i < nodes.length; i++) {
    var d = nodes[i];
    if (d.in_progress === true){ in_progress = true; return false; }
  }
}

function findNode(name) {
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].name === name){ return nodes[i]; }
  }
}

function findNodeIndex(name) {
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].name === name){ return i; }
  }
}

function addNode (node) {
  nodes.push(node);
  needs_update = true;
}

function removeNode (name) {
  var i = 0;
  var n = findNode(name);
  while (i < links.length) {
    if (links[i].source === n || links[i].target === n) {
      links.splice(i, 1);
    } else {
      i++;
    }
  }
  nodes.splice(findNodeIndex(name),1);
  needs_update = true;
}

function remove_nodes(old_nodes, new_nodes){
  //Check for removed nodes
  for (var i=0;i<old_nodes.length;i++) {
    var remove_node = true;
    for (var j=0;j<new_nodes.length;j++) {
      if (old_nodes[i].name === new_nodes[j].name){
        remove_node = false;
        break;
      }
    }
    if (remove_node === true){
      removeNode(old_nodes[i].name);
    }
  }
}

function build_links(){
  for (var i=0;i<nodes.length;i++){
    build_node_links(nodes[i]);
    build_reverse_links(nodes[i]);
  }
}

function build_node_links(node){
  for (var j=0;j<node.required_by.length;j++){
    var push_link = true;
    var target_idx = '';
    var source_idx = findNodeIndex(node.name);
    //make sure target node exists
    try {
      target_idx = findNodeIndex(node.required_by[j]);
    } catch(err) {
      push_link =false;
    }
    //check for duplicates
    for (var lidx=0;lidx<links.length;lidx++) {
      if (links[lidx].source === source_idx && links[lidx].target === target_idx) {
        push_link=false;
        break;
      }
    }

    if (push_link === true && (source_idx && target_idx)){
      links.push({
        'source':source_idx,
        'target':target_idx,
        'value':1
      });
    }
  }
}

function build_reverse_links(node){
  for (var i=0;i<nodes.length;i++){
    if(nodes[i].required_by){
      for (var j=0;j<nodes[i].required_by.length;j++){
        var dependency = nodes[i].required_by[j];
        //if new node is required by existing node, push new link
        if(node.name === dependency){
          links.push({
            'source':findNodeIndex(nodes[i].name),
            'target':findNodeIndex(node.name),
            'value':1
          });
        }
      }
    }
  }
}

function ajax_poll(poll_time){
  setTimeout(function() {
    $.getJSON(ajax_url, function(json) {
      //update d3 data element
      $("#d3_data").attr("data-d3_data", JSON.stringify(json));

      //update stack
      $("#stack_box").html(json.stack.info_box);
      set_in_progress(json.stack, json.nodes);
      needs_update = false;

      //Check Remove nodes
      remove_nodes(nodes, json.nodes);

      //Check for updates and new nodes
      json.nodes.forEach(function(d){
        var current_node = findNode(d.name);
        //Check if node already exists
        if (current_node) {
          //Node already exists, just update it
          current_node.status = d.status;

          //Status has changed, image should be updated
          if (current_node.image !== d.image){
            current_node.image = d.image;
            var this_image = d3.select("#image_"+current_node.name);
            this_image
              .transition()
              .attr("x", function(d) { return d.image_x + 5; })
              .duration(100)
              .transition()
              .attr("x", function(d) { return d.image_x - 5; })
              .duration(100)
              .transition()
              .attr("x", function(d) { return d.image_x + 5; })
              .duration(100)
              .transition()
              .attr("x", function(d) { return d.image_x - 5; })
              .duration(100)
              .transition()
              .attr("xlink:href", d.image)
              .transition()
              .attr("x", function(d) { return d.image_x; })
              .duration(100)
              .ease("bounce");
          }

          //Status has changed, update info_box
          current_node.info_box = d.info_box;

        } else {
          addNode(d);
          build_links();
        }
      });

      //if any updates needed, do update now
      if (needs_update === true){
        update();
      }
    });
    //if no nodes still in progress, slow AJAX polling
    if (in_progress === false) { poll_time = 30000; }
    else { poll_time = 3000; }
    ajax_poll(poll_time);
  }, poll_time);
}

/* eslint-disable no-use-before-define */

if ($(container).length){
  var width = $(container).width(),
    height = 500,
    stack_id = $("#stack_id").data("stack_id"),
    ajax_url = '/project/stacks/get_d3_data/' + stack_id + '/',
    graph = $("#d3_data").data("d3_data"),
    force = d3.layout.force()
      .nodes(graph.nodes)
      .links([])
      .gravity(0.1)
      .charge(-2000)
      .linkDistance(100)
      .size([width, height])
      .on("tick", tick),
    svg = d3.select(container).append("svg")
      .attr("width", width)
      .attr("height", height),
    node = svg.selectAll(".node"),
    link = svg.selectAll(".link"),
    needs_update = false,
    nodes = force.nodes(),
    links = force.links();

  build_links();
  update();

  //Load initial Stack box
  $("#stack_box").html(graph.stack.info_box);
  //On Page load, set Action In Progress
  var in_progress = false;
  set_in_progress(graph.stack, node);

  //If status is In Progress, start AJAX polling
  var poll_time = 0;
  if (in_progress === true) { poll_time = 3000; }
  else { poll_time = 30000; }
  ajax_poll(poll_time);
}
<commit_msg>Incorrect URL for polling heat stack<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

/**
 *
 * HeatTop JS Framework
 * Dependencies: jQuery 1.7.1 or later, d3 v3 or later
 * Date: June 2013
 * Description: JS Framework that subclasses the D3 Force Directed Graph library to create
 * Heat-specific objects and relationships with the purpose of displaying
 * Stacks, Resources, and related Properties in a Resource Topology Graph.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

var container = "#heat_resource_topology";

/* NOTE: The structure/architecture of this file (lots of global variables
 *       being referenced within stand-alone functions) means that
 *       "no-use-before-define" eslint warnings will be rampant.
 *       I don't believe there's any plan to overhaul this file, so let's not
 *       clutter up our eslint output with this file's singluar-but-repeated issue.
 */
/* eslint-disable no-use-before-define */

function update(){
  node = node.data(nodes, function(d) { return d.name; });
  link = link.data(links);

  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("node_name", function(d) { return d.name; })
    .attr("node_id", function(d) { return d.instance; })
    .call(force.drag);

  nodeEnter.append("image")
    .attr("xlink:href", function(d) { return d.image; })
    .attr("id", function(d){ return "image_"+ d.name; })
    .attr("x", function(d) { return d.image_x; })
    .attr("y", function(d) { return d.image_y; })
    .attr("width", function(d) { return d.image_size; })
    .attr("height", function(d) { return d.image_size; });
  node.exit().remove();

  link.enter().insert("svg:line", "g.node")
    .attr("class", "link")
    .style("stroke-width", function(d) { return Math.sqrt(d.value); });
  link.exit().remove();
  //Setup click action for all nodes
  node.on("mouseover", function(d) {
    $("#info_box").html(d.info_box);
  });
  node.on("mouseout", function() {
    $("#info_box").html('');
  });

  force.start();
}

function tick() {
  link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

  node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}

function set_in_progress(stack, nodes) {
  if (stack.in_progress === true) { in_progress = true; }
  for (var i = 0; i < nodes.length; i++) {
    var d = nodes[i];
    if (d.in_progress === true){ in_progress = true; return false; }
  }
}

function findNode(name) {
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].name === name){ return nodes[i]; }
  }
}

function findNodeIndex(name) {
  for (var i = 0; i < nodes.length; i++) {
    if (nodes[i].name === name){ return i; }
  }
}

function addNode (node) {
  nodes.push(node);
  needs_update = true;
}

function removeNode (name) {
  var i = 0;
  var n = findNode(name);
  while (i < links.length) {
    if (links[i].source === n || links[i].target === n) {
      links.splice(i, 1);
    } else {
      i++;
    }
  }
  nodes.splice(findNodeIndex(name),1);
  needs_update = true;
}

function remove_nodes(old_nodes, new_nodes){
  //Check for removed nodes
  for (var i=0;i<old_nodes.length;i++) {
    var remove_node = true;
    for (var j=0;j<new_nodes.length;j++) {
      if (old_nodes[i].name === new_nodes[j].name){
        remove_node = false;
        break;
      }
    }
    if (remove_node === true){
      removeNode(old_nodes[i].name);
    }
  }
}

function build_links(){
  for (var i=0;i<nodes.length;i++){
    build_node_links(nodes[i]);
    build_reverse_links(nodes[i]);
  }
}

function build_node_links(node){
  for (var j=0;j<node.required_by.length;j++){
    var push_link = true;
    var target_idx = '';
    var source_idx = findNodeIndex(node.name);
    //make sure target node exists
    try {
      target_idx = findNodeIndex(node.required_by[j]);
    } catch(err) {
      push_link =false;
    }
    //check for duplicates
    for (var lidx=0;lidx<links.length;lidx++) {
      if (links[lidx].source === source_idx && links[lidx].target === target_idx) {
        push_link=false;
        break;
      }
    }

    if (push_link === true && (source_idx && target_idx)){
      links.push({
        'source':source_idx,
        'target':target_idx,
        'value':1
      });
    }
  }
}

function build_reverse_links(node){
  for (var i=0;i<nodes.length;i++){
    if(nodes[i].required_by){
      for (var j=0;j<nodes[i].required_by.length;j++){
        var dependency = nodes[i].required_by[j];
        //if new node is required by existing node, push new link
        if(node.name === dependency){
          links.push({
            'source':findNodeIndex(nodes[i].name),
            'target':findNodeIndex(node.name),
            'value':1
          });
        }
      }
    }
  }
}

function ajax_poll(poll_time){
  setTimeout(function() {
    $.getJSON(ajax_url, function(json) {
      //update d3 data element
      $("#d3_data").attr("data-d3_data", JSON.stringify(json));

      //update stack
      $("#stack_box").html(json.stack.info_box);
      set_in_progress(json.stack, json.nodes);
      needs_update = false;

      //Check Remove nodes
      remove_nodes(nodes, json.nodes);

      //Check for updates and new nodes
      json.nodes.forEach(function(d){
        var current_node = findNode(d.name);
        //Check if node already exists
        if (current_node) {
          //Node already exists, just update it
          current_node.status = d.status;

          //Status has changed, image should be updated
          if (current_node.image !== d.image){
            current_node.image = d.image;
            var this_image = d3.select("#image_"+current_node.name);
            this_image
              .transition()
              .attr("x", function(d) { return d.image_x + 5; })
              .duration(100)
              .transition()
              .attr("x", function(d) { return d.image_x - 5; })
              .duration(100)
              .transition()
              .attr("x", function(d) { return d.image_x + 5; })
              .duration(100)
              .transition()
              .attr("x", function(d) { return d.image_x - 5; })
              .duration(100)
              .transition()
              .attr("xlink:href", d.image)
              .transition()
              .attr("x", function(d) { return d.image_x; })
              .duration(100)
              .ease("bounce");
          }

          //Status has changed, update info_box
          current_node.info_box = d.info_box;

        } else {
          addNode(d);
          build_links();
        }
      });

      //if any updates needed, do update now
      if (needs_update === true){
        update();
      }
    });
    //if no nodes still in progress, slow AJAX polling
    if (in_progress === false) { poll_time = 30000; }
    else { poll_time = 3000; }
    ajax_poll(poll_time);
  }, poll_time);
}

/* eslint-disable no-use-before-define */
if ($(container).length){
  var width = $(container).width(),
    height = 500,
    stack_id = $("#stack_id").data("stack_id"),
    ajax_url = WEBROOT + 'project/stacks/get_d3_data/' + stack_id + '/',
    graph = $("#d3_data").data("d3_data"),
    force = d3.layout.force()
      .nodes(graph.nodes)
      .links([])
      .gravity(0.1)
      .charge(-2000)
      .linkDistance(100)
      .size([width, height])
      .on("tick", tick),
    svg = d3.select(container).append("svg")
      .attr("width", width)
      .attr("height", height),
    node = svg.selectAll(".node"),
    link = svg.selectAll(".link"),
    needs_update = false,
    nodes = force.nodes(),
    links = force.links();

  build_links();
  update();

  //Load initial Stack box
  $("#stack_box").html(graph.stack.info_box);
  //On Page load, set Action In Progress
  var in_progress = false;
  set_in_progress(graph.stack, node);

  //If status is In Progress, start AJAX polling
  var poll_time = 0;
  if (in_progress === true) { poll_time = 3000; }
  else { poll_time = 30000; }
  ajax_poll(poll_time);
}
<|endoftext|>


<commit_before>/* global document */
/* global window */
/* global localStorage */
/* global XMLHttpRequest */
/* jshint -W107 */

var util = {

  url: {
    remote: 'http://jdh11235.github.io/jsGameHacks/',
    local: 'http://localhost:8000/'
  },

  cleanWhitespace: function(text) {
    return text.replace(/[\040\n]/gi, '%20');
  },

  fetchTextFile: function(url) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    return xmlhttp.responseText;
  },

  makeAttacherMarklet: function(url) {
    var fn_pre = util.fetchTextFile('templates/attacherMarklet.js');
    var fn = fn_pre.replace(/\$URL/g, url);

    var prefix = 'javascript:{';
    var suffix = '};void(0)';

    var marklet_pre = prefix + fn + suffix;
    var marklet = util.cleanWhitespace(marklet_pre);

    return(marklet);
  },

  expandURL: function(url) {
    return localStorage.urlBase + url + '.js';
  },

  convertToMarklet: function(elm) {
    var url = util.expandURL(elm.innerHTML);
    elm.href = util.makeAttacherMarklet(url);

    if (localStorage.urlBase == util.url.local) {
      elm.innerHTML = '*' + elm.innerHTML;
    }

    elm.addEventListener('click', function(event) {
      event.preventDefault();
      console.log(elm.innerHTML + ' ' + elm.href);
    });
  },

  autoMarkletBoxes: function() {
    var containers = document.getElementsByClassName('marklet-box');
    for (var i = 0; i < containers.length; i++) {
      util.convertToMarklet(containers[i]);
    }
  },

  checkSrc: function() {
    var statusBox = document.getElementById('srcStatus');

    if (!localStorage.urlBase) {
      localStorage.urlBase = util.url.remote;
    } else if (localStorage.urlBase == util.url.local) {
       statusBox.innerHTML = 'local';
    } else if (localStorage.urlBase == util.url.remote) {
      statusBox.innerHTML = '';
    }
  },

  switchSrc: function() {
    if (localStorage.urlBase == util.url.remote) {
      localStorage.urlBase = util.url.local;
    } else if (localStorage.urlBase == util.url.local) {
      localStorage.urlBase = util.url.remote;
    }

    util.checkSrc();
    util.autoMarkletBoxes();
  },

  init: function() {
    util.checkSrc();
    util.autoMarkletBoxes();

    console.log('To switch marklet sources, util.switchSrc()');
  }

};

window.addEventListener('load', util.init);
<commit_msg>fix local * not being removed when switchSrc()<commit_after>/* global document */
/* global window */
/* global localStorage */
/* global XMLHttpRequest */
/* jshint -W107 */

var util = {

  url: {
    remote: 'http://jdh11235.github.io/jsGameHacks/',
    local: 'http://localhost:8000/'
  },

  cleanWhitespace: function(text) {
    return text.replace(/[\040\n]/gi, '%20');
  },

  fetchTextFile: function(url) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    return xmlhttp.responseText;
  },

  makeAttacherMarklet: function(url) {
    var fn_pre = util.fetchTextFile('templates/attacherMarklet.js');
    var fn = fn_pre.replace(/\$URL/g, url);

    var prefix = 'javascript:{';
    var suffix = '};void(0)';

    var marklet_pre = prefix + fn + suffix;
    var marklet = util.cleanWhitespace(marklet_pre);

    return(marklet);
  },

  expandURL: function(url) {
    return localStorage.urlBase + url + '.js';
  },

  convertToMarklet: function(elm) {
    var url = util.expandURL(elm.innerHTML);
    elm.href = util.makeAttacherMarklet(url);

    if (localStorage.urlBase == util.url.local) {
      elm.innerHTML = '*' + elm.innerHTML;
    } else {
      elm.innerHTML = elm.innerHTML.replace(/\*/g, '');
    }

    elm.addEventListener('click', function(event) {
      event.preventDefault();
      console.log(elm.innerHTML + ' ' + elm.href);
    });
  },

  autoMarkletBoxes: function() {
    var containers = document.getElementsByClassName('marklet-box');
    for (var i = 0; i < containers.length; i++) {
      util.convertToMarklet(containers[i]);
    }
  },

  checkSrc: function() {
    var statusBox = document.getElementById('srcStatus');

    if (!localStorage.urlBase) {
      localStorage.urlBase = util.url.remote;
    } else if (localStorage.urlBase == util.url.local) {
       statusBox.innerHTML = 'local';
    } else if (localStorage.urlBase == util.url.remote) {
      statusBox.innerHTML = '';
    }
  },

  switchSrc: function() {
    if (localStorage.urlBase == util.url.remote) {
      localStorage.urlBase = util.url.local;
    } else if (localStorage.urlBase == util.url.local) {
      localStorage.urlBase = util.url.remote;
    }

    util.checkSrc();
    util.autoMarkletBoxes();
  },

  init: function() {
    util.checkSrc();
    util.autoMarkletBoxes();

    console.log('To enable local marklet sources, util.switchSrc()');
  }

};

window.addEventListener('load', util.init);
<|endoftext|>


<commit_before>var cookie = require('cookie')
var yargs = require('yargs')
var URL = require('url')
var querystring = require('querystring')

/**
 * given this: [ 'msg1=value1', 'msg2=value2' ]
 * output this: 'msg1=value1&msg2=value2'
 * @param dataArguments
 */
var joinDataArguments = function (dataArguments) {
  var data = ''
  dataArguments.forEach(function (argument, i) {
    if (i === 0) {
      data += argument
    } else {
      data += '&' + argument
    }
  })
  return data
}

var parseCurlCommand = function (curlCommand) {
  var newlineFound = /\r|\n/.exec(curlCommand)
  if (newlineFound) {
    // remove newlines
    curlCommand = curlCommand.replace(/\\\r|\\\n/g, '')
  }
  // yargs parses -XPOST as separate arguments. just prescreen for it.
  curlCommand = curlCommand.replace(/ -XPOST/, ' -X POST')
  curlCommand = curlCommand.replace(/ -XGET/, ' -X GET')
  curlCommand = curlCommand.replace(/ -XPUT/, ' -X PUT')
  curlCommand = curlCommand.replace(/ -XPATCH/, ' -X PATCH')
  curlCommand = curlCommand.replace(/ -XDELETE/, ' -X DELETE')
  curlCommand = curlCommand.trim()
  var yargObject = yargs(curlCommand)
  var parsedArguments = yargObject.argv
  var cookieString
  var cookies
  var url = parsedArguments._[1]
  // if url argument wasn't where we expected it, try to find it in the other arguments
  if (!url) {
    for (var argName in parsedArguments) {
      if (typeof parsedArguments[argName] === 'string') {
        if (parsedArguments[argName].indexOf('http') === 0 || parsedArguments[argName].indexOf('www.') === 0) {
          url = parsedArguments[argName]
        }
      }
    }
  }

  var headers

  var parseHeaders = function (headerFieldName) {
    if (parsedArguments[headerFieldName]) {
      if (!headers) {
        headers = {}
      }
      if (!Array.isArray(parsedArguments[headerFieldName])) {
        parsedArguments[headerFieldName] = [parsedArguments[headerFieldName]]
      }
      parsedArguments[headerFieldName].forEach(function (header) {
        if (header.indexOf('Cookie') !== -1) {
          // stupid javascript tricks: closure
          cookieString = header
        } else {
          var colonIndex = header.indexOf(':')
          var headerName = header.substring(0, colonIndex)
          var headerValue = header.substring(colonIndex + 1).trim()
          headers[headerName] = headerValue
        }
      })
    }
  }

  parseHeaders('H')
  parseHeaders('header')
  if (parsedArguments.A) {
    if (!headers) {
      headers = []
    }
    headers['User-Agent'] = parsedArguments.A
  } else if (parsedArguments['user-agent']) {
    if (!headers) {
      headers = []
    }
    headers['User-Agent'] = parsedArguments['user-agent']
  }

  if (parsedArguments.b) {
    cookieString = parsedArguments.b
  }
  if (parsedArguments.cookie) {
    cookieString = parsedArguments.cookie
  }
  var multipartUploads
  if (parsedArguments.F) {
    multipartUploads = {}
    if (!Array.isArray(parsedArguments.F)) {
      parsedArguments.F = [parsedArguments.F]
    }
    parsedArguments.F.forEach(function (multipartArgument) {
      // input looks like key=value. value could be json or a file path prepended with an @
      var splitArguments = multipartArgument.split('=', 2)
      var key = splitArguments[0]
      var value = splitArguments[1]
      multipartUploads[key] = value
    })
  }
  if (cookieString) {
    var cookieParseOptions = {
      decode: function (s) { return s }
    }
    cookies = cookie.parse(cookieString.replace('Cookie: ', ''), cookieParseOptions)
  }
  var method
  if (parsedArguments.X === 'POST') {
    method = 'post'
  } else if (parsedArguments.X === 'PUT' ||
    parsedArguments['T']) {
    method = 'put'
  } else if (parsedArguments.X === 'PATCH') {
    method = 'patch'
  } else if (parsedArguments.X === 'DELETE') {
    method = 'delete'
  } else if (parsedArguments.X === 'OPTIONS') {
    method = 'options'
  } else if ((parsedArguments['d'] ||
    parsedArguments['data'] ||
    parsedArguments['data-binary'] ||
    parsedArguments['F'] ||
    parsedArguments['form']) && !((parsedArguments['G'] || parsedArguments['get']))) {
    method = 'post'
  } else if (parsedArguments['I'] ||
    parsedArguments['head']) {
    method = 'head'
  } else {
    method = 'get'
  }

  var compressed = !!parsedArguments.compressed
  var urlObject = URL.parse(url) // eslint-disable-line

  // if GET request with data, convert data to query string
  // NB: the -G flag does not change the http verb. It just moves the data into the url.
  if (parsedArguments['G'] || parsedArguments['get']) {
    urlObject.query = urlObject.query ? urlObject.query : ''
    var option = 'd' in parsedArguments ? 'd' : 'data' in parsedArguments ? 'data' : null
    if (option) {
      var urlQueryString = ''

      if (url.indexOf('?') < 0) {
        url += '?'
      } else {
        urlQueryString += '&'
      }

      if (typeof (parsedArguments[option]) === 'object') {
        urlQueryString += parsedArguments[option].join('&')
      } else {
        urlQueryString += parsedArguments[option]
      }
      urlObject.query += urlQueryString
      url += urlQueryString
      delete parsedArguments[option]
    }
  }
  var query = querystring.parse(urlObject.query, null, null, { maxKeys: 10000 })

  urlObject.search = null // Clean out the search/query portion.
  var request = {
    url: url,
    urlWithoutQuery: URL.format(urlObject)
  }
  if (compressed) {
    request['compressed'] = true
  }

  if (Object.keys(query).length > 0) {
    request.query = query
  }
  if (headers) {
    request.headers = headers
  }
  request['method'] = method

  if (cookies) {
    request.cookies = cookies
    request.cookieString = cookieString.replace('Cookie: ', '')
  }
  if (multipartUploads) {
    request.multipartUploads = multipartUploads
  }
  if (parsedArguments.data) {
    request.data = parsedArguments.data
  } else if (parsedArguments['data-binary']) {
    request.data = parsedArguments['data-binary']
    request.isDataBinary = true
  } else if (parsedArguments['d']) {
    request.data = parsedArguments['d']
  }

  if (parsedArguments['u']) {
    request.auth = parsedArguments['u']
  }
  if (parsedArguments['user']) {
    request.auth = parsedArguments['user']
  }
  if (Array.isArray(request.data)) {
    request.dataArray = request.data
    request.data = joinDataArguments(request.data)
  }

  if (parsedArguments['k'] || parsedArguments['insecure']) {
    request.insecure = true
  }
  return request
}

var serializeCookies = function (cookieDict) {
  var cookieString = ''
  var i = 0
  var cookieCount = Object.keys(cookieDict).length
  for (var cookieName in cookieDict) {
    var cookieValue = cookieDict[cookieName]
    cookieString += cookieName + '=' + cookieValue
    if (i < cookieCount - 1) {
      cookieString += '; '
    }
    i++
  }
  return cookieString
}

module.exports = {
  parseCurlCommand: parseCurlCommand,
  serializeCookies: serializeCookies
}
<commit_msg>parser regex for starts with cookie, case insensitive<commit_after>var cookie = require('cookie')
var yargs = require('yargs')
var URL = require('url')
var querystring = require('querystring')

/**
 * given this: [ 'msg1=value1', 'msg2=value2' ]
 * output this: 'msg1=value1&msg2=value2'
 * @param dataArguments
 */
var joinDataArguments = function (dataArguments) {
  var data = ''
  dataArguments.forEach(function (argument, i) {
    if (i === 0) {
      data += argument
    } else {
      data += '&' + argument
    }
  })
  return data
}

var parseCurlCommand = function (curlCommand) {
  var newlineFound = /\r|\n/.exec(curlCommand)
  if (newlineFound) {
    // remove newlines
    curlCommand = curlCommand.replace(/\\\r|\\\n/g, '')
  }
  // yargs parses -XPOST as separate arguments. just prescreen for it.
  curlCommand = curlCommand.replace(/ -XPOST/, ' -X POST')
  curlCommand = curlCommand.replace(/ -XGET/, ' -X GET')
  curlCommand = curlCommand.replace(/ -XPUT/, ' -X PUT')
  curlCommand = curlCommand.replace(/ -XPATCH/, ' -X PATCH')
  curlCommand = curlCommand.replace(/ -XDELETE/, ' -X DELETE')
  curlCommand = curlCommand.trim()
  var yargObject = yargs(curlCommand)
  var parsedArguments = yargObject.argv
  var cookieString
  var cookies
  var url = parsedArguments._[1]
  // if url argument wasn't where we expected it, try to find it in the other arguments
  if (!url) {
    for (var argName in parsedArguments) {
      if (typeof parsedArguments[argName] === 'string') {
        if (parsedArguments[argName].indexOf('http') === 0 || parsedArguments[argName].indexOf('www.') === 0) {
          url = parsedArguments[argName]
        }
      }
    }
  }

  var headers

  var parseHeaders = function (headerFieldName) {
    if (parsedArguments[headerFieldName]) {
      if (!headers) {
        headers = {}
      }
      if (!Array.isArray(parsedArguments[headerFieldName])) {
        parsedArguments[headerFieldName] = [parsedArguments[headerFieldName]]
      }
      parsedArguments[headerFieldName].forEach(function (header) {
        if (header.indexOf('Cookie') !== -1) {
          // stupid javascript tricks: closure
          cookieString = header
        } else {
          var colonIndex = header.indexOf(':')
          var headerName = header.substring(0, colonIndex)
          var headerValue = header.substring(colonIndex + 1).trim()
          headers[headerName] = headerValue
        }
      })
    }
  }

  parseHeaders('H')
  parseHeaders('header')
  if (parsedArguments.A) {
    if (!headers) {
      headers = []
    }
    headers['User-Agent'] = parsedArguments.A
  } else if (parsedArguments['user-agent']) {
    if (!headers) {
      headers = []
    }
    headers['User-Agent'] = parsedArguments['user-agent']
  }

  if (parsedArguments.b) {
    cookieString = parsedArguments.b
  }
  if (parsedArguments.cookie) {
    cookieString = parsedArguments.cookie
  }
  var multipartUploads
  if (parsedArguments.F) {
    multipartUploads = {}
    if (!Array.isArray(parsedArguments.F)) {
      parsedArguments.F = [parsedArguments.F]
    }
    parsedArguments.F.forEach(function (multipartArgument) {
      // input looks like key=value. value could be json or a file path prepended with an @
      var splitArguments = multipartArgument.split('=', 2)
      var key = splitArguments[0]
      var value = splitArguments[1]
      multipartUploads[key] = value
    })
  }
  if (cookieString) {
    var cookieParseOptions = {
      decode: function (s) { return s }
    }
    // separate out cookie headers into separate data structure
    // note: cookie is case insensitive
    cookies = cookie.parse(cookieString.replace(/^Cookie: /gi, ''), cookieParseOptions)
  }
  var method
  if (parsedArguments.X === 'POST') {
    method = 'post'
  } else if (parsedArguments.X === 'PUT' ||
    parsedArguments['T']) {
    method = 'put'
  } else if (parsedArguments.X === 'PATCH') {
    method = 'patch'
  } else if (parsedArguments.X === 'DELETE') {
    method = 'delete'
  } else if (parsedArguments.X === 'OPTIONS') {
    method = 'options'
  } else if ((parsedArguments['d'] ||
    parsedArguments['data'] ||
    parsedArguments['data-binary'] ||
    parsedArguments['F'] ||
    parsedArguments['form']) && !((parsedArguments['G'] || parsedArguments['get']))) {
    method = 'post'
  } else if (parsedArguments['I'] ||
    parsedArguments['head']) {
    method = 'head'
  } else {
    method = 'get'
  }

  var compressed = !!parsedArguments.compressed
  var urlObject = URL.parse(url) // eslint-disable-line

  // if GET request with data, convert data to query string
  // NB: the -G flag does not change the http verb. It just moves the data into the url.
  if (parsedArguments['G'] || parsedArguments['get']) {
    urlObject.query = urlObject.query ? urlObject.query : ''
    var option = 'd' in parsedArguments ? 'd' : 'data' in parsedArguments ? 'data' : null
    if (option) {
      var urlQueryString = ''

      if (url.indexOf('?') < 0) {
        url += '?'
      } else {
        urlQueryString += '&'
      }

      if (typeof (parsedArguments[option]) === 'object') {
        urlQueryString += parsedArguments[option].join('&')
      } else {
        urlQueryString += parsedArguments[option]
      }
      urlObject.query += urlQueryString
      url += urlQueryString
      delete parsedArguments[option]
    }
  }
  var query = querystring.parse(urlObject.query, null, null, { maxKeys: 10000 })

  urlObject.search = null // Clean out the search/query portion.
  var request = {
    url: url,
    urlWithoutQuery: URL.format(urlObject)
  }
  if (compressed) {
    request['compressed'] = true
  }

  if (Object.keys(query).length > 0) {
    request.query = query
  }
  if (headers) {
    request.headers = headers
  }
  request['method'] = method

  if (cookies) {
    request.cookies = cookies
    request.cookieString = cookieString.replace('Cookie: ', '')
  }
  if (multipartUploads) {
    request.multipartUploads = multipartUploads
  }
  if (parsedArguments.data) {
    request.data = parsedArguments.data
  } else if (parsedArguments['data-binary']) {
    request.data = parsedArguments['data-binary']
    request.isDataBinary = true
  } else if (parsedArguments['d']) {
    request.data = parsedArguments['d']
  }

  if (parsedArguments['u']) {
    request.auth = parsedArguments['u']
  }
  if (parsedArguments['user']) {
    request.auth = parsedArguments['user']
  }
  if (Array.isArray(request.data)) {
    request.dataArray = request.data
    request.data = joinDataArguments(request.data)
  }

  if (parsedArguments['k'] || parsedArguments['insecure']) {
    request.insecure = true
  }
  return request
}

var serializeCookies = function (cookieDict) {
  var cookieString = ''
  var i = 0
  var cookieCount = Object.keys(cookieDict).length
  for (var cookieName in cookieDict) {
    var cookieValue = cookieDict[cookieName]
    cookieString += cookieName + '=' + cookieValue
    if (i < cookieCount - 1) {
      cookieString += '; '
    }
    i++
  }
  return cookieString
}

module.exports = {
  parseCurlCommand: parseCurlCommand,
  serializeCookies: serializeCookies
}
<|endoftext|>


<commit_before>var path = require('path')
var pull = require('pull-stream')
var split = require('pull-split')
var core  = require('./core')

var ancestors =
exports.ancestors =
function (dir) {
  dir = dir || process.cwd()
  var paths = []

  while(dir) {
    paths.push(dir)
    dir = path.dirname(dir)
    if(dir === '/') {
      paths.push(dir)
      break
    }
  }

  return pull.values(paths)
}

var wc =
exports.wc =
function () {
  return pull.asyncMap(function (file, cb) {
    var data = {lines: 0, chars:0, words: 0, file: file}

    core.read(file)
    .pipe(split())
    .pipe(pull.reduce(function (total, line) {
      total.lines ++
      total.chars += line.length + 1 //+1 for new line
      //note, splitting, since it creates an array,
      //will not be the most optimal method.
      total.words +=
        line.split(/\s+/)
        .reduce(function (s, i) {
          return s + (i ? 1 : 0)
        }, 0)

      return total
    }, data, cb))
  })
}

var star =
exports.star =
function (match) {
  return pull.map(function (dir) {
    return core.readdir(dir)
  })
  .pipe(pull.flatten())
  .pipe(pull.filter(match))
}

var resolve =
exports.resolve =
function (rel) {
 return pull.map(function (dir) { //map to $dir/node_modules
    return path.resolve(dir, rel)
  })
}

<commit_msg>filterable star and starStar<commit_after>var path = require('path')
var pull = require('pull-stream')
var split = require('pull-split')
var core  = require('./core')
var fs    = require('fs')

var ancestors =
exports.ancestors =
function (dir) {
  dir = dir || process.cwd()
  var paths = []

  while(dir) {
    paths.push(dir)
    dir = path.dirname(dir)
    if(dir === '/') {
      paths.push(dir)
      break
    }
  }

  return pull.values(paths)
}

var wc =
exports.wc =
function () {
  return pull.asyncMap(function (file, cb) {
    var data = {lines: 0, chars:0, words: 0, file: file}

    core.read(file)
    .pipe(split())
    .pipe(pull.reduce(function (total, line) {
      total.lines ++
      total.chars += line.length + 1 //+1 for new line
      //note, splitting, since it creates an array,
      //will not be the most optimal method.
      total.words +=
        line.split(/\s+/)
        .reduce(function (s, i) {
          return s + (i ? 1 : 0)
        }, 0)

      return total
    }, data, cb))
  })
}

var star =
exports.star =
function (match) {
  return pull.map(function (dir) {
    return core.readdir(dir, match)
  })
  .pipe(pull.flatten())
  .pipe(pull.filter())
}

var starStar =
exports.starStar =
function (match) {
  var seen = {}
  return pull.map(function (dir) {
    return pull.depthFirst(dir, function (_dir) {
      return core.readdir(_dir, match)
      .pipe(pull.filter(function (e) {
        if(seen[e]) return false
        return seen[e] = true
      }))
    })
  })
  .pipe(pull.flatten())
  .pipe(pull.filter())
}

var resolve =
exports.resolve =
function (rel) {
 return pull.map(function (dir) { //map to $dir/node_modules
    if(rel)
      return path.resolve(dir, rel)
    return path.resolve(dir)
  })
}

var relative =
exports.relative =
function (rel) {
  rel = rel || process.cwd()
  return pull.map(function (file) {
    return path.relative(rel, file)
  })
}

var absolute =
exports.absolute =
function () {
  return resolve()
}

var read =
exports.read = function (parse) {
  return pull.asyncMap(function (file, cb) {
    fs.readFile(file, 'utf-8', function (err, data) {
      if(err) return cb(err)
      try {
         data = parse ? parse(data) : data
      } catch (err) {
        return cb(err)
      }
      return cb(null, data)
    })
  })
}

<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var github = require('github-from-package')
var home = require('os-homedir')
var cp = require('child_process')
var expandTemplate = require('expand-template')()
var error = require('./error')

function getDownloadUrl (opts) {
  var pkgName = opts.pkg.name.replace(/^@\w+\//, '')
  return expandTemplate(urlTemplate(opts), {
    name: pkgName,
    package_name: pkgName,
    version: opts.pkg.version,
    major: opts.pkg.version.split('.')[0],
    minor: opts.pkg.version.split('.')[1],
    patch: opts.pkg.version.split('.')[2],
    prerelease: opts.pkg.version.split('-')[1],
    build: opts.pkg.version.split('+')[1],
    abi: opts.abi || process.versions.modules,
    node_abi: process.versions.modules,
    platform: opts.platform,
    arch: opts.arch,
    libc: opts.libc || '',
    configuration: (opts.debug ? 'Debug' : 'Release'),
    module_name: opts.pkg.binary && opts.pkg.binary.module_name
  })
}

function urlTemplate (opts) {
  if (typeof opts.download === 'string') {
    return opts.download
  }

  var packageName = '{name}-v{version}-node-v{abi}-{platform}{libc}-{arch}.tar.gz'
  if (opts.pkg.binary) {
    return [
      opts.pkg.binary.host,
      opts.pkg.binary.remote_path,
      opts.pkg.binary.package_name || packageName
    ].map(function (path) {
      return trimSlashes(path)
    }).filter(Boolean).join('/')
  }
  return github(opts.pkg) + '/releases/download/v{version}/' + packageName
}

function trimSlashes (str) {
  if (str) return str.replace(/^\.\/|^\/|\/$/g, '')
}

function cachedPrebuild (url) {
  return path.join(prebuildCache(), url.replace(/[^a-zA-Z0-9.]+/g, '-'))
}

function npmCache () {
  return process.env.APPDATA ? path.join(process.env.APPDATA, 'npm-cache') : path.join(home(), '.npm')
}

function prebuildCache () {
  return path.join(npmCache(), '_prebuilds')
}

function tempFile (cached) {
  return cached + '.' + process.pid + '-' + Math.random().toString(16).slice(2) + '.tmp'
}

function getTarPath (opts, abi) {
  return path.join('prebuilds', [
    opts.pkg.name,
    '-v', opts.pkg.version,
    '-node-v', abi,
    '-', opts.platform,
    '-', opts.arch,
    opts.libc,
    '.tar.gz'
  ].join(''))
}

function localPrebuild (url) {
  return path.join('prebuilds', path.basename(url))
}

function readGypFile (opts, cb) {
  var version = opts.version
  var file = opts.file
  var dir = '.' + (opts.backend || 'node-gyp')
  fs.exists(path.join(nodeGypPath(dir), 'iojs-' + version), function (isIojs) {
    if (isIojs) version = 'iojs-' + version
    fs.exists(nodeGypPath(dir, version, 'include/node'), function (exists) {
      if (exists) {
        fs.readFile(nodeGypPath(dir, version, 'include/node', file), 'utf-8', cb)
      } else {
        fs.readFile(nodeGypPath(dir, version, 'src', file), 'utf-8', cb)
      }
    })
  })
}

function nodeGypPath () {
  var args = [].slice.call(arguments)
  return path.join(home(), args.join('/'))
}

function spawn (cmd, args, cb) {
  args = args || []
  if (typeof args === 'function') {
    cb = args
    args = []
  }
  return cp.spawn(cmd, args, {stdio: 'inherit'}).on('exit', function (code) {
    if (code === 0) return cb()
    cb(error.spawnFailed(cmd, args, code))
  })
}

function platform () {
  return process.platform
}

function releaseFolder (opts, version) {
  var type = (opts.debug ? 'Debug' : 'Release')
  var binary = opts.pkg.binary
  if (opts.backend === 'node-ninja') {
    return (binary && binary.module_path) || 'build/' + version + '/' + type
  } else {
    return (binary && binary.module_path) || 'build/' + type
  }
}

exports.getDownloadUrl = getDownloadUrl
exports.urlTemplate = urlTemplate
exports.cachedPrebuild = cachedPrebuild
exports.localPrebuild = localPrebuild
exports.prebuildCache = prebuildCache
exports.npmCache = npmCache
exports.tempFile = tempFile
exports.getTarPath = getTarPath
exports.readGypFile = readGypFile
exports.spawn = spawn
exports.platform = platform
exports.releaseFolder = releaseFolder
exports.nodeGypPath = nodeGypPath
<commit_msg>Fix tar name<commit_after>var fs = require('fs')
var path = require('path')
var github = require('github-from-package')
var home = require('os-homedir')
var cp = require('child_process')
var expandTemplate = require('expand-template')()
var error = require('./error')

function getDownloadUrl (opts) {
  var pkgName = opts.pkg.name.replace(/^@\w+\//, '')
  return expandTemplate(urlTemplate(opts), {
    name: pkgName,
    package_name: pkgName,
    version: opts.pkg.version,
    major: opts.pkg.version.split('.')[0],
    minor: opts.pkg.version.split('.')[1],
    patch: opts.pkg.version.split('.')[2],
    prerelease: opts.pkg.version.split('-')[1],
    build: opts.pkg.version.split('+')[1],
    abi: opts.abi || process.versions.modules,
    node_abi: process.versions.modules,
    platform: opts.platform,
    arch: opts.arch,
    libc: opts.libc || '',
    configuration: (opts.debug ? 'Debug' : 'Release'),
    module_name: opts.pkg.binary && opts.pkg.binary.module_name
  })
}

function urlTemplate (opts) {
  if (typeof opts.download === 'string') {
    return opts.download
  }

  var packageName = '{name}-v{version}-node-v{abi}-{platform}{libc}-{arch}.tar.gz'
  if (opts.pkg.binary) {
    return [
      opts.pkg.binary.host,
      opts.pkg.binary.remote_path,
      opts.pkg.binary.package_name || packageName
    ].map(function (path) {
      return trimSlashes(path)
    }).filter(Boolean).join('/')
  }
  return github(opts.pkg) + '/releases/download/v{version}/' + packageName
}

function trimSlashes (str) {
  if (str) return str.replace(/^\.\/|^\/|\/$/g, '')
}

function cachedPrebuild (url) {
  return path.join(prebuildCache(), url.replace(/[^a-zA-Z0-9.]+/g, '-'))
}

function npmCache () {
  return process.env.APPDATA ? path.join(process.env.APPDATA, 'npm-cache') : path.join(home(), '.npm')
}

function prebuildCache () {
  return path.join(npmCache(), '_prebuilds')
}

function tempFile (cached) {
  return cached + '.' + process.pid + '-' + Math.random().toString(16).slice(2) + '.tmp'
}

function getTarPath (opts, abi) {
  return path.join('prebuilds', [
    opts.pkg.name,
    '-v', opts.pkg.version,
    '-node-v', abi,
    '-', opts.platform,
    opts.libc,
    '-', opts.arch,
    '.tar.gz'
  ].join(''))
}

function localPrebuild (url) {
  return path.join('prebuilds', path.basename(url))
}

function readGypFile (opts, cb) {
  var version = opts.version
  var file = opts.file
  var dir = '.' + (opts.backend || 'node-gyp')
  fs.exists(path.join(nodeGypPath(dir), 'iojs-' + version), function (isIojs) {
    if (isIojs) version = 'iojs-' + version
    fs.exists(nodeGypPath(dir, version, 'include/node'), function (exists) {
      if (exists) {
        fs.readFile(nodeGypPath(dir, version, 'include/node', file), 'utf-8', cb)
      } else {
        fs.readFile(nodeGypPath(dir, version, 'src', file), 'utf-8', cb)
      }
    })
  })
}

function nodeGypPath () {
  var args = [].slice.call(arguments)
  return path.join(home(), args.join('/'))
}

function spawn (cmd, args, cb) {
  args = args || []
  if (typeof args === 'function') {
    cb = args
    args = []
  }
  return cp.spawn(cmd, args, {stdio: 'inherit'}).on('exit', function (code) {
    if (code === 0) return cb()
    cb(error.spawnFailed(cmd, args, code))
  })
}

function platform () {
  return process.platform
}

function releaseFolder (opts, version) {
  var type = (opts.debug ? 'Debug' : 'Release')
  var binary = opts.pkg.binary
  if (opts.backend === 'node-ninja') {
    return (binary && binary.module_path) || 'build/' + version + '/' + type
  } else {
    return (binary && binary.module_path) || 'build/' + type
  }
}

exports.getDownloadUrl = getDownloadUrl
exports.urlTemplate = urlTemplate
exports.cachedPrebuild = cachedPrebuild
exports.localPrebuild = localPrebuild
exports.prebuildCache = prebuildCache
exports.npmCache = npmCache
exports.tempFile = tempFile
exports.getTarPath = getTarPath
exports.readGypFile = readGypFile
exports.spawn = spawn
exports.platform = platform
exports.releaseFolder = releaseFolder
exports.nodeGypPath = nodeGypPath
<|endoftext|>


<commit_before>

//generate an array of ordered hashes.
var crypto = require('crypto')
var hashes = 0
function hash(x) {
  hashes ++
  return crypto.createHash('sha1').update(x, 'hex').digest('hex')
}

exports.table = table
exports.maxPrefix = maxPrefix
exports.startsWith = startsWith
exports.group = group
exports.merkleize = merkleize
exports.tree = tree

function startsWith(a, prefix) {
  var o = {}
  if(Array.isArray(a)) {
    for(var i in a)
      o[a[i].substring(0, prefix)] = a[i]
  } else {
    for(var k in a)
      o[k.substring(0, prefix)] = a[k]
  }
  return o
}

function group(o, l, iter) {
  var n = {}, cur
  function emit(k) {
    iter(k, n)
    n = {}
  }

  for(var k in o) {
    if(!cur)
      cur = k.substring(0, l)
    var pre = k.substring(0, l)
    if(cur != pre) {
      emit(cur, n)
      cur = pre
    }
    n[k] = o[k]
  }
  emit(cur, n)
}

function tree (a) {
  var m = maxPrefix(a)
  var o = startsWith(a, m)
  function recurse(o, m) {
    if(m == 0) return o
    var g = {}
    group(o, --m, function (key, group) {
      g[key] = merkleize(group)
    })
    if(!m)
      return g
    else
      return recurse(g, m)
  }

  return recurse(o, m)['']
//  return 'string' === typeof g ? {hash: g} : g
}

function getHash(obj) {

}

function merkleize (obj) {
  var keys = Object.keys(obj)
  if(keys.length === 1)
    return obj[keys[0]]

  var h = keys.map(function (e) {
    var v = obj[e]
    if('string' === typeof v)
      return v
    return v.hash
  }).join('')

  return {
    hash: hash(h), tree: obj
  }
}

function table (bits) {
  var max = 1 << bits
  var a = []
  for(var i = 0; i < max; i++) {
    var x = i.toString(16)
    if(x.length % 2)
      x = '0' + ''+x
    a.push(hash(x))
  }
  return a.sort()
}

//console.log(a)
START = Date.now()
/*
function each(a, iter) {
  for(var i in a)
    iter(a[i], i, a)
}

function tree (a, len) {
  var cur, acc = [], result = {}, tree = [], tree2 = {}
  function key (r, k) {
    return 'object' === typeof r ? k.substring(0, len) : r.substring(0, len)
  }

  function value (r) {
    return 'object' === typeof r ? r.hash : r
  }

  each(a, function (r, k) {
    if(!cur) {
      cur = key(r, k)
      acc = [], tree = [], tree2 = {}
    }
    var pre = key(r, k)
    if(pre === cur) {
      acc.push(value(r))
      tree.push(r)
      tree2[cur] = r
    } else {
      var _tree =
          tree.length > 1
          ? levelOne(tree, len + 1)
          : tree

      if(acc.length == 1)
        result[cur] = acc[0] //({pre: cur, hash: acc[0]})
      else {
        result[cur] = ({pre: cur, hash: hash(acc.join('')), tree: _tree})
      }
      cur = pre
      acc = [value(r)]; tree = [r]; tree2 = {}
    }
  })
  console.log(cur, acc, tree)
  return result
}

function wholeTree(a, depth) {
  //console.log(tree)
  if(depth == null)
    depth = maxPrefix(a)
  if(depth === 1)
    return tree(a, 1)
  return wholeTree(tree(a, depth), depth - 1)
}

//var result = wholeTree(a, 3)

function levelOne(a, m) {
  var t = {}//tree(a, m)
  var o = {}
  for(var i in a) {
    var v = a[i].pre || a[i]
    if(!v.substring) {
      console.log(a[i])
    }

    t[v.substring(0, m)] = a[i]
  }
  if(a.length != Object.keys(t).length) {
    throw new Error('wrong length')
  }
  return t
}
*/
function prefix(a, b) {
  if(a == b)
    return a.length
  for(var i in a)
    if(a[i] !== b[i])
      return 1 + +i
}

function maxPrefix (a) {
  var prev, max = 0
  a.forEach(function (k) {
    if(!prev)
      prev = k
    else {
      var l = prefix(prev, k)
      var a = prev.substring(0, l), b = k.substring(0, l)
      if(a === b)
        throw new Error(prev + ' === ' + k)
      max = Math.max(max, l)
    }
    prev = k
  })
  return max
}

if(!module.parent) {
  var a = table(16)

  START = Date.now()
  console.log(maxPrefix(a))
  var H = hashes
  console.log(hashes)
  var g = tree(a)
//  console.log(JSON.stringify(, null, 2))
  console.log(Date.now() - START, hashes - H)
}
<commit_msg>this works, but it creates way too many objects.<commit_after>//generate an array of ordered hashes.
var crypto = require('crypto')
var hashes = 0
var OBJECTS = 0
function hash(x) {
  hashes ++
  return crypto.createHash('sha1').update(x, 'hex').digest('hex')
}

exports.table = table
exports.maxPrefix = maxPrefix
exports.startsWith = startsWith
exports.group = group
exports.merkleize = merkleize
exports.tree = tree

function startsWith(a, prefix) {
  OBJECTS ++
  var o = {}
  if(Array.isArray(a)) {
    for(var i in a)
      o[a[i].substring(0, prefix)] = a[i]
  } else {
    for(var k in a)
      o[k.substring(0, prefix)] = a[k]
  }
  return o
}

function group(o, l, iter) {
  var n = {}, cur
  OBJECTS ++
  function emit(k) {
    iter(k, n)
    OBJECTS ++
    n = {}
  }

  for(var k in o) {
    var pre
    if(!cur)
      pre = cur = k.substring(0, l)
    else
      pre = k.substring(0, l)
    if(cur != pre) {
      emit(cur, n)
      cur = pre
    }
    n[k] = o[k]
  }
  emit(cur, n)
}

function tree (a) {
  var m = maxPrefix(a)
  console.log('MAX', m)
  var o = startsWith(a, m)
  function recurse(o, m) {
    if(m === 0) return o
    OBJECTS ++
    var g = {}
    group(o, --m, function (key, group) {
      g[key] = merkleize(group)
    })
    if(!m)
      return g
    else
      return recurse(g, m)
  }

  return recurse(o, m)['']
//  return 'string' === typeof g ? {hash: g} : g
}

function getHash(obj) {

}

function oneKey(obj) {
  var i = 0
  for(var k in obj) {
    f = k
    if(i++) return false
  }
  return i === 1
}

function first (o) {
  for(var k in o)
    return k
}

function merkleize (obj) {
  var keys = Object.keys(obj)

//  var h = '', n = 0
  var h = keys.map(function (k) {
    var v = obj[k]
//    n ++
    return v.hash || v //('string' === typeof v ? v : v.hash)
  })
  //.join('')

  return h.length == 1 ? h[0] : OBJECTS ++, {
    hash: hash(h.join('')), tree: obj
  }
}

function table (bits) {
  var max = 1 << bits
  var a = []
  for(var i = 0; i < max; i++) {
    var x = i.toString(16)
    if(x.length % 2)
      x = '0' + ''+x
    a.push(hash(x))
  }
  return a.sort()
}

//console.log(a)
START = Date.now()

function prefix(a, b) {
  if(a == b)
    return a.length
  for(var i in a)
    if(a[i] !== b[i])
      return 1 + +i
}

function maxPrefix (a) {
  var prev, max = 0
  a.forEach(function (k) {
    if(!prev)
      prev = k
    else {
      var l = prefix(prev, k)
      var a = prev.substring(0, l), b = k.substring(0, l)
      if(a === b)
        throw new Error(prev + ' === ' + k)
      max = Math.max(max, l)
    }
    prev = k
  })
  return max
}

if(!module.parent) {
  var a = table(12)

  START = Date.now()
//  console.log(maxPrefix(a))
  var H = hashes
  console.log(hashes)
  var g = tree(a)
  console.log(JSON.stringify(g, null, 2))
  console.log(Date.now() - START, hashes - H, OBJECTS)
}
//
// 331290 / 65536
//5.055084228515625
<|endoftext|>


<commit_before>'use strict'
function isString(s) { return 'string' === typeof s }

function isNumber(n) { return !isNaN(+n) }

function isBoolean (b) { return 'boolean' === typeof b }

function isBasic (p) { return isString(p) || isNumber(p) || isBoolean(p) }

var isArray = Array.isArray

function isObject (o) { return o && 'object' === typeof o && !isArray(o) }

function has(o, k) {
  return Object.hasOwnProperty.call(o, k)
}

function isExact (v) {
  if(isBasic(v)) return true
  if(isArray(v))
    return v.every(isExact)
  return isObject(v) && has(v, '$eq')
}

function isLtgt (v) {
  return has(v, '$lt') || has(v, '$gt') || has(v, '$lte') || has(v, '$gte')
}

function isRange (v) {
  if(!isObject(v)) return false
  if(isString(v.$prefix)) return true
  if(isArray(v)) return find(v, isRange)
  return isLtgt(v)
}

function find (ary, test) {
  for(var i = 0; i < ary.length; i++)
    if(test(ary[i], i, ary)) return true
  return false
}

function lower (v) {
  if(isBasic(v)) return v
  if(isObject(v)) {
    if(isArray(v.$prefix)) return v.$prefix.concat(exports.HI)
    if(isString(v.$prefix)) return v.$prefix
    if(has(v, '$gt')) return v.$gt
    if(has(v, '$gte')) return v.$gte
  }
  if(isArray(v)) return v.map(lower)
}

function upper (v) {
  if(isBasic(v)) return v
  if(isObject(v)) {
    if(isArray(v.$prefix)) return v.$prefix.concat(exports.LO)
    if(isString(v.$prefix)) return v.$prefix+'\uffff'
    if(has(v, '$le')) return v.$lt
    if(has(v, '$lte')) return v.$lte
  }
  if(isArray(v)) return v.map(upper)
}

function get(obj, path) {
  if(isString(path)) return obj[path]
  if(isArray(path)) {
    for(var i = 0; i < path.length; i++) {
      if(obj == null) return undefined
      obj = obj[path[i]]
    }
    return obj
  }
  if(path === true) return obj
  return undefined
}

function map(obj, iter, o) {
  if(Array.isArray(obj)) return obj.map(iter)
  o = o || {}
  for(var k in obj) {
    var v = iter(obj[k], k, obj)
    if(v !== undefined) o[k] = v
  }
  return o
}

function mapa(obj, iter) {
  if(Array.isArray(obj)) return obj.map(iter)
  var a = []
  for(var k in obj) {
    var v = iter(obj[k], k, obj)
    if(v !== undefined) a.push(v)
  }
  return a

}

function each(obj, iter) {
  if(Array.isArray(obj)) return obj.forEach(iter)
  else if(isObject(obj))
    for(var k in obj) iter(obj[k], k, obj)
  else
    iter(obj)
}

function project (value, map, isObj) {
  isObj = isObj || isObject
  if(!isObj(value))
    return map(value)
  else {
    var o
    for(var k in value) {
      var v = project(value[k], map, isObj)
      if(v !== undefined)
        (o = o || {})[k] = v
    }
    return o
  }
}

//get all paths within an object
//this can probably be optimized to create less arrays!
function paths (object, test) {
  var p = []
  for(var key in object) {
    var value = object[key]
    if(test(value)) p.push(key)
    else if(isObject(value))
      p = p.concat(paths(value, test).map(function (path) {
        return [key].concat(path)
      }))
  }
  return p
}

exports.isString = isString
exports.isNumber = isNumber
exports.isBasic = isBasic
exports.isArray = isArray
exports.isObject = isObject
exports.isRange = isRange
exports.isExact = isExact
exports.isLtgt = isLtgt

exports.has     = has
exports.get     = get
exports.map     = map
exports.mapa    = mapa
exports.project = project
exports.paths   = paths
exports.each    = each

exports.upper = upper
exports.lower = lower

exports.HI = undefined
exports.LO = null

<commit_msg>util.isFunction<commit_after>'use strict'

function isString(s) { return 'string' === typeof s }

function isNumber(n) { return !isNaN(+n) }

function isBoolean (b) { return 'boolean' === typeof b }

function isBasic (p) { return isString(p) || isNumber(p) || isBoolean(p) }

function isFunction (f) { return 'function' === typeof f }

var isArray = Array.isArray

function isObject (o) { return o && 'object' === typeof o && !isArray(o) }

function has(o, k) {
  return Object.hasOwnProperty.call(o, k)
}

function isExact (v) {
  if(isBasic(v)) return true
  if(isArray(v))
    return v.every(isExact)
  return isObject(v) && has(v, '$eq')
}

function isLtgt (v) {
  return has(v, '$lt') || has(v, '$gt') || has(v, '$lte') || has(v, '$gte')
}

function isRange (v) {
  if(!isObject(v)) return false
  if(isString(v.$prefix)) return true
  if(isArray(v)) return find(v, isRange)
  return isLtgt(v)
}

function find (ary, test) {
  for(var i = 0; i < ary.length; i++)
    if(test(ary[i], i, ary)) return true
  return false
}

function lower (v) {
  if(isBasic(v)) return v
  if(isObject(v)) {
    if(isArray(v.$prefix)) return v.$prefix.concat(exports.HI)
    if(isString(v.$prefix)) return v.$prefix
    if(has(v, '$gt')) return v.$gt
    if(has(v, '$gte')) return v.$gte
  }
  if(isArray(v)) return v.map(lower)
}

function upper (v) {
  if(isBasic(v)) return v
  if(isObject(v)) {
    if(isArray(v.$prefix)) return v.$prefix.concat(exports.LO)
    if(isString(v.$prefix)) return v.$prefix+'\uffff'
    if(has(v, '$le')) return v.$lt
    if(has(v, '$lte')) return v.$lte
  }
  if(isArray(v)) return v.map(upper)
}

function get(obj, path) {
  if(isString(path)) return obj[path]
  if(isArray(path)) {
    for(var i = 0; i < path.length; i++) {
      if(obj == null) return undefined
      obj = obj[path[i]]
    }
    return obj
  }
  if(path === true) return obj
  return undefined
}

function map(obj, iter, o) {
  if(Array.isArray(obj)) return obj.map(iter)
  o = o || {}
  for(var k in obj) {
    var v = iter(obj[k], k, obj)
    if(v !== undefined) o[k] = v
  }
  return o
}

function mapa(obj, iter) {
  if(Array.isArray(obj)) return obj.map(iter)
  var a = []
  for(var k in obj) {
    var v = iter(obj[k], k, obj)
    if(v !== undefined) a.push(v)
  }
  return a

}

function each(obj, iter) {
  if(Array.isArray(obj)) return obj.forEach(iter)
  else if(isObject(obj))
    for(var k in obj) iter(obj[k], k, obj)
  else
    iter(obj)
}

function project (value, map, isObj) {
  isObj = isObj || isObject
  if(!isObj(value))
    return map(value)
  else {
    var o
    for(var k in value) {
      var v = project(value[k], map, isObj)
      if(v !== undefined)
        (o = o || {})[k] = v
    }
    return o
  }
}

//get all paths within an object
//this can probably be optimized to create less arrays!
function paths (object, test) {
  var p = []
  if(test(object)) return []
  for(var key in object) {
    var value = object[key]
    if(test(value)) p.push(key)
    else if(isObject(value))
      p = p.concat(paths(value, test).map(function (path) {
        return [key].concat(path)
      }))
  }
  return p
}

exports.isString = isString
exports.isNumber = isNumber
exports.isBasic = isBasic
exports.isArray = isArray
exports.isObject = isObject
exports.isRange = isRange
exports.isExact = isExact
exports.isLtgt = isLtgt
exports.isFunction = isFunction

exports.has     = has
exports.get     = get
exports.map     = map
exports.mapa    = mapa
exports.project = project
exports.paths   = paths
exports.each    = each

exports.upper = upper
exports.lower = lower

exports.HI = undefined
exports.LO = null

<|endoftext|>


<commit_before>$(function () {

  $('.dropdown.select .dropdown-option').on('click', function() {
    var text = $(this).text(),
        value = $(this).data('value'),
        $parent = $(this).parents('.dropdown');

    $parent.find('.selectedInput').val(value);
    $parent.find('.selected').text(text);

    var primaryLocale = $('.dropdown.select.origin .selectedInput').val(),
        toLocale = $('.dropdown.select.target .selectedInput').val(),
        path = '?primary_locale=' + primaryLocale + '&to_locale=' + toLocale;

    location.replace(path);
  });

  $('.translation-entry textarea').on('change', function() {
    var me = this,
        value = $.trim($(this).val());
    if (value) {
      var data = $($(this)[0].form).serializeArray();
      $.ajax({
        url: location.pathname,
        type: 'POST',
        cache: false,
        timeout: 7777,
        data: data
      }).done(function() {
        $(me).parent().addClass('done');
      });
    }
  }).on('keypress', function() {
    var me = this;
    $(me).parent().removeClass('done');
  });
});
<commit_msg>change keypress to keyup for delete key<commit_after>$(function () {

  $('.dropdown.select .dropdown-option').on('click', function() {
    var text = $(this).text(),
        value = $(this).data('value'),
        $parent = $(this).parents('.dropdown');

    $parent.find('.selectedInput').val(value);
    $parent.find('.selected').text(text);

    var primaryLocale = $('.dropdown.select.origin .selectedInput').val(),
        toLocale = $('.dropdown.select.target .selectedInput').val(),
        path = '?primary_locale=' + primaryLocale + '&to_locale=' + toLocale;

    location.replace(path);
  });

  $('.translation-entry textarea').on('change', function() {
    var me = this,
        value = $.trim($(this).val());
    if (value) {
      var data = $($(this)[0].form).serializeArray();
      $.ajax({
        url: location.pathname,
        type: 'POST',
        cache: false,
        timeout: 7777,
        data: data
      }).done(function() {
        $(me).parent().addClass('done');
      });
    }
  }).on('keyup', function() {
    var me = this;
    $(me).parent().removeClass('done');
  });
});
<|endoftext|>


<commit_before>$("#dataConfirmOK").click(function(){
    $("#dataConfirmModal").modal({show:false});
});
$("form").submit(function(e){
    var errors=false;
    $('.commitment-indicator').each(function(indicator){
        var commitmentval = $('#'+$(this).attr('id') + ' .commitment-indicator-value').val();
        if (!checkNumeric(commitmentval)){
            errors = true;
            $('#'+$(this).attr('id') + " .control-group").addClass('error');
        } else {
            $('#'+$(this).attr('id') + " .control-group").removeClass('error');
        }
    });
    if (errors) {
        e.preventDefault();
        if (!$('#dataConfirmModal').length) {
            $('body').append('

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Errors in your survey input

<button class="btn" data-dismiss="modal" aria-hidden="true">OK</button>

');
        }
        warning_text = "Commitment indicators must have numerical scores. Please correct errors above.";
        $('#dataConfirmModal').find('.modal-body').text(warning_text);
        $('#dataConfirmModal').modal({show:true});
    }
});

function checkNumeric(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}
$("#submit").click(function(e){
    e.preventDefault();
    if (!$('#dataConfirmModal').length) {
        $('form').append('

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Confirm submit survey

<button class="btn" data-dismiss="modal" aria-hidden="true">OK</button><input type="submit" name="submit" class="btn btn-success" id="dataConfirmOK" value="Submit data" />

');
        warning_text = "Are you sure you want to submit this survey? You cannot make any changes once you have submitted.";
        $('#dataConfirmModal').find('.modal-body').text(warning_text);
        $('#dataConfirmModal').modal({show:true});
    }
});
<commit_msg>Move data confirm modal prompt around<commit_after>$("form").submit(function(e){
    var errors=false;
    $('.commitment-indicator').each(function(indicator){
        var commitmentval = $('#'+$(this).attr('id') + ' .commitment-indicator-value').val();
        if (!checkNumeric(commitmentval)){
            errors = true;
            $('#'+$(this).attr('id') + " .control-group").addClass('error');
        } else {
            $('#'+$(this).attr('id') + " .control-group").removeClass('error');
        }
    });
    if (errors) {
        e.preventDefault();
        $('#dataConfirmModal').modal({show:false});
        if (!$('#dataConfirmModal').length) {
            $('body').append('

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Errors in your survey input

<button class="btn" data-dismiss="modal" aria-hidden="true">OK</button>

');
        }
        warning_text = "Commitment indicators must have numerical scores. Please correct errors above.";
        $('#dataConfirmModal').find('.modal-body').text(warning_text);
        $('#dataConfirmModal').modal({show:true});
    }
});

function checkNumeric(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}
$("#submit").click(function(e){
    e.preventDefault();
    if (!$('#dataConfirmModal').length) {
        $('form').append('

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Confirm submit survey

<button class="btn" data-dismiss="modal" aria-hidden="true">OK</button><input type="submit" name="submit" class="btn btn-success" id="dataConfirmOK" value="Submit data" />

');
        warning_text = "Are you sure you want to submit this survey? You cannot make any changes once you have submitted.";
        $('#dataConfirmModal').find('.modal-body').text(warning_text);
        $('#dataConfirmModal').modal({show:true});
    }
});
<|endoftext|>


<commit_before>'use strict';

var Db = require('dbjs');

Db.Base.set('DOMRadioBox', Db.external(function () {
	var Parent, Box, proto, localAttrs;
	localAttrs = { name: true, required: true };
	Parent = this.DOMInputBox;
	Box = function (document) {
		this.document = document;
		this.dom = document.createElement('ul');
		this.options = {};
	};
	proto = Box.prototype = Object.create(Parent.prototype);
	proto.constructor = Box;
	proto.createOption = function (value, labelTextDOM) {
		var dom, label, input;
		dom = this.document.createElement('li');
		label = dom.appendChild(this.document.createElement('label'));
		input = this.options[value] =
			label.appendChild(this.document.createElement('input'));
		input.setAttribute('type', 'radio');
		input.setAttribute('value', value);
		label.appendChild(this.document.createTextNode(' '));
		label.appendChild(labelTextDOM);
		return dom;
	};
	proto.set = function (value) {
		if (value == null) {
			Object.keys(this.options).forEach(function (name) {
				this[name].checked = false;
				this[name].removeAttribute('checked');
			}, this.options);
		} else {
			this.options[value].setAttribute('checked', 'checked');
			this.options[value].checked = true;
		}
	};
	proto.setAttribute = function (name, value) {
		if (localAttrs.hasOwnProperty(name)) {
			Object.keys(this.options).forEach(function (iName) {
				this[iName].setAttribute(name, value);
			}, this.options);
			return;
		}
		Parent.prototype.setAttribute.call(this, name, value);
	};
	return Box;
}));
<commit_msg>Identify radio list with html class<commit_after>'use strict';

var Db = require('dbjs');

Db.Base.set('DOMRadioBox', Db.external(function () {
	var Parent, Box, proto, localAttrs;
	localAttrs = { name: true, required: true };
	Parent = this.DOMInputBox;
	Box = function (document) {
		this.document = document;
		this.dom = document.createElement('ul');
		this.dom.setAttribute('class', 'radio');
		this.options = {};
	};
	proto = Box.prototype = Object.create(Parent.prototype);
	proto.constructor = Box;
	proto.createOption = function (value, labelTextDOM) {
		var dom, label, input;
		dom = this.document.createElement('li');
		label = dom.appendChild(this.document.createElement('label'));
		input = this.options[value] =
			label.appendChild(this.document.createElement('input'));
		input.setAttribute('type', 'radio');
		input.setAttribute('value', value);
		label.appendChild(this.document.createTextNode(' '));
		label.appendChild(labelTextDOM);
		return dom;
	};
	proto.set = function (value) {
		if (value == null) {
			Object.keys(this.options).forEach(function (name) {
				this[name].checked = false;
				this[name].removeAttribute('checked');
			}, this.options);
		} else {
			this.options[value].setAttribute('checked', 'checked');
			this.options[value].checked = true;
		}
	};
	proto.setAttribute = function (name, value) {
		if (localAttrs.hasOwnProperty(name)) {
			Object.keys(this.options).forEach(function (iName) {
				this[iName].setAttribute(name, value);
			}, this.options);
			return;
		}
		Parent.prototype.setAttribute.call(this, name, value);
	};
	return Box;
}));
<|endoftext|>