<commit_before>var net = require('net');
var clc = require('cli-color');
var Jetty = require("jetty");
var jetty = new Jetty(process.stdout);
var notifier = require('node-notifier');

var level = {
  info: clc.blue,
  error: clc.red,
  ok: clc.green,
  warning: clc.yellow
}

function repeat(interval, fn) {
  fn();
  setTimeout(repeat.bind(undefined, interval, fn), interval);
}

function slice(string, length) {
  var s = string.substring(0, length);
  return new String(new Array(length).join(" ") + s).slice(s.length)
}

function fill(string, length) {
  var diff = length - string.length;
  return string + new Array(diff).join("-");
}

function compareState(a, b) {
  if (a.name > b.name) {
    return 1;
  }
  if (a.name < b.name) {
    return -1;
  }
  return 0;
}

function printStatus(connectionState) {
  jetty.clear();
  jetty.moveTo([0,0]);
  var groups = {};
  for (var value of connectionState.values()) {
    if (!groups[value.group]) {
      groups[value.group] = [];
    }
    groups[value.group].push(value);
  }
  Object.getOwnPropertyNames(groups).sort().forEach(function (group) {
    jetty.text(fill("----- " + group + " -", 63) + "\n");
    groups[group].sort(compareState).forEach(function (state) {
      jetty.text(slice(state.name, 30) + " - " + level[state.level](slice(state.status, 30)));
      jetty.text('\n');
    });
  });
}

function createStateObject(msg, c) {
  var state = JSON.parse(msg);
  if (!state.name) {
    state.name = c.remoteAddress;
  }
  if (!state.level) {
    state.level = "info";
  }
  if (!state.status) {
    state.status = "unknown";
    state.level = "warning";
  }
  if (!state.group) {
    state.group = "no group";
  }
  return state;
}

function notify(state) {
  if (state.notify) {
    notifier.notify({
      title: state.name,
      message: state.status,
      sound: true,
      wait: true
    }, function (err, response) {
    });
  }
}

function handleBuffer(buffer, c, connectionState) {
  var index = buffer.indexOf("}");
  if (index !== -1) {
    var msg = buffer.substring(0, index + 1);
    buffer = buffer.substring(index + 1);
    try {
      var state = createStateObject(msg, c);
      connectionState.set(c, state);
      notify(state);
    } catch (e) {
      // ignore invalid messages
    }
    return handleBuffer(buffer, c);
  } else {
    return buffer;
  }
}

function start(port) {
  var connectionState = new Map();

  var server = net.createServer(function(c) {
    connectionState.set(c, {
      name: "Client connected",
      status: "Waiting...",
      level: "warning",
      group: "no group"
    });
    var buffer = "";
    c.on('end', function() {
      setTimeout(function() {
        connectionState.delete(c);
      }, 10000);
    });
    c.on('data', function(data) {
      buffer = handleBuffer(buffer + data.toString(), c, connectionState);
    });
  });
  server.listen(port, function() {
    console.log('Server started...');
  });
  repeat(this.refresh, printStatus.bind(undefined, connectionState));
}

module.exports = function(flags) {
  this.refresh = 2000;
  if (flags) {
    if (flags.refresh) {
      this.refresh = flags.refresh;
      console.log("Use " + this.refresh);
    }
  }
  this.startServer = start;
}<commit_msg>Save notify flag<commit_after>var net = require('net');
var clc = require('cli-color');
var Jetty = require("jetty");
var jetty = new Jetty(process.stdout);
var notifier = require('node-notifier');

var level = {
  info: clc.blue,
  error: clc.red,
  ok: clc.green,
  warning: clc.yellow
}

function repeat(interval, fn) {
  fn();
  setTimeout(repeat.bind(undefined, interval, fn), interval);
}

function slice(string, length) {
  var s = string.substring(0, length);
  return new String(new Array(length).join(" ") + s).slice(s.length)
}

function fill(string, length) {
  var diff = length - string.length;
  return string + new Array(diff).join("-");
}

function compareState(a, b) {
  if (a.name > b.name) {
    return 1;
  }
  if (a.name < b.name) {
    return -1;
  }
  return 0;
}

function printStatus(connectionState) {
  jetty.clear();
  jetty.moveTo([0,0]);
  var groups = {};
  for (var value of connectionState.values()) {
    if (!groups[value.group]) {
      groups[value.group] = [];
    }
    groups[value.group].push(value);
  }
  Object.getOwnPropertyNames(groups).sort().forEach(function (group) {
    jetty.text(fill("----- " + group + " -", 63) + "\n");
    groups[group].sort(compareState).forEach(function (state) {
      jetty.text(slice(state.name, 30) + " - " + level[state.level](slice(state.status, 30)));
      jetty.text('\n');
    });
  });
}

function createStateObject(msg, c) {
  var state = JSON.parse(msg);
  if (!state.name) {
    state.name = c.remoteAddress;
  }
  if (!state.level) {
    state.level = "info";
  }
  if (!state.status) {
    state.status = "unknown";
    state.level = "warning";
  }
  if (!state.group) {
    state.group = "no group";
  }
  return state;
}

function notify(state) {
  if (state.notify) {
    notifier.notify({
      title: state.name,
      message: state.status,
      sound: true,
      wait: true
    }, function (err, response) {
    });
  }
}

function handleBuffer(buffer, c, connectionState) {
  var index = buffer.indexOf("}");
  if (index !== -1) {
    var msg = buffer.substring(0, index + 1);
    buffer = buffer.substring(index + 1);
    try {
      var state = createStateObject(msg, c);
      connectionState.set(c, state);
      notify(state);
    } catch (e) {
      // ignore invalid messages
    }
    return handleBuffer(buffer, c);
  } else {
    return buffer;
  }
}

function start(port) {
  var connectionState = new Map();

  var server = net.createServer(function(c) {
    connectionState.set(c, {
      name: "Client connected",
      status: "Waiting...",
      level: "warning",
      group: "no group"
    });
    var buffer = "";
    c.on('end', function() {
      setTimeout(function() {
        connectionState.delete(c);
      }, 10000);
    });
    c.on('data', function(data) {
      buffer = handleBuffer(buffer + data.toString(), c, connectionState);
    });
  });
  server.listen(port, function() {
    console.log('Server started...');
  });
  repeat(this.refresh, printStatus.bind(undefined, connectionState));
}

module.exports = function(flags) {
  this.refresh = 2000;
  if (flags) {
    if (flags.refresh) {
      this.refresh = flags.refresh;
    }
    if (flags.notify) {
      this.notify = flags.notify;
    }
  }
  this.startServer = start;
}
<|endoftext|>


<commit_before>(function() {

var $clicked = $(null);
var searchTimeout = null;
var searchCache = [];
var caseSensitiveMatch = false;
var ignoreKeyCodeMin = 8;
var ignoreKeyCodeMax = 46;
var commandKey = 91;

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function escapeShortcut() {
  $(document).keydown(function(evt) {
    if (evt.which == 27) {
      window.parent.postMessage('navEscape', '*');
    }
  });
}

function navResizer() {
  $(window).mousemove(function(e) {
    window.parent.postMessage({
      action: 'mousemove', event: {pageX: e.pageX, which: e.which}
    }, '*');
  }).mouseup(function(e) {
    window.parent.postMessage({action: 'mouseup'}, '*');
  });
  window.parent.postMessage("navReady", "*");
}

function clearSearchTimeout() {
  clearTimeout(searchTimeout);
  searchTimeout = null;
}

function enableLinks() {
  // load the target page in the parent window
  $('#full_list li').on('click', function(evt) {
    $('#full_list li').removeClass('clicked');
    $clicked = $(this);
    $clicked.addClass('clicked');

    if (evt.target.tagName === 'A') return true;

    var elem = $clicked.find('> .item .object_link a')[0];
    var e = evt.originalEvent;
    var newEvent = new MouseEvent(evt.originalEvent.type);
    newEvent.initMouseEvent(e.type, e.canBubble, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
    elem.dispatchEvent(newEvent);
  });
}

function enableToggles() {
  // show/hide nested classes on toggle click
  $('#full_list a.toggle').on('click', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    $(this).parent().parent().toggleClass('collapsed');
    highlight();
  });
}

function populateSearchCache() {
  $('#full_list li .item').each(function() {
    var $node = $(this);
    var $link = $node.find('.object_link a');
    if ($link.length > 0) {
      searchCache.push({
        node: $node,
        link: $link,
        name: $link.text(),
        fullName: $link.attr('title').split(' ')[0]
      });
    }
  });
}

function enableSearch() {
  $('#search input').keyup(function(event) {
    if (ignoredKeyPress(event)) return;
    if (this.value === "") {
      clearSearch();
    } else {
      performSearch(this.value);
    }
  });

  $('#full_list').after("

");
}

function ignoredKeyPress(event) {
  if (
    (event.keyCode > ignoreKeyCodeMin && event.keyCode < ignoreKeyCodeMax) ||
    (event.keyCode == commandKey)
  ) {
    return true;
  } else {
    return false;
  }
}

function clearSearch() {
  clearSearchTimeout();
  $('#full_list .found').removeClass('found').each(function() {
    var $link = $(this).find('.object_link a');
    $link.text($link.text());
  });
  $('#full_list, #content').removeClass('insearch');
  $clicked.parents().removeClass('collapsed');
  highlight();
}

function performSearch(searchString) {
  clearSearchTimeout();
  $('#full_list, #content').addClass('insearch');
  $('#noresults').text('').hide();
  partialSearch(searchString, 0);
}

function partialSearch(searchString, offset) {
  var lastRowClass = '';
  var i = null;
  for (i = offset; i < Math.min(offset + 50, searchCache.length); i++) {
    var item = searchCache[i];
    var searchName = (searchString.indexOf('::') != -1 ? item.fullName : item.name);
    var matchString = buildMatchString(searchString);
    var matchRegexp = new RegExp(matchString, caseSensitiveMatch ? "" : "i");
    if (searchName.match(matchRegexp) == null) {
      item.node.removeClass('found');
      item.link.text(item.link.text());
    }
    else {
      item.node.addClass('found');
      item.node.removeClass(lastRowClass).addClass(lastRowClass == 'r1' ? 'r2' : 'r1');
      lastRowClass = item.node.hasClass('r1') ? 'r1' : 'r2';
      item.link.html(item.name.replace(matchRegexp, "$&"));
    }
  }
  if(i == searchCache.length) {
    searchDone();
  } else {
    searchTimeout = setTimeout(function() {
      partialSearch(searchString, i);
    }, 0);
  }
}

function searchDone() {
  searchTimeout = null;
  highlight();
  if ($('#full_list li:visible').size() === 0) {
    $('#noresults').text('No results were found.').hide().fadeIn();
  } else {
    $('#noresults').text('').hide();
  }
  $('#content').removeClass('insearch');
}

function buildMatchString(searchString, event) {
  caseSensitiveMatch = searchString.match(/[A-Z]/) != null;
  var regexSearchString = RegExp.escape(searchString);
  if (caseSensitiveMatch) {
    regexSearchString += "|" +
      $.map(searchString.split(''), function(e) { return RegExp.escape(e); }).
      join('.+?');
  }
  return regexSearchString;
}

function highlight() {
  $('#full_list li:visible').each(function(n) {
    $(this).removeClass('even odd').addClass(n % 2 == 0 ? 'odd' : 'even');
  });
}

/**
 * Expands the tree to the target element and its immediate
 * children.
 */
function expandTo(path) {
  var $target = $(document.getElementById('object_' + path));
  $target.addClass('clicked');
  $target.removeClass('collapsed');
  $target.parentsUntil('#full_list', 'li').removeClass('collapsed');
  if($target[0]) {
    window.scrollTo(window.scrollX, $target.offset().top - 250);
    highlight();
  }
}

function windowEvents(event) {
  var msg = event.data;
  if (msg.action === "expand") {
    expandTo(msg.path);
  }
  return false;
}

window.addEventListener("message", windowEvents, false);

$(document).ready(function() {
  escapeShortcut();
  navResizer();
  enableLinks();
  enableToggles();
  populateSearchCache();
  enableSearch();
});

})();
<commit_msg>Stop propagation of original event<commit_after>(function() {

var $clicked = $(null);
var searchTimeout = null;
var searchCache = [];
var caseSensitiveMatch = false;
var ignoreKeyCodeMin = 8;
var ignoreKeyCodeMax = 46;
var commandKey = 91;

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

function escapeShortcut() {
  $(document).keydown(function(evt) {
    if (evt.which == 27) {
      window.parent.postMessage('navEscape', '*');
    }
  });
}

function navResizer() {
  $(window).mousemove(function(e) {
    window.parent.postMessage({
      action: 'mousemove', event: {pageX: e.pageX, which: e.which}
    }, '*');
  }).mouseup(function(e) {
    window.parent.postMessage({action: 'mouseup'}, '*');
  });
  window.parent.postMessage("navReady", "*");
}

function clearSearchTimeout() {
  clearTimeout(searchTimeout);
  searchTimeout = null;
}

function enableLinks() {
  // load the target page in the parent window
  $('#full_list li').on('click', function(evt) {
    $('#full_list li').removeClass('clicked');
    $clicked = $(this);
    $clicked.addClass('clicked');

    if (evt.target.tagName === 'A') return true;

    var elem = $clicked.find('> .item .object_link a')[0];
    var e = evt.originalEvent;
    var newEvent = new MouseEvent(evt.originalEvent.type);
    newEvent.initMouseEvent(e.type, e.canBubble, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
    elem.dispatchEvent(newEvent);
    evt.preventDefault();
    evt.stopPropagation();
    return false;
  });
}

function enableToggles() {
  // show/hide nested classes on toggle click
  $('#full_list a.toggle').on('click', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    $(this).parent().parent().toggleClass('collapsed');
    highlight();
  });
}

function populateSearchCache() {
  $('#full_list li .item').each(function() {
    var $node = $(this);
    var $link = $node.find('.object_link a');
    if ($link.length > 0) {
      searchCache.push({
        node: $node,
        link: $link,
        name: $link.text(),
        fullName: $link.attr('title').split(' ')[0]
      });
    }
  });
}

function enableSearch() {
  $('#search input').keyup(function(event) {
    if (ignoredKeyPress(event)) return;
    if (this.value === "") {
      clearSearch();
    } else {
      performSearch(this.value);
    }
  });

  $('#full_list').after("

");
}

function ignoredKeyPress(event) {
  if (
    (event.keyCode > ignoreKeyCodeMin && event.keyCode < ignoreKeyCodeMax) ||
    (event.keyCode == commandKey)
  ) {
    return true;
  } else {
    return false;
  }
}

function clearSearch() {
  clearSearchTimeout();
  $('#full_list .found').removeClass('found').each(function() {
    var $link = $(this).find('.object_link a');
    $link.text($link.text());
  });
  $('#full_list, #content').removeClass('insearch');
  $clicked.parents().removeClass('collapsed');
  highlight();
}

function performSearch(searchString) {
  clearSearchTimeout();
  $('#full_list, #content').addClass('insearch');
  $('#noresults').text('').hide();
  partialSearch(searchString, 0);
}

function partialSearch(searchString, offset) {
  var lastRowClass = '';
  var i = null;
  for (i = offset; i < Math.min(offset + 50, searchCache.length); i++) {
    var item = searchCache[i];
    var searchName = (searchString.indexOf('::') != -1 ? item.fullName : item.name);
    var matchString = buildMatchString(searchString);
    var matchRegexp = new RegExp(matchString, caseSensitiveMatch ? "" : "i");
    if (searchName.match(matchRegexp) == null) {
      item.node.removeClass('found');
      item.link.text(item.link.text());
    }
    else {
      item.node.addClass('found');
      item.node.removeClass(lastRowClass).addClass(lastRowClass == 'r1' ? 'r2' : 'r1');
      lastRowClass = item.node.hasClass('r1') ? 'r1' : 'r2';
      item.link.html(item.name.replace(matchRegexp, "$&"));
    }
  }
  if(i == searchCache.length) {
    searchDone();
  } else {
    searchTimeout = setTimeout(function() {
      partialSearch(searchString, i);
    }, 0);
  }
}

function searchDone() {
  searchTimeout = null;
  highlight();
  if ($('#full_list li:visible').size() === 0) {
    $('#noresults').text('No results were found.').hide().fadeIn();
  } else {
    $('#noresults').text('').hide();
  }
  $('#content').removeClass('insearch');
}

function buildMatchString(searchString, event) {
  caseSensitiveMatch = searchString.match(/[A-Z]/) != null;
  var regexSearchString = RegExp.escape(searchString);
  if (caseSensitiveMatch) {
    regexSearchString += "|" +
      $.map(searchString.split(''), function(e) { return RegExp.escape(e); }).
      join('.+?');
  }
  return regexSearchString;
}

function highlight() {
  $('#full_list li:visible').each(function(n) {
    $(this).removeClass('even odd').addClass(n % 2 == 0 ? 'odd' : 'even');
  });
}

/**
 * Expands the tree to the target element and its immediate
 * children.
 */
function expandTo(path) {
  var $target = $(document.getElementById('object_' + path));
  $target.addClass('clicked');
  $target.removeClass('collapsed');
  $target.parentsUntil('#full_list', 'li').removeClass('collapsed');
  if($target[0]) {
    window.scrollTo(window.scrollX, $target.offset().top - 250);
    highlight();
  }
}

function windowEvents(event) {
  var msg = event.data;
  if (msg.action === "expand") {
    expandTo(msg.path);
  }
  return false;
}

window.addEventListener("message", windowEvents, false);

$(document).ready(function() {
  escapeShortcut();
  navResizer();
  enableLinks();
  enableToggles();
  populateSearchCache();
  enableSearch();
});

})();
<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');
const _ = require('lodash');
const R = require('ramda');

/**
 * Polifill
 */
if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}
/**
 * Lib
 */

function getImageAgeDays(timestamp) {

  const y = parseInt(timestamp.split('-')[0]);
  const m = parseInt(timestamp.split('-')[1]) - 1;
  const d = parseInt(timestamp.split('-')[2].split('T')[0]);
  const h = parseInt(timestamp.split('T')[1].split(':')[0]);

  const age = Date.now() - Date.UTC(y, m, d, h);
  const days = 1000 * 60 * 60 * 24;
  return (Math.round(age / days));
}

exports.getRepoImages = (config, ecr, ecs) => {
  var params = {
    repositoryName: config.REPO_TO_CLEAN
  };
  return ecr.listImagesAsync(params);
};

// Takes an argument of an array of full image definitions
//   and splits into tags to delete from the REPO_TO_CLEAN repo
exports.deleteImages = (config, ecr, ecs) => images => {
  return new Promise(function(resolve) {
    console.info('IMAGES TO DELETE:', images);
    var imageTagsToDelete = _.map(images, function(image) {
      return { imageTag: image.split(':')[1] };
    });

    console.info('IMAGE TAGS TO DELETE:', imageTagsToDelete);

    // Make sure we are doing this for real
    if (config.DRY_RUN !== true) {
      if (imageTagsToDelete.length > 0) {
        const params = {
          imageIds: imageTagsToDelete,
          repositoryName: config.REPO_TO_CLEAN
        };

        // Batch delete all images in the deletionQueue
        ecr.batchDeleteImageAsync(params)
          .then(function(deletions) {
            resolve({
              failures: deletions.failures,
              imagesDeleted: deletions.imageIds,
              count: _.keys(deletions.imageIds)
                .length
            });
          });
      } else {
        resolve({
          failures: [],
          imagesDeleted: [],
          count: 0
        });
      }
    } else {
      // Fake Results
      resolve({
        dryRun: true,
        failures: [],
        imagesDeleted: imageTagsToDelete,
        count: imageTagsToDelete.length
      });
    }
  });
};

// Goes through all of ECS in a particular region and determines what is still
// marked as active and in use containers at a Task level (not actual running tasks)
exports.filterOutActiveImages = (config, ecr, ecs) => eligibleForDeletion => {
  console.info('BEFORE FILTER:', eligibleForDeletion);

  return ecs.listTaskDefinitionsAsync({ status: 'ACTIVE' })
    .then(function(taskDefs) {
      return new Promise(function(resolve) {
        Promise.map(taskDefs.taskDefinitionArns, function(taskDefinitionARN) {

            // Get all active images from all container defintions
            return ecs.describeTaskDefinitionAsync({ taskDefinition: taskDefinitionARN })
              .then(function(taskDefinitionDetails) {
                return _.chain(taskDefinitionDetails)
                  .map(function(taskDefinitionDetail) {
                    return taskDefinitionDetail.containerDefinitions;
                  })
                  .map(function(containerDefinition) {
                    return _.map(containerDefinition, 'image');
                  })
                  .value();
              });
          })
          .then(resolve);
      });
    })
    .then(function(allImages) {
      // Then reduce the big array and reduce to uniq values
      const activeImages = _.chain(allImages)
        .flattenDeep()
        .uniq()
        .value();
      console.log('ACTIVE IMAGES:', activeImages);

      // Remove images from deletion that are active
      return _.difference(eligibleForDeletion, activeImages);
    });
};

// Fetch all layers / image details from the repo
// Filter out everything newer than some variable amount of days
// set via REPO_AGE_THRESHOLD (90 days by default)
exports.filterImagesByDateThreshold = (config, ecr, ecs) => images => {
  console.info('IMAGES TO PROCESS (filterImagesByDateThreshold):', images);
  const params = {
    imageIds: images.imageIds,
    repositoryName: config.REPO_TO_CLEAN
  };

  return ecr.describeImagesAsync(params)
    .then(function(imageDetails) {
      // Get all tags eligible for deletion by age threshold
      // coerce each of the tags to a full image reference for easy comparison
      return imageDetails
        .map(image => {

          const created = image.imagePushedAt
          const imageTag = (image.imageTags || [])[0] || '';

          if (created &&
            imageTag !== 'latest' &&
            getImageAgeDays(created) >= config.REPO_AGE_THRESHOLD) {
            return config.AWS_ACCOUNT_ID + '.dkr.ecr.' + config.REGION + '.amazonaws.com/' +
              config.REPO_TO_CLEAN + ':' + imageTag;
          } else {
            return null;
          }
        })
        .filter(image => image != null);

    });
};
// Fetch all layers / image details from the repo
// Filter out everything newer than some variable amount of days
// set via REPO_AGE_THRESHOLD (90 days by default)
exports.filterImagesByFirstN = (config, ecr, ecs) => images => {
  console.info('IMAGES TO PROCESS (filterImagesByFirstN):', images);
  const sortByFirstItem = R.sortBy(R.prop(0));
  const byEnv = R.groupBy(image => {
    const tag = image[1];
    for (let i = 0; i < config.ENVS.length; i++) {
      if (tag.includes(config.ENVS[i])) {
        return config.ENVS[i]
      }
    }
    return tag;
  });
  const params = {
    imageIds: images.imageIds,
    repositoryName: config.REPO_TO_CLEAN
  };

  return ecr.describeImagesAsync(params)
    .then(function(imageDetails) {
      // Get all tags eligible for deletion by age threshold
      // coerce each of the tags to a full image reference for easy comparison
      const imagesAndDays = imageDetails
        .map(image => {

          const created = image.imagePushedAt
          const imageTag = (image.imageTags || [])[0] || '';

          if (created) {
            return [
              getImageAgeDays(created),
              config.AWS_ACCOUNT_ID + '.dkr.ecr.' + config.REGION + '.amazonaws.com/' +
              config.REPO_TO_CLEAN + ':' + imageTag
            ];
          } else {
            return null;
          }
        })
        .filter(image => image != null);
      return R.compose(
        R.map(R.prop(1)),
        R.unnest,
        R.values,
        R.map(R.drop(config.REPO_FIRST_N_THRESHOLD)),
        byEnv,
        sortByFirstItem
      )(imagesAndDays)

    });
};
<commit_msg>time-calc<commit_after>'use strict';

const Promise = require('bluebird');
const _ = require('lodash');
const R = require('ramda');

/**
 * Polifill
 */
if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}
/**
 * Lib
 */

function getImageAgeDays(date) {
  const age = Date.now() - (new Date(date)).getTime();
  const days = 1000 * 60 * 60 * 24;
  console.log('days count:', Math.round(age / days))
  return (Math.round(age / days));
}

exports.getRepoImages = (config, ecr, ecs) => {
  var params = {
    repositoryName: config.REPO_TO_CLEAN
  };
  return ecr.listImagesAsync(params);
};

// Takes an argument of an array of full image definitions
//   and splits into tags to delete from the REPO_TO_CLEAN repo
exports.deleteImages = (config, ecr, ecs) => images => {
  return new Promise(function(resolve) {
    console.info('IMAGES TO DELETE:', images);
    var imageTagsToDelete = _.map(images, function(image) {
      return { imageTag: image.split(':')[1] };
    });

    console.info('IMAGE TAGS TO DELETE:', imageTagsToDelete);

    // Make sure we are doing this for real
    if (config.DRY_RUN !== true) {
      if (imageTagsToDelete.length > 0) {
        const params = {
          imageIds: imageTagsToDelete,
          repositoryName: config.REPO_TO_CLEAN
        };

        // Batch delete all images in the deletionQueue
        ecr.batchDeleteImageAsync(params)
          .then(function(deletions) {
            resolve({
              failures: deletions.failures,
              imagesDeleted: deletions.imageIds,
              count: _.keys(deletions.imageIds)
                .length
            });
          });
      } else {
        resolve({
          failures: [],
          imagesDeleted: [],
          count: 0
        });
      }
    } else {
      // Fake Results
      resolve({
        dryRun: true,
        failures: [],
        imagesDeleted: imageTagsToDelete,
        count: imageTagsToDelete.length
      });
    }
  });
};

// Goes through all of ECS in a particular region and determines what is still
// marked as active and in use containers at a Task level (not actual running tasks)
exports.filterOutActiveImages = (config, ecr, ecs) => eligibleForDeletion => {
  console.info('BEFORE FILTER:', eligibleForDeletion);

  return ecs.listTaskDefinitionsAsync({ status: 'ACTIVE' })
    .then(function(taskDefs) {
      return new Promise(function(resolve) {
        Promise.map(taskDefs.taskDefinitionArns, function(taskDefinitionARN) {

            // Get all active images from all container defintions
            return ecs.describeTaskDefinitionAsync({ taskDefinition: taskDefinitionARN })
              .then(function(taskDefinitionDetails) {
                return _.chain(taskDefinitionDetails)
                  .map(function(taskDefinitionDetail) {
                    return taskDefinitionDetail.containerDefinitions;
                  })
                  .map(function(containerDefinition) {
                    return _.map(containerDefinition, 'image');
                  })
                  .value();
              });
          })
          .then(resolve);
      });
    })
    .then(function(allImages) {
      // Then reduce the big array and reduce to uniq values
      const activeImages = _.chain(allImages)
        .flattenDeep()
        .uniq()
        .value();
      console.log('ACTIVE IMAGES:', activeImages);

      // Remove images from deletion that are active
      return _.difference(eligibleForDeletion, activeImages);
    });
};

// Fetch all layers / image details from the repo
// Filter out everything newer than some variable amount of days
// set via REPO_AGE_THRESHOLD (90 days by default)
exports.filterImagesByDateThreshold = (config, ecr, ecs) => images => {
  console.info('IMAGES TO PROCESS (filterImagesByDateThreshold):', images);
  const params = {
    imageIds: images.imageIds,
    repositoryName: config.REPO_TO_CLEAN
  };

  return ecr.describeImagesAsync(params)
    .then(function(response) {
      // Get all tags eligible for deletion by age threshold
      // coerce each of the tags to a full image reference for easy comparison
      return response.imageDetails
        .map(image => {

          const created = image.imagePushedAt
          const imageTag = (image.imageTags || [])[0] || '';
          console.log('imageTag: ', imageTag);
          if (created &&
            imageTag !== 'latest' &&
            getImageAgeDays(created) >= config.REPO_AGE_THRESHOLD) {
            return config.AWS_ACCOUNT_ID + '.dkr.ecr.' + config.REGION + '.amazonaws.com/' +
              config.REPO_TO_CLEAN + ':' + imageTag;
          } else {
            return null;
          }
        })
        .filter(image => image != null);

    });
};
// Fetch all layers / image details from the repo
// Filter out everything newer than some variable amount of days
// set via REPO_AGE_THRESHOLD (90 days by default)
exports.filterImagesByFirstN = (config, ecr, ecs) => images => {
  console.info('IMAGES TO PROCESS (filterImagesByFirstN):', images);
  const sortByFirstItem = R.sortBy(R.prop(0));
  const byEnv = R.groupBy(image => {
    const tag = image[1];
    for (let i = 0; i < config.ENVS.length; i++) {
      if (tag.includes(config.ENVS[i])) {
        return config.ENVS[i]
      }
    }
    return tag;
  });
  const params = {
    imageIds: images.imageIds,
    repositoryName: config.REPO_TO_CLEAN
  };

  return ecr.describeImagesAsync(params)
    .then(function(response) {
      // Get all tags eligible for deletion by age threshold
      // coerce each of the tags to a full image reference for easy comparison
      const imagesAndDays = response.imageDetails
        .map(image => {

          const created = image.imagePushedAt
          const imageTag = (image.imageTags || [])[0] || '';

          if (created) {
            return [
              getImageAgeDays(created),
              config.AWS_ACCOUNT_ID + '.dkr.ecr.' + config.REGION + '.amazonaws.com/' +
              config.REPO_TO_CLEAN + ':' + imageTag
            ];
          } else {
            return null;
          }
        })
        .filter(image => image != null);
      return R.compose(
        R.map(R.prop(1)),
        R.unnest,
        R.values,
        R.map(R.drop(config.REPO_FIRST_N_THRESHOLD)),
        byEnv,
        sortByFirstItem
      )(imagesAndDays)

    });
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var typescript = require('gulp-typescript');
var merge2 = require('merge2');
var concat = require('gulp-concat');
var runsequence = require('run-sequence');
var zip = require('gulp-zip');
var replace = require('gulp-replace');
var markdown = require('gulp-markdown');
var pug = require('gulp-pug');
var webserver = require('gulp-webserver');

//ライブラリのドキュメント作成
var typedoc = require("gulp-typedoc");
gulp.task('createDoc',function(){
	return gulp
		.src(['./framework/**/**.ts'])
		.pipe(typedoc({
			// TypeScript options (see typescript docs)
			module: "commonjs",
			target: "es5",
			includeDeclarations: false,
			mode:"file",
			entryPoint :"Rf.ETS.FrameWork",
			// Output options (see typedoc docs)
			out: "./starter/doc",

			// TypeDoc options (see typedoc docs)
			name: "efs-framework",
			ignoreCompilerErrors: false,
			version: true,
		}))
	;
});

//スーパークラスのビルド
var buildBasesProject = typescript.createProject('./framework/tsconfig.json', { sortOutput: true });
gulp.task('_beforeBuildBases',function(){
	var result = gulp.src(["./framework/**/*.ts"])
      .pipe(typescript(buildBasesProject));

    return merge2[
    result.pipe(typescript.filter(
        buildBasesProject
        ,{referencedFrom: ['compileEntry.ts']}
    ))
    //result.js
    .pipe(concat('ets-framework.js'))
    .pipe(gulp.dest('./build'))
    .pipe(gulp.dest('./assets/js'))
    ,
    //dts
    result.dts
    .pipe(concat('ets-framework.d.ts'))
    .pipe(gulp.dest('./temp'))
    ];
});

gulp.task('buildBases',['_beforeBuildBases'], function () {
    return gulp.src(['./framework/typings/*.d.ts','./temp/ets-framework.d.ts'])
            .pipe(concat('ets-framework.d.ts'))
            .pipe(gulp.dest('./typings'))
            .pipe(gulp.dest('./build'));
});

//実装例のビルド
gulp.task('buildExamples', function () {
    return merge2(
            [
                gulp.src(['./example/ImageSpriteSample/*.ts','./typings/ets-framework.d.ts'])
                    .pipe(typescript('./example/ImageSpriteSample/tsconfig.json')).js
                    .pipe(gulp.dest('./build/ImageSpriteSample')),

                gulp.src(['./example/LoginSample/*.ts','./typings/ets-framework.d.ts'])
                    .pipe(typescript('./example/LoginSample/tsconfig.json')).js
                    .pipe(gulp.dest('./build/LoginSample')),

                gulp.src(['./example/2DRPGMapSample/*.ts','./typings/ets-framework.d.ts'])
                    .pipe(typescript('./example/2DRPGMapSample/tsconfig.json')).js
                    .pipe(gulp.dest('./build/2DRPGMapSample')),

                gulp.src(['./example/UseEnchantDtsOnly/*.ts','./framework/typings/enchant.d.ts'])
                    .pipe(typescript('./example/UseEnchantDtsOnly/tsconfig.json')).js
                    .pipe(gulp.dest('./build/UseEnchantDtsOnly'))
            ]
    );
});

//スターターの作成
gulp.task('CreateStarter',['_CreateStarterZip'],function () {
});

//1.スターターの作成準備(ファイルコピー)
gulp.task('_CreateStarterCopyFiles', function () {
    return merge2(
            [
                //starter/simpleへコピー
                gulp.src([
                    './framework/typings/enchant.d.ts'
                ])
                .pipe(gulp.dest('./starter/simple/typings')),

                gulp.src([
                    './assets/resources/*.*'
                ])
                .pipe(gulp.dest('./starter/simple/assets/resources')),

                gulp.src([
                    './assets/js/enchant.js'
                ])
                .pipe(gulp.dest('./starter/simple/assets/js')),

                gulp.src([
                    './example/UseEnchantDtsOnly/**/*.ts'
                ])
                .pipe(gulp.dest('./starter/simple')),

                //starter/use-frameworkへコピー
                gulp.src([
                    './typings/ets-framework.d.ts',
                    './assets/**/*.*'
                ],{base:'./'})
                .pipe(gulp.dest('./starter/use-framework')),

                gulp.src([
                    './example/ImageSpriteSample/**/*.ts'
                ])
                .pipe(gulp.dest('./starter/use-framework'))
            ]
    );
});

//2.スターターの作成準備(リソースパスの修正)
gulp.task('_CreateStarterReplacePath',['_CreateStarterCopyFiles'], function () {
    return gulp.src(['./starter/**/*.ts','!./starter/**/*.d.ts'],{base:'./starter'})
        .pipe(replace('../../assets/resources/','./assets/resources/'))
        .pipe(gulp.dest('./starter'));
});

//3.スターターの作成準備(ビルド)
gulp.task('_CreateStarterBuild',['_CreateStarterReplacePath'], function () {
    return merge2(
        [
            //TypeScriptのビルド
            gulp.src(['./starter/simple/**/*.ts'])
            .pipe(typescript('./starter/simple/tsconfig.json')).js
            .pipe(gulp.dest('./starter/simple')),

            gulp.src(['./starter/use-framework/**/*.ts'])
            .pipe(typescript('./starter/use-framework/tsconfig.json')).js
            .pipe(gulp.dest('./starter/use-framework'))
        ]
    );
});

//4.readme.mdをhtmlタグに変換
gulp.task('_CreateStarterConvertMD',['_CreateStarterBuild'], function () {
    return gulp.src('./starter/README.md')
        .pipe(markdown())
        .pipe(gulp.dest('./temp'));
});

//5.変換したhtmlタグをベースにHTMLを作成
gulp.task('_CreateStarterCreateHTML',['_CreateStarterConvertMD'], function () {
  return gulp.src('./pug-files/*.pug')
    .pipe(pug({
      pretty: true
    }))
    .pipe(gulp.dest('./starter'));
});

//6.スターターの作成準備(zip圧縮)
gulp.task('_CreateStarterZip',['_CreateStarterCreateHTML'], function () {
    return  gulp.src(['./starter/**/*'],{base:'./starter'})
            .pipe(zip('starter.zip'))
            .pipe(gulp.dest('./'))
});

//デフォルト
gulp.task('default',['buildBases'], function () {
    runsequence('buildExamples');
});

gulp.task('startServer', function() {
  webStream = gulp.src('./').pipe(webserver());
});
<commit_msg>スターターキットにLoginSampleと2DRPGMapSampleを追加<commit_after>var gulp = require('gulp');
var typescript = require('gulp-typescript');
var merge2 = require('merge2');
var concat = require('gulp-concat');
var runsequence = require('run-sequence');
var zip = require('gulp-zip');
var replace = require('gulp-replace');
var markdown = require('gulp-markdown');
var pug = require('gulp-pug');
var webserver = require('gulp-webserver');

//ライブラリのドキュメント作成
var typedoc = require("gulp-typedoc");
gulp.task('createDoc',function(){
	return gulp
		.src(['./framework/**/**.ts'])
		.pipe(typedoc({
			// TypeScript options (see typescript docs)
			module: "commonjs",
			target: "es5",
			includeDeclarations: false,
			mode:"file",
			entryPoint :"Rf.ETS.FrameWork",
			// Output options (see typedoc docs)
			out: "./starter/doc",

			// TypeDoc options (see typedoc docs)
			name: "efs-framework",
			ignoreCompilerErrors: false,
			version: true,
		}))
	;
});

//スーパークラスのビルド
var buildBasesProject = typescript.createProject('./framework/tsconfig.json', { sortOutput: true });
gulp.task('_beforeBuildBases',function(){
	var result = gulp.src(["./framework/**/*.ts"])
      .pipe(typescript(buildBasesProject));

    return merge2[
    result.pipe(typescript.filter(
        buildBasesProject
        ,{referencedFrom: ['compileEntry.ts']}
    ))
    //result.js
    .pipe(concat('ets-framework.js'))
    .pipe(gulp.dest('./build'))
    .pipe(gulp.dest('./assets/js'))
    ,
    //dts
    result.dts
    .pipe(concat('ets-framework.d.ts'))
    .pipe(gulp.dest('./temp'))
    ];
});

gulp.task('buildBases',['_beforeBuildBases'], function () {
    return gulp.src(['./framework/typings/*.d.ts','./temp/ets-framework.d.ts'])
            .pipe(concat('ets-framework.d.ts'))
            .pipe(gulp.dest('./typings'))
            .pipe(gulp.dest('./build'));
});

//実装例のビルド
gulp.task('buildExamples', function () {
    return merge2(
            [
                gulp.src(['./example/ImageSpriteSample/*.ts','./typings/ets-framework.d.ts'])
                    .pipe(typescript('./example/ImageSpriteSample/tsconfig.json')).js
                    .pipe(gulp.dest('./build/ImageSpriteSample')),

                gulp.src(['./example/LoginSample/*.ts','./typings/ets-framework.d.ts'])
                    .pipe(typescript('./example/LoginSample/tsconfig.json')).js
                    .pipe(gulp.dest('./build/LoginSample')),

                gulp.src(['./example/2DRPGMapSample/*.ts','./typings/ets-framework.d.ts'])
                    .pipe(typescript('./example/2DRPGMapSample/tsconfig.json')).js
                    .pipe(gulp.dest('./build/2DRPGMapSample')),

                gulp.src(['./example/UseEnchantDtsOnly/*.ts','./framework/typings/enchant.d.ts'])
                    .pipe(typescript('./example/UseEnchantDtsOnly/tsconfig.json')).js
                    .pipe(gulp.dest('./build/UseEnchantDtsOnly'))
            ]
    );
});

//スターターの作成
gulp.task('CreateStarter',['_CreateStarterZip'],function () {
});

//1.スターターの作成準備(ファイルコピー)
gulp.task('_CreateStarterCopyFiles', function () {
    return merge2(
            [
                //starter/simpleへコピー
                gulp.src([
                    './framework/typings/enchant.d.ts'
                ])
                .pipe(gulp.dest('./starter/simple/typings')),

                gulp.src([
                    './assets/resources/*.*'
                ])
                .pipe(gulp.dest('./starter/simple/assets/resources')),

                gulp.src([
                    './assets/js/enchant.js'
                ])
                .pipe(gulp.dest('./starter/simple/assets/js')),

                gulp.src([
                    './example/UseEnchantDtsOnly/**/*.ts'
                ])
                .pipe(gulp.dest('./starter/simple')),

                //starter/use-framework/ImageSpriteSampleへコピー
                gulp.src([
                    './typings/ets-framework.d.ts',
                    './assets/**/*.*'
                ],{base:'./'})
                .pipe(gulp.dest('./starter/use-framework/ImageSpriteSample')),

                gulp.src([
                    './example/ImageSpriteSample/**/*.ts'
                ])
                .pipe(gulp.dest('./starter/use-framework/ImageSpriteSample')),

                //starter/use-framework/LoginSampleへコピー
                gulp.src([
                    './typings/ets-framework.d.ts'
                ],{base:'./'})
                .pipe(gulp.dest('./starter/use-framework/LoginSample')),
                gulp.src([
                    './example/LoginSample/assets/**/*.*'
                ],{base:'./example/LoginSample/'})
                .pipe(gulp.dest('./starter/use-framework/LoginSample')),

                gulp.src([
                    './example/LoginSample/**/*.ts'
                ])
                .pipe(gulp.dest('./starter/use-framework/LoginSample')),

                //starter/use-framework/2DRPGMapSampleへコピー
                gulp.src([
                    './typings/ets-framework.d.ts'
                ],{base:'./'})
                .pipe(gulp.dest('./starter/use-framework/2DRPGMapSample')),
                gulp.src([
                    './example/2DRPGMapSample/assets/**/*.*'
                ],{base:'./example/2DRPGMapSample'})
                .pipe(gulp.dest('./starter/use-framework/2DRPGMapSample')),

                gulp.src([
                    './example/2DRPGMapSample/**/*.ts'
                ])
                .pipe(gulp.dest('./starter/use-framework/2DRPGMapSample'))
            ]
    );
});

//2.スターターの作成準備(リソースパスの修正)
gulp.task('_CreateStarterReplacePath',['_CreateStarterCopyFiles'], function () {
    return gulp.src(['./starter/**/*.ts','!./starter/**/*.d.ts'],{base:'./starter'})
        .pipe(replace('../../assets/resources/','./assets/resources/'))
        .pipe(gulp.dest('./starter'));
});

//3.スターターの作成準備(ビルド)
gulp.task('_CreateStarterBuild',['_CreateStarterReplacePath'], function () {
    return merge2(
        [
            //TypeScriptのビルド
            gulp.src(['./starter/simple/**/*.ts'])
            .pipe(typescript('./starter/simple/tsconfig.json')).js
            .pipe(gulp.dest('./starter/simple')),

            gulp.src(['./starter/use-framework/ImageSpriteSample/*.ts'])
            .pipe(typescript('./starter/use-framework/ImageSpriteSample/tsconfig.json')).js
            .pipe(gulp.dest('./starter/use-framework/ImageSpriteSample')),

            gulp.src(['./starter/use-framework/LoginSample/*.ts'])
            .pipe(typescript('./starter/use-framework/LoginSample/tsconfig.json')).js
            .pipe(gulp.dest('./starter/use-framework/LoginSample')),

            gulp.src(['./starter/use-framework/2DRPGMapSample/*.ts'])
            .pipe(typescript('./starter/use-framework/2DRPGMapSample/tsconfig.json')).js
            .pipe(gulp.dest('./starter/use-framework/2DRPGMapSample'))
        ]
    );
});

//4.readme.mdをhtmlタグに変換
gulp.task('_CreateStarterConvertMD',['_CreateStarterBuild'], function () {
    return gulp.src('./starter/README.md')
        .pipe(markdown())
        .pipe(gulp.dest('./temp'));
});

//5.変換したhtmlタグをベースにHTMLを作成
gulp.task('_CreateStarterCreateHTML',['_CreateStarterConvertMD'], function () {
  return gulp.src('./pug-files/*.pug')
    .pipe(pug({
      pretty: true
    }))
    .pipe(gulp.dest('./starter'));
});

//6.スターターの作成準備(zip圧縮)
gulp.task('_CreateStarterZip',['_CreateStarterCreateHTML'], function () {
    return  gulp.src(['./starter/**/*'],{base:'./starter'})
            .pipe(zip('starter.zip'))
            .pipe(gulp.dest('./'))
});

//デフォルト
gulp.task('default',['buildBases'], function () {
    runsequence('buildExamples');
});

gulp.task('startServer', function() {
  webStream = gulp.src('./').pipe(webserver());
});
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var EventEmitter = require('events').EventEmitter;

var Slack = require('slack-client');
var Listener = require('./listener');

function BeerBot(options) {
  this.listeners = {};
  this.options = options || {};
  this.initialize();
}
util.inherits(BeerBot, EventEmitter);

BeerBot.prototype.addListener = function(listener) {
  var self = this;
  if (!listener) {
    throw new Error('Listener is required');
  }
  self.listeners[listener.name] = listener.listen(self);
};

BeerBot.prototype.start = function() {
  this.slack.login();
};

BeerBot.prototype.createListener = function(name, handler, options) {
  return new Listener(name, handler, options);
};

BeerBot.prototype.initialize = function() {
  var self = this;
  self.options = self.options || {};
  if (!self.options.token) {
    throw new Error('Slack user token is required');
  }
  self.logger = require('winston');
  self.logger.level = self.options.logger && self.options.logger.level ? self.options.logger.level : 'info';
  var autoReconnect = self.options.autoReconnect || true;
  var autoMark = self.options.autoMark || true;

  self.slack = new Slack(self.options.token, autoReconnect, autoMark);

  self.options.listeners.forEach(function(l) {
    var handler = getListenerHandler(l);
    if (!handler) {
      self.logger.error('Can not load handler', l.name);
    }
    self.addListener(new Listener(l.name, handler, l));
  });

  self.slack.on('open', function() {
    self.logger.debug('Welcome to BeerBot for Slack. You are @' + self.slack.self.name + ' of ' + self.slack.team.name);
    self.emit('connected', {name: self.slack.self.name, team: self.slack.team.name});
  });

  self.slack.on('error', function(error) {
    self.logger.debug('Slack Error:', + error);
    self.emit('error', error);
  });
};

function getListenerHandler(options) {
  if (!options.name) {
    return;
  }

  try {
    return require(options.name);
  } catch (err) {
    return;
  }
}

module.exports = BeerBot;
<commit_msg>Check if listeners are defined<commit_after>'use strict';

var util = require('util');
var EventEmitter = require('events').EventEmitter;

var Slack = require('slack-client');
var Listener = require('./listener');

function BeerBot(options) {
  this.listeners = {};
  this.options = options || {};
  this.initialize();
}
util.inherits(BeerBot, EventEmitter);

BeerBot.prototype.addListener = function(listener) {
  var self = this;
  if (!listener) {
    throw new Error('Listener is required');
  }
  self.listeners[listener.name] = listener.listen(self);
};

BeerBot.prototype.start = function() {
  this.slack.login();
};

BeerBot.prototype.createListener = function(name, handler, options) {
  return new Listener(name, handler, options);
};

BeerBot.prototype.initialize = function() {
  var self = this;
  self.options = self.options || {};
  if (!self.options.token) {
    throw new Error('Slack user token is required');
  }
  self.logger = require('winston');
  self.logger.level = self.options.logger && self.options.logger.level ? self.options.logger.level : 'info';
  var autoReconnect = self.options.autoReconnect || true;
  var autoMark = self.options.autoMark || true;

  self.slack = new Slack(self.options.token, autoReconnect, autoMark);

  if (self.options.listeners) {
    self.options.listeners.forEach(function(l) {
      var handler = getListenerHandler(l);
      if (!handler) {
        self.logger.error('Can not load handler', l.name);
      }
      self.addListener(new Listener(l.name, handler, l));
    });
  }

  self.slack.on('open', function() {
    self.logger.debug('Welcome to BeerBot for Slack. You are @' + self.slack.self.name + ' of ' + self.slack.team.name);
    self.emit('connected', {name: self.slack.self.name, team: self.slack.team.name});
  });

  self.slack.on('error', function(error) {
    self.logger.debug('Slack Error:', + error);
    self.emit('error', error);
  });
};

function getListenerHandler(options) {
  if (!options.name) {
    return;
  }

  try {
    return require(options.name);
  } catch (err) {
    return;
  }
}

module.exports = BeerBot;
<|endoftext|>


<commit_before>var should = require("should");
var ec = require("../lib/encode_decode");
var opcua = require("../lib/nodeopcua");
var BinaryStream = require("../lib/binaryStream").BinaryStream;
var ExpandedNodeId = require("./../lib/nodeId").ExpandedNodeId;
var NodeIdType = require("./../lib/nodeId").NodeIdType;

function test_encode_decode(obj, encode_func, decode_func, expectedLength, verify_buffer_func) {
    var binaryStream = new BinaryStream();
    binaryStream.length.should.equal(0);

    encode_func(obj, binaryStream);
    binaryStream.length.should.equal(expectedLength);

    if (verify_buffer_func) {
        verify_buffer_func(binaryStream._buffer);
    }
    binaryStream.rewind();

    var obj_verif = decode_func(binaryStream);
    binaryStream.length.should.equal(expectedLength);

    if (obj !== undefined) {
        obj_verif.should.eql(obj);

    } else {
        should.not.exists(obj_verif);
    }
}

describe("testing built-in type encoding", function () {

    it("should encode and decode a boolean as a single byte", function () {

        test_encode_decode(true, ec.encodeBoolean, ec.decodeBoolean, 1);
        test_encode_decode(false, ec.encodeBoolean, ec.decodeBoolean, 1);

    });

    it("should encode and decode a Int16 (2 bytes)", function () {

        test_encode_decode(255, ec.encodeInt16, ec.decodeInt16, 2, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0xFF);
            buffer.readUInt8(1).should.equal(0x00);
        });
        test_encode_decode(-32000, ec.encodeInt16, ec.decodeInt16, 2);

    });

    it("should encode and decode a Int16 (2 bytes)", function () {

        test_encode_decode(0xFFFE, ec.encodeUInt16, ec.decodeUInt16, 2, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0xFE);
            buffer.readUInt8(1).should.equal(0xFF);
        });

    });

    it("should encode and decode a Integer (4 bytes)", function () {

        test_encode_decode(1000000000, ec.encodeInt32, ec.decodeInt32, 4, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x00);
            buffer.readUInt8(1).should.equal(0xCA);
            buffer.readUInt8(2).should.equal(0x9A);
            buffer.readUInt8(3).should.equal(0x3B);
        });
        test_encode_decode(-100000000, ec.encodeInt32, ec.decodeInt32, 4);

    });

    it("should encode and decode a Floating Point (4 bytes)", function () {

        var value = -6.5;
        // I EEE-754
        test_encode_decode(value, ec.encodeFloat, ec.decodeFloat, 4, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x00);
            buffer.readUInt8(1).should.equal(0x00);
            buffer.readUInt8(2).should.equal(0xD0);
            buffer.readUInt8(3).should.equal(0xC0);
        });

    });

    it("should encode and decode a Double Point (8 bytes)", function () {
        // I EEE-754

        var value = -6.5;
        // I EEE-754
        test_encode_decode(value, ec.encodeDouble, ec.decodeDouble, 8, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x00);
            buffer.readUInt8(1).should.equal(0x00);
            buffer.readUInt8(2).should.equal(0x00);
            buffer.readUInt8(3).should.equal(0x00);
            buffer.readUInt8(4).should.equal(0x00);
            buffer.readUInt8(5).should.equal(0x00);
            buffer.readUInt8(6).should.equal(0x1a);
            buffer.readUInt8(7).should.equal(0xc0);
        });

    });

    it("should encode and decode a null string", function () {

        var value = undefined;

        test_encode_decode(value, ec.encodeUAString, ec.decodeUAString, 4, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0xff);
            buffer.readUInt8(1).should.equal(0xff);
            buffer.readUInt8(2).should.equal(0xff);
            buffer.readUInt8(3).should.equal(0xff);
        });

    });

    it("should encode and decode a normal string", function () {

        var value = "Hello";

        test_encode_decode(value, ec.encodeUAString, ec.decodeUAString, 9, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x05);
            buffer.readUInt8(1).should.equal(0x00);
            buffer.readUInt8(2).should.equal(0x00);
            buffer.readUInt8(3).should.equal(0x00);
            buffer.readUInt8(4).should.equal('H'.charCodeAt(0));
            buffer.readUInt8(5).should.equal('e'.charCodeAt(0));
            buffer.readUInt8(6).should.equal('l'.charCodeAt(0));
            buffer.readUInt8(7).should.equal('l'.charCodeAt(0));
            buffer.readUInt8(8).should.equal('o'.charCodeAt(0));
        });

    });

    it("should encode and decode a DateTime", function () {

        var value = new Date(2014,0,2,15,0);
        test_encode_decode(value, ec.encodeDateTime, ec.decodeDateTime, 8, function (buffer) {
            // todo
        });

    });

    it("should encode and decode a GUID", function () {

        var value = "72962B91-FA75-4AE6-8D28-B404DC7DAF63";

        test_encode_decode(value, ec.encodeGUID, ec.decodeGUID, 16, function (buffer) {
            buffer.readUInt8(0).should.equal(0x91);
            buffer.readUInt8(1).should.equal(0x2B);
            buffer.readUInt8(2).should.equal(0x96);
            buffer.readUInt8(3).should.equal(0x72);

            buffer.readUInt8(4).should.equal(0x75);
            buffer.readUInt8(5).should.equal(0xFA);

            buffer.readUInt8(6).should.equal(0xE6);
            buffer.readUInt8(7).should.equal(0x4A);

            buffer.readUInt8(8).should.equal(0x8D);
            buffer.readUInt8(9).should.equal(0x28);

            buffer.readUInt8(10).should.equal(0xB4);
            buffer.readUInt8(11).should.equal(0x04);
            buffer.readUInt8(12).should.equal(0xDC);
            buffer.readUInt8(13).should.equal(0x7D);
            buffer.readUInt8(14).should.equal(0xAF);
            buffer.readUInt8(15).should.equal(0x63);
        });
    });

    it("should encode and decode a ByteString", function () {

        var buf = new Buffer(256);
        buf.write("THIS IS MY BUFFER");

        test_encode_decode(buf, ec.encodeByteString, ec.decodeByteString, 256 + 4, function (buffer) {

            buffer.readUInt32LE(0).should.equal(256);
        });
        //xx check_buf.toString('hex').should.equal(buf.toString('hex'));

    });

    it("should encode and decode a two byte NodeId", function () {

        var nodeId = ec.makeNodeId(25);
        nodeId.identifierType.should.eql(ec.NodeIdType.NUMERIC);

        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            2,
            function verify_buffer(buffer) {
                buffer.readUInt8(0).should.equal(0);
                buffer.readUInt8(1).should.equal(25); // namespace
            }
        );

    });

    it("should encode and decode a four byte NodeId", function () {

        var nodeId = ec.makeNodeId(258);
        nodeId.identifierType.should.eql(ec.NodeIdType.NUMERIC);
        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            4,
            function verify_buffer(buffer) {
                buffer.readUInt8(0).should.equal(1);
                buffer.readUInt8(1).should.equal(0); // namespace
                buffer.readUInt16LE(2).should.equal(258);
            }
        );
    });

    it("should encode and decode a Numeric NodeId", function () {

        var nodeId = ec.makeNodeId(545889, 2500);
        nodeId.identifierType.should.eql(ec.NodeIdType.NUMERIC);
        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            7
        );
    });

    it("should encode and decode a String NodeId", function () {

        var nodeId = ec.makeNodeId("SomeStuff", 2500);
        nodeId.identifierType.should.eql(ec.NodeIdType.STRING);

        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            4 + 9 + 2 + 1
        );

    });

    it("should encode and decode a Guid NodeId", function () {

        var nodeId = ec.makeNodeId("72962B91-FA75-4AE6-8D28-B404DC7DAF63", 2500);
        nodeId.identifierType.should.eql(ec.NodeIdType.GUID);
        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            16 + 2 + 1
        );
    });

    it("should encode and decode a Opaque NodeId", function () {

        var value = Buffer(32);
        for(var i= 0; i< 32;i++) { value.writeUInt8(i,i); }
        var nodeId = ec.makeNodeId(value, 0x1BCD);
        nodeId.identifierType.should.equal(ec.NodeIdType.BYTESTRING);
        var expectedLength = 1+ 2 + 4 + 32;
        test_encode_decode(nodeId, ec.encodeNodeId, ec.decodeNodeId, expectedLength, function (buffer) {
            // cod
            buffer.readUInt8(0).should.equal(0x05);
            // namespace
            buffer.readUInt8(1).should.equal(0xCD);
            buffer.readUInt8(2).should.equal(0x1B);
            // size
            buffer.readUInt32LE(3).should.equal(32);

            buffer.readUInt8( 7).should.equal(0x00);
            buffer.readUInt8( 8).should.equal(0x01);
            buffer.readUInt8( 9).should.equal(0x02);
            buffer.readUInt8(10).should.equal(0x03);
            buffer.readUInt8(11).should.equal(0x04);
            buffer.readUInt8(12).should.equal(0x05);
            // ...
            buffer.readUInt8(38).should.equal( 31);
        });
    });

    it("should encode and decode a Expanded NodeId  - TwoBytes", function () {

        test_encode_decode(
            ec.makeExpandedNodeId(10),
            ec.encodeExpandedNodeId,
            ec.decodeExpandedNodeId,
            2
        );
    });

    it("should encode and decode a Expanded NodeId  - FourBytes", function () {

        test_encode_decode(
            ec.makeExpandedNodeId(32000),
            ec.encodeExpandedNodeId,
            ec.decodeExpandedNodeId,
            4
        );
    });

    it("should encode and decode a Expanded NodeId with namespaceUri", function () {

        var serverIndex = 2;
        var namespaceUri = "some:namespace:uri";
        var expandedNodeId = new ExpandedNodeId(NodeIdType.NUMERIC,4123,4,namespaceUri,serverIndex);
        test_encode_decode(
            expandedNodeId,
            ec.encodeExpandedNodeId,
            ec.decodeExpandedNodeId,
            33
        );
    });

});

describe("check OPCUA Date Type ", function () {

    it("should convert date in 2014 ",function(){

        var date    = new Date(2014,0,1);
        var nano   = ec.dateToHundredNanoSecondFrom1601(date);
        var date2  = ec.hundredNanoSecondFrom1601ToDate(nano);

        date2.toString().should.equal(date.toString());

    });
    it("dateToHundredNanoSecondFrom1601 should return 0 for 1st of January 1601",function(){

        var date    = new Date(Date.UTC(1601,0,1,0,0));
        var nano   = ec.dateToHundredNanoSecondFrom1601(date);
        nano.should.equal(0);
    });

    it("dateToHundredNanoSecondFrom1601 should return xx nanos for 2st of January 1601",function(){

        var date    = new Date(Date.UTC(1601,0,2,0,0));
        var nano   = ec.dateToHundredNanoSecondFrom1601(date);
        nano.should.equal(24*60*60*1000*10000);
    });

    it("hundredNanoSecondFrom1601ToDate and dateToHundredNanoSecondFrom1601 ",function(){

        var date    = new Date(1789,6,14,19,47);
        var nano    = ec.dateToHundredNanoSecondFrom1601(date);
        var date2   = ec.hundredNanoSecondFrom1601ToDate(nano);

        date2.toString().should.equal(date.toString());

    });

    it("should decode 92c253d3 0cf7ce01 DateTime as  Dec 12, 2013 08:36:09.747317000 ", function () {

        var buf = new Buffer(8);
        buf.writeUInt32BE(0x92c253d3, 0);
        buf.writeUInt32BE(0x0cf7ce01, 4);
        buf.readUInt8(0).should.equal(0x92);
        buf.readUInt8(1).should.equal(0xc2);
        buf.readUInt8(2).should.equal(0x53);
        buf.readUInt8(7).should.equal(0x01);

        var stream = new BinaryStream(buf);
        var date = ec.decodeDateTime(stream);

        stream.rewind();
        ec.encodeDateTime(new Date(2013,11,12,9,36,9),stream);

    });
    //
    //  =>
});

<commit_msg>fix case in require<commit_after>var should = require("should");
var ec = require("../lib/encode_decode");
var opcua = require("../lib/nodeopcua");
var BinaryStream = require("../lib/binaryStream").BinaryStream;
var ExpandedNodeId = require("./../lib/nodeid").ExpandedNodeId;
var NodeIdType = require("./../lib/nodeid").NodeIdType;

function test_encode_decode(obj, encode_func, decode_func, expectedLength, verify_buffer_func) {
    var binaryStream = new BinaryStream();
    binaryStream.length.should.equal(0);

    encode_func(obj, binaryStream);
    binaryStream.length.should.equal(expectedLength);

    if (verify_buffer_func) {
        verify_buffer_func(binaryStream._buffer);
    }
    binaryStream.rewind();

    var obj_verif = decode_func(binaryStream);
    binaryStream.length.should.equal(expectedLength);

    if (obj !== undefined) {
        obj_verif.should.eql(obj);

    } else {
        should.not.exists(obj_verif);
    }
}

describe("testing built-in type encoding", function () {

    it("should encode and decode a boolean as a single byte", function () {

        test_encode_decode(true, ec.encodeBoolean, ec.decodeBoolean, 1);
        test_encode_decode(false, ec.encodeBoolean, ec.decodeBoolean, 1);

    });

    it("should encode and decode a Int16 (2 bytes)", function () {

        test_encode_decode(255, ec.encodeInt16, ec.decodeInt16, 2, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0xFF);
            buffer.readUInt8(1).should.equal(0x00);
        });
        test_encode_decode(-32000, ec.encodeInt16, ec.decodeInt16, 2);

    });

    it("should encode and decode a Int16 (2 bytes)", function () {

        test_encode_decode(0xFFFE, ec.encodeUInt16, ec.decodeUInt16, 2, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0xFE);
            buffer.readUInt8(1).should.equal(0xFF);
        });

    });

    it("should encode and decode a Integer (4 bytes)", function () {

        test_encode_decode(1000000000, ec.encodeInt32, ec.decodeInt32, 4, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x00);
            buffer.readUInt8(1).should.equal(0xCA);
            buffer.readUInt8(2).should.equal(0x9A);
            buffer.readUInt8(3).should.equal(0x3B);
        });
        test_encode_decode(-100000000, ec.encodeInt32, ec.decodeInt32, 4);

    });

    it("should encode and decode a Floating Point (4 bytes)", function () {

        var value = -6.5;
        // I EEE-754
        test_encode_decode(value, ec.encodeFloat, ec.decodeFloat, 4, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x00);
            buffer.readUInt8(1).should.equal(0x00);
            buffer.readUInt8(2).should.equal(0xD0);
            buffer.readUInt8(3).should.equal(0xC0);
        });

    });

    it("should encode and decode a Double Point (8 bytes)", function () {
        // I EEE-754

        var value = -6.5;
        // I EEE-754
        test_encode_decode(value, ec.encodeDouble, ec.decodeDouble, 8, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x00);
            buffer.readUInt8(1).should.equal(0x00);
            buffer.readUInt8(2).should.equal(0x00);
            buffer.readUInt8(3).should.equal(0x00);
            buffer.readUInt8(4).should.equal(0x00);
            buffer.readUInt8(5).should.equal(0x00);
            buffer.readUInt8(6).should.equal(0x1a);
            buffer.readUInt8(7).should.equal(0xc0);
        });

    });

    it("should encode and decode a null string", function () {

        var value = undefined;

        test_encode_decode(value, ec.encodeUAString, ec.decodeUAString, 4, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0xff);
            buffer.readUInt8(1).should.equal(0xff);
            buffer.readUInt8(2).should.equal(0xff);
            buffer.readUInt8(3).should.equal(0xff);
        });

    });

    it("should encode and decode a normal string", function () {

        var value = "Hello";

        test_encode_decode(value, ec.encodeUAString, ec.decodeUAString, 9, function (buffer) {
            // should be little endian
            buffer.readUInt8(0).should.equal(0x05);
            buffer.readUInt8(1).should.equal(0x00);
            buffer.readUInt8(2).should.equal(0x00);
            buffer.readUInt8(3).should.equal(0x00);
            buffer.readUInt8(4).should.equal('H'.charCodeAt(0));
            buffer.readUInt8(5).should.equal('e'.charCodeAt(0));
            buffer.readUInt8(6).should.equal('l'.charCodeAt(0));
            buffer.readUInt8(7).should.equal('l'.charCodeAt(0));
            buffer.readUInt8(8).should.equal('o'.charCodeAt(0));
        });

    });

    it("should encode and decode a DateTime", function () {

        var value = new Date(2014,0,2,15,0);
        test_encode_decode(value, ec.encodeDateTime, ec.decodeDateTime, 8, function (buffer) {
            // todo
        });

    });

    it("should encode and decode a GUID", function () {

        var value = "72962B91-FA75-4AE6-8D28-B404DC7DAF63";

        test_encode_decode(value, ec.encodeGUID, ec.decodeGUID, 16, function (buffer) {
            buffer.readUInt8(0).should.equal(0x91);
            buffer.readUInt8(1).should.equal(0x2B);
            buffer.readUInt8(2).should.equal(0x96);
            buffer.readUInt8(3).should.equal(0x72);

            buffer.readUInt8(4).should.equal(0x75);
            buffer.readUInt8(5).should.equal(0xFA);

            buffer.readUInt8(6).should.equal(0xE6);
            buffer.readUInt8(7).should.equal(0x4A);

            buffer.readUInt8(8).should.equal(0x8D);
            buffer.readUInt8(9).should.equal(0x28);

            buffer.readUInt8(10).should.equal(0xB4);
            buffer.readUInt8(11).should.equal(0x04);
            buffer.readUInt8(12).should.equal(0xDC);
            buffer.readUInt8(13).should.equal(0x7D);
            buffer.readUInt8(14).should.equal(0xAF);
            buffer.readUInt8(15).should.equal(0x63);
        });
    });

    it("should encode and decode a ByteString", function () {

        var buf = new Buffer(256);
        buf.write("THIS IS MY BUFFER");

        test_encode_decode(buf, ec.encodeByteString, ec.decodeByteString, 256 + 4, function (buffer) {

            buffer.readUInt32LE(0).should.equal(256);
        });
        //xx check_buf.toString('hex').should.equal(buf.toString('hex'));

    });

    it("should encode and decode a two byte NodeId", function () {

        var nodeId = ec.makeNodeId(25);
        nodeId.identifierType.should.eql(ec.NodeIdType.NUMERIC);

        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            2,
            function verify_buffer(buffer) {
                buffer.readUInt8(0).should.equal(0);
                buffer.readUInt8(1).should.equal(25); // namespace
            }
        );

    });

    it("should encode and decode a four byte NodeId", function () {

        var nodeId = ec.makeNodeId(258);
        nodeId.identifierType.should.eql(ec.NodeIdType.NUMERIC);
        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            4,
            function verify_buffer(buffer) {
                buffer.readUInt8(0).should.equal(1);
                buffer.readUInt8(1).should.equal(0); // namespace
                buffer.readUInt16LE(2).should.equal(258);
            }
        );
    });

    it("should encode and decode a Numeric NodeId", function () {

        var nodeId = ec.makeNodeId(545889, 2500);
        nodeId.identifierType.should.eql(ec.NodeIdType.NUMERIC);
        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            7
        );
    });

    it("should encode and decode a String NodeId", function () {

        var nodeId = ec.makeNodeId("SomeStuff", 2500);
        nodeId.identifierType.should.eql(ec.NodeIdType.STRING);

        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            4 + 9 + 2 + 1
        );

    });

    it("should encode and decode a Guid NodeId", function () {

        var nodeId = ec.makeNodeId("72962B91-FA75-4AE6-8D28-B404DC7DAF63", 2500);
        nodeId.identifierType.should.eql(ec.NodeIdType.GUID);
        test_encode_decode(
            nodeId,
            ec.encodeNodeId,
            ec.decodeNodeId,
            16 + 2 + 1
        );
    });

    it("should encode and decode a Opaque NodeId", function () {

        var value = Buffer(32);
        for(var i= 0; i< 32;i++) { value.writeUInt8(i,i); }
        var nodeId = ec.makeNodeId(value, 0x1BCD);
        nodeId.identifierType.should.equal(ec.NodeIdType.BYTESTRING);
        var expectedLength = 1+ 2 + 4 + 32;
        test_encode_decode(nodeId, ec.encodeNodeId, ec.decodeNodeId, expectedLength, function (buffer) {
            // cod
            buffer.readUInt8(0).should.equal(0x05);
            // namespace
            buffer.readUInt8(1).should.equal(0xCD);
            buffer.readUInt8(2).should.equal(0x1B);
            // size
            buffer.readUInt32LE(3).should.equal(32);

            buffer.readUInt8( 7).should.equal(0x00);
            buffer.readUInt8( 8).should.equal(0x01);
            buffer.readUInt8( 9).should.equal(0x02);
            buffer.readUInt8(10).should.equal(0x03);
            buffer.readUInt8(11).should.equal(0x04);
            buffer.readUInt8(12).should.equal(0x05);
            // ...
            buffer.readUInt8(38).should.equal( 31);
        });
    });

    it("should encode and decode a Expanded NodeId  - TwoBytes", function () {

        test_encode_decode(
            ec.makeExpandedNodeId(10),
            ec.encodeExpandedNodeId,
            ec.decodeExpandedNodeId,
            2
        );
    });

    it("should encode and decode a Expanded NodeId  - FourBytes", function () {

        test_encode_decode(
            ec.makeExpandedNodeId(32000),
            ec.encodeExpandedNodeId,
            ec.decodeExpandedNodeId,
            4
        );
    });

    it("should encode and decode a Expanded NodeId with namespaceUri", function () {

        var serverIndex = 2;
        var namespaceUri = "some:namespace:uri";
        var expandedNodeId = new ExpandedNodeId(NodeIdType.NUMERIC,4123,4,namespaceUri,serverIndex);
        test_encode_decode(
            expandedNodeId,
            ec.encodeExpandedNodeId,
            ec.decodeExpandedNodeId,
            33
        );
    });

});

describe("check OPCUA Date Type ", function () {

    it("should convert date in 2014 ",function(){

        var date    = new Date(2014,0,1);
        var nano   = ec.dateToHundredNanoSecondFrom1601(date);
        var date2  = ec.hundredNanoSecondFrom1601ToDate(nano);

        date2.toString().should.equal(date.toString());

    });
    it("dateToHundredNanoSecondFrom1601 should return 0 for 1st of January 1601",function(){

        var date    = new Date(Date.UTC(1601,0,1,0,0));
        var nano   = ec.dateToHundredNanoSecondFrom1601(date);
        nano.should.equal(0);
    });

    it("dateToHundredNanoSecondFrom1601 should return xx nanos for 2st of January 1601",function(){

        var date    = new Date(Date.UTC(1601,0,2,0,0));
        var nano   = ec.dateToHundredNanoSecondFrom1601(date);
        nano.should.equal(24*60*60*1000*10000);
    });

    it("hundredNanoSecondFrom1601ToDate and dateToHundredNanoSecondFrom1601 ",function(){

        var date    = new Date(1789,6,14,19,47);
        var nano    = ec.dateToHundredNanoSecondFrom1601(date);
        var date2   = ec.hundredNanoSecondFrom1601ToDate(nano);

        date2.toString().should.equal(date.toString());

    });

    it("should decode 92c253d3 0cf7ce01 DateTime as  Dec 12, 2013 08:36:09.747317000 ", function () {

        var buf = new Buffer(8);
        buf.writeUInt32BE(0x92c253d3, 0);
        buf.writeUInt32BE(0x0cf7ce01, 4);
        buf.readUInt8(0).should.equal(0x92);
        buf.readUInt8(1).should.equal(0xc2);
        buf.readUInt8(2).should.equal(0x53);
        buf.readUInt8(7).should.equal(0x01);

        var stream = new BinaryStream(buf);
        var date = ec.decodeDateTime(stream);

        stream.rewind();
        ec.encodeDateTime(new Date(2013,11,12,9,36,9),stream);

    });
    //
    //  =>
});

<|endoftext|>


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

  var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    concat = require('gulp-concat'),
    //debug = require('gulp-debug'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    browserify = require('browserify'),
    debowerify = require("debowerify"),
    nodemon = require('gulp-nodemon'),
    notifier = require("node-notifier"),
    gutil = require('gulp-util'),
    ngAnnotate = require('gulp-ng-annotate'),
    templateCache = require('gulp-angular-templatecache');

  /**
   *  Caching templates
   */
  gulp.task('templateCache', function () {
    gulp.src('client/**/*.html')
      .pipe(templateCache({
        standalone: true,
        root: 'client/'
      }))
      .pipe(gulp.dest('client/app'));
  });

  /**
   * Build application (concat and uglify)
   */
  gulp.task('buildApp', function () {
    gulp.src([
      './client/app/components/modules.js/',
      './client/app/shared/modules.js/',
      './client/app/app.modules.js',
      './client/app/**/*.js'
    ])
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(concat('app.js'))
      .pipe(ngAnnotate())
      .pipe(uglify().on('error', gutil.log))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Build application vendor (browserify and uglify)
   */
  gulp.task('buildAppVendor', function () {
    var vendor = browserify('./client/vendor.js', {
      debug: false
    });
    vendor.transform(debowerify);
    vendor.bundle()
      .on('error', function (err) {
        gutil.log(gutil.colors.bgRed("Browserify error (Vendor)"), gutil.colors.bgBlue(err.message));
        notifier.notify({title: "Browserify error (Vendor)", message: err.message });
        this.emit("end");
      })
      .pipe(source('vendor.js'))
      .pipe(buffer())
      .pipe(uglify())
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Build styles for application from SASS for
   */
  gulp.task('buildSass', function () {
    gulp.src('./client/main.scss')
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sass().on('error', function (err) {
        gutil.log(gutil.colors.bgRed("Sass compile error"), gutil.colors.bgBlue(err.message));
        notifier.notify({title: "Sass compile error", message: err.message });
        this.emit("end");
      }))
      .pipe(autoprefixer('last 2 versions'))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Build styles for vendors from SASS
   */
  gulp.task('buildSassVendor', function () {
    gulp.src('./client/vendor.scss')
      .pipe(sass().on('error', function (err) {
        gutil.log(gutil.colors.bgRed("Sass compile error (vendor)"), gutil.colors.bgBlue(err.message));
        notifier.notify({title: "Sass compile error (vendor)", message: err.message });
        this.emit("end");
      }))
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Watch for file changes
   */
  gulp.task('watch', function () {
    gulp.watch(['./client/main.js', './client/app/**/*.js'], ['buildApp']);
    gulp.watch(['./client/app/**/*.html'], ['templateCache', 'buildApp']);
    gulp.watch('./client/vendor.js', ['buildAppVendor']);
    gulp.watch(['./client/main.scss', './client/styles/*.scss', './client/app/**/*.scss'], ['buildSass']);
    gulp.watch('./client/vendor.scss', ['buildSassVendor']);
  });

  /**
   * Start the server and watch for changes in server folder
   */
  gulp.task('startServer', function () {
    nodemon({
      script: 'server/server.js',
      ext: 'js',
      ignore: ['node_modules/**', 'client/**', 'gulpfile.js']
    });
  });

  // Default Gulp Task
  gulp.task('default', ['templateCache', 'buildApp', 'buildAppVendor', 'buildSass', 'buildSassVendor', 'startServer', 'watch']);

}());<commit_msg>Fix templateCache callback<commit_after>(function () {
  'use strict';

  var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    concat = require('gulp-concat'),
    //debug = require('gulp-debug'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    uglify = require('gulp-uglify'),
    browserify = require('browserify'),
    debowerify = require("debowerify"),
    nodemon = require('gulp-nodemon'),
    notifier = require("node-notifier"),
    gutil = require('gulp-util'),
    ngAnnotate = require('gulp-ng-annotate'),
    templateCache = require('gulp-angular-templatecache');

  /**
   *  Caching templates
   */
  gulp.task('templateCache', function (cb) {
    gulp.src('client/**/*.html')
      .pipe(templateCache({
        standalone: true,
        root: 'client/'
      }))
      .pipe(gulp.dest('client/app', cb));
  });

  /**
   * Build application (concat and uglify)
   */
  gulp.task('buildApp', ['templateCache'], function () {
    gulp.src([
      './client/app/components/modules.js/',
      './client/app/shared/modules.js/',
      './client/app/app.modules.js',
      './client/app/**/*.js'
    ])
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(concat('app.js'))
      .pipe(ngAnnotate())
      .pipe(uglify().on('error', gutil.log))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Build application vendor (browserify and uglify)
   */
  gulp.task('buildAppVendor', function () {
    var vendor = browserify('./client/vendor.js', {
      debug: false
    });
    vendor.transform(debowerify);
    vendor.bundle()
      .on('error', function (err) {
        gutil.log(gutil.colors.bgRed("Browserify error (Vendor)"), gutil.colors.bgBlue(err.message));
        notifier.notify({title: "Browserify error (Vendor)", message: err.message });
        this.emit("end");
      })
      .pipe(source('vendor.js'))
      .pipe(buffer())
      .pipe(uglify())
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Build styles for application from SASS for
   */
  gulp.task('buildSass', function () {
    gulp.src('./client/main.scss')
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sass().on('error', function (err) {
        gutil.log(gutil.colors.bgRed("Sass compile error"), gutil.colors.bgBlue(err.message));
        notifier.notify({title: "Sass compile error", message: err.message });
        this.emit("end");
      }))
      .pipe(autoprefixer('last 2 versions'))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Build styles for vendors from SASS
   */
  gulp.task('buildSassVendor', function () {
    gulp.src('./client/vendor.scss')
      .pipe(sass().on('error', function (err) {
        gutil.log(gutil.colors.bgRed("Sass compile error (vendor)"), gutil.colors.bgBlue(err.message));
        notifier.notify({title: "Sass compile error (vendor)", message: err.message });
        this.emit("end");
      }))
      .pipe(gulp.dest('./client/build/'));
  });

  /**
   * Watch for file changes
   */
  gulp.task('watch', function () {
    gulp.watch(['./client/main.js', './client/app/**/*.js'], ['buildApp']);
    gulp.watch(['./client/app/**/*.html'], ['templateCache', 'buildApp']);
    gulp.watch('./client/vendor.js', ['buildAppVendor']);
    gulp.watch(['./client/main.scss', './client/styles/*.scss', './client/app/**/*.scss'], ['buildSass']);
    gulp.watch('./client/vendor.scss', ['buildSassVendor']);
  });

  /**
   * Start the server and watch for changes in server folder
   */
  gulp.task('startServer', function () {
    nodemon({
      script: 'server/server.js',
      ext: 'js',
      ignore: ['node_modules/**', 'client/**', 'gulpfile.js']
    });
  });

  // Default Gulp Task
  gulp.task('default', ['templateCache', 'buildApp', 'buildAppVendor', 'buildSass', 'buildSassVendor', 'startServer', 'watch']);

}());<|endoftext|>


<commit_before>// Dependencies
var FsExtra = require("fs-extra")
  , Ul = require("ul")
  , Moment = require("moment")
  , Couleurs = require("couleurs")()
  , CliBox = require("cli-box")
  ;

// Constants
const STORE_PATH = Ul.USER_DIR + "/.git-stats"
    , LEVELS = 5
    , SQUARES = process.argv.indexOf("--no-ansi") !== -1 ? [
        "⬚"
      , "▢"
      , "▢"
      , "▤"
      , "▣"
      , "⬛"
      ] : [
        Couleurs.fg("⬚", "#eee")
      , Couleurs.fg("▢", "#eee")
      , Couleurs.fg("▢", "#d6e685")
      , Couleurs.fg("▤", "#8cc665")
      , Couleurs.fg("▤", "#8cc665")
      , Couleurs.fg("▣", "#44a340")
      , Couleurs.fg("▣", "#1e6823")
      ]
    , DAYS = {
        Sun: 0
      , Mon: 1
      , Tue: 2
      , Wed: 3
      , Thu: 4
      , Fri: 5
      , Sat: 6
      }
    , DAYS_ARR = [
        "Sun"
      , "Mon"
      , "Tue"
      , "Wed"
      , "Thu"
      , "Fri"
      , "Sat"
      ]
    ;

// Constructor
var GitStats = module.exports = {};

/**
 * record
 * Records a new commit.
 *
 * @name record
 * @function
 * @param {Object} data The commit data containing:
 *
 *  - `date` (String|Date): The date object or a string in a format that can be parsed.
 *  - `url` (String): The repository remote url.
 *  - `hash` (String): The commit hash.
 *
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
GitStats.record = function (data, callback) {

    // Validate data
    callback = callback || function (err) { if (err) throw err; };
    data = Object(data);
    if (typeof data.date === "string") {
        data.date = new Moment(new Date(data.date));
    }

    if (!data.date || !/^Moment|Date$/.test(data.date.constructor.name)) {
        return callback(new Error("The date field should be a string or a date object."));
    }

    if (typeof data.hash !== "string" || !data.hash) {
        return callback(new Error("Invalid hash."));
    }

    if (typeof data.url !== "string" || !data.url) {
        return callback(new Error("Invalid url field."));
    }

    // Get stats
    GitStats.get(function (err, stats) {
        stats = stats || {};
        var day = data.date.format("MMM D, YYYY")
          , today = stats[day] = Object(stats[day])
          , repo = today[data.url] = Object(today[data.url])
          ;

        repo[data.hash] = { date: data.date };

        FsExtra.writeJSON(STORE_PATH, stats, callback);
    });
};

/**
 * get
 * Gets the git stats.
 *
 * @name get
 * @function
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
GitStats.get = function (callback) {
    FsExtra.readJSON(STORE_PATH, callback);
};

GitStats.iterateDays = function (data, callback) {

    if (typeof data === "function") {
        callback = data;
        data = undefined;
    }

    // Merge the defaults
    data = Ul.merge({
        end: Moment()
      , start: Moment().subtract(1, "years")
      , format: "MMM D, YYYY"
    }, data);

    var start = data.start
      , end = data.end
      , cDay = null
      ;

    while (!start.isAfter(end)) {
        cDay = start.format(data.format);
        callback(cDay, start);
        start.add(1, "days")
    }
};

GitStats.graph = function (data, callback) {

    if (typeof data === "function") {
        callback = data;
        data = undefined;
    }

    // Get commits
    GitStats.get(function (err, stats) {
        if (err) { return callback(err); }

        var cDayObj = null
          , year = {}
          ;

        // Iterate days
        GitStats.iterateDays(data, function (cDay) {
            cDayObj = year[cDay] = {
                _: stats[cDay] || {}
              , c: 0
            };

            Object.keys(cDayObj._).forEach(function (c) {
                cDayObj.c += Object.keys(cDayObj._[c]).length;
            });
        });

        callback(null, year);
    });
};

GitStats.calendar = function (data, callback) {
    GitStats.graph(data, function (err, graph) {
        if (err) { return callback(err); }
        var cal = { total: 0, days: {}, cStreak: 0, lStreak: 0 }
          , cDay = null
          , days = Object.keys(graph)
          , max = 0
          ;

        days.forEach(function (c) {
            cDay = graph[c];
            cal.total += cDay.c;
            if (cDay.c > max) {
                max = cDay.c;
            }

            if (cDay.c > 0) {
                if (++cal.cStreak > cal.lStreak) {
                    cal.lStreak = cal.cStreak;
                }
            } else {
                cal.cStreak = 0;
            }
        });

        days.forEach(function (c) {
            cDay = graph[c];
            cal.days[c] = {
                c: cDay.c
              , level: cDay.c === 0 ? 0 : LEVELS - Math.floor(max / (cDay.c + 2))
            };
        });

        callback(null, cal);
    });
};

GitStats.ansiCalendar = function (data, callback) {

    if (typeof data === "function") {
        callback = data;
        data = undefined;
    }

    var year = []
      , cWeek = [" ", " ", " ", " ", " ", " ", " "]
      , sDay = ""
      , cDayObj = null
      , strYear = ""
      , w = 0
      , d = 0
      ;

    GitStats.calendar(data, function (err, cal) {
        if (err) { return callback(err); }
        GitStats.iterateDays(function (cDay, mDay) {
            sDay = mDay.format("ddd");
            cDayObj = cal.days[cDay];

            if (sDay === "Sun" && Object.keys(cWeek).length) {
                year.push(cWeek);
                cWeek = [" ", " ", " ", " ", " ", " ", " "];
            }

            if (!cDayObj) return;

            cWeek[DAYS[sDay]] = SQUARES[cDayObj.level];
        });

        if (cWeek.length) {
            year.push(cWeek);
        }

        for (d = 0; d < 7; ++d) {
            for (w = 0; w < year.length; ++w) {
                strYear += " " + year[w][d];
            }
            strYear += "\n";
        }

        strYear = strYear.split("\n").map(function (c, i) {
            if (i > 6) { return; }
            return DAYS_ARR[i] + c;
        }).join("\n");

        strYear +=
             new Array(4 + 2 * Math.ceil(365 / 7)).join("-")
          + "\n" + "Total commits: " + cal.total
          + "\n" + "Current Streak: " + cal.cStreak
          + "\n" + "Longest Streak: " + cal.lStreak
          ;

        strYear = new CliBox({
            w: 10
          , h: 10
          , marks: {
                nw: "╔"
              , n:  "═"
              , ne: "╗"
              , e:  "║"
              , se: "╝"
              , s:  "═"
              , sw: "╚"
              , w:  "║"
              , b: " "
            }
        }, {
            text: strYear
          , stretch: true
          , hAlign: "left"
        });

        callback(null, strYear.toString());
    });
};
<commit_msg>Removed duplicated days object.<commit_after>// Dependencies
var FsExtra = require("fs-extra")
  , Ul = require("ul")
  , Moment = require("moment")
  , Couleurs = require("couleurs")()
  , CliBox = require("cli-box")
  ;

// Constants
const STORE_PATH = Ul.USER_DIR + "/.git-stats"
    , LEVELS = 5
    , SQUARES = process.argv.indexOf("--no-ansi") !== -1 ? [
        "⬚"
      , "▢"
      , "▢"
      , "▤"
      , "▣"
      , "⬛"
      ] : [
        Couleurs.fg("⬚", "#eee")
      , Couleurs.fg("▢", "#eee")
      , Couleurs.fg("▢", "#d6e685")
      , Couleurs.fg("▤", "#8cc665")
      , Couleurs.fg("▤", "#8cc665")
      , Couleurs.fg("▣", "#44a340")
      , Couleurs.fg("▣", "#1e6823")
      ]
    , DAYS = [
        "Sun"
      , "Mon"
      , "Tue"
      , "Wed"
      , "Thu"
      , "Fri"
      , "Sat"
      ]
    ;

// Constructor
var GitStats = module.exports = {};

/**
 * record
 * Records a new commit.
 *
 * @name record
 * @function
 * @param {Object} data The commit data containing:
 *
 *  - `date` (String|Date): The date object or a string in a format that can be parsed.
 *  - `url` (String): The repository remote url.
 *  - `hash` (String): The commit hash.
 *
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
GitStats.record = function (data, callback) {

    // Validate data
    callback = callback || function (err) { if (err) throw err; };
    data = Object(data);
    if (typeof data.date === "string") {
        data.date = new Moment(new Date(data.date));
    }

    if (!data.date || !/^Moment|Date$/.test(data.date.constructor.name)) {
        return callback(new Error("The date field should be a string or a date object."));
    }

    if (typeof data.hash !== "string" || !data.hash) {
        return callback(new Error("Invalid hash."));
    }

    if (typeof data.url !== "string" || !data.url) {
        return callback(new Error("Invalid url field."));
    }

    // Get stats
    GitStats.get(function (err, stats) {
        stats = stats || {};
        var day = data.date.format("MMM D, YYYY")
          , today = stats[day] = Object(stats[day])
          , repo = today[data.url] = Object(today[data.url])
          ;

        repo[data.hash] = { date: data.date };

        FsExtra.writeJSON(STORE_PATH, stats, callback);
    });
};

/**
 * get
 * Gets the git stats.
 *
 * @name get
 * @function
 * @param {Function} callback The callback function.
 * @return {undefined}
 */
GitStats.get = function (callback) {
    FsExtra.readJSON(STORE_PATH, callback);
};

GitStats.iterateDays = function (data, callback) {

    if (typeof data === "function") {
        callback = data;
        data = undefined;
    }

    // Merge the defaults
    data = Ul.merge({
        end: Moment()
      , start: Moment().subtract(1, "years")
      , format: "MMM D, YYYY"
    }, data);

    var start = data.start
      , end = data.end
      , cDay = null
      ;

    while (!start.isAfter(end)) {
        cDay = start.format(data.format);
        callback(cDay, start);
        start.add(1, "days")
    }
};

GitStats.graph = function (data, callback) {

    if (typeof data === "function") {
        callback = data;
        data = undefined;
    }

    // Get commits
    GitStats.get(function (err, stats) {
        if (err) { return callback(err); }

        var cDayObj = null
          , year = {}
          ;

        // Iterate days
        GitStats.iterateDays(data, function (cDay) {
            cDayObj = year[cDay] = {
                _: stats[cDay] || {}
              , c: 0
            };

            Object.keys(cDayObj._).forEach(function (c) {
                cDayObj.c += Object.keys(cDayObj._[c]).length;
            });
        });

        callback(null, year);
    });
};

GitStats.calendar = function (data, callback) {
    GitStats.graph(data, function (err, graph) {
        if (err) { return callback(err); }
        var cal = { total: 0, days: {}, cStreak: 0, lStreak: 0 }
          , cDay = null
          , days = Object.keys(graph)
          , max = 0
          ;

        days.forEach(function (c) {
            cDay = graph[c];
            cal.total += cDay.c;
            if (cDay.c > max) {
                max = cDay.c;
            }

            if (cDay.c > 0) {
                if (++cal.cStreak > cal.lStreak) {
                    cal.lStreak = cal.cStreak;
                }
            } else {
                cal.cStreak = 0;
            }
        });

        days.forEach(function (c) {
            cDay = graph[c];
            cal.days[c] = {
                c: cDay.c
              , level: cDay.c === 0 ? 0 : LEVELS - Math.floor(max / (cDay.c + 2))
            };
        });

        callback(null, cal);
    });
};

GitStats.ansiCalendar = function (data, callback) {

    if (typeof data === "function") {
        callback = data;
        data = undefined;
    }

    var year = []
      , cWeek = [" ", " ", " ", " ", " ", " ", " "]
      , sDay = ""
      , cDayObj = null
      , strYear = ""
      , w = 0
      , d = 0
      ;

    GitStats.calendar(data, function (err, cal) {
        if (err) { return callback(err); }
        GitStats.iterateDays(function (cDay, mDay) {
            sDay = mDay.format("ddd");
            cDayObj = cal.days[cDay];

            if (sDay === "Sun" && Object.keys(cWeek).length) {
                year.push(cWeek);
                cWeek = [" ", " ", " ", " ", " ", " ", " "];
            }

            if (!cDayObj) return;

            cWeek[DAYS.indexOf(sDay)] = SQUARES[cDayObj.level];
        });

        if (cWeek.length) {
            year.push(cWeek);
        }

        for (d = 0; d < 7; ++d) {
            for (w = 0; w < year.length; ++w) {
                strYear += " " + year[w][d];
            }
            strYear += "\n";
        }

        strYear = strYear.split("\n").map(function (c, i) {
            if (i > 6) { return; }
            return DAYS[i] + c;
        }).join("\n");

        strYear +=
             new Array(4 + 2 * Math.ceil(365 / 7)).join("-")
          + "\n" + "Total commits: " + cal.total
          + "\n" + "Current Streak: " + cal.cStreak
          + "\n" + "Longest Streak: " + cal.lStreak
          ;

        strYear = new CliBox({
            w: 10
          , h: 10
          , marks: {
                nw: "╔"
              , n:  "═"
              , ne: "╗"
              , e:  "║"
              , se: "╝"
              , s:  "═"
              , sw: "╚"
              , w:  "║"
              , b: " "
            }
        }, {
            text: strYear
          , stretch: true
          , hAlign: "left"
        });

        callback(null, strYear.toString());
    });
};
<|endoftext|>


<commit_before>import {addLocaleData} from 'react-intl';
import en_messages from './en';
import de_messages from './de';
import bs_messages from './bs';
import en from 'react-intl/locale-data/en';
import de from 'react-intl/locale-data/de';
import bs from 'react-intl/locale-data/bs';

var areIntlLocalesSupported = require('intl-locales-supported');

//START: Intl polyfill
//Required for working on Safari
//Code from here: https://formatjs.io/guides/runtime-environments/
var localesMyAppSupports = [
    /* list locales here */
];

if (global.Intl) {
    // Determine if the built-in `Intl` has the locale data we need.
    if (!areIntlLocalesSupported(localesMyAppSupports)) {
        // `Intl` exists, but it doesn't have the data we need, so load the
        // polyfill and replace the constructors with need with the polyfill's.
        var IntlPolyfill = require('intl');
        Intl.NumberFormat   = IntlPolyfill.NumberFormat;
        Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    }
} else {
    // No `Intl`, so use and load the polyfill.
    global.Intl = require('intl');
}
//END: Intl polyfill

const locales = [
  {
    locale: 'en',
    messages: en_messages,
    data: en
  },
  {
    locale: 'de',
    messages: de_messages,
    data: de
  },
  {
    locale: 'bs',
    messages: bs_messages,
    data: bs
  },

]

export function getLocaleMessages(locale){

  if(locales){
    for (var i = 0; i < locales.length; i++) {
      if(locales[i]['locale']===locale){
        return locales[i]['messages']
      }
    }
  }

  return en_messages; //Default locale

}

export function addLocalizationData(){

  locales.map((l)=>{
    addLocaleData(l.data);
    return l;
  });

}

export default locales;
<commit_msg>Added russian language<commit_after>import {addLocaleData} from 'react-intl';
import en_messages from './en';
import de_messages from './de';
import ru_messages from './ru';
import bs_messages from './bs';
import en from 'react-intl/locale-data/en';
import de from 'react-intl/locale-data/de';
import ru from 'react-intl/locale-data/ru';
import bs from 'react-intl/locale-data/bs';

var areIntlLocalesSupported = require('intl-locales-supported');

//START: Intl polyfill
//Required for working on Safari
//Code from here: https://formatjs.io/guides/runtime-environments/
var localesMyAppSupports = [
    /* list locales here */
];

if (global.Intl) {
    // Determine if the built-in `Intl` has the locale data we need.
    if (!areIntlLocalesSupported(localesMyAppSupports)) {
        // `Intl` exists, but it doesn't have the data we need, so load the
        // polyfill and replace the constructors with need with the polyfill's.
        var IntlPolyfill = require('intl');
        Intl.NumberFormat   = IntlPolyfill.NumberFormat;
        Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    }
} else {
    // No `Intl`, so use and load the polyfill.
    global.Intl = require('intl');
}
//END: Intl polyfill

const locales = [
  {
    locale: 'en',
    messages: en_messages,
    data: en
  },
  {
    locale: 'de',
    messages: de_messages,
    data: de
  },
  {
    locale: 'bs',
    messages: bs_messages,
    data: bs
  },

]

export function getLocaleMessages(locale){

  if(locales){
    for (var i = 0; i < locales.length; i++) {
      if(locales[i]['locale']===locale){
        return locales[i]['messages']
      }
    }
  }

  return en_messages; //Default locale

}

export function addLocalizationData(){

  locales.map((l)=>{
    addLocaleData(l.data);
    return l;
  });

}

export default locales;
<|endoftext|>