<commit_before>var Class = require('./Class');
var lang = require('./lang');
var Runner = Class.extend(
  /** @lends gvr.runner.Runner# */
  {
    /**
     * @class Object for running a program.
     * @constructs
     * @param program See {@link gvr.runner.Runner#program}
     * @param renderer See {@link gvr.runner.Runner#renderer}
     */
    init: function(program, renderer, notify){
      /**
       * The program to run.
       * @type {gvr.lang.Block}
       */
      this.program = program;

      /**
       * The execution stack
       * @type {Array}
       */
      this.stack = [this.program];

      /**
       * The renderer, which gets called after every execution step.
       * @type {gvr.renderer.Renderer}
       */
      this.renderer = renderer;

      /**
       * @private
       */
      this.globals = {};
      this.globals[lang.RUNNER_GLOBAL_KEY] = this;

      /**
       * keeps track of the timeout which pauses program execution.
       * @private
       */
      this.timeout = null;

      /**
       * Keeps track of whether or not the runner is currently running.
       * @type {boolean}
       */
      this.running = false;

      this.notify = notify || function() {};
    },

    /**
     * Print out a human readable representation of the current
     * execution stack
     * @returns Array
     */
    printStackTrace: function(){
      var trace = [];
      for (var i = 0; i < this.stack.length; i++){
        trace.push(this.stack[i].name);
      }
      return trace;
    },

    /**
     * Perform the next execution step.
     * @param Same as the callback parameter for {@link gvr.runner.Runner#run}
     */
    step: function(callback, notify){
      this.run(0, callback, notify, true);
    },

    /**
     * Stop all execution.
     */
    stop: function(){
      window.clearTimeout(this.timeout);
      this.running = false;
    },

    /**
     * Run the program.
     * @param speed The number of milliseconds to wait
     *        before performing the next execution step.
     *        Use 0 for instant execution.
     * @param callback function to call when there is nothing left to run.
     * @param step If true, only one execution step will occur.
     *       If false, execution will continue to happen
     *       until there is an error or the program finishes.
     */
    run: function(speed, callback, notify, step){
      this.running = true;
      var instant = speed === -1;
      speed = speed || 200;

      if (this.stack.length > 0){
        // stepping
        var last = this.stack.pop();
        try {
          var next = last.step(this.globals);
        } catch (e){
          alert(e.message);
          return;
        }
        this.stack = this.stack.concat(next);
        // rendering and loopback
        if (!instant){
          this.renderer.render();
        }
        notify && notify(this);

        if (next.length > 0){
          if (instant){
            this.run(speed, callback, notify, step);
          } else if (!step){
            this.timeout = window.setTimeout(
              function(){this.run(speed, callback, notify, step);}.bind(this),
              speed
            );
          }
        } else {
          this.run(speed, callback, notify, step);
        }

      } else {
        this.stop();
        if (this.renderer.world.robot.on){
          this.stop();
          alert("Robot ran out of instructions.");
        }
        if (typeof callback === "function"){
          callback();
        }
        if (instant){
          this.renderer.render();
        }
      }
    }
  });

module.exports = Runner;<commit_msg>don't alert when people forget to add the turnoff instruction<commit_after>var Class = require('./Class');
var lang = require('./lang');
var Runner = Class.extend(
  /** @lends gvr.runner.Runner# */
  {
    /**
     * @class Object for running a program.
     * @constructs
     * @param program See {@link gvr.runner.Runner#program}
     * @param renderer See {@link gvr.runner.Runner#renderer}
     */
    init: function(program, renderer, notify){
      /**
       * The program to run.
       * @type {gvr.lang.Block}
       */
      this.program = program;

      /**
       * The execution stack
       * @type {Array}
       */
      this.stack = [this.program];

      /**
       * The renderer, which gets called after every execution step.
       * @type {gvr.renderer.Renderer}
       */
      this.renderer = renderer;

      /**
       * @private
       */
      this.globals = {};
      this.globals[lang.RUNNER_GLOBAL_KEY] = this;

      /**
       * keeps track of the timeout which pauses program execution.
       * @private
       */
      this.timeout = null;

      /**
       * Keeps track of whether or not the runner is currently running.
       * @type {boolean}
       */
      this.running = false;

      this.notify = notify || function() {};
    },

    /**
     * Print out a human readable representation of the current
     * execution stack
     * @returns Array
     */
    printStackTrace: function(){
      var trace = [];
      for (var i = 0; i < this.stack.length; i++){
        trace.push(this.stack[i].name);
      }
      return trace;
    },

    /**
     * Perform the next execution step.
     * @param Same as the callback parameter for {@link gvr.runner.Runner#run}
     */
    step: function(callback, notify){
      this.run(0, callback, notify, true);
    },

    /**
     * Stop all execution.
     */
    stop: function(){
      window.clearTimeout(this.timeout);
      this.running = false;
    },

    /**
     * Run the program.
     * @param speed The number of milliseconds to wait
     *        before performing the next execution step.
     *        Use 0 for instant execution.
     * @param callback function to call when there is nothing left to run.
     * @param step If true, only one execution step will occur.
     *       If false, execution will continue to happen
     *       until there is an error or the program finishes.
     */
    run: function(speed, callback, notify, step){
      this.running = true;
      var instant = speed === -1;
      speed = speed || 200;

      if (this.stack.length > 0){
        // stepping
        var last = this.stack.pop();
        try {
          var next = last.step(this.globals);
        } catch (e){
          alert(e.message);
          return;
        }
        this.stack = this.stack.concat(next);
        // rendering and loopback
        if (!instant){
          this.renderer.render();
        }
        notify && notify(this);

        if (next.length > 0){
          if (instant){
            this.run(speed, callback, notify, step);
          } else if (!step){
            this.timeout = window.setTimeout(
              function(){this.run(speed, callback, notify, step);}.bind(this),
              speed
            );
          }
        } else {
          this.run(speed, callback, notify, step);
        }

      } else {
        this.stop();
        if (this.renderer.world.robot.on){
          this.stop();
          console.error("Robot ran out of instructions.");
        }
        if (typeof callback === "function"){
          callback();
        }
        if (instant){
          this.renderer.render();
        }
      }
    }
  });

module.exports = Runner;<|endoftext|>


