<commit_before>Element `infinity-calendar`

(class extends HTMLElement {

  initialize ()
    { this.context.date = new Date }

  static onready () {
    this.select
      ('[name=month]').value = this.month

    this.select
      ('[name=year]').value = this.year

  console.log ('onready')
  }

  static onnext () {
    this.date_from_month (+1)
    this.render ()
  }

  static onprevious () {
    this.date_from_month (-1)
    this.render ()
  }

  static ondayclick (event)
    { alert (event.target.textContent) }

  get year ()
    { return this.context.date.getFullYear () }

  get month ()
    { return this.context.date.getMonth () }

  get years () {
    const
      deviation = 5
    , years = new Array

    for
      (let year = this.year - deviation; year < this.year + deviation; year ++)
        years.push (year)

    return years
  }

  get months () {
    return [
      'January', 'February', 'March', 'April', 'May',
      'June', 'July','August','September','October','December' ]
  }

  get days () {
    const
      dates = []
    , daily = undefined

    , days  = day =>
        { return { day: day } }

    , date  =
        new Date ( this.year , this.context.date.getMonth () + 1 , 0)

    for (let day=1; day <= date.getDate (); day++)
      dates.push (day)

    return dates.map (days)
  }

  date_from_month (change) {
    this.context.date = new Date
      (this.context.date.setMonth (this.month + change))
  }
})
<commit_msg>examples/infinity-calendar.js add support for <select> <options><commit_after><|endoftext|>


<commit_before>var Fiber = Npm.require('fibers');
var url = Npm.require('url');
var CAS = Npm.require('cas');

var _casCredentialTokens = {};

RoutePolicy.declare('/_cas/', 'network');

// Listen to incoming OAuth http requests
WebApp.connectHandlers.use(function(req, res, next) {
  // Need to create a Fiber since we're using synchronous http calls and nothing
  // else is wrapping this in a fiber automatically
  Fiber(function () {
    middleware(req, res, next);
  }).run();
});

middleware = function (req, res, next) {
  // Make sure to catch any exceptions because otherwise we'd crash
  // the runner
  try {
    var barePath = req.url.substring(0, req.url.indexOf('?'));
    var splitPath = barePath.split('/');

    // Any non-cas request will continue down the default
    // middlewares.
    if (splitPath[1] !== '_cas') {
      next();
      return;
    }

    // get auth token
    var credentialToken = splitPath[2];
    if (!credentialToken) {
      closePopup(res);
      return;
    }

    // validate ticket
    casTicket(req, credentialToken, function() {
      closePopup(res);
    });

  } catch (err) {
    console.log("account-cas: unexpected error : " + err.message);
    closePopup(res);
  }
};

var casTicket = function (req, token, callback) {
  // get configuration
  if (!Meteor.settings.cas && !Meteor.settings.cas.validate) {
    console.log("accounts-cas: unable to get configuration");
    callback();
  }

  // get ticket and validate.
  var parsedUrl = url.parse(req.url, true);
  var ticketId = parsedUrl.query.ticket;

  var cas = new CAS({
    base_url: Meteor.settings.cas.baseUrl,
    service: Meteor.absoluteUrl() + "_cas/" + token
  });

  cas.validate(ticketId, function(err, status, username) {
    if (err) {
      console.log("accounts-cas: error when trying to validate " + err);
    } else {
      if (status) {
        console.log("accounts-cas: user validated " + username.toLowerCase());
        _casCredentialTokens[token] = { id: username.toLowerCase() };
      } else {
        console.log("accounts-cas: unable to validate " + ticketId);
      }
    }

    callback();
  });

  return;
};

/*
 * Register a server-side login handle.
 * It is call after Accounts.callLoginMethod() is call from client.
 *
 */
 Accounts.registerLoginHandler(function (options) {
  if (!options.cas)
    return undefined;
  if (!_hasCredential(options.cas.credentialToken)) {
    throw new Meteor.Error(Accounts.LoginCancelledError.numericError,
      'no matching login attempt found');
  }

  var result = _retrieveCredential(options.cas.credentialToken);
  var options = { profile: { name: result.id } };
  var user = Meteor.users.findOne({username: result.id});

  // the below method will not work correctly as is an undocumented feature of meteor
  // var user = Accounts.updateOrCreateUserFromExternalService("cas", result, options);
  // return userId;
  //Create the user if it does not exit.
	var userId = null;
	if (!user) {

		//Create the user
		userId = Meteor.users.insert({
		username: result.id,
		profile: {name: result.id},
		emails: [{address: result.id + '@manchester.ac.uk', verified: true}],

		});
    //Roles.addUsersToRoles(userId, ['view-rooms']);
	} else {
		//Get the user id of the already created user
		userId = user._id;

	}

	//creating the token and add to the user
	var stampedToken = Accounts._generateStampedLoginToken();
	Meteor.users.update(userId,
		{$push: {'services.resume.loginTokens': stampedToken}}
	);

	//send logged in user's user id
	return {
		userId: userId,
		type: 'cas',
		token: stampedToken.token,
		tokenExpires: Accounts._tokenExpiration(stampedToken.when)
	}
});

var _hasCredential = function(credentialToken) {
  return _.has(_casCredentialTokens, credentialToken);
}

/*
 * Retrieve token and delete it to avoid replaying it.
 */
var _retrieveCredential = function(credentialToken) {
  var result = _casCredentialTokens[credentialToken];
  delete _casCredentialTokens[credentialToken];
  return result;
}

var closePopup = function(res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var content = '';
  res.end(content, 'utf-8');
}
<commit_msg>manchester-ism removed. optional email parameter generated via cas username and static suffix in settings.json<commit_after>var Fiber = Npm.require('fibers');
var url = Npm.require('url');
var CAS = Npm.require('cas');

var _casCredentialTokens = {};

RoutePolicy.declare('/_cas/', 'network');

// Listen to incoming OAuth http requests
WebApp.connectHandlers.use(function(req, res, next) {
  // Need to create a Fiber since we're using synchronous http calls and nothing
  // else is wrapping this in a fiber automatically
  Fiber(function () {
    middleware(req, res, next);
  }).run();
});

middleware = function (req, res, next) {
  // Make sure to catch any exceptions because otherwise we'd crash
  // the runner
  try {
    var barePath = req.url.substring(0, req.url.indexOf('?'));
    var splitPath = barePath.split('/');

    // Any non-cas request will continue down the default
    // middlewares.
    if (splitPath[1] !== '_cas') {
      next();
      return;
    }

    // get auth token
    var credentialToken = splitPath[2];
    if (!credentialToken) {
      closePopup(res);
      return;
    }

    // validate ticket
    casTicket(req, credentialToken, function() {
      closePopup(res);
    });

  } catch (err) {
    console.log("account-cas: unexpected error : " + err.message);
    closePopup(res);
  }
};

var casTicket = function (req, token, callback) {
  // get configuration
  if (!Meteor.settings.cas && !Meteor.settings.cas.validate) {
    console.log("accounts-cas: unable to get configuration");
    callback();
  }

  // get ticket and validate.
  var parsedUrl = url.parse(req.url, true);
  var ticketId = parsedUrl.query.ticket;

  var cas = new CAS({
    base_url: Meteor.settings.cas.baseUrl,
    service: Meteor.absoluteUrl() + "_cas/" + token
  });

  cas.validate(ticketId, function(err, status, username) {
    if (err) {
      console.log("accounts-cas: error when trying to validate " + err);
    } else {
      if (status) {
        console.log("accounts-cas: user validated " + username.toLowerCase());
        _casCredentialTokens[token] = { id: username.toLowerCase() };
      } else {
        console.log("accounts-cas: unable to validate " + ticketId);
      }
    }

    callback();
  });

  return;
};

/*
 * Register a server-side login handle.
 * It is call after Accounts.callLoginMethod() is call from client.
 *
 */
 Accounts.registerLoginHandler(function (options) {
  if (!options.cas)
    return undefined;
  if (!_hasCredential(options.cas.credentialToken)) {
    throw new Meteor.Error(Accounts.LoginCancelledError.numericError,
      'no matching login attempt found');
  }

  var result = _retrieveCredential(options.cas.credentialToken);
  var options = { profile: { name: result.id } };
  var user = Meteor.users.findOne({username: result.id});

  // the below method will not work correctly as is an undocumented feature of meteor
  // var user = Accounts.updateOrCreateUserFromExternalService("cas", result, options);
  // return userId;
  //Create the user if it does not exit.
	var userId = null;
	if (!user) {

		//Create the user
		userId = Meteor.users.insert({
		username: result.id,
		profile: {name: result.id},
    // getting email attribute from CAS would require a more advanced version of the package
    // optional generating email based on cas username and static suffix
		// emails: [{address: result.id + Meteor.settings.cas.emailsuffix, verified: true}],

		});
    //Roles.addUsersToRoles(userId, ['view-rooms']);
	} else {
		//Get the user id of the already created user
		userId = user._id;

	}

	//creating the token and add to the user
	var stampedToken = Accounts._generateStampedLoginToken();
	Meteor.users.update(userId,
		{$push: {'services.resume.loginTokens': stampedToken}}
	);

	//send logged in user's user id
	return {
		userId: userId,
		type: 'cas',
		token: stampedToken.token,
		tokenExpires: Accounts._tokenExpiration(stampedToken.when)
	}
});

var _hasCredential = function(credentialToken) {
  return _.has(_casCredentialTokens, credentialToken);
}

/*
 * Retrieve token and delete it to avoid replaying it.
 */
var _retrieveCredential = function(credentialToken) {
  var result = _casCredentialTokens[credentialToken];
  delete _casCredentialTokens[credentialToken];
  return result;
}

