<commit_before>/**
 * react-lazyload
 */
import React, { Component, PropTypes } from 'react';
import ReactDom from 'react-dom';
import { on, off } from './utils/event';
import scrollParent from './utils/scrollParent';
import debounce from './utils/debounce';
import throttle from './utils/throttle';

const LISTEN_FLAG = 'data-lazyload-listened';
const listeners = [];
let pending = [];

let warnedAboutPlaceholderHeight = false;
const heightDiffThreshold = 20;

/**
 * Check if `component` is visible in overflow container `parent`
 * @param  {node} component React component
 * @param  {node} parent    component's scroll parent
 * @return {bool}
 */
const checkOverflowVisible = function checkOverflowVisible(component, parent) {
  const node = ReactDom.findDOMNode(component);

  const scrollTop = parent.scrollTop;
  const parentBottom = scrollTop + parent.offsetHeight;
  const { height: elementHeight } = node.getBoundingClientRect();

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  const elementTop = node.offsetTop;
  const elementBottom = elementTop + elementHeight;

  return (elementTop - offsets[0] <= parentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Check if `component` is visible in document
 * @param  {node} component React component
 * @return {bool}
 */
const checkNormalVisible = function checkNormalVisible(component) {
  const node = ReactDom.findDOMNode(component);

  const supportPageOffset = window.pageXOffset !== undefined;
  const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
  const scrollTop = supportPageOffset ? window.pageYOffset :
                                        isCSS1Compat ?
                                        document.documentElement.scrollTop :
                                        document.body.scrollTop;

  const { top, height: elementHeight } = node.getBoundingClientRect();
  const elementTop = top + scrollTop; // element top relative to document
  const elementBottom = elementTop + elementHeight;

  const windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
  const documentBottom = scrollTop + windowInnerHeight;

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  return (elementTop - offsets[0] <= documentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Detect if element is visible in viewport, if so, set `visible` state to true.
 * If `once` prop is provided true, remove component as listener after checkVisible
 *
 * @param  {React} component   React component that respond to scroll and resize
 */
const checkVisible = function checkVisible(component) {
  const node = ReactDom.findDOMNode(component);
  if (!node) {
    return;
  }

  const parent = scrollParent(node);
  const isOverflow = parent !== (node.ownerDocument || document);

  const visible = isOverflow ?
                  checkOverflowVisible(component, parent) :
                  checkNormalVisible(component);

  if (visible) {
    // Avoid extra render if previously is visible, yeah I mean `render` call,
    // not actual DOM render
    if (!component.visible) {
      if (component.props.once) {
        pending.push(component);
      }

      component.visible = true;
      component.forceUpdate();
    }
  } else if (!(component.props.once && component.visible)) {
    component.visible = false;
  }
};

const purgePending = function purgePending() {
  pending.forEach(component => {
    const index = listeners.indexOf(component);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  });

  pending = [];
};

const lazyLoadHandler = () => {
  for (let i = 0; i < listeners.length; ++i) {
    const listener = listeners[i];
    checkVisible(listener);
  }

  // Remove `once` component in listeners
  purgePending();
};

// Depending on component's props
let delayType;
let finalLazyLoadHandler = null;

class LazyLoad extends Component {
  constructor(props) {
    super(props);

    this.visible = false;

    if (React.Children.count(this.props.children) > 1) {
      console.warn('[react-lazyload] Only one child is allowed to be passed to `LazyLoad`.');
    }

    if (typeof this.props.height !== 'number') {
      console.warn('[react-lazyload] Please add `height` props to <LazyLoad> for better performance.');
    }

    if (this.props.wheel) { // eslint-disable-line
      console.warn('[react-lazyload] Props `wheel` is not supported anymore, try set `overflow` for lazy loading in overflow containers.');
    }
  }

  componentDidMount() {
    // It's unlikely to change delay type for an application, this is mainly
    // designed for tests
    let needResetFinalLazyLoadHandler = false;
    if (this.props.debounce !== undefined && delayType === 'throttle') {
      console.warn('[react-lazyload] Previous delay function is `throttle`, now switching to `debounce`, try to set them unanimously');
      needResetFinalLazyLoadHandler = true;
    } else if (delayType === 'debounce' && this.props.debounce === undefined) {
      console.warn('[react-lazyload] Previous delay function is `debounce`, now switching to `throttle`, try to set them unanimously');
      needResetFinalLazyLoadHandler = true;
    }

    if (needResetFinalLazyLoadHandler) {
      off(window, 'scroll', finalLazyLoadHandler);
      off(window, 'resize', finalLazyLoadHandler);
      finalLazyLoadHandler = null;
    }

    if (!finalLazyLoadHandler) {
      if (this.props.debounce !== undefined) {
        finalLazyLoadHandler = debounce(lazyLoadHandler, typeof this.props.debounce === 'number' ?
                                                         this.props.debounce :
                                                         300);
        delayType = 'debounce';
      } else {
        finalLazyLoadHandler = throttle(lazyLoadHandler, typeof this.props.throttle === 'number' ?
                                                         this.props.throttle :
                                                         300);
        delayType = 'throttle';
      }
    }

    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent && parent.getAttribute(LISTEN_FLAG) === null) {
        parent.addEventListener('scroll', finalLazyLoadHandler);
        parent.setAttribute(LISTEN_FLAG, 1);
      }
    } else if (listeners.length === 0 || needResetFinalLazyLoadHandler) {
      const { scroll, resize } = this.props;

      if (scroll) {
        on(window, 'scroll', finalLazyLoadHandler);
      }

      if (resize) {
        on(window, 'resize', finalLazyLoadHandler);
      }
    }

    listeners.push(this);
    checkVisible(this);

    if (process.env.NODE_ENV !== 'production') {
      if (this.props.placeholder) {
        const node = ReactDom.findDOMNode(this);
        if (!warnedAboutPlaceholderHeight &&
            Math.abs(node.offsetHeight - this.props.height) > heightDiffThreshold) {
          console.warn('[react-lazyload] A more specific `height` or `minHeight` for your own placeholder will result better lazyload performance.');
          warnedAboutPlaceholderHeight = true;
        }
      }
    }
  }

  shouldComponentUpdate() {
    return this.visible;
  }

  componentWillUnmount() {
    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent) {
        parent.removeEventListener('scroll', finalLazyLoadHandler);
        parent.removeAttribute(LISTEN_FLAG);
      }
    }

    const index = listeners.indexOf(this);
    if (index !== -1) {
      listeners.splice(index, 1);
    }

    if (listeners.length === 0) {
      off(window, 'resize', finalLazyLoadHandler);
      off(window, 'scroll', finalLazyLoadHandler);
    }
  }

  render() {
    return this.visible ?
           this.props.children :
             this.props.placeholder ?
                this.props.placeholder :

;
  }
}

LazyLoad.propTypes = {
  once: PropTypes.bool,
  height: PropTypes.number.isRequired,
  offset: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
  overflow: PropTypes.bool,
  resize: PropTypes.bool,
  scroll: PropTypes.bool,
  children: PropTypes.node,
  throttle: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  debounce: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  placeholder: PropTypes.node
};

LazyLoad.defaultProps = {
  once: false,
  height: 100,
  offset: 0,
  overflow: false,
  resize: false,
  scroll: true
};

import decorator from './decorator';
export const lazyload = decorator;
export default LazyLoad;
export { lazyLoadHandler as forceCheck };
<commit_msg>fix: ignore `html` as scroll parent<commit_after>/**
 * react-lazyload
 */
import React, { Component, PropTypes } from 'react';
import ReactDom from 'react-dom';
import { on, off } from './utils/event';
import scrollParent from './utils/scrollParent';
import debounce from './utils/debounce';
import throttle from './utils/throttle';

const LISTEN_FLAG = 'data-lazyload-listened';
const listeners = [];
let pending = [];

let warnedAboutPlaceholderHeight = false;
const heightDiffThreshold = 20;

/**
 * Check if `component` is visible in overflow container `parent`
 * @param  {node} component React component
 * @param  {node} parent    component's scroll parent
 * @return {bool}
 */
const checkOverflowVisible = function checkOverflowVisible(component, parent) {
  const node = ReactDom.findDOMNode(component);

  const scrollTop = parent.scrollTop;
  const parentBottom = scrollTop + parent.offsetHeight;
  const { height: elementHeight } = node.getBoundingClientRect();

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  const elementTop = node.offsetTop;
  const elementBottom = elementTop + elementHeight;

  return (elementTop - offsets[0] <= parentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Check if `component` is visible in document
 * @param  {node} component React component
 * @return {bool}
 */
const checkNormalVisible = function checkNormalVisible(component) {
  const node = ReactDom.findDOMNode(component);

  const supportPageOffset = window.pageXOffset !== undefined;
  const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
  const scrollTop = supportPageOffset ? window.pageYOffset :
                                        isCSS1Compat ?
                                        document.documentElement.scrollTop :
                                        document.body.scrollTop;

  const { top, height: elementHeight } = node.getBoundingClientRect();
  const elementTop = top + scrollTop; // element top relative to document
  const elementBottom = elementTop + elementHeight;

  const windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
  const documentBottom = scrollTop + windowInnerHeight;

  const offsets = Array.isArray(component.props.offset) ?
                component.props.offset :
                [component.props.offset, component.props.offset]; // Be compatible with previous API

  return (elementTop - offsets[0] <= documentBottom) &&
         (elementBottom + offsets[1] >= scrollTop);
};

/**
 * Detect if element is visible in viewport, if so, set `visible` state to true.
 * If `once` prop is provided true, remove component as listener after checkVisible
 *
 * @param  {React} component   React component that respond to scroll and resize
 */
const checkVisible = function checkVisible(component) {
  const node = ReactDom.findDOMNode(component);
  if (!node) {
    return;
  }

  const parent = scrollParent(node);
  const isOverflow = parent !== node.ownerDocument &&
                     parent !== document &&
                     parent !== document.documentElement;

  const visible = isOverflow ?
                  checkOverflowVisible(component, parent) :
                  checkNormalVisible(component);

  if (visible) {
    // Avoid extra render if previously is visible, yeah I mean `render` call,
    // not actual DOM render
    if (!component.visible) {
      if (component.props.once) {
        pending.push(component);
      }

      component.visible = true;
      component.forceUpdate();
    }
  } else if (!(component.props.once && component.visible)) {
    component.visible = false;
  }
};

const purgePending = function purgePending() {
  pending.forEach(component => {
    const index = listeners.indexOf(component);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  });

  pending = [];
};

const lazyLoadHandler = () => {
  for (let i = 0; i < listeners.length; ++i) {
    const listener = listeners[i];
    checkVisible(listener);
  }

  // Remove `once` component in listeners
  purgePending();
};

// Depending on component's props
let delayType;
let finalLazyLoadHandler = null;

class LazyLoad extends Component {
  constructor(props) {
    super(props);

    this.visible = false;

    if (React.Children.count(this.props.children) > 1) {
      console.warn('[react-lazyload] Only one child is allowed to be passed to `LazyLoad`.');
    }

    if (typeof this.props.height !== 'number') {
      console.warn('[react-lazyload] Please add `height` props to <LazyLoad> for better performance.');
    }

    if (this.props.wheel) { // eslint-disable-line
      console.warn('[react-lazyload] Props `wheel` is not supported anymore, try set `overflow` for lazy loading in overflow containers.');
    }
  }

  componentDidMount() {
    // It's unlikely to change delay type for an application, this is mainly
    // designed for tests
    let needResetFinalLazyLoadHandler = false;
    if (this.props.debounce !== undefined && delayType === 'throttle') {
      console.warn('[react-lazyload] Previous delay function is `throttle`, now switching to `debounce`, try to set them unanimously');
      needResetFinalLazyLoadHandler = true;
    } else if (delayType === 'debounce' && this.props.debounce === undefined) {
      console.warn('[react-lazyload] Previous delay function is `debounce`, now switching to `throttle`, try to set them unanimously');
      needResetFinalLazyLoadHandler = true;
    }

    if (needResetFinalLazyLoadHandler) {
      off(window, 'scroll', finalLazyLoadHandler);
      off(window, 'resize', finalLazyLoadHandler);
      finalLazyLoadHandler = null;
    }

    if (!finalLazyLoadHandler) {
      if (this.props.debounce !== undefined) {
        finalLazyLoadHandler = debounce(lazyLoadHandler, typeof this.props.debounce === 'number' ?
                                                         this.props.debounce :
                                                         300);
        delayType = 'debounce';
      } else {
        finalLazyLoadHandler = throttle(lazyLoadHandler, typeof this.props.throttle === 'number' ?
                                                         this.props.throttle :
                                                         300);
        delayType = 'throttle';
      }
    }

    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent && parent.getAttribute(LISTEN_FLAG) === null) {
        parent.addEventListener('scroll', finalLazyLoadHandler);
        parent.setAttribute(LISTEN_FLAG, 1);
      }
    } else if (listeners.length === 0 || needResetFinalLazyLoadHandler) {
      const { scroll, resize } = this.props;

      if (scroll) {
        on(window, 'scroll', finalLazyLoadHandler);
      }

      if (resize) {
        on(window, 'resize', finalLazyLoadHandler);
      }
    }

    listeners.push(this);
    checkVisible(this);

    if (process.env.NODE_ENV !== 'production') {
      if (this.props.placeholder) {
        const node = ReactDom.findDOMNode(this);
        if (!warnedAboutPlaceholderHeight &&
            Math.abs(node.offsetHeight - this.props.height) > heightDiffThreshold) {
          console.warn('[react-lazyload] A more specific `height` or `minHeight` for your own placeholder will result better lazyload performance.');
          warnedAboutPlaceholderHeight = true;
        }
      }
    }
  }

  shouldComponentUpdate() {
    return this.visible;
  }

  componentWillUnmount() {
    if (this.props.overflow) {
      const parent = scrollParent(ReactDom.findDOMNode(this));
      if (parent) {
        parent.removeEventListener('scroll', finalLazyLoadHandler);
        parent.removeAttribute(LISTEN_FLAG);
      }
    }

    const index = listeners.indexOf(this);
    if (index !== -1) {
      listeners.splice(index, 1);
    }

    if (listeners.length === 0) {
      off(window, 'resize', finalLazyLoadHandler);
      off(window, 'scroll', finalLazyLoadHandler);
    }
  }

  render() {
    return this.visible ?
           this.props.children :
             this.props.placeholder ?
                this.props.placeholder :

;
  }
}

LazyLoad.propTypes = {
  once: PropTypes.bool,
  height: PropTypes.number.isRequired,
  offset: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
  overflow: PropTypes.bool,
  resize: PropTypes.bool,
  scroll: PropTypes.bool,
  children: PropTypes.node,
  throttle: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  debounce: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
  placeholder: PropTypes.node
};

LazyLoad.defaultProps = {
  once: false,
  height: 100,
  offset: 0,
  overflow: false,
  resize: false,
  scroll: true
};

import decorator from './decorator';
export const lazyload = decorator;
export default LazyLoad;
export { lazyLoadHandler as forceCheck };
<|endoftext|>


<commit_before>var ReactDOM = require('react-dom');
var React = require('react');
var Web3 = require('web3');
var Web3Admin = require('./web3Admin')

 web3 = new Web3();
 web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
 Web3Admin.extend(web3);

var Debugger = require('./debugger');

ReactDOM.render(
  <Debugger/>,
  document.getElementById('app')
);
<commit_msg>indent<commit_after>var ReactDOM = require('react-dom');
var React = require('react');
var Web3 = require('web3');
var Web3Admin = require('./web3Admin')

web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
Web3Admin.extend(web3);

var Debugger = require('./debugger');

ReactDOM.render(
  <Debugger/>,
  document.getElementById('app')
);
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var spawn = require('child_process').spawn;

/**
 * The default path to the CINEMA 4D Application.
 *
 * @api private
 */
var cinema4d_path = '/Applications/MAXON/CINEMA\ 4D R14/CINEMA\ 4D.app/Contents/MacOS/CINEMA\ 4D';

/**
 * Set the path to the CINEMA 4D Application.
 *
 * @param {String} path
 * @api public
 */
exports.setApplicationPath = function(path) {
  cinema4d_path = path;
}

/**
 * This is the main render function.
 *
 * @api public
 */
exports.render = function(d) {
  // Print the d object. used for development and debugging
  console.log(d);

  // Check if a filepath is set. if no filepath is set, we cannot render...
  if (d.filepath === undefined) {
    log(d, 'No CINEMA 4D file to render.');
  }
  // Call the render...
  else {
    // This is the cli options array we need to execute with the spawn function.
    var tmpOptionsArray = [];
    tmpOptionsArray.push('-nogui');
    tmpOptionsArray.push('-render');
    tmpOptionsArray.push(d.filepath);

    // Check the different options...
    if (d.oimage !== undefined) {
      tmpOptionsArray.push('-oimage');
      tmpOptionsArray.push(d.oimage);
    };
    if (d.omultipass !== undefined) {
      tmpOptionsArray.push('-omultipass');
      tmpOptionsArray.push(d.omultipass);
    };
    if (d.oformat !== undefined) {
      tmpOptionsArray.push('-oformat');
      tmpOptionsArray.push(d.oformat);
    };
    if (d.threads !== undefined) {
      tmpOptionsArray.push('-threads');
      tmpOptionsArray.push(d.threads);
    };

    //log(d, tmpOptionsArray);

    // Execute the CINEMA 4D commandline interface.
    var c4dRender = spawn(cinema4d_path, tmpOptionsArray);
    c4dRender.stdout.on('data', function(data) {
      //console.log('VERSION: '+utils.getVersionFromStdout(data.toString()) );
      log(d, data.toString());
    });
    c4dRender.stderr.on('data', function(data) {
      log(d, 'Error: '+data.toString());
    });
    c4dRender.on('close', function(code) {
      //log(d, 'Closed with code: '+code);
    });
  }
}

/**
 * Log some data if the silent mode is not defined.
 *
 * @param d The data object.
 * @parma s The string we want to print out.
 * @api private
 */
function log(d, s) {
  if(d.silent === undefined) {
    console.log(s);
  }
}
<commit_msg>src/index.js added exports.getApplicationPath, changes at cli options array, moved c4dRender spawn to private function<commit_after>/**
 * Module dependencies.
 */
var spawn = require('child_process').spawn;

/**
 * The default path to the CINEMA 4D Application.
 *
 * @api private
 */
var cinema4d_path = '/Applications/MAXON/CINEMA\ 4D R14/CINEMA\ 4D.app/Contents/MacOS/CINEMA\ 4D';

/**
 * Set the path to the CINEMA 4D Application.
 *
 * @param {String} path
 * @api public
 */
exports.setApplicationPath = function(path) {
  cinema4d_path = path;
}

/**
 * Get the path to the CINEMA 4D Application.
 *
 * @return {String}
 * @api public
 */
exports.getApplicationPath = function() {
  return cinema4d_path;
}

/**
 * This is the main render function.
 *
 * @param {Object} d
 * @api public
 */
exports.render = function(d) {
  // Check if a filepath is set. if no filepath is set, we cannot render...
  if (d.filepath === undefined) {
    log(d, 'No CINEMA 4D file to render.');
  }
  // Call the render...
  else {
    execCinemaCli(d);
  }
}

/**
 * This function execute the CINEMA 4D commandline interface.
 *
 * @param {Object} d
 * @api private
 */
function execCinemaCli(d) {
  // Print the d object. used for development and debugging
  console.log(d);

  // This is the cli options array we need to execute with the spawn function.
  var tmpOptionsArray = [];
  tmpOptionsArray.push('-nogui');
  tmpOptionsArray.push('-render');
  tmpOptionsArray.push(d.filepath);

  // Check the different options...
  if (d.frame !== undefined) {
    tmpOptionsArray.push('-frame');
    var tmpFrame = d.frame.split(',');
    // Check how many parameter we add to the tmpOptionsArray.
    if (tmpFrame.length === 1) {
      tmpOptionsArray.push(tmpFrame[0]);
    }
    if (tmpFrame.length === 2) {
      tmpOptionsArray.push(tmpFrame[0]);
      tmpOptionsArray.push(tmpFrame[1]);
    }
    if (tmpFrame.length === 3) {
      tmpOptionsArray.push(tmpFrame[0]);
      tmpOptionsArray.push(tmpFrame[1]);
      tmpOptionsArray.push(tmpFrame[2]);
    }
  };
  if (d.oimage !== undefined) {
    tmpOptionsArray.push('-oimage');
    tmpOptionsArray.push(d.oimage);
  };
  if (d.omultipass !== undefined) {
    tmpOptionsArray.push('-omultipass');
    tmpOptionsArray.push(d.omultipass);
  };
  if (d.oformat !== undefined) {
    tmpOptionsArray.push('-oformat');
    tmpOptionsArray.push(d.oformat);
  };
  if (d.oresolution !== undefined) {
    tmpOptionsArray.push('-oresolution');
    var tmpResolution = d.oresolution.split(',');
    tmpOptionsArray.push(tmpResolution[0]);
    tmpOptionsArray.push(tmpResolution[1]);
  };
  if (d.threads !== undefined) {
    tmpOptionsArray.push('-threads');
    tmpOptionsArray.push(d.threads);
  };

  //log(d, tmpOptionsArray);

  // Execute the CINEMA 4D commandline interface.
  var c4dRender = spawn(cinema4d_path, tmpOptionsArray);
  c4dRender.stdout.on('data', function(data) {
    //console.log('VERSION: '+utils.getVersionFromStdout(data.toString()) );
    log(d, data.toString());
  });
  c4dRender.stderr.on('data', function(data) {
    log(d, 'Error: '+data.toString());
  });
  c4dRender.on('close', function(code) {
    //log(d, 'Closed with code: '+code);
  });
}

/**
 * Log some data if the silent mode is not defined.
 *
 * @param d The data object.
 * @parma s The string we want to print out.
 * @api private
 */
function log(d, s) {
  if(d.silent === undefined) {
    console.log(s);
  }
}
<|endoftext|>


<commit_before>
const pinchIt = () => {
  // private variable cache

  let elements;
  let scaling;
  let firstMove;
  let firstTouch;

  const cancelEvent = (e) => {
    e.stopPropagation();
    e.preventDefault();
  };

  const calcDist = (touches) => {
    console.log(touches);
    const [first, second] = touches;
    return Math.sqrt(
      ((first.pageX - second.pageX) * (first.pageX - second.pageX)) +
      ((first.pageY - second.pageY) * (first.pageY - second.pageY))
    );
  };

  const calcScale = (startTouch, endTouch) => (
    calcDist(endTouch) / calcDist(startTouch)
  );

  const attachEvents = (el) => {
    el.addEventListener('touchstart', (e) => {
      scaling = (e.touches.length === 2);
      firstMove = true;
    });

    el.addEventListener('touchmove', (e) => {
      const { target } = e;
      if (scaling && !firstTouch) {
        firstTouch = Array.from(e.touches);
      }
      if (scaling && firstTouch) {
        cancelEvent(e);
        const scale = calcScale(firstTouch, Array.from(e.touches));
        target.style.transform = `scale(${scale})`;
      }
      firstMove = false;
    });

    el.addEventListener('touchend', () => {
      scaling = false;
    });
  };

  const pinch = (target, options = {}) => {
    const opt = Object.assign({}, {

    }, options);

    // resolve target
    switch (typeof target) {
      case 'object':
        elements = target;
        break;
      case 'string':
        elements = document.querySelectorAll(target);
        break;
      default:
        console.warn('missing target, either pass an node or a string');
    }

    elements.forEach(attachEvents);
  };

  return pinch;
};

export default pinchIt();
<commit_msg>removed base code from index<commit_after>import pinchIt from './pinch-it';

export default pinchIt;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';

const propTypes = {
  className: PropTypes.string,
  onloadCallbackName: PropTypes.string,
  elementID: PropTypes.string,
  onloadCallback: PropTypes.func,
  verifyCallback: PropTypes.func,
  expiredCallback: PropTypes.func,
  render: PropTypes.string,
  sitekey: PropTypes.string,
  theme: PropTypes.string,
  type: PropTypes.string,
  verifyCallbackName: PropTypes.string,
  expiredCallbackName: PropTypes.string,
  size: PropTypes.string,
  tabindex: PropTypes.string,
  hl: PropTypes.string,
  badge: PropTypes.string,
};

const defaultProps = {
  elementID: 'g-recaptcha',
  onloadCallback: undefined,
  onloadCallbackName: 'onloadCallback',
  verifyCallback: undefined,
  verifyCallbackName: 'verifyCallback',
  expiredCallback: undefined,
  expiredCallbackName: 'expiredCallback',
  render: 'onload',
  theme: 'light',
  type: 'image',
  size: 'normal',
  tabindex: '0',
  hl: 'en',
  badge: 'bottomright',
};

const isReady = () => typeof window !== 'undefined'
  && typeof window.grecaptcha !== 'undefined'
  && typeof window.grecaptcha.render === 'function';

let readyCheck;

export default class Recaptcha extends Component {

  constructor(props) {
    super(props);
    this._renderGrecaptcha = this._renderGrecaptcha.bind(this);
    this.reset = this.reset.bind(this);
    this.state = {
      ready: isReady(),
      widget: null,
    };

    if (!this.state.ready) {
      readyCheck = setInterval(this._updateReadyState.bind(this), 1000);
    }
  }

  componentDidMount() {
    if (this.state.ready) {
      this._renderGrecaptcha();
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { render, onloadCallback } = this.props;

    if (render === 'explicit' && onloadCallback && this.state.ready && !prevState.ready) {
      this._renderGrecaptcha();
    }
  }

  componentWillUnmount() {
    clearInterval(readyCheck);
  }

  reset() {
    const { ready, widget } = this.state;
    if (ready && widget !== null) {
      grecaptcha.reset(widget);
    }
  }

  execute() {
    const { ready, widget } = this.state;
    if (ready && widget !== null) {
      grecaptcha.execute(widget);
    }
  }

  _updateReadyState() {
    if (isReady()) {
      this.setState({
        ready: true,
      });

      clearInterval(readyCheck);
    }
  }

  _renderGrecaptcha() {
    this.state.widget = grecaptcha.render(this.props.elementID, {
      sitekey: this.props.sitekey,
      callback: (this.props.verifyCallback) ? this.props.verifyCallback : undefined,
      theme: this.props.theme,
      type: this.props.type,
      size: this.props.size,
      tabindex: this.props.tabindex,
      hl: this.props.hl,
      badge: this.props.badge,
      'expired-callback': (this.props.expiredCallback) ? this.props.expiredCallback : undefined,
    });

    if (this.props.onloadCallback) {
      this.props.onloadCallback();
    }
  }

  render() {
    if (this.props.render === 'explicit' && this.props.onloadCallback) {
      return (

      );
    }

    return (

    );
  }
}

Recaptcha.propTypes = propTypes;
Recaptcha.defaultProps = defaultProps;
<commit_msg>set prop types for render, theme, size and badge from string to oneOf (#236)<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';

const propTypes = {
  className: PropTypes.string,
  onloadCallbackName: PropTypes.string,
  elementID: PropTypes.string,
  onloadCallback: PropTypes.func,
  verifyCallback: PropTypes.func,
  expiredCallback: PropTypes.func,
  render: PropTypes.oneOf(['onload', 'explicit']),
  sitekey: PropTypes.string,
  theme: PropTypes.oneOf(['light', 'dark']),
  type: PropTypes.string,
  verifyCallbackName: PropTypes.string,
  expiredCallbackName: PropTypes.string,
  size: PropTypes.oneOf(['invisible', 'compact', 'normal']),
  tabindex: PropTypes.string,
  hl: PropTypes.string,
  badge: PropTypes.oneOf(['bottomright', 'bottomleft', 'inline']),
};

const defaultProps = {
  elementID: 'g-recaptcha',
  onloadCallback: undefined,
  onloadCallbackName: 'onloadCallback',
  verifyCallback: undefined,
  verifyCallbackName: 'verifyCallback',
  expiredCallback: undefined,
  expiredCallbackName: 'expiredCallback',
  render: 'onload',
  theme: 'light',
  type: 'image',
  size: 'normal',
  tabindex: '0',
  hl: 'en',
  badge: 'bottomright',
};

const isReady = () => typeof window !== 'undefined'
  && typeof window.grecaptcha !== 'undefined'
  && typeof window.grecaptcha.render === 'function';

let readyCheck;

export default class Recaptcha extends Component {

  constructor(props) {
    super(props);
    this._renderGrecaptcha = this._renderGrecaptcha.bind(this);
    this.reset = this.reset.bind(this);
    this.state = {
      ready: isReady(),
      widget: null,
    };

    if (!this.state.ready) {
      readyCheck = setInterval(this._updateReadyState.bind(this), 1000);
    }
  }

  componentDidMount() {
    if (this.state.ready) {
      this._renderGrecaptcha();
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { render, onloadCallback } = this.props;

    if (render === 'explicit' && onloadCallback && this.state.ready && !prevState.ready) {
      this._renderGrecaptcha();
    }
  }

  componentWillUnmount() {
    clearInterval(readyCheck);
  }

  reset() {
    const { ready, widget } = this.state;
    if (ready && widget !== null) {
      grecaptcha.reset(widget);
    }
  }

  execute() {
    const { ready, widget } = this.state;
    if (ready && widget !== null) {
      grecaptcha.execute(widget);
    }
  }

  _updateReadyState() {
    if (isReady()) {
      this.setState({
        ready: true,
      });

      clearInterval(readyCheck);
    }
  }

  _renderGrecaptcha() {
    this.state.widget = grecaptcha.render(this.props.elementID, {
      sitekey: this.props.sitekey,
      callback: (this.props.verifyCallback) ? this.props.verifyCallback : undefined,
      theme: this.props.theme,
      type: this.props.type,
      size: this.props.size,
      tabindex: this.props.tabindex,
      hl: this.props.hl,
      badge: this.props.badge,
      'expired-callback': (this.props.expiredCallback) ? this.props.expiredCallback : undefined,
    });

    if (this.props.onloadCallback) {
      this.props.onloadCallback();
    }
  }

  render() {
    if (this.props.render === 'explicit' && this.props.onloadCallback) {
      return (

      );
    }

    return (

    );
  }
}

Recaptcha.propTypes = propTypes;
Recaptcha.defaultProps = defaultProps;
<|endoftext|>


<commit_before>"use strict";

const express = require('express');
const bodyParser = require('body-parser');
const {buildSchema} = require('graphql');
const httpError = require('http-errors');
const neo = require('./neo4j').graphql(process.env.GRAPHENEDB_URL);
const schema = require('./schema');

/**
 * Is the application in development?
 *
 * @return {boolean}
 */
function inDev(app) {
  return app.get('env') === 'development';
}

/**
 * Does this request prefer HTML over JSON?
 *
 * @return {boolean}
 */
function isHtmlPreferred(request) {
  return require('accepts')(request).types(['json', 'html']) === 'html';
}

neo.on('schema:uploaded', () => console.log('Schema has been uploaded!'));
neo.schema = schema;

const app = express();
app.use(bodyParser.json());

// GraphQL HTTP only supports GET and POST methods.
app.use((request, response, next) => {
  let error;

  if (!['GET', 'POST'].includes(request.method)) {
    response.setHeader('Allow', 'GET, POST');
    error = httpError(405, 'GraphQL only supports GET and POST requests.');
  }

  next(error);
});

if (inDev(app)) {
  // Show GraphiQL if this request prefers HTML over JSON.
  app.use((request, response, next) => {
    if (isHtmlPreferred(request)) {
      response.sendFile(require('path').join(`${__dirname}/graphiql.html`));
    } else {
      next();
    }
  });
}

// Make JSON GraphQL queries.
app.use((request, response, next) => {
  const query = request.body && request.body.query ? request.body.query : null;

  neo.query(query)
    .then(json => {
      response.json(json);
      next();
    })
    .catch(error => next(httpError(error)));
});

// Handle errors.
app.use((error, request, response, next) => {
  if (response.headersSent) {
    return next(err);
  }

  let data = {
    message: error.message
  };

  if (inDev(app)) {
    data.error = error;
  }

  response.status(error.status || 500);
  response.json(data);
});

// Start the server.
const server = app.listen(80, () => {
  const port = server.address().port;
  require('dns').lookup(require('os').hostname(), (err, address, fam) => {
    console.log(
      'Running a GraphQL API server in %s at %s:%s',
      app.get('env'),
      address,
      port
    );
  });
});
<commit_msg>Let the user know that the API isn't ready yet<commit_after>"use strict";

const express = require('express');
const bodyParser = require('body-parser');
const {buildSchema} = require('graphql');
const httpError = require('http-errors');
const neo = require('./neo4j').graphql(process.env.GRAPHENEDB_URL);
const schema = require('./schema');

/**
 * Is the application in development?
 *
 * @return {boolean}
 */
function inDev(app) {
  return app.get('env') === 'development';
}

/**
 * Does this request prefer HTML over JSON?
 *
 * @return {boolean}
 */
function isHtmlPreferred(request) {
  return require('accepts')(request).types(['json', 'html']) === 'html';
}

let uploadingSchema = true;
neo.on('schema:uploaded', () => {
  uploadingSchema = false;
  console.log('Schema has been uploaded!');
});
neo.schema = schema;

const app = express();
app.use(bodyParser.json());

// GraphQL HTTP only supports GET and POST methods.
app.use((request, response, next) => {
  let error;

  if (!['GET', 'POST'].includes(request.method)) {
    response.setHeader('Allow', 'GET, POST');
    error = httpError(405, 'GraphQL only supports GET and POST requests.');
  }

  next(error);
});

// Let the user know that the API isn't ready yet.
app.use((request, response, next) => {
  let error;

  if (uploadingSchema) {
    error = httpError(503, 'Initializing GraphQL API.');
  }

  next(error);
});

if (inDev(app)) {
  // Show GraphiQL if this request prefers HTML over JSON.
  app.use((request, response, next) => {
    if (isHtmlPreferred(request)) {
      response.sendFile(require('path').join(`${__dirname}/graphiql.html`));
    } else {
      next();
    }
  });
}

// Make JSON GraphQL queries.
app.use((request, response, next) => {
  const query = request.body && request.body.query ? request.body.query : null;

  neo.query(query)
    .then(json => {
      response.json(json);
      next();
    })
    .catch(error => next(httpError(error)));
});

// Handle errors.
app.use((error, request, response, next) => {
  if (response.headersSent) {
    return next(err);
  }

  let data = {
    message: error.message
  };

  if (inDev(app)) {
    data.error = error;
  }

  response.status(error.status || 500);
  response.json(data);
});

// Start the server.
const server = app.listen(80, () => {
  const port = server.address().port;
  require('dns').lookup(require('os').hostname(), (err, address, fam) => {
    console.log(
      'Running a GraphQL API server in %s at %s:%s',
      app.get('env'),
      address,
      port
    );
  });
});
<|endoftext|>


<commit_before>'use strict';

// NodeJS library
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var util = require('util');
var svgo = require('svgo');
var Stream = require('stream').Stream;

// NPM library
var gutil = require('gulp-util');
var through = require('through2');
var request = require('request');
var buffers = require('buffers');
var async = require('async');
var chalk = require('chalk');

var rImages = /url(?:\(['|"]?)(.*?.svg)(?:['|"]?\))(?!.*\/\*svg:skip\*\/)/ig;

function gulpCssSvg(opts) {
  opts = JSON.parse(JSON.stringify(opts || {}));
  opts.maxWeightResource = opts.maxWeightResource || 32768;
  if (util.isArray(opts.extensionsAllowed)) {
    opts.extensionsAllowed = opts.extensionsAllowed;
  } else {
    opts.extensionsAllowed = [];
  }
  opts.extensionsAllowed = opts.extensionsAllowed || [];
  opts.baseDir = opts.baseDir || '';
  opts.verbose = process.argv.indexOf('--verbose') !== -1;

    // Creating a stream through which each file will pass
  var stream = through.obj(function (file, enc, callbackStream) {
    var currentStream = this;
    var cache = [];

    if (file.isNull()) {
            // Do nothing if no contents
      currentStream.push(file);

      return callbackStream();
    }

    if (file.isBuffer()) {
      var src = file.contents.toString();
      var result = [];

      async.whilst(
                function () {
                  result = rImages.exec(src);

                  return result !== null;
                },
                function (callback) {
                  if (cache[result[1]]) {
                    src = src.replace(result[1], cache[result[1]]);
                    callback();
                    return;
                  }

                  var pureUrl = result[1].split('?')[0].split('#')[0];
                  if (opts.extensionsAllowed.length !== 0 && opts.extensionsAllowed.indexOf(path.extname(pureUrl)) === -1) {
                    log('Ignores ' + chalk.yellow(result[1]) + ', extension not allowed ' + chalk.yellow(path.extname(result[1])), opts.verbose);
                    callback();
                    return;
                  }

                  encodeResource(result[1], file, opts, function (fileRes) {
                    if (undefined !== fileRes) {
                      if (fileRes.contents.length > opts.maxWeightResource) {
                        log('Ignores ' + chalk.yellow(result[1]) + ', file is too big ' + chalk.yellow(fileRes.contents.length + ' bytes'), opts.verbose);
                        callback();
                        return;
                      }

                      var strRes = 'data:' + mime.lookup(fileRes.path) + ';utf8,';
										 new svgo().optimize(fileRes.contents.toString('utf8'), function(result) { strRes += result.data; });//.replace("'",'"').replace(/<!-- .* -->/,'').replace(/<\?;
                      src = src.replace(result[1], strRes);

                            // Store in cache
                      cache[result[1]] = strRes;
                    }
                    callback();
                  });
                },
                function () {
                  file.contents = new Buffer(src);
                  currentStream.push(file);

                  return callbackStream();
                }
            );
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-css-svg', 'Stream not supported!'));
    }
  });

    // returning the file stream
  return stream;
}

function encodeResource(img, file, opts, doneCallback) {
  var fileRes = new gutil.File();

  if (/^data:/.test(img)) {
    log('Ignores ' + chalk.yellow(img.substring(0, 30) + '...') + ', already encoded', opts.verbose);
    doneCallback();
    return;
  }

  if (img[0] === '#') {
    log('Ignores ' + chalk.yellow(img.substring(0, 30) + '...') + ', SVG mask', opts.verbose);
    doneCallback();
    return;
  }

  if (/^(http|https|\/\/)/.test(img)) {
    log('Fetch ' + chalk.yellow(img), opts.verbose);
        // different case for uri start '//'
    if (img[0] + img[1] === '//') {
      img = 'http:' + img;
    }

    fetchRemoteRessource(img, function (resultBuffer) {
      if (resultBuffer === null) {
        log('Error: ' + chalk.red(img) + ', unable to fetch', opts.verbose);
        doneCallback();
        return;
      }
      fileRes.path = img;
      fileRes.contents = resultBuffer;
      doneCallback(fileRes);
      return;
    });
  } else {
    var location = '';
    var binRes = '';

    location = img.charAt(0) === '/' ? (opts.baseDir || '') + img : path.join(path.dirname(file.path), (opts.baseDir || '') + '/' + img);
    location = location.replace(/([?#].*)$/, '');

    if (!fs.existsSync(location)) {
      log('Error: ' + chalk.red(location) + ', file not found', opts.verbose);
      doneCallback();
      return;
    }

    binRes = fs.readFileSync(location);

    fileRes.path = location;
    fileRes.contents = binRes;

    doneCallback(fileRes);
    return;
  }
}

function fetchRemoteRessource(url, callback) {
  var resultBuffer;
  var buffList = buffers();
  var imageStream = new Stream();

  imageStream.writable = true;
  imageStream.write = function (data) {
    buffList.push(new Buffer(data));
  };
  imageStream.end = function () {
    resultBuffer = buffList.toBuffer();
  };

  request(url, function (error, response) {
    if (error) {
      callback(null);
      return;
    }

        // Bail if we get anything other than 200
    if (response.statusCode !== 200) {
      callback(null);
      return;
    }

    callback(resultBuffer);
  }).pipe(imageStream);
}

function log(message, isVerbose) {
  if (isVerbose === true) {
    gutil.log(message);
  }
}

// Exporting the plugin main function
module.exports = gulpCssSvg;
<commit_msg>Remove incorrect ;utf8 and url encode propertly for IE.<commit_after>'use strict';

// NodeJS library
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var util = require('util');
var svgo = require('svgo');
var Stream = require('stream').Stream;

// NPM library
var gutil = require('gulp-util');
var through = require('through2');
var request = require('request');
var buffers = require('buffers');
var async = require('async');
var chalk = require('chalk');

var rImages = /url(?:\(['|"]?)(.*?.svg)(?:['|"]?\))(?!.*\/\*svg:skip\*\/)/ig;

function gulpCssSvg(opts) {
  opts = JSON.parse(JSON.stringify(opts || {}));
  opts.maxWeightResource = opts.maxWeightResource || 32768;
  if (util.isArray(opts.extensionsAllowed)) {
    opts.extensionsAllowed = opts.extensionsAllowed;
  } else {
    opts.extensionsAllowed = [];
  }
  opts.extensionsAllowed = opts.extensionsAllowed || [];
  opts.baseDir = opts.baseDir || '';
  opts.verbose = process.argv.indexOf('--verbose') !== -1;

    // Creating a stream through which each file will pass
  var stream = through.obj(function (file, enc, callbackStream) {
    var currentStream = this;
    var cache = [];

    if (file.isNull()) {
            // Do nothing if no contents
      currentStream.push(file);

      return callbackStream();
    }

    if (file.isBuffer()) {
      var src = file.contents.toString();
      var result = [];

      async.whilst(
                function () {
                  result = rImages.exec(src);

                  return result !== null;
                },
                function (callback) {
                  if (cache[result[1]]) {
                    src = src.replace(result[1], cache[result[1]]);
                    callback();
                    return;
                  }

                  var pureUrl = result[1].split('?')[0].split('#')[0];
                  if (opts.extensionsAllowed.length !== 0 && opts.extensionsAllowed.indexOf(path.extname(pureUrl)) === -1) {
                    log('Ignores ' + chalk.yellow(result[1]) + ', extension not allowed ' + chalk.yellow(path.extname(result[1])), opts.verbose);
                    callback();
                    return;
                  }

                  encodeResource(result[1], file, opts, function (fileRes) {
                    if (undefined !== fileRes) {
                      if (fileRes.contents.length > opts.maxWeightResource) {
                        log('Ignores ' + chalk.yellow(result[1]) + ', file is too big ' + chalk.yellow(fileRes.contents.length + ' bytes'), opts.verbose);
                        callback();
                        return;
                      }

                      var strRes = 'data:' + mime.lookup(fileRes.path) + ';';
										 new svgo().optimize(fileRes.contents.toString('utf8'), function(result) { strRes += result.data.replace(/"/g,"'").replace(/</g,'%3C').replace(/>/g,'%3E'); });//.replace("'",'"').replace(/<!-- .* -->/,'').replace(/<\?;
                      src = src.replace(result[1], '"' + strRes + '"');

                            // Store in cache
                      cache[result[1]] = strRes;
                    }
                    callback();
                  });
                },
                function () {
                  file.contents = new Buffer(src);
                  currentStream.push(file);

                  return callbackStream();
                }
            );
    }

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-css-svg', 'Stream not supported!'));
    }
  });

    // returning the file stream
  return stream;
}

function encodeResource(img, file, opts, doneCallback) {
  var fileRes = new gutil.File();

  if (/^data:/.test(img)) {
    log('Ignores ' + chalk.yellow(img.substring(0, 30) + '...') + ', already encoded', opts.verbose);
    doneCallback();
    return;
  }

  if (img[0] === '#') {
    log('Ignores ' + chalk.yellow(img.substring(0, 30) + '...') + ', SVG mask', opts.verbose);
    doneCallback();
    return;
  }

  if (/^(http|https|\/\/)/.test(img)) {
    log('Fetch ' + chalk.yellow(img), opts.verbose);
        // different case for uri start '//'
    if (img[0] + img[1] === '//') {
      img = 'http:' + img;
    }

    fetchRemoteRessource(img, function (resultBuffer) {
      if (resultBuffer === null) {
        log('Error: ' + chalk.red(img) + ', unable to fetch', opts.verbose);
        doneCallback();
        return;
      }
      fileRes.path = img;
      fileRes.contents = resultBuffer;
      doneCallback(fileRes);
      return;
    });
  } else {
    var location = '';
    var binRes = '';

    location = img.charAt(0) === '/' ? (opts.baseDir || '') + img : path.join(path.dirname(file.path), (opts.baseDir || '') + '/' + img);
    location = location.replace(/([?#].*)$/, '');

    if (!fs.existsSync(location)) {
      log('Error: ' + chalk.red(location) + ', file not found', opts.verbose);
      doneCallback();
      return;
    }

    binRes = fs.readFileSync(location);

    fileRes.path = location;
    fileRes.contents = binRes;

    doneCallback(fileRes);
    return;
  }
}

function fetchRemoteRessource(url, callback) {
  var resultBuffer;
  var buffList = buffers();
  var imageStream = new Stream();

  imageStream.writable = true;
  imageStream.write = function (data) {
    buffList.push(new Buffer(data));
  };
  imageStream.end = function () {
    resultBuffer = buffList.toBuffer();
  };

  request(url, function (error, response) {
    if (error) {
      callback(null);
      return;
    }

        // Bail if we get anything other than 200
    if (response.statusCode !== 200) {
      callback(null);
      return;
    }

    callback(resultBuffer);
  }).pipe(imageStream);
}

function log(message, isVerbose) {
  if (isVerbose === true) {
    gutil.log(message);
  }
}

// Exporting the plugin main function
module.exports = gulpCssSvg;
<|endoftext|>


<commit_before>const mysql = require('mysql2');

const config = JSON.parse(global.LoadResourceFile('ghmattimysql', 'config.json'));
const configString = global.GetConvar('mysql_connection_string', 'mysql://localhost/fivem');
const useBoolean = global.GetConvarInt('mysql_use_boolean', 0);
const showDebug = global.GetConvarInt('mysql_debug', 0);
const pool = mysql.createPool(config || configString);

function prepareLegacyQuery(query, parameters) {
  let sql = query;
  let params = parameters;
  if (parameters !== null && typeof params === 'object' && !Array.isArray(params)) {
    params = [];
    sql = query.replace(/@(\w+)/g, (txt, key) => {
      if (Object.prototype.hasOwnProperty.call(parameters, key)) {
        params.push(parameters[key]);
        return '?';
      }
      return txt;
    });
  }
  return [sql, params];
}

function transformToBoolean(fields, result) {
  const res = result;
  if (fields) {
    fields.forEach((field) => {
      if (field.columnType === 1 && field.columnLength === 1) {
        result.forEach((_, index) => {
          res[index][field.name] = (result[index][field.name] !== 0);
        });
      }
    });
  }
  return res;
}

function sanitizeInput(query, parameters, callback) {
  let sql = query;
  let params = parameters;
  let cb = callback;

  if (typeof parameters === 'function') {
    cb = parameters;
  }
  [sql, params] = prepareLegacyQuery(query, params);
  if (!Array.isArray(params)) {
    params = [];
  }
  return [sql, params, cb];
}

async function safeInvoke(callback, args) {
  if (typeof callback === 'function') {
    setImmediate(() => {
      callback(args);
    });
  }
}

function execute(sql, params, connection) {
  const orm = connection || pool;
  return new Promise((resolve, reject) => {
    orm[(params.length) ? 'execute' : 'query'](sql, params, (error, result, fields) => {
      if (showDebug) console.log(`[MySQL] ${sql} : ${JSON.stringify(params)}`);
      if (error) reject(error);
      resolve((useBoolean) ? transformToBoolean(fields, result) : result);
    });
  });
}

global.exports('scalar', (query, parameters, callback) => {
  let sql = query;
  let params = parameters;
  let cb = callback;
  [sql, params, cb] = sanitizeInput(sql, params, cb);

  execute(sql, params).then((result) => {
    safeInvoke(cb, Object.values(result[0] || {})[0]);
  });
});

global.exports('execute', (query, parameters, callback) => {
  let sql = query;
  let params = parameters;
  let cb = callback;
  [sql, params, cb] = sanitizeInput(sql, params, cb);

  execute(sql, params).then((result) => {
    safeInvoke(cb, result);
  });
});

function onTransactionError(error, connection, callback) {
  connection.rollback(() => {
    console.error(error);
    safeInvoke(callback, false);
  });
}

global.exports('transaction', (querys, parameters, callback) => {
  let sqls = [];
  let params = parameters;
  let cb = callback;
  // start by type-checking and sorting the data
  if (!querys.every(element => typeof element === 'string')) {
    sqls = querys;
    if (typeof parameters === 'function') cb = parameters;
  } else {
    if (typeof parameters === 'function') {
      cb = parameters;
      params = [];
    }
    querys.forEach((element) => {
      sqls.push({ query: element, parameters: params });
    });
  }
  // build the actual queries
  sqls.forEach((element, index) => {
    const [stmt, stmtParams] = prepareLegacyQuery(element.query, element.parameters);
    sqls[index] = {
      query: stmt,
      parameters: (Array.isArray(stmtParams)) ? stmtParams : [],
    };
  });
  // the real transaction can begin
  pool.getConnection((connectionError, connection) => {
    if (connectionError) {
      console.error(connectionError);
      safeInvoke(cb, false);
      return;
    }
    connection.beginTransaction((transactionError) => {
      if (transactionError) {
        onTransactionError(transactionError, connection, callback);
        return;
      }
      const promises = [];
      // execute each query on the connection
      sqls.forEach((element) => {
        promises.push(execute(element.query, element.parameters, connection));
      });
      // If all have resolved, then commit
      Promise.all(promises).then(() => {
        connection.commit((commitError) => {
          if (commitError) {
            onTransactionError(commitError, connection, callback);
          } else safeInvoke(cb, true);
        });
        // Otherwise catch the error from the execution
      }).catch((executeError) => {
        onTransactionError(executeError, connection, callback);
      });
    });
  });
});
<commit_msg>Unified some variables<commit_after>const mysql = require('mysql2');

const config = JSON.parse(global.LoadResourceFile('ghmattimysql', 'config.json'));
const configString = global.GetConvar('mysql_connection_string', 'mysql://localhost/fivem');
const useBoolean = global.GetConvarInt('mysql_use_boolean', 0);
const showDebug = global.GetConvarInt('mysql_debug', 0);
const pool = mysql.createPool(config || configString);

function prepareLegacyQuery(query, parameters) {
  let sql = query;
  let params = parameters;
  if (params !== null && typeof params === 'object' && !Array.isArray(params)) {
    params = [];
    sql = sql.replace(/@(\w+)/g, (txt, key) => {
      if (Object.prototype.hasOwnProperty.call(parameters, key)) {
        params.push(parameters[key]);
        return '?';
      }
      return txt;
    });
  }
  return [sql, params];
}

function transformToBoolean(fields, result) {
  const res = result;
  if (fields) {
    fields.forEach((field) => {
      if (field.columnType === 1 && field.columnLength === 1) {
        result.forEach((_, index) => {
          res[index][field.name] = (result[index][field.name] !== 0);
        });
      }
    });
  }
  return res;
}

function sanitizeInput(query, parameters, callback) {
  let sql = query;
  let params = parameters;
  let cb = callback;

  if (typeof parameters === 'function') {
    cb = parameters;
  }
  [sql, params] = prepareLegacyQuery(query, params);
  if (!Array.isArray(params)) {
    params = [];
  }
  return [sql, params, cb];
}

async function safeInvoke(callback, args) {
  if (typeof callback === 'function') {
    setImmediate(() => {
      callback(args);
    });
  }
}

function execute(sql, params, connection) {
  const orm = connection || pool;
  return new Promise((resolve, reject) => {
    orm[(params.length) ? 'execute' : 'query'](sql, params, (error, result, fields) => {
      if (showDebug) console.log(`[MySQL] ${sql} : ${JSON.stringify(params)}`);
      if (error) reject(error);
      resolve((useBoolean) ? transformToBoolean(fields, result) : result);
    });
  });
}

global.exports('scalar', (query, parameters, callback) => {
  let sql = query;
  let params = parameters;
  let cb = callback;
  [sql, params, cb] = sanitizeInput(sql, params, cb);

  execute(sql, params).then((result) => {
    safeInvoke(cb, Object.values(result[0] || {})[0]);
  });
});

global.exports('execute', (query, parameters, callback) => {
  let sql = query;
  let params = parameters;
  let cb = callback;
  [sql, params, cb] = sanitizeInput(sql, params, cb);

  execute(sql, params).then((result) => {
    safeInvoke(cb, result);
  });
});

function onTransactionError(error, connection, callback) {
  connection.rollback(() => {
    console.error(error);
    safeInvoke(callback, false);
  });
}

global.exports('transaction', (querys, parameters, callback) => {
  let sqls = [];
  let params = parameters;
  let cb = callback;
  // start by type-checking and sorting the data
  if (!querys.every(element => typeof element === 'string')) {
    sqls = querys;
    if (typeof parameters === 'function') cb = parameters;
  } else {
    if (typeof parameters === 'function') {
      cb = parameters;
      params = [];
    }
    querys.forEach((element) => {
      sqls.push({ query: element, parameters: params });
    });
  }
  // build the actual queries
  sqls.forEach((element, index) => {
    const [stmt, stmtParams] = prepareLegacyQuery(element.query, element.parameters);
    sqls[index] = {
      query: stmt,
      parameters: (Array.isArray(stmtParams)) ? stmtParams : [],
    };
  });
  // the real transaction can begin
  pool.getConnection((connectionError, connection) => {
    if (connectionError) {
      console.error(connectionError);
      safeInvoke(cb, false);
      return;
    }
    connection.beginTransaction((transactionError) => {
      if (transactionError) {
        onTransactionError(transactionError, connection, callback);
        return;
      }
      const promises = [];
      // execute each query on the connection
      sqls.forEach((element) => {
        promises.push(execute(element.query, element.parameters, connection));
      });
      // If all have resolved, then commit
      Promise.all(promises).then(() => {
        connection.commit((commitError) => {
          if (commitError) {
            onTransactionError(commitError, connection, callback);
          } else safeInvoke(cb, true);
        });
        // Otherwise catch the error from the execution
      }).catch((executeError) => {
        onTransactionError(executeError, connection, callback);
      });
    });
  });
});
<|endoftext|>


<commit_before>import pify from 'pify'
import resolve from 'resolve';
import nodeSass from 'node-sass';
import { dirname } from 'path';
import { writeFileSync } from 'fs';
import { isString, isFunction } from 'util';
import { createFilter } from 'rollup-pluginutils';
import { insertStyle } from './style.js';
import { ensureFileSync } from 'fs-extra';

const MATCH_SASS_FILENAME_RE = /\.sass$/;
const MATCH_NODE_MODULE_RE = /^~([a-z0-9]|@).+/i;

export default function plugin(options = {}) {
  const filter = createFilter(options.include || [ '**/*.sass', '**/*.scss' ], options.exclude || 'node_modules/**');
  const insertFnName = '___$insertStyle';
  const styles = [];
  const styleMaps = {};

  options.output = options.output || false;
  options.insert = options.insert || false;

  const sassRuntime = options.runtime || nodeSass;

  return {
    name: 'sass',

    intro() {
      if (options.insert) {
        return insertStyle.toString().replace(/insertStyle/, insertFnName);
      }
    },

    async transform(code, id) {
      if (!filter(id)) {
        return;
      }

      try {
        const paths = [dirname(id), process.cwd()];
        const customizedSassOptions = options.options || {};
        const res = await pify(sassRuntime.render.bind(sassRuntime))(Object.assign({}, customizedSassOptions, {
          file: id,
          data: customizedSassOptions.data && `${customizedSassOptions.data}${code}`,
          indentedSyntax: MATCH_SASS_FILENAME_RE.test(id),
          includePaths: customizedSassOptions.includePaths
            ? customizedSassOptions.includePaths.concat(paths)
            : paths,
          importer: [
            (url, importer, done) => {
              if (!MATCH_NODE_MODULE_RE.test(url)) {
                return done({ file: url });
              }

              const moduleUrl = url.slice(1);
              const resolveOptions = {
                basedir: dirname(importer),
                extensions: ['.scss', '.sass'],
              };

              try {
                done({
                  file: resolve.sync(moduleUrl, resolveOptions),
                });
              } catch (err) {
                done({
                  file: url,
                });
              }
            },
          ].concat(customizedSassOptions.importer || []),
        }));
        let css = res.css.toString().trim();
        let defaultExport = '';
        let restExports;

        if (css) {
          if (isFunction(options.processor)) {
            const processResult = await options.processor(css, id);

            if (typeof processResult === 'object') {
              if (typeof processResult.css !== 'string') {
                throw new Error('You need to return the styles using the `css` property. See https://github.com/differui/rollup-plugin-sass#processor');
              }
              css = processResult.css;
              delete processResult.css;
              restExports = Object.keys(processResult).map(name => `export const ${name} = ${JSON.stringify(processResult[name])};`);
            } else if (typeof processResult === 'string') {
              css = processResult;
            }
          }
          if (styleMaps[id]) {
            styleMaps[id].content = css;
          } else {
            styles.push(styleMaps[id] = {
              id: id,
              content: css,
            });
          }
          if (options.insert === true) {
            defaultExport = `${insertFnName}(${JSON.stringify(css)});`;
          } else if (options.output === false) {
            defaultExport = JSON.stringify(css);
          } else {
            defaultExport = `"";`;
          }
        }
        return {
          code: [
            `export default ${defaultExport};`,
            ...(restExports || []),
          ].join('\n'),
          map: {
            mappings: res.map
              ? res.map.toString()
              : '',
          },
        };
      } catch (error) {
        throw error;
      }
    },

    async ongenerate(generateOptions) {
      if (!options.insert && (!styles.length || options.output === false)) {
        return;
      }

      const css = styles.map(style => style.content).join('');

      if (isString(options.output)) {
        ensureFileSync(options.output, (err) => {
          if (err) {
            throw err;
          }
        });
        return writeFileSync(options.output, css);
      } else if (isFunction(options.output)) {
        return options.output(css, styles);
      } else if (!options.insert && generateOptions.file) {
        let dest = generateOptions.file;

        if (dest.endsWith('.js') || dest.endsWith('.ts')) {
          dest = dest.slice(0, -3);
        }
        dest = `${dest}.css`;
        ensureFileSync(dest, (err) => {
          if (err) {
            throw err;
          }
        });
        return writeFileSync(dest, css);
      }
    },
  };
}
<commit_msg>Switch to sass from node-sass<commit_after>import pify from 'pify'
import resolve from 'resolve';
import sass from 'sass';
import { dirname } from 'path';
import { writeFileSync } from 'fs';
import { isString, isFunction } from 'util';
import { createFilter } from 'rollup-pluginutils';
import { insertStyle } from './style.js';
import { ensureFileSync } from 'fs-extra';

const MATCH_SASS_FILENAME_RE = /\.sass$/;
const MATCH_NODE_MODULE_RE = /^~([a-z0-9]|@).+/i;

export default function plugin(options = {}) {
  const filter = createFilter(options.include || [ '**/*.sass', '**/*.scss' ], options.exclude || 'node_modules/**');
  const insertFnName = '___$insertStyle';
  const styles = [];
  const styleMaps = {};

  options.output = options.output || false;
  options.insert = options.insert || false;

  const sassRuntime = options.runtime || sass;

  return {
    name: 'sass',

    intro() {
      if (options.insert) {
        return insertStyle.toString().replace(/insertStyle/, insertFnName);
      }
    },

    async transform(code, id) {
      if (!filter(id)) {
        return;
      }

      try {
        const paths = [dirname(id), process.cwd()];
        const customizedSassOptions = options.options || {};
        const res = await pify(sassRuntime.render.bind(sassRuntime))(Object.assign({}, customizedSassOptions, {
          file: id,
          data: customizedSassOptions.data && `${customizedSassOptions.data}${code}`,
          indentedSyntax: MATCH_SASS_FILENAME_RE.test(id),
          includePaths: customizedSassOptions.includePaths
            ? customizedSassOptions.includePaths.concat(paths)
            : paths,
          importer: [
            (url, importer, done) => {
              if (!MATCH_NODE_MODULE_RE.test(url)) {
                return done({ file: url });
              }

              const moduleUrl = url.slice(1);
              const resolveOptions = {
                basedir: dirname(importer),
                extensions: ['.scss', '.sass'],
              };

              try {
                done({
                  file: resolve.sync(moduleUrl, resolveOptions),
                });
              } catch (err) {
                done({
                  file: url,
                });
              }
            },
          ].concat(customizedSassOptions.importer || []),
        }));
        let css = res.css.toString().trim();
        let defaultExport = '';
        let restExports;

        if (css) {
          if (isFunction(options.processor)) {
            const processResult = await options.processor(css, id);

            if (typeof processResult === 'object') {
              if (typeof processResult.css !== 'string') {
                throw new Error('You need to return the styles using the `css` property. See https://github.com/differui/rollup-plugin-sass#processor');
              }
              css = processResult.css;
              delete processResult.css;
              restExports = Object.keys(processResult).map(name => `export const ${name} = ${JSON.stringify(processResult[name])};`);
            } else if (typeof processResult === 'string') {
              css = processResult;
            }
          }
          if (styleMaps[id]) {
            styleMaps[id].content = css;
          } else {
            styles.push(styleMaps[id] = {
              id: id,
              content: css,
            });
          }
          if (options.insert === true) {
            defaultExport = `${insertFnName}(${JSON.stringify(css)});`;
          } else if (options.output === false) {
            defaultExport = JSON.stringify(css);
          } else {
            defaultExport = `"";`;
          }
        }
        return {
          code: [
            `export default ${defaultExport};`,
            ...(restExports || []),
          ].join('\n'),
          map: {
            mappings: res.map
              ? res.map.toString()
              : '',
          },
        };
      } catch (error) {
        throw error;
      }
    },

    async ongenerate(generateOptions) {
      if (!options.insert && (!styles.length || options.output === false)) {
        return;
      }

      const css = styles.map(style => style.content).join('');

      if (isString(options.output)) {
        ensureFileSync(options.output, (err) => {
          if (err) {
            throw err;
          }
        });
        return writeFileSync(options.output, css);
      } else if (isFunction(options.output)) {
        return options.output(css, styles);
      } else if (!options.insert && generateOptions.file) {
        let dest = generateOptions.file;

        if (dest.endsWith('.js') || dest.endsWith('.ts')) {
          dest = dest.slice(0, -3);
        }
        dest = `${dest}.css`;
        ensureFileSync(dest, (err) => {
          if (err) {
            throw err;
          }
        });
        return writeFileSync(dest, css);
      }
    },
  };
}
<|endoftext|>


<commit_before>import {
  format,
  complementError,
  asyncMap,
  warning,
  deepMerge,
  convertFieldsError,
} from './util';
import validators from './validator/index';
import { messages as defaultMessages, newMessages } from './messages';

/**
 *  Encapsulates a validation schema.
 *
 *  @param descriptor An object declaring validation rules
 *  for this schema.
 */
function Schema(descriptor) {
  this.rules = null;
  this._messages = defaultMessages;
  this.define(descriptor);
}

Schema.prototype = {
  messages(messages) {
    if (messages) {
      this._messages = deepMerge(newMessages(), messages);
    }
    return this._messages;
  },
  define(rules) {
    if (!rules) {
      throw new Error('Cannot configure a schema with no rules');
    }
    if (typeof rules !== 'object' || Array.isArray(rules)) {
      throw new Error('Rules must be an object');
    }
    this.rules = {};
    let z;
    let item;
    for (z in rules) {
      if (rules.hasOwnProperty(z)) {
        item = rules[z];
        this.rules[z] = Array.isArray(item) ? item : [item];
      }
    }
  },
  validate(source_, o = {}, oc = () => {}) {
    let source = source_;
    let options = o;
    let callback = oc;
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
    if (!this.rules || Object.keys(this.rules).length === 0) {
      if (callback) {
        callback();
      }
      return Promise.resolve();
    }

    function complete(results) {
      let i;
      let errors = [];
      let fields = {};

      function add(e) {
        if (Array.isArray(e)) {
          errors = errors.concat(...e);
        } else {
          errors.push(e);
        }
      }

      for (i = 0; i < results.length; i++) {
        add(results[i]);
      }
      if (!errors.length) {
        errors = null;
        fields = null;
      } else {
        fields = convertFieldsError(errors);
      }
      callback(errors, fields);
    }

    if (options.messages) {
      let messages = this.messages();
      if (messages === defaultMessages) {
        messages = newMessages();
      }
      deepMerge(messages, options.messages);
      options.messages = messages;
    } else {
      options.messages = this.messages();
    }
    let arr;
    let value;
    const series = {};
    const keys = options.keys || Object.keys(this.rules);
    keys.forEach(z => {
      arr = this.rules[z];
      value = source[z];
      arr.forEach(r => {
        let rule = r;
        if (typeof rule.transform === 'function') {
          if (source === source_) {
            source = { ...source };
          }
          value = source[z] = rule.transform(value);
        }
        if (typeof rule === 'function') {
          rule = {
            validator: rule,
          };
        } else {
          rule = { ...rule };
        }
        rule.validator = this.getValidationMethod(rule);
        rule.field = z;
        rule.fullField = rule.fullField || z;
        rule.type = this.getType(rule);
        if (!rule.validator) {
          return;
        }
        series[z] = series[z] || [];
        series[z].push({
          rule,
          value,
          source,
          field: z,
        });
      });
    });
    const errorFields = {};
    return asyncMap(
      series,
      options,
      (data, doIt) => {
        const rule = data.rule;
        let deep =
          (rule.type === 'object' || rule.type === 'array') &&
          (typeof rule.fields === 'object' ||
            typeof rule.defaultField === 'object');
        deep = deep && (rule.required || (!rule.required && data.value));
        rule.field = data.field;

        function addFullfield(key, schema) {
          return {
            ...schema,
            fullField: `${rule.fullField}.${key}`,
          };
        }

        function cb(e = []) {
          let errors = e;
          if (!Array.isArray(errors)) {
            errors = [errors];
          }
          if (!options.suppressWarning && errors.length) {
            Schema.warning('async-validator:', errors);
          }
          if (errors.length && rule.message) {
            errors = [].concat(rule.message);
          }

          errors = errors.map(complementError(rule));

          if (options.first && errors.length) {
            errorFields[rule.field] = 1;
            return doIt(errors);
          }
          if (!deep) {
            doIt(errors);
          } else {
            // if rule is required but the target object
            // does not exist fail at the rule level and don't
            // go deeper
            if (rule.required && !data.value) {
              if (rule.message) {
                errors = [].concat(rule.message).map(complementError(rule));
              } else if (options.error) {
                errors = [
                  options.error(
                    rule,
                    format(options.messages.required, rule.field),
                  ),
                ];
              } else {
                errors = [];
              }
              return doIt(errors);
            }

            let fieldsSchema = {};
            if (rule.defaultField) {
              for (const k in data.value) {
                if (data.value.hasOwnProperty(k)) {
                  fieldsSchema[k] = rule.defaultField;
                }
              }
            }
            fieldsSchema = {
              ...fieldsSchema,
              ...data.rule.fields,
            };
            for (const f in fieldsSchema) {
              if (fieldsSchema.hasOwnProperty(f)) {
                const fieldSchema = Array.isArray(fieldsSchema[f])
                  ? fieldsSchema[f]
                  : [fieldsSchema[f]];
                fieldsSchema[f] = fieldSchema.map(addFullfield.bind(null, f));
              }
            }
            const schema = new Schema(fieldsSchema);
            schema.messages(options.messages);
            if (data.rule.options) {
              data.rule.options.messages = options.messages;
              data.rule.options.error = options.error;
            }
            schema.validate(data.value, data.rule.options || options, errs => {
              const finalErrors = [];
              if (errors && errors.length) {
                finalErrors.push(...errors);
              }
              if (errs && errs.length) {
                finalErrors.push(...errs);
              }
              doIt(finalErrors.length ? finalErrors : null);
            });
          }
        }

        let res;
        if (rule.asyncValidator) {
          res = rule.asyncValidator(rule, data.value, cb, data.source, options);
        } else if (rule.validator) {
          res = rule.validator(rule, data.value, cb, data.source, options);
          if (res === true) {
            cb();
          } else if (res === false) {
            cb(rule.message || `${rule.field} fails`);
          } else if (res instanceof Array) {
            cb(res);
          } else if (res instanceof Error) {
            cb(res.message);
          }
        }
        if (res && res.then) {
          res.then(() => cb(), e => cb(e));
        }
      },
      results => {
        complete(results);
      },
    );
  },
  getType(rule) {
    if (rule.type === undefined && rule.pattern instanceof RegExp) {
      rule.type = 'pattern';
    }
    if (
      typeof rule.validator !== 'function' &&
      (rule.type && !validators.hasOwnProperty(rule.type))
    ) {
      throw new Error(format('Unknown rule type %s', rule.type));
    }
    return rule.type || 'string';
  },
  getValidationMethod(rule) {
    if (typeof rule.validator === 'function') {
      return rule.validator;
    }
    const keys = Object.keys(rule);
    const messageIndex = keys.indexOf('message');
    if (messageIndex !== -1) {
      keys.splice(messageIndex, 1);
    }
    if (keys.length === 1 && keys[0] === 'required') {
      return validators.required;
    }
    return validators[this.getType(rule)] || false;
  },
};

Schema.register = function register(type, validator) {
  if (typeof validator !== 'function') {
    throw new Error(
      'Cannot register a validator by type, validator is not a function',
    );
  }
  validators[type] = validator;
};

Schema.warning = warning;

Schema.messages = defaultMessages;

export default Schema;
<commit_msg>export validators<commit_after>import {
  format,
  complementError,
  asyncMap,
  warning,
  deepMerge,
  convertFieldsError,
} from './util';
import validators from './validator/index';
import { messages as defaultMessages, newMessages } from './messages';

/**
 *  Encapsulates a validation schema.
 *
 *  @param descriptor An object declaring validation rules
 *  for this schema.
 */
function Schema(descriptor) {
  this.rules = null;
  this._messages = defaultMessages;
  this.define(descriptor);
}

Schema.prototype = {
  messages(messages) {
    if (messages) {
      this._messages = deepMerge(newMessages(), messages);
    }
    return this._messages;
  },
  define(rules) {
    if (!rules) {
      throw new Error('Cannot configure a schema with no rules');
    }
    if (typeof rules !== 'object' || Array.isArray(rules)) {
      throw new Error('Rules must be an object');
    }
    this.rules = {};
    let z;
    let item;
    for (z in rules) {
      if (rules.hasOwnProperty(z)) {
        item = rules[z];
        this.rules[z] = Array.isArray(item) ? item : [item];
      }
    }
  },
  validate(source_, o = {}, oc = () => {}) {
    let source = source_;
    let options = o;
    let callback = oc;
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
    if (!this.rules || Object.keys(this.rules).length === 0) {
      if (callback) {
        callback();
      }
      return Promise.resolve();
    }

    function complete(results) {
      let i;
      let errors = [];
      let fields = {};

      function add(e) {
        if (Array.isArray(e)) {
          errors = errors.concat(...e);
        } else {
          errors.push(e);
        }
      }

      for (i = 0; i < results.length; i++) {
        add(results[i]);
      }
      if (!errors.length) {
        errors = null;
        fields = null;
      } else {
        fields = convertFieldsError(errors);
      }
      callback(errors, fields);
    }

    if (options.messages) {
      let messages = this.messages();
      if (messages === defaultMessages) {
        messages = newMessages();
      }
      deepMerge(messages, options.messages);
      options.messages = messages;
    } else {
      options.messages = this.messages();
    }
    let arr;
    let value;
    const series = {};
    const keys = options.keys || Object.keys(this.rules);
    keys.forEach(z => {
      arr = this.rules[z];
      value = source[z];
      arr.forEach(r => {
        let rule = r;
        if (typeof rule.transform === 'function') {
          if (source === source_) {
            source = { ...source };
          }
          value = source[z] = rule.transform(value);
        }
        if (typeof rule === 'function') {
          rule = {
            validator: rule,
          };
        } else {
          rule = { ...rule };
        }
        rule.validator = this.getValidationMethod(rule);
        rule.field = z;
        rule.fullField = rule.fullField || z;
        rule.type = this.getType(rule);
        if (!rule.validator) {
          return;
        }
        series[z] = series[z] || [];
        series[z].push({
          rule,
          value,
          source,
          field: z,
        });
      });
    });
    const errorFields = {};
    return asyncMap(
      series,
      options,
      (data, doIt) => {
        const rule = data.rule;
        let deep =
          (rule.type === 'object' || rule.type === 'array') &&
          (typeof rule.fields === 'object' ||
            typeof rule.defaultField === 'object');
        deep = deep && (rule.required || (!rule.required && data.value));
        rule.field = data.field;

        function addFullfield(key, schema) {
          return {
            ...schema,
            fullField: `${rule.fullField}.${key}`,
          };
        }

        function cb(e = []) {
          let errors = e;
          if (!Array.isArray(errors)) {
            errors = [errors];
          }
          if (!options.suppressWarning && errors.length) {
            Schema.warning('async-validator:', errors);
          }
          if (errors.length && rule.message) {
            errors = [].concat(rule.message);
          }

          errors = errors.map(complementError(rule));

          if (options.first && errors.length) {
            errorFields[rule.field] = 1;
            return doIt(errors);
          }
          if (!deep) {
            doIt(errors);
          } else {
            // if rule is required but the target object
            // does not exist fail at the rule level and don't
            // go deeper
            if (rule.required && !data.value) {
              if (rule.message) {
                errors = [].concat(rule.message).map(complementError(rule));
              } else if (options.error) {
                errors = [
                  options.error(
                    rule,
                    format(options.messages.required, rule.field),
                  ),
                ];
              } else {
                errors = [];
              }
              return doIt(errors);
            }

            let fieldsSchema = {};
            if (rule.defaultField) {
              for (const k in data.value) {
                if (data.value.hasOwnProperty(k)) {
                  fieldsSchema[k] = rule.defaultField;
                }
              }
            }
            fieldsSchema = {
              ...fieldsSchema,
              ...data.rule.fields,
            };
            for (const f in fieldsSchema) {
              if (fieldsSchema.hasOwnProperty(f)) {
                const fieldSchema = Array.isArray(fieldsSchema[f])
                  ? fieldsSchema[f]
                  : [fieldsSchema[f]];
                fieldsSchema[f] = fieldSchema.map(addFullfield.bind(null, f));
              }
            }
            const schema = new Schema(fieldsSchema);
            schema.messages(options.messages);
            if (data.rule.options) {
              data.rule.options.messages = options.messages;
              data.rule.options.error = options.error;
            }
            schema.validate(data.value, data.rule.options || options, errs => {
              const finalErrors = [];
              if (errors && errors.length) {
                finalErrors.push(...errors);
              }
              if (errs && errs.length) {
                finalErrors.push(...errs);
              }
              doIt(finalErrors.length ? finalErrors : null);
            });
          }
        }

        let res;
        if (rule.asyncValidator) {
          res = rule.asyncValidator(rule, data.value, cb, data.source, options);
        } else if (rule.validator) {
          res = rule.validator(rule, data.value, cb, data.source, options);
          if (res === true) {
            cb();
          } else if (res === false) {
            cb(rule.message || `${rule.field} fails`);
          } else if (res instanceof Array) {
            cb(res);
          } else if (res instanceof Error) {
            cb(res.message);
          }
        }
        if (res && res.then) {
          res.then(() => cb(), e => cb(e));
        }
      },
      results => {
        complete(results);
      },
    );
  },
  getType(rule) {
    if (rule.type === undefined && rule.pattern instanceof RegExp) {
      rule.type = 'pattern';
    }
    if (
      typeof rule.validator !== 'function' &&
      (rule.type && !validators.hasOwnProperty(rule.type))
    ) {
      throw new Error(format('Unknown rule type %s', rule.type));
    }
    return rule.type || 'string';
  },
  getValidationMethod(rule) {
    if (typeof rule.validator === 'function') {
      return rule.validator;
    }
    const keys = Object.keys(rule);
    const messageIndex = keys.indexOf('message');
    if (messageIndex !== -1) {
      keys.splice(messageIndex, 1);
    }
    if (keys.length === 1 && keys[0] === 'required') {
      return validators.required;
    }
    return validators[this.getType(rule)] || false;
  },
};

Schema.register = function register(type, validator) {
  if (typeof validator !== 'function') {
    throw new Error(
      'Cannot register a validator by type, validator is not a function',
    );
  }
  validators[type] = validator;
};

Schema.warning = warning;

Schema.messages = defaultMessages;

Schema.validators = validators;

export default Schema;
<|endoftext|>


<commit_before>;(function () {
  'use strict'

  /* imports */
  var funPredicate = require('fun-predicate')
  var stringify = require('stringify-anything')

  module.exports = assert

  var METHODS = [
    'truthy',
    'falsey',
    'equal',
    'equalDeep',
    'type',
    'match',
    'yes',
    'no'
  ]

  METHODS.forEach(function (method) {
    module.exports[method] = function (reference) {
      return assert(funPredicate[method](reference))
    }
  })

  module.exports.nothing = function nothing (subject) { return subject }

  function assert (predicate) {
    function toString (subject) {
      var subjectString = subject ? stringify(subject) : ''
      return subjectString + ' should ' + stringify(predicate)
    }

    function assertion (subject) {
      if (!predicate(subject)) {
        var message = toString(subject)

        throw new Error(message)
      }

      return subject
    }

    assertion.toString = toString

    return assertion
  }
})()

<commit_msg>[PATCH][ADD] pass and fail aliases for yes and no<commit_after>;(function () {
  'use strict'

  /* imports */
  var funPredicate = require('fun-predicate')
  var stringify = require('stringify-anything')

  module.exports = assert

  var METHODS = [
    'truthy',
    'falsey',
    'equal',
    'equalDeep',
    'type',
    'match',
    'yes',
    'no'
  ]

  METHODS.forEach(function (method) {
    module.exports[method] = function (reference) {
      return assert(funPredicate[method](reference))
    }
  })

  module.exports.fail = module.exports.no
  module.exports.pass = module.exports.yes

  module.exports.nothing = function nothing (subject) { return subject }

  function assert (predicate) {
    function toString (subject) {
      var subjectString = subject ? stringify(subject) : ''
      return subjectString + ' should ' + stringify(predicate)
    }

    function assertion (subject) {
      if (!predicate(subject)) {
        var message = toString(subject)

        throw new Error(message)
      }

      return subject
    }

    assertion.toString = toString

    return assertion
  }
})()

<|endoftext|>


<commit_before>import http from 'http'
import express from 'express'
import expressValidator from 'express-validator'
import bodyParser from 'body-parser'
import cors from 'cors'
import jsend from 'jsend'
import morgan from 'morgan'
import validators from './util/validators'
import api from './routes'
import setStatusMiddleware from './middlewares/format-errors'

const app = express()
app.server = http.createServer(app)

// 3rd party middleware
app.use(cors({
  exposedHeaders: ['Link'],
}))

app.use(bodyParser.json({
  limit: '100kb',
}))

app.use(bodyParser.urlencoded({
  extended: true,
}))

app.use(expressValidator({
  customValidators: validators,
}))

app.use(jsend.middleware)

app.use(setStatusMiddleware)

// api router
app.use(api)

// no need to start a server when testing
if (process.env.NODE_ENV !== 'test') {
  app.use(morgan('combined'))
  app.server.listen(process.env.PORT || 8080)
  /* eslint-disable no-console */
  console.log(`Started on port ${app.server.address().port}`)
  /* eslint-enable no-console */
}

export default app
<commit_msg>Log with morgan before routes are loaded<commit_after>import http from 'http'
import express from 'express'
import expressValidator from 'express-validator'
import bodyParser from 'body-parser'
import cors from 'cors'
import jsend from 'jsend'
import morgan from 'morgan'
import validators from './util/validators'
import api from './routes'
import setStatusMiddleware from './middlewares/format-errors'

const app = express()
app.server = http.createServer(app)

// 3rd party middleware
app.use(cors({
  exposedHeaders: ['Link'],
}))

app.use(bodyParser.json({
  limit: '100kb',
}))

app.use(bodyParser.urlencoded({
  extended: true,
}))

app.use(expressValidator({
  customValidators: validators,
}))

app.use(jsend.middleware)

app.use(setStatusMiddleware)

if (process.env.NODE_ENV !== 'test') {
  app.use(morgan('combined'))
}

// api router
app.use(api)

// don't start a server when testing
if (process.env.NODE_ENV !== 'test') {
  app.server.listen(process.env.PORT || 8080)
  /* eslint-disable no-console */
  console.log(`Started on port ${app.server.address().port}`)
  /* eslint-enable no-console */
}

export default app
<|endoftext|>


<commit_before>;(function () {
  'use strict'

  /* imports */
  var typeCheck = require('type-check').typeCheck
  var stringifySafe = require('json-stringify-safe')
  var deepEqual = require('deep-equal')

  /* exports */
  module.exports = {
    type: type,
    equal: equal,
    or: or,
    and: and,
    not: not
  }

  function equal (reference) {
    function asserter (subject) {
      var ok = reference === subject

      if (typeCheck('Object', reference)) {
        ok = deepEqual(subject, reference, {strict: true})
      }

      if (!ok) {
        throw error(subject)
      }
    }

    function error (subject) {
      var verb = 'equal'

      return makeError(subject, verb, reference)
    }

    asserter.error = error

    return asserter
  }

  function type (reference) {
    function asserter (subject) {
      var ok = typeCheck(reference, subject)

      if (!ok) {
        throw error(subject)
      }
    }

    function error (subject) {
      var verb = 'have type'

      return makeError(subject, verb, reference)
    }

    asserter.error = error

    return asserter
  }

  function and (asserters) {
    return function (subject) {
      asserters.forEach(function (asserter) {
        asserter(subject)
      })
    }
  }

  function or (asserters) {
    return function (subject) {
      var errors = asserters.reduce(function (results, asserter) {
        try {
          asserter(subject)
        } catch (error) {
          results.push(error)
        }

        return results
      }, [])

      if (errors.length === asserters.length) {
        var combinedError = errors.reduce(function (combined, error) {
          combined.message += ' OR ' + error.message

          return combined
        })

        throw combinedError
      }
    }
  }

  function not (asserter) {
    return function (subject) {
      try {
        asserter(subject)
      } catch (error) {
        return
      }

      var error = asserter.error(subject)
      error.message = error.message.replace('should','should not')

      throw error
    }
  }

  function makeError (subject, verb, reference) {
      var s = stringifySafe(subject)
      var r = stringifySafe(reference)
      var message = s + ' should ' + verb + ' ' + r

      return new Error(message)
  }
})()

<commit_msg>[PATCH][FIX] errors for and, or, not functions<commit_after>;(function () {
  'use strict'

  /* imports */
  var typeCheck = require('type-check').typeCheck
  var stringifySafe = require('json-stringify-safe')
  var deepEqual = require('deep-equal')

  /* exports */
  module.exports = {
    type: type,
    equal: equal,
    or: or,
    and: and,
    not: not
  }

  function equal (reference) {
    function asserter (subject) {
      var ok = reference === subject

      if (typeCheck('Object', reference)) {
        ok = deepEqual(subject, reference, {strict: true})
      }

      if (!ok) {
        throw error(subject)
      }
    }

    function error (subject) {
      var verb = 'equal'

      return makeError(subject, verb, reference)
    }

    asserter.error = error

    return asserter
  }

  function type (reference) {
    function asserter (subject) {
      var ok = typeCheck(reference, subject)

      if (!ok) {
        throw error(subject)
      }
    }

    function error (subject) {
      var verb = 'have type'

      return makeError(subject, verb, reference)
    }

    asserter.error = error

    return asserter
  }

  function and (asserters) {
    function asserter (subject) {
      asserters.forEach(function (asserter) {
        try {
          asserter(subject)
        } catch (e) {
          throw error(subject)
        }
      })
    }

    function error (subject) {
      var errors = asserters.map(function (asserter) {
        return asserter.error(subject)
      })

      var combinedError = errors.reduce(function (combined, error) {
        combined.message += ' AND ' + error.message

        return combined
      })

      combinedError.message = '(' + combinedError.message + ')'
      return combinedError
    }

    asserter.error = error

    return asserter
  }

  function or (asserters) {
    function asserter (subject) {
      var errors = asserters.reduce(function (results, asserter) {
        try {
          asserter(subject)
        } catch (error) {
          results.push(error)
        }

        return results
      }, [])

      if (errors.length === asserters.length) {
        var combinedError = errors.reduce(function (combined, error) {
          combined.message += ' OR ' + error.message

          return combined
        })

        throw combinedError
      }
    }

    function error (subject) {
      var errors = asserters.map(function (asserter) {
        return asserter.error(subject)
      })

      var combinedError = errors.reduce(function (combined, error) {
        combined.message += ' OR ' + error.message

        return combined
      })

      combinedError.message = '(' + combinedError.message + ')'
      return combinedError
    }

    asserter.error = error

    return asserter
  }

  function not (originalAsserter) {
    function asserter (subject) {
      try {
        originalAsserter(subject)
      } catch (error) {
        return
      }

      throw error(subject)
    }

    function error (subject) {
      var original = originalAsserter.error(subject)

      original.message = original.message.replace(/should/g,'should not')

      original.message = '(' + original.message + ')'
      return original
    }

    return asserter
  }

  function makeError (subject, verb, reference) {
      var s = stringifySafe(subject)
      var r = stringifySafe(reference)
      var message = s + ' should ' + verb + ' ' + r

      return new Error(message)
  }
})()

<|endoftext|>