<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight, SHJS, Rainbow
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };
  var style = {
    'bold': {pattern: /\*/gm, regex: /\*{1,}(.*?)\*{1,}/gm},
    'italic': {pattern: /\//gm, regex: /\/{1,}(.*?)\/{1,}/gm},
    'underline': {pattern: /\_/gm, regex: /\_{1,}(.*?)\_{1,}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={1,}(.*?)\={1,}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /\-/gm, regex: /\-{4,}/gm},
    'rule-dash': {pattern: /\./gm, regex: /\.{4,}/gm}
  };
  var block = {
    'code': {pattern: /\|/gm, regex: /\|{1,}(.*?)\|{1,}/gm},
    'pre-external': {pattern: /(\`|\[(.*?)\])/gm, regex: /(\[(.*?)\|(.*?)\])\`{1,}([\s\S]*?)\`{1,}/gm},
    'pre': {pattern: /\`/gm, regex: /\`{1,}([\s\S]*?)\`{1,}/gm},
    'quote': {pattern: /[\{\}]/gm, regex: /\{{1,}([\s\S]*?)\}{1,}/gm}
  };
  var list = {
    'unordered': {pattern: /\-/gm, regex: /((.*?)\-(?!\-).+$\n){1,}/gm},
    'ordered': {pattern: /\d{1,}\./gm, regex: /((.*?)\d{1,}\..+$\n){1,}/gm}
  };
  var link = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Block=============================
  ============================================================*/
  exports.Block = function(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        var temp;
        if (key != 'pre-external') {
          temp = exports.Prepare(match).replace(block[key].pattern, '');
        }
        if (key == 'code') {
          return '' + exports.Trim(temp) + '';
        } else if (key == 'pre-external') {
          var extra = exports.Prepare(match).replace(/(\[|\]|\`([\s\S]*?)\`)/gm, ''),
            language = extra.split('|')[0].toLowerCase(),
            url = 'Syntax/' + extra.split('|')[1].toLowerCase();
          temp = exports.Prepare(match).replace(block[key].pattern, '');
          exports.LoadScript(url + '/script.js');
          exports.LoadStyle(url + '/' + exports.theme + '.css');
          var classes = 'language-' + language + ' sh_' + language + ' prettyprint lang-' + language;
          var dataClasses = 'data-language="' + language + '"';
          return '
' + exports.Trim(temp) + '
';
        } else if (key == 'pre') {
          return '
' + exports.Trim(temp) + '
';
        } else {
          return '' + exports.Trim(temp) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var tag = key == 'unordered' ? 'ul' : 'ol';
        return '<' + tag + ' class="' + prefix + key + '"' + match.replace(/.+/gm, function(line) {
          var temp = exports.Prepare(line).replace(style[key].pattern, '');
          return '
' + exports.Trim(temp) + '
';
        }) + '</' + tag + '>';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<commit_msg>Update extension.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight, SHJS, Rainbow
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };
  var style = {
    'bold': {pattern: /\*/gm, regex: /\*{1,}(.*?)\*{1,}/gm},
    'italic': {pattern: /\//gm, regex: /\/{1,}(.*?)\/{1,}/gm},
    'underline': {pattern: /\_/gm, regex: /\_{1,}(.*?)\_{1,}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={1,}(.*?)\={1,}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /\-/gm, regex: /\-{4,}/gm},
    'rule-dash': {pattern: /\./gm, regex: /\.{4,}/gm}
  };
  var block = {
    'code': {pattern: /\|/gm, regex: /\|{1,}(.*?)\|{1,}/gm},
    'pre-external': {pattern: /(\`|\[(.*?)\])/gm, regex: /(\[(.*?)\|(.*?)\])\`{1,}([\s\S]*?)\`{1,}/gm},
    'pre': {pattern: /\`/gm, regex: /\`{1,}([\s\S]*?)\`{1,}/gm},
    'quote': {pattern: /[\{\}]/gm, regex: /\{{1,}([\s\S]*?)\}{1,}/gm}
  };
  var list = {
    'unordered': {pattern: /\-/gm, regex: /((.*?)\-(?!(.*?)\-).+$\n){1,}/gm},
    'ordered': {pattern: /\d{1,}\./gm, regex: /((.*?)\d{1,}\..+$\n){1,}/gm}
  };
  var link = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Block=============================
  ============================================================*/
  exports.Block = function(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        var temp;
        if (key != 'pre-external') {
          temp = exports.Prepare(match).replace(block[key].pattern, '');
        }
        if (key == 'code') {
          return '' + exports.Trim(temp) + '';
        } else if (key == 'pre-external') {
          var extra = exports.Prepare(match).replace(/(\[|\]|\`([\s\S]*?)\`)/gm, ''),
            language = extra.split('|')[0].toLowerCase(),
            url = 'Syntax/' + extra.split('|')[1].toLowerCase();
          temp = exports.Prepare(match).replace(block[key].pattern, '');
          exports.LoadScript(url + '/script.js');
          exports.LoadStyle(url + '/' + exports.theme + '.css');
          var classes = 'language-' + language + ' sh_' + language + ' prettyprint lang-' + language;
          var dataClasses = 'data-language="' + language + '"';
          return '
' + exports.Trim(temp) + '
';
        } else if (key == 'pre') {
          return '
' + exports.Trim(temp) + '
';
        } else {
          return '' + exports.Trim(temp) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var tag = key == 'unordered' ? 'ul' : 'ol';
        return '<' + tag + ' class="' + prefix + key + '"' + match.replace(/.+/gm, function(line) {
          var temp = exports.Prepare(line).replace(style[key].pattern, '');
          return '
' + exports.Trim(temp) + '
';
        }) + '</' + tag + '>';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<|endoftext|>


<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#/gm, regex: /\#.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(?!\*{2,})(.*?)\*{2}/gm},
    'italic': {pattern: /\*/gm, regex: /\*(?!\*{3,})(.*?)\*/gm},
    'underline': {pattern: /\_/gm, regex: /\_{2}(?!\_{2,})(.*?)\_{2}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{2}(?!\~{2,})(.*?)\~{2}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={2}(?!\={2,})(.*?)\={2}/gm},
    'superscript': {pattern: /\+/gm, regex: /\+{2}(?!\+{2,})(.*?)\+{2}/gm},
    'subscript': {pattern: /\-/gm, regex: /\-{2}(?!\-{2,})(.*?)\-{2}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /\_{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /\-{4,}/gm},
    'rule-dotted': {pattern: /[]/gm, regex: /\.{4,}/gm},
    'rule-double': {pattern: /[]/gm, regex: /\={4,}/gm},
    'rule-thick': {pattern: /[]/gm, regex: /\+{4,}/gm}
  };
  var quote = {
    'quote-code': {pattern: /\`/gm, regex: /\`(.*?)\`/gm},
    'quote-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\[([\s\S]*?)\]\}/gm},
    'quote-plain': {pattern: /(\{\[|\]\})/gm, regex: /\{\[([\s\S]*?)\]\}/gm}
  };
  var code = {
    'code-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\(([\s\S]*?)\)\}/gm},
    'code-plain': {pattern: /(\{\(|\)\})/gm, regex: /\{\(([\s\S]*?)\)\}/gm}
  };
  var list = {
    'list-disc': {pattern: /(\-)/gm, regex: /(^\-(?!\-{3,}).+\n){1,}/gm},
    'list-circle': {pattern: /(\*)/gm, regex: /(^\*(?!\*{3,}).+\n){1,}/gm},
    'list-square': {pattern: /(\@)/gm, regex: /(^\@(?!\@{3,}).+\n){1,}/gm},
    'list-decimal': {pattern: /(\o\.)/gm, regex: /(^\o\..+\n){1,}/igm},
    'list-roman': {pattern: /(\i\.)/gm, regex: /(^\i\..+\n){1,}/igm},
    'list-alpha': {pattern: /(\a\.)/gm, regex: /(^\a\..+\n){1,}/igm},
    'checklist': {pattern: /\[[Xx\s]?\]/gm, regex: /(^\[[Xx\s]?\].+\n){1,}/gm}
  };
  var link = {
    'url': {pattern: /[]/gm, regex: /(\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)|\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b)/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };
  var image = {
    'image-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\!\((.*?)\)/gm},
    'image-plain': {pattern: /(\!\(|\))/gm, regex: /\!\((.*?)\)/gm}
  };
  var table = {
    'table': {pattern: /\=/gm, regex: /\{\|([\s\S]*?)\|\}/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        if (key == 'header1' || key == 'header2') {
          return '' + exports.Trim(temp) + '
';
        } else {
          return '' + exports.Trim(temp) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Quote=============================
  ============================================================*/
  exports.Quote = function(doc) {
    for (key in quote) {
      doc = doc.replace(quote[key].regex, function(match) {
        if (key == 'quote-code') {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key + ' nohighlight language-none';
          return '' + exports.Trim(temp) + '';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']{['),
            credit = extra[0].split('[')[1],
            content = extra[1].split(']}')[0],
            classes = prefix + key;
          return '
"' + exports.Trim(content) + '"
' + exports.Trim(credit) + '
';
        } else {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key;
          return '
"' + exports.Trim(temp) + '"
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Code==============================
  ============================================================*/
  exports.Code = function(doc) {
    for (key in code) {
      doc = doc.replace(code[key].regex, function(match) {
        if (key == 'code-extra') {
          var extra = exports.Prepare(match).split(']{('),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split(')}')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = prefix + key + ' language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = language;
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + second + '
';
        } else {
          var temp = exports.Prepare(match).replace(code[key].pattern, ''),
            classes = 'nohighlight language-none';
          return '
' + temp + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'list-disc' || key == 'list-circle' || key == 'list-square') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else if (key == 'list-decimal' || key == 'list-roman' || key == 'list-alpha') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx\s]?\]/gm, ''),
              tag = (new RegExp(/\[\s?\]/gm)).test(line) ? 'unchecked' : 'checked';
            return '' + exports.Trim(temp) + '
';
          }) + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url') {
          if ((new RegExp(/^\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)$/gm)).test(match)) {
            var extra = exports.Prepare(match).split(']('),
              title = extra[0].split('[')[1],
              url = extra[1].split(']')[0];
            return '' + exports.Trim(title) + '';
          } else {
            return '' + exports.Trim(match) + '';
          }
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Image=============================
  ============================================================*/
  exports.Image = function(doc) {
    for (key in image) {
      if (key == 'image-extra') {
        doc = doc.replace(image[key].regex, function(match) {
          var extra = exports.Prepare(match).split(']!('),
            alt = extra[0].split('[')[1],
            url = extra[1].split(')')[0];
          return '

' + exports.Trim(alt) + '

';
        });
      } else {
        doc = doc.replace(image[key].regex, function(match) {
          var temp = exports.Prepare(match).replace(image[key].pattern, '');
          return '

';
        });
      }
    }
    return doc;
  };

  /*============================================================
  ============================Table=============================
  ============================================================*/
  exports.Table = function(doc) {
    for (key in table) {
      doc = '

' + doc.replace(table[key].regex, function(match) {
        var extra = exports.Prepare(match).split('{|')[1].split('|}')[0],
          rows = extra.split('||'),
          data = '';
        for (var a = 0; a < rows.length; a++) {
          var row = rows[a],
            tag = (new RegExp(/\={2}/gm)).test(row) ? 'th' : 'td';
          data += '
' + row.replace(/.+\n/gm, function(col) {
            var temp = col.replace(table[key].pattern, '');
            return '<' + tag + ' class="' + prefix + 'col">' + exports.Trim(temp) + '</' + tag + '>';
          }) + '
';
        }
        return data;
      }) + '

';
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n{1,}/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<commit_msg>Update extension.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#/gm, regex: /\#.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(?!\*{2,})(.*?)\*{2}/gm},
    'italic': {pattern: /\*/gm, regex: /\*(?!\*{3,})(.*?)\*/gm},
    'underline': {pattern: /\_/gm, regex: /\_{2}(?!\_{2,})(.*?)\_{2}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{2}(?!\~{2,})(.*?)\~{2}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={2}(?!\={2,})(.*?)\={2}/gm},
    'superscript': {pattern: /\+/gm, regex: /\+{2}(?!\+{2,})(.*?)\+{2}/gm},
    'subscript': {pattern: /\-/gm, regex: /\-{2}(?!\-{2,})(.*?)\-{2}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /\_{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /\-{4,}/gm},
    'rule-dotted': {pattern: /[]/gm, regex: /\.{4,}/gm},
    'rule-double': {pattern: /[]/gm, regex: /\={4,}/gm},
    'rule-thick': {pattern: /[]/gm, regex: /\+{4,}/gm}
  };
  var quote = {
    'quote-code': {pattern: /\`/gm, regex: /\`(.*?)\`/gm},
    'quote-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\[([\s\S]*?)\]\}/gm},
    'quote-plain': {pattern: /(\{\[|\]\})/gm, regex: /\{\[([\s\S]*?)\]\}/gm}
  };
  var code = {
    'code-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\(([\s\S]*?)\)\}/gm},
    'code-plain': {pattern: /(\{\(|\)\})/gm, regex: /\{\(([\s\S]*?)\)\}/gm}
  };
  var list = {
    'list-disc': {pattern: /(\-)/gm, regex: /(^\-(?!\-{3,}).+\n){1,}/gm},
    'list-circle': {pattern: /(\*)/gm, regex: /(^\*(?!\*{3,}).+\n){1,}/gm},
    'list-square': {pattern: /(\@)/gm, regex: /(^\@(?!\@{3,}).+\n){1,}/gm},
    'list-decimal': {pattern: /(\o\.)/gm, regex: /(^\o\..+\n){1,}/igm},
    'list-roman': {pattern: /(\i\.)/gm, regex: /(^\i\..+\n){1,}/igm},
    'list-alpha': {pattern: /(\a\.)/gm, regex: /(^\a\..+\n){1,}/igm},
    'checklist': {pattern: /\[[Xx\s]?\]/gm, regex: /(^\[[Xx\s]?\].+\n){1,}/gm}
  };
  var link = {
    'url': {pattern: /[]/gm, regex: /(\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)|\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b)/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };
  var image = {
    'image-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\!\((.*?)\)/gm},
    'image-plain': {pattern: /(\!\(|\))/gm, regex: /\!\((.*?)\)/gm}
  };
  var table = {
    'table': {pattern: /\=/gm, regex: /\{\|([\s\S]*?)\|\}/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        if (key == 'header1' || key == 'header2') {
          return '' + exports.Trim(temp) + '
';
        } else {
          return '' + exports.Trim(temp) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Quote=============================
  ============================================================*/
  exports.Quote = function(doc) {
    for (key in quote) {
      doc = doc.replace(quote[key].regex, function(match) {
        if (key == 'quote-code') {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key + ' nohighlight language-none';
          return '' + exports.Trim(temp) + '';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']{['),
            credit = extra[0].split('[')[1],
            content = extra[1].split(']}')[0],
            classes = prefix + key;
          return '
"' + exports.Trim(content) + '"
' + exports.Trim(credit) + '
';
        } else {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key;
          return '
"' + exports.Trim(temp) + '"
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Code==============================
  ============================================================*/
  exports.Code = function(doc) {
    for (key in code) {
      doc = doc.replace(code[key].regex, function(match) {
        if (key == 'code-extra') {
          var extra = exports.Prepare(match).split(']{('),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split(')}')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = prefix + key + ' language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = language;
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + second + '
';
        } else {
          var temp = exports.Prepare(match).replace(code[key].pattern, ''),
            classes = 'nohighlight language-none';
          return '
' + temp + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'list-disc' || key == 'list-circle' || key == 'list-square') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else if (key == 'list-decimal' || key == 'list-roman' || key == 'list-alpha') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx\s]?\]/gm, ''),
              tag = (new RegExp(/\[\s?\]/gm)).test(line) ? 'unchecked' : 'checked';
            return '' + exports.Trim(temp) + '
';
          }) + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url') {
          if ((new RegExp(/^\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)$/gm)).test(match)) {
            var extra = exports.Prepare(match).split(']('),
              title = extra[0].split('[')[1],
              url = extra[1].split(']')[0];
            return '' + exports.Trim(title) + '';
          } else {
            return '' + exports.Trim(match) + '';
          }
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Image=============================
  ============================================================*/
  exports.Image = function(doc) {
    for (key in image) {
      if (key == 'image-extra') {
        doc = doc.replace(image[key].regex, function(match) {
          var extra = exports.Prepare(match).split(']!('),
            alt = extra[0].split('[')[1],
            url = extra[1].split(')')[0];
          return '

' + exports.Trim(alt) + '

';
        });
      } else {
        doc = doc.replace(image[key].regex, function(match) {
          var temp = exports.Prepare(match).replace(image[key].pattern, '');
          return '

';
        });
      }
    }
    return doc;
  };

  /*============================================================
  ============================Table=============================
  ============================================================*/
  exports.Table = function(doc) {
    for (key in table) {
      doc = '

' + doc.replace(table[key].regex, function(match) {
        var extra = exports.Prepare(match).split('{|')[1].split('|}')[0],
          rows = extra.split('||'),
          data = '';
        for (var a = 0; a < rows.length; a++) {
          var row = rows[a],
            tag = (new RegExp(/\={2}/gm)).test(row) ? 'th' : 'td';
          data += '
' + row.replace(/.+\n/gm, function(col) {
            var temp = col.replace(table[key].pattern, '');
            return '<' + tag + ' class="' + prefix + 'col">' + exports.Trim(temp) + '</' + tag + '>';
          }) + '
';
        }
        return data;
      }) + '

';
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/(\n|\
){1,}/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<|endoftext|>


<commit_before>/* eslint-disable */
var gulp = require('gulp'),
  path = require('path'),
  ngc = require('@angular/compiler-cli/src/main').main,
  rollup = require('gulp-rollup'),
  rename = require('gulp-rename'),
  del = require('del'),
  runSequence = require('run-sequence'),
  inlineResources = require('./tools/gulp/inline-resources');

const rootFolder = path.join(__dirname);
const srcFolder = path.join(rootFolder, 'src');
const tmpFolder = path.join(rootFolder, '.tmp');
const buildFolder = path.join(rootFolder, 'build');
const distFolder = path.join(rootFolder, 'dist');

/**
 * 1. Delete /dist folder
 */
gulp.task('clean:dist', function () {

  // Delete contents but not dist folder to avoid broken npm links
  // when dist directory is removed while npm link references it.
  return deleteFolders([distFolder + '/**', '!' + distFolder]);
});

/**
 * 2. Clone the /src folder into /.tmp. If an npm link inside /src has been made,
 *    then it's likely that a node_modules folder exists. Ignore this folder
 *    when copying to /.tmp.
 */
gulp.task('copy:source', function () {
  return gulp.src([`${srcFolder}/**/*`, `!${srcFolder}/node_modules`])
    .pipe(gulp.dest(tmpFolder));
});

/**
 * 3. Inline template (.html) and style (.css) files into the the component .ts files.
 *    We do this on the /.tmp folder to avoid editing the original /src files
 */
gulp.task('inline-resources', function () {
  return Promise.resolve()
    .then(() => inlineResources(tmpFolder));
});

/**
 * 4. Run the Angular compiler, ngc, on the /.tmp folder. This will output all
 *    compiled modules to the /build folder.
 */
gulp.task('ngc', function () {
  return ngc({
    project: `${tmpFolder}/tsconfig.es5.json`
  })
    .then((exitCode) => {
      if (exitCode === 1) {
        // This error is caught in the 'compile' task by the runSequence method callback
        // so that when ngc fails to compile, the whole compile process stops running
        throw new Error('ngc compilation failed');
      }
    });
});

/**
 * 5. Run rollup inside the /build folder to generate our Flat ES module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup:fesm', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({

      // Bundle's entry point
      // See "input" in https://rollupjs.org/#core-functionality
      input: `${buildFolder}/index.js`,

      // Allow mixing of hypothetical and actual files. "Actual" files can be files
      // accessed by Rollup or produced by plugins further down the chain.
      // This prevents errors like: 'path/file' does not exist in the hypothetical file system
      // when subdirectories are used in the `src` directory.
      allowRealFiles: true,

      // A list of IDs of modules that should remain external to the bundle
      // See "external" in https://rollupjs.org/#core-functionality
      external: [
        '@angular/core',
        '@angular/common'
      ],

      // Format of generated bundle
      // See "format" in https://rollupjs.org/#core-functionality
      format: 'es'
    }))
    .pipe(gulp.dest(distFolder));
});

/**
 * 6. Run rollup inside the /build folder to generate our UMD module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup:umd', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({

      // Bundle's entry point
      // See "input" in https://rollupjs.org/#core-functionality
      input: `${buildFolder}/index.js`,

      // Allow mixing of hypothetical and actual files. "Actual" files can be files
      // accessed by Rollup or produced by plugins further down the chain.
      // This prevents errors like: 'path/file' does not exist in the hypothetical file system
      // when subdirectories are used in the `src` directory.
      allowRealFiles: true,

      // A list of IDs of modules that should remain external to the bundle
      // See "external" in https://rollupjs.org/#core-functionality
      external: [
        '@angular/core',
        '@angular/common'
      ],

      // Format of generated bundle
      // See "format" in https://rollupjs.org/#core-functionality
      format: 'umd',

      // Export mode to use
      // See "exports" in https://rollupjs.org/#danger-zone
      exports: 'named',

      // The name to use for the module for UMD/IIFE bundles
      // (required for bundles with exports)
      // See "name" in https://rollupjs.org/#core-functionality
      name: '<%= props.libraryName.original %>',

      // See "globals" in https://rollupjs.org/#core-functionality
      globals: {
        typescript: 'ts'
      }

    }))
    .pipe(rename('<%= props.libraryName.kebabCase %>.umd.js'))
    .pipe(gulp.dest(distFolder));
});

/**
 * 7. Copy all the files from /build to /dist, except .js files. We ignore all .js from /build
 *    because with don't need individual modules anymore, just the Flat ES module generated
 *    on step 5.
 */
gulp.task('copy:build', function () {
  return gulp.src([`${buildFolder}/**/*`, `!${buildFolder}/**/*.js`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 8. Copy package.json from /src to /dist
 */
gulp.task('copy:manifest', function () {
  return gulp.src([`${srcFolder}/package.json`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 9. Copy README.md from / to /dist
 */
gulp.task('copy:readme', function () {
  return gulp.src([path.join(rootFolder, 'README.MD')])
    .pipe(gulp.dest(distFolder));
});

/**
 * 10. Delete /.tmp folder
 */
gulp.task('clean:tmp', function () {
  return deleteFolders([tmpFolder]);
});

/**
 * 11. Delete /build folder
 */
gulp.task('clean:build', function () {
  return deleteFolders([buildFolder]);
});

gulp.task('compile', function () {
  runSequence(
    'clean:dist',
    'copy:source',
    'inline-resources',
    'ngc',
    'rollup:fesm',
    'rollup:umd',
    'copy:build',
    'copy:manifest',
    'copy:readme',
    'clean:build',
    'clean:tmp',
    function (err) {
      if (err) {
        console.log('ERROR:', err.message);
        deleteFolders([distFolder, tmpFolder, buildFolder]);
      } else {
        console.log('Compilation finished succesfully');
      }
    });
});

/**
 * Watch for any change in the /src folder and compile files
 */
gulp.task('watch', function () {
  gulp.watch(`${srcFolder}/**/*`, ['compile']);
});

gulp.task('clean', ['clean:dist', 'clean:tmp', 'clean:build']);

gulp.task('build', ['clean', 'compile']);
gulp.task('build:watch', ['build', 'watch']);
gulp.task('default', ['build:watch']);

/**
 * Deletes the specified folder
 */
function deleteFolders(folders) {
  return del(folders);
}
<commit_msg>feat(gulp): update ngc task to Angular 5 compiler syntax<commit_after>/* eslint-disable */
var gulp = require('gulp'),
  path = require('path'),
  ngc = require('@angular/compiler-cli/src/main').main,
  rollup = require('gulp-rollup'),
  rename = require('gulp-rename'),
  del = require('del'),
  runSequence = require('run-sequence'),
  inlineResources = require('./tools/gulp/inline-resources');

const rootFolder = path.join(__dirname);
const srcFolder = path.join(rootFolder, 'src');
const tmpFolder = path.join(rootFolder, '.tmp');
const buildFolder = path.join(rootFolder, 'build');
const distFolder = path.join(rootFolder, 'dist');

/**
 * 1. Delete /dist folder
 */
gulp.task('clean:dist', function () {

  // Delete contents but not dist folder to avoid broken npm links
  // when dist directory is removed while npm link references it.
  return deleteFolders([distFolder + '/**', '!' + distFolder]);
});

/**
 * 2. Clone the /src folder into /.tmp. If an npm link inside /src has been made,
 *    then it's likely that a node_modules folder exists. Ignore this folder
 *    when copying to /.tmp.
 */
gulp.task('copy:source', function () {
  return gulp.src([`${srcFolder}/**/*`, `!${srcFolder}/node_modules`])
    .pipe(gulp.dest(tmpFolder));
});

/**
 * 3. Inline template (.html) and style (.css) files into the the component .ts files.
 *    We do this on the /.tmp folder to avoid editing the original /src files
 */
gulp.task('inline-resources', function () {
  return Promise.resolve()
    .then(() => inlineResources(tmpFolder));
});

/**
 * 4. Run the Angular compiler, ngc, on the /.tmp folder. This will output all
 *    compiled modules to the /build folder.
 *
 *    As of Angular 5, ngc accepts an array and no longer returns a promise.
 */
gulp.task('ngc', function () {
  ngc([ '--project', `${tmpFolder}/tsconfig.es5.json` ]);
  return Promise.resolve()
});

/**
 * 5. Run rollup inside the /build folder to generate our Flat ES module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup:fesm', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({

      // Bundle's entry point
      // See "input" in https://rollupjs.org/#core-functionality
      input: `${buildFolder}/index.js`,

      // Allow mixing of hypothetical and actual files. "Actual" files can be files
      // accessed by Rollup or produced by plugins further down the chain.
      // This prevents errors like: 'path/file' does not exist in the hypothetical file system
      // when subdirectories are used in the `src` directory.
      allowRealFiles: true,

      // A list of IDs of modules that should remain external to the bundle
      // See "external" in https://rollupjs.org/#core-functionality
      external: [
        '@angular/core',
        '@angular/common'
      ],

      // Format of generated bundle
      // See "format" in https://rollupjs.org/#core-functionality
      format: 'es'
    }))
    .pipe(gulp.dest(distFolder));
});

/**
 * 6. Run rollup inside the /build folder to generate our UMD module and place the
 *    generated file into the /dist folder
 */
gulp.task('rollup:umd', function () {
  return gulp.src(`${buildFolder}/**/*.js`)
  // transform the files here.
    .pipe(rollup({

      // Bundle's entry point
      // See "input" in https://rollupjs.org/#core-functionality
      input: `${buildFolder}/index.js`,

      // Allow mixing of hypothetical and actual files. "Actual" files can be files
      // accessed by Rollup or produced by plugins further down the chain.
      // This prevents errors like: 'path/file' does not exist in the hypothetical file system
      // when subdirectories are used in the `src` directory.
      allowRealFiles: true,

      // A list of IDs of modules that should remain external to the bundle
      // See "external" in https://rollupjs.org/#core-functionality
      external: [
        '@angular/core',
        '@angular/common'
      ],

      // Format of generated bundle
      // See "format" in https://rollupjs.org/#core-functionality
      format: 'umd',

      // Export mode to use
      // See "exports" in https://rollupjs.org/#danger-zone
      exports: 'named',

      // The name to use for the module for UMD/IIFE bundles
      // (required for bundles with exports)
      // See "name" in https://rollupjs.org/#core-functionality
      name: '<%= props.libraryName.original %>',

      // See "globals" in https://rollupjs.org/#core-functionality
      globals: {
        typescript: 'ts'
      }

    }))
    .pipe(rename('<%= props.libraryName.kebabCase %>.umd.js'))
    .pipe(gulp.dest(distFolder));
});

/**
 * 7. Copy all the files from /build to /dist, except .js files. We ignore all .js from /build
 *    because with don't need individual modules anymore, just the Flat ES module generated
 *    on step 5.
 */
gulp.task('copy:build', function () {
  return gulp.src([`${buildFolder}/**/*`, `!${buildFolder}/**/*.js`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 8. Copy package.json from /src to /dist
 */
gulp.task('copy:manifest', function () {
  return gulp.src([`${srcFolder}/package.json`])
    .pipe(gulp.dest(distFolder));
});

/**
 * 9. Copy README.md from / to /dist
 */
gulp.task('copy:readme', function () {
  return gulp.src([path.join(rootFolder, 'README.MD')])
    .pipe(gulp.dest(distFolder));
});

/**
 * 10. Delete /.tmp folder
 */
gulp.task('clean:tmp', function () {
  return deleteFolders([tmpFolder]);
});

/**
 * 11. Delete /build folder
 */
gulp.task('clean:build', function () {
  return deleteFolders([buildFolder]);
});

gulp.task('compile', function () {
  runSequence(
    'clean:dist',
    'copy:source',
    'inline-resources',
    'ngc',
    'rollup:fesm',
    'rollup:umd',
    'copy:build',
    'copy:manifest',
    'copy:readme',
    'clean:build',
    'clean:tmp',
    function (err) {
      if (err) {
        console.log('ERROR:', err.message);
        deleteFolders([distFolder, tmpFolder, buildFolder]);
      } else {
        console.log('Compilation finished succesfully');
      }
    });
});

/**
 * Watch for any change in the /src folder and compile files
 */
gulp.task('watch', function () {
  gulp.watch(`${srcFolder}/**/*`, ['compile']);
});

gulp.task('clean', ['clean:dist', 'clean:tmp', 'clean:build']);

gulp.task('build', ['clean', 'compile']);
gulp.task('build:watch', ['build', 'watch']);
gulp.task('default', ['build:watch']);

/**
 * Deletes the specified folder
 */
function deleteFolders(folders) {
  return del(folders);
}
<|endoftext|>


<commit_before>"use strict";

var React = require('react'),
    ReactDOM = require('react-dom'),
    PropTypes = require('prop-types'),
    createReactClass = require('create-react-class'),
    S3Upload = require('./s3upload.js'),
    objectAssign = require('object-assign');

var ReactS3Uploader = createReactClass({

    propTypes: {
        signingUrl: PropTypes.string,
        getSignedUrl: PropTypes.func,
        preprocess: PropTypes.func,
        onSignedUrl: PropTypes.func,
        onProgress: PropTypes.func,
        onFinish: PropTypes.func,
        onError: PropTypes.func,
        signingUrlMethod: PropTypes.string,
        signingUrlHeaders: PropTypes.oneOfType([
          PropTypes.object,
          PropTypes.func
        ]),
        signingUrlQueryParams: PropTypes.oneOfType([
          PropTypes.object,
          PropTypes.func
        ]),
        signingUrlWithCredentials: PropTypes.bool,
        uploadRequestHeaders: PropTypes.object,
        contentDisposition: PropTypes.string,
        server: PropTypes.string,
        scrubFilename: PropTypes.func,
        s3path: PropTypes.string,
        inputRef: PropTypes.func,
        autoUpload: PropTypes.bool
    },

    getDefaultProps: function() {
        return {
            preprocess: function(file, next) {
                console.log('Pre-process: ' + file.name);
                next(file);
            },
            onSignedUrl: function( signingServerResponse ) {
                console.log('Signing server response', signingServerResponse);
            },
            onProgress: function(percent, message) {
                console.log('Upload progress: ' + percent + '% ' + message);
            },
            onFinish: function(signResult) {
                console.log("Upload finished: " + signResult.publicUrl)
            },
            onError: function(message) {
                console.log("Upload error: " + message);
            },
            server: '',
            signingUrlMethod: 'GET',
            scrubFilename: function(filename) {
                return filename.replace(/[^\w\d_\-\.]+/ig, '');
            },
            s3path: '',
            autoUpload: true
        };
    },

    uploadFile: function() {
        this.myUploader = new S3Upload({
            fileElement: ReactDOM.findDOMNode(this),
            signingUrl: this.props.signingUrl,
            getSignedUrl: this.props.getSignedUrl,
            preprocess: this.props.preprocess,
            onSignedUrl: this.props.onSignedUrl,
            onProgress: this.props.onProgress,
            onFinishS3Put: this.props.onFinish,
            onError: this.props.onError,
            signingUrlMethod: this.props.signingUrlMethod,
            signingUrlHeaders: this.props.signingUrlHeaders,
            signingUrlQueryParams: this.props.signingUrlQueryParams,
            signingUrlWithCredentials: this.props.signingUrlWithCredentials,
            uploadRequestHeaders: this.props.uploadRequestHeaders,
            contentDisposition: this.props.contentDisposition,
            server: this.props.server,
            scrubFilename: this.props.scrubFilename,
            s3path: this.props.s3path
        });
    },

    abort: function() {
        this.myUploader && this.myUploader.abortUpload();
    },

    clear: function() {
        clearInputFile(ReactDOM.findDOMNode(this));
    },

    render: function() {
        return React.createElement('input', this.getInputProps());
    },

    getInputProps: function() {
        // declare ref beforehand and filter out
        // `inputRef` by `ReactS3Uploader.propTypes`
        var additional = {
            type: 'file',
            ref: this.props.inputRef
        };

        if ( this.props.autoUpload ) {
            additional.onChange = this.uploadFile;
        }

        var temporaryProps = objectAssign({}, this.props, additional);
        var inputProps = {};

        var invalidProps = Object.keys(ReactS3Uploader.propTypes);

        for(var key in temporaryProps) {
            if(temporaryProps.hasOwnProperty(key) && invalidProps.indexOf(key) === -1) {
                inputProps[key] = temporaryProps[key];
            }
        }

        return inputProps;
    }

});

// http://stackoverflow.com/a/24608023/194065
function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){ }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}

module.exports = ReactS3Uploader;
<commit_msg>Make logging in default onSignedUrl handler conform to style<commit_after>"use strict";

var React = require('react'),
    ReactDOM = require('react-dom'),
    PropTypes = require('prop-types'),
    createReactClass = require('create-react-class'),
    S3Upload = require('./s3upload.js'),
    objectAssign = require('object-assign');

var ReactS3Uploader = createReactClass({

    propTypes: {
        signingUrl: PropTypes.string,
        getSignedUrl: PropTypes.func,
        preprocess: PropTypes.func,
        onSignedUrl: PropTypes.func,
        onProgress: PropTypes.func,
        onFinish: PropTypes.func,
        onError: PropTypes.func,
        signingUrlMethod: PropTypes.string,
        signingUrlHeaders: PropTypes.oneOfType([
          PropTypes.object,
          PropTypes.func
        ]),
        signingUrlQueryParams: PropTypes.oneOfType([
          PropTypes.object,
          PropTypes.func
        ]),
        signingUrlWithCredentials: PropTypes.bool,
        uploadRequestHeaders: PropTypes.object,
        contentDisposition: PropTypes.string,
        server: PropTypes.string,
        scrubFilename: PropTypes.func,
        s3path: PropTypes.string,
        inputRef: PropTypes.func,
        autoUpload: PropTypes.bool
    },

    getDefaultProps: function() {
        return {
            preprocess: function(file, next) {
                console.log('Pre-process: ' + file.name);
                next(file);
            },
            onSignedUrl: function( signingServerResponse ) {
                console.log('Signing server response: ', signingServerResponse);
            },
            onProgress: function(percent, message) {
                console.log('Upload progress: ' + percent + '% ' + message);
            },
            onFinish: function(signResult) {
                console.log("Upload finished: " + signResult.publicUrl)
            },
            onError: function(message) {
                console.log("Upload error: " + message);
            },
            server: '',
            signingUrlMethod: 'GET',
            scrubFilename: function(filename) {
                return filename.replace(/[^\w\d_\-\.]+/ig, '');
            },
            s3path: '',
            autoUpload: true
        };
    },

    uploadFile: function() {
        this.myUploader = new S3Upload({
            fileElement: ReactDOM.findDOMNode(this),
            signingUrl: this.props.signingUrl,
            getSignedUrl: this.props.getSignedUrl,
            preprocess: this.props.preprocess,
            onSignedUrl: this.props.onSignedUrl,
            onProgress: this.props.onProgress,
            onFinishS3Put: this.props.onFinish,
            onError: this.props.onError,
            signingUrlMethod: this.props.signingUrlMethod,
            signingUrlHeaders: this.props.signingUrlHeaders,
            signingUrlQueryParams: this.props.signingUrlQueryParams,
            signingUrlWithCredentials: this.props.signingUrlWithCredentials,
            uploadRequestHeaders: this.props.uploadRequestHeaders,
            contentDisposition: this.props.contentDisposition,
            server: this.props.server,
            scrubFilename: this.props.scrubFilename,
            s3path: this.props.s3path
        });
    },

    abort: function() {
        this.myUploader && this.myUploader.abortUpload();
    },

    clear: function() {
        clearInputFile(ReactDOM.findDOMNode(this));
    },

    render: function() {
        return React.createElement('input', this.getInputProps());
    },

    getInputProps: function() {
        // declare ref beforehand and filter out
        // `inputRef` by `ReactS3Uploader.propTypes`
        var additional = {
            type: 'file',
            ref: this.props.inputRef
        };

        if ( this.props.autoUpload ) {
            additional.onChange = this.uploadFile;
        }

        var temporaryProps = objectAssign({}, this.props, additional);
        var inputProps = {};

        var invalidProps = Object.keys(ReactS3Uploader.propTypes);

        for(var key in temporaryProps) {
            if(temporaryProps.hasOwnProperty(key) && invalidProps.indexOf(key) === -1) {
                inputProps[key] = temporaryProps[key];
            }
        }

        return inputProps;
    }

});

// http://stackoverflow.com/a/24608023/194065
function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){ }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}

module.exports = ReactS3Uploader;
<|endoftext|>


<commit_before>(function () {
    var dropdowns = [];

    var hideAllDropdowns = function () {
        for (var i = 0; i < dropdowns.length; i++) {
            dropdowns[i].dropdownOpen(false);
        }
    }

    window.addEventListener('click', hideAllDropdowns);

    ko.components.register("ko-dropdown", {
        viewModel: function (params) {
            var self = this;

            dropdowns.push(self);

            self.caption = params.caption;
            self.value = params.value;
            self.options = params.options;
            self.isEnabled = params.isEnabled ? params.isEnabled : ko.observable(true); //Enabled by default if isEnabled isn't passed in

            self.dropdownOpen = ko.observable(false);

            self.selectedOption = ko.observable();
            self.selectedText = ko.computed(function () {
                return ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).text : "";
            });

            self.selectOption = function (option) {
                self.value(option.value);
                self.selectedOption(option);
            }

            self.dropdownOptions = ko.computed(function () {
                var retOptions = [];
                self.options().forEach(function (option) {
                    if (typeof option === 'object' || option instanceof Object) {
                        retOptions.push(option);
                    } else {
                        retOptions.push({
                            value: option,
                            text: option
                        });
                    }
                });

                if (retOptions.length > 0 && !ko.unwrap(self.caption)) {
                    self.selectOption(retOptions[0]);
                }

                return retOptions;
            });

            self.dropdownOptions.subscribe(function () {
                self.value.notifySubscribers(self.value()); // so if dropdown options change, update selected value
            })

            if (ko.unwrap(self.value)) {
                self.selectedOption(findOptionByValue(ko.unwrap(self.value)));
            } else if (ko.unwrap(self.caption)) {
                self.selectedOption({
                    text: self.caption
                });
            }

            self.toggleOpen = function (data, event) {
                event.stopPropagation();
                self.dropdownOpen(!self.dropdownOpen());
            }

            self.toggleOpen = function (data, event) {
                var currentStatus = self.dropdownOpen();

                event.stopPropagation();
                hideAllDropdowns();

                if (!currentStatus) {
                    self.dropdownOpen(true);
                }
            }

            self.value.subscribe(function (newValue) {
                var selectedValue = ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).value : null;

                if (newValue !== selectedValue) {
                    var option = findOptionByValue(newValue);
                    if (option != null) {
                        self.selectOption(option);
                    }
                }
            });

            window.addEventListener('click', function (e) {
                self.dropdownOpen(false);
            });

            function findOptionByValue(val) {
                var foundOption = null;
                if (ko.unwrap(self.dropdownOptions)) {
                    self.dropdownOptions().forEach(function (option) {
                        if (option.value === val) {
                            foundOption = option;
                        }
                    });
                }
                return foundOption;
            }
        },
        template: "
\
    \

\

\

\

"
    });

}());
<commit_msg>Prevents auto option select if self.value<commit_after>(function () {
    var dropdowns = [];

    var hideAllDropdowns = function () {
        for (var i = 0; i < dropdowns.length; i++) {
            dropdowns[i].dropdownOpen(false);
        }
    }

    window.addEventListener('click', hideAllDropdowns);

    ko.components.register("ko-dropdown", {
        viewModel: function (params) {
            var self = this;

            dropdowns.push(self);

            self.caption = params.caption;
            self.value = params.value;
            self.options = params.options;
            self.isEnabled = params.isEnabled ? params.isEnabled : ko.observable(true); //Enabled by default if isEnabled isn't passed in

            self.dropdownOpen = ko.observable(false);

            self.selectedOption = ko.observable();
            self.selectedText = ko.computed(function () {
                return ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).text : "";
            });

            self.selectOption = function (option) {
                self.value(option.value);
                self.selectedOption(option);
            }

            self.dropdownOptions = ko.computed(function () {
                var retOptions = [];
                self.options().forEach(function (option) {
                    if (typeof option === 'object' || option instanceof Object) {
                        retOptions.push(option);
                    } else {
                        retOptions.push({
                            value: option,
                            text: option
                        });
                    }
                });

                if (retOptions.length > 0 && !ko.unwrap(self.caption) && !ko.unwrap(self.value)) {
                    self.selectOption(retOptions[0]);
                }

                return retOptions;
            });

            self.dropdownOptions.subscribe(function () {
                self.value.notifySubscribers(self.value()); // so if dropdown options change, update selected value
            })

            if (ko.unwrap(self.value)) {
                self.selectedOption(findOptionByValue(ko.unwrap(self.value)));
            } else if (ko.unwrap(self.caption)) {
                self.selectedOption({
                    text: self.caption
                });
            }

            self.toggleOpen = function (data, event) {
                event.stopPropagation();
                self.dropdownOpen(!self.dropdownOpen());
            }

            self.toggleOpen = function (data, event) {
                var currentStatus = self.dropdownOpen();

                event.stopPropagation();
                hideAllDropdowns();

                if (!currentStatus) {
                    self.dropdownOpen(true);
                }
            }

            self.value.subscribe(function (newValue) {
                var selectedValue = ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).value : null;

                if (newValue !== selectedValue) {
                    var option = findOptionByValue(newValue);
                    if (option != null) {
                        self.selectOption(option);
                    }
                }
            });

            window.addEventListener('click', function (e) {
                self.dropdownOpen(false);
            });

            function findOptionByValue(val) {
                var foundOption = null;
                if (ko.unwrap(self.dropdownOptions)) {
                    self.dropdownOptions().forEach(function (option) {
                        if (option.value == val) {
                            foundOption = option;
                        }
                    });
                }
                return foundOption;
            }
        },
        template: "
\
    \

\

\

\

"
    });

}());
<|endoftext|>


<commit_before>export function createChainCreator(chainFactory, render) {
  // This Proxy initiates the chain, and must return a new Chain
  const handler = {
    get(target, name, receiver) {
      return createChain(name, chainFactory, render);
    }
  };

  return new Proxy({}, handler);
};

const NO_INTERCEPT = [
  'constructor',
  'toString',
  'inspect',
  'nodeType',
  Symbol.toStringTag
];

function createChain(chainName, chainFactory, render) {
  return new Proxy(() => {}, {
    get(target, name) {
      if (name === 'toString') {
        return () => chainName
      }

      if (NO_INTERCEPT.includes(name)) {
        return target[name];
      }

      const chain = chainFactory()
        .startWith(chainName)

      const chainer = createMemberChainer(chain, render);

      chainer[name];

      return chainer;
    },

    apply(target, thisArg, args) {
      const chain = chainFactory()
        .startWith(chainName);

      chain.addArguments(...args);

      const chainer = createMemberChainer(chain, render);

      return chainer;
    },
  });
}

export function createMemberChainer(chain, render) {
  const chainProxy = new Proxy(() => chain, {
    get(target, name, receiver) {

      if (name === 'name') {
        // KEEP ??? Maybe not
        // TODO: less dirty (ensure proper return value)
        return {}
        // return target[name];
      }

      if (name === 'toString') {
        // KEEP
        // TODO: less dirty (ensure proper return value)
        return () => {
          return render(chain);
        };
      }

      if (name === '__repr__') {
        return () => {
          return chain.members
        };
      }

      if (name === 'inspect') {
        // KEEP
        // TODO: less dirty (ensure proper return value)
        return {};
      }

      if (name === 'valueOf') {
        // KEEP
        return () => {
          return render(chain);
        }
      }

      if (name === Symbol.toPrimitive) {
        // KEEP
        return () => {
          // TODO: improve string representation
          return render(chain);
        };
      }

      if (name === Symbol.toStringTag) {
        // KEEP
        // TODO: less dirty (ensure proper return value)
        return {}
      }

      chain.addStep(name);

      return receiver;
    },

    apply(target, thisArg, args) {
      chain.addArguments(...args);

      return chainProxy;
    }
  });

  return chainProxy;
};
<commit_msg>Refactor intercepted methods from if chain to handlers object<commit_after>export function createChainCreator(chainFactory, render) {
  // This Proxy initiates the chain, and must return a new Chain
  const handler = {
    get(target, name, receiver) {
      return createChain(name, chainFactory, render);
    }
  };

  return new Proxy({}, handler);
};

const NO_INTERCEPT = [
  'constructor',
  'toString',
  'inspect',
  'nodeType',
  Symbol.toStringTag
];

function createChain(chainName, chainFactory, render) {
  return new Proxy(() => {}, {
    get(target, name) {
      if (name === 'toString') {
        return () => chainName
      }

      if (NO_INTERCEPT.includes(name)) {
        return target[name];
      }

      const chain = chainFactory()
        .startWith(chainName)

      const chainer = createMemberChainer(chain, render);

      chainer[name];

      return chainer;
    },

    apply(target, thisArg, args) {
      const chain = chainFactory()
        .startWith(chainName);

      chain.addArguments(...args);

      const chainer = createMemberChainer(chain, render);

      return chainer;
    },
  });
}

function createHandler(chain, methodName, render) {
  const handlers = {
    name() {
      return {};
    },
    toString() {
      return () => render(chain)
    },
    inspect() {
      return {};
    },
    valueOf() {
      return () => render(chain)
    },
    [Symbol.toPrimitive]() {
      return () => render(chain)
    },
    [Symbol.toStringTag]() {
      return {}
    },
    __repr__() {
      return () => chain.members;
    }
  }

  return handlers[methodName];
}

export function createMemberChainer(chain, render) {
  const chainProxy = new Proxy(() => chain, {
    get(target, name, receiver) {
      const handler = createHandler(chain, name, render);

      if (handler) {
        return handler();
      }

      chain.addStep(name);

      return receiver;
    },

    apply(target, thisArg, args) {
      chain.addArguments(...args);

      return chainProxy;
    }
  });

  return chainProxy;
};
<|endoftext|>