var closePopup = function(res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var content = '';
  res.end(content, 'utf-8');
}
<|endoftext|>


<commit_before>'use strict';

var mm = require('..');
var pattern = '*(*(of*(a)x)z)';

var ast = mm.parse(pattern, {sourcemap: true});
var res = mm.compile(ast);
console.log(res);
// { map:
//    { version: 3,
//      sources: [ 'string' ],
//      names: [],
//      mappings: 'AAAA,CAAE,CAAE,EAAE,CAAE,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC',
//      sourcesContent: [ '*(*(of*(a)x)z)' ] }},
<commit_msg>update sourcemap example<commit_after>'use strict';

var mm = require('..');
var pattern = '*(*(of*(a)x)z)';

var ast = mm.parse(pattern);
var res = mm.compile(ast, {sourcemap: true});
console.log(res)
// { map:
//    { version: 3,
//      sources: [ 'string' ],
//      names: [],
//      mappings: 'AAAA,CAAE,CAAE,EAAE,CAAE,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC',
//      sourcesContent: [ '*(*(of*(a)x)z)' ] }},
<|endoftext|>


<commit_before>const rp = require('request-promise');
const cheerio = require('cheerio');

const getStreakBody = (userName) => {
	var options = {
		uri: `https://github.com/users/${userName}/contributions`,
		transform: function (body) {
			return cheerio.load(body);
		}
	};

	return rp(options)

	.then(function ($) {

			const currentDateStreak = [];
			let currentStreak = [];

			$('.day').each(function (index) {

				const date = new Date($(this).prop('data-date'));
				console.log('final', date);

				date.setHours(0, 0, 0, 0);

				const commit = $(this).prop('data-count');

				if (currentDateStreak[index - 1]) {
					const tempDate = currentDateStreak[index - 1].date;
					tempDate.setDate(tempDate.getDate() + 1);
					tempDate.setHours(0, 0, 0, 0);

					if (commit > 0 && date.getTime() === tempDate.getTime()) {
						console.log('fisrt', $(this).prop('data-date'));
						currentStreak.push({
							date: date,
							commit: commit
						});
						console.log('quantity', currentStreak.length);
					} else {
						console.log('zerou');
						console.log('tempDate', tempDate);
						console.log('date', date);
						console.log('commit', commit);
						console.log('tempDate.getTime', tempDate.getTime());
						console.log('tempDate.getTime', tempDate.getTime());
						currentStreak = [];
					}
				}

				currentDateStreak.push({
					date: date
				});

			});
			console.log('currentStreak', currentStreak.length);
			return currentStreak;
		})
		.catch(function (err) {
			console.log('errror', err);
		});
};

module.exports = {
	getStreakBody
};<commit_msg>add scrap service<commit_after>const rp = require('request-promise');
const cheerio = require('cheerio');

const getStreakBody = (userName) => {
	var options = {
		uri: `https://github.com/users/${userName}/contributions`,
		transform: function (body) {
			return cheerio.load(body);
		}
	};

	return rp(options)

	.then(function ($) {

			const currentDateStreak = [];
			let currentStreak = [];

			$('.day').filter(function (i, el) {
				return $(this).prop('data-count') !== '0';
			}).each(function (index) {

				const date = new Date($(this).prop('data-date'));
				date.setHours(0, 0, 0, 0);

				if (currentDateStreak[index - 1]) {
					const tempDate = currentDateStreak[index - 1].date;
					tempDate.setDate(tempDate.getDate() + 1);
					tempDate.setHours(0, 0, 0, 0);

					if (date.getTime() === tempDate.getTime()) {
						if ($(this).prop('fill') != '#ebedf0') {
							currentStreak.push({
								date: date,
								commit: $(this).prop('data-count')
							});
						}
					} else {
						currentStreak = [];
					}
				}
				currentDateStreak.push({
					date: date
				});
			});

			return currentStreak;
		})
		.catch( (err) => {
			console.log('errror', err);
		});
};

module.exports = {
	getStreakBody
};<|endoftext|>


<commit_before>/*eslint-disable no-console*/

import { SagaCancellationException } from 'redux-saga'

import {
  monitorActions as actions,
  is, asEffect,
  MANUAL_CANCEL
} from 'redux-saga/utils'

const PENDING = 'PENDING'
const RESOLVED = 'RESOLVED'
const REJECTED = 'REJECTED'

export const LOG_EFFECT = 'LOG_EFFECT'
export const logEffect = (effectId = 0) => ({type: LOG_EFFECT, effectId})

const DEFAULT_STYLE = 'color: black'
const LABEL_STYLE = 'font-weight: bold'
const EFFECT_TYPE_STYLE = 'color: blue'
const ERROR_STYLE = 'color: red'
const AUTO_CANCEL_STYLE = 'color: lightgray'

const time = () => performance.now()
const env = process.env.NODE_ENV

function checkEnv() {
  if (env !== 'production' && env !== 'development') {
    console.error('Saga Monitor cannot be used outside of NODE_ENV === \'development\'. ' +
      'Consult tools such as loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
      'and DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' +
      'to build with proper NODE_ENV')
  }
}

let effectsById = {}
export default () => next => action => {

  switch (action.type) {
    case actions.EFFECT_TRIGGERED:
      effectsById[action.effectId] = Object.assign({},
        action,
        {
          status: PENDING,
          start: time()
        }
      )
      break;
    case actions.EFFECT_RESOLVED:
      resolveEffect(action.effectId, action.result)
      break;
    case actions.EFFECT_REJECTED:
      rejectEffect(action.effectId, action.error)
      break;
    case LOG_EFFECT:
      checkEnv()
      logEffectTree(action.effectId || 0)
      break;
    default:
      return next(action)
  }
}

window.$$LogSagas = () => {
  checkEnv()
  logEffectTree(0)
}

function resolveEffect(effectId, result) {
  const effect = effectsById[effectId]
  const now = time()

  if(is.task(result)) {
    result.done.then(
      taskResult => resolveEffect(effectId, taskResult),
      taskError  => rejectEffect(effectId, taskError)
    )
  } else {
    effectsById[effectId] = Object.assign({},
      effect,
      {
        result: result,
        status: RESOLVED,
        end: now,
        duration: now - effect.start
      }
    )
    if(effect && asEffect.race(effect.effect))
      setRaceWinner(effectId, result)
  }
}

function rejectEffect(effectId, error) {
  const effect = effectsById[effectId]
  const now = time()
  effectsById[effectId] = Object.assign({},
    effect,
    {
      error: error,
      status: REJECTED,
      end: now,
      duration: now - effect.start
    }
  )
  if(effect && asEffect.race(effect.effect))
    setRaceWinner(effectId, error)
}

function setRaceWinner(raceEffectId, result) {
  const winnerLabel = Object.keys(result)[0]
  const children = getChildEffects(raceEffectId)
  for (var i = 0; i < children.length; i++) {
    const childEffect = effectsById[ children[i] ]
    if(childEffect.label === winnerLabel)
      childEffect.winner = true
  }
}

function getChildEffects(parentEffectId) {
  return Object.keys(effectsById)
    .filter(effectId => effectsById[effectId].parentEffectId === parentEffectId)
    .map(effectId => +effectId)
}

function logEffectTree(effectId) {
  const effect = effectsById[effectId]
  if(effectId === undefined) {
    console.log('Saga monitor: No effect data for', effectId)
    return
  }
  const childEffects = getChildEffects(effectId)

  if(!childEffects.length)
    logSimpleEffect(effect)
  else {
    if(effect) {
      const {formatter} = getEffectLog(effect)
      console.group(...formatter.getLog())
    } else
      console.group('root')
    childEffects.forEach(logEffectTree)
    console.groupEnd()
  }
}

function logSimpleEffect(effect) {
  const {method, formatter} = getEffectLog(effect)
  console[method](...formatter.getLog())
}

