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

  var L20n = {
    getContext: function L20n_getContext(id) {
      return new Context(id);
    },
  };

  function Source(url, text) {
    this.text = text;
    this.ast = null;
    this.url = url;
  }

  function Resource(id, parser) {
    var self = this;

    this.id = id;
    this.resources = [];
    this.source = null;
    this.isReady = false;
    this.ast = {
      type: 'LOL',
      body: [],
    };

    this.fetch = fetch;
    this.build = build;
    this.addResource = addResource;
    this.linkResource = linkResource;
    this.parse = parse;

    // what is that?
    var _resources_parsed = [];
    // what is that?
    var _imports_positions = [];

    function inlineResource(res, pos) {
      // is this the Context's _resource?
      if (self.source === null) {
        self.ast.body = self.ast.body.concat(res.source.ast.body);
      } else {
        Array.prototype.splice.apply(self.ast.body,
                                     [pos, 1].concat(res.source.ast.body));
      }
    }

    function fetch() {
      var deferreds = [];
      var self = this;
      for (var i in this.resources) {
        deferreds.push(this.resources[i].fetch());
      }
      if (this.id) {
        var deferred = when.defer();
        deferreds.push(deferred.promise);
        loadSourceAsync(this.id).then(
          function(source) {
            if (source) {
              self.source = source;
              self.parse(true);
              deferred.resolve();
            }
          }
        );
      }
      return when.all(deferreds);
    }

    function merge() {
      for (var i = 0, res; res = self.resources[i]; i++) {
        var pos = _imports_positions[i];
        // source is false (sync) or undefined (async) if the source file fails
        // to download
        if (res.source) {
          inlineResource(res, pos);
        }
      }
    }

    function parse(async, nesting) {
      this.ast = this.source.ast = parser.parse(this.source.text);
      var imports = this.source.ast.body.filter(function(elem, i) {
        if (elem.type == 'ImportStatement') {
          _imports_positions.push(i);
          return true;
        }
        return false;
      });
      imports.forEach(function(imp) {
        addResource(imp.uri.content, async, nesting + 1);
      });
    }

    function addResource(id, text) {
      var res = new Resource(id, parser);
      var source = new Source(id, text);
      res.source = source;
      source.ast = parser.parse(source.text);
      this.resources.push(res);
      _imports_positions.push(0);
    }

    function relativeToSelf(url) {
      var dirname = self.source.url.split('/').slice(0, -1).join('/');
      if (url[0] == '/') {
        return url;
      } else if (dirname) {
        // strip the trailing slash if present
        if (dirname[dirname.length - 1] == '/') {
          dirname = dirname.slice(0, dirname.length - 1);
        }
        return dirname + '/' + url;
      } else {
        return './' + url;
      }
    }

    function loadSourceAsync(url) {
      var loaded = when.defer();
      if (self.source) {
        url = relativeToSelf(url);
      }
      L20n.IO.loadAsync(url).then(
        function loadResource_success(text) {
          var source = new Source(url, text);
          loaded.resolve(source);
        },
        function loadResource_failure() {
          return loaded.resolve();
        }
      );
      return loaded.promise;
    }

    function loadSourceSync(url) {
      if (self.source) {
        url = relativeToSelf(url);
      }
      var text = null;
      text = L20n.IO.loadSync(url);
      if (text) {
        var source = new Source(url, text);
        return source;
      }
      return false;
    }

    function linkResource(url, async, nesting) {
      if (nesting > 7) {
        return false;
      }
      var res = new Resource(url, parser);
      self.resources.push(res);
    }

    function build() {
      var merged = when.defer();
      var imports_built = [];
      self.resources.forEach(function(res) {
        imports_built.push(res.build());
      });
      when.all(imports_built).then(
          function() {
            merge();
            self.isReady = true;
            return merged.resolve();
          }
      );
      return merged.promise;
    }

  }

  function Locale(id, parser, compiler) {
    this.id = id;
    this.resource = new Resource(null, parser);

    this.freeze = freeze;
    this.get = get;

    var _entries = null;

    function freeze(callback) {
      var self = this;
      this.resource.fetch().then(
          function() {
            self.resource.build()
          }
      ).then(
        function freeze_success() {
          _entries = compiler.compile(self.resource.ast);
          callback();
        }
      );
    }

    function get(id, data) {
      return _entries[id].toString();
    }

  }

  function Context(id) {

    this.ContextError = ContextError;
    this.data = {};

    this.addResource = addResource;
    this.linkResource = linkResource;
    this.bindResource = bindResource;
    this.registerLocales = registerLocales;
    this.freeze = freeze;

    this.get = get;
    this.getEntity = getEntity;
    this.localize = null;

    this.addEventListener = addEventListener;
    this.removeEventListener = removeEventListener;

    var _isFrozen = false;
    var _emitter = new L20n.EventEmitter();
    var _parser = new L20n.Parser(L20n.EventEmitter);
    var _compiler = new L20n.Compiler(L20n.EventEmitter, L20n.Parser);
    // singleton within the context
    var _globals = {
      get hour() {
        return new Date().getHours();
      },
    };
    var _listeners = [];
    var _languages = [];
    var _locales = [];

    _parser.addEventListener('error', echo);
    _compiler.addEventListener('error', echo);
    _compiler.setGlobals(_globals);

    function get(id, data) {
      return _locales[0].get(id, getArgs.bind(this, data));
    }

    function getArgs(data) {
      if (!data) {
        return this.data;
      }
      var args = {};
      for (var i in this.data) {
        if (this.data.hasOwnProperty(i)) {
          args[i] = this.data[i];
        }
      }
      if (data) {
        for (i in data) {
          if (data.hasOwnProperty(i)) {
            args[i] = data[i];
          }
        }
      }
      return args;
    }

    function getEntity(id, data) {
    }

    function addResource(text) {
      if (_locales.length === 0) {
        _locales.push(new Locale(null, _parser, _compiler));
      }
      _locales[0].resource.addResource(null, text);
    }

    function linkResource(uri) {
      if (_locales.length === 0) {
        _locales.push(new Locale(null, _parser, _compiler));
      }
      if (uri instanceof Function) {
        for (var i in _locales) {
          _locales[i].resource.linkResource(uri(_locales[i].id));
        }
      } else {
        _locales[0].resource.linkResource(uri);
      }

    }

    function bindResource(uri, text) {
    }

    function freeze(async) {
      _isFrozen = true;
      _locales[0].freeze(ready);
      return this;
    }

    function registerLocales() {
      for (var i in arguments) {
        _locales.push(new Locale(arguments[i], _parser, _compiler));
      }
    }

    function ready() {
      _emitter.emit('ready');
    }

    function addEventListener(type, listener) {
      _emitter.addEventListener(type, listener);
    }

    function removeEventListener(type, listener) {
      _emitter.removeEventListener(type, listener);
    }

    function echo(e) {
      _emitter.emit('error', e);
    }

    function emit(msg, id) {
      _emitter.emit('error', new ContextError(msg, id, _settings.locales[0]));
    }

  /* ContextError class */

  function ContextError(message, id, locale) {
    this.name = 'ContextError';
    this.id = id;
    this.locale = locale;
    this.message = message + ', locale: '+locale+', id: '+id;
  }
  ContextError.prototype = Object.create(Error.prototype);
  ContextError.prototype.constructor = ContextError;

}

  this.L20n = L20n;

}).call(this);
<commit_msg>New Resource.build<commit_after>(function() {
  'use strict';

  var L20n = {
    getContext: function L20n_getContext(id) {
      return new Context(id);
    },
  };

  function Source(url, text) {
    this.text = text;
    this.ast = null;
    this.url = url;
  }

  function Resource(id, parser) {
    var self = this;

    this.id = id;
    this.resources = [];
    this.source = null;
    this.isReady = false;
    this.ast = {
      type: 'LOL',
      body: [],
    };

    this.build = build;
    this.fetch = fetch;
    this.parse = parse;
    this.buildImports = buildImports;
    this.inline = inline;

    var _imports_positions = [];

    var self = this;

    function build(nesting) {
      if (nesting >= 7) {
        throw new ContextError("Too many nested imports.");
      }
      return fetch().then(parse).then(function(ast) {
        buildImports(ast, nesting + 1);
      }).then(inline);
    }

    function fetch() {
      var source = when.defer();
      if (self.source) {
        source.resolve(self.source);
        return source.promise;
      }
      L20n.IO.loadAsync(id).then(
        function loadResource_success(text) {
          self.source = new Source(id, text);
          source.resolve(self.source);
        },
        function loadResource_failure() {
          return source.resolve();
        }
      );
      return source.promise;
    }

    function parse(source) {
      var ast = when.defer();
      self.ast = self.source.ast = parser.parse(source.text);
      ast.resolve(self.ast);
      return ast.promise;
    }

    function buildImports(ast, nesting) {
      var imports = ast.body.filter(function(elem, i) {
        if (elem.type == 'ImportStatement') {
          _imports_positions.push(i);
          return true;
        }
        return false;
      });

      imports.forEach(function(imp) {
        var uri = relativeToSelf(imp.uri.content);
        var res = Resource(uri, parser);
        self.resources.push(res);
      });

      var imports_built = [];
      self.resources.forEach(function(res) {
        imports_built.push(res.build(nesting));
      });

      return when.all(imports_built);
    }

    function inline() {
      for (var i = 0, res; res = self.resources[i]; i++) {
        var pos = _imports_positions[i];
        // source is false (sync) or undefined (async) if the source file fails
        // to download
        if (res.source) {
          // check if this is the Locale's _resource
          if (self.source === null) {
            self.ast.body = self.ast.body.concat(res.source.ast.body);
          } else {
            Array.prototype.splice.apply(self.ast.body,
              [pos, 1].concat(res.source.ast.body));
          }
        }
      }
      self.isReady = true;
      var flat = when.defer();
      flat.resolve();
      return flat.promise;
    }

    function relativeToSelf(url) {
      var dirname = self.source.url.split('/').slice(0, -1).join('/');
      if (url[0] == '/') {
        return url;
      } else if (dirname) {
        // strip the trailing slash if present
        if (dirname[dirname.length - 1] == '/') {
          dirname = dirname.slice(0, dirname.length - 1);
        }
        return dirname + '/' + url;
      } else {
        return './' + url;
      }
    }

  }

  function Locale(id, parser, compiler) {
    this.id = id;
    this.resource = new Resource(null, parser);

    this.freeze = freeze;
    this.get = get;

    var _entries = null;

    function freeze(callback) {
      var self = this;
      this.resource.build().then(function freeze_success() {
        _entries = compiler.compile(self.resource.ast);
        callback();
      });
    }

    function get(id, data) {
      return _entries[id].toString();
    }

  }

  function Context(id) {

    this.ContextError = ContextError;
    this.data = {};

    this.addResource = addResource;
    this.linkResource = linkResource;
    this.bindResource = bindResource;
    this.registerLocales = registerLocales;
    this.freeze = freeze;

    this.get = get;
    this.getEntity = getEntity;
    this.localize = null;

    this.addEventListener = addEventListener;
    this.removeEventListener = removeEventListener;

    var _isFrozen = false;
    var _emitter = new L20n.EventEmitter();
    var _parser = new L20n.Parser(L20n.EventEmitter);
    var _compiler = new L20n.Compiler(L20n.EventEmitter, L20n.Parser);
    var _globals = {
      get hour() {
        return new Date().getHours();
      },
    };
    var _listeners = [];
    var _languages = [];
    var _locales = [];

    _parser.addEventListener('error', echo);
    _compiler.addEventListener('error', echo);
    _compiler.setGlobals(_globals);

    function get(id, data) {
      return _locales[0].get(id, getArgs.bind(this, data));
    }

    function getArgs(data) {
      if (!data) {
        return this.data;
      }
      var args = {};
      for (var i in this.data) {
        if (this.data.hasOwnProperty(i)) {
          args[i] = this.data[i];
        }
      }
      if (data) {
        for (i in data) {
          if (data.hasOwnProperty(i)) {
            args[i] = data[i];
          }
        }
      }
      return args;
    }

    function getEntity(id, data) {
    }

    function addResource(text) {
      if (_locales.length === 0) {
        _locales.push(new Locale(null, _parser, _compiler));
      }
      var res = new Resource(null, _parser);
      res.source = new Source(null, text);
      _locales[0].resource.resources.push(res);
    }

    function linkResource(uri) {
      if (_locales.length === 0) {
        _locales.push(new Locale(null, _parser, _compiler));
      }
      if (uri instanceof Function) {
        for (var i in _locales) {
          _locales[i].resource.linkResource(uri(_locales[i].id));
        }
      } else {
        _locales[0].resource.linkResource(uri);
      }

    }

    function bindResource(uri, text) {
    }

    function freeze(async) {
      _isFrozen = true;
      _locales[0].freeze(ready);
      return this;
    }

    function registerLocales() {
      for (var i in arguments) {
        _locales.push(new Locale(arguments[i], _parser, _compiler));
      }
    }

    function ready() {
      _emitter.emit('ready');
    }

    function addEventListener(type, listener) {
      _emitter.addEventListener(type, listener);
    }

    function removeEventListener(type, listener) {
      _emitter.removeEventListener(type, listener);
    }

    function echo(e) {
      _emitter.emit('error', e);
    }

    function emit(msg, id) {
      _emitter.emit('error', new ContextError(msg, id, _settings.locales[0]));
    }

  /* ContextError class */

  function ContextError(message, id, locale) {
    this.name = 'ContextError';
    this.id = id;
    this.locale = locale;
    this.message = message + ', locale: '+locale+', id: '+id;
  }
  ContextError.prototype = Object.create(Error.prototype);
  ContextError.prototype.constructor = ContextError;

}

  this.L20n = L20n;

}).call(this);
<|endoftext|>


<commit_before>'use strict';

var cheerio = require('cheerio');
var snakeCase = require('change-case').snakeCase;
var flatten = require('annofp').flatten;
var is = require('annois');
var unidecode = require('unidecode');

var convertTag = require('./convert_tag');
var toMarkdown = require('./to_markdown');

module.exports = function(json, extend) {
    extend = extend || function(data) {
        return data;
    };

    if(!json.feed) {
        return {};
    }

    var slugs = [], images = [];

    var posts = json.feed.entry ? json.feed.entry.map(function(post, i) {
        var title = post.title['$t'].trim(),
            slug = snakeCase(unidecode(title)),
            html = post.content['$t'],
            markdown = tomd(html),
            published = Date.parse(post.published['$t']);

        // prevent duplicate slugs (suffix post index if slug exists)
        slug = slugs.indexOf(slug) === -1 ? slug : slug + i;
        slugs.push(slug);

        // grab a post's images and add to global images array (for download later)
        var postImages = markdown.match(/\[!\[]\((.*?)\)/);
        if (postImages !== null) {
            postImages.forEach(function(image){
                images.push(image.replace('[![](', '').replace(/.(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG)\)/, '.$1'));
            });
        }

        return extend({
            id: i,
            title: title,
            slug: slug,
            markdown: markdown,
            html: html,
            image: null,
            featured: 0,
            page: 0,
            status: 'published',
            language: 'en_US',
            'meta_title': null,
            'meta_description': null,
            'author_id': 1,
            'created_at': published,
            'created_by': 1,
            'updated_at': Date.parse(post.updated['$t']),
            'updated_by': 1,
            'published_at': published,
            'published_by': 1
        }, post);
    }): [];

    var tagIds = {};
    var tags = json.feed.category ? json.feed.category.map(function(category, i) {
        var name = convertTag(category.term);

        tagIds[name] = i;

        return {
            id: i,
            name: name,
            slug: snakeCase(unidecode(name)),
            description: ''
        };
    }): [];

    var postsTags = json.feed.entry ? flatten(json.feed.entry.map(function(post, i) {
        if(!is.array(post.category)) {
            return [];
        }

        return post.category.map(function(category) {
            var term = convertTag(category.term);
            var tagId = tagIds[term];

            if(!is.defined(tagId)) {
                console.error(term + ' doesn\'t have a tag associated to it!');

                return {};
            }

            return {
                'tag_id': tagId,
                'post_id': i
            };
        });
    })): [];

    return {
        meta: {
            'exported_on': Date.now(),
            version: '000'
        },
        images: images,
        data: {
            posts: posts,
            tags: tags,
            'posts_tags': postsTags
        }
    };
};

function tomd(html) {
    var $ = cheerio.load(html);

    // remove links from img's that link to themselves
    $('a').replaceWith(function(i, e) {
        if ($(e).find('img').length) {
            if ($(e).attr('href') === $(e).find('img').first().attr('src')) {
                return $(e).find('img').first();
            }
        }

        return $(e);
    });

    html = $.html();

    // remove div's
    html = html.replace(/<div(.*?)>|<\/div>/gi, '');

    // remove span's
    html = html.replace(/<span(.*?)>|<\/span>/gi, '');

    // remove tables
    html = html.replace(/<table(.*?)>|<thead(.*?)>|<tbody(.*?)>|<tr(.*?)>|<td(.*?)>|<\/td>|<\/tr>|<\/tbody>|<\/thead>|<\/table>/gi, '');

    var markdown = toMarkdown(html);

    markdown = markdown
        .replace(/ /gi, ' ') // remove nbsp's
        .replace(/&/g, '&') // replace ampersands
        .replace(/  +/g, ' ') // remove double spaces
        .replace(/\!\[]\((.*?)\)/g, '![]($1)\n\n') // add double line break after images
        .replace(/(\n\s+)/g, '\n\n') // remove space at beginning of a line
        .trim(); // remove trailing whitespace

    // replace image paths
    markdown = markdown.replace(/\!\[\]\((\bhttps?:\/\/[^\s()<>]+(?:\([\w\d]+\)|[^[:punct:]\s]|\/))/ig, '![](');

    return markdown;
}
<commit_msg>convert image paths<commit_after>'use strict';

var cheerio = require('cheerio');
var snakeCase = require('change-case').snakeCase;
var flatten = require('annofp').flatten;
var is = require('annois');
var unidecode = require('unidecode');

var convertTag = require('./convert_tag');
var toMarkdown = require('./to_markdown');

module.exports = function(json, extend) {
    extend = extend || function(data) {
        return data;
    };

    if(!json.feed) {
        return {};
    }

    var slugs = [], images = [];

    var posts = json.feed.entry ? json.feed.entry.map(function(post, i) {
        var title = post.title['$t'].trim(),
            slug = snakeCase(unidecode(title)),
            html = post.content['$t'],
            markdown = tomd(html),
            published = Date.parse(post.published['$t']);

        // prevent duplicate slugs (suffix post index if slug exists)
        slug = slugs.indexOf(slug) === -1 ? slug : slug + i;
        slugs.push(slug);

        // grab a post's images and add to global images array (for download later)
        var postImages = markdown.match(/\[!\[]\((.*?)\)/);
        if (postImages !== null) {
            postImages.forEach(function(image){
                images.push(image.replace('[![](', '').replace(/.(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG)\)/, '.$1'));
            });
        }

        return extend({
            id: i,
            title: title,
            slug: slug,
            markdown: markdown,
            html: html,
            image: null,
            featured: 0,
            page: 0,
            status: 'published',
            language: 'en_US',
            'meta_title': null,
            'meta_description': null,
            'author_id': 1,
            'created_at': published,
            'created_by': 1,
            'updated_at': Date.parse(post.updated['$t']),
            'updated_by': 1,
            'published_at': published,
            'published_by': 1
        }, post);
    }): [];

    var tagIds = {};
    var tags = json.feed.category ? json.feed.category.map(function(category, i) {
        var name = convertTag(category.term);

        tagIds[name] = i;

        return {
            id: i,
            name: name,
            slug: snakeCase(unidecode(name)),
            description: ''
        };
    }): [];

    var postsTags = json.feed.entry ? flatten(json.feed.entry.map(function(post, i) {
        if(!is.array(post.category)) {
            return [];
        }

        return post.category.map(function(category) {
            var term = convertTag(category.term);
            var tagId = tagIds[term];

            if(!is.defined(tagId)) {
                console.error(term + ' doesn\'t have a tag associated to it!');

                return {};
            }

            return {
                'tag_id': tagId,
                'post_id': i
            };
        });
    })): [];

    return {
        meta: {
            'exported_on': Date.now(),
            version: '000'
        },
        images: images,
        data: {
            posts: posts,
            tags: tags,
            'posts_tags': postsTags
        }
    };
};

function tomd(html) {
    var $ = cheerio.load(html);

    // remove links from img's that link to themselves
    $('a').replaceWith(function(i, e) {
        if ($(e).find('img').length) {
            if ($(e).attr('href') === $(e).find('img').first().attr('src')) {
                return $(e).find('img').first();
            }
        }

        return $(e);
    });

    html = $.html();

    // remove div's
    html = html.replace(/<div(.*?)>|<\/div>/gi, '');

    // remove span's
    html = html.replace(/<span(.*?)>|<\/span>/gi, '');

    // remove tables
    html = html.replace(/<table(.*?)>|<thead(.*?)>|<tbody(.*?)>|<tr(.*?)>|<td(.*?)>|<\/td>|<\/tr>|<\/tbody>|<\/thead>|<\/table>/gi, '');

    var markdown = toMarkdown(html);

    markdown = markdown
        .replace(/ /gi, ' ') // remove nbsp's
        .replace(/&/g, '&') // replace ampersands
        .replace(/  +/g, ' ') // remove double spaces
        .replace(/\!\[]\((.*?)\)/g, '![]($1)\n\n') // add double line break after images
        .replace(/(\n\s+)/g, '\n\n') // remove space at beginning of a line
        .trim(); // remove trailing whitespace

    // replace image paths
    markdown = markdown.replace(/\!\[\]\((\bhttps?:\/\/[^\s()<>]+(?:\([\w\d]+\)|[^[:punct:]\s]|\/))/ig, '![](/content/images/blogger/');

    return markdown;
}
<|endoftext|>


<commit_before>// @flow

import * as ls from './languageclient';
import {Point, Range} from 'atom';

// Public: Class that contains a number of helper methods for general conversions
// between the language server protocol and Atom/Atom packages.
export default class Convert {
  // Public: Convert a path to a Uri.
  //
  // * `filePath` A file path to convert to a Uri.
  //
  // Returns the Uri corresponding to the path. e.g. file:///a/b/c.txt
  static pathToUri(filePath: string): string {
    let newPath = filePath.replace(/\\/g, '/');
    if (newPath[0] !== '/') {
      newPath = `/${newPath}`;
    }
    return encodeURI(`file://${newPath}`).replace(/[?#]/g, encodeURIComponent);
  }

  // Public: Convert a Uri to a path.
  //
  // * `uri` A Uri to convert to a file path.
  //
  // Returns a file path corresponding to the Uri. e.g. /a/b/c.txt
  // If the Uri does not begin file: then it is returned as-is to allow Atom
  // to deal with http/https sources in the future.
  static uriToPath(uri: string): string {
    const url = require('url').parse(uri);
    if (url.protocol !== 'file:') {
      return uri;
    }

    let filePath = decodeURIComponent(url.path);
    if (process.platform === 'win32') {
      // Deal with Windows drive names
      if (filePath[0] === '/') {
        filePath = filePath.substr(1);
      }
      return filePath.replace(/\//g, '\\');
    }
    return filePath;
  }

  // Public: Convert an Atom {PointObject} to a language server {Position}.
  //
  // * `point` An Atom {PointObject} to convert from.
  //
  // Returns the {Position} representation of the Atom {PointObject}.
  static pointToPosition(point: atom$PointObject): ls.Position {
    return {line: point.row, character: point.column};
  }

  // Public: Convert a language server {Position} into an Atom {PointObject}.
  //
  // * 'position' A language server {Position} to convert from.
  //
  // Returns the Atom {PointObject} representation of the given {Position}.
  static positionToPoint(position: ls.Position): atom$Point {
    return new Point(position.line, position.character);
  }

  // Public: Convert a language server {Range} into an Atom {Range}.
  //
  // * 'range' A language server {Range} to convert from.
  //
  // Returns the Atom {Range} representation of the given language server {Range}.
  static lsRangeToAtomRange(range: ls.Range): atom$Range {
    return new Range(Convert.positionToPoint(range.start), Convert.positionToPoint(range.end));
  }

  // Public: Convert an Atom {Range} into an language server {Range}.
  //
  // * 'range' An Atom {Range} to convert from.
  //
  // Returns the language server {Range} representation of the given Atom {Range}.
  static atomRangeToLSRange(range: atom$Range): ls.Range {
    return {
      start: Convert.pointToPosition(range.start),
      end: Convert.pointToPosition(range.end),
    };
  }

  // Public: Create a {TextDocumentIdentifier} from an Atom {TextEditor}.
  //
  // * `editor` A {TextEditor} that will be used to form the uri property.
  //
  // Returns a {TextDocumentIdentifier} that has a `uri` property with the Uri for the
  // given editor's path.
  static editorToTextDocumentIdentifier(editor: atom$TextEditor): ls.TextDocumentIdentifier {
    return {uri: Convert.pathToUri(editor.getPath() || '')};
  }

  // Public: Create a {TextDocumentPositionParams} from a {TextEditor} and optional {Point}.
  //
  // * `editor` A {TextEditor} that will be used to form the uri property.
  // * `point`  An optional {Point} that will supply the position property. If not specified
  //            the current cursor position will be used.
  //
  // Returns a {TextDocumentPositionParams} that has textDocument property with the editors {TextDocumentIdentifier}
  // and a position property with the supplied point (or current cursor position when not specified).
  static editorToTextDocumentPositionParams(
    editor: atom$TextEditor,
    point: ?atom$Point,
  ): ls.TextDocumentPositionParams {
    return {
      textDocument: Convert.editorToTextDocumentIdentifier(editor),
      position: Convert.pointToPosition(point != null ? point : editor.getCursorBufferPosition()),
    };
  }

  // Public: Create a string of scopes for the atom text editor using the data-grammar selector from an
  // {Array} of grammarScope strings.
  //
  // * `grammarScopes` An {Array} of grammar scope string to convert from.
  //
  // Returns a single comma-separated list of CSS selectors targetting the grammars of Atom text editors.
  // e.g. `['c', 'cpp']` => `'atom-text-editor[data-grammar='c'], atom-text-editor[data-grammar='cpp']`
  static grammarScopesToTextEditorScopes(grammarScopes: Array<string>): string {
    return grammarScopes
      .map(g => `atom-text-editor[data-grammar="${Convert.encodeHTMLAttribute(g.replace(/\./g, ' '))}"]`)
      .join(', ');
  }

  // Public: Encode a string so that it can be safely used within a HTML attribute - i.e. replacing all quoted
  // values with their HTML entity encoded versions.  e.g. `Hello"` becomes `Hello"`
  //
  // * 's' A string to be encoded.
  //
  // Returns a string that is HTML attribute encoded by replacing &, <, >, " and ' with their HTML entity
  // named equivalents.
  static encodeHTMLAttribute(s: string): string {
    const attributeMap = {
      '&': '&',
      '<': '<',
      '>': '>',
      '"': '"',
      "'": ''',
    };
    return s.replace(/[&<>'"]/g, c => attributeMap[c]);
  }

  // Public: Convert an Atom File Event as received from atom.project.onDidChangeFiles and convert
  // it into an Array of Language Server Protocol {FileEvent} objects. Normally this will be a 1-to-1
  // but renames will be represented by a deletion and a subsequent creation as LSP does not know about
  // renames.
  //
  // * 'fileEvent' An {atom$ProjectFileEvent} to be converted.
  //
  // Returns an array of LSP {ls.FileEvent} objects that equivalent conversions to the fileEvent parameter.
  static atomFileEventToLSFileEvents(fileEvent: atom$ProjectFileEvent): ls.FileEvent[] {
    switch (fileEvent.action) {
      case 'created':
        return [{uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Created}];
      case 'modified':
        return [{uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Changed}];
      case 'deleted':
        return [{uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Deleted}];
      case 'renamed': {
        const results = [];
        if (fileEvent.oldPath) {
          results.push({uri: Convert.pathToUri(fileEvent.oldPath || ''), type: ls.FileChangeType.Deleted});
        }
        if (fileEvent.path) {
          results.push({uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Created});
        }
        return results;
      }
      default:
        return [];
    }
  }

  static atomIdeDiagnosticToLSDiagnostic(diagnostic: atomIde$Diagnostic): ls.Diagnostic {
    return {
      range: Convert.atomRangeToLSRange(diagnostic.range),
      severity: Convert.diagnosticTypeToLSSeverity(diagnostic.type),
      source: diagnostic.providerName,
      message: diagnostic.text || '',
    };
  }

  static diagnosticTypeToLSSeverity(type: atomIde$DiagnosticType): $Values<typeof ls.DiagnosticSeverity> {
    switch (type) {
      case 'Error':
        return ls.DiagnosticSeverity.Error;
      case 'Warning':
        return ls.DiagnosticSeverity.Warning;
      case 'Info':
        return ls.DiagnosticSeverity.Information;
      default:
        (type: empty);
        throw Error(`Unexpected diagnostic type ${type}`);
    }
  }

  // Public: Convert an array of language server protocol {TextEdit} objects to an
  // equivalent array of Atom {TextEdit} objects.
  //
  // * `textEdits` The language server protocol {TextEdit} objects to convert.
  //
  // Returns an {Array} of Atom {TextEdit} objects.
  static convertLsTextEdits(textEdits: ?Array<ls.TextEdit>): Array<atomIde$TextEdit> {
    return (textEdits || []).map(Convert.convertLsTextEdit);
  }

  // Public: Convert a language server protocol {TextEdit} object to the
  // Atom equivalent {TextEdit}.
  //
  // * `textEdits` The language server protocol {TextEdit} objects to convert.
  //
  // Returns an Atom {TextEdit} object.
  static convertLsTextEdit(textEdit: ls.TextEdit): atomIde$TextEdit {
    return {
      oldRange: Convert.lsRangeToAtomRange(textEdit.range),
      newText: textEdit.newText,
    };
  }
}
<commit_msg>Added a check that URL path is not undefined<commit_after>// @flow

import * as ls from './languageclient';
import {Point, Range} from 'atom';
import URL from 'url';

// Public: Class that contains a number of helper methods for general conversions
// between the language server protocol and Atom/Atom packages.
export default class Convert {
  // Public: Convert a path to a Uri.
  //
  // * `filePath` A file path to convert to a Uri.
  //
  // Returns the Uri corresponding to the path. e.g. file:///a/b/c.txt
  static pathToUri(filePath: string): string {
    let newPath = filePath.replace(/\\/g, '/');
    if (newPath[0] !== '/') {
      newPath = `/${newPath}`;
    }
    return encodeURI(`file://${newPath}`).replace(/[?#]/g, encodeURIComponent);
  }

  // Public: Convert a Uri to a path.
  //
  // * `uri` A Uri to convert to a file path.
  //
  // Returns a file path corresponding to the Uri. e.g. /a/b/c.txt
  // If the Uri does not begin file: then it is returned as-is to allow Atom
  // to deal with http/https sources in the future.
  static uriToPath(uri: string): string {
    const url = URL.parse(uri);
    if (url.protocol !== 'file:' || url.path === undefined) {
      return uri;
    }

    let filePath = decodeURIComponent(url.path);
    if (process.platform === 'win32') {
      // Deal with Windows drive names
      if (filePath[0] === '/') {
        filePath = filePath.substr(1);
      }
      return filePath.replace(/\//g, '\\');
    }
    return filePath;
  }

  // Public: Convert an Atom {PointObject} to a language server {Position}.
  //
  // * `point` An Atom {PointObject} to convert from.
  //
  // Returns the {Position} representation of the Atom {PointObject}.
  static pointToPosition(point: atom$PointObject): ls.Position {
    return {line: point.row, character: point.column};
  }

  // Public: Convert a language server {Position} into an Atom {PointObject}.
  //
  // * 'position' A language server {Position} to convert from.
  //
  // Returns the Atom {PointObject} representation of the given {Position}.
  static positionToPoint(position: ls.Position): atom$Point {
    return new Point(position.line, position.character);
  }

  // Public: Convert a language server {Range} into an Atom {Range}.
  //
  // * 'range' A language server {Range} to convert from.
  //
  // Returns the Atom {Range} representation of the given language server {Range}.
  static lsRangeToAtomRange(range: ls.Range): atom$Range {
    return new Range(Convert.positionToPoint(range.start), Convert.positionToPoint(range.end));
  }

  // Public: Convert an Atom {Range} into an language server {Range}.
  //
  // * 'range' An Atom {Range} to convert from.
  //
  // Returns the language server {Range} representation of the given Atom {Range}.
  static atomRangeToLSRange(range: atom$Range): ls.Range {
    return {
      start: Convert.pointToPosition(range.start),
      end: Convert.pointToPosition(range.end),
    };
  }

  // Public: Create a {TextDocumentIdentifier} from an Atom {TextEditor}.
  //
  // * `editor` A {TextEditor} that will be used to form the uri property.
  //
  // Returns a {TextDocumentIdentifier} that has a `uri` property with the Uri for the
  // given editor's path.
  static editorToTextDocumentIdentifier(editor: atom$TextEditor): ls.TextDocumentIdentifier {
    return {uri: Convert.pathToUri(editor.getPath() || '')};
  }

  // Public: Create a {TextDocumentPositionParams} from a {TextEditor} and optional {Point}.
  //
  // * `editor` A {TextEditor} that will be used to form the uri property.
  // * `point`  An optional {Point} that will supply the position property. If not specified
  //            the current cursor position will be used.
  //
  // Returns a {TextDocumentPositionParams} that has textDocument property with the editors {TextDocumentIdentifier}
  // and a position property with the supplied point (or current cursor position when not specified).
  static editorToTextDocumentPositionParams(
    editor: atom$TextEditor,
    point: ?atom$Point,
  ): ls.TextDocumentPositionParams {
    return {
      textDocument: Convert.editorToTextDocumentIdentifier(editor),
      position: Convert.pointToPosition(point != null ? point : editor.getCursorBufferPosition()),
    };
  }

  // Public: Create a string of scopes for the atom text editor using the data-grammar selector from an
  // {Array} of grammarScope strings.
  //
  // * `grammarScopes` An {Array} of grammar scope string to convert from.
  //
  // Returns a single comma-separated list of CSS selectors targetting the grammars of Atom text editors.
  // e.g. `['c', 'cpp']` => `'atom-text-editor[data-grammar='c'], atom-text-editor[data-grammar='cpp']`
  static grammarScopesToTextEditorScopes(grammarScopes: Array<string>): string {
    return grammarScopes
      .map(g => `atom-text-editor[data-grammar="${Convert.encodeHTMLAttribute(g.replace(/\./g, ' '))}"]`)
      .join(', ');
  }

  // Public: Encode a string so that it can be safely used within a HTML attribute - i.e. replacing all quoted
  // values with their HTML entity encoded versions.  e.g. `Hello"` becomes `Hello"`
  //
  // * 's' A string to be encoded.
  //
  // Returns a string that is HTML attribute encoded by replacing &, <, >, " and ' with their HTML entity
  // named equivalents.
  static encodeHTMLAttribute(s: string): string {
    const attributeMap = {
      '&': '&',
      '<': '<',
      '>': '>',
      '"': '"',
      "'": ''',
    };
    return s.replace(/[&<>'"]/g, c => attributeMap[c]);
  }

  // Public: Convert an Atom File Event as received from atom.project.onDidChangeFiles and convert
  // it into an Array of Language Server Protocol {FileEvent} objects. Normally this will be a 1-to-1
  // but renames will be represented by a deletion and a subsequent creation as LSP does not know about
  // renames.
  //
  // * 'fileEvent' An {atom$ProjectFileEvent} to be converted.
  //
  // Returns an array of LSP {ls.FileEvent} objects that equivalent conversions to the fileEvent parameter.
  static atomFileEventToLSFileEvents(fileEvent: atom$ProjectFileEvent): ls.FileEvent[] {
    switch (fileEvent.action) {
      case 'created':
        return [{uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Created}];
      case 'modified':
        return [{uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Changed}];
      case 'deleted':
        return [{uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Deleted}];
      case 'renamed': {
        const results = [];
        if (fileEvent.oldPath) {
          results.push({uri: Convert.pathToUri(fileEvent.oldPath || ''), type: ls.FileChangeType.Deleted});
        }
        if (fileEvent.path) {
          results.push({uri: Convert.pathToUri(fileEvent.path), type: ls.FileChangeType.Created});
        }
        return results;
      }
      default:
        return [];
    }
  }

  static atomIdeDiagnosticToLSDiagnostic(diagnostic: atomIde$Diagnostic): ls.Diagnostic {
    return {
      range: Convert.atomRangeToLSRange(diagnostic.range),
      severity: Convert.diagnosticTypeToLSSeverity(diagnostic.type),
      source: diagnostic.providerName,
      message: diagnostic.text || '',
    };
  }

  static diagnosticTypeToLSSeverity(type: atomIde$DiagnosticType): $Values<typeof ls.DiagnosticSeverity> {
    switch (type) {
      case 'Error':
        return ls.DiagnosticSeverity.Error;
      case 'Warning':
        return ls.DiagnosticSeverity.Warning;
      case 'Info':
        return ls.DiagnosticSeverity.Information;
      default:
        (type: empty);
        throw Error(`Unexpected diagnostic type ${type}`);
    }
  }

  // Public: Convert an array of language server protocol {TextEdit} objects to an
  // equivalent array of Atom {TextEdit} objects.
  //
  // * `textEdits` The language server protocol {TextEdit} objects to convert.
  //
  // Returns an {Array} of Atom {TextEdit} objects.
  static convertLsTextEdits(textEdits: ?Array<ls.TextEdit>): Array<atomIde$TextEdit> {
    return (textEdits || []).map(Convert.convertLsTextEdit);
  }

  // Public: Convert a language server protocol {TextEdit} object to the
  // Atom equivalent {TextEdit}.
  //
  // * `textEdits` The language server protocol {TextEdit} objects to convert.
  //
  // Returns an Atom {TextEdit} object.
  static convertLsTextEdit(textEdit: ls.TextEdit): atomIde$TextEdit {
    return {
      oldRange: Convert.lsRangeToAtomRange(textEdit.range),
      newText: textEdit.newText,
    };
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');

fs.createReadStream("../template/sample.md").pipe(fs.createWriteStream("../../README.md"));<commit_msg>test2<commit_after>var fs = require('fs');

function copyFile(source, target, cb) {
    var cbCalled = false;

    var rd = fs.createReadStream(source);
    rd.on("error", function(err) {
        done(err);
    });
    var wr = fs.createWriteStream(target);
    wr.on("error", function(err) {
        done(err);
    });
    wr.on("close", function(ex) {
        done();
    });
    rd.pipe(wr);

    function done(err) {
        if (!cbCalled) {
            cb(err);
            cbCalled = true;
        }
    }
}

copyFile("../templates/sample.md","../../README.md",function(){console.log('done')});<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var codecs = require('./codecs');

/**
 * Expose `Decoder`.
 */

exports = module.exports = Decoder;

/**
 * Initialize a new `Decoder`.
 *
 * The "Decoder" encapsulates message framing and
 * applying of codecs for each message received.
 *
 * @api private
 */

function Decoder(){
  this.buff = new Buffer(4);
  this.i = 0;
  this.state = 'header';
  this.headers = null;
  this.body = null;
}

/**
 * Temporary stub. Calling context should impement this
 * in order to receive the parsed message(s).
 *
 * @param {Mixed} message
 * @api private
 */

Decoder.prototype.onmessage = function(msg){};

/**
 * Frame the given `chunk`.
 *
 * @param {Buffer} chunk
 * @api private
 */

Decoder.prototype.write = function(chunk){
  switch (this.state) {
    case 'header': this.frameHeader(chunk); break;
    case 'body': this.frameBody(chunk); break;
    default: throw new Error('invalid state "' + this.state + '"');
  }
};

/**
 * Frame headers.
 *
 * @param {Buffer} chunk
 * @api private
 */

Decoder.prototype.frameHeader = function(chunk) {
  var remaining = 4 - this.i;

  var n = remaining > chunk.length
    ? chunk.length
    : remaining;

  // buffer
  for (var i = 0; i < n; i++) {
    this.buff[this.i++] = chunk[i];
  }

  // complete
  if (4 === this.i) {
    this.state = 'body';
    this.i = 0;
    this.headers = this.parseHeaders(this.buff);
    this.body = new Buffer(this.headers.length);
  }

  // remaining chunks
  if (chunk.length - n) this.write(chunk.slice(n));
};

/**
 * Frame body.
 *
 * @param {Buffer} chunk
 * @api private
 */

Decoder.prototype.frameBody = function(chunk) {
  var remaining = this.headers.length - this.i;

  var n = remaining > chunk.length
    ? chunk.length
    : remaining;

  var multipart = this.headers.meta === 0x00;

  // buffer
  chunk.copy(this.body, this.i, 0, n);
  this.i += n;

  // complete
  if (this.headers.length === this.i) {
    this.onmessage(this.parseBody(this.body, this.headers), multipart);
    this.reset();
  }

  // bytes remaining
  if (chunk.length - n) this.write(chunk.slice(n));
};

/**
 * Parsers out `meta` and `length` header octets.
 *
 * @param {Buffer} buff
 * @return {Object}
 * @api private
 */

Decoder.prototype.parseHeaders = function(buff) {
  var meta = buff[0]
    , len = 0;

  // zero out MSB
  buff[0] = 0x0;
  len = buff.readUInt32BE(0);

  // undo side-effect
  buff[0] = meta;

  return {
    length: len,
    meta: meta
  };
};

/**
 * Parses out multipart messages.
 *
 * @param {Buffer} buff
 * @return {Boolean} multipart
 * @api private
 */

Decoder.prototype.parseBody = function(body, headers) {
  var multipart = headers.meta === 0x00;
  var msgs = []
    , buff
    , header;

  if (!multipart) return this.decode(body, headers.meta);

  for (var i = 0; i < body.length;) {
    header = this.parseHeaders(body.slice(i, i + 4));
    buff = body.slice(i + 4, i + header.length + 4);
    msgs.push(this.decode(buff, header.meta));
    i += header.length + 4;
  }

  return msgs;
};

/**
 * Apply the codec `type` to `msg`.
 *
 * @param {Buffer} msg
 * @param {String} fmt
 * @return {Mixed} decoded message
 * @api private
 */

Decoder.prototype.decode = function(msg, type) {
  var codec = codecs.byId(type);
  return codec.decode(msg);
};

/**
 * Set/resets to the default state.
 */

Decoder.prototype.reset = function() {
  this.state = 'header';
  this.i = 0;
  this.buff.fill(0x0);
  this.headers = null;
  this.body = null;
};

<commit_msg>Go back to small if/else branch rather than switch statement<commit_after>
/**
 * Module dependencies.
 */

var codecs = require('./codecs');

/**
 * Expose `Decoder`.
 */

exports = module.exports = Decoder;

/**
 * Initialize a new `Decoder`.
 *
 * The "Decoder" encapsulates message framing and
 * applying of codecs for each message received.
 *
 * @api private
 */

function Decoder(){
  this.buff = new Buffer(4);
  this.i = 0;
  this.state = 'header';
  this.headers = null;
  this.body = null;
}

/**
 * Temporary stub. Calling context should impement this
 * in order to receive the parsed message(s).
 *
 * @param {Mixed} message
 * @api private
 */

Decoder.prototype.onmessage = function(msg){};

/**
 * Frame the given `chunk`.
 *
 * @param {Buffer} chunk
 * @api private
 */

Decoder.prototype.write = function(chunk){
  if ('header' == this.state) this.frameHeader(chunk)
  else this.frameBody(chunk);
};

/**
 * Frame headers.
 *
 * @param {Buffer} chunk
 * @api private
 */

Decoder.prototype.frameHeader = function(chunk) {
  var remaining = 4 - this.i;

  var n = remaining > chunk.length
    ? chunk.length
    : remaining;

  // buffer
  for (var i = 0; i < n; i++) {
    this.buff[this.i++] = chunk[i];
  }

  // complete
  if (4 === this.i) {
    this.state = 'body';
    this.i = 0;
    this.headers = this.parseHeaders(this.buff);
    this.body = new Buffer(this.headers.length);
  }

  // remaining chunks
  if (chunk.length - n) this.write(chunk.slice(n));
};

/**
 * Frame body.
 *
 * @param {Buffer} chunk
 * @api private
 */

Decoder.prototype.frameBody = function(chunk) {
  var remaining = this.headers.length - this.i;

  var n = remaining > chunk.length
    ? chunk.length
    : remaining;

  var multipart = this.headers.meta === 0x00;

  // buffer
  chunk.copy(this.body, this.i, 0, n);
  this.i += n;

  // complete
  if (this.headers.length === this.i) {
    this.onmessage(this.parseBody(this.body, this.headers), multipart);
    this.reset();
  }

  // bytes remaining
  if (chunk.length - n) this.write(chunk.slice(n));
};

/**
 * Parsers out `meta` and `length` header octets.
 *
 * @param {Buffer} buff
 * @return {Object}
 * @api private
 */

Decoder.prototype.parseHeaders = function(buff) {
  var meta = buff[0]
    , len = 0;

  // zero out MSB
  buff[0] = 0x0;
  len = buff.readUInt32BE(0);

  // undo side-effect
  buff[0] = meta;

  return {
    length: len,
    meta: meta
  };
};

/**
 * Parses out multipart messages.
 *
 * @param {Buffer} buff
 * @return {Boolean} multipart
 * @api private
 */

Decoder.prototype.parseBody = function(body, headers) {
  var multipart = headers.meta === 0x00;
  var msgs = []
    , buff
    , header;

  if (!multipart) return this.decode(body, headers.meta);

  for (var i = 0; i < body.length;) {
    header = this.parseHeaders(body.slice(i, i + 4));
    buff = body.slice(i + 4, i + header.length + 4);
    msgs.push(this.decode(buff, header.meta));
    i += header.length + 4;
  }

  return msgs;
};

/**
 * Apply the codec `type` to `msg`.
 *
 * @param {Buffer} msg
 * @param {String} fmt
 * @return {Mixed} decoded message
 * @api private
 */

Decoder.prototype.decode = function(msg, type) {
  var codec = codecs.byId(type);
  return codec.decode(msg);
};

/**
 * Set/resets to the default state.
 */

Decoder.prototype.reset = function() {
  this.state = 'header';
  this.i = 0;
  this.buff.fill(0x0);
  this.headers = null;
  this.body = null;
};

<|endoftext|>


<commit_before>/**
 * empower.js - Power Assert feature enhancer for assert function/object.
 *
 * https://github.com/twada/empower
 *
 * Copyright (c) 2013 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/empower/master/MIT-LICENSE.txt
 *
 * A part of extend function is:
 *   Copyright 2012 jQuery Foundation and other contributors
 *   Released under the MIT license.
 *   http://jquery.org/license
 */
(function (root, factory) {
    'use strict';

    // using returnExports UMD pattern
    if (typeof define === 'function' && define.amd) {
        define(['./power-assert-formatter'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('./power-assert-formatter'));
    } else {
        root.empower = factory(root.powerAssertFormatter);
    }
}(this, function (defaultFormatter) {
    'use strict';

    function defaultOptions () {
        return {
            destructive: false,
            formatter: defaultFormatter,
            lineSeparator: '\n',
            targetMethods: {
                oneArg: [
                    'ok'
                ],
                twoArgs: [
                    'equal',
                    'notEqual',
                    'strictEqual',
                    'notStrictEqual',
                    'deepEqual',
                    'notDeepEqual'
                ]
            }
        };
    }

    /**
     * Enhance Power Assert feature to assert function/object.
     * @param assert target assert function or object to enhance
     * @param options enhancement options
     * @return enhanced assert function/object
     */
    function empower (assert, options) {
        var typeOfAssert = (typeof assert),
            config;
        if ((typeOfAssert !== 'object' && typeOfAssert !== 'function') || assert === null) {
            throw new TypeError('empower argument should be a function or object.');
        }
        if (isEmpowered(assert)) {
            return assert;
        }
        config = extend(defaultOptions(), (options || {}));
        switch (typeOfAssert) {
        case 'function':
            return empowerAssertFunction(assert, config);
        case 'object':
            return empowerAssertObject(assert, config);
        default:
            throw new Error('Cannot be here');
        }
    }

    function empowerAssertObject (assertObject, config) {
        if (typeof assertObject.ok !== 'function') {
            throw new TypeError('empower target object should be respond to \'ok\' method.');
        }
        var enhancement = enhance(assertObject, config),
            target = config.destructive ? assertObject : Object.create(assertObject);
        return extend(target, enhancement);
    }

    function empowerAssertFunction (assertFunction, config) {
        if (config.destructive) {
            throw new Error('cannot use destructive:true to function.');
        }
        var enhancement = enhance(assertFunction, config),
            powerAssert = function powerAssert (context, message) {
                enhancement.ok(context, message);
            };
        extend(powerAssert, assertFunction);
        return extend(powerAssert, enhancement);
    }

    function isEmpowered (assertObjectOrFunction) {
        return (typeof assertObjectOrFunction._capt === 'function') && (typeof assertObjectOrFunction._expr === 'function');
    }

    function enhance (target, config) {
        var events = [],
            proxy = {};

        function PowerAssertContext (arg) {
            this.context = arg;
        }

        function _capt (value, kind, location) {
            events.push({value: value, kind: kind, location: location});
            return value;
        }

        function _expr (value, location, content) {
            var captured = events;
            events = [];
            return new PowerAssertContext({value: value, location: location, content: content, events: captured});
        }

        function singleArgAssert (baseAssert) {
            return function (value, message) {
                var context, powerAssertText;
                if (value instanceof PowerAssertContext) {
                    context = value.context;
                    powerAssertText = config.formatter.format(context).join(config.lineSeparator);
                    baseAssert(context.value, message ? message + ' ' + powerAssertText : powerAssertText);
                } else {
                    baseAssert(value, message);
                }
            };
        }

        function doubleArgsAssert (baseAssert) {
            return function (arg1, arg2, message) {
                var context, val1, val2, powerAssertText;
                if ((arg1 instanceof PowerAssertContext) || (arg2 instanceof PowerAssertContext)) {
                    if (arg1 instanceof PowerAssertContext) {
                        context = extend({}, arg1.context);
                        val1 = arg1.context.value;
                    } else {
                        val1 = arg1;
                    }
                    if (arg2 instanceof PowerAssertContext) {
                        if (context.events) {
                            context.events = context.events.concat(arg2.context.events);
                        } else {
                            context = extend({}, arg2.context);
                        }
                        val2 = arg2.context.value;
                    } else {
                        val2 = arg2;
                    }
                    powerAssertText = config.formatter.format(context).join(config.lineSeparator);
                    baseAssert(val1, val2, message ? message + ' ' + powerAssertText : powerAssertText);
                } else {
                    baseAssert(arg1, arg2, message);
                }
            };
        }

        config.targetMethods.oneArg.forEach(function (methodName) {
            if (typeof target[methodName] === 'function') {
                proxy[methodName] = singleArgAssert(bind(target[methodName], target));
            }
        });
        config.targetMethods.twoArgs.forEach(function (methodName) {
            if (typeof target[methodName] === 'function') {
                proxy[methodName] = doubleArgsAssert(bind(target[methodName], target));
            }
        });
        proxy._capt = _capt;
        proxy._expr = _expr;
        return proxy;
    }

    // borrowed from qunit.js
    function extend (a, b) {
        var prop;
        for (prop in b) {
            if (b.hasOwnProperty(prop)) {
                if (typeof b[prop] === 'undefined') {
                    delete a[prop];
                } else {
                    a[prop] = b[prop];
                }
            }
        }
        return a;
    }

    // borrowed from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
    function bind (aFunction, oThis) {
        if (typeof aFunction !== 'function') {
            throw new TypeError('bind - what is trying to be bound is not callable');
        }
        var aArgs = Array.prototype.slice.call(arguments, 2),
            fToBind = aFunction,
            NOP = function () {},
            fBound = function () {
                return fToBind.apply(((aFunction instanceof NOP) && oThis) ? aFunction : oThis,
                                     aArgs.concat(Array.prototype.slice.call(arguments)));
            };
        NOP.prototype = aFunction.prototype;
        fBound.prototype = new NOP();
        return fBound;
    }

    // using returnExports UMD pattern with substack pattern
    empower.defaultOptions = defaultOptions;
    return empower;
}));
<commit_msg>Extract assert proxy functions out from closure.<commit_after>/**
 * empower.js - Power Assert feature enhancer for assert function/object.
 *
 * https://github.com/twada/empower
 *
 * Copyright (c) 2013 Takuto Wada
 * Licensed under the MIT license.
 *   https://raw.github.com/twada/empower/master/MIT-LICENSE.txt
 *
 * A part of extend function is:
 *   Copyright 2012 jQuery Foundation and other contributors
 *   Released under the MIT license.
 *   http://jquery.org/license
 */
(function (root, factory) {
    'use strict';

    // using returnExports UMD pattern
    if (typeof define === 'function' && define.amd) {
        define(['./power-assert-formatter'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('./power-assert-formatter'));
    } else {
        root.empower = factory(root.powerAssertFormatter);
    }
}(this, function (defaultFormatter) {
    'use strict';

    function defaultOptions () {
        return {
            destructive: false,
            formatter: defaultFormatter,
            lineSeparator: '\n',
            targetMethods: {
                oneArg: [
                    'ok'
                ],
                twoArgs: [
                    'equal',
                    'notEqual',
                    'strictEqual',
                    'notStrictEqual',
                    'deepEqual',
                    'notDeepEqual'
                ]
            }
        };
    }

    /**
     * Enhance Power Assert feature to assert function/object.
     * @param assert target assert function or object to enhance
     * @param options enhancement options
     * @return enhanced assert function/object
     */
    function empower (assert, options) {
        var typeOfAssert = (typeof assert),
            config;
        if ((typeOfAssert !== 'object' && typeOfAssert !== 'function') || assert === null) {
            throw new TypeError('empower argument should be a function or object.');
        }
        if (isEmpowered(assert)) {
            return assert;
        }
        config = extend(defaultOptions(), (options || {}));
        switch (typeOfAssert) {
        case 'function':
            return empowerAssertFunction(assert, config);
        case 'object':
            return empowerAssertObject(assert, config);
        default:
            throw new Error('Cannot be here');
        }
    }

    function isEmpowered (assertObjectOrFunction) {
        return (typeof assertObjectOrFunction._capt === 'function') && (typeof assertObjectOrFunction._expr === 'function');
    }

    function empowerAssertObject (assertObject, config) {
        if (typeof assertObject.ok !== 'function') {
            throw new TypeError('empower target object should be respond to \'ok\' method.');
        }
        var enhancement = enhance(assertObject, config),
            target = config.destructive ? assertObject : Object.create(assertObject);
        return extend(target, enhancement);
    }

    function empowerAssertFunction (assertFunction, config) {
        if (config.destructive) {
            throw new Error('cannot use destructive:true to function.');
        }
        var enhancement = enhance(assertFunction, config),
            powerAssert = function powerAssert (context, message) {
                enhancement.ok(context, message);
            };
        extend(powerAssert, assertFunction);
        return extend(powerAssert, enhancement);
    }

    function enhance (target, config) {
        var events = [],
            proxy = {};

        function _capt (value, kind, location) {
            events.push({value: value, kind: kind, location: location});
            return value;
        }

        function _expr (value, location, content) {
            var captured = events;
            events = [];
            return new PowerAssertContext({value: value, location: location, content: content, events: captured});
        }

        config.targetMethods.oneArg.forEach(function (methodName) {
            if (typeof target[methodName] === 'function') {
                proxy[methodName] = singleArgAssert(bind(target[methodName], target), config);
            }
        });
        config.targetMethods.twoArgs.forEach(function (methodName) {
            if (typeof target[methodName] === 'function') {
                proxy[methodName] = doubleArgsAssert(bind(target[methodName], target), config);
            }
        });

        proxy._capt = _capt;
        proxy._expr = _expr;
        return proxy;
    }

    function PowerAssertContext (arg) {
        this.context = arg;
    }

    function singleArgAssert (baseAssert, config) {
        return function (value, message) {
            var context, powerAssertText;
            if (value instanceof PowerAssertContext) {
                context = value.context;
                powerAssertText = config.formatter.format(context).join(config.lineSeparator);
                baseAssert(context.value, message ? message + ' ' + powerAssertText : powerAssertText);
            } else {
                baseAssert(value, message);
            }
        };
    }

    function doubleArgsAssert (baseAssert, config) {
        return function (arg1, arg2, message) {
            var context, val1, val2, powerAssertText;
            if ((arg1 instanceof PowerAssertContext) || (arg2 instanceof PowerAssertContext)) {
                if (arg1 instanceof PowerAssertContext) {
                    context = extend({}, arg1.context);
                    val1 = arg1.context.value;
                } else {
                    val1 = arg1;
                }
                if (arg2 instanceof PowerAssertContext) {
                    if (context.events) {
                        context.events = context.events.concat(arg2.context.events);
                    } else {
                        context = extend({}, arg2.context);
                    }
                    val2 = arg2.context.value;
                } else {
                    val2 = arg2;
                }
                powerAssertText = config.formatter.format(context).join(config.lineSeparator);
                baseAssert(val1, val2, message ? message + ' ' + powerAssertText : powerAssertText);
            } else {
                baseAssert(arg1, arg2, message);
            }
        };
    }

    // borrowed from qunit.js
    function extend (a, b) {
        var prop;
        for (prop in b) {
            if (b.hasOwnProperty(prop)) {
                if (typeof b[prop] === 'undefined') {
                    delete a[prop];
                } else {
                    a[prop] = b[prop];
                }
            }
        }
        return a;
    }

    // borrowed from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
    function bind (aFunction, oThis) {
        if (typeof aFunction !== 'function') {
            throw new TypeError('bind - what is trying to be bound is not callable');
        }
        var aArgs = Array.prototype.slice.call(arguments, 2),
            fToBind = aFunction,
            NOP = function () {},
            fBound = function () {
                return fToBind.apply(((aFunction instanceof NOP) && oThis) ? aFunction : oThis,
                                     aArgs.concat(Array.prototype.slice.call(arguments)));
            };
        NOP.prototype = aFunction.prototype;
        fBound.prototype = new NOP();
        return fBound;
    }

    // using returnExports UMD pattern with substack pattern
    empower.defaultOptions = defaultOptions;
    return empower;
}));
<|endoftext|>


<commit_before>'use strict';

const
	$C = require('collection.js'),
	Sugar = require('sugar'),
	fs = require('fs-extra-promise'),
	vinyl = require('vinyl-fs'),
	path = require('upath');

const
	Block = require('./block'),
	{entry, entryDependencies, lib, isNodeModule} = require('./resolve'),
	{blockName} = require('./validators');

const
	hasImport = /^import\s+(['"])(.*?)\1;?/,
	entriesDir = new RegExp(`^(?:${$C(entryDependencies).map(Sugar.RegExp.escape).join('|')})(?:[/\\\\]|$)`),
	insideEntry = /^\.\//,
	eol = /\r?\n|\r/;

/**
 * Returns a name for a common chunk by the specified id
 * @param {(string|number)} id
 */
function getCommonName(id) {
	return `common_${id}`;
}

/**
 * Returns a graph with dependencies and union entry points from the specified entries
 *
 * @param entries
 * @param {Map<string, !Block>=} [cache] - optional cache object with predefined blocks
 * @returns {!Promise<{dependencies: Object<string, !Set<string>>, entry: Object<string, !Map<string, !Block>>}>}
 */
async function getUnionEntryPoints(entries, {cache} = {}) {
	const
		packs = Object.create(null),
		weights = Object.create(null);

	await $C(entries).parallel().forEach(async (el) => {
		const
			key = path.basename(el.path, '.js'),
			deps = packs[key] = await getEntryRuntimeDependencies(path.dirname(el.path), el.source, {cache});

		const walk = (block) => {
			const
				name = block.name || block;

			if (name in weights) {
				const
					w = weights[name];

				w.i++;
				if (w.isParent) {
					w.isParent = deps.parents.has(name);
				}

			} else {
				weights[name] = {
					i: 0,
					name,
					isParent: deps.parents.has(name)
				};
			}
		};

		$C(deps.runtime).forEach(walk);
		$C(deps.libs).forEach(walk);
	});

	// Find common modules (weight > 1)

	const commonPacks = $C(weights).to([]).reduce((arr, el, key) => {
		if (el.i > 1) {
			const pos = $C(entries).length() - el.i - 1;
			arr[pos] = (arr[pos] || new Map()).set(key, el);
		}

		return arr;
	});

	// Remove empty modules
	$C(commonPacks).remove((el) => !el);

	const getTopParents = (entry, set = new Set(), first = true) => {
		const
			obj = entries[entry];

		if (!obj) {
			set.add(entry);
			return set;
		}

		const
			{parents} = obj;

		if (parents.size) {
			$C(parents).forEach((entry) => getTopParents(entry, set, false));

		} else if (!first) {
			set.add(entry);
		}

		return set;
	};

	const dependencies = await $C(packs)
		.parallel()
		.to({})
		.reduce(async (map, deps, name) => {
			const
				depSet = new Set();

			$C(deps.runtime).forEach((el, block) => {
				const
					pos = $C(commonPacks).one.search((map) => map.has(block));

				if (pos !== null) {
					depSet.add(pos);
					deps.runtime.delete(block);
				}
			});

			const depList = [...depSet].sort((a, b) => a - b).map((i) => getCommonName(i));
			map[name] = new Set([...getTopParents(name), ...depList]);
			return map;
		});

	const entry = $C(commonPacks).to({}).reduce((map, deps, i) => {
		map[getCommonName(i)] = deps;
		return map;
	});

	$C(packs).forEach((deps, name) => {
		entry[name] = $C(deps.runtime).to(new Map()).reduce((map, block, name) => map.set(name, {
			name,
			isParent: deps.parents.has(name)
		}));
	});

	return {dependencies, entry};
}

/**
 * Returns a list of imports from the specified entry file
 *
 * @param {string} dir - entry directory
 * @param {string} content - file content
 * @param {!Array} [arr]
 * @returns {!Array<string>}
 */
function getEntryImports(dir, content, arr = []) {
	$C(content.split(eol)).forEach((line) => {
		if (!hasImport.test(line)) {
			return;
		}

		const
			url = RegExp.$2,
			nodeModule = isNodeModule(url);

		if (nodeModule && entriesDir.test(url) || insideEntry.test(url)) {
			const
				d = nodeModule ? lib : dir;

			let
				f = path.join(d, `${url}.js`);

			if (!fs.existsSync(f)) {
				f = path.join(d, url, 'index.js');
			}

			getEntryImports(path.dirname(f), fs.readFileSync(f, 'utf-8'), arr);

		} else {
			arr.push(nodeModule ? url : path.join(dir, url));
		}
	});

	return arr;
}

/**
 * Returns a set of parent entries for the specified entry
 *
 * @param {string} content - file content
 * @returns {!Set<string>}
 */
function getEntryParents(content) {
	const
		parents = new Set(),
		clrfx = /\.\//;

	$C(content.split(eol)).forEach((line) => {
		if (!hasImport.test(line)) {
			return;
		}

		const
			url = RegExp.$2;

		if (isNodeModule(url) && entriesDir.test(url) || insideEntry.test(url)) {
			parents.add(url.replace(clrfx, ''));
		}
	});

	return parents;
}

/**
 * Returns a graph with dependencies for an entry file
 *
 * @param {string} dir - entry directory
 * @param {string} content - file content
 * @param {Map<string, !Block>=} [cache] - optional cache object with predefined blocks
 * @returns {!Promise<{runtime: !Map<string, !Block>, parents: !Map<string, !Block>, libs: !Set<string>}>}
 */
async function getEntryRuntimeDependencies(dir, content, {cache} = {}) {
	const deps = {
		runtime: new Map(),
		parents: new Map(),
		libs: new Set()
	};

	const
		runtime = new Set();

	await $C(getEntryImports(dir, content)).async.forEach(async (el) => {
		const
			name = path.basename(el, path.extname(el)),
			block = cache ? cache.get(name) : await Block.get(name);

		if (!blockName(name) || !block) {
			deps.runtime.set(el, el);
			return;
		}

		const
			blockDeps = await block.getRuntimeDependencies({cache});

		$C(blockDeps.runtime).forEach((obj, block) => {
			if (!blockDeps.parents.has(block)) {
				runtime.add(block);
			}
		});

		deps.runtime = new Map([...deps.runtime.entries(), ...blockDeps.runtime.entries()]);
		deps.parents = new Map(
			$C([...deps.parents.entries(), ...blockDeps.parents.entries()])
				.filter(([block]) => !runtime.has(block))
				.map()
		);

		deps.libs = new Set([...deps.libs, ...blockDeps.libs]);
	});

	return deps;
}

/**
 * Returns build config for entries
 * @returns {!Promise<!{entries, dependencies, commons}>}
 */
async function getBuildConfig() {
	const entries = await $C(vinyl.src(path.join(entry(), '*.js'), {read: false}))
		.async
		.to({})
		.reduce((res, el) => {
			const
				src = el.path,
				name = path.basename(src, '.js');

			let source;
			function getSource() {
				source = source || fs.readFileSync(src, 'utf-8');
				return source;
			}

			res[name] = {
				path: src,

				get source() {
					return getSource();
				},

				get parent() {
					return $C(getEntryParents(getSource())).one.get();
				},

				get parents() {
					return getEntryParents(getSource());
				},

				getRuntimeDependencies({cache} = {}) {
					return getEntryRuntimeDependencies(path.dirname(src), getSource(), {cache});
				}
			};

			return res;
		});

	function factory(entries) {
		function filter(cb) {
			return factory($C(entries).filter(cb).map());
		}

		return {
			entries,
			filter,
			getUnionEntryPoints({cache} = {}) {
				return getUnionEntryPoints(entries, {cache});
			}
		};
	}

	return factory(entries);
}

module.exports = {
	getCommonName,
	getBuildConfig
};
<commit_msg>Don't skip extensions of imports<commit_after>'use strict';

const
	$C = require('collection.js'),
	Sugar = require('sugar'),
	fs = require('fs-extra-promise'),
	vinyl = require('vinyl-fs'),
	path = require('upath');

const
	Block = require('./block'),
	{entry, entryDependencies, lib, isNodeModule} = require('./resolve'),
	{blockName} = require('./validators');

const
	hasImport = /^import\s+(['"])(.*?)\1;?/,
	entriesDir = new RegExp(`^(?:${$C(entryDependencies).map(Sugar.RegExp.escape).join('|')})(?:[/\\\\]|$)`),
	insideEntry = /^\.\//,
	eol = /\r?\n|\r/;

/**
 * Returns a name for a common chunk by the specified id
 * @param {(string|number)} id
 */
function getCommonName(id) {
	return `common_${id}`;
}

/**
 * Returns a graph with dependencies and union entry points from the specified entries
 *
 * @param entries
 * @param {Map<string, !Block>=} [cache] - optional cache object with predefined blocks
 * @returns {!Promise<{dependencies: Object<string, !Set<string>>, entry: Object<string, !Map<string, !Block>>}>}
 */
async function getUnionEntryPoints(entries, {cache} = {}) {
	const
		packs = Object.create(null),
		weights = Object.create(null);

	await $C(entries).parallel().forEach(async (el) => {
		const
			key = path.basename(el.path, '.js'),
			deps = packs[key] = await getEntryRuntimeDependencies(path.dirname(el.path), el.source, {cache});

		const walk = (block) => {
			const
				name = block.name || block;

			if (name in weights) {
				const
					w = weights[name];

				w.i++;
				if (w.isParent) {
					w.isParent = deps.parents.has(name);
				}

			} else {
				weights[name] = {
					i: 0,
					name,
					isParent: deps.parents.has(name)
				};
			}
		};

		$C(deps.runtime).forEach(walk);
		$C(deps.libs).forEach(walk);
	});

	// Find common modules (weight > 1)

	const commonPacks = $C(weights).to([]).reduce((arr, el, key) => {
		if (el.i > 1) {
			const pos = $C(entries).length() - el.i - 1;
			arr[pos] = (arr[pos] || new Map()).set(key, el);
		}

		return arr;
	});

	// Remove empty modules
	$C(commonPacks).remove((el) => !el);

	const getTopParents = (entry, set = new Set(), first = true) => {
		const
			obj = entries[entry];

		if (!obj) {
			set.add(entry);
			return set;
		}

		const
			{parents} = obj;

		if (parents.size) {
			$C(parents).forEach((entry) => getTopParents(entry, set, false));

		} else if (!first) {
			set.add(entry);
		}

		return set;
	};

	const dependencies = await $C(packs)
		.parallel()
		.to({})
		.reduce(async (map, deps, name) => {
			const
				depSet = new Set();

			$C(deps.runtime).forEach((el, block) => {
				const
					pos = $C(commonPacks).one.search((map) => map.has(block));

				if (pos !== null) {
					depSet.add(pos);
					deps.runtime.delete(block);
				}
			});

			const depList = [...depSet].sort((a, b) => a - b).map((i) => getCommonName(i));
			map[name] = new Set([...getTopParents(name), ...depList]);
			return map;
		});

	const entry = $C(commonPacks).to({}).reduce((map, deps, i) => {
		map[getCommonName(i)] = deps;
		return map;
	});

	$C(packs).forEach((deps, name) => {
		entry[name] = $C(deps.runtime).to(new Map()).reduce((map, block, name) => map.set(name, {
			name,
			isParent: deps.parents.has(name)
		}));
	});

	return {dependencies, entry};
}

/**
 * Returns a list of imports from the specified entry file
 *
 * @param {string} dir - entry directory
 * @param {string} content - file content
 * @param {!Array} [arr]
 * @returns {!Array<string>}
 */
function getEntryImports(dir, content, arr = []) {
	$C(content.split(eol)).forEach((line) => {
		if (!hasImport.test(line)) {
			return;
		}

		const
			url = RegExp.$2,
			nodeModule = isNodeModule(url);

		if (nodeModule && entriesDir.test(url) || insideEntry.test(url)) {
			const
				d = nodeModule ? lib : dir;

			let
				f = path.join(d, `${url}.js`);

			if (!fs.existsSync(f)) {
				f = path.join(d, url, 'index.js');
			}

			getEntryImports(path.dirname(f), fs.readFileSync(f, 'utf-8'), arr);

		} else {
			arr.push(nodeModule ? url : path.join(dir, url));
		}
	});

	return arr;
}

/**
 * Returns a set of parent entries for the specified entry
 *
 * @param {string} content - file content
 * @returns {!Set<string>}
 */
function getEntryParents(content) {
	const
		parents = new Set(),
		clrfx = /\.\//;

	$C(content.split(eol)).forEach((line) => {
		if (!hasImport.test(line)) {
			return;
		}

		const
			url = RegExp.$2;

		if (isNodeModule(url) && entriesDir.test(url) || insideEntry.test(url)) {
			parents.add(url.replace(clrfx, ''));
		}
	});

	return parents;
}

/**
 * Returns a graph with dependencies for an entry file
 *
 * @param {string} dir - entry directory
 * @param {string} content - file content
 * @param {Map<string, !Block>=} [cache] - optional cache object with predefined blocks
 * @returns {!Promise<{runtime: !Map<string, !Block>, parents: !Map<string, !Block>, libs: !Set<string>}>}
 */
async function getEntryRuntimeDependencies(dir, content, {cache} = {}) {
	const deps = {
		runtime: new Map(),
		parents: new Map(),
		libs: new Set()
	};

	const
		runtime = new Set();

	await $C(getEntryImports(dir, content)).async.forEach(async (el) => {
		const
			name = path.basename(el),
			block = cache ? cache.get(name) : await Block.get(name);

		if (!blockName(name) || !block) {
			deps.runtime.set(el, el);
			return;
		}

		const
			blockDeps = await block.getRuntimeDependencies({cache});

		$C(blockDeps.runtime).forEach((obj, block) => {
			if (!blockDeps.parents.has(block)) {
				runtime.add(block);
			}
		});

		deps.runtime = new Map([...deps.runtime.entries(), ...blockDeps.runtime.entries()]);
		deps.parents = new Map(
			$C([...deps.parents.entries(), ...blockDeps.parents.entries()])
				.filter(([block]) => !runtime.has(block))
				.map()
		);

		deps.libs = new Set([...deps.libs, ...blockDeps.libs]);
	});

	return deps;
}

/**
 * Returns build config for entries
 * @returns {!Promise<!{entries, dependencies, commons}>}
 */
async function getBuildConfig() {
	const entries = await $C(vinyl.src(path.join(entry(), '*.js'), {read: false}))
		.async
		.to({})
		.reduce((res, el) => {
			const
				src = el.path,
				name = path.basename(src, '.js');

			let source;
			function getSource() {
				source = source || fs.readFileSync(src, 'utf-8');
				return source;
			}

			res[name] = {
				path: src,

				get source() {
					return getSource();
				},

				get parent() {
					return $C(getEntryParents(getSource())).one.get();
				},

				get parents() {
					return getEntryParents(getSource());
				},

				getRuntimeDependencies({cache} = {}) {
					return getEntryRuntimeDependencies(path.dirname(src), getSource(), {cache});
				}
			};

			return res;
		});

	function factory(entries) {
		function filter(cb) {
			return factory($C(entries).filter(cb).map());
		}

		return {
			entries,
			filter,
			getUnionEntryPoints({cache} = {}) {
				return getUnionEntryPoints(entries, {cache});
			}
		};
	}

	return factory(entries);
}

module.exports = {
	getCommonName,
	getBuildConfig
};
<|endoftext|>


<commit_before>/*!
 * Escaper
 * https://github.com/kobezzza/Escaper
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Escaper/blob/master/LICENSE
 */

const Escaper = { VERSION: [2, 2, 25] };
export default Escaper;

const
	stringLiterals = {
		'"': true,
		'\'': true,
		'`': true
	},

	literals = {
		'/': true
	};

for (let key in stringLiterals) {
	if (!stringLiterals.hasOwnProperty(key)) {
		continue;
	}

	literals[key] = true;
}

const
	singleComments = {
		'//': true
	},

	multComments = {
		'/*': true,
		'/**': true,
		'/*!': true
	};

const
	keyArr = [],
	finalMap = {};

for (let key in literals) {
	if (!literals.hasOwnProperty(key)) {
		continue;
	}

	keyArr.push(key);
	finalMap[key] = true;
}

for (let key in singleComments) {
	if (!singleComments.hasOwnProperty(key)) {
		continue;
	}

	keyArr.push(key);
	finalMap[key] = true;
}

for (let key in multComments) {
	if (!multComments.hasOwnProperty(key)) {
		continue;
	}

	keyArr.push(key);
	finalMap[key] = true;
}

const
	rgxpFlags = [],
	rgxpFlagsMap = {
		'g': true,
		'm': true,
		'i': true,
		'y': true,
		'u': true
	};

for (let key in rgxpFlagsMap) {
	if (!rgxpFlagsMap.hasOwnProperty(key)) {
		continue;
	}

	rgxpFlags.push(key);
}

const
	escapeEndMap = {
		'-': true,
		'+': true,
		'*': true,
		'%': true,
		'~': true,
		'>': true,
		'<': true,
		'^': true,
		',': true,
		';': true,
		'=': true,
		'|': true,
		'&': true,
		'!': true,
		'?': true,
		':': true,
		'(': true,
		'{': true,
		'[': true
	};

const
	escapeEndWordMap = {
		'typeof': true,
		'void': true,
		'instanceof': true,
		'delete': true,
		'in': true,
		'new': true,
		'of': true
	};

const
	cache = {},
	content = [];

/**
 * @param {!Object} obj
 * @param {!Object} p
 * @param {(boolean|number)} val
 */
function mix(obj, p, val) {
	for (let key in obj) {
		if (!obj.hasOwnProperty(key)) {
			continue;
		}

		if (key in p === false) {
			p[key] = val;
		}
	}
}

/** @type {!Array} */
Escaper.quotContent = content;

const
	uSRgxp = /[^\s\/]/,
	wRgxp = /[a-z]/,
	sRgxp = /\s/,
	nRgxp = /\r|\n/;

let
	symbols,
	snakeskinRgxp;

Escaper.symbols = null;
Escaper.snakeskinRgxp = null;

const
	objMap = {
		'object': true,
		'function': true
	};

/**
 * Replaces all found blocks ' ... ', " ... ", ` ... `, / ... /, // ..., /* ... *\/ to
 * __ESCAPER_QUOT__number_ in a string and returns a new string
 *
 * @param {string} str - the source string
 * @param {(Object.<string, boolean>|boolean)=} [opt_withCommentsOrParams=false] - parameters:
 *
 *     (if a parameter value is set to -1, then all found matches will be removed from the final string,
 *          or if the value will be set to true/false they will be included/excluded)
 *
 *     *) @all      - replaces all found matches
 *     *) @comments - replaces all kinds of comments
 *     *) @strings  - replaces all kinds of string literals
 *     *) @literals - replaces all kinds of string literals and regular expressions
 *     *) `
 *     *) '
 *     *) "
 *     *) /
 *     *) //
 *     *) /*
 *     *) /**
 *     *) /*!
 *
 *     OR if the value is boolean, then will be replaced all found comments (true) / literals (false)
 *
 * @param {Array=} [opt_quotContent=Escaper.quotContent] - an array for matches
 * @param {?boolean=} [opt_snakeskin] - a private parameter for using with Snakeskin
 * @return {string}
 */
Escaper.replace = function (str, opt_withCommentsOrParams, opt_quotContent, opt_snakeskin) {
	symbols = symbols ||
		Escaper.symbols || 'a-z';

	snakeskinRgxp = snakeskinRgxp ||
		Escaper.snakeskinRgxp ||
		new RegExp(`[!$${symbols}_]`, 'i');

	const
		isObj = Boolean(
			opt_withCommentsOrParams &&
				objMap[typeof opt_withCommentsOrParams]
		),

		p = isObj ?
			Object(opt_withCommentsOrParams) : {};

	let withComments = false;
	if (typeof opt_withCommentsOrParams === 'boolean') {
		withComments = Boolean(opt_withCommentsOrParams);
	}

	if ('@comments' in p) {
		mix(multComments, p, p['@comments']);
		mix(singleComments, p, p['@comments']);
		delete p['@comments'];
	}

	if ('@strings' in p) {
		mix(stringLiterals, p, p['@strings']);
		delete p['@strings'];
	}

	if ('@literals' in p) {
		mix(literals, p, p['@literals']);
		delete p['@literals'];
	}

	if ('@all' in p) {
		mix(finalMap, p, p['@all']);
		delete p['@all'];
	}

	let cacheKey = '';
	for (let i = -1; ++i < keyArr.length;) {
		let el = keyArr[i];

		if (multComments[el] || singleComments[el]) {
			p[el] = withComments || p[el];

		} else {
			p[el] = p[el] || !isObj;
		}

		cacheKey += `${p[el]},`;
	}

	const
		initStr = str,
		stack = opt_quotContent || content;

	if (stack === content && cache[cacheKey] && cache[cacheKey][initStr]) {
		return cache[cacheKey][initStr];
	}

	let
		begin = false,
		end = true;

	let
		escape = false,
		comment = false;

	let
		selectionStart = 0,
		block = false;

	let
		templateVar = 0,
		filterStart = false;

	let
		cut,
		label;

	let
		part = '',
		rPart = '';

	for (let i = -1; ++i < str.length;) {
		let
			el = str.charAt(i),
			next = str.charAt(i + 1);

		let
			word = str.substr(i, 2),
			extWord = str.substr(i, 3);

		if (!comment) {
			if (!begin) {
				if (el === '/') {
					if (singleComments[word] || multComments[word]) {
						if (singleComments[extWord] || multComments[extWord]) {
							comment = extWord;

						} else {
							comment = word;
						}
					}

					if (comment) {
						selectionStart = i;
						continue;
					}
				}

				if (escapeEndMap[el] || escapeEndWordMap[rPart]) {
					end = true;
					rPart = '';

				} else if (uSRgxp.test(el)) {
					end = false;
				}

				if (wRgxp.test(el)) {
					part += el;

				} else {
					rPart = part;
					part = '';
				}

				let skip = false;
				if (opt_snakeskin) {
					if (el === '|' && snakeskinRgxp.test(next)) {
						filterStart = true;
						end = false;
						skip = true;

					} else if (filterStart && sRgxp.test(el)) {
						filterStart = false;
						end = true;
						skip = true;
					}
				}

				if (!skip) {
					if (escapeEndMap[el]) {
						end = true;

					} else if (uSRgxp.test(el)) {
						end = false;
					}
				}
			}

			// [] inside RegExp
			if (begin === '/' && !escape) {
				if (el === '[') {
					block = true;

				} else if (el === ']') {
					block = false;
				}
			}

			if (!begin && templateVar) {
				if (el === '}') {
					templateVar--;

				} else if (el === '{') {
					templateVar++;
				}

				if (!templateVar) {
					el = '`';
				}
			}

			if (begin === '`' && !escape && word === '${') {
				el = '`';
				i++;
				templateVar++;
			}

			if (finalMap[el] && (el !== '/' || end) && !begin) {
				begin = el;
				selectionStart = i;

			} else if (begin && (el === '\\' || escape)) {
				escape = !escape;

			} else if (finalMap[el] && begin === el && !escape && (begin !== '/' || !block)) {
				if (el === '/') {
					for (let j = -1; ++j < rgxpFlags.length;) {
						if (rgxpFlagsMap[str.charAt(i + 1)]) {
							i++;
						}
					}
				}

				begin = false;
				end = false;

				if (p[el]) {
					cut = str.substring(selectionStart, i + 1);

					if (p[el] === -1) {
						label = '';

					} else {
						label = `__ESCAPER_QUOT__${stack.length}_`;
						stack.push(cut);
					}

					str = str.substring(0, selectionStart) + label + str.substring(i + 1);
					i += label.length - cut.length;
				}
			}

		} else if ((nRgxp.test(next) && singleComments[comment]) ||
			(multComments[el + str.charAt(i - 1)] && i - selectionStart > 2 && multComments[comment])

		) {
			if (p[comment]) {
				cut = str.substring(selectionStart, i + 1);

				if (p[comment] === -1) {
					label = '';

				} else {
					label = `__ESCAPER_QUOT__${stack.length}_`;
					stack.push(cut);
				}

				str = str.substring(0, selectionStart) + label + str.substring(i + 1);
				i += label.length - cut.length;
			}

			comment = false;
		}
	}

	if (stack === content) {
		cache[cacheKey] = cache[cacheKey] || {};
		cache[cacheKey][initStr] = str;
	}

	return str;
};

const pasteRgxp = /__ESCAPER_QUOT__(\d+)_/g;

/**
 * Replaces all found blocks __ESCAPER_QUOT__number_ to real content in a string
 * and returns a new string
 *
 * @param {string} str - the source string
 * @param {Array=} [opt_quotContent=Escaper.quotContent] - an array of matches
 * @return {string}
 */
Escaper.paste = function (str, opt_quotContent) {
	return str.replace(pasteRgxp, (sstr, pos) => (opt_quotContent || content)[pos]);
};
<commit_msg>Added new literals and parameters<commit_after>/*!
 * Escaper
 * https://github.com/kobezzza/Escaper
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Escaper/blob/master/LICENSE
 */

const Escaper = { VERSION: [2, 3, 0] };
export default Escaper;

const
	stringLiterals = {
		'"': true,
		'\'': true,
		'`': true
	},

	literals = {
		'/': true
	};

for (let key in stringLiterals) {
	if (!stringLiterals.hasOwnProperty(key)) {
		continue;
	}

	literals[key] = true;
}

const
	singleComments = {
		'//': true
	},

	multComments = {
		'/*': true,
		'/**': true,
		'/*!': true,
		'/*#': true,
		'/*@': true,
		'/*$': true
	};

const
	keyArr = [],
	finalMap = {};

for (let key in literals) {
	if (!literals.hasOwnProperty(key)) {
		continue;
	}

	keyArr.push(key);
	finalMap[key] = true;
}

for (let key in singleComments) {
	if (!singleComments.hasOwnProperty(key)) {
		continue;
	}

	keyArr.push(key);
	finalMap[key] = true;
}

for (let key in multComments) {
	if (!multComments.hasOwnProperty(key)) {
		continue;
	}

	keyArr.push(key);
	finalMap[key] = true;
}

const
	rgxpFlags = [],
	rgxpFlagsMap = {
		'g': true,
		'm': true,
		'i': true,
		'y': true,
		'u': true
	};

for (let key in rgxpFlagsMap) {
	if (!rgxpFlagsMap.hasOwnProperty(key)) {
		continue;
	}

	rgxpFlags.push(key);
}

const
	escapeEndMap = {
		'-': true,
		'+': true,
		'*': true,
		'%': true,
		'~': true,
		'>': true,
		'<': true,
		'^': true,
		',': true,
		';': true,
		'=': true,
		'|': true,
		'&': true,
		'!': true,
		'?': true,
		':': true,
		'(': true,
		'{': true,
		'[': true
	};

const
	escapeEndWordMap = {
		'typeof': true,
		'void': true,
		'instanceof': true,
		'delete': true,
		'in': true,
		'new': true,
		'of': true
	};

const
	cache = {},
	content = [];

/**
 * @param {!Object} obj
 * @param {!Object} p
 * @param {(boolean|number)} val
 */
function mix(obj, p, val) {
	for (let key in obj) {
		if (!obj.hasOwnProperty(key)) {
			continue;
		}

		if (key in p === false) {
			p[key] = val;
		}
	}
}

/** @type {!Array} */
Escaper.quotContent = content;

const
	uSRgxp = /[^\s\/]/,
	wRgxp = /[a-z]/,
	sRgxp = /\s/,
	nRgxp = /\r|\n/;

let
	symbols,
	snakeskinRgxp;

Escaper.symbols = null;
Escaper.snakeskinRgxp = null;

const
	objMap = {
		'object': true,
		'function': true
	};

/**
 * Replaces all found blocks ' ... ', " ... ", ` ... `, / ... /, // ..., /* ... *\/ to
 * __ESCAPER_QUOT__number_ in a string and returns a new string
 *
 * @param {string} str - the source string
 * @param {(Object.<string, boolean>|boolean)=} [opt_withCommentsOrParams=false] - parameters:
 *
 *     (if a parameter value is set to -1, then all found matches will be removed from the final string,
 *          or if the value will be set to true/false they will be included/excluded)
 *
 *     *) @label    - template for replacement, e.g. __ESCAPER_QUOT__${pos}_
 *     *) @all      - replaces all found matches
 *     *) @comments - replaces all kinds of comments
 *     *) @strings  - replaces all kinds of string literals
 *     *) @literals - replaces all kinds of string literals and regular expressions
 *     *) `
 *     *) '
 *     *) "
 *     *) /
 *     *) //
 *     *) /*
 *     *) /**
 *     *) /*!
 *     *) /*#
 *     *) /*@
 *     *) /*$
 *
 *     OR if the value is boolean, then will be replaced all found comments (true) / literals (false)
 *
 * @param {Array=} [opt_quotContent=Escaper.quotContent] - an array for matches
 * @param {?boolean=} [opt_snakeskin] - a private parameter for using with Snakeskin
 * @return {string}
 */
Escaper.replace = function (str, opt_withCommentsOrParams, opt_quotContent, opt_snakeskin) {
	symbols = symbols ||
		Escaper.symbols || 'a-z';

	snakeskinRgxp = snakeskinRgxp ||
		Escaper.snakeskinRgxp ||
		new RegExp(`[!$${symbols}_]`, 'i');

	const
		isObj = Boolean(
			opt_withCommentsOrParams &&
				objMap[typeof opt_withCommentsOrParams]
		),

		p = isObj ?
			Object(opt_withCommentsOrParams) : {};

	const posRgxp = /\$\{pos}/g;
	function mark(pos) {
		if (p['@label']) {
			return p['@label'].replace(posRgxp, pos);
		}

		return `__ESCAPER_QUOT__${pos}_`;
	}

	let withComments = false;
	if (typeof opt_withCommentsOrParams === 'boolean') {
		withComments = Boolean(opt_withCommentsOrParams);
	}

	if ('@comments' in p) {
		mix(multComments, p, p['@comments']);
		mix(singleComments, p, p['@comments']);
		delete p['@comments'];
	}

	if ('@strings' in p) {
		mix(stringLiterals, p, p['@strings']);
		delete p['@strings'];
	}

	if ('@literals' in p) {
		mix(literals, p, p['@literals']);
		delete p['@literals'];
	}

	if ('@all' in p) {
		mix(finalMap, p, p['@all']);
		delete p['@all'];
	}

	let cacheKey = '';
	for (let i = -1; ++i < keyArr.length;) {
		let el = keyArr[i];

		if (multComments[el] || singleComments[el]) {
			p[el] = withComments || p[el];

		} else {
			p[el] = p[el] || !isObj;
		}

		cacheKey += `${p[el]},`;
	}

	const
		initStr = str,
		stack = opt_quotContent || content;

	if (stack === content && cache[cacheKey] && cache[cacheKey][initStr]) {
		return cache[cacheKey][initStr];
	}

	let
		begin = false,
		end = true;

	let
		escape = false,
		comment = false;

	let
		selectionStart = 0,
		block = false;

	let
		templateVar = 0,
		filterStart = false;

	let
		cut,
		label;

	let
		part = '',
		rPart = '';

	for (let i = -1; ++i < str.length;) {
		let
			el = str.charAt(i),
			next = str.charAt(i + 1);

		let
			word = str.substr(i, 2),
			extWord = str.substr(i, 3);

		if (!comment) {
			if (!begin) {
				if (el === '/') {
					if (singleComments[word] || multComments[word]) {
						if (singleComments[extWord] || multComments[extWord]) {
							comment = extWord;

						} else {
							comment = word;
						}
					}

					if (comment) {
						selectionStart = i;
						continue;
					}
				}

				if (escapeEndMap[el] || escapeEndWordMap[rPart]) {
					end = true;
					rPart = '';

				} else if (uSRgxp.test(el)) {
					end = false;
				}

				if (wRgxp.test(el)) {
					part += el;

				} else {
					rPart = part;
					part = '';
				}

				let skip = false;
				if (opt_snakeskin) {
					if (el === '|' && snakeskinRgxp.test(next)) {
						filterStart = true;
						end = false;
						skip = true;

					} else if (filterStart && sRgxp.test(el)) {
						filterStart = false;
						end = true;
						skip = true;
					}
				}

				if (!skip) {
					if (escapeEndMap[el]) {
						end = true;

					} else if (uSRgxp.test(el)) {
						end = false;
					}
				}
			}

			// [] inside RegExp
			if (begin === '/' && !escape) {
				if (el === '[') {
					block = true;

				} else if (el === ']') {
					block = false;
				}
			}

			if (!begin && templateVar) {
				if (el === '}') {
					templateVar--;

				} else if (el === '{') {
					templateVar++;
				}

				if (!templateVar) {
					el = '`';
				}
			}

			if (begin === '`' && !escape && word === '${') {
				el = '`';
				i++;
				templateVar++;
			}

			if (finalMap[el] && (el !== '/' || end) && !begin) {
				begin = el;
				selectionStart = i;

			} else if (begin && (el === '\\' || escape)) {
				escape = !escape;

			} else if (finalMap[el] && begin === el && !escape && (begin !== '/' || !block)) {
				if (el === '/') {
					for (let j = -1; ++j < rgxpFlags.length;) {
						if (rgxpFlagsMap[str.charAt(i + 1)]) {
							i++;
						}
					}
				}

				begin = false;
				end = false;

				if (p[el]) {
					cut = str.substring(selectionStart, i + 1);

					if (p[el] === -1) {
						label = '';

					} else {
						label = mark(stack.length);
						stack.push(cut);
					}

					str = str.substring(0, selectionStart) + label + str.substring(i + 1);
					i += label.length - cut.length;
				}
			}

		} else if ((nRgxp.test(next) && singleComments[comment]) ||
			(multComments[el + str.charAt(i - 1)] && i - selectionStart > 2 && multComments[comment])

		) {
			if (p[comment]) {
				cut = str.substring(selectionStart, i + 1);

				if (p[comment] === -1) {
					label = '';

				} else {
					label = mark(stack.length);
					stack.push(cut);
				}

				str = str.substring(0, selectionStart) + label + str.substring(i + 1);
				i += label.length - cut.length;
			}

			comment = false;
		}
	}

	if (stack === content) {
		cache[cacheKey] = cache[cacheKey] || {};
		cache[cacheKey][initStr] = str;
	}

	return str;
};

const pasteRgxp = /__ESCAPER_QUOT__(\d+)_/g;

/**
 * Replaces all found blocks __ESCAPER_QUOT__number_ to real content in a string
 * and returns a new string
 *
 * @param {string} str - the source string
 * @param {Array=} [opt_quotContent=Escaper.quotContent] - an array of matches
 * @param {RegExp=} [opt_rgxp] - RegExp for searching, e.g. /__ESCAPER_QUOT__(\d+)_/g
 * @return {string}
 */
Escaper.paste = function (str, opt_quotContent, opt_rgxp) {
	return str.replace(opt_rgxp || pasteRgxp, (sstr, pos) => (opt_quotContent || content)[pos]);
};
<|endoftext|>


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

    if (typeof module !== 'undefined' && module.exports)
        module.exports = extendy;
    else
        global.extendy = extendy;

    function extendy(to, from) {
        check(to, from);

        Object.keys(to).forEach(function(name) {
            from[name] = to[name];
        });
    }

    function check(to, from) {
        var empty = 'could not be empty!';

        if (!to)
            throw(Error('to ' + empty));

        if (!from)
            throw(Error('from ' + empty));
    }

})(this);<commit_msg>fix from to<commit_after>(function(global) {
    'use strict';

    if (typeof module !== 'undefined' && module.exports)
        module.exports = extendy;
    else
        global.extendy = extendy;

    function extendy(to, from) {
        check(to, from);

        Object.keys(from).forEach(function(name) {
            to[name] = from[name];
        });
    }

    function check(to, from) {
        var empty = 'could not be empty!';

        if (!to)
            throw(Error('to ' + empty));

        if (!from)
            throw(Error('from ' + empty));
    }

})(this);
<|endoftext|>