<commit_before>"use strict";

import crypto from 'crypto';

const FUNCTION_NAMES = ["defineMessages"]

export default function({ types: t }) {
  function referencesImport(path, mod, importedNames) {
    if (!(path.isIdentifier() || path.isJSXIdentifier())) { return false; }
    return importedNames.some((name) => path.referencesImport(mod, name));
  }

  /**
   * @param  {Object}  opts - A Babel options object
   *
   * @return {Object}  Returns the module name to search for imports of. Defaults to `react-intl`
   */
  function getModuleSourceName(opts) {
    return opts.moduleSourceName || "react-intl";
  }

  /**
   * @param  {String}  hashKey - A string used to generate a SHA1 hash
   *
   * @return {Object}  A SHA1 hash of the hashKey
   */
  function getHash(hashKey) {
    return crypto
      .createHash('sha1')
      .update(hashKey || "")
      .digest('hex');
  }

  /**
   * @param  {ASTNode}  path - An AST node representing a POJO.
   *
   * @return {Object}  A POJO representation of an AST node
   */
  function generateObjectFromNode(path) {
    return path.get('properties').map((prop) => [
      prop.get('key').node.value,
      prop.get('value').node.value,
    ]).reduce((previousValue, property) => {
      previousValue[property[0]] = property[1]
      return previousValue;
    }, {});
  }

  function processMessage(filename, messageObj) {
    if (!(messageObj[1] && messageObj[1].isObjectExpression())) {
      throw path.buildCodeFrameError(
        `[babel-plugin-i18n-id-hashing] ${callee.node.name}() must be called with message ` +
        `descriptors defined as object expressions.`
      );
    }

    const objectIdProperty = messageObj[1]
      .get('properties')
      // Returns all an array for keyNode, ValueNode pairs
      .map((prop) => [
        prop.get('key'),
        prop.get('value'),
      ])
      // Returns [[idKeyNode, idValueNode]]
      .filter((prop) => prop[0].node.value === "id")
      // Returns [idKeyNode, idValueNode]
      .pop()
      // Retuens idValueNode
      [1];

    const objectProperties = generateObjectFromNode(messageObj[1]);
    const generatedMessageId = `${getHash(filename)}.${objectProperties.id}`

    // Replace the Object's key with the generatedMessageId
    const objectKey = messageObj[0];
    objectKey.replaceWith(t.stringLiteral(generatedMessageId));
    // Replace the Object's `id` property with the generatedMessageId
    objectIdProperty.replaceWith(t.stringLiteral(generatedMessageId));
  }

  return {
    visitor: {
      CallExpression(path, state) {
        const moduleSourceName = getModuleSourceName(state.opts);
        const callee = path.get('callee');

        // Return if the call expression is either
        //   - not found in a file that imports `react-intl`
        //   - is not a call to one of the FUNCTION_NAMES
        if(referencesImport(callee, moduleSourceName, FUNCTION_NAMES) === false) { return; }

        // FUNCTION_NAMES functions are of the form function(Object messages)
        // https://github.com/yahoo/react-intl/blob/2fdf9e7e695fa04673573d72ab6265f0eef3f98e/src/react-intl.js#L25-L29
        let messagesObj = path.get('arguments')[0];

        // Process each message
        messagesObj
          .get('properties')
          .map((prop) => [
            prop.get('key'),
            prop.get('value'),
          ])
          .forEach(processMessage.bind(null, state.file.opts.filename));
      },
      // TODO: if this gets called before CallExpression Visitor - register a search for that key
      MemberExpression(path, state) {
        // TODO: Take messageName as an option
        // TODO: register messageName when ExpressionStatement is called
        if (path.node.object.name !== "defaultMessages") { return; }

        const filename = state.file.opts.filename;
        let accessor = path.get("property");

        if (accessor.type === "StringLiteral") {
          accessor.replaceWith(t.stringLiteral(`${getHash(filename)}.${accessor.node.value}`))
        } else {
          // Convert xMemberExpression.identifier -> xMemberExpression[identifier]
          path.node.computed = true
          // Add the hash to the result of any Identifier or Expression
          accessor.replaceWith(t.binaryExpression("+", t.stringLiteral(getHash(filename)), accessor.node))
        }
      }
    }
  };
};
<commit_msg>Extract the methodName string into getMethodName<commit_after>"use strict";

import crypto from 'crypto';

const FUNCTION_NAMES = ["defineMessages"]

export default function({ types: t }) {
  function referencesImport(path, mod, importedNames) {
    if (!(path.isIdentifier() || path.isJSXIdentifier())) { return false; }
    return importedNames.some((name) => path.referencesImport(mod, name));
  }

  /**
   * @param  {Object}  opts - A Babel options object
   *
   * @return {Object}  Returns the module name to search for imports of. Defaults to `react-intl`
   */
  function getModuleSourceName(opts) {
    return opts.moduleSourceName || "react-intl";
  }

  /**
   * @param  {Object}  opts - A Babel options object
   *
   * @return {Object}  Returns the Identifier name to search for calls of. Defaults to `defaultMessages`
   */
  function getMethodName(opts) {
    return opts.methodName || "defaultMessages";
  }

  /**
   * @param  {String}  hashKey - A string used to generate a SHA1 hash
   *
   * @return {Object}  A SHA1 hash of the hashKey
   */
  function getHash(hashKey) {
    return crypto
      .createHash('sha1')
      .update(hashKey || "")
      .digest('hex');
  }

  /**
   * @param  {ASTNode}  path - An AST node representing a POJO.
   *
   * @return {Object}  A POJO representation of an AST node
   */
  function generateObjectFromNode(path) {
    return path.get('properties').map((prop) => [
      prop.get('key').node.value,
      prop.get('value').node.value,
    ]).reduce((previousValue, property) => {
      previousValue[property[0]] = property[1]
      return previousValue;
    }, {});
  }

  function processMessage(filename, messageObj) {
    if (!(messageObj[1] && messageObj[1].isObjectExpression())) {
      throw path.buildCodeFrameError(
        `[babel-plugin-i18n-id-hashing] ${callee.node.name}() must be called with message ` +
        `descriptors defined as object expressions.`
      );
    }

    const objectIdProperty = messageObj[1]
      .get('properties')
      // Returns all an array for keyNode, ValueNode pairs
      .map((prop) => [
        prop.get('key'),
        prop.get('value'),
      ])
      // Returns [[idKeyNode, idValueNode]]
      .filter((prop) => prop[0].node.value === "id")
      // Returns [idKeyNode, idValueNode]
      .pop()
      // Retuens idValueNode
      [1];

    const objectProperties = generateObjectFromNode(messageObj[1]);
    const generatedMessageId = `${getHash(filename)}.${objectProperties.id}`

    // Replace the Object's key with the generatedMessageId
    const objectKey = messageObj[0];
    objectKey.replaceWith(t.stringLiteral(generatedMessageId));
    // Replace the Object's `id` property with the generatedMessageId
    objectIdProperty.replaceWith(t.stringLiteral(generatedMessageId));
  }

  return {
    visitor: {
      CallExpression(path, state) {
        const moduleSourceName = getModuleSourceName(state.opts);
        const callee = path.get('callee');

        // Return if the call expression is either
        //   - not found in a file that imports `react-intl`
        //   - is not a call to one of the FUNCTION_NAMES
        if(referencesImport(callee, moduleSourceName, FUNCTION_NAMES) === false) { return; }

        // FUNCTION_NAMES functions are of the form function(Object messages)
        // https://github.com/yahoo/react-intl/blob/2fdf9e7e695fa04673573d72ab6265f0eef3f98e/src/react-intl.js#L25-L29
        let messagesObj = path.get('arguments')[0];

        // Process each message
        messagesObj
          .get('properties')
          .map((prop) => [
            prop.get('key'),
            prop.get('value'),
          ])
          .forEach(processMessage.bind(null, state.file.opts.filename));
      },
      // TODO: if this gets called before CallExpression Visitor - register a search for that key
      MemberExpression(path, state) {
        // TODO: register messageName when ExpressionStatement is called
        if (path.node.object.name !== getMethodName(state.opts)) { return; }

        const filename = state.file.opts.filename;
        let accessor = path.get("property");

        if (accessor.type === "StringLiteral") {
          accessor.replaceWith(t.stringLiteral(`${getHash(filename)}.${accessor.node.value}`))
        } else {
          // Convert xMemberExpression.identifier -> xMemberExpression[identifier]
          path.node.computed = true
          // Add the hash to the result of any Identifier or Expression
          accessor.replaceWith(t.binaryExpression("+", t.stringLiteral(getHash(filename)), accessor.node))
        }
      }
    }
  };
};
<|endoftext|>


<commit_before>// Copyright 2010 Michael Geary
// http://mg.to/
// Free Beer and Free Speech License (any OSI license)
// http://freebeerfreespeech.org/

document.write(
	'<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery', opt.debug ? '' : '.min', '.js">',
	'</script>'
);

opt.writeScript( 'voter-info-thanks.js?2010' );
<commit_msg>Switch back from "thanks for voting" message to real gadget<commit_after>// Copyright 2010 Michael Geary
// http://mg.to/
// Free Beer and Free Speech License (any OSI license)
// http://freebeerfreespeech.org/

document.write(
	'<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery', opt.debug ? '' : '.min', '.js">',
	'</script>'
);

opt.writeScript( 'voter-info-main.js' );
<|endoftext|>


<commit_before>module.exports = function multiply(first, second) {

    function remeberTheOne(string, index){
      var result;
      if(index == -1){  // or 0
        return '1' + string;
      }

      while(true){
        var number = string.charAt(index);
        if(++number < 9){
          result = string.substring(0 , index) + number + string.substring(index+1);
          return result;
        }
        else{
          result = string.substring(0 , index) + '0' + string.substring(index + 1);
          remeberTheOne(result, index - 1);
        }
      }
    }

    function sum(str1, str2){
      var bigString = "";
      var smallString = "";
      var result = "";

      if(str1.length >= str2.length){
        bigString = str1;
        smallString = str2;
      }
      else{
        bigString = str2;
        smallString = str1;
      }

      for(var i = 0; i < smallString.length; i++){
        var sum = Number(bigString.charAt(bigString.length - i - 1)) + Number(smallString.charAt(smallString.length - i - 1));

        if(sum > 9){
          sum-= 10;
              if(i == 0){
                  result = bigString.substring(0, bigString.length - i - 1) + sum;
              }
              else{
                  result = bigString.substring(0, bigString.length - i - 1) + sum + bigString.substring(bigString.length - i);
                  result = remeberTheOne(result , bigString.length - i - 1);
              }
        }

        else  {

          if(i == 0){
              result = bigString.substring(0, bigString.length - i - 1) + sum;
          }
          else
              result = bigString.substring(0, bigString.length - i - 1) + sum + bigString.substring(bigString.length - i);

        }
      }
      return result;
    }

    var result = first;
    for(var i = 0; i < Number(second); i++){
      result = sum(result , first);
    }
    return result;
  }

  function remeberTheOne(string, index){
      var result;
      if(index == -1){  // or 0
        return '1' + string;
      }

      while(true){
        var number = string.charAt(index);
        if(++number < 9){
          result = string.substring(0 , index) + number + string.substring(index+1);
          return result;
        }
        else{
          result = string.substring(0 , index) + '0' + string.substring(index + 1);
          remeberTheOne(result, index - 1);
        }
      }
    }

    function sum(str1, str2){
      var bigString = "";
      var smallString = "";
      var result = "";

      if(str1.length >= str2.length){
        bigString = str1;
        smallString = str2;
      }
      else{
        bigString = str2;
        smallString = str1;
      }

      for(var i = 0; i < smallString.length; i++){
        var sum = Number(bigString.charAt(bigString.length - i - 1)) + Number(smallString.charAt(smallString.length - i - 1));

        if(sum > 9){
          sum-= 10;
              if(i == 0){
                  result = bigString.substring(0, bigString.length - 1) + sum;

              }
              else{
                  result = bigString.substring(0, bigString.length - i - 1) + sum + bigString.substring(bigString.length - i);

              }
              result = remeberTheOne(result , bigString.length - i - 2);

        }

        else  {

          if(i == 0){
              result = bigString.substring(0, bigString.length - i - 1) + sum;
          }
          else
              result = bigString.substring(0, bigString.length - i - 1) + sum + bigString.substring(bigString.length - i);

        }
      }
      return result;
    }
<commit_msg>Working very slow<commit_after>module.exports = function multiply(first, second) {

    function convertingInArray(str){
      var arr = [];
      var length = str.length;
      for(var i = 0; i < length ; i++){
        arr[i] = Number(str.charAt(length - 1 - i));
      }
      return arr;
    }

    function sum(str1, str2){
      var arr1 = convertingInArray(str1);
      var arr2 = convertingInArray(str2);

      var bigArray = [];
      var smallArray = [];

      if(arr1.length >= arr2.length){
        bigArray = arr1;
        smallArray = arr2;
      }

      else{
        bigArray = arr2;
        smallArray = arr1;
      }

      for(var i = smallArray.length; i < bigArray.length; i++){
        smallArray.push(0);
      }

      var result = [];

      for(var i = 0; i < bigArray.length; i++){
        result[i] = bigArray[i] + smallArray[i];
      }

      for(var i =  0; i < result.length; i++){
        if(result[i] > 9){
          result[i] -= 10;
          if(i == result.length - 1)
            result.push(1);
          else
            result[i+1]++;
        }
    }
    var string = "";
    for(var i = result.length - 1; i >= 0; i--)
      string+=result[i];
    return string;
  }

    var result  = first;

    for(var i = 0; i < Number(second) - 1; i++){
      result = sum(result , first);
    }
    return result;
  }<|endoftext|>


<commit_before>import JavaFormatter from "./javaFormatter"

module.exports = function() {
    /**
     *
     * @param spacing
     * @returns {JavaFormatter}
     */
    this.createJavaFormatter = function(spacing) {
        return new JavaFormatter(spacing)
    }
};<commit_msg>changed index.js<commit_after>import JavaFormatter from "./javaFormatter"

module.exports = {
    /**
     *
     * @param spacing
     * @returns {JavaFormatter}
     */
    createJavaFormatter: function(spacing) {
        return new JavaFormatter(spacing)
    }
};<|endoftext|>


<commit_before>var EMPTY_OBJECT = {}
var EMPTY_ARRAY = []
var map = EMPTY_ARRAY.map
var isArray = Array.isArray

var SVG_NS = "http://www.w3.org/2000/svg"
var DEFAULT_NODE = 0
var RECYCLED_NODE = 1
var LAZY_NODE = 2
var TEXT_NODE = 3

var defer =
  typeof Promise === "function"
    ? function(cb) {
        Promise.resolve().then(cb)
      }
    : setTimeout

var merge = function(a, b) {
  var out = {}

  for (var i in a) out[i] = a[i]
  for (var i in b) out[i] = b[i]

  return out
}

function createClass(obj) {
  var out = ""
  var tmp = typeof obj

  if (tmp === "string" || tmp === "number") return obj

  if (isArray(obj) && obj.length > 0) {
    for (var i = 0; i < obj.length; i++) {
      if ((tmp = createClass(obj[i])) !== "") out += (out && " ") + tmp
    }
  } else {
    for (var i in obj) {
      if (obj[i]) out += (out && " ") + i
    }
  }

  return out
}

var updateProperty = function(element, name, value, newValue, cb, isSvg) {
  if (name === "key") {
  } else if (name === "style") {
    for (var i in merge(value, newValue)) {
      var style = newValue == null || newValue[i] == null ? "" : newValue[i]
      if (i[0] === "-") {
        element[name].setProperty(i, style)
      } else {
        element[name][i] = style
      }
    }
  } else {
    if (name[0] === "o" && name[1] === "n") {
      if (
        !((element.events || (element.events = {}))[
          (name = name.slice(2).toLowerCase())
        ] = newValue)
      ) {
        element.removeEventListener(name, cb)
      } else if (!value) {
        element.addEventListener(name, cb)
      }
    } else if (name !== "list" && !isSvg && name in element) {
      element[name] = newValue == null ? "" : newValue
    } else if (
      newValue == null ||
      newValue === false ||
      (name === "class" && !(newValue = createClass(newValue)))
    ) {
      element.removeAttribute(name)
    } else {
      element.setAttribute(name, newValue)
    }
  }
}

var removeElement = function(parent, node) {
  parent.removeChild(node.element)
}

var createElement = function(node, cb, isSvg) {
  var element =
    node.type === TEXT_NODE
      ? document.createTextNode(node.name)
      : (isSvg = isSvg || node.name === "svg")
      ? document.createElementNS(SVG_NS, node.name)
      : document.createElement(node.name)

  for (var i = 0, len = node.children.length; i < len; i++) {
    element.appendChild(
      createElement((node.children[i] = getNode(node.children[i])), cb, isSvg)
    )
  }

  var props = node.props
  for (var k in props) {
    updateProperty(element, k, null, props[k], cb, isSvg)
  }

  return (node.element = element)
}

var updateElement = function(element, props, newProps, cb, isSvg) {
  for (var k in merge(props, newProps)) {
    if (
      (k === "value" || k === "checked" ? element[k] : props[k]) !== newProps[k]
    ) {
      updateProperty(element, k, props[k], newProps[k], cb, isSvg)
    }
  }
}

var getKey = function(node) {
  return node == null ? null : node.key
}

var createKeyMap = function(children, start, end) {
  for (var out = {}, key, node; start <= end; start++) {
    if ((key = (node = children[start]).key) != null) {
      out[key] = node
    }
  }
  return out
}

var patchElement = function(parent, element, node, newNode, cb, isSvg) {
  if (newNode === node) {
  } else if (
    node != null &&
    node.type === TEXT_NODE &&
    newNode.type === TEXT_NODE
  ) {
    if (node.name !== newNode.name) {
      element.nodeValue = newNode.name
    }
  } else if (node == null || node.name !== newNode.name) {
    var newElement = parent.insertBefore(
      createElement((newNode = getNode(newNode)), cb, isSvg),
      element
    )

    if (node != null) removeElement(parent, node)

    element = newElement
  } else {
    updateElement(
      element,
      node.props,
      newNode.props,
      cb,
      (isSvg = isSvg || newNode.name === "svg")
    )

    var savedNode
    var childNode

    var key
    var children = node.children
    var start = 0
    var end = children.length - 1

    var newKey
    var newChildren = newNode.children
    var newStart = 0
    var newEnd = newChildren.length - 1

    while (newStart <= newEnd && start <= end) {
      key = getKey(children[start])
      newKey = getKey(newChildren[newStart])

      if (key == null || key !== newKey) break

      patchElement(
        element,
        children[start].element,
        children[start],
        (newChildren[newStart] = getNode(
          newChildren[newStart],
          children[start]
        )),
        cb,
        isSvg
      )

      start++
      newStart++
    }

    while (newStart <= newEnd && start <= end) {
      key = getKey(children[end])
      newKey = getKey(newChildren[newEnd])

      if (key == null || key !== newKey) break

      patchElement(
        element,
        children[end].element,
        children[end],
        (newChildren[newEnd] = getNode(newChildren[newEnd], children[end])),
        cb,
        isSvg
      )

      end--
      newEnd--
    }

    if (start > end) {
      while (newStart <= newEnd) {
        element.insertBefore(
          createElement(
            (newChildren[newStart] = getNode(newChildren[newStart++])),
            cb,
            isSvg
          ),
          (childNode = children[start]) && childNode.element
        )
      }
    } else if (newStart > newEnd) {
      while (start <= end) {
        removeElement(element, children[start++])
      }
    } else {
      var keyed = createKeyMap(children, start, end)
      var newKeyed = {}

      while (newStart <= newEnd) {
        key = getKey((childNode = children[start]))
        newKey = getKey(
          (newChildren[newStart] = getNode(newChildren[newStart], childNode))
        )

        if (
          newKeyed[key] ||
          (newKey != null && newKey === getKey(children[start + 1]))
        ) {
          if (key == null) {
            removeElement(element, childNode)
          }
          start++
          continue
        }

        if (newKey == null || node.type === RECYCLED_NODE) {
          if (key == null) {
            patchElement(
              element,
              childNode && childNode.element,
              childNode,
              newChildren[newStart],
              cb,
              isSvg
            )
            newStart++
          }
          start++
        } else {
          if (key === newKey) {
            patchElement(
              element,
              childNode.element,
              childNode,
              newChildren[newStart],
              cb,
              isSvg
            )
            newKeyed[newKey] = true
            start++
          } else {
            if ((savedNode = keyed[newKey]) != null) {
              patchElement(
                element,
                element.insertBefore(
                  savedNode.element,
                  childNode && childNode.element
                ),
                savedNode,
                newChildren[newStart],
                cb,
                isSvg
              )
              newKeyed[newKey] = true
            } else {
              patchElement(
                element,
                childNode && childNode.element,
                null,
                newChildren[newStart],
                cb,
                isSvg
              )
            }
          }
          newStart++
        }
      }

      while (start <= end) {
        if (getKey((childNode = children[start++])) == null) {
          removeElement(element, childNode)
        }
      }

      for (var key in keyed) {
        if (newKeyed[key] == null) {
          removeElement(element, keyed[key])
        }
      }
    }
  }

  return (newNode.element = element)
}

var shouldUpdate = function(a, b) {
  for (var k in a) if (a[k] !== b[k]) return true
  for (var k in b) if (a[k] !== b[k]) return true
}

var getNode = function(newNode, node) {
  return newNode.type === LAZY_NODE
    ? !node || shouldUpdate(newNode.lazy, node.lazy)
      ? newNode.render()
      : node
    : newNode
}

var createVNode = function(name, props, children, element, key, type) {
  return {
    name: name,
    props: props,
    children: children,
    element: element,
    type: type,
    key: key
  }
}

var createTextVNode = function(text, element) {
  return createVNode(text, EMPTY_OBJECT, EMPTY_ARRAY, element, null, TEXT_NODE)
}

var recycleChild = function(element) {
  return element.nodeType === TEXT_NODE
    ? createTextVNode(element.nodeValue, element)
    : recycleElement(element)
}

var recycleElement = function(element) {
  return createVNode(
    element.nodeName.toLowerCase(),
    EMPTY_OBJECT,
    map.call(element.childNodes, recycleChild),
    element,
    null,
    RECYCLED_NODE
  )
}

var patch = function(container, element, node, newNode, cb) {
  return (element = patchElement(container, element, node, newNode, cb))
}

export var Lazy = function(props) {
  return {
    type: LAZY_NODE,
    key: props.key,
    lazy: props,
    render: function() {
      var node = props.render(props)
      node.lazy = props
      return node
    }
  }
}

export var h = function(name, props) {
  for (var node, rest = [], children = [], i = arguments.length; i-- > 2; ) {
    rest.push(arguments[i])
  }

  for (; rest.length > 0; ) {
    if (isArray((node = rest.pop()))) {
      for (i = node.length; i-- > 0; ) rest.push(node[i])
    } else if (node === false || node === true || node == null) {
    } else {
      children.push(typeof node === "object" ? node : createTextVNode(node))
    }
  }

  props = props || EMPTY_OBJECT

  return typeof name === "function"
    ? name(props, children)
    : createVNode(name, props, children, null, props.key, DEFAULT_NODE)
}

var isSameAction = function(a, b) {
  return isArray(a) && isArray(b) && typeof a[0] === "function" && a[0] === b[0]
}

var shouldRestart = function(a, b) {
  for (var k in merge(a, b)) {
    if (a[k] === b[k] || isSameAction(a[k], b[k])) b[k] = a[k]
    else return true
  }
}

var patchSub = function(sub, newSub, dispatch) {
  if (
    (newSub && (!newSub[0] || isArray(newSub[0]))) ||
    (sub && (!sub[0] || isArray(sub[0])))
  ) {
    var out = []
    var subs = sub ? sub : [sub]
    var newSubs = newSub ? newSub : [newSub]

    for (var i = 0; i < newSubs.length || i < subs.length; i++) {
      out.push(patchSub(subs[i], newSubs[i], dispatch))
    }

    return out
  }

  return newSub
    ? !sub || newSub[0] !== sub[0] || shouldRestart(newSub[1], sub[1])
      ? [newSub[0], newSub[1], newSub[0](newSub[1], dispatch), sub && sub[2]()]
      : sub
    : sub && sub[2]()
}

export function app(props) {
  var container = props.container
  var element = container && container.children[0]
  var node = element && recycleElement(element)
  var subs = props.subscriptions
  var view = props.view
  var renderLock = false
  var state
  var sub

  var setState = function(newState) {
    if (!(state === newState || renderLock)) {
      defer(render, (renderLock = true))
    }
    state = newState
  }

  var dispatch = function(obj, props) {
    if (obj == null) {
    } else if (typeof obj === "function") {
      dispatch(obj(state, props))
    } else if (isArray(obj)) {
      if (typeof obj[0] === "function") {
        dispatch(obj[0](state, obj[1], props))
      } else {
        obj.slice(1).map(function(fx) {
          fx[0](fx[1], dispatch)
        }, setState(obj[0]))
      }
    } else {
      setState(obj)
    }
  }

  var cb = function(event) {
    dispatch(event.currentTarget.events[event.type], event)
  }

  var render = function() {
    renderLock = false
    if (subs) sub = patchSub(sub, subs(state), dispatch)
    if (view) {
      element = patch(container, element, node, (node = view(state)), cb)
    }
  }

  dispatch(props.init || {})
}
<commit_msg>Refactor batched subs/fx; shave more bytes<commit_after>var EMPTY_OBJECT = {}
var EMPTY_ARRAY = []

var map = EMPTY_ARRAY.map
var isArray = Array.isArray

var DEFAULT_NODE = 0
var RECYCLED_NODE = 1
var LAZY_NODE = 2
var TEXT_NODE = 3

var defer =
  typeof Promise === "function"
    ? function(cb) {
        Promise.resolve().then(cb)
      }
    : setTimeout

var merge = function(a, b) {
  var out = {}

  for (var i in a) out[i] = a[i]
  for (var i in b) out[i] = b[i]

  return out
}

var batch = function(list) {
  return list.reduce(function(out, obj) {
    return out.concat(
      !obj || obj === true
        ? false
        : typeof obj[0] === "function"
        ? [obj]
        : batch(obj)
    )
  }, EMPTY_ARRAY)
}

var isSameAction = function(a, b) {
  return isArray(a) && isArray(b) && a[0] === b[0] && typeof a[0] === "function"
}

var shouldRestart = function(a, b) {
  for (var k in merge(a, b)) {
    if (a[k] === b[k] || isSameAction(a[k], b[k])) b[k] = a[k]
    else return true
  }
}

var patchSub = function(sub, newSub, dispatch) {
  return batch(newSub).map(function(a, b) {
    b = sub[b]
    return a
      ? !b || a[0] !== b[0] || shouldRestart(a[1], b[1])
        ? [a[0], a[1], a[0](a[1], dispatch), b && b[2]()]
        : b
      : b && b[2]()
  })
}

var createClass = function(obj) {
  var out = ""
  var tmp = typeof obj

  if (tmp === "string" || tmp === "number") return obj

  if (isArray(obj) && obj.length > 0) {
    for (var i = 0; i < obj.length; i++) {
      if ((tmp = createClass(obj[i])) !== "") out += (out && " ") + tmp
    }
  } else {
    for (var i in obj) {
      if (obj[i]) out += (out && " ") + i
    }
  }

  return out
}

var updateProperty = function(element, name, value, newValue, eventCb, isSvg) {
  if (name === "key") {
  } else if (name === "style") {
    for (var i in merge(value, newValue)) {
      var style = newValue == null || newValue[i] == null ? "" : newValue[i]
      if (i[0] === "-") {
        element[name].setProperty(i, style)
      } else {
        element[name][i] = style
      }
    }
  } else {
    if (name[0] === "o" && name[1] === "n") {
      if (
        !((element.events || (element.events = {}))[
          (name = name.slice(2).toLowerCase())
        ] = newValue)
      ) {
        element.removeEventListener(name, eventCb)
      } else if (!value) {
        element.addEventListener(name, eventCb)
      }
    } else if (name !== "list" && !isSvg && name in element) {
      element[name] = newValue == null ? "" : newValue
    } else if (
      newValue == null ||
      newValue === false ||
      (name === "class" && !(newValue = createClass(newValue)))
    ) {
      element.removeAttribute(name)
    } else {
      element.setAttribute(name, newValue)
    }
  }
}

var removeElement = function(parent, node) {
  parent.removeChild(node.element)
}

var createElement = function(node, eventCb, isSvg) {
  var element =
    node.type === TEXT_NODE
      ? document.createTextNode(node.name)
      : (isSvg = isSvg || node.name === "svg")
      ? document.createElementNS("http://www.w3.org/2000/svg", node.name)
      : document.createElement(node.name)
  var props = node.props

  for (var i = 0, len = node.children.length; i < len; i++) {
    element.appendChild(
      createElement(
        (node.children[i] = getNode(node.children[i])),
        eventCb,
        isSvg
      )
    )
  }

  for (var k in props) {
    updateProperty(element, k, null, props[k], eventCb, isSvg)
  }

  return (node.element = element)
}

var updateElement = function(element, props, newProps, eventCb, isSvg) {
  for (var k in merge(props, newProps)) {
    if (
      (k === "value" || k === "checked" ? element[k] : props[k]) !== newProps[k]
    ) {
      updateProperty(element, k, props[k], newProps[k], eventCb, isSvg)
    }
  }
}

var getKey = function(node) {
  return node == null ? null : node.key
}

var createKeyMap = function(children, start, end) {
  for (var out = {}, key, node; start <= end; start++) {
    if ((key = (node = children[start]).key) != null) {
      out[key] = node
    }
  }
  return out
}

var patch = function(parent, element, node, newNode, eventCb, isSvg) {
  if (newNode === node) {
  } else if (
    node != null &&
    node.type === TEXT_NODE &&
    newNode.type === TEXT_NODE
  ) {
    if (node.name !== newNode.name) element.nodeValue = newNode.name
  } else if (node == null || node.name !== newNode.name) {
    var newElement = parent.insertBefore(
      createElement((newNode = getNode(newNode)), eventCb, isSvg),
      element
    )

    if (node != null) removeElement(parent, node)

    element = newElement
  } else {
    updateElement(
      element,
      node.props,
      newNode.props,
      eventCb,
      (isSvg = isSvg || newNode.name === "svg")
    )

    var savedNode
    var childNode

    var key
    var children = node.children
    var start = 0
    var end = children.length - 1

    var newKey
    var newChildren = newNode.children
    var newStart = 0
    var newEnd = newChildren.length - 1

    while (newStart <= newEnd && start <= end) {
      key = getKey(children[start])
      newKey = getKey(newChildren[newStart])

      if (key == null || key !== newKey) break

      patch(
        element,
        children[start].element,
        children[start],
        (newChildren[newStart] = getNode(
          newChildren[newStart],
          children[start]
        )),
        eventCb,
        isSvg
      )

      start++
      newStart++
    }

    while (newStart <= newEnd && start <= end) {
      key = getKey(children[end])
      newKey = getKey(newChildren[newEnd])

      if (key == null || key !== newKey) break

      patch(
        element,
        children[end].element,
        children[end],
        (newChildren[newEnd] = getNode(newChildren[newEnd], children[end])),
        eventCb,
        isSvg
      )

      end--
      newEnd--
    }

    if (start > end) {
      while (newStart <= newEnd) {
        element.insertBefore(
          createElement(
            (newChildren[newStart] = getNode(newChildren[newStart++])),
            eventCb,
            isSvg
          ),
          (childNode = children[start]) && childNode.element
        )
      }
    } else if (newStart > newEnd) {
      while (start <= end) {
        removeElement(element, children[start++])
      }
    } else {
      var keyed = createKeyMap(children, start, end)
      var newKeyed = {}

      while (newStart <= newEnd) {
        key = getKey((childNode = children[start]))
        newKey = getKey(
          (newChildren[newStart] = getNode(newChildren[newStart], childNode))
        )

        if (
          newKeyed[key] ||
          (newKey != null && newKey === getKey(children[start + 1]))
        ) {
          if (key == null) {
            removeElement(element, childNode)
          }
          start++
          continue
        }

        if (newKey == null || node.type === RECYCLED_NODE) {
          if (key == null) {
            patch(
              element,
              childNode && childNode.element,
              childNode,
              newChildren[newStart],
              eventCb,
              isSvg
            )
            newStart++
          }
          start++
        } else {
          if (key === newKey) {
            patch(
              element,
              childNode.element,
              childNode,
              newChildren[newStart],
              eventCb,
              isSvg
            )
            newKeyed[newKey] = true
            start++
          } else {
            if ((savedNode = keyed[newKey]) != null) {
              patch(
                element,
                element.insertBefore(
                  savedNode.element,
                  childNode && childNode.element
                ),
                savedNode,
                newChildren[newStart],
                eventCb,
                isSvg
              )
              newKeyed[newKey] = true
            } else {
              patch(
                element,
                childNode && childNode.element,
                null,
                newChildren[newStart],
                eventCb,
                isSvg
              )
            }
          }
          newStart++
        }
      }

      while (start <= end) {
        if (getKey((childNode = children[start++])) == null) {
          removeElement(element, childNode)
        }
      }

      for (var key in keyed) {
        if (newKeyed[key] == null) {
          removeElement(element, keyed[key])
        }
      }
    }
  }

  return (newNode.element = element)
}

var shouldUpdate = function(a, b) {
  for (var k in a) if (a[k] !== b[k]) return true
  for (var k in b) if (a[k] !== b[k]) return true
}

var getNode = function(newNode, node) {
  return newNode.type === LAZY_NODE
    ? !node || shouldUpdate(newNode.lazy, node.lazy)
      ? newNode.render()
      : node
    : newNode
}

var createVNode = function(name, props, children, element, key, type) {
  return {
    name: name,
    props: props,
    children: children,
    element: element,
    type: type,
    key: key
  }
}

var createTextVNode = function(text, element) {
  return createVNode(text, EMPTY_OBJECT, EMPTY_ARRAY, element, null, TEXT_NODE)
}

var recycleChild = function(element) {
  return element.nodeType === TEXT_NODE
    ? createTextVNode(element.nodeValue, element)
    : recycleElement(element)
}

var recycleElement = function(element) {
  return createVNode(
    element.nodeName.toLowerCase(),
    EMPTY_OBJECT,
    map.call(element.childNodes, recycleChild),
    element,
    null,
    RECYCLED_NODE
  )
}

export var Lazy = function(props) {
  return {
    type: LAZY_NODE,
    key: props.key,
    lazy: props,
    render: function() {
      var node = props.render(props)
      node.lazy = props
      return node
    }
  }
}

export var h = function(name, props) {
  for (var node, rest = [], children = [], i = arguments.length; i-- > 2; ) {
    rest.push(arguments[i])
  }

  for (; rest.length > 0; ) {
    if (isArray((node = rest.pop()))) {
      for (i = node.length; i-- > 0; ) rest.push(node[i])
    } else if (node === false || node === true || node == null) {
    } else {
      children.push(typeof node === "object" ? node : createTextVNode(node))
    }
  }

  props = props || EMPTY_OBJECT

  return typeof name === "function"
    ? name(props, children)
    : createVNode(name, props, children, null, props.key, DEFAULT_NODE)
}

export var app = function(props) {
  var container = props.container
  var element = container && container.children[0]
  var node = element && recycleElement(element)
  var subs = props.subscriptions
  var view = props.view
  var lock = false
  var sub = []
  var state

  var eventCb = function(event) {
    dispatch(event.currentTarget.events[event.type], event)
  }

  var setState = function(newState) {
    if (!(state === newState || lock)) {
      defer(render, (lock = true))
    }
    state = newState
  }

  var dispatch = function(obj, props) {
    if (typeof obj === "function") {
      dispatch(obj(state, props))
    } else if (isArray(obj)) {
      if (typeof obj[0] === "function") {
        dispatch(obj[0](state, obj[1], props))
      } else {
        batch(obj.slice(1)).map(function(fx) {
          fx && fx[0](fx[1], dispatch)
        }, setState(obj[0]))
      }
    } else {
      setState(obj)
    }
  }

  var render = function() {
    lock = false
    if (subs) sub = patchSub(sub, subs(state), dispatch)
    if (view) {
      element = patch(container, element, node, (node = view(state)), eventCb)
    }
  }

  dispatch(props.init || {})
}
<|endoftext|>


<commit_before>$(document).ready(function() {
	initPolling();
	initTooltips();
	initDatePicker();
	initAutocomplete();
	initTaskCompletion();

	// Fluid-specific stuff.
	if (window.fluid) {
		refreshDockBadge();
	}
});

var initPolling = function() {
	var polling = $.cookie('taskwarrior-web-polling');
	if (polling) {
		var pollingInterval = startPolling();
	} else {
		$('#polling-info a').text('Start polling');
	}

	$('#polling-info a').click(function(e) {
		if (polling) {
			window.clearInterval(pollingInterval);
			polling = false;
			$(this).text('Start polling');
			$.cookie('taskwarrior-web-polling', null);
		} else {
			pollingInterval = startPolling();
			polling = true;
			$(this).text('Stop polling');
			$.cookie('taskwarrior-web-polling', true);
		}
		e.preventDefault();
	});
};

var startPolling = function() {
	var pollingInterval = window.setInterval('refreshPageContents()', 3000);
	return pollingInterval;
};

var refreshPageContents = function() {
	$.ajax({
		url: window.location,
		success: function(data) {
			$('#listing').replaceWith($('#listing', data));
			refreshSubnavCount();
			refreshDockBadge();
		}
	});
};

var initTooltips = function() {
	$('.tooltip').tipsy({
		title: 'data-tooltip',
		gravity: 's'
	});
};

var initDatePicker = function() {
	$('.datefield input').datepicker({
		dateFormat: $('.datefield input').data('format'),
		autoSize: true
	});
};

var initAutocomplete = function() {
	$('#task-project').autocomplete({
		source: '/ajax/projects'
	});

	$('#task-tags').tagsInput({
		autocomplete_url: '/ajax/tags',
		defaultText: ''
	});
};

var initTaskCompletion = function() {
	$('input.complete').click(function() {
		// Cache the checkbox in case we need to restore it.
		var container $(this).parent();
		var checkbox = container.html();
		var row = $(this).closest('tr');
		container.html('');
		$.ajax({
			url: '/ajax/task-complete/' + $(this).data('task-id'),
			type: 'POST',
			success: function(data) {
				var message = (data === '') ? 'Task marked as completed.' : data;
				set_message(message, 'success');
				row.fadeOut();
			},
			error: function(data) {
				set_message('There was an error when marking the task as completed.', 'error');
				container.html(checkbox);
			}
		});
	});
};

// Count updating.

var getCount = function(callback) {
	$.ajax({
		url: '/ajax/count',
		success: callback
	});
};

var refreshDockBadge = function() {
	getCount(function(data) {
		window.fluid.dockBadge = data;
	});
};

var refreshSubnavCount = function() {
	getCount(function(data) {
		$('#subnav-bar ul li:first-child a').text('Pending ('+data+')');
	});
};

function set_message(msg, severity) {
	severity = severity ? severity : 'info';
	$('#flash-messages').append('
' + msg + '
');
}
<commit_msg>Hotfix: error in application.js<commit_after>$(document).ready(function() {
	initPolling();
	initTooltips();
	initDatePicker();
	initAutocomplete();
	initTaskCompletion();

	// Fluid-specific stuff.
	if (typeof window.fluid !== undefined) {
		refreshDockBadge();
	}
});

var initPolling = function() {
	var polling = $.cookie('taskwarrior-web-polling');
	if (polling) {
		var pollingInterval = startPolling();
	} else {
		$('#polling-info a').text('Start polling');
	}

	$('#polling-info a').click(function(e) {
		if (polling) {
			window.clearInterval(pollingInterval);
			polling = false;
			$(this).text('Start polling');
			$.cookie('taskwarrior-web-polling', null);
		} else {
			pollingInterval = startPolling();
			polling = true;
			$(this).text('Stop polling');
			$.cookie('taskwarrior-web-polling', true);
		}
		e.preventDefault();
	});
};

var startPolling = function() {
	var pollingInterval = window.setInterval('refreshPageContents()', 3000);
	return pollingInterval;
};

var refreshPageContents = function() {
	$.ajax({
		url: window.location,
		success: function(data) {
			$('#listing').replaceWith($('#listing', data));
			refreshSubnavCount();
			refreshDockBadge();
		}
	});
};

var initTooltips = function() {
	$('.tooltip').tipsy({
		title: 'data-tooltip',
		gravity: 's'
	});
};

var initDatePicker = function() {
	$('.datefield input').datepicker({
		dateFormat: $('.datefield input').data('format'),
		autoSize: true
	});
};

var initAutocomplete = function() {
	$('#task-project').autocomplete({
		source: '/ajax/projects'
	});

	$('#task-tags').tagsInput({
		autocomplete_url: '/ajax/tags',
		defaultText: ''
	});
};

var initTaskCompletion = function() {
	$('input.complete').click(function() {
		// Cache the checkbox in case we need to restore it.
		var container = $(this).parent();
		var checkbox = container.html();
		var row = $(this).closest('tr');
		container.html('');
		$.ajax({
			url: '/ajax/task-complete/' + $(this).data('task-id'),
			type: 'POST',
			success: function(data) {
				var message = (data === '') ? 'Task marked as completed.' : data;
				set_message(message, 'success');
				row.fadeOut();
			},
			error: function(data) {
				set_message('There was an error when marking the task as completed.', 'error');
				container.html(checkbox);
			}
		});
	});
};

// Count updating.

var getCount = function(callback) {
	$.ajax({
		url: '/ajax/count',
		success: callback
	});
};

var refreshDockBadge = function() {
	getCount(function(data) {
		window.fluid.dockBadge = data;
	});
};

var refreshSubnavCount = function() {
	getCount(function(data) {
		$('#subnav-bar ul li:first-child a').text('Pending ('+data+')');
	});
};

function set_message(msg, severity) {
	severity = severity ? severity : 'info';
	$('#flash-messages').append('
' + msg + '
');
}
<|endoftext|>


<commit_before>(() => {
    // Set to null to connect to regular game servers
    window.overrideIP = '127.0.0.1:5000';
    // window.overrideIP = null;
    let log = console.debug; // Can change to console.log if needed
    console.clear();
    if (localStorage['load_local_script']) {
        log('Local script loaded');
    }
    let init = () => {
        // The Socket.io script tag has loaded
        window.ioconn = window.io.connect;

        window.io.connect = function() { // The moomoo.io game client uses io.connect to establish a socket.io connection
            if (window.overrideIP) {
                arguments[0] = window.overrideIP;
            }
            if (!arguments[1] || !arguments[1]["query"]) {
                // The client always makes a connection with a query string, and this connection doesn't supply one.
                return ioconn.apply(this, arguments);
            } else {
                // The game client is attempting to connect to the Socket.io server
                var s = ioconn.apply(this, arguments);
                var socketEmit = s.emit;

                // Capture outgoing traffic
                s.emit = function() {
                    var packetType = arguments[0];
                    var mainData = arguments[1];
                    // There are also other arguments that are supplied based on the packet being sent...

                    switch (packetType) {
                        case "1":
                            // Spawn packet
                            log("Player spawn detected. name:", mainData.name);
                            break;
                        case "2":
                            // Angle packet
                            // Commented out because of spam
                            // log("Ange update", mainData);
                            break;
                        case "connect":
                            log('Connection handshake sent.');
                            break;
                        case "ping":
                            log('Ping!');
                            break;
                        case "pong":
                            log('Pong!');
                            break;
                        case "3":
                            var move = "";
                            switch(mainData) {
                                case "u":
                                    move = "Up";
                                    break;
                                case "d":
                                    move = "Down";
                                    break;
                                case "l":
                                    move = "Left";
                                    break;
                                case "r":
                                    move = "Right";
                                    break;
                            }
                            log('Move direction:', move, "isMoving:", !!arguments[2]);
                            break;
                        case "7":
                            log('Auto attack toggled');
                            break;
                        case "4":
                            log('Attacking:', !!mainData);
                            break;
                        case "rk":
                            log('Key reset');
                            break;
                        default:
                            log("Unknown outgoing packet with args", arguments);
                            break;
                    }
                    return socketEmit.apply(this, arguments); // Call the real emit
                }

                // Capture incoming traffic
                s.on('ch', (sid, msg) => {
                    // Chat message
                    log('Player with sid', sid, 'send message:', msg);
                });
                s.on('1', mySid => {
                    console.log('I recieved my SID:', mySid);
                });
                s.on('2', (data, isYou) => {
                    console.log('Add player', data, 'isYou', isYou);
                });
                // TODO: capture more incoming traffic

                return s;
            }
        }
    }
    window.addEventListener('load', init);
})();<commit_msg>Alert when there is a connection failure<commit_after>(() => {
    // Set to null to connect to regular game servers
    window.overrideIP = '127.0.0.1:5000';
    // window.overrideIP = null;
    let log = console.debug; // Can change to console.log if needed
    console.clear();
    if (localStorage['load_local_script']) {
        log('Local script loaded');
    }
    let init = () => {
        // The Socket.io script tag has loaded
        window.ioconn = window.io.connect;

        window.io.connect = function() { // The moomoo.io game client uses io.connect to establish a socket.io connection
            if (window.overrideIP) {
                arguments[0] = window.overrideIP;
            }
            if (!arguments[1] || !arguments[1]["query"]) {
                // The client always makes a connection with a query string, and this connection doesn't supply one.
                return ioconn.apply(this, arguments);
            } else {
                // The game client is attempting to connect to the Socket.io server
                var s = ioconn.apply(this, arguments);
                var socketEmit = s.emit;

                // Capture outgoing traffic
                s.emit = function() {
                    var packetType = arguments[0];
                    var mainData = arguments[1];
                    // There are also other arguments that are supplied based on the packet being sent...

                    switch (packetType) {
                        case "1":
                            // Spawn packet
                            log("Player spawn detected. name:", mainData.name);
                            break;
                        case "2":
                            // Angle packet
                            // Commented out because of spam
                            // log("Ange update", mainData);
                            break;
                        case "connect":
                            log('Connection handshake sent.');
                            break;
                        case "ping":
                            log('Ping!');
                            break;
                        case "pong":
                            log('Pong!');
                            break;
                        case "3":
                            var move = "";
                            switch(mainData) {
                                case "u":
                                    move = "Up";
                                    break;
                                case "d":
                                    move = "Down";
                                    break;
                                case "l":
                                    move = "Left";
                                    break;
                                case "r":
                                    move = "Right";
                                    break;
                            }
                            log('Move direction:', move, "isMoving:", !!arguments[2]);
                            break;
                        case "7":
                            log('Auto attack toggled');
                            break;
                        case "4":
                            log('Attacking:', !!mainData);
                            break;
                        case "rk":
                            log('Key reset');
                            break;
                        default:
                            log("Unknown outgoing packet with args", arguments);
                            break;
                    }
                    return socketEmit.apply(this, arguments); // Call the real emit
                }

                // Capture incoming traffic
                s.on('ch', (sid, msg) => {
                    // Chat message
                    log('Player with sid', sid, 'send message:', msg);
                });
                s.on('1', mySid => {
                    console.log('I recieved my SID:', mySid);
                });
                s.on('2', (data, isYou) => {
                    console.log('Add player', data, 'isYou', isYou);
                });
                s.on("connect_error", err => {
                    console.error(err);
                    alert("Server connection error:\n" + err.toString());
                });
                // TODO: capture more incoming traffic

                return s;
            }
        }
    }
    window.addEventListener('load', init);
})();<|endoftext|>


<commit_before>'use strict'

/**
 * @module serverless-plugin-warmup
 *
 * @see {@link https://serverless.com/framework/docs/providers/aws/guide/plugins/}
 *
 * @requires 'bluebird'
 * @requires 'fs-extra'
 * @requires 'path'
 * */
const BbPromise = require('bluebird')
const fs = BbPromise.promisifyAll(require('fs-extra'))
const path = require('path')

/**
 * @classdesc Keep your lambdas warm during Winter
 * @class WarmUP
 * */
class WarmUP {
  /**
   * @description Serverless Warm Up
   * @constructor
   *
   * @param {!Object} serverless - Serverless object
   * @param {!Object} options - Serverless options
   * */
  constructor (serverless, options) {
    /** Serverless variables */
    this.serverless = serverless
    this.options = options

    this.provider = this.serverless.getProvider('aws')

    this.hooks = {
      'after:package:initialize': this.afterPackageInitialize.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'after:deploy:deploy': this.afterDeployFunctions.bind(this)
    }
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @fulfil {} — Warm up set
   * @reject {Error} Warm up error
   *
   * @return {(boolean|Promise)}
   * */
  afterPackageInitialize () {
    // See https://github.com/serverless/serverless/issues/2631
    this.options.stage = this.options.stage ||
      this.serverless.service.provider.stage ||
      (this.serverless.service.defaults && this.serverless.service.defaults.stage) ||
      'dev'
    this.options.region = this.options.region ||
      this.serverless.service.provider.region ||
      (this.serverless.service.defaults && this.serverless.service.defaults.region) ||
      'us-east-1'

    this.custom = this.serverless.service.custom

    this.configPlugin()
    return this.createWarmer()
  }

  /**
   * @description After create deployment artifacts. Clean prefix folder.
   *
   * @fulfil {} — Optimization finished
   * @reject {Error} Optimization error
   *
   * @return {Promise}
   * */
  afterCreateDeploymentArtifacts () {
    return this.cleanFolder()
  }

  /**
   * @description After deploy functions hooks
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  afterDeployFunctions () {
    this.configPlugin()
    if (this.warmup.prewarm) {
      return this.warmUpFunctions()
    }
  }

  /**
   * @description Configure the plugin based on the context of serverless.yml
   *
   * @return {}
   * */
  configPlugin () {
    /** Set warm up folder, file and handler paths */
    this.folderName = '_warmup'
    if (this.custom && this.custom.warmup && typeof this.custom.warmup.folderName === 'string') {
      this.folderName = this.custom.warmup.folderName
    }
    this.pathFolder = this.getPath(this.folderName)
    this.pathFile = this.pathFolder + '/index.js'
    this.pathHandler = this.folderName + '/index.warmUp'

    /** Default options */
    this.warmup = {
      default: false,
      cleanFolder: true,
      memorySize: 128,
      name: this.serverless.service.service + '-' + this.options.stage + '-warmup-plugin',
      schedule: ['rate(5 minutes)'],
      timeout: 10,
      source: JSON.stringify({ source: 'serverless-plugin-warmup' }),
      prewarm: false,
      concurrency: 1
    }

    /** Set global custom options */
    if (!this.custom || !this.custom.warmup) {
      return
    }

    /** Default warmup */
    if (typeof this.custom.warmup.default !== 'undefined') {
      this.warmup.default = this.custom.warmup.default
    }

    /** Clean folder */
    if (typeof this.custom.warmup.cleanFolder === 'boolean') {
      this.warmup.cleanFolder = this.custom.warmup.cleanFolder
    }

    /** Memory size */
    if (typeof this.custom.warmup.memorySize === 'number') {
      this.warmup.memorySize = this.custom.warmup.memorySize
    }

    /** Function name */
    if (typeof this.custom.warmup.name === 'string') {
      this.warmup.name = this.custom.warmup.name
    }

    /** Role */
    if (typeof this.custom.warmup.role === 'string') {
      this.warmup.role = this.custom.warmup.role
    }

    /** Tags */
    if (typeof this.custom.warmup.tags === 'object') {
      this.warmup.tags = this.custom.warmup.tags
    }

    /** Schedule expression */
    if (typeof this.custom.warmup.schedule === 'string') {
      this.warmup.schedule = [this.custom.warmup.schedule]
    } else if (Array.isArray(this.custom.warmup.schedule)) {
      this.warmup.schedule = this.custom.warmup.schedule
    }

    /** Timeout */
    if (typeof this.custom.warmup.timeout === 'number') {
      this.warmup.timeout = this.custom.warmup.timeout
    }

    /** Source */
    if (typeof this.custom.warmup.source !== 'undefined') {
      this.warmup.source = this.custom.warmup.sourceRaw ? this.custom.warmup.source : JSON.stringify(this.custom.warmup.source)
    }

    /** Pre-warm */
    if (typeof this.custom.warmup.prewarm === 'boolean') {
      this.warmup.prewarm = this.custom.warmup.prewarm
    }

    /** Concurrency */
    if (typeof this.custom.warmup.concurrency === 'number') {
      this.warmup.concurrency = this.custom.warmup.concurrency
    }
  }

  /**
   * @description After create deployment artifacts
   *
   * @param {string} file — File path
   *
   * @return {String} Absolute file path
   * */
  getPath (file) {
    return path.join(this.serverless.config.servicePath, file)
  }

  /**
   * @description Clean prefix folder
   *
   * @fulfil {} — Folder cleaned
   * @reject {Error} File system error
   *
   * @return {Promise}
   * */
  cleanFolder () {
    if (!this.warmup.cleanFolder) {
      return Promise.resolve()
    }
    return fs.removeAsync(this.pathFolder)
  }

  /**
   * @description Warm up functions
   *
   * @fulfil {} — Warm up function created and added to service
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmer () {
    /** Get functions */
    const allFunctions = this.serverless.service.getAllFunctions()
    let functionConcurrency = {}

    /** Filter functions for warm up */
    return BbPromise.filter(allFunctions, (functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)

      const enable = (config) => config === true ||
        config === this.options.stage ||
        (Array.isArray(config) && config.indexOf(this.options.stage) !== -1)

      const functionConfig = functionObject.hasOwnProperty('warmup')
        ? functionObject.warmup
        : this.warmup.default

      /** Function needs to be warm */
      if (enable(functionConfig)) {
        const concurrency = functionObject.hasOwnProperty('warmup') && functionObject.warmup.hasOwnProperty('concurrency')
          ? functionObject.warmup.concurrency
          : this.warmup.concurrency
        functionConcurrency[functionName] = concurrency

        return true
      } else {
        return false
      }
    }).then((functionNames) => {
      /** Skip writing if no functions need to be warm */
      if (!functionNames.length) {
        /** Log no warmup */
        this.serverless.cli.log('WarmUP: no lambda to warm')
        return true
      }

      /** Write warm up function */
      return this.createWarmUpFunctionArtifact(functionNames, functionConcurrency)
    }).then((skip) => {
      /** Add warm up function to service */
      if (skip !== true) {
        return this.addWarmUpFunctionToService()
      }
    })
  }

  /**
   * @description Write warm up ES6 function
   *
   * @param {Array} functionNames - Function names
   *
   * @fulfil {} — Warm up function created
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmUpFunctionArtifact (functionNames, functionConcurrency) {
    /** Log warmup start */
    this.serverless.cli.log('WarmUP: setting ' + functionNames.length + ' lambdas to be warm')

    /** Get function names */
    functionNames = functionNames.map((functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)
      this.serverless.cli.log('WarmUP: ' + functionObject.name)
      return functionObject.name
    })

    const warmUpFunction = `"use strict";

/** Generated by Serverless WarmUP Plugin at ${new Date().toISOString()} */
const aws = require("aws-sdk");
aws.config.region = "${this.options.region}";
const lambda = new aws.Lambda();
const functionNames = ${JSON.stringify(functionNames)};
const functionConcurrency = ${JSON.stringify(functionConcurrency)};
module.exports.warmUp = async (event, context, callback) => {
  console.log("Warm Up Start");
  const invokes = await Promise.all(functionNames.map(async (functionName) => {
    let concurrency = functionConcurrency[functionName] > 0 ? functionConcurrency[functionName] : 1;
    let source = ${JSON.stringify(this.warmup.source)};
    let promises = [];

    for (let x = 0; x < concurrency; x++) {
      const params = {
        ClientContext: Buffer.from(JSON.stringify({"custom":source, "concurrencyIndex":x})).toString('base64'),
        FunctionName: functionName,
        InvocationType: "RequestResponse",
        LogType: "None",
        Qualifier: process.env.SERVERLESS_ALIAS || "$LATEST",
        Payload: source
      };

      promises.push(lambda.invoke(params).promise());
    }

    return Promise.all(promises).then(function(data) {
      console.log(\`Warm Up Invoke Success: \${functionName}\`, data);
      resolve(true);
    }, function(err) {
      console.log(\`Warm Up Invoke Error: \${functionName}\`, err);
      resolve(false);
    });
  }));

  console.log(\`Warm Up Finished with \${invokes.filter(r => !r).length} invoke errors\`);
}`

    /** Write warm up file */
    return fs.outputFileAsync(this.pathFile, warmUpFunction)
  }

  /**
   * @description Add warm up function to service
   *
   * @return {Object} Warm up service function object
   * */
  addWarmUpFunctionToService () {
    /** SLS warm up function */
    this.serverless.service.functions.warmUpPlugin = {
      description: 'Serverless WarmUP Plugin',
      events: this.warmup.schedule.map(schedule => ({ schedule })),
      handler: this.pathHandler,
      memorySize: this.warmup.memorySize,
      name: this.warmup.name,
      runtime: 'nodejs8.10',
      package: {
        individually: true,
        exclude: ['**'],
        include: [this.folderName + '/**']
      },
      timeout: this.warmup.timeout
    }

    if (this.warmup.role) {
      this.serverless.service.functions.warmUpPlugin.role = this.warmup.role
    }

    if (this.warmup.tags) {
      this.serverless.service.functions.warmUpPlugin.tags = this.warmup.tags
    }

    /** Return service function object */
    return this.serverless.service.functions.warmUpPlugin
  }

  /**
   * @description Warm up the functions immediately after deployment
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  warmUpFunctions () {
    this.serverless.cli.log('WarmUP: Pre-warming up your functions')

    const params = {
      FunctionName: this.warmup.name,
      InvocationType: 'RequestResponse',
      LogType: 'None',
      Qualifier: process.env.SERVERLESS_ALIAS || '$LATEST',
      Payload: this.warmup.source
    }

    return this.provider.request('Lambda', 'invoke', params)
      .then(data => this.serverless.cli.log('WarmUp: Functions sucessfuly pre-warmed'))
      .catch(error => this.serverless.cli.log('WarmUp: Error while pre-warming functions', error))
  }
}

/** Export WarmUP class */
module.exports = WarmUP
<commit_msg>Fixed mapping of concurrency setting to full function name.<commit_after>'use strict'

/**
 * @module serverless-plugin-warmup
 *
 * @see {@link https://serverless.com/framework/docs/providers/aws/guide/plugins/}
 *
 * @requires 'bluebird'
 * @requires 'fs-extra'
 * @requires 'path'
 * */
const BbPromise = require('bluebird')
const fs = BbPromise.promisifyAll(require('fs-extra'))
const path = require('path')

/**
 * @classdesc Keep your lambdas warm during Winter
 * @class WarmUP
 * */
class WarmUP {
  /**
   * @description Serverless Warm Up
   * @constructor
   *
   * @param {!Object} serverless - Serverless object
   * @param {!Object} options - Serverless options
   * */
  constructor (serverless, options) {
    /** Serverless variables */
    this.serverless = serverless
    this.options = options

    this.provider = this.serverless.getProvider('aws')

    this.hooks = {
      'after:package:initialize': this.afterPackageInitialize.bind(this),
      'after:package:createDeploymentArtifacts': this.afterCreateDeploymentArtifacts.bind(this),
      'after:deploy:deploy': this.afterDeployFunctions.bind(this)
    }
  }

  /**
   * @description After package initialize hook. Create warmer function and add it to the service.
   *
   * @fulfil {} — Warm up set
   * @reject {Error} Warm up error
   *
   * @return {(boolean|Promise)}
   * */
  afterPackageInitialize () {
    // See https://github.com/serverless/serverless/issues/2631
    this.options.stage = this.options.stage ||
      this.serverless.service.provider.stage ||
      (this.serverless.service.defaults && this.serverless.service.defaults.stage) ||
      'dev'
    this.options.region = this.options.region ||
      this.serverless.service.provider.region ||
      (this.serverless.service.defaults && this.serverless.service.defaults.region) ||
      'us-east-1'

    this.custom = this.serverless.service.custom

    this.configPlugin()
    return this.createWarmer()
  }

  /**
   * @description After create deployment artifacts. Clean prefix folder.
   *
   * @fulfil {} — Optimization finished
   * @reject {Error} Optimization error
   *
   * @return {Promise}
   * */
  afterCreateDeploymentArtifacts () {
    return this.cleanFolder()
  }

  /**
   * @description After deploy functions hooks
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  afterDeployFunctions () {
    this.configPlugin()
    if (this.warmup.prewarm) {
      return this.warmUpFunctions()
    }
  }

  /**
   * @description Configure the plugin based on the context of serverless.yml
   *
   * @return {}
   * */
  configPlugin () {
    /** Set warm up folder, file and handler paths */
    this.folderName = '_warmup'
    if (this.custom && this.custom.warmup && typeof this.custom.warmup.folderName === 'string') {
      this.folderName = this.custom.warmup.folderName
    }
    this.pathFolder = this.getPath(this.folderName)
    this.pathFile = this.pathFolder + '/index.js'
    this.pathHandler = this.folderName + '/index.warmUp'

    /** Default options */
    this.warmup = {
      default: false,
      cleanFolder: true,
      memorySize: 128,
      name: this.serverless.service.service + '-' + this.options.stage + '-warmup-plugin',
      schedule: ['rate(5 minutes)'],
      timeout: 10,
      source: JSON.stringify({ source: 'serverless-plugin-warmup' }),
      prewarm: false,
      concurrency: 1
    }

    /** Set global custom options */
    if (!this.custom || !this.custom.warmup) {
      return
    }

    /** Default warmup */
    if (typeof this.custom.warmup.default !== 'undefined') {
      this.warmup.default = this.custom.warmup.default
    }

    /** Clean folder */
    if (typeof this.custom.warmup.cleanFolder === 'boolean') {
      this.warmup.cleanFolder = this.custom.warmup.cleanFolder
    }

    /** Memory size */
    if (typeof this.custom.warmup.memorySize === 'number') {
      this.warmup.memorySize = this.custom.warmup.memorySize
    }

    /** Function name */
    if (typeof this.custom.warmup.name === 'string') {
      this.warmup.name = this.custom.warmup.name
    }

    /** Role */
    if (typeof this.custom.warmup.role === 'string') {
      this.warmup.role = this.custom.warmup.role
    }

    /** Tags */
    if (typeof this.custom.warmup.tags === 'object') {
      this.warmup.tags = this.custom.warmup.tags
    }

    /** Schedule expression */
    if (typeof this.custom.warmup.schedule === 'string') {
      this.warmup.schedule = [this.custom.warmup.schedule]
    } else if (Array.isArray(this.custom.warmup.schedule)) {
      this.warmup.schedule = this.custom.warmup.schedule
    }

    /** Timeout */
    if (typeof this.custom.warmup.timeout === 'number') {
      this.warmup.timeout = this.custom.warmup.timeout
    }

    /** Source */
    if (typeof this.custom.warmup.source !== 'undefined') {
      this.warmup.source = this.custom.warmup.sourceRaw ? this.custom.warmup.source : JSON.stringify(this.custom.warmup.source)
    }

    /** Pre-warm */
    if (typeof this.custom.warmup.prewarm === 'boolean') {
      this.warmup.prewarm = this.custom.warmup.prewarm
    }

    /** Concurrency */
    if (typeof this.custom.warmup.concurrency === 'number') {
      this.warmup.concurrency = this.custom.warmup.concurrency
    }
  }

  /**
   * @description After create deployment artifacts
   *
   * @param {string} file — File path
   *
   * @return {String} Absolute file path
   * */
  getPath (file) {
    return path.join(this.serverless.config.servicePath, file)
  }

  /**
   * @description Clean prefix folder
   *
   * @fulfil {} — Folder cleaned
   * @reject {Error} File system error
   *
   * @return {Promise}
   * */
  cleanFolder () {
    if (!this.warmup.cleanFolder) {
      return Promise.resolve()
    }
    return fs.removeAsync(this.pathFolder)
  }

  /**
   * @description Warm up functions
   *
   * @fulfil {} — Warm up function created and added to service
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmer () {
    /** Get functions */
    const allFunctions = this.serverless.service.getAllFunctions()
    let functionConcurrency = {}

    /** Filter functions for warm up */
    return BbPromise.filter(allFunctions, (functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)

      const enable = (config) => config === true ||
        config === this.options.stage ||
        (Array.isArray(config) && config.indexOf(this.options.stage) !== -1)

      const functionConfig = functionObject.hasOwnProperty('warmup')
        ? functionObject.warmup
        : this.warmup.default

      /** Function needs to be warm */
      if (enable(functionConfig)) {
        const concurrency = functionObject.hasOwnProperty('warmup') && functionObject.warmup.hasOwnProperty('concurrency')
          ? functionObject.warmup.concurrency
          : this.warmup.concurrency
        functionConcurrency[functionName] = concurrency

        return true
      } else {
        return false
      }
    }).then((functionNames) => {
      /** Skip writing if no functions need to be warm */
      if (!functionNames.length) {
        /** Log no warmup */
        this.serverless.cli.log('WarmUP: no lambda to warm')
        return true
      }

      /** Write warm up function */
      return this.createWarmUpFunctionArtifact(functionNames, functionConcurrency)
    }).then((skip) => {
      /** Add warm up function to service */
      if (skip !== true) {
        return this.addWarmUpFunctionToService()
      }
    })
  }

  /**
   * @description Write warm up ES6 function
   *
   * @param {Array} functionNames - Function names
   *
   * @fulfil {} — Warm up function created
   * @reject {Error} Warm up error
   *
   * @return {Promise}
   * */
  createWarmUpFunctionArtifact (functionNames, functionConcurrency) {
    /** Log warmup start */
    this.serverless.cli.log('WarmUP: setting ' + functionNames.length + ' lambdas to be warm')

    /** Get function names */
    let fullFunctionConcurrency = {}
    functionNames = functionNames.map((functionName) => {
      const functionObject = this.serverless.service.getFunction(functionName)
      this.serverless.cli.log('WarmUP: ' + functionObject.name)
      fullFunctionConcurrency[functionObject.name] = functionConcurrency[functionName]
      return functionObject.name
    })

    const warmUpFunction = `"use strict";

/** Generated by Serverless WarmUP Plugin at ${new Date().toISOString()} */
const aws = require("aws-sdk");
aws.config.region = "${this.options.region}";
const lambda = new aws.Lambda();
const functionNames = ${JSON.stringify(functionNames)};
const functionConcurrency = ${JSON.stringify(fullFunctionConcurrency)};
module.exports.warmUp = async (event, context, callback) => {
  console.log("Warm Up Start");
  const invokes = await Promise.all(functionNames.map(async (functionName) => {
    let concurrency = functionConcurrency[functionName] > 0 ? functionConcurrency[functionName] : 1;
    let source = ${JSON.stringify(this.warmup.source)};
    let promises = [];

    for (let x = 0; x < concurrency; x++) {
      const params = {
        ClientContext: Buffer.from(JSON.stringify({"custom":source, "concurrencyIndex":x})).toString('base64'),
        FunctionName: functionName,
        InvocationType: "RequestResponse",
        LogType: "None",
        Qualifier: process.env.SERVERLESS_ALIAS || "$LATEST",
        Payload: source
      };

      promises.push(lambda.invoke(params).promise());
    }

    return Promise.all(promises).then(function(data) {
      console.log(\`Warm Up Invoke Success: \${functionName}\`, data);
      resolve(true);
    }, function(err) {
      console.log(\`Warm Up Invoke Error: \${functionName}\`, err);
      resolve(false);
    });
  }));

  console.log(\`Warm Up Finished with \${invokes.filter(r => !r).length} invoke errors\`);
}`

    /** Write warm up file */
    return fs.outputFileAsync(this.pathFile, warmUpFunction)
  }

  /**
   * @description Add warm up function to service
   *
   * @return {Object} Warm up service function object
   * */
  addWarmUpFunctionToService () {
    /** SLS warm up function */
    this.serverless.service.functions.warmUpPlugin = {
      description: 'Serverless WarmUP Plugin',
      events: this.warmup.schedule.map(schedule => ({ schedule })),
      handler: this.pathHandler,
      memorySize: this.warmup.memorySize,
      name: this.warmup.name,
      runtime: 'nodejs8.10',
      package: {
        individually: true,
        exclude: ['**'],
        include: [this.folderName + '/**']
      },
      timeout: this.warmup.timeout
    }

    if (this.warmup.role) {
      this.serverless.service.functions.warmUpPlugin.role = this.warmup.role
    }

    if (this.warmup.tags) {
      this.serverless.service.functions.warmUpPlugin.tags = this.warmup.tags
    }

    /** Return service function object */
    return this.serverless.service.functions.warmUpPlugin
  }

  /**
   * @description Warm up the functions immediately after deployment
   *
   * @fulfil {} — Functions warmed up sucessfuly
   * @reject {Error} Functions couldn't be warmed up
   *
   * @return {Promise}
   * */
  warmUpFunctions () {
    this.serverless.cli.log('WarmUP: Pre-warming up your functions')

    const params = {
      FunctionName: this.warmup.name,
      InvocationType: 'RequestResponse',
      LogType: 'None',
      Qualifier: process.env.SERVERLESS_ALIAS || '$LATEST',
      Payload: this.warmup.source
    }

    return this.provider.request('Lambda', 'invoke', params)
      .then(data => this.serverless.cli.log('WarmUp: Functions sucessfuly pre-warmed'))
      .catch(error => this.serverless.cli.log('WarmUp: Error while pre-warming functions', error))
  }
}

/** Export WarmUP class */
module.exports = WarmUP
<|endoftext|>