/*eslint-disable no-cond-assign*/
function getEffectLog(effect) {
  let data, log

  if(data = asEffect.take(effect.effect)) {
    log = getLogPrefix('take', effect)
    log.formatter.addValue(data)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.put(effect.effect)) {
    log = getLogPrefix('put', effect)
    logResult(Object.assign({}, effect, { result: data }), log.formatter)
  }

  else if(data = asEffect.call(effect.effect)) {
    log = getLogPrefix('call', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.cps(effect.effect)) {
    log = getLogPrefix('cps', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.fork(effect.effect)) {
    log = getLogPrefix('', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.join(effect.effect)) {
    log = getLogPrefix('join', effect)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.race(effect.effect)) {
    log = getLogPrefix('race', effect)
    logResult(effect, log.formatter, true)
  }

  else if(data = asEffect.cancel(effect.effect)) {
    log = getLogPrefix('cancel', effect)
    log.formatter.appendData(data.name)
  }

  else if(data = asEffect.select(effect.effect)) {
    log = getLogPrefix('select', effect)
    log.formatter.appendData(data.name)
    logResult(effect, log.formatter)
  }

  else if(data = is.array(effect.effect)) {
    log = getLogPrefix('parallel', effect)
    logResult(effect, log.formatter, true)
  }

  else {
    log = getLogPrefix('unkown', effect)
    logResult(effect, log.formatter)
  }

  return log
}

function getLogPrefix(type, effect) {

  const autoCancel = isAutoCancel(effect.error)
  const isError = effect && effect.status === REJECTED && !autoCancel
  const method = isError ? 'error' : 'log'
  const winnerInd = effect && effect.winner
    ? ( isError ? '✘' : '✓' )
    : ''

  const style = s =>
      autoCancel  ? AUTO_CANCEL_STYLE
    : isError     ? ERROR_STYLE
    : s

  const formatter = logFormatter()

  if(winnerInd)
    formatter.add(`%c ${winnerInd}`, style(LABEL_STYLE))

  if(effect && effect.label)
    formatter.add(`%c ${effect.label}: `,  style(LABEL_STYLE))

  if(type)
    formatter.add(`%c ${type} `, style(EFFECT_TYPE_STYLE))

  formatter.add('%c', style(DEFAULT_STYLE))

  return {
    method,
    formatter
  }
}

function argToString(arg) {
  return (
      typeof arg === 'function' ? `${arg.name}`
    : typeof arg === 'string'   ? `'${arg}'`
    : arg
  )
}

function logResult({status, result, error, duration}, formatter, ignoreResult) {

  if(status === RESOLVED && !ignoreResult) {
    if( is.array(result) ) {
      formatter.addValue(' → ')
      formatter.addValue(result)
    } else
      formatter.appendData('→',result)
  }

  else if(status === REJECTED) {
    if(isAutoCancel(error))
      return

    if(isManualCancel(error))
      formatter.appendData('→ ⚠', 'Cancelled!')
    else
      formatter.appendData('→ ⚠', error)
  }

  else if(status === PENDING)
    formatter.appendData('⌛')

  if(status !== PENDING)
    formatter.appendData(`(${duration.toFixed(2)}ms)`)
}

function isAutoCancel(error) {
  return error instanceof SagaCancellationException && error.type !== MANUAL_CANCEL
}

function isManualCancel(error) {
  return error instanceof SagaCancellationException && error.type === MANUAL_CANCEL
}

function isPrimitive(val) {
  return  typeof val === 'string'   ||
          typeof val === 'number'   ||
          typeof val === 'boolean'  ||
          typeof val === 'symbol'   ||
          val === null              ||
          val === undefined;
}

function logFormatter() {
  const logs = []
  let suffix = []

  function add(msg, ...args) {
    logs.push({msg, args})
  }

  function appendData(...data) {
    suffix = suffix.concat(data)
  }

  function addValue(value) {
    if(isPrimitive(value))
      add(value)
    else
      add('%O', value)
  }

  function addCall(name, args) {
    if(!args.length)
      add( `${name}()` )
    else {
      add(name)
      add('(')
      args.forEach( (arg, i) => {
        addValue( argToString(arg) )
        addValue( i === args.length - 1 ? ')' : ', ')
      })
    }
  }

  function getLog() {
    let msgs = [], msgsArgs = []
    for (var i = 0; i < logs.length; i++) {
      msgs.push(logs[i].msg)
      msgsArgs = msgsArgs.concat(logs[i].args)
    }
    return [msgs.join('')].concat(msgsArgs).concat(suffix)
  }

  return {
    add, addValue, addCall, appendData, getLog
  }
}
<commit_msg>fixed logging for select effects<commit_after>/*eslint-disable no-console*/

import { SagaCancellationException } from 'redux-saga'

import {
  monitorActions as actions,
  is, asEffect,
  MANUAL_CANCEL
} from 'redux-saga/utils'

const PENDING = 'PENDING'
const RESOLVED = 'RESOLVED'
const REJECTED = 'REJECTED'

export const LOG_EFFECT = 'LOG_EFFECT'
export const logEffect = (effectId = 0) => ({type: LOG_EFFECT, effectId})

const DEFAULT_STYLE = 'color: black'
const LABEL_STYLE = 'font-weight: bold'
const EFFECT_TYPE_STYLE = 'color: blue'
const ERROR_STYLE = 'color: red'
const AUTO_CANCEL_STYLE = 'color: lightgray'

const time = () => performance.now()
const env = process.env.NODE_ENV

function checkEnv() {
  if (env !== 'production' && env !== 'development') {
    console.error('Saga Monitor cannot be used outside of NODE_ENV === \'development\'. ' +
      'Consult tools such as loose-envify (https://github.com/zertosh/loose-envify) for browserify ' +
      'and DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' +
      'to build with proper NODE_ENV')
  }
}

let effectsById = {}
export default () => next => action => {

  switch (action.type) {
    case actions.EFFECT_TRIGGERED:
      effectsById[action.effectId] = Object.assign({},
        action,
        {
          status: PENDING,
          start: time()
        }
      )
      break;
    case actions.EFFECT_RESOLVED:
      resolveEffect(action.effectId, action.result)
      break;
    case actions.EFFECT_REJECTED:
      rejectEffect(action.effectId, action.error)
      break;
    case LOG_EFFECT:
      checkEnv()
      logEffectTree(action.effectId || 0)
      break;
    default:
      return next(action)
  }
}

window.$$LogSagas = () => {
  checkEnv()
  logEffectTree(0)
}

function resolveEffect(effectId, result) {
  const effect = effectsById[effectId]
  const now = time()

  if(is.task(result)) {
    result.done.then(
      taskResult => resolveEffect(effectId, taskResult),
      taskError  => rejectEffect(effectId, taskError)
    )
  } else {
    effectsById[effectId] = Object.assign({},
      effect,
      {
        result: result,
        status: RESOLVED,
        end: now,
        duration: now - effect.start
      }
    )
    if(effect && asEffect.race(effect.effect))
      setRaceWinner(effectId, result)
  }
}

function rejectEffect(effectId, error) {
  const effect = effectsById[effectId]
  const now = time()
  effectsById[effectId] = Object.assign({},
    effect,
    {
      error: error,
      status: REJECTED,
      end: now,
      duration: now - effect.start
    }
  )
  if(effect && asEffect.race(effect.effect))
    setRaceWinner(effectId, error)
}

function setRaceWinner(raceEffectId, result) {
  const winnerLabel = Object.keys(result)[0]
  const children = getChildEffects(raceEffectId)
  for (var i = 0; i < children.length; i++) {
    const childEffect = effectsById[ children[i] ]
    if(childEffect.label === winnerLabel)
      childEffect.winner = true
  }
}

function getChildEffects(parentEffectId) {
  return Object.keys(effectsById)
    .filter(effectId => effectsById[effectId].parentEffectId === parentEffectId)
    .map(effectId => +effectId)
}

function logEffectTree(effectId) {
  const effect = effectsById[effectId]
  if(effectId === undefined) {
    console.log('Saga monitor: No effect data for', effectId)
    return
  }
  const childEffects = getChildEffects(effectId)

  if(!childEffects.length)
    logSimpleEffect(effect)
  else {
    if(effect) {
      const {formatter} = getEffectLog(effect)
      console.group(...formatter.getLog())
    } else
      console.group('root')
    childEffects.forEach(logEffectTree)
    console.groupEnd()
  }
}

function logSimpleEffect(effect) {
  const {method, formatter} = getEffectLog(effect)
  console[method](...formatter.getLog())
}

/*eslint-disable no-cond-assign*/
function getEffectLog(effect) {
  let data, log

  if(data = asEffect.take(effect.effect)) {
    log = getLogPrefix('take', effect)
    log.formatter.addValue(data)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.put(effect.effect)) {
    log = getLogPrefix('put', effect)
    logResult(Object.assign({}, effect, { result: data }), log.formatter)
  }

  else if(data = asEffect.call(effect.effect)) {
    log = getLogPrefix('call', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.cps(effect.effect)) {
    log = getLogPrefix('cps', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.fork(effect.effect)) {
    log = getLogPrefix('', effect)
    log.formatter.addCall(data.fn.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.join(effect.effect)) {
    log = getLogPrefix('join', effect)
    logResult(effect, log.formatter)
  }

  else if(data = asEffect.race(effect.effect)) {
    log = getLogPrefix('race', effect)
    logResult(effect, log.formatter, true)
  }

  else if(data = asEffect.cancel(effect.effect)) {
    log = getLogPrefix('cancel', effect)
    log.formatter.appendData(data.name)
  }

  else if(data = asEffect.select(effect.effect)) {
    log = getLogPrefix('select', effect)
    log.formatter.addCall(data.selector.name, data.args)
    logResult(effect, log.formatter)
  }

  else if(data = is.array(effect.effect)) {
    log = getLogPrefix('parallel', effect)
    logResult(effect, log.formatter, true)
  }

  else {
    log = getLogPrefix('unkown', effect)
    logResult(effect, log.formatter)
  }

  return log
}

function getLogPrefix(type, effect) {

  const autoCancel = isAutoCancel(effect.error)
  const isError = effect && effect.status === REJECTED && !autoCancel
  const method = isError ? 'error' : 'log'
  const winnerInd = effect && effect.winner
    ? ( isError ? '✘' : '✓' )
    : ''

  const style = s =>
      autoCancel  ? AUTO_CANCEL_STYLE
    : isError     ? ERROR_STYLE
    : s

  const formatter = logFormatter()

  if(winnerInd)
    formatter.add(`%c ${winnerInd}`, style(LABEL_STYLE))

  if(effect && effect.label)
    formatter.add(`%c ${effect.label}: `,  style(LABEL_STYLE))

  if(type)
    formatter.add(`%c ${type} `, style(EFFECT_TYPE_STYLE))

  formatter.add('%c', style(DEFAULT_STYLE))

  return {
    method,
    formatter
  }
}

function argToString(arg) {
  return (
      typeof arg === 'function' ? `${arg.name}`
    : typeof arg === 'string'   ? `'${arg}'`
    : arg
  )
}

function logResult({status, result, error, duration}, formatter, ignoreResult) {

  if(status === RESOLVED && !ignoreResult) {
    if( is.array(result) ) {
      formatter.addValue(' → ')
      formatter.addValue(result)
    } else
      formatter.appendData('→',result)
  }

  else if(status === REJECTED) {
    if(isAutoCancel(error))
      return

    if(isManualCancel(error))
      formatter.appendData('→ ⚠', 'Cancelled!')
    else
      formatter.appendData('→ ⚠', error)
  }

  else if(status === PENDING)
    formatter.appendData('⌛')

  if(status !== PENDING)
    formatter.appendData(`(${duration.toFixed(2)}ms)`)
}

function isAutoCancel(error) {
  return error instanceof SagaCancellationException && error.type !== MANUAL_CANCEL
}

function isManualCancel(error) {
  return error instanceof SagaCancellationException && error.type === MANUAL_CANCEL
}

function isPrimitive(val) {
  return  typeof val === 'string'   ||
          typeof val === 'number'   ||
          typeof val === 'boolean'  ||
          typeof val === 'symbol'   ||
          val === null              ||
          val === undefined;
}

function logFormatter() {
  const logs = []
  let suffix = []

  function add(msg, ...args) {
    logs.push({msg, args})
  }

  function appendData(...data) {
    suffix = suffix.concat(data)
  }

  function addValue(value) {
    if(isPrimitive(value))
      add(value)
    else
      add('%O', value)
  }

  function addCall(name, args) {
    if(!args.length)
      add( `${name}()` )
    else {
      add(name)
      add('(')
      args.forEach( (arg, i) => {
        addValue( argToString(arg) )
        addValue( i === args.length - 1 ? ')' : ', ')
      })
    }
  }

  function getLog() {
    let msgs = [], msgsArgs = []
    for (var i = 0; i < logs.length; i++) {
      msgs.push(logs[i].msg)
      msgsArgs = msgsArgs.concat(logs[i].args)
    }
    return [msgs.join('')].concat(msgsArgs).concat(suffix)
  }

  return {
    add, addValue, addCall, appendData, getLog
  }
}
<|endoftext|>


<commit_before>var _assign = require('lodash.assign');
var Joi = require('joi');

const defaults = require('../../lib/defaults');
const schema = require('../../lib/schema');
var pagesService = require('../../services/pages');

exports.register = function (server, options, next) {
  server.route({
    method: 'GET',
    path: '/',
    config: {
      auth: {
        mode: 'try',
        strategy: 'session'
      }
    },
    handler: function (request, reply) {
      var authorized = false;

      if (request.auth.isAuthenticated) {
        authorized = true;
      }

      reply.view('home/index', _assign(defaults.testPageContext, {
        test: [defaults.test, defaults.test],
        authorized: authorized
      }));
    }
  });

  server.route({
    method: 'POST',
    path: '/',
    config: {
      auth: 'session'
    },
    handler: function (request, reply) {
      var errResp = function (errObj) {
        if (errObj.message) {
          errObj.genError = errObj.message;
        }
        reply.view('home/index', _assign(defaults.testPageContext, request.payload, {authorized: true}, errObj)).code(400);
      };

      Joi.validate(request.payload, schema.testPage, function (er, pageWithTests) {
        if (er) {
          var errObj = {};
          // `abortEarly` option defaults to `true` so can rely on 0 index
          // but just in case...
          try {
            const valErr = er.details[0];

            switch (valErr.path) {
              case 'title':
                errObj.titleError = defaults.errors.title;
                break;
              case 'slug':
                errObj.slugError = defaults.errors.slug;
                break;
              default:
                const idx = valErr.path.split('.')[1];
                switch (valErr.context.key) {
                  case 'title':
                    request.payload.test[idx].codeTitleError = defaults.errors.codeTitle;
                    break;
                  case 'code':
                    request.payload.test[idx].codeError = defaults.errors.code;
                    break;
                  default:
                    throw new Error('unknown validation error');
                }
            }
          } catch (ex) {
            errObj.genError = defaults.errors.general;
          }
          errResp(errObj);
        } else {
          // Joi defaults any properties not present in `request.payload` so use `payload` from here on out
          var payload = pageWithTests;

          pagesService.checkIfSlugAvailable(server, payload.slug)
          .then(function (isAvail) {
            if (!isAvail) {
              errResp({
                slugError: defaults.errors.slugDupe
              });
            } else {
              return pagesService.create(payload).then(function () {
                request.yar.set('authorSlug', payload.author.replace(' ', '-').replace(/[^a-zA-Z0-9 -]/, ''));
                reply.redirect('/' + payload.slug);
              });
            }
          })
          .catch(errResp);
        }
      });
    }
  });

  return next();
};

exports.register.attributes = {
  name: 'web/home'
};
<commit_msg>Fix accidental caching (#233)<commit_after>var _assign = require('lodash.assign');
var Joi = require('joi');

const defaults = require('../../lib/defaults');
const schema = require('../../lib/schema');
var pagesService = require('../../services/pages');

exports.register = function (server, options, next) {
  server.route({
    method: 'GET',
    path: '/',
    config: {
      auth: {
        mode: 'try',
        strategy: 'session'
      }
    },
    handler: function (request, reply) {
      var authorized = false;

      if (request.auth.isAuthenticated) {
        authorized = true;
      }
      reply.view('home/index', _assign({}, defaults.testPageContext, {
        test: [defaults.test, defaults.test],
        authorized: authorized
      }));
    }
  });

  server.route({
    method: 'POST',
    path: '/',
    config: {
      auth: 'session'
    },
    handler: function (request, reply) {
      var errResp = function (errObj) {
        if (errObj.message) {
          errObj.genError = errObj.message;
        }
        reply.view('home/index', _assign({}, defaults.testPageContext, request.payload, {authorized: true}, errObj)).code(400);
      };

      Joi.validate(request.payload, schema.testPage, function (er, pageWithTests) {
        if (er) {
          var errObj = {};
          // `abortEarly` option defaults to `true` so can rely on 0 index
          // but just in case...
          try {
            const valErr = er.details[0];

            switch (valErr.path) {
              case 'title':
                errObj.titleError = defaults.errors.title;
                break;
              case 'slug':
                errObj.slugError = defaults.errors.slug;
                break;
              default:
                const idx = valErr.path.split('.')[1];
                switch (valErr.context.key) {
                  case 'title':
                    request.payload.test[idx].codeTitleError = defaults.errors.codeTitle;
                    break;
                  case 'code':
                    request.payload.test[idx].codeError = defaults.errors.code;
                    break;
                  default:
                    throw new Error('unknown validation error');
                }
            }
          } catch (ex) {
            errObj.genError = defaults.errors.general;
          }
          errResp(errObj);
        } else {
          // Joi defaults any properties not present in `request.payload` so use `payload` from here on out
          var payload = pageWithTests;

          pagesService.checkIfSlugAvailable(server, payload.slug)
          .then(function (isAvail) {
            if (!isAvail) {
              errResp({
                slugError: defaults.errors.slugDupe
              });
            } else {
              return pagesService.create(payload).then(function () {
                request.yar.set('authorSlug', payload.author.replace(' ', '-').replace(/[^a-zA-Z0-9 -]/, ''));
                reply.redirect('/' + payload.slug);
              });
            }
          })
          .catch(errResp);
        }
      });
    }
  });

  return next();
};

exports.register.attributes = {
  name: 'web/home'
};
<|endoftext|>


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

var devFlagPlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './frontend/index'
  ],
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    devFlagPlugin
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel'],
      exclude: [/node_modules/,/scripts/],
      include: __dirname
    }],
    eslint: {
      configFile: './.eslintrc'
    }
  }
};

// When inside Redux repo, prefer src to compiled version.
// You can safely delete these lines in your project.
var reduxSrc = path.join(__dirname, '..', '..', 'src');
var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules');
var fs = require('fs');
if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {
  // Resolve Redux to source
  module.exports.resolve = { alias: { 'redux': reduxSrc } };
  // Compile Redux from source
  module.exports.module.loaders.push({
    test: /\.js$/,
    loaders: ['babel', 'eslint-loader'],
    include: reduxSrc
  });
}
<commit_msg>Correct reinsertion of eslint-loader into webpack config<commit_after>var path = require('path');
var webpack = require('webpack');

var devFlagPlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './frontend/index'
  ],
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    devFlagPlugin
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['babel', 'eslint-loader'],
      exclude: [/node_modules/,/scripts/],
      include: __dirname
    }],
    eslint: {
      configFile: './.eslintrc'
    }
  }
};

// When inside Redux repo, prefer src to compiled version.
// You can safely delete these lines in your project.
var reduxSrc = path.join(__dirname, '..', '..', 'src');
var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules');
var fs = require('fs');
if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {
  // Resolve Redux to source
  module.exports.resolve = { alias: { 'redux': reduxSrc } };
  // Compile Redux from source
  module.exports.module.loaders.push({
    test: /\.js$/,
    loaders: ['babel'],
    include: reduxSrc
  });
}
<|endoftext|>


<commit_before>import path from "path";
import { createHash } from "crypto";
import { getRootDir } from "lasso-package-root";
import { types as t } from "@marko/babel-types";
import { getLoc } from "@marko/babel-utils";
import traverse, { visitors } from "@babel/traverse";
import { buildLookup } from "../taglib";
import { parseMarko } from "./parser";
import { visitor as migrate } from "./plugins/migrate";
import { visitor as transform } from "./plugins/transform";
import markoModules from "../../modules";
import { MarkoFile } from "./file";

const SOURCE_FILES = new WeakMap();
let ROOT = process.cwd();
try {
  ROOT = getRootDir(ROOT);
  // eslint-disable-next-line no-empty
} catch {}

export default (api, markoOpts) => {
  api.assertVersion(7);
  const translator = markoOpts.translator;

  markoOpts.output = markoOpts.output || "html";

  if (markoOpts.optimize === undefined) {
    markoOpts.optimize = api.env("production");
  }

  if (!translator || !translator.visitor) {
    throw new Error(
      "@marko/compiler: translator must provide a visitor object"
    );
  }

  return {
    name: "marko",
    parserOverride(code, jsParseOptions) {
      const file = getMarkoFile(code, jsParseOptions, markoOpts);
      const finalAst = t.cloneDeep(file.ast);
      SOURCE_FILES.set(finalAst, file);
      return finalAst;
    },
    pre(file) {
      const { ast, metadata } = file;
      const sourceFile = SOURCE_FILES.get(ast);
      metadata.marko = shallowClone(sourceFile.metadata.marko);

      if (markoOpts._translate !== false) {
        const { buildCodeFrameError } = file;
        const { buildError } = file.hub;
        file.buildCodeFrameError = MarkoFile.prototype.buildCodeFrameError;
        file.hub.buildError = file.buildCodeFrameError.bind(file);
        file.markoOpts = markoOpts;
        file.___taglibLookup = sourceFile.___taglibLookup;
        file.___getMarkoFile = getMarkoFile;
        traverse(ast, translator.visitor, file.scope);
        file.buildCodeFrameError = buildCodeFrameError;
        file.hub.buildError = buildError;
        file.markoOpts = file.___taglibLookup = file.___getMarkoFile = undefined;
      }

      metadata.marko.watchFiles = metadata.marko.watchFiles.filter(unique);
    }
  };
};

export function getMarkoFile(code, jsParseOptions, markoOpts) {
  let compileCache = markoOpts.cache.get(markoOpts.translator);

  if (!compileCache) {
    markoOpts.cache.set(markoOpts.translator, (compileCache = new Map()));
  }

  const filename = jsParseOptions.sourceFileName;
  const componentId = path.relative(ROOT, filename);
  const contentHash = createHash("MD5")
    .update(code)
    .digest("hex");
  const cacheKey = createHash("MD5")
    .update(componentId)
    .update(markoOpts.migrate ? "\0" : "")
    .digest("hex");

  let cached = compileCache.get(cacheKey);

  if (cached) {
    if (cached.contentHash !== contentHash) {
      // File content changed, invalidate the cache.
      cached = undefined;
    } else {
      for (const watchFile of cached.file.metadata.marko.watchFiles) {
        let mtime = Infinity;
        try {
          mtime = markoOpts.fileSystem.statSync(watchFile).mtime;
          // eslint-disable-next-line no-empty
        } catch {}

        if (mtime > cached.time) {
          // Some dependency changed, invalidate the cache.
          cached = undefined;
          break;
        }
      }
    }
  }

  if (cached) {
    return cached.file;
  }

  const taglibLookup = buildLookup(
    path.dirname(filename),
    markoOpts.translator
  );

  const file = new MarkoFile(jsParseOptions, {
    code,
    ast: {
      type: "File",
      program: {
        type: "Program",
        sourceType: "module",
        body: [],
        directives: []
      }
    }
  });

  const meta = (file.metadata.marko = {
    id: componentId,
    macros: {},
    deps: [],
    tags: [],
    watchFiles: []
  });

  const rootMigrators = [migrate];
  const rootTransformers = [transform];

  file.markoOpts = markoOpts;
  file.___taglibLookup = taglibLookup;
  file.___getMarkoFile = getMarkoFile;

  file.ast.start = file.ast.program.start = 0;
  file.ast.end = file.ast.program.end = code.length - 1;
  file.ast.loc = file.ast.program.loc = {
    start: { line: 0, column: 0 },
    end: getLoc(file, file.ast.end)
  };

  parseMarko(file);
  file.path.scope.crawl(); // Initialize bindings.

  for (const id in taglibLookup.taglibsById) {
    const { migratorPath } = taglibLookup.taglibsById[id];
    if (migratorPath) {
      const mod = markoModules.require(migratorPath);
      meta.watchFiles.push(migratorPath);
      rootMigrators.push(mod.default || mod);
    }
  }

  for (const { path: transformerPath } of taglibLookup.merged.transformers) {
    const mod = markoModules.require(transformerPath);
    meta.watchFiles.push(transformerPath);
    rootTransformers.push(mod.default || mod);
  }

  traverse(file.ast, mergeVisitors(rootMigrators), file.scope);
  traverse(file.ast, mergeVisitors(rootTransformers), file.scope);

  for (const taglibId in taglibLookup.taglibsById) {
    const { filePath } = taglibLookup.taglibsById[taglibId];

    if (
      filePath[filePath.length - 5] === "." &&
      filePath.endsWith("marko.json")
    ) {
      meta.watchFiles.push(filePath);
    }
  }

  compileCache.set(cacheKey, {
    time: Date.now(),
    file,
    contentHash
  });

  return file;
}

function shallowClone(data) {
  const clone = {};

  for (const key in data) {
    const v = data[key];

    if (v !== undefined) {
      if (v === null || typeof v !== "object") {
        clone[key] = v;
      } else {
        const Ctor = v.constructor;

        switch (Ctor) {
          case Array:
            clone[key] = [...v];
            break;
          case Object:
          case null:
            clone[key] = { ...v };
            break;
          case Map:
          case Set:
          case Date:
          case RegExp:
            clone[key] = new Ctor(v);
            break;

          default:
            throw new Error(`Unsupported metadata type of ${Ctor.name}`);
        }
      }
    }
  }

  return clone;
}

function mergeVisitors(all) {
  if (all.length <= 1) {
    return all[0];
  }

  return visitors.merge(all);
}

function unique(item, i, list) {
  return list.indexOf(item) === i;
}
<commit_msg>fix(compiler): no longer error when compiling from root dir<commit_after>import path from "path";
import { createHash } from "crypto";
import { getRootDir } from "lasso-package-root";
import { types as t } from "@marko/babel-types";
import { getLoc } from "@marko/babel-utils";
import traverse, { visitors } from "@babel/traverse";
import { buildLookup } from "../taglib";
import { parseMarko } from "./parser";
import { visitor as migrate } from "./plugins/migrate";
import { visitor as transform } from "./plugins/transform";
import markoModules from "../../modules";
import { MarkoFile } from "./file";

const SOURCE_FILES = new WeakMap();
let ROOT = process.cwd();
try {
  ROOT = getRootDir(ROOT) || ROOT;
  // eslint-disable-next-line no-empty
} catch {}

export default (api, markoOpts) => {
  api.assertVersion(7);
  const translator = markoOpts.translator;

  markoOpts.output = markoOpts.output || "html";

  if (markoOpts.optimize === undefined) {
    markoOpts.optimize = api.env("production");
  }

  if (!translator || !translator.visitor) {
    throw new Error(
      "@marko/compiler: translator must provide a visitor object"
    );
  }

  return {
    name: "marko",
    parserOverride(code, jsParseOptions) {
      const file = getMarkoFile(code, jsParseOptions, markoOpts);
      const finalAst = t.cloneDeep(file.ast);
      SOURCE_FILES.set(finalAst, file);
      return finalAst;
    },
    pre(file) {
      const { ast, metadata } = file;
      const sourceFile = SOURCE_FILES.get(ast);
      metadata.marko = shallowClone(sourceFile.metadata.marko);

      if (markoOpts._translate !== false) {
        const { buildCodeFrameError } = file;
        const { buildError } = file.hub;
        file.buildCodeFrameError = MarkoFile.prototype.buildCodeFrameError;
        file.hub.buildError = file.buildCodeFrameError.bind(file);
        file.markoOpts = markoOpts;
        file.___taglibLookup = sourceFile.___taglibLookup;
        file.___getMarkoFile = getMarkoFile;
        traverse(ast, translator.visitor, file.scope);
        file.buildCodeFrameError = buildCodeFrameError;
        file.hub.buildError = buildError;
        file.markoOpts = file.___taglibLookup = file.___getMarkoFile = undefined;
      }

      metadata.marko.watchFiles = metadata.marko.watchFiles.filter(unique);
    }
  };
};

export function getMarkoFile(code, jsParseOptions, markoOpts) {
  let compileCache = markoOpts.cache.get(markoOpts.translator);

  if (!compileCache) {
    markoOpts.cache.set(markoOpts.translator, (compileCache = new Map()));
  }

  const filename = jsParseOptions.sourceFileName;
  const componentId = path.relative(ROOT, filename);
  const contentHash = createHash("MD5")
    .update(code)
    .digest("hex");
  const cacheKey = createHash("MD5")
    .update(componentId)
    .update(markoOpts.migrate ? "\0" : "")
    .digest("hex");

  let cached = compileCache.get(cacheKey);

  if (cached) {
    if (cached.contentHash !== contentHash) {
      // File content changed, invalidate the cache.
      cached = undefined;
    } else {
      for (const watchFile of cached.file.metadata.marko.watchFiles) {
        let mtime = Infinity;
        try {
          mtime = markoOpts.fileSystem.statSync(watchFile).mtime;
          // eslint-disable-next-line no-empty
        } catch {}

        if (mtime > cached.time) {
          // Some dependency changed, invalidate the cache.
          cached = undefined;
          break;
        }
      }
    }
  }

  if (cached) {
    return cached.file;
  }

  const taglibLookup = buildLookup(
    path.dirname(filename),
    markoOpts.translator
  );

  const file = new MarkoFile(jsParseOptions, {
    code,
    ast: {
      type: "File",
      program: {
        type: "Program",
        sourceType: "module",
        body: [],
        directives: []
      }
    }
  });

  const meta = (file.metadata.marko = {
    id: componentId,
    macros: {},
    deps: [],
    tags: [],
    watchFiles: []
  });

  const rootMigrators = [migrate];
  const rootTransformers = [transform];

  file.markoOpts = markoOpts;
  file.___taglibLookup = taglibLookup;
  file.___getMarkoFile = getMarkoFile;

  file.ast.start = file.ast.program.start = 0;
  file.ast.end = file.ast.program.end = code.length - 1;
  file.ast.loc = file.ast.program.loc = {
    start: { line: 0, column: 0 },
    end: getLoc(file, file.ast.end)
  };

  parseMarko(file);
  file.path.scope.crawl(); // Initialize bindings.

  for (const id in taglibLookup.taglibsById) {
    const { migratorPath } = taglibLookup.taglibsById[id];
    if (migratorPath) {
      const mod = markoModules.require(migratorPath);
      meta.watchFiles.push(migratorPath);
      rootMigrators.push(mod.default || mod);
    }
  }

  for (const { path: transformerPath } of taglibLookup.merged.transformers) {
    const mod = markoModules.require(transformerPath);
    meta.watchFiles.push(transformerPath);
    rootTransformers.push(mod.default || mod);
  }

  traverse(file.ast, mergeVisitors(rootMigrators), file.scope);
  traverse(file.ast, mergeVisitors(rootTransformers), file.scope);

  for (const taglibId in taglibLookup.taglibsById) {
    const { filePath } = taglibLookup.taglibsById[taglibId];

    if (
      filePath[filePath.length - 5] === "." &&
      filePath.endsWith("marko.json")
    ) {
      meta.watchFiles.push(filePath);
    }
  }

  compileCache.set(cacheKey, {
    time: Date.now(),
    file,
    contentHash
  });

  return file;
}

function shallowClone(data) {
  const clone = {};

  for (const key in data) {
    const v = data[key];

    if (v !== undefined) {
      if (v === null || typeof v !== "object") {
        clone[key] = v;
      } else {
        const Ctor = v.constructor;

        switch (Ctor) {
          case Array:
            clone[key] = [...v];
            break;
          case Object:
          case null:
            clone[key] = { ...v };
            break;
          case Map:
          case Set:
          case Date:
          case RegExp:
            clone[key] = new Ctor(v);
            break;

          default:
            throw new Error(`Unsupported metadata type of ${Ctor.name}`);
        }
      }
    }
  }

  return clone;
}

function mergeVisitors(all) {
  if (all.length <= 1) {
    return all[0];
  }

  return visitors.merge(all);
}

function unique(item, i, list) {
  return list.indexOf(item) === i;
}
<|endoftext|>


<commit_before>import { combineReducers } from 'redux'
import counterReducer from './counter'

const rootReducer = combineReducers({
  count: counterReducer
})

export default rootReducer
<commit_msg>Fixing code style<commit_after>import { combineReducers } from 'redux'
import counterReducer from './counter'

const rootReducer = combineReducers({
  count: counterReducer,
})

export default rootReducer
<|endoftext|>


<commit_before>import { props, define } from '@bolt/core/utils';
import { withLitHtml, html } from '@bolt/core/renderers/renderer-lit-html';
import { parse } from 'himalaya';

import classNames from 'classnames/bind';

import styles from './table.scss';
import schema from '../table.schema.yml';

let cx = classNames.bind(styles);

@define
class BoltTable extends withLitHtml() {
  static is = 'bolt-table';

  static props = {
    format: {
      ...props.string,
      ...{ default: 'regular' },
    },
    borderless: {
      ...props.boolean,
      ...{ default: false },
    },
    firstColFixedWidth: {
      ...props.boolean,
      ...{ default: false },
    },
  };

  // constructor(self) {
  //   self = super(self);
  //   self.useShadow = hasNativeShadowDomSupport;
  //   self.validate = ajv.compile(schema);
  //   return self;
  // }

  removeEmptyNodes(nodes) {
    return nodes.filter(node => {
      if (node.type === 'element') {
        node.children = this.removeEmptyNodes(node.children);
        return true;
      }
      return node.content.length;
    });
  }

  stripWhitespace(nodes) {
    return nodes.map(node => {
      if (node.type === 'element') {
        node.children = this.stripWhitespace(node.children);
      } else {
        node.content = node.content.trim();
      }
      return node;
    });
  }

  removeWhitespace(nodes) {
    return this.removeEmptyNodes(this.stripWhitespace(nodes));
  }

  createProp(object, prop, value) {
    if (object[`${prop}`] === undefined) {
      object[`${prop}`] = value;
    }
  }

  convertElements(element, object, parent = 'rows') {
    const boltedObject = object !== undefined ? object : {};

    element.map(element => {
      switch (element.tagName) {
        case 'thead':
          this.createProp(boltedObject, 'header', []);
          this.convertElements(element.children, boltedObject, 'header');
          break;
        case 'tbody':
          this.createProp(boltedObject, 'rows', []);
          this.convertElements(element.children, boltedObject, 'rows');
          break;
        case 'tfoot':
          this.createProp(boltedObject, 'footer', []);
          this.convertElements(element.children, boltedObject, 'footer');
          break;
        case 'tr':
          const elements = element.children.map(child => {
            const { type, children, ...partialObject } = child;

            const correctText =
              child.children[0] !== undefined ? child.children[0].content : '';

            const updatedChild = {
              text: correctText,
              ...partialObject,
            };

            return updatedChild;
          });

          boltedObject[`${parent}`].push(elements);
          break;
        default:
          this.convertElements(element.children, boltedObject);
      }
    });

    return boltedObject;
  }

  // setAttr(element, attribute, value, defaultValue) {
  //   value === ''
  //     ? element.setAttribute(attribute, defaultValue)
  //     : element.setAttribute(attribute, value);
  // }

  render() {
    const parseCode = this.removeWhitespace(parse(this.innerHTML));
    const { format, borderless, firstColFixedWidth } = this.props;
    console.log(format);
    const tableClasses = cx('c-bolt-table', {
      [`c-bolt-table--format-${format}`]: format !== 'regular',
      [`c-bolt-table--borderless`]: borderless,
      [`c-bolt-table--first-col-fixed-width`]: firstColFixedWidth,
    });
    const bodyClasses = cx('c-bolt-table__body');
    const headClasses = cx('c-bolt-table__head');
    const footClasses = cx('c-bolt-table__foot');
    const rowClasses = cx('c-bolt-table__row');
    const cellClasses = cx('c-bolt-table__cell');
    let boltTableMarkup = [];

    this.setAttribute('format', format);

    const boltTable = this.convertElements(parseCode);

    function setRowTag(row) {
      return html`

          ${row.map(
            item =>
              html`
                ${setCellTag(item)}
              `,
          )}

      `;
    }

    function setCellTag(cell) {
      if (cell.tagName === 'th') {
        return html`

            ${cell.text}

        `;
      } else {
        return html`

            ${cell.text}

        `;
      }
    }

    // function setAttributes(element, attributes) {
    //   if (attributes.length > 0) {
    //     return attributes.map(attribute =>
    //       element.setAttribute(attribute.key, attribute.value),
    //     );
    //   }
    // }

    if (boltTable.header) {
      boltTableMarkup.push(html`

          ${boltTable.header.map(
            row => html`
              ${setRowTag(row)}
            `,
          )}

      `);
    }

    if (boltTable.rows) {
      boltTableMarkup.push(html`

          ${boltTable.rows.map(
            row => html`
              ${setRowTag(row)}
            `,
          )}

      `);
    }

    if (boltTable.footer) {
      boltTableMarkup.push(html`

          ${boltTable.footer.map(
            row => html`
              ${setRowTag(row)}
            `,
          )}

      `);
    }

    console.log('BT:', boltTable);
    console.log('BTM:', boltTableMarkup);

    return html`
      ${this.addStyles([styles])}

        ${boltTableMarkup}

    `;
  }
}

export { BoltTable };
<commit_msg>WIP(@bolt/components-table): update table object structure<commit_after>import { props, define } from '@bolt/core/utils';
import { withLitHtml, html } from '@bolt/core/renderers/renderer-lit-html';
import { parse } from 'himalaya';

import classNames from 'classnames/bind';

import styles from './table.scss';
import schema from '../table.schema.yml';

let cx = classNames.bind(styles);

@define
class BoltTable extends withLitHtml() {
  static is = 'bolt-table';

  static props = {
    format: {
      ...props.string,
      ...{ default: 'regular' },
    },
    borderless: {
      ...props.boolean,
      ...{ default: false },
    },
    firstColFixedWidth: {
      ...props.boolean,
      ...{ default: false },
    },
  };

  // constructor(self) {
  //   self = super(self);
  //   self.useShadow = hasNativeShadowDomSupport;
  //   self.validate = ajv.compile(schema);
  //   return self;
  // }

  removeEmptyNodes(nodes) {
    return nodes.filter(node => {
      if (node.type === 'element') {
        node.children = this.removeEmptyNodes(node.children);
        return true;
      }
      return node.content.length;
    });
  }

  stripWhitespace(nodes) {
    return nodes.map(node => {
      if (node.type === 'element') {
        node.children = this.stripWhitespace(node.children);
      } else {
        node.content = node.content.trim();
      }
      return node;
    });
  }

  removeWhitespace(nodes) {
    return this.removeEmptyNodes(this.stripWhitespace(nodes));
  }

  createProp(object, prop, value) {
    if (object[`${prop}`] === undefined) {
      object[`${prop}`] = value;
    }
  }

  convertElements(element, object, parent = 'body') {
    const boltedObject = object !== undefined ? object : {};

    element.map(element => {
      switch (element.tagName) {
        case 'thead':
          this.createProp(boltedObject, 'head', []);
          this.convertElements(element.children, boltedObject, 'head');
          break;
        case 'tbody':
          this.createProp(boltedObject, 'body', []);
          this.convertElements(element.children, boltedObject, 'body');
          break;
        case 'tfoot':
          this.createProp(boltedObject, 'foot', []);
          this.convertElements(element.children, boltedObject, 'foot');
          break;
        case 'tr':
          const elements = element.children.map(child => {
            const { type, children, ...partialObject } = child;

            const correctText =
              child.children[0] !== undefined ? child.children[0].content : '';

            const updatedChild = {
              text: correctText,
              ...partialObject,
            };

            return updatedChild;
          });

          boltedObject[`${parent}`].push(elements);
          break;
        default:
          this.convertElements(element.children, boltedObject);
      }
    });

    return boltedObject;
  }

  // setAttr(element, attribute, value, defaultValue) {
  //   value === ''
  //     ? element.setAttribute(attribute, defaultValue)
  //     : element.setAttribute(attribute, value);
  // }

  render() {
    const parseCode = this.removeWhitespace(parse(this.innerHTML));
    const { format, borderless, firstColFixedWidth } = this.props;
    console.log(format);
    const tableClasses = cx('c-bolt-table', {
      [`c-bolt-table--format-${format}`]: format !== 'regular',
      [`c-bolt-table--borderless`]: borderless,
      [`c-bolt-table--first-col-fixed-width`]: firstColFixedWidth,
    });
    const bodyClasses = cx('c-bolt-table__body');
    const headClasses = cx('c-bolt-table__head');
    const footClasses = cx('c-bolt-table__foot');
    const rowClasses = cx('c-bolt-table__row');
    const cellClasses = cx('c-bolt-table__cell');
    let boltTableMarkup = [];

    this.setAttribute('format', format);

    const boltTable = this.convertElements(parseCode);

    function setRowTag(row) {
      return html`

          ${row.map(
            item =>
              html`
                ${setCellTag(item)}
              `,
          )}

      `;
    }

    function setCellTag(cell) {
      if (cell.tagName === 'th') {
        return html`

            ${cell.text}

        `;
      } else {
        return html`

            ${cell.text}

        `;
      }
    }

    // function setAttributes(element, attributes) {
    //   if (attributes.length > 0) {
    //     return attributes.map(attribute =>
    //       element.setAttribute(attribute.key, attribute.value),
    //     );
    //   }
    // }

    if (boltTable.head) {
      boltTableMarkup.push(html`

          ${boltTable.head.map(
            row => html`
              ${setRowTag(row)}
            `,
          )}

      `);
    }

    if (boltTable.body) {
      boltTableMarkup.push(html`

          ${boltTable.body.map(
            row => html`
              ${setRowTag(row)}
            `,
          )}

      `);
    }

    if (boltTable.foot) {
      boltTableMarkup.push(html`

          ${boltTable.foot.map(
            row => html`
              ${setRowTag(row)}
            `,
          )}

      `);
    }

    console.log('BT:', boltTable);
    console.log('BTM:', boltTableMarkup);

    return html`
      ${this.addStyles([styles])}

        ${boltTableMarkup}

    `;
  }
}

export { BoltTable };
<|endoftext|>


<commit_before>var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false, frame: false });
var path = require('path');
var getPrivateInfo = require('./getPrivateInfo').usaa;

nightmare
  .goto(getPrivateInfo().url())
  .click('#logOnButton a')
  .type('input#input_onlineid', getPrivateInfo().username())
  .type('input#input_password', getPrivateInfo().password())
  .click('input[type="submit"]')
  .wait('input#pinTextField')
  .type('input#pinTextField', getPrivateInfo().pin())
  .click('button[type="submit"]')
  .wait('label[for="securityQuestionTextField"]')
  .evaluate(() => document.querySelector('label[for="securityQuestionTextField"]').innerHTML)
  .then(result => {
    return nightmare
      .type('#securityQuestionTextField', getPrivateInfo().answer(result.toLowerCase()))
      .click('button[type="submit"]')
      .wait('#menu')
      .click('#menu li:first-child a')
      .wait('.acct-group-list')
      .evaluate(() => [...document.querySelectorAll('.acct-group-list:first-child  li .link-liner')]
        .map(node=>{ return node.innerHTML; })
      )
      .then(result => {
        result.forEach(string=>{
            if(!string.split('acct-bal">')[1]) return;
            const account = {
              name: string.split('acct-name">')[1].split('')[0] + ' ' + string.split('acct-detail">')[1].split('')[0],
              balance: string.split('acct-bal">')[1].split('')[0]
            };
            console.log(account)
        });
        return nightmare
          .click('.custom-accts > div:first-child > div:nth-child(2) .acct-group-list:first-child .acct-group-row:first-child a:first-child')
          //.click('a.acct-info')
          .wait('.section')
          .evaluate(() => [...document.querySelectorAll('.details')]
            .map(node=>{ return node.innerText.replace(/\n/g,'').replace(/\t/g,'').replace(' ',''); })
          )
          .then(result => {
            console.log(result);
            return nightmare
              .screenshot(path.join(__dirname, 'usaa.png'))
          })

      })
  })
  .then(() => {
    return nightmare
      .end()
  })
  .catch(function (error) {
    console.error('Error:', error);
  });

    // nightmare
    //   .goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1')
    //   .click('input#input_onlineid')
    //   .click('div#main-ctr > div.section-ctr:nth-child(4)')
    //   .click('input#input_password')
    //   .click('div#main-ctr > div.section-ctr:nth-child(4)')
    //   .click('div#main-ctr > div.section-ctr:nth-child(4) > div.button-ctr:nth-child(1) > div.yui3-g.padded:nth-child(1) > div.yui3-u-1:nth-child(1) > input.main-button:nth-child(1)')
    //   .click('input#pinTextField')
    //   .click('button#id4')
    //   .click('input#securityQuestionTextField')
    //   .click('div#flowWrapper')
    //   .click('button#id6')
    //   .click('div#id3 > ul.acct-group-list:nth-child(1) > li.acct-group-row:nth-child(1) > a.usaa-link.acct-info.clearfix:nth-child(1) > span.link-liner:nth-child(1) > span.acct-name:nth-child(1)')
    //   .end()
    //     .then(function (result) {
    //       console.log(result)
    //     })
    //     .catch(function (error) {
    //       console.error('Error:', error);
    //     });
<commit_msg>usaa scraper: modularize and add scraping of other accounts<commit_after>var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: false, frame: false });
var path = require('path');
var getPrivateInfo = require('./getPrivateInfo').usaa;

const getUSAA = callback => {
  var usaaOutput = {
    accounts: []
  };
  nightmare
    .goto(getPrivateInfo().url())
    .click('#logOnButton a')
    .type('input#input_onlineid', getPrivateInfo().username())
    .type('input#input_password', getPrivateInfo().password())
    .click('input[type="submit"]')
    .wait('input#pinTextField')
    .type('input#pinTextField', getPrivateInfo().pin())
    .click('button[type="submit"]')
    .wait('label[for="securityQuestionTextField"]')
    .evaluate(() => document.querySelector('label[for="securityQuestionTextField"]').innerHTML)
    .then(result => {
      return nightmare
        .type('#securityQuestionTextField', getPrivateInfo().answer(result.toLowerCase()))
        .click('button[type="submit"]')
        .wait('#menu')
        .click('#menu li:first-child a')
        .wait('.acct-group-list')
        .evaluate(() => [...document.querySelectorAll('.acct-group-list:first-child  li .link-liner')]
          .map(node=>{ return node.innerHTML; })
        )
    })
    .then(result => {
      // results of accounts overview
      result.forEach(string=>{
          if(!string.split('acct-bal">')[1]) return;
          const account = {
            name: string.split('acct-name">')[1].split('')[0] + ' ' + string.split('acct-detail">')[1].split('')[0],
            balance: string.split('acct-bal">')[1].split('')[0].replace('$','').replace(',','')
          };
          usaaOutput.accounts.push(account);
      });
    })
    .then(() => {
      return nightmare
        .click('.custom-accts > div:first-child > div:nth-child(2) .acct-group-list:first-child .acct-group-row:first-child a:first-child')
        //.click('a.acct-info')
        .wait('.section')
        .evaluate(() => [...document.querySelectorAll('.details')]
          .map(node=>{ return node.innerText.replace(/\n/g,'').replace(/\t/g,'').replace(' ',''); })
        )
    })
    .then(result => {
      // results of main account list
      const transactions = result
        .filter(x => /(\s){3}/g.test(x) ) //has whitespace repeated 3 times
        .map(x => ({
          date: x.split(/(\s){3}/g)[0],
          description: x.split(/(\s){3}/g)[2],
          amount: (() => {
            const value = x.split(/(\s){3}/g)[4].replace('$','').replace(',','');
            return value.match(/^\([\d,\.]*\)$/)
              ? '-' + value.replace(/[\(\)]/g,'')
              : value;
          })()
        }))
      usaaOutput.accounts[0].transactions = transactions;
    })
    .then(() => {
      return nightmare
        .back()
        .wait('.acct-group-list')
        .click('.acct-group-list li:nth-child(2) a')
        .wait('.section')
        .evaluate(() => [...document.querySelectorAll('.details')]
          .map(node=>{ return node.innerText.replace(/\n/g,'').replace(/\t/g,'').replace(' ',''); })
        )
        //TODO: get info from other accounts
    })
    .then(result => {
      // results of savings account list
      const transactions = result
        .filter(x => /(\s){3}/g.test(x) ) //has whitespace repeated 3 times
        .map(x => ({
          date: x.split(/(\s){3}/g)[0],
          description: x.split(/(\s){3}/g)[2],
          amount: (() => {
            const value = x.split(/(\s){3}/g)[4].replace('$','').replace(',','');
            return value.match(/^\([\d,\.]*\)$/)
              ? '-' + value.replace(/[\(\)]/g,'')
              : value;
          })()
        }))
      usaaOutput.accounts[1].transactions = transactions;
    })
    .then(() => {
      return nightmare
        .back()
        .wait('.acct-group-list')
        .click('.acct-group-list li:nth-child(3) a')
        .wait('.section')
        .evaluate(() => [...document.querySelectorAll('.details')]
          .map(node=>{ return node.innerText.replace(/\n/g,'').replace(/\t/g,'').replace(' ',''); })
        )
        //TODO: get info from other accounts
    })
    .then(result => {
      // results of savings account list
      const transactions = result
        .filter(x => /(\s){3}/g.test(x) ) //has whitespace repeated 3 times
        .map(x => ({
          date: x.split(/(\s){3}/g)[0],
          description: x.split(/(\s){3}/g)[2],
          amount: (() => {
            const value = x.split(/(\s){3}/g)[4].replace('$','').replace(',','');
            return value.match(/^\([\d,\.]*\)$/)
              ? '-' + value.replace(/[\(\)]/g,'')
              : value;
          })()
        }))
      usaaOutput.accounts[2].transactions = transactions;
    })
    // TODO: get VISA details
    // .then(() => {
    //   return nightmare
    //     .back()
    //     .wait('.acct-group-list')
    //     .click('.acct-group-list li:nth-child(4) a')
    //     .wait('.section')
    //     .evaluate(() => [...document.querySelectorAll('.details')]
    //       .map(node=>{ return node.innerText.replace(/\n/g,'').replace(/\t/g,'').replace(' ',''); })
    //     )
    // })
    // .then(result => {
    //   // results of VISA account list
    //   const transactions = result
    //     .filter(x => /(\s){3}/g.test(x) ) //has whitespace repeated 3 times
    //     .map(x => ({
    //       date: x.split(/(\s){3}/g)[0],
    //       description: x.split(/(\s){3}/g)[2],
    //       amount: (() => {
    //         const value = x.split(/(\s){3}/g)[4].replace('$','').replace(',','');
    //         return value.match(/^\([\d,\.]*\)$/)
    //           ? '-' + value.replace(/[\(\)]/g,'')
    //           : value;
    //       })()
    //     }))
    //   usaaOutput.accounts[3].transactions = transactions;
    // })
    .then(() => {
      callback(null, usaaOutput)
      return nightmare
        .screenshot(path.join(__dirname, 'usaa.png'))
        .end()
    })
    .catch(function (error) {
      callback(error);
    });
}

const callback = (err, data) => {
  if (err){
    return console.log('Error:\n', err);
  }
  console.log('USAA:\n', JSON.stringify(data, null, '  '));
};

getUSAA(callback);
<|endoftext|>


<commit_before>'use strict'

const mw = require('./middleware')

const isAuthenticated = require('../../passport/authorization-middleware').isAuthenticated

module.exports = [
  [ '/api/users/', 'get', [ isAuthenticated, mw.formatQuery, mw.query ] ],
  [ '/api/users/', 'post', [ mw.register ]],
  [ '/api/users/me', 'get', [ mw.getCurrent ] ],
  [ '/api/users/:id', 'delete', [ isAuthenticated, mw.remove ]],
  [ '/api/users/:id', 'get', [ isAuthenticated, mw.findOne ] ],
  [ '/api/users/:id', 'patch', [ isAuthenticated, mw.update ] ],
  [ '/api/users/:id', 'put', [ isAuthenticated, mw.update ] ],
  [ '/api/users/reset-password', 'post', [ mw.resetPassword ] ],
  [ '/api/users/update-password', 'post', [ mw.updatePassword ] ],
]
<commit_msg>Unwrap [] from middleware<commit_after>'use strict'

const mw = require('./middleware')

const isAuthenticated = require('../../passport/authorization-middleware').isAuthenticated

module.exports = [
  [ '/api/users/', 'get', isAuthenticated, mw.formatQuery, mw.query ],
  [ '/api/users/', 'post', mw.register ],
  [ '/api/users/me', 'get', mw.getCurrent ],
  [ '/api/users/:id', 'delete', isAuthenticated, mw.remove],
  [ '/api/users/:id', 'get', isAuthenticated, mw.findOne ],
  [ '/api/users/:id', 'patch', isAuthenticated, mw.update ],
  [ '/api/users/:id', 'put', isAuthenticated, mw.update ],
  [ '/api/users/reset-password', 'post', mw.resetPassword ],
  [ '/api/users/update-password', 'post', mw.updatePassword ]
]
<|endoftext|>


<commit_before>import { describe } from 'riteway';
import createFeatures from '../test/fixtures/createFeatures';
import Response from './test/Response';
import Request from './test/Request';
import Next from './test/Next';
import Callback from './test/Callback';

import createRouteMiddleware from './index';

describe('createRouteMiddleware()', async should => {
  const { assert } = should('update the status code correctly');

  {
    const features = createFeatures();
    const req = Request();
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const req = Request({ method: 'GET' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature : 'help' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is disabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 404
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const req = Request({ url: 'http://mydomain.com/help?ft=help' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'help' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is disabled and a search string that enables it',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const req = Request({ url: 'http://mydomain.com/help?ft=posts' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'help' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is disabled and an incorrect search string',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 404
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }
});

describe('createRouteMiddleware() auto curried', async should => {
  const { assert } = should('update the status code correctly');

  {
    const features = createFeatures();
    const req = Request();
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features)({requiredFeature: 'posts'});

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const getHander = Callback();
    const req = Request({ method: 'GET' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', get: getHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a GET request and a get handler',
      should: 'call the get handler',
      actual: getHander.isCalled,
      expected: true
    });

    assert({
      given: 'a GET request and a get handler',
      should: 'pass the correct arguments to the handler',
      actual: getHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

  {
    const features = createFeatures();
    const postHander = Callback();
    const req = Request({ method: 'POST' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', post: postHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a POST request and a post handler',
      should: 'call the post handler',
      actual: postHander.isCalled,
      expected: true
    });

    assert({
      given: 'a POST request and a post handler',
      should: 'pass the correct arguments to the handler',
      actual: postHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

  {
    const features = createFeatures();
    const deleteHander = Callback();
    const req = Request({ method: 'DELETE' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', delete: deleteHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a DELETE request and a delete handler',
      should: 'call the delete handler',
      actual: deleteHander.isCalled,
      expected: true
    });

    assert({
      given: 'a DELETE request and a delete handler',
      should: 'pass the correct arguments to the handler',
      actual: deleteHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

  {
    const features = createFeatures();
    const putHander = Callback();
    const req = Request({ method: 'PUT' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', put: putHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a PUT request and a put handler',
      should: 'call the put handler',
      actual: putHander.isCalled,
      expected: true
    });

    assert({
      given: 'a PUT request and a put handler',
      should: 'pass the correct arguments to the handler',
      actual: putHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

});

<commit_msg>use better wordering for test message<commit_after>import { describe } from 'riteway';
import createFeatures from '../test/fixtures/createFeatures';
import Response from './test/Response';
import Request from './test/Request';
import Next from './test/Next';
import Callback from './test/Callback';

import createRouteMiddleware from './index';

describe('createRouteMiddleware()', async should => {
  const { assert } = should('update the status code correctly');

  {
    const features = createFeatures();
    const req = Request();
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const req = Request({ method: 'GET' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature : 'help' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is disabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 404
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const req = Request({ url: 'http://mydomain.com/help?ft=help' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'help' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is disabled and a search string that enables it',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const req = Request({ url: 'http://mydomain.com/help?ft=posts' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'help' });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is disabled and an incorrect search string',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 404
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }
});

describe('createRouteMiddleware() auto curried', async should => {
  const { assert } = should('update the status code correctly');

  {
    const features = createFeatures();
    const req = Request();
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features)({requiredFeature: 'posts'});

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'next callback',
      should: 'call next after completing',
      actual: next.valueOf(),
      expected: true
    });
  }

  {
    const features = createFeatures();
    const getHander = Callback();
    const req = Request({ method: 'GET' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', get: getHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a GET request and a get handler',
      should: 'call the get handler',
      actual: getHander.isCalled,
      expected: true
    });

    assert({
      given: 'a GET request and a get handler',
      should: 'pass the correct arguments to the handler',
      actual: getHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler has been applied',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

  {
    const features = createFeatures();
    const postHander = Callback();
    const req = Request({ method: 'POST' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', post: postHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a POST request and a post handler',
      should: 'call the post handler',
      actual: postHander.isCalled,
      expected: true
    });

    assert({
      given: 'a POST request and a post handler',
      should: 'pass the correct arguments to the handler',
      actual: postHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler has been applied',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

  {
    const features = createFeatures();
    const deleteHander = Callback();
    const req = Request({ method: 'DELETE' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', delete: deleteHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a DELETE request and a delete handler',
      should: 'call the delete handler',
      actual: deleteHander.isCalled,
      expected: true
    });

    assert({
      given: 'a DELETE request and a delete handler',
      should: 'pass the correct arguments to the handler',
      actual: deleteHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler has been applied',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

  {
    const features = createFeatures();
    const putHander = Callback();
    const req = Request({ method: 'PUT' });
    const res = Response();
    const next = Next();
    const middleware = createRouteMiddleware(features, { requiredFeature: 'posts', put: putHander.callback });

    middleware(req, res, next.next);

    assert({
      given: 'a feature that is enabled',
      should: 'have the correct status code for res',
      actual: res.statusCode,
      expected: 200
    });

    assert({
      given: 'a PUT request and a put handler',
      should: 'call the put handler',
      actual: putHander.isCalled,
      expected: true
    });

    assert({
      given: 'a PUT request and a put handler',
      should: 'pass the correct arguments to the handler',
      actual: putHander.args,
      expected: [req, res]
    });

    assert({
      given: 'a method handler has been applied',
      should: 'do not call next after calling method handler',
      actual: next.valueOf(),
      expected: false
    });
  }

});

<|endoftext|>