<commit_before>/*jslint node: true */
"use strict";

if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined') { // desktop
	var desktopApp = require('./desktop_app.js');
	var appRootDir = desktopApp.getAppRootDir();
	require('dotenv').config({path: appRootDir + '/.env'});
}

if (!Number.MAX_SAFE_INTEGER)
	Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991

exports.COUNT_WITNESSES = 12;
exports.MAX_WITNESS_LIST_MUTATIONS = 1;
exports.TOTAL_WHITEBYTES = 1e15;
exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);
exports.COUNT_MC_BALLS_FOR_PAID_WITNESSING = 100;

exports.bTestnet = !!process.env.testnet;
console.log('===== testnet = ' + exports.bTestnet);

exports.version = exports.bTestnet ? '3.0t' : '3.0';
exports.alt = exports.bTestnet ? '2' : '1';

exports.supported_versions = exports.bTestnet ? ['1.0t', '2.0t', '3.0t'] : ['1.0', '2.0', '3.0'];
exports.versionWithoutTimestamp = exports.bTestnet ? '1.0t' : '1.0';
exports.versionWithoutKeySizes = exports.bTestnet ? '2.0t' : '2.0';

//exports.bTestnet = (exports.alt === '2' && exports.version === '1.0t');

exports.GENESIS_UNIT = exports.bTestnet ? 'TvqutGPz3T4Cs6oiChxFlclY92M2MvCvfXR5/FETato=' : 'oj8yEksX9Ubq7lLc+p6F2uyHUuynugeVq4+ikT67X6E=';
exports.BLACKBYTES_ASSET = exports.bTestnet ? 'LUQu5ik4WLfCrr8OwXezqBa+i3IlZLqxj2itQZQm8WY=' : 'qO2JsiuDMh/j+pqJYZw3u82O71WjCDf0vTNvsnntr8o=';

exports.HASH_LENGTH = 44;
exports.PUBKEY_LENGTH = 44;
exports.SIG_LENGTH = 88;

// anti-spam limits
exports.MAX_AUTHORS_PER_UNIT = 16;
exports.MAX_PARENTS_PER_UNIT = 16;
exports.MAX_MESSAGES_PER_UNIT = 128;
exports.MAX_SPEND_PROOFS_PER_MESSAGE = 128;
exports.MAX_INPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_OUTPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_CHOICES_PER_POLL = 128;
exports.MAX_CHOICE_LENGTH = 64;
exports.MAX_DENOMINATIONS_PER_ASSET_DEFINITION = 64;
exports.MAX_ATTESTORS_PER_ASSET = 64;
exports.MAX_DATA_FEED_NAME_LENGTH = 64;
exports.MAX_DATA_FEED_VALUE_LENGTH = 64;
exports.MAX_AUTHENTIFIER_LENGTH = 4096;
exports.MAX_CAP = 9e15;
exports.MAX_COMPLEXITY = 100;
exports.MAX_UNIT_LENGTH = 5e6;

exports.MAX_PROFILE_FIELD_LENGTH = 50;
exports.MAX_PROFILE_VALUE_LENGTH = 100;

exports.MAX_AA_STRING_LENGTH = 4096;
exports.MAX_STATE_VAR_NAME_LENGTH = 128;
exports.MAX_STATE_VAR_VALUE_LENGTH = 1024;
exports.MAX_OPS = 2000;
exports.MAX_RESPONSES_PER_PRIMARY_TRIGGER = 10;

exports.MIN_BYTES_BOUNCE_FEE = 10000;

exports.minCoreVersion = exports.bTestnet ? '0.3.12' : '0.3.12';
exports.minCoreVersionForFullNodes = exports.bTestnet ? '0.3.12' : '0.3.12';
exports.minCoreVersionToSharePeers = exports.bTestnet ? '0.3.9' : '0.3.9';

exports.lastBallStableInParentsUpgradeMci =  exports.bTestnet ? 0 : 1300000;
exports.witnessedLevelMustNotRetreatUpgradeMci = exports.bTestnet ? 684000 : 1400000;
exports.skipEvaluationOfUnusedNestedAddressUpgradeMci = exports.bTestnet ? 1400000 : 1400000;
exports.spendUnconfirmedUpgradeMci = exports.bTestnet ? 589000 : 2909000;
exports.branchedMinMcWlUpgradeMci = exports.bTestnet ? 593000 : 2909000;
exports.otherAddressInDefinitionUpgradeMci = exports.bTestnet ? 602000 : 2909000;
exports.attestedInDefinitionUpgradeMci = exports.bTestnet ? 616000 : 2909000;
exports.altBranchByBestParentUpgradeMci = exports.bTestnet ? 642000 : 3009824;
exports.anyDefinitionChangeUpgradeMci = exports.bTestnet ? 855000 : 4229100;
exports.formulaUpgradeMci = exports.bTestnet ? 961000 : 5210000;
exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = exports.bTestnet ? 909000 : 5210000;
exports.timestampUpgradeMci = exports.bTestnet ? 909000 : 5210000;
exports.aaStorageSizeUpgradeMci = exports.bTestnet ? 1034000 : 5210000;
exports.aa2UpgradeMci = exports.bTestnet ? 1358300 : 5494000;
exports.unstableInitialDefinitionUpgradeMci = exports.bTestnet ? 1358300 : 5494000;
exports.includeKeySizesUpgradeMci = exports.bTestnet ? 1383500 : 5530000;

if (process.env.devnet) {
	console.log('===== devnet');
	exports.bDevnet = true;
	exports.version = '3.0dev';
	exports.alt = '3';
	exports.supported_versions = ['1.0dev', '2.0dev', '3.0dev'];
	exports.versionWithoutTimestamp = '1.0dev';
	exports.versionWithoutKeySizes = '2.0dev';
	exports.GENESIS_UNIT = 'pLzHaCisvxkfgwyBDzgvZzhPp37ZKnuMOxiI3QwXxqM=';
	exports.BLACKBYTES_ASSET = 'GRzA4D/ElsiwivoUrkCg36s+CoOr6rLsSH2F0EOes64=';

	exports.COUNT_WITNESSES = 1;
	exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);

	exports.lastBallStableInParentsUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatUpgradeMci = 0;
	exports.spendUnconfirmedUpgradeMci = 0;
	exports.branchedMinMcWlUpgradeMci = 0;
	exports.otherAddressInDefinitionUpgradeMci = 0;
	exports.attestedInDefinitionUpgradeMci = 0;
	exports.altBranchByBestParentUpgradeMci = 0;
	exports.anyDefinitionChangeUpgradeMci = 0;
	exports.formulaUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = 0;
	exports.timestampUpgradeMci = 0;
	exports.aaStorageSizeUpgradeMci = 0;
	exports.aa2UpgradeMci = 0;
	exports.unstableInitialDefinitionUpgradeMci = 0;
	exports.includeKeySizesUpgradeMci = 0;
}

exports.TEXTCOIN_CLAIM_FEE = 772 + (exports.version.length - 3);
exports.TEXTCOIN_ASSET_CLAIM_HEADER_FEE = 399 + 115 + (exports.version.length - 3);
exports.TEXTCOIN_ASSET_CLAIM_MESSAGE_FEE = 201 + 98;
exports.TEXTCOIN_ASSET_CLAIM_BASE_MSG_FEE = 157 + 101 + 1; // 1 for base output
exports.TEXTCOIN_ASSET_CLAIM_FEE = exports.TEXTCOIN_ASSET_CLAIM_HEADER_FEE + exports.TEXTCOIN_ASSET_CLAIM_MESSAGE_FEE + exports.TEXTCOIN_ASSET_CLAIM_BASE_MSG_FEE;
exports.TEXTCOIN_PRIVATE_ASSET_CLAIM_MESSAGE_FEE = 153;
<commit_msg>network params in .env<commit_after>/*jslint node: true */
"use strict";

if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined') { // desktop
	var desktopApp = require('./desktop_app.js');
	var appRootDir = desktopApp.getAppRootDir();
	require('dotenv').config({path: appRootDir + '/.env'});
}

if (!Number.MAX_SAFE_INTEGER)
	Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991

exports.COUNT_WITNESSES = process.env.COUNT_WITNESSES || 12;
exports.MAX_WITNESS_LIST_MUTATIONS = 1;
exports.TOTAL_WHITEBYTES = process.env.TOTAL_WHITEBYTES || 1e15;
exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);
exports.COUNT_MC_BALLS_FOR_PAID_WITNESSING = process.env.COUNT_MC_BALLS_FOR_PAID_WITNESSING || 100;

exports.bTestnet = !!process.env.testnet;
console.log('===== testnet = ' + exports.bTestnet);

exports.version = exports.bTestnet ? '3.0t' : '3.0';
exports.alt = exports.bTestnet ? '2' : '1';

exports.supported_versions = exports.bTestnet ? ['1.0t', '2.0t', '3.0t'] : ['1.0', '2.0', '3.0'];
exports.versionWithoutTimestamp = exports.bTestnet ? '1.0t' : '1.0';
exports.versionWithoutKeySizes = exports.bTestnet ? '2.0t' : '2.0';

//exports.bTestnet = (exports.alt === '2' && exports.version === '1.0t');

exports.GENESIS_UNIT = process.env.GENESIS_UNIT || (exports.bTestnet ? 'TvqutGPz3T4Cs6oiChxFlclY92M2MvCvfXR5/FETato=' : 'oj8yEksX9Ubq7lLc+p6F2uyHUuynugeVq4+ikT67X6E=');
exports.BLACKBYTES_ASSET = process.env.BLACKBYTES_ASSET || (exports.bTestnet ? 'LUQu5ik4WLfCrr8OwXezqBa+i3IlZLqxj2itQZQm8WY=' : 'qO2JsiuDMh/j+pqJYZw3u82O71WjCDf0vTNvsnntr8o=');

exports.HASH_LENGTH = 44;
exports.PUBKEY_LENGTH = 44;
exports.SIG_LENGTH = 88;

// anti-spam limits
exports.MAX_AUTHORS_PER_UNIT = 16;
exports.MAX_PARENTS_PER_UNIT = 16;
exports.MAX_MESSAGES_PER_UNIT = 128;
exports.MAX_SPEND_PROOFS_PER_MESSAGE = 128;
exports.MAX_INPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_OUTPUTS_PER_PAYMENT_MESSAGE = 128;
exports.MAX_CHOICES_PER_POLL = 128;
exports.MAX_CHOICE_LENGTH = 64;
exports.MAX_DENOMINATIONS_PER_ASSET_DEFINITION = 64;
exports.MAX_ATTESTORS_PER_ASSET = 64;
exports.MAX_DATA_FEED_NAME_LENGTH = 64;
exports.MAX_DATA_FEED_VALUE_LENGTH = 64;
exports.MAX_AUTHENTIFIER_LENGTH = 4096;
exports.MAX_CAP = 9e15;
exports.MAX_COMPLEXITY = process.env.MAX_COMPLEXITY || 100;
exports.MAX_UNIT_LENGTH = process.env.MAX_UNIT_LENGTH || 5e6;

exports.MAX_PROFILE_FIELD_LENGTH = 50;
exports.MAX_PROFILE_VALUE_LENGTH = 100;

exports.MAX_AA_STRING_LENGTH = 4096;
exports.MAX_STATE_VAR_NAME_LENGTH = 128;
exports.MAX_STATE_VAR_VALUE_LENGTH = 1024;
exports.MAX_OPS = process.env.MAX_OPS || 2000;
exports.MAX_RESPONSES_PER_PRIMARY_TRIGGER = process.env.MAX_RESPONSES_PER_PRIMARY_TRIGGER || 10;

exports.MIN_BYTES_BOUNCE_FEE = process.env.MIN_BYTES_BOUNCE_FEE || 10000;

exports.minCoreVersion = exports.bTestnet ? '0.3.12' : '0.3.12';
exports.minCoreVersionForFullNodes = exports.bTestnet ? '0.3.12' : '0.3.12';
exports.minCoreVersionToSharePeers = exports.bTestnet ? '0.3.9' : '0.3.9';

exports.lastBallStableInParentsUpgradeMci =  exports.bTestnet ? 0 : 1300000;
exports.witnessedLevelMustNotRetreatUpgradeMci = exports.bTestnet ? 684000 : 1400000;
exports.skipEvaluationOfUnusedNestedAddressUpgradeMci = exports.bTestnet ? 1400000 : 1400000;
exports.spendUnconfirmedUpgradeMci = exports.bTestnet ? 589000 : 2909000;
exports.branchedMinMcWlUpgradeMci = exports.bTestnet ? 593000 : 2909000;
exports.otherAddressInDefinitionUpgradeMci = exports.bTestnet ? 602000 : 2909000;
exports.attestedInDefinitionUpgradeMci = exports.bTestnet ? 616000 : 2909000;
exports.altBranchByBestParentUpgradeMci = exports.bTestnet ? 642000 : 3009824;
exports.anyDefinitionChangeUpgradeMci = exports.bTestnet ? 855000 : 4229100;
exports.formulaUpgradeMci = exports.bTestnet ? 961000 : 5210000;
exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = exports.bTestnet ? 909000 : 5210000;
exports.timestampUpgradeMci = exports.bTestnet ? 909000 : 5210000;
exports.aaStorageSizeUpgradeMci = exports.bTestnet ? 1034000 : 5210000;
exports.aa2UpgradeMci = exports.bTestnet ? 1358300 : 5494000;
exports.unstableInitialDefinitionUpgradeMci = exports.bTestnet ? 1358300 : 5494000;
exports.includeKeySizesUpgradeMci = exports.bTestnet ? 1383500 : 5530000;

if (process.env.devnet) {
	console.log('===== devnet');
	exports.bDevnet = true;
	exports.version = '3.0dev';
	exports.alt = '3';
	exports.supported_versions = ['1.0dev', '2.0dev', '3.0dev'];
	exports.versionWithoutTimestamp = '1.0dev';
	exports.versionWithoutKeySizes = '2.0dev';
	exports.GENESIS_UNIT = 'pLzHaCisvxkfgwyBDzgvZzhPp37ZKnuMOxiI3QwXxqM=';
	exports.BLACKBYTES_ASSET = 'GRzA4D/ElsiwivoUrkCg36s+CoOr6rLsSH2F0EOes64=';

	exports.COUNT_WITNESSES = 1;
	exports.MAJORITY_OF_WITNESSES = (exports.COUNT_WITNESSES%2===0) ? (exports.COUNT_WITNESSES/2+1) : Math.ceil(exports.COUNT_WITNESSES/2);
}

// run the latest version
if (process.env.devnet || process.env.GENESIS_UNIT) {
	exports.lastBallStableInParentsUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatUpgradeMci = 0;
	exports.skipEvaluationOfUnusedNestedAddressUpgradeMci = 0;
	exports.spendUnconfirmedUpgradeMci = 0;
	exports.branchedMinMcWlUpgradeMci = 0;
	exports.otherAddressInDefinitionUpgradeMci = 0;
	exports.attestedInDefinitionUpgradeMci = 0;
	exports.altBranchByBestParentUpgradeMci = 0;
	exports.anyDefinitionChangeUpgradeMci = 0;
	exports.formulaUpgradeMci = 0;
	exports.witnessedLevelMustNotRetreatFromAllParentsUpgradeMci = 0;
	exports.timestampUpgradeMci = 0;
	exports.aaStorageSizeUpgradeMci = 0;
	exports.aa2UpgradeMci = 0;
	exports.unstableInitialDefinitionUpgradeMci = 0;
	exports.includeKeySizesUpgradeMci = 0;
}

// textcoins
exports.TEXTCOIN_CLAIM_FEE = 772 + (exports.version.length - 3);
exports.TEXTCOIN_ASSET_CLAIM_HEADER_FEE = 399 + 115 + (exports.version.length - 3);
exports.TEXTCOIN_ASSET_CLAIM_MESSAGE_FEE = 201 + 98;
exports.TEXTCOIN_ASSET_CLAIM_BASE_MSG_FEE = 157 + 101 + 1; // 1 for base output
exports.TEXTCOIN_ASSET_CLAIM_FEE = exports.TEXTCOIN_ASSET_CLAIM_HEADER_FEE + exports.TEXTCOIN_ASSET_CLAIM_MESSAGE_FEE + exports.TEXTCOIN_ASSET_CLAIM_BASE_MSG_FEE;
exports.TEXTCOIN_PRIVATE_ASSET_CLAIM_MESSAGE_FEE = 153;
<|endoftext|>


<commit_before>'use strict';
const bcd = require('..');

const { argv } = require('yargs').command('$0 <browser> [folder] [value]', 'Test for specified values in any specified browser', (yargs) => {
  yargs.positional('browser', {
    describe: 'The browser to test for',
    type: 'string'
  }).positional('folder', {
    describe: 'The folder(s) to test',
    type: 'array',
    default: ['api', 'css', 'html', 'http', 'svg', 'javascript', 'mathml', 'webdriver', 'xpath', 'xslt']
  }).positional('value', {
    describe: 'The value(s) to test against',
    type: 'array',
    default: ["null", "true"]
  });
});

function traverseFeatures(obj, depth, identifier) {
  depth--;
  if (depth >= 0) {
    for (let i in obj) {
      if (!!obj[i] && typeof(obj[i]) == "object" && i !== '__compat') {
        if (obj[i].__compat) {
          let comp = obj[i].__compat.support;
          let browser = comp[argv.browser];
          if (!Array.isArray(browser)) {
            browser = [browser];
          }
          for (let range in browser) {
            if (browser[range] === undefined) {
              if (values.includes("null")) features.push(`${identifier}${i}`);
            }
            else if (values.includes(String(browser[range].version_added)) ||
                     values.includes(String(browser[range].version_removed))) {
              if (browser[range].prefix) features.push(`${identifier}${i} (${browser[range].prefix} prefix)`);
              else features.push(`${identifier}${i}`);
            }
          }
        }
        traverseFeatures(obj[i], depth, identifier + i + '.');
      }
    }
  }
}

let features = [];
let folders = Array.isArray(argv.folder) ? argv.folder : argv.folder.split(",");
let values = Array.isArray(argv.value) ? argv.value : argv.value.toString().split(",");

for (let folder in folders) traverseFeatures(bcd[folders[folder]], 100, `${folders[folder]}.`);

console.log(features.join("\n"));
console.log(features.length);
<commit_msg>Add alternative_name to traverse script (#4456)<commit_after>'use strict';
const bcd = require('..');

const { argv } = require('yargs').command('$0 <browser> [folder] [value]', 'Test for specified values in any specified browser', (yargs) => {
  yargs.positional('browser', {
    describe: 'The browser to test for',
    type: 'string'
  }).positional('folder', {
    describe: 'The folder(s) to test',
    type: 'array',
    default: ['api', 'css', 'html', 'http', 'svg', 'javascript', 'mathml', 'webdriver', 'xpath', 'xslt']
  }).positional('value', {
    describe: 'The value(s) to test against',
    type: 'array',
    default: ["null", "true"]
  });
});

function traverseFeatures(obj, depth, identifier) {
  depth--;
  if (depth >= 0) {
    for (let i in obj) {
      if (!!obj[i] && typeof(obj[i]) == "object" && i !== '__compat') {
        if (obj[i].__compat) {
          let comp = obj[i].__compat.support;
          let browser = comp[argv.browser];
          if (!Array.isArray(browser)) {
            browser = [browser];
          }
          for (let range in browser) {
            if (browser[range] === undefined) {
              if (values.includes("null")) features.push(`${identifier}${i}`);
            }
            else if (values.includes(String(browser[range].version_added)) ||
                     values.includes(String(browser[range].version_removed))) {
              let f = `${identifier}${i}`;
              if (browser[range].prefix) f += ` (${browser[range].prefix} prefix)`;
              if (browser[range].alternative_name) f += ` (as ${browser[range].alternative_name})`;
              features.push(f);
            }
          }
        }
        traverseFeatures(obj[i], depth, identifier + i + '.');
      }
    }
  }
}

let features = [];
let folders = Array.isArray(argv.folder) ? argv.folder : argv.folder.split(",");
let values = Array.isArray(argv.value) ? argv.value : argv.value.toString().split(",");

for (let folder in folders) traverseFeatures(bcd[folders[folder]], 100, `${folders[folder]}.`);

console.log(features.join("\n"));
console.log(features.length);
<|endoftext|>


<commit_before>/**
 * Copyright 2013-present NightWorld.
 *
 * 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 error = require('./error'),
  AuthCodeGrant = require('./authCodeGrant'),
  Authorise = require('./authorise'),
  Grant = require('./grant'),
  Scope = require('./scope'),
  ImplicitGrant = require('./implicit');

module.exports = OAuth2Server;

/**
 * Constructor
 *
 * @param {Object} config Configuration object
 */
function OAuth2Server (config) {

  if (!(this instanceof OAuth2Server)) return new OAuth2Server(config);

  config = config || {};

  if (!config.model) throw new Error('No model supplied to OAuth2Server');
  this.model = config.model;

  this.grants = config.grants || [];
  this.debug = config.debug || function () {};
  if (typeof this.debug !== 'function') {
      this.debug = console.log;
  }
  this.passthroughErrors = config.passthroughErrors;
  this.continueAfterResponse = config.continueAfterResponse;

  this.accessTokenLifetime = config.accessTokenLifetime !== undefined ?
    config.accessTokenLifetime : 3600;
  this.refreshTokenLifetime = config.refreshTokenLifetime !== undefined ?
    config.refreshTokenLifetime : 1209600;
  this.authCodeLifetime = config.authCodeLifetime || 30;

  this.regex = {
    clientId: config.clientIdRegex || /^[a-z0-9-_]{3,40}$/i,
    grantType: new RegExp('^(' + this.grants.join('|') + ')$', 'i')
  };
}

/**
 * Authorisation Middleware
 *
 * Returns middleware that will authorise the request using oauth,
 * if successful it will allow the request to proceed to the next handler
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.authorise = function (options) {
  var self = this;

  return function oauthAuthorise(req, res, next) {
    return new Authorise(self, req, res, options, next);
  };
};

/**
 * Grant Middleware
 *
 * Returns middleware that will grant tokens to valid requests.
 * This would normally be mounted at '/oauth/token' e.g.
 *
 * `app.all('/oauth/token', oauth.grant());`
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.grant = function (options) {
  var self = this;

  return function oauthGrant(req, res, next) {
    return new Grant(self, options, req, res, next);
  };
};

/**
 * Code Auth Grant Middleware
 *
 * @param  {Function} check Function will be called with req to check if the
 *                          user has authorised the request.
 * @return {Function}       middleware
 */
OAuth2Server.prototype.authCodeGrant = function (check) {
  var self = this;

  return function oauthAuthCodeGrant(req, res, next) {
    new AuthCodeGrant(self, req, res, next, check);
  };
};

/**
 * Implicit Auth Grant Middleware
 * @param  {Function} check   Function will be called with req to check if the
 *                            user has authorised the request.
 * @param  {Function} handler middleware
 * @return {Function}         middleware
 */
OAuth2Server.prototype.implicit = function(check) {
  var self = this;
  return function oauthImplicit(req, res, next) {
    new ImplicitGrant(self, req, res, next, check);
  };
};

OAuth2Server.prototype.implicitRedirect = function() {
  var errfunc = function (err, req, res, next) {
    if (res.oauthRedirect && res.redirectUri) {
      return res.redirect(res.redirectUri + '?error=' + err.error +
          '&error_description=' + err.error_description + '&code=' + err.code);
    }
    next(err);
  };

  var goodfunc = function (req, res, next) {
    if (res.oauthRedirect && res.redirectUri) {
      return res.redirect(res.redirectUri + '#token=' + res.accessToken +
          (req.query.state ? '&state=' + req.query.state : ''));
    }
    next();
  };

  return [errfunc, goodfunc];
};

/**
 * Scope Check Middleware
 *
 * Returns middleware that allows the specification of required
 * scope(s) for routers and/or routes, which is validated by the model.
 *
 * @param  {Mixed}    requiredScope String or list of scope keys
 *                                  required to access the route.
 * @return {Function}
 */
OAuth2Server.prototype.scope = function(requiredScope) {
  var self = this;

  return function oauthScope(req, res, next) {
    return new Scope(self, req, next, requiredScope);
  };
};

/**
 * OAuth Error Middleware
 *
 * Returns middleware that will catch OAuth errors and ensure an OAuth
 * complaint response
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.errorHandler = function () {
  var self = this;

  return function oauthErrorHandler(err, req, res, next) {
    if (!(err instanceof error) || self.passthroughErrors || res.headersSent) return next(err);

    delete err.name;
    delete err.message;

    self.debug(err.stack || err);
    delete err.stack;

    if (err.headers) res.set(err.headers);
    delete err.headers;

    res.status(err.code);
    delete err.code;
    res.send(err);
  };
};

/**
 * Lockdown
 *
 * When using the lockdown patter, this function should be called after
 * all routes have been declared.
 * It will search through each route and if it has not been explitly bypassed
 * (by passing oauth.bypass) then authorise will be inserted.
 * If oauth.grant has been passed it will replace it with the proper grant
 * middleware
 * NOTE: When using this method, you must PASS the method not CALL the method,
 * e.g.:
 *
 * `
 * app.all('/oauth/token', app.oauth.grant);
 *
 * app.get('/secrets', function (req, res) {
 *   res.send('secrets');
 * });
 *
 * app.get('/public', app.oauth.bypass, function (req, res) {
 *   res.send('publci');
 * });
 *
 * app.oauth.lockdown(app);
 * `
 *
 * @param  {Object} app Express app
 */
OAuth2Server.prototype.lockdown = function (app) {
  var self = this;

  var lockdownExpress3 = function (stack) {
    // Check if it's a grant route
    var pos = stack.indexOf(self.grant);
    if (pos !== -1) {
      stack[pos] = self.grant();
      return;
    }

    // Check it's not been explitly bypassed
    pos = stack.indexOf(self.bypass);
    if (pos === -1) {
      stack.unshift(self.authorise());
    } else {
      stack.splice(pos, 1);
    }
  };

  var lockdownExpress4 = function (layer) {
    if (layer.name === 'router') {
      layer.handle.stack.forEach(lockdownExpress4);
      return;
    }

    if (!layer.route)
      return;

    var stack = layer.route.stack;
    var handlers = stack.map(function (item) {
      return item.handle._datadog_orig || item.handle;
    });

    // Check if it's a grant route
    var pos;
    var isGrant = false;
    while ((pos = handlers.indexOf(self.grant)) !== -1) {
      stack[pos].handle = self.grant();
      handlers[pos] = null;
      isGrant = true;
    }
    if (isGrant) {
      return;
    }

    // Check it's not been explitly bypassed
    pos = handlers.indexOf(self.bypass);
    if (pos === -1) {
      // Add authorise another route that applies to all methods
      var copy = {};
      var first = stack[0];
      for (var key in first) {
        copy[key] = first[key];
      }
      delete copy.method;
      copy.handle = self.authorise();
      stack.unshift(copy);
    } else {
      while ((pos = handlers.indexOf(self.bypass)) !== -1) {
        stack.splice(pos, 1);
        handlers[pos] = null;
      }
    }
  };

  if (app.routes) {
    for (var method in app.routes) {
      app.routes[method].forEach(function (route) {
        lockdownExpress3(route.callbacks);
      });
    }
  } else {
    app._router.stack.forEach(lockdownExpress4);
  }
};

/**
 * Bypass
 *
 * This is used as placeholder for when using the lockdown pattern
 *
 * @return {Function} noop
 */
OAuth2Server.prototype.bypass = function () {};
<commit_msg>Use wrapped handle if it exists<commit_after>/**
 * Copyright 2013-present NightWorld.
 *
 * 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 error = require('./error'),
  AuthCodeGrant = require('./authCodeGrant'),
  Authorise = require('./authorise'),
  Grant = require('./grant'),
  Scope = require('./scope'),
  ImplicitGrant = require('./implicit');

module.exports = OAuth2Server;

/**
 * Constructor
 *
 * @param {Object} config Configuration object
 */
function OAuth2Server (config) {

  if (!(this instanceof OAuth2Server)) return new OAuth2Server(config);

  config = config || {};

  if (!config.model) throw new Error('No model supplied to OAuth2Server');
  this.model = config.model;

  this.grants = config.grants || [];
  this.debug = config.debug || function () {};
  if (typeof this.debug !== 'function') {
      this.debug = console.log;
  }
  this.passthroughErrors = config.passthroughErrors;
  this.continueAfterResponse = config.continueAfterResponse;

  this.accessTokenLifetime = config.accessTokenLifetime !== undefined ?
    config.accessTokenLifetime : 3600;
  this.refreshTokenLifetime = config.refreshTokenLifetime !== undefined ?
    config.refreshTokenLifetime : 1209600;
  this.authCodeLifetime = config.authCodeLifetime || 30;

  this.regex = {
    clientId: config.clientIdRegex || /^[a-z0-9-_]{3,40}$/i,
    grantType: new RegExp('^(' + this.grants.join('|') + ')$', 'i')
  };
}

/**
 * Authorisation Middleware
 *
 * Returns middleware that will authorise the request using oauth,
 * if successful it will allow the request to proceed to the next handler
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.authorise = function (options) {
  var self = this;

  return function oauthAuthorise(req, res, next) {
    return new Authorise(self, req, res, options, next);
  };
};

/**
 * Grant Middleware
 *
 * Returns middleware that will grant tokens to valid requests.
 * This would normally be mounted at '/oauth/token' e.g.
 *
 * `app.all('/oauth/token', oauth.grant());`
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.grant = function (options) {
  var self = this;

  return function oauthGrant(req, res, next) {
    return new Grant(self, options, req, res, next);
  };
};

/**
 * Code Auth Grant Middleware
 *
 * @param  {Function} check Function will be called with req to check if the
 *                          user has authorised the request.
 * @return {Function}       middleware
 */
OAuth2Server.prototype.authCodeGrant = function (check) {
  var self = this;

  return function oauthAuthCodeGrant(req, res, next) {
    new AuthCodeGrant(self, req, res, next, check);
  };
};

/**
 * Implicit Auth Grant Middleware
 * @param  {Function} check   Function will be called with req to check if the
 *                            user has authorised the request.
 * @param  {Function} handler middleware
 * @return {Function}         middleware
 */
OAuth2Server.prototype.implicit = function(check) {
  var self = this;
  return function oauthImplicit(req, res, next) {
    new ImplicitGrant(self, req, res, next, check);
  };
};

OAuth2Server.prototype.implicitRedirect = function() {
  var errfunc = function (err, req, res, next) {
    if (res.oauthRedirect && res.redirectUri) {
      return res.redirect(res.redirectUri + '?error=' + err.error +
          '&error_description=' + err.error_description + '&code=' + err.code);
    }
    next(err);
  };

  var goodfunc = function (req, res, next) {
    if (res.oauthRedirect && res.redirectUri) {
      return res.redirect(res.redirectUri + '#token=' + res.accessToken +
          (req.query.state ? '&state=' + req.query.state : ''));
    }
    next();
  };

  return [errfunc, goodfunc];
};

/**
 * Scope Check Middleware
 *
 * Returns middleware that allows the specification of required
 * scope(s) for routers and/or routes, which is validated by the model.
 *
 * @param  {Mixed}    requiredScope String or list of scope keys
 *                                  required to access the route.
 * @return {Function}
 */
OAuth2Server.prototype.scope = function(requiredScope) {
  var self = this;

  return function oauthScope(req, res, next) {
    return new Scope(self, req, next, requiredScope);
  };
};

/**
 * OAuth Error Middleware
 *
 * Returns middleware that will catch OAuth errors and ensure an OAuth
 * complaint response
 *
 * @return {Function} middleware
 */
OAuth2Server.prototype.errorHandler = function () {
  var self = this;

  return function oauthErrorHandler(err, req, res, next) {
    if (!(err instanceof error) || self.passthroughErrors || res.headersSent) return next(err);

    delete err.name;
    delete err.message;

    self.debug(err.stack || err);
    delete err.stack;

    if (err.headers) res.set(err.headers);
    delete err.headers;

    res.status(err.code);
    delete err.code;
    res.send(err);
  };
};

/**
 * Lockdown
 *
 * When using the lockdown patter, this function should be called after
 * all routes have been declared.
 * It will search through each route and if it has not been explitly bypassed
 * (by passing oauth.bypass) then authorise will be inserted.
 * If oauth.grant has been passed it will replace it with the proper grant
 * middleware
 * NOTE: When using this method, you must PASS the method not CALL the method,
 * e.g.:
 *
 * `
 * app.all('/oauth/token', app.oauth.grant);
 *
 * app.get('/secrets', function (req, res) {
 *   res.send('secrets');
 * });
 *
 * app.get('/public', app.oauth.bypass, function (req, res) {
 *   res.send('publci');
 * });
 *
 * app.oauth.lockdown(app);
 * `
 *
 * @param  {Object} app Express app
 */
OAuth2Server.prototype.lockdown = function (app) {
  var self = this;

  var lockdownExpress3 = function (stack) {
    // Check if it's a grant route
    var pos = stack.indexOf(self.grant);
    if (pos !== -1) {
      stack[pos] = self.grant();
      return;
    }

    // Check it's not been explitly bypassed
    pos = stack.indexOf(self.bypass);
    if (pos === -1) {
      stack.unshift(self.authorise());
    } else {
      stack.splice(pos, 1);
    }
  };

  var lockdownExpress4 = function (layer) {
    if (layer.name === 'router') {
      const handle = layer.handle._datadog_orig || layer.handle;
      handle.stack.forEach(lockdownExpress4);
      return;
    }

    if (!layer.route)
      return;

    var stack = layer.route.stack;
    var handlers = stack.map(function (item) {
      return item.handle._datadog_orig || item.handle;
    });

    // Check if it's a grant route
    var pos;
    var isGrant = false;
    while ((pos = handlers.indexOf(self.grant)) !== -1) {
      stack[pos].handle = self.grant();
      handlers[pos] = null;
      isGrant = true;
    }
    if (isGrant) {
      return;
    }

    // Check it's not been explitly bypassed
    pos = handlers.indexOf(self.bypass);
    if (pos === -1) {
      // Add authorise another route that applies to all methods
      var copy = {};
      var first = stack[0];
      for (var key in first) {
        copy[key] = first[key];
      }
      delete copy.method;
      copy.handle = self.authorise();
      stack.unshift(copy);
    } else {
      while ((pos = handlers.indexOf(self.bypass)) !== -1) {
        stack.splice(pos, 1);
        handlers[pos] = null;
      }
    }
  };

  if (app.routes) {
    for (var method in app.routes) {
      app.routes[method].forEach(function (route) {
        lockdownExpress3(route.callbacks);
      });
    }
  } else {
    app._router.stack.forEach(lockdownExpress4);
  }
};

/**
 * Bypass
 *
 * This is used as placeholder for when using the lockdown pattern
 *
 * @return {Function} noop
 */
OAuth2Server.prototype.bypass = function () {};
<|endoftext|>


<commit_before>/*
 * Support javascript module for the gfactroy monitoring
 * Part of the gldieinWMS package
 *
 * Original repository: http://www.uscms.org/SoftwareComputing/Grid/WMS/glideinWMS/
 *
 */

// Load FactoryQStats XML file and return the object
function loadFactoryQStats() {
  var request =  new XMLHttpRequest();
  request.open("GET", "schedd_status.xml",false);
  request.send(null);

  var factoryQStats=request.responseXML.firstChild;
  return factoryQStats;
}

// Extract entry names from a factoryQStats XML object
function getFactoryEntries(factoryQStats) {
  entries=new Array();
  for (var elc=0; elc<factoryQStats.childNodes.length; elc++) {
    var el=factoryQStats.childNodes[elc];
    if ((el.nodeType==1) && (el.nodeName=="entries")) {
      for (var etc=0; etc<el.childNodes.length; etc++) {
	var entry=el.childNodes[etc];
	if ((entry.nodeType==1)&&(entry.nodeName=="entry")) {
	  var entry_name=entry.attributes.getNamedItem("name");
	  entries.push(entry_name.value);
	}
      }
    }
  }
  return entries;
}
<commit_msg>Extract group names from every entry<commit_after>/*
 * Support javascript module for the gfactroy monitoring
 * Part of the gldieinWMS package
 *
 * Original repository: http://www.uscms.org/SoftwareComputing/Grid/WMS/glideinWMS/
 *
 */

// Load FactoryQStats XML file and return the object
function loadFactoryQStats() {
  var request =  new XMLHttpRequest();
  request.open("GET", "schedd_status.xml",false);
  request.send(null);

  var factoryQStats=request.responseXML.firstChild;
  return factoryQStats;
}

// Extract entry names from a factoryQStats XML object
function getFactoryEntries(factoryQStats) {
  entries=new Array();
  for (var elc=0; elc<factoryQStats.childNodes.length; elc++) {
    var el=factoryQStats.childNodes[elc];
    if ((el.nodeType==1) && (el.nodeName=="entries")) {
      for (var etc=0; etc<el.childNodes.length; etc++) {
	var entry=el.childNodes[etc];
	if ((entry.nodeType==1)&&(entry.nodeName=="entry")) {
	  var entry_name=entry.attributes.getNamedItem("name");
	  entries.push(entry_name.value);
	}
      }
    }
  }
  return entries;
}

// Extract group names from each entry XML object
function getFactoryEntryGroups(factoryQStats) {
  groups=new Array();
  for (var elc=0; elc<factoryQStats.childNodes.length; elc++) {
    var el=factoryQStats.childNodes[elc];
    if ((el.nodeType==1) && (el.nodeName=="entries")) {
      for (var etc=0; etc<el.childNodes.length; etc++) {
	var entry=el.childNodes[etc];
	if ((entry.nodeType==1)&&(entry.nodeName=="entry")) {
	  var entry_name=entry.attributes.getNamedItem("name");
          for (var etgs=0; etgs<entry.childNodes.length; etgs++) {
            var grps=entry.childNodes[etgs];
	    if ((grps.nodeType==1)&&(grps.nodeName=="monitor")) {
              for (var etg=0; etg<grps.childNodes.length; etg++) {
                var grp=grps.childNodes[etg];
	        if ((grp.nodeType==1)&&(grp.nodeName=="group")) {
	          var group_name=grp.attributes.getNamedItem("name");
                  if (group_name.value in groups) {
                    (groups[group_name.value]).push(entry_name.value);
                  }
                  else {
                    groups[group_name.value] = new Array();
                    (groups[group_name.value]).push(entry_name.value);
                  }
	          //groups.push(group_name.value);
                }
              }
            }
	  }
	}
      }
    }
  }
  return groups;
}
<|endoftext|>


<commit_before>'use strict';

class FormePageLocation {
    constructor(form, destination) {
        this._form = form;
        this._destination = destination;
    };

    //private properties
    get _name() {
        //page location doesn't have a name, so we have to use teh destination instead
        //each destination should be unique (within a single form)
        return this._destination;
    }

    get _inputs() {
        return null;
    }

    get _url() {
        return this._destination;
    }

    //private methods
    _build() {
        return Promise.resolve(this);
    }

    _validate() {
        return Promise.resolve();
    }

    _success() {
        return Promise.resolve();
    }

    _fail() {
        return Promise.resolve();
    }

    _submit() {
        return Promise.resolve();
    }

    _done() {
        return Promise.resolve();
    }

    _nextActionHandler() {
        return Promise.resolve();
    }
}

//expose
module.exports = FormePageLocation;<commit_msg>added some missing place holder vars in pageLocation class.<commit_after>'use strict';

class FormePageLocation {
    constructor(form, destination) {
        this._form = form;
        this._destination = destination;
    };

    //private properties
    get _name() {
        //page location doesn't have a name, so we have to use teh destination instead
        //each destination should be unique (within a single form)
        return this._destination;
    }

    get _inputs() {
        return null;
    }

    get _url() {
        return this._destination;
    }

    get _loadHandlers() {
        return null;
    };

    get _buildHandlers() {
        return null;
    };

    get _actionHandlers() {
        return null;
    };

    get _processHandlers() {
        return null;
    };

    get _validateHandlers() {
        return null;
    };

    get _executeHandlers() {
        return null;
    };

    get _successHandlers() {
        return null;
    };

    get _failHandlers() {
        return null;
    };

    get _submitHandlers() {
        return null;
    };

    get _doneHandlers() {
        return null;
    };

    //private methods
    _build() {
        return Promise.resolve(this);
    }

    _validate() {
        return Promise.resolve();
    }

    _success() {
        return Promise.resolve();
    }

    _fail() {
        return Promise.resolve();
    }

    _submit() {
        return Promise.resolve();
    }

    _done() {
        return Promise.resolve();
    }

    _nextActionHandler() {
        return Promise.resolve();
    }
}

//expose
module.exports = FormePageLocation;<|endoftext|>


<commit_before>// ==UserScript==
// @name         RohBot Imperial to Metric
// @version      1.17
// @description  Converts imperial to metric if it finds any
// @author       Spans
// @match        https://rohbot.net
// @grant        none
// @updateURL	 https://raw.githubusercontent.com/Spanfile/RohBot-Imperial-to-Metric-Converter/master/converter.js
// ==/UserScript==

chatMgr.lineFilter.add(function (line, prepend, e) {
	line.Content = applyConversions(line.Content);
});

String.prototype.splice = function(idx, rem, s) {
	return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};

var conversions = [
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(ft|feet|foot)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 3.2808 },
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(yd|yards|yard)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 1.0936 },
	{ name: "centimeters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(in|inches|inch|")(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.39370 },
	{ name: "kilometers", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(miles|mi)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.62137 },
	{ name: "Celsius", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(f|fahrenheit|degrees fahrenheit)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 1.8, subtract: 32},
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(lb|lbs|pounds|pound)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 2.2046 },
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(st|stone)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.157473 },
	{ name: "grams", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(oz|ounces|ounce)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.035274 },
	{ name: "liters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(gal|gallons|gallon)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.26417 },
	{ name: "KPH", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?) ?(mph|miles per hour)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 1/1.6093 },

	{ name: "meters", specialFunc: function(message) {
		// the ' there in the middle is for ' and " is for "
		var regex = /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)'([\d,]+(?:\.\d+)?)?(?:")?(?=\s|$|,|\.|!|\?|\*)/ig;
		var m;
		var results = [];
		while ((m = regex.exec(message)) !== null) {
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}

			var feet = m[1].replace(",", ""); // get rid of thousand separator commas
			var inches = 0;

			if (m[2] !== null) {
				inches = m[2].replace(",", ""); // get rid of thousand separator commas
			}

			var convertedFeet = feet / 3.2808;
			var convertedInches = inches / 39.370;

			var total = Math.round((convertedFeet + convertedInches) * 100) / 100;
			results[results.length] = {original:m[0], index:m.index, conversion:total, unit:"meters"};
		}

		return results;
	}}
];

function applyConversions(message) {
	var results = [];

	// aggregate the results
	conversions.forEach(function(conversion) {
		var result = conversion.specialFunc ? conversion.specialFunc(message) : commonConversion(message, conversion.regex, conversion.divide, conversion.subtract || 0, conversion.name);

		if (result.length > 0) {
			//console.log(result);
			results[results.length] = result;
		}
	});

	// since the converters can return multiple conversions, flatten the results
	// the result looks like [[{stuff here}, {stuff here}], [{stuff here}, {stuff here}]]
	// flattening it turns it into [{stuff here}, {stuff here}, {stuff here}, {stuff here}]
	var flattened = [].concat.apply([], results);

	// sort them
	flattened.sort(function(a, b) {
		if (a.index > b.index) {
			return 1;
		}

		if (a.index < b.index) {
			return -1;
		}

		return 0;
	});

	var newMsg = message;
	var inserted = 0;
	// combine them all
	flattened.forEach(function(result) {
		var title = result.conversion.toLocaleString() + " " + result.unit;
		var original = result.original;
		var begin = "";

		// because the js regex engine doesn't support positive lookbehinds, the regexes return the whitespace before every match
		// most of the time they do it unless the match is at the start of the message
		// in case there is a whitespace, remove it and have one added before the  tag
		if (original.substring(0, 1) == " ") {
			original = original.substring(1);
			begin = " ";
		}

		var toInsert = begin + "" + original + "";
		newMsg = newMsg.splice(result.index + inserted, result.original.length, toInsert);
		inserted += toInsert.length - result.original.length;
	});

	return newMsg;
}

function commonConversion(message, regex, divide, subtract, unit) {
	var m;
	var results = [];
	while ((m = regex.exec(message)) !== null) {
		if (m.index === regex.lastIndex) {
			regex.lastIndex++;
		}

		var offset = 0;
		var amountStr = m[1];

		// remove leading comma if found
		if (amountStr.substring(0, 1) == ",") {
			amountStr = amountStr.substring(1);
			m[0] = m[0].substring(1);
			offset = 1;
		}

		var amount = Number(amountStr.replace(",", "")); // get rid of thousand separator commas
		var converted = Math.round(((amount - subtract) / divide) * 100) / 100;
		//console.log("Conversion: " + amount + " "  + m[2] + " to " + converted + " " + unit);
		results[results.length] = { original:m[0], index:m.index + offset, conversion:converted, unit:unit };
	}

	return results;
}
<commit_msg>Added support for thousands-prefixes<commit_after>// ==UserScript==
// @name         RohBot Imperial to Metric
// @version      1.18
// @description  Converts imperial to metric if it finds any
// @author       Spans
// @match        https://rohbot.net
// @grant        none
// @updateURL	 https://raw.githubusercontent.com/Spanfile/RohBot-Imperial-to-Metric-Converter/master/converter.js
// ==/UserScript==

chatMgr.lineFilter.add(function (line, prepend, e) {
	line.Content = applyConversions(line.Content);
});

String.prototype.splice = function(idx, rem, s) {
	return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};

var prefixes = {
	"k": 1000,
	"m": 1000000,
	"b": 1000000000
}

var conversions = [
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(ft|feet|foot)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 3.2808 },
	{ name: "meters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(yd|yards|yard)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 1.0936 },
	{ name: "centimeters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(in|inches|inch|")(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.39370 },
	{ name: "kilometers", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(miles|mi)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.62137 },
	{ name: "Celsius", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(f|fahrenheit|degrees fahrenheit)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 1.8, subtract: 32},
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(lb|lbs|pounds|pound)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 2.2046 },
	{ name: "kilograms", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(st|stone)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.157473 },
	{ name: "grams", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(oz|ounces|ounce)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.035274 },
	{ name: "liters", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(gal|gallons|gallon)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 0.26417 },
	{ name: "KPH", regex: /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])? ?(mph|miles per hour)(?=\s|$|,|\.|!|\?|\*)/ig, divide: 1/1.6093 },

	{ name: "meters", specialFunc: function(message) {
		// the ' there in the middle is for ' and " is for "
		var regex = /(?:\s|^|,|\.|!|\?|\*)([\d,]+(?:\.\d+)?)([kmb])?'([\d,]+(?:\.\d+)?)([kmb])??(?:")?(?=\s|$|,|\.|!|\?|\*)/ig;
		var m;
		var results = [];
		while ((m = regex.exec(message)) !== null) {
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}

			var feet = m[1].replace(",", ""); // get rid of thousand separator commas
			var inches = 0;

			if (m[2] !== null) {
				inches = m[2].replace(",", ""); // get rid of thousand separator commas
			}

			var convertedFeet = feet / 3.2808;
			var convertedInches = inches / 39.370;

			var total = Math.round((convertedFeet + convertedInches) * 100) / 100;
			results[results.length] = {original:m[0], index:m.index, conversion:total, unit:"meters"};
		}

		return results;
	}}
];

function applyConversions(message) {
	var results = [];

	// aggregate the results
	conversions.forEach(function(conversion) {
		var result = conversion.specialFunc ? conversion.specialFunc(message) : commonConversion(message, conversion.regex, conversion.divide, conversion.subtract || 0, conversion.name);

		if (result.length > 0) {
			//console.log(result);
			results[results.length] = result;
		}
	});

	// since the converters can return multiple conversions, flatten the results
	// the result looks like [[{stuff here}, {stuff here}], [{stuff here}, {stuff here}]]
	// flattening it turns it into [{stuff here}, {stuff here}, {stuff here}, {stuff here}]
	var flattened = [].concat.apply([], results);

	// sort them
	flattened.sort(function(a, b) {
		if (a.index > b.index) {
			return 1;
		}

		if (a.index < b.index) {
			return -1;
		}

		return 0;
	});

	var newMsg = message;
	var inserted = 0;
	// combine them all
	flattened.forEach(function(result) {
		var title = result.conversion.toLocaleString() + " " + result.unit;
		var original = result.original;
		var begin = "";

		// because the js regex engine doesn't support positive lookbehinds, the regexes return the whitespace before every match
		// most of the time they do it unless the match is at the start of the message
		// in case there is a whitespace, remove it and have one added before the  tag
		if (original.substring(0, 1) == " ") {
			original = original.substring(1);
			begin = " ";
		}

		var toInsert = begin + "" + original + "";
		newMsg = newMsg.splice(result.index + inserted, result.original.length, toInsert);
		inserted += toInsert.length - result.original.length;
	});

	return newMsg;
}

function commonConversion(message, regex, divide, subtract, unit) {
	var m;
	var results = [];
	while ((m = regex.exec(message)) !== null) {
		if (m.index === regex.lastIndex) {
			regex.lastIndex++;
		}

		var offset = 0;
		var amountStr = m[1];
		var prefix = m[2];

		// remove leading comma if found
		if (amountStr.substring(0, 1) == ",") {
			amountStr = amountStr.substring(1);
			m[0] = m[0].substring(1);
			offset = 1;
		}

		var amount = Number(amountStr.replace(",", "")); // get rid of thousand separator commas

		if (prefix) {
				amount *= prefixes[prefix];
			}

		var converted = Math.round(((amount - subtract) / divide) * 100) / 100;
		//console.log("Conversion: " + amount + " "  + m[2] + " to " + converted + " " + unit);
		results[results.length] = { original:m[0], index:m.index + offset, conversion:converted, unit:unit };
	}

	return results;
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         RohBot Currency Converter
// @version      1.7
// @description  Allows the user to select their currency and then converts any found currencies to the one the user selected
// @author       Spans
// @match        https://rohbot.net
// @grant        none
// @updateURL	 https://raw.githubusercontent.com/Spanfile/RohBot-Currency-Converter/master/converter.js
// @require		 http://openexchangerates.github.io/money.js/money.min.js
// @require		 http://code.jquery.com/jquery-2.1.4.min.js
// ==/UserScript==

// first of all, setup the currency conversion
$.getJSON("https://api.fixer.io/latest", function(data) {
	if (typeof fx !== "undefined" && fx.rates) {
		fx.rates = data.rates;
		fx.base = data.base;
	} else {
		var fxSetup = {
			rates: data.rates,
			base: base.rates
		};
	}

	//console.log("Currency test: €1 = $" + fx(1).from("EUR").to("USD"));
});

chatMgr.lineFilter.add(function(line, prepend, e) {
	line.Content = applyConversions(line.Content);
});

var user = "eur";

// the £ is for £
var currencies = {
	usd: { regexes: [ /(?:\s|^)\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig, /(?:\s|^)(\d+(?:(?:\.|,)\d+)?)(?: dollars)(?=\s|$)/ig ], name: "USD" },
	eur: { regexes: [ /(?:\s|^)(\d+(?:(?:\.|,)\d+)?)€(?=\s|$)/ig ], name: "EUR" },
	gbp: { regexes: [ /(?:\s|^)(\d+(?:(?:\.|,)\d+)?)£(?=\s|$)/ig ], name: "GBP" },
	cad: { regexes: [ /(?:\s|^)CA\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig ], name: "CAD" },
	aud: { regexes: [ /(?:\s|^)A\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig ], name: "AUD" },
	nzd: { regexes: [ /(?:\s|^)NZ\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig ], name: "NZD" },
	sek: { regexes: [ /(?:\s|^)(\d+(?:(?:\.|,)\d+)?) ?kr(?=\s|$)/ig ], name: "SEK" },
};

function applyConversions(message) {
	var results = [];
	var userCurrency = currencies[user.toLowerCase()]; // toLowerCase() in case it's in upper case

	// try to find and convert any currencies except the users currency found in the message to the users currency
	for (var key in currencies) {
		if (currencies.hasOwnProperty(key)) { // hasOwnProperty() makes sure we don't loop over stuff inherited from the object's prototype
			var currency = currencies[key];

			if (currency.name != userCurrency.name) {
				var result = commonConversion(message, currency, userCurrency);

				if (result.length > 0) {
					results.push(result);
				}
			}
		}
	}

	// since the converters can return multiple conversions, flatten the results
	// the result looks like [[{stuff here}, {stuff here}], [{stuff here}, {stuff here}]]
	// flattening it turns it into [{stuff here}, {stuff here}, {stuff here}, {stuff here}]
	var flattened = [].concat.apply([], results);

	// sort them
	flattened.sort(function(a, b) {
		if (a.index > b.index) {
			return 1;
		}

		if (a.index < b.index) {
			return -1;
		}

		return 0;
	});

	var newMsg = message;
	var inserted = 0;
	// combine them all
	flattened.forEach(function(result) {
		var title = result.conversion.toLocaleString("en-IN", {style: "currency", currency: result.unit});
		var original = result.original;
		var begin = "";

		// because the js regex engine doesn't support positive lookbehinds, the regexes return the whitespace before every match
		// most of the time they do it unless the match is at the start of the message
		// in case there is a whitespace, remove it and have one added before the  tag
		if (original.substring(0, 1) == " ") {
			original = original.substring(1);
			begin = " ";
		}

		var toInsert = begin + "" + original + "";
		newMsg = newMsg.splice(result.index + inserted, result.original.length, toInsert);
		inserted += toInsert.length - result.original.length;
	});

	return newMsg;
}

function commonConversion(message, from, to) {
	var m;
	var results = [];

	from.regexes.forEach(function(regex) {
		while ((m = regex.exec(message)) !== null) {
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}

			var amount = Number(m[1].replace(',', '.')); // js wants dots as decimal separators
			var converted = Math.round(fx(amount).from(from.name).to(to.name) * 100) / 100; // two decimals is enough for currencies

			results[results.length] = {original:m[0], index:m.index, conversion:converted, unit:to.name};
		}
	});

	return results;
}

String.prototype.splice = function(idx, rem, s) {
	return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};
<commit_msg>Added support for 'n eur/o/os' notation<commit_after>// ==UserScript==
// @name         RohBot Currency Converter
// @version      1.8
// @description  Allows the user to select their currency and then converts any found currencies to the one the user selected
// @author       Spans
// @match        https://rohbot.net
// @grant        none
// @updateURL	 https://raw.githubusercontent.com/Spanfile/RohBot-Currency-Converter/master/converter.js
// @require		 http://openexchangerates.github.io/money.js/money.min.js
// @require		 http://code.jquery.com/jquery-2.1.4.min.js
// ==/UserScript==

// first of all, setup the currency conversion
$.getJSON("https://api.fixer.io/latest", function(data) {
	if (typeof fx !== "undefined" && fx.rates) {
		fx.rates = data.rates;
		fx.base = data.base;
	} else {
		var fxSetup = {
			rates: data.rates,
			base: base.rates
		};
	}

	//console.log("Currency test: €1 = $" + fx(1).from("EUR").to("USD"));
});

chatMgr.lineFilter.add(function(line, prepend, e) {
	line.Content = applyConversions(line.Content);
});

var user = "eur";

// the £ is for £
var currencies = {
	usd: { regexes: [ /(?:\s|^)\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig, /(?:\s|^)(\d+(?:(?:\.|,)\d+)?)(?: dollars)(?=\s|$)/ig ], name: "USD" },
	eur: { regexes: [ /(?:\s|^)(\d+(?:(?:\.|,)\d+)?)(?:€|e| eur(?:o|os)?)?(?=\s|$)/ig ], name: "EUR" },
	gbp: { regexes: [ /(?:\s|^)(\d+(?:(?:\.|,)\d+)?)£(?=\s|$)/ig ], name: "GBP" },
	cad: { regexes: [ /(?:\s|^)CA\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig ], name: "CAD" },
	aud: { regexes: [ /(?:\s|^)A\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig ], name: "AUD" },
	nzd: { regexes: [ /(?:\s|^)NZ\$(\d+(?:(?:\.|,)\d+)?)(?=\s|$)/ig ], name: "NZD" },
	sek: { regexes: [ /(?:\s|^)(\d+(?:(?:\.|,)\d+)?) ?kr(?=\s|$)/ig ], name: "SEK" },
};

function applyConversions(message) {
	var results = [];
	var userCurrency = currencies[user.toLowerCase()]; // toLowerCase() in case it's in upper case

	// try to find and convert any currencies except the users currency found in the message to the users currency
	for (var key in currencies) {
		if (currencies.hasOwnProperty(key)) { // hasOwnProperty() makes sure we don't loop over stuff inherited from the object's prototype
			var currency = currencies[key];

			if (currency.name != userCurrency.name) {
				var result = commonConversion(message, currency, userCurrency);

				if (result.length > 0) {
					results.push(result);
				}
			}
		}
	}

	// since the converters can return multiple conversions, flatten the results
	// the result looks like [[{stuff here}, {stuff here}], [{stuff here}, {stuff here}]]
	// flattening it turns it into [{stuff here}, {stuff here}, {stuff here}, {stuff here}]
	var flattened = [].concat.apply([], results);

	// sort them
	flattened.sort(function(a, b) {
		if (a.index > b.index) {
			return 1;
		}

		if (a.index < b.index) {
			return -1;
		}

		return 0;
	});

	var newMsg = message;
	var inserted = 0;
	// combine them all
	flattened.forEach(function(result) {
		var title = result.conversion.toLocaleString("en-IN", {style: "currency", currency: result.unit});
		var original = result.original;
		var begin = "";

		// because the js regex engine doesn't support positive lookbehinds, the regexes return the whitespace before every match
		// most of the time they do it unless the match is at the start of the message
		// in case there is a whitespace, remove it and have one added before the  tag
		if (original.substring(0, 1) == " ") {
			original = original.substring(1);
			begin = " ";
		}

		var toInsert = begin + "" + original + "";
		newMsg = newMsg.splice(result.index + inserted, result.original.length, toInsert);
		inserted += toInsert.length - result.original.length;
	});

	return newMsg;
}

function commonConversion(message, from, to) {
	var m;
	var results = [];

	from.regexes.forEach(function(regex) {
		while ((m = regex.exec(message)) !== null) {
			if (m.index === regex.lastIndex) {
				regex.lastIndex++;
			}

			var amount = Number(m[1].replace(',', '.')); // js wants dots as decimal separators
			var converted = Math.round(fx(amount).from(from.name).to(to.name) * 100) / 100; // two decimals is enough for currencies

			results[results.length] = {original:m[0], index:m.index, conversion:converted, unit:to.name};
		}
	});

	return results;
}

String.prototype.splice = function(idx, rem, s) {
	return (this.slice(0, idx) + s + this.slice(idx + Math.abs(rem)));
};
<|endoftext|>


<commit_before>'use strict';

var ParserStream = require('../common').ParserStream;
var once         = require('../common').once;

function readIFDValue(tiff_sig, data, data_offset) {
  var endianness = (tiff_sig[0] === 'M' ? 'BE' : 'LE');
  var type       = data['readUInt16' + endianness](data_offset + 2);
  var values     = data['readUInt16' + endianness](data_offset + 4);

  if (values !== 1 && (type !== 3 && type !== 4)) {
    return null;
  }

  var depth = (type === 3 ? '16' : '32');

  return data['readUInt' + depth + endianness](data_offset + 8);
}

module.exports = function (input, _callback) {
  var callback = once(_callback);
  var parser = new ParserStream();

  parser.on('unpipe', function () {
    callback();
    return;
  });

  // read header
  parser._bytes(8, function (data) {
    // check TIFF signature
    var sig = data.toString('binary', 0, 4);

    if (sig !== 'II\x2A\0' && sig !== 'MM\0\x2A') {
      parser._skipBytes(Infinity);
      callback();
      return;
    }

    var readUInt16 = (sig[0] === 'M' ? 'readUInt16BE' : 'readUInt16LE');
    var readUInt32 = (sig[0] === 'M' ? 'readUInt32BE' : 'readUInt32LE');

    var count = data[readUInt32](4) - 8;

    if (count < 0) {
      parser._skipBytes(Infinity);
      callback();
      return;
    }

    // skip until IFD
    parser._skipBytes(count, function () {
      // read number of IFD entries
      parser._bytes(2, function (data) {
        var count = data[readUInt16](0) * 12;

        // read all IFD entries
        parser._bytes(count, function (data) {
          parser._skipBytes(Infinity);

          var i, width, height, tag;

          for (i = 0; i < data.length; i += 12) {
            tag = data[readUInt16](i);

            if (tag === 256) {
              width = readIFDValue(sig, data, i);
            } else if (tag === 257) {
              height = readIFDValue(sig, data, i);
            }
          }

          if (width && height) {
            callback(null, {
              width:  width,
              height: height,
              type:   'tiff',
              mime:   'image/tiff'
            });
          }
        });
      });
    });
  });

  input.pipe(parser);
};
<commit_msg>fix edge case when passing zero value to skipBytes<commit_after>'use strict';

var ParserStream = require('../common').ParserStream;
var once         = require('../common').once;

function readIFDValue(tiff_sig, data, data_offset) {
  var endianness = (tiff_sig[0] === 'M' ? 'BE' : 'LE');
  var type       = data['readUInt16' + endianness](data_offset + 2);
  var values     = data['readUInt16' + endianness](data_offset + 4);

  if (values !== 1 && (type !== 3 && type !== 4)) {
    return null;
  }

  var depth = (type === 3 ? '16' : '32');

  return data['readUInt' + depth + endianness](data_offset + 8);
}

module.exports = function (input, _callback) {
  var callback = once(_callback);
  var parser = new ParserStream();

  parser.on('unpipe', function () {
    callback();
    return;
  });

  // read header
  parser._bytes(8, function (data) {
    // check TIFF signature
    var sig = data.toString('binary', 0, 4);

    if (sig !== 'II\x2A\0' && sig !== 'MM\0\x2A') {
      parser._skipBytes(Infinity);
      callback();
      return;
    }

    var readUInt16 = (sig[0] === 'M' ? 'readUInt16BE' : 'readUInt16LE');
    var readUInt32 = (sig[0] === 'M' ? 'readUInt32BE' : 'readUInt32LE');

    var count = data[readUInt32](4) - 8;

    if (count < 0) {
      parser._skipBytes(Infinity);
      callback();
      return;
    }

    function safeSkip(parser, count, callback) {
      if (count === 0) { // parser._skipBytes throws error if count === 0
        callback();
        return;
      }

      parser._skipBytes(count, callback);
    }

    // skip until IFD
    safeSkip(parser, count, function () {
      // read number of IFD entries
      parser._bytes(2, function (data) {
        var count = data[readUInt16](0) * 12;

        // read all IFD entries
        parser._bytes(count, function (data) {
          parser._skipBytes(Infinity);

          var i, width, height, tag;

          for (i = 0; i < data.length; i += 12) {
            tag = data[readUInt16](i);

            if (tag === 256) {
              width = readIFDValue(sig, data, i);
            } else if (tag === 257) {
              height = readIFDValue(sig, data, i);
            }
          }

          if (width && height) {
            callback(null, {
              width:  width,
              height: height,
              type:   'tiff',
              mime:   'image/tiff'
            });
          }
        });
      });
    });
  });

  input.pipe(parser);
};
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var url = require('url')
  , util = require('util')
  , Strategy = require('passport-strategy')
  , CAS = require('cas');

/**
 * Creates an instance of `CasStrategy`.
 *
 * CAS stands for Central Authentication Service, and is a single sign-on
 * solution for the web.
 *
 * Authentication is done by redirecting the user to the CAS login page. The
 * user will return with a ticket in the querystring. This ticket is then
 * validated by the application against the CAS server to obtain the username
 * and profile.
 *
 * (CAS optionally allows the application to obtain tickets for 3rd party
 * services on behalf of the user. This requires the use of a PGT callback
 * server, which can be run with the PgtServer() function also from this
 * module.)
 *
 * Applications must supply a `verify` callback, for which the function
 * signature is:
 *
 *     function(username, profile, done) { ... }
 *
 * The verify callback is responsible for finding or creating the user, and
 * invoking `done` with the following arguments:
 *
 *     done(err, user, info);
 *
 * `user` should be set to `false` to indicate an authentication failure.
 * Additional `info` can optionally be passed as a third argument, typically
 * used to display informational messages.  If an exception occured, `err`
 * should be set.
 *
 * Options:
 *
 *   - `casURL`            URL of the CAS server (e.g. https://signin.example.com/cas)
 *   - `pgtURL`            Optional. URL of the PGT callback server (e.g. https://callback.example.com)
 *   - `sessionKey`        Optional. The name to use for storing CAS information within the `req.session` object. Default is 'cas'.
 *   - `propertyMap`       Optional. A basic key-value object for mapping extended user attributes from CAS to passport's profile format.
 *
 * Example:
 *
 *     var CasStrategy = require('passport-cas2').Strategy;
 *     var cas = new CasStrategy({
 *        casURL: 'https://signin.example.com/cas',
 *        propertyMap: {
 *          id: 'guid',
 *          givenName: 'givenname',
 *          familyName: 'surname',
 *          emails: 'defaultmail'
 *        }
 *     },
 *     function(username, profile, done) {
 *        User.findOrCreate(..., function(err, user) {
 *          done(err, user);
 *        });
 *     });
 *     passport.use(cas);
 *
 * @constructor
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function CasStrategy(options, verify) {
  if (typeof options == 'function') {
    verify = options;
    options = undefined;
  }
  options = options || {};

  if (!verify) { throw new TypeError('CasStrategy requires a verify callback'); }
  if (!options.casURL) { throw new TypeError('CasStrategy requires a casURL option'); }

  Strategy.call(this);
  this.name = 'cas';
  this._verify = verify;

  this.casBaseUrl = options.casURL;
  this.casPgtUrl = options.pgtURL || undefined;
  this.casPropertyMap = options.propertyMap || {};
  this.casSessionKey = options.sessionKey || 'cas';

  this.cas = new CAS({
    base_url: this.casBaseUrl,
    version: 2,
    external_pgt_url: this.casPgtUrl
  });

}

/**
 * Inherit from `Strategy`.
 */
util.inherits(CasStrategy, Strategy);

/**
 * Authenticate request by validating a ticket with the CAS server.
 *
 * @param {Object} req
 * @param {Object} options
 * @api protected
 */
CasStrategy.prototype.authenticate = function(req, options) {
  if (!req._passport) { return this.error(new Error('passport.initialize() middleware not in use')); }
  options = options || {};

  var self = this;
  var reqURL = url.parse(req.url, true);
  var service;

  // `ticket` is present if user is already authenticated/authorized by CAS
  var ticket = reqURL.query['ticket'];

  // The `service` string is the current URL, minus the ticket
  delete reqURL.query['ticket'];
  service = url.format({
    protocol: req.protocol || 'http',
    host: req.headers['host'],
    pathname: reqURL.pathname,
    query: reqURL.query
  });

  if (!ticket) {
    // Redirect to CAS server for authentication
    self.redirect(self.casBaseUrl + '/login?service=' + encodeURIComponent(service), 307);
  }
  else {
    // User has returned from CAS site with a ticket
    self.cas.validate(ticket, function(err, status, username, extended) {

      // Ticket validation failed
      if (err) {
        var date = new Date();
        var token = Math.round(date.getTime() / 60000);
        if (req.query['_cas_retry'] != token) {
            // There was a CAS error. A common cause is when an old
            // `ticket` portion of the querystring remains after the
            // session times out and the user refreshes the page.
            // So remove the `ticket` and try again.
            var url = req.url
                .replace(/_cas_retry=\d+&?/, '')
                .replace(/([?&])ticket=[\w-]+/, '$1_cas_retry='+token);
            self.redirect(url, 307);
        } else {
            // Already retried. There is no way to recover from this.
            self.fail(err.message);
        }
      }

      // Validation successful
      else {
        // The provided `verify` callback will call this on completion
        function verified(err, user, info) {
          if (err) { return self.error(err); }
          if (!user) { return self.fail(info); }
          self.success(user, info);
        }

        if (self.casPgtUrl) {
          req.session[self.casSessionKey].PGTIOU = extended.PGTIOU;
        }

        var attributes = extended.attributes;
        var profile = {
          provider: 'CAS',
          id: extended.id || username,
          displayName: attributes.displayName || username,
          name: {
            familyName: null,
            givenName: null,
            middleName: null
          },
          emails: []
        };

        // Map relevant extended attributes returned by CAS into the profile
        for (var key in profile) {
          if (key == 'name') {
            for (var subKey in profile[key]) {
              var mappedKey = self.casPropertyMap[subKey] || subKey;
              var value = attributes[mappedKey];
              if (Array.isArray(value)) {
                profile.name[subKey] = value[0];
              } else {
                profile.name[subKey] = value;
              }
              delete attributes[mappedKey];
            }
          }
          else if (key == 'emails') {
            var mappedKey = self.casPropertyMap.emails || 'emails';
            var emails = attributes[mappedKey];
            if (Array.isArray(emails)) {
              if (typeof emails[0] == 'object') {
                profile.emails = emails;
              }
              else {
                for (var i=0; i<emails.length; i++) {
                  profile.emails.push({
                    'value': emails[i],
                    'type': 'default'
                  });
                }
              }
            }
            else {
              profile.emails = [emails];
            }
            delete attributes[mappedKey];
          }
          else {
            var mappedKey = self.casPropertyMap[key] || key;
            var value = attributes[mappedKey];
            if (Array.isArray(value)) {
              profile[key] = value[0];
            }
            else if (value) {
              profile[key] = value;
            }
            delete attributes[mappedKey];
          }
        }
        // Add remaining attributes to the profile object
        for (var key in attributes) {
          profile[key] = attributes[key];
        }

        self._verify(username, profile, verified);
      }

    }, service);
  }
};

/**
 * Log the user out of the application site, and also out of CAS.
 *
 * @param (Object) req
 * @param (Object) res
 * @param {String} returnUrl
 * @api public
 */
CasStrategy.prototype.logout = function(req, res, returnUrl) {
  req.logout();
  if (returnUrl) {
    this.cas.logout(req, res, returnUrl, true);
  } else {
    this.cas.logout(req, res);
  }
};

/**
 * Request a CAS ticket for accessing a service on behalf of the logged in user.
 * This ticket is to be added to the service's query string.
 *
 * Example:
 *
 *      var serviceURL = 'http://example.com/get/my/data';
 *      cas.getProxyTicket(req, serviceURL, function(err, ticket) {
 *          if (!err) {
 *              serviceURL += '?ticket=' + ticket;
 *              request(serviceURL, ... ); // request the service
 *          }
 *      });
 *
 * @param {Object} req
 *      HTTPRequest object from Connect/Express
 * @param {String} targetService
 *      The URL of service being requested on behalf of the user
 * @param {Function} done
 *      Completion callback with signature `fn(err, ticket)`
 * @api public
 */
CasStrategy.prototype.getProxyTicket = function(req, targetService, done) {
  var err, pgtiou;
  if (!req.session) {
    err = new Error('Session is not found');
  }
  else if (!req.session[this.casSessionKey]) {
    err = new Error('User is not authenticated with CAS');
  }
  else {
    pgtiou = req.session[this.casSessionKey].PGTIOU;
    if (!pgtiou) {
      err = new Error('PGTIOU token not found. Make sure pgtURL option is correct, and the CAS server allows proxies.');
    }
  }

  if (err) {
    return done(err);
  }
  else {
    this.cas.getProxyTicket(pgtiou, targetService, function(err, PT) {
      done(err, PT);
    });
  }
}

/**
 * Expose `CasStrategy`.
 */
module.exports.Strategy = CasStrategy;

/**
 * Start a CAS PGT callback server. PGT stands for proxy granting ticket.
 *
 * This is the server needed to obtain CAS tickets for 3rd party services on
 * behalf of the user. It is typically run as a separate process from the
 * application. Multiple applications may share the same PGT callback server.
 *
 * @param {String} casURL
 *      The URL of the CAS server.
 * @param {String} pgtURL
 *      The URL of this PGT callback server. It must use HTTPS and be accessible
 *      by the CAS server over the network.
 *      The 3rd party services you request may need to add this URL as a trusted
 *      proxy as well.
 * @param {String} serverCertificate
 *      The SSL certificate for this PGT callback server.
 * @param {String} serverKey
 *      The key for the SSL certificate.
 * @api public
 */
function PgtServer(casURL, pgtURL, serverCertificate, serverKey) {
  var parsedURL = url.parse(pgtURL);
  var cas = new CAS({
    base_url: casURL,
    version: 2.0,
    proxy_server: true,
    proxy_callback_host: parsedURL.hostname,
    proxy_callback_port: parsedURL.port,
    proxy_server_key: options.serverKey,
    proxy_server_cert: options.serverCertificate
  });
}

/**
 * Expose `PgtServer`.
 */
module.exports.PgtServer = PgtServer;
 <commit_msg>Removed reference to non-existent `options` object<commit_after>/**
 * Module dependencies.
 */
var url = require('url')
  , util = require('util')
  , Strategy = require('passport-strategy')
  , CAS = require('cas');

/**
 * Creates an instance of `CasStrategy`.
 *
 * CAS stands for Central Authentication Service, and is a single sign-on
 * solution for the web.
 *
 * Authentication is done by redirecting the user to the CAS login page. The
 * user will return with a ticket in the querystring. This ticket is then
 * validated by the application against the CAS server to obtain the username
 * and profile.
 *
 * (CAS optionally allows the application to obtain tickets for 3rd party
 * services on behalf of the user. This requires the use of a PGT callback
 * server, which can be run with the PgtServer() function also from this
 * module.)
 *
 * Applications must supply a `verify` callback, for which the function
 * signature is:
 *
 *     function(username, profile, done) { ... }
 *
 * The verify callback is responsible for finding or creating the user, and
 * invoking `done` with the following arguments:
 *
 *     done(err, user, info);
 *
 * `user` should be set to `false` to indicate an authentication failure.
 * Additional `info` can optionally be passed as a third argument, typically
 * used to display informational messages.  If an exception occured, `err`
 * should be set.
 *
 * Options:
 *
 *   - `casURL`            URL of the CAS server (e.g. https://signin.example.com/cas)
 *   - `pgtURL`            Optional. URL of the PGT callback server (e.g. https://callback.example.com)
 *   - `sessionKey`        Optional. The name to use for storing CAS information within the `req.session` object. Default is 'cas'.
 *   - `propertyMap`       Optional. A basic key-value object for mapping extended user attributes from CAS to passport's profile format.
 *
 * Example:
 *
 *     var CasStrategy = require('passport-cas2').Strategy;
 *     var cas = new CasStrategy({
 *        casURL: 'https://signin.example.com/cas',
 *        propertyMap: {
 *          id: 'guid',
 *          givenName: 'givenname',
 *          familyName: 'surname',
 *          emails: 'defaultmail'
 *        }
 *     },
 *     function(username, profile, done) {
 *        User.findOrCreate(..., function(err, user) {
 *          done(err, user);
 *        });
 *     });
 *     passport.use(cas);
 *
 * @constructor
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function CasStrategy(options, verify) {
  if (typeof options == 'function') {
    verify = options;
    options = undefined;
  }
  options = options || {};

  if (!verify) { throw new TypeError('CasStrategy requires a verify callback'); }
  if (!options.casURL) { throw new TypeError('CasStrategy requires a casURL option'); }

  Strategy.call(this);
  this.name = 'cas';
  this._verify = verify;

  this.casBaseUrl = options.casURL;
  this.casPgtUrl = options.pgtURL || undefined;
  this.casPropertyMap = options.propertyMap || {};
  this.casSessionKey = options.sessionKey || 'cas';

  this.cas = new CAS({
    base_url: this.casBaseUrl,
    version: 2,
    external_pgt_url: this.casPgtUrl
  });

}

/**
 * Inherit from `Strategy`.
 */
util.inherits(CasStrategy, Strategy);

/**
 * Authenticate request by validating a ticket with the CAS server.
 *
 * @param {Object} req
 * @param {Object} options
 * @api protected
 */
CasStrategy.prototype.authenticate = function(req, options) {
  if (!req._passport) { return this.error(new Error('passport.initialize() middleware not in use')); }
  options = options || {};

  var self = this;
  var reqURL = url.parse(req.url, true);
  var service;

  // `ticket` is present if user is already authenticated/authorized by CAS
  var ticket = reqURL.query['ticket'];

  // The `service` string is the current URL, minus the ticket
  delete reqURL.query['ticket'];
  service = url.format({
    protocol: req.protocol || 'http',
    host: req.headers['host'],
    pathname: reqURL.pathname,
    query: reqURL.query
  });

  if (!ticket) {
    // Redirect to CAS server for authentication
    self.redirect(self.casBaseUrl + '/login?service=' + encodeURIComponent(service), 307);
  }
  else {
    // User has returned from CAS site with a ticket
    self.cas.validate(ticket, function(err, status, username, extended) {

      // Ticket validation failed
      if (err) {
        var date = new Date();
        var token = Math.round(date.getTime() / 60000);
        if (req.query['_cas_retry'] != token) {
            // There was a CAS error. A common cause is when an old
            // `ticket` portion of the querystring remains after the
            // session times out and the user refreshes the page.
            // So remove the `ticket` and try again.
            var url = req.url
                .replace(/_cas_retry=\d+&?/, '')
                .replace(/([?&])ticket=[\w-]+/, '$1_cas_retry='+token);
            self.redirect(url, 307);
        } else {
            // Already retried. There is no way to recover from this.
            self.fail(err.message);
        }
      }

      // Validation successful
      else {
        // The provided `verify` callback will call this on completion
        function verified(err, user, info) {
          if (err) { return self.error(err); }
          if (!user) { return self.fail(info); }
          self.success(user, info);
        }

        if (self.casPgtUrl) {
          req.session[self.casSessionKey].PGTIOU = extended.PGTIOU;
        }

        var attributes = extended.attributes;
        var profile = {
          provider: 'CAS',
          id: extended.id || username,
          displayName: attributes.displayName || username,
          name: {
            familyName: null,
            givenName: null,
            middleName: null
          },
          emails: []
        };

        // Map relevant extended attributes returned by CAS into the profile
        for (var key in profile) {
          if (key == 'name') {
            for (var subKey in profile[key]) {
              var mappedKey = self.casPropertyMap[subKey] || subKey;
              var value = attributes[mappedKey];
              if (Array.isArray(value)) {
                profile.name[subKey] = value[0];
              } else {
                profile.name[subKey] = value;
              }
              delete attributes[mappedKey];
            }
          }
          else if (key == 'emails') {
            var mappedKey = self.casPropertyMap.emails || 'emails';
            var emails = attributes[mappedKey];
            if (Array.isArray(emails)) {
              if (typeof emails[0] == 'object') {
                profile.emails = emails;
              }
              else {
                for (var i=0; i<emails.length; i++) {
                  profile.emails.push({
                    'value': emails[i],
                    'type': 'default'
                  });
                }
              }
            }
            else {
              profile.emails = [emails];
            }
            delete attributes[mappedKey];
          }
          else {
            var mappedKey = self.casPropertyMap[key] || key;
            var value = attributes[mappedKey];
            if (Array.isArray(value)) {
              profile[key] = value[0];
            }
            else if (value) {
              profile[key] = value;
            }
            delete attributes[mappedKey];
          }
        }
        // Add remaining attributes to the profile object
        for (var key in attributes) {
          profile[key] = attributes[key];
        }

        self._verify(username, profile, verified);
      }

    }, service);
  }
};

/**
 * Log the user out of the application site, and also out of CAS.
 *
 * @param (Object) req
 * @param (Object) res
 * @param {String} returnUrl
 * @api public
 */
CasStrategy.prototype.logout = function(req, res, returnUrl) {
  req.logout();
  if (returnUrl) {
    this.cas.logout(req, res, returnUrl, true);
  } else {
    this.cas.logout(req, res);
  }
};

/**
 * Request a CAS ticket for accessing a service on behalf of the logged in user.
 * This ticket is to be added to the service's query string.
 *
 * Example:
 *
 *      var serviceURL = 'http://example.com/get/my/data';
 *      cas.getProxyTicket(req, serviceURL, function(err, ticket) {
 *          if (!err) {
 *              serviceURL += '?ticket=' + ticket;
 *              request(serviceURL, ... ); // request the service
 *          }
 *      });
 *
 * @param {Object} req
 *      HTTPRequest object from Connect/Express
 * @param {String} targetService
 *      The URL of service being requested on behalf of the user
 * @param {Function} done
 *      Completion callback with signature `fn(err, ticket)`
 * @api public
 */
CasStrategy.prototype.getProxyTicket = function(req, targetService, done) {
  var err, pgtiou;
  if (!req.session) {
    err = new Error('Session is not found');
  }
  else if (!req.session[this.casSessionKey]) {
    err = new Error('User is not authenticated with CAS');
  }
  else {
    pgtiou = req.session[this.casSessionKey].PGTIOU;
    if (!pgtiou) {
      err = new Error('PGTIOU token not found. Make sure pgtURL option is correct, and the CAS server allows proxies.');
    }
  }

  if (err) {
    return done(err);
  }
  else {
    this.cas.getProxyTicket(pgtiou, targetService, function(err, PT) {
      done(err, PT);
    });
  }
}

/**
 * Expose `CasStrategy`.
 */
module.exports.Strategy = CasStrategy;

/**
 * Start a CAS PGT callback server. PGT stands for proxy granting ticket.
 *
 * This is the server needed to obtain CAS tickets for 3rd party services on
 * behalf of the user. It is typically run as a separate process from the
 * application. Multiple applications may share the same PGT callback server.
 *
 * @param {String} casURL
 *      The URL of the CAS server.
 * @param {String} pgtURL
 *      The URL of this PGT callback server. It must use HTTPS and be accessible
 *      by the CAS server over the network.
 *      The 3rd party services you request may need to add this URL as a trusted
 *      proxy as well.
 * @param {String} serverCertificate
 *      The SSL certificate for this PGT callback server.
 * @param {String} serverKey
 *      The key for the SSL certificate.
 * @api public
 */
function PgtServer(casURL, pgtURL, serverCertificate, serverKey) {
  var parsedURL = url.parse(pgtURL);
  var cas = new CAS({
    base_url: casURL,
    version: 2.0,
    proxy_server: true,
    proxy_callback_host: parsedURL.hostname,
    proxy_callback_port: parsedURL.port,
    proxy_server_key: serverKey,
    proxy_server_cert: serverCertificate
  });
}

/**
 * Expose `PgtServer`.
 */
module.exports.PgtServer = PgtServer;
 <|endoftext|>


<commit_before>// Parse pianod responses (yes, it sadly takes this much code)

var codeMap = require('./codeMap')

exports.parse = function(data, self) {
  code = parseInt(data.slice(0,3))

  if ([101,102,106].indexOf(code) !== -1) {
    var time = data
      .slice(4,22)
      .replace('-','')
      .split('/')
      .map(function(t) {
        return t
          .split(':')
          .reduce(function(m, s) {
            return parseInt(m)*60 + parseInt(s)
          })
      })
    self.status.time = {
      elapsed: time[0],
      duration: time[1],
      remaining: time[2],
      string: {
        elapsed: secToString(time[0]),
        duration: secToString(time[1]),
        remaining: secToString(time[2])
      }
    }
  }

  switch (code) {
    case 136:
    case 141:
    case 200:
      break

    case 100:
      self.version = /(?:pianod\s)(\d*)/.exec(data)[1]
      self.emit('connection', self.version)
      break

    case 101:
    case 102:
    case 106:
    case 103:
    case 104:
    case 105:
      self.status.state = codeMap[code]
      self.emit(self.status.state)
      self.emit('stateChange', self.status.state)
      break

    case 108:
    case 109:
      self.status.station = (code !== 108 ? extractData(data).replace('station ','') : '')
      self.emit('station', self.status.station)
      break

    case 115:
      if (self.q.type === 'stationList') {
        self.q.stations.push(extractData(data))
        break
      }
    case 111:
      if (code === 111) self.q.type = 'track'
    case 112:
    case 113:
    case 114:
    case 116:
    case 117:
    case 118:
    case 119:
    case 120:
      self.q[codeMap[code]] = extractData(data)
      if (code === 120 && self.q.type === 'track') {
        delete self.q.type
        self.status.track = self.q
        self.q = {}
        self.emit('track', self.status.track)
      }
      break

    case 132:
      var msg = data.slice(4);
      /signed in/.test(msg) ? self.emit('login', msg) : self.emit('activity', msg)
      break

    case 203:
      break

    case 135:
      self.q = {type:"stationList", stations: []}
    case 204:
      if (self.q.type === 'stationList') {
        self.stations = self.q.stations
        self.emit('stationList', self.stations)
      }
      self.q = {}
      break

    default:
      self.emit('activity', data)
      break
  }
}

function extractData(data) {
  return /(?::\s)(.*)/.exec(data)[1]
}

function secToString(sec) {
  var min = Math.floor(sec / 60).pad(),
      sec = (sec % 60).pad()
  return min + ':' + sec
}

Number.prototype.pad = function() {
  return (this < 10) ? '0'+this : this.toString()
}
<commit_msg>timestamp for calculating track progress<commit_after>// Parse pianod responses (yes, it sadly takes this much code)

var codeMap = require('./codeMap')

exports.parse = function(data, self) {
  code = parseInt(data.slice(0,3))

  if ([101,102,106].indexOf(code) !== -1) {
    var time = data
      .slice(4,22)
      .replace('-','')
      .split('/')
      .map(function(t) {
        return t
          .split(':')
          .reduce(function(m, s) {
            return parseInt(m)*60 + parseInt(s)
          })
      })
    self.status.time = {
      elapsed: time[0],
      duration: time[1],
      remaining: time[2],
      timestamp: new Date().getTime() - time[0]*1000,
      string: {
        elapsed: secToString(time[0]),
        duration: secToString(time[1]),
        remaining: secToString(time[2])
      }
    }
  }

  switch (code) {
    case 136:
    case 141:
    case 200:
      break

    case 100:
      self.version = /(?:pianod\s)(\d*)/.exec(data)[1]
      self.emit('connection', self.version)
      break

    case 101:
    case 102:
    case 106:
    case 103:
    case 104:
    case 105:
      self.status.state = codeMap[code]
      self.emit(self.status.state)
      self.emit('stateChange', self.status.state)
      break

    case 108:
    case 109:
      self.status.station = (code !== 108 ? extractData(data).replace('station ','') : '')
      self.emit('station', self.status.station)
      break

    case 115:
      if (self.q.type === 'stationList') {
        self.q.stations.push(extractData(data))
        break
      }
    case 111:
      if (code === 111) self.q.type = 'track'
    case 112:
    case 113:
    case 114:
    case 116:
    case 117:
    case 118:
    case 119:
    case 120:
      self.q[codeMap[code]] = extractData(data)
      if (code === 120 && self.q.type === 'track') {
        delete self.q.type
        self.status.track = self.q
        self.q = {}
        self.emit('track', self.status.track)
      }
      break

    case 132:
      var msg = data.slice(4);
      /signed in/.test(msg) ? self.emit('login', msg) : self.emit('activity', msg)
      break

    case 203:
      break

    case 135:
      self.q = {type:"stationList", stations: []}
    case 204:
      if (self.q.type === 'stationList') {
        self.stations = self.q.stations
        self.emit('stationList', self.stations)
      }
      self.q = {}
      break

    default:
      self.emit('activity', data)
      break
  }
}

function extractData(data) {
  return /(?::\s)(.*)/.exec(data)[1]
}

function secToString(sec) {
  var min = Math.floor(sec / 60).pad(),
      sec = (sec % 60).pad()
  return min + ':' + sec
}

Number.prototype.pad = function() {
  return (this < 10) ? '0'+this : this.toString()
}
<|endoftext|>


<commit_before>//
// Find and load modules
//
var fs = require('fs');
var join = require('path').join;
var config = require('../configs');
var log = require('debug')('datahub:plugin');

var Router = require('express').Router;

/**
 * find plugins in node_modules
 *   with name prefixed 'datahub-plugin-'
 * @return {array} result
 */
function findPlugins() {
  var dir = join(__dirname, '../node_modules');

  var list = fs.readdirSync(dir);

  var result = list.filter(function(item) {
    return /^datahub-plugin-/.test(item);
  });

  return result;
}

/**
 * load plugins and assign router
 *   /{plugin-name}/**
 * @param  {object} app express instance
 * @param  {object} hub EventEmitter instance
 * @return {object}     plugins map object
 */
exports.load = function(app, hub) {
  var pluginList = findPlugins();
  var pluginMap = {};

  pluginList.forEach(function(mod) {

    var modName = mod.replace(/^datahub-plugin-/, '');
    var settings = config.plugin[modName] || {};

    log('Load plugin %s as name "%s"', mod, modName);

    var Plugin = require(mod);
    var router = Router();
    app.use('/' + modName, router);

    pluginMap[modName] = new Plugin(settings, hub, router);
  });

  return pluginMap;
}
<commit_msg>provide logger to plugins<commit_after>//
// Find and load modules
//
var fs = require('fs');
var join = require('path').join;
var config = require('../configs');
var Debug = require('debug');
var log = Debug('datahub:plugin');

var Router = require('express').Router;

/**
 * find plugins in node_modules
 *   with name prefixed 'datahub-plugin-'
 * @return {array} result
 */
function findPlugins() {
  var dir = join(__dirname, '../node_modules');

  var list = fs.readdirSync(dir);

  var result = list.filter(function(item) {
    return /^datahub-plugin-/.test(item);
  });

  return result;
}

/**
 * load plugins and assign router
 *   /{plugin-name}/**
 * @param  {object} app express instance
 * @param  {object} hub EventEmitter instance
 * @return {object}     plugins map object
 */
exports.load = function(app, hub) {
  var pluginList = findPlugins();
  var pluginMap = {};

  pluginList.forEach(function(mod) {

    var modName = mod.replace(/^datahub-plugin-/, '');
    var debug = Debug('datahub:plugin:' + modName)

    var settings = config.plugin[modName] || {};

    log('Load plugin %s as name "%s"', mod, modName);

    var Plugin = require(mod);
    var router = Router();
    app.use('/' + modName, router);

    pluginMap[modName] = new Plugin(settings, hub, router, debug);
  });

  return pluginMap;
}
<|endoftext|>


<commit_before>var path = require('path')

async function RunPlugins (self, type, func, queue, job, args, pluginCounter) {
  if (!pluginCounter) { pluginCounter = 0 }
  if (!job) { return true }
  if (job.plugins === null || job.plugins === undefined || job.plugins.length === 0) {
    return true
  }
  if (pluginCounter >= job.plugins.length) {
    return true
  }

  let pluginRefrence = job.plugins[pluginCounter]
  let toRun = await RunPlugin(self, pluginRefrence, type, func, queue, job, args)
  pluginCounter++
  if (toRun === false) { return false }

  return RunPlugins(self, type, func, queue, job, args, pluginCounter)
}

async function RunPlugin (self, PluginRefrence, type, func, queue, job, args) {
  if (!job) { return true }

  let pluginName = PluginRefrence
  if (typeof pluginRefrence === 'function') {
    pluginName = new PluginRefrence(self, func, queue, job, args, {}).name
  } else if (typeof pluginName === 'function') {
    pluginName = pluginName.name
  }

  var pluginOptions = null
  if (self.jobs[func].pluginOptions && self.jobs[func].pluginOptions[pluginName]) {
    pluginOptions = self.jobs[func].pluginOptions[pluginName]
  } else {
    pluginOptions = {}
  }

  let plugin = null
  if (typeof PluginRefrence === 'string') {
    let PluginConstructor = require(path.join(__dirname, 'plugins', (PluginRefrence + '.js')))[PluginRefrence]
    plugin = new PluginConstructor(self, func, queue, job, args, pluginOptions)
  } else if (typeof PluginRefrence === 'function') {
    plugin = new PluginRefrence(self, func, queue, job, args, pluginOptions)
  } else {
    throw new Error('Plugin must be the constructor name or an object')
  }

  if (plugin[type] === null || plugin[type] === undefined || typeof plugin[type] !== 'function') {
    return true
  }

  return plugin[type]()
}

exports.RunPlugin = RunPlugin
exports.RunPlugins = RunPlugins
<commit_msg>fix: Fix typo in lib/pluginRunner<commit_after>var path = require('path')

async function RunPlugins (self, type, func, queue, job, args, pluginCounter) {
  if (!pluginCounter) { pluginCounter = 0 }
  if (!job) { return true }
  if (job.plugins === null || job.plugins === undefined || job.plugins.length === 0) {
    return true
  }
  if (pluginCounter >= job.plugins.length) {
    return true
  }

  let pluginRefrence = job.plugins[pluginCounter]
  let toRun = await RunPlugin(self, pluginRefrence, type, func, queue, job, args)
  pluginCounter++
  if (toRun === false) { return false }

  return RunPlugins(self, type, func, queue, job, args, pluginCounter)
}

async function RunPlugin (self, PluginRefrence, type, func, queue, job, args) {
  if (!job) { return true }

  let pluginName = PluginRefrence
  if (typeof PluginRefrence === 'function') {
    pluginName = new PluginRefrence(self, func, queue, job, args, {}).name
  } else if (typeof pluginName === 'function') {
    pluginName = pluginName.name
  }

  var pluginOptions = null
  if (self.jobs[func].pluginOptions && self.jobs[func].pluginOptions[pluginName]) {
    pluginOptions = self.jobs[func].pluginOptions[pluginName]
  } else {
    pluginOptions = {}
  }

  let plugin = null
  if (typeof PluginRefrence === 'string') {
    let PluginConstructor = require(path.join(__dirname, 'plugins', (PluginRefrence + '.js')))[PluginRefrence]
    plugin = new PluginConstructor(self, func, queue, job, args, pluginOptions)
  } else if (typeof PluginRefrence === 'function') {
    plugin = new PluginRefrence(self, func, queue, job, args, pluginOptions)
  } else {
    throw new Error('Plugin must be the constructor name or an object')
  }

  if (plugin[type] === null || plugin[type] === undefined || typeof plugin[type] !== 'function') {
    return true
  }

  return plugin[type]()
}

exports.RunPlugin = RunPlugin
exports.RunPlugins = RunPlugins
<|endoftext|>


<commit_before>'use strict';

var path = require( 'path' ),
	Instrumenter = require( 'istanbul' ).Instrumenter,
	instrumenter;

function processContent( content, file ) {
	return instrumenter.instrumentSync( content, file );
}

module.exports = {
	name: 'bender-preprocessor-coverage',

	processContent: processContent,

	attach: function() {
		var bender = this,
			config = bender.conf.coverage || {},
			paths = config.paths || [];

		instrumenter = new Instrumenter( config.options || {} );

		function processFile( file ) {
			if ( !paths.length ||
				path.extname( file.oldPath ) !== '.js' ||
				!bender.files.isValidPath( file.oldPath, paths ) ) {
				return file;
			}

			file.content = new Buffer( processContent( file.content.toString(), file.oldPath ), 'utf-8' );

			return file;
		}

		// bender.preprocessors.push( processFile );
		bender.preprocessors.add( 'coverage', processFile );
	}
};
<commit_msg>Fixed #1 - don't instrument the code in single test runs and dashboard runs.<commit_after>'use strict';

var path = require( 'path' ),
	Instrumenter = require( 'istanbul' ).Instrumenter,
	instrumenter;

/**
 * Instrument the code synchronously
 * @param  {String} content Contents of a file
 * @param  {String} file    Original file path
 * @return {String}
 */
function processContent( content, file ) {
	return instrumenter.instrumentSync( content, file );
}

module.exports = {
	name: 'bender-preprocessor-coverage',

	processContent: processContent,

	attach: function() {
		var bender = this,
			config = bender.conf.coverage || {},
			paths = config.paths || [];

		instrumenter = new Instrumenter( config.options || {} );

		function processFile( file ) {
			// no paths to instrument defined
			if ( !paths.length ||
				// we work with JS files only
				path.extname( file.originalPath ) !== '.js' ||
				// if the path is the same as the originalPath
				// then the file wasn't copied to the job's directory
				// and we don't care about it
				file.path === file.originalPath ||
				// file doesn't match the instrumentation paths
				!bender.files.isValidPath( file.originalPath, paths ) ) {
				return file;
			}

			file.content = new Buffer( processContent( file.content.toString(), file.originalPath ), 'utf-8' );

			return file;
		}

		bender.preprocessors.add( 'coverage', processFile );
	}
};
<|endoftext|>