VaKeR CYBER ARMY
Logo of a company Server : Apache/2.4.41 (Ubuntu)
System : Linux absol.cf 5.4.0-198-generic #218-Ubuntu SMP Fri Sep 27 20:18:53 UTC 2024 x86_64
User : www-data ( 33)
PHP Version : 7.4.33
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Directory :  /var/www/html/libs/absol/dist/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/html/libs/absol/dist/absol.js
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 30);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "f", function() { return /* binding */ waitImageLoaded; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ depthClone; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ copyStyleRule; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ getSystemFontSize; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* binding */ getTextNodeBound; });

// UNUSED EXPORTS: FeatureClass, isDomNode, activeFullScreen, inactiveFullScreen, deactiveFullScreen, isFullScreen, traceOutBoundingClientRect, fontFaceIsLoaded, getScreenSize, waitIFrameLoaded, imageToCanvas, getScrollSize, depthCloneWithStyle, getConstructDescriptor

// EXTERNAL MODULE: ./src/HTML5/JSPath.js
var JSPath = __webpack_require__(17);

// EXTERNAL MODULE: ./src/HTML5/OOP.js
var OOP = __webpack_require__(3);

// CONCATENATED MODULE: ./src/String/getFunctionName.js
/**
 * 
 * @param {Function} func 
 */
function getFunctionName(func) {
  var ret = func.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}
// EXTERNAL MODULE: ./src/HTML5/ElementNS.js
var ElementNS = __webpack_require__(16);

// EXTERNAL MODULE: ./src/HTML5/AElement.js
var AElement = __webpack_require__(1);

// EXTERNAL MODULE: ./src/HTML5/ResizeSystem.js
var ResizeSystem = __webpack_require__(12);

// EXTERNAL MODULE: ./src/JSX/attribute.js
var attribute = __webpack_require__(5);

// EXTERNAL MODULE: ./src/HTML5/AttachHook.js
var AttachHook = __webpack_require__(13);

// CONCATENATED MODULE: ./src/HTML5/Dom.js
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }









/***
 * @typedef {{"accept-charset":string, "http-equiv": string, accept : string, accesskey : string, action : string, align : string, allow : string, alt : string, async : string, autocapitalize : string, autocomplete : string, autofocus : string, autoplay : string, background : string, bgcolor : string, border : string, buffered : string, capture : string, challenge : string, charset : string, checked : string, cite : string, class : string, code : string, codebase : string, color : string, cols : string, colspan : string, content : string, contenteditable : string, contextmenu : string, controls : string, coords : string, crossorigin : string, csp : string, data : string, "data-*" : string, datetime : string, decoding : string, default : string, defer : string, dir : string, dirname : string, disabled : string, download : string, draggable : string, dropzone : string, enctype : string, enterkeyhint : string, for : string,     form : string, formaction : string, formenctype : string, formmethod : string, formnovalidate : string, formtarget : string, headers : string, height : string, hidden : string, high : string, href : string, hreflang : string, icon : string, id : string, importance : string, integrity : string, intrinsicsize : string, inputmode : string, ismap : string, itemprop : string, keytype : string, kind : string, label : string, lang : string, language : string, loading : string, list : string, loop : string, low : string, manifest : string, max : string, maxlength : string, minlength : string, media : string, method : string, min : string, multiple : string, muted : string, name : string, novalidate : string, open : string, optimum : string, pattern : string, ping : string, placeholder : string, poster : string, preload : string, radiogroup : string, readonly : string, referrerpolicy : string, rel : string, required : string, reversed : string, rows : string, rowspan : string, sandbox : string, scope : string, scoped : string, selected : string, shape : string, size : string, sizes : string, slot : string, span : string, spellcheck : string, src : string, srcdoc : string, srclang : string, srcset : string, start : string, step : string, style : string, summary : string, tabindex : string, target : string, title : string, translate : string, type : string, usemap : string, value : string, width : string, wrap : string, }} AElementAttributeDescriptor
 */

/**
 * @typedef {{"arabic-form":string,"baseline-shift": string, "accent-height": string,  "alignment-baseline": string,  "cap-height": string,  "clip-path": string,  "clip-rule": string,  "color-dinterpolation": string,  "color-interpolation-filters": string,  "color-profile": string,  "color-rendering": string,  "dominant-baseline": string,  "enable-background": string,  "fill-opacity": string,  "fill-rule": string,  "flood-color": string,  "flood-opacity": string,  "font-family": string,  "font-size": string,  "font-size-adjust": string,  "font-stretch": string,  "font-style": string,  "font-variant": string,  "font-weight": string,  "glyph-name": string,  "glyph-orientation-horizontal": string,  "glyph-orientation-vertical": string,  "horiz-adv-x": string,  "horiz-origin-x": string,  "image-rendering": string,  "letter-spacing": string,  "lighting-color": string,  "marker-end": string,  "marker-mid": string,  "marker-start": string,  "overline-position": string,  "overline-thickness": string,  "panose-1": string,  "paint-order": string,  "pointer-events": string,  "rendering-intent": string,  "shape-rendering": string,  "stop-color": string,  "stop-opacity": string,  "strikethrough-position": string,  "strikethrough-thickness": string,  "stroke-dasharray": string,  "stroke-dashoffset": string,  "stroke-linecap": string,  "stroke-linejoin": string,  "stroke-miterlimit": string,  "stroke-opacity": string,  "stroke-width": string,  "text-anchor": string,  "text-decoration": string,  "text-rendering": string,  "transform-origin": string,  "underline-position": string,  "underline-thickness": string,  "unicode-bidi": string,  "unicode-range": string,  "units-per-em": string,  "v-alphabetic": string,  "v-hanging": string,  "v-ideographic": string,  "v-mathematical": string,  "vector-effect": string,  "vert-adv-y": string,  "vert-origin-x": string,  "vert-origin-y": string,  "word-spacing": string,  "writing-mode": string,  "x-height": string,  "xlink:actuate": string,  "xlink:arcrole": string,  "xlink:href": string,  "xlink:role": string,  "xlink:show": string,  "xlink:title": string,  "xlink:type": string,  "xml:base": string,  "xml:lang": string,  "xml:space": string, accumulate:string, additive:string, allowReorder:string, alphabetic:string, amplitude:string, ascent:string, attributeName:string, attributeType:string, autoReverse:string, azimuth:string, baseFrequency:string, baseProfile:string, bbox:string, begin:string, bias:string, by:string, calcMode:string, class:string, clip:string, clipPathUnits:string, color:string, contentScriptType:string, contentStyleType:string, cursor:string, cx:string, cy:string, d:string, decelerate:string, descent:string, diffuseConstant:string, direction:string, display:string, divisor:string, dur:string, dx:string, dy:string, edgeMode:string, elevation:string, end:string, exponent:string, externalResourcesRequired:string, fill:NamedColor|Color|string, filter:string, filterRes:string, filterUnits:string, format:string, from:string, fr:string, fx:string, fy:string, g1:string, g2:string, glyphRef:string, gradientTransform:string, gradientUnits:string, hanging:string, height:string, href:string, hreflang:string, id:string, ideographic:string, in:string, in2:string, intercept:string, k:string, k1:string, k2:string, k3:string, k4:string, kernelMatrix:string, kernelUnitLength:string, kerning:string, keyPoints:string, keySplines:string, keyTimes:string, lang:string, lengthAdjust:string, limitingConeAngle:string, local:string, markerHeight:string, markerUnits:string, markerWidth:string, mask:string, maskContentUnits:string, maskUnits:string, mathematical:string, max:string, media:string, method:string, min:string, mode:string, name:string, numOctaves:string, offset:string, opacity:string, operator:string, order:string, orient:string, orientation:string, origin:string, overflow:string, path:string, pathLength:string, patternContentUnits:string, patternTransform:string, patternUnits:string, ping:string, points:string, pointsAtX:string, pointsAtY:string, pointsAtZ:string, preserveAlpha:string, preserveAspectRatio:string, primitiveUnits:string, r:string, radius:string, referrerPolicy:string, refX:string, refY:string, rel:string, repeatCount:string, repeatDur:string, requiredExtensions:string, requiredFeatures:string, restart:string, result:string, rotate:string, rx:string, ry:string, scale:string, seed:string, slope:string, spacing:string, specularConstant:string, specularExponent:string, speed:string, spreadMethod:string, startOffset:string, stdDeviation:string, stemh:string, stemv:string, stitchTiles:string, string:string, stroke:string, style:string, surfaceScale:string, systemLanguage:string, tabindex:string, tableValues:string, target:string, targetX:string, targetY:string, textLength:string, to:string, transform:string, type:string, u1:string, u2:string, unicode:string, values:string, version:string, viewBox:string, viewTarget:string, visibility:string, width:string, widths:string, x:string, x1:string, x2:string, xChannelSelector:string, y:string, y1:string, y2:string, yChannelSelector:string, z:string, zoomAndPan:string, }}  AElementNSAttributeDescriptor
 */

/***
 * @typedef {{abort:function(event:(UiEvent|Event)):void,afterprint:function(event:Event):void,animationend:function(event:AnimationEvent):void,animationiteration:function(event:AnimationEvent):void,animationstart:function(event:AnimationEvent):void,beforeprint:function(event:Event):void,beforeunload:function(event:(UiEvent|Event)):void,blur:function(event:FocusEvent):void,canplay:function(event:Event):void,canplaythrough:function(event:Event):void,change:function(event:Event):void,click:function(event:MouseEvent):void,contextmenu:function(event:MouseEvent):void,copy:function(event:ClipboardEvent):void,cut:function(event:ClipboardEvent):void,dblclick:function(event:MouseEvent):void,drag:function(event:DragEvent):void,dragend:function(event:DragEvent):void,dragenter:function(event:DragEvent):void,dragleave:function(event:DragEvent):void,dragover:function(event:DragEvent):void,dragstart:function(event:DragEvent):void,drop:function(event:DragEvent):void,durationchange:function(event:Event):void,ended:function(event:Event):void,error:function(event:(ProgressEvent|UiEvent|Event)):void,focus:function(event:FocusEvent):void,focusin:function(event:FocusEvent):void,focusout:function(event:FocusEvent):void,fullscreenchange:function(event:Event):void,fullscreenerror:function(event:Event):void,hashchange:function(event:HashChangeEvent):void,input:function(event:(InputEvent|Event)):void,invalid:function(event:Event):void,keydown:function(event:KeyboardEvent):void,keypress:function(event:KeyboardEvent):void,keyup:function(event:KeyboardEvent):void,load:function(event:(UiEvent|Event)):void,loadeddata:function(event:Event):void,loadedmetadata:function(event:Event):void,loadstart:function(event:ProgressEvent):void,message:function(event:Event):void,mousedown:function(event:MouseEvent):void,mouseenter:function(event:MouseEvent):void,mouseleave:function(event:MouseEvent):void,mousemove:function(event:MouseEvent):void,mouseover:function(event:MouseEvent):void,mouseout:function(event:MouseEvent):void,mouseup:function(event:MouseEvent):void,mousewheel:function(event:WheelEvent):void,offline:function(event:Event):void,online:function(event:Event):void,open:function(event:Event):void,pagehide:function(event:PageTransitionEvent):void,pageshow:function(event:PageTransitionEvent):void,paste:function(event:ClipboardEvent):void,pause:function(event:Event):void,play:function(event:Event):void,playing:function(event:Event):void,popstate:function(event:PopStateEvent):void,progress:function(event:Event):void,ratechange:function(event:Event):void,resize:function(event:(UiEvent|Event)):void,reset:function(event:Event):void,scroll:function(event:(UiEvent|Event)):void,search:function(event:Event):void,seeked:function(event:Event):void,seeking:function(event:Event):void,select:function(event:(UiEvent|Event)):void,show:function(event:Event):void,stalled:function(event:Event):void,storage:function(event:StorageEvent):void,submit:function(event:Event):void,suspend:function(event:Event):void,timeupdate:function(event:Event):void,toggle:function(event:Event):void,touchcancel:function(event:TouchEvent):void,touchend:function(event:TouchEvent):void,touchmove:function(event:TouchEvent):void,touchstart:function(event:TouchEvent):void,transitionend:function(event:TransitionEvent):void,unload:function(event:(UiEvent|Event)):void,volumechange:function(event:Event):void,waiting:function(event:Event):void,wheel:function(event:WheelEvent):void}} AElementEventDescriptor
 */

/***
 * @typedef AbsolConstructDescriptor
 * @property {string | function |null} tag
 * @property {CSSStyleDeclaration} style
 * @property {Array | string} extendEvent
 * @property {Array | string} class
 * @property {AElementAttributeDescriptor|AElementNSAttributeDescriptor} attr
 * @property {string|AElement | AElementNS | AbsolConstructDescriptor | string[] |AElement[] | AElementNS[] | AbsolConstructDescriptor[]} child
 * @property {string} text to create a TextNode, not Element
 * @property {AElement} elt
 * @property {AElementEventDescriptor|{}} on
 * @property {Object} props
 *
 */

var Dom_svgCreator = function svgCreator() {
  var temp = document.createElement('div');
  temp.innerHTML = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>';
  var element = temp.childNodes[0];
  var prototypes = Object.getOwnPropertyDescriptors(AElement["a" /* default */].prototype);
  Object.defineProperties(element, prototypes);
  AElement["a" /* default */].call(element);
  return element;
};
/***
 *
 * @param {*=} option
 * @constructor
 */


function Dom(option) {
  option = option || {};
  this.creator = option.creator || {};
  Object.defineProperties(this.creator, {
    svg: {
      set: function set() {//do nothing
      },
      get: function get() {
        return Dom_svgCreator;
      }
    },
    attachhook: {
      set: function set() {//do nothing
      },
      get: function get() {
        return AttachHook["a" /* default */];
      }
    }
  });
  this['$ '.trim()] = this.$.bind(this);
  this['_ '.trim()] = this._.bind(this);
  this['$' + '$'] = this.$$.bind(this);
  this.buildDom = this._;
}

Dom.prototype.defaultTag = 'div';

Dom.prototype.fromCode = function (code) {
  code = code.trim().replace(/>\s+</gm, '><');
  var temTag = 'div';
  if (code.startsWith('<td') || code.startsWith('<th') && !code.startsWith('<thead')) temTag = 'tr';else if (code.startsWith('<tr')) temTag = 'tbody';else if (code.startsWith('<thead') || code.startsWith('<tbody')) temTag = 'table';
  var tempDiv = document.createElement(temTag);
  tempDiv.innerHTML = code;
  var element = tempDiv.childNodes[0];
  var prototypes = Object.getOwnPropertyDescriptors(AElement["a" /* default */].prototype);
  Object.defineProperties(element, prototypes);
  AElement["a" /* default */].call(element);
  return element;
};
/**
 * DFS
 * @param {string | AElement} query
 * @param {AElement} root
 * @param {function} onFound - return true to stop find
 * @returns {AElement | AElementNS}
 */


Dom.prototype.$ = function (query, root, onFound) {
  var res;
  if (Dom.isDomNode(query)) res = query;else res = this.select(query, root, onFound);
  if (res) this.attach(res);
  return res;
};
/***
 *
 * @type {function(string, AElement, Function): AElement}
 */


Dom.prototype.selectAttacth = Dom.prototype.$;
/**
 * DFS
 * @param {string} query
 * @param {AElement} root
 * @param {function} onFound - return true to stop find
 */

Dom.prototype.select = function (query, root, onFound) {
  root = root || document.documentElement;
  var matcher = JSPath["a" /* default */].compileJSPath(query);
  return matcher.findFirst(root, onFound);
};

var FeatureClass = {
  AElementNS: {
    constructor: ElementNS["a" /* default */],
    prototypeKeys: Object.keys(ElementNS["a" /* default */].prototype)
  },
  AElement: {
    constructor: AElement["a" /* default */],
    prototypeKeys: Object.keys(AElement["a" /* default */].prototype)
  }
};
/**
 *
 * @param {AElement | AElementNS } element
 */

Dom.prototype.attach = function (element) {
  if (element.attr) return;
  var feature = element.getBBox && element.tagName !== 'svg' ? FeatureClass.AElementNS : FeatureClass.AElement;
  var elementConstructor = feature.constructor;
  var proto = elementConstructor.prototype;
  var prototypeKeys = feature.prototypeKeys;
  var n = prototypeKeys.length;
  var key;

  for (var i = 0; i < n; ++i) {
    key = prototypeKeys[i];
    element[key] = proto[key];
  }

  Object.assign(element, elementConstructor.prototype);
  elementConstructor.call(element);
};

Dom.prototype.makeNewElement = function (tagName) {
  return document.createElement(tagName);
};

Dom.prototype.makeNewTextNode = function (data) {
  return document.createTextNode(data);
};
/**
 *
 * @param {AbsolConstructDescriptor | string | {} } option
 * @param {boolean=} isInherited
 * @returns {AElementNS| AElement | Text}
 */


Dom.prototype._ = function (option, isInherited) {
  var res;
  var creator;

  if (Dom.isDomNode(option)) {
    res = option;
    option = {};
    /** fix reinit component */

    isInherited = true;
  } else {
    if (option.charAt) {
      option = option.trim();

      if (option[0] === '<') {
        res = this.fromCode(option);
        option = {};
      } else {
        var queryObj = JSPath["a" /* default */].parseQuery(option);
        option = {};
        option.tag = queryObj.tagName || this.defaultTag;
        if (queryObj.classList && queryObj.classList.length > 0) option.class = queryObj.classList;
        if (queryObj.id) option.id = queryObj.id;
        if (queryObj.attributes) option.attr = queryObj.attributes;
      }
    }
  }

  if (option.text || option.text === '') {
    //is textNode
    return this.makeNewTextNode(option.text);
  }

  option.tag = option.tag || this.defaultTag;
  creator = option.tag.prototype ? option.tag : this.creator[option.tag];
  if (option.tag.prototype) option.tag = option.tag.tag;

  if (option.elt) {
    res = this._(option.elt);
  } else {
    if (!res) {
      if (creator) {
        if (creator.render) {
          res = creator.render(option.data, this);
        } else {
          res = creator(option.data, this);
        }
      } else {
        res = this.makeNewElement(option.tag);
        Object.assign(res, option.data);
      }
    }
  }

  this.attach(res);

  if (creator) {
    res._azar_extendTags = res._azar_extendTags || {};
    res._azar_extendTags[option.tag] = creator;
    creator.property && Object.defineProperties(res, creator.property);
    creator.prototype && OOP["a" /* default */].extends(res, creator.prototype);
    creator.attribute && res.defineAttributes(creator.attribute);

    if (creator.render) {
      if (creator.eventHandler) {
        res.eventHandler = res.eventHandler || {};
        var eventHandler = OOP["a" /* default */].bindFunctions(res, creator.eventHandler || creator.prototype.eventHandler);

        for (var eventHandlerKey in eventHandler) {
          if (res.eventHandler[eventHandlerKey]) {
            throw new Error("Same name of eventHandler[" + eventHandlerKey + "]");
          } else {
            res.eventHandler[eventHandlerKey] = eventHandler[eventHandlerKey];
          }
        }
      }

      creator.call(res);
    }
  }

  option.extendEvent && res.defineEvent(option.extendEvent);
  option.attr && res.attr(option.attr);
  option.on && res.on(option.on);
  option.once && res.once(option.once);
  option.class && res.addClass(option.class);
  option.style && res.addStyle(option.style);
  option.id && res.attr('id', option.id);
  if (!isInherited) res.init(option.props);

  if (option.child) {
    option.child = option.child instanceof Array ? option.child : [option.child];

    for (var i = 0; i < option.child.length; ++i) {
      res.addChild(this._(option.child[i], false, true));
    }
  }

  return res;
};
/***
 *
 * @type {function(Object, boolean): AElement}
 */


Dom.prototype.create = Dom.prototype._;
/***
 *
 * @param query
 * @param root
 * @returns {Array<AElement|AElementNS>}
 */

Dom.prototype.$$ = function (query, root) {
  var thisD = this;
  var res = [];
  this.selectAttacth(query, root, function (elt) {
    thisD.attach(elt);
    res.push(elt);
  });
  return res;
};

Dom.prototype.install = function (arg0, arg1) {
  var _this = this;

  if (arguments.length === 1) {
    if (arg0.creator && arg0.create && arg0.select) {
      // is a dom core
      var creator = arg0.creator;
      Object.keys(creator).forEach(function (key) {
        if (key.startsWith('_') || key.startsWith('$')) return;
        var func = creator[key];
        if (typeof func == 'function') if (_this.creator[key] !== func) _this.creator[key] = func;
      });
    } else if (typeof arg0 == 'function') {
      var name = arg0.tag || getFunctionName(arg0) || arg0.name;

      if (name) {
        this.creator[name.toLowerCase()] = arg0;
      } else {
        console.error('No ident name of creator function', arg0);
      }
    } else if (arg0 instanceof Array) {
      arg0.forEach(function (func) {
        var name = func.tag || getFunctionName(func) || func.name;

        if (name) {
          _this.creator[name.toLowerCase()] = func;
        }
      });
    } else if (_typeof(arg0) == 'object') {
      Object.keys(arg0).forEach(function (key) {
        if (key.startsWith('_') || key.startsWith('$')) return;
        var func = arg0[key];
        if (typeof func == 'function') if (_this.creator[key] !== func) _this.creator[key] = func;
      });
    } else {
      console.error('Unknown data', arg0);
    }
  } else if (arguments.length === 2) {
    if (arg0 instanceof Array) {
      if (arg1.creator) arg1 = arg1.creator;
      arg0.forEach(function (key) {
        var func = arg1[key];
        if (typeof func == 'function') if (_this.creator[key] !== func) _this.creator[key] = func;
      });
    } else if (arg0 instanceof RegExp) {
      if (arg1.creator) arg1 = arg1.creator;
      Object.keys(arg1).forEach(function (key) {
        if (key.match(arg0)) {
          var func = arg1[key];
          if (typeof func == 'function') if (_this.creator[key] !== func) _this.creator[key] = func;
        }
      });
    } else if (typeof arg0 == 'string' && arg0.length > 0) {
      if (typeof arg1 == 'function') {
        this.creator[arg0] = arg1;
      } else {
        console.error('arg1 is not a function');
      }
    }
  } else {
    console.error('Invalid param');
  }

  return this;
};
/***
 *
 * @param {String | null} tagName
 */


Dom.prototype.require = function (tagName) {
  return this.creator[tagName] || null;
};
/**
 *
 * @param {*} o
 * @returns {Boolean}
 */


function isDomNode(o) {
  return (typeof Node === "undefined" ? "undefined" : _typeof(Node)) === "object" ? o instanceof Node : o && _typeof(o) === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string";
}
Dom.isDomNode = isDomNode;
/**
 * @param {AElement|Node|HTMLElement} element
 */

function activeFullScreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen(AElement["a" /* default */].ALLOW_KEYBOARD_INPUT);
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}
Dom.activeFullScreen = activeFullScreen;
function inactiveFullScreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
}
Dom.inactiveFullScreen = inactiveFullScreen; //adapt

var deactiveFullScreen = inactiveFullScreen;
Dom.deactiveFullScreen = deactiveFullScreen;
function isFullScreen() {
  var fullScreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  return !!fullScreenElement;
}
Dom.isFullScreen = isFullScreen;
/**
 * @param {AElement|Node|HTMLElement} current
 * @returns {ClientRect}
 */

function traceOutBoundingClientRect(current) {
  var screenSize = Dom.getScreenSize();
  var left = 0;
  var right = screenSize.width;
  var top = 0;
  var bottom = screenSize.height;

  while (current) {
    var ox = AElement["a" /* default */].prototype.getComputedStyleValue.call(current, 'overflow-x') !== "visible";
    var oy = AElement["a" /* default */].prototype.getComputedStyleValue.call(current, 'overflow-y') !== "visible";
    var isHtml = current.tagName.toLowerCase() === 'html';

    if (ox || oy || isHtml) {
      var bound;

      if (isHtml) {
        bound = Object.assign({
          left: 0,
          top: 0
        }, getScreenSize());
        bound.bottom = bound.height;
        bound.right = bound.width;
      } else {
        bound = current.getBoundingClientRect();
      }

      if (ox || isHtml) {
        left = Math.max(left, bound.left);
        right = Math.min(right, bound.right);
      }

      if (oy || isHtml) {
        top = Math.max(top, bound.top);
        bottom = Math.min(bottom, bound.bottom);
      }
    }

    if (isHtml) break;
    current = current.parentElement;
  }

  return {
    left: left,
    right: right,
    top: top,
    bottom: bottom,
    width: right - left,
    height: bottom - top
  };
}
Dom.traceOutBoundingClientRect = traceOutBoundingClientRect;
/***
 *
 * @param {string} fontFace
 * @param {number} timeout
 * @returns {Promise<boolean>}
 */

function fontFaceIsLoaded(fontFace, timeout) {
  timeout = timeout || 0;

  var element = this.ShareInstance._({
    tag: 'span',
    style: {
      visibility: 'hidden',
      position: 'fixed',
      top: '-9999px',
      left: '-9999px',
      'font-size': '256px'
    },
    props: {
      innerHTML: "Test string long long long"
    }
  });

  element.addTo(document.body);
  return element.afterAttached().then(function () {
    var lastOffsetWidth = element.getBoundingClientRect().width;
    element.addStyle('font-family', fontFace);
    return new Promise(function (resolve, reject) {
      function check(remainTime) {
        if (remainTime < 0) {
          resolve(false);
          element.selfRemove();
        } else requestAnimationFrame(function () {
          var currentOffsetWidth = element.getBoundingClientRect().width;

          if (currentOffsetWidth != lastOffsetWidth) {
            resolve(true);
            element.selfRemove();
          } else check(remainTime - 10);
        });
      }

      check(timeout);
    });
  });
}
Dom.fontFaceIsLoaded = fontFaceIsLoaded;
/***
 *
 * @returns {{width: number, WIDTH: number, HEIGHT: number, height: number}}
 */

function getScreenSize() {
  var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  return {
    WIDTH: width,
    HEIGHT: height,
    width: width,
    height: height
  };
}
Dom.getScreenSize = getScreenSize;
/***
 *
 * @param {HTMLImageElement} img
 * @param {number=} timeout
 * @returns {Promise<void>}
 */

function waitImageLoaded(img, timeout) {
  var isLoaded = true;

  if (!img.complete) {
    isLoaded = false;
  }

  if (img.naturalWidth === 0) {
    isLoaded = false;
  }

  if (isLoaded) return Promise.resolve();
  if (!img.src) return Promise.resolve();
  return new Promise(function (rs) {
    if (img.addEventListener) {
      img.addEventListener('load', rs, false);
      img.addEventListener('error', rs, false);
    } else {
      img.attachEvent('onload', rs, false);
    }

    setTimeout(rs, timeout || 5000);
  }); // No other way of checking: assume it’s ok.
}
Dom.waitImageLoaded = waitImageLoaded;
/***
 *
 * @param {HTMLIFrameElement| Worker} iframe
 * @returns {Promise}
 */

function waitIFrameLoaded(iframe) {
  return new Promise(function (rs, rj) {
    if (document.all) {
      iframe.onreadystatechange = function () {
        if (iframe.readyState === "complete" || iframe.readyState === "loaded") rs();
      };
    } else {
      iframe.onload = rs;
    }

    setTimeout(rs, 5000);
  });
}
Dom.waitIFrameLoaded = waitIFrameLoaded;
/***
 *
 * @param {Image} element
 * @returns {Promise<HTMLCanvasElement>}
 */

function imageToCanvas(element) {
  if (typeof element == 'string') {
    element = Dom.ShareInstance.$(element);
  }

  if (element.tagName.toLowerCase() === 'img') {
    var preRender = Dom.ShareInstance._('div');

    preRender.addStyle({
      position: 'fixed',
      top: '0',
      left: '0',
      zIndex: '-10000',
      opacity: '0'
    }).addTo(document.body);
    var canvas = document.createElement("canvas");
    preRender.addChild(canvas);
    return Dom.waitImageLoaded(element).then(function () {
      canvas.width = element.width;
      canvas.height = element.height;
      var context = canvas.getContext("2d");
      context.drawImage(element, 0, 0);
      preRender.selfRemove();
      return canvas;
    });
  } else {
    throw new Error("AElement must be image");
  }
}
Dom.imageToCanvas = imageToCanvas;
Dom.ShareInstance = new Dom();
Dom.scrollWidthPromise;
Dom.documentReady = new Promise(function (resolve) {
  if (document.body) {
    resolve();
  } else {
    window.addEventListener("load", resolve);
  }
});
function getScrollSize() {
  if (!Dom.scrollWidthPromise) Dom.scrollWidthPromise = new Promise(function (resolve) {
    function prerender() {
      var parent = Dom.ShareInstance._({
        style: {
          'z-index': '-100',
          opacity: '0',
          width: '100px',
          height: '100px',
          overflow: 'scroll',
          top: '0',
          left: '0',
          'box-sizing': 'content-box',
          position: 'fixed'
        }
      }).addTo(document.body);

      var child = Dom.ShareInstance._({
        style: {
          width: '100%',
          height: '100%'
        }
      }).addTo(parent);

      requestAnimationFrame(function () {
        var parentBound = parent.getBoundingClientRect();
        var childBound = child.getBoundingClientRect();
        resolve({
          width: parentBound.width - childBound.width,
          height: parentBound.height - childBound.height
        });
        parent.selfRemove();
      });
    }

    Dom.documentReady.then(prerender);
  });
  return Dom.scrollWidthPromise;
}
Dom.getScrollSize = getScrollSize;
/***
 *
 * @param {(AElement|AElementNS|Node)} originElt
 * @param {function(originElt: (AElement|AElementNS|Node), originElt: (AElement|AElementNS|Node)):void } afterCloneCb
 * @return {AElement|AElementNS|Node}
 */

function depthClone(originElt, afterCloneCb) {
  /***
   *
   * @type {AElement|AElementNS|Node}
   */
  var newElt = originElt.cloneNode(); //no deep

  if (originElt.childNodes) {
    /***
     *
     * @type {(AElement|AElementNS)[]}
     */
    var children = Array.prototype.map.call(originElt.childNodes, function (child) {
      return depthClone(child, afterCloneCb);
    });

    for (var i = 0; i < children.length; ++i) {
      newElt.appendChild(children[i]);
    }
  }

  return afterCloneCb && afterCloneCb(originElt, newElt) || newElt;
}
/***
 *
 * @param originElt
 * @param afterCloneCb
 * @returns {AElement|HTMLElement|Node}
 */

function depthCloneWithStyle(originElt, afterCloneCb) {
  return depthClone(originElt, function (originElt, newElt) {
    if (!originElt.getAttribute && !originElt.getAttributeNS) return;
    copyStyleRule(originElt, newElt);
    afterCloneCb && afterCloneCb(originElt, newElt);
  });
}
Dom.depthClone = depthClone;
Dom.depthCloneWithStyle = depthCloneWithStyle;
/***
 *
 * @param  {AElement|HTMLElement|Node}sourceElt
 * @param  {AElement|HTMLElement|Node} destElt
 * @returns  {AElement|HTMLElement|Node}
 */

function copyStyleRule(sourceElt, destElt) {
  if (!sourceElt.getAttribute && !sourceElt.getAttributeNS) return destElt; //is text node

  if (!destElt.getAttribute && !destElt.getAttributeNS) return destElt; //is text node, nothing to copy

  var cssRules = AElement["a" /* default */].prototype.getCSSRules.call(sourceElt);
  var cssKey = cssRules.reduce(function (ac, rule) {
    for (var i = 0; i < rule.style.length; ++i) {
      ac[rule.style[i]] = true;
    }

    return ac;
  }, {});

  for (var key in cssKey) {
    destElt.style[key] = AElement["a" /* default */].prototype.getComputedStyleValue.call(sourceElt, key);
  }

  return destElt;
}
Dom.copyStyleRule = copyStyleRule;
/**
 *
 */

function getSystemFontSize() {
  if (window.mobileHost && window.mobileHost.systemFont) {
    return window.mobileHost.systemFont.pointSize;
  }

  var _ = Dom.ShareInstance._;

  var initSpan = Dom.ShareInstance._({
    tag: 'span',
    style: {
      font: 'inherit'
    }
  });

  var appleSpan = Dom.ShareInstance._({
    tag: 'span',
    style: {
      font: '-apple-system-body'
    }
  }).addTo(document.body);

  var renderer = _({
    style: {
      font: 'initial',
      position: 'fixed',
      top: 0,
      left: 0,
      visibility: 'hidden',
      opacity: 0,
      zIndex: -100
    },
    child: [initSpan && appleSpan]
  }).addTo(document.body);

  var appleSize = appleSpan.getFontSize();
  var initSize = initSpan.getFontSize();
  var defaultSize = appleSize !== initSize ? appleSize : initSize;
  renderer.remove();
  return Math.round(defaultSize * 14 / 16);
}
function getTextNodeBound(textNode) {
  if (document.createRange) {
    var range = document.createRange();
    range.selectNodeContents(textNode);

    if (range.getBoundingClientRect) {
      return range.getBoundingClientRect();
    }
  }

  return null;
}
Dom.getTextNodeBound = getTextNodeBound;
/***
 * get absol construct descriptor for HTML element only
 * @param {AElement | Text} elt
 * @returns {AbsolConstructDescriptor}
 */

function getConstructDescriptor(elt) {
  var obj = {};
  obj.tag = elt.tagName.toLowerCase();
  var classAttr = elt.getAttribute('class');
  var classList;
  if (classAttr) classList = Object(attribute["parseClassAttr"])(classAttr);
  if (classList && classList.length > 0) obj.class = classList;
  var styleAttr = elt.getAttribute('style');
  var style;
  if (styleAttr) style = Object(attribute["parseStyleAttr"])(styleAttr);
  var attributes = elt.attributes;
  var attNode;
  var attrName;
  var attrValue;
  var attr = {};
  var on = {};
  var props = {};
  var eventMatch, eventName;
  var propMatch, propName;

  for (var i = 0; i < attributes.length; ++i) {
    attNode = attributes[i];
    attrName = attNode.nodeName;
    attrValue = attNode.nodeValue;
    if (attrName == 'style' || attrName == 'class') continue;
    eventMatch = attrName.match(/^on(.+)/);

    if (eventMatch) {
      eventName = eventMatch[1];
      on[eventName] = new Function('event', 'sender', attrValue);
      continue;
    }

    propMatch = attrName.match(/^prop-(.+)/);

    if (propMatch) {
      propName = propMatch[1];
      props[propName] = attrValue;
      continue;
    }

    attr[attrName] = attrValue;
  }

  var key;

  for (key in style) {
    //style is not empty
    obj.style = style;
    break;
  }

  for (key in attr) {
    obj.attr = attr;
    break;
  }

  for (key in on) {
    obj.on = on;
    break;
  }

  for (key in props) {
    obj.props = props;
    break;
  }

  return obj;
}
Dom.getConstructDescriptor = getConstructDescriptor;

Dom.addToResizeSystem = function (element) {
  ResizeSystem["a" /* default */].add(element);
};

Dom.updateResizeSystem = function () {
  ResizeSystem["a" /* default */].update();
};

Dom.updateSizeUp = function (fromElt) {
  ResizeSystem["a" /* default */].updateUp(fromElt);
};

/* harmony default export */ var HTML5_Dom = __webpack_exports__["b"] = (Dom);

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _EventEmitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _Detector_BrowserDetector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _OOP__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);



/***
 * @augments Node
 * @augments ChildNode
 * @augments ParentNode
 * @augments Element
 * @augments HTMLElement
 * @augments EventEmitter
 * @augments ElementCSSInlineStyle
 * @constructor
 */

function AElement() {
  _EventEmitter__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].call(this);
  this._azar_extendAttributes = this._azar_extendAttributes || {};
  this._azar_extendTags = {};
  this.eventHandler = {};
}

_OOP__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].mixClass(AElement, _EventEmitter__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]);

AElement.prototype.init = function (props) {
  Object.assign(this, props || {});
};

AElement.prototype.eventHandler = {};
/***
 * run super-class method
 */

AElement.prototype.super = function () {
  /* nope */
};
/**
 * @typedef {Object} AttributeDefiner
 * @property {Function} set
 * @property {Function} get
 * @property {Function} remove
 *
 * @param {String} key
 * @param {AttributeDefiner} def
 */


AElement.prototype.defineAttribute = function (key, def) {
  this._azar_extendAttributes[key] = def;
};

AElement.prototype.defineAttributes = function (defs) {
  for (var key in defs) {
    this.defineAttribute(key, defs[key]);
  }
};

AElement.prototype.attr = function () {
  if (arguments.length === 1) {
    if (typeof arguments[0] == 'string') {
      if (this._azar_extendAttributes[arguments[0]]) {
        return this._azar_extendAttributes[arguments[0]].get.call(this);
      } else return this.getAttribute(arguments[0]);
    } else {
      for (var key in arguments[0]) {
        this.attr(key, arguments[0][key]);
      }
    }
  } else {
    if (arguments.length == 2) {
      if (arguments[1] === null || arguments[1] === undefined) {
        if (this._azar_extendAttributes[arguments[0]]) {
          this._azar_extendAttributes[arguments[0]].remove.call(this, arguments[1]);
        } else this.removeAttribute(arguments[0]);
      } else {
        if (this._azar_extendAttributes[arguments[0]]) {
          this._azar_extendAttributes[arguments[0]].set.call(this, arguments[1]);
        } else {
          this.setAttribute(arguments[0], arguments[1]);
        }
      }
    }
  }

  return this;
};
/***
 * add style
 * @param {CSSStyleDeclaration|string|{}} arg0
 * @param {string} arg1
 * @returns {this}
 */

/**
 * add style
 * @param {CSSStyleDeclaration|string|{}} arg0
 * @param {string|[]=} arg1
 * @returns {this}
 */


AElement.prototype.addStyle = function (arg0, arg1) {
  if (typeof arg0 == 'string') {
    if (arg0.indexOf('-') >= 0) {
      if (arg1 && arg1.forEach) {
        this.style.setProperty.apply(this.style, [arg0].concat(arg1));
      } else {
        this.style.setProperty(arg0, arg1);
      }
    } else {
      this.style[arg0] = arg1;
    }
  } else {
    for (var key in arg0) {
      this.addStyle(key, arg0[key]);
    }
  }
  return this;
};
/***
 *
 * @param {string|string[]|CSSStyleDeclaration} arg0
 * @returns {this}
 */


AElement.prototype.removeStyle = function (arg0) {
  var key;

  if (arg0.charAt) {
    if (arg0.indexOf('-') >= 0) {
      this.style.removeProperty(arg0);
    } else {
      this.style[arg0] = null;
      delete this.style[arg0];
    }
  } else {
    if (arg0.map && arg0.forEach) {
      for (var i = 0; i < arg0.length; ++i) {
        this.removeStyle(arg0[i]);
      }
    } else {
      for (key in arg0) {
        this.removeStyle(key);
      }
    }
  }

  return this;
};

AElement.prototype.addChild = function (child) {
  if (child.indexOf && child.map && child.forEach) {
    for (var i = 0; i < child.length; ++i) {
      this.appendChild(child[i]);
    }
  } else this.appendChild(child);

  return this;
};

AElement.prototype.addTo = function (parent) {
  if (parent && parent.appendChild) {
    if (parent.addChild) parent.addChild(this);else parent.appendChild(this);
  } else throw Error("Can not append to " + parent + "!");

  return this;
};

AElement.prototype.selfRemove = function () {
  if (this.parentElement) this.parentElement.removeChild(this);
  return this;
};

AElement.prototype.selfReplace = function (newNode) {
  if (this.parentElement) this.parentElement.replaceChild(newNode, this);
  return this;
};

AElement.prototype.clearChild = function () {
  while (this.firstChild) {
    this.removeChild(this.firstChild);
  }

  return this;
};
/**
 *
 * @param {string|Array} className
 * @returns {Boolean}
 */


AElement.prototype.hasClass = function (className) {
  return this.classList.contains(className);
};
/**
 *
 * @param {string|Array} className
 * @returns {this}
 */


AElement.prototype.addClass = function (className) {
  if (className && className.forEach && className.map) {
    for (var i = 0; i < className.length; ++i) {
      this.classList.add(className[i]);
    }
  } else this.classList.add(className);

  return this;
};
/**
 *
 * @param {string|Array} className
 * @returns {this}
 */


AElement.prototype.removeClass = function (className) {
  if (className && className.forEach && className.map) {
    for (var i = 0; i < className.length; ++i) {
      this.classList.remove(className[i]);
    }
  } else this.classList.remove(className);

  return this;
};

AElement.prototype.getComputedStyleValue = function (key) {
  return window.getComputedStyle(this).getPropertyValue(key);
};

AElement.prototype.getFontSize = function () {
  return parseFloat(this.getComputedStyleValue('font-size').replace('px', ''));
};

AElement.prototype.findChildAfter = function (obj) {
  var r = 0;

  for (var i = 0; i < this.childNodes.length; ++i) {
    if (obj == this.childNodes[i]) {
      r = i + 1;
      break;
    }
  }

  if (this.childNodes[r]) return this.childNodes[r];
  return undefined;
};

AElement.prototype.findChildBefore = function (obj) {
  var r = 0;

  for (var i = 0; i < this.childNodes.length; ++i) {
    if (obj == this.childNodes[i]) {
      r = i - 1;
      break;
    }
  }

  if (this.childNodes[r]) return this.childNodes[r];
  return undefined;
};

AElement.prototype.addChildBefore = function (newItem, bf) {
  this.insertBefore(newItem, bf);
  return this;
};

AElement.prototype.addChildAfter = function (newItem, at) {
  var atIdx;

  if (at) {
    atIdx = Array.prototype.indexOf.call(this.childNodes, at);

    if (atIdx >= 0) {
      this.insertBefore(newItem, this.childNodes[atIdx + 1]);
    } else {
      throw new Error("Failed to execute 'addChildAfter' on 'Node': The node before which the new node is to be inserted is not a child of this node.");
    }
  } else {
    this.insertBefore(newItem, this.firstChild);
  }

  return this;
};
/**
 * @returns {DOMRect}
 */


AElement.prototype.getBoundingRecursiveRect = function (depth) {
  if (depth === undefined) depth = 10000;
  var current, next;
  var oo = 1000000;
  var ac = {
    left: oo,
    right: -oo,
    top: oo,
    bottom: -oo,
    width: 0,
    height: 0
  };
  var stacks = [{
    e: this,
    d: 0
  }];

  while (stacks.length > 0) {
    current = stacks.pop();

    if (current.e.getBoundingClientRect) {
      var cRect = current.e.getBoundingClientRect();
      if (!cRect || !(cRect.width || cRect.height || cRect.left || cRect.right)) continue;
      ac.left = Math.min(ac.left, cRect.left);
      ac.top = Math.min(ac.top, cRect.top);
      ac.bottom = Math.max(ac.bottom, cRect.bottom);
      ac.right = Math.max(ac.right, cRect.right);
      ac.height = ac.bottom - ac.top;
      ac.width = ac.right - ac.left;
      var childNodes = current.e.childNodes;

      if (childNodes && childNodes.length > 0 && current.d < depth) {
        for (var i = 0; i < childNodes.length; ++i) {
          next = {
            e: childNodes[i],
            d: current.d + 1
          };
          stacks.push(next);
        }
      }
    }
  }

  return ac;
};
/***
 *
 * @param parent
 * @returns {boolean}
 */


AElement.prototype.isDescendantOf = function (parent) {
  var child = this;

  while (child) {
    if (child === parent) return true;
    child = child.parentNode;
  }

  return false;
};
/*************************** **********************/


AElement.prototype.getCSSRules = function () {
  var sheets = document.styleSheets;
  var ret = [];
  this.matches = this.matches || this.webkitMatchesSelector || this.mozMatchesSelector || this.msMatchesSelector || this.oMatchesSelector;

  for (var i in sheets) {
    if (sheets[i].href) continue; //because can not access, you must clone link node instead

    var rules = sheets[i].rules || sheets[i].cssRules;

    for (var r in rules) {
      if (this.matches(rules[r].selectorText)) {
        ret.push(rules[r]);
      }
    }
  }

  return ret;
};
/***
 * @returns {Promise}
 */

/***
 * WARNING: this function may be unsafe
 */


AElement.prototype.afterDisplayed = function (requestTimesOut) {
  if (!requestTimesOut) requestTimesOut = 24 * 3600 * 33; // var tracer = new Error();

  var current = this;
  return new Promise(function (resolve, reject) {
    function trace() {
      if (requestTimesOut < 0) {// reject(tracer);
        // if (absol.BUILD && absol.BUILD.version == "DEBUG")
        //     console.warn("Element not displayed", trace);
      } else {
        requestTimesOut--;
        var bound = current.getBoundingClientRect();

        if (bound.width > 0 || bound.height > 0) {
          resolve();
        } else {
          setTimeout(trace, 33);
          return;
        }
      }
    }

    trace();
  });
};

!function () {
  var origin = AElement.prototype.on;

  if (_Detector_BrowserDetector__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].isSafari && !_Detector_BrowserDetector__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].isMobile) {
    AElement.prototype.on = function () {
      if (!this.isSupportedEvent('mouseleave') && arguments[0] == 'mouseleave') {
        this.defineEvent('mouseleave');

        var mouseLeaveEventHandler = function mouseLeaveEventHandler(event) {
          var bound = this.getBoundingClientRect();
          var ok = false;
          ok |= event.clientX < bound.left + 1;
          ok |= event.clientX >= bound.right - 1;
          ok |= event.clientY < bound.top + 1;
          ok |= event.clientY >= bound.bottom - 1;
          if (ok) this.emit('mouseleave', event);
        };

        this.addEventListener('mouseleave', mouseLeaveEventHandler, true);
      }

      origin.apply(this, arguments);
      return this;
    };
  }

  if (_Detector_BrowserDetector__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].isFirefox) {
    AElement.prototype.on = function () {
      if (!this.isSupportedEvent('wheel') && arguments[0] == 'wheel') {
        this.defineEvent('wheel');

        var wheelEventHandler = function wheelEventHandler(oldEvent) {
          //clone event to avoid some lib fix it
          var event = oldEvent.absolEvent;

          if (!event) {
            event = Object.assign({}, oldEvent);

            for (var i = 0; i < AElement.eventProperties.length; ++i) {
              var key = AElement.eventProperties[i];

              if (typeof event[key] == 'function') {
                event[key] = event[key].bind(oldEvent);
              }
            }

            event.preventDefault = function () {
              oldEvent.preventDefault();
            };

            if (!event.mozFixWheelScale) {
              event.mozDeltaY = oldEvent.deltaY;
              event.mozFixWheelScale = true;
              Object.defineProperty(event, 'deltaY', {
                get: function get() {
                  return this.mozDeltaY * 100 / 3;
                }
              });
            }

            oldEvent.absolEvent = event;
          }

          this.emit('wheel', event);
        };

        this.addEventListener('wheel', wheelEventHandler);
      }

      origin.apply(this, arguments);
      return this;
    };
  }
}();
AElement.eventProperties = ["altKey", "bubbles", "button", "buttons", "cancelBubble", "cancelable", "clientX", "clientY", "composed", "ctrlKey", "currentTarget", "defaultPrevented", "deltaMode", "deltaX", "deltaY", "deltaZ", "detail", "eventPhase", "explicitOriginalTarget", "isTrusted", "layerX", "layerY", "metaKey", "movementX", "movementY", "mozInputSource", "mozPressure", "offsetX", "offsetY", "originalTarget", "pageX", "pageY", "rangeOffset", "rangeParent", "region", "relatedTarget", "returnValue", "screenX", "screenY", "shiftKey", "srcElement", "target", "timeStamp", "type", "deltaMode", "deltaX", "deltaY", "deltaZ"];
/* harmony default export */ __webpack_exports__["a"] = (AElement);

/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export eventProperties */
/* unused harmony export touchProperties */
/* unused harmony export isMouseRight */
/* unused harmony export isMouseLeft */
/* unused harmony export hitElement */
/* unused harmony export copyEvent */
/* unused harmony export copyTouch */
/* unused harmony export findChangedTouchByIdent */
/* unused harmony export findTouchByIdent */
/* harmony import */ var _Code_safeThrow__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }



function EventEmitter() {
  if (!this._azar_extendEvents) {
    Object.defineProperty(this, '_azar_extendEvents', {
      enumerable: false,
      value: this._azar_extendEvents || {
        supported: {},
        prioritize: {},
        nonprioritize: {}
      }
    });
    Object.defineProperty(this, '__azar_force', {
      value: !((typeof Node === "undefined" ? "undefined" : _typeof(Node)) === "object" ? this instanceof Node : this && _typeof(this) === "object" && typeof this.nodeType === "number" && typeof this.nodeName === "string"),
      enumerable: false
    });
  }
}

EventEmitter.prototype.defineEvent = function (name) {
  if (name instanceof Array) {
    for (var i = 0; i < name.length; ++i) {
      this._azar_extendEvents.supported[name[i]] = true;
    }
  } else this._azar_extendEvents.supported[name] = true;

  return this;
};

EventEmitter.prototype.isSupportedEvent = function (name) {
  return this.__azar_force || !!this._azar_extendEvents.supported[name];
};

EventEmitter.prototype.emit = function (eventName, data) {
  this.fire.apply(this, arguments);
};

EventEmitter.prototype.fire = function (eventName, data) {
  var others = Array.prototype.slice.call(arguments, 1);

  if (this.isSupportedEvent(eventName)) {
    var listenerList;
    var i;

    if (this._azar_extendEvents.prioritize[eventName]) {
      listenerList = this._azar_extendEvents.prioritize[eventName].slice();

      for (i = 0; i < listenerList.length; ++i) {
        try {
          listenerList[i].wrappedCallback.apply(this, others);
        } catch (e) {
          Object(_Code_safeThrow__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(e);
        }
      }
    }

    if (this._azar_extendEvents.nonprioritize[eventName]) {
      listenerList = this._azar_extendEvents.nonprioritize[eventName].slice();

      for (i = 0; i < listenerList.length; ++i) {
        try {
          listenerList[i].wrappedCallback.apply(this, others);
        } catch (e) {
          Object(_Code_safeThrow__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(e);
        }
      }
    }
  } else {
    if (this.dispatchEvent) {
      var event = new Event(eventName);
      data && Object.assign(event, data);
      this.dispatchEvent(event);
    } else throw new Error("Not support event " + eventName);
  }

  return this;
};

EventEmitter.prototype.eventEmittorOnWithTime = function (isOnce, arg0, arg1, arg2) {
  if (_typeof(arg0) == 'object') {
    for (var key in arg0) {
      this.eventEmittorOnWithTime(isOnce, key, arg0[key]);
    }

    return this;
  } else {
    if (_typeof(arg1) == 'object') {
      return this.eventEmittorOnWithTime(isOnce, arg0, arg1.callback, arg1.cap);
    } else {
      var eventArr = this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] || [];
      var eventIndex = -1;

      for (var i = 0; i < eventArr.length; ++i) {
        if (eventArr[i].wrappedCallback == arg1) {
          eventIndex = i;
          break;
        }
      }

      if (eventIndex < 0) {
        var event = {
          isOnce: isOnce,
          eventName: arg0,
          callback: arg1,
          cap: !!arg2
        }; //wrappedCallback will be call

        if (isOnce) {
          event.wrappedCallback = function () {
            this.off(event.eventName, event.wrappedCallback, event.cap);
            event.callback.apply(this, arguments);
          };
        } else {
          event.wrappedCallback = event.callback;
        }

        if (!this.isSupportedEvent(arg0)) {
          if (this.addEventListener) {
            this.addEventListener(arg0, event.wrappedCallback, !!arg2);
          } else {
            this.attachEvent('on' + arg0, arg1, !!arg2);
          }
        }

        eventArr.push(event);
        this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] = eventArr;
      } else {
        console.warn("dupplicate event");
      }
    }

    return this;
  }
};

EventEmitter.prototype.on = function (arg0, arg1, arg2) {
  this.eventEmittorOnWithTime(false, arg0, arg1, arg2);
  return this;
};

EventEmitter.prototype.once = function (arg0, arg1, arg2) {
  this.eventEmittorOnWithTime(true, arg0, arg1, arg2);
  return this;
};

EventEmitter.prototype.off = function (arg0, arg1, arg2) {
  if (_typeof(arg0) == 'object') {
    for (var key in arg0) {
      this.off(key, arg0[key]);
    }

    return this;
  } else {
    if (_typeof(arg1) == 'object') {
      return this.off(arg0, arg1.callback, arg1.cap);
    } else {
      var eventArr = this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] || [];
      var newEventArray = [];

      for (var i = 0; i < eventArr.length; ++i) {
        var event = eventArr[i];

        if (event.wrappedCallback == arg1) {
          //Dont add to newEventArray
          if (this.isSupportedEvent(arg0)) {} else {
            if (this.removeEventListener) {
              this.removeEventListener(event.eventName, event.wrappedCallback, !!event.cap);
            } else {
              this.detachEvent('on' + event.eventName, event.wrappedCallback, !!event.cap);
            }
          }
        } else {
          newEventArray.push(event);
        }
      }

      this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] = newEventArray;
      return this;
    }
  }
};

var eventProperties = ["altKey", "bubbles", "button", "buttons", "cancelBubble", "cancelable", "clientX", "clientY", "composed", "ctrlKey", "currentTarget", "defaultPrevented", "deltaMode", "deltaX", "deltaY", "deltaZ", "detail", "eventPhase", "explicitOriginalTarget", "isTrusted", "layerX", "layerY", "metaKey", "movementX", "movementY", "mozInputSource", "mozPressure", "offsetX", "offsetY", "originalTarget", "pageX", "pageY", "rangeOffset", "rangeParent", "region", "relatedTarget", "returnValue", "screenX", "screenY", "shiftKey", "srcElement", "target", "timeStamp", "type", "deltaMode", "deltaX", "deltaY", "deltaZ", 'preventDefault'];
var touchProperties = ['clientX', 'clientY', 'force', 'identifier', 'pageX', 'pageY', 'rotationAngle', 'screenX', 'screenY', 'target'];
function isMouseRight(event) {
  var isRightMB = false;
  if ("which" in event) // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
    isRightMB = event.which == 3;else if ("button" in event) // IE, Opera
    isRightMB = event.button == 2;
  return isRightMB;
}
function isMouseLeft(event) {
  var isLeftMB = false;
  if ("which" in event) // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
    isLeftMB = event.which == 1;else if ("button" in event) // IE, Opera
    isLeftMB = event.button == 1;
  return isLeftMB;
}
function hitElement(element, event) {
  var current = event.target;

  while (current) {
    if (current == element) return true;
    current = current.parentElement;
  }

  return false;
}
function copyEvent(event, props) {
  var result = {};
  var key, value; //copy native property

  for (var i = 0; i < eventProperties.length; ++i) {
    key = eventProperties[i];
    value = event[key];

    if (value !== undefined) {
      if (typeof value == "function") {
        result[key] = event[key].bind(event);
      } else {
        result[key] = event[key];
      }
    }
  }

  Object.assign(result, event);
  if (props) Object.assign(result, props);

  if (event.changedTouches) {
    result.changedTouches = Array.prototype.map.call(event.changedTouches, function (touch) {
      return copyTouch(touch);
    });
  }

  if (event.touches) {
    result.touches = Array.prototype.map.call(event.touches, function (touch) {
      return copyTouch(touch);
    });
  }

  return result;
}
function copyTouch(touch, props) {
  var result = {};
  var key, value; //copy native property

  for (var i = 0; i < touchProperties.length; ++i) {
    key = touchProperties[i];
    value = touch[key];

    if (value !== undefined) {
      if (typeof value == "function") {
        result[key] = touch[key].bind(touch);
      } else {
        result[key] = touch[key];
      }
    }
  }

  Object.assign(result, touch);
  if (props) Object.assign(result, props);
  return result;
}
/***
 *
 * @param {TouchEvent} event
 * @return {Touch | null}
 */

function findChangedTouchByIdent(event, identifier) {
  if (event.changedTouches) {
    for (var i = 0; i < event.changedTouches.length; ++i) {
      if (event.changedTouches[i].identifier === identifier) {
        return event.changedTouches[i];
      }
    }
  }

  return null;
}
/***
 *
 * @param event
 * @param identifier
 * @return {Touch|null}
 */

function findTouchByIdent(event, identifier) {
  if (event.touches) {
    for (var i = 0; i < event.touches.length; ++i) {
      if (event.touches[i].identifier === identifier) {
        return event.touches[i];
      }
    }
  }

  return null;
}
EventEmitter.isMouseRight = isMouseRight;
EventEmitter.isMouseLeft = isMouseLeft;
EventEmitter.hitElement = hitElement;
EventEmitter.copyEvent = copyEvent;
EventEmitter.eventProperties = eventProperties;
/* harmony default export */ __webpack_exports__["a"] = (EventEmitter);

/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
var OOP = {};
/**
 * @param {Object} object
 * @param {String} key
 * @param {Function} method
 */

OOP.overrideMethod = function (object, key, method) {
  if (object[key] === undefined) object[key] = method;else {
    var _superMethod = object[key];

    object[key] = function (_superMethod, method) {
      return function () {
        var _super = this.super;
        this.super = _superMethod;
        var result = method.apply(this, arguments);
        this.super = _super;
        return result;
      };
    }(_superMethod, method);
  }
};

OOP.extends = function (object, prototype) {
  // do not use setter, getter
  for (var key in prototype) {
    if (key !== 'constructor' && key !== '__proto__') {
      if (typeof prototype[key] == 'function') {
        OOP.overrideMethod(object, key, prototype[key]);
      } else if (prototype[key] !== undefined && prototype[key] !== null) {
        object[key] = prototype[key]; //just copy
      }
    }
  }
};

OOP.inherit = function (child, parent) {
  // do not use setter, getter
  Object.keys(parent).forEach(function (key) {
    if (key !== 'constructor' && typeof parent[key] == 'function') {
      var superMethod = parent[key];
      var currentMethod = child[key];
      if (!currentMethod) child[key] = superMethod;else {
        child[key] = function () {
          var _super = this.super;
          this.super = superMethod;
          var result = currentMethod.apply(this, arguments);
          this.super = _super;
          return result;
        };
      }
    }
  });
};

OOP.drillProperty = function (topObject, botObject, keyTop, keyBot) {
  if (typeof keyTop == 'string') {
    keyBot = keyBot || keyTop;
    Object.defineProperty(topObject, keyTop, {
      set: function set(value) {
        botObject[keyBot] = value;
      },
      get: function get() {
        return botObject[keyBot];
      }
    });
  } else {
    if (keyTop instanceof Array) {
      for (var i = 0; i < keyTop.length; ++i) {
        OOP.drillProperty(topObject, botObject, keyTop[i], keyTop[i]);
      }
    } else {
      for (var key in keyTop) {
        OOP.drillProperty(topObject, botObject, key, keyTop[key]);
      }
    }
  }
};

OOP.bindFunctions = function (_this, handlers) {
  var res = {};

  for (var key in handlers) {
    res[key] = handlers[key].bind(_this);
  }

  return res;
};

OOP.inheritCreator = function (parent, child) {
  var i;

  if (child.property) {
    if (parent.property) {
      for (i in parent.property) {
        if (!child.property[i]) child.property[i] = parent.property[i];
      }
    }
  }

  for (i in parent.prototype) {
    if (!child.prototype[i]) {
      child.prototype[i] = parent.prototype[i];
    } else {
      child.prototype[i] = function (superFunction, childFunction) {
        return function () {
          var _super = this.super;
          this.super = superFunction;
          var result = childFunction.apply(this, arguments);
          this.super = _super;
          return result;
        };
      }(parent.prototype[i], child.prototype[i]);
    }
  }
};
/***
 *
 * @param {Function} constructor
 */


OOP.mixClass = function (constructor) {
  var descriptors = {};

  for (var i = 1; i < arguments.length; ++i) {
    Object.assign(descriptors, Object.getOwnPropertyDescriptors(arguments[i].prototype));
  }

  delete descriptors.constructor;
  Object.defineProperties(constructor.prototype, descriptors);
};

/* harmony default export */ __webpack_exports__["a"] = (OOP);

/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return noop; });
function noop() {}
;

/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseStyleAttr", function() { return parseStyleAttr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseClassAttr", function() { return parseClassAttr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseMeasureValue", function() { return parseMeasureValue; });
/**
 * 
 * @param {String} text 
 *  @returns {Object}
 */
function parseStyleAttr(text) {
  return text.split(';').map(function (line) {
    var parts = line.split(':');
    if (parts.length < 2) return null;
    var key = parts.shift().trim();
    var value = parts.join(':').trim();
    if (key.length == 0 || value.length == 0) return null;
    return [key, value];
  }).filter(function (it) {
    return it != null;
  }).reduce(function (ac, cr) {
    ac[cr[0]] = cr[1];
    return ac;
  }, {});
}
/**
 * 
 * @param {String} text 
 *  @returns {Array<String>}
 */

function parseClassAttr(text) {
  return text.trim().split(/\s+/);
}
/**
 *
 * @param mValue
 * @returns {{unit: null, value: string}|{unit: string, value: number}|null}
 */

function parseMeasureValue(mValue) {
  if (mValue === 'auto') return {
    unit: null,
    value: 'auto'
  };
  if (mValue === 'match_parent') return {
    unit: null,
    value: 'match_parent'
  };
  var value = NaN;
  var unit = null;
  var matched;

  if (typeof mValue === "number") {
    value = mValue;
    unit = 'px';
  } else if (typeof mValue === "string") {
    matched = mValue.match(/([+-]?([0-9]*[.])?[0-9]+([eE][+-]?[0-9]+)?)(px|%|vw|vh)?/i);

    if (matched) {
      value = parseFloat(matched[1]);
      unit = matched[4];
    }
  }

  if (isNaN(value)) return null;
  unit = unit || 'px';
  return {
    value: value,
    unit: unit
  };
}

/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return safeThrow; });
function safeThrow(error) {
  setTimeout(function () {
    throw error;
  }, 0);
}

/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
function TemplateString(props) {
  this.parts = props.parts;
}

TemplateString.prototype.toJSCode = function () {
  return this.parts.map(function (e) {
    if (e.type == TemplateString.TYPE_EXPRESSION) {
      return '(' + e.data + ')';
    } else {
      return JSON.stringify(e.data);
    }
  }).join('+');
};

TemplateString.__partRegex = /(\{\{(([^\}]|(\}[^\}]))*)\}\})|(([^\{]|(\{[^\{]))+)/g;
/**
 *  @param  {String} text 
 */

TemplateString.__matchExpression = function (text) {
  if (text[0] == '{' && text[1] == '{' && text[text.length - 1] == '}' && text[text.length - 2] == '}') {
    return [text, text.substr(2, text.length - 4).trim()];
  } else {
    return false;
  }
};

TemplateString.TYPE_STRING = 0;
TemplateString.TYPE_EXPRESSION = 1;

TemplateString.parse = function (text) {
  text = text + '';
  var matchedParts = text.match(this.__partRegex);

  if (matchedParts) {
    var parts = matchedParts.map(function (e) {
      var matchedExp = this.__matchExpression(e);

      if (matchedExp) {
        return {
          type: this.TYPE_EXPRESSION,
          data: matchedExp[1]
        };
      } else {
        return {
          type: this.TYPE_STRING,
          data: e
        };
      }
    }.bind(this));
    return new TemplateString({
      parts: parts
    });
  } else {
    return new TemplateString({
      parts: []
    });
  }
};

/* harmony default export */ __webpack_exports__["a"] = (TemplateString);

/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* unused harmony export calcBenchmark */
/* harmony import */ var _BrowserRules__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var _BrowserRules__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_BrowserRules__WEBPACK_IMPORTED_MODULE_0__);

/**
 *
 * @param {BrowserRules} rulesheet
 */

function BrowserDetector(rulesheet) {
  this.au = global.navigator ? navigator.userAgent || '' : '';
  this.rulesheet = rulesheet;
  this.os = this.detectByRules(this.rulesheet.os);
  this.device = this.detectByRules(this.rulesheet.device);
  this.engine = this.detectByRules(this.rulesheet.engine);
  this.browser = this.detectByRules(this.rulesheet.browser);
  this.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  this.isCococ = navigator.userAgent.toLowerCase().indexOf('coc_coc_browser') >= 1;
  this.isSafari = !this.isCococ && navigator.userAgent.toLowerCase().indexOf('safari') > -1 && navigator.userAgent.toLowerCase().indexOf('win') < 0 && navigator.userAgent.toLowerCase().indexOf('android') < 0; // this.isSafari = /constructor/i.test(window.HTMLElement) || window.safari;

  this.isMobile = navigator.userAgent.indexOf('KFFOWI') > -1 || navigator.userAgent.toLowerCase().indexOf('mobile') > -1;
  this.isMacOSWebView = /Macintosh/.test(this.au) && /AppWebkit/.test(this.au) && !/Safari/.test(this.au);
  this.isChromeIOS = /CriOS\/[\d]+/.test(this.au);
  this.hasTouch = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch || navigator.maxTouchPoints > 0 || window.navigator.msMaxTouchPoints > 0;
  this.isTouchDevice = this.isMobile && this.hasTouch;

  this.supportPassiveEvent = function () {
    var supportsPassiveOption = false;

    try {
      var opts = Object.defineProperty({}, 'passive', {
        get: function get() {
          supportsPassiveOption = true;
        }
      });
      window.addEventListener('test', null, opts);
      window.removeEventListener('test', null, opts);
    } catch (e) {}

    return supportsPassiveOption;
  }();

  this.supportGridLayout = typeof document.createElement('div').style.grid === 'string';
  Object.defineProperty(this, 'zoom', {
    get: function get() {
      return this.getZoom();
    },
    enumerable: true,
    configurable: false
  });
}

BrowserDetector.prototype.detectByRules = function (rules) {
  var result = {};

  for (var i = 0; i < rules.length; ++i) {
    var rule = rules[i];
    var type = rule[0];
    var rgx = rule[1];

    if (typeof rgx == 'function') {
      rgx = rgx(this.au.toLowerCase());
    }

    if (Object.prototype.toString.call(rgx).indexOf('RegExp') >= 0) {
      var matched = this.au.toLowerCase().match(rgx);

      if (matched) {
        result.type = type;

        if (matched[1]) {
          result.version = matched[1];
        }

        break;
      }
    } else if (typeof rgx == 'string') {
      if (this.au.toLowerCase().indexOf(rgx) >= 0) {
        result.type = type;
      }
    }
  }

  return result;
};

BrowserDetector.prototype.getZoom = function () {
  //todo: wrong on chrome
  var type;

  if ('chrome' in window) {
    type = "chrome";
  } else if (this.isSafari) {
    type = 'safari';
  } else if ('orientation' in window && 'webkitRequestAnimationFrame' in window) {
    type = 'webkitMobile';
  } else if ('webkitRequestAnimationFrame' in window) {
    type = 'webkit';
  }

  switch (type) {
    case 'chrome':
      return Math.round(window.outerWidth / window.innerWidth * 100) / 100;

    case 'safari':
      return Math.round(document.documentElement.clientWidth / window.innerWidth * 100) / 100;

    case 'webkitMobile':
      return (Math.abs(window.orientation) == 90 ? screen.height : screen.width) / window.innerWidth;

    case 'webkit':
      return function () {
        var important = function important(str) {
          return str.replace(/;/g, " !important;");
        };

        var div = document.createElement('div');
        div.innerHTML = "1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0";
        div.setAttribute('style', important('font: 100px/1em sans-serif; -webkit-text-size-adjust: none; text-size-adjust: none; height: auto; width: 1em; padding: 0; overflow: visible;'));
        var container = document.createElement('div');
        container.setAttribute('style', important('width:0; height:0; overflow:hidden; visibility:hidden; position: absolute;'));
        container.appendChild(div);
        document.body.appendChild(container);
        var zoom = 1000 / div.clientHeight;
        zoom = Math.round(zoom * 100) / 100;
        document.body.removeChild(container);
        return zoom;
      }();

    default:
      return 1;
  }

  return 1;
};

function calcBenchmark() {
  var now = new Date().getTime();
  var i = 0;

  while (now === new Date().getTime()) {}

  now++;

  while (now === new Date().getTime()) {
    ++i;
  }

  return i;
}
BrowserDetector.prototype.calcBenchmark = calcBenchmark;
/* harmony default export */ __webpack_exports__["a"] = (new BrowserDetector(_BrowserRules__WEBPACK_IMPORTED_MODULE_0___default.a));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 9 */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export svgToRasterImageUrl */
/* unused harmony export svgToExportedString */
/* harmony import */ var _Dom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _ElementNS__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/* harmony import */ var _AElement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _Color_Color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14);
/* harmony import */ var _AttachHook__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(13);
/* harmony import */ var _OOP__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3);






/***
 * @extends Dom
 * @param option
 * @constructor
 */

function Svg(option) {
  _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].call(this, option);
  this.svgNS = "http://www.w3.org/2000/svg";
  Object.defineProperties(this.creator, {
    sattachhook: {
      set: function set() {//do nothing
      },
      get: function get() {
        return _AttachHook__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"];
      }
    }
  });
  delete this.buidDom;
  this.buildSvg = this.create.bind(this);
}

_OOP__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].mixClass(Svg, _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"]);
Svg.prototype.defaultTag = 'g';

Svg.prototype.fromCode = function (code) {
  code = code.trim();
  var receptacle = document.createElement('div');
  var element;
  var prototypes;

  if (code.startsWith('<svg')) {
    receptacle.innerHTML = code;
    element = receptacle.childNodes[0];
    prototypes = Object.getOwnPropertyDescriptors(_AElement__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].prototype);
    Object.defineProperties(element, prototypes);
    _AElement__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].call(element);
  } else {
    var svgfragment = '<svg  version="1.1" xmlns="http://www.w3.org/2000/svg">' + code + '</svg>';
    receptacle.innerHTML = '' + svgfragment;
    element = receptacle.childNodes[0].childNodes[0];
    prototypes = Object.getOwnPropertyDescriptors(_ElementNS__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].prototype);
    Object.defineProperties(element, prototypes);
    _ElementNS__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].call(element);
  }

  return element;
};

Svg.prototype.makeNewElement = function (tagName) {
  return document.createElementNS(this.svgNS, tagName);
};

Svg.ShareInstance = new Svg();

Svg.svgToCanvas = function (element) {
  if (typeof element == 'string') {
    element = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance.$(element);
  }

  if (element && element.tagName == 'svg') {
    var depthClone = function depthClone(originElt) {
      var newElt = originElt.cloneNode(); //no deep

      if (!originElt.getAttributeNS) return newElt; //is text node

      var style = getComputedStyle(originElt);
      var key, value;

      for (var i = 0; i < style.length; ++i) {
        key = style[i];
        value = style.getPropertyValue(key);

        if (value && value.length > 0 && value !== 'auto') {
          newElt.style.setProperty(key, value);
        }
      }

      var children = Array.prototype.map.call(originElt.childNodes, depthClone);

      for (var i = 0; i < children.length; ++i) {
        newElt.appendChild(children[i]);
      }

      return newElt;
    };

    var cloneElement = depthClone(element);

    var renderSpace = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance._({
      style: {
        // opacity:0,
        zIndex: -1000,
        position: 'fixed',
        top: 0,
        bottom: 0
      }
    }).addTo(document.body);

    renderSpace.addChild(cloneElement);
    var svgCode = renderSpace.innerHTML;
    renderSpace.clearChild();
    var mBlob = new Blob([svgCode], {
      type: "image/svg+xml;charset=utf-8"
    });
    var src = (URL || webkitURL).createObjectURL(mBlob);

    var image = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance._('img');

    image.attr('src', src).addTo(renderSpace);
    var canvas = document.createElement("canvas");
    renderSpace.addChild(canvas);
    return _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].waitImageLoaded(image).then(function () {
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext("2d");
      context.drawImage(image, 0, 0);
      renderSpace.selfRemove();
      return canvas;
    });
  } else {
    throw new Error('Element must be svg');
  }
};

function svgToRasterImageUrl(element) {
  return Svg.svgToCanvas(element).then(function (canvas) {
    return canvas.toDataURL();
  });
}
Svg.svgToRasterImageUrl = svgToRasterImageUrl;
function svgToExportedString(element) {
  if (typeof element == 'string') {
    element = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance.$(element);
  }

  if (element && element.tagName == 'svg') {
    var depthClone = function depthClone(originElt) {
      var newElt = originElt.cloneNode(); //no deep

      if (!originElt.getAttributeNS) return newElt; //is text node

      var cssRules = _AElement__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].prototype.getCSSRules.call(originElt);
      var cssKey = cssRules.reduce(function (ac, rule) {
        for (var i = 0; i < rule.style.length; ++i) {
          ac[rule.style[i]] = true;
        }

        return ac;
      }, {});

      for (var key in cssKey) {
        newElt.style[key] = _AElement__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].prototype.getComputedStyleValue.call(originElt, key);
      }

      var children = Array.prototype.map.call(originElt.childNodes, depthClone);

      for (var i = 0; i < children.length; ++i) {
        newElt.appendChild(children[i]);
      }

      return newElt;
    };

    var cloneElement = depthClone(element);

    var renderSpace = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance._({
      style: {
        // opacity:0,
        zIndex: -1000,
        position: 'fixed',
        top: 0,
        bottom: 0
      }
    }).addTo(document.body);

    renderSpace.addChild(cloneElement);
    var svgCode = renderSpace.innerHTML;
    renderSpace.selfRemove();
    return svgCode;
  } else {
    throw new Error('Element must be svg');
  }
}
;
Svg.svgToExportedString = svgToExportedString;

function svgToSvgUrl(element) {
  var svg = svgToExportedString(element);
  svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' + svg;
  var blob = new Blob([svg], {
    type: 'image/svg+xml'
  });
  var url = URL.createObjectURL(blob);
  return url;
}

Svg.svgToSvgUrl = svgToSvgUrl;
/***
 *
 * @param {AElement|String | {computeStyle?: boolean, elt: AElement, keepBackgroundColor?:boolean,convertSVG?:boolean}} option
 * @return {Promise<unknown>}
 */

_Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].printElement = function (option) {
  var _ = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance._;
  var $ = _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance.$;
  option = option || {};

  if (typeof option == 'string') {
    option = {
      elt: _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].ShareInstance.$(option)
    };
  } else if (typeof option.elt == 'string') {
    option.elt = $(option.elt);
  } else if (_Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].isDomNode(option)) {
    option = {
      elt: option
    };
  }

  option = Object.assign({
    keepBackgroundColor: true,
    convertSVG: false,
    computeStyle: false
  }, option);

  if (_Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].isDomNode(option.elt)) {
    var afterCloneCb = function afterCloneCb(originElt, newElt) {
      if (!newElt.tagName) return;
      var tagName = newElt.tagName.toLowerCase();
      if (newElt.getBBox && tagName !== 'svg') return;
      var url, img;
      var needCopyStyle = option.computeStyle;
      var needKeepBackgroundColor = option.keepBackgroundColor;

      if (tagName === 'canvas' || tagName === 'svg' && option.convertSVG) {
        if (tagName === "canvas") {
          url = originElt.toDataURL();
        } else {
          url = svgToSvgUrl(originElt);
        }

        img = _({
          tag: 'img',
          props: {
            src: url
          }
        });
        $(newElt).selfReplace(img);
        newElt = img;
        needCopyStyle = true;
      } else if (tagName === 'script') {
        newElt.remove();
      } else if (tagName === 'img') {
        newElt.setAttribute('src', originElt.src);
      } else if (tagName === 'input') {
        if (originElt.getAttribute('type') === 'radio' || originElt.getAttribute('type') === 'checkbox') {
          if (originElt.checked) {
            newElt.setAttribute('checked', true);
          }
        } else if (originElt.getAttribute('type') === 'text' || !originElt.getAttribute('type') || originElt.getAttribute('type') === 'number') {
          newElt.setAttribute('value', originElt.value);
        }
      }

      if (needCopyStyle) {
        Object(_Dom__WEBPACK_IMPORTED_MODULE_0__[/* copyStyleRule */ "a"])(originElt, newElt);
      }

      if (needKeepBackgroundColor) {
        try {
          var bgColor = _AElement__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].prototype.getComputedStyleValue.call(originElt, 'background-color');

          if (bgColor) {
            bgColor = _Color_Color__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].parse(bgColor);

            if (bgColor.rgba[3] > 0) {
              newElt.style.setProperty('background-color', bgColor.toString('hex8'), 'important');
            }
          }
        } catch (e) {}
      }

      return newElt;
    };

    var newElt = Object(_Dom__WEBPACK_IMPORTED_MODULE_0__[/* depthClone */ "c"])(option.elt, afterCloneCb);

    var renderSpace = _({
      style: {
        position: 'fixed',
        top: '0',
        left: '0',
        right: '0',
        bottom: '0',
        overflow: 'auto',
        zIndex: '10',
        opacity: '0',
        visibility: 'hidden'
      }
    });

    $('link', document.head, function (elt) {
      var temp = elt.cloneNode(false); //copy absolute url

      temp.setAttribute('href', elt.href);
      renderSpace.addChild(temp);
    });

    if (!option.computeStyle) {
      $('style', document.head, function (elt) {
        if (elt == _Dom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"].$printStyle) return;
        renderSpace.addChild(elt.cloneNode(true));
      });
    }

    renderSpace.addChild(newElt);
    var eltCode = renderSpace.innerHTML;
    renderSpace.clearChild();
    option.title = option.title || ($('title', document.head) || {
      innerHTML: 'absol.js'
    }).innerHTML;
    var htmlCode = ['<ht' + 'ml>', ' <h' + 'ead><title>' + option.title + '</title><meta charset="UTF-8">', '<style>', option.overideStyle ? 'html, body{width:initial !important; height:initial !important; overflow: initial !important; overflow-x: initial !important;overflow-y: initial !important;  }' : '', '@media print {', //still not work
    '    body{', '      -webkit-print-color-adjust: exact;', '       color-adjust: exact;', '    } ', '    div, tr, td, table{', '    }', '  }', 'div, table, tr, td{', '    page-break-inside: initial;', '    page-break-before: avoid;', '    page-break-after: avoid;', '}', option.extendCss || '', '</style>', '</he' + 'ad>', '<bod' + 'y>', eltCode, '<scr' + 'ipt>' + (option.extendScript || '') + '</scri' + 'pt>', //browser parse  script tag fail
    '<scr' + 'ipt>setTimeout(function(){ window.print();},1000);</scri' + 'pt>', //browser parse  script tag fail
    '</bod' + 'y>', '</ht' + 'ml>'].join('\n');
    var blob = new Blob([htmlCode], {
      type: 'text/html; charset=UTF-8'
    });
    renderSpace.addTo(document.body);

    var iframe = _('iframe').attr('src', URL.createObjectURL(blob)).addStyle({
      width: '100%',
      height: '100%'
    }).addTo(renderSpace);

    return new Promise(function (rs, rj) {
      function waitLoad() {
        if (iframe.contentWindow && iframe.contentWindow.document && iframe.contentWindow.document.body) {
          if (typeof option.onLoad == 'function') option.onLoad();
          iframe.contentWindow.focus();
          setTimeout(function () {
            function waitFocusBack() {
              if (!document.hasFocus || document.hasFocus()) {
                renderSpace.remove();
                if (typeof option.onFinish == 'function') option.onFinish();
                rs();
              } else {
                setTimeout(waitFocusBack, 300);
              }
            }

            waitFocusBack();
          }, 4000);
        } else setTimeout(waitLoad, 1000);
      }

      waitLoad();
    });
  } else {
    throw new Error('Invalid param!');
  }
};

/* harmony default export */ __webpack_exports__["a"] = (Svg);

/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _AElement__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _OOP__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);


/***
 * @augments AElement
 * @augments SVGGraphicsElement
 * @constructor
 */

function AElementNS() {
  _AElement__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].call(this);
}

_AElement__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].prototype.afterAttached = function () {
  if (this.isDescendantOf(document.body)) return Promise.resolve();
  var attachHookElt = this.$attachhook || this.querySelector('.absol-attachhook');

  if (!attachHookElt) {
    var constructor;

    if (this.tagName.toLowerCase() === 'svg' || this.getBBox) {
      attachHookElt = document.createElementNS('http://www.w3.org/2000/svg', 'image');
      attachHookElt.setAttributeNS(null, 'href', '');
      constructor = AElementNS;
    } else {
      attachHookElt = document.createElement('img');
      attachHookElt.src = '';
      constructor = AElementNS;
    }

    attachHookElt.classList.add('absol-attachhook');
    Object.assign(attachHookElt, constructor.prototype);
    constructor.call(attachHookElt);
    attachHookElt.defineEvent('attached');
    this.$attachhook = attachHookElt;
    this.$attachhook.on('error', function (event) {
      if (this.isDescendantOf(document.body)) this.emit('attached', event, this);
    });
    this.appendChild(attachHookElt);
  }

  return new Promise(function (rs) {
    attachHookElt.once('attached', rs);
  });
};

_OOP__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].mixClass(AElementNS, _AElement__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]);

AElementNS.prototype.attr = function () {
  if (arguments.length == 1) {
    if (typeof arguments[0] == 'string') {
      if (this._azar_extendAttributes[arguments[0]]) {
        return this._azar_extendAttributes[arguments[0]].get.call(this);
      } else return this.getAttributeNS(null, arguments[0]);
    } else {
      for (var key in arguments[0]) {
        this.attr(key, arguments[0][key]);
      }
    }
  } else {
    if (arguments.length == 2) {
      if (arguments[1] === null || arguments[1] === undefined) {
        if (this._azar_extendAttributes[arguments[0]]) {
          this._azar_extendAttributes[arguments[0]].remove.call(this, arguments[1]);
        } else this.removeAttributeNS(null, arguments[0]);
      } else {
        if (this._azar_extendAttributes[arguments[0]]) {
          this._azar_extendAttributes[arguments[0]].set.call(this, arguments[1]);
        } else {
          this.setAttributeNS(null, arguments[0], arguments[1]);
        }
      }
    }
  }

  return this;
};

/* harmony default export */ __webpack_exports__["a"] = (AElementNS);

/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _AElement__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _AElementNS__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);
/* harmony import */ var _DomSignal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);



/**
 *
 * @constructor
 */

function ResizeSystem() {
  var _this = this;

  this.elts = [];
  this.cache = [];
  this.cacheOf = null;
  this.lastResizeTime = 0;
  window.addEventListener('resize', this.update.bind(this));
  this['goDown' + 'AndCache'] = this.goDownAndCache.bind(this);
  this['notify' + 'ToElt'] = this.notifyToElt.bind(this);
  setTimeout(function () {
    _this.domSignal = new _DomSignal__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"]();

    _this.domSignal.on('request_update_signal', _this.update.bind(_this));
  }, 1000);
}
/***
 *
 * @param {AElement | AElementNS} elt
 */


ResizeSystem.prototype.goDownAndCache = function (elt) {
  if (this.notifyToElt(elt)) this.cache.push(elt);

  if (elt.childNodes) {
    Array.prototype.forEach.call(elt.childNodes, this.goDownAndCache);
  }
};

ResizeSystem.prototype.notifyToElt = function (elt) {
  if (typeof elt.requestUpdateSize == 'function') {
    elt.requestUpdateSize();
    return true;
  } else if (typeof elt.updateSize == 'function') {
    elt.updateSize();
    return true;
  } else if (typeof elt.onresize == 'function') {
    elt.onresize();
    return true;
  }
};

ResizeSystem.prototype.update = function () {
  var now = new Date().getTime();

  if (now - 100 > this.lastResizeTime) {
    this.removeTrash();
    this.cache = undefined;
  }

  this.lastResizeTime = now;

  if (this.cacheOf !== null) {
    this.cache = undefined;
    this.cacheOf = null;
  }

  if (this.cache === undefined) {
    this.cache = [];
    this.elts.forEach(this.goDownAndCache);
  } else {
    this.cache.forEach(this.notifyToElt);
  }
};

ResizeSystem.prototype.requestUpdateSignal = function () {
  if (!this.domSignal) return;
  this.domSignal.emit('request_update_signal');
};

ResizeSystem.prototype.removeTrash = function () {
  this.elts = this.elts.filter(function (element) {
    return _AElement__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].prototype.isDescendantOf.call(element, document.body);
  });
};
/***
 *
 * @param  {AElement| AElementNS | Node} fromElt
 * @returns {boolean}
 */


ResizeSystem.prototype.updateUp = function (fromElt) {
  while (fromElt) {
    if (typeof fromElt.requestUpdateSize == 'function') {
      fromElt.requestUpdateSize();
      return true;
    } else if (typeof fromElt.updateSize == 'function') {
      fromElt.updateSize();
      return true;
    } else if (typeof fromElt.onresize == 'function') {
      fromElt.onresize();
      return true;
    }

    fromElt = fromElt.parentElement;
  }
};
/***
 *
 * @param  {AElement| AElementNS | Node} fromElt
 * @returns {boolean}
 */


ResizeSystem.prototype.updateDown = function (fromElt) {
  var now = new Date().getTime();

  if (now - 100 > this.lastResizeTime) {
    this.cache = undefined;
  }

  this.lastResizeTime = now;

  if (this.cacheOf !== fromElt) {
    this.cache = undefined;
    this.cacheOf = fromElt;
  }

  if (this.cache === undefined) {
    this.cache = [];
    this.goDownAndCache(fromElt);
  } else {
    this.cache.forEach(this.notifyToElt);
  }
};
/***
 *
 * @param {AElement| AElementNS | Node} elt
 * @return {boolean}
 */


ResizeSystem.prototype.add = function (elt) {
  for (var i = 0; i < this.elts.length; ++i) {
    if (_AElement__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].prototype.isDescendantOf.call(elt, this.elts[i])) {
      return false;
    }
  }

  this.elts = this.elts.filter(function (e) {
    return !_AElement__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].prototype.isDescendantOf.call(e, elt);
  });
  this.elts.push(elt);
  return true;
};

/* harmony default export */ __webpack_exports__["a"] = (new ResizeSystem());

/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export AttachHook */
/***
 * @extends AElement
 * @constructor
 */
function AttachHook() {
  this.on('error', function (event) {
    if (!this._attached && this.isDescendantOf(document.body)) {
      this._attached = true;
      this.emit('attached', event, this);
    }
  });
}

AttachHook.render = function (data, domInstance) {
  var attributes = {};
  var tag;

  if (domInstance.defaultTag === 'div') {
    attributes.src = '';
    tag = 'img';
  } else {
    tag = 'image';
    attributes.href = '';
  }

  return domInstance._({
    tag: tag,
    class: 'absol-attachhook',
    extendEvent: ['attached'],
    style: {
      display: 'none'
    },
    attr: attributes,
    props: {
      domInstance: domInstance
    }
  });
};

AttachHook.prototype.resetState = function () {
  this._attached = false;

  if (this.tagName.toLowerCase() === 'img') {
    this.src = '';
  } else {
    this.href = '';
  }
};

AttachHook.property = {
  attached: {
    get: function get() {
      return !!this._attached;
    }
  }
};
/* harmony default export */ __webpack_exports__["a"] = (AttachHook);

/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _JSMaker_TemplateString__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);


function Color(rgba) {
  this.rgba = rgba.slice();
}
/***
 *
 * @returns {string}
 */


Color.prototype.toHex6 = function () {
  return this.rgba.slice(0, 3).map(function (b) {
    b = b * 255 >> 0;
    return (b < 16 ? '0' : '') + b.toString(16);
  }).join('');
};
/***
 *
 * @returns {string}
 */


Color.prototype.toHex8 = function () {
  return this.rgba.map(function (b) {
    b = b * 255 >> 0;
    return (b < 16 ? '0' : '') + b.toString(16);
  }).join('');
};
/***
 *
 * @returns {string}
 */


Color.prototype.toHex3 = function () {
  return this.rgba.slice(0, 3).map(function (b) {
    b = b * 255 / 17 >> 0;
    return b.toString(16);
  }).join('');
};
/***
 *
 * @returns {string}
 */


Color.prototype.toHex4 = function () {
  return this.rgba.map(function (b) {
    b = b * 255 / 17 >> 0;
    return b.toString(16);
  }).join('');
};
/***
 *
 * @returns {number[]}
 */


Color.prototype.toHSLA = function () {
  return Color.rgbaToHSLA(this.rgba);
};
/***
 *
 * @returns {number[]}
 */


Color.prototype.toHSBA = function () {
  return Color.rgbaToHSBA(this.rgba);
};
/***
 *
 * @returns {number[]}
 */


Color.prototype.toHWBA = function () {
  return Color.rgbaToHWBA(this.rgba);
};
/***
 *
 * @returns {number[]}
 */


Color.prototype.toCMYK = function () {
  return Color.rgbToCMYK(this.rgba);
};
/***
 *
 * @returns {Color}
 */


Color.prototype.getHighContrastColor = function () {
  var hsba = this.toHSBA();
  var h, s, b;
  h = hsba[0] > 0.5 ? hsba[0] - 0.5 : hsba[0] + 0.5;
  s = hsba[1] > 0.5 ? hsba[1] - 0.5 : hsba[1] + 0.5;
  b = hsba[2] > 0.5 ? hsba[2] - 0.5 : hsba[2] + 0.5;
  return Color.fromHSB(h, s, b);
};

Color.prototype.getHightContrastColor = Color.prototype.getHighContrastColor;

Color.prototype.getLuminance = function () {
  var a = this.rgba.slice(0, 3).map(function (v) {
    return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
  });
  return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
};
/***
 *
 * @param {Color} other
 * @returns {number}
 */


Color.prototype.getContrastWith = function (other) {
  var lum1 = this.getLuminance();
  var lum2 = other.getLuminance();
  var brightest = Math.max(lum1, lum2);
  var darkest = Math.min(lum1, lum2);
  return (brightest + 0.05) / (darkest + 0.05);
};
/***
 *
 * @returns {Color}
 */


Color.prototype.getContrastYIQ = function () {
  var r = this.rgba[0] * 255;
  var g = this.rgba[1] * 255;
  var b = this.rgba[2] * 255;
  var yiq = (r * 299 + g * 587 + b * 114) / 1000;
  return yiq >= 128 ? new Color([0, 0, 0, 1]) : new Color([1, 1, 1, 1]);
};
/**
 *
 * @returns {Color}
 */


Color.prototype.clone = function () {
  return new Color(this.rgba.slice());
};
/**
 *
 *  ['rgba', 'rgba', 'rgba({{x[0]*255>>0}}, {{x[1]*255>>0}}, {{x[2]*255>>0}}, {{x[3]}})'],
 *     ['rgb', 'rgba', 'rgb({{x[0]*255>>0}}, {{x[1]*255>>0}}, {{x[2]*255>>0}})'],
 *     ['hsl', 'toHSLA()', 'hsl({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%)'],
 *     ['hsla', 'toHSLA()', 'hsla({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%, {{x[3]}})'],
 *     ['hsb', 'toHSBA()', 'hsb({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%)'],
 *     ['hsba', 'toHSBA()', 'hsba({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%, {{x[3]}})'],
 *     ['hex3', 'toHex3()', '#{{x}}'],
 *     ['hex4', 'toHex4()', '#{{x}}'],
 *     ['hex6', 'toHex6()', '#{{x}}'],
 *     ['hex6', 'toHex8()', '#{{x}}'],
 *     ['hwb', 'toHWBA()', 'hwb({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%)'],
 *     ['hwba', 'toHWBA()', 'hwba({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%, {{x[3]}})']
 *     ['cmyk', 'toCMYK()', 'hwba({{x[0] * 100%}}, {{x[1] * 100}}%, {{x[2] * 100}}%)']
 */

/****
 *
 * @param {"rgba"|"rgb"|"hsl"|"hsla"|"hsb"|"hsba"|"hex3"|"hex4"|"hex6"|"hex6"|hex8|"hwb"|"hwba"} mode
 * @returns {string}
 */


Color.prototype.toString = function (mode) {
  mode = mode || 'rgba';
  mode = mode.toLocaleLowerCase();
  return Color.templates[mode](this);
};
/***
 *
 * @param notStandard
 * @param {number[]} hsbWeight
 * @returns {Color}
 */


Color.prototype.nearestNamedColor = function (notStandard, hsbWeight) {
  hsbWeight = hsbWeight || [5, 3, 1];
  var hsba = this.toHSBA();
  var bestMatch = null;
  var dist = 1000;
  Object.keys(Color.namedColors).concat(notStandard ? Object.keys(Color.nonStandarNamedColors) : []).forEach(function (name) {
    var c = Color.parse(Color.namedColors[name] || Color.nonStandarNamedColors[name]);
    var cHSBA = c.toHSBA();
    var cDist = Math.abs(hsba[0] - cHSBA[0]) * hsbWeight[0] + Math.abs(hsba[1] - cHSBA[1]) * hsbWeight[1] + Math.abs(hsba[2] - cHSBA[2]) * hsbWeight[2];

    if (cDist < dist) {
      dist = cDist;
      bestMatch = name;
    }
  });
  return bestMatch;
};

Color.templates = [['rgba', 'rgba', 'rgba({{x[0]*255>>0}}, {{x[1]*255>>0}}, {{x[2]*255>>0}}, {{x[3]}})'], ['rgb', 'rgba', 'rgb({{x[0]*255>>0}}, {{x[1]*255>>0}}, {{x[2]*255>>0}})'], ['hsl', 'toHSLA()', 'hsl({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%)'], ['hsla', 'toHSLA()', 'hsla({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%, {{x[3]}})'], ['hsb', 'toHSBA()', 'hsb({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%)'], ['hsba', 'toHSBA()', 'hsba({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%, {{x[3]}})'], ['hex3', 'toHex3()', '#{{x}}'], ['hex4', 'toHex4()', '#{{x}}'], ['hex6', 'toHex6()', '#{{x}}'], ['hex8', 'toHex8()', '#{{x}}'], ['hwb', 'toHWBA()', 'hwb({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%)'], ['hwba', 'toHWBA()', 'hwba({{x[0] * 360}}, {{x[1] * 100}}%, {{x[2] * 100}}%, {{x[3]}})'], ['cmyk', 'toCMYK()', 'cmyk({{x[0] * 100}}%, {{x[1] * 100}}%, {{x[2] * 100}}%)']].reduce(function (ac, cr) {
  ac[cr[0]] = new Function('color', ['var x = color.' + cr[1] + ';', 'return ' + _JSMaker_TemplateString__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].parse(cr[2]).toJSCode() + ';'].join('\n'));
  return ac;
}, {});
Color.regexes = {
  whiteSpace: /\s*/,
  // Match zero or more whitespace characters.
  integer: /(\d{1,3})/,
  // Match integers: 79, 255, etc.
  decimal: /((?:\d+(?:\.\d+)?)|(?:\.\d+))/,
  // Match 129.6, 79, .9, etc.
  percent: /((?:\d+(?:\.\d+)?)|(?:\.\d+))%/,
  // Match 12.9%, 79%, .9%, etc.
  hex3: /^#([a-f0-9])([a-f0-9])([a-f0-9])$/i,
  // Match colors in format #XXXX, e.g. #5123.
  hex4: /^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i,
  // Match colors in format #XXXXXX, e.g. #b4d455.
  hex6: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,
  // Match colors in format #XXXXXXXX, e.g. #b4d45535.
  hex8: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i
};
Color.regexes.percent = new RegExp(Color.regexes.decimal.source + '%');
Color.regexes.rgb = new RegExp(['^rgb\\(', Color.regexes.integer.source, ',', Color.regexes.integer.source, ',', Color.regexes.integer.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i');
Color.regexes.rgbPercent = new RegExp(['^rgb\\(', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format rgb(R, G, B, A), e.g. rgb(255, 0, 128, 0.25).

Color.regexes.rgba = new RegExp(['^rgba\\(', Color.regexes.integer.source, ',', Color.regexes.integer.source, ',', Color.regexes.integer.source, ',', Color.regexes.decimal.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format rgb(R%, G%, B%, A), e.g. rgb(100%, 0%, 28.9%, 0.5).

Color.regexes.rgbaPercent = new RegExp(['^rgba\\(', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.decimal.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format hsla(H, S%, L%), e.g. hsl(100, 40%, 28.9%).

Color.regexes.hsl = new RegExp(['^hsl\\(', Color.regexes.integer.source, '[deg]*', ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format hsla(H, S%, L%, A), e.g. hsla(100, 40%, 28.9%, 0.5).

Color.regexes.hsla = new RegExp(['^hsla\\(', Color.regexes.integer.source, '[deg]*', ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.decimal.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format hsb(H, S%, B%), e.g. hsb(100, 40%, 28.9%).

Color.regexes.hsb = new RegExp(['^hsb\\(', Color.regexes.integer.source, '[deg]*', ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format hsba(H, S%, B%, A), e.g. hsba(100, 40%, 28.9%, 0.5).

Color.regexes.hsba = new RegExp(['^hsba\\(', Color.regexes.integer.source, '[deg]*', ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.decimal.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i');
Color.regexes.hwb = new RegExp(['^hwb\\(', Color.regexes.integer.source, '[deg]*', ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i'); // Match colors in format hsba(H, S%, B%, A), e.g. hsba(100, 40%, 28.9%, 0.5).

Color.regexes.hwba = new RegExp(['^hwba\\(', Color.regexes.integer.source, '[deg]*', ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.decimal.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i');
Color.regexes.cmyk = new RegExp(['^cmyk\\(', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, ',', Color.regexes.percent.source, '\\)$'].join(Color.regexes.whiteSpace.source), 'i');
/***
 *
 * @param {number} code
 * @param {32|24|16|8} bits
 * @returns {Color}
 */

Color.fromInt = function (code, bits) {
  var r, g, b, a;

  if (bits == 32) {
    b = (code & 0xff) / 255;
    g = ((code & 0xff00) >> 8) / 255;
    r = ((code & 0xff0000) >> 16) / 255;
    a = (code >> 24) / 255;
  } else if (bits == 24) {
    b = (code & 0xff) / 255;
    g = ((code & 0xff00) >> 8) / 255;
    r = ((code & 0xff0000) >> 16) / 255;
    a = 1;
  } else if (bits == 16) {
    b = (code & 0x1f) / 0x1f;
    g = ((code & 0x7e0) >> 5) / 0x3f;
    b = (code >> 10) / 0x1f;
    a = 1;
  } else if (bits == 8) {
    //gray-scale
    b = (code & 0x3) / 0x3;
    g = ((code & 0x1c) >> 2) / 0x7;
    b = (code >> 5) / 0x7;
    a = 1;
  }

  return new Color([r, g, b, a]);
};
/**
 *
 * @param {number} r
 * @param {number} g
 * @param {number} b
 * @returns {Color}
 */


Color.fromRGB = function (r, g, b) {
  return new Color([r, g, b, 1]);
};
/**
 *
 * @param {number} r
 * @param {number} g
 * @param {number} b
 * @param {number} a
 * @returns {Color}
 */


Color.fromRGBA = function (r, g, b, a) {
  return new Color([r, g, b, a]);
};
/***
 *
 * @param {number} h
 * @param {number} s
 * @param {number} l
 * @returns {Color}
 */


Color.fromHSL = function (h, s, l) {
  var rgba = this.hslaToRGBA([h, s, l, 1]);
  return new Color(rgba);
};
/***
 *
 * @param {number} h
 * @param {number} s
 * @param {number} l
 * @param {number} a
 * @returns {Color}
 */


Color.fromHSLA = function (h, s, l, a) {
  var rgba = this.hslaToRGBA([h, s, l, a]);
  return new Color(rgba);
};
/***
 *
 * @param {number} h
 * @param {number} s
 * @param {number} b
 * @returns {Color}
 */


Color.fromHSB = function (h, s, b) {
  var rgba = this.hsbaToRGBA([h, s, b, 1]);
  return new Color(rgba);
};
/***
 *
 * @param {number} h
 * @param {number} s
 * @param {number} b
 * @param {number} a
 * @returns {Color}
 */


Color.fromHSBA = function (h, s, b, a) {
  var rgba = this.hsbaToRGBA([h, s, b, a]);
  return new Color(rgba);
};
/***
 *
 * @param {number} h
 * @param {number} s
 * @param {number} b
 * @returns {Color}
 */


Color.fromHWB = function (h, s, b) {
  var rgba = this.hwbaToRGBA([h, s, b, 1]);
  return new Color(rgba);
};
/***
 *
 * @param {number} h
 * @param {number} s
 * @param {number} b
 * @param {number} a
 * @returns {Color}
 */


Color.fromHWBA = function (h, s, b, a) {
  var rgba = this.hwbaToRGBA([h, s, b, a]);
  return new Color(rgba);
};

Color.fromCMYK = function (c, m, y, k) {
  var rgba = this.cmykToRGB([c, m, y, k]).concat([0]);
  return new Color(rgba);
};
/**
 * @param {String} text
 * @returns {Color}
 */


Color.parse = function (text) {
  if (this.namedColors[text]) text = this.namedColors[text];
  if (this.nonStandarNamedColors[text]) text = this.nonStandarNamedColors[text];

  if (this.regexes.hex8.test(text)) {
    return this.fromRGBA.apply(this, this.regexes.hex8.exec(text).slice(1).map(function (v) {
      return parseInt(v, 16) / 255;
    }));
  } else if (this.regexes.hex6.test(text)) {
    return this.fromRGB.apply(this, this.regexes.hex6.exec(text).slice(1).map(function (v) {
      return parseInt(v, 16) / 255;
    }));
  } else if (this.regexes.hex4.test(text)) {
    return this.fromRGBA.apply(this, this.regexes.hex4.exec(text).slice(1).map(function (v) {
      return parseInt(v + v, 16) / 255;
    }));
  } else if (this.regexes.hex3.test(text)) {
    return this.fromRGB.apply(this, this.regexes.hex3.exec(text).slice(1).map(function (v) {
      return parseInt(v + v, 16) / 255;
    }));
  } else if (this.regexes.rgba.test(text)) {
    return this.fromRGBA.apply(this, this.regexes.rgba.exec(text).slice(1).map(function (v, i) {
      return i < 3 ? parseFloat(v) / 255 : parseFloat(v);
    }));
  } else if (this.regexes.rgb.test(text)) {
    return this.fromRGB.apply(this, this.regexes.rgb.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / 255;
    }));
  } else if (this.regexes.rgbPercent.test(text)) {
    return this.fromRGB.apply(this, this.regexes.rgbPercent.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / 100;
    }));
  } else if (this.regexes.rgbaPercent.test(text)) {
    return this.fromRGBA.apply(this, this.regexes.rgbaPercent.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i < 3 ? 100 : 1);
    }));
  } else if (this.regexes.hsl.test(text)) {
    return this.fromHSL.apply(this, this.regexes.hsl.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i == 0 ? 360 : 100);
    }));
  } else if (this.regexes.hsla.test(text)) {
    return this.fromHSLA.apply(this, this.regexes.hsla.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i == 0 ? 360 : i < 3 ? 100 : 1);
    }));
  } else if (this.regexes.hsb.test(text)) {
    return this.fromHSB.apply(this, this.regexes.hsb.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i == 0 ? 360 : 100);
    }));
  } else if (this.regexes.hsba.test(text)) {
    return this.fromHSBA.apply(this, this.regexes.hsba.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i == 0 ? 360 : i < 3 ? 100 : 1);
    }));
  } else if (this.regexes.hwb.test(text)) {
    return this.fromHWB.apply(this, this.regexes.hwb.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i == 0 ? 360 : 100);
    }));
  } else if (this.regexes.hwba.test(text)) {
    return this.fromHWBA.apply(this, this.regexes.hwba.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / (i == 0 ? 360 : i < 3 ? 100 : 1);
    }));
  } else if (this.regexes.cmyk.test(text)) {
    return this.fromCMYK.apply(this, this.regexes.cmyk.exec(text).slice(1).map(function (v, i) {
      return parseFloat(v) / 100;
    }));
  } else {
    throw new Error("Fail to parse " + text);
  }
};
/***
 * @typedef {"aliceblue"|"antiquewhite"|"aqua"|"aquamarine"|"azure"|"beige"|"bisque"|"black"|"blanchedalmond"|"blue"|"blueviolet"|"brown"|"burlywood"|"cadetblue"|"chartreuse"|"chocolate"|"coral"|"cornflowerblue"|"cornsilk"|"crimson"|"cyan"|"darkblue"|"darkcyan"|"darkgoldenrod"|"darkgray"|"darkgreen"|"darkgrey"|"darkkhaki"|"darkmagenta"|"darkolivegreen"|"darkorange"|"darkorchid"|"darkred"|"darksalmon"|"darkseagreen"|"darkslateblue"|"darkslategray"|"darkslategrey"|"darkturquoise"|"darkviolet"|"deeppink"|"deepskyblue"|"dimgray"|"dimgrey"|"dodgerblue"|"firebrick"|"floralwhite"|"forestgreen"|"fuchsia"|"gainsboro"|"ghostwhite"|"gold"|"goldenrod"|"gray"|"green"|"greenyellow"|"grey"|"honeydew"|"hotpink"|"indianred"|"indigo"|"ivory"|"khaki"|"lavender"|"lavenderblush"|"lawngreen"|"lemonchiffon"|"lightblue"|"lightcoral"|"lightcyan"|"lightgoldenrodyellow"|"lightgray"|"lightgreen"|"lightgrey"|"lightpink"|"lightsalmon"|"lightseagreen"|"lightskyblue"|"lightslategray"|"lightslategrey"|"lightsteelblue"|"lightyellow"|"lime"|"limegreen"|"linen"|"magenta"|"maroon"|"mediumaquamarine"|"mediumblue"|"mediumorchid"|"mediumpurple"|"mediumseagreen"|"mediumslateblue"|"mediumspringgreen"|"mediumturquoise"|"mediumvioletred"|"midnightblue"|"mintcream"|"mistyrose"|"moccasin"|"navajowhite"|"navy"|"oldlace"|"olive"|"olivedrab"|"orange"|"orangered"|"orchid"|"palegoldenrod"|"palegreen"|"paleturquoise"|"palevioletred"|"papayawhip"|"peachpuff"|"peru"|"pink"|"plum"|"powderblue"|"purple"|"red"|"rosybrown"|"royalblue"|"saddlebrown"|"salmon"|"sandybrown"|"seagreen"|"seashell"|"sienna"|"silver"|"skyblue"|"slateblue"|"slategray"|"slategrey"|"snow"|"springgreen"|"steelblue"|"tan"|"teal"|"thistle"|"tomato"|"turquoise"|"violet"|"wheat"|"white"|"whitesmoke"|"yellow"|"yellowgreen"|"transparent"} NamedColor
 */


Color.namedColors = {
  aliceblue: '#f0f8ff',
  antiquewhite: '#faebd7',
  aqua: '#00ffff',
  aquamarine: '#7fffd4',
  azure: '#f0ffff',
  beige: '#f5f5dc',
  bisque: '#ffe4c4',
  black: '#000000',
  blanchedalmond: '#ffebcd',
  blue: '#0000ff',
  blueviolet: '#8a2be2',
  brown: '#a52a2a',
  burlywood: '#deb887',
  cadetblue: '#5f9ea0',
  chartreuse: '#7fff00',
  chocolate: '#d2691e',
  coral: '#ff7f50',
  cornflowerblue: '#6495ed',
  cornsilk: '#fff8dc',
  crimson: '#dc143c',
  cyan: '#00ffff',
  darkblue: '#00008b',
  darkcyan: '#008b8b',
  darkgoldenrod: '#b8860b',
  darkgray: '#a9a9a9',
  darkgreen: '#006400',
  darkgrey: '#a9a9a9',
  darkkhaki: '#bdb76b',
  darkmagenta: '#8b008b',
  darkolivegreen: '#556b2f',
  darkorange: '#ff8c00',
  darkorchid: '#9932cc',
  darkred: '#8b0000',
  darksalmon: '#e9967a',
  darkseagreen: '#8fbc8f',
  darkslateblue: '#483d8b',
  darkslategray: '#2f4f4f',
  darkslategrey: '#2f4f4f',
  darkturquoise: '#00ced1',
  darkviolet: '#9400d3',
  deeppink: '#ff1493',
  deepskyblue: '#00bfff',
  dimgray: '#696969',
  dimgrey: '#696969',
  dodgerblue: '#1e90ff',
  firebrick: '#b22222',
  floralwhite: '#fffaf0',
  forestgreen: '#228b22',
  fuchsia: '#ff00ff',
  gainsboro: '#dcdcdc',
  ghostwhite: '#f8f8ff',
  gold: '#ffd700',
  goldenrod: '#daa520',
  gray: '#808080',
  green: '#008000',
  greenyellow: '#adff2f',
  grey: '#808080',
  honeydew: '#f0fff0',
  hotpink: '#ff69b4',
  indianred: '#cd5c5c',
  indigo: '#4b0082',
  ivory: '#fffff0',
  khaki: '#f0e68c',
  lavender: '#e6e6fa',
  lavenderblush: '#fff0f5',
  lawngreen: '#7cfc00',
  lemonchiffon: '#fffacd',
  lightblue: '#add8e6',
  lightcoral: '#f08080',
  lightcyan: '#e0ffff',
  lightgoldenrodyellow: '#fafad2',
  lightgray: '#d3d3d3',
  lightgreen: '#90ee90',
  lightgrey: '#d3d3d3',
  lightpink: '#ffb6c1',
  lightsalmon: '#ffa07a',
  lightseagreen: '#20b2aa',
  lightskyblue: '#87cefa',
  lightslategray: '#778899',
  lightslategrey: '#778899',
  lightsteelblue: '#b0c4de',
  lightyellow: '#ffffe0',
  lime: '#00ff00',
  limegreen: '#32cd32',
  linen: '#faf0e6',
  magenta: '#ff00ff',
  maroon: '#800000',
  mediumaquamarine: '#66cdaa',
  mediumblue: '#0000cd',
  mediumorchid: '#ba55d3',
  mediumpurple: '#9370db',
  mediumseagreen: '#3cb371',
  mediumslateblue: '#7b68ee',
  mediumspringgreen: '#00fa9a',
  mediumturquoise: '#48d1cc',
  mediumvioletred: '#c71585',
  midnightblue: '#191970',
  mintcream: '#f5fffa',
  mistyrose: '#ffe4e1',
  moccasin: '#ffe4b5',
  navajowhite: '#ffdead',
  navy: '#000080',
  oldlace: '#fdf5e6',
  olive: '#808000',
  olivedrab: '#6b8e23',
  orange: '#ffa500',
  orangered: '#ff4500',
  orchid: '#da70d6',
  palegoldenrod: '#eee8aa',
  palegreen: '#98fb98',
  paleturquoise: '#afeeee',
  palevioletred: '#db7093',
  papayawhip: '#ffefd5',
  peachpuff: '#ffdab9',
  peru: '#cd853f',
  pink: '#ffc0cb',
  plum: '#dda0dd',
  powderblue: '#b0e0e6',
  purple: '#800080',
  red: '#ff0000',
  rosybrown: '#bc8f8f',
  royalblue: '#4169e1',
  saddlebrown: '#8b4513',
  salmon: '#fa8072',
  sandybrown: '#f4a460',
  seagreen: '#2e8b57',
  seashell: '#fff5ee',
  sienna: '#a0522d',
  silver: '#c0c0c0',
  skyblue: '#87ceeb',
  slateblue: '#6a5acd',
  slategray: '#708090',
  slategrey: '#708090',
  snow: '#fffafa',
  springgreen: '#00ff7f',
  steelblue: '#4682b4',
  tan: '#d2b48c',
  teal: '#008080',
  thistle: '#d8bfd8',
  tomato: '#ff6347',
  turquoise: '#40e0d0',
  violet: '#ee82ee',
  wheat: '#f5deb3',
  white: '#ffffff',
  whitesmoke: '#f5f5f5',
  yellow: '#ffff00',
  yellowgreen: '#9acd32',
  transparent: '#00000000'
};
Color.nonStandarNamedColors = {
  night: '#0C090A',
  gunmetal: '#2C3539',
  midnight: '#2B1B17',
  charcoal: '#34282C',
  oil: '#3B3131',
  blackcat: '#413839',
  iridium: '#3D3C3A',
  blackeel: '#463E3F',
  blackcow: '#4C4646',
  graywolf: '#504A4B',
  vampiregray: '#565051',
  graydolphin: '#5C5858',
  carbongray: '#625D5D',
  ashgray: '#666362',
  cloudygray: '#6D6968',
  smokeygray: '#726E6D',
  granite: '#837E7C',
  battleshipgray: '#848482',
  graycloud: '#B6B6B4',
  graygoose: '#D1D0CE',
  platinum: '#E5E4E2',
  metallicsilver: '#BCC6CC',
  bluegray: '#98AFC7',
  raven: '#657383',
  jetgray: '#616D7E',
  mistblue: '#646D7E',
  marbleblue: '#566D7E',
  shipcove: '#737CA1',
  mariner: '#4863A0',
  bluejay: '#2B547E',
  biscay: '#2B3856',
  navyblue: '#000080',
  bluewhale: '#342D7E',
  lapisblue: '#15317E',
  denimdarkblue: '#151B8D',
  earthblue: '#0000A0',
  cobaltblue: '#0020C2',
  blueberryblue: '#0041C2',
  sapphireblue: '#2554C7',
  blueeyes: '#1569C7',
  blueorchid: '#1F45FC',
  bluelotus: '#6960EC',
  lightslateblue: '#736AFF',
  windowsblue: '#357EC7',
  glacialblueice: '#368BC1',
  silkblue: '#488AC7',
  blueivy: '#3090C7',
  bluekoi: '#659EC7',
  columbiablue: '#87AFC7',
  babyblue: '#95B9C7',
  oceanblue: '#2B65EC',
  blueribbon: '#306EFF',
  bluedress: '#157DEC',
  butterflyblue: '#38ACEC',
  iceberg: '#56A5EC',
  crystalblue: '#5CB3FF',
  denimblue: '#79BAEC',
  dayskyblue: '#82CAFF',
  jeansblue: '#A0CFEC',
  blueangel: '#B7CEEC',
  pastelblue: '#B4CFEC',
  seablue: '#C2DFFF',
  coralblue: '#AFDCEC',
  robineggblue: '#BDEDFF',
  palebluelily: '#CFECEC',
  water: '#EBF4FA',
  lightslate: '#CCFFFF',
  lightaquamarine: '#93FFE8',
  electricblue: '#9AFEFF',
  cyanoraqua: '#00FFFF',
  tronblue: '#7DFDFE',
  bluezircon: '#57FEFF',
  bluelagoon: '#8EEBEC',
  celeste: '#50EBEC',
  bluediamond: '#4EE2EC',
  tiffanyblue: '#81D8D0',
  cyanopaque: '#92C7C7',
  bluehosta: '#77BFC7',
  northernlightsblue: '#78C7C7',
  jellyfish: '#46C7C7',
  bluegreen: '#7BCCB5',
  macawbluegreen: '#43BFC7',
  seaturtlegreen: '#438D80',
  greenishblue: '#307D7E',
  grayishturquoise: '#5E7D7E',
  beetlegreen: '#4C787E',
  camouflagegreen: '#78866B',
  sagegreen: '#848b79',
  hazelgreen: '#617C58',
  venomgreen: '#728C00',
  ferngreen: '#667C26',
  darkforestgreen: '#254117',
  mediumforestgreen: '#347235',
  seaweedgreen: '#437C17',
  pinegreen: '#387C44',
  junglegreen: '#347C2C',
  shamrockgreen: '#347C17',
  greenonion: '#6AA121',
  clovergreen: '#3EA055',
  greensnake: '#6CBB3C',
  aliengreen: '#6CC417',
  greenapple: '#4CC417',
  kellygreen: '#4CC552',
  zombiegreen: '#54C571',
  froggreen: '#99C68E',
  greenpeas: '#89C35C',
  dollarbillgreen: '#85BB65',
  iguanagreen: '#9CB071',
  avocadogreen: '#B2C248',
  pistachiogreen: '#9DC209',
  saladgreen: '#A1C935',
  hummingbirdgreen: '#7FE817',
  nebulagreen: '#59E817',
  stoplightgogreen: '#57E964',
  algaegreen: '#64E986',
  jadegreen: '#5EFB6E',
  emeraldgreen: '#5FFB17',
  dragongreen: '#6AFB92',
  mintgreen: '#98FF98',
  greenthumb: '#B5EAAA',
  lightjade: '#C3FDB8',
  teagreen: '#CCFB5D',
  slimegreen: '#BCE954',
  harvestgold: '#EDE275',
  sunyellow: '#FFE87C',
  cornyellow: '#FFF380',
  parchment: '#FFFFC2',
  cream: '#FFFFCC',
  blonde: '#FBF6D9',
  champagne: '#F7E7CE',
  vanilla: '#F3E5AB',
  tanbrown: '#ECE5B6',
  peach: '#FFE5B4',
  mustard: '#FFDB58',
  rubberduckyyellow: '#FFD801',
  brightgold: '#FDD017',
  goldenbrown: '#EAC117',
  macaroniandcheese: '#F2BB66',
  saffron: '#FBB917',
  beer: '#FBB117',
  cantaloupe: '#FFA62F',
  beeyellow: '#E9AB17',
  brownsugar: '#E2A76F',
  deeppeach: '#FFCBA4',
  gingerbrown: '#C9BE62',
  schoolbusyellow: '#E8A317',
  fallleafbrown: '#C8B560',
  orangegold: '#D4A017',
  sand: '#C2B280',
  cookiebrown: '#C7A317',
  caramel: '#C68E17',
  brass: '#B5A642',
  camelbrown: '#C19A6B',
  bronze: '#CD7F32',
  tigerorange: '#C88141',
  cinnamon: '#C58917',
  bulletshell: '#AF9B60',
  copper: '#B87333',
  wood: '#966F33',
  oakbrown: '#806517',
  armybrown: '#827B60',
  sandstone: '#786D5F',
  mocha: '#493D26',
  taupe: '#483C32',
  coffee: '#6F4E37',
  brownbear: '#835C3B',
  reddirt: '#7F5217',
  sepia: '#7F462C',
  orangesalmon: '#C47451',
  rust: '#C36241',
  redfox: '#C35817',
  sedona: '#CC6600',
  papayaorange: '#E56717',
  halloweenorange: '#E66C2C',
  pumpkinorange: '#F87217',
  constructionconeorange: '#F87431',
  sunriseorange: '#E67451',
  mangoorange: '#FF8040',
  basketballorange: '#F88158',
  tangerine: '#E78A61',
  beanred: '#F75D59',
  valentinered: '#E55451',
  shockingorange: '#E55B3C',
  scarlet: '#FF2400',
  rubyred: '#F62217',
  ferrarired: '#F70D1A',
  fireenginered: '#F62817',
  lavared: '#E42217',
  lovered: '#E41B17',
  grapefruit: '#DC381F',
  chestnutred: '#C34A2C',
  cherryred: '#C24641',
  mahogany: '#C04000',
  chillipepper: '#C11B17',
  cranberry: '#9F000F',
  redwine: '#990012',
  burgundy: '#8C001A',
  chestnut: '#954535',
  bloodred: '#7E3517',
  sangria: '#7E3817',
  plumpie: '#7D0541',
  velvetmaroon: '#7E354D',
  plumvelvet: '#7D0552',
  rosyfinch: '#7F4E52',
  puce: '#7F5A58',
  dullpurple: '#7F525D',
  khakirose: '#C5908E',
  pinkbow: '#C48189',
  lipstickpink: '#C48793',
  rose: '#E8ADAA',
  rosegold: '#ECC5C0',
  desertsand: '#EDC9AF',
  pigpink: '#FDD7E4',
  cottoncandy: '#FCDFFF',
  pinkbubblegum: '#FFDFDD',
  flamingopink: '#F9A7B0',
  pinkrose: '#E7A1B0',
  pinkdaisy: '#E799A3',
  cadillacpink: '#E38AAE',
  carnationpink: '#F778A1',
  blushred: '#E56E94',
  watermelonpink: '#FC6C85',
  violetred: '#F6358A',
  pinkcupcake: '#E45E9D',
  pinklemonade: '#E4287C',
  neonpink: '#F535AA',
  dimorphothecamagenta: '#E3319D',
  brightneonpink: '#F433FF',
  tulippink: '#C25A7C',
  roguepink: '#C12869',
  burntpink: '#C12267',
  bashfulpink: '#C25283',
  darkcarnationpink: '#C12283',
  violapurple: '#7E587E',
  purpleiris: '#571B7E',
  plumpurple: '#583759',
  purplemonster: '#461B7E',
  purplehaze: '#4E387E',
  eggplant: '#614051',
  grape: '#5E5A80',
  purplejam: '#6A287E',
  purpleflower: '#A74AC7',
  purpleamethyst: '#6C2DC7',
  purplesagebush: '#7A5DC7',
  lovelypurple: '#7F38EC',
  aztechpurple: '#893BFF',
  jasminepurple: '#A23BEC',
  purpledaffodil: '#B041FF',
  tyrianpurple: '#C45AEC',
  crocuspurple: '#9172EC',
  purplemimosa: '#9E7BFF',
  heliotropepurple: '#D462FF',
  purpledragon: '#C38EC7',
  lilac: '#C8A2C8',
  blushpink: '#E6A9EC',
  mauve: '#E0B0FF',
  wisteriapurple: '#C6AEC7',
  blossompink: '#F9B7FF',
  periwinkle: '#E9CFEC',
  lavenderpinocchio: '#EBDDE2',
  lavenderblue: '#E3E4FA',
  pearl: '#FDEEF4',
  milkwhite: '#FEFCFF'
};
/********************** COLOR CONVERTER *******************/

Color.rgbToHex = function (rgb) {
  return '#' + rgb.slice(0, 3).map(function (c) {
    var res = (c * 255 >> 0).toString(16);
    if (res < 10) res = '0' + res;
    return res.toUpperCase();
  }).join('');
};

Color.rgbaToHex = function (rgb) {
  return '#' + rgb.map(function (c) {
    var res = (c * 255 >> 0).toString(16);
    if (res < 10) res = '0' + res;
    return res.toUpperCase();
  }).join('');
};

Color.hsbaToText = function (hsba) {
  return 'hsba(' + (hsba[0] * 360 >> 0) + 'deg, ' + (hsba[1] * 100 >> 0) + '%, ' + (hsba[2] * 100 >> 0) + '%, ' + hsba[3].toFixed(3) + ')';
};

Color.hslaToText = function (hsla) {
  return 'hsla(' + (hsla[0] * 360 >> 0) + 'deg, ' + (hsla[1] * 100 >> 0) + '%, ' + (hsla[2] * 100 >> 0) + '%, ' + hsla[3].toFixed(3) + ')';
};

Color.rgbaToText = function (rgba) {
  return 'rgba(' + (rgba[0] * 255 >> 0) + ', ' + (rgba[1] * 255 >> 0) + ', ' + (rgba[2] * 255 >> 0) + ', ' + rgba[3].toFixed(3) + ')';
};

Color.hsbToText = function (hsba) {
  return 'hsb(' + (hsba[0] * 360 >> 0) + 'deg, ' + (hsba[1] * 100 >> 0) + '%, ' + (hsba[2] * 100 >> 0) + '%)';
};

Color.hslToText = function (hsl) {
  return 'hsl(' + (hsl[0] * 360 >> 0) + 'deg, ' + (hsl[1] * 100 >> 0) + '%, ' + (hsl[2] * 100 >> 0) + '%)';
};

Color.rgbToText = function (rgba) {
  return 'rgb(' + (rgba[0] * 255 >> 0) + ', ' + (rgba[1] * 255 >> 0) + ', ' + (rgba[2] * 255 >> 0) + ')';
};

Color.cmykToText = function (cmyk) {
  return 'cmyk(' + cmyk.map(function (x) {
    return x * 100 + '%';
  }).join(', ') + ')';
};

Color.hsbaToHSLA = function (hsba) {
  var hue = hsba[0];
  var sat = hsba[1];
  var val = hsba[2]; // Calculate lightness.

  var li = (2 - sat) * val / 2; // Convert saturation.

  if (li !== 0) {
    if (li === 1) {
      sat = 0;
    } else if (li < 0.5) {
      sat = sat / (2 - sat);
    } else {
      sat = sat * val / (2 - li * 2);
    }
  } // Hue and alpha stay the same.


  return [hue, sat, li, hsba[3]];
};

Color.hsbaToRGBA = function (hsba) {
  var hue = hsba[0] * 6; // We will split hue into 6 sectors.

  var sat = hsba[1];
  var val = hsba[2];
  var RGBA = [];

  if (sat === 0) {
    RGBA = [val, val, val, hsba[3]]; // Return early if grayscale.
  } else {
    var sector = Math.floor(hue);
    var tint1 = val * (1 - sat);
    var tint2 = val * (1 - sat * (hue - sector));
    var tint3 = val * (1 - sat * (1 + sector - hue));
    var red, green, blue;

    if (sector === 1) {
      // Yellow to green.
      red = tint2;
      green = val;
      blue = tint1;
    } else if (sector === 2) {
      // Green to cyan.
      red = tint1;
      green = val;
      blue = tint3;
    } else if (sector === 3) {
      // Cyan to blue.
      red = tint1;
      green = tint2;
      blue = val;
    } else if (sector === 4) {
      // Blue to magenta.
      red = tint3;
      green = tint1;
      blue = val;
    } else if (sector === 5) {
      // Magenta to red.
      red = val;
      green = tint1;
      blue = tint2;
    } else {
      // Red to yellow (sector could be 0 or 6).
      red = val;
      green = tint3;
      blue = tint1;
    }

    RGBA = [red, green, blue, hsba[3]];
  }

  return RGBA;
};

Color.hslaToHSBA = function (hsla) {
  var hue = hsla[0];
  var sat = hsla[1];
  var li = hsla[2]; // Calculate brightness.

  var val;

  if (li < 0.5) {
    val = (1 + sat) * li;
  } else {
    val = li + sat - li * sat;
  } // Convert saturation.


  sat = 2 * (val - li) / val; // Hue and alpha stay the same.

  return [hue, sat, val, hsla[3]];
};

Color.hslaToRGBA = function (hsla) {
  var hue = hsla[0] * 6; // We will split hue into 6 sectors.

  var sat = hsla[1];
  var li = hsla[2];
  var RGBA = [];

  if (sat === 0) {
    RGBA = [li, li, li, hsla[3]]; // Return early if grayscale.
  } else {
    // Calculate brightness.
    var val;

    if (li < 0.5) {
      val = (1 + sat) * li;
    } else {
      val = li + sat - li * sat;
    } // Define zest.


    var zest = 2 * li - val; // Implement projection (project onto green by default).

    var hzvToRGB = function hzvToRGB(hue, zest, val) {
      if (hue < 0) {
        // Hue must wrap to allow projection onto red and blue.
        hue += 6;
      } else if (hue >= 6) {
        hue -= 6;
      }

      if (hue < 1) {
        // Red to yellow (increasing green).
        return zest + (val - zest) * hue;
      } else if (hue < 3) {
        // Yellow to cyan (greatest green).
        return val;
      } else if (hue < 4) {
        // Cyan to blue (decreasing green).
        return zest + (val - zest) * (4 - hue);
      } else {
        // Blue to red (least green).
        return zest;
      }
    }; // Perform projections, offsetting hue as necessary.


    RGBA = [hzvToRGB(hue + 2, zest, val), hzvToRGB(hue, zest, val), hzvToRGB(hue - 2, zest, val), hsla[3]];
  }

  return RGBA;
};

Color.rgbaToHSBA = function (rgba) {
  var red = rgba[0];
  var green = rgba[1];
  var blue = rgba[2];
  var val = Math.max(red, green, blue);
  var chroma = val - Math.min(red, green, blue);
  var hue, sat;

  if (chroma === 0) {
    // Return early if grayscale.
    hue = 0;
    sat = 0;
  } else {
    sat = chroma / val;

    if (red === val) {
      // Magenta to yellow.
      hue = (green - blue) / chroma;
    } else if (green === val) {
      // Yellow to cyan.
      hue = 2 + (blue - red) / chroma;
    } else if (blue === val) {
      // Cyan to magenta.
      hue = 4 + (red - green) / chroma;
    }

    if (hue < 0) {
      // Confine hue to the interval [0, 1).
      hue += 6;
    } else if (hue >= 6) {
      hue -= 6;
    }
  }

  return [hue / 6, sat, val, rgba[3]];
};

Color.rgbaToHSLA = function (rgba) {
  var red = rgba[0];
  var green = rgba[1];
  var blue = rgba[2];
  var val = Math.max(red, green, blue);
  var min = Math.min(red, green, blue);
  var li = val + min; // We will halve this later.

  var chroma = val - min;
  var hue, sat;

  if (chroma === 0) {
    // Return early if grayscale.
    hue = 0;
    sat = 0;
  } else {
    if (li < 1) {
      sat = chroma / li;
    } else {
      sat = chroma / (2 - li);
    }

    if (red === val) {
      // Magenta to yellow.
      hue = (green - blue) / chroma;
    } else if (green === val) {
      // Yellow to cyan.
      hue = 2 + (blue - red) / chroma;
    } else if (blue === val) {
      // Cyan to magenta.
      hue = 4 + (red - green) / chroma;
    }

    if (hue < 0) {
      // Confine hue to the interval [0, 1).
      hue += 6;
    } else if (hue >= 6) {
      hue -= 6;
    }
  }

  return [hue / 6, sat, li / 2, rgba[3]];
};

Color.hwbaToHSBA = function (hwba) {
  return [hwba[0], 1 - hwba[1] / (1 - hwba[2]), 1 - hwba[2], hwba[3]];
};

Color.hsbaToHWBA = function (hsla) {
  return [hsla[0], (1 - hsla[1]) * hsla[2], 1 - hsla[2], hsla[3]];
};

Color.rgbaToHWBA = function (rgba) {
  return this.hsbaToHWBA(this.rgbaToHSBA(rgba));
};

Color.hwbaToRGBA = function (hwba) {
  return this.hsbaToRGBA(this.hwbaToHSBA(hwba));
};

Color.cmykToRGB = function (cmyk) {
  var c = cmyk[0];
  var m = cmyk[1];
  var y = cmyk[2];
  var k = cmyk[3];
  c = c * (1 - k) + k;
  m = m * (1 - k) + k;
  y = y * (1 - k) + k;
  var r = 1 - c;
  var g = 1 - m;
  var b = 1 - y;
  return [r, g, b];
};

Color.rgbToCMYK = function (rgb) {
  var r = rgb[0];
  var g = rgb[1];
  var b = rgb[2];
  var c = 1 - r;
  var m = 1 - g;
  var y = 1 - b;
  var k = Math.min(c, Math.min(m, y));
  c = (c - k) / (1 - k);
  m = (m - k) / (1 - k);
  y = (y - k) / (1 - k);
  c = isNaN(c) ? 0 : c;
  m = isNaN(m) ? 0 : m;
  y = isNaN(y) ? 0 : y;
  k = isNaN(k) ? 0 : k;
  return [c, m, y, k];
};

/* harmony default export */ __webpack_exports__["a"] = (Color);

/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _HTML5_EventEmitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _HTML5_OOP__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);


/***
 * @extends EventEmitter
 * @constructor
 */

function FlagManager() {
  _HTML5_EventEmitter__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].call(this);
  this.flag = {};
  this.readSetting();
}

_HTML5_OOP__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].mixClass(FlagManager, _HTML5_EventEmitter__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]);
FlagManager.prototype.STORE_KEY = "ABSOL_FLAG";

FlagManager.prototype.readSetting = function () {
  var flagText = localStorage.getItem(this.STORE_KEY) || '{}';
  var newFlag = {};

  try {
    newFlag = JSON.parse(flagText);
  } catch (err) {}

  this.applyFlag(newFlag);
};

FlagManager.prototype.applyFlag = function (newFlag, save) {
  var changed = [];
  Object.keys(Object.assign({}, this.flag, newFlag)).forEach(function (key) {
    if (key in window) {
      if (key in newFlag) {
        if (window[key] !== newFlag[key]) {
          window[key] = newFlag[key];
          changed.push(key);
        }
      } else {
        changed.push(key);
        delete window[key];
      }
    } else {
      if (key in newFlag) {
        if (window[key] !== newFlag[key]) {
          window[key] = newFlag[key];
          changed.push(key);
        }
      }
    }
  });
  this.flag = newFlag;
  if (save) this.saveSetting();

  if (changed.length > 0) {
    this.emit('change', {
      type: 'change',
      target: this,
      keys: changed
    });
  }
};

FlagManager.prototype.saveSetting = function () {
  localStorage.setItem(this.STORE_KEY, JSON.stringify(this.flag));
};
/***
 *
 * @param {string} key
 * @param {boolean=} value
 */


FlagManager.prototype.add = function (key, value) {
  if (!key || typeof key != 'string') return;
  if (key in this.flag) return;

  if (typeof value != "boolean") {
    value = !!window[key];
  }

  this.flag[key] = value;
  window[key] = value;
  this.saveSetting();
  this.emit('change', {
    type: 'change',
    target: this,
    keys: [key]
  });
};

FlagManager.prototype.set = function (key, value) {
  if (!key || typeof key != 'string') return;

  if (typeof value != "boolean") {
    value = !!window[key];
  }

  var changed = false;
  this.flag[key] = value;

  if (window[key] !== value) {
    changed = true;
  }

  this.saveSetting();

  if (changed) {
    this.emit('change', {
      type: 'change',
      target: this,
      keys: [key]
    });
  }
};

FlagManager.prototype.remove = function (key) {
  if (key in this.flag) {
    delete window[key];
    delete this.flag[key];
    this.emit('change', {
      type: 'change',
      target: this,
      keys: [key]
    });
  }
};

/* harmony default export */ __webpack_exports__["a"] = (new FlagManager());

/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _AElementNS__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11);

/* harmony default export */ __webpack_exports__["a"] = (_AElementNS__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]);

/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
function JSPath(props) {
  this.path = props.path;
}
/**
 *
 * @param {Element} element
 * @returns {Boolean}
 */


JSPath.prototype.match = function (element, query) {
  if (query.id) {
    if (!element.getAttribute || element.getAttribute('id') != query.id) return false;
  }

  if (query.tagName) {
    var matchTag = false;
    if (element._azar_extendTags && element._azar_extendTags[query.tagName]) matchTag = true;
    matchTag = matchTag || (element.tagName || '').toUpperCase() == query.tagName.toUpperCase();
    if (!matchTag) return false;
  }

  if (query.classList) for (var i = 0; i < query.classList.length; ++i) {
    if (!element.classList || !element.classList.contains(query.classList[i])) return false;
  }

  if (query.attributes) {
    for (var key in query.attributes) {
      var value;

      if (element.attr) {
        value = element.attr(key);
        if (value != query.attributes[key]) return false;
      } else if (element.getAttribute) {
        value = element.getAttribute(key);
        if (value != query.attributes[key]) return false;
      }
    }
  }

  return true;
};
/**
 * Warning : still fail in some testcase
 */


JSPath.prototype.findFirst = function (root, onFound) {
  var queue = [{
    e: root,
    i: 0
  }];
  var current;

  while (queue.length > 0) {
    current = queue.shift();
    var isMathed = false;
    var currentElt = current.e;
    var currentI = current.i;

    if (this.match(currentElt, this.path[currentI])) {
      if (this.path[currentI].childCombinate) {
        var trackI = currentI;
        var trackElement = currentElt;
        var isTrackMatch = true;

        while (isTrackMatch && trackI > 0 && this.path[trackI].childCombinate) {
          if (!trackElement.parentNode || !this.match(trackElement.parentNode, this.path[trackI - 1])) {
            isTrackMatch = false;
          } else {
            trackElement = trackElement.parentNode;
            trackI--;
          }
        }

        if (isTrackMatch) isMathed = true;
      } else {
        isMathed = true;
      }
    }

    if (isMathed && currentI + 1 == this.path.length) {
      if (!onFound || onFound && onFound(currentElt)) return currentElt;
    }

    if (currentElt.childNodes) {
      var l = currentElt.childNodes.length;

      for (var i = 0; i < l; ++i) {
        if (currentElt.childNodes[i].tagName) queue.push({
          e: currentElt.childNodes[i],
          i: currentI + (isMathed && currentI + 1 < this.path.length ? 1 : 0)
        });
      }
    }
  }

  return undefined;
};

JSPath.prototype.findAll = function (root, onFound) {
  var res = [];
  var queue = [{
    e: root,
    i: 0
  }];
  var current;

  while (queue.length > 0) {
    current = queue.shift();
    var isMathed = false;
    var currentElt = current.e;
    var currentI = current.i;

    if (this.match(currentElt, this.path[currentI])) {
      if (this.path[currentI].childCombinate) {
        var trackI = currentI;
        var trackElement = currentElt;
        var isTrackMatch = true;

        while (isTrackMatch && trackI > 0 && this.path[trackI].childCombinate) {
          if (!trackElement.parentNode || !this.match(trackElement.parentNode, this.path[trackI - 1])) {
            isTrackMatch = false;
          } else {
            trackElement = trackElement.parentNode;
            trackI--;
          }
        }

        if (isTrackMatch) isMathed = true;
      } else {
        isMathed = true;
      }
    }

    if (isMathed && currentI + 1 == this.path.length) {
      if (!onFound || onFound && onFound(currentElt)) res.push(currentElt);
    }

    if (currentElt.childNodes) {
      var l = currentElt.childNodes.length;

      for (var i = 0; i < l; ++i) {
        if (currentElt.childNodes[i].tagName) queue.push({
          e: currentElt.childNodes[i],
          i: currentI + (isMathed && currentI + 1 < this.path.length ? 1 : 0)
        });
      }
    }
  }

  return res;
};

var identRegex = /[a-zA-Z0-9\-_]+/;
var stringRegex = /"(([^"\\]*|(\\.))*)"/;
var classRegex = new RegExp('\\.' + identRegex.source);
var idRegex = new RegExp('#' + identRegex.source);
var booleanRegex = /true|false/;
var valueRegex = new RegExp(stringRegex.source + '|' + booleanRegex.source);
var attributeRegex = new RegExp('\\[\\s*(' + identRegex.source + ')\\s*(=\\s*(' + valueRegex.source + '))\\]');
var queryRegex = new RegExp(['(', identRegex.source, '|', attributeRegex.source, '|', classRegex.source, '|', idRegex.source, ')+'].join(''));
JSPath.__tagRegex = new RegExp(queryRegex.source + '|\\>', 'g');
JSPath.__tagNameRegex = new RegExp('^' + identRegex.source, 'i');
JSPath.__classRegex = new RegExp(classRegex.source, 'g');
JSPath.__idRegex = new RegExp(idRegex.source, 'i');
JSPath.__attrRegex = new RegExp(attributeRegex.source, 'g');

JSPath.parseQuery = function (s) {
  var tag = {};
  s = s.replace(JSPath.__attrRegex, function (full, name, assign, jsonTextValue) {
    tag.attributes = tag.attributes || {};

    if (assign) {
      tag.attributes[name] = JSON.parse(jsonTextValue);
    } else tag.attributes[name] = true;

    return '';
  });
  var classList = s.match(this.__classRegex);
  var idList = s.match(this.__idRegex);
  var tagList = s.match(this.__tagNameRegex);

  if (idList && idList.length > 0) {
    tag.id = idList[0].substring(1);
  }

  if (tagList && tagList.length > 0) {
    tag.tagName = tagList[0].trim();
  }

  if (classList && classList.length > 0) {
    tag.classList = classList.map(function (s) {
      return s.substring(1);
    });
  }

  return tag;
};
/**
 * @param {String} text
 * @returns {JSPath}
 */


JSPath.compileJSPath = function (text) {
  var tagTexts = text.match(this.__tagRegex) || [''];
  var path = [];
  var childCombinate = false;

  for (var i = 0; i < tagTexts.length; ++i) {
    var s = tagTexts[i];

    if (s == '>') {
      childCombinate = true;
    } else {
      var tag = this.parseQuery(s);
      tag.childCombinate = childCombinate;
      path.push(tag);
      childCombinate = false;
    }
  }

  return new JSPath({
    path: path
  });
};

/* harmony default export */ __webpack_exports__["a"] = (JSPath);

/***/ }),
/* 18 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./src/JSMaker/TemplateString.js
var TemplateString = __webpack_require__(7);

// CONCATENATED MODULE: ./src/JSDocx/templates/document.tpl
/* harmony default export */ var templates_document = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n<w:document\r\n  xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"\r\n  xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"\r\n  xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\r\n  xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\"\r\n  xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"\r\n  xmlns:ns6=\"http://schemas.openxmlformats.org/schemaLibrary/2006/main\"\r\n  xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"\r\n  xmlns:ns8=\"http://schemas.openxmlformats.org/drawingml/2006/chartDrawing\"\r\n  xmlns:dgm=\"http://schemas.openxmlformats.org/drawingml/2006/diagram\"\r\n  xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"\r\n  xmlns:ns11=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\"\r\n  xmlns:dsp=\"http://schemas.microsoft.com/office/drawing/2008/diagram\"\r\n  xmlns:ns13=\"urn:schemas-microsoft-com:office:excel\"\r\n  xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n  xmlns:v=\"urn:schemas-microsoft-com:vml\"\r\n  xmlns:w10=\"urn:schemas-microsoft-com:office:word\"\r\n  xmlns:ns17=\"urn:schemas-microsoft-com:office:powerpoint\"\r\n  xmlns:odx=\"http://opendope.org/xpaths\"\r\n  xmlns:odc=\"http://opendope.org/conditions\"\r\n  xmlns:odq=\"http://opendope.org/questions\"\r\n  xmlns:odi=\"http://opendope.org/components\"\r\n  xmlns:odgm=\"http://opendope.org/SmartArt/DataHierarchy\"\r\n  xmlns:ns24=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\"\r\n  xmlns:ns25=\"http://schemas.openxmlformats.org/drawingml/2006/compatibility\"\r\n  xmlns:ns26=\"http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas\">\r\n  <w:body>\r\n    <w:altChunk r:id=\"htmlChunk\" />\r\n    <w:sectPr>\r\n      <w:pgSz w:w=\"{{ pageSetting.width }}\" w:h=\"{{ pageSetting.height }}\" w:orient=\"{{ pageSetting.orient }}\" />\r\n      <w:pgMar w:top=\"{{ pageSetting.margins.top }}\"\r\n               w:right=\"{{ pageSetting.margins.right }}\"\r\n               w:bottom=\"{{ pageSetting.margins.bottom }}\"\r\n               w:left=\"{{ pageSetting.margins.left }}\"\r\n               w:header=\"{{ pageSetting.margins.header }}\"\r\n               w:footer=\"{{ pageSetting.margins.footer }}\"\r\n               w:gutter=\"{{ pageSetting.margins.gutter }}\"/>\r\n    </w:sectPr>\r\n  </w:body>\r\n</w:document>\r\n");
// CONCATENATED MODULE: ./src/JSDocx/templates/mht_document.tpl
/* harmony default export */ var mht_document = ("MIME-Version: 1.0\r\nContent-Type: multipart/related;\r\n    type=\"text/html\";\r\n    boundary=\"----=mhtDocumentPart\"\r\n\r\n\r\n------=mhtDocumentPart\r\nContent-Type: text/html;\r\n    charset=\"utf-8\"\r\nContent-Transfer-Encoding: quoted-printable\r\nContent-Location: file:///C:/fake/document.html\r\n\r\n{{ htmlSource }}\r\n\r\n{{ contentParts }}\r\n\r\n------=mhtDocumentPart--\r\n");
// CONCATENATED MODULE: ./src/JSDocx/templates/mht_part.tpl
/* harmony default export */ var mht_part = ("------=mhtDocumentPart\r\nContent-Type: {{ contentType }}\r\nContent-Transfer-Encoding: {{ contentEncoding }}\r\nContent-Location: {{ contentLocation }}\r\n\r\n{{ encodedContent }}\r\n");
// CONCATENATED MODULE: ./src/JSDocx/DocxTpl.js




/* harmony default export */ var DocxTpl = __webpack_exports__["a"] = ({
  document: new Function('pageSetting', 'return ' + TemplateString["a" /* default */].parse(templates_document).toJSCode()),
  mht_document: new Function('htmlSource', 'contentParts', 'return ' + TemplateString["a" /* default */].parse(mht_document).toJSCode()),
  mht_part: new Function('contentType', 'contentEncoding', 'contentLocation', 'encodedContent', 'return ' + TemplateString["a" /* default */].parse(mht_part).toJSCode())
});

/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _EventEmitter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _AElement__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _OOP__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
/* harmony import */ var _AttachHook__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13);




/***
 *
 * @extends EventEmitter
 * @param {AElement=} attachHookElt
 * @constructor
 */

function DomSignal(attachHookElt) {
  _EventEmitter__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].call(this);
  this.signals = {};
  this.ev_attached = this.ev_attached.bind(this);
  this.$attachhook = attachHookElt || this.createBuildInAttachHook();
  this.$attachhookParent = attachHookElt && attachHookElt.parentElement || null;
  this.$attachhook.on('attached', this.ev_attached);
}

_OOP__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].mixClass(DomSignal, _EventEmitter__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]);

DomSignal.prototype.createBuildInAttachHook = function () {
  var elt = document.createElement('img');
  Object.defineProperties(elt, Object.getOwnPropertyDescriptors(_AElement__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].prototype));
  Object.defineProperties(elt, Object.getOwnPropertyDescriptors(_AttachHook__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].prototype));
  Object.defineProperties(elt, _AttachHook__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].property);
  _AElement__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].call(elt);
  elt.setAttribute('src', '');
  elt.defineEvent('attached');
  _AttachHook__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].call(elt);
  return elt;
};

DomSignal.prototype.execSignal = function () {
  var signals = this.signals;

  if (this.$attachhook) {
    this.$attachhook.remove();
    this.$attachhook.resetState();
  }

  this.signals = {};

  for (var name in signals) {
    this.fire.apply(this, [name].concat(signals[name]));
  }
};

DomSignal.prototype.emit = function (name) {
  this.signals[name] = Array.prototype.slice.call(arguments, 1);

  if (!this.$attachhookParent) {
    this.$attachhookParent = document.body;
  }

  if (!this.$attachhook.parentElement) {
    this.$attachhookParent.appendChild(this.$attachhook);
  }
};

DomSignal.prototype.ev_attached = function () {
  this.execSignal();
};

/* harmony default export */ __webpack_exports__["a"] = (DomSignal);

/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <http://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



var base64 = __webpack_require__(35)
var ieee754 = __webpack_require__(36)
var isArray = __webpack_require__(37)

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Use Object implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * Due to various browser bugs, sometimes the Object implementation will be used even
 * when the browser supports typed arrays.
 *
 * Note:
 *
 *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
 *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
 *
 *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
 *
 *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
 *     incorrect length in some situations.

 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
 * get the Object implementation, which is slower but behaves correctly.
 */
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  ? global.TYPED_ARRAY_SUPPORT
  : typedArraySupport()

/*
 * Export kMaxLength after typed array support is determined.
 */
exports.kMaxLength = kMaxLength()

function typedArraySupport () {
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
    return arr.foo() === 42 && // typed array instances can be augmented
        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
        arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  } catch (e) {
    return false
  }
}

function kMaxLength () {
  return Buffer.TYPED_ARRAY_SUPPORT
    ? 0x7fffffff
    : 0x3fffffff
}

function createBuffer (that, length) {
  if (kMaxLength() < length) {
    throw new RangeError('Invalid typed array length')
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = new Uint8Array(length)
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    if (that === null) {
      that = new Buffer(length)
    }
    that.length = length
  }

  return that
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
    return new Buffer(arg, encodingOrOffset, length)
  }

  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new Error(
        'If encoding is specified then the first argument must be a string'
      )
    }
    return allocUnsafe(this, arg)
  }
  return from(this, arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192 // not used by this implementation

// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
  arr.__proto__ = Buffer.prototype
  return arr
}

function from (that, value, encodingOrOffset, length) {
  if (typeof value === 'number') {
    throw new TypeError('"value" argument must not be a number')
  }

  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length)
  }

  if (typeof value === 'string') {
    return fromString(that, value, encodingOrOffset)
  }

  return fromObject(that, value)
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(null, value, encodingOrOffset, length)
}

if (Buffer.TYPED_ARRAY_SUPPORT) {
  Buffer.prototype.__proto__ = Uint8Array.prototype
  Buffer.__proto__ = Uint8Array
  if (typeof Symbol !== 'undefined' && Symbol.species &&
      Buffer[Symbol.species] === Buffer) {
    // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
    Object.defineProperty(Buffer, Symbol.species, {
      value: null,
      configurable: true
    })
  }
}

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be a number')
  } else if (size < 0) {
    throw new RangeError('"size" argument must not be negative')
  }
}

function alloc (that, size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(that, size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(that, size).fill(fill, encoding)
      : createBuffer(that, size).fill(fill)
  }
  return createBuffer(that, size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(null, size, fill, encoding)
}

function allocUnsafe (that, size) {
  assertSize(size)
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0
    }
  }
  return that
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(null, size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(null, size)
}

function fromString (that, string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding')
  }

  var length = byteLength(string, encoding) | 0
  that = createBuffer(that, length)

  var actual = that.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    that = that.slice(0, actual)
  }

  return that
}

function fromArrayLike (that, array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  that = createBuffer(that, length)
  for (var i = 0; i < length; i += 1) {
    that[i] = array[i] & 255
  }
  return that
}

function fromArrayBuffer (that, array, byteOffset, length) {
  array.byteLength // this throws if `array` is not a valid ArrayBuffer

  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('\'offset\' is out of bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('\'length\' is out of bounds')
  }

  if (byteOffset === undefined && length === undefined) {
    array = new Uint8Array(array)
  } else if (length === undefined) {
    array = new Uint8Array(array, byteOffset)
  } else {
    array = new Uint8Array(array, byteOffset, length)
  }

  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = array
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    that = fromArrayLike(that, array)
  }
  return that
}

function fromObject (that, obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    that = createBuffer(that, len)

    if (that.length === 0) {
      return that
    }

    obj.copy(that, 0, 0, len)
    return that
  }

  if (obj) {
    if ((typeof ArrayBuffer !== 'undefined' &&
        obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
      if (typeof obj.length !== 'number' || isnan(obj.length)) {
        return createBuffer(that, 0)
      }
      return fromArrayLike(that, obj)
    }

    if (obj.type === 'Buffer' && isArray(obj.data)) {
      return fromArrayLike(that, obj.data)
    }
  }

  throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}

function checked (length) {
  // Note: cannot use `length < kMaxLength()` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= kMaxLength()) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + kMaxLength().toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return !!(b != null && b._isBuffer)
}

Buffer.compare = function compare (a, b) {
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError('Arguments must be Buffers')
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
      (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    string = '' + string
  }

  var len = string.length
  if (len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
      case undefined:
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) return utf8ToBytes(string).length // assume utf8
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length | 0
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  if (this.length > 0) {
    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
    if (this.length > max) str += ' ... '
  }
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (!Buffer.isBuffer(target)) {
    throw new TypeError('Argument must be a Buffer')
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset  // Coerce to Number.
  if (isNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (Buffer.TYPED_ARRAY_SUPPORT &&
        typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  // must be an even number of digits
  var strLen = string.length
  if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (isNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset | 0
    if (isFinite(length)) {
      length = length | 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  // legacy write(string, encoding, offset, length) - remove in v0.13
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
      : (firstByte > 0xBF) ? 2
      : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end)
    newBuf.__proto__ = Buffer.prototype
  } else {
    var sliceLen = end - start
    newBuf = new Buffer(sliceLen, undefined)
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start]
    }
  }

  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  this[offset] = (value & 0xff)
  return offset + 1
}

function objectWriteUInt16 (buf, value, offset, littleEndian) {
  if (value < 0) value = 0xffff + value + 1
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
      (littleEndian ? i : 1 - i) * 8
  }
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
  } else {
    objectWriteUInt16(this, value, offset, true)
  }
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
  } else {
    objectWriteUInt16(this, value, offset, false)
  }
  return offset + 2
}

function objectWriteUInt32 (buf, value, offset, littleEndian) {
  if (value < 0) value = 0xffffffff + value + 1
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  }
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset + 3] = (value >>> 24)
    this[offset + 2] = (value >>> 16)
    this[offset + 1] = (value >>> 8)
    this[offset] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, true)
  }
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, false)
  }
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
  } else {
    objectWriteUInt16(this, value, offset, true)
  }
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
  } else {
    objectWriteUInt16(this, value, offset, false)
  }
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
    this[offset + 2] = (value >>> 16)
    this[offset + 3] = (value >>> 24)
  } else {
    objectWriteUInt32(this, value, offset, true)
  }
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, false)
  }
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start
  var i

  if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
    // ascending copy from start
    for (i = 0; i < len; ++i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, start + len),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if (code < 256) {
        val = code
      }
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : utf8ToBytes(new Buffer(val, encoding).toString())
    var len = bytes.length
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function stringtrim (str) {
  if (str.trim) return str.trim()
  return str.replace(/^\s+|\s+$/g, '')
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

function isnan (val) {
  return val !== val // eslint-disable-line no-self-compare
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer, module) {(function (w) {
  "use strict";

  function findBest(atobNative) {
    // normal window
    if ('function' === typeof atobNative) { return atobNative; }


    // browserify (web worker)
    if ('function' === typeof Buffer) {
      return function atobBrowserify(a) {
        //!! Deliberately using an API that's deprecated in node.js because
        //!! this file is for browsers and we expect them to cope with it.
        //!! Discussion: github.com/node-browser-compat/atob/pull/9
        return new Buffer(a, 'base64').toString('binary');
      };
    }

    // ios web worker with base64js
    if ('object' === typeof w.base64js) {
      // bufferToBinaryString
      // https://git.coolaj86.com/coolaj86/unibabel.js/blob/master/index.js#L50
      return function atobWebWorker_iOS(a) {
        var buf = w.base64js.b64ToByteArray(a);
        return Array.prototype.map.call(buf, function (ch) {
          return String.fromCharCode(ch);
        }).join('');
      };
    }

		return function () {
			// ios web worker without base64js
			throw new Error("You're probably in an old browser or an iOS webworker." +
				" It might help to include beatgammit's base64-js.");
    };
  }

  var atobBest = findBest(w.atob);
  w.atob = atobBest;

  if (( true) && module && module.exports) {
    module.exports = atobBest;
  }
}(window));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(20).Buffer, __webpack_require__(38)(module)))

/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {(function () {
  "use strict";

  function btoa(str) {
    var buffer;

    if (str instanceof Buffer) {
      buffer = str;
    } else {
      buffer = Buffer.from(str.toString(), 'binary');
    }

    return buffer.toString('base64');
  }

  module.exports = btoa;
}());

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(20).Buffer))

/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {// Expose `IntlPolyfill` as global to add locale data into runtime later on.
global.IntlPolyfill = __webpack_require__(39);

// Require all locale data for `Intl`. This module will be
// ignored when bundling for the browser with Browserify/Webpack.
__webpack_require__(40);

// hack to export the polyfill as global Intl if needed
if (!global.Intl) {
    global.Intl = global.IntlPolyfill;
    global.IntlPolyfill.__applyLocaleSensitivePrototypes();
}

// providing an idiomatic api for the nodejs version of this module
module.exports = global.IntlPolyfill;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var external = global.external;
var re_msie = /\b(?:msie |ie |trident\/[0-9].*rv[ :])([0-9.]+)/;
var re_blackberry_10 = /\bbb10\b.+?\bversion\/([\d.]+)/;
var re_blackberry_6_7 = /\bblackberry\b.+\bversion\/([\d.]+)/;
var re_blackberry_4_5 = /\bblackberry\d+\/([\d.]+)/;
var NA_VERSION = "-1";
var DEVICES = [["nokia", function (ua) {
  //  nokia/-1
  if (ua.indexOf("nokia ") !== -1) {
    return /\bnokia ([0-9]+)?/;
  } else {
    return /\bnokia([a-z0-9]+)?/;
  }
}], //Android WP
["samsung", function (ua) {
  if (ua.indexOf("samsung") !== -1) {
    return /\bsamsung(?:[ \-](?:sgh|gt|sm))?-([a-z0-9]+)/;
  } else {
    return /\b(?:sgh|sch|gt|sm)-([a-z0-9]+)/;
  }
}], ["wp", function (ua) {
  return ua.indexOf("windows phone ") !== -1 || ua.indexOf("xblwp") !== -1 || ua.indexOf("zunewp") !== -1 || ua.indexOf("windows ce") !== -1;
}], ["pc", "windows"], ["ipad", "ipad"], // ipod iphone
["ipod", "ipod"], ["iphone", /\biphone\b|\biph(\d)/], ["mac", "macintosh"], ["mi", /\bmi[ \-]?([a-z0-9 ]+(?= build|\)))/], ["hongmi", /\bhm[ \-]?([a-z0-9]+)/], ["aliyun", /\baliyunos\b(?:[\-](\d+))?/], ["meizu", function (ua) {
  return ua.indexOf("meizu") >= 0 ? /\bmeizu[\/ ]([a-z0-9]+)\b/ : /\bm([0-9cx]{1,4})\b/;
}], ["nexus", /\bnexus ([0-9s.]+)/], ["huawei", function (ua) {
  var re_mediapad = /\bmediapad (.+?)(?= build\/huaweimediapad\b)/;

  if (ua.indexOf("huawei-huawei") !== -1) {
    return /\bhuawei\-huawei\-([a-z0-9\-]+)/;
  } else if (re_mediapad.test(ua)) {
    return re_mediapad;
  } else {
    return /\bhuawei[ _\-]?([a-z0-9]+)/;
  }
}], ["lenovo", function (ua) {
  if (ua.indexOf("lenovo-lenovo") !== -1) {
    return /\blenovo\-lenovo[ \-]([a-z0-9]+)/;
  } else {
    return /\blenovo[ \-]?([a-z0-9]+)/;
  }
}], ["zte", function (ua) {
  if (/\bzte\-[tu]/.test(ua)) {
    return /\bzte-[tu][ _\-]?([a-su-z0-9\+]+)/;
  } else {
    return /\bzte[ _\-]?([a-su-z0-9\+]+)/;
  }
}], ["vivo", /\bvivo(?: ([a-z0-9]+))?/], ["htc", function (ua) {
  if (/\bhtc[a-z0-9 _\-]+(?= build\b)/.test(ua)) {
    return /\bhtc[ _\-]?([a-z0-9 ]+(?= build))/;
  } else {
    return /\bhtc[ _\-]?([a-z0-9 ]+)/;
  }
}], ["oppo", /\boppo[_ ]([a-z0-9]+)/], ["konka", /\bkonka[_\-]([a-z0-9]+)/], ["sonyericsson", /\bmt([a-z0-9]+)/], ["coolpad", /\bcoolpad[_ ]?([a-z0-9]+)/], ["lg", /\blg[\-]([a-z0-9]+)/], ["android", /\bandroid\b|\badr\b/], ["blackberry", function (ua) {
  if (ua.indexOf("blackberry") >= 0) {
    return /\bblackberry\s?(\d+)/;
  }

  return "bb10";
}]];
var OS = [["wp", function (ua) {
  if (ua.indexOf("windows phone ") !== -1) {
    return /\bwindows phone (?:os )?([0-9.]+)/;
  } else if (ua.indexOf("xblwp") !== -1) {
    return /\bxblwp([0-9.]+)/;
  } else if (ua.indexOf("zunewp") !== -1) {
    return /\bzunewp([0-9.]+)/;
  }

  return "windows phone";
}], ["windows", /\bwindows nt ([0-9.]+)/], ["macosx", /\bmac os x ([0-9._]+)/], ["ios", function (ua) {
  if (/\bcpu(?: iphone)? os /.test(ua)) {
    return /\bcpu(?: iphone)? os ([0-9._]+)/;
  } else if (ua.indexOf("iph os ") !== -1) {
    return /\biph os ([0-9_]+)/;
  } else {
    return /\bios\b/;
  }
}], ["yunos", /\baliyunos ([0-9.]+)/], ["android", function (ua) {
  if (ua.indexOf("android") >= 0) {
    return /\bandroid[ \/-]?([0-9.x]+)?/;
  } else if (ua.indexOf("adr") >= 0) {
    if (ua.indexOf("mqqbrowser") >= 0) {
      return /\badr[ ]\(linux; u; ([0-9.]+)?/;
    } else {
      return /\badr(?:[ ]([0-9.]+))?/;
    }
  }

  return "android"; //return /\b(?:android|\badr)(?:[\/\- ](?:\(linux; u; )?)?([0-9.x]+)?/;
}], ["chromeos", /\bcros i686 ([0-9.]+)/], ["linux", "linux"], ["windowsce", /\bwindows ce(?: ([0-9.]+))?/], ["symbian", /\bsymbian(?:os)?\/([0-9.]+)/], ["blackberry", function (ua) {
  var m = ua.match(re_blackberry_10) || ua.match(re_blackberry_6_7) || ua.match(re_blackberry_4_5);
  return m ? {
    version: m[1]
  } : "blackberry";
}], ['ie', /\rv\:\/([0-9.]+)/]];
var ENGINE = [["edgehtml", /edge\/([0-9.]+)/], ["trident", re_msie], ["blink", function () {
  return "chrome" in global && "CSS" in global && /\bapplewebkit[\/]?([0-9.+]+)/;
}], ["webkit", /\bapplewebkit[\/]?([0-9.+]+)/], ["gecko", function (ua) {
  var match = ua.match(/\brv:([\d\w.]+).*\bgecko\/(\d+)/);

  if (match) {
    return {
      version: match[1] + "." + match[2]
    };
  }
}], ["presto", /\bpresto\/([0-9.]+)/], ["androidwebkit", /\bandroidwebkit\/([0-9.]+)/], ["coolpadwebkit", /\bcoolpadwebkit\/([0-9.]+)/], ["u2", /\bu2\/([0-9.]+)/], ["u3", /\bu3\/([0-9.]+)/]];
var BROWSER = [['coccoc', /coc_coc_browser\/([0-9.]+)/], // Microsoft Edge Browser, Default browser in Windows 10.
["edge", /edge\/([0-9.]+)/], ["chrome-edge", /chrome.+edg\/([0-9.]+)/], // Sogou.
["sogou", function (ua) {
  if (ua.indexOf("sogoumobilebrowser") >= 0) {
    return /sogoumobilebrowser\/([0-9.]+)/;
  } else if (ua.indexOf("sogoumse") >= 0) {
    return true;
  }

  return / se ([0-9.x]+)/;
}], // Maxthon
["maxthon", function () {
  try {
    if (external && (external.mxVersion || external.max_version)) {
      return {
        version: external.mxVersion || external.max_version
      };
    }
  } catch (ex) {
    /* */
  }

  return /\b(?:maxthon|mxbrowser)(?:[ \/]([0-9.]+))?/;
}], ["micromessenger", /\bmicromessenger\/([\d.]+)/], ["qq", /\bm?qqbrowser\/([0-9.]+)/], ["green", "greenbrowser"], ["tt", /\btencenttraveler ([0-9.]+)/], ["liebao", function (ua) {
  if (ua.indexOf("liebaofast") >= 0) {
    return /\bliebaofast\/([0-9.]+)/;
  }

  if (ua.indexOf("lbbrowser") === -1) {
    return false;
  }

  var version;

  try {
    if (external && external.LiebaoGetVersion) {
      version = external.LiebaoGetVersion();
    }
  } catch (ex) {
    /* */
  }

  return {
    version: version || NA_VERSION
  };
}], ["tao", /\btaobrowser\/([0-9.]+)/], ["coolnovo", /\bcoolnovo\/([0-9.]+)/], ["saayaa", "saayaa"], ["baidu", /\b(?:ba?idubrowser|baiduhd)[ \/]([0-9.x]+)/], ["ie", re_msie], ["mi", /\bmiuibrowser\/([0-9.]+)/], ["opera", function (ua) {
  var re_opera_old = /\bopera.+version\/([0-9.ab]+)/;
  var re_opera_new = /\bopr\/([0-9.]+)/;
  return re_opera_old.test(ua) ? re_opera_old : re_opera_new;
}], ["oupeng", /\boupeng\/([0-9.]+)/], ["yandex", /yabrowser\/([0-9.]+)/], ["ali-ap", function (ua) {
  if (ua.indexOf("aliapp") > 0) {
    return /\baliapp\(ap\/([0-9.]+)\)/;
  } else {
    return /\balipayclient\/([0-9.]+)\b/;
  }
}], ["ali-ap-pd", /\baliapp\(ap-pd\/([0-9.]+)\)/], ["ali-am", /\baliapp\(am\/([0-9.]+)\)/], ["ali-tb", /\baliapp\(tb\/([0-9.]+)\)/], ["ali-tb-pd", /\baliapp\(tb-pd\/([0-9.]+)\)/], ["ali-tm", /\baliapp\(tm\/([0-9.]+)\)/], ["ali-tm-pd", /\baliapp\(tm-pd\/([0-9.]+)\)/], ["uc", function (ua) {
  if (ua.indexOf("ucbrowser/") >= 0) {
    return /\bucbrowser\/([0-9.]+)/;
  } else if (ua.indexOf("ubrowser/") >= 0) {
    return /\bubrowser\/([0-9.]+)/;
  } else if (/\buc\/[0-9]/.test(ua)) {
    return /\buc\/([0-9.]+)/;
  } else if (ua.indexOf("ucweb") >= 0) {
    // `ucweb/2.0` is compony info.
    // `UCWEB8.7.2.214/145/800` is browser info.
    return /\bucweb([0-9.]+)?/;
  } else {
    return /\b(?:ucbrowser|uc)\b/;
  }
}], ["baiduboxapp", function (ua) {
  var back = 0;
  var a;

  if (/ baiduboxapp\//i.test(ua)) {
    a = /([\d+.]+)_(?:diordna|enohpi)_/.exec(ua);

    if (a) {
      a = a[1].split(".");
      back = a.reverse().join(".");
    } else if (a = /baiduboxapp\/([\d+.]+)/.exec(ua)) {
      back = a[1];
    }

    return {
      version: back
    };
  }

  return false;
}], ["oppobrowser", /\boppobrowser\/([0-9.]+)/], ["edge-android", / (?:edga)\/([0-9.]+)/], ["chrome", / (?:chrome|crios|crmo)\/([0-9.]+)/], // Android safari 
["android", function (ua) {
  if (ua.indexOf("android") === -1) {
    return;
  }

  return /\bversion\/([0-9.]+(?: beta)?)/;
}], ["blackberry", function (ua) {
  var m = ua.match(re_blackberry_10) || ua.match(re_blackberry_6_7) || ua.match(re_blackberry_4_5);
  return m ? {
    version: m[1]
  } : "blackberry";
}], ["safari", /\bversion\/([0-9.]+(?: beta)?)(?: mobile(?:\/[a-z0-9]+)?)? safari\//], //  Safari, WebView
["webview", /\bcpu(?: iphone)? os (?:[0-9._]+).+\bapplewebkit\b/], ["firefox", /\bfirefox\/([0-9.ab]+)/], ["nokia", /\bnokiabrowser\/([0-9.]+)/]];
module.exports = {
  device: DEVICES,
  os: OS,
  browser: BROWSER,
  engine: ENGINE,
  re_msie: re_msie
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 25 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global, Buffer) {/* harmony import */ var _DocxTpl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18);
/* harmony import */ var _assets_content_types_xml__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(26);
/* harmony import */ var _assets_rels_xml__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27);
/* harmony import */ var _assets_document_xml_rels__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(28);
/* harmony import */ var _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(0);
/* harmony import */ var _HTML5_Svg__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(10);






var JSZip = window.JSZip;

function JSDocx(props) {
  if (props.blob) this.blob = props.blob;
  if (props.blob) this.buffer = props.buffer;
}

JSDocx.prototype.saveAs = function (fileName) {
  var src;

  if (this.blob) {
    src = (URL || webkitURL).createObjectURL(this.blob);
  } else if (this.buffer) {
    src = "data:application/octet-stream," + encodeURIComponent(this.buffer);
  }

  var element = document.createElement('a');
  element.setAttribute('href', src);
  element.setAttribute('download', fileName);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
};

JSDocx._prepareImageParts = function (htmlSource) {
  var imageContentParts = [];
  var inlinedSrcPattern = /\"data:(\w+\/\w+);(\w+),(\S+)\"/g;

  var inlinedReplacer = function inlinedReplacer(match, contentType, contentEncoding, encodedContent) {
    var index = imageContentParts.length;
    var extension = contentType.split('/')[1];
    var contentLocation = "file:///C:/fake/image" + index + "." + extension; // mht_part: new Function('contentType', 'contentEncoding', 'contentLocation', 'encodedContent', 'return ' + TemplateString.parse(mht_pathTpl).toJSCode())

    imageContentParts.push(_DocxTpl__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].mht_part(contentType, contentEncoding, contentLocation, encodedContent));
    return "\"" + contentLocation + "\"";
  };

  if (typeof htmlSource === 'string') {
    if (!/<img/g.test(htmlSource)) {
      return {
        htmlSource: htmlSource,
        imageContentParts: imageContentParts
      };
    }

    htmlSource = htmlSource.replace(inlinedSrcPattern, inlinedReplacer);
    return {
      htmlSource: htmlSource,
      imageContentParts: imageContentParts
    };
  } else {
    throw new Error("Not a valid source provided!");
  }
};

JSDocx._getMHTdocument = function (htmlSource) {
  var imageContentParts, _ref;

  _ref = this._prepareImageParts(htmlSource), htmlSource = _ref.htmlSource, imageContentParts = _ref.imageContentParts;
  htmlSource = htmlSource.replace(/\=/g, '=3D');
  return _DocxTpl__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].mht_document(htmlSource, imageContentParts.join('\n'));
};
/**
 * @param {JSZip} zip
 */


JSDocx._generateDocument = function (zip) {
  return zip.generateAsync({
    type: 'arraybuffer'
  }).then(function (buffer) {
    var props = {};
    if (global.Blob) props.blob = new Blob([buffer], {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    });else if (global.Buffer) props.buffer = new Buffer(new Uint8Array(buffer));else throw new Error("Neither Blob nor Buffer are accessible in this environment. " + "Consider adding Blob.js shim");
    return new JSDocx(props);
  });
};

JSDocx._renderDocumentFile = function (pageSetting) {
  return _DocxTpl__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].document(pageSetting);
};

JSDocx._createPageSetting = function (documentOptions) {
  documentOptions = documentOptions || {};
  var pageSetting = {
    margins: {
      top: 1440,
      right: 1440,
      bottom: 1440,
      left: 1440,
      header: 720,
      footer: 720,
      gutter: 0
    }
  };

  if (documentOptions.orientation == 'landscape') {
    Object.assign(pageSetting, {
      height: 12240,
      width: 15840,
      orient: 'landscape'
    });
  } else {
    Object.assign(pageSetting, {
      width: 12240,
      height: 15840,
      orient: 'portrait'
    });
  }

  if (documentOptions.margins) {
    Object.assign(pageSetting, documentOptions.margins);
  }

  return pageSetting;
};

JSDocx._addFiles = function (zip, htmlSource, pageSetting) {
  zip.file('[Content_Types].xml', _assets_content_types_xml__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"]);
  zip.folder('_rels').file('.rels', _assets_rels_xml__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"]);
  zip.folder('word').file('document.xml', _DocxTpl__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].document(pageSetting));
  zip.folder('word').file('document.xml', JSDocx._renderDocumentFile(pageSetting)).file('afchunk.mht', JSDocx._getMHTdocument(htmlSource)).folder('_rels').file('document.xml.rels', _assets_document_xml_rels__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"]);
  return zip;
};

JSDocx.fromHTMLCode = function (html, options) {
  var zip = new JSZip();

  JSDocx._addFiles(zip, html, JSDocx._createPageSetting(options));

  return JSDocx._generateDocument(zip);
};

JSDocx.fromHTMLElement = function (element, options, getOuter, isWorkingElement) {
  if (typeof element == 'string') {
    element = _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance.$(element);
  }

  if (!element) throw new Error('@param element must be HTMLElement');
  var preRender;

  if (!isWorkingElement) {
    preRender = _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance._('div');
    preRender.addStyle({
      position: 'fixed',
      top: '0',
      left: '0',
      zIndex: '-10000',
      opacity: '0'
    }).addTo(document.body);
    Array.prototype.forEach.call(element.childNodes, function (e) {
      if (e.tagName != 'script') preRender.addChild(e.cloneNode(true));
    });
  } else {
    preRender = element;
  }

  _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance.$('script', preRender, function (e) {
    e.parentElement.removeChild(e);
    return false;
  });
  var imageTask = [];
  _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance.$('img', preRender, function (e) {
    if (e.src && !e.src.match(/data:/)) {
      var task = _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].imageToCanvas(e).then(function (canvas) {
        var newSrc = canvas.toDataURL();
        e.src = newSrc;
      });
      imageTask.push(task);
    }

    return false;
  });
  _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance.$('svg', preRender, function (e) {
    var task = _HTML5_Svg__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].svgToCanvas(e).then(function (canvas) {
      var newSrc = canvas.toDataURL();

      var image = _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance._('img');

      image.src = newSrc;
      _HTML5_Dom__WEBPACK_IMPORTED_MODULE_4__[/* default */ "b"].ShareInstance.$(e).selfReplace(image);
    });
    imageTask.push(task);
    return false;
  });
  return Promise.all(imageTask).then(function () {
    var code;

    if (getOuter) {
      code = preRender.outerHTML;

      if (!code) {
        var temp = document.createElement('div');
        temp.addChild(preRender);
        code = temp.innerHTML;
      }
    } else {
      code = preRender.innerHTML;
    }

    return JSDocx.fromHTMLCode(code, options);
  });
};

/* harmony default export */ __webpack_exports__["a"] = (JSDocx);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9), __webpack_require__(20).Buffer))

/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony default export */ __webpack_exports__["a"] = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\r\n  <Default Extension=\"rels\" ContentType=\r\n    \"application/vnd.openxmlformats-package.relationships+xml\" />\r\n  <Override PartName=\"/word/document.xml\" ContentType=\r\n    \"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/>\r\n  <Override PartName=\"/word/afchunk.mht\" ContentType=\"message/rfc822\"/>\r\n</Types>\r\n");

/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony default export */ __webpack_exports__["a"] = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\r\n  <Relationship\r\n      Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\"\r\n      Target=\"/word/document.xml\" Id=\"R09c83fafc067488e\" />\r\n</Relationships>\r\n");

/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony default export */ __webpack_exports__["a"] = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\r\n  <Relationship Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk\"\r\n    Target=\"/word/afchunk.mht\" Id=\"htmlChunk\" />\r\n</Relationships>\r\n");

/***/ }),
/* 29 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _FlagManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);



_FlagManager__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].add('ABSOL_DEBUG', false);

function ALogger() {
  _FlagManager__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].on('change', this._updateProto.bind(this));

  this._updateProto();
}

ALogger.prototype._updateProto = function () {
  ['log', 'table', 'table', 'error', 'warn'].forEach(function (name) {
    var cFunction = window['ABSOL_DEBUG'] ? console[name] && console[name].bind(console) : _noop__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
    this[name] = cFunction || _noop__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
  }.bind(this));
};

ALogger.prototype.log = _noop__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
ALogger.prototype.table = _noop__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
ALogger.prototype.error = _noop__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
ALogger.prototype.warn = _noop__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"];
(window || global).ALogger = new ALogger();
/* harmony default export */ __webpack_exports__["a"] = (ALogger);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(42);


/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setImmediate, global) {/* harmony import */ var atob__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var atob__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(atob__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var btoa__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22);
/* harmony import */ var btoa__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(btoa__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var intl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var intl__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(intl__WEBPACK_IMPORTED_MODULE_2__);
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }





if (!('Intl' in window)) {
  window.Intl = intl__WEBPACK_IMPORTED_MODULE_2___default.a;
}

if (!('atob' in window)) {
  window.atob = atob__WEBPACK_IMPORTED_MODULE_0___default.a;
}

if (!('btoa' in window)) {
  window.btoa = btoa__WEBPACK_IMPORTED_MODULE_1___default.a;
}

!function (e, n) {
  "object" == (typeof exports === "undefined" ? "undefined" : _typeof(exports)) && "undefined" != typeof module ? n() : "function" == typeof define && __webpack_require__(41) ? define(n) : n();
}(0, function () {
  "use strict";

  function e(e) {
    var n = this.constructor;
    return this.then(function (t) {
      return n.resolve(e()).then(function () {
        return t;
      });
    }, function (t) {
      return n.resolve(e()).then(function () {
        return n.reject(t);
      });
    });
  }

  function n() {}

  function t(e) {
    if (!(this instanceof t)) throw new TypeError("Promises must be constructed via new");
    if ("function" != typeof e) throw new TypeError("not a function");
    this._state = 0, this._handled = !1, this._value = undefined, this._deferreds = [], u(e, this);
  }

  function o(e, n) {
    for (; 3 === e._state;) {
      e = e._value;
    }

    0 !== e._state ? (e._handled = !0, t._immediateFn(function () {
      var t = 1 === e._state ? n.onFulfilled : n.onRejected;

      if (null !== t) {
        var o;

        try {
          o = t(e._value);
        } catch (f) {
          return void i(n.promise, f);
        }

        r(n.promise, o);
      } else (1 === e._state ? r : i)(n.promise, e._value);
    })) : e._deferreds.push(n);
  }

  function r(e, n) {
    try {
      if (n === e) throw new TypeError("A promise cannot be resolved with itself.");

      if (n && ("object" == _typeof(n) || "function" == typeof n)) {
        var o = n.then;
        if (n instanceof t) return e._state = 3, e._value = n, void f(e);
        if ("function" == typeof o) return void u(function (e, n) {
          return function () {
            e.apply(n, arguments);
          };
        }(o, n), e);
      }

      e._state = 1, e._value = n, f(e);
    } catch (r) {
      i(e, r);
    }
  }

  function i(e, n) {
    e._state = 2, e._value = n, f(e);
  }

  function f(e) {
    2 === e._state && 0 === e._deferreds.length && t._immediateFn(function () {
      e._handled || t._unhandledRejectionFn(e._value);
    });

    for (var n = 0, r = e._deferreds.length; r > n; n++) {
      o(e, e._deferreds[n]);
    }

    e._deferreds = null;
  }

  function u(e, n) {
    var t = !1;

    try {
      e(function (e) {
        t || (t = !0, r(n, e));
      }, function (e) {
        t || (t = !0, i(n, e));
      });
    } catch (o) {
      if (t) return;
      t = !0, i(n, o);
    }
  }

  var c = setTimeout;
  t.prototype["catch"] = function (e) {
    return this.then(null, e);
  }, t.prototype.then = function (e, t) {
    var r = new this.constructor(n);
    return o(this, new function (e, n, t) {
      this.onFulfilled = "function" == typeof e ? e : null, this.onRejected = "function" == typeof n ? n : null, this.promise = t;
    }(e, t, r)), r;
  }, t.prototype["finally"] = e, t.all = function (e) {
    return new t(function (n, t) {
      function o(e, f) {
        try {
          if (f && ("object" == _typeof(f) || "function" == typeof f)) {
            var u = f.then;
            if ("function" == typeof u) return void u.call(f, function (n) {
              o(e, n);
            }, t);
          }

          r[e] = f, 0 == --i && n(r);
        } catch (c) {
          t(c);
        }
      }

      if (!e || "undefined" == typeof e.length) throw new TypeError("Promise.all accepts an array");
      var r = Array.prototype.slice.call(e);
      if (0 === r.length) return n([]);

      for (var i = r.length, f = 0; r.length > f; f++) {
        o(f, r[f]);
      }
    });
  }, t.resolve = function (e) {
    return e && "object" == _typeof(e) && e.constructor === t ? e : new t(function (n) {
      n(e);
    });
  }, t.reject = function (e) {
    return new t(function (n, t) {
      t(e);
    });
  }, t.race = function (e) {
    return new t(function (n, t) {
      for (var o = 0, r = e.length; r > o; o++) {
        e[o].then(n, t);
      }
    });
  }, t._immediateFn = "function" == typeof setImmediate && function (e) {
    setImmediate(e);
  } || function (e) {
    c(e, 0);
  }, t._unhandledRejectionFn = function (e) {
    void 0 !== console && console && console.warn("Possible Unhandled Promise Rejection:", e);
  };

  var l = function () {
    if ("undefined" != typeof self) return self;
    if ("undefined" != typeof window) return window;
    if ("undefined" != typeof global) return global;
    throw Error("unable to locate global object");
  }();

  "Promise" in l ? l.Promise.prototype["finally"] || (l.Promise.prototype["finally"] = e) : l.Promise = t;
});
!function () {
  var vendors = ['ms', 'moz', 'webkit', 'o'];

  for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
  }

  if (!window.requestAnimationFrame) window.requestAnimationFrame = function (callback, element) {
    var id = window.setTimeout(function () {
      callback(element);
    }, 1000 / 60);
    return id;
  };
  if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function (id) {
    clearTimeout(id);
  };
}(); //Object

(function () {
  'use strict';

  var ObjectProto = Object.prototype,
      defineGetter = ObjectProto.__defineGetter__,
      defineSetter = ObjectProto.__defineSetter__,
      lookupGetter = ObjectProto.__lookupGetter__,
      lookupSetter = ObjectProto.__lookupSetter__,
      hasOwnProp = ObjectProto.hasOwnProperty;
  var supportDom = true;

  try {
    if (Object.defineProperty) {
      Object.defineProperty(document.createElement('div'), 'theRandomName', {
        set: function set() {},
        get: function get() {}
      });
    }
  } catch (error) {
    supportDom = false;
  }

  if ((!supportDom || !Object.defineProperty) && defineGetter && defineSetter && lookupGetter && lookupSetter) {
    var originObjetDefineProperty = Object.defineProperty;

    Object.defineProperty = function (obj, prop, descriptor) {
      if (!originObjetDefineProperty || typeof obj.nodeType === "number" && typeof obj.nodeName === "string") {
        if (arguments.length < 3) {
          // all arguments required
          throw new TypeError("Arguments not optional");
        }

        prop += ""; // convert prop to string

        if (hasOwnProp.call(descriptor, "value")) {
          if (!lookupGetter.call(obj, prop) && !lookupSetter.call(obj, prop)) {
            // data property defined and no pre-existing accessors
            obj[prop] = descriptor.value;
          }

          if (hasOwnProp.call(descriptor, "get") || hasOwnProp.call(descriptor, "set")) {
            // descriptor has a value prop but accessor already exists
            throw new TypeError("Cannot specify an accessor and a value");
          }
        }

        if (descriptor.get) {
          defineGetter.call(obj, prop, descriptor.get);
        }

        if (descriptor.set) {
          defineSetter.call(obj, prop, descriptor.set);
        }

        return obj;
      } else {
        return originObjetDefineProperty.call(this, obj, prop, descriptor);
      }
    };

    var originObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

    Object.getOwnPropertyDescriptor = function (obj, prop) {
      if (!originObjectGetOwnPropertyDescriptor || typeof obj.nodeType === "number" && typeof obj.nodeName === "string") {
        if (arguments.length < 2) {
          // all arguments required
          throw new TypeError("Arguments not optional.");
        }

        prop += ""; // convert prop to string

        var descriptor = {
          configurable: true,
          enumerable: true,
          writable: true
        },
            getter = lookupGetter.call(obj, prop),
            setter = lookupSetter.call(obj, prop);

        if (!hasOwnProp.call(obj, prop)) {
          // property doesn't exist or is inherited
          return descriptor;
        }

        if (!getter && !setter) {
          // not an accessor so return prop
          descriptor.value = obj[prop];
          return descriptor;
        } // there is an accessor, remove descriptor.writable;
        // populate descriptor.get and descriptor.set (IE's behavior)


        delete descriptor.writable;
        descriptor.get = descriptor.set = undefined;

        if (getter) {
          descriptor.get = getter;
        }

        if (setter) {
          descriptor.set = setter;
        }

        return descriptor;
      } else {
        return originObjectGetOwnPropertyDescriptor(obj, prop);
      }
    };
  }

  if (!supportDom || !Object.getOwnPropertyDescriptors) {
    Object.getOwnPropertyDescriptors = function (o) {
      var res = {};

      for (var key in o) {
        res[key] = Object.getOwnPropertyDescriptor(o, key);
      }

      return res;
    };
  }

  if (!supportDom || !Object.defineProperties) {
    Object.defineProperties = function (obj, props) {
      var prop;

      for (prop in props) {
        if (hasOwnProp.call(props, prop)) {
          Object.defineProperty(obj, prop, props[prop]);
        }
      }
    };
  }

  if (typeof Object.assign != 'function') {
    Object.assign = function (target, varArgs) {
      'use strict';

      if (target == null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) {
          for (var nextKey in nextSource) {
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }

      return to;
    };
  }
})(); //string


!function () {
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (searchString, position) {
      position = position || 0;
      return this.indexOf(searchString, position) === position;
    };
  }

  if (!String.prototype.replaceAll) {
    String.prototype.replaceAll = function () {
      var find = arguments[0];
      if (!find) return this;

      if (typeof find == "string") {
        return this.split(find).join(arguments[1]);
      } else if (find instanceof RegExp) {
        return this.replace(new RegExp(find.source, 'g'), arguments[1]);
      }
    };
  }
}(); //array

!function () {
  if (!Array.prototype.fill) {
    Object.defineProperty(Array.prototype, 'fill', {
      value: function value(_value) {
        // Steps 1-2.
        if (this == null) {
          throw new TypeError('this is null or not defined');
        }

        var O = Object(this); // Steps 3-5.

        var len = O.length >>> 0; // Steps 6-7.

        var start = arguments[1];
        var relativeStart = start >> 0; // Step 8.

        var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); // Steps 9-10.

        var end = arguments[2];
        var relativeEnd = end === undefined ? len : end >> 0; // Step 11.

        var final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // Step 12.

        while (k < final) {
          O[k] = _value;
          k++;
        } // Step 13.


        return O;
      }
    });
  }

  if (!Array.prototype.some) {
    Array.prototype.some = function (fun
    /*, thisp */
    ) {
      "use strict";

      if (this == null) throw new TypeError();
      var t = Object(this),
          len = t.length >>> 0;
      if (typeof fun != "function") throw new TypeError();
      var thisp = arguments[1];

      for (var i = 0; i < len; i++) {
        if (i in t && fun.call(thisp, t[i], i, t)) return true;
      }

      return false;
    };
  }
}(); //function

!function () {
  if (!Function.prototype.bind) {
    var ArrayPrototypeSlice = Array.prototype.slice;

    Function.prototype.bind = function (otherThis) {
      if (typeof this !== 'function') {
        // closest thing possible to the ECMAScript 5
        // internal IsCallable function
        throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
      }

      var baseArgs = ArrayPrototypeSlice.call(arguments, 1),
          baseArgsLength = baseArgs.length,
          fToBind = this,
          fNOP = function fNOP() {},
          fBound = function fBound() {
        baseArgs.length = baseArgsLength; // reset to default base arguments

        baseArgs.push.apply(baseArgs, arguments);
        return fToBind.apply(fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs);
      };

      if (this.prototype) {
        // Function.prototype doesn't have a prototype property
        fNOP.prototype = this.prototype;
      }

      fBound.prototype = new fNOP();
      return fBound;
    };
  }
}();
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(32).setImmediate, __webpack_require__(9)))

/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
            (typeof self !== "undefined" && self) ||
            window;
var apply = Function.prototype.apply;

// DOM APIs, for completeness

exports.setTimeout = function() {
  return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
  return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
  if (timeout) {
    timeout.close();
  }
};

function Timeout(id, clearFn) {
  this._id = id;
  this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  this._clearFn.call(scope, this._id);
};

// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
};

exports.unenroll = function(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
};

exports._unrefActive = exports.active = function(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
};

// setimmediate attaches itself to the global object
__webpack_require__(33);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto.  Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
                       (typeof global !== "undefined" && global.setImmediate) ||
                       (this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
                         (typeof global !== "undefined" && global.clearImmediate) ||
                         (this && this.clearImmediate);

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
    "use strict";

    if (global.setImmediate) {
        return;
    }

    var nextHandle = 1; // Spec says greater than zero
    var tasksByHandle = {};
    var currentlyRunningATask = false;
    var doc = global.document;
    var registerImmediate;

    function setImmediate(callback) {
      // Callback can either be a function or a string
      if (typeof callback !== "function") {
        callback = new Function("" + callback);
      }
      // Copy function arguments
      var args = new Array(arguments.length - 1);
      for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i + 1];
      }
      // Store and register the task
      var task = { callback: callback, args: args };
      tasksByHandle[nextHandle] = task;
      registerImmediate(nextHandle);
      return nextHandle++;
    }

    function clearImmediate(handle) {
        delete tasksByHandle[handle];
    }

    function run(task) {
        var callback = task.callback;
        var args = task.args;
        switch (args.length) {
        case 0:
            callback();
            break;
        case 1:
            callback(args[0]);
            break;
        case 2:
            callback(args[0], args[1]);
            break;
        case 3:
            callback(args[0], args[1], args[2]);
            break;
        default:
            callback.apply(undefined, args);
            break;
        }
    }

    function runIfPresent(handle) {
        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
        // So if we're currently running a task, we'll need to delay this invocation.
        if (currentlyRunningATask) {
            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
            // "too much recursion" error.
            setTimeout(runIfPresent, 0, handle);
        } else {
            var task = tasksByHandle[handle];
            if (task) {
                currentlyRunningATask = true;
                try {
                    run(task);
                } finally {
                    clearImmediate(handle);
                    currentlyRunningATask = false;
                }
            }
        }
    }

    function installNextTickImplementation() {
        registerImmediate = function(handle) {
            process.nextTick(function () { runIfPresent(handle); });
        };
    }

    function canUsePostMessage() {
        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
        // where `global.postMessage` means something completely different and can't be used for this purpose.
        if (global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function() {
                postMessageIsAsynchronous = false;
            };
            global.postMessage("", "*");
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous;
        }
    }

    function installPostMessageImplementation() {
        // Installs an event handler on `global` for the `message` event: see
        // * https://developer.mozilla.org/en/DOM/window.postMessage
        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

        var messagePrefix = "setImmediate$" + Math.random() + "$";
        var onGlobalMessage = function(event) {
            if (event.source === global &&
                typeof event.data === "string" &&
                event.data.indexOf(messagePrefix) === 0) {
                runIfPresent(+event.data.slice(messagePrefix.length));
            }
        };

        if (global.addEventListener) {
            global.addEventListener("message", onGlobalMessage, false);
        } else {
            global.attachEvent("onmessage", onGlobalMessage);
        }

        registerImmediate = function(handle) {
            global.postMessage(messagePrefix + handle, "*");
        };
    }

    function installMessageChannelImplementation() {
        var channel = new MessageChannel();
        channel.port1.onmessage = function(event) {
            var handle = event.data;
            runIfPresent(handle);
        };

        registerImmediate = function(handle) {
            channel.port2.postMessage(handle);
        };
    }

    function installReadyStateChangeImplementation() {
        var html = doc.documentElement;
        registerImmediate = function(handle) {
            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();

    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();

    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();

    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();

    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9), __webpack_require__(34)))

/***/ }),
/* 34 */
/***/ (function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };


/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}


/***/ }),
/* 36 */
/***/ (function(module, exports) {

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),
/* 37 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),
/* 38 */
/***/ (function(module, exports) {

module.exports = function(module) {
	if (!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};

var jsx = function () {
  var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7;
  return function createRawReactElement(type, props, key, children) {
    var defaultProps = type && type.defaultProps;
    var childrenLength = arguments.length - 3;

    if (!props && childrenLength !== 0) {
      props = {};
    }

    if (props && defaultProps) {
      for (var propName in defaultProps) {
        if (props[propName] === void 0) {
          props[propName] = defaultProps[propName];
        }
      }
    } else if (!props) {
      props = defaultProps || {};
    }

    if (childrenLength === 1) {
      props.children = children;
    } else if (childrenLength > 1) {
      var childArray = Array(childrenLength);

      for (var i = 0; i < childrenLength; i++) {
        childArray[i] = arguments[i + 3];
      }

      props.children = childArray;
    }

    return {
      $$typeof: REACT_ELEMENT_TYPE,
      type: type,
      key: key === undefined ? null : '' + key,
      ref: null,
      props: props,
      _owner: null
    };
  };
}();

var asyncToGenerator = function (fn) {
  return function () {
    var gen = fn.apply(this, arguments);
    return new Promise(function (resolve, reject) {
      function step(key, arg) {
        try {
          var info = gen[key](arg);
          var value = info.value;
        } catch (error) {
          reject(error);
          return;
        }

        if (info.done) {
          resolve(value);
        } else {
          return Promise.resolve(value).then(function (value) {
            return step("next", value);
          }, function (err) {
            return step("throw", err);
          });
        }
      }

      return step("next");
    });
  };
};

var classCallCheck = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

var createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

var defineEnumerableProperties = function (obj, descs) {
  for (var key in descs) {
    var desc = descs[key];
    desc.configurable = desc.enumerable = true;
    if ("value" in desc) desc.writable = true;
    Object.defineProperty(obj, key, desc);
  }

  return obj;
};

var defaults = function (obj, defaults) {
  var keys = Object.getOwnPropertyNames(defaults);

  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var value = Object.getOwnPropertyDescriptor(defaults, key);

    if (value && value.configurable && obj[key] === undefined) {
      Object.defineProperty(obj, key, value);
    }
  }

  return obj;
};

var defineProperty$1 = function (obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
};

var _extends = Object.assign || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

var get = function get(object, property, receiver) {
  if (object === null) object = Function.prototype;
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent === null) {
      return undefined;
    } else {
      return get(parent, property, receiver);
    }
  } else if ("value" in desc) {
    return desc.value;
  } else {
    var getter = desc.get;

    if (getter === undefined) {
      return undefined;
    }

    return getter.call(receiver);
  }
};

var inherits = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};

var _instanceof = function (left, right) {
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
    return right[Symbol.hasInstance](left);
  } else {
    return left instanceof right;
  }
};

var interopRequireDefault = function (obj) {
  return obj && obj.__esModule ? obj : {
    default: obj
  };
};

var interopRequireWildcard = function (obj) {
  if (obj && obj.__esModule) {
    return obj;
  } else {
    var newObj = {};

    if (obj != null) {
      for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
      }
    }

    newObj.default = obj;
    return newObj;
  }
};

var newArrowCheck = function (innerThis, boundThis) {
  if (innerThis !== boundThis) {
    throw new TypeError("Cannot instantiate an arrow function");
  }
};

var objectDestructuringEmpty = function (obj) {
  if (obj == null) throw new TypeError("Cannot destructure undefined");
};

var objectWithoutProperties = function (obj, keys) {
  var target = {};

  for (var i in obj) {
    if (keys.indexOf(i) >= 0) continue;
    if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
    target[i] = obj[i];
  }

  return target;
};

var possibleConstructorReturn = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && (typeof call === "object" || typeof call === "function") ? call : self;
};

var selfGlobal = typeof global === "undefined" ? self : global;

var set = function set(object, property, value, receiver) {
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent !== null) {
      set(parent, property, value, receiver);
    }
  } else if ("value" in desc && desc.writable) {
    desc.value = value;
  } else {
    var setter = desc.set;

    if (setter !== undefined) {
      setter.call(receiver, value);
    }
  }

  return value;
};

var slicedToArray = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();

var slicedToArrayLoose = function (arr, i) {
  if (Array.isArray(arr)) {
    return arr;
  } else if (Symbol.iterator in Object(arr)) {
    var _arr = [];

    for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
      _arr.push(_step.value);

      if (i && _arr.length === i) break;
    }

    return _arr;
  } else {
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
  }
};

var taggedTemplateLiteral = function (strings, raw) {
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
};

var taggedTemplateLiteralLoose = function (strings, raw) {
  strings.raw = raw;
  return strings;
};

var temporalRef = function (val, name, undef) {
  if (val === undef) {
    throw new ReferenceError(name + " is not defined - temporal dead zone");
  } else {
    return val;
  }
};

var temporalUndefined = {};

var toArray = function (arr) {
  return Array.isArray(arr) ? arr : Array.from(arr);
};

var toConsumableArray = function (arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

    return arr2;
  } else {
    return Array.from(arr);
  }
};



var babelHelpers$1 = Object.freeze({
  jsx: jsx,
  asyncToGenerator: asyncToGenerator,
  classCallCheck: classCallCheck,
  createClass: createClass,
  defineEnumerableProperties: defineEnumerableProperties,
  defaults: defaults,
  defineProperty: defineProperty$1,
  get: get,
  inherits: inherits,
  interopRequireDefault: interopRequireDefault,
  interopRequireWildcard: interopRequireWildcard,
  newArrowCheck: newArrowCheck,
  objectDestructuringEmpty: objectDestructuringEmpty,
  objectWithoutProperties: objectWithoutProperties,
  possibleConstructorReturn: possibleConstructorReturn,
  selfGlobal: selfGlobal,
  set: set,
  slicedToArray: slicedToArray,
  slicedToArrayLoose: slicedToArrayLoose,
  taggedTemplateLiteral: taggedTemplateLiteral,
  taggedTemplateLiteralLoose: taggedTemplateLiteralLoose,
  temporalRef: temporalRef,
  temporalUndefined: temporalUndefined,
  toArray: toArray,
  toConsumableArray: toConsumableArray,
  typeof: _typeof,
  extends: _extends,
  instanceof: _instanceof
});

var realDefineProp = function () {
    var sentinel = function sentinel() {};
    try {
        Object.defineProperty(sentinel, 'a', {
            get: function get() {
                return 1;
            }
        });
        Object.defineProperty(sentinel, 'prototype', { writable: false });
        return sentinel.a === 1 && sentinel.prototype instanceof Object;
    } catch (e) {
        return false;
    }
}();

// Need a workaround for getters in ES3
var es3 = !realDefineProp && !Object.prototype.__defineGetter__;

// We use this a lot (and need it for proto-less objects)
var hop = Object.prototype.hasOwnProperty;

// Naive defineProperty for compatibility
var defineProperty = realDefineProp ? Object.defineProperty : function (obj, name, desc) {
    if ('get' in desc && obj.__defineGetter__) obj.__defineGetter__(name, desc.get);else if (!hop.call(obj, name) || 'value' in desc) obj[name] = desc.value;
};

// Array.prototype.indexOf, as good as we need it to be
var arrIndexOf = Array.prototype.indexOf || function (search) {
    /*jshint validthis:true */
    var t = this;
    if (!t.length) return -1;

    for (var i = arguments[1] || 0, max = t.length; i < max; i++) {
        if (t[i] === search) return i;
    }

    return -1;
};

// Create an object with the specified prototype (2nd arg required for Record)
var objCreate = Object.create || function (proto, props) {
    var obj = void 0;

    function F() {}
    F.prototype = proto;
    obj = new F();

    for (var k in props) {
        if (hop.call(props, k)) defineProperty(obj, k, props[k]);
    }

    return obj;
};

// Snapshot some (hopefully still) native built-ins
var arrSlice = Array.prototype.slice;
var arrConcat = Array.prototype.concat;
var arrPush = Array.prototype.push;
var arrJoin = Array.prototype.join;
var arrShift = Array.prototype.shift;

// Naive Function.prototype.bind for compatibility
var fnBind = Function.prototype.bind || function (thisObj) {
    var fn = this,
        args = arrSlice.call(arguments, 1);

    // All our (presently) bound functions have either 1 or 0 arguments. By returning
    // different function signatures, we can pass some tests in ES3 environments
    if (fn.length === 1) {
        return function () {
            return fn.apply(thisObj, arrConcat.call(args, arrSlice.call(arguments)));
        };
    }
    return function () {
        return fn.apply(thisObj, arrConcat.call(args, arrSlice.call(arguments)));
    };
};

// Object housing internal properties for constructors
var internals = objCreate(null);

// Keep internal properties internal
var secret = Math.random();

// Helper functions
// ================

/**
 * A function to deal with the inaccuracy of calculating log10 in pre-ES6
 * JavaScript environments. Math.log(num) / Math.LN10 was responsible for
 * causing issue #62.
 */
function log10Floor(n) {
    // ES6 provides the more accurate Math.log10
    if (typeof Math.log10 === 'function') return Math.floor(Math.log10(n));

    var x = Math.round(Math.log(n) * Math.LOG10E);
    return x - (Number('1e' + x) > n);
}

/**
 * A map that doesn't contain Object in its prototype chain
 */
function Record(obj) {
    // Copy only own properties over unless this object is already a Record instance
    for (var k in obj) {
        if (obj instanceof Record || hop.call(obj, k)) defineProperty(this, k, { value: obj[k], enumerable: true, writable: true, configurable: true });
    }
}
Record.prototype = objCreate(null);

/**
 * An ordered list
 */
function List() {
    defineProperty(this, 'length', { writable: true, value: 0 });

    if (arguments.length) arrPush.apply(this, arrSlice.call(arguments));
}
List.prototype = objCreate(null);

/**
 * Constructs a regular expression to restore tainted RegExp properties
 */
function createRegExpRestore() {
    if (internals.disableRegExpRestore) {
        return function () {/* no-op */};
    }

    var regExpCache = {
        lastMatch: RegExp.lastMatch || '',
        leftContext: RegExp.leftContext,
        multiline: RegExp.multiline,
        input: RegExp.input
    },
        has = false;

    // Create a snapshot of all the 'captured' properties
    for (var i = 1; i <= 9; i++) {
        has = (regExpCache['$' + i] = RegExp['$' + i]) || has;
    }return function () {
        // Now we've snapshotted some properties, escape the lastMatch string
        var esc = /[.?*+^$[\]\\(){}|-]/g,
            lm = regExpCache.lastMatch.replace(esc, '\\$&'),
            reg = new List();

        // If any of the captured strings were non-empty, iterate over them all
        if (has) {
            for (var _i = 1; _i <= 9; _i++) {
                var m = regExpCache['$' + _i];

                // If it's empty, add an empty capturing group
                if (!m) lm = '()' + lm;

                // Else find the string in lm and escape & wrap it to capture it
                else {
                        m = m.replace(esc, '\\$&');
                        lm = lm.replace(m, '(' + m + ')');
                    }

                // Push it to the reg and chop lm to make sure further groups come after
                arrPush.call(reg, lm.slice(0, lm.indexOf('(') + 1));
                lm = lm.slice(lm.indexOf('(') + 1);
            }
        }

        var exprStr = arrJoin.call(reg, '') + lm;

        // Shorten the regex by replacing each part of the expression with a match
        // for a string of that exact length.  This is safe for the type of
        // expressions generated above, because the expression matches the whole
        // match string, so we know each group and each segment between capturing
        // groups can be matched by its length alone.
        exprStr = exprStr.replace(/(\\\(|\\\)|[^()])+/g, function (match) {
            return '[\\s\\S]{' + match.replace('\\', '').length + '}';
        });

        // Create the regular expression that will reconstruct the RegExp properties
        var expr = new RegExp(exprStr, regExpCache.multiline ? 'gm' : 'g');

        // Set the lastIndex of the generated expression to ensure that the match
        // is found in the correct index.
        expr.lastIndex = regExpCache.leftContext.length;

        expr.exec(regExpCache.input);
    };
}

/**
 * Mimics ES5's abstract ToObject() function
 */
function toObject(arg) {
    if (arg === null) throw new TypeError('Cannot convert null or undefined to object');

    if ((typeof arg === 'undefined' ? 'undefined' : babelHelpers$1['typeof'](arg)) === 'object') return arg;
    return Object(arg);
}

function toNumber(arg) {
    if (typeof arg === 'number') return arg;
    return Number(arg);
}

function toInteger(arg) {
    var number = toNumber(arg);
    if (isNaN(number)) return 0;
    if (number === +0 || number === -0 || number === +Infinity || number === -Infinity) return number;
    if (number < 0) return Math.floor(Math.abs(number)) * -1;
    return Math.floor(Math.abs(number));
}

function toLength(arg) {
    var len = toInteger(arg);
    if (len <= 0) return 0;
    if (len === Infinity) return Math.pow(2, 53) - 1;
    return Math.min(len, Math.pow(2, 53) - 1);
}

/**
 * Returns "internal" properties for an object
 */
function getInternalProperties(obj) {
    if (hop.call(obj, '__getInternalProperties')) return obj.__getInternalProperties(secret);

    return objCreate(null);
}

/**
* Defines regular expressions for various operations related to the BCP 47 syntax,
* as defined at http://tools.ietf.org/html/bcp47#section-2.1
*/

// extlang       = 3ALPHA              ; selected ISO 639 codes
//                 *2("-" 3ALPHA)      ; permanently reserved
var extlang = '[a-z]{3}(?:-[a-z]{3}){0,2}';

// language      = 2*3ALPHA            ; shortest ISO 639 code
//                 ["-" extlang]       ; sometimes followed by
//                                     ; extended language subtags
//               / 4ALPHA              ; or reserved for future use
//               / 5*8ALPHA            ; or registered language subtag
var language = '(?:[a-z]{2,3}(?:-' + extlang + ')?|[a-z]{4}|[a-z]{5,8})';

// script        = 4ALPHA              ; ISO 15924 code
var script = '[a-z]{4}';

// region        = 2ALPHA              ; ISO 3166-1 code
//               / 3DIGIT              ; UN M.49 code
var region = '(?:[a-z]{2}|\\d{3})';

// variant       = 5*8alphanum         ; registered variants
//               / (DIGIT 3alphanum)
var variant = '(?:[a-z0-9]{5,8}|\\d[a-z0-9]{3})';

//                                     ; Single alphanumerics
//                                     ; "x" reserved for private use
// singleton     = DIGIT               ; 0 - 9
//               / %x41-57             ; A - W
//               / %x59-5A             ; Y - Z
//               / %x61-77             ; a - w
//               / %x79-7A             ; y - z
var singleton = '[0-9a-wy-z]';

// extension     = singleton 1*("-" (2*8alphanum))
var extension = singleton + '(?:-[a-z0-9]{2,8})+';

// privateuse    = "x" 1*("-" (1*8alphanum))
var privateuse = 'x(?:-[a-z0-9]{1,8})+';

// irregular     = "en-GB-oed"         ; irregular tags do not match
//               / "i-ami"             ; the 'langtag' production and
//               / "i-bnn"             ; would not otherwise be
//               / "i-default"         ; considered 'well-formed'
//               / "i-enochian"        ; These tags are all valid,
//               / "i-hak"             ; but most are deprecated
//               / "i-klingon"         ; in favor of more modern
//               / "i-lux"             ; subtags or subtag
//               / "i-mingo"           ; combination
//               / "i-navajo"
//               / "i-pwn"
//               / "i-tao"
//               / "i-tay"
//               / "i-tsu"
//               / "sgn-BE-FR"
//               / "sgn-BE-NL"
//               / "sgn-CH-DE"
var irregular = '(?:en-GB-oed' + '|i-(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)' + '|sgn-(?:BE-FR|BE-NL|CH-DE))';

// regular       = "art-lojban"        ; these tags match the 'langtag'
//               / "cel-gaulish"       ; production, but their subtags
//               / "no-bok"            ; are not extended language
//               / "no-nyn"            ; or variant subtags: their meaning
//               / "zh-guoyu"          ; is defined by their registration
//               / "zh-hakka"          ; and all of these are deprecated
//               / "zh-min"            ; in favor of a more modern
//               / "zh-min-nan"        ; subtag or sequence of subtags
//               / "zh-xiang"
var regular = '(?:art-lojban|cel-gaulish|no-bok|no-nyn' + '|zh-(?:guoyu|hakka|min|min-nan|xiang))';

// grandfathered = irregular           ; non-redundant tags registered
//               / regular             ; during the RFC 3066 era
var grandfathered = '(?:' + irregular + '|' + regular + ')';

// langtag       = language
//                 ["-" script]
//                 ["-" region]
//                 *("-" variant)
//                 *("-" extension)
//                 ["-" privateuse]
var langtag = language + '(?:-' + script + ')?(?:-' + region + ')?(?:-' + variant + ')*(?:-' + extension + ')*(?:-' + privateuse + ')?';

// Language-Tag  = langtag             ; normal language tags
//               / privateuse          ; private use tag
//               / grandfathered       ; grandfathered tags
var expBCP47Syntax = RegExp('^(?:' + langtag + '|' + privateuse + '|' + grandfathered + ')$', 'i');

// Match duplicate variants in a language tag
var expVariantDupes = RegExp('^(?!x).*?-(' + variant + ')-(?:\\w{4,8}-(?!x-))*\\1\\b', 'i');

// Match duplicate singletons in a language tag (except in private use)
var expSingletonDupes = RegExp('^(?!x).*?-(' + singleton + ')-(?:\\w+-(?!x-))*\\1\\b', 'i');

// Match all extension sequences
var expExtSequences = RegExp('-' + extension, 'ig');

// Default locale is the first-added locale data for us
var defaultLocale = void 0;
function setDefaultLocale(locale) {
    defaultLocale = locale;
}

// IANA Subtag Registry redundant tag and subtag maps
var redundantTags = {
    tags: {
        "art-lojban": "jbo",
        "i-ami": "ami",
        "i-bnn": "bnn",
        "i-hak": "hak",
        "i-klingon": "tlh",
        "i-lux": "lb",
        "i-navajo": "nv",
        "i-pwn": "pwn",
        "i-tao": "tao",
        "i-tay": "tay",
        "i-tsu": "tsu",
        "no-bok": "nb",
        "no-nyn": "nn",
        "sgn-BE-FR": "sfb",
        "sgn-BE-NL": "vgt",
        "sgn-CH-DE": "sgg",
        "zh-guoyu": "cmn",
        "zh-hakka": "hak",
        "zh-min-nan": "nan",
        "zh-xiang": "hsn",
        "sgn-BR": "bzs",
        "sgn-CO": "csn",
        "sgn-DE": "gsg",
        "sgn-DK": "dsl",
        "sgn-ES": "ssp",
        "sgn-FR": "fsl",
        "sgn-GB": "bfi",
        "sgn-GR": "gss",
        "sgn-IE": "isg",
        "sgn-IT": "ise",
        "sgn-JP": "jsl",
        "sgn-MX": "mfs",
        "sgn-NI": "ncs",
        "sgn-NL": "dse",
        "sgn-NO": "nsl",
        "sgn-PT": "psr",
        "sgn-SE": "swl",
        "sgn-US": "ase",
        "sgn-ZA": "sfs",
        "zh-cmn": "cmn",
        "zh-cmn-Hans": "cmn-Hans",
        "zh-cmn-Hant": "cmn-Hant",
        "zh-gan": "gan",
        "zh-wuu": "wuu",
        "zh-yue": "yue"
    },
    subtags: {
        BU: "MM",
        DD: "DE",
        FX: "FR",
        TP: "TL",
        YD: "YE",
        ZR: "CD",
        heploc: "alalc97",
        'in': "id",
        iw: "he",
        ji: "yi",
        jw: "jv",
        mo: "ro",
        ayx: "nun",
        bjd: "drl",
        ccq: "rki",
        cjr: "mom",
        cka: "cmr",
        cmk: "xch",
        drh: "khk",
        drw: "prs",
        gav: "dev",
        hrr: "jal",
        ibi: "opa",
        kgh: "kml",
        lcq: "ppr",
        mst: "mry",
        myt: "mry",
        sca: "hle",
        tie: "ras",
        tkk: "twm",
        tlw: "weo",
        tnf: "prs",
        ybd: "rki",
        yma: "lrr"
    },
    extLang: {
        aao: ["aao", "ar"],
        abh: ["abh", "ar"],
        abv: ["abv", "ar"],
        acm: ["acm", "ar"],
        acq: ["acq", "ar"],
        acw: ["acw", "ar"],
        acx: ["acx", "ar"],
        acy: ["acy", "ar"],
        adf: ["adf", "ar"],
        ads: ["ads", "sgn"],
        aeb: ["aeb", "ar"],
        aec: ["aec", "ar"],
        aed: ["aed", "sgn"],
        aen: ["aen", "sgn"],
        afb: ["afb", "ar"],
        afg: ["afg", "sgn"],
        ajp: ["ajp", "ar"],
        apc: ["apc", "ar"],
        apd: ["apd", "ar"],
        arb: ["arb", "ar"],
        arq: ["arq", "ar"],
        ars: ["ars", "ar"],
        ary: ["ary", "ar"],
        arz: ["arz", "ar"],
        ase: ["ase", "sgn"],
        asf: ["asf", "sgn"],
        asp: ["asp", "sgn"],
        asq: ["asq", "sgn"],
        asw: ["asw", "sgn"],
        auz: ["auz", "ar"],
        avl: ["avl", "ar"],
        ayh: ["ayh", "ar"],
        ayl: ["ayl", "ar"],
        ayn: ["ayn", "ar"],
        ayp: ["ayp", "ar"],
        bbz: ["bbz", "ar"],
        bfi: ["bfi", "sgn"],
        bfk: ["bfk", "sgn"],
        bjn: ["bjn", "ms"],
        bog: ["bog", "sgn"],
        bqn: ["bqn", "sgn"],
        bqy: ["bqy", "sgn"],
        btj: ["btj", "ms"],
        bve: ["bve", "ms"],
        bvl: ["bvl", "sgn"],
        bvu: ["bvu", "ms"],
        bzs: ["bzs", "sgn"],
        cdo: ["cdo", "zh"],
        cds: ["cds", "sgn"],
        cjy: ["cjy", "zh"],
        cmn: ["cmn", "zh"],
        coa: ["coa", "ms"],
        cpx: ["cpx", "zh"],
        csc: ["csc", "sgn"],
        csd: ["csd", "sgn"],
        cse: ["cse", "sgn"],
        csf: ["csf", "sgn"],
        csg: ["csg", "sgn"],
        csl: ["csl", "sgn"],
        csn: ["csn", "sgn"],
        csq: ["csq", "sgn"],
        csr: ["csr", "sgn"],
        czh: ["czh", "zh"],
        czo: ["czo", "zh"],
        doq: ["doq", "sgn"],
        dse: ["dse", "sgn"],
        dsl: ["dsl", "sgn"],
        dup: ["dup", "ms"],
        ecs: ["ecs", "sgn"],
        esl: ["esl", "sgn"],
        esn: ["esn", "sgn"],
        eso: ["eso", "sgn"],
        eth: ["eth", "sgn"],
        fcs: ["fcs", "sgn"],
        fse: ["fse", "sgn"],
        fsl: ["fsl", "sgn"],
        fss: ["fss", "sgn"],
        gan: ["gan", "zh"],
        gds: ["gds", "sgn"],
        gom: ["gom", "kok"],
        gse: ["gse", "sgn"],
        gsg: ["gsg", "sgn"],
        gsm: ["gsm", "sgn"],
        gss: ["gss", "sgn"],
        gus: ["gus", "sgn"],
        hab: ["hab", "sgn"],
        haf: ["haf", "sgn"],
        hak: ["hak", "zh"],
        hds: ["hds", "sgn"],
        hji: ["hji", "ms"],
        hks: ["hks", "sgn"],
        hos: ["hos", "sgn"],
        hps: ["hps", "sgn"],
        hsh: ["hsh", "sgn"],
        hsl: ["hsl", "sgn"],
        hsn: ["hsn", "zh"],
        icl: ["icl", "sgn"],
        ils: ["ils", "sgn"],
        inl: ["inl", "sgn"],
        ins: ["ins", "sgn"],
        ise: ["ise", "sgn"],
        isg: ["isg", "sgn"],
        isr: ["isr", "sgn"],
        jak: ["jak", "ms"],
        jax: ["jax", "ms"],
        jcs: ["jcs", "sgn"],
        jhs: ["jhs", "sgn"],
        jls: ["jls", "sgn"],
        jos: ["jos", "sgn"],
        jsl: ["jsl", "sgn"],
        jus: ["jus", "sgn"],
        kgi: ["kgi", "sgn"],
        knn: ["knn", "kok"],
        kvb: ["kvb", "ms"],
        kvk: ["kvk", "sgn"],
        kvr: ["kvr", "ms"],
        kxd: ["kxd", "ms"],
        lbs: ["lbs", "sgn"],
        lce: ["lce", "ms"],
        lcf: ["lcf", "ms"],
        liw: ["liw", "ms"],
        lls: ["lls", "sgn"],
        lsg: ["lsg", "sgn"],
        lsl: ["lsl", "sgn"],
        lso: ["lso", "sgn"],
        lsp: ["lsp", "sgn"],
        lst: ["lst", "sgn"],
        lsy: ["lsy", "sgn"],
        ltg: ["ltg", "lv"],
        lvs: ["lvs", "lv"],
        lzh: ["lzh", "zh"],
        max: ["max", "ms"],
        mdl: ["mdl", "sgn"],
        meo: ["meo", "ms"],
        mfa: ["mfa", "ms"],
        mfb: ["mfb", "ms"],
        mfs: ["mfs", "sgn"],
        min: ["min", "ms"],
        mnp: ["mnp", "zh"],
        mqg: ["mqg", "ms"],
        mre: ["mre", "sgn"],
        msd: ["msd", "sgn"],
        msi: ["msi", "ms"],
        msr: ["msr", "sgn"],
        mui: ["mui", "ms"],
        mzc: ["mzc", "sgn"],
        mzg: ["mzg", "sgn"],
        mzy: ["mzy", "sgn"],
        nan: ["nan", "zh"],
        nbs: ["nbs", "sgn"],
        ncs: ["ncs", "sgn"],
        nsi: ["nsi", "sgn"],
        nsl: ["nsl", "sgn"],
        nsp: ["nsp", "sgn"],
        nsr: ["nsr", "sgn"],
        nzs: ["nzs", "sgn"],
        okl: ["okl", "sgn"],
        orn: ["orn", "ms"],
        ors: ["ors", "ms"],
        pel: ["pel", "ms"],
        pga: ["pga", "ar"],
        pks: ["pks", "sgn"],
        prl: ["prl", "sgn"],
        prz: ["prz", "sgn"],
        psc: ["psc", "sgn"],
        psd: ["psd", "sgn"],
        pse: ["pse", "ms"],
        psg: ["psg", "sgn"],
        psl: ["psl", "sgn"],
        pso: ["pso", "sgn"],
        psp: ["psp", "sgn"],
        psr: ["psr", "sgn"],
        pys: ["pys", "sgn"],
        rms: ["rms", "sgn"],
        rsi: ["rsi", "sgn"],
        rsl: ["rsl", "sgn"],
        sdl: ["sdl", "sgn"],
        sfb: ["sfb", "sgn"],
        sfs: ["sfs", "sgn"],
        sgg: ["sgg", "sgn"],
        sgx: ["sgx", "sgn"],
        shu: ["shu", "ar"],
        slf: ["slf", "sgn"],
        sls: ["sls", "sgn"],
        sqk: ["sqk", "sgn"],
        sqs: ["sqs", "sgn"],
        ssh: ["ssh", "ar"],
        ssp: ["ssp", "sgn"],
        ssr: ["ssr", "sgn"],
        svk: ["svk", "sgn"],
        swc: ["swc", "sw"],
        swh: ["swh", "sw"],
        swl: ["swl", "sgn"],
        syy: ["syy", "sgn"],
        tmw: ["tmw", "ms"],
        tse: ["tse", "sgn"],
        tsm: ["tsm", "sgn"],
        tsq: ["tsq", "sgn"],
        tss: ["tss", "sgn"],
        tsy: ["tsy", "sgn"],
        tza: ["tza", "sgn"],
        ugn: ["ugn", "sgn"],
        ugy: ["ugy", "sgn"],
        ukl: ["ukl", "sgn"],
        uks: ["uks", "sgn"],
        urk: ["urk", "ms"],
        uzn: ["uzn", "uz"],
        uzs: ["uzs", "uz"],
        vgt: ["vgt", "sgn"],
        vkk: ["vkk", "ms"],
        vkt: ["vkt", "ms"],
        vsi: ["vsi", "sgn"],
        vsl: ["vsl", "sgn"],
        vsv: ["vsv", "sgn"],
        wuu: ["wuu", "zh"],
        xki: ["xki", "sgn"],
        xml: ["xml", "sgn"],
        xmm: ["xmm", "ms"],
        xms: ["xms", "sgn"],
        yds: ["yds", "sgn"],
        ysl: ["ysl", "sgn"],
        yue: ["yue", "zh"],
        zib: ["zib", "sgn"],
        zlm: ["zlm", "ms"],
        zmi: ["zmi", "ms"],
        zsl: ["zsl", "sgn"],
        zsm: ["zsm", "ms"]
    }
};

/**
 * Convert only a-z to uppercase as per section 6.1 of the spec
 */
function toLatinUpperCase(str) {
    var i = str.length;

    while (i--) {
        var ch = str.charAt(i);

        if (ch >= "a" && ch <= "z") str = str.slice(0, i) + ch.toUpperCase() + str.slice(i + 1);
    }

    return str;
}

/**
 * The IsStructurallyValidLanguageTag abstract operation verifies that the locale
 * argument (which must be a String value)
 *
 * - represents a well-formed BCP 47 language tag as specified in RFC 5646 section
 *   2.1, or successor,
 * - does not include duplicate variant subtags, and
 * - does not include duplicate singleton subtags.
 *
 * The abstract operation returns true if locale can be generated from the ABNF
 * grammar in section 2.1 of the RFC, starting with Language-Tag, and does not
 * contain duplicate variant or singleton subtags (other than as a private use
 * subtag). It returns false otherwise. Terminal value characters in the grammar are
 * interpreted as the Unicode equivalents of the ASCII octet values given.
 */
function /* 6.2.2 */IsStructurallyValidLanguageTag(locale) {
    // represents a well-formed BCP 47 language tag as specified in RFC 5646
    if (!expBCP47Syntax.test(locale)) return false;

    // does not include duplicate variant subtags, and
    if (expVariantDupes.test(locale)) return false;

    // does not include duplicate singleton subtags.
    if (expSingletonDupes.test(locale)) return false;

    return true;
}

/**
 * The CanonicalizeLanguageTag abstract operation returns the canonical and case-
 * regularized form of the locale argument (which must be a String value that is
 * a structurally valid BCP 47 language tag as verified by the
 * IsStructurallyValidLanguageTag abstract operation). It takes the steps
 * specified in RFC 5646 section 4.5, or successor, to bring the language tag
 * into canonical form, and to regularize the case of the subtags, but does not
 * take the steps to bring a language tag into “extlang form” and to reorder
 * variant subtags.

 * The specifications for extensions to BCP 47 language tags, such as RFC 6067,
 * may include canonicalization rules for the extension subtag sequences they
 * define that go beyond the canonicalization rules of RFC 5646 section 4.5.
 * Implementations are allowed, but not required, to apply these additional rules.
 */
function /* 6.2.3 */CanonicalizeLanguageTag(locale) {
    var match = void 0,
        parts = void 0;

    // A language tag is in 'canonical form' when the tag is well-formed
    // according to the rules in Sections 2.1 and 2.2

    // Section 2.1 says all subtags use lowercase...
    locale = locale.toLowerCase();

    // ...with 2 exceptions: 'two-letter and four-letter subtags that neither
    // appear at the start of the tag nor occur after singletons.  Such two-letter
    // subtags are all uppercase (as in the tags "en-CA-x-ca" or "sgn-BE-FR") and
    // four-letter subtags are titlecase (as in the tag "az-Latn-x-latn").
    parts = locale.split('-');
    for (var i = 1, max = parts.length; i < max; i++) {
        // Two-letter subtags are all uppercase
        if (parts[i].length === 2) parts[i] = parts[i].toUpperCase();

        // Four-letter subtags are titlecase
        else if (parts[i].length === 4) parts[i] = parts[i].charAt(0).toUpperCase() + parts[i].slice(1);

            // Is it a singleton?
            else if (parts[i].length === 1 && parts[i] !== 'x') break;
    }
    locale = arrJoin.call(parts, '-');

    // The steps laid out in RFC 5646 section 4.5 are as follows:

    // 1.  Extension sequences are ordered into case-insensitive ASCII order
    //     by singleton subtag.
    if ((match = locale.match(expExtSequences)) && match.length > 1) {
        // The built-in sort() sorts by ASCII order, so use that
        match.sort();

        // Replace all extensions with the joined, sorted array
        locale = locale.replace(RegExp('(?:' + expExtSequences.source + ')+', 'i'), arrJoin.call(match, ''));
    }

    // 2.  Redundant or grandfathered tags are replaced by their 'Preferred-
    //     Value', if there is one.
    if (hop.call(redundantTags.tags, locale)) locale = redundantTags.tags[locale];

    // 3.  Subtags are replaced by their 'Preferred-Value', if there is one.
    //     For extlangs, the original primary language subtag is also
    //     replaced if there is a primary language subtag in the 'Preferred-
    //     Value'.
    parts = locale.split('-');

    for (var _i = 1, _max = parts.length; _i < _max; _i++) {
        if (hop.call(redundantTags.subtags, parts[_i])) parts[_i] = redundantTags.subtags[parts[_i]];else if (hop.call(redundantTags.extLang, parts[_i])) {
            parts[_i] = redundantTags.extLang[parts[_i]][0];

            // For extlang tags, the prefix needs to be removed if it is redundant
            if (_i === 1 && redundantTags.extLang[parts[1]][1] === parts[0]) {
                parts = arrSlice.call(parts, _i++);
                _max -= 1;
            }
        }
    }

    return arrJoin.call(parts, '-');
}

/**
 * The DefaultLocale abstract operation returns a String value representing the
 * structurally valid (6.2.2) and canonicalized (6.2.3) BCP 47 language tag for the
 * host environment’s current locale.
 */
function /* 6.2.4 */DefaultLocale() {
    return defaultLocale;
}

// Sect 6.3 Currency Codes
// =======================

var expCurrencyCode = /^[A-Z]{3}$/;

/**
 * The IsWellFormedCurrencyCode abstract operation verifies that the currency argument
 * (after conversion to a String value) represents a well-formed 3-letter ISO currency
 * code. The following steps are taken:
 */
function /* 6.3.1 */IsWellFormedCurrencyCode(currency) {
    // 1. Let `c` be ToString(currency)
    var c = String(currency);

    // 2. Let `normalized` be the result of mapping c to upper case as described
    //    in 6.1.
    var normalized = toLatinUpperCase(c);

    // 3. If the string length of normalized is not 3, return false.
    // 4. If normalized contains any character that is not in the range "A" to "Z"
    //    (U+0041 to U+005A), return false.
    if (expCurrencyCode.test(normalized) === false) return false;

    // 5. Return true
    return true;
}

var expUnicodeExSeq = /-u(?:-[0-9a-z]{2,8})+/gi; // See `extension` below

function /* 9.2.1 */CanonicalizeLocaleList(locales) {
    // The abstract operation CanonicalizeLocaleList takes the following steps:

    // 1. If locales is undefined, then a. Return a new empty List
    if (locales === undefined) return new List();

    // 2. Let seen be a new empty List.
    var seen = new List();

    // 3. If locales is a String value, then
    //    a. Let locales be a new array created as if by the expression new
    //    Array(locales) where Array is the standard built-in constructor with
    //    that name and locales is the value of locales.
    locales = typeof locales === 'string' ? [locales] : locales;

    // 4. Let O be ToObject(locales).
    var O = toObject(locales);

    // 5. Let lenValue be the result of calling the [[Get]] internal method of
    //    O with the argument "length".
    // 6. Let len be ToUint32(lenValue).
    var len = toLength(O.length);

    // 7. Let k be 0.
    var k = 0;

    // 8. Repeat, while k < len
    while (k < len) {
        // a. Let Pk be ToString(k).
        var Pk = String(k);

        // b. Let kPresent be the result of calling the [[HasProperty]] internal
        //    method of O with argument Pk.
        var kPresent = Pk in O;

        // c. If kPresent is true, then
        if (kPresent) {
            // i. Let kValue be the result of calling the [[Get]] internal
            //     method of O with argument Pk.
            var kValue = O[Pk];

            // ii. If the type of kValue is not String or Object, then throw a
            //     TypeError exception.
            if (kValue === null || typeof kValue !== 'string' && (typeof kValue === "undefined" ? "undefined" : babelHelpers$1["typeof"](kValue)) !== 'object') throw new TypeError('String or Object type expected');

            // iii. Let tag be ToString(kValue).
            var tag = String(kValue);

            // iv. If the result of calling the abstract operation
            //     IsStructurallyValidLanguageTag (defined in 6.2.2), passing tag as
            //     the argument, is false, then throw a RangeError exception.
            if (!IsStructurallyValidLanguageTag(tag)) throw new RangeError("'" + tag + "' is not a structurally valid language tag");

            // v. Let tag be the result of calling the abstract operation
            //    CanonicalizeLanguageTag (defined in 6.2.3), passing tag as the
            //    argument.
            tag = CanonicalizeLanguageTag(tag);

            // vi. If tag is not an element of seen, then append tag as the last
            //     element of seen.
            if (arrIndexOf.call(seen, tag) === -1) arrPush.call(seen, tag);
        }

        // d. Increase k by 1.
        k++;
    }

    // 9. Return seen.
    return seen;
}

/**
 * The BestAvailableLocale abstract operation compares the provided argument
 * locale, which must be a String value with a structurally valid and
 * canonicalized BCP 47 language tag, against the locales in availableLocales and
 * returns either the longest non-empty prefix of locale that is an element of
 * availableLocales, or undefined if there is no such element. It uses the
 * fallback mechanism of RFC 4647, section 3.4. The following steps are taken:
 */
function /* 9.2.2 */BestAvailableLocale(availableLocales, locale) {
    // 1. Let candidate be locale
    var candidate = locale;

    // 2. Repeat
    while (candidate) {
        // a. If availableLocales contains an element equal to candidate, then return
        // candidate.
        if (arrIndexOf.call(availableLocales, candidate) > -1) return candidate;

        // b. Let pos be the character index of the last occurrence of "-"
        // (U+002D) within candidate. If that character does not occur, return
        // undefined.
        var pos = candidate.lastIndexOf('-');

        if (pos < 0) return;

        // c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate,
        //    then decrease pos by 2.
        if (pos >= 2 && candidate.charAt(pos - 2) === '-') pos -= 2;

        // d. Let candidate be the substring of candidate from position 0, inclusive,
        //    to position pos, exclusive.
        candidate = candidate.substring(0, pos);
    }
}

/**
 * The LookupMatcher abstract operation compares requestedLocales, which must be
 * a List as returned by CanonicalizeLocaleList, against the locales in
 * availableLocales and determines the best available language to meet the
 * request. The following steps are taken:
 */
function /* 9.2.3 */LookupMatcher(availableLocales, requestedLocales) {
    // 1. Let i be 0.
    var i = 0;

    // 2. Let len be the number of elements in requestedLocales.
    var len = requestedLocales.length;

    // 3. Let availableLocale be undefined.
    var availableLocale = void 0;

    var locale = void 0,
        noExtensionsLocale = void 0;

    // 4. Repeat while i < len and availableLocale is undefined:
    while (i < len && !availableLocale) {
        // a. Let locale be the element of requestedLocales at 0-origined list
        //    position i.
        locale = requestedLocales[i];

        // b. Let noExtensionsLocale be the String value that is locale with all
        //    Unicode locale extension sequences removed.
        noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');

        // c. Let availableLocale be the result of calling the
        //    BestAvailableLocale abstract operation (defined in 9.2.2) with
        //    arguments availableLocales and noExtensionsLocale.
        availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);

        // d. Increase i by 1.
        i++;
    }

    // 5. Let result be a new Record.
    var result = new Record();

    // 6. If availableLocale is not undefined, then
    if (availableLocale !== undefined) {
        // a. Set result.[[locale]] to availableLocale.
        result['[[locale]]'] = availableLocale;

        // b. If locale and noExtensionsLocale are not the same String value, then
        if (String(locale) !== String(noExtensionsLocale)) {
            // i. Let extension be the String value consisting of the first
            //    substring of locale that is a Unicode locale extension sequence.
            var extension = locale.match(expUnicodeExSeq)[0];

            // ii. Let extensionIndex be the character position of the initial
            //     "-" of the first Unicode locale extension sequence within locale.
            var extensionIndex = locale.indexOf('-u-');

            // iii. Set result.[[extension]] to extension.
            result['[[extension]]'] = extension;

            // iv. Set result.[[extensionIndex]] to extensionIndex.
            result['[[extensionIndex]]'] = extensionIndex;
        }
    }
    // 7. Else
    else
        // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract
        //    operation (defined in 6.2.4).
        result['[[locale]]'] = DefaultLocale();

    // 8. Return result
    return result;
}

/**
 * The BestFitMatcher abstract operation compares requestedLocales, which must be
 * a List as returned by CanonicalizeLocaleList, against the locales in
 * availableLocales and determines the best available language to meet the
 * request. The algorithm is implementation dependent, but should produce results
 * that a typical user of the requested locales would perceive as at least as
 * good as those produced by the LookupMatcher abstract operation. Options
 * specified through Unicode locale extension sequences must be ignored by the
 * algorithm. Information about such subsequences is returned separately.
 * The abstract operation returns a record with a [[locale]] field, whose value
 * is the language tag of the selected locale, which must be an element of
 * availableLocales. If the language tag of the request locale that led to the
 * selected locale contained a Unicode locale extension sequence, then the
 * returned record also contains an [[extension]] field whose value is the first
 * Unicode locale extension sequence, and an [[extensionIndex]] field whose value
 * is the index of the first Unicode locale extension sequence within the request
 * locale language tag.
 */
function /* 9.2.4 */BestFitMatcher(availableLocales, requestedLocales) {
    return LookupMatcher(availableLocales, requestedLocales);
}

/**
 * The ResolveLocale abstract operation compares a BCP 47 language priority list
 * requestedLocales against the locales in availableLocales and determines the
 * best available language to meet the request. availableLocales and
 * requestedLocales must be provided as List values, options as a Record.
 */
function /* 9.2.5 */ResolveLocale(availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) {
    if (availableLocales.length === 0) {
        throw new ReferenceError('No locale data has been provided for this object yet.');
    }

    // The following steps are taken:
    // 1. Let matcher be the value of options.[[localeMatcher]].
    var matcher = options['[[localeMatcher]]'];

    var r = void 0;

    // 2. If matcher is "lookup", then
    if (matcher === 'lookup')
        // a. Let r be the result of calling the LookupMatcher abstract operation
        //    (defined in 9.2.3) with arguments availableLocales and
        //    requestedLocales.
        r = LookupMatcher(availableLocales, requestedLocales);

        // 3. Else
    else
        // a. Let r be the result of calling the BestFitMatcher abstract
        //    operation (defined in 9.2.4) with arguments availableLocales and
        //    requestedLocales.
        r = BestFitMatcher(availableLocales, requestedLocales);

    // 4. Let foundLocale be the value of r.[[locale]].
    var foundLocale = r['[[locale]]'];

    var extensionSubtags = void 0,
        extensionSubtagsLength = void 0;

    // 5. If r has an [[extension]] field, then
    if (hop.call(r, '[[extension]]')) {
        // a. Let extension be the value of r.[[extension]].
        var extension = r['[[extension]]'];
        // b. Let split be the standard built-in function object defined in ES5,
        //    15.5.4.14.
        var split = String.prototype.split;
        // c. Let extensionSubtags be the result of calling the [[Call]] internal
        //    method of split with extension as the this value and an argument
        //    list containing the single item "-".
        extensionSubtags = split.call(extension, '-');
        // d. Let extensionSubtagsLength be the result of calling the [[Get]]
        //    internal method of extensionSubtags with argument "length".
        extensionSubtagsLength = extensionSubtags.length;
    }

    // 6. Let result be a new Record.
    var result = new Record();

    // 7. Set result.[[dataLocale]] to foundLocale.
    result['[[dataLocale]]'] = foundLocale;

    // 8. Let supportedExtension be "-u".
    var supportedExtension = '-u';
    // 9. Let i be 0.
    var i = 0;
    // 10. Let len be the result of calling the [[Get]] internal method of
    //     relevantExtensionKeys with argument "length".
    var len = relevantExtensionKeys.length;

    // 11 Repeat while i < len:
    while (i < len) {
        // a. Let key be the result of calling the [[Get]] internal method of
        //    relevantExtensionKeys with argument ToString(i).
        var key = relevantExtensionKeys[i];
        // b. Let foundLocaleData be the result of calling the [[Get]] internal
        //    method of localeData with the argument foundLocale.
        var foundLocaleData = localeData[foundLocale];
        // c. Let keyLocaleData be the result of calling the [[Get]] internal
        //    method of foundLocaleData with the argument key.
        var keyLocaleData = foundLocaleData[key];
        // d. Let value be the result of calling the [[Get]] internal method of
        //    keyLocaleData with argument "0".
        var value = keyLocaleData['0'];
        // e. Let supportedExtensionAddition be "".
        var supportedExtensionAddition = '';
        // f. Let indexOf be the standard built-in function object defined in
        //    ES5, 15.4.4.14.
        var indexOf = arrIndexOf;

        // g. If extensionSubtags is not undefined, then
        if (extensionSubtags !== undefined) {
            // i. Let keyPos be the result of calling the [[Call]] internal
            //    method of indexOf with extensionSubtags as the this value and
            // an argument list containing the single item key.
            var keyPos = indexOf.call(extensionSubtags, key);

            // ii. If keyPos ≠ -1, then
            if (keyPos !== -1) {
                // 1. If keyPos + 1 < extensionSubtagsLength and the length of the
                //    result of calling the [[Get]] internal method of
                //    extensionSubtags with argument ToString(keyPos +1) is greater
                //    than 2, then
                if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) {
                    // a. Let requestedValue be the result of calling the [[Get]]
                    //    internal method of extensionSubtags with argument
                    //    ToString(keyPos + 1).
                    var requestedValue = extensionSubtags[keyPos + 1];
                    // b. Let valuePos be the result of calling the [[Call]]
                    //    internal method of indexOf with keyLocaleData as the
                    //    this value and an argument list containing the single
                    //    item requestedValue.
                    var valuePos = indexOf.call(keyLocaleData, requestedValue);

                    // c. If valuePos ≠ -1, then
                    if (valuePos !== -1) {
                        // i. Let value be requestedValue.
                        value = requestedValue,
                        // ii. Let supportedExtensionAddition be the
                        //     concatenation of "-", key, "-", and value.
                        supportedExtensionAddition = '-' + key + '-' + value;
                    }
                }
                // 2. Else
                else {
                        // a. Let valuePos be the result of calling the [[Call]]
                        // internal method of indexOf with keyLocaleData as the this
                        // value and an argument list containing the single item
                        // "true".
                        var _valuePos = indexOf(keyLocaleData, 'true');

                        // b. If valuePos ≠ -1, then
                        if (_valuePos !== -1)
                            // i. Let value be "true".
                            value = 'true';
                    }
            }
        }
        // h. If options has a field [[<key>]], then
        if (hop.call(options, '[[' + key + ']]')) {
            // i. Let optionsValue be the value of options.[[<key>]].
            var optionsValue = options['[[' + key + ']]'];

            // ii. If the result of calling the [[Call]] internal method of indexOf
            //     with keyLocaleData as the this value and an argument list
            //     containing the single item optionsValue is not -1, then
            if (indexOf.call(keyLocaleData, optionsValue) !== -1) {
                // 1. If optionsValue is not equal to value, then
                if (optionsValue !== value) {
                    // a. Let value be optionsValue.
                    value = optionsValue;
                    // b. Let supportedExtensionAddition be "".
                    supportedExtensionAddition = '';
                }
            }
        }
        // i. Set result.[[<key>]] to value.
        result['[[' + key + ']]'] = value;

        // j. Append supportedExtensionAddition to supportedExtension.
        supportedExtension += supportedExtensionAddition;

        // k. Increase i by 1.
        i++;
    }
    // 12. If the length of supportedExtension is greater than 2, then
    if (supportedExtension.length > 2) {
        // a.
        var privateIndex = foundLocale.indexOf("-x-");
        // b.
        if (privateIndex === -1) {
            // i.
            foundLocale = foundLocale + supportedExtension;
        }
        // c.
        else {
                // i.
                var preExtension = foundLocale.substring(0, privateIndex);
                // ii.
                var postExtension = foundLocale.substring(privateIndex);
                // iii.
                foundLocale = preExtension + supportedExtension + postExtension;
            }
        // d. asserting - skipping
        // e.
        foundLocale = CanonicalizeLanguageTag(foundLocale);
    }
    // 13. Set result.[[locale]] to foundLocale.
    result['[[locale]]'] = foundLocale;

    // 14. Return result.
    return result;
}

/**
 * The LookupSupportedLocales abstract operation returns the subset of the
 * provided BCP 47 language priority list requestedLocales for which
 * availableLocales has a matching locale when using the BCP 47 Lookup algorithm.
 * Locales appear in the same order in the returned list as in requestedLocales.
 * The following steps are taken:
 */
function /* 9.2.6 */LookupSupportedLocales(availableLocales, requestedLocales) {
    // 1. Let len be the number of elements in requestedLocales.
    var len = requestedLocales.length;
    // 2. Let subset be a new empty List.
    var subset = new List();
    // 3. Let k be 0.
    var k = 0;

    // 4. Repeat while k < len
    while (k < len) {
        // a. Let locale be the element of requestedLocales at 0-origined list
        //    position k.
        var locale = requestedLocales[k];
        // b. Let noExtensionsLocale be the String value that is locale with all
        //    Unicode locale extension sequences removed.
        var noExtensionsLocale = String(locale).replace(expUnicodeExSeq, '');
        // c. Let availableLocale be the result of calling the
        //    BestAvailableLocale abstract operation (defined in 9.2.2) with
        //    arguments availableLocales and noExtensionsLocale.
        var availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale);

        // d. If availableLocale is not undefined, then append locale to the end of
        //    subset.
        if (availableLocale !== undefined) arrPush.call(subset, locale);

        // e. Increment k by 1.
        k++;
    }

    // 5. Let subsetArray be a new Array object whose elements are the same
    //    values in the same order as the elements of subset.
    var subsetArray = arrSlice.call(subset);

    // 6. Return subsetArray.
    return subsetArray;
}

/**
 * The BestFitSupportedLocales abstract operation returns the subset of the
 * provided BCP 47 language priority list requestedLocales for which
 * availableLocales has a matching locale when using the Best Fit Matcher
 * algorithm. Locales appear in the same order in the returned list as in
 * requestedLocales. The steps taken are implementation dependent.
 */
function /*9.2.7 */BestFitSupportedLocales(availableLocales, requestedLocales) {
    // ###TODO: implement this function as described by the specification###
    return LookupSupportedLocales(availableLocales, requestedLocales);
}

/**
 * The SupportedLocales abstract operation returns the subset of the provided BCP
 * 47 language priority list requestedLocales for which availableLocales has a
 * matching locale. Two algorithms are available to match the locales: the Lookup
 * algorithm described in RFC 4647 section 3.4, and an implementation dependent
 * best-fit algorithm. Locales appear in the same order in the returned list as
 * in requestedLocales. The following steps are taken:
 */
function /*9.2.8 */SupportedLocales(availableLocales, requestedLocales, options) {
    var matcher = void 0,
        subset = void 0;

    // 1. If options is not undefined, then
    if (options !== undefined) {
        // a. Let options be ToObject(options).
        options = new Record(toObject(options));
        // b. Let matcher be the result of calling the [[Get]] internal method of
        //    options with argument "localeMatcher".
        matcher = options.localeMatcher;

        // c. If matcher is not undefined, then
        if (matcher !== undefined) {
            // i. Let matcher be ToString(matcher).
            matcher = String(matcher);

            // ii. If matcher is not "lookup" or "best fit", then throw a RangeError
            //     exception.
            if (matcher !== 'lookup' && matcher !== 'best fit') throw new RangeError('matcher should be "lookup" or "best fit"');
        }
    }
    // 2. If matcher is undefined or "best fit", then
    if (matcher === undefined || matcher === 'best fit')
        // a. Let subset be the result of calling the BestFitSupportedLocales
        //    abstract operation (defined in 9.2.7) with arguments
        //    availableLocales and requestedLocales.
        subset = BestFitSupportedLocales(availableLocales, requestedLocales);
        // 3. Else
    else
        // a. Let subset be the result of calling the LookupSupportedLocales
        //    abstract operation (defined in 9.2.6) with arguments
        //    availableLocales and requestedLocales.
        subset = LookupSupportedLocales(availableLocales, requestedLocales);

    // 4. For each named own property name P of subset,
    for (var P in subset) {
        if (!hop.call(subset, P)) continue;

        // a. Let desc be the result of calling the [[GetOwnProperty]] internal
        //    method of subset with P.
        // b. Set desc.[[Writable]] to false.
        // c. Set desc.[[Configurable]] to false.
        // d. Call the [[DefineOwnProperty]] internal method of subset with P, desc,
        //    and true as arguments.
        defineProperty(subset, P, {
            writable: false, configurable: false, value: subset[P]
        });
    }
    // "Freeze" the array so no new elements can be added
    defineProperty(subset, 'length', { writable: false });

    // 5. Return subset
    return subset;
}

/**
 * The GetOption abstract operation extracts the value of the property named
 * property from the provided options object, converts it to the required type,
 * checks whether it is one of a List of allowed values, and fills in a fallback
 * value if necessary.
 */
function /*9.2.9 */GetOption(options, property, type, values, fallback) {
    // 1. Let value be the result of calling the [[Get]] internal method of
    //    options with argument property.
    var value = options[property];

    // 2. If value is not undefined, then
    if (value !== undefined) {
        // a. Assert: type is "boolean" or "string".
        // b. If type is "boolean", then let value be ToBoolean(value).
        // c. If type is "string", then let value be ToString(value).
        value = type === 'boolean' ? Boolean(value) : type === 'string' ? String(value) : value;

        // d. If values is not undefined, then
        if (values !== undefined) {
            // i. If values does not contain an element equal to value, then throw a
            //    RangeError exception.
            if (arrIndexOf.call(values, value) === -1) throw new RangeError("'" + value + "' is not an allowed value for `" + property + '`');
        }

        // e. Return value.
        return value;
    }
    // Else return fallback.
    return fallback;
}

/**
 * The GetNumberOption abstract operation extracts a property value from the
 * provided options object, converts it to a Number value, checks whether it is
 * in the allowed range, and fills in a fallback value if necessary.
 */
function /* 9.2.10 */GetNumberOption(options, property, minimum, maximum, fallback) {
    // 1. Let value be the result of calling the [[Get]] internal method of
    //    options with argument property.
    var value = options[property];

    // 2. If value is not undefined, then
    if (value !== undefined) {
        // a. Let value be ToNumber(value).
        value = Number(value);

        // b. If value is NaN or less than minimum or greater than maximum, throw a
        //    RangeError exception.
        if (isNaN(value) || value < minimum || value > maximum) throw new RangeError('Value is not a number or outside accepted range');

        // c. Return floor(value).
        return Math.floor(value);
    }
    // 3. Else return fallback.
    return fallback;
}

// 8 The Intl Object
var Intl = {};

// 8.2 Function Properties of the Intl Object

// 8.2.1
// @spec[tc39/ecma402/master/spec/intl.html]
// @clause[sec-intl.getcanonicallocales]
function getCanonicalLocales(locales) {
    // 1. Let ll be ? CanonicalizeLocaleList(locales).
    var ll = CanonicalizeLocaleList(locales);
    // 2. Return CreateArrayFromList(ll).
    {
        var result = [];

        var len = ll.length;
        var k = 0;

        while (k < len) {
            result[k] = ll[k];
            k++;
        }
        return result;
    }
}

Object.defineProperty(Intl, 'getCanonicalLocales', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: getCanonicalLocales
});

// Currency minor units output from get-4217 grunt task, formatted
var currencyMinorUnits = {
    BHD: 3, BYR: 0, XOF: 0, BIF: 0, XAF: 0, CLF: 4, CLP: 0, KMF: 0, DJF: 0,
    XPF: 0, GNF: 0, ISK: 0, IQD: 3, JPY: 0, JOD: 3, KRW: 0, KWD: 3, LYD: 3,
    OMR: 3, PYG: 0, RWF: 0, TND: 3, UGX: 0, UYI: 0, VUV: 0, VND: 0
};

// Define the NumberFormat constructor internally so it cannot be tainted
function NumberFormatConstructor() {
    var locales = arguments[0];
    var options = arguments[1];

    if (!this || this === Intl) {
        return new Intl.NumberFormat(locales, options);
    }

    return InitializeNumberFormat(toObject(this), locales, options);
}

defineProperty(Intl, 'NumberFormat', {
    configurable: true,
    writable: true,
    value: NumberFormatConstructor
});

// Must explicitly set prototypes as unwritable
defineProperty(Intl.NumberFormat, 'prototype', {
    writable: false
});

/**
 * The abstract operation InitializeNumberFormat accepts the arguments
 * numberFormat (which must be an object), locales, and options. It initializes
 * numberFormat as a NumberFormat object.
 */
function /*11.1.1.1 */InitializeNumberFormat(numberFormat, locales, options) {
    // This will be a internal properties object if we're not already initialized
    var internal = getInternalProperties(numberFormat);

    // Create an object whose props can be used to restore the values of RegExp props
    var regexpRestore = createRegExpRestore();

    // 1. If numberFormat has an [[initializedIntlObject]] internal property with
    // value true, throw a TypeError exception.
    if (internal['[[initializedIntlObject]]'] === true) throw new TypeError('`this` object has already been initialized as an Intl object');

    // Need this to access the `internal` object
    defineProperty(numberFormat, '__getInternalProperties', {
        value: function value() {
            // NOTE: Non-standard, for internal use only
            if (arguments[0] === secret) return internal;
        }
    });

    // 2. Set the [[initializedIntlObject]] internal property of numberFormat to true.
    internal['[[initializedIntlObject]]'] = true;

    // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList
    //    abstract operation (defined in 9.2.1) with argument locales.
    var requestedLocales = CanonicalizeLocaleList(locales);

    // 4. If options is undefined, then
    if (options === undefined)
        // a. Let options be the result of creating a new object as if by the
        // expression new Object() where Object is the standard built-in constructor
        // with that name.
        options = {};

        // 5. Else
    else
        // a. Let options be ToObject(options).
        options = toObject(options);

    // 6. Let opt be a new Record.
    var opt = new Record(),


    // 7. Let matcher be the result of calling the GetOption abstract operation
    //    (defined in 9.2.9) with the arguments options, "localeMatcher", "string",
    //    a List containing the two String values "lookup" and "best fit", and
    //    "best fit".
    matcher = GetOption(options, 'localeMatcher', 'string', new List('lookup', 'best fit'), 'best fit');

    // 8. Set opt.[[localeMatcher]] to matcher.
    opt['[[localeMatcher]]'] = matcher;

    // 9. Let NumberFormat be the standard built-in object that is the initial value
    //    of Intl.NumberFormat.
    // 10. Let localeData be the value of the [[localeData]] internal property of
    //     NumberFormat.
    var localeData = internals.NumberFormat['[[localeData]]'];

    // 11. Let r be the result of calling the ResolveLocale abstract operation
    //     (defined in 9.2.5) with the [[availableLocales]] internal property of
    //     NumberFormat, requestedLocales, opt, the [[relevantExtensionKeys]]
    //     internal property of NumberFormat, and localeData.
    var r = ResolveLocale(internals.NumberFormat['[[availableLocales]]'], requestedLocales, opt, internals.NumberFormat['[[relevantExtensionKeys]]'], localeData);

    // 12. Set the [[locale]] internal property of numberFormat to the value of
    //     r.[[locale]].
    internal['[[locale]]'] = r['[[locale]]'];

    // 13. Set the [[numberingSystem]] internal property of numberFormat to the value
    //     of r.[[nu]].
    internal['[[numberingSystem]]'] = r['[[nu]]'];

    // The specification doesn't tell us to do this, but it's helpful later on
    internal['[[dataLocale]]'] = r['[[dataLocale]]'];

    // 14. Let dataLocale be the value of r.[[dataLocale]].
    var dataLocale = r['[[dataLocale]]'];

    // 15. Let s be the result of calling the GetOption abstract operation with the
    //     arguments options, "style", "string", a List containing the three String
    //     values "decimal", "percent", and "currency", and "decimal".
    var s = GetOption(options, 'style', 'string', new List('decimal', 'percent', 'currency'), 'decimal');

    // 16. Set the [[style]] internal property of numberFormat to s.
    internal['[[style]]'] = s;

    // 17. Let c be the result of calling the GetOption abstract operation with the
    //     arguments options, "currency", "string", undefined, and undefined.
    var c = GetOption(options, 'currency', 'string');

    // 18. If c is not undefined and the result of calling the
    //     IsWellFormedCurrencyCode abstract operation (defined in 6.3.1) with
    //     argument c is false, then throw a RangeError exception.
    if (c !== undefined && !IsWellFormedCurrencyCode(c)) throw new RangeError("'" + c + "' is not a valid currency code");

    // 19. If s is "currency" and c is undefined, throw a TypeError exception.
    if (s === 'currency' && c === undefined) throw new TypeError('Currency code is required when style is currency');

    var cDigits = void 0;

    // 20. If s is "currency", then
    if (s === 'currency') {
        // a. Let c be the result of converting c to upper case as specified in 6.1.
        c = c.toUpperCase();

        // b. Set the [[currency]] internal property of numberFormat to c.
        internal['[[currency]]'] = c;

        // c. Let cDigits be the result of calling the CurrencyDigits abstract
        //    operation (defined below) with argument c.
        cDigits = CurrencyDigits(c);
    }

    // 21. Let cd be the result of calling the GetOption abstract operation with the
    //     arguments options, "currencyDisplay", "string", a List containing the
    //     three String values "code", "symbol", and "name", and "symbol".
    var cd = GetOption(options, 'currencyDisplay', 'string', new List('code', 'symbol', 'name'), 'symbol');

    // 22. If s is "currency", then set the [[currencyDisplay]] internal property of
    //     numberFormat to cd.
    if (s === 'currency') internal['[[currencyDisplay]]'] = cd;

    // 23. Let mnid be the result of calling the GetNumberOption abstract operation
    //     (defined in 9.2.10) with arguments options, "minimumIntegerDigits", 1, 21,
    //     and 1.
    var mnid = GetNumberOption(options, 'minimumIntegerDigits', 1, 21, 1);

    // 24. Set the [[minimumIntegerDigits]] internal property of numberFormat to mnid.
    internal['[[minimumIntegerDigits]]'] = mnid;

    // 25. If s is "currency", then let mnfdDefault be cDigits; else let mnfdDefault
    //     be 0.
    var mnfdDefault = s === 'currency' ? cDigits : 0;

    // 26. Let mnfd be the result of calling the GetNumberOption abstract operation
    //     with arguments options, "minimumFractionDigits", 0, 20, and mnfdDefault.
    var mnfd = GetNumberOption(options, 'minimumFractionDigits', 0, 20, mnfdDefault);

    // 27. Set the [[minimumFractionDigits]] internal property of numberFormat to mnfd.
    internal['[[minimumFractionDigits]]'] = mnfd;

    // 28. If s is "currency", then let mxfdDefault be max(mnfd, cDigits); else if s
    //     is "percent", then let mxfdDefault be max(mnfd, 0); else let mxfdDefault
    //     be max(mnfd, 3).
    var mxfdDefault = s === 'currency' ? Math.max(mnfd, cDigits) : s === 'percent' ? Math.max(mnfd, 0) : Math.max(mnfd, 3);

    // 29. Let mxfd be the result of calling the GetNumberOption abstract operation
    //     with arguments options, "maximumFractionDigits", mnfd, 20, and mxfdDefault.
    var mxfd = GetNumberOption(options, 'maximumFractionDigits', mnfd, 20, mxfdDefault);

    // 30. Set the [[maximumFractionDigits]] internal property of numberFormat to mxfd.
    internal['[[maximumFractionDigits]]'] = mxfd;

    // 31. Let mnsd be the result of calling the [[Get]] internal method of options
    //     with argument "minimumSignificantDigits".
    var mnsd = options.minimumSignificantDigits;

    // 32. Let mxsd be the result of calling the [[Get]] internal method of options
    //     with argument "maximumSignificantDigits".
    var mxsd = options.maximumSignificantDigits;

    // 33. If mnsd is not undefined or mxsd is not undefined, then:
    if (mnsd !== undefined || mxsd !== undefined) {
        // a. Let mnsd be the result of calling the GetNumberOption abstract
        //    operation with arguments options, "minimumSignificantDigits", 1, 21,
        //    and 1.
        mnsd = GetNumberOption(options, 'minimumSignificantDigits', 1, 21, 1);

        // b. Let mxsd be the result of calling the GetNumberOption abstract
        //     operation with arguments options, "maximumSignificantDigits", mnsd,
        //     21, and 21.
        mxsd = GetNumberOption(options, 'maximumSignificantDigits', mnsd, 21, 21);

        // c. Set the [[minimumSignificantDigits]] internal property of numberFormat
        //    to mnsd, and the [[maximumSignificantDigits]] internal property of
        //    numberFormat to mxsd.
        internal['[[minimumSignificantDigits]]'] = mnsd;
        internal['[[maximumSignificantDigits]]'] = mxsd;
    }
    // 34. Let g be the result of calling the GetOption abstract operation with the
    //     arguments options, "useGrouping", "boolean", undefined, and true.
    var g = GetOption(options, 'useGrouping', 'boolean', undefined, true);

    // 35. Set the [[useGrouping]] internal property of numberFormat to g.
    internal['[[useGrouping]]'] = g;

    // 36. Let dataLocaleData be the result of calling the [[Get]] internal method of
    //     localeData with argument dataLocale.
    var dataLocaleData = localeData[dataLocale];

    // 37. Let patterns be the result of calling the [[Get]] internal method of
    //     dataLocaleData with argument "patterns".
    var patterns = dataLocaleData.patterns;

    // 38. Assert: patterns is an object (see 11.2.3)

    // 39. Let stylePatterns be the result of calling the [[Get]] internal method of
    //     patterns with argument s.
    var stylePatterns = patterns[s];

    // 40. Set the [[positivePattern]] internal property of numberFormat to the
    //     result of calling the [[Get]] internal method of stylePatterns with the
    //     argument "positivePattern".
    internal['[[positivePattern]]'] = stylePatterns.positivePattern;

    // 41. Set the [[negativePattern]] internal property of numberFormat to the
    //     result of calling the [[Get]] internal method of stylePatterns with the
    //     argument "negativePattern".
    internal['[[negativePattern]]'] = stylePatterns.negativePattern;

    // 42. Set the [[boundFormat]] internal property of numberFormat to undefined.
    internal['[[boundFormat]]'] = undefined;

    // 43. Set the [[initializedNumberFormat]] internal property of numberFormat to
    //     true.
    internal['[[initializedNumberFormat]]'] = true;

    // In ES3, we need to pre-bind the format() function
    if (es3) numberFormat.format = GetFormatNumber.call(numberFormat);

    // Restore the RegExp properties
    regexpRestore();

    // Return the newly initialised object
    return numberFormat;
}

function CurrencyDigits(currency) {
    // When the CurrencyDigits abstract operation is called with an argument currency
    // (which must be an upper case String value), the following steps are taken:

    // 1. If the ISO 4217 currency and funds code list contains currency as an
    // alphabetic code, then return the minor unit value corresponding to the
    // currency from the list; else return 2.
    return currencyMinorUnits[currency] !== undefined ? currencyMinorUnits[currency] : 2;
}

/* 11.2.3 */internals.NumberFormat = {
    '[[availableLocales]]': [],
    '[[relevantExtensionKeys]]': ['nu'],
    '[[localeData]]': {}
};

/**
 * When the supportedLocalesOf method of Intl.NumberFormat is called, the
 * following steps are taken:
 */
/* 11.2.2 */
defineProperty(Intl.NumberFormat, 'supportedLocalesOf', {
    configurable: true,
    writable: true,
    value: fnBind.call(function (locales) {
        // Bound functions only have the `this` value altered if being used as a constructor,
        // this lets us imitate a native function that has no constructor
        if (!hop.call(this, '[[availableLocales]]')) throw new TypeError('supportedLocalesOf() is not a constructor');

        // Create an object whose props can be used to restore the values of RegExp props
        var regexpRestore = createRegExpRestore(),


        // 1. If options is not provided, then let options be undefined.
        options = arguments[1],


        // 2. Let availableLocales be the value of the [[availableLocales]] internal
        //    property of the standard built-in object that is the initial value of
        //    Intl.NumberFormat.

        availableLocales = this['[[availableLocales]]'],


        // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList
        //    abstract operation (defined in 9.2.1) with argument locales.
        requestedLocales = CanonicalizeLocaleList(locales);

        // Restore the RegExp properties
        regexpRestore();

        // 4. Return the result of calling the SupportedLocales abstract operation
        //    (defined in 9.2.8) with arguments availableLocales, requestedLocales,
        //    and options.
        return SupportedLocales(availableLocales, requestedLocales, options);
    }, internals.NumberFormat)
});

/**
 * This named accessor property returns a function that formats a number
 * according to the effective locale and the formatting options of this
 * NumberFormat object.
 */
/* 11.3.2 */defineProperty(Intl.NumberFormat.prototype, 'format', {
    configurable: true,
    get: GetFormatNumber
});

function GetFormatNumber() {
    var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this);

    // Satisfy test 11.3_b
    if (!internal || !internal['[[initializedNumberFormat]]']) throw new TypeError('`this` value for format() is not an initialized Intl.NumberFormat object.');

    // The value of the [[Get]] attribute is a function that takes the following
    // steps:

    // 1. If the [[boundFormat]] internal property of this NumberFormat object
    //    is undefined, then:
    if (internal['[[boundFormat]]'] === undefined) {
        // a. Let F be a Function object, with internal properties set as
        //    specified for built-in functions in ES5, 15, or successor, and the
        //    length property set to 1, that takes the argument value and
        //    performs the following steps:
        var F = function F(value) {
            // i. If value is not provided, then let value be undefined.
            // ii. Let x be ToNumber(value).
            // iii. Return the result of calling the FormatNumber abstract
            //      operation (defined below) with arguments this and x.
            return FormatNumber(this, /* x = */Number(value));
        };

        // b. Let bind be the standard built-in function object defined in ES5,
        //    15.3.4.5.
        // c. Let bf be the result of calling the [[Call]] internal method of
        //    bind with F as the this value and an argument list containing
        //    the single item this.
        var bf = fnBind.call(F, this);

        // d. Set the [[boundFormat]] internal property of this NumberFormat
        //    object to bf.
        internal['[[boundFormat]]'] = bf;
    }
    // Return the value of the [[boundFormat]] internal property of this
    // NumberFormat object.
    return internal['[[boundFormat]]'];
}

function formatToParts() {
    var value = arguments.length <= 0 || arguments[0] === undefined ? undefined : arguments[0];

    var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this);
    if (!internal || !internal['[[initializedNumberFormat]]']) throw new TypeError('`this` value for formatToParts() is not an initialized Intl.NumberFormat object.');

    var x = Number(value);
    return FormatNumberToParts(this, x);
}

Object.defineProperty(Intl.NumberFormat.prototype, 'formatToParts', {
    configurable: true,
    enumerable: false,
    writable: true,
    value: formatToParts
});

/*
 * @spec[stasm/ecma402/number-format-to-parts/spec/numberformat.html]
 * @clause[sec-formatnumbertoparts]
 */
function FormatNumberToParts(numberFormat, x) {
    // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
    var parts = PartitionNumberPattern(numberFormat, x);
    // 2. Let result be ArrayCreate(0).
    var result = [];
    // 3. Let n be 0.
    var n = 0;
    // 4. For each part in parts, do:
    for (var i = 0; parts.length > i; i++) {
        var part = parts[i];
        // a. Let O be ObjectCreate(%ObjectPrototype%).
        var O = {};
        // a. Perform ? CreateDataPropertyOrThrow(O, "type", part.[[type]]).
        O.type = part['[[type]]'];
        // a. Perform ? CreateDataPropertyOrThrow(O, "value", part.[[value]]).
        O.value = part['[[value]]'];
        // a. Perform ? CreateDataPropertyOrThrow(result, ? ToString(n), O).
        result[n] = O;
        // a. Increment n by 1.
        n += 1;
    }
    // 5. Return result.
    return result;
}

/*
 * @spec[stasm/ecma402/number-format-to-parts/spec/numberformat.html]
 * @clause[sec-partitionnumberpattern]
 */
function PartitionNumberPattern(numberFormat, x) {

    var internal = getInternalProperties(numberFormat),
        locale = internal['[[dataLocale]]'],
        nums = internal['[[numberingSystem]]'],
        data = internals.NumberFormat['[[localeData]]'][locale],
        ild = data.symbols[nums] || data.symbols.latn,
        pattern = void 0;

    // 1. If x is not NaN and x < 0, then:
    if (!isNaN(x) && x < 0) {
        // a. Let x be -x.
        x = -x;
        // a. Let pattern be the value of numberFormat.[[negativePattern]].
        pattern = internal['[[negativePattern]]'];
    }
    // 2. Else,
    else {
            // a. Let pattern be the value of numberFormat.[[positivePattern]].
            pattern = internal['[[positivePattern]]'];
        }
    // 3. Let result be a new empty List.
    var result = new List();
    // 4. Let beginIndex be Call(%StringProto_indexOf%, pattern, "{", 0).
    var beginIndex = pattern.indexOf('{', 0);
    // 5. Let endIndex be 0.
    var endIndex = 0;
    // 6. Let nextIndex be 0.
    var nextIndex = 0;
    // 7. Let length be the number of code units in pattern.
    var length = pattern.length;
    // 8. Repeat while beginIndex is an integer index into pattern:
    while (beginIndex > -1 && beginIndex < length) {
        // a. Set endIndex to Call(%StringProto_indexOf%, pattern, "}", beginIndex)
        endIndex = pattern.indexOf('}', beginIndex);
        // a. If endIndex = -1, throw new Error exception.
        if (endIndex === -1) throw new Error();
        // a. If beginIndex is greater than nextIndex, then:
        if (beginIndex > nextIndex) {
            // i. Let literal be a substring of pattern from position nextIndex, inclusive, to position beginIndex, exclusive.
            var literal = pattern.substring(nextIndex, beginIndex);
            // ii. Add new part record { [[type]]: "literal", [[value]]: literal } as a new element of the list result.
            arrPush.call(result, { '[[type]]': 'literal', '[[value]]': literal });
        }
        // a. Let p be the substring of pattern from position beginIndex, exclusive, to position endIndex, exclusive.
        var p = pattern.substring(beginIndex + 1, endIndex);
        // a. If p is equal "number", then:
        if (p === "number") {
            // i. If x is NaN,
            if (isNaN(x)) {
                // 1. Let n be an ILD String value indicating the NaN value.
                var n = ild.nan;
                // 2. Add new part record { [[type]]: "nan", [[value]]: n } as a new element of the list result.
                arrPush.call(result, { '[[type]]': 'nan', '[[value]]': n });
            }
            // ii. Else if isFinite(x) is false,
            else if (!isFinite(x)) {
                    // 1. Let n be an ILD String value indicating infinity.
                    var _n = ild.infinity;
                    // 2. Add new part record { [[type]]: "infinity", [[value]]: n } as a new element of the list result.
                    arrPush.call(result, { '[[type]]': 'infinity', '[[value]]': _n });
                }
                // iii. Else,
                else {
                        // 1. If the value of numberFormat.[[style]] is "percent" and isFinite(x), let x be 100 × x.
                        if (internal['[[style]]'] === 'percent' && isFinite(x)) x *= 100;

                        var _n2 = void 0;
                        // 2. If the numberFormat.[[minimumSignificantDigits]] and numberFormat.[[maximumSignificantDigits]] are present, then
                        if (hop.call(internal, '[[minimumSignificantDigits]]') && hop.call(internal, '[[maximumSignificantDigits]]')) {
                            // a. Let n be ToRawPrecision(x, numberFormat.[[minimumSignificantDigits]], numberFormat.[[maximumSignificantDigits]]).
                            _n2 = ToRawPrecision(x, internal['[[minimumSignificantDigits]]'], internal['[[maximumSignificantDigits]]']);
                        }
                        // 3. Else,
                        else {
                                // a. Let n be ToRawFixed(x, numberFormat.[[minimumIntegerDigits]], numberFormat.[[minimumFractionDigits]], numberFormat.[[maximumFractionDigits]]).
                                _n2 = ToRawFixed(x, internal['[[minimumIntegerDigits]]'], internal['[[minimumFractionDigits]]'], internal['[[maximumFractionDigits]]']);
                            }
                        // 4. If the value of the numberFormat.[[numberingSystem]] matches one of the values in the "Numbering System" column of Table 2 below, then
                        if (numSys[nums]) {
                            (function () {
                                // a. Let digits be an array whose 10 String valued elements are the UTF-16 string representations of the 10 digits specified in the "Digits" column of the matching row in Table 2.
                                var digits = numSys[nums];
                                // a. Replace each digit in n with the value of digits[digit].
                                _n2 = String(_n2).replace(/\d/g, function (digit) {
                                    return digits[digit];
                                });
                            })();
                        }
                        // 5. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system.
                        else _n2 = String(_n2); // ###TODO###

                        var integer = void 0;
                        var fraction = void 0;
                        // 6. Let decimalSepIndex be Call(%StringProto_indexOf%, n, ".", 0).
                        var decimalSepIndex = _n2.indexOf('.', 0);
                        // 7. If decimalSepIndex > 0, then:
                        if (decimalSepIndex > 0) {
                            // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive.
                            integer = _n2.substring(0, decimalSepIndex);
                            // a. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n.
                            fraction = _n2.substring(decimalSepIndex + 1, decimalSepIndex.length);
                        }
                        // 8. Else:
                        else {
                                // a. Let integer be n.
                                integer = _n2;
                                // a. Let fraction be undefined.
                                fraction = undefined;
                            }
                        // 9. If the value of the numberFormat.[[useGrouping]] is true,
                        if (internal['[[useGrouping]]'] === true) {
                            // a. Let groupSepSymbol be the ILND String representing the grouping separator.
                            var groupSepSymbol = ild.group;
                            // a. Let groups be a List whose elements are, in left to right order, the substrings defined by ILND set of locations within the integer.
                            var groups = [];
                            // ----> implementation:
                            // Primary group represents the group closest to the decimal
                            var pgSize = data.patterns.primaryGroupSize || 3;
                            // Secondary group is every other group
                            var sgSize = data.patterns.secondaryGroupSize || pgSize;
                            // Group only if necessary
                            if (integer.length > pgSize) {
                                // Index of the primary grouping separator
                                var end = integer.length - pgSize;
                                // Starting index for our loop
                                var idx = end % sgSize;
                                var start = integer.slice(0, idx);
                                if (start.length) arrPush.call(groups, start);
                                // Loop to separate into secondary grouping digits
                                while (idx < end) {
                                    arrPush.call(groups, integer.slice(idx, idx + sgSize));
                                    idx += sgSize;
                                }
                                // Add the primary grouping digits
                                arrPush.call(groups, integer.slice(end));
                            } else {
                                arrPush.call(groups, integer);
                            }
                            // a. Assert: The number of elements in groups List is greater than 0.
                            if (groups.length === 0) throw new Error();
                            // a. Repeat, while groups List is not empty:
                            while (groups.length) {
                                // i. Remove the first element from groups and let integerGroup be the value of that element.
                                var integerGroup = arrShift.call(groups);
                                // ii. Add new part record { [[type]]: "integer", [[value]]: integerGroup } as a new element of the list result.
                                arrPush.call(result, { '[[type]]': 'integer', '[[value]]': integerGroup });
                                // iii. If groups List is not empty, then:
                                if (groups.length) {
                                    // 1. Add new part record { [[type]]: "group", [[value]]: groupSepSymbol } as a new element of the list result.
                                    arrPush.call(result, { '[[type]]': 'group', '[[value]]': groupSepSymbol });
                                }
                            }
                        }
                        // 10. Else,
                        else {
                                // a. Add new part record { [[type]]: "integer", [[value]]: integer } as a new element of the list result.
                                arrPush.call(result, { '[[type]]': 'integer', '[[value]]': integer });
                            }
                        // 11. If fraction is not undefined, then:
                        if (fraction !== undefined) {
                            // a. Let decimalSepSymbol be the ILND String representing the decimal separator.
                            var decimalSepSymbol = ild.decimal;
                            // a. Add new part record { [[type]]: "decimal", [[value]]: decimalSepSymbol } as a new element of the list result.
                            arrPush.call(result, { '[[type]]': 'decimal', '[[value]]': decimalSepSymbol });
                            // a. Add new part record { [[type]]: "fraction", [[value]]: fraction } as a new element of the list result.
                            arrPush.call(result, { '[[type]]': 'fraction', '[[value]]': fraction });
                        }
                    }
        }
        // a. Else if p is equal "plusSign", then:
        else if (p === "plusSign") {
                // i. Let plusSignSymbol be the ILND String representing the plus sign.
                var plusSignSymbol = ild.plusSign;
                // ii. Add new part record { [[type]]: "plusSign", [[value]]: plusSignSymbol } as a new element of the list result.
                arrPush.call(result, { '[[type]]': 'plusSign', '[[value]]': plusSignSymbol });
            }
            // a. Else if p is equal "minusSign", then:
            else if (p === "minusSign") {
                    // i. Let minusSignSymbol be the ILND String representing the minus sign.
                    var minusSignSymbol = ild.minusSign;
                    // ii. Add new part record { [[type]]: "minusSign", [[value]]: minusSignSymbol } as a new element of the list result.
                    arrPush.call(result, { '[[type]]': 'minusSign', '[[value]]': minusSignSymbol });
                }
                // a. Else if p is equal "percentSign" and numberFormat.[[style]] is "percent", then:
                else if (p === "percentSign" && internal['[[style]]'] === "percent") {
                        // i. Let percentSignSymbol be the ILND String representing the percent sign.
                        var percentSignSymbol = ild.percentSign;
                        // ii. Add new part record { [[type]]: "percentSign", [[value]]: percentSignSymbol } as a new element of the list result.
                        arrPush.call(result, { '[[type]]': 'literal', '[[value]]': percentSignSymbol });
                    }
                    // a. Else if p is equal "currency" and numberFormat.[[style]] is "currency", then:
                    else if (p === "currency" && internal['[[style]]'] === "currency") {
                            // i. Let currency be the value of numberFormat.[[currency]].
                            var currency = internal['[[currency]]'];

                            var cd = void 0;

                            // ii. If numberFormat.[[currencyDisplay]] is "code", then
                            if (internal['[[currencyDisplay]]'] === "code") {
                                // 1. Let cd be currency.
                                cd = currency;
                            }
                            // iii. Else if numberFormat.[[currencyDisplay]] is "symbol", then
                            else if (internal['[[currencyDisplay]]'] === "symbol") {
                                    // 1. Let cd be an ILD string representing currency in short form. If the implementation does not have such a representation of currency, use currency itself.
                                    cd = data.currencies[currency] || currency;
                                }
                                // iv. Else if numberFormat.[[currencyDisplay]] is "name", then
                                else if (internal['[[currencyDisplay]]'] === "name") {
                                        // 1. Let cd be an ILD string representing currency in long form. If the implementation does not have such a representation of currency, then use currency itself.
                                        cd = currency;
                                    }
                            // v. Add new part record { [[type]]: "currency", [[value]]: cd } as a new element of the list result.
                            arrPush.call(result, { '[[type]]': 'currency', '[[value]]': cd });
                        }
                        // a. Else,
                        else {
                                // i. Let literal be the substring of pattern from position beginIndex, inclusive, to position endIndex, inclusive.
                                var _literal = pattern.substring(beginIndex, endIndex);
                                // ii. Add new part record { [[type]]: "literal", [[value]]: literal } as a new element of the list result.
                                arrPush.call(result, { '[[type]]': 'literal', '[[value]]': _literal });
                            }
        // a. Set nextIndex to endIndex + 1.
        nextIndex = endIndex + 1;
        // a. Set beginIndex to Call(%StringProto_indexOf%, pattern, "{", nextIndex)
        beginIndex = pattern.indexOf('{', nextIndex);
    }
    // 9. If nextIndex is less than length, then:
    if (nextIndex < length) {
        // a. Let literal be the substring of pattern from position nextIndex, inclusive, to position length, exclusive.
        var _literal2 = pattern.substring(nextIndex, length);
        // a. Add new part record { [[type]]: "literal", [[value]]: literal } as a new element of the list result.
        arrPush.call(result, { '[[type]]': 'literal', '[[value]]': _literal2 });
    }
    // 10. Return result.
    return result;
}

/*
 * @spec[stasm/ecma402/number-format-to-parts/spec/numberformat.html]
 * @clause[sec-formatnumber]
 */
function FormatNumber(numberFormat, x) {
    // 1. Let parts be ? PartitionNumberPattern(numberFormat, x).
    var parts = PartitionNumberPattern(numberFormat, x);
    // 2. Let result be an empty String.
    var result = '';
    // 3. For each part in parts, do:
    for (var i = 0; parts.length > i; i++) {
        var part = parts[i];
        // a. Set result to a String value produced by concatenating result and part.[[value]].
        result += part['[[value]]'];
    }
    // 4. Return result.
    return result;
}

/**
 * When the ToRawPrecision abstract operation is called with arguments x (which
 * must be a finite non-negative number), minPrecision, and maxPrecision (both
 * must be integers between 1 and 21) the following steps are taken:
 */
function ToRawPrecision(x, minPrecision, maxPrecision) {
    // 1. Let p be maxPrecision.
    var p = maxPrecision;

    var m = void 0,
        e = void 0;

    // 2. If x = 0, then
    if (x === 0) {
        // a. Let m be the String consisting of p occurrences of the character "0".
        m = arrJoin.call(Array(p + 1), '0');
        // b. Let e be 0.
        e = 0;
    }
    // 3. Else
    else {
            // a. Let e and n be integers such that 10ᵖ⁻¹ ≤ n < 10ᵖ and for which the
            //    exact mathematical value of n × 10ᵉ⁻ᵖ⁺¹ – x is as close to zero as
            //    possible. If there are two such sets of e and n, pick the e and n for
            //    which n × 10ᵉ⁻ᵖ⁺¹ is larger.
            e = log10Floor(Math.abs(x));

            // Easier to get to m from here
            var f = Math.round(Math.exp(Math.abs(e - p + 1) * Math.LN10));

            // b. Let m be the String consisting of the digits of the decimal
            //    representation of n (in order, with no leading zeroes)
            m = String(Math.round(e - p + 1 < 0 ? x * f : x / f));
        }

    // 4. If e ≥ p, then
    if (e >= p)
        // a. Return the concatenation of m and e-p+1 occurrences of the character "0".
        return m + arrJoin.call(Array(e - p + 1 + 1), '0');

        // 5. If e = p-1, then
    else if (e === p - 1)
            // a. Return m.
            return m;

            // 6. If e ≥ 0, then
        else if (e >= 0)
                // a. Let m be the concatenation of the first e+1 characters of m, the character
                //    ".", and the remaining p–(e+1) characters of m.
                m = m.slice(0, e + 1) + '.' + m.slice(e + 1);

                // 7. If e < 0, then
            else if (e < 0)
                    // a. Let m be the concatenation of the String "0.", –(e+1) occurrences of the
                    //    character "0", and the string m.
                    m = '0.' + arrJoin.call(Array(-(e + 1) + 1), '0') + m;

    // 8. If m contains the character ".", and maxPrecision > minPrecision, then
    if (m.indexOf(".") >= 0 && maxPrecision > minPrecision) {
        // a. Let cut be maxPrecision – minPrecision.
        var cut = maxPrecision - minPrecision;

        // b. Repeat while cut > 0 and the last character of m is "0":
        while (cut > 0 && m.charAt(m.length - 1) === '0') {
            //  i. Remove the last character from m.
            m = m.slice(0, -1);

            //  ii. Decrease cut by 1.
            cut--;
        }

        // c. If the last character of m is ".", then
        if (m.charAt(m.length - 1) === '.')
            //    i. Remove the last character from m.
            m = m.slice(0, -1);
    }
    // 9. Return m.
    return m;
}

/**
 * @spec[tc39/ecma402/master/spec/numberformat.html]
 * @clause[sec-torawfixed]
 * When the ToRawFixed abstract operation is called with arguments x (which must
 * be a finite non-negative number), minInteger (which must be an integer between
 * 1 and 21), minFraction, and maxFraction (which must be integers between 0 and
 * 20) the following steps are taken:
 */
function ToRawFixed(x, minInteger, minFraction, maxFraction) {
    // 1. Let f be maxFraction.
    var f = maxFraction;
    // 2. Let n be an integer for which the exact mathematical value of n ÷ 10f – x is as close to zero as possible. If there are two such n, pick the larger n.
    var n = Math.pow(10, f) * x; // diverging...
    // 3. If n = 0, let m be the String "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
    var m = n === 0 ? "0" : n.toFixed(0); // divering...

    {
        // this diversion is needed to take into consideration big numbers, e.g.:
        // 1.2344501e+37 -> 12344501000000000000000000000000000000
        var idx = void 0;
        var exp = (idx = m.indexOf('e')) > -1 ? m.slice(idx + 1) : 0;
        if (exp) {
            m = m.slice(0, idx).replace('.', '');
            m += arrJoin.call(Array(exp - (m.length - 1) + 1), '0');
        }
    }

    var int = void 0;
    // 4. If f ≠ 0, then
    if (f !== 0) {
        // a. Let k be the number of characters in m.
        var k = m.length;
        // a. If k ≤ f, then
        if (k <= f) {
            // i. Let z be the String consisting of f+1–k occurrences of the character "0".
            var z = arrJoin.call(Array(f + 1 - k + 1), '0');
            // ii. Let m be the concatenation of Strings z and m.
            m = z + m;
            // iii. Let k be f+1.
            k = f + 1;
        }
        // a. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
        var a = m.substring(0, k - f),
            b = m.substring(k - f, m.length);
        // a. Let m be the concatenation of the three Strings a, ".", and b.
        m = a + "." + b;
        // a. Let int be the number of characters in a.
        int = a.length;
    }
    // 5. Else, let int be the number of characters in m.
    else int = m.length;
    // 6. Let cut be maxFraction – minFraction.
    var cut = maxFraction - minFraction;
    // 7. Repeat while cut > 0 and the last character of m is "0":
    while (cut > 0 && m.slice(-1) === "0") {
        // a. Remove the last character from m.
        m = m.slice(0, -1);
        // a. Decrease cut by 1.
        cut--;
    }
    // 8. If the last character of m is ".", then
    if (m.slice(-1) === ".") {
        // a. Remove the last character from m.
        m = m.slice(0, -1);
    }
    // 9. If int < minInteger, then
    if (int < minInteger) {
        // a. Let z be the String consisting of minInteger–int occurrences of the character "0".
        var _z = arrJoin.call(Array(minInteger - int + 1), '0');
        // a. Let m be the concatenation of Strings z and m.
        m = _z + m;
    }
    // 10. Return m.
    return m;
}

// Sect 11.3.2 Table 2, Numbering systems
// ======================================
var numSys = {
    arab: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"],
    arabext: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
    bali: ["᭐", "᭑", "᭒", "᭓", "᭔", "᭕", "᭖", "᭗", "᭘", "᭙"],
    beng: ["০", "১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯"],
    deva: ["०", "१", "२", "३", "४", "५", "६", "७", "८", "९"],
    fullwide: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
    gujr: ["૦", "૧", "૨", "૩", "૪", "૫", "૬", "૭", "૮", "૯"],
    guru: ["੦", "੧", "੨", "੩", "੪", "੫", "੬", "੭", "੮", "੯"],
    hanidec: ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
    khmr: ["០", "១", "២", "៣", "៤", "៥", "៦", "៧", "៨", "៩"],
    knda: ["೦", "೧", "೨", "೩", "೪", "೫", "೬", "೭", "೮", "೯"],
    laoo: ["໐", "໑", "໒", "໓", "໔", "໕", "໖", "໗", "໘", "໙"],
    latn: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
    limb: ["᥆", "᥇", "᥈", "᥉", "᥊", "᥋", "᥌", "᥍", "᥎", "᥏"],
    mlym: ["൦", "൧", "൨", "൩", "൪", "൫", "൬", "൭", "൮", "൯"],
    mong: ["᠐", "᠑", "᠒", "᠓", "᠔", "᠕", "᠖", "᠗", "᠘", "᠙"],
    mymr: ["၀", "၁", "၂", "၃", "၄", "၅", "၆", "၇", "၈", "၉"],
    orya: ["୦", "୧", "୨", "୩", "୪", "୫", "୬", "୭", "୮", "୯"],
    tamldec: ["௦", "௧", "௨", "௩", "௪", "௫", "௬", "௭", "௮", "௯"],
    telu: ["౦", "౧", "౨", "౩", "౪", "౫", "౬", "౭", "౮", "౯"],
    thai: ["๐", "๑", "๒", "๓", "๔", "๕", "๖", "๗", "๘", "๙"],
    tibt: ["༠", "༡", "༢", "༣", "༤", "༥", "༦", "༧", "༨", "༩"]
};

/**
 * This function provides access to the locale and formatting options computed
 * during initialization of the object.
 *
 * The function returns a new object whose properties and attributes are set as
 * if constructed by an object literal assigning to each of the following
 * properties the value of the corresponding internal property of this
 * NumberFormat object (see 11.4): locale, numberingSystem, style, currency,
 * currencyDisplay, minimumIntegerDigits, minimumFractionDigits,
 * maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits, and
 * useGrouping. Properties whose corresponding internal properties are not present
 * are not assigned.
 */
/* 11.3.3 */defineProperty(Intl.NumberFormat.prototype, 'resolvedOptions', {
    configurable: true,
    writable: true,
    value: function value() {
        var prop = void 0,
            descs = new Record(),
            props = ['locale', 'numberingSystem', 'style', 'currency', 'currencyDisplay', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'useGrouping'],
            internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this);

        // Satisfy test 11.3_b
        if (!internal || !internal['[[initializedNumberFormat]]']) throw new TypeError('`this` value for resolvedOptions() is not an initialized Intl.NumberFormat object.');

        for (var i = 0, max = props.length; i < max; i++) {
            if (hop.call(internal, prop = '[[' + props[i] + ']]')) descs[props[i]] = { value: internal[prop], writable: true, configurable: true, enumerable: true };
        }

        return objCreate({}, descs);
    }
});

/* jslint esnext: true */

// Match these datetime components in a CLDR pattern, except those in single quotes
var expDTComponents = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g;
// trim patterns after transformations
var expPatternTrimmer = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
// Skip over patterns with these datetime components because we don't have data
// to back them up:
// timezone, weekday, amoung others
var unwantedDTCs = /[rqQASjJgwWIQq]/; // xXVO were removed from this list in favor of computing matches with timeZoneName values but printing as empty string

var dtKeys = ["era", "year", "month", "day", "weekday", "quarter"];
var tmKeys = ["hour", "minute", "second", "hour12", "timeZoneName"];

function isDateFormatOnly(obj) {
    for (var i = 0; i < tmKeys.length; i += 1) {
        if (obj.hasOwnProperty(tmKeys[i])) {
            return false;
        }
    }
    return true;
}

function isTimeFormatOnly(obj) {
    for (var i = 0; i < dtKeys.length; i += 1) {
        if (obj.hasOwnProperty(dtKeys[i])) {
            return false;
        }
    }
    return true;
}

function joinDateAndTimeFormats(dateFormatObj, timeFormatObj) {
    var o = { _: {} };
    for (var i = 0; i < dtKeys.length; i += 1) {
        if (dateFormatObj[dtKeys[i]]) {
            o[dtKeys[i]] = dateFormatObj[dtKeys[i]];
        }
        if (dateFormatObj._[dtKeys[i]]) {
            o._[dtKeys[i]] = dateFormatObj._[dtKeys[i]];
        }
    }
    for (var j = 0; j < tmKeys.length; j += 1) {
        if (timeFormatObj[tmKeys[j]]) {
            o[tmKeys[j]] = timeFormatObj[tmKeys[j]];
        }
        if (timeFormatObj._[tmKeys[j]]) {
            o._[tmKeys[j]] = timeFormatObj._[tmKeys[j]];
        }
    }
    return o;
}

function computeFinalPatterns(formatObj) {
    // From http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns:
    //  'In patterns, two single quotes represents a literal single quote, either
    //   inside or outside single quotes. Text within single quotes is not
    //   interpreted in any way (except for two adjacent single quotes).'
    formatObj.pattern12 = formatObj.extendedPattern.replace(/'([^']*)'/g, function ($0, literal) {
        return literal ? literal : "'";
    });

    // pattern 12 is always the default. we can produce the 24 by removing {ampm}
    formatObj.pattern = formatObj.pattern12.replace('{ampm}', '').replace(expPatternTrimmer, '');
    return formatObj;
}

function expDTComponentsMeta($0, formatObj) {
    switch ($0.charAt(0)) {
        // --- Era
        case 'G':
            formatObj.era = ['short', 'short', 'short', 'long', 'narrow'][$0.length - 1];
            return '{era}';

        // --- Year
        case 'y':
        case 'Y':
        case 'u':
        case 'U':
        case 'r':
            formatObj.year = $0.length === 2 ? '2-digit' : 'numeric';
            return '{year}';

        // --- Quarter (not supported in this polyfill)
        case 'Q':
        case 'q':
            formatObj.quarter = ['numeric', '2-digit', 'short', 'long', 'narrow'][$0.length - 1];
            return '{quarter}';

        // --- Month
        case 'M':
        case 'L':
            formatObj.month = ['numeric', '2-digit', 'short', 'long', 'narrow'][$0.length - 1];
            return '{month}';

        // --- Week (not supported in this polyfill)
        case 'w':
            // week of the year
            formatObj.week = $0.length === 2 ? '2-digit' : 'numeric';
            return '{weekday}';
        case 'W':
            // week of the month
            formatObj.week = 'numeric';
            return '{weekday}';

        // --- Day
        case 'd':
            // day of the month
            formatObj.day = $0.length === 2 ? '2-digit' : 'numeric';
            return '{day}';
        case 'D': // day of the year
        case 'F': // day of the week
        case 'g':
            // 1..n: Modified Julian day
            formatObj.day = 'numeric';
            return '{day}';

        // --- Week Day
        case 'E':
            // day of the week
            formatObj.weekday = ['short', 'short', 'short', 'long', 'narrow', 'short'][$0.length - 1];
            return '{weekday}';
        case 'e':
            // local day of the week
            formatObj.weekday = ['numeric', '2-digit', 'short', 'long', 'narrow', 'short'][$0.length - 1];
            return '{weekday}';
        case 'c':
            // stand alone local day of the week
            formatObj.weekday = ['numeric', undefined, 'short', 'long', 'narrow', 'short'][$0.length - 1];
            return '{weekday}';

        // --- Period
        case 'a': // AM, PM
        case 'b': // am, pm, noon, midnight
        case 'B':
            // flexible day periods
            formatObj.hour12 = true;
            return '{ampm}';

        // --- Hour
        case 'h':
        case 'H':
            formatObj.hour = $0.length === 2 ? '2-digit' : 'numeric';
            return '{hour}';
        case 'k':
        case 'K':
            formatObj.hour12 = true; // 12-hour-cycle time formats (using h or K)
            formatObj.hour = $0.length === 2 ? '2-digit' : 'numeric';
            return '{hour}';

        // --- Minute
        case 'm':
            formatObj.minute = $0.length === 2 ? '2-digit' : 'numeric';
            return '{minute}';

        // --- Second
        case 's':
            formatObj.second = $0.length === 2 ? '2-digit' : 'numeric';
            return '{second}';
        case 'S':
        case 'A':
            formatObj.second = 'numeric';
            return '{second}';

        // --- Timezone
        case 'z': // 1..3, 4: specific non-location format
        case 'Z': // 1..3, 4, 5: The ISO8601 varios formats
        case 'O': // 1, 4: miliseconds in day short, long
        case 'v': // 1, 4: generic non-location format
        case 'V': // 1, 2, 3, 4: time zone ID or city
        case 'X': // 1, 2, 3, 4: The ISO8601 varios formats
        case 'x':
            // 1, 2, 3, 4: The ISO8601 varios formats
            // this polyfill only supports much, for now, we are just doing something dummy
            formatObj.timeZoneName = $0.length < 4 ? 'short' : 'long';
            return '{timeZoneName}';
    }
}

/**
 * Converts the CLDR availableFormats into the objects and patterns required by
 * the ECMAScript Internationalization API specification.
 */
function createDateTimeFormat(skeleton, pattern) {
    // we ignore certain patterns that are unsupported to avoid this expensive op.
    if (unwantedDTCs.test(pattern)) return undefined;

    var formatObj = {
        originalPattern: pattern,
        _: {}
    };

    // Replace the pattern string with the one required by the specification, whilst
    // at the same time evaluating it for the subsets and formats
    formatObj.extendedPattern = pattern.replace(expDTComponents, function ($0) {
        // See which symbol we're dealing with
        return expDTComponentsMeta($0, formatObj._);
    });

    // Match the skeleton string with the one required by the specification
    // this implementation is based on the Date Field Symbol Table:
    // http://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
    // Note: we are adding extra data to the formatObject even though this polyfill
    //       might not support it.
    skeleton.replace(expDTComponents, function ($0) {
        // See which symbol we're dealing with
        return expDTComponentsMeta($0, formatObj);
    });

    return computeFinalPatterns(formatObj);
}

/**
 * Processes DateTime formats from CLDR to an easier-to-parse format.
 * the result of this operation should be cached the first time a particular
 * calendar is analyzed.
 *
 * The specification requires we support at least the following subsets of
 * date/time components:
 *
 *   - 'weekday', 'year', 'month', 'day', 'hour', 'minute', 'second'
 *   - 'weekday', 'year', 'month', 'day'
 *   - 'year', 'month', 'day'
 *   - 'year', 'month'
 *   - 'month', 'day'
 *   - 'hour', 'minute', 'second'
 *   - 'hour', 'minute'
 *
 * We need to cherry pick at least these subsets from the CLDR data and convert
 * them into the pattern objects used in the ECMA-402 API.
 */
function createDateTimeFormats(formats) {
    var availableFormats = formats.availableFormats;
    var timeFormats = formats.timeFormats;
    var dateFormats = formats.dateFormats;
    var result = [];
    var skeleton = void 0,
        pattern = void 0,
        computed = void 0,
        i = void 0,
        j = void 0;
    var timeRelatedFormats = [];
    var dateRelatedFormats = [];

    // Map available (custom) formats into a pattern for createDateTimeFormats
    for (skeleton in availableFormats) {
        if (availableFormats.hasOwnProperty(skeleton)) {
            pattern = availableFormats[skeleton];
            computed = createDateTimeFormat(skeleton, pattern);
            if (computed) {
                result.push(computed);
                // in some cases, the format is only displaying date specific props
                // or time specific props, in which case we need to also produce the
                // combined formats.
                if (isDateFormatOnly(computed)) {
                    dateRelatedFormats.push(computed);
                } else if (isTimeFormatOnly(computed)) {
                    timeRelatedFormats.push(computed);
                }
            }
        }
    }

    // Map time formats into a pattern for createDateTimeFormats
    for (skeleton in timeFormats) {
        if (timeFormats.hasOwnProperty(skeleton)) {
            pattern = timeFormats[skeleton];
            computed = createDateTimeFormat(skeleton, pattern);
            if (computed) {
                result.push(computed);
                timeRelatedFormats.push(computed);
            }
        }
    }

    // Map date formats into a pattern for createDateTimeFormats
    for (skeleton in dateFormats) {
        if (dateFormats.hasOwnProperty(skeleton)) {
            pattern = dateFormats[skeleton];
            computed = createDateTimeFormat(skeleton, pattern);
            if (computed) {
                result.push(computed);
                dateRelatedFormats.push(computed);
            }
        }
    }

    // combine custom time and custom date formats when they are orthogonals to complete the
    // formats supported by CLDR.
    // This Algo is based on section "Missing Skeleton Fields" from:
    // http://unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems
    for (i = 0; i < timeRelatedFormats.length; i += 1) {
        for (j = 0; j < dateRelatedFormats.length; j += 1) {
            if (dateRelatedFormats[j].month === 'long') {
                pattern = dateRelatedFormats[j].weekday ? formats.full : formats.long;
            } else if (dateRelatedFormats[j].month === 'short') {
                pattern = formats.medium;
            } else {
                pattern = formats.short;
            }
            computed = joinDateAndTimeFormats(dateRelatedFormats[j], timeRelatedFormats[i]);
            computed.originalPattern = pattern;
            computed.extendedPattern = pattern.replace('{0}', timeRelatedFormats[i].extendedPattern).replace('{1}', dateRelatedFormats[j].extendedPattern).replace(/^[,\s]+|[,\s]+$/gi, '');
            result.push(computeFinalPatterns(computed));
        }
    }

    return result;
}

// this represents the exceptions of the rule that are not covered by CLDR availableFormats
// for single property configurations, they play no role when using multiple properties, and
// those that are not in this table, are not exceptions or are not covered by the data we
// provide.
var validSyntheticProps = {
    second: {
        numeric: 's',
        '2-digit': 'ss'
    },
    minute: {
        numeric: 'm',
        '2-digit': 'mm'
    },
    year: {
        numeric: 'y',
        '2-digit': 'yy'
    },
    day: {
        numeric: 'd',
        '2-digit': 'dd'
    },
    month: {
        numeric: 'L',
        '2-digit': 'LL',
        narrow: 'LLLLL',
        short: 'LLL',
        long: 'LLLL'
    },
    weekday: {
        narrow: 'ccccc',
        short: 'ccc',
        long: 'cccc'
    }
};

function generateSyntheticFormat(propName, propValue) {
    if (validSyntheticProps[propName] && validSyntheticProps[propName][propValue]) {
        var _ref2;

        return _ref2 = {
            originalPattern: validSyntheticProps[propName][propValue],
            _: defineProperty$1({}, propName, propValue),
            extendedPattern: "{" + propName + "}"
        }, defineProperty$1(_ref2, propName, propValue), defineProperty$1(_ref2, "pattern12", "{" + propName + "}"), defineProperty$1(_ref2, "pattern", "{" + propName + "}"), _ref2;
    }
}

// An object map of date component keys, saves using a regex later
var dateWidths = objCreate(null, { narrow: {}, short: {}, long: {} });

/**
 * Returns a string for a date component, resolved using multiple inheritance as specified
 * as specified in the Unicode Technical Standard 35.
 */
function resolveDateString(data, ca, component, width, key) {
    // From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance:
    // 'In clearly specified instances, resources may inherit from within the same locale.
    //  For example, ... the Buddhist calendar inherits from the Gregorian calendar.'
    var obj = data[ca] && data[ca][component] ? data[ca][component] : data.gregory[component],


    // "sideways" inheritance resolves strings when a key doesn't exist
    alts = {
        narrow: ['short', 'long'],
        short: ['long', 'narrow'],
        long: ['short', 'narrow']
    },


    //
    resolved = hop.call(obj, width) ? obj[width] : hop.call(obj, alts[width][0]) ? obj[alts[width][0]] : obj[alts[width][1]];

    // `key` wouldn't be specified for components 'dayPeriods'
    return key !== null ? resolved[key] : resolved;
}

// Define the DateTimeFormat constructor internally so it cannot be tainted
function DateTimeFormatConstructor() {
    var locales = arguments[0];
    var options = arguments[1];

    if (!this || this === Intl) {
        return new Intl.DateTimeFormat(locales, options);
    }
    return InitializeDateTimeFormat(toObject(this), locales, options);
}

defineProperty(Intl, 'DateTimeFormat', {
    configurable: true,
    writable: true,
    value: DateTimeFormatConstructor
});

// Must explicitly set prototypes as unwritable
defineProperty(DateTimeFormatConstructor, 'prototype', {
    writable: false
});

/**
 * The abstract operation InitializeDateTimeFormat accepts the arguments dateTimeFormat
 * (which must be an object), locales, and options. It initializes dateTimeFormat as a
 * DateTimeFormat object.
 */
function /* 12.1.1.1 */InitializeDateTimeFormat(dateTimeFormat, locales, options) {
    // This will be a internal properties object if we're not already initialized
    var internal = getInternalProperties(dateTimeFormat);

    // Create an object whose props can be used to restore the values of RegExp props
    var regexpRestore = createRegExpRestore();

    // 1. If dateTimeFormat has an [[initializedIntlObject]] internal property with
    //    value true, throw a TypeError exception.
    if (internal['[[initializedIntlObject]]'] === true) throw new TypeError('`this` object has already been initialized as an Intl object');

    // Need this to access the `internal` object
    defineProperty(dateTimeFormat, '__getInternalProperties', {
        value: function value() {
            // NOTE: Non-standard, for internal use only
            if (arguments[0] === secret) return internal;
        }
    });

    // 2. Set the [[initializedIntlObject]] internal property of numberFormat to true.
    internal['[[initializedIntlObject]]'] = true;

    // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList
    //    abstract operation (defined in 9.2.1) with argument locales.
    var requestedLocales = CanonicalizeLocaleList(locales);

    // 4. Let options be the result of calling the ToDateTimeOptions abstract
    //    operation (defined below) with arguments options, "any", and "date".
    options = ToDateTimeOptions(options, 'any', 'date');

    // 5. Let opt be a new Record.
    var opt = new Record();

    // 6. Let matcher be the result of calling the GetOption abstract operation
    //    (defined in 9.2.9) with arguments options, "localeMatcher", "string", a List
    //    containing the two String values "lookup" and "best fit", and "best fit".
    var matcher = GetOption(options, 'localeMatcher', 'string', new List('lookup', 'best fit'), 'best fit');

    // 7. Set opt.[[localeMatcher]] to matcher.
    opt['[[localeMatcher]]'] = matcher;

    // 8. Let DateTimeFormat be the standard built-in object that is the initial
    //    value of Intl.DateTimeFormat.
    var DateTimeFormat = internals.DateTimeFormat; // This is what we *really* need

    // 9. Let localeData be the value of the [[localeData]] internal property of
    //    DateTimeFormat.
    var localeData = DateTimeFormat['[[localeData]]'];

    // 10. Let r be the result of calling the ResolveLocale abstract operation
    //     (defined in 9.2.5) with the [[availableLocales]] internal property of
    //      DateTimeFormat, requestedLocales, opt, the [[relevantExtensionKeys]]
    //      internal property of DateTimeFormat, and localeData.
    var r = ResolveLocale(DateTimeFormat['[[availableLocales]]'], requestedLocales, opt, DateTimeFormat['[[relevantExtensionKeys]]'], localeData);

    // 11. Set the [[locale]] internal property of dateTimeFormat to the value of
    //     r.[[locale]].
    internal['[[locale]]'] = r['[[locale]]'];

    // 12. Set the [[calendar]] internal property of dateTimeFormat to the value of
    //     r.[[ca]].
    internal['[[calendar]]'] = r['[[ca]]'];

    // 13. Set the [[numberingSystem]] internal property of dateTimeFormat to the value of
    //     r.[[nu]].
    internal['[[numberingSystem]]'] = r['[[nu]]'];

    // The specification doesn't tell us to do this, but it's helpful later on
    internal['[[dataLocale]]'] = r['[[dataLocale]]'];

    // 14. Let dataLocale be the value of r.[[dataLocale]].
    var dataLocale = r['[[dataLocale]]'];

    // 15. Let tz be the result of calling the [[Get]] internal method of options with
    //     argument "timeZone".
    var tz = options.timeZone;

    // 16. If tz is not undefined, then
    if (tz !== undefined) {
        // a. Let tz be ToString(tz).
        // b. Convert tz to upper case as described in 6.1.
        //    NOTE: If an implementation accepts additional time zone values, as permitted
        //          under certain conditions by the Conformance clause, different casing
        //          rules apply.
        tz = toLatinUpperCase(tz);

        // c. If tz is not "UTC", then throw a RangeError exception.
        // ###TODO: accept more time zones###
        if (tz !== 'UTC') throw new RangeError('timeZone is not supported.');
    }

    // 17. Set the [[timeZone]] internal property of dateTimeFormat to tz.
    internal['[[timeZone]]'] = tz;

    // 18. Let opt be a new Record.
    opt = new Record();

    // 19. For each row of Table 3, except the header row, do:
    for (var prop in dateTimeComponents) {
        if (!hop.call(dateTimeComponents, prop)) continue;

        // 20. Let prop be the name given in the Property column of the row.
        // 21. Let value be the result of calling the GetOption abstract operation,
        //     passing as argument options, the name given in the Property column of the
        //     row, "string", a List containing the strings given in the Values column of
        //     the row, and undefined.
        var value = GetOption(options, prop, 'string', dateTimeComponents[prop]);

        // 22. Set opt.[[<prop>]] to value.
        opt['[[' + prop + ']]'] = value;
    }

    // Assigned a value below
    var bestFormat = void 0;

    // 23. Let dataLocaleData be the result of calling the [[Get]] internal method of
    //     localeData with argument dataLocale.
    var dataLocaleData = localeData[dataLocale];

    // 24. Let formats be the result of calling the [[Get]] internal method of
    //     dataLocaleData with argument "formats".
    //     Note: we process the CLDR formats into the spec'd structure
    var formats = ToDateTimeFormats(dataLocaleData.formats);

    // 25. Let matcher be the result of calling the GetOption abstract operation with
    //     arguments options, "formatMatcher", "string", a List containing the two String
    //     values "basic" and "best fit", and "best fit".
    matcher = GetOption(options, 'formatMatcher', 'string', new List('basic', 'best fit'), 'best fit');

    // Optimization: caching the processed formats as a one time operation by
    // replacing the initial structure from localeData
    dataLocaleData.formats = formats;

    // 26. If matcher is "basic", then
    if (matcher === 'basic') {
        // 27. Let bestFormat be the result of calling the BasicFormatMatcher abstract
        //     operation (defined below) with opt and formats.
        bestFormat = BasicFormatMatcher(opt, formats);

        // 28. Else
    } else {
        {
            // diverging
            var _hr = GetOption(options, 'hour12', 'boolean' /*, undefined, undefined*/);
            opt.hour12 = _hr === undefined ? dataLocaleData.hour12 : _hr;
        }
        // 29. Let bestFormat be the result of calling the BestFitFormatMatcher
        //     abstract operation (defined below) with opt and formats.
        bestFormat = BestFitFormatMatcher(opt, formats);
    }

    // 30. For each row in Table 3, except the header row, do
    for (var _prop in dateTimeComponents) {
        if (!hop.call(dateTimeComponents, _prop)) continue;

        // a. Let prop be the name given in the Property column of the row.
        // b. Let pDesc be the result of calling the [[GetOwnProperty]] internal method of
        //    bestFormat with argument prop.
        // c. If pDesc is not undefined, then
        if (hop.call(bestFormat, _prop)) {
            // i. Let p be the result of calling the [[Get]] internal method of bestFormat
            //    with argument prop.
            var p = bestFormat[_prop];
            {
                // diverging
                p = bestFormat._ && hop.call(bestFormat._, _prop) ? bestFormat._[_prop] : p;
            }

            // ii. Set the [[<prop>]] internal property of dateTimeFormat to p.
            internal['[[' + _prop + ']]'] = p;
        }
    }

    var pattern = void 0; // Assigned a value below

    // 31. Let hr12 be the result of calling the GetOption abstract operation with
    //     arguments options, "hour12", "boolean", undefined, and undefined.
    var hr12 = GetOption(options, 'hour12', 'boolean' /*, undefined, undefined*/);

    // 32. If dateTimeFormat has an internal property [[hour]], then
    if (internal['[[hour]]']) {
        // a. If hr12 is undefined, then let hr12 be the result of calling the [[Get]]
        //    internal method of dataLocaleData with argument "hour12".
        hr12 = hr12 === undefined ? dataLocaleData.hour12 : hr12;

        // b. Set the [[hour12]] internal property of dateTimeFormat to hr12.
        internal['[[hour12]]'] = hr12;

        // c. If hr12 is true, then
        if (hr12 === true) {
            // i. Let hourNo0 be the result of calling the [[Get]] internal method of
            //    dataLocaleData with argument "hourNo0".
            var hourNo0 = dataLocaleData.hourNo0;

            // ii. Set the [[hourNo0]] internal property of dateTimeFormat to hourNo0.
            internal['[[hourNo0]]'] = hourNo0;

            // iii. Let pattern be the result of calling the [[Get]] internal method of
            //      bestFormat with argument "pattern12".
            pattern = bestFormat.pattern12;
        }

        // d. Else
        else
            // i. Let pattern be the result of calling the [[Get]] internal method of
            //    bestFormat with argument "pattern".
            pattern = bestFormat.pattern;
    }

    // 33. Else
    else
        // a. Let pattern be the result of calling the [[Get]] internal method of
        //    bestFormat with argument "pattern".
        pattern = bestFormat.pattern;

    // 34. Set the [[pattern]] internal property of dateTimeFormat to pattern.
    internal['[[pattern]]'] = pattern;

    // 35. Set the [[boundFormat]] internal property of dateTimeFormat to undefined.
    internal['[[boundFormat]]'] = undefined;

    // 36. Set the [[initializedDateTimeFormat]] internal property of dateTimeFormat to
    //     true.
    internal['[[initializedDateTimeFormat]]'] = true;

    // In ES3, we need to pre-bind the format() function
    if (es3) dateTimeFormat.format = GetFormatDateTime.call(dateTimeFormat);

    // Restore the RegExp properties
    regexpRestore();

    // Return the newly initialised object
    return dateTimeFormat;
}

/**
 * Several DateTimeFormat algorithms use values from the following table, which provides
 * property names and allowable values for the components of date and time formats:
 */
var dateTimeComponents = {
    weekday: ["narrow", "short", "long"],
    era: ["narrow", "short", "long"],
    year: ["2-digit", "numeric"],
    month: ["2-digit", "numeric", "narrow", "short", "long"],
    day: ["2-digit", "numeric"],
    hour: ["2-digit", "numeric"],
    minute: ["2-digit", "numeric"],
    second: ["2-digit", "numeric"],
    timeZoneName: ["short", "long"]
};

/**
 * When the ToDateTimeOptions abstract operation is called with arguments options,
 * required, and defaults, the following steps are taken:
 */
function ToDateTimeFormats(formats) {
    if (Object.prototype.toString.call(formats) === '[object Array]') {
        return formats;
    }
    return createDateTimeFormats(formats);
}

/**
 * When the ToDateTimeOptions abstract operation is called with arguments options,
 * required, and defaults, the following steps are taken:
 */
function ToDateTimeOptions(options, required, defaults) {
    // 1. If options is undefined, then let options be null, else let options be
    //    ToObject(options).
    if (options === undefined) options = null;else {
        // (#12) options needs to be a Record, but it also needs to inherit properties
        var opt2 = toObject(options);
        options = new Record();

        for (var k in opt2) {
            options[k] = opt2[k];
        }
    }

    // 2. Let create be the standard built-in function object defined in ES5, 15.2.3.5.
    var create = objCreate;

    // 3. Let options be the result of calling the [[Call]] internal method of create with
    //    undefined as the this value and an argument list containing the single item
    //    options.
    options = create(options);

    // 4. Let needDefaults be true.
    var needDefaults = true;

    // 5. If required is "date" or "any", then
    if (required === 'date' || required === 'any') {
        // a. For each of the property names "weekday", "year", "month", "day":
        // i. If the result of calling the [[Get]] internal method of options with the
        //    property name is not undefined, then let needDefaults be false.
        if (options.weekday !== undefined || options.year !== undefined || options.month !== undefined || options.day !== undefined) needDefaults = false;
    }

    // 6. If required is "time" or "any", then
    if (required === 'time' || required === 'any') {
        // a. For each of the property names "hour", "minute", "second":
        // i. If the result of calling the [[Get]] internal method of options with the
        //    property name is not undefined, then let needDefaults be false.
        if (options.hour !== undefined || options.minute !== undefined || options.second !== undefined) needDefaults = false;
    }

    // 7. If needDefaults is true and defaults is either "date" or "all", then
    if (needDefaults && (defaults === 'date' || defaults === 'all'))
        // a. For each of the property names "year", "month", "day":
        // i. Call the [[DefineOwnProperty]] internal method of options with the
        //    property name, Property Descriptor {[[Value]]: "numeric", [[Writable]]:
        //    true, [[Enumerable]]: true, [[Configurable]]: true}, and false.
        options.year = options.month = options.day = 'numeric';

    // 8. If needDefaults is true and defaults is either "time" or "all", then
    if (needDefaults && (defaults === 'time' || defaults === 'all'))
        // a. For each of the property names "hour", "minute", "second":
        // i. Call the [[DefineOwnProperty]] internal method of options with the
        //    property name, Property Descriptor {[[Value]]: "numeric", [[Writable]]:
        //    true, [[Enumerable]]: true, [[Configurable]]: true}, and false.
        options.hour = options.minute = options.second = 'numeric';

    // 9. Return options.
    return options;
}

/**
 * When the BasicFormatMatcher abstract operation is called with two arguments options and
 * formats, the following steps are taken:
 */
function BasicFormatMatcher(options, formats) {
    // 1. Let removalPenalty be 120.
    var removalPenalty = 120;

    // 2. Let additionPenalty be 20.
    var additionPenalty = 20;

    // 3. Let longLessPenalty be 8.
    var longLessPenalty = 8;

    // 4. Let longMorePenalty be 6.
    var longMorePenalty = 6;

    // 5. Let shortLessPenalty be 6.
    var shortLessPenalty = 6;

    // 6. Let shortMorePenalty be 3.
    var shortMorePenalty = 3;

    // 7. Let bestScore be -Infinity.
    var bestScore = -Infinity;

    // 8. Let bestFormat be undefined.
    var bestFormat = void 0;

    // 9. Let i be 0.
    var i = 0;

    // 10. Assert: formats is an Array object.

    // 11. Let len be the result of calling the [[Get]] internal method of formats with argument "length".
    var len = formats.length;

    // 12. Repeat while i < len:
    while (i < len) {
        // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i).
        var format = formats[i];

        // b. Let score be 0.
        var score = 0;

        // c. For each property shown in Table 3:
        for (var property in dateTimeComponents) {
            if (!hop.call(dateTimeComponents, property)) continue;

            // i. Let optionsProp be options.[[<property>]].
            var optionsProp = options['[[' + property + ']]'];

            // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format
            //     with argument property.
            // iii. If formatPropDesc is not undefined, then
            //     1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property.
            var formatProp = hop.call(format, property) ? format[property] : undefined;

            // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by
            //     additionPenalty.
            if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty;

            // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by
            //    removalPenalty.
            else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty;

                // vi. Else
                else {
                        // 1. Let values be the array ["2-digit", "numeric", "narrow", "short",
                        //    "long"].
                        var values = ['2-digit', 'numeric', 'narrow', 'short', 'long'];

                        // 2. Let optionsPropIndex be the index of optionsProp within values.
                        var optionsPropIndex = arrIndexOf.call(values, optionsProp);

                        // 3. Let formatPropIndex be the index of formatProp within values.
                        var formatPropIndex = arrIndexOf.call(values, formatProp);

                        // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2).
                        var delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2);

                        // 5. If delta = 2, decrease score by longMorePenalty.
                        if (delta === 2) score -= longMorePenalty;

                        // 6. Else if delta = 1, decrease score by shortMorePenalty.
                        else if (delta === 1) score -= shortMorePenalty;

                            // 7. Else if delta = -1, decrease score by shortLessPenalty.
                            else if (delta === -1) score -= shortLessPenalty;

                                // 8. Else if delta = -2, decrease score by longLessPenalty.
                                else if (delta === -2) score -= longLessPenalty;
                    }
        }

        // d. If score > bestScore, then
        if (score > bestScore) {
            // i. Let bestScore be score.
            bestScore = score;

            // ii. Let bestFormat be format.
            bestFormat = format;
        }

        // e. Increase i by 1.
        i++;
    }

    // 13. Return bestFormat.
    return bestFormat;
}

/**
 * When the BestFitFormatMatcher abstract operation is called with two arguments options
 * and formats, it performs implementation dependent steps, which should return a set of
 * component representations that a typical user of the selected locale would perceive as
 * at least as good as the one returned by BasicFormatMatcher.
 *
 * This polyfill defines the algorithm to be the same as BasicFormatMatcher,
 * with the addition of bonus points awarded where the requested format is of
 * the same data type as the potentially matching format.
 *
 * This algo relies on the concept of closest distance matching described here:
 * http://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons
 * Typically a “best match” is found using a closest distance match, such as:
 *
 * Symbols requesting a best choice for the locale are replaced.
 *      j → one of {H, k, h, K}; C → one of {a, b, B}
 * -> Covered by cldr.js matching process
 *
 * For fields with symbols representing the same type (year, month, day, etc):
 *     Most symbols have a small distance from each other.
 *         M ≅ L; E ≅ c; a ≅ b ≅ B; H ≅ k ≅ h ≅ K; ...
 *     -> Covered by cldr.js matching process
 *
 *     Width differences among fields, other than those marking text vs numeric, are given small distance from each other.
 *         MMM ≅ MMMM
 *         MM ≅ M
 *     Numeric and text fields are given a larger distance from each other.
 *         MMM ≈ MM
 *     Symbols representing substantial differences (week of year vs week of month) are given much larger a distances from each other.
 *         d ≋ D; ...
 *     Missing or extra fields cause a match to fail. (But see Missing Skeleton Fields).
 *
 *
 * For example,
 *
 *     { month: 'numeric', day: 'numeric' }
 *
 * should match
 *
 *     { month: '2-digit', day: '2-digit' }
 *
 * rather than
 *
 *     { month: 'short', day: 'numeric' }
 *
 * This makes sense because a user requesting a formatted date with numeric parts would
 * not expect to see the returned format containing narrow, short or long part names
 */
function BestFitFormatMatcher(options, formats) {
    /** Diverging: this block implements the hack for single property configuration, eg.:
     *
     *      `new Intl.DateTimeFormat('en', {day: 'numeric'})`
     *
     * should produce a single digit with the day of the month. This is needed because
     * CLDR `availableFormats` data structure doesn't cover these cases.
     */
    {
        var optionsPropNames = [];
        for (var property in dateTimeComponents) {
            if (!hop.call(dateTimeComponents, property)) continue;

            if (options['[[' + property + ']]'] !== undefined) {
                optionsPropNames.push(property);
            }
        }
        if (optionsPropNames.length === 1) {
            var _bestFormat = generateSyntheticFormat(optionsPropNames[0], options['[[' + optionsPropNames[0] + ']]']);
            if (_bestFormat) {
                return _bestFormat;
            }
        }
    }

    // 1. Let removalPenalty be 120.
    var removalPenalty = 120;

    // 2. Let additionPenalty be 20.
    var additionPenalty = 20;

    // 3. Let longLessPenalty be 8.
    var longLessPenalty = 8;

    // 4. Let longMorePenalty be 6.
    var longMorePenalty = 6;

    // 5. Let shortLessPenalty be 6.
    var shortLessPenalty = 6;

    // 6. Let shortMorePenalty be 3.
    var shortMorePenalty = 3;

    var patternPenalty = 2;

    var hour12Penalty = 1;

    // 7. Let bestScore be -Infinity.
    var bestScore = -Infinity;

    // 8. Let bestFormat be undefined.
    var bestFormat = void 0;

    // 9. Let i be 0.
    var i = 0;

    // 10. Assert: formats is an Array object.

    // 11. Let len be the result of calling the [[Get]] internal method of formats with argument "length".
    var len = formats.length;

    // 12. Repeat while i < len:
    while (i < len) {
        // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i).
        var format = formats[i];

        // b. Let score be 0.
        var score = 0;

        // c. For each property shown in Table 3:
        for (var _property in dateTimeComponents) {
            if (!hop.call(dateTimeComponents, _property)) continue;

            // i. Let optionsProp be options.[[<property>]].
            var optionsProp = options['[[' + _property + ']]'];

            // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format
            //     with argument property.
            // iii. If formatPropDesc is not undefined, then
            //     1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property.
            var formatProp = hop.call(format, _property) ? format[_property] : undefined;

            // Diverging: using the default properties produced by the pattern/skeleton
            // to match it with user options, and apply a penalty
            var patternProp = hop.call(format._, _property) ? format._[_property] : undefined;
            if (optionsProp !== patternProp) {
                score -= patternPenalty;
            }

            // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by
            //     additionPenalty.
            if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty;

            // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by
            //    removalPenalty.
            else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty;

                // vi. Else
                else {
                        // 1. Let values be the array ["2-digit", "numeric", "narrow", "short",
                        //    "long"].
                        var values = ['2-digit', 'numeric', 'narrow', 'short', 'long'];

                        // 2. Let optionsPropIndex be the index of optionsProp within values.
                        var optionsPropIndex = arrIndexOf.call(values, optionsProp);

                        // 3. Let formatPropIndex be the index of formatProp within values.
                        var formatPropIndex = arrIndexOf.call(values, formatProp);

                        // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2).
                        var delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2);

                        {
                            // diverging from spec
                            // When the bestFit argument is true, subtract additional penalty where data types are not the same
                            if (formatPropIndex <= 1 && optionsPropIndex >= 2 || formatPropIndex >= 2 && optionsPropIndex <= 1) {
                                // 5. If delta = 2, decrease score by longMorePenalty.
                                if (delta > 0) score -= longMorePenalty;else if (delta < 0) score -= longLessPenalty;
                            } else {
                                // 5. If delta = 2, decrease score by longMorePenalty.
                                if (delta > 1) score -= shortMorePenalty;else if (delta < -1) score -= shortLessPenalty;
                            }
                        }
                    }
        }

        {
            // diverging to also take into consideration differences between 12 or 24 hours
            // which is special for the best fit only.
            if (format._.hour12 !== options.hour12) {
                score -= hour12Penalty;
            }
        }

        // d. If score > bestScore, then
        if (score > bestScore) {
            // i. Let bestScore be score.
            bestScore = score;
            // ii. Let bestFormat be format.
            bestFormat = format;
        }

        // e. Increase i by 1.
        i++;
    }

    // 13. Return bestFormat.
    return bestFormat;
}

/* 12.2.3 */internals.DateTimeFormat = {
    '[[availableLocales]]': [],
    '[[relevantExtensionKeys]]': ['ca', 'nu'],
    '[[localeData]]': {}
};

/**
 * When the supportedLocalesOf method of Intl.DateTimeFormat is called, the
 * following steps are taken:
 */
/* 12.2.2 */
defineProperty(Intl.DateTimeFormat, 'supportedLocalesOf', {
    configurable: true,
    writable: true,
    value: fnBind.call(function (locales) {
        // Bound functions only have the `this` value altered if being used as a constructor,
        // this lets us imitate a native function that has no constructor
        if (!hop.call(this, '[[availableLocales]]')) throw new TypeError('supportedLocalesOf() is not a constructor');

        // Create an object whose props can be used to restore the values of RegExp props
        var regexpRestore = createRegExpRestore(),


        // 1. If options is not provided, then let options be undefined.
        options = arguments[1],


        // 2. Let availableLocales be the value of the [[availableLocales]] internal
        //    property of the standard built-in object that is the initial value of
        //    Intl.NumberFormat.

        availableLocales = this['[[availableLocales]]'],


        // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList
        //    abstract operation (defined in 9.2.1) with argument locales.
        requestedLocales = CanonicalizeLocaleList(locales);

        // Restore the RegExp properties
        regexpRestore();

        // 4. Return the result of calling the SupportedLocales abstract operation
        //    (defined in 9.2.8) with arguments availableLocales, requestedLocales,
        //    and options.
        return SupportedLocales(availableLocales, requestedLocales, options);
    }, internals.NumberFormat)
});

/**
 * This named accessor property returns a function that formats a number
 * according to the effective locale and the formatting options of this
 * DateTimeFormat object.
 */
/* 12.3.2 */defineProperty(Intl.DateTimeFormat.prototype, 'format', {
    configurable: true,
    get: GetFormatDateTime
});

function GetFormatDateTime() {
    var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this);

    // Satisfy test 12.3_b
    if (!internal || !internal['[[initializedDateTimeFormat]]']) throw new TypeError('`this` value for format() is not an initialized Intl.DateTimeFormat object.');

    // The value of the [[Get]] attribute is a function that takes the following
    // steps:

    // 1. If the [[boundFormat]] internal property of this DateTimeFormat object
    //    is undefined, then:
    if (internal['[[boundFormat]]'] === undefined) {
        // a. Let F be a Function object, with internal properties set as
        //    specified for built-in functions in ES5, 15, or successor, and the
        //    length property set to 0, that takes the argument date and
        //    performs the following steps:
        var F = function F() {
            var date = arguments.length <= 0 || arguments[0] === undefined ? undefined : arguments[0];

            //   i. If date is not provided or is undefined, then let x be the
            //      result as if by the expression Date.now() where Date.now is
            //      the standard built-in function defined in ES5, 15.9.4.4.
            //  ii. Else let x be ToNumber(date).
            // iii. Return the result of calling the FormatDateTime abstract
            //      operation (defined below) with arguments this and x.
            var x = date === undefined ? Date.now() : toNumber(date);
            return FormatDateTime(this, x);
        };
        // b. Let bind be the standard built-in function object defined in ES5,
        //    15.3.4.5.
        // c. Let bf be the result of calling the [[Call]] internal method of
        //    bind with F as the this value and an argument list containing
        //    the single item this.
        var bf = fnBind.call(F, this);
        // d. Set the [[boundFormat]] internal property of this NumberFormat
        //    object to bf.
        internal['[[boundFormat]]'] = bf;
    }
    // Return the value of the [[boundFormat]] internal property of this
    // NumberFormat object.
    return internal['[[boundFormat]]'];
}

function formatToParts$1() {
    var date = arguments.length <= 0 || arguments[0] === undefined ? undefined : arguments[0];

    var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this);

    if (!internal || !internal['[[initializedDateTimeFormat]]']) throw new TypeError('`this` value for formatToParts() is not an initialized Intl.DateTimeFormat object.');

    var x = date === undefined ? Date.now() : toNumber(date);
    return FormatToPartsDateTime(this, x);
}

Object.defineProperty(Intl.DateTimeFormat.prototype, 'formatToParts', {
    enumerable: false,
    writable: true,
    configurable: true,
    value: formatToParts$1
});

function CreateDateTimeParts(dateTimeFormat, x) {
    // 1. If x is not a finite Number, then throw a RangeError exception.
    if (!isFinite(x)) throw new RangeError('Invalid valid date passed to format');

    var internal = dateTimeFormat.__getInternalProperties(secret);

    // Creating restore point for properties on the RegExp object... please wait
    /* let regexpRestore = */createRegExpRestore(); // ###TODO: review this

    // 2. Let locale be the value of the [[locale]] internal property of dateTimeFormat.
    var locale = internal['[[locale]]'];

    // 3. Let nf be the result of creating a new NumberFormat object as if by the
    // expression new Intl.NumberFormat([locale], {useGrouping: false}) where
    // Intl.NumberFormat is the standard built-in constructor defined in 11.1.3.
    var nf = new Intl.NumberFormat([locale], { useGrouping: false });

    // 4. Let nf2 be the result of creating a new NumberFormat object as if by the
    // expression new Intl.NumberFormat([locale], {minimumIntegerDigits: 2, useGrouping:
    // false}) where Intl.NumberFormat is the standard built-in constructor defined in
    // 11.1.3.
    var nf2 = new Intl.NumberFormat([locale], { minimumIntegerDigits: 2, useGrouping: false });

    // 5. Let tm be the result of calling the ToLocalTime abstract operation (defined
    // below) with x, the value of the [[calendar]] internal property of dateTimeFormat,
    // and the value of the [[timeZone]] internal property of dateTimeFormat.
    var tm = ToLocalTime(x, internal['[[calendar]]'], internal['[[timeZone]]']);

    // 6. Let result be the value of the [[pattern]] internal property of dateTimeFormat.
    var pattern = internal['[[pattern]]'];

    // 7.
    var result = new List();

    // 8.
    var index = 0;

    // 9.
    var beginIndex = pattern.indexOf('{');

    // 10.
    var endIndex = 0;

    // Need the locale minus any extensions
    var dataLocale = internal['[[dataLocale]]'];

    // Need the calendar data from CLDR
    var localeData = internals.DateTimeFormat['[[localeData]]'][dataLocale].calendars;
    var ca = internal['[[calendar]]'];

    // 11.
    while (beginIndex !== -1) {
        var fv = void 0;
        // a.
        endIndex = pattern.indexOf('}', beginIndex);
        // b.
        if (endIndex === -1) {
            throw new Error('Unclosed pattern');
        }
        // c.
        if (beginIndex > index) {
            arrPush.call(result, {
                type: 'literal',
                value: pattern.substring(index, beginIndex)
            });
        }
        // d.
        var p = pattern.substring(beginIndex + 1, endIndex);
        // e.
        if (dateTimeComponents.hasOwnProperty(p)) {
            //   i. Let f be the value of the [[<p>]] internal property of dateTimeFormat.
            var f = internal['[[' + p + ']]'];
            //  ii. Let v be the value of tm.[[<p>]].
            var v = tm['[[' + p + ']]'];
            // iii. If p is "year" and v ≤ 0, then let v be 1 - v.
            if (p === 'year' && v <= 0) {
                v = 1 - v;
            }
            //  iv. If p is "month", then increase v by 1.
            else if (p === 'month') {
                    v++;
                }
                //   v. If p is "hour" and the value of the [[hour12]] internal property of
                //      dateTimeFormat is true, then
                else if (p === 'hour' && internal['[[hour12]]'] === true) {
                        // 1. Let v be v modulo 12.
                        v = v % 12;
                        // 2. If v is 0 and the value of the [[hourNo0]] internal property of
                        //    dateTimeFormat is true, then let v be 12.
                        if (v === 0 && internal['[[hourNo0]]'] === true) {
                            v = 12;
                        }
                    }

            //  vi. If f is "numeric", then
            if (f === 'numeric') {
                // 1. Let fv be the result of calling the FormatNumber abstract operation
                //    (defined in 11.3.2) with arguments nf and v.
                fv = FormatNumber(nf, v);
            }
            // vii. Else if f is "2-digit", then
            else if (f === '2-digit') {
                    // 1. Let fv be the result of calling the FormatNumber abstract operation
                    //    with arguments nf2 and v.
                    fv = FormatNumber(nf2, v);
                    // 2. If the length of fv is greater than 2, let fv be the substring of fv
                    //    containing the last two characters.
                    if (fv.length > 2) {
                        fv = fv.slice(-2);
                    }
                }
                // viii. Else if f is "narrow", "short", or "long", then let fv be a String
                //     value representing f in the desired form; the String value depends upon
                //     the implementation and the effective locale and calendar of
                //     dateTimeFormat. If p is "month", then the String value may also depend
                //     on whether dateTimeFormat has a [[day]] internal property. If p is
                //     "timeZoneName", then the String value may also depend on the value of
                //     the [[inDST]] field of tm.
                else if (f in dateWidths) {
                        switch (p) {
                            case 'month':
                                fv = resolveDateString(localeData, ca, 'months', f, tm['[[' + p + ']]']);
                                break;

                            case 'weekday':
                                try {
                                    fv = resolveDateString(localeData, ca, 'days', f, tm['[[' + p + ']]']);
                                    // fv = resolveDateString(ca.days, f)[tm['[['+ p +']]']];
                                } catch (e) {
                                    throw new Error('Could not find weekday data for locale ' + locale);
                                }
                                break;

                            case 'timeZoneName':
                                fv = ''; // ###TODO
                                break;

                            case 'era':
                                try {
                                    fv = resolveDateString(localeData, ca, 'eras', f, tm['[[' + p + ']]']);
                                } catch (e) {
                                    throw new Error('Could not find era data for locale ' + locale);
                                }
                                break;

                            default:
                                fv = tm['[[' + p + ']]'];
                        }
                    }
            // ix
            arrPush.call(result, {
                type: p,
                value: fv
            });
            // f.
        } else if (p === 'ampm') {
            // i.
            var _v = tm['[[hour]]'];
            // ii./iii.
            fv = resolveDateString(localeData, ca, 'dayPeriods', _v > 11 ? 'pm' : 'am', null);
            // iv.
            arrPush.call(result, {
                type: 'dayPeriod',
                value: fv
            });
            // g.
        } else {
            arrPush.call(result, {
                type: 'literal',
                value: pattern.substring(beginIndex, endIndex + 1)
            });
        }
        // h.
        index = endIndex + 1;
        // i.
        beginIndex = pattern.indexOf('{', index);
    }
    // 12.
    if (endIndex < pattern.length - 1) {
        arrPush.call(result, {
            type: 'literal',
            value: pattern.substr(endIndex + 1)
        });
    }
    // 13.
    return result;
}

/**
 * When the FormatDateTime abstract operation is called with arguments dateTimeFormat
 * (which must be an object initialized as a DateTimeFormat) and x (which must be a Number
 * value), it returns a String value representing x (interpreted as a time value as
 * specified in ES5, 15.9.1.1) according to the effective locale and the formatting
 * options of dateTimeFormat.
 */
function FormatDateTime(dateTimeFormat, x) {
    var parts = CreateDateTimeParts(dateTimeFormat, x);
    var result = '';

    for (var i = 0; parts.length > i; i++) {
        var part = parts[i];
        result += part.value;
    }
    return result;
}

function FormatToPartsDateTime(dateTimeFormat, x) {
    var parts = CreateDateTimeParts(dateTimeFormat, x);
    var result = [];
    for (var i = 0; parts.length > i; i++) {
        var part = parts[i];
        result.push({
            type: part.type,
            value: part.value
        });
    }
    return result;
}

/**
 * When the ToLocalTime abstract operation is called with arguments date, calendar, and
 * timeZone, the following steps are taken:
 */
function ToLocalTime(date, calendar, timeZone) {
    // 1. Apply calendrical calculations on date for the given calendar and time zone to
    //    produce weekday, era, year, month, day, hour, minute, second, and inDST values.
    //    The calculations should use best available information about the specified
    //    calendar and time zone. If the calendar is "gregory", then the calculations must
    //    match the algorithms specified in ES5, 15.9.1, except that calculations are not
    //    bound by the restrictions on the use of best available information on time zones
    //    for local time zone adjustment and daylight saving time adjustment imposed by
    //    ES5, 15.9.1.7 and 15.9.1.8.
    // ###TODO###
    var d = new Date(date),
        m = 'get' + (timeZone || '');

    // 2. Return a Record with fields [[weekday]], [[era]], [[year]], [[month]], [[day]],
    //    [[hour]], [[minute]], [[second]], and [[inDST]], each with the corresponding
    //    calculated value.
    return new Record({
        '[[weekday]]': d[m + 'Day'](),
        '[[era]]': +(d[m + 'FullYear']() >= 0),
        '[[year]]': d[m + 'FullYear'](),
        '[[month]]': d[m + 'Month'](),
        '[[day]]': d[m + 'Date'](),
        '[[hour]]': d[m + 'Hours'](),
        '[[minute]]': d[m + 'Minutes'](),
        '[[second]]': d[m + 'Seconds'](),
        '[[inDST]]': false // ###TODO###
    });
}

/**
 * The function returns a new object whose properties and attributes are set as if
 * constructed by an object literal assigning to each of the following properties the
 * value of the corresponding internal property of this DateTimeFormat object (see 12.4):
 * locale, calendar, numberingSystem, timeZone, hour12, weekday, era, year, month, day,
 * hour, minute, second, and timeZoneName. Properties whose corresponding internal
 * properties are not present are not assigned.
 */
/* 12.3.3 */defineProperty(Intl.DateTimeFormat.prototype, 'resolvedOptions', {
    writable: true,
    configurable: true,
    value: function value() {
        var prop = void 0,
            descs = new Record(),
            props = ['locale', 'calendar', 'numberingSystem', 'timeZone', 'hour12', 'weekday', 'era', 'year', 'month', 'day', 'hour', 'minute', 'second', 'timeZoneName'],
            internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this);

        // Satisfy test 12.3_b
        if (!internal || !internal['[[initializedDateTimeFormat]]']) throw new TypeError('`this` value for resolvedOptions() is not an initialized Intl.DateTimeFormat object.');

        for (var i = 0, max = props.length; i < max; i++) {
            if (hop.call(internal, prop = '[[' + props[i] + ']]')) descs[props[i]] = { value: internal[prop], writable: true, configurable: true, enumerable: true };
        }

        return objCreate({}, descs);
    }
});

var ls = Intl.__localeSensitiveProtos = {
    Number: {},
    Date: {}
};

/**
 * When the toLocaleString method is called with optional arguments locales and options,
 * the following steps are taken:
 */
/* 13.2.1 */ls.Number.toLocaleString = function () {
    // Satisfy test 13.2.1_1
    if (Object.prototype.toString.call(this) !== '[object Number]') throw new TypeError('`this` value must be a number for Number.prototype.toLocaleString()');

    // 1. Let x be this Number value (as defined in ES5, 15.7.4).
    // 2. If locales is not provided, then let locales be undefined.
    // 3. If options is not provided, then let options be undefined.
    // 4. Let numberFormat be the result of creating a new object as if by the
    //    expression new Intl.NumberFormat(locales, options) where
    //    Intl.NumberFormat is the standard built-in constructor defined in 11.1.3.
    // 5. Return the result of calling the FormatNumber abstract operation
    //    (defined in 11.3.2) with arguments numberFormat and x.
    return FormatNumber(new NumberFormatConstructor(arguments[0], arguments[1]), this);
};

/**
 * When the toLocaleString method is called with optional arguments locales and options,
 * the following steps are taken:
 */
/* 13.3.1 */ls.Date.toLocaleString = function () {
    // Satisfy test 13.3.0_1
    if (Object.prototype.toString.call(this) !== '[object Date]') throw new TypeError('`this` value must be a Date instance for Date.prototype.toLocaleString()');

    // 1. Let x be this time value (as defined in ES5, 15.9.5).
    var x = +this;

    // 2. If x is NaN, then return "Invalid Date".
    if (isNaN(x)) return 'Invalid Date';

    // 3. If locales is not provided, then let locales be undefined.
    var locales = arguments[0];

    // 4. If options is not provided, then let options be undefined.
    var options = arguments[1];

    // 5. Let options be the result of calling the ToDateTimeOptions abstract
    //    operation (defined in 12.1.1) with arguments options, "any", and "all".
    options = ToDateTimeOptions(options, 'any', 'all');

    // 6. Let dateTimeFormat be the result of creating a new object as if by the
    //    expression new Intl.DateTimeFormat(locales, options) where
    //    Intl.DateTimeFormat is the standard built-in constructor defined in 12.1.3.
    var dateTimeFormat = new DateTimeFormatConstructor(locales, options);

    // 7. Return the result of calling the FormatDateTime abstract operation (defined
    //    in 12.3.2) with arguments dateTimeFormat and x.
    return FormatDateTime(dateTimeFormat, x);
};

/**
 * When the toLocaleDateString method is called with optional arguments locales and
 * options, the following steps are taken:
 */
/* 13.3.2 */ls.Date.toLocaleDateString = function () {
    // Satisfy test 13.3.0_1
    if (Object.prototype.toString.call(this) !== '[object Date]') throw new TypeError('`this` value must be a Date instance for Date.prototype.toLocaleDateString()');

    // 1. Let x be this time value (as defined in ES5, 15.9.5).
    var x = +this;

    // 2. If x is NaN, then return "Invalid Date".
    if (isNaN(x)) return 'Invalid Date';

    // 3. If locales is not provided, then let locales be undefined.
    var locales = arguments[0],


    // 4. If options is not provided, then let options be undefined.
    options = arguments[1];

    // 5. Let options be the result of calling the ToDateTimeOptions abstract
    //    operation (defined in 12.1.1) with arguments options, "date", and "date".
    options = ToDateTimeOptions(options, 'date', 'date');

    // 6. Let dateTimeFormat be the result of creating a new object as if by the
    //    expression new Intl.DateTimeFormat(locales, options) where
    //    Intl.DateTimeFormat is the standard built-in constructor defined in 12.1.3.
    var dateTimeFormat = new DateTimeFormatConstructor(locales, options);

    // 7. Return the result of calling the FormatDateTime abstract operation (defined
    //    in 12.3.2) with arguments dateTimeFormat and x.
    return FormatDateTime(dateTimeFormat, x);
};

/**
 * When the toLocaleTimeString method is called with optional arguments locales and
 * options, the following steps are taken:
 */
/* 13.3.3 */ls.Date.toLocaleTimeString = function () {
    // Satisfy test 13.3.0_1
    if (Object.prototype.toString.call(this) !== '[object Date]') throw new TypeError('`this` value must be a Date instance for Date.prototype.toLocaleTimeString()');

    // 1. Let x be this time value (as defined in ES5, 15.9.5).
    var x = +this;

    // 2. If x is NaN, then return "Invalid Date".
    if (isNaN(x)) return 'Invalid Date';

    // 3. If locales is not provided, then let locales be undefined.
    var locales = arguments[0];

    // 4. If options is not provided, then let options be undefined.
    var options = arguments[1];

    // 5. Let options be the result of calling the ToDateTimeOptions abstract
    //    operation (defined in 12.1.1) with arguments options, "time", and "time".
    options = ToDateTimeOptions(options, 'time', 'time');

    // 6. Let dateTimeFormat be the result of creating a new object as if by the
    //    expression new Intl.DateTimeFormat(locales, options) where
    //    Intl.DateTimeFormat is the standard built-in constructor defined in 12.1.3.
    var dateTimeFormat = new DateTimeFormatConstructor(locales, options);

    // 7. Return the result of calling the FormatDateTime abstract operation (defined
    //    in 12.3.2) with arguments dateTimeFormat and x.
    return FormatDateTime(dateTimeFormat, x);
};

defineProperty(Intl, '__applyLocaleSensitivePrototypes', {
    writable: true,
    configurable: true,
    value: function value() {
        defineProperty(Number.prototype, 'toLocaleString', { writable: true, configurable: true, value: ls.Number.toLocaleString });
        // Need this here for IE 8, to avoid the _DontEnum_ bug
        defineProperty(Date.prototype, 'toLocaleString', { writable: true, configurable: true, value: ls.Date.toLocaleString });

        for (var k in ls.Date) {
            if (hop.call(ls.Date, k)) defineProperty(Date.prototype, k, { writable: true, configurable: true, value: ls.Date[k] });
        }
    }
});

/**
 * Can't really ship a single script with data for hundreds of locales, so we provide
 * this __addLocaleData method as a means for the developer to add the data on an
 * as-needed basis
 */
defineProperty(Intl, '__addLocaleData', {
    value: function value(data) {
        if (!IsStructurallyValidLanguageTag(data.locale)) throw new Error("Object passed doesn't identify itself with a valid language tag");

        addLocaleData(data, data.locale);
    }
});

function addLocaleData(data, tag) {
    // Both NumberFormat and DateTimeFormat require number data, so throw if it isn't present
    if (!data.number) throw new Error("Object passed doesn't contain locale data for Intl.NumberFormat");

    var locale = void 0,
        locales = [tag],
        parts = tag.split('-');

    // Create fallbacks for locale data with scripts, e.g. Latn, Hans, Vaii, etc
    if (parts.length > 2 && parts[1].length === 4) arrPush.call(locales, parts[0] + '-' + parts[2]);

    while (locale = arrShift.call(locales)) {
        // Add to NumberFormat internal properties as per 11.2.3
        arrPush.call(internals.NumberFormat['[[availableLocales]]'], locale);
        internals.NumberFormat['[[localeData]]'][locale] = data.number;

        // ...and DateTimeFormat internal properties as per 12.2.3
        if (data.date) {
            data.date.nu = data.number.nu;
            arrPush.call(internals.DateTimeFormat['[[availableLocales]]'], locale);
            internals.DateTimeFormat['[[localeData]]'][locale] = data.date;
        }
    }

    // If this is the first set of locale data added, make it the default
    if (defaultLocale === undefined) setDefaultLocale(tag);
}

defineProperty(Intl, '__disableRegExpRestore', {
    value: function value() {
        internals.disableRegExpRestore = true;
    }
});

module.exports = Intl;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(9)))

/***/ }),
/* 40 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 41 */
/***/ (function(module, exports) {

/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
module.exports = __webpack_amd_options__;

/* WEBPACK VAR INJECTION */}.call(this, {}))

/***/ }),
/* 42 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// NAMESPACE OBJECT: ./src/String/stringGenerate.js
var stringGenerate_namespaceObject = {};
__webpack_require__.r(stringGenerate_namespaceObject);
__webpack_require__.d(stringGenerate_namespaceObject, "identCharacters", function() { return identCharacters; });
__webpack_require__.d(stringGenerate_namespaceObject, "randomIdent", function() { return randomIdent; });
__webpack_require__.d(stringGenerate_namespaceObject, "parallelMatch", function() { return parallelMatch; });
__webpack_require__.d(stringGenerate_namespaceObject, "ipsumLoremWord", function() { return ipsumLoremWord; });
__webpack_require__.d(stringGenerate_namespaceObject, "randomWord", function() { return randomWord; });
__webpack_require__.d(stringGenerate_namespaceObject, "randomPhrase", function() { return randomPhrase; });
__webpack_require__.d(stringGenerate_namespaceObject, "randomSentence", function() { return randomSentence; });
__webpack_require__.d(stringGenerate_namespaceObject, "randomParagraph", function() { return randomParagraph; });

// NAMESPACE OBJECT: ./src/HTML5/Text.js
var Text_namespaceObject = {};
__webpack_require__.r(Text_namespaceObject);
__webpack_require__.d(Text_namespaceObject, "getTextNodesIn", function() { return getTextNodesIn; });
__webpack_require__.d(Text_namespaceObject, "setSelectionRangeStart", function() { return setSelectionRangeStart; });
__webpack_require__.d(Text_namespaceObject, "setSelectionRangeEnd", function() { return setSelectionRangeEnd; });
__webpack_require__.d(Text_namespaceObject, "setSelectionRange", function() { return setSelectionRange; });
__webpack_require__.d(Text_namespaceObject, "getTextIn", function() { return getTextIn; });
__webpack_require__.d(Text_namespaceObject, "textToNodes", function() { return textToNodes; });
__webpack_require__.d(Text_namespaceObject, "getCaretPosition", function() { return getCaretPosition; });
__webpack_require__.d(Text_namespaceObject, "setCaretPosition", function() { return setCaretPosition; });
__webpack_require__.d(Text_namespaceObject, "measureText", function() { return measureText; });

// NAMESPACE OBJECT: ./src/Converter/file.js
var file_namespaceObject = {};
__webpack_require__.r(file_namespaceObject);
__webpack_require__.d(file_namespaceObject, "blobToFile", function() { return blobToFile; });
__webpack_require__.d(file_namespaceObject, "dataURItoBlob", function() { return dataURItoBlob; });
__webpack_require__.d(file_namespaceObject, "blobToArrayBuffer", function() { return blobToArrayBuffer; });
__webpack_require__.d(file_namespaceObject, "stringToBlob", function() { return stringToBlob; });

// NAMESPACE OBJECT: ./src/Converter/base64.js
var base64_namespaceObject = {};
__webpack_require__.r(base64_namespaceObject);
__webpack_require__.d(base64_namespaceObject, "base64EncodeUnicode", function() { return base64EncodeUnicode; });
__webpack_require__.d(base64_namespaceObject, "base64DecodeUnicode", function() { return base64DecodeUnicode; });
__webpack_require__.d(base64_namespaceObject, "UnicodeBase64Converter", function() { return UnicodeBase64Converter; });

// NAMESPACE OBJECT: ./src/String/stringFormat.js
var stringFormat_namespaceObject = {};
__webpack_require__.r(stringFormat_namespaceObject);
__webpack_require__.d(stringFormat_namespaceObject, "wrapToLines", function() { return wrapToLines; });
__webpack_require__.d(stringFormat_namespaceObject, "nonAccentVietnamese", function() { return nonAccentVietnamese; });
__webpack_require__.d(stringFormat_namespaceObject, "pascalCaseToCamelCase", function() { return pascalCaseToCamelCase; });
__webpack_require__.d(stringFormat_namespaceObject, "kebabCaseToCamelCase", function() { return kebabCaseToCamelCase; });
__webpack_require__.d(stringFormat_namespaceObject, "underScoreToCamelCase", function() { return underScoreToCamelCase; });
__webpack_require__.d(stringFormat_namespaceObject, "camelCaseToPascalCase", function() { return camelCaseToPascalCase; });
__webpack_require__.d(stringFormat_namespaceObject, "underScoreToPascalCase", function() { return underScoreToPascalCase; });
__webpack_require__.d(stringFormat_namespaceObject, "kebabCaseToPascalCase", function() { return kebabCaseToPascalCase; });
__webpack_require__.d(stringFormat_namespaceObject, "pascalCaseToKebabCase", function() { return pascalCaseToKebabCase; });
__webpack_require__.d(stringFormat_namespaceObject, "camelCaseToKebabCase", function() { return camelCaseToKebabCase; });
__webpack_require__.d(stringFormat_namespaceObject, "underScoreToKebabCase", function() { return underScoreToKebabCase; });
__webpack_require__.d(stringFormat_namespaceObject, "pascalCaseToUnderScore", function() { return pascalCaseToUnderScore; });
__webpack_require__.d(stringFormat_namespaceObject, "pascalCaseToUpperUnderScore", function() { return pascalCaseToUpperUnderScore; });
__webpack_require__.d(stringFormat_namespaceObject, "camelCaseToUnderScore", function() { return camelCaseToUnderScore; });
__webpack_require__.d(stringFormat_namespaceObject, "camelCaseToUpperUnderScore", function() { return camelCaseToUpperUnderScore; });
__webpack_require__.d(stringFormat_namespaceObject, "kebabCaseToUnderScore", function() { return kebabCaseToUnderScore; });
__webpack_require__.d(stringFormat_namespaceObject, "kebabCaseToUpperUnderScore", function() { return kebabCaseToUpperUnderScore; });
__webpack_require__.d(stringFormat_namespaceObject, "normalizeIdent", function() { return normalizeIdent; });

// NAMESPACE OBJECT: ./src/JSX/dom.js
var dom_namespaceObject = {};
__webpack_require__.r(dom_namespaceObject);
__webpack_require__.d(dom_namespaceObject, "domVisitor", function() { return domVisitor; });
__webpack_require__.d(dom_namespaceObject, "parseDom", function() { return parseDom; });

// NAMESPACE OBJECT: ./src/Math/int.js
var int_namespaceObject = {};
__webpack_require__.r(int_namespaceObject);
__webpack_require__.d(int_namespaceObject, "map", function() { return map; });
__webpack_require__.d(int_namespaceObject, "sumArr", function() { return sumArr; });
__webpack_require__.d(int_namespaceObject, "radianInRange", function() { return radianInRange; });
__webpack_require__.d(int_namespaceObject, "distance", function() { return distance; });
__webpack_require__.d(int_namespaceObject, "numberToString", function() { return numberToString; });
__webpack_require__.d(int_namespaceObject, "numberAutoFixed", function() { return numberAutoFixed; });
__webpack_require__.d(int_namespaceObject, "integerZeroPadding", function() { return integerZeroPadding; });
__webpack_require__.d(int_namespaceObject, "harmonicMean", function() { return harmonicMean; });

// NAMESPACE OBJECT: ./src/HTML5/Clipboard.js
var Clipboard_namespaceObject = {};
__webpack_require__.r(Clipboard_namespaceObject);
__webpack_require__.d(Clipboard_namespaceObject, "copyImage", function() { return copyImage; });
__webpack_require__.d(Clipboard_namespaceObject, "copyText", function() { return copyText; });
__webpack_require__.d(Clipboard_namespaceObject, "pasteText", function() { return pasteText; });

// NAMESPACE OBJECT: ./src/Time/datetime.js
var datetime_namespaceObject = {};
__webpack_require__.r(datetime_namespaceObject);
__webpack_require__.d(datetime_namespaceObject, "MILLIS_PER_DAY", function() { return MILLIS_PER_DAY; });
__webpack_require__.d(datetime_namespaceObject, "MILLIS_PER_HOUR", function() { return MILLIS_PER_HOUR; });
__webpack_require__.d(datetime_namespaceObject, "MILLIS_PER_MINUTE", function() { return MILLIS_PER_MINUTE; });
__webpack_require__.d(datetime_namespaceObject, "getDefaultFirstDayOfWeek", function() { return getDefaultFirstDayOfWeek; });
__webpack_require__.d(datetime_namespaceObject, "setDefaultFirstDayOfWeek", function() { return setDefaultFirstDayOfWeek; });
__webpack_require__.d(datetime_namespaceObject, "ddmmyyyy", function() { return ddmmyyyy; });
__webpack_require__.d(datetime_namespaceObject, "language2LocalDateFormat", function() { return language2LocalDateFormat; });
__webpack_require__.d(datetime_namespaceObject, "dateFormat2LocationList", function() { return dateFormat2LocationList; });
__webpack_require__.d(datetime_namespaceObject, "dateFormatList", function() { return dateFormatList; });
__webpack_require__.d(datetime_namespaceObject, "yyymmdd", function() { return yyymmdd; });
__webpack_require__.d(datetime_namespaceObject, "dayNames", function() { return dayNames; });
__webpack_require__.d(datetime_namespaceObject, "shortDayNames", function() { return shortDayNames; });
__webpack_require__.d(datetime_namespaceObject, "monthNames", function() { return monthNames; });
__webpack_require__.d(datetime_namespaceObject, "shortMonthNames", function() { return shortMonthNames; });
__webpack_require__.d(datetime_namespaceObject, "formatTokenRegex", function() { return formatTokenRegex; });
__webpack_require__.d(datetime_namespaceObject, "DATE_TIME_TOKEN_RGX", function() { return DATE_TIME_TOKEN_RGX; });
__webpack_require__.d(datetime_namespaceObject, "formatDateString", function() { return formatDateString; });
__webpack_require__.d(datetime_namespaceObject, "LOCAL_DATE_FORMAT", function() { return LOCAL_DATE_FORMAT; });
__webpack_require__.d(datetime_namespaceObject, "LOCAL_DATE_TIME_FORMAT", function() { return LOCAL_DATE_TIME_FORMAT; });
__webpack_require__.d(datetime_namespaceObject, "formartDateString", function() { return formartDateString; });
__webpack_require__.d(datetime_namespaceObject, "parseDateString", function() { return parseDateString; });
__webpack_require__.d(datetime_namespaceObject, "addDate", function() { return addDate; });
__webpack_require__.d(datetime_namespaceObject, "prevDate", function() { return prevDate; });
__webpack_require__.d(datetime_namespaceObject, "nextDate", function() { return nextDate; });
__webpack_require__.d(datetime_namespaceObject, "weekIndexOf", function() { return weekIndexOf; });
__webpack_require__.d(datetime_namespaceObject, "weekInYear", function() { return weekInYear; });
__webpack_require__.d(datetime_namespaceObject, "beginOfSecond", function() { return beginOfSecond; });
__webpack_require__.d(datetime_namespaceObject, "beginOfMinute", function() { return beginOfMinute; });
__webpack_require__.d(datetime_namespaceObject, "beginOfDay", function() { return beginOfDay; });
__webpack_require__.d(datetime_namespaceObject, "beginOfHour", function() { return beginOfHour; });
__webpack_require__.d(datetime_namespaceObject, "beginOfWeek", function() { return beginOfWeek; });
__webpack_require__.d(datetime_namespaceObject, "addWeek", function() { return addWeek; });
__webpack_require__.d(datetime_namespaceObject, "nextWeek", function() { return nextWeek; });
__webpack_require__.d(datetime_namespaceObject, "prevWeek", function() { return prevWeek; });
__webpack_require__.d(datetime_namespaceObject, "beginOfMonth", function() { return beginOfMonth; });
__webpack_require__.d(datetime_namespaceObject, "beginOfQuarter", function() { return beginOfQuarter; });
__webpack_require__.d(datetime_namespaceObject, "addQuarter", function() { return addQuarter; });
__webpack_require__.d(datetime_namespaceObject, "nextQuarter", function() { return nextQuarter; });
__webpack_require__.d(datetime_namespaceObject, "prevQuarter", function() { return prevQuarter; });
__webpack_require__.d(datetime_namespaceObject, "beginOfYear", function() { return beginOfYear; });
__webpack_require__.d(datetime_namespaceObject, "addYear", function() { return addYear; });
__webpack_require__.d(datetime_namespaceObject, "nextYear", function() { return nextYear; });
__webpack_require__.d(datetime_namespaceObject, "prevYear", function() { return prevYear; });
__webpack_require__.d(datetime_namespaceObject, "compareDate", function() { return compareDate; });
__webpack_require__.d(datetime_namespaceObject, "compareMonth", function() { return compareMonth; });
__webpack_require__.d(datetime_namespaceObject, "compareYear", function() { return compareYear; });
__webpack_require__.d(datetime_namespaceObject, "addMonth", function() { return addMonth; });
__webpack_require__.d(datetime_namespaceObject, "nextMonth", function() { return nextMonth; });
__webpack_require__.d(datetime_namespaceObject, "prevMonth", function() { return prevMonth; });
__webpack_require__.d(datetime_namespaceObject, "daysInMonth", function() { return daysInMonth; });
__webpack_require__.d(datetime_namespaceObject, "parseDateTime", function() { return parseDateTime; });
__webpack_require__.d(datetime_namespaceObject, "formatDateTime", function() { return formatDateTime; });
__webpack_require__.d(datetime_namespaceObject, "implicitDate", function() { return implicitDate; });

// NAMESPACE OBJECT: ./src/Network/FileSaver.js
var FileSaver_namespaceObject = {};
__webpack_require__.r(FileSaver_namespaceObject);
__webpack_require__.d(FileSaver_namespaceObject, "fileExist", function() { return fileExist; });
__webpack_require__.d(FileSaver_namespaceObject, "saveAs", function() { return saveAs; });
__webpack_require__.d(FileSaver_namespaceObject, "saveTextAs", function() { return saveTextAs; });

// NAMESPACE OBJECT: ./src/DataStructure/Array.js
var Array_namespaceObject = {};
__webpack_require__.r(Array_namespaceObject);
__webpack_require__.d(Array_namespaceObject, "arrayUnique", function() { return arrayUnique; });
__webpack_require__.d(Array_namespaceObject, "arrayRemoveNone", function() { return arrayRemoveNone; });
__webpack_require__.d(Array_namespaceObject, "arrayIntersection", function() { return arrayIntersection; });
__webpack_require__.d(Array_namespaceObject, "arrayIsSubset", function() { return arrayIsSubset; });
__webpack_require__.d(Array_namespaceObject, "arrayCompare", function() { return arrayCompare; });
__webpack_require__.d(Array_namespaceObject, "arrayShuffle", function() { return arrayShuffle; });

// NAMESPACE OBJECT: ./src/Print/printer.js
var printer_namespaceObject = {};
__webpack_require__.r(printer_namespaceObject);
__webpack_require__.d(printer_namespaceObject, "ShareSerializer", function() { return ShareSerializer; });
__webpack_require__.d(printer_namespaceObject, "downloadAsPDF", function() { return downloadAsPDF; });
__webpack_require__.d(printer_namespaceObject, "PaperPrinter", function() { return Print_PaperPrinter; });
__webpack_require__.d(printer_namespaceObject, "PrintSerializer", function() { return Print_PrintSerializer; });

// EXTERNAL MODULE: ./src/Polyfill/polyfill.js
var polyfill = __webpack_require__(31);

// EXTERNAL MODULE: ./src/HTML5/EventEmitter.js
var EventEmitter = __webpack_require__(2);

// EXTERNAL MODULE: ./src/Detector/BrowserDetector.js
var BrowserDetector = __webpack_require__(8);

// EXTERNAL MODULE: ./src/HTML5/JSPath.js
var JSPath = __webpack_require__(17);

// EXTERNAL MODULE: ./src/JSMaker/TemplateString.js
var TemplateString = __webpack_require__(7);

// CONCATENATED MODULE: ./src/XML/XMLConstant.js
var XMLConstant = {
  TYPE_ELEMENT: 1,
  TYPE_TEXT: 3,
  TYPE_COMMENT: 8,
  TYPE_DECLARATION: 16
};
/* harmony default export */ var XML_XMLConstant = (XMLConstant);
// CONCATENATED MODULE: ./src/XML/XMLDeclarationNode.js


function XMLDeclaretionNode() {
  this.nodeType = XML_XMLConstant.TYPE_DECLARATION;
  this.parentNode;
  /**
   * @type {String}
   */

  this.tagName = '';
  /**
  * @type {XMLElement}
  */

  this.parentNode;
  this.attributes = {};
}
/**
 * @param {String} name attribute name
 */


XMLDeclaretionNode.prototype.getAttribute = function (name) {
  return this.attributes[name];
};
/**
 * @param {String} name attribute name
 * @param {String} value 
 */


XMLDeclaretionNode.prototype.setAttribute = function (name, value) {
  this.attributes[name] = value;
};
/**
 * @param {String} name attribute name
 */


XMLDeclaretionNode.prototype.removeAttribute = function (name) {
  delete this.attributes[name];
};

XMLDeclaretionNode.prototype.remove = function () {
  if (this.parentNode) {
    this.parentNode.removeChild(this);
  }
};

XMLDeclaretionNode.prototype.toObject = function () {
  return {
    nodeType: this.nodeType,
    tagName: this.tagName,
    attributes: Object.assign({}, this.attributes)
  };
};

/* harmony default export */ var XMLDeclarationNode = (XMLDeclaretionNode);
// CONCATENATED MODULE: ./src/XML/XMLClassList.js
/**
 * 
 * @param {XMLElement} xmlNode 
 */
function XMLClassList(xmlNode) {
  this.xmlNode = xmlNode;
}
/**
 * @param {String} name
 * @returns {Boolean}
 */


XMLClassList.prototype.contains = function (name) {
  var className = this.xmlNode.getAttribute('class');

  if (className) {
    var classes = className.trim().split(/\s+/);

    for (var i = 0; i < classes.length; ++i) {
      if (classes[i] == name) return true;
    }

    return false;
  } else return false;
};
/**
 * @param {Number} index
 * @returns {String}
 */


XMLClassList.prototype.item = function (index) {
  var className = this.xmlNode.getAttribute('class');

  if (className) {
    var classes = className.trim().split(/\s+/);
    return classes[index];
  } else return undefined;
};
/**
 * @param {Array<String>} arguments
 */


XMLClassList.prototype.remove = function () {
  var dict = Array.prototype.reduce.call(arguments, function (ac, name) {
    ac[name] = true;
    return ac;
  }, {});
  var className = this.xmlNode.getAttribute('class');

  if (className) {
    var classes = className.trim().split(/\s+/);
    var newClasses = classes.filter(function (name) {
      dict[name];
    });
    this.xmlNode.setAttribute(newClasses.join(' '));
  }
};
/**
 * @param {Array<String>} arguments
 */


XMLClassList.prototype.add = function () {
  var className = this.xmlNode.getAttribute('class') || '';
  var classes = className.trim().split(/\s+/);
  var dict = classes.reduce(function (ac, name) {
    ac[name] = true;
    return ac;
  }, {});

  for (var i = 0; i < arguments.length; ++i) {
    var newClass = arguments[i].trim();
    if (newClass.length == 0) return;

    if (!dict[newClass]) {
      classes.push(newClass);
      dict[newClass] = true;
    }
  }

  this.xmlNode.setAttribute('class', classes.join(' '));
};

/* harmony default export */ var XML_XMLClassList = (XMLClassList);
// CONCATENATED MODULE: ./src/XML/XMLElement.js



function XMLElement() {
  this.nodeType = XML_XMLConstant.TYPE_ELEMENT;
  /**
   * @type {String}
   */

  this.tagName = '';
  /**
   * @type {XMLElement}
   */

  this.parentNode;
  this.attributes = {};
  /**
   * @type {Array} Array of  XMLElement or XMLText
   */

  this.childNodes = [];
  Object.defineProperty(this, 'classList', {
    value: new XML_XMLClassList(this),
    writable: false
  });
}
/**
 * @param {String} name attribute name
 */


XMLElement.prototype.getAttribute = function (name) {
  return this.attributes[name];
};
/**
 * @param {String} name attribute name
 * @param {String} value 
 */


XMLElement.prototype.setAttribute = function (name, value) {
  this.attributes[name] = value;
};
/**
 * @param {String} name attribute name
 */


XMLElement.prototype.removeAttribute = function (name) {
  delete this.attributes[name];
};

XMLElement.prototype.appendChild = function (node) {
  node.remove();
  this.childNodes.push(node);
  node.parentNode = this;
  return node;
};
/**
 * @param {XMLElement} child
 * @returns {XMLElement} removed node
 */


XMLElement.prototype.removeChild = function (child) {
  var result;

  if (this == child.parentNode) {
    var j = 0;

    for (var i = 0; i < this.childNodes.length; ++i) {
      if (child != this.childNodes[i]) {
        this.childNodes[j] = this.childNodes[i];
        ++j;
      } else {
        child.parentNode = undefined;
        result = child;
      }
    }

    while (j > this.childNodes.length) {
      this.childNodes.pop();
    }
  }

  return result;
};
/**
 * @param {XMLElement|XMLText|XMLDeclaretionNode} node
 */


XMLElement.prototype.inserBefore = function (node, child) {
  if (node == child) return;
  var childIndex = -1;

  for (var i = 0; i < this.childNodes.length; ++i) {
    if (this.childNodes[i] == child) {
      childIndex = i;
      break;
    }
  }

  if (childIndex < 0) return;
  node.remove();
  node.parentNode = this;
  this.childNodes.push(null);
  var cIndex = this.childNodes.length - 2;

  while (cIndex >= 0) {
    if (this.childNodes[cIndex] == child) {
      this.childNodes[cIndex + 1] = node;
    } else this.childNodes[cIndex + 1] = this.childNodes[cIndex];
  }
};

XMLElement.prototype.remove = function () {
  if (this.parentNode) {
    this.parentNode.removeChild(this);
  }
};

XMLElement.prototype.toObject = function () {
  return {
    nodeType: this.nodeType,
    tagName: this.tagName,
    attributes: Object.assign({}, this.attributes),
    childNodes: this.childNodes.map(function (child) {
      return child.toObject();
    })
  };
};

/* harmony default export */ var XML_XMLElement = (XMLElement);
// CONCATENATED MODULE: ./src/XML/XMLTextNode.js


function XMLTextNode(data) {
  this.nodeType = XML_XMLConstant.TYPE_TEXT;
  /**
   * @type {XMLNode}
   */

  this.parentNode;
  /**
   * @type {String}
   */

  this.data = data || '';
}

XMLTextNode.prototype.remove = function () {
  if (this.parentNode) {
    this.parentNode.removeChild(this);
  }
};

XMLTextNode.prototype.toObject = function () {
  return {
    nodeType: this.nodeType,
    data: this.data
  };
};

/* harmony default export */ var XML_XMLTextNode = (XMLTextNode);
// CONCATENATED MODULE: ./src/XML/XMLCommentNode.js


function XMLCommentNode(data) {
  this.nodeType = XML_XMLConstant.TYPE_COMMENT;
  /**
   * @type {XMLNode}
   */

  this.parentNode;
  /**
   * @type {String}
   */

  this.data = data || '';
}

XMLCommentNode.prototype.remove = function () {
  if (this.parentNode) {
    this.parentNode.removeChild(this);
  }
};

XMLCommentNode.prototype.toObject = function () {
  return {
    nodeType: this.nodeType,
    data: this.data
  };
};

/* harmony default export */ var XML_XMLCommentNode = (XMLCommentNode);
// CONCATENATED MODULE: ./src/XML/XML.js





/**
 * 
 * @param {RegExp} regex 
 */

function getRegexBody(regex) {
  return regex.toString().match(/^\/(.+)\/([gimuy]*)$/)[1];
}

var BEGIN_TAG = 1;
var END_TAG = 2;
var CDATA = 3;
var DECLARATION = 4;
var COMMENT = 5;
var TEXT = 6;
var identRgx = /[^\s\"\r\n\'\!\/=\>\<\]\[\?\+\.]+/;
var spaceRgx = /[\s\r\n]+/;
var stringRgx = /\"(([^\"\\]*|(\\.))*)\"/;
var textRgx = /[^\<\-]+/;
var doctypeOpenRgx = /\<\!DOCTYPE/;
var commentOpenRgx = /\<!\-\-/;
var commentCloseRgx = /\-\-\>/;
var cdataOpenRgx = /\<\!\[CDATA\[/;
var cdataCloseRgx = /\]\]\>/;
var openRgx = /\</;
var openEndTagRgx = /\<\//;
var closeRgx = /\>/;
var shortCloseRgx = /\/\>/;
var declarationOpenRgx = /\<\?/;
var declarationCloseRgx = /\?\>/;
var assignOpRgx = /=/;
var tokenRgxBody = '(' + [spaceRgx, doctypeOpenRgx, declarationOpenRgx, cdataOpenRgx, commentOpenRgx, openEndTagRgx, openRgx, assignOpRgx, stringRgx, commentCloseRgx, identRgx, declarationCloseRgx, shortCloseRgx, closeRgx, cdataCloseRgx, textRgx].map(function (e) {
  return getRegexBody(e);
}).join(')|(') + ')';
var tokenType = {
  space: spaceRgx,
  doctypeOpen: doctypeOpenRgx,
  declarationOpen: declarationOpenRgx,
  cdataOpen: cdataOpenRgx,
  commentOpen: commentOpenRgx,
  openEndTag: openEndTagRgx,
  open: openRgx,
  ident: identRgx,
  assignOp: assignOpRgx,
  string: stringRgx,
  commentClose: commentCloseRgx,
  declarationClose: declarationCloseRgx,
  shortClose: shortCloseRgx,
  close: closeRgx,
  cdataClose: cdataCloseRgx,
  text: textRgx
};
var tokenRgx = new RegExp(tokenRgxBody);
/**
 * 
 * @typedef {Object} Token
 * @property {String} text
 * @property {*} matched
 */

/**
 * 
 * @param {String} text 
 * @returns {Array<Token>}
 */

function xmlTokenize(text) {
  var texts = text.match(new RegExp(tokenRgxBody, 'g'));
  return text.match(new RegExp(tokenRgxBody, 'g')).map(function (tokenText, i) {
    var result = {
      text: tokenText,
      matched: {}
    };

    for (var tType in tokenType) {
      var matched = tokenText.match(tokenType[tType]);

      if (matched) {
        if (matched[0] == tokenText) result.matched[tType] = matched;
      }
    }

    return result;
  });
}
/**
 * @typedef {Object} XMLPaseInfo
 * @property {Array<Token>} tokens
 * @property {Number} type
 * @property {Number} start
 * @property {Number} end
 * @property {Error} error
 * @property {Boolean} closed
 * 
 * 
 * 
 * @typedef {Object} XMLParseNode 
 * @property {XMLPaseInfo} __xml__
 * @property {String} tagName
 * @property {*} attributes
 * @property {String} text
 */

/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Number} i 
 * @returns {XMLParseNode}
 */


function matchAssign(tokens, i) {
  var result = {
    __xml__: {
      start: i
    }
  };
  var cToken;

  if (i < tokens.length) {
    cToken = tokens[i];

    if (cToken.matched['ident']) {
      result.key = cToken.text;
      ++i;

      if (i < tokens.length) {
        cToken = tokens[i];

        if (cToken.matched['space']) {
          ++i;
        }

        if (i < tokens.length) {
          cToken = tokens[i];

          if (cToken.matched['assignOp']) {
            ++i;

            if (i < tokens.length) {
              cToken = tokens[i];

              if (cToken.matched['space']) {
                ++i;
              }

              if (i < tokens.length) {
                cToken = tokens[i];

                if (cToken.matched['string']) {
                  result.value = cToken.matched.string[1];
                  ++i;
                } else {
                  result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected string');
                }
              } else {
                result.__xml__.error = new Error('End of data found, expected ident');
              }
            } else {
              result.__xml__.error = new Error('End of data found, expected ident');
            }
          } else {
            result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected =');
          }
        } else {
          result.__xml__.error = new Error('End of data found, expected =');
        }
      } else {
        result.__xml__.error = new Error('End of data found, expected =');
      }
    } else {
      result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected ident');
    }
  } else {
    result.__xml__.error = new Error('End of data found, expected ident');
  }

  result.__xml__.end = i;
  return result;
}
/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Number} i 
 * @returns {XMLParseNode}
 */


function matchBeginTag(tokens, i) {
  var result = {
    __xml__: {
      type: BEGIN_TAG,
      start: i
    }
  };
  var cToken;

  if (i < tokens.length) {
    cToken = tokens[i];

    if (cToken.matched['open']) {
      ++i;

      if (i < tokens.length) {
        cToken = tokens[i];

        if (cToken.matched['ident']) {
          result.tagName = cToken.text;
          ++i;

          if (i < tokens.length) {
            var finished = false; //when find the close symbol

            while (i < tokens.length) {
              cToken = tokens[i];

              if (cToken.matched['space']) {
                ++i;
              } //skip space between attributes


              if (i < tokens.length) {
                cToken = tokens[i];

                if (cToken.matched['shortClose']) {
                  result.__xml__.closed = true;
                  ++i;
                  finished = true;
                  break;
                } else if (cToken.matched['close']) {
                  result.__xml__.closed = false;
                  ++i;
                  finished = true;
                  break;
                } else if (tokens[i - 1].matched['space']) {
                  var assign = matchAssign(tokens, i);

                  if (!assign.__xml__.error) {
                    result.attributes = result.attributes || {};
                    result.attributes[assign.key] = assign.value;
                    i = assign.__xml__.end;
                  } else if (cToken.matched['ident']) {
                    result.attributes = result.attributes || {};
                    result.attributes[cToken.text] = true; // a flag

                    ++i;
                  } else {
                    //TODO: we can ignore some error here, the same with order Match* function
                    result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected > or indent');
                    break;
                  }
                } else {
                  //TODO: we can ignore some error here
                  result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected > or indent');
                  break;
                }
              } else {
                result.__xml__.error = new Error('End of data found, expected /> or >');
                break;
              }
            }

            if (!finished && !result.__xml__.error) {
              result.__xml__.error = new Error('End of data found, expected /> or >');
            }
          } else {
            result.__xml__.error = new Error('End of data found, expected /> or >');
          }
        } else {
          result.__xml__.error = new Error('Expected indent');
        }
      } else {
        result.__xml__.error = new Error('End of data found, expected indent');
      }

      result.__xml__.end = i;
    } else {
      result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected <');
    }
  } else {
    result.__xml__.error = new Error('End of data found, expected <');
  }

  result.__xml__.end = i;
  return result;
}
/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Number} i 
 * @returns {XMLParseNode}
 */


function matchEndTag(tokens, i) {
  var result = {
    __xml__: {
      type: END_TAG,
      closed: true,
      start: i
    }
  };
  var cToken;

  if (i < tokens.length) {
    cToken = tokens[i];

    if (cToken.matched['openEndTag']) {
      ++i;

      if (i < tokens.length) {
        cToken = tokens[i];

        if (cToken.matched['ident']) {
          result.tagName = cToken.text;
          ++i;

          if (i < tokens.length) {
            var finished = false; //when find the close symbol

            while (i < tokens.length) {
              cToken = tokens[i];

              if (cToken.matched['space']) {
                ++i;
              } //skip space between attributes


              if (i < tokens.length) {
                cToken = tokens[i];

                if (cToken.matched['close']) {
                  ++i;
                  finished = true;
                  break;
                } else if (tokens[i - 1].matched['space']) {
                  var assign = matchAssign(tokens, i);

                  if (!assign.__xml__.error) {
                    result.attributes = result.attributes || {};
                    result.attributes[assign.key] = assign.value;
                    i = assign.__xml__.end;
                  } else if (cToken.matched['ident']) {
                    result.attributes = result.attributes || {};
                    result.attributes[cToken.text] = true; // a flag

                    ++i;
                  } else {
                    result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected > or indent');
                  }
                } else {
                  result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected > or indent');
                }
              } else {
                result.__xml__.error = new Error('End of data found, expected /> or >');
              }
            }

            if (!finished && !result.__xml__.error) {
              result.__xml__.error = new Error('End of data found, expected /> or >');
            }
          } else {
            result.__xml__.error = new Error('End of data found, expected /> or >');
          }
        } else {
          result.__xml__.error = new Error('Expected indent');
        }
      } else {
        result.__xml__.error = new Error('End of data found, expected indent');
      }

      result.__xml__.end = i;
    } else {
      result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected <');
    }
  } else {
    result.__xml__.error = new Error('End of data found, expected <');
  }

  result.__xml__.end = i;
  return result;
}
/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Number} i 
 * @returns {XMLParseNode}
 */


function matchDeclaration(tokens, i) {
  var result = {
    __xml__: {
      type: DECLARATION,
      start: i
    }
  };
  var cToken;

  if (i < tokens.length) {
    cToken = tokens[i];

    if (cToken.matched['declarationOpen']) {
      ++i;

      if (i < tokens.length) {
        cToken = tokens[i];

        if (cToken.matched['ident']) {
          result.tagName = cToken.text;
          ++i;

          if (i < tokens.length) {
            var finished = false; //when find the close symbol

            while (i < tokens.length) {
              cToken = tokens[i];

              if (cToken.matched['space']) {
                ++i;
              } //skip space between attributes


              if (i < tokens.length) {
                cToken = tokens[i];

                if (cToken.matched['declarationClose']) {
                  result.__xml__.closed = false;
                  ++i;
                  finished = true;
                  break;
                } else if (tokens[i - 1].matched['space']) {
                  var assign = matchAssign(tokens, i);

                  if (!assign.__xml__.error) {
                    result.attributes = result.attributes || {};
                    result.attributes[assign.key] = assign.value;
                    i = assign.__xml__.end;
                  } else if (cToken.matched['ident']) {
                    result.attributes = result.attributes || {};
                    result.attributes[cToken.text] = true; // a flag

                    ++i;
                  } else {
                    result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected > or indent');
                  }
                } else {
                  result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected > or indent');
                }
              } else {
                result.__xml__.error = new Error('End of data found, expected /> or >');
              }
            }

            if (!finished && !result.__xml__.error) {
              result.__xml__.error = new Error('End of data found, expected /> or >');
            }
          } else {
            result.__xml__.error = new Error('End of data found, expected /> or >');
          }
        } else {
          result.__xml__.error = new Error('Expected indent');
        }
      } else {
        result.__xml__.error = new Error('End of data found, expected indent');
      }

      result.__xml__.end = i;
    } else {
      result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected <');
    }
  } else {
    result.__xml__.error = new Error('End of data found, expected <');
  }

  result.__xml__.end = i;
  return result;
}
/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Number} i 
 * @returns {XMLParseNode}
 */


function matchCData(tokens, i) {
  var result = {
    __xml__: {
      type: CDATA,
      start: i
    }
  };
  var cToken;

  if (i < tokens.length) {
    cToken = tokens[i];

    if (cToken.matched['cdataOpen']) {
      ++i;
      result.text = '';
      var finished = false;

      while (i < tokens.length) {
        cToken = tokens[i];

        if (cToken.matched['cdataClose']) {
          finished = true;
          ++i;
          break;
        } else {
          result.text += cToken.text;
          ++i;
        }
      }

      if (!finished) {
        result.__xml__.error = new Error('End of data found, expected ]]>');
      }
    } else {
      result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected <![CDATA[');
    }
  } else {
    result.__xml__.error = new Error('End of data found, expected <![CDATA[');
  }

  result.__xml__.end = i;
  return result;
}
/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Number} i 
 * @returns {XMLParseNode}
 */


function matchComment(tokens, i) {
  var result = {
    __xml__: {
      type: COMMENT,
      start: i
    }
  };
  var cToken;

  if (i < tokens.length) {
    cToken = tokens[i];

    if (cToken.matched['commentOpen']) {
      ++i;
      result.text = '';
      var finished = false;

      while (i < tokens.length) {
        cToken = tokens[i];

        if (cToken.matched['commentClose']) {
          finished = true;
          ++i;
          break;
        } else {
          result.text += cToken.text;
          ++i;
        }
      }

      if (!finished) {
        result.__xml__.error = new Error('End of data found, expected -->');
      }
    } else {
      result.__xml__.error = new Error('"' + cToken.text + '"' + 'found, expected <!--');
    }
  } else {
    result.__xml__.error = new Error('End of data found, expected <!--');
  }

  result.__xml__.end = i;
  return result;
}
/**
 * 
 * @param {Token} tokens 
 */


function parseXMLTab(tokens) {
  var tabs = [];
  var i = 0;

  while (i < tokens.length) {
    var comment = matchComment(tokens, i);

    if (!comment.__xml__.error) {
      tabs.push(comment);
      i = comment.__xml__.end;
    } else {
      var declaration = matchDeclaration(tokens, i);

      if (!declaration.__xml__.error) {
        tabs.push(declaration);
        i = declaration.__xml__.end;
      } else {
        var begin = matchBeginTag(tokens, i);

        if (!begin.__xml__.error) {
          tabs.push(begin);
          i = begin.__xml__.end;
        } else {
          var end = matchEndTag(tokens, i);

          if (!end.__xml__.error) {
            tabs.push(end);
            i = end.__xml__.end;
          } else {
            var cdata = matchCData(tokens, i);

            if (!cdata.__xml__.error) {
              tabs.push(cdata);
              i = cdata.__xml__.end;
            } else {
              ++i; //skip
            }
          }
        }
      }
    }
  }

  return tabs;
}
/**
 * 
 * @param {Array<Token>} tokens 
 * @param {Array<XMLParseNode>} tabs 
 * @returns {Array<XMLParseNode>}
 */


function parseXMLText(tokens, tabs) {
  var texts = [];
  var ofs = 0;
  var text;
  var tab;

  for (var i = 0; i < tabs.length; ++i) {
    tab = tabs[i];

    if (tab.__xml__.start > ofs) {
      text = tokens.slice(ofs, tab.__xml__.start).map(function (token) {
        return token.text;
      }).join('').trim();
      if (text.length > 0) texts.push({
        __xml__: {
          type: TEXT,
          tokens: tokens,
          start: ofs,
          end: tab.__xml__.start
        },
        text: text
      });
    }

    ofs = tab.__xml__.end;
  }

  if (ofs < tokens.length) {
    text = tokens.slice(ofs).map(function (token) {
      return token.text;
    }).join('').trim();
    if (text.length > 0) texts.push({
      __xml__: {
        type: TEXT,
        tokens: tokens,
        start: ofs,
        end: tab.__xml__.start
      },
      text: text
    });
  }

  return texts;
}
/**
 * 
 * @param {Array<XMLParseNode>} tabs 
 * @param {Array<XMLParseNode>} texts 
 * @return {Array<XMLParseNode>}  
 */


function mergeNodes(tabs, texts) {
  var nodes = [];
  var choose;
  var iTabs = 0,
      iTexts = 0;
  var diTabs, diTexts;
  var minStart;

  do {
    choose = undefined;
    diTabs = 0, diTexts = 0;
    minStart = 100000000;

    if (iTabs < tabs.length) {
      choose = tabs[iTabs];
      minStart = choose.__xml__.start;
      diTabs = 1;
    }

    if (iTexts < texts.length && texts[iTexts].__xml__.start < minStart) {
      choose = texts[iTexts];
      minStart = choose.__xml__.start;
      diTabs = 0;
      diTexts = 1;
    }

    if (choose) {
      iTexts += diTexts;
      iTabs += diTabs;
      nodes.push(choose);
    }
  } while (choose);

  return nodes;
}
/**
 * 
 * @param {String} text 
 * @return {Array<XMLParseNode>} 
 */


function parseXMLTextToXMLParseNode(text) {
  text = text.trim();
  var tokens = xmlTokenize(text.trim());
  var tabs = parseXMLTab(tokens);
  var texts = parseXMLText(tokens, tabs);
  return mergeNodes(tabs, texts);
}
/**
 * 
 * @param {Array<XMLParseNode>} nodes
 * @returns {Array}
 */


function paresNodesToXMLs(nodes) {
  var node;
  var parentXMLElement = new XML_XMLElement();
  parentXMLElement.tagName = "FAKE_DOCUMENT";

  var assignAttributes = function assignAttributes(node, attributes) {
    Object.keys(attributes).forEach(function (key) {
      node.setAttribute(key, attributes[key]);
    });
  };

  var newXMLNode;

  for (var i = 0; i < nodes.length; ++i) {
    node = nodes[i];
    newXMLNode = undefined;

    switch (node.__xml__.type) {
      case DECLARATION:
        newXMLNode = new XMLDeclarationNode();
        newXMLNode.tagName = node.tagName;
        if (node.attributes) assignAttributes(newXMLNode, node.attributes);
        parentXMLElement.appendChild(newXMLNode);
        break;

      case BEGIN_TAG:
        newXMLNode = new XML_XMLElement();
        newXMLNode.tagName = node.tagName;
        if (node.attributes) assignAttributes(newXMLNode, node.attributes);
        parentXMLElement.appendChild(newXMLNode);
        if (!node.__xml__.closed) parentXMLElement = newXMLNode;
        break;

      case END_TAG:
        if (parentXMLElement && node.tagName == parentXMLElement.tagName) {
          parentXMLElement = parentXMLElement.parentNode;
        } else if (parentXMLElement && (parentXMLElement.tagName == 'img' || parentXMLElement.tagName == 'input')) {
          // image can be not close
          while (parentXMLElement.tagName == 'img' || parentXMLElement.tagName == 'input') {
            parentXMLElement = parentXMLElement.parentNode;
          }

          parentXMLElement = parentXMLElement.parentNode;
        } else {
          throw new Error("Unknown close of tagName " + node.tagName + ', but ' + (parentXMLElement ? parentXMLElement.tagName : "EOF") + ' expected');
        }

        break;

      case TEXT:
        newXMLNode = new XML_XMLTextNode(node.text);
        parentXMLElement.appendChild(newXMLNode);
        break;

      case COMMENT:
        newXMLNode = new XML_XMLCommentNode(node.text);
        parentXMLElement.appendChild(newXMLNode);
        break;
    }
  }

  return parentXMLElement.childNodes.slice().map(function (e) {
    e.remove();
    return e;
  });
}
/**
 * 
 * @param {XMLElement} node 
 */


function makeOpenXMLElementTab(node) {
  var res = '<' + node.tagName;
  var attributesText = Object.keys(node.attributes).map(function (key) {
    var value = node.attributes[key];

    if (value === null) {
      return key;
    } else {
      return key + '=' + '"' + value + '"';
    }
  }).join(' ');

  if (attributesText.length > 0) {
    res += ' ' + attributesText;
  }

  res += '>';
  return res;
}
/**
 * 
 * @param {XMLDeclaretionNode} node 
 */


function makeXMLDeclaretionTab(node) {
  var res = '<?' + node.tagName;
  var attributesText = Object.keys(node.attributes).map(function (key) {
    var value = node.attributes[key];

    if (value === null) {
      return key;
    } else {
      return key + '=' + '"' + value + '"';
    }
  }).join(' ');

  if (attributesText.length > 0) {
    res += ' ' + attributesText;
  }

  res += '?>';
  return res;
}
/**
 * 
 * @param {XMLDeclaretionNode} node 
 */


function makeXMLCommentTab(node) {
  var res = '<!--' + node.data + '-->';
  return res;
}

var XML = {};
/**
 * @param {String} code
 * @returns {Array<XMLElement>}
 */

XML.parseLikeHTML = function (code) {
  var nodes = parseXMLTextToXMLParseNode(code); // console.log('nodes', nodes);

  var xmls = paresNodesToXMLs(nodes);
  return xmls;
};
/**
 * @param {String} code
 * @returns {XMLElement}
 */


XML.parse = function (code) {
  var xmls = this.parseLikeHTML(code);
  if (xmls.length == 0) return undefined;
  var obj = xmls[xmls.length - 1].toObject();
  return obj;
};

XML.DFNodeVisit = function (node, handlers, accumulator) {
  if (!node.childNodes || node.childNodes.length == 0) {
    if (handlers.leaf) handlers.leaf(accumulator, node);
  } else {
    if (handlers.open) handlers.open(accumulator, node);

    for (var i = 0; i < node.childNodes.length; ++i) {
      this.DFNodeVisit(node.childNodes[i], handlers, accumulator);
    }

    if (handlers.close) handlers.close(accumulator, node);
    return accumulator;
  }
};
/**
 * @typedef {Object} XMLBeautifyOption
 * @property {String} indent
 * @property {Number} initDepth 
 */

/**
 * @param {Array<XMLElement>} o 
 * @param {XMLBeautifyOption} beautifyOption 
 * 
 * 
 */


XML.stringify = function (o, beautifyOption) {
  var texts = [];
  var indent = '';
  var lineBreak = '';
  var depth = 0;

  if (beautifyOption) {
    lineBreak = '\n';
    indent = typeof beautifyOption.indent == 'string' ? beautifyOption.indent : '    ';
    depth = beautifyOption.initDepth || 0;
  }

  if (!(o instanceof Array)) {
    o = [o];
  }

  var visitor = {
    open: function open(ac, node) {
      var currentLineIndent = ac.lineIndentStack[ac.lineIndentStack.length - 1];
      var openTabText = makeOpenXMLElementTab(node);
      ac.texts.push(currentLineIndent + openTabText);
      ac.lineIndentStack.push(currentLineIndent + ac.indent);
    },
    close: function close(ac, node) {
      ac.lineIndentStack.pop();
      var currentLineIndent = ac.lineIndentStack[ac.lineIndentStack.length - 1];
      var endTab = '</' + node.tagName + '>';

      if (node.childNodes.length == 1 && node.childNodes[0].nodeType == XML_XMLConstant.TYPE_TEXT) {
        ac.texts[ac.texts.length - 1] += endTab;
      } else {
        ac.texts.push(currentLineIndent + endTab);
      }
    },
    leaf: function leaf(ac, node) {
      var currentLineIndent = ac.lineIndentStack[ac.lineIndentStack.length - 1];
      var tab;

      if (node.nodeType == XML_XMLConstant.TYPE_TEXT) {
        if (node.parentNode && node.parentNode.childNodes.length == 1) {
          ac.texts[ac.texts.length - 1] += node.data;
        } else {
          ac.texts.push(currentLineIndent + node.data);
        }
      } else if (node.nodeType == XML_XMLConstant.TYPE_ELEMENT) {
        var openTabText = makeOpenXMLElementTab(node);
        var endTab = '</' + node.tagName + '>';
        ac.texts.push(currentLineIndent + openTabText + endTab);
      } else if (node.nodeType == XML_XMLConstant.TYPE_DECLARATION) {
        tab = makeXMLDeclaretionTab(node);
        ac.texts.push(currentLineIndent + tab);
      } else if (node.nodeType == XML_XMLConstant.TYPE_COMMENT) {
        tab = makeXMLCommentTab(node);
        ac.texts.push(currentLineIndent + tab);
      }
    }
  };

  for (var i = 0; i < o.length; ++i) {
    this.DFNodeVisit(o[i], visitor, {
      depth: 0,
      texts: texts,
      lineIndentStack: [''],
      indent: indent
    });
  }

  return texts.join(lineBreak);
};

/* harmony default export */ var XML_XML = (XML);
// CONCATENATED MODULE: ./src/JSMaker/TemplateXML.js




function TemplateXML(props) {
  this.xml = props.xml;
}

TemplateXML.prototype._xmlNodeToJSCode = function (node) {
  var body = [];

  if (node.nodeType == XML_XMLConstant.TYPE_ELEMENT) {
    body.push('tag:' + JSON.stringify(node.tagName));
    var attributeKeys = Object.keys(node.attributes).filter(function (x) {
      return x != 'class' && x != 'style' && !x.startsWith('az-');
    });

    if (attributeKeys && attributeKeys.length > 0) {
      body.push('attr: {' + attributeKeys.map(function (key) {
        return JSON.stringify(key) + ': ' + TemplateString["a" /* default */].parse(node.attributes[key]).toJSCode();
      }).join(', ') + '}');
    }

    if (node.attributes['az-props']) {
      body.push('props: ' + TemplateString["a" /* default */].parse(node.attributes['az-props']).toJSCode());
    }

    if (node.attributes['az-data']) {
      body.push('data: ' + TemplateString["a" /* default */].parse(node.attributes['az-data']).toJSCode());
    }

    if (node.attributes.style) {
      var styleSheet = node.attributes.style.split(';').map(function (s) {
        var t = s.split(':').map(function (text) {
          return text.trim();
        });

        if (t.length == 2) {
          return JSON.stringify(t[0]) + ': ' + JSON.stringify(t[1]);
        } else return false;
      }).filter(function (e) {
        return !!e;
      });

      if (styleSheet.length > 0) {
        body.push('style:{' + styleSheet.join(',') + '}');
      }
    }

    if (node.attributes.class) {
      var classList = node.attributes.class.trim().split(/\s+/);
      if (classList.length > 0) body.push('class:' + JSON.stringify(classList));
    }

    if (node.childNodes && node.childNodes.length > 0) {
      var childList = '[' + node.childNodes.filter(function (e) {
        return e.nodeType == XML_XMLConstant.TYPE_ELEMENT || e.nodeType == XML_XMLConstant.TYPE_TEXT;
      }).map(function (e) {
        return this._xmlNodeToJSCode(e);
      }.bind(this)).filter(function (e) {
        return !!e;
      }).join(', ') + ']';
      if (childList && childList.length > 0) body.push('child: ' + childList);
    }
  } else if (node.nodeType == XML_XMLConstant.TYPE_TEXT) {
    body.push('text: ' + TemplateString["a" /* default */].parse(node.data).toJSCode());
  } else return undefined;

  var res = '{' + body.join(', ') + '}';
  return res;
};

TemplateXML.prototype.toJSCode = function () {
  var res = this._xmlNodeToJSCode(this.xml);

  return res;
};
/**
 * 
 * @param  {...any} args 
 * @returns {Function}
 */


TemplateXML.compileToFunction = function () {
  var innerCode = 'return ' + this.parse(arguments[arguments.length - 1]).toJSCode() + ';';
  var fParam = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
  fParam.push(innerCode);
  return Function.apply(null, fParam);
};

TemplateXML.parse = function (text) {
  var xml = XML_XML.parse(text);

  if (xml) {
    return new TemplateXML({
      xml: xml
    });
  } else return undefined;
};

/* harmony default export */ var JSMaker_TemplateXML = (TemplateXML);
// EXTERNAL MODULE: ./src/HTML5/Dom.js + 1 modules
var Dom = __webpack_require__(0);

// EXTERNAL MODULE: ./src/HTML5/Svg.js
var Svg = __webpack_require__(10);

// EXTERNAL MODULE: ./src/HTML5/OOP.js
var OOP = __webpack_require__(3);

// EXTERNAL MODULE: ./src/Color/Color.js
var Color = __webpack_require__(14);

// CONCATENATED MODULE: ./src/Math/random.js
/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function randomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomPick(arr) {
  var id = randomInt(0, arr.length - 1);
  return arr[id];
}
// CONCATENATED MODULE: ./src/String/stringGenerate.js

var identCharacters = function () {
  var chars = 'qwertyuiopasdfghjklzxcvbnm';
  chars = chars + chars.toUpperCase();
  var num = '0123456789';
  var spect = '_';
  return (chars + spect + num).split('');
}();
function randomIdent(length) {
  if (!(length > 0)) length = 4;
  var factor = identCharacters;
  return [factor[Math.random() * (factor.length - 10) >> 0]].concat(Array(length - 1).fill('').map(function () {
    return factor[Math.random() * factor.length >> 0];
  })).join('');
}
function parallelMatch(a, b) {
  var l = Math.min(a.length, b.length);
  var res = 0;

  for (var i = 0; i < l; ++i) {
    if (a[i] == b[i]) ++res;
  }

  return res;
}
var ipsumLoremWord = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'enim', 'ad', 'minim', 'veniam', 'quis', 'nostrud', 'exercitation', 'ullamco', 'laboris', 'nisi', 'aliquip', 'ex', 'ea', 'commodo', 'consequat', 'duis', 'aute', 'irure', 'in', 'reprehenderit', 'voluptate', 'velit', 'esse', 'cillum', 'eu', 'fugiat', 'nulla', 'pariatur', 'excepteur', 'sint', 'occaecat', 'cupidatat', 'non', 'proident', 'sunt', 'culpa', 'qui', 'officia', 'deserunt', 'mollit', 'anim', 'id', 'est', 'laborum', 'perspiciatis', 'unde', 'omnis', 'iste', 'natus', 'error', 'voluptatem', 'accusantium', 'doloremque', 'laudantium', 'totam', 'rem', 'aperiam', 'eaque', 'ipsa', 'quae', 'ab', 'illo', 'inventore', 'veritatis', 'quasi', 'architecto', 'beatae', 'vitae', 'dicta', 'explicabo', 'nemo', 'ipsam', 'quia', 'voluptas', 'aspernatur', 'aut', 'odit', 'fugit', 'consequuntur', 'magni', 'dolores', 'eos', 'ratione', 'sequi', 'nesciunt', 'neque', 'porro', 'quisquam', 'dolorem', 'adipisci', 'numquam', 'eius', 'modi', 'tempora', 'incidunt', 'magnam', 'aliquam', 'quaerat', 'minima', 'nostrum', 'exercitationem', 'ullam', 'corporis', 'suscipit', 'laboriosam', 'aliquid', 'commodi', 'consequatur', 'autem', 'vel', 'eum', 'iure', 'quam', 'nihil', 'molestiae', 'illum', 'quo', 'at', 'vero', 'accusamus', 'iusto', 'odio', 'dignissimos', 'ducimus', 'blanditiis', 'praesentium', 'voluptatum', 'deleniti', 'atque', 'corrupti', 'quos', 'quas', 'molestias', 'excepturi', 'occaecati', 'cupiditate', 'provident', 'similique', 'mollitia', 'animi', 'dolorum', 'fuga', 'harum', 'quidem', 'rerum', 'facilis', 'expedita', 'distinctio', 'nam', 'libero', 'tempore', 'sum', 'soluta', 'nobis', 'eligendi', 'optio', 'cumque', 'impedit', 'minus', 'quod', 'maxime', 'placeat', 'facere', 'possimus', 'assumenda', 'repellendus', 'temporibus', 'quibusdam', 'officiis', 'debitis', 'necessitatibus', 'saepe', 'eveniet', 'voluptates', 'repudiandae', 'recusandae', 'itaque', 'earum', 'hic', 'tenetur', 'a', 'sapiente', 'delectus', 'reiciendis', 'voluptatibus', 'maiores', 'alias', 'perferendis', 'doloribus', 'asperiores', 'repellat', 'integer', 'nec', 'praesent', 'cursus', 'ante', 'dapibus', 'diam', 'sem', 'nibh', 'elementum', 'imperdiet', 'sagittis', 'mauris', 'fusce', 'tellus', 'augue', 'semper', 'porta', 'massa', 'vestibulum', 'lacinia', 'arcu', 'eget', 'class', 'aptent', 'taciti', 'sociosqu', 'litora', 'torquent', 'per', 'conubia', 'nostra', 'inceptos', 'himenaeos', 'curabitur', 'sodales', 'ligula', 'dignissim', 'nunc', 'tortor', 'pellentesque', 'aenean', 'scelerisque', 'maecenas', 'mattis', 'convallis', 'tristique', 'proin', 'egestas', 'porttitor', 'morbi', 'lectus', 'risus', 'iaculis', 'luctus', 'ac', 'turpis', 'aliquet', 'metus', 'ullamcorper', 'tincidunt', 'euismod', 'quisque', 'volutpat', 'condimentum', 'urna', 'facilisi', 'fringilla', 'suspendisse', 'potenti', 'feugiat', 'mi', 'sapien', 'etiam', 'ultrices', 'justo', 'lacus', 'pharetra', 'auctor', 'interdum', 'primis', 'faucibus', 'orci', 'posuere', 'cubilia', 'curae', 'molestie', 'dui', 'blandit', 'congue', 'pede', 'facilisis', 'laoreet', 'donec', 'viverra', 'malesuada', 'pulvinar', 'sollicitudin', 'cras', 'nisl', 'felis', 'venenatis', 'ultricies', 'accumsan', 'pretium', 'fermentum', 'nullam', 'purus', 'mollis', 'vivamus', 'consectetuer'];
function randomWord() {
  var arr = ipsumLoremWord;
  var idx = randomInt(0, arr.length - 1);
  return arr[idx];
}
function randomPhrase(limitLenght) {
  if (!limitLenght) limitLenght = 50;
  var length = Math.ceil(Math.random() * limitLenght / 7);
  return new Array(length).fill(null).map(randomWord).reduce(function (ac, cr) {
    if (ac.length + cr.length < limitLenght) {
      ac.parts.push(cr);
    }

    return ac;
  }, {
    parts: [],
    length: 0
  }).parts.join(' ');
}
function randomSentence(limitLenght) {
  if (!limitLenght) limitLenght = 300;
  var length = Math.ceil(Math.random() * limitLenght / 70);
  var res = new Array(length).fill(null).map(randomPhrase).reduce(function (ac, cr) {
    if (ac.length + cr.length < limitLenght) {
      ac.parts.push(cr);
    }

    return ac;
  }, {
    parts: [],
    length: 0
  }).parts.join(', ');

  if (Math.random() < 0.03) {
    res = res.replace(/\,/i, ':');
  }

  res = res.replace(/^./, function (x) {
    return x.toUpperCase();
  });
  res += '.';
  return res;
}
function randomParagraph(limitLength) {
  if (!limitLength) limitLength = 1000;
  var length = Math.ceil(Math.random() * limitLength / 200);
  return new Array(length).fill(null).map(randomSentence).reduce(function (ac, cr) {
    if (ac.length + cr.length < limitLength) {
      ac.parts.push(cr);
    }

    return ac;
  }, {
    parts: [],
    length: 0
  }).parts.join(' ');
}
// EXTERNAL MODULE: ./src/Code/safeThrow.js
var safeThrow = __webpack_require__(6);

// CONCATENATED MODULE: ./src/Network/IFrameBridge.js



var TYPE_WORKER = 'WORKER';
var TYPE_IFRAME = 'IFRAME';
var TYPE_IFRAME_MASTER = 'IFRAME_MASTER';
var TYPE_WORKER_MASTER = 'WORKER_MASTER';
/**
 *
 * @param {Worker|HTMLIFrameElement|WorkerGlobalScope|Window=} host
 */

function IFrameBridge(host) {
  var _this = this;

  EventEmitter["a" /* default */].call(this);
  /***
   *
   * @type {Worker|HTMLIFrameElement|WorkerGlobalScope|Window|WorkerGlobalScope|Window}
   */

  this.host = host || self;
  this.sender = null;
  this.receiver = null;
  this.origin = null;
  this.type = 'NOT_DETECT';
  this.id = "UNSET";
  this.sync = this._detectHost().then(function () {
    return _this._attach();
  });
  this.__azarResolveCallbacks = {};
  this.__azarRejectCallbacks = {};
}

IFrameBridge.TYPE_WORKER = TYPE_WORKER;
IFrameBridge.TYPE_IFRAME = TYPE_IFRAME;
IFrameBridge.TYPE_IFRAME_MASTER = TYPE_IFRAME_MASTER;
IFrameBridge.TYPE_WORKER_MASTER = TYPE_WORKER_MASTER;

IFrameBridge.prototype._detectHost = function () {
  var _this2 = this;

  return new Promise(function (rs) {
    var iframeLoaded = function iframeLoaded() {
      if (_this2.host.removeEventListener) {
        _this2.host.removeEventListener("load", iframeLoaded);
      } else {
        _this2.host.detachEvent("onload", iframeLoaded);
      }

      _this2.sender = _this2.host.contentWindow;
      rs();
    };

    if (_this2.host instanceof Worker) {
      _this2.type = TYPE_WORKER_MASTER;
      _this2.sender = _this2.host;
      _this2.receiver = _this2.host;
    } else if (_this2.host.tagName === 'IFRAME') {
      _this2.type = TYPE_IFRAME_MASTER;
      _this2.receiver = self;
      _this2.id = _this2.host.src;
      _this2.origin = '*';

      if (_this2.host.addEventListener) {
        _this2.host.addEventListener("load", iframeLoaded);
      } else {
        _this2.host.attachEvent("onload", iframeLoaded);
      }
    } else if (IFrameBridge.isInIFrame()) {
      _this2.type = TYPE_IFRAME;
      _this2.sender = window.parent;
      _this2.receiver = _this2.host;
      _this2.id = location.href;
      _this2.origin = '*';
    } else if (IFrameBridge.isInWorker()) {
      _this2.type = TYPE_WORKER;
      _this2.sender = _this2.host;
      _this2.receiver = _this2.host;
    }

    if (_this2.sender) rs();
  });
};

IFrameBridge.prototype._attach = function () {
  if (this.receiver.addEventListener) {
    this.receiver.addEventListener("message", this.__azarMessageListener.bind(this), false);
  } else if (this.receiver.attachEvent) {
    this.receiver.attachEvent("onmessage", this.__azarMessageListener.bind(this));
  } else {
    this.receiver.onmessage = this.__azarMessageListener.bind(this);
  }
};

IFrameBridge.fromIFrame = function (iframe) {
  return new IFrameBridge(iframe);
  var host = iframe.contentWindow || iframe.contentDocument;
  var src = iframe.src;
  var rootOrigin = location.origin;
  var iframeOrigin = src.match(/^(http|https):\/\/[^/]+/);

  if (iframeOrigin) {
    iframeOrigin = iframeOrigin[0];
  } else {
    iframeOrigin = rootOrigin;
  }

  if (host) return new IFrameBridge(host, iframeOrigin);else {
    var result = new IFrameBridge(undefined, iframeOrigin);

    var attachedHost = function attachedHost() {
      var host = iframe.contentWindow || iframe.contentDocument;
      result.attach(host);
    };

    if (iframe.addEventListener) {
      iframe.addEventListener("load", attachedHost);
    } else {
      iframe.attachEvent("onload", attachedHost);
    }

    return result;
  }
};

IFrameBridge.getInstance = function () {
  if (!IFrameBridge.shareInstance) {
    var origin = location.origin;
    var rootOrigin = IFrameBridge.fromIFrame() ? IFrameBridge.getParentUrl().match(/^(http|https):\/\/[^/]+/) : null;

    if (rootOrigin) {
      rootOrigin = rootOrigin[0];
    } else {
      rootOrigin = origin;
    } // IFrameBridge.shareInstance = new IFrameBridge(self, rootOrigin == origin? undefined: "*" || rootOrigin );


    var host = self;
    IFrameBridge.shareInstance = new IFrameBridge(host, rootOrigin);
  }

  return IFrameBridge.shareInstance;
};

Object.defineProperties(IFrameBridge.prototype, Object.getOwnPropertyDescriptors(EventEmitter["a" /* default */].prototype));
IFrameBridge.prototype.constructor = IFrameBridge;

IFrameBridge.isInIFrame = function () {
  return !IFrameBridge.isInWorker() && top !== self;
};

IFrameBridge.isInWorker = function () {
  return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
};

IFrameBridge.getParentUrl = function () {
  var parentUrl = window.location != window.parent.location ? document.referrer : document.location.href;
  return parentUrl;
};

IFrameBridge.prototype.__azarMessageListener = function (event) {
  this.__azarHandleData(event.data);
};

IFrameBridge.prototype.__azarHandleData = function (data) {
  if (data.bridgeId !== this.id) return;

  if (data.type) {
    if (data.type == "INVOKE") {
      try {
        var result = this.__azarSelfInvoke(data.name, data.params);

        if (result && typeof result.then == 'function') {
          result.then(function (result) {
            this.__azarResolve(data.taskId, result);
          }.bind(this)).catch(function (err) {
            Object(safeThrow["a" /* default */])(err);

            this.__azarResolve(data.taskId, null, err);
          }.bind(this));
        } else {
          this.__azarResolve(data.taskId, result);
        }
      } catch (err) {
        Object(safeThrow["a" /* default */])(err);

        this.__azarResolve(data.taskId, null, err);
      }
    } else if (data.type == "INVOKE_RESULT") {
      if (this.__azarResolveCallbacks[data.taskId]) {
        if (data.error) {
          this.__azarRejectCallbacks[data.taskId](data.error);
        } else {
          this.__azarResolveCallbacks[data.taskId](data.result);
        }

        delete this.__azarResolveCallbacks[data.taskId];
        delete this.__azarRejectCallbacks[data.taskId];
      }
    } else if (data.type == "EMIT") {
      this.fire.apply(this, data.params);
    } else this.fire('message', data, this);
  }
};

IFrameBridge.prototype.__azarResolve = function (taskId, result, error) {
  var data = {
    type: "INVOKE_RESULT",
    taskId: taskId,
    result: result,
    error: error,
    bridgeId: this.id
  };

  if (this.origin) {
    this.sender.postMessage(data, this.origin);
  } else {
    this.sender.postMessage(data);
  }
};

IFrameBridge.prototype.__azarSelfInvoke = function (name, params) {
  if (typeof this[name] == 'function') {
    return this[name].apply(this, params);
  } else {
    return this[name];
  }
};

IFrameBridge.prototype.emit = function () {
  var params = [];
  params.push.apply(params, arguments);
  this.sync.then(function () {
    var data = {
      type: "EMIT",
      params: params,
      bridgeId: this.id
    };

    if (this.origin) {
      this.sender.postMessage(data, this.origin);
    } else {
      this.sender.postMessage(data);
    }
  }.bind(this));
  return this;
};

IFrameBridge.prototype.invoke = function (name) {
  var params = [];
  params.push.apply(params, arguments);
  params.shift();
  return this.sync.then(function () {
    var indent = randomIdent(32);
    var data = {
      type: 'INVOKE',
      params: params,
      taskId: indent,
      name: name,
      bridgeId: this.id
    };

    if (this.origin) {
      this.host.postMessage(data, this.origin);
    } else {
      this.host.postMessage(data);
    }

    return new Promise(function (resolve, reject) {
      this.__azarResolveCallbacks[indent] = resolve;
      this.__azarRejectCallbacks[indent] = reject;
    }.bind(this));
  }.bind(this));
};

IFrameBridge.prototype.importScriptURLs = function () {
  return this.invoke.apply(this, ['_receiveScriptURLs'].concat(Array.prototype.slice.call(arguments)));
};

IFrameBridge.prototype.importScript = function (code) {
  var blob = new Blob([code], {
    type: 'application/javascript'
  });
  var url = URL.createObjectURL(blob);
  return this.importScriptURLs(url);
};

IFrameBridge.prototype.createMethod = function (name, fx) {
  this[name] = function () {
    return this.invoke.apply(this, [name].concat(Array.prototype.slice.call(arguments)));
  };

  return this.invoke.apply(this, ['_receiveMethod', name, fx.toString()]);
};

IFrameBridge.prototype._receiveScriptURLs = function () {
  if (self.importScripts) {
    self.importScripts.apply(self, arguments);
  }
};

IFrameBridge.prototype._receiveMethod = function (name, code) {
  this[name] = new Function('return ' + code)();
};

/* harmony default export */ var Network_IFrameBridge = (IFrameBridge);
// EXTERNAL MODULE: ./src/JSDocx/JSDocx.js
var JSDocx = __webpack_require__(25);

// CONCATENATED MODULE: ./src/Network/Broadcast.js


 // it can be replace BroadcastChanel

function Broadcast(channel, id) {
  EventEmitter["a" /* default */].call(this);
  this.channel = channel;
  this.id = id || randomIdent(32);
  this._ev_message = this._ev_message.bind(this);
  this._ev_storage = this._ev_storage.bind(this);

  this._init();
}

OOP["a" /* default */].mixClass(Broadcast, EventEmitter["a" /* default */]);

Broadcast.prototype._init = function () {
  if ('BroadcastChannel' in window) {
    this.nativeBroadcastChannel = new BroadcastChannel(this.channel);
    this.nativeBroadcastChannel.onmessage = this._ev_message;
  } else if ('localStorage' in window) {
    if (!('onstorage' in window)) console.warn("Your browser may not support onstorage event.");

    if (window.addEventListener) {
      window.addEventListener('storage', this._ev_storage);
    } else {
      window.attachEvent('onstorage', this._ev_storage);
    }

    this.storageKey = '_broadcast_' + this.channel;
  } else {
    throw new Error("Your browser can not support broadcast!");
  }
};

Broadcast.prototype._ev_storage = function (event) {
  if (event.key == this.storageKey) {
    var data = JSON.parse(event.newValue);
    if (data.sourceId != this.id) this.handleMessData(data.message);
  }
};

Broadcast.prototype._ev_message = function (event) {
  var data = event.data;
  this.handleMessData(data);
};

Broadcast.prototype.handleMessData = function (data) {
  if (data.type == "EMIT") this.fire.apply(this, data.params);
  if (typeof this.onmessage == 'function') this.onmessage(event);
};
/**
 * @param {...Array<*>}
 */


Broadcast.prototype.emit = function () {
  var params = Array.prototype.slice.call(arguments);
  this.postMessage({
    type: "EMIT",
    params: params,
    sourceId: this.id
  });
};
/**
 * @param {*} message
 */


Broadcast.prototype.postMessage = function (message) {
  if (this.nativeBroadcastChannel) {
    this.nativeBroadcastChannel.postMessage(message);
  } else {
    localStorage.setItem(this.storageKey, JSON.stringify({
      message: message,
      sourceId: this.id
    }));
  }
};

Broadcast.prototype.onmessage = null;

Broadcast.prototype.close = function () {
  if (this.nativeBroadcastChannel) this.nativeBroadcastChannel.close();
};

/* harmony default export */ var Network_Broadcast = (Broadcast);
// CONCATENATED MODULE: ./src/HTML5/Text.js

function getTextNodesIn(node) {
  var textNodes = [];

  if (node.nodeType == 3) {
    textNodes.push(node);
  } else {
    var children = node.childNodes;

    for (var i = 0, len = children.length; i < len; ++i) {
      textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
    }
  }

  return textNodes;
}
/**
 * 
 * @param {Element} el 
 * @param {Range} range 
 * @param {Number} start 
 * @returns {Number} -1: ok,  ret >= 0(is length of text) : need move to next element
 * 
 */

function setSelectionRangeStart(el, range, start) {
  if (start > 0) {
    if (el.nodeType == Node.TEXT_NODE) {
      var text = el.data;

      if (start <= text.length) {
        range.setStart(el, start);
        return -1;
      } else return text.length;
    }

    if (el.tagName.toLowerCase() == 'br') {
      return 0;
    } else {
      var delta = 0;
      var i = 0;
      var textLength = 0;
      var newLine = false;

      while (delta >= 0 && i < el.childNodes.length) {
        var childElt = el.childNodes[i];

        if (newLine) {
          newLine = false;
          ++textLength;
        }

        delta = setSelectionRangeStart(childElt, range, start - textLength);
        if (delta >= 0) textLength += delta;

        if (childElt.nodeType != Node.TEXT_NODE && (window.getComputedStyle(childElt).display == 'block' || childElt.tagName.toLowerCase() == 'br')) {
          newLine = true;
        }

        ++i;
      }

      if (delta >= 0) return textLength;
      return -1;
    }
  } else {
    range.setStart(el, 0);
    return -1;
  }
}
/**
 * 
 * @param {Element} el 
 * @param {Range} range 
 * @param {Number} end 
 * @returns {Number} -1: ok,  ret >= 0(is length of text) : need move to next element
 * 
 */

function setSelectionRangeEnd(el, range, end) {
  if (end > 0) {
    if (el.nodeType == Node.TEXT_NODE) {
      var text = el.data;

      if (end <= text.length) {
        range.setEnd(el, end);
        return -1;
      } else return text.length;
    }

    if (el.tagName.toLowerCase() == 'br') {
      return 0;
    } else {
      var delta = 0;
      var i = 0;
      var textLength = 0;
      var newLine = false;

      while (delta >= 0 && i < el.childNodes.length) {
        var childElt = el.childNodes[i];

        if (newLine) {
          newLine = false;
          ++textLength;
        }

        delta = setSelectionRangeEnd(childElt, range, end - textLength);
        if (delta >= 0) textLength += delta;

        if (childElt.nodeType != Node.TEXT_NODE && (window.getComputedStyle(childElt).display == 'block' || childElt.tagName.toLowerCase() == 'br')) {
          newLine = true;
        }

        ++i;
      }

      if (delta >= 0) return textLength;
      return -1;
    }
  } else {
    range.setEnd(el, 0);
    return -1;
  }
}
function setSelectionRange(el, start, end) {
  if (document.createRange && window.getSelection) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var delta;

    if (start >= 0) {
      delta = setSelectionRangeStart(el, range, start);
      if (delta >= 0) range.setStart(el, el.childNodes.length);
    } else {
      start = 0;
      range.setStart(el, 0);
    }

    if (end >= start) {
      delta = setSelectionRangeEnd(el, range, end);
      if (delta >= 0) range.setEnd(el, el.childNodes.length);
    }

    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (document.selection && document.body.createTextRange) {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.collapse(true);
    textRange.moveEnd("character", end);
    textRange.moveStart("character", start);
    textRange.select();
  }
}
function getTextIn(e) {
  if (e.nodeType == Node.TEXT_NODE) {
    return e.data;
  }

  if (e.tagName && e.tagName.toLowerCase() == 'br') return '';
  var texts = [];
  var newLine = false;

  for (var i = 0; i < e.childNodes.length; ++i) {
    if (newLine) {
      newLine = false;
      texts.push('\n');
    }

    var childElt = e.childNodes[i];
    texts.push(getTextIn(childElt));

    if (childElt.nodeType != Node.TEXT_NODE && (window.getComputedStyle(childElt).display == 'block' || childElt.tagName.toLowerCase() == 'br')) {
      newLine = true;
    }
  }

  return texts.join('');
}
function textToNodes(text) {
  var lines = text.split(/\r?\n/);
  return lines.map(function (text) {
    if (text.length == 0) {
      return Dom["b" /* default */].ShareInstance._({
        child: {
          tag: 'br'
        }
      });
    } else {
      return Dom["b" /* default */].ShareInstance._({
        child: {
          text: text
        }
      });
    }
  });
}
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/

function getCaretPosition(oField) {
  // Initialize
  var iCaretPos = 0; // IE Support

  if (document.selection) {
    // Set focus on the element
    oField.focus(); // To get cursor position, get empty selection range

    var oSel = document.selection.createRange(); // Move selection start to 0 position

    oSel.moveStart('character', -oField.value.length); // The caret position is selection length

    iCaretPos = oSel.text.length;
  } // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0') iCaretPos = oField.selectionDirection == 'backward' ? oField.selectionStart : oField.selectionEnd; // Return results


  return iCaretPos;
}
function setCaretPosition(oField, caretPos) {
  if (oField.createTextRange) {
    var range = oField.createTextRange();
    range.move('character', caretPos);
    range.select();
  } else {
    if (oField.selectionStart) {
      oField.focus();
      oField.setSelectionRange(caretPos, caretPos);
    } else oField.focus();
  }
}
function measureText(text, font) {
  // re-use canvas object for better performance
  var canvas = measureText.canvas || (measureText.canvas = document.createElement("canvas"));
  var context = canvas.getContext("2d");
  if (font) context.font = font;
  var metrics = context.measureText(text);
  return metrics;
}
// CONCATENATED MODULE: ./src/Converter/ext2MineType.js
var ext2MineType = {
  aac: "audio/aac",
  abw: "application/x-abiword",
  arc: "application/x-freearc",
  avi: "video/x-msvideo",
  azw: "application/vnd.amazon.ebook",
  bin: "application/octet-stream",
  bmp: "image/bmp",
  bz: "application/x-bzip",
  bz2: "application/x-bzip2",
  cda: "application/x-cdf",
  csh: "application/x-csh",
  css: "text/css",
  csv: "text/csv",
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  eot: "application/vnd.ms-fontobject",
  epub: "application/epub+zip",
  gz: "application/gzip",
  gif: "image/gif",
  htm: "text/html",
  html: "text/html",
  ico: "image/vnd.microsoft.icon",
  ics: "text/calendar",
  jar: "application/java-archive",
  jpeg: "image/jpeg",
  js: "text/javascript",
  json: "application/json",
  jsonld: "application/ld+json",
  mid: "audio/midi",
  mjs: "text/javascript",
  mp3: "audio/mpeg",
  mp4: "video/mp4",
  mpeg: "video/mpeg",
  mpkg: "application/vnd.apple.installer+xml",
  odp: "application/vnd.oasis.opendocument.presentation",
  ods: "application/vnd.oasis.opendocument.spreadsheet",
  odt: "application/vnd.oasis.opendocument.text",
  oga: "audio/ogg",
  ogv: "video/ogg",
  ogx: "application/ogg",
  opus: "audio/opus",
  otf: "font/otf",
  png: "image/png",
  pdf: "application/pdf",
  php: "application/x-httpd-php",
  ppt: "application/vnd.ms-powerpoint",
  pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  rar: "application/vnd.rar",
  rtf: "application/rtf",
  sh: "application/x-sh",
  svg: "image/svg+xml",
  swf: "application/x-shockwave-flash",
  tar: "application/x-tar",
  tif: "image/tiff",
  tiff: "image/tiff",
  ts: "video/mp2t",
  ttf: "font/ttf",
  txt: "text/plain",
  vsd: "application/vnd.visio",
  wav: "audio/wav",
  weba: "audio/webm",
  webm: "video/webm",
  webp: "image/webp",
  woff: "font/woff",
  woff2: "font/woff2",
  xhtml: "application/xhtml+xml",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  xml: "application/xml",
  xul: "application/vnd.mozilla.xul+xml",
  zip: "application/zip",
  "3gp": "video/3gpp",
  "3g2": "video/3gpp2",
  "7z": "application/x-7z-compressed"
};
/* harmony default export */ var Converter_ext2MineType = (ext2MineType);
// CONCATENATED MODULE: ./src/Converter/file.js

function blobToFile(theBlob, fileName) {
  return new File([theBlob], fileName);
}
function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);

  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  var blob = new Blob([ab], {
    type: mimeString
  });
  return blob;
}
function blobToArrayBuffer(blob) {
  var fileReader = new FileReader();
  return new Promise(function (rs) {
    fileReader.onload = function (event) {
      var arrayBuffer = event.target.result;
      rs(arrayBuffer);
    };

    fileReader.readAsArrayBuffer(blob);
  });
}
function stringToBlob(text, type) {
  type = type || 'text/plain';
  var mineTye = type.split('/').length === 2 ? type : Converter_ext2MineType[type] || 'text/plain';
  return new Blob([text], {
    type: mineTye
  });
}
// CONCATENATED MODULE: ./src/Converter/base64.js
function base64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function toSolidBytes(match, p1) {
    return String.fromCharCode('0x' + p1);
  }));
}
;
function base64DecodeUnicode(str) {
  return decodeURIComponent(atob(str).split('').map(function (c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
}
var UnicodeBase64Converter = {
  encode: base64EncodeUnicode,
  decode: base64DecodeUnicode
};
// CONCATENATED MODULE: ./src/Time/Alarm.js
/**
 * 
 * @param {Date| Number} time 
 * @param {Function} callback 
 */
function Alarm(time, callback) {
  this.LIMIT_TIMEOUT = 2147483647;
  this.callback = callback;
  this.state = "STAND_BY";
  this.timeout = -1;
  if (typeof time == 'number') this.time = time;else this.time = time.getTime();
  this.args = Array.prototype.slice.call(arguments, 2);
  this.tick = this.tick.bind(this);
  if (this.time >= new Date().getTime()) this.start();else this.kill();
}

Alarm.prototype.start = function () {
  if (this.state == 'STAND_BY' || this.state == "PAUSE") {
    this.state = "RUNNING";
    this.tick();
    return true;
  }

  return false;
};

Alarm.prototype.pause = function () {
  if (this.state == "RUNNING") {
    clearTimeout(this.timeout);
    this.timeout = -1;
    this.state = 'PAUSE';
  }
};

Alarm.prototype.tick = function () {
  var now = new Date().getTime();

  if (now >= this.time) {
    this.callback && this.callback.apply(null, this.args);
    this.start = 'FINISH';
  } else {
    var deltaTime = Math.min(this.LIMIT_TIMEOUT, this.time - now);
    this.timeout = setTimeout(this.tick, deltaTime);
    this.state = "RUNNING";
  }
};

Alarm.prototype.kill = function () {
  if (this.state != "FINISH" && this.state != "DEAD") {
    if (this.timeout >= 0) clearTimeout(this.timeout);
    this.state = 'DEAD';
    return true;
  }

  return false;
};

/* harmony default export */ var Time_Alarm = (Alarm);
// CONCATENATED MODULE: ./src/AppPattern/Ref.js
/***
 *
 * @param {T} value
 * @constructor
 * @template T
 */
function Ref(value) {
  this.set(value);
}

Ref.prototype.toString = function () {
  return this.value + '';
};
/***
 *
 * @return {T}
 */


Ref.prototype.valueOf = function () {
  return this.value;
};
/***
 *
 * @param {T}value
 */


Ref.prototype.set = function (value) {
  this.value = value;
};
/**
 *
 * @return {T}
 */


Ref.prototype.get = function () {
  return this.value;
};

/* harmony default export */ var AppPattern_Ref = (Ref);
// CONCATENATED MODULE: ./src/Network/XHR.js
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

var XHR = {};

XHR.makeHttpObject = function () {
  try {
    return new XMLHttpRequest();
  } catch (error) {}

  try {
    return new ActiveXObject("Msxml2.XMLHTTP");
  } catch (error) {}

  try {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } catch (error) {}

  throw new Error("Could not create HTTP request object.");
};
/***
 * 
 * @param {String} url
 * @param {String} body
 * @param {String} responseType
 * @param {Function} success
 * @param {Function} failure
 * @returns {Promise}
 */


XHR.getRequest = function (url, props, success, failure) {
  return new Promise(function (rs, rj) {
    var request = XHR.makeHttpObject();
    request.open("GET", url, true);
    if (typeof props == 'string') request.responseType = props || '';else if (props && _typeof(props) == 'object') {
      Object.assign(request, props);
    }
    request.send(null);

    request.onreadystatechange = function () {
      if (request.readyState == 4) {
        if (request.status == 200) {
          var response = request.response;
          success && success(response);
          rs(response);
        } else {
          failure && failure(request.status, request.statusText);
          rj(request.status);
        }
      }
    };

    request.onerror = function () {
      failure && failure(request.status, request.statusText);
      rj(new Error(request.status + request.statusText));
    };
  });
};

XHR.postRepquest = function (url, payload, props, headers, success, failure) {
  return new Promise(function (rs, rj) {
    var method = "POST";
    var shouldBeAsync = true;
    var request = XHR.makeHttpObject();

    request.onreadystatechange = function () {
      if (request.readyState == 4) {
        if (request.status == 200) {
          success && success(request.response);
          rs(request.response);
        } else if (failure) {
          failure && failure(request.status, request.statusText);
          rj({
            status: request.status,
            statusText: request.statusText
          });
        }
      }
    };

    request.onerror = function () {
      failure && failure(request.status, request.statusText);
      rj(new Error(request.status + request.statusText));
    };

    request.open(method, url, shouldBeAsync);
    if (typeof props == 'string') request.responseType = props || '';else if (props && _typeof(props) == 'object') {
      Object.assign(request, props);
    }
    headers = headers || {};
    headers["Content-Type"] = headers["Content-Type"] || "application/json;charset=UTF-8";
    Object.keys(headers).forEach(function (key) {
      request.setRequestHeader(key, headers[key]);
    });
    request.send(payload);
  });
};

XHR.request = function (method, url, props, headers, body, successCallback, failureCallback) {
  return new Promise(function (rs, rj) {
    var shouldBeAsync = true;
    var request = new XMLHttpRequest();

    request.onreadystatechange = function () {
      if (request.readyState == 4) {
        if (request.status == 200) {
          successCallback && successCallback(request.response);
          rs(request.response);
        } else {
          failureCallback && failureCallback(request.status, request.statusText);
          rj({
            status: request.status,
            statusText: request.statusText
          });
        }
      }
    };

    request.onerror = function () {
      var error = new Error("Network Error!");
      if (failureCallback) failureCallback(error);
      rj(error);
    };

    request.open(method, url, shouldBeAsync);
    if (typeof props == 'string') request.responseType = props || '';else if (props && _typeof(props) == 'object') {
      Object.assign(request, props);
    }
    headers = headers || {};
    headers["Content-Type"] = headers["Content-Type"] || "application/json;charset=UTF-8";
    Object.keys(headers).forEach(function (key) {
      request.setRequestHeader(key, headers[key]);
    });
    request.send(body);
  });
};

/* harmony default export */ var Network_XHR = (XHR);
// CONCATENATED MODULE: ./src/String/stringFormat.js
/**
 *
 * @param {String} s
 * @param {Number} maxLength
 */
function wrapToLines(s, maxLength) {
  var res = [];
  var currentWord = '';
  var currentLine = '';

  for (var i = 0; i < s.length; ++i) {
    if (s[i].match(/\s/)) {
      if (currentWord.length + currentLine.length >= maxLength) {
        if (currentLine.length > 0) {
          res.push(currentLine.trim());
          currentLine = '';
          currentWord = currentWord.trimLeft() + s[i];
        } else {
          currentLine = currentLine + currentWord;
          res.push(currentLine.trim());
          currentLine = '';
          currentWord = '';
        }
      } else {
        currentLine = currentLine + currentWord;
        currentWord = s[i];
      }
    } else {
      currentWord = currentWord + s[i];
    }
  }

  currentLine = (currentLine + currentWord).trim();
  if (currentLine.length > 0) res.push(currentLine);
  return res;
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function nonAccentVietnamese(s) {
  return s.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a").replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, "A").replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e").replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, "E").replace(/ì|í|ị|ỉ|ĩ/g, "i").replace(/Ì|Í|Ị|Ỉ|Ĩ/g, "I").replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o").replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, "O").replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u").replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, "U").replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y").replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, "Y").replace(/đ/g, "d").replace(/Đ/g, "D").replace(/\u0300|\u0301|\u0303|\u0309|\u0323/g, "").replace(/\u02C6|\u0306|\u031B/g, "");
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function pascalCaseToCamelCase(s) {
  return s.substr(0, 1).toLowerCase() + s.substr(1);
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function kebabCaseToCamelCase(s) {
  return s.replace(/-+([^-])/g, function (full, c) {
    return c.toUpperCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function underScoreToCamelCase(s) {
  return s.replace(/(_+)?([^_]+)/g, function (full, underscore, word) {
    if (underscore) {
      if (word) {
        return word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase();
      } else return '';
    } else {
      return word.toLowerCase();
    }
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function camelCaseToPascalCase(s) {
  return s.substr(0, 1).toUpperCase() + s.substr(1);
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function underScoreToPascalCase(s) {
  return s.replace(/(_+|^)?([^_]+)/g, function (full, underscore, word) {
    return word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function kebabCaseToPascalCase(s) {
  return s.replace(/(-+|^)([^-])/g, function (full, u, c) {
    return c.toUpperCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function pascalCaseToKebabCase(s) {
  return s.replace(/[A-Z][^A-Z]*/g, function (full, index) {
    if (index == 0) return full.toLowerCase();
    return '-' + full.toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function camelCaseToKebabCase(s) {
  return s.replace(/(^|[A-Z])[^A-Z]*/g, function (full, index) {
    if (index == 0) return full.toLowerCase();
    return '-' + full.toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function underScoreToKebabCase(s) {
  return s.replace(/(^|_+)([^_]+)/g, function (full, score, word, index) {
    if (index == 0) return word.toLowerCase();
    return '-' + word.toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function pascalCaseToUnderScore(s) {
  return s.replace(/[A-Z][^A-Z]*/g, function (full, index) {
    if (index == 0) return full.toLowerCase();
    return '_' + full.toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function pascalCaseToUpperUnderScore(s) {
  return s.replace(/[A-Z][^A-Z]*/g, function (full, index) {
    if (index == 0) return full.toUpperCase();
    return '_' + full.toUpperCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function camelCaseToUnderScore(s) {
  return s.replace(/(^|[A-Z])[^A-Z]*/g, function (full, index) {
    if (index == 0) return full.toLowerCase();
    return '_' + full.toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function camelCaseToUpperUnderScore(s) {
  return s.replace(/(^|[A-Z])[^A-Z]*/g, function (full, index) {
    if (index == 0) return full.toUpperCase();
    return '_' + full.toUpperCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function kebabCaseToUnderScore(s) {
  return s.replace(/(-+|^)([^-]+)/g, function (full, u, word, index) {
    if (index == 0) return word.toLowerCase();
    return '_' + word.toLowerCase();
  });
}
/**
 *
 * @param {String} s
 * @returns {String}
 */

function kebabCaseToUpperUnderScore(s) {
  return s.replace(/(-+|^)([^-]+)/g, function (full, u, word, index) {
    if (index == 0) return word.toUpperCase();
    return '_' + word.toUpperCase();
  });
}
/***
 *
 * @param {String} text
 */

function normalizeIdent(text, opt) {
  var spaces = '_';

  if (opt && 'spaces' in opt) {
    spaces = opt.spaces || '';
  }

  var symbols = '_';

  if (opt && 'symbols' in opt) {
    symbols = opt.symbols || '';
  }

  var startsWithDigit = false;

  if (opt && 'startsWithDigit' in opt) {
    startsWithDigit = opt.startsWithDigit || false;
  }

  var res = nonAccentVietnamese(text);

  if (typeof spaces === "string") {
    res = res.replace(/\s+/g, spaces);
  }

  if (typeof symbols === 'string') {
    if (spaces === '_') res = res.replace(/[^a-zA-Z0-9_$]+/g, symbols);else if (spaces === '-') {
      res = res.replace(/[^a-zA-Z0-9_$\-]+/g, symbols);
    }
  }

  if (!startsWithDigit && res.match(/^[0-9]/)) {
    res = '$' + res;
  }

  return res;
}
String.nonAccentVietnamese = nonAccentVietnamese;

String.prototype.nonAccentVietnamese = function () {
  return String.nonAccentVietnamese(this);
};
// EXTERNAL MODULE: ./src/JSX/attribute.js
var JSX_attribute = __webpack_require__(5);

// CONCATENATED MODULE: ./src/JSX/dom.js

function domVisitor(jsxCode) {
  var visitor = {
    File: function File(node, ac) {
      return acept(node.program, ac);
    },
    Program: function Program(node, ac) {
      ac.child = node.body.map(function (cNode) {
        return acept(cNode, {});
      });
      return ac;
    },
    ExpressionStatement: function ExpressionStatement(node, ac) {
      return acept(node.expression, ac);
    },
    JSXElement: function JSXElement(node, ac) {
      acept(node.openingElement, ac);

      if (node.children && node.children.length > 0) {
        ac.child = node.children.map(function (cNode) {
          return acept(cNode, {});
        });
      }

      return ac;
    },
    JSXOpeningElement: function JSXOpeningElement(node, ac) {
      var name = {};
      acept(node.name, name);
      ac.tag = name.value;

      if (node.attributes && node.attributes.length > 0) {
        node.attributes.forEach(function (aNode) {
          var attribute = {};
          acept(aNode, attribute);

          if (attribute.key) {
            if (attribute.key.startsWith('data-')) {
              ac.data = ac.data || {};
              ac.data[attribute.key.replace('data-', '')] = attribute.value;
            } else if (attribute.key.startsWith('prop-')) {
              ac.props = ac.props || {};
              ac.props[attribute.key.replace('prop-', '')] = attribute.value;
            } else if (attribute.key.startsWith('on-')) {
              ac.on = ac.props || {};
              ac.on[attribute.key.replace('on-', '')] = attribute.value;
            } else if (attribute.key == 'style') {
              ac.style = Object(JSX_attribute["parseStyleAttr"])(attribute.value);
            } else if (attribute.key == 'class') {
              var classList = Object(JSX_attribute["parseClassAttr"])(attribute.value);
              if (classList.length > 0) ac.class = classList;
            } else {
              ac.attr = ac.attr || {};
              ac.attr[attribute.key] = attribute.value;
            }
          }
        }, {});
      }

      return ac;
    },
    JSXIdentifier: function JSXIdentifier(node, ac) {
      ac.value = node.name;
    },
    JSXAttribute: function JSXAttribute(node, ac) {
      var key = {};
      acept(node.name, key);
      ac.key = key.value;
      var value = {};
      acept(node.value, value);
      ac.value = value.value;
      return ac;
    },
    StringLiteral: function StringLiteral(node, ac) {
      ac.value = node.value;
    },
    JSXExpressionContainer: function JSXExpressionContainer(node, ac) {
      ac.value = {
        expression: jsxCode.substring(node.expression.start, node.expression.end)
      };
      return ac;
    },
    JSXText: function JSXText(node, ac) {
      ac.text = node.value;
      return ac;
    }
  };

  function acept(node, ac) {
    return node && visitor[node.type] && visitor[node.type](node, ac);
  }

  return {
    acept: acept,
    visitor: visitor
  };
}
/***
 * @param {String} jsxCode
 */

function parseDom(jsxCode) {
  jsxCode = jsxCode.trim().replace(/>\s+</gm, '><').replace(/<(\/?)(img|input|link|br|meta)([^>]*)>/g, function (sub, end, tag, content) {
    if (end == '/') return '';
    return '<' + tag + content + '/>';
  });
  var ast = babel.parse(jsxCode, {
    plugins: [babel.pluginSyntaxJsx]
  });
  var xmlData = {};
  domVisitor(jsxCode).acept(ast, xmlData);
  if (xmlData.child.length > 1) return xmlData.child;
  return xmlData.child[0];
}
// EXTERNAL MODULE: ./src/Code/noop.js
var noop = __webpack_require__(4);

// CONCATENATED MODULE: ./src/AppPattern/Context.js


function Context() {
  /****
   *
   * @type {"CREATE"|"PAUSE"|"RUNNING"|"STANDBY"|"DIE"|"STOP"}
   */
  this.state = "CREATE";
  /**
   * @type {Context}
   */

  this.parent = null;
  /***
   *
   * @type {null|ContextManager}
   */

  this.ctxMng = null;
}
/**
 * @returns {*}
 */


Context.prototype.getContext = function (key) {
  var ctx = this;
  var res;

  while (ctx && !res) {
    if (ctx.ctxMng) {
      res = ctx.ctxMng.get(key);
    }

    ctx = ctx.parent;
  }

  return res;
};
/**
 * @param {string} key
 * @param {*} value
 * @returns {*}
 */


Context.prototype.setContext = function (key, value) {
  return this.getContextManager().set(key, value);
};
/**
 * @returns {ContextManager}
 */


Context.prototype.getContextManager = function () {
  var ctx = this;
  var res;

  while (ctx && !res) {
    if (ctx.ctxMng) {
      res = ctx.ctxMng;
    }

    ctx = ctx.parent;
  }

  return res;
};
/**
 * @param {Context} parent
 */


Context.prototype.attach = function (parent) {
  //stop before attach to new context
  this.stop();
  /**
   * @type {Application}
   */

  this.parent = parent;
  this.onAttached && this.onAttached();
};

Context.prototype.detach = function () {
  this.stop();
  this.onDetached && this.onDetached();
  this.parent = null;
};

Context.prototype.pause = function () {
  if (this.state.match(/RUNNING|PAUSE/)) {
    if (this.state === "RUNNING") {
      this.state = "PAUSE";
      this.onPause && this.onPause();
    }
  } else {
    console.warn(this, "NOT RUNNING");
  }
};

Context.prototype.resume = function () {
  if (!this.state.match(/STANDBY|PAUSE|RUNNING/)) {
    console.error(this, 'NOT READY!', this.state);
    return;
  }

  if (this.state === "RUNNING") return;
  this.state = "RUNNING";
  this.onResume && this.onResume();
};
/***
 * @param {boolean=} standBy start but waiting for resume()
 */


Context.prototype.start = function (standBy) {
  if (this.state.match(/DIE/)) {
    console.error(this, 'DIED!');
    return;
  }

  if (this.state.match(/RUNNING/)) return;

  if (this.state.match(/STOP|CREATE/)) {
    this.state = "STANDBY";
    this.onStart && this.onStart();
  }

  if (!standBy && this.state.match(/STANDBY|PAUSE/)) {
    this.resume();
  }
};

Context.prototype.stop = function () {
  if (this.state.match(/STOP|DIE|CREATE/)) return;
  if (this.state.match(/RUNNING/)) this.pause();
  this.state = "STOP";
  this.onStop && this.onStop();
};

Context.prototype.destroy = function () {
  if (this.state.match(/DIE/)) return;
  if (this.state.match(/RUNNING|PAUSE/)) this.stop();
  this.state = "DIE";
  this.onDestroy && this.onDestroy();
};

Context.prototype.onDestroy = noop["a" /* default */];
Context.prototype.onStop = noop["a" /* default */];
Context.prototype.onStart = noop["a" /* default */];
Context.prototype.onResume = noop["a" /* default */];
Context.prototype.onPause = noop["a" /* default */];
Context.prototype.onDetached = noop["a" /* default */];
Context.prototype.onAttached = noop["a" /* default */];
/* harmony default export */ var AppPattern_Context = (Context);
// CONCATENATED MODULE: ./src/AppPattern/Activity.js
 //NOTE: !impotant : don't make setter, getter for activity, just code like JAVA

/** 
 * @class
 */

function Activity() {
  AppPattern_Context.call(this);
}

Object.defineProperties(Activity.prototype, Object.getOwnPropertyDescriptors(AppPattern_Context.prototype));
Activity.prototype.constructor = Activity;

Activity.prototype.startActivity = function (activity) {
  if (this.parent) {
    this.parent.startActivity(activity);
  } else {}
};

Activity.prototype.finish = function () {
  if (this.parent) {
    this.parent.stopActivity(this);
  } else {}
};

/* harmony default export */ var AppPattern_Activity = (Activity);
// CONCATENATED MODULE: ./src/AppPattern/ContextManager.js
function ContextManager() {
  this.__contextData__ = {};
}
/**
 * @param {String} key
 * @returns {*}
 */


ContextManager.prototype.get = function (key) {
  return this.__contextData__[key];
};
/**
 * @param {String} key
 * @param {*} value
 * @returns {Context}
 */


ContextManager.prototype.set = function (key, value) {
  this.__contextData__[key] = value;
  return this;
};

ContextManager.prototype.assign = function (obj) {
  Object.assign(this.__contextData__, obj);
  return this;
};

ContextManager.prototype.remove = function (key) {
  delete this.__contextData__[key];
  return this;
};

ContextManager.prototype.contains = function (key) {
  return key in this.__contextData__;
};

/* harmony default export */ var AppPattern_ContextManager = (ContextManager);
// CONCATENATED MODULE: ./src/AppPattern/Application.js


/**
 * @class
 */

function Application() {
  AppPattern_Context.call(this);
  this.activityStack = [];
  /** @type {Activity} */

  this.currentActivity = null;
}

Object.defineProperties(Application.prototype, Object.getOwnPropertyDescriptors(AppPattern_Context.prototype));
Application.prototype.constructor = Application;
/**
 * @param {Activity} activity
 */

Application.prototype.startActivity = function (activity) {
  if (this.currentActivity != null) {
    this.currentActivity.pause();
    this.activityStack.push(this.currentActivity);
  }

  this.currentActivity = activity;
  this.appendChild(activity);
  activity.attach(this);
  this.setContentView(activity.getView(), true);
  activity.start();
};
/**
 * @param {Activity} activity
 */


Application.prototype.stopActivity = function (activity) {
  if (this.currentActivity == activity) {
    if (this.activityStack.length == 0) {//todo
    } else {
      activity.detach();
      this.removeChild(this.currentActivity);
      this.currentActivity = this.activityStack.pop();
      this.setContentView(this.currentActivity.getView());
      this.currentActivity.resume();
    }
  } else {
    console.error("NOT ON TOP ACTIVITY");
  }
};
/**
 * @param {HTMLElement} view
 */


Application.prototype.setContentView = function (view, overlay) {
  throw new Error("Not Implement!");
};

Application.prototype.backToTopActivity = function () {
  while (this.activityStack.length > 0) {
    this.currentActivity.stop();
    this.currentActivity = this.activityStack.pop();
  }

  this.setContentView(this.currentActivity.getView());
  this.currentActivity.resume();
};

/* harmony default export */ var AppPattern_Application = (Application);
// CONCATENATED MODULE: ./src/AppPattern/VarScope.js
function VarScope(parent) {
  this.parent = parent;
  this.data = {};
}

VarScope.prototype.revoke = function (name) {
  delete this.data[name];
  return this;
};

VarScope.prototype.isDeclared = function (name) {
  return name in this.data;
};
/***
 *
 * @param name
 * @param initValue
 * @param {boolean=} force
 * @return {VarScope}
 */


VarScope.prototype.declare = function (name, initValue, force) {
  if (name in this.data && !force) throw new Error(name + ' is already delared in this scope!');
  this.data[name] = initValue;
  return this;
};

VarScope.prototype.get = function (name) {
  var scope = this.findScope(name);
  if (!scope) throw new Error(name + ' is not declared!');
  return scope.data[name];
};

VarScope.prototype.set = function (name, value) {
  var scope = this.findScope(name);
  if (!scope) throw new Error(name + ' is not declared!');
  scope.data[name] = value;
};

VarScope.prototype.findScope = function (name) {
  var currentScope = this;

  while (currentScope) {
    if (name in currentScope.data) break;
    currentScope = currentScope.parent;
  }

  return currentScope;
};

/* harmony default export */ var AppPattern_VarScope = (VarScope);
// CONCATENATED MODULE: ./src/AppPattern/GrandContext.js



/***
 * @extends Context
 * @constructor
 */

function GrandContext() {
  AppPattern_Context.call(this);
  this.ctxMng = new AppPattern_ContextManager();
}

OOP["a" /* default */].mixClass(GrandContext, AppPattern_Context);
/* harmony default export */ var AppPattern_GrandContext = (GrandContext);
// CONCATENATED MODULE: ./src/AppPattern/Fragment.js




/***
 * @extends GrandContext
 * @constructor
 */

function Fragment() {
  AppPattern_GrandContext.call(this);
}

OOP["a" /* default */].mixClass(Fragment, AppPattern_GrandContext);

Fragment.prototype.createView = function () {
  throw new Error("Not implement!");
};

Fragment.prototype.getView = function () {
  if (this.$view) return this.$view;
  this.$view = this.createView() || this.$view;
  if (!this.$view) throw new Error("this.$view must be not null!");
  if (this.onCreated) this.onCreated();
  return this.$view;
};

Fragment.prototype.onCreated = noop["a" /* default */];
/* harmony default export */ var AppPattern_Fragment = (Fragment);
// CONCATENATED MODULE: ./src/Math/Vec2.js
/***
 *
 * @param  {Number} x
 * @param {Number} y
 * @constructor
 */
function Vec2(x, y) {
  this.x = x;
  this.y = y;
}
/***
 *
 * @returns {Vec2}
 */


Vec2.prototype.copy = function () {
  return new Vec2(this.x, this.y);
};
/***
 *
 * @returns {string}
 */


Vec2.prototype.toString = function () {
  return "(" + this.x + ", " + this.y + ")";
};
/***
 *
 * @returns {number}
 */


Vec2.prototype.abs = function () {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};
/***
 *
 * @returns {Vec2}
 */


Vec2.prototype.normalized = function () {
  var l = this.abs();
  if (l == 0) l = 1;
  return this.div(l);
};
/***
 *
 * @param {number} h
 * @returns {Vec2}
 */


Vec2.prototype.mult = function (h) {
  return new Vec2(this.x * h, this.y * h);
};
/***
 *
 * @param {number} h
 * @returns {Vec2}
 */


Vec2.prototype.div = function (h) {
  return new Vec2(this.x / h, this.y / h);
};
/***
 *
 * @param v
 * @returns {number}
 */


Vec2.prototype.dist = function (v) {
  var dx = v.x - this.x;
  var dy = v.y - this.y;
  return Math.sqrt(dx * dx + dy * dy);
};
/***
 *
 * @param {Vec2} v
 * @returns {Vec2}
 */


Vec2.prototype.sub = function (v) {
  return new Vec2(this.x - v.x, this.y - v.y);
};
/***
 *
 * @param {Vec2} v
 * @returns {Vec2}
 */


Vec2.prototype.add = function (v) {
  return new Vec2(this.x + v.x, this.y + v.y);
};
/***
 *
 * @returns {Vec2}
 */


Vec2.prototype.inv = function () {
  return new Vec2(-this.x, -this.y);
};
/***
 *
 * @param {Vec2} v
 * @param {number} h
 * @returns {Vec2}
 */


Vec2.prototype.linear = function (v, h) {
  return new Vec2(this.x * (1 - h) + v.x * h, this.y * (1 - h) + v.y * h);
};
/***
 *
 * @param {Vec2} v1
 * @returns {number}
 */


Vec2.prototype.dot = function (v1) {
  return this.x * v1.x + this.y * v1.y;
};
/***
 *
 * @param {Vec2} v1
 * @returns {number}
 */


Vec2.prototype.cross = function (v1) {
  return this.x * v1.y - this.y * v1.x;
};
/***
 *
 * @returns {number}
 */


Vec2.prototype.direction = function () {
  return Math.atan2(this.y, this.x);
};
/***
 *
 * @param {Number} dx
 * @param {Number} dy
 */


Vec2.prototype.translate = function (dx, dy) {
  return this.add(new Vec2(dx, dy));
};
/****
 *
 * @param {Number} angle - radian
 * @returns {Vec2}
 */


Vec2.prototype.rotate = function (angle) {
  var sinA = Math.sin(angle);
  var cosA = Math.cos(angle);
  var x = this.x * cosA - this.y * sinA;
  var y = this.x * sinA + this.y * cosA;
  return new Vec2(x, y);
};
/***
 *
 * @returns {Vec2}
 */


Vec2.prototype.rotate90 = function () {
  return new Vec2(-this.y, this.x);
};
/***
 *
 * @param {Vec2} b
 */


Vec2.prototype.equals = function (b) {
  return b && this.x === b.x && this.y === b.y;
};
/***
 *
 * @param {number} angle
 * @returns {Vec2}
 */


Vec2.fromDirection = function (angle) {
  return new Vec2(Math.cos(angle), Math.sin(angle));
};
/***
 *
 * @param x
 * @param y
 * @returns {Vec2}
 */


Vec2.make = function (x, y) {
  if (x instanceof Array) {
    return new Vec2(x[0], x[1]);
  } else if (x instanceof Vec2) {
    return x.copy();
  } else return new Vec2(x, y);
};

/* harmony default export */ var Math_Vec2 = (Vec2);
// CONCATENATED MODULE: ./src/Math/Rectangle.js

/**
 *
 * @param {Number} x
 * @param {Number} y
 * @param {Number} width
 * @param {Number} height
 */

function Rectangle(x, y, width, height) {
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
}
/**
 *
 * @return {Vec2}
 * @constructor
 */


Rectangle.prototype.A = function () {
  return new Math_Vec2(this.x, this.y);
};
/***
 *
 * @return {Vec2}
 * @constructor
 */


Rectangle.prototype.B = function () {
  return new Math_Vec2(this.x + this.width, this.y);
};
/***
 *
 * @return {Vec2}
 * @constructor
 */


Rectangle.prototype.C = function () {
  return new Math_Vec2(this.x + this.width, this.y + this.height);
};
/***
 *
 * @return {Vec2}
 * @constructor
 */


Rectangle.prototype.D = function () {
  return new Math_Vec2(this.x, this.y + this.height);
};
/***
 *
 * @return {number}
 */


Rectangle.prototype.square = function () {
  return this.width * this.height;
};

Rectangle.prototype.nearestPoint = function (arg0, arg1) {
  if (arg1) arg0 = Math_Vec2.make(arg0, arg1);
  var res = this.A();
  var mind = res.dist(arg0);
  var d = this.B().dist(arg0);

  if (d < mind) {
    mind = d;
    res = this.B();
  }

  d = this.C().dist(arg0);

  if (d < mind) {
    mind = d;
    res = this.C();
  }

  d = this.D().dist(arg0);

  if (d < mind) {
    mind = d;
    res = this.D();
  }

  return res;
};

Rectangle.prototype.centerPoint = function () {
  return new Math_Vec2(this.x + this.width / 2, this.y + this.height / 2);
};
/***
 *
 * @param {Rectangle} r
 * @param {number} margin
 * @return {boolean}
 */


Rectangle.prototype.isCollapse = function (r, margin) {
  if (!margin) margin = 0;
  return !(this.x >= r.x + r.width + margin || this.y >= r.y + r.height + margin || r.x >= this.x + this.width + margin || r.y >= this.y + this.height + margin);
};
/***
 *
 * @param {Rectangle} r
 * @return {number}
 */


Rectangle.prototype.collapsedSquare = function (r) {
  var collapseRect = this.collapsedRect(r);

  if (collapseRect) {
    return collapseRect.square();
  } else {
    return 0;
  }
};
/***
 *
 * @param {Rectangle} r
 * @return {Rectangle}
 */


Rectangle.prototype.collapsedRect = function (r) {
  var maxX, minX, maxY, minY, width, height;
  minX = Math.max(this.x, r.x);
  minY = Math.max(this.y, r.y);
  maxX = Math.min(this.x + this.width, r.x + r.width);
  maxY = Math.min(this.y + this.height, r.y + r.height);
  width = maxX - minX;
  height = maxY - minY;

  if (width >= 0 && height >= 0) {
    return new Rectangle(minX, minY, width, height);
  }

  return null;
};
/**
 * @param {Rectangle} r
 * @returns {Boolean}
 */


Rectangle.prototype.contains = function (r) {
  return this.x <= r.x && this.y <= r.y && this.x + this.width >= r.x + r.width && this.y + this.height >= r.y + r.height;
};
/**
 * @param {Vec2} p
 * @returns {Boolean}
 */


Rectangle.prototype.containsPoint = function (p) {
  return this.x <= p.x && this.y <= p.y && this.x + this.width >= p.x && this.y + this.height >= p.y;
};
/**
 * @param {Rectangle} other
 * @returns {Rectangle}
 */


Rectangle.prototype.merge = function (other) {
  var left = Math.min(this.x, other.x);
  var top = Math.min(this.y, other.y);
  var right = Math.max(this.x + this.width, other.x + other.width);
  var bottom = Math.max(this.y + this.height, other.y + other.height);
  return new Rectangle(left, top, right - left, bottom - top);
};
/**
 * @returns {Rectangle}
 */


Rectangle.prototype.clone = function () {
  return new Rectangle(this.x, this.y, this.width, this.height);
};
/***
 *
 * @param {Rectangle} r
 */


Rectangle.prototype.equals = function (r) {
  return this.x === r.x && this.y === r.y && this.height === r.height && this.width === r.width;
};
/**
 * @param {Number} x
 * @param {Number} y
 * @param {Number} width
 * @param {Number} height
 * @returns {Rectangle}
 */


Rectangle.make = function (x, y, width, height) {
  return new Rectangle(x, y, width, height);
};
/**
 * @param {Number} x
 * @param {Number} y
 * @param {Number} width
 * @param {Number} height
 * @returns {Rectangle}
 */


Rectangle.makeCenter = function (x, y, width, height) {
  return new Rectangle(x - width / 2, y - height / 2, width, height);
};
/**
 * @param {ClientRect|DOMRect} clientRect
 * @returns {Rectangle}
 */


Rectangle.fromClientRect = function (clientRect) {
  return new Rectangle(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
};
/***
 *
 * @param {Vec2[]} points
 * @returns  {Rectangle}
 */


Rectangle.boundingPoints = function (points) {
  var minX = Infinity,
      minY = Infinity,
      maxX = -Infinity,
      maxY = -Infinity;
  var point;

  for (var i = 0; i < points.length; ++i) {
    point = points[i];
    minX = Math.min(minX, point.x);
    maxX = Math.max(maxX, point.x);
    minY = Math.min(minY, point.y);
    maxY = Math.max(maxY, point.y);
  }

  return new Rectangle(minX, minY, maxX - minX, maxY - minY);
};

/* harmony default export */ var Math_Rectangle = (Rectangle);
// CONCATENATED MODULE: ./src/Math/int.js
/**
 *
 * @param {number} x
 * @param {number} l
 * @param {number} h
 * @param {number} L
 * @param {number} H
 * @returns {number}
 */
function map(x, l, h, L, H) {
  return (x - l) / (h - l) * (H - L) + L;
}
function sumArr(arr) {
  var res = 0;

  for (var i = 0; i < arr.length; ++i) {
    res += arr[i];
  }

  return res;
}
function radianInRange(x, start, end) {
  if (start > end) return radianInRange(x, end, start);
  if (x < start) x += Math.PI * 2 * Math.ceil((start - x) / 2 / Math.PI);
  if (x > end) x -= Math.PI * 2 * Math.ceil((x - end) / 2 / Math.PI);
  return x >= start && x <= end;
}
function distance(x0, y0, x1, y1) {
  var dx = x0 - x1;
  var dy = y0 - y1;
  return Math.sqrt(dx * dx + dy * dy);
}
/**
 *
 * @param {Number} numb
 * @param {Number} floatFixed
 * @param {"."|","} decimalSeparator
 * @param {","|"."} thousandsSeparator
 * @param {Number} decimalPadding
 */

function numberToString(numb, floatFixed, decimalSeparator, thousandsSeparator, decimalPadding) {
  if (floatFixed === undefined || floatFixed === null || typeof floatFixed != "number" || isNaN(floatFixed) || floatFixed < -1) floatFixed = -1;
  if (decimalSeparator === undefined || decimalSeparator === null || decimalSeparator != '.' && decimalSeparator != ',') decimalSeparator = '.';
  if (thousandsSeparator === undefined || thousandsSeparator === null || floatFixed >= 0 && thousandsSeparator == decimalSeparator) thousandsSeparator = undefined;
  if (thousandsSeparator != ',' && thousandsSeparator != '.') thousandsSeparator = undefined;
  if (decimalPadding === undefined || decimalPadding === null || typeof decimalPadding != "number" || isNaN(decimalPadding) || decimalPadding < 0) decimalPadding = 0;
  var text = numb.toString();
  var matched = text.match(/[+-]?([0-9]*)(\.([0-9]*))?(e([+-]?[0-9]+))?/);
  var dec = matched[1] || '';
  var real = matched[3] || '';
  var floatPoint = parseInt(matched[5] || '0');
  var decDigits = dec.split('').map(function (d) {
    return parseInt(d);
  });
  var realDigits = real.split('').map(function (d) {
    return parseInt(d);
  });

  while (floatPoint < 0) {
    if (decDigits.length > 0) {
      realDigits.unshift(decDigits.pop());
    } else {
      realDigits.unshift(0);
    }

    floatPoint++;
  }

  while (floatPoint > 0) {
    if (realDigits.length > 0) {
      decDigits.push(realDigits.unshift());
    } else {
      decDigits.push(0);
    }

    floatPoint++;
  }

  var mem = 0,
      i,
      cValue;

  if (floatFixed > realDigits.length) {
    while (realDigits.length < floatFixed) {
      realDigits.push(0);
    }
  } else if (floatFixed < realDigits.length && floatFixed >= 0) {
    i = floatFixed;
    mem = realDigits[i] >= 5 ? 1 : 0;
    realDigits.splice(floatFixed);
    --i;

    while (mem > 0) {
      if (i >= 0) {
        cValue = realDigits[i] + mem;
        realDigits[i] = cValue % 10;
        mem = Math.floor(cValue / 10);
      } else {
        if (decDigits.length + i < 0) decDigits.unshift(0);
        cValue = decDigits[decDigits.length + i] + mem;
        decDigits[decDigits.length + i] = cValue % 10;
        mem = Math.floor(cValue / 10);
      }

      --i;
    }
  }

  while (decDigits.length < decimalPadding) {
    decDigits.unshift(0);
  }

  var decText = numb < 0 ? '-' : '';
  var breadMod = (decDigits.length + 2) % 3;

  if (thousandsSeparator) {
    for (i = 0; i < decDigits.length; ++i) {
      decText += decDigits[i];

      if (i % 3 == breadMod && i + 1 < decDigits.length) {
        decText += thousandsSeparator;
      }
    }
  } else {
    decText += decDigits.join('');
  }

  var realText = realDigits.length == 0 ? '' : decimalSeparator + realDigits.join('');
  return decText + realText;
}
function numberAutoFixed(x, eDelta) {
  eDelta = eDelta || 10;
  eDelta = Math.round(eDelta);
  var e = parseFloat('1e+' + eDelta);
  return Math.round(x * e) / e;
}
/***
 *
 * @param {number} number
 * @param {number} length
 * @returns {string}
 */

function integerZeroPadding(number, length) {
  var res = number + '';

  while (res.length < length) {
    res = '0' + res;
  }

  return res;
}
function harmonicMean(a, b) {
  return 2 / (1 / a + 1 / b);
}
// CONCATENATED MODULE: ./src/Math/Arc.js



function Arc(x, y, r, start, end) {
  this.x = x;
  this.y = y;
  this.r = r;
  this.start = start;
  this.end = end;
}

Arc.prototype.isPointInBound = function (p) {
  if (distance(this.x, this.y, p.x, p.y) > r) return false;
  return radianInRange(Math.atan2(p.y - this.y, p.x - this.x), start, end);
};

Arc.prototype.isRectInBound = function (rect) {
  return this.isPointInBound(rect.A()) && this.isPointInBound(rect.B()) && this.isPointInBound(rect.C()) && this.isPointInBound(rect.D());
};

Arc.prototype.isRectOutBound = function (rect) {
  return !this.isPointInBound(rect.A()) && !this.isPointInBound(rect.B()) && !this.isPointInBound(rect.C()) && !this.isPointInBound(rect.D());
};

Arc.prototype.isRectCollapse = function (rect) {
  return this.isPointInBound(rect.A()) || this.isPointInBound(rect.B()) || this.isPointInBound(rect.C()) || this.isPointInBound(rect.D());
};

Arc.prototype.centerPoint = function () {
  var mid = (this.start + this.end) / 2;
  var x = this.x + Math.cos(mid) * this.r * 2 / 3;
  var y = this.y + Math.sin(mid) * this.r * 2 / 3;
  return new Math_Vec2(x, y);
};

Arc.prototype.centerRoundPoint = function () {
  var mid = (this.start + this.end) / 2;
  var x = this.x + Math.cos(mid) * this.r;
  var y = this.y + Math.sin(mid) * this.r;
  return new Math_Vec2(x, y);
};

Arc.make = function (x, y, r, start, end) {
  return new Arc(x, y, r, start, end);
};

/* harmony default export */ var Math_Arc = (Arc);
// CONCATENATED MODULE: ./src/Math/NumRange.js
/**
 * 
 * @param {Number} start 
 */
function NumRange(start, length) {
  if (arguments.length == 1) length = 0;else if (arguments.length == 0) {
    length = 0;
    start = 0;
  }
  this.start = start;
  this.length = length;
}
/**
 * @param {Number} num 
 */


NumRange.prototype.contains = function (num) {
  return num >= this.start && num <= this.start + this.length;
};
/**
 * @param {NumRange} other
 * @returns {NumRange}
 */


NumRange.prototype.merge = function (other) {
  var start = Math.min(this.start, other.start);
  var end = Math.max(this.start + this.length, other.start + other.length);
  return new NumRange(start, end - start);
};

NumRange.prototype.centerValue = function () {
  return this.start + this.length / 2;
};
/**
 * @param {NumRange} other
 * @returns {Boolean}
 */


NumRange.prototype.isCollapse = function (other) {
  var start = Math.max(this.start, other.start);
  var end = Math.min(this.start + this.length, other.start + other.length);
  return start <= end;
};
/**
 * @param {NumRange} other
 * @returns {Boolean}
 */


NumRange.prototype.collapsedNumRange = function (other) {
  var start = Math.max(this.start, other.start);
  var end = Math.min(this.start + this.length, other.start + other.length);
  if (start <= end) return new NumRange(start, end - start);
  return null;
};

NumRange.prototype.clone = function () {
  return new NumRange(this.start, this.length);
};

/* harmony default export */ var Math_NumRange = (NumRange);
// CONCATENATED MODULE: ./src/HTML5/Clipboard.js
function copyImage(src) {
  var ranges, sel;

  if (window.getSelection) {
    sel = window.getSelection(); //backup

    ranges = [];

    for (var i = 0; i < sel.rangeCount; ++i) {
      ranges.push(sel.getRangeAt(i));
    } //copy


    var contentdiv = document.createElement('div');
    var image = document.createElement('img');
    contentdiv.appendChild(image);
    image.src = src;
    contentdiv.contentEditable = true; // contentdiv.style.display = 'none';

    document.body.appendChild(contentdiv);
    var range = document.createRange();
    range.selectNodeContents(image);
    sel.removeAllRanges();
    sel.addRange(range);
    document.execCommand('copy'); // contentdiv.remove();
    //recover

    sel.removeAllRanges();

    for (var i = 0; i < sel.rangeCount; ++i) {
      sel.addRange(ranges[i]);
    }
  } else {
    console.error("Not support copy!"); //not support IE
  }
}

function fallbackCopyTextToClipboard(text) {
  return new Promise(function (resolve, reject) {
    var textArea = document.createElement("textarea");
    textArea.value = text; // Avoid scrolling to bottom

    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      var successful = document.execCommand('copy');

      if (successful) {
        resolve();
      } else {
        reject();
      }
    } catch (err) {
      reject(err);
    }

    document.body.removeChild(textArea);
  });
}

function copyText(text) {
  if (!navigator.clipboard) {
    return fallbackCopyTextToClipboard(text);
  }

  return navigator.clipboard.writeText(text);
}

function fallbackReadTextFromClipboard() {
  return new Promise(function (resolve, reject) {
    var textArea = document.createElement("textarea"); // Avoid scrolling to bottom

    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    document.body.appendChild(textArea);
    textArea.focus();

    try {
      var successful = document.execCommand('paste');

      if (successful) {
        resolve(textArea.value);
      } else {
        reject();
      }
    } catch (err) {
      reject(err);
    }

    document.body.removeChild(textArea);
  });
}

function pasteText() {
  if (navigator.clipboard) {
    return navigator.clipboard.readText();
  } else {
    return fallbackReadTextFromClipboard();
  }
}
// CONCATENATED MODULE: ./src/DataStructure/Heap.js
function defaultCmp(x, y) {
  if (x < y) {
    return -1;
  }

  if (x > y) {
    return 1;
  }

  return 0;
}
;
/**
 * 
 * @param {Array} arr 
 * @param {Number} pos 
 * @param {Function} cmp 
 */

function heapDown(arr, pos, cmp) {
  if (!cmp) cmp = defaultCmp;
  var item = arr[pos];
  var endPos = arr.length;
  var childPos = pos << 1 | 1;
  var childRightPos;

  while (childPos < endPos) {
    childRightPos = childPos + 1;

    if (childPos + 1 < endPos && cmp(arr[childPos], arr[childRightPos]) > 0) {
      childPos = childRightPos;
    }

    if (cmp(arr[childPos], item) < 0) {
      arr[pos] = arr[childPos];
      arr[childPos] = item;
      pos = childPos;
      childPos = pos << 1 | 1;
    } else break;
  }
}
/**
 * 
 * @param {Array} arr 
 * @param {Number} pos 
 * @param {Function} cmp 
 */

function heapUp(arr, pos, cmp) {
  if (!cmp) cmp = defaultCmp;
  var item = arr[pos];
  var parPos;

  while (pos > 0) {
    parPos = pos - 1 >> 1;

    if (cmp(arr[parPos], item) > 0) {
      arr[pos] = arr[parPos];
      arr[parPos] = item;
      pos = parPos;
    } else break;
  }
}
/**
 *
 * @param {Array} arr
 * @param {Function} cmp
 */

function heapify(arr, cmp) {
  if (!cmp) cmp = defaultCmp;
  var endPos = arr.length;

  for (var i = 0; i < endPos; ++i) {
    heapUp(arr, i, cmp);
  }
}
/**
 * 
 * @param {Array} arr 
 * @param {Function} cmp 
 */

function heapPop(arr, cmp) {
  if (!cmp) cmp = defaultCmp;
  var item = arr[0];
  var lastItem = arr.pop();

  if (arr.length > 0) {
    arr[0] = lastItem;
    heapDown(arr, 0, cmp);
  }

  return item;
}
/**
 * 
 * @param {Array} arr 
 * @param {*} item
 * @param {Function} cmp 
 */

function heapPush(arr, item, cmp) {
  if (!cmp) cmp = defaultCmp;
  arr.push(item);
  heapUp(arr, arr.length - 1, cmp);
}

function Heap(cmd) {
  this.cmp = cmd || defaultCmp;
  this.arr = [];
}
/**
 * @param {Array} arr
 * @param {Function} cmp
 * @returns {Heap}
 */


Heap.fromArray = function (arr, cmp) {
  var heap = new Heap(cmp);
  heapify(arr);
  heap.arr = arr;
  return heap;
};

Heap.prototype.push = function (x) {
  heapPush(this.arr, x, this.cmp);
  return this;
};

Heap.prototype.pop = function () {
  return heapPop(this.arr, this.cmp);
};

Heap.prototype.peek = function () {
  return this.arr[0];
};

Heap.prototype.contains = function (x) {
  return this.arr.indexOf(x) !== -1;
};

Heap.prototype.clear = function () {
  this.arr.splice(0, this.arr.length);
  return this;
};

Heap.prototype.empty = function () {
  return this.arr.length === 0;
};

Heap.prototype.size = function () {
  return this.arr.length;
};

Heap.prototype.clone = function () {
  var heap;
  heap = new Heap(this.cmp);
  heap.arr = this.arr.slice(0);
  return heap;
};

Heap.prototype.toArray = function () {
  return this.arr.slice(0);
};

Heap.prototype.toSortedArray = function () {
  var res = [];
  var heap = this.clone();

  while (!heap.empty()) {
    res.push(heap.pop());
  }

  return res;
};

Heap.prototype.insert = Heap.prototype.push;
Heap.prototype.top = Heap.prototype.peek;
Heap.prototype.front = Heap.prototype.peek;
Heap.prototype.has = Heap.prototype.contains;
Heap.prototype.copy = Heap.prototype.clone;
/* harmony default export */ var DataStructure_Heap = (Heap);
// CONCATENATED MODULE: ./src/Time/datetime.js


var MILLIS_PER_DAY = 24 * 3600000;
var MILLIS_PER_HOUR = 3600000;
var MILLIS_PER_MINUTE = 60000;
var _default_first_day_of_week = 1;
function getDefaultFirstDayOfWeek() {
  return _default_first_day_of_week;
}
function setDefaultFirstDayOfWeek(value) {
  if (isNaN(value) || !isFinite(value)) return;
  value = Math.floor(value) % 7;
  _default_first_day_of_week = value;
}
/**
 *
 * @param {Date} date
 * @returns {String}
 */

function ddmmyyyy(date) {
  return formatDateTime(date, 'dd/MM/yyyy');
}
var language2LocalDateFormat = {
  "af-ZA": "yyyy/mm/dd",
  "am-ET": "d/m/yyyy",
  "ar-AE": "dd/mm/yyyy",
  "ar-BH": "dd/mm/yyyy",
  "ar-DZ": "dd-mm-yyyy",
  "ar-EG": "dd/mm/yyyy",
  "ar-IQ": "dd/mm/yyyy",
  "ar-JO": "dd/mm/yyyy",
  "ar-KW": "dd/mm/yyyy",
  "ar-LB": "dd/mm/yyyy",
  "ar-LY": "dd/mm/yyyy",
  "ar-MA": "dd-mm-yyyy",
  "ar-OM": "dd/mm/yyyy",
  "ar-QA": "dd/mm/yyyy",
  "ar-SA": "dd/mm/yy",
  "ar-SY": "dd/mm/yyyy",
  "ar-TN": "dd-mm-yyyy",
  "ar-YE": "dd/mm/yyyy",
  "arn-CL": "dd-mm-yyyy",
  "as-IN": "dd-mm-yyyy",
  "az-Cyrl-AZ": "dd.mm.yyyy",
  "az-Latn-AZ": "dd.mm.yyyy",
  "ba-RU": "dd.mm.yy",
  "be-BY": "dd.mm.yyyy",
  "bg-BG": "dd.m.yyyy",
  "bn-BD": "dd-mm-yy",
  "bn-IN": "dd-mm-yy",
  "bo-CN": "yyyy/m/d",
  "br-FR": "dd/mm/yyyy",
  "bs-Cyrl-BA": "d.m.yyyy",
  "bs-Latn-BA": "d.m.yyyy",
  "ca-ES": "dd/mm/yyyy",
  "co-FR": "dd/mm/yyyy",
  "cs-CZ": "d.m.yyyy",
  "cy-GB": "dd/mm/yyyy",
  "da-DK": "dd-mm-yyyy",
  "de-AT": "dd.mm.yyyy",
  "de-CH": "dd.mm.yyyy",
  "de-DE": "dd.mm.yyyy",
  "de-LI": "dd.mm.yyyy",
  "de-LU": "dd.mm.yyyy",
  "dsb-DE": "d. m. yyyy",
  "dv-MV": "dd/mm/yy",
  "el-GR": "d/m/yyyy",
  "en-029": "mm/dd/yyyy",
  "en-AU": "d/mm/yyyy",
  "en-BZ": "dd/mm/yyyy",
  "en-CA": "dd/mm/yyyy",
  "en-GB": "dd/mm/yyyy",
  "en-IE": "dd/mm/yyyy",
  "en-IN": "dd-mm-yyyy",
  "en-JM": "dd/mm/yyyy",
  "en-MY": "d/m/yyyy",
  "en-NZ": "d/mm/yyyy",
  "en-PH": "m/d/yyyy",
  "en-SG": "d/m/yyyy",
  "en-TT": "dd/mm/yyyy",
  "en-US": "m/d/yyyy",
  "en-ZA": "yyyy/mm/dd",
  "en-ZW": "m/d/yyyy",
  "es-AR": "dd/mm/yyyy",
  "es-BO": "dd/mm/yyyy",
  "es-CL": "dd-mm-yyyy",
  "es-CO": "dd/mm/yyyy",
  "es-CR": "dd/mm/yyyy",
  "es-DO": "dd/mm/yyyy",
  "es-EC": "dd/mm/yyyy",
  "es-ES": "dd/mm/yyyy",
  "es-GT": "dd/mm/yyyy",
  "es-HN": "dd/mm/yyyy",
  "es-MX": "dd/mm/yyyy",
  "es-NI": "dd/mm/yyyy",
  "es-PA": "mm/dd/yyyy",
  "es-PE": "dd/mm/yyyy",
  "es-PR": "dd/mm/yyyy",
  "es-PY": "dd/mm/yyyy",
  "es-SV": "dd/mm/yyyy",
  "es-US": "m/d/yyyy",
  "es-UY": "dd/mm/yyyy",
  "es-VE": "dd/mm/yyyy",
  "et-EE": "d.mm.yyyy",
  "eu-ES": "yyyy/mm/dd",
  "fa-IR": "mm/dd/yyyy",
  "fi-FI": "d.m.yyyy",
  "fil-PH": "m/d/yyyy",
  "fo-FO": "dd-mm-yyyy",
  "fr-BE": "d/mm/yyyy",
  "fr-CA": "yyyy-mm-dd",
  "fr-CH": "dd.mm.yyyy",
  "fr-FR": "dd/mm/yyyy",
  "fr-LU": "dd/mm/yyyy",
  "fr-MC": "dd/mm/yyyy",
  "fy-NL": "d-m-yyyy",
  "ga-IE": "dd/mm/yyyy",
  "gd-GB": "dd/mm/yyyy",
  "gl-ES": "dd/mm/yy",
  "gsw-FR": "dd/mm/yyyy",
  "gu-IN": "dd-mm-yy",
  "ha-Latn-NG": "d/m/yyyy",
  "he-IL": "dd/mm/yyyy",
  "hi-IN": "dd-mm-yyyy",
  "hr-BA": "d.m.yyyy.",
  "hr-HR": "d.m.yyyy",
  "hsb-DE": "d. m. yyyy",
  "hu-HU": "yyyy. mm. dd.",
  "hy-AM": "dd.mm.yyyy",
  "id-ID": "dd/mm/yyyy",
  "ig-NG": "d/m/yyyy",
  "ii-CN": "yyyy/m/d",
  "is-IS": "d.m.yyyy",
  "it-CH": "dd.mm.yyyy",
  "it-IT": "dd/mm/yyyy",
  "iu-Cans-CA": "d/m/yyyy",
  "iu-Latn-CA": "d/mm/yyyy",
  "ja-JP": "yyyy/mm/dd",
  "ka-GE": "dd.mm.yyyy",
  "kk-KZ": "dd.mm.yyyy",
  "kl-GL": "dd-mm-yyyy",
  "km-KH": "yyyy-mm-dd",
  "kn-IN": "dd-mm-yy",
  "ko-KR": "yyyy-mm-dd",
  "kok-IN": "dd-mm-yyyy",
  "ky-KG": "dd.mm.yy",
  "lb-LU": "dd/mm/yyyy",
  "lo-LA": "dd/mm/yyyy",
  "lt-LT": "yyyy.mm.dd",
  "lv-LV": "yyyy.mm.dd.",
  "mi-NZ": "dd/mm/yyyy",
  "mk-MK": "dd.mm.yyyy",
  "ml-IN": "dd-mm-yy",
  "mn-MN": "yy.mm.dd",
  "mn-Mong-CN": "yyyy/m/d",
  "moh-CA": "m/d/yyyy",
  "mr-IN": "dd-mm-yyyy",
  "ms-BN": "dd/mm/yyyy",
  "ms-MY": "dd/mm/yyyy",
  "mt-MT": "dd/mm/yyyy",
  "nb-NO": "dd.mm.yyyy",
  "ne-NP": "m/d/yyyy",
  "nl-BE": "d/mm/yyyy",
  "nl-NL": "d-m-yyyy",
  "nn-NO": "dd.mm.yyyy",
  "nso-ZA": "yyyy/mm/dd",
  "oc-FR": "dd/mm/yyyy",
  "or-IN": "dd-mm-yy",
  "pa-IN": "dd-mm-yy",
  "pl-PL": "yyyy-mm-dd",
  "prs-AF": "dd/mm/yy",
  "ps-AF": "dd/mm/yy",
  "pt-BR": "d/m/yyyy",
  "pt-PT": "dd-mm-yyyy",
  "qut-GT": "dd/mm/yyyy",
  "quz-BO": "dd/mm/yyyy",
  "quz-EC": "dd/mm/yyyy",
  "quz-PE": "dd/mm/yyyy",
  "rm-CH": "dd/mm/yyyy",
  "ro-RO": "dd.mm.yyyy",
  "ru-RU": "dd.mm.yyyy",
  "rw-RW": "m/d/yyyy",
  "sa-IN": "dd-mm-yyyy",
  "sah-RU": "mm.dd.yyyy",
  "se-FI": "d.m.yyyy",
  "se-NO": "dd.mm.yyyy",
  "se-SE": "yyyy-mm-dd",
  "si-LK": "yyyy-mm-dd",
  "sk-SK": "d. m. yyyy",
  "sl-SI": "d.m.yyyy",
  "sma-NO": "dd.mm.yyyy",
  "sma-SE": "yyyy-mm-dd",
  "smj-NO": "dd.mm.yyyy",
  "smj-SE": "yyyy-mm-dd",
  "smn-FI": "d.m.yyyy",
  "sms-FI": "d.m.yyyy",
  "sq-AL": "yyyy-mm-dd",
  "sr-Cyrl-BA": "d.m.yyyy",
  "sr-Cyrl-CS": "d.m.yyyy",
  "sr-Cyrl-ME": "d.m.yyyy",
  "sr-Cyrl-RS": "d.m.yyyy",
  "sr-Latn-BA": "d.m.yyyy",
  "sr-Latn-CS": "d.m.yyyy",
  "sr-Latn-ME": "d.m.yyyy",
  "sr-Latn-RS": "d.m.yyyy",
  "sv-FI": "d.m.yyyy",
  "sv-SE": "yyyy-mm-dd",
  "sw-KE": "m/d/yyyy",
  "syr-SY": "dd/mm/yyyy",
  "ta-IN": "dd-mm-yyyy",
  "te-IN": "dd-mm-yy",
  "tg-Cyrl-TJ": "dd.mm.yy",
  "th-TH": "d/m/yyyy",
  "tk-TM": "dd.mm.yy",
  "tn-ZA": "yyyy/mm/dd",
  "tr-TR": "dd.mm.yyyy",
  "tt-RU": "dd.mm.yyyy",
  "tzm-Latn-DZ": "dd-mm-yyyy",
  "ug-CN": "yyyy-m-d",
  "uk-UA": "dd.mm.yyyy",
  "ur-PK": "dd/mm/yyyy",
  "uz-Cyrl-UZ": "dd.mm.yyyy",
  "uz-Latn-UZ": "dd/mm yyyy",
  "vi-VN": "dd/mm/yyyy",
  "wo-SN": "dd/mm/yyyy",
  "xh-ZA": "yyyy/mm/dd",
  "yo-NG": "d/m/yyyy",
  "zh-CN": "yyyy/m/d",
  "zh-HK": "d/m/yyyy",
  "zh-MO": "d/m/yyyy",
  "zh-SG": "d/m/yyyy",
  "zh-TW": "yyyy/m/d",
  "zu-ZA": "yyyy/mm/dd"
};
var dateFormat2LocationList = Object.keys(language2LocalDateFormat).reduce(function (ac, cr) {
  ac[language2LocalDateFormat[cr]] = ac[language2LocalDateFormat[cr]] || [];
  ac[language2LocalDateFormat[cr]].push(cr);
  return ac;
}, {});
var dateFormatList = Object.keys(dateFormat2LocationList);
/**
 *
 * @param {Date} date
 * @returns {String}
 */

function yyymmdd(date) {
  return formatDateTime(date, 'yyyy/MM/dd');
}
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var shortDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var shortMonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var formatTokenRegex = /([,.\-\/])|([a-zA-Z0-9]+)/g; //more

var DATE_TIME_TOKEN_RGX = /([^\s.\/:\-,]+)|([.\/:\-,]+)/i;
/**
 *
 * @param {Date} date
 * @param {String=} format
 * @returns {String}
 */

function formatDateString(date, format) {
  format = format || 'dd/mm/yyyy';
  var dt = date.getDate();
  var day = date.getDay();
  var month = date.getMonth();
  var year = date.getFullYear();
  return format.replace(formatTokenRegex, function (x) {
    switch (x) {
      case "dddd":
        return dayNames[day];

      case "ddd":
        return shortDayNames[day];

      case "dd":
        return dt < 10 ? '0' + dt : '' + dt;

      case "d":
        return '' + dt;

      case "mmmm":
        return monthNames[month];

      case "mmm":
        return shortMonthNames[month];

      case "mm":
        return month + 1 < 10 ? '0' + (month + 1) : '' + (month + 1);

      case "m":
        return '' + (month + 1);

      case 'yy':
        return (year + '').match(/..$/)[0];

      case 'yyyy':
        return year + '';

      default:
        return x;
    }
  });
}
var LOCAL_DATE_FORMAT = function () {
  var d = new Date(2021, 4, 4);
  var s = d.toLocaleDateString();
  var fm = s.replace(new RegExp(DATE_TIME_TOKEN_RGX.source, 'g'), function (token) {
    switch (token) {
      case '2021':
        return 'yyyy';

      case '5':
        return 'M';

      case '05':
        return 'MM';

      case '4':
        return 'd';

      case '04':
        return 'dd';

      default:
        return token;
    }
  });
  return fm;
}();
var LOCAL_DATE_TIME_FORMAT = function () {
  var d = new Date(2021, 4, 4, 6, 7, 3);
  var s = d.toLocaleString();
  var fm = s.replace(new RegExp(DATE_TIME_TOKEN_RGX.source, 'g'), function (token) {
    switch (token) {
      case '2021':
        return 'yyyy';

      case '5':
        return 'M';

      case '05':
        return 'MM';

      case '4':
        return 'd';

      case '04':
        return 'dd';

      case '06':
        if (new Date(2021, 4, 4, 18, 7, 3).toLocaleString().indexOf(18) >= 0) return 'HH';
        return 'hh';

      case '6':
        return 'h';

      case '07':
        return 'mm';

      case '7':
        return 'm';

      case '03':
        return 'ss';

      case '3':
        return 's';

      case 'AM':
        return 'a';

      default:
        return token;
    }
  });
  return fm;
}();
function formartDateString() {
  window.ALogger.warn("spelled incorrectly: formartDateString");
  return formatDateString.apply(null, arguments);
}
/**
 *
 * @param {String} text
 * @param {String} format
 * @returns {Date}
 */

function parseDateString(text, format) {
  text = nonAccentVietnamese(text).toLowerCase();
  format = nonAccentVietnamese(format).toLowerCase();
  var textTokens = text.match(formatTokenRegex) || [];
  var formatTokens = format.match(formatTokenRegex) || [];
  var year = new Date().getFullYear();
  var month = 0;
  var day = 1;
  var n = Math.min(textTokens.length, formatTokens.length);
  var textToken;
  var formatToken;

  for (var i = 0; i < n; ++i) {
    textToken = textTokens[i];
    formatToken = formatTokens[i];

    switch (formatToken) {
      case "dd":
        day = parseInt(textToken);
        break;

      case "d":
        day = parseInt(textToken);
        break;

      case "mmmm":
        month = monthNames.indexOf(textToken.substr(0, 1).toUpperCase() + textToken.substr(1).toLowerCase());
        break;

      case "mmm":
        month = shortMonthNames.indexOf(textToken.substr(0, 1).toUpperCase() + textToken.substr(1).toLowerCase());
        break;

      case "mm":
      case 'MM':
        month = parseInt(textToken) - 1;
        break;

      case "m":
      case 'M':
        month = parseInt(textToken) - 1;
        break;

      case 'yy':
        year = Math.floor(new Date().getFullYear() / 100) * 100 + parseInt(textToken);
        break;

      case 'yyyy':
        year = parseInt(textToken);
        break;

      default:
        if (textToken !== formatToken) throw new Error('Unexpected token ' + textToken);
    }
  }

  if (isNaN(year)) throw new Error('Invalid year');

  if (isNaN(month) && month !== -1) {
    throw new Error('Invalid month');
  } else {
    month = Math.max(0, Math.min(11, month));
  }

  if (!isNaN(day)) {
    day = Math.max(1, Math.min(31, day));

    if (!isNaN(month)) {
      day = Math.min(daysInMonth(2000, month), day);
      if (!isNaN(year)) day = Math.min(daysInMonth(year, month), day);
    }
  } else {
    throw new Error('Invalid day');
  }

  return new Date(year, month, day);
}
/***
 *
 * @param date
 * @param {number} delta - must be a integer
 * @param {boolean=} gmt
 * @returns {Date}
 */

function addDate(date, delta, gmt) {
  delta = Math.round(delta);
  var res = beginOfDay(date, gmt);

  if (gmt) {
    res.setUTCDate(date.getUTCDate() + delta);
  } else {
    res.setDate(date.getDate() + delta);
  }

  return beginOfDay(res, gmt);
}
/**
 * @param {Date} date
 * @param {boolean=} gmt
 * @return {Date}
 */

function prevDate(date, gmt) {
  return addDate(date, -1, gmt);
}
/**
 * @param {Date} date
 * @param {boolean=} gmt
 * @return {Date}
 */

function nextDate(date, gmt) {
  return addDate(date, 1, gmt);
}
/****
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @param {number=} startDayOfWeek
 * @returns {number}
 */

function weekIndexOf(date, gmt, startDayOfWeek) {
  if (typeof startDayOfWeek !== "number") startDayOfWeek = getDefaultFirstDayOfWeek();
  var by = beginOfYear(date, gmt);
  var byw = beginOfWeek(by, gmt, startDayOfWeek);
  var bw = beginOfWeek(date, gmt, startDayOfWeek);

  if (compareYear(by, bw) > 0) {
    return weekIndexOf(bw, gmt, startDayOfWeek);
  }

  var i = compareYear(byw, by) < 0 ? -1 : 0;
  return Math.floor(compareDate(date, byw, gmt) / 7) + i;
}
/***
 *
 * @param {number} year
 * @param {number} weekIdx
 * @param {boolean=} gmt
 * @param {number=} startDayOfWeek
 * @returns {Date}
 */

function weekInYear(year, weekIdx, gmt, startDayOfWeek) {
  if (typeof startDayOfWeek !== "number") startDayOfWeek = getDefaultFirstDayOfWeek();
  var bg = new Date(year, 0, 1);
  if (gmt) bg.setUTCHours(0);
  var byw = beginOfWeek(bg, gmt, startDayOfWeek);
  var d = compareYear(bg, byw) > 0 ? MILLIS_PER_DAY * 7 : 0;
  return new Date(byw.getTime() + d + weekIdx * 7 * MILLIS_PER_DAY);
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at xx:xx:xx:00
 */

function beginOfSecond(date, gmt) {
  var res = new Date(date.getTime());
  if (gmt) res.setUTCMilliseconds(0);else res.setMilliseconds(0);
  return res;
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at xx:xx:00
 */

function beginOfMinute(date, gmt) {
  var res = new Date(date.getTime());
  if (gmt) res.setUTCSeconds(0, 0);else res.setSeconds(0, 0);
  return res;
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00
 */

function beginOfDay(date, gmt) {
  var res = new Date(date.getTime());
  if (gmt) res.setUTCHours(0, 0, 0, 0);else res.setHours(0, 0, 0, 0);
  return res;
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at xx:00
 */

function beginOfHour(date, gmt) {
  var res = new Date(date.getTime());
  if (gmt) res.setUTCMinutes(0, 0, 0);else res.setMinutes(0, 0, 0);
  return res;
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @param {number=} startDayOfWeek default:0
 * @return {Date} date at 00:00
 */

function beginOfWeek(date, gmt, startDayOfWeek) {
  if (typeof startDayOfWeek !== "number") startDayOfWeek = getDefaultFirstDayOfWeek();
  var res = beginOfDay(date, gmt);

  while ((gmt ? res.getUTCDay() : res.getDay()) !== startDayOfWeek) {
    res = prevDate(res, gmt);
  }

  return res;
}
/***
 *
 * @param {Date} date
 * @param {number} delta
 * @param {boolean=} gmt
 */

function addWeek(date, delta, gmt) {
  date = beginOfWeek(date, gmt);
  delta = Math.round(delta);
  return addDate(date, delta * 7, gmt);
}
/****
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @returns {Date}
 */

function nextWeek(date, gmt) {
  return addWeek(date, 1, gmt);
}
/****
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @returns {Date}
 */

function prevWeek(date, gmt) {
  return addWeek(date, -1, gmt);
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00 AM
 */

function beginOfMonth(date, gmt) {
  var m = gmt ? date.getUTCMonth() : date.getMonth();
  var y = gmt ? date.getUTCFullYear() : date.getFullYear();
  var res = new Date();
  if (gmt) res.setUTCFullYear(y, m, 1);else res.setFullYear(y, m, 1);
  return beginOfDay(res, gmt);
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00 AM
 */

function beginOfQuarter(date, gmt) {
  var y = gmt ? date.getUTCFullYear() : date.getFullYear();
  var m = gmt ? date.getUTCMonth() : date.getMonth();
  m = Math.floor(m / 3) * 3;
  var res = new Date();
  if (gmt) res.setUTCFullYear(y, m, 1);else res.setFullYear(y, m, 1);
  return beginOfDay(res, gmt);
}
/***
 *
 * @param {Date} date
 * @param {number=} delta
 * @param {boolean=} gmt
 */

function addQuarter(date, delta, gmt) {
  delta = Math.round(delta);
  date = beginOfQuarter(date, gmt);
  return addMonth(date, delta * 3, gmt);
}
/***
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @returns {Date}
 */

function nextQuarter(date, gmt) {
  date = beginOfQuarter(date);
  return nextMonth(nextMonth(nextMonth(date, gmt), gmt), gmt);
}
/***
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @returns {Date}
 */

function prevQuarter(date, gmt) {
  date = beginOfQuarter(date, gmt);
  return prevMonth(prevMonth(prevMonth(date, gmt), gmt), gmt);
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00 AM
 */

function beginOfYear(date, gmt) {
  var y = gmt ? date.getUTCFullYear() : date.getFullYear();
  var res = new Date();
  if (gmt) res.setUTCFullYear(y, 0, 1);else res.setFullYear(y, 0, 1);
  return beginOfDay(res, gmt);
}
/**
 * @param {Date} date
 * @param {number} delta
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00 AM
 */

function addYear(date, delta, gmt) {
  delta = Math.round(delta);
  var y = gmt ? date.getUTCFullYear() : date.getFullYear();
  var res = new Date();
  if (gmt) res.setUTCFullYear(y + delta, 0, 1);else res.setFullYear(y + delta, 0, 1);
  return beginOfDay(res, gmt);
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00 AM
 */

function nextYear(date, gmt) {
  return addYear(date, 1, gmt);
}
/**
 * @param {Date} date
 * @param {Boolean=} gmt default:false
 * @return {Date} date at 00:00 AM
 */

function prevYear(date, gmt) {
  return addYear(date, -1, gmt);
}
/**
 * @param {Date} date0
 * @param {Date} date1
 * @param {Boolean=} gmt default:false
 * @return {number}
 */

function compareDate(date0, date1, gmt) {
  date0 = beginOfDay(date0, gmt);
  date1 = beginOfDay(date1, gmt); //Date(1975, 5, 12) has 1 hour extend

  return Math.floor((date0.getTime() - date1.getTime()) / 86400000);
}
/**
 * @param {Date} date0
 * @param {Date} date1
 * @param {Boolean=} gmt default:false
 * @return {number}
 */

function compareMonth(date0, date1, gmt) {
  var m0 = gmt ? date0.getUTCMonth() : date0.getMonth();
  var y0 = gmt ? date0.getUTCFullYear() : date0.getFullYear();
  var m1 = gmt ? date1.getUTCMonth() : date1.getMonth();
  var y1 = gmt ? date1.getUTCFullYear() : date1.getFullYear();
  return (y0 - y1) * 12 + (m0 - m1);
}
/***
 *
 * @param {Date} date0
 * @param {Date} date1
 * @param {boolean=}gmt
 * @returns {number}
 */

function compareYear(date0, date1, gmt) {
  var y0 = gmt ? date0.getUTCFullYear() : date0.getFullYear();
  var y1 = gmt ? date1.getUTCFullYear() : date1.getFullYear();
  return y0 - y1;
}
/**
 *
 * @param {Date} date
 * @param {number} delta
 * @param {boolean=} gmt
 * @returns {Date}
 */

function addMonth(date, delta, gmt) {
  var res = beginOfMonth(date, gmt);

  if (gmt) {
    res.setUTCMonth(res.getUTCMonth() + delta);
  } else {
    res.setMonth(res.getMonth() + delta);
  }

  return beginOfDay(res, gmt);
}
/**
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @returns {Date}
 */

function nextMonth(date, gmt) {
  return addMonth(date, 1, gmt);
}
/**
 *
 * @param {Date} date
 * @param {boolean=} gmt
 * @returns {Date}
 */

function prevMonth(date, gmt) {
  return addMonth(date, -1, gmt);
}
/**
 *
 * @param {Number} year
 * @param {Number} month
 * @returns {Number}
 */

function daysInMonth(year, month) {
  var start = new Date(year, month, 1);
  var end = nextMonth(start);
  return compareDate(end, start);
}
/****
 *
 * @param text
 * @param format support d, M, Y, Q
 * @param {*=} opt
 * @returns {Date}
 */

function parseDateTime(text, format, opt) {
  opt = Object.assign({
    startDayOfWeek: 0
  }, opt);
  var tokenMap = {};
  var txtRgx = new RegExp(DATE_TIME_TOKEN_RGX.source, 'g');
  var fmRgx = new RegExp(DATE_TIME_TOKEN_RGX.source, 'g');
  var tkMatched, fmMatched;
  tkMatched = txtRgx.exec(text);
  fmMatched = fmRgx.exec(format);
  var tkText, fmText;

  while (tkMatched && fmMatched) {
    tkText = tkMatched[0];
    fmText = fmMatched[0];

    switch (fmText) {
      case 'd':
      case 'dd':
        tokenMap.day = parseInt(tkText, 10);
        break;

      case 'w':
      case 'ww':
        tokenMap.week = parseInt(tkText, 10) - 1;
        break;

      case 'M':
      case 'MM':
        tokenMap.month = parseInt(tkText, 10) - 1;
        break;

      case 'y':
      case 'yyyy':
        tokenMap.year = parseInt(tkText, 10);
        break;

      case 'h':
      case 'hh':
      case 'H':
      case 'HH':
        tokenMap.hour = parseInt(tkText, 10);
        break;

      case 'm':
      case 'mm':
        tokenMap.minute = parseInt(tkText, 10);
        break;

      case 'a':
        if (tkText === 'AM' || tkText === 'PM') tokenMap.period = tkText;else throw new Error('Invalid period(a):' + tkText);
        break;

      case 'Q':
      case 'QQ':
        tokenMap.month = (parseInt(tkText, 10) - 1) * 3;
        break;

      default:
        if (tkText !== fmText) {
          throw new Error('Unexpected token ' + JSON.stringify(tkText) + ' at ' + tkMatched.index + ', expected ' + fmText);
        }

    }

    tkMatched = txtRgx.exec(text);
    fmMatched = fmRgx.exec(format);
  }

  if (tokenMap.period) {
    if (tokenMap.period === 'AM' && tokenMap.hour === 12) tokenMap.hour = 0;else if (tokenMap.period === "PM" && tokenMap.hour < 12) tokenMap.hour += 12;
  }

  var paramNames = ['year', 'month', 'day', 'hour', 'minute', 'second'];
  var paramShortNames = ['y', 'M', 'd', 'h', 'm', 's'];
  var paramDefaultValues = [new Date().getFullYear(), 0, 1, 0, 0, 0];
  var resParam = paramDefaultValues.slice();
  var paramList = paramNames.reduce(function (ac, cr, i) {
    var sN = paramShortNames[i];

    if (cr in tokenMap) {
      ac += sN;
    }

    return ac;
  }, '');
  var paramName;

  for (var i = 0; i < paramNames.length; ++i) {
    paramName = paramNames[i];
    resParam[i] = tokenMap[paramName] === undefined ? paramDefaultValues[i] : tokenMap[paramName];
  }

  var weekDate;

  if ('week' in tokenMap && !isNaN(tokenMap.week)) {
    weekDate = weekInYear(resParam[0], tokenMap.week, false, opt.startDayOfWeek);
    resParam[1] = weekDate.getMonth();
    resParam[2] = weekDate.getDate();
  }

  switch (paramList) {
    case 'hm':
      resParam.splice(1, 2, new Date().getMonth(), new Date().getDate());
      break;
  }

  return new Date(resParam[0], resParam[1], resParam[2], resParam[3], resParam[4], resParam[5]);
}
/***
 *
 * @param {Date} date
 * @param {string} format
 * @param {*=} opt
 * @return {string}
 */

function formatDateTime(date, format, opt) {
  opt = Object.assign({
    startDayOfWeek: 0
  }, opt);
  var fmRgx = new RegExp(DATE_TIME_TOKEN_RGX.source, 'g');
  return format.replace(fmRgx, function (s) {
    var res = s;

    switch (s) {
      case 'd':
      case 'dd':
        res = integerZeroPadding(date.getDate(), s.length);
        break;

      case 'w':
      case 'ww':
        res = integerZeroPadding(weekIndexOf(date, false, opt.startDayOfWeek || 0) + 1, s.length);
        break;

      case 'M':
      case 'MM':
        res = integerZeroPadding(date.getMonth() + 1, s.length);
        break;

      case 'MMM':
        res = shortMonthNames[date.getMonth()];
        break;

      case 'MMMM':
        res = monthNames[date.getMonth()];
        break;

      case 'y':
      case 'yyyy':
        res = integerZeroPadding(date.getFullYear(), s.length);
        break;

      case 'yy':
        res = integerZeroPadding(date.getFullYear() % 100, s.length);
        break;

      case 'a':
        res = date.getHours() < 12 ? "AM" : "PM";
        break;

      case "H":
      case 'HH':
        res = integerZeroPadding(date.getHours(), s.length);
        break;

      case 'h':
      case 'hh':
        res = integerZeroPadding(1 + (date.getHours() - 1) % 12, s.length);
        break;

      case 'm':
      case 'mm':
        res = integerZeroPadding(date.getMinutes(), s.length);
        break;

      case 'Q':
      case 'QQ':
        res = integerZeroPadding(Math.floor(date.getMonth() / 3) + 1, s.length);
        break;
    }

    return res;
  });
}
var number = [/[+-]?\d+$/, function (matched) {
  return new Date(parseInt(matched[0]));
}];
var reISO = [/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/, function (matched) {
  return new Date(matched[0]);
}];
var reMsAjax = [/^\/Date\((d|-|.*)\)[\/|\\]$/, function (matched) {
  return new Date(parseInt(matched[1]));
}];
var reString = [/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+([a-zA-Z]{3})\s+[\d\s:]+GMT[\d+]+\s*\([^)]+\)$/, function (matched) {
  return new Date(matched[0]);
}];
function implicitDate(o) {
  var res = null;

  if (o instanceof Date) {
    res = new Date(o.getTime());
  } else if (typeof o === "number") {
    res = new Date(o);
  } else if (typeof o === 'string') {
    [reString, reISO, reMsAjax, number].some(function (rule) {
      var matched = o.match(rule[0]);

      if (matched) {
        res = rule[1](matched);
        return true;
      }

      return false;
    });
  }

  if (res && isNaN(res.getTime())) res = null;
  return res;
}
// CONCATENATED MODULE: ./src/AppPattern/CMDRunner.js
function CMDRunner(_this, commands) {
  this._this = _this;
  this.commands = {};
  this.assign(commands);
}

CMDRunner.prototype.has = function (cmdName) {
  return !!this.commands[cmdName];
};

CMDRunner.prototype.add = function (cmdName, handler) {
  this.commands[cmdName] = handler;
  return this;
};

CMDRunner.prototype.remove = function (cmdName) {
  delete this.commands[cmdName];
  return this;
};

CMDRunner.prototype.assign = function (obj) {
  for (var cmdName in obj) {
    if (typeof obj[cmdName] == 'function') {
      this.add(cmdName, obj[cmdName]);
    }
  }
};

CMDRunner.prototype.invoke = function () {
  if (this.commands[arguments[0]]) {
    var args = Array.prototype.slice.call(arguments, 1);
    return this.commands[arguments[0]].apply(this._this, args);
  } else {
    throw new Error('No command: ' + arguments[0]);
  }
};

/* harmony default export */ var AppPattern_CMDRunner = (CMDRunner);
// EXTERNAL MODULE: ./src/HTML5/AElement.js
var AElement = __webpack_require__(1);

// CONCATENATED MODULE: ./src/HTML5/Element.js

/* harmony default export */ var Element = (AElement["a" /* default */]);
// EXTERNAL MODULE: ./src/HTML5/AElementNS.js
var AElementNS = __webpack_require__(11);

// EXTERNAL MODULE: ./src/HTML5/DomSignal.js
var DomSignal = __webpack_require__(19);

// CONCATENATED MODULE: ./src/Cookie/CookieStore.js


function CookieStore(converter) {
  this.converter = converter || UnicodeBase64Converter;
}

CookieStore.prototype.isEnabled = function () {
  var cookieEnabled = !!navigator.cookieEnabled; //if not IE4+ nor NS6+

  if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
    document.cookie = "testcookie_enabled";
    cookieEnabled = document.cookie.indexOf("testcookie_enabled") != -1;
  }

  return cookieEnabled;
};

CookieStore.prototype.secure = function () {
  document.cookie = "secure";
};

CookieStore.prototype.get = function (key) {
  var bkey = this.converter.encode(key).replace(/=/g, '_');
  var pairs = document.cookie.split(';').map(function (text) {
    return text.split('=');
  }).filter(function (pair) {
    return pair[0].trim() == bkey;
  });

  if (pairs.length > 0) {
    if (pairs[0].length > 1) {
      var bvalue = pairs[0][1];
      return this.converter.decode(bvalue.replace(/_/g, '=').trim());
    } else {
      return true;
    }
  } else return undefined;
};

CookieStore.prototype.set = function (key, value) {
  var bkey = this.converter.encode(key);
  var bvalue = this.converter.encode(value);
  document.cookie = bkey.replace(/=/g, '_') + "=" + bvalue.replace(/=/g, '_');
};

/* harmony default export */ var Cookie_CookieStore = (new CookieStore());
// CONCATENATED MODULE: ./src/Cookie/parseCookieString.js
/***
 *
 * @param {string} text
 * @return {{}}
 */
function parseCookieString(text) {
  return text.split(/\s*;\s*/).reduce(function (ac, item) {
    var tokens = item.split('=');
    var name = (tokens.shift() || '').trim();
    if (!name) return ac;
    var value = (tokens.shift() || '').trim();
    if (!value) value = true;
    ac[name] = value;
    return ac;
  }, {});
}
// EXTERNAL MODULE: ./src/HTML5/ResizeSystem.js
var ResizeSystem = __webpack_require__(12);

// CONCATENATED MODULE: ./src/Math/Mat3.js


function Mat3(data) {
  this.data = data || Array(6).fill(0);
}

Mat3.identity = function () {
  return new Mat3([1, 0, 0, 0, 1, 0, 0, 0, 1]);
};
/**
 *
 * @returns {Mat3|null}
 */


Mat3.prototype.invert = function () {
  var a = this.data;
  var out = Array(9);
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2];
  var a10 = a[3],
      a11 = a[4],
      a12 = a[5];
  var a20 = a[6],
      a21 = a[7],
      a22 = a[8];
  var b01 = a22 * a11 - a12 * a21;
  var b11 = -a22 * a10 + a12 * a20;
  var b21 = a21 * a10 - a11 * a20; // Calculate the determinant

  var det = a00 * b01 + a01 * b11 + a02 * b21;
  if (!det) return null;
  det = 1.0 / det;
  out[0] = b01 * det;
  out[1] = (-a22 * a01 + a02 * a21) * det;
  out[2] = (a12 * a01 - a02 * a11) * det;
  out[3] = b11 * det;
  out[4] = (a22 * a00 - a02 * a20) * det;
  out[5] = (-a12 * a00 + a02 * a10) * det;
  out[6] = b21 * det;
  out[7] = (-a21 * a00 + a01 * a20) * det;
  out[8] = (a11 * a00 - a01 * a10) * det;
  return new Mat3(out);
};
/**
 *
 * @param {Vec2} v
 * @return {Mat3}
 */


Mat3.prototype.translate = function (v) {
  var out = Array(9);
  var a = this.data;
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2];
  var a10 = a[3],
      a11 = a[4],
      a12 = a[5];
  var a20 = a[6],
      a21 = a[7],
      a22 = a[8];
  var x = v.x,
      y = v.y;
  out[0] = a00;
  out[1] = a01;
  out[2] = a02;
  out[3] = a10;
  out[4] = a11;
  out[5] = a12;
  out[6] = x * a00 + y * a10 + a20;
  out[7] = x * a01 + y * a11 + a21;
  out[8] = x * a02 + y * a12 + a22;
  return new Mat3(out);
};
/**
 *
 * @param {Mat3} mat
 * @returns {Mat3}
 */


Mat3.prototype.multiply = function (mat) {
  var a = this.data;
  var b = mat.data;
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2];
  var a10 = a[3],
      a11 = a[4],
      a12 = a[5];
  var a20 = a[6],
      a21 = a[7],
      a22 = a[8];
  var b00 = b[0],
      b01 = b[1],
      b02 = b[2];
  var b10 = b[3],
      b11 = b[4],
      b12 = b[5];
  var b20 = b[6],
      b21 = b[7],
      b22 = b[8];
  var out = Array(9);
  out[0] = b00 * a00 + b01 * a10 + b02 * a20;
  out[1] = b00 * a01 + b01 * a11 + b02 * a21;
  out[2] = b00 * a02 + b01 * a12 + b02 * a22;
  out[3] = b10 * a00 + b11 * a10 + b12 * a20;
  out[4] = b10 * a01 + b11 * a11 + b12 * a21;
  out[5] = b10 * a02 + b11 * a12 + b12 * a22;
  out[6] = b20 * a00 + b21 * a10 + b22 * a20;
  out[7] = b20 * a01 + b21 * a11 + b22 * a21;
  out[8] = b20 * a02 + b21 * a12 + b22 * a22;
  return new Mat3(out);
};
/***
 *
 * @param {Number} rad
 * @return {Mat3}
 */


Mat3.prototype.rotate = function (rad) {
  var a = this.data;
  var a00 = a[0],
      a01 = a[1],
      a02 = a[2];
  var a10 = a[3],
      a11 = a[4],
      a12 = a[5];
  var a20 = a[6],
      a21 = a[7],
      a22 = a[8];
  var s = Math.sin(rad);
  var c = Math.cos(rad);
  var out = Array(9);
  out[0] = c * a00 + s * a10;
  out[1] = c * a01 + s * a11;
  out[2] = c * a02 + s * a12;
  out[3] = c * a10 - s * a00;
  out[4] = c * a11 - s * a01;
  out[5] = c * a12 - s * a02;
  out[6] = a20;
  out[7] = a21;
  out[8] = a22;
  return new Mat3(out);
};
/***
 *
 * @param {Vec2} v
 * @returns {Mat3}
 */


Mat3.prototype.scale = function (v) {
  var x = v.x;
  var y = v.y;
  var out = Array(9);
  out[0] = x * a[0];
  out[1] = x * a[1];
  out[2] = x * a[2];
  out[3] = y * a[3];
  out[4] = y * a[4];
  out[5] = y * a[5];
  out[6] = a[6];
  out[7] = a[7];
  out[8] = a[8];
  return new Mat3(out);
};
/***
 *
 * @return {Mat3}
 */


Mat3.prototype.transpose = function () {
  var a = this.data;
  var out = Array(9);
  out[0] = a[0];
  out[1] = a[3];
  out[2] = a[6];
  out[3] = a[1];
  out[4] = a[4];
  out[5] = a[7];
  out[6] = a[2];
  out[7] = a[5];
  out[8] = a[8];
  return new Mat3(out);
};
/**
 *
 * @param {Vec2}v
 */


Mat3.prototype.apply2DTransform = function (v) {
  var a = this.data;
  var x0 = v.x;
  var y0 = v.y;
  var x = x0 * a[0] + y0 * a[3] + a[6];
  var y = x0 * a[1] + y0 * a[4] + a[7];
  return new Math_Vec2(x, y);
};

/* harmony default export */ var Math_Mat3 = (Mat3);
// CONCATENATED MODULE: ./src/HTML5/LanguageSystem.js


/***
 * @typedef LanguageSystemExtension
 * @property {function(key: string, code?: string): (string | null)} getText
 */

/****
 *
 * @constructor
 */

function LanguageSystem() {
  this.data = {};
  this.code = navigator.language || navigator.userLanguage;
  /***
   *
   * @type {LanguageSystemExtension[]}
   * @private
   */

  this._extensions = [];
}

LanguageSystem.prototype.notifyLanguageChange = function () {
  var sizeChange = false;

  function visit(elt) {
    if (elt.onlanguagechange) {
      try {
        elt.onlanguagechange();
        sizeChange = true;
      } catch (err) {
        Object(safeThrow["a" /* default */])(err);
      }

      if (elt.childNodes && elt.childNodes.length > 0) {
        Array.prototype.forEach.call(elt.childNodes, visit);
      }
    }
  }

  visit(document.body);
  if (sizeChange) ResizeSystem["a" /* default */].update();
};
/***
 *
 * @param {ChildNode | Text | HTMLElement | Element} node
 */


LanguageSystem.prototype.bind = function (node, key) {
  if (node.nodeType === 1) {
    this.bindTextNode(node, key);
  } else if (node.nodeType === 3) {
    this.bindElement(node, key);
  }
};
/***
 *
 * @param {Text | {__as_language_key: string}} node
 * @param {string} key
 */


LanguageSystem.prototype.bindTextNode = function (node, key) {
  node.__as_language_key = key;
  node.onlanguagechange = textNodeLanguageChangeHandler;
};
/***
 *
 * @param {ChildNode | HTMLElement | Element | {__as_language_key: string}} node
 * @param {string} key
 */


LanguageSystem.prototype.bindElement = function (node, key) {
  node.__as_language_key = key;
  node.onlanguagechange = elementLanguageChangeHandler;
};
/***
 *
 * @param {string} key
 * @param {string} [code]
 */


LanguageSystem.prototype.getText = function (key, code) {
  var code = code || this.code;
  var res;
  var ex;

  for (var i = this._extensions.length - 1; i >= 0; --i) {
    ex = this._extensions[i];
    res = ex.getText && ex.getText.apply(ex, arguments);
    if (res) break;
  }

  if (!res) {
    res = this.data[code] && this.data[code][key];
  }

  return res || null;
};
/***
 *
 * @param {LanguageSystemExtension} ex
 */


LanguageSystem.prototype.addExtension = function (ex) {
  this._extensions.push(ex);
};

var LangSys = new LanguageSystem();
function textNodeLanguageChangeHandler() {
  if (this.__as_language_key) {
    var newText = LangSys.getText(this.__as_language_key);

    if (newText && newText.trim) {
      this.data = newText;
    }
  }
}
function elementLanguageChangeHandler() {
  if (this.__as_language_key) {
    var newText = LangSys.getText(this.__as_language_key);

    if (newText && newText.trim) {
      var textNode;

      for (var i = 0; i < this.childNodes.length; ++i) {
        if (this.childNodes[i].nodeType === 1) {
          textNode = this.childNodes[i];
          break;
        }
      }

      if (!textNode) {
        textNode = document.createTextNode('');
      }

      textNode.data = newText;
    }
  }
}
/* harmony default export */ var HTML5_LanguageSystem = (LangSys);
// EXTERNAL MODULE: ./src/Code/ALogger.js
var ALogger = __webpack_require__(29);

// EXTERNAL MODULE: ./src/Code/FlagManager.js
var FlagManager = __webpack_require__(15);

// CONCATENATED MODULE: ./src/AppPattern/ObservableArray.js

/***
 * @augments EventEmitter
 * @extends Array
 * @constructor
 */

function ObservableArray(array) {
  EventEmitter["a" /* default */].call(this);
  Object.defineProperty(this, '_array', {
    configurable: false,
    enumerable: false,
    value: array
  });

  this._makeArrIndex(0, array.length);
}

Object.defineProperty(ObservableArray.prototype, 'unshift', {
  enumerable: false,
  value: function value() {
    var newItems = Array.prototype.slice.call(arguments);
    var cN = this._array.length;

    this._makeArrIndex(cN, this._array.length + newItems.length);

    this._array.unshift.apply(this._array, newItems);

    this.emit("additem", {
      target: this,
      items: newItems,
      type: 'additem',
      offset: 0,
      action: 'unshift'
    }, this);
  }
});
Object.defineProperty(ObservableArray.prototype, 'shift', {
  enumerable: false,
  value: function value() {
    var res = undefined;

    if (this._array.length > 0) {
      res = this._array.shift();

      this._removeIndex(this._array.length);

      this.emit("removeitem", {
        target: this,
        type: 'additem',
        offset: 0,
        action: 'shift',
        items: [res],
        item: res
      }, this);
    }

    return res;
  }
});
Object.defineProperty(ObservableArray.prototype, 'push', {
  enumerable: false,
  value: function value() {
    var newItems = Array.prototype.slice.call(arguments);
    var cN = this._array.length;

    this._makeArrIndex(this._array.length, this._array.length + newItems.length);

    this._array.push.apply(this._array, newItems);

    this.emit("additem", {
      target: this,
      items: newItems,
      type: 'additem',
      offset: cN,
      action: 'push'
    }, this);
  }
});
Object.defineProperty(ObservableArray.prototype, 'pop', {
  enumerable: false,
  value: function value() {
    var res = undefined;

    if (this._array.length > 0) {
      res = this._array.pop();

      this._removeIndex(this._array.length);

      this.emit("removeitem", {
        target: this,
        type: 'additem',
        offset: this._array.length,
        action: 'shift',
        items: [res],
        item: res
      }, this);
    }

    return res;
  }
});
Object.defineProperty(ObservableArray.prototype, 'replace', {
  enumerable: false,
  value: function value(offset, items) {
    for (var i = 0; i < items.length && offset < this._array.length; ++i, ++offset) {
      this._array[offset] = items[i];
    }
  }
});
Object.defineProperty(ObservableArray.prototype, 'toJSON', {
  enumerable: false,
  value: function value() {
    return this._array;
  }
});
Object.defineProperty(ObservableArray.prototype, 'valueOf', {
  enumerable: false,
  value: function value() {
    return this._array;
  }
});
Object.defineProperty(ObservableArray.prototype, '_makeArrIndex', {
  enumerable: false,
  value: function value(cN, nN) {
    var i;

    if (nN > cN) {
      for (i = cN; i < nN; ++i) {
        this._defineIndex(i);
      }
    } else {
      for (i = cN - 1; i >= nN; --i) {
        this._removeIndex(i);
      }
    }
  }
});
/***
 *
 * @param {number} idx
 * @private
 */

Object.defineProperty(ObservableArray.prototype, '_defineIndex', {
  enumerable: false,
  value: function value(idx) {
    if (!(idx in this)) {
      Object.defineProperty(this, idx, {
        set: function set(value) {
          var oldValue = this._array[idx];
          this._array[idx] = value;
          this.emit('setitem', {
            type: 'setitem',
            target: this,
            oldValue: oldValue,
            vale: value,
            offset: idx
          }, this);
        },
        get: function get() {
          return this._array[idx];
        },
        configurable: true,
        enumerable: true
      });
    }
  }
});
Object.defineProperty(ObservableArray.prototype, '_removeIndex', {
  enumerable: false,
  value: function value(idx) {
    delete this[idx];
  }
});
Object.defineProperty(ObservableArray.prototype, 'splice', {
  enumerable: false,
  value: function value(index, howMany) {
    var res = [];
    var newItems = Array.prototype.slice.call(arguments, 2);
    index = index == null ? 0 : index < 0 ? this._array.length + index : index;
    howMany = howMany == null ? this._array.length - index : howMany > 0 ? howMany : 0;

    if (howMany > 0) {
      this._makeArrIndex(this._array.length, this._array.length - howMany);

      res = this._array.splice(index, howMany);

      if (newItems.length > 0) {
        if (res.length > 0) {
          this.emit('replaceitem', {
            type: 'replaceitem',
            offset: index,
            oldItems: res,
            newItems: newItems,
            target: this,
            action: 'splice'
          }, this);
        } else {
          this.emit('additem', {
            type: 'additem',
            offset: index,
            items: newItems,
            target: this
          }, this);
        }
      } else {
        if (res.length > 0) {
          this.emit('removeitem', {
            target: this,
            type: 'additem',
            offset: 0,
            action: 'splice',
            items: res
          }, this);
        }
      }
    }

    return res;
  }
});
Object.defineProperty(ObservableArray.prototype, 'length', {
  set: function set(value) {
    var n = Number(value);
    var length = this._array.length;

    if (n % 1 === 0 && n >= 0) {
      if (n < length) {
        this.splice(n);
      } else if (n > length) {
        this.push.apply(this, new Array(n - length));
      }
    } else {
      throw new RangeError("Invalid array length");
    }

    this._array.length = n;
  },
  get: function get() {
    return this._array.length;
  }
});
Object.getOwnPropertyNames(Array.prototype).forEach(function (name) {
  if (!(name in ObservableArray.prototype)) {
    Object.defineProperty(ObservableArray.prototype, name, {
      configurable: false,
      enumerable: false,
      writable: false,
      value: Array.prototype[name]
    });
  }
});
Object.getOwnPropertyNames(EventEmitter["a" /* default */].prototype).forEach(function (name) {
  if (!(name in ObservableArray.prototype)) {
    Object.defineProperty(ObservableArray.prototype, name, {
      configurable: false,
      enumerable: false,
      writable: false,
      value: EventEmitter["a" /* default */].prototype[name]
    });
  }
});
/* harmony default export */ var AppPattern_ObservableArray = (ObservableArray);
// CONCATENATED MODULE: ./src/AppPattern/ObservableStruct.js

/***
 * @extends EventEmitter
 * @param {Object} o
 * @constructor
 */

function ObservableStruct(o) {
  EventEmitter["a" /* default */].call(this);
  Object.defineProperty(this, '__o__', {
    configurable: false,
    enumerable: false,
    value: o
  });

  for (var key in o) {
    this.defineProperty(key);
  }
}

Object.defineProperty(ObservableStruct.prototype, 'defineProperty', {
  configurable: false,
  enumerable: false,
  writable: false,

  /***
   *
   * @param {string} name
   * @param {*=} value
   */
  value: function value(name, _value) {
    if (!(name in this)) {
      Object.defineProperty(this, name, {
        set: function set(value) {
          var oldValue = this.__o__[name];
          this.__o__[name] = value;
          this.emit('setproperty', {
            type: 'setproperty',
            target: this,
            oldValue: oldValue,
            vale: value,
            name: name
          }, this);
        },
        get: function get() {
          return this.__o__[name];
        },
        configurable: true,
        enumerable: true
      });
    }
  }
});
Object.getOwnPropertyNames(EventEmitter["a" /* default */].prototype).forEach(function (name) {
  if (!(name in ObservableStruct.prototype)) {
    Object.defineProperty(ObservableStruct.prototype, name, {
      configurable: false,
      enumerable: false,
      writable: false,
      value: EventEmitter["a" /* default */].prototype[name]
    });
  }
});
/* harmony default export */ var AppPattern_ObservableStruct = (ObservableStruct);
// CONCATENATED MODULE: ./src/AppPattern/circuit/CCBlock.js


/***
 *
 * @param {{id?:string}=} opt
 * @constructor
 */

function CCBlock(opt) {
  opt = opt || {};
  this.id = opt.id || randomIdent(16);
  Object.defineProperty(this, '__cc_listener__', {
    enumerable: false,
    configurable: true,
    writable: false,
    value: {}
  });
  Object.defineProperty(this, '__cc_line_list_by_id__', {
    enumerable: false,
    configurable: true,
    writable: false,
    value: {}
  });
}
/***
 *
 * @param {string} pinName
 * @param {function} listener
 * @return {CCBlock}
 */


CCBlock.prototype.pinOn = function (pinName, listener) {
  var cbList;

  if (this.__cc_listener__[pinName]) {
    cbList = this.__cc_listener__[pinName];
  } else {
    cbList = [];
    this.__cc_listener__[pinName] = cbList;
  }

  if (cbList.indexOf(listener) < 0) {
    cbList.push(listener);
  } else {
    console.warn("Duplicate pin listener!");
  }

  return this;
};

CCBlock.prototype.pinOff = function (pinName, listener) {
  if (!this.__cc_listener__[pinName]) return this;
  var cbList = this.__cc_listener__[pinName];
  var cbIdx = cbList.indexOf(listener);

  if (cbIdx >= 0) {
    cbList.splice(cbIdx);
  }

  return this;
};

CCBlock.prototype.pinFire = function (pinName) {
  if (!this.__cc_listener__[pinName]) return this;

  var cbList = this.__cc_listener__[pinName].slice();

  var args = Array.prototype.slice.call(arguments, 1);
  if (args.length === 0 && this.pinHandlers[pinName] && this.pinHandlers[pinName].get && cbList.length > 0) args.push(this.pinGetValue(pinName));

  for (var i = 0; i < cbList.length; ++i) {
    try {
      cbList[i].apply(this, args);
    } catch (e) {
      Object(safeThrow["a" /* default */])(e);
    }
  }
};

CCBlock.prototype.pinFireAll = function () {
  var pinNames = Object.keys(this.pinHandlers);
  var pinName;

  for (var i = 0; i < pinNames.length; ++i) {
    pinName = pinNames[i];
    if (this.pinHandlers[pinName] && this.pinHandlers[pinName].get) this.pinFire(pinName);
  }
};

CCBlock.prototype.pinReceives = function (pinName) {
  var args = Array.prototype.slice.call(arguments, 1);

  if (this.pinHandlers[pinName] && this.pinHandlers[pinName].receives) {
    this.pinHandlers[pinName].receives.apply(this, args);
  }
};

CCBlock.prototype.pinGetValue = function (pinName) {
  var args = Array.prototype.slice.call(arguments, 1);

  if (this.pinHandlers[pinName] && this.pinHandlers[pinName].get) {
    return this.pinHandlers[pinName].get.apply(this, args);
  }

  return undefined;
};

CCBlock.prototype.pinGetDescriptor = function (pinName) {
  var args = Array.prototype.slice.call(arguments, 1);
  var descriptor = this.pinHandlers[pinName] && this.pinHandlers[pinName].descriptor;

  if (descriptor) {
    if (typeof descriptor === "function") return this.pinHandlers[pinName].get.apply(this, args);
    return descriptor;
  }

  return undefined;
};

Object.defineProperty(CCBlock.prototype, 'pinLines', {
  get: function get() {
    var lineList = this.__cc_line_list_by_id__;
    return Object.keys(lineList).map(function (id) {
      return lineList[id];
    });
  }
});
CCBlock.prototype.pinHandlers = {};
/* harmony default export */ var circuit_CCBlock = (CCBlock);
// CONCATENATED MODULE: ./src/AppPattern/circuit/CCLine.js

/***
 *
 * @param {CCBlock} u
 * @param {string} uPinName
 * @param {CCBlock} v
 * @param {string} vPinName
 * @param {boolean=} twoWay
 * @param {{id?:string}=} opt
 * @constructor
 */

function CCLine(u, uPinName, v, vPinName, twoWay, opt) {
  opt = opt || {};
  twoWay = !!twoWay;
  Object.defineProperty(this, 'id', {
    enumerable: true,
    writable: false,
    value: opt.id || randomIdent(32)
  });
  Object.defineProperty(this, 'u', {
    enumerable: true,
    writable: false,
    value: u
  });
  Object.defineProperty(this, 'v', {
    enumerable: true,
    writable: false,
    value: v
  });
  Object.defineProperty(this, 'uPinName', {
    enumerable: true,
    writable: false,
    value: uPinName
  });
  Object.defineProperty(this, 'vPinName', {
    enumerable: true,
    writable: false,
    value: vPinName
  });
  Object.defineProperty(this, 'twoWay', {
    enumerable: true,
    writable: false,
    value: twoWay
  });
  this.vToU = this.vToU.bind(this);
  this.uToV = this.uToV.bind(this);
  this.u.pinOn(this.uPinName, this.uToV);
  if (this.twoWay) this.v.pinOn(this.vPinName, this.vToU);
  this.u.__cc_line_list_by_id__[this.id] = this;
  this.v.__cc_line_list_by_id__[this.id] = this;
}

CCLine.prototype.remove = function () {
  this.u.pinOff(this.uPinName, this.uToV);
  if (this.twoWay) this.v.pinOff(this.vPinName, this.vToU);
  delete this.u.__cc_line_list_by_id__[this.id];
  delete this.v.__cc_line_list_by_id__[this.id];
};

CCLine.prototype.uToV = function () {
  var args = [this.vPinName].concat(Array.prototype.slice.call(arguments));
  this.v.pinReceives.apply(this.v, args);
};

CCLine.prototype.vToU = function () {
  var args = [this.uPinName].concat(Array.prototype.slice.call(arguments));
  this.u.pinReceives.apply(this.u, args);
};

/* harmony default export */ var circuit_CCLine = (CCLine);
// CONCATENATED MODULE: ./src/Network/FileSaver.js
function FileSaver_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { FileSaver_typeof = function _typeof(obj) { return typeof obj; }; } else { FileSaver_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return FileSaver_typeof(obj); }

/***
 * @typedef {{revokeTimeout?: number, autoBom?:boolean }} FileSaverOpts
 *
 */

function fileExist(url) {
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', url, true);
  return new Promise(function (resolve) {
    xhr.onreadystatechange = function () {
      if (this.readyState === 4) {
        resolve(xhr.status === 200);
      }
    };

    xhr.onerror = function (err) {};

    xhr.send();
  });
}
/***
 *
 * @param url
 * @param name
 * @param {FileSaverOpts} opts
 */

function download(url, name, opts) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = 'blob';

  xhr.onload = function () {
    saveAs(xhr.response, name, opts);
  };

  xhr.onerror = function () {
    console.error('Could not download: ' + url);
  };

  xhr.send(null);
}

function bom(blob, opts) {
  if (FileSaver_typeof(opts) === undefined) opts = {
    autoBom: false
  };else if (FileSaver_typeof(opts) !== 'object') opts = {
    autoBom: !opts
  };

  if (opts.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
    return new Blob([String.fromCharCode(0xFEFF), blob], {
      type: blob.type
    });
  }

  return blob;
}

function corsEnabled(url) {
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', url, false);

  try {
    xhr.send();
  } catch (e) {}

  return xhr.status >= 200 && xhr.status < 299;
}

function click(node) {
  try {
    node.dispatchEvent(new MouseEvent('click'));
  } catch (e) {
    var evt = document.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
    node.dispatchEvent(evt);
  }
}

function normalSaveAs(blob, name, opts) {
  var URL = window.URL || window.webkitURL;
  var a = document.createElement('a');
  name = name || blob.name || 'download';
  a.download = name;
  a.rel = 'noopener';

  if (typeof blob === 'string') {
    a.href = blob;

    if (a.origin !== location.origin) {
      if (corsEnabled(a.href)) {
        download(blob, name, opts);
      } else {
        a.target = '_blank';
        click(a);
      }
    } else {
      click(a);
    }
  } else {
    a.href = URL.createObjectURL(blob);
    setTimeout(function () {}, opts && opts.revokeTimeout || 4E4);
    setTimeout(function () {
      click(a);
    }, 0);
  }
}

function msSaveAs(blob, name, opts) {
  name = name || blob.name || 'download';

  if (typeof blob === 'string') {
    if (corsEnabled(blob)) {
      download(blob, name, opts);
    } else {
      var a = document.createElement('a');
      a.href = blob;
      a.target = '_blank';
      setTimeout(function () {
        click(a);
      });
    }
  } else {
    navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  }
}

function popupSaveAs(blob, name, opts, popup) {
  if (typeof blob === 'string') {
    download(blob, name, opts);
    return;
  }

  popup = popup || open('', '_blank');

  if (popup) {
    popup.document.title = name || 'download';
    popup.document.body.innerText = "downloading...";
  }

  name = name || blob.name || 'download';
  blob.name = name;
  var force = blob.type === 'application/octet-stream';
  var isSafari = BrowserDetector["a" /* default */].isSafari;
  var isChromeIOS = BrowserDetector["a" /* default */].isChromeIOS;
  var isMacOSWebView = BrowserDetector["a" /* default */].isMacOSWebView;
  var isSafariUnder13 = BrowserDetector["a" /* default */].browser.type === 'safari' && parseFloat(BrowserDetector["a" /* default */].browser.version) < 13;

  if ((!isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== 'undefined' & !isSafariUnder13) {
    var reader = new FileReader();

    reader.onloadend = function () {
      var url = reader.result;
      url = isChromeIOS ? url : url.replace(/^data:[^;]*/, 'data:attachment/file');
      if (popup) popup.location.href = url;else location = url;
      popup = null;
    };

    reader.readAsDataURL(blob);
  } else {
    var URL = window.URL || window.webkitURL;
    var url = URL.createObjectURL(blob);
    if (popup) popup.location.href = url;else location.href = url;
    popup = null;
    setTimeout(function () {
      URL.revokeObjectURL(blob);
    }, opts && opts.revokeTimeout || 4E4);
  }
}
/***
 *
 * @param {string  | File | Blob}blob
 * @param {string=} name
 * @param {Object=} opts
 * @param {Object=} popup
 */


function saveAs(blob, name, opts, popup) {
  if ((typeof window === "undefined" ? "undefined" : FileSaver_typeof(window)) !== "object" || window !== self) {
    console.error("FileSaver is not support!");
  } else if ('download' in HTMLAnchorElement.prototype && !BrowserDetector["a" /* default */].isMacOSWebView) {
    normalSaveAs(blob, name, opts);
  } else if ('msSaveOrOpenBlob' in navigator) {
    msSaveAs(blob, name, opts);
  } else {
    setTimeout(function () {
      popupSaveAs(blob, name, opts, popup);
    }, 100);
  }
}
function saveTextAs(text, name, opts) {
  var blob = new Blob([text], {
    type: 'text/plain'
  });
  saveAs(blob, name, opts);
}
// CONCATENATED MODULE: ./src/Network/RemoteThread.tpl
/* harmony default export */ var RemoteThread = ("function safeThrow(error) {\r\n    setTimeout(function () {\r\n        throw  error;\r\n    }, 0);\r\n}\r\n\r\nfunction EventEmitter() {\r\n    if (!this._azar_extendEvents) {\r\n        Object.defineProperty(this, '_azar_extendEvents', {\r\n            enumerable: false,\r\n            value: this._azar_extendEvents || { supported: {}, prioritize: {}, nonprioritize: {} }\r\n        });\r\n        Object.defineProperty(this, '__azar_force', {\r\n            value: true,\r\n            enumerable: false\r\n        });\r\n    }\r\n}\r\n\r\n\r\nEventEmitter.prototype.defineEvent = function (name) {\r\n    if (name instanceof Array) {\r\n        for (var i = 0; i < name.length; ++i)\r\n            this._azar_extendEvents.supported[name[i]] = true;\r\n    }\r\n    else\r\n        this._azar_extendEvents.supported[name] = true;\r\n    return this;\r\n};\r\n\r\nEventEmitter.prototype.isSupportedEvent = function (name) {\r\n    return true;\r\n};\r\n\r\n\r\nEventEmitter.prototype.emit = function (eventName, data) {\r\n    this.fire.apply(this, arguments);\r\n};\r\n\r\nEventEmitter.prototype.fire = function (eventName, data) {\r\n    var others = Array.prototype.slice.call(arguments, 1);\r\n    if (this.isSupportedEvent(eventName)) {\r\n        var listenerList;\r\n        var i;\r\n        if (this._azar_extendEvents.prioritize[eventName]) {\r\n            listenerList = this._azar_extendEvents.prioritize[eventName].slice();\r\n            for (i = 0; i < listenerList.length; ++i) {\r\n                try {\r\n                    listenerList[i].wrappedCallback.apply(this, others);\r\n                } catch (e) {\r\n                   safeThrow(e);\r\n                }\r\n            }\r\n        }\r\n\r\n        if (this._azar_extendEvents.nonprioritize[eventName]) {\r\n            listenerList = this._azar_extendEvents.nonprioritize[eventName].slice();\r\n            for (i = 0; i < listenerList.length; ++i) {\r\n                try {\r\n                    listenerList[i].wrappedCallback.apply(this, others);\r\n                } catch (e) {\r\n                    safeThrow(e);\r\n                }\r\n            }\r\n        }\r\n    }\r\n    else {\r\n        if (this.dispatchEvent) {\r\n            var event = new Event(eventName);\r\n            data && Object.assign(event, data);\r\n            this.dispatchEvent(event);\r\n        }\r\n        else\r\n            throw new Error(\"Not support event \" + eventName);\r\n    }\r\n    return this;\r\n};\r\n\r\n\r\nEventEmitter.prototype.eventEmittorOnWithTime = function (isOnce, arg0, arg1, arg2) {\r\n    if (typeof arg0 == 'object') {\r\n        for (var key in arg0) {\r\n            this.eventEmittorOnWithTime(isOnce, key, arg0[key]);\r\n        }\r\n        return this;\r\n    }\r\n    else {\r\n        if (typeof arg1 == 'object') {\r\n            return this.eventEmittorOnWithTime(isOnce, arg0, arg1.callback, arg1.cap);\r\n        }\r\n        else {\r\n            var eventArr = this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] || [];\r\n            var eventIndex = -1;\r\n            for (var i = 0; i < eventArr.length; ++i) {\r\n                if (eventArr[i].wrappedCallback == arg1) {\r\n                    eventIndex = i;\r\n                    break;\r\n                }\r\n            }\r\n            if (eventIndex < 0) {\r\n                var event = { isOnce: isOnce, eventName: arg0, callback: arg1, cap: !!arg2 };\r\n                //wrappedCallback will be call\r\n                if (isOnce) {\r\n                    event.wrappedCallback = function () {\r\n                        event.callback.apply(this, arguments);\r\n                        this.off(event.eventName, event.wrappedCallback, event.cap);\r\n                    };\r\n                }\r\n                else {\r\n                    event.wrappedCallback = event.callback;\r\n                }\r\n\r\n                if (!this.isSupportedEvent(arg0)) {\r\n                    if (this.addEventListener) {\r\n                        this.addEventListener(arg0, event.wrappedCallback, !!arg2);\r\n                    }\r\n                    else {\r\n                        this.attachEvent('on' + arg0, arg1, !!arg2);\r\n                    }\r\n                }\r\n\r\n                eventArr.push(event);\r\n                this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] = eventArr;\r\n            }\r\n            else {\r\n                console.warn(\"dupplicate event\");\r\n            }\r\n\r\n        }\r\n        return this;\r\n    }\r\n};\r\n\r\n\r\nEventEmitter.prototype.on = function (arg0, arg1, arg2) {\r\n    this.eventEmittorOnWithTime(false, arg0, arg1, arg2);\r\n    return this;\r\n};\r\n\r\n\r\nEventEmitter.prototype.once = function (arg0, arg1, arg2) {\r\n    this.eventEmittorOnWithTime(true, arg0, arg1, arg2);\r\n    return this;\r\n};\r\n\r\nEventEmitter.prototype.off = function (arg0, arg1, arg2) {\r\n    if (typeof arg0 == 'object') {\r\n        for (var key in arg0) {\r\n            this.off(key, arg0[key]);\r\n        }\r\n        return this;\r\n    }\r\n    else {\r\n        if (typeof arg1 == 'object') {\r\n            return this.off(arg0, arg1.callback, arg1.cap);\r\n        }\r\n        else {\r\n            var eventArr = this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] || [];\r\n            var newEventArray = [];\r\n            for (var i = 0; i < eventArr.length; ++i) {\r\n                var event = eventArr[i];\r\n                if (event.wrappedCallback == arg1) {\r\n                    //Dont add to newEventArray\r\n                    if (this.isSupportedEvent(arg0)) {\r\n                    }\r\n                    else {\r\n                        if (this.removeEventListener) {\r\n                            this.removeEventListener(event.eventName, event.wrappedCallback, !!event.cap);\r\n                        }\r\n                        else {\r\n                            this.detachEvent('on' + event.eventName, event.wrappedCallback, !!event.cap);\r\n                        }\r\n                    }\r\n                }\r\n                else {\r\n                    newEventArray.push(event);\r\n                }\r\n            }\r\n            this._azar_extendEvents[arg2 ? 'prioritize' : 'nonprioritize'][arg0] = newEventArray;\r\n            return this;\r\n        }\r\n    }\r\n\r\n};\r\n\r\n\r\nvar TYPE_WORKER = 'WORKER';\r\n\r\n/**\r\n *\r\n * @param {Worker|HTMLIFrameElement|WorkerGlobalScope|Window=} host\r\n */\r\nfunction IFrameBridge(host) {\r\n    EventEmitter.call(this);\r\n    /***\r\n     *\r\n     * @type {Worker|HTMLIFrameElement|WorkerGlobalScope|Window|WorkerGlobalScope|Window}\r\n     */\r\n    this.host = host || self;\r\n    this.sender = null;\r\n    this.receiver = null;\r\n    this.origin = null;\r\n    this.type = 'NOT_DETECT';\r\n    this.id = \"UNSET\";\r\n\r\n    this.sync = this._detectHost().then(() => this._attach());\r\n\r\n    this.__azarResolveCallbacks = {};\r\n    this.__azarRejectCallbacks = {};\r\n}\r\n\r\nIFrameBridge.prototype._detectHost = function () {\r\n          this.type = TYPE_WORKER;\r\n          this.sender = this.host;\r\n          this.receiver = this.host;\r\n          return Promise.resolve();\r\n};\r\n\r\n\r\nIFrameBridge.prototype._attach = function () {\r\n    if (this.receiver.addEventListener) {\r\n        this.receiver.addEventListener(\"message\", this.__azarMessageListener.bind(this), false);\r\n    }\r\n    else if (this.receiver.attachEvent) {\r\n        this.receiver.attachEvent(\"onmessage\", this.__azarMessageListener.bind(this));\r\n    }\r\n    else {\r\n        this.receiver.onmessage = this.__azarMessageListener.bind(this);\r\n    }\r\n};\r\n\r\n\r\nIFrameBridge.getInstance = function () {\r\n    if (!IFrameBridge.shareInstance) {\r\n        var origin = location.origin;\r\n        var rootOrigin = IFrameBridge.getParentUrl().match(/^(http|https):\\/\\/[^/]+/);\r\n        if (rootOrigin) {\r\n            rootOrigin = rootOrigin[0];\r\n        }\r\n        else {\r\n            rootOrigin = origin;\r\n        }\r\n\r\n        // IFrameBridge.shareInstance = new IFrameBridge(self, rootOrigin == origin? undefined: \"*\" || rootOrigin );\r\n        var host = self;\r\n        IFrameBridge.shareInstance = new IFrameBridge(host, rootOrigin);\r\n    }\r\n    return IFrameBridge.shareInstance;\r\n};\r\n\r\n\r\nObject.defineProperties(IFrameBridge.prototype, Object.getOwnPropertyDescriptors(EventEmitter.prototype));\r\nIFrameBridge.prototype.constructor = IFrameBridge;\r\n\r\n\r\nIFrameBridge.getParentUrl = function () {\r\n    var parentUrl = (window.location != window.parent.location)\r\n        ? document.referrer\r\n        : document.location.href;\r\n    return parentUrl;\r\n};\r\n\r\nIFrameBridge.prototype.__azarMessageListener = function (event) {\r\n    this.__azarHandleData(event.data);\r\n};\r\n\r\n\r\nIFrameBridge.prototype.__azarHandleData = function (data) {\r\n    if (data.bridgeId !== this.id) return;\r\n    if (data.type) {\r\n        if (data.type == \"INVOKE\") {\r\n            try {\r\n                var result = this.__azarSelfInvoke(data.name, data.params);\r\n                if (result && typeof result.then == 'function') {\r\n                    result.then(function (result) {\r\n                        this.__azarResolve(data.taskId, result);\r\n                    }.bind(this))\r\n                        .catch(function (err) {\r\n                            safeThrow(err);\r\n                            this.__azarResolve(data.taskId, null, err);\r\n                        }.bind(this));\r\n                }\r\n                else {\r\n                    this.__azarResolve(data.taskId, result);\r\n                }\r\n            } catch (err) {\r\n                safeThrow(err);\r\n                this.__azarResolve(data.taskId, null, err);\r\n            }\r\n        }\r\n        else if (data.type == \"INVOKE_RESULT\") {\r\n            if (this.__azarResolveCallbacks[data.taskId]) {\r\n                if (data.error) {\r\n                    this.__azarRejectCallbacks[data.taskId](data.error);\r\n                }\r\n                else {\r\n                    this.__azarResolveCallbacks[data.taskId](data.result);\r\n                }\r\n                delete this.__azarResolveCallbacks[data.taskId];\r\n                delete this.__azarRejectCallbacks[data.taskId];\r\n            }\r\n        }\r\n        else if (data.type == \"EMIT\") {\r\n            this.fire.apply(this, data.params);\r\n        }\r\n        else this.fire('message', data, this);\r\n    }\r\n};\r\n\r\n\r\nIFrameBridge.prototype.__azarResolve = function (taskId, result, error) {\r\n    var data = {\r\n        type: \"INVOKE_RESULT\",\r\n        taskId: taskId,\r\n        result: result,\r\n        error: error,\r\n        bridgeId: this.id\r\n    };\r\n\r\n    if (this.origin) {\r\n        this.sender.postMessage(data, this.origin);\r\n    }\r\n    else {\r\n        this.sender.postMessage(data);\r\n    }\r\n};\r\n\r\n\r\nIFrameBridge.prototype.__azarSelfInvoke = function (name, params) {\r\n    if (typeof this[name] == 'function') {\r\n        return this[name].apply(this, params);\r\n    }\r\n    else {\r\n        return this[name];\r\n    }\r\n};\r\n\r\n\r\nIFrameBridge.prototype.emit = function () {\r\n    var params = [];\r\n    params.push.apply(params, arguments);\r\n    this.sync.then(function () {\r\n        var data = {\r\n            type: \"EMIT\",\r\n            params: params,\r\n            bridgeId: this.id\r\n        };\r\n        if (this.origin) {\r\n            this.sender.postMessage(data, this.origin);\r\n        }\r\n        else {\r\n            this.sender.postMessage(data);\r\n        }\r\n    }.bind(this));\r\n    return this;\r\n};\r\n\r\n\r\nIFrameBridge.prototype.invoke = function (name) {\r\n    var params = [];\r\n    params.push.apply(params, arguments);\r\n    params.shift();\r\n    return this.sync.then(function () {\r\n        var indent = randomIdent(32);\r\n        var data = {\r\n            type: 'INVOKE',\r\n            params: params,\r\n            taskId: indent,\r\n            name: name,\r\n            bridgeId: this.id\r\n        };\r\n        if (this.origin) {\r\n            this.host.postMessage(data, this.origin);\r\n        }\r\n        else {\r\n            this.host.postMessage(data);\r\n        }\r\n        return new Promise(function (resolve, reject) {\r\n            this.__azarResolveCallbacks[indent] = resolve;\r\n            this.__azarRejectCallbacks[indent] = reject;\r\n        }.bind(this));\r\n    }.bind(this));\r\n};\r\n\r\nIFrameBridge.prototype.importScriptURLs = function () {\r\n    return this.invoke.apply(this, ['_receiveScriptURLs'].concat(Array.prototype.slice.call(arguments)));\r\n};\r\n\r\nIFrameBridge.prototype.importScript = function (code) {\r\n    var blob = new Blob([code], { type: 'application/javascript' });\r\n    var url = URL.createObjectURL(blob);\r\n    return this.importScriptURLs(url);\r\n};\r\n\r\n\r\nIFrameBridge.prototype.createMethod = function (name, fx) {\r\n    this[name] = function () {\r\n        return this.invoke.apply(this, [name].concat(Array.prototype.slice.call(arguments)));\r\n    };\r\n    return this.invoke.apply(this, ['_receiveMethod', name, fx.toString()]);\r\n};\r\n\r\n\r\nIFrameBridge.prototype._receiveScriptURLs = function () {\r\n    if (self.importScripts) {\r\n        self.importScripts.apply(self, arguments);\r\n    }\r\n};\r\n\r\n\r\nIFrameBridge.prototype._receiveMethod = function (name, code) {\r\n    this[name] = (new Function('return ' + code))();\r\n};\r\n\r\n\r\nvar IFrameBridge_prototype_descriptors = Object.getOwnPropertyDescriptors(IFrameBridge.prototype);\r\ndelete IFrameBridge_prototype_descriptors.constructor;\r\n\r\nObject.defineProperties(self, IFrameBridge_prototype_descriptors);\r\nIFrameBridge.call(self, self);");
// CONCATENATED MODULE: ./src/Network/Thread.js



/***
 *
 * @param {{methods?:Object, extendCode: string}} opt
 * @constructor
 */

function Thread(opt) {
  this.worker = new Worker(this._makeCodeUrl(opt));
  Network_IFrameBridge.call(this, this.worker);

  this._attachClientMethods(opt.methods);
}

Thread.prototype._makeCodeUrl = function (opt) {
  var code = [this._makeLibCode(opt.libs), RemoteThread, this._makeMethodCode(opt.methods), this._makePropCode(opt.props), opt.extendCode || ''].join('\n\n');
  var blob = new Blob([code], {
    type: 'application/javascript'
  });
  var url = URL.createObjectURL(blob);
  return url;
};

Thread.prototype._makePropCode = function (props) {
  if (!props) return '';
  return 'Object.assign(self, ' + JSON.stringify(props) + ');';
};

Thread.prototype._makeLibCode = function (libs) {
  if (!libs) return '';
  return libs.map(function (lib) {
    return 'self.importScripts(' + JSON.stringify(lib) + ');';
  }).join('\n');
};

Thread.prototype._makeMethodCode = function (methods) {
  if (!methods) return '';
  return Object.keys(methods).map(function (key) {
    var fx = methods[key];

    if (typeof fx === "function") {
      fx = fx.toString();
      return 'self[' + JSON.stringify(key) + '] = ' + fx;
    }
  }).join('\n\n');
};

Thread.prototype._attachClientMethods = function (methods) {
  if (!methods) return '';
  Object.keys(methods).reduce(function (ac, name) {
    ac[name] = function () {
      return this.invoke.apply(this, [name].concat(Array.prototype.slice.call(arguments)));
    };

    return ac;
  }, this);
};

OOP["a" /* default */].mixClass(Thread, Network_IFrameBridge);
/* harmony default export */ var Network_Thread = (Thread);
// CONCATENATED MODULE: ./src/JSMaker/generator.js
function generator_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { generator_typeof = function _typeof(obj) { return typeof obj; }; } else { generator_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return generator_typeof(obj); }

function generateJSVariable(obj, indent) {
  indent = indent || '';
  var childIndent = indent + '    ';

  if (obj === null) {
    return 'null';
  } else if (obj instanceof Date) {
    return 'new Date(' + obj.getTime() + ')';
  } else if (obj instanceof Array) {
    if (obj.length === 0) return '[]';
    return '[\n' + obj.map(function (it) {
      return childIndent + generateJSVariable(it, childIndent);
    }).join(',\n') + '\n' + indent + ']';
  } else if (obj instanceof Error) {
    return generateJSVariable({
      message: obj.message,
      stack: obj.stack
    });
  } else if (generator_typeof(obj) === 'object') {
    var keys = Object.keys(obj);
    if (keys.length === 0) return '{}';
    return '{\n' + keys.map(function (key) {
      var value = obj[key];
      if (!key.match(/^[a-zA-Z_$]([a-zA-Z_0-9$]*)$/)) key = JSON.stringify(key);
      return childIndent + key + ': ' + generateJSVariable(value, childIndent);
    }).join(',\n') + '\n' + indent + '}';
  } else if (obj === undefined) {
    return 'undefined';
  } else {
    return JSON.stringify(obj);
  }
}
/***
 *
 * @param o
 * @param {Array<{test, replace}>| null=} replacers
 * @returns {*}
 */

function copyJSVariable(o, replacers) {
  var _arguments = arguments;
  var replacer;

  if (replacers && replacers.length > 0) {
    replacer = replacers.find(function (rp) {
      return rp.test.apply(rp, [o].concat(Array.prototype.slice.call(_arguments, 2)));
    });

    if (replacer) {
      return replacer.replace.apply(replacer, [o].concat(Array.prototype.slice.call(arguments, 2)));
    }
  }

  if (o === null) return null;
  if (o === undefined) return undefined;

  var type = generator_typeof(o);

  if (type === "boolean") return o;
  if (o instanceof Date || typeof o.getTime === "function") return new Date(o.getTime());
  if (type === "number") return o;
  if (type === "string") return o + '';

  if (typeof o.map === "function") {
    return o.map(function (it, i) {
      return copyJSVariable(it, replacers, i, o);
    });
  }

  if (type === "object" && o.constructor === Object) {
    return Object.keys(o).reduce(function (ac, cr) {
      ac[cr] = copyJSVariable(o[cr], replacers, cr, o);
      return ac;
    }, {});
  }

  return o;
}
function replaceDateStringJSVariable(o) {
  return copyJSVariable(o, [{
    test: function test(x) {
      return typeof x === "string" && x.match(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+([a-zA-Z]{3})\s+[\d\s:]+GMT[\d+]+\s*\([^)]+\)$/) && !isNaN(new Date(x).getTime());
    },
    replace: function replace(x) {
      return new Date(x);
    }
  }]);
}
/***
 *
 * @param a
 * @param b
 * @return {boolean}
 */

function isJSVariableEqual(a, b) {
  if (a === b) return true; //1

  var tA = generator_typeof(a);

  var tB = generator_typeof(b);

  if (tA !== tB) return false; //2

  if (!a !== !b) return false;
  if (tA === 'string') return false; //because 1 & 2

  if (tA === "number") {
    if (isNaN(a) && isNaN(b)) return true; //because 2

    return false; //because 1
  }

  var aIsDate = a instanceof Date;
  var bIsDate = b instanceof Date;
  if (aIsDate !== bIsDate) return false;
  if (aIsDate) return isJSVariableEqual(a.getTime(), b.getTime());
  var aIsArray = a instanceof Array;
  var bIsArray = a instanceof Array;
  if (aIsArray !== bIsArray) return false;
  var i;

  if (aIsArray) {
    if (a.length !== b.length) return false;

    for (i = 0; i < a.length; ++i) {
      if (!isJSVariableEqual(a[i], b[i])) return false;
    }

    return true;
  } //object


  if (a.equals) return a.equals(b);
  var aKeys = Object.keys(a);
  var bKeys = Object.keys(b);
  aKeys.sort();
  bKeys.sort();
  if (!isJSVariableEqual(aKeys, bKeys)) return false;

  for (i = 0; i < aKeys.length; ++i) {
    if (!isJSVariableEqual(a[aKeys[i]], b[aKeys[i]])) return false;
  }

  return true;
}
// CONCATENATED MODULE: ./src/AppPattern/ShareConfiguration.js
function ShareConfiguration_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ShareConfiguration_typeof = function _typeof(obj) { return typeof obj; }; } else { ShareConfiguration_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ShareConfiguration_typeof(obj); }



function ShareConfiguration() {
  Object.defineProperty(this, 'data', {
    value: {},
    enumerable: true,
    writable: false
  });
  Object.defineProperty(this, '__listener__', {
    value: {},
    enumerable: false,
    writable: false
  });
}
/***
 *
 * @param {string} key
 * @param {*|undefined} value
 */


ShareConfiguration.prototype.set = function (key, value) {
  var prev = this.data[key];
  this.data[key] = value;

  if (value !== prev) {
    this.emit(key, value, this);
  }

  return this;
};

ShareConfiguration.prototype.emit = function (key) {
  var args = Array.prototype.slice.call(arguments, 1);
  var self = this;

  if (this.__listener__[key]) {
    this.__listener__[key].slice().forEach(function (f) {
      try {
        f.apply(self, args);
      } catch (err) {
        Object(safeThrow["a" /* default */])(err);
      }
    });
  }

  return this;
};
/***
 *
 * @param {string|Object} key
 * @param {function=}listener
 * @return {ShareConfiguration}
 */


ShareConfiguration.prototype.on = function (key, listener) {
  if (typeof key === "string") {
    if (!this.__listener__[key]) this.__listener__[key] = [];

    if (this.__listener__[key].indexOf(listener) < 0) {
      this.__listener__[key].push(listener);
    }
  } else if (ShareConfiguration_typeof(key) === "object") {
    for (var key1 in key) {
      this.on(key1, key[key1]);
    }
  }

  return this;
};
/***
 *
 * @param {string|Object} key
 * @param {function=}listener
 * @return {ShareConfiguration}
 */


ShareConfiguration.prototype.off = function (key, listener) {
  if (typeof key === "string" && this.__listener__[key]) {
    var idx = this.__listener__[key].indexOf(listener);

    if (idx >= 0) {
      this.__listener__[key].splice(idx, 1);
    }
  } else if (ShareConfiguration_typeof(key) === "object") {
    for (var key1 in key) {
      this.off(key1, key[key1]);
    }
  }

  return this;
};
/***
 *
 * @param {string} key
 * @param {*=} defaultValue
 * @return {*}
 */


ShareConfiguration.prototype.get = function (key, defaultValue) {
  return this.data[key];
};

ShareConfiguration.prototype.contains = function (key) {
  return this.data[key] === undefined;
};

ShareConfiguration.instance = new ShareConfiguration();
/* harmony default export */ var AppPattern_ShareConfiguration = (ShareConfiguration);
// CONCATENATED MODULE: ./src/DataStructure/Array.js
function Array_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Array_typeof = function _typeof(obj) { return typeof obj; }; } else { Array_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Array_typeof(obj); }

/***
 *
 * @param {(string|number|boolean|null)[]} arr
 * @returns {(string|number|boolean|null)[]}
 */
function arrayUnique(arr) {
  var dict = {};
  return arr.reduce(function (ac, cr) {
    var key = Array_typeof(cr) + '//' + cr;
    if (key in dict) return ac;
    ac.push(cr);
    dict[key] = true;
    return ac;
  }, []);
}
/***
 *
 * @param {[]}arr
 * @return {[]}
 */

function arrayRemoveNone(arr) {
  return arr.filter(function (c) {
    return c !== null && c !== undefined;
  });
}
function arrayIntersection(a1, a2) {
  var dict1 = a1.reduce(function (ac, cr) {
    ac[Array_typeof(cr) + cr] = true;
    return ac;
  }, {});
  var dict2 = a2.reduce(function (ac, cr) {
    ac[Array_typeof(cr) + cr] = true;
    return ac;
  }, {});
  var dictAdded = {};
  var res = [];
  var i, k, x;

  for (i = 0; i < a1.length; ++i) {
    x = a1[i];
    k = Array_typeof(x) + x;

    if (dict1[k] && dict2[k] && !dictAdded[k]) {
      res.push(x);
      dictAdded[k] = true;
    }
  }

  for (i = 0; i < a2.length; ++i) {
    x = a2[i];
    k = Array_typeof(x) + x;

    if (dict1[k] && dict2[k] && !dictAdded[k]) {
      res.push(x);
      dictAdded[k] = true;
    }
  }

  return res;
}
function arrayIsSubset(childArr, parentArr) {
  if (!(childArr instanceof Array) || !(parentArr instanceof Array)) return false;
  var dict2 = parentArr.reduce(function (ac, cr) {
    ac[Array_typeof(cr) + cr] = true;
    return ac;
  }, {});
  var res = true;
  var n = childArr.length;
  var k;

  for (var i = 0; i < n; ++i) {
    k = Array_typeof(childArr[i]) + childArr[i];

    if (!dict2[k]) {
      res = false;
      break;
    }
  }

  return res;
}
/***
 *
 * @param {[]}a1
 * @param {[]}a2
 * @param {boolean=} order
 * @returns {boolean}
 */

function arrayCompare(a1, a2, order) {
  if (a1 === a2) return true;
  if (!a1 || !a2) return false;
  if (a1.length !== a2.length) return false;
  if (!a1.sort || !a2.sort) return false;

  if (!order) {
    a1.sort();
    a2.sort();
  }

  var n = a1.length;

  for (var i = 0; i < n; ++i) {
    if (a1[i] !== a2[i]) return false;
  }

  return true;
}
/***
 *
 * @param {Array} arr
 */

function arrayShuffle(arr) {
  var temp;
  var j;

  for (var i = 0; i < arr.length; ++i) {
    j = Math.floor(Math.random() * arr.length);

    if (i !== j) {
      temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
  }
}
// CONCATENATED MODULE: ./src/Network/remoteRequireNodeAsync.js
function remoteRequireNodeAsync(filename, entry) {
  var moduleCache = {};
  var factors = {};
  var resources = {};

  function getFileName(path) {
    return path.split('/').pop();
  }

  function getExtension(fileName) {
    return fileName.split('.').slice(1).pop() || null;
  }

  function require(currentLoc, fn) {
    var dir = concatUrl(currentLoc, '..');
    var fullPath = concatUrl(dir, fn);
    if (factors[fullPath + '.js']) fullPath = fullPath + '.js';
    var filename = getFileName(fullPath); //__filename

    var module = moduleCache[fullPath];

    if (!module) {
      if (factors[fullPath]) {
        module = {
          'exports': {}
        };
        moduleCache[fullPath] = module;
        factors[fullPath](require.bind(null, fullPath), module, module.exports, dir, filename, window);
      } else {
        throw new Error("Could not find module :" + fullPath);
      }
    }

    return module.exports;
  }

  function concatUrl(url, concat) {
    if (concat.startsWith('https:') || concat.startsWith('http:')) return concat;
    var url1 = url.split('/');
    var url2 = concat.split('/');
    var url3 = [];
    var i, l;

    for (i = 0, l = url1.length; i < l; i++) {
      if (url1[i] === '..') {
        url3.pop();
      } else if (url1[i] !== '.') {
        url3.push(url1[i]);
      }
    }

    for (i = 0, l = url2.length; i < l; i++) {
      if (url2[i] === '..') {
        url3.pop();
      } else if (url2[i] !== '.') {
        url3.push(url2[i]);
      }
    }

    return url3.join('/');
  }

  function findAllRequire(s) {
    var regex0 = /[^a-zA-Z_.0-9]require\s*\([^\)]+\)/gm;
    var regex1 = /require\s*\([^)]+\)/gm;
    var regex2 = /\([^)]+\)/gm;
    var es = s.match(regex0);
    if (!es) return [];
    return es.map(function (s) {
      s = s.match(regex1)[0];
      s = s.match(regex2)[0];
      s = s.replace(/['"()]/gm, '');
      if (!getExtension(getFileName(s))) s += '.js';
      return s;
    });
  }

  function fetchResource(fullPath) {
    if (resources[fullPath]) return Promise.resolve();
    var resource = {};
    resources[fullPath] = resource;
    var dir = concatUrl(fullPath, '..');
    var ext = getExtension(getFileName(fullPath));
    resource.sync = fetch(fullPath, {
      cache: "no-cache"
    }).then(function (res) {
      return res.text();
    }).then(function (text) {
      resource.text = text;

      switch (ext) {
        case 'js':
          factors[fullPath] = new Function('require', 'module', 'exports', '__dir', '__filename', 'global', text);
          break;

        case 'html':
        case 'tpl':
        case 'svg':
          factors[fullPath] = true;
          moduleCache = {
            exports: text
          };
          break;

        case 'json':
          factors[fullPath] = true;
          moduleCache = {
            exports: JSON.parse(text)
          };
          break;
      }

      var requiredNodes;

      if (ext === 'js') {
        requiredNodes = findAllRequire(text);
        var syncs = requiredNodes.map(function (ident) {
          return fetchResource(concatUrl(dir, ident));
        });
        return Promise.all(syncs);
      }
    });
    return resource.sync;
  }

  var absoluteEntry = location.href[location.href.length - 1] === '/' ? location.href : concatUrl(location.href, "..");

  function requireCode(filename, entry, fileList) {
    if (!fileList) fileList = {};
    if (!entry) entry = absoluteEntry;
    var fullPath = concatUrl(entry, filename);

    if (fileList[fullPath] === 'pending') {
      return Promise.resolve();
    } else if (fileList[fullPath] !== undefined && fileList[fullPath] !== 'pending') {
      return Promise.resolve();
    }

    fileList[fullPath] = true;
    var dir = concatUrl(fullPath, '..');
    fileList[fullPath] = 'pending';
    return fetch(fullPath, {
      cache: "no-cache"
    }).then(function (res) {
      return res.text();
    }).then(function (text) {
      fileList[fullPath] = text;
      var requirePath = findAllRequire(text);
      var waitCode = requirePath.map(function (e) {
        return requireCode(e, dir, fileList);
      });
      return Promise.all(waitCode).then(function () {
        return fileList;
      });
    });
  }

  if (!entry) entry = absoluteEntry;
  if (!getExtension(filename)) filename += '.js';
  var fullPath = concatUrl(entry, filename);
  return fetchResource(fullPath).then(function () {
    return require('', fullPath);
  });
}
// CONCATENATED MODULE: ./src/Math/Polygon.js

/***
 *
 * @param {Vec2[]} vertices
 * @constructor
 */

function Polygon(vertices) {
  this.vertices = vertices;
}
/***
 *
 * @param {Vec2} P
 * @returns {-1|0|1}
 */


Polygon.prototype.pointLocalIn = function (P) {
  var A = this.vertices[this.vertices.length - 1];
  var B;
  var AB, PA, PB;
  var t, x;
  var count = 0;

  for (var i = 0; i < this.vertices.length; ++i) {
    B = this.vertices[i];
    PA = A.sub(P);
    PB = B.sub(P);

    if (PA.cross(PB) === 0 && PA.dot(PB) <= 0) {
      return 0;
    }

    AB = B.sub(A);

    if (A.y !== B.y) {
      t = -PA.y / AB.y;
      x = A.x + AB.x * t;

      if (t >= 0 && t < 1 && x > P.x) {
        count++;
      }
    }

    A = B;
  }

  return count % 2 === 1 ? 1 : -1;
};

Polygon.prototype.getPathString = function () {
  var vts = this.vertices;
  var res = 'M' + vts[0].x + ' ' + vts[0].y;

  for (var i = 1; i < vts.length; ++i) {
    res += 'L' + vts[i].x + ' ' + vts[i].y;
  }

  res += 'z';
  return res;
};

Polygon.make = function (vertices) {
  return new Polygon(vertices);
};

/* harmony default export */ var Math_Polygon = (Polygon);
// CONCATENATED MODULE: ./src/HTML5/DynamicCSS.js
function DynamicCSS() {
  this.elt = document.createElement('style');
  this.data = {};
  this.state = 'STANDBY';
  this.start();
}
/**
 *
 * @returns {this}
 */


DynamicCSS.prototype.commit = function () {
  var _this = this;

  this.elt.innerHTML = Object.keys(this.data).map(function (ruleQuery) {
    var rule = _this.data[ruleQuery];
    return [ruleQuery + ' {', '    ' + Object.keys(rule).map(function (name) {
      return name + ': ' + rule[name] + ';';
    }).join('\n'), '}'].join('\n');
  }).join('\n\n');
  return this;
};

DynamicCSS.prototype.start = function () {
  if (this.state !== 'STANDBY' && this.state !== 'STOP') return;
  this.state = 'RUNNING';
  document.head.appendChild(this.elt);
  return this;
};

DynamicCSS.prototype.stop = function () {
  if (this.state !== 'RUNNING') return;
  this.elt.remove();
  return this;
};

DynamicCSS.prototype.destroy = function () {
  this.stop();
  if (this.state !== 'STOP') return;
  this.elt = null;
  return this;
};
/***
 *
 * @param {string} ruleQuery
 * @param {string} name
 * @param {string} value
 * @returns {this}
 */


DynamicCSS.prototype.setProperty = function (ruleQuery, name, value) {
  this.data[ruleQuery] = this.data[ruleQuery] || {};
  this.data[ruleQuery][name] = value;
  return this;
};
/**
 *
 * @param ruleQuery
 * @param name
 * @returns {*|undefined}
 */


DynamicCSS.prototype.getProperty = function (ruleQuery, name) {
  var rule = this.data[ruleQuery];
  return rule ? rule[name] : undefined;
};
/***
 *
 * @param ruleQuery
 * @param property
 * @returns {DynamicCSS}
 */


DynamicCSS.prototype.removeProperty = function (ruleQuery, property) {
  var rule = this.data[ruleQuery];
  if (rule) delete rule[property];
  return this;
};
/***
 *
 * @param ruleQuery
 * @param {object} properties
 * @returns {this}
 */


DynamicCSS.prototype.setRule = function (ruleQuery, properties) {
  this.data[ruleQuery] = Object.assign({}, properties);
  return this;
};
/***
 *
 * @param ruleQuery
 * @param {object} properties
 * @returns {this}
 */


DynamicCSS.prototype.modifyRule = function (ruleQuery, properties) {
  this.data[ruleQuery] = Object.assign(this.data[ruleQuery] || {}, properties);
  return this;
};
/***
 *
 * @param {string} ruleQuery
 * @returns {object}
 */


DynamicCSS.prototype.getRule = function (ruleQuery) {
  return this.data[ruleQuery];
};
/**
 *
 * @param {string} ruleQuery
 * @returns {this}
 */


DynamicCSS.prototype.removeRule = function (ruleQuery) {
  delete this.data[ruleQuery];
  return this;
};
/***
 *
 * @param {object} rules
 * @returns {this}
 */


DynamicCSS.prototype.setRules = function (rules) {
  var _this2 = this;

  Object.keys(rules).forEach(function (key) {
    return _this2.setRule(key, rules[key]);
  });
  return this;
};

DynamicCSS.prototype.getRules = function () {
  return this.data;
};

DynamicCSS.prototype.modifyRules = function (rules) {
  var _this3 = this;

  Object.keys(rules).forEach(function (key) {
    return _this3.modifyRule(key, rules[key]);
  });
  return this;
};

/* harmony default export */ var HTML5_DynamicCSS = (DynamicCSS);
// CONCATENATED MODULE: ./src/Pharse/DPTokenizer.js
function DPTokenizer(opt) {
  opt = opt || {};
  if (opt.elementRegexes) this.elementRegexes = opt.elementRegexes;

  this._combineTokenRegex();
}

DPTokenizer.prototype.elementRegexes = [['string', /("(?:[^"\\]|\\.)*?")|('(?:[^'\\]|\\.)*?')/], ['number', /[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)/], ['word', /[_a-zA-Z][_a-zA-Z0-9]*/], ['dsymbol', /\+\+|--/], ['symbol', /[^\s_a-zA-Z0-9]/], ['skip', /[\s\r\n]+/]];

DPTokenizer.prototype._combineTokenRegex = function () {
  var tokenRegexSource = this.elementRegexes.map(function (cr) {
    return '(' + cr[1].source + ')';
  }).join('|');
  this.tokenRegex = new RegExp(tokenRegexSource, 'g');
  this.groupIndexOfTypes = this.elementRegexes.slice(0, this.elementRegexes.length - 1).reduce(function (ac, cr) {
    var subGroupLength = new RegExp(cr[1].source + '|.').exec('a').length;
    ac.push(ac[ac.length - 1] + subGroupLength);
    return ac;
  }, [1]);
  this.types = this.elementRegexes.reduce(function (ac, cr) {
    ac[cr[0]] = cr;
    return ac;
  }, {});
};

DPTokenizer.prototype.tokenize = function (source) {
  var regex = new RegExp(this.tokenRegex.source, 'g');
  var elementRegexes = this.elementRegexes;
  var groupIndexOfTypes = this.groupIndexOfTypes;
  var res = [];
  var matched = regex.exec(source);
  var type, i;

  while (matched) {
    type = null;

    for (i = 0; i < groupIndexOfTypes.length; ++i) {
      if (matched[groupIndexOfTypes[i]]) {
        type = elementRegexes[i][0];
      }
    }

    res.push({
      type: type,
      content: matched[0],
      start: matched.index,
      end: matched.index + matched[0].length
    });
    matched = regex.exec(source);
  }

  return res;
};

/* harmony default export */ var Pharse_DPTokenizer = (DPTokenizer);
// CONCATENATED MODULE: ./src/Pharse/DPParseInstance.js

var TARGET = 0;
var RULE = 1;
var PASSED = 2;
var LENGTH = 3;
var TRACK = 4;
/***
 * @param {string} target
 * @param {Rule|null} rule
 * @param {number} passed
 * @param {number} length
 * @param {[]} track
 *
 * @returns {*[]}
 */

function mkItem(target, rule, passed, length, track) {
  return [target, rule, passed, length, track];
}

function indexingItem(item) {
  return item[TARGET] + '*' + item[PASSED] + '*' + item[LENGTH];
}
/****
 *
 * @param {DPParser} parser
 * @param {string || []} source
 * @param {string} target
 * @constructor
 */


function DPParseInstance(parser, source, target) {
  this.target = target;
  this.parser = parser;
  this.targets = parser.targets;
  this.rules = parser.rules;
  this.tokenTypes = parser.tokenizer.types;
  this.error = null;
  this.source = source;

  if (typeof source === "string") {
    this.tokens = parser.tokenizer.tokenize(source).filter(function (tk) {
      return tk.type !== 'skip';
    });
  } else if (source instanceof Array) {
    this.tokens = source;
  } else {
    throw new Error("Invalid source, source must be string or array of token");
  }

  this.tokenIdx = 0;
  this.priQueue = new DataStructure_Heap(this._cmpFunction);
  this.maxSize = 0;
  this.expectedArr = [];
  this.parsedNode = null;
  this.ast = null;

  this._dp();

  this._trackBack();

  if (this.parsedNode) {
    this._calcAST();
  } else {
    this._findError();
  }
}

DPParseInstance.prototype._dp = function () {
  while (this.tokenIdx < this.tokens.length) {
    this._nextToken();
  }
};

DPParseInstance.prototype._cmpFunction = function (a, b) {
  return a[1] - b[1];
};

DPParseInstance.prototype._nextToken = function () {
  var idx = this.tokenIdx++;
  var token = this.tokens[idx];
  this.priQueue.push(mkItem('.' + token.type, null, 1, 1, [null, token]));
  this.priQueue.push(mkItem('_' + token.content, null, 1, 1, [null, token]));
  var expected = {};
  var pushed = {};
  var itemIndex;
  this.expectedArr.push(expected);
  var cur, next;
  var i, j, rule;
  var prevExpectedList, prevRule;
  var prevExpectedItem;

  while (this.priQueue.size() > 0) {
    this.maxSize = Math.max(this.maxSize, this.priQueue.size());
    cur = this.priQueue.pop();

    for (i = 0; i < this.rules.length; ++i) {
      rule = this.rules[i];

      if (rule.elements[0] === cur[TARGET]) {
        if (rule.elements.length === 1) {
          next = mkItem(rule.target, rule, cur[PASSED], cur[LENGTH], [null, cur]);
          itemIndex = indexingItem(next);

          if (pushed) {
            pushed[itemIndex] = true;
            this.priQueue.push(next);
          }

          expected['^'] = expected['^'] || [];
          expected['^'].push(next);
        } else {
          next = mkItem(rule.target, rule, 1, cur[LENGTH], [null, cur]);
          expected[rule.elements[1]] = expected[rule.elements[1]] || [];
          expected[rule.elements[1]].push(next);
        }
      }
    }

    prevExpectedList = this.expectedArr[idx - cur[LENGTH]] && this.expectedArr[idx - cur[LENGTH]][cur[TARGET]];

    if (prevExpectedList) {
      for (j = 0; j < prevExpectedList.length; ++j) {
        prevExpectedItem = prevExpectedList[j];
        prevRule = prevExpectedItem[RULE];
        next = mkItem(prevRule.target, prevRule, prevExpectedItem[PASSED] + 1, prevExpectedItem[LENGTH] + cur[LENGTH], [prevExpectedItem, cur]);

        if (prevExpectedItem[PASSED] + 1 === prevRule.elements.length) {
          itemIndex = indexingItem(next);

          if (pushed) {
            pushed[itemIndex] = true;
            this.priQueue.push(next);
          }

          expected['^'] = expected['^'] || [];
          expected['^'].push(next); //[rule index, passed, length]
        } else {
          expected[prevRule.elements[prevExpectedItem[PASSED] + 1]] = expected[prevRule.elements[prevExpectedItem[PASSED] + 1]] || [];
          expected[prevRule.elements[prevExpectedItem[PASSED] + 1]].push(next);
        }
      }
    }
  }
};

DPParseInstance.prototype._trackBack = function () {
  var expectedAr = this.expectedArr;

  function visit(target, start, length) {
    var node = {
      type: target,
      start: start,
      end: start + length
    };
    var matchedItem = null;
    var expected = expectedAr[start + length - 1];
    if (!expected) return null;
    var itemList = expected['^'];
    if (!itemList) return null;
    var item;

    if (itemList) {
      for (var j = 0; j < itemList.length; ++j) {
        item = itemList[j];

        if (item[TARGET] === target) {
          if (item[LENGTH] === length) {
            matchedItem = item;
          }
        }
      }
    }

    if (!matchedItem) {
      return null;
    }

    node.rule = matchedItem[RULE];
    var childItem = [];
    var cTrack = matchedItem[TRACK];
    var right, left;

    while (cTrack) {
      left = cTrack[0];
      right = cTrack[1];
      childItem.unshift(right);
      cTrack = left && left[TRACK];
    }

    var ac = childItem.reduce(function (ac, item) {
      if (typeof item[TRACK][1].type === "string") {
        ac.child.push(item[TRACK][1]);
        ac.start += 1;
      } else {
        ac.child.push(visit(item[TARGET], ac.start, item[LENGTH]));
        ac.start += item[LENGTH];
      }

      return ac;
    }, {
      start: start,
      child: []
    });
    node.children = ac.child;
    node.end = ac.start;
    return node;
  }

  this.parsedNode = visit(this.target, 0, this.expectedArr.length);
};

DPParseInstance.prototype._findError = function () {
  function cmp(a, b) {
    return b.i - a.i;
  }

  var queue = new DataStructure_Heap(cmp);
  var doneArr = Array(this.expectedArr.length).fill(null).map(function () {
    return {};
  });
  this.expectedArr.forEach(function (ex, i) {
    for (var k in ex) {
      ex[k].forEach(function (it) {
        var target = it[TARGET];
        var done = doneArr[i - it[LENGTH] + 1];
        done[target] = done[target] || [];
        done[target].push(it);
      });
    }
  });
  var d = {};
  queue.push({
    t: this.target,
    i: 0
  });
  d[this.target + '/' + 0] = true;
  var cr, next;
  var nextIdent;
  var item;
  var hasNewExpected;

  while (queue.size() > 0) {
    cr = queue.pop();

    if (cr.i >= doneArr.length) {
      if (!this.error || this.error.tokenIdx < cr.i || this.error.type !== "expected") {
        this.error = {
          tokenIdx: cr.i,
          type: 'expected',
          expectedToken: []
        };
      }

      if (cr.t[0] === '_' || cr.t[0] === '.') {
        this.error.expectedToken.push(cr.t);
      }

      continue;
    }

    hasNewExpected = false;

    if (doneArr[cr.i][cr.t]) {
      doneArr[cr.i][cr.t].forEach(function (item) {
        if (item[PASSED] < item[RULE].elements.length) {
          next = {
            i: cr.i + item[LENGTH],
            t: item[RULE].elements[item[PASSED]]
          };
          nextIdent = next.t + '/' + next.i;
          hasNewExpected = true;

          if (!d[nextIdent]) {
            d[nextIdent] = true;
            queue.push(next);
          }
        }
      });
    }

    this.rules.forEach(function (rule) {
      if (rule.target === cr.t) {
        next = {
          i: cr.i,
          t: rule.elements[0]
        };
        nextIdent = next.t + '/' + next.i;

        if (!d[nextIdent]) {
          d[nextIdent] = true;
          queue.push(next);
        }
      }
    });

    if (!hasNewExpected) {
      if (!this.error || this.error.tokenIdx < cr.i) {
        this.error = {
          tokenIdx: cr.i,
          type: 'unexpected'
        };
      }
    }
  }

  if (this.error.type === 'expected') {
    this.error.message = 'Expected: ' + this.error.expectedToken.map(function (t) {
      if (t[0] === '.') return t.substring(1);
      if (t[0] === '_') return JSON.stringify(t.substring(1));
    }).join(', ');
  } else if (this.error.type === 'unexpected') {
    this.error.message = 'Unexpected token ' + (this.tokens[this.error.tokenIdx].content || JSON.stringify(this.tokens[this.error.tokenIdx]));
  }
};

DPParseInstance.prototype._calcAST = function () {
  this.ast = this.parsedNode.rule.toAST(this.parsedNode);
};

function parsedNodeToAST(parsedNode) {
  return parsedNode.rule.toAST(parsedNode);
}
function parsedNodeToASTChain(parsedNode) {
  return parsedNode.rule.toASTChain(parsedNode);
}
/* harmony default export */ var Pharse_DPParseInstance = (DPParseInstance);
// CONCATENATED MODULE: ./src/Pharse/DPParser.js


/***
 * @typedef Rule
 * @property {string} target
 * @property {string[]} elements
 */

/***
 *
 * @param opt
 * @constructor
 */

function DPParser(opt) {
  opt = opt || {};

  if (opt.rules) {
    this.rules = opt.rules;
  }

  this.targets = {};
  this.tokenizer = new Pharse_DPTokenizer(opt);
  this.computeTarget();
}
/****
 * @type {Rule[]}
 */


DPParser.prototype.rules = [];

DPParser.prototype.computeTarget = function () {
  this.rules.reduce(function (ac, rule) {
    var target = ac[rule.target];

    if (!target) {
      target = {
        rules: []
      };
      ac[rule.target] = target;
    }

    target.rules.push(rule);
    return ac;
  }, this.targets);
};
/***
 *
 * @param {string|[]}source
 * @param target
 * @returns {DPParseInstance}
 */


DPParser.prototype.parse = function (source, target) {
  return new Pharse_DPParseInstance(this, source, target);
};

/* harmony default export */ var Pharse_DPParser = (DPParser);
// CONCATENATED MODULE: ./src/SCLang/SCGrammar.js

/*********************************
 * EXPRESSION
 */

var operatorOrder = {
  'NOT': 4,
  '!': 4,
  '*': 5,
  '/': 5,
  'MOD': 5,
  '%': 5,
  '+': 6,
  '-': 6,
  '<': 9,
  '>': 9,
  '<=': 9,
  '>=': 9,
  '==': 9,
  '!=': 9,
  'AND': 14,
  '&&': 14,
  'OR': 15,
  '||': 15,
  'XOR': 15
};
var elementRegexes = [['string', /("(?:[^"\\]|\\.)*?")|('(?:[^'\\]|\\.)*?')/], ['number', /(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)/], ['word', /[_a-zA-Z][_a-zA-Z0-9]*/], ['skip', /([\s\r\n]+)|(\/\/[^\n]*)|(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)/], ['dsymbol', /\+\+|--|==|!=|<=|>=/], ['tsymbol', /\.\.\./], ['symbol', /[^\s_a-zA-Z0-9]/]];
var rules = [];
rules.push({
  target: 'null',
  elements: ['_null'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'NullLiteral'
    };
  }
});
rules.push({
  target: 'ident',
  elements: ['.word'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'Identifier',
      name: parsedNode.children[0].content
    };
  }
});
rules.push({
  target: 'args_list',
  elements: ['exp'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  },
  toASTChain: function toASTChain(parsedNode) {
    return [parsedNodeToAST(parsedNode)];
  }
});
rules.push({
  target: 'args_list',
  elements: ['args_list', '_,', 'exp'],
  toASTChain: function toASTChain(parsedNode) {
    return parsedNodeToASTChain(parsedNode.children[0]).concat(parsedNodeToAST(parsedNode.children[2]));
  }
});
rules.push({
  target: 'function_callee',
  elements: ['ident'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'function_callee',
  elements: ['mem_exp'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'function_call',
  elements: ['function_callee', '_(', 'args_list', '_)'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'CallExpression',
      arguments: parsedNode.children[2].rule.toASTChain(parsedNode.children[2]),
      callee: parsedNodeToAST(parsedNode.children[0])
    };
  }
});
rules.push({
  target: 'function_call',
  elements: ['function_callee', '_(', '_)'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'CallExpression',
      arguments: [],
      callee: parsedNodeToAST(parsedNode.children[0])
    };
  }
});
rules.push({
  target: 'new_expression',
  elements: ['_new', 'function_call'],
  toAST: function toAST(parsedNode) {
    var callAst = parsedNodeToAST(parsedNode.children[1]);
    return {
      type: 'NewExpression',
      arguments: callAst.arguments,
      callee: callAst.callee
    };
  }
});
rules.push({
  target: 'exp',
  elements: ['new_expression'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'exp',
  elements: ['null'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'exp',
  elements: ['ident'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'number',
  elements: ['.number'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'NumericLiteral',
      value: parseFloat(parsedNode.children[0].content)
    };
  }
});
rules.push({
  target: 'string',
  elements: ['.string'],
  toAST: function toAST(parsedNode) {
    var content = parsedNode.children[0].content;
    if (content[0] === "'") content = '"' + content.substring(1, content.length - 1).replace(/["]/g, '\\"') + '"';
    return {
      type: 'StringLiteral',
      value: JSON.parse(content)
    };
  }
});
rules.push({
  target: 'boolean',
  elements: ['_true'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'BooleanLiteral',
      value: true
    };
  }
});
rules.push({
  target: 'boolean',
  elements: ['_false'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'BooleanLiteral',
      value: false
    };
  }
});
rules.push({
  target: 'exp',
  elements: ['number'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'exp',
  elements: ['string'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'exp',
  elements: ['boolean'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
['+', '-', '*', '/', '%', '&&', '||', 'XOR', '==', '!=', '<', '>', '>=', '<='].forEach(function (op) {
  rules.push({
    target: 'bin_op',
    elements: ['_' + op],
    toAST: function toAST(parsedNode) {
      return {
        type: "BinaryOperator",
        content: op
      };
    }
  });
});
rules.push({
  target: 'exp',
  elements: ['exp', 'bin_op', 'exp'],
  toASTChain: function toASTChain(parseNode) {
    var res = [];

    if (parseNode.children[0].rule === this) {
      res = res.concat(this.toASTChain(parseNode.children[0]));
    } else {
      res.push(parsedNodeToAST(parseNode.children[0]));
    }

    res.push(parseNode.children[1].children[0]);

    if (parseNode.children[2].rule === this) {
      res = res.concat(this.toASTChain(parseNode.children[2]));
    } else {
      res.push(parsedNodeToAST(parseNode.children[2]));
    }

    return res;
  },
  toAST: function toAST(parsedNode) {
    var chain = this.toASTChain(parsedNode);
    var stack = [];
    var item;
    var newNode;

    while (chain.length > 0) {
      item = chain.shift();

      if (item.content in operatorOrder) {
        while (stack.length >= 3 && operatorOrder[stack[stack.length - 2].content] <= operatorOrder[item.content]) {
          newNode = {
            type: 'BinaryExpression'
          };
          newNode.right = stack.pop();
          newNode.operator = stack.pop();
          newNode.left = stack.pop();
          stack.push(newNode);
        }
      }

      stack.push(item);
    }

    while (stack.length >= 3) {
      newNode = {
        type: 'BinaryExpression'
      };
      newNode.right = stack.pop();
      newNode.operator = stack.pop();
      newNode.left = stack.pop();
      stack.push(newNode);
    }

    return stack.pop();
  }
});
rules.push({
  target: 'exp',
  elements: ['function_call'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'bracket_group',
  elements: ['_(', 'exp', '_)'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[1]);
  }
});
rules.push({
  target: 'exp',
  elements: ['bracket_group'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
}); // rules.push({
//     target: 'exp',
//     elements: ['_(', 'exp', '_)'],
//     toAST: function (parsedNode) {
//         return parsedNodeToAST(parsedNode.children[1]);
//     }
// });

['+', '-', '!'].forEach(function (op) {
  ['number', 'bracket_group', 'ident', 'function_call', 'mem_exp', 'unary_exp'].forEach(function (arg) {
    rules.push({
      target: 'unary_exp',
      elements: ['_' + op, arg],
      toAST: function toAST(parsedNode) {
        return {
          type: 'UnaryExpression',
          argument: parsedNodeToAST(parsedNode.children[1]),
          operator: {
            type: 'UnaryOperator',
            content: op
          }
        };
      }
    });
  });
});
rules.push({
  target: 'exp',
  elements: ['unary_exp'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['ident', '_.', 'ident'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: false,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['ident', '_[', 'exp', '_]'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: true,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['new_expression', '_.', 'ident'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: false,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['new_expression', '_[', 'exp', '_]'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: true,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['mem_exp', '_.', 'ident'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: false,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['mem_exp', '_[', 'exp', '_]'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: true,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['bracket_group', '_.', 'ident'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: false,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'mem_exp',
  elements: ['bracket_group', '_[', 'exp', '_]'],
  toAST: function toAST(parsedNode) {
    return {
      type: "MemberExpression",
      computed: true,
      object: parsedNodeToAST(parsedNode.children[0]),
      property: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'exp',
  elements: ['mem_exp'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'object_exp',
  elements: ['_{', '_}'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'ObjectExpression',
      properties: []
    };
  }
});
rules.push({
  target: 'object_exp',
  elements: ['_{', 'object_property_list', '_}'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'ObjectExpression',
      properties: parsedNodeToASTChain(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'exp',
  elements: ['object_exp'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'object_property',
  elements: ['ident', '_:', 'exp'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'ObjectProperty',
      key: parsedNodeToAST(parsedNode.children[0]),
      value: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'object_property',
  elements: ['string', '_:', 'exp'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'ObjectProperty',
      key: parsedNodeToAST(parsedNode.children[0]),
      value: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'object_property_list',
  elements: ['object_property'],
  toASTChain: function toASTChain(parsedNode) {
    return [parsedNodeToAST(parsedNode.children[0])];
  }
});
rules.push({
  target: 'object_property_list',
  elements: ['object_property_list', '_,', 'object_property'],
  toASTChain: function toASTChain(parsedNode) {
    return parsedNodeToASTChain(parsedNode.children[0]).concat([parsedNodeToAST(parsedNode.children[2])]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'exp',
  elements: ['array_exp'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'array_exp',
  elements: ['_[', '_]'],
  toAST: function toAST(parsedNode) {
    return {
      type: "ArrayExpression",
      elements: []
    };
  }
});
rules.push({
  target: 'array_exp',
  elements: ['_[', 'array_item_list', '_]'],
  toAST: function toAST(parsedNode) {
    return {
      type: "ArrayExpression",
      elements: parsedNodeToASTChain(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'array_item_list',
  elements: ['exp'],
  toASTChain: function toASTChain(parsedNode) {
    return [parsedNodeToAST(parsedNode.children[0])];
  }
});
rules.push({
  target: 'array_item_list',
  elements: ['array_item_list', '_,', 'exp'],
  toASTChain: function toASTChain(parsedNode) {
    return parsedNodeToASTChain(parsedNode.children[0]).concat([parsedNodeToAST(parsedNode.children[2])]);
  }
});
/**********************************************************************************************************************/

/**************FOR QUICK PARSING***********************/

rules.push({
  target: 'exp',
  elements: ['.constance'],
  toAST: function toAST(parsedNode) {
    return parsedNode.children[0];
  },
  toASTChain: function toASTChain(parsedNode) {
    return [parsedNode.children[0]];
  }
});
/***********************************************************************************************************************/

rules.push({
  target: 'generic_type',
  elements: ['ident'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'GenericType',
      id: parsedNodeToAST(parsedNode.children[0])
    };
  }
});
rules.push({
  target: 'linked_type',
  elements: ['_linktype', 'exp'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'LinkedType',
      address: parsedNodeToAST(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'var_type',
  elements: ['generic_type'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'var_type',
  elements: ['linked_type'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/*
rules.push({
    target: 'var_type',
    elements: ['ident', '<', 'var_type', '>']
});

rules.push({
    target: 'var_type',
    elements: ['ident', '<', '.string', '>']
});
*/

rules.push({
  target: 'type_annotation',
  elements: ['_:', 'var_type'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'TypeAnnotation',
      typeAnnotation: parsedNodeToAST(parsedNode.children[1])
    };
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'variable_declaration',
  elements: ['_var', 'ident', 'type_annotation', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'VariableDeclaration',
      id: parsedNodeToAST(parsedNode.children[1]),
      typeAnnotation: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'variable_declaration',
  elements: ['_var', 'ident', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'VariableDeclaration',
      id: parsedNodeToAST(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'variable_declaration',
  elements: ['_var', 'ident', '_=', 'exp', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'VariableDeclaration',
      id: parsedNodeToAST(parsedNode.children[1]),
      init: parsedNodeToAST(parsedNode.children[3])
    };
  }
});
/**********************************************************************************************************************/
//todo

rules.push({
  target: 'expression_statement',
  elements: ['function_call', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'ExpressionStatement',
      expression: parsedNodeToAST(parsedNode.children[0])
    };
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'assign_statement',
  elements: ['ident', '_=', 'exp', '_;'],
  toAST: function toAST(parseNode) {
    return {
      type: 'AssignStatement',
      left: parsedNodeToAST(parseNode.children[0]),
      right: parsedNodeToAST(parseNode.children[2])
    };
  }
});
rules.push({
  target: 'assign_statement',
  elements: ['mem_exp', '_=', 'exp', '_;'],
  toAST: function toAST(parseNode) {
    return {
      type: 'AssignStatement',
      left: parsedNodeToAST(parseNode.children[0]),
      right: parsedNodeToAST(parseNode.children[2])
    };
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'if_statement_1',
  elements: ['_if', '_(', 'exp', '_)', 'statement'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'IfStatement',
      test: parsedNodeToAST(parsedNode.children[2]),
      consequent: parsedNodeToAST(parsedNode.children[4])
    };
  }
});
rules.push({
  target: 'if_statement_2',
  elements: ['if_statement_1', '_else', 'statement'],
  toAST: function toAST(parsedNode) {
    var ast = parsedNodeToAST(parsedNode.children[0]);
    ast.alternate = parsedNodeToAST(parsedNode.children[2]);
    return ast;
  }
});
rules.push({
  target: 'statement',
  elements: ['if_statement_1'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'statement',
  elements: ['if_statement_2'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'for_count_statement',
  elements: ['_for', 'ident', '_from', 'exp', '_to', 'exp', 'block_statement'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'ForCountStatement',
      for: parsedNodeToAST(parsedNode.children[1]),
      from: parsedNodeToAST(parsedNode.children[3]),
      to: parsedNodeToAST(parsedNode.children[5]),
      body: parsedNodeToAST(parsedNode.children[6])
    };
  }
});
rules.push({
  target: 'iterable_range',
  elements: ['iterable_range_limit', '_...', 'iterable_range_limit']
});
rules.push({
  target: 'iterable_range_limit',
  elements: ['.number']
});
rules.push({
  target: 'iterable_range_limit',
  elements: ['ident']
});
/**********************************************************************************************************************/

rules.push({
  target: 'while_statement',
  elements: ['_while', 'bracket_group', 'statement'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'WhileStatement',
      test: parsedNodeToAST(parsedNode.children[1]),
      body: parsedNodeToAST(parsedNode.children[2])
    };
  }
});
rules.push({
  target: 'statement',
  elements: ['while_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'do_while_statement',
  elements: ['_do', 'statement', '_while', 'bracket_group', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'DoWhileStatement',
      test: parsedNodeToAST(parsedNode.children[3]),
      body: parsedNodeToAST(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'statement',
  elements: ['do_while_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'break_statement',
  elements: ['_break', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'BreakStatement'
    };
  }
});
rules.push({
  target: 'statement',
  elements: ['break_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'block_statement',
  elements: ['_{', '_}'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'BlockStatement',
      body: []
    };
  }
});
rules.push({
  target: 'block_statement',
  elements: ['_{', 'statement_arr', '_}'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'BlockStatement',
      body: parsedNodeToASTChain(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'statement',
  elements: ['variable_declaration'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'statement',
  elements: ['block_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'statement',
  elements: ['expression_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'statement',
  elements: ['for_count_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'statement',
  elements: ['assign_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'statement_arr',
  elements: ['statement'],
  toASTChain: function toASTChain(parsedNode) {
    return [parsedNodeToAST(parsedNode.children[0])];
  }
});
rules.push({
  target: 'statement_arr',
  elements: ['statement_arr', 'statement'],
  toASTChain: function toASTChain(parsedNode) {
    return parsedNodeToASTChain(parsedNode.children[0]).concat([parsedNodeToAST(parsedNode.children[1])]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'function_arguments_declaration',
  elements: ['_(', '_)'],
  toASTChain: function toASTChain(parsedNode) {
    return [];
  }
});
rules.push({
  target: 'function_arguments_declaration',
  elements: ['_(', 'argument_declaration_list', '_)'],
  toASTChain: function toASTChain(parsedNode) {
    return parsedNodeToASTChain(parsedNode.children[1]);
  }
});
rules.push({
  target: 'argument_declaration',
  elements: ['ident', 'type_annotation'],
  toAST: function toAST(parsedNode) {
    return {
      type: "ArgumentDeclaration",
      id: parsedNodeToAST(parsedNode.children[0]),
      typeAnnotation: parsedNodeToAST(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'argument_declaration',
  elements: ['ident'],
  toAST: function toAST(parsedNode) {
    return {
      type: "ArgumentDeclaration",
      id: parsedNodeToAST(parsedNode.children[0])
    };
  }
});
rules.push({
  target: 'argument_declaration_list',
  elements: ['argument_declaration'],
  toASTChain: function toASTChain(parsedNode) {
    return [parsedNodeToAST(parsedNode.children[0])];
  }
});
rules.push({
  target: 'argument_declaration_list',
  elements: ['argument_declaration_list', '_,', 'argument_declaration'],
  toASTChain: function toASTChain(parsedNode) {
    return parsedNodeToASTChain(parsedNode.children[0]).concat([parsedNodeToAST(parsedNode.children[2])]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'return_statement',
  elements: ['_return', 'exp', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: "ReturnStatement",
      argument: parsedNodeToAST(parsedNode.children[1])
    };
  }
});
rules.push({
  target: 'return_statement',
  elements: ['_return', '_;'],
  toAST: function toAST(parsedNode) {
    return {
      type: "ReturnStatement"
    };
  }
});
rules.push({
  target: 'statement',
  elements: ['return_statement'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
/**********************************************************************************************************************/

rules.push({
  target: 'function_declare',
  elements: ['_function', 'ident', 'function_arguments_declaration', 'type_annotation', 'block_statement'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'FunctionDeclaration',
      id: parsedNodeToAST(parsedNode.children[1]),
      params: parsedNodeToASTChain(parsedNode.children[2]),
      returnType: parsedNodeToAST(parsedNode.children[3]),
      body: parsedNodeToAST(parsedNode.children[4])
    };
  }
});
rules.push({
  target: 'function_declare',
  elements: ['_function', 'ident', 'function_arguments_declaration', 'block_statement'],
  toAST: function toAST(parsedNode) {
    return {
      type: 'FunctionDeclaration',
      id: parsedNodeToAST(parsedNode.children[1]),
      params: parsedNodeToASTChain(parsedNode.children[2]),
      body: parsedNodeToAST(parsedNode.children[3])
    };
  }
});
rules.push({
  target: 'statement',
  elements: ['function_declare'],
  toAST: function toAST(parsedNode) {
    return parsedNodeToAST(parsedNode.children[0]);
  }
});
rules.push({
  target: 'program',
  elements: ['statement_arr'],
  toAST: function toAST(parsedNode) {
    return {
      type: "Program",
      body: parsedNodeToASTChain(parsedNode.children[0])
    };
  }
});
/* harmony default export */ var SCGrammar = ({
  elementRegexes: elementRegexes,
  rules: rules,
  operatorOrder: operatorOrder
});
// CONCATENATED MODULE: ./src/SCLang/SCParser.js


/***
 * @type {DPParser}
 */

var SCParser = new Pharse_DPParser(SCGrammar);
/* harmony default export */ var SCLang_SCParser = (SCParser);
// CONCATENATED MODULE: ./src/SCLang/SCOperatorExecutor.js
function SCOperatorExecutor() {
  this.oFXYs = {};
  this.oFXs = {};
}
/***
 *
 * @param {string} operator
 * @param {function(x, y, next: function):void} fxy
 */


SCOperatorExecutor.prototype.addBinaryOperator = function (operator, fxy) {
  if (!this.oFXYs[operator]) this.oFXYs[operator] = [];
  this.oFXYs[operator].unshift(fxy);
};
/***
 *
 * @param {string} operator
 * @param {function(x,  next: function):void} fx
 */


SCOperatorExecutor.prototype.addUnaryOperator = function (operator, fx) {
  if (!this.oFXs[operator]) this.oFXs[operator] = [];
  this.oFXs[operator].unshift(fx);
};

SCOperatorExecutor.prototype.executeBinaryOperator = function (operator, x, y) {
  var fXYs = this.oFXYs[operator];

  var i, _next;

  if (fXYs) {
    i = -1;

    _next = function next() {
      ++i;
      if (i >= fXYs.length) throw {
        message: 'Could not match any function for operator' + operator,
        x: x,
        y: y
      };
      return fXYs[i](x, y, _next);
    };

    return _next();
  } else {
    throw {
      message: 'Could not find operate: ' + operator
    };
  }
};

SCOperatorExecutor.prototype.executeUnaryOperator = function (operator, x) {
  var fXs = this.oFXs[operator];

  var i, _next2;

  if (fXs) {
    i = -1;

    _next2 = function next() {
      ++i;
      if (i >= fXs.length) throw {
        message: 'Could not match any function for operator' + operator,
        x: x
      };
      return fXs[i](x, _next2);
    };

    return _next2();
  } else {
    throw {
      message: 'Could not find operate: ' + operator
    };
  }
};
/***
 * @type {SCOperatorExecutor}
 */


/* harmony default export */ var SCLang_SCOperatorExecutor = (new SCOperatorExecutor());
// CONCATENATED MODULE: ./src/SCLang/SCOperators.js
function SCOperators_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { SCOperators_typeof = function _typeof(obj) { return typeof obj; }; } else { SCOperators_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return SCOperators_typeof(obj); }



function ADD(a, b) {
  var type_a = SCOperators_typeof(a);

  var type_b = SCOperators_typeof(b);

  if (type_a === "number") {
    if (type_b === "number" || type_b === 'string') return a + b;
  }

  if (type_a === "undefined" && type_b === "undefined") return undefined;

  if (type_a === 'string') {
    if (type_b === "string") return a + b;
    if (b instanceof Date) return a + formatDateTime(b, 'dd/MM/yyyy');
    if (type_b === "number") return a + b;
  }

  if (a instanceof Date) {
    if (type_b === 'number') {
      return new Date(a.getTime() + MILLIS_PER_DAY * b);
    } else if (type_b === 'string') {
      return formatDateTime(a, 'dd/MM/yyyy') + b;
    }
  }

  if (a.add && a.constructor === b.constructor) return a.add(b);
  console.error("Can not add: ", a, b);
  return NaN;
}
SCLang_SCOperatorExecutor.addBinaryOperator('+', ADD);
function SUB(a, b) {
  var type_a = SCOperators_typeof(a);

  var type_b = SCOperators_typeof(b);

  if (type_a === "number" && type_b === "number") {
    return a - b;
  }

  if (type_a === "undefined" && type_b === "undefined") return undefined;

  if (a instanceof Date) {
    if (type_b === 'number') {
      return new Date(a.getTime() - MILLIS_PER_DAY * b);
    }
  }

  if (a.sub && a.constructor === b.constructor) return a.sub(b);
  console.error("Can not sub: ", a, b);
  return NaN;
}
SCLang_SCOperatorExecutor.addBinaryOperator('-', SUB);
function MUL(a, b) {
  var type_a = SCOperators_typeof(a);

  var type_b = SCOperators_typeof(b);

  if (type_a === "number" && type_b === "number") {
    return a * b;
  }

  if (type_a === "undefined" && type_b === "undefined") return undefined;

  if (type_a === "string" && type_b === "number") {
    return a.repeat(b);
  }

  console.error("Can not mul: ", a, b);
  return NaN;
}
SCLang_SCOperatorExecutor.addBinaryOperator('*', MUL);
function DIV(a, b) {
  var type_a = SCOperators_typeof(a);

  var type_b = SCOperators_typeof(b);

  if (type_a === "number" && type_b === "number") {
    return a / b;
  }

  if (type_a === "undefined" && type_b === "undefined") return undefined;
  console.error("Can not div: ", a, b);
  return NaN;
}
SCLang_SCOperatorExecutor.addBinaryOperator('/', DIV);
function MOD(x, m) {
  return x % m;
}
SCLang_SCOperatorExecutor.addBinaryOperator('%', MOD);
function NEGATIVE(x) {
  return -x;
}
SCLang_SCOperatorExecutor.addUnaryOperator('-', NEGATIVE);
function POSITIVE(x) {
  return x;
}
SCLang_SCOperatorExecutor.addUnaryOperator('+', POSITIVE);
function NOT(x) {
  return !x;
}
SCLang_SCOperatorExecutor.addUnaryOperator('!', NOT);
function LESS_THAN(a, b) {
  if (a instanceof Date) a = a.getTime();
  if (b instanceof Date) b = b.getTime();
  return a < b;
}
SCLang_SCOperatorExecutor.addBinaryOperator('<', LESS_THAN);
function MORE_THAN(a, b) {
  if (a instanceof Date) a = a.getTime();
  if (b instanceof Date) b = b.getTime();
  return a > b;
}
SCLang_SCOperatorExecutor.addBinaryOperator('>', MORE_THAN);
function EQUAL(a, b) {
  if (a instanceof Date) a = a.getTime();
  if (b instanceof Date) b = b.getTime();
  return a === b;
}
SCLang_SCOperatorExecutor.addBinaryOperator('==', EQUAL);
function LESS_AND_EQUAL(a, b) {
  if (a instanceof Date) a = a.getTime();
  if (b instanceof Date) b = b.getTime();
  return a <= b;
}
SCLang_SCOperatorExecutor.addBinaryOperator('<=', LESS_AND_EQUAL);
function MORE_AND_EQUAL(a, b) {
  if (a instanceof Date) a = a.getTime();
  if (b instanceof Date) b = b.getTime();
  return a >= b;
}
SCLang_SCOperatorExecutor.addBinaryOperator('>=', MORE_AND_EQUAL);
function NOT_EQUAL(a, b) {
  if (a instanceof Date) a = a.getTime();
  if (b instanceof Date) b = b.getTime();
  return a != b;
}
SCLang_SCOperatorExecutor.addBinaryOperator('!=', NOT_EQUAL);
// CONCATENATED MODULE: ./src/AppPattern/Const.js
/***
 *
 * @param {T} value
 * @constructor
 * @template T
 */
function Const(value) {
  this.value = value;
}

Const.prototype.toString = function () {
  return this.value + '';
};
/***
 *
 * @return {T}
 */


Const.prototype.valueOf = function () {
  return this.value;
};
/**
 *
 * @return {T}
 */


Const.prototype.get = function () {
  return this.value;
};

/* harmony default export */ var AppPattern_Const = (Const);
// CONCATENATED MODULE: ./src/SCLang/SCScope.js


/***
 *
 * @param {SCScope=} parent
 * @constructor
 */

function SCScope(parent) {
  this.parent = parent;
  /***
   *
   * @type {Object<string, Ref|Const>}
   */

  this.data = {};
}

SCScope.prototype.set = function (name, value) {
  var ref = this.findRef(name);
  if (!ref) throw new Error('"' + name + '" was not declared!');

  if (ref.set) {
    ref.set(value);
  } else {
    throw new Error('"' + name + '" defined with const cannot be modified!');
  }
};

SCScope.prototype.get = function (name, value) {
  var ref = this.findRef(name);
  if (!ref) throw new Error('"' + name + '" was not declared!');
  return ref.get();
};

SCScope.prototype.declareConst = function (name, value, force) {
  if (name in this.data && !force) throw new Error("Cannot redefine an already declared variable");
  this.data[name] = new AppPattern_Const(value);
};

SCScope.prototype.declareVar = function (name, value, force) {
  if (name in this.data && !force) throw new Error("Cannot redefine an already declared variable");
  this.data[name] = new AppPattern_Ref(value);
};

SCScope.prototype.revoke = function (name) {
  delete this.data[name];
};
/***
 *
 * @param {string} name
 * @return {Ref|Const|null}
 */


SCScope.prototype.findRef = function (name) {
  return this.data[name] || this.parent && this.parent.findRef(name) || null;
};
/***
 *
 * @param {string} name
 * @return {SCScope|null}
 */


SCScope.prototype.findScope = function (name) {
  if (this.data[name]) return this;
  if (this.parent) return this.parent.findScope(name);
  return null;
};

/* harmony default export */ var SCLang_SCScope = (SCScope);
// CONCATENATED MODULE: ./src/SCLang/SCProgramInstance.js




var SCStaticLibScope = new SCLang_SCScope();
var SCDynamicLibScope = new SCLang_SCScope(SCStaticLibScope);

function SCProgramInstance(ast, env) {
  var _this = this;

  env = env || {};

  if (env instanceof SCLang_SCScope) {
    this.global = env;
  } else {
    this.global = new SCLang_SCScope(SCDynamicLibScope);
    Object.keys(env).forEach(function (key) {
      _this.global.declareConst(key, env[key]);
    });
  }

  this.topScope = this.global;
  this.stack = [{
    scope: this.global
  }];
  this.ast = ast;
}

SCProgramInstance.prototype.exec = function () {
  return this.accept(this.ast);
};

SCProgramInstance.prototype.accept = function (node) {
  var visitor = this.visitors[node.type];

  if (visitor) {
    return this.visitors[node.type].apply(this, arguments); // try {
    //
    // } catch (e) {
    //     console.error(e, node)
    // }
  } else {
    throw {
      message: 'Can not handle ',
      node: node
    };
  }
};

SCProgramInstance.prototype.getRefOf = function (name) {
  return this.topScope.findRef(name);
};

SCProgramInstance.prototype.isFunctionReturned = function () {
  var topStack = this.stack[this.stack.length - 1];

  if (topStack.isFunctionReturned) {
    return topStack.isFunctionReturned();
  }

  return false;
};

SCProgramInstance.prototype.functionReturn = function (res) {
  var topStack = this.stack[this.stack.length - 1];

  if (topStack.functionReturn) {
    return topStack.functionReturn(res);
  }
};

SCProgramInstance.prototype.isLoopBroken = function () {
  var topStack = this.stack[this.stack.length - 1];

  if (topStack.loop && topStack.loop.length > 0) {
    // console.log(topStack.loop[topStack.loop.length - 1].isBroken());
    return topStack.loop[topStack.loop.length - 1].isBroken();
  }

  return false;
};

SCProgramInstance.prototype.loopPush = function (holder) {
  var topStack = this.stack[this.stack.length - 1];
  topStack.loop = topStack.loop || [];
  topStack.loop.push(holder);
};

SCProgramInstance.prototype.loopPop = function () {
  var topStack = this.stack[this.stack.length - 1];
  topStack.loop.pop();
};

SCProgramInstance.prototype.loopBreak = function () {
  var topStack = this.stack[this.stack.length - 1];
  topStack.loop[topStack.loop.length - 1].break();
};

SCProgramInstance.prototype.visitors = {
  Program: function Program(node) {
    var _this2 = this;

    var i = 0;
    var statements = node.body;
    var returnWith;
    var res = new Promise(function (rs) {
      return returnWith = rs;
    });

    var runStep = function runStep() {
      var statement;
      var sResult;

      while (i < statements.length) {
        statement = statements[i++];
        sResult = _this2.accept(statement);

        if (sResult && sResult.then) {
          sResult.then(runStep);
          return;
        }
      }

      returnWith(0);
    };

    runStep();
    return res;
  },
  BooleanLiteral: function BooleanLiteral(node) {
    return node.value;
  },
  BlockStatement: function BlockStatement(node) {
    var _this3 = this;

    var i = 0;
    var statements = node.body;
    var returnWith;
    var resolved = false;
    var result = undefined;
    var sync = new Promise(function (rs) {
      returnWith = function returnWith(res) {
        resolved = true;
        result = res;
        rs(res);
      };
    });

    var runStep = function runStep() {
      var statement;
      var sResult;

      while (i < statements.length && !_this3.isFunctionReturned() && !_this3.isLoopBroken()) {
        statement = statements[i++];
        sResult = _this3.accept(statement);

        if (sResult && sResult.then) {
          sResult.then(runStep);
          return;
        }
      }

      returnWith(0);
    };

    runStep();

    if (resolved) {
      return this.result;
    } else return sync;
  },
  ExpressionStatement: function ExpressionStatement(node) {
    return this.accept(node.expression);
  },
  VariableDeclaration: function VariableDeclaration(node) {
    var _this4 = this;

    var initValue = null;

    if (node.init) {
      initValue = this.accept(node.init);
    }

    if (initValue && initValue.then) {
      return initValue.then(function (result) {
        _this4.topScope.declareVar(node.id.name, result);
      });
    } else {
      this.topScope.declareVar(node.id.name, initValue);
    }
  },
  ArrayExpression: function ArrayExpression(node) {
    var _this5 = this;

    var res = [];
    var resolved = false;
    var resolve;
    var sync = new Promise(function (rs) {
      resolve = function resolve() {
        resolved = true;
        rs(res);
      };
    });
    var elements = node.elements;
    var i = 0;

    var doStep = function doStep() {
      var eResult;

      while (i < elements.length) {
        eResult = _this5.accept(elements[i++], 'const');

        if (eResult && eResult.then) {
          eResult.then(function (item) {
            res.push(item);
            doStep();
          });
          return;
        } else {
          res.push(eResult);
        }
      }

      resolve();
    };

    doStep();

    if (resolved) {
      return res;
    } else {
      return sync;
    }
  },
  ForCountStatement: function ForCountStatement(node) {
    var _this6 = this;

    var idRef = this.accept(node.for, 'ref');
    var from = this.accept(node.from, 'const');
    var to = this.accept(node.to, 'const');
    var result;
    var resolved = false;
    var resolveWith;
    var sync = new Promise(function (rs) {
      resolveWith = function resolveWith(res) {
        result = res;
        resolved = true;
        rs(res);
      };
    });
    var i = from;

    var runStep = function runStep() {
      while (i <= to) {
        idRef.set(i);
        ++i;

        var stResult = _this6.accept(node.body);

        if (stResult && stResult.then) {
          stResult.then(runStep);
          return;
        }
      }

      resolveWith(0);
    };

    runStep();

    if (resolved) {
      return result;
    } else {
      return sync;
    }
  },
  WhileStatement: function WhileStatement(node) {
    var _this7 = this;

    var resolved = false;
    var resolve;
    var sync = new Promise(function (rs) {
      resolve = function resolve() {
        resolved = true;
        rs(undefined);
      };
    });
    this.loopPush({
      break: function _break() {
        resolved = true;
      },
      isBroken: function isBroken() {
        return resolved;
      }
    });
    var state = 0;

    var doStep = function doStep() {
      var sResult;

      while (!resolved) {
        if (_this7.isFunctionReturned()) {
          resolve();
          return;
        }

        if (state === 0) {
          sResult = _this7.accept(node.test, 'const');
          state = 1;
        } else {
          sResult = _this7.accept(node.body);
          state = 0;
        }

        if (sResult && typeof sResult.then === "function") {
          sResult.then(function (sResult) {
            if (state === 0 || sResult) {
              doStep();
            } else {
              resolve();
            }
          });
          return;
        } else {
          if (state === 1 && !sResult) {
            resolve();
          }
        }
      }
    };

    doStep();

    if (resolved) {
      this.loopPop();
      return undefined;
    } else {
      return sync.then(function () {
        return _this7.loopPop();
      });
    }
  },
  DoWhileStatement: function DoWhileStatement(node) {
    var _this8 = this;

    var resolved = false;
    var resolve;
    var sync = new Promise(function (rs) {
      resolve = function resolve() {
        resolved = true;
        rs(undefined);
      };
    });
    var state = 1;

    var doStep = function doStep() {
      var sResult;

      while (!resolved) {
        if (state === 0) {
          sResult = _this8.accept(node.test, 'const');
          state = 1;
        } else {
          sResult = _this8.accept(node.body);
          state = 0;
        }

        if (sResult && typeof sResult.then === "function") {
          sResult.then(function (sResult) {
            if (state === 0 || sResult) {
              doStep();
            } else {
              resolve();
            }
          });
          return;
        } else {
          if (state === 1 && !sResult) {
            resolve();
          }
        }
      }
    };

    doStep();

    if (resolved) {
      return undefined;
    } else {
      return sync;
    }
  },
  AssignStatement: function AssignStatement(node) {
    var leftRef = this.accept(node.left, 'ref');
    var right = this.accept(node.right, 'const');
    leftRef.set(right);
  },
  IfStatement: function IfStatement(node) {
    var _this9 = this;

    var test = this.accept(node.test);

    if (test && typeof test.then === 'function') {
      return test.then(function (test) {
        if (test) {
          return _this9.accept(node.consequent);
        } else if (node.alternate) {
          return _this9.accept(node.alternate);
        }
      });
    } else {
      if (test) {
        return this.accept(node.consequent);
      } else if (node.alternate) {
        return this.accept(node.alternate);
      }
    }
  },
  // CallExpression: function (node){
  //     var funcRef;
  //     var object = null;
  //     var func = null;
  //     if (node.callee.type === 'Identifier'){
  //         funcRef = this.topScope.get(node.callee.name);
  //     }
  //     else {
  //         console.log(node.callee)
  //     }
  //
  //Vả
  // },
  NullLiteral: function NullLiteral(node) {
    return null;
  },
  NumericLiteral: function NumericLiteral(node) {
    return node.value;
  },
  StringLiteral: function StringLiteral(node) {
    return node.value;
  },
  BinaryExpression: function BinaryExpression(node) {
    var leftValue = this.accept(node.left, 'const');
    var rightValue = this.accept(node.right, 'const');
    var sync = [];

    if (leftValue && leftValue.then) {
      sync.push(leftValue);
      leftValue.then(function (result) {
        return leftValue = result;
      });
    }

    if (rightValue && rightValue.then) {
      sync.push(rightValue);
      rightValue.then(function (result) {
        return rightValue = result;
      });
    }

    if (sync.length === 0) {
      return SCLang_SCOperatorExecutor.executeBinaryOperator(node.operator.content, leftValue, rightValue);
    } else {
      return Promise.all(sync).then(function (u) {
        return SCLang_SCOperatorExecutor.executeBinaryOperator(node.operator.content, leftValue, rightValue);
      });
    }
  },
  UnaryExpression: function UnaryExpression(node) {
    var arg = this.accept(node.argument, 'const');

    if (arg && arg.then) {
      return arg.then(function (value) {
        return SCLang_SCOperatorExecutor.executeUnaryOperator(node.operator.content, value);
      });
    } else {
      return SCLang_SCOperatorExecutor.executeUnaryOperator(node.operator.content, arg);
    }
  },
  Identifier: function Identifier(node, type) {
    var ref;

    if (type === 'const') {
      ref = this.getRefOf(node.name);

      if (ref) {
        return ref.get();
      } else {
        throw {
          type: "NotDeclare",
          name: node.name
        };
      }
    } else if (type === 'ref') {
      ref = this.getRefOf(node.name);

      if (ref) {
        return ref;
      } else {
        throw {
          type: "NotDeclare",
          name: node.name
        };
      }
    }

    return node.name;
  },
  CallExpression: function CallExpression(node) {
    var _this10 = this;

    var calleeFunction;
    var object = null;
    var ref;

    if (node.callee.type === "Identifier") {
      ref = this.getRefOf(node.callee.name);
      calleeFunction = ref.get();
    } else if (node.callee.type === 'MemberExpression') {
      ref = this.accept(node.callee);
      calleeFunction = ref.get();
      object = ref.object;
    }

    var argumentValues = node.arguments.map(function (exp) {
      return _this10.accept(exp, 'const');
    });
    var sync = [];
    argumentValues.forEach(function (arg, i) {
      if (arg && arg.then) {
        sync.push(arg.then(function (result) {
          argumentValues[i] = result;
        }));
      }
    });

    if (sync.length > 0) {
      return Promise.all(sync).then(function () {
        return calleeFunction.apply(object, argumentValues);
      });
    } else return calleeFunction.apply(object, argumentValues);
  },
  NewExpression: function NewExpression(node) {
    var _this11 = this;

    var calleeFunction;
    var ref;

    if (node.callee.type === "Identifier") {
      ref = this.getRefOf(node.callee.name);
      calleeFunction = ref.get();
    } else if (node.callee.type === 'MemberExpression') {
      ref = this.accept(node.callee);
      calleeFunction = ref.get();
    }

    var argumentValues = node.arguments.map(function (exp) {
      return _this11.accept(exp, 'const');
    });
    var code = "return new clazz(".concat(argumentValues.map(function (u, i) {
      return "args[".concat(i, "]");
    }).join(', '), ");");
    var f = new Function('clazz', 'args', code);
    return f(calleeFunction, argumentValues);
  },
  MemberExpression: function MemberExpression(node, type) {
    var object = this.accept(node.object, 'const');
    var key;

    if (node.property.type === 'Identifier' && !node.computed) {
      key = node.property.name;
    } else {
      key = this.accept(node.property, 'const');
    }

    if (key && key.then) {
      return key.then(function (key) {
        if (type === 'const') return object[key];
        return {
          set: function set(value) {
            return object[key] = value;
          },
          get: function get() {
            return object[key];
          },
          object: object
        };
      });
    } else {
      if (type === 'const') return object[key];
      return {
        set: function set(value) {
          return object[key] = value;
        },
        get: function get() {
          return object[key];
        },
        object: object
      };
    }
  },
  ObjectProperty: function ObjectProperty(node) {
    var res = {};
    var key = this.accept(node.key);
    var value = this.accept(node.value, 'const');

    if (value && typeof value.then === 'function') {
      return value.then(function (value) {
        res[key] = value;
        return res;
      });
    } else {
      res[key] = value;
    }

    return res;
  },
  ObjectExpression: function ObjectExpression(node) {
    var _this12 = this;

    var res = {};
    var resolved = false;
    var resolve;
    var sync = new Promise(function (rs) {
      resolve = function resolve() {
        resolved = true;
        rs(res);
      };
    });
    var i = 0;
    var properties = node.properties;

    var doStep = function doStep() {
      var pResult;

      while (i < properties.length) {
        pResult = _this12.accept(properties[i++]);

        if (pResult && typeof pResult.then === "function") {
          pResult.then(function (pO) {
            Object.assign(res, pO);
          });
          return;
        } else {
          Object.assign(res, pResult);
        }
      }

      resolve();
    };

    doStep();

    if (resolved) {
      return res;
    } else {
      return sync;
    }
  },
  FunctionDeclaration: function FunctionDeclaration(node) {
    var self = this; //todo: overloading

    var functionName = node.id.name;

    function f() {
      var scope = new SCLang_SCScope(self.topScope);
      var result = undefined;
      var resolved = false;

      var functionReturn = function functionReturn(res) {
        resolved = true;
        result = res;
      };

      var isFunctionReturned = function isFunctionReturned() {
        return resolved;
      };

      self.stack.push({
        scope: scope,
        functionReturn: functionReturn,
        isFunctionReturned: isFunctionReturned
      });
      self.topScope = scope;

      for (var i = 0; i < node.params.length; ++i) {
        scope.declareVar(node.params[i].id.name, arguments[i]);
      }

      scope.declareVar('arguments', arguments);
      var res = self.accept(node.body);

      if (res && typeof res.then === "function") {
        return res.then(function (res) {
          if (self.stack[self.stack.length - 1].scope === scope) {
            self.stack.pop();
            self.topScope = self.stack[self.stack.length - 1].scope;
            return result;
          } else {
            throw new Error('EngineError: Bug in stack!');
          }
        });
      } else {
        if (self.stack[self.stack.length - 1].scope === scope) {
          self.stack.pop();
          self.topScope = self.stack[self.stack.length - 1].scope;
          return result;
        } else {
          throw new Error('EngineError: Bug in stack!');
        }
      }
    }

    var code = "return function ".concat(functionName, "(").concat(node.params.map(function (pr) {
      return pr.id.name || randomIdent(5);
    }).join(','), ") { return f.apply(this, arguments); }");
    var func = new Function('f', code)(f);
    this.topScope.declareVar(functionName, func);
    return func;
  },
  BreakStatement: function BreakStatement(node) {
    this.loopBreak();
  },
  ReturnStatement: function ReturnStatement(node) {
    var _this13 = this;

    var res = undefined;

    if (node.argument) {
      res = this.accept(node.argument, 'const');
    }

    if (res && res.then) {
      res.then(function (res) {
        _this13.functionReturn(res);
      });
    } else {
      this.functionReturn(res);
    }
  }
};
/* harmony default export */ var SCLang_SCProgramInstance = (SCProgramInstance);
// CONCATENATED MODULE: ./src/SCLang/SCCodeGenerator.js



function SCCodeGenerator() {}

SCCodeGenerator.prototype.accept = function (node) {
  if (!node) return '/*TODO*/';
  var visitor = this.visitors[node.type];

  if (visitor) {
    try {
      return this.visitors[node.type].apply(this, arguments);
    } catch (e) {
      console.error(e, node);
    }
  } else {
    return '[' + node.type + ']'; // throw { message: 'Can not handle ', node: node };
  }
};

SCCodeGenerator.prototype.generate = function (ast) {
  return this.accept(ast);
};
/***
 *
 * @type {Object<string, function>}
 */


SCCodeGenerator.prototype.visitors = {
  Program: function Program(node) {
    var _this = this;

    return node.body.map(function (st) {
      return _this.accept(st);
    }).join('\n');
  },
  FunctionDeclaration: function FunctionDeclaration(node) {
    var _this2 = this;

    var bodyCode = this.accept(node.body);
    var argsCode = node.params.map(function (arg) {
      return _this2.accept(arg);
    }).join(', ');
    return "function ".concat(node.id.name, "(").concat(argsCode, ") ").concat(bodyCode);
  },
  ArgumentDeclaration: function ArgumentDeclaration(node) {
    var res = node.id.name;
    var typeText;
    if (node.typeAnnotation) typeText = this.accept(node.typeAnnotation);
    if (typeText && typeText !== 'any') res += ': ' + typeText;
    return res;
  },
  TypeAnnotation: function TypeAnnotation(node) {
    return this.accept(node.typeAnnotation);
  },
  GenericType: function GenericType(node) {
    return this.accept(node.id);
  },
  LinkedType: function LinkedType(node) {
    return 'linktype ' + this.accept(node.address);
  },
  Identifier: function Identifier(node) {
    return node.name;
  },
  VariableDeclaration: function VariableDeclaration(node) {
    var res = 'var ' + node.id.name;
    var typeText;
    if (node.typeAnnotation) typeText = this.accept(node.typeAnnotation);
    if (typeText && typeText !== 'any') res += ': ' + typeText;
    res += ';';
    return res;
  },
  BlockStatement: function BlockStatement(node) {
    var _this3 = this;

    var bodyCode = node.body.map(function (it) {
      return _this3.accept(it);
    }).join('\n');

    if (bodyCode.length > 0) {
      bodyCode = bodyCode.split('\n').map(function (r) {
        return '    ' + r;
      }).join('\n');
    }

    return ['{', bodyCode, '}'].join('\n');
  },
  AssignStatement: function AssignStatement(node) {
    return this.accept(node.left) + ' = ' + this.accept(node.right) + ';';
  },
  BooleanLiteral: function BooleanLiteral(node) {
    return node.value ? 'true' : 'false';
  },
  NullLiteral: function NullLiteral(node) {
    return "null";
  },
  NewExpression: function NewExpression(node) {
    var _this4 = this;

    var res = 'new ';

    if (node.callee.type === 'Identifier' || node.callee.type === 'MemberExpression') {
      res += this.accept(node.callee);
    } else {
      res += '(' + this.accept(node.callee) + ')';
    }

    res += '(';
    res += node.arguments.map(function (arg) {
      return _this4.accept(arg);
    }).join(', ');
    res += ')';
    return res;
  },
  CallExpression: function CallExpression(node) {
    var _this5 = this;

    var res = '';

    if (node.callee.type === 'Identifier' || node.callee.type === 'MemberExpression') {
      res += this.accept(node.callee);
    } else {
      res += '(' + this.accept(node.callee) + ')';
    }

    res += '(';
    res += node.arguments.map(function (arg) {
      return _this5.accept(arg);
    }).join(', ');
    res += ')';
    return res;
  },
  MemberExpression: function MemberExpression(node) {
    var res = '';

    if (node.object.type === 'Identifier' || node.object.type === 'MemberExpression') {
      res += this.accept(node.object);
    } else {
      res += '(' + this.accept(node.object) + ')';
    }

    if (node.computed) {
      res += '[';
      res += this.accept(node.property);
      res += ']';
    } else {
      res += '.';
      res += this.accept(node.property);
    }

    return res;
  },
  IfStatement: function IfStatement(node) {
    var res = 'if (';
    res += this.accept(node.test);
    res += ') ';
    res += this.accept(node.consequent);

    if (node.alternate) {
      res += '\nelse ';
      res += this.accept(node.alternate);
    }

    return res;
  },
  WhileStatement: function WhileStatement(node) {
    var res = 'while (';
    res += this.accept(node.test);
    res += ') ';
    res += this.accept(node.body);
    return res;
  },
  ForCountStatement: function ForCountStatement(node) {
    var res = ['for', this.accept(node.for), 'from', this.accept(node.from), 'to', this.accept(node.to)].join(' ') + ' ';
    res += this.accept(node.body);
    return res;
  },
  BreakStatement: function BreakStatement() {
    return 'break;';
  },
  ReturnStatement: function ReturnStatement(node) {
    if (node.argument) return 'return ' + this.accept(node.argument) + ';';
    return 'return;';
  },
  BinaryExpression: function BinaryExpression(node) {
    var callOrderOf = function callOrderOf(snode) {
      if (!snode) return 100;

      if (snode.type === 'BinaryExpression') {
        return Math.max(SCGrammar.operatorOrder[snode.operator.content], callOrderOf(snode.right), callOrderOf(snode.right));
      } else if (snode.type === 'UnaryExpression') return -1;else return -2;
    };

    var operatorContent = node.operator.content;
    var cOrder = SCGrammar.operatorOrder[operatorContent];
    var left = this.accept(node.left);
    var right = this.accept(node.right);
    var leftOrder = callOrderOf(node.left);
    var rightOrder = callOrderOf(node.right);
    if (leftOrder > cOrder) left = '(' + left + ')';
    if (rightOrder >= cOrder) right = '(' + right + ')';
    return [left, operatorContent, right].join(' ');
  },
  UnaryExpression: function UnaryExpression(node) {
    var res = node.operator.content;

    if (node.argument && node.argument.type === 'BinaryExpression') {
      res += '(' + this.accept(node.argument) + ')';
    } else {
      res += this.accept(node.argument);
    }

    return res;
  },
  ExpressionStatement: function ExpressionStatement(node) {
    return this.accept(node.expression) + ';';
  },
  NumericLiteral: function NumericLiteral(node) {
    return node.value;
  },
  StringLiteral: function StringLiteral(node) {
    return JSON.stringify(node.value);
  },
  ArrayExpression: function ArrayExpression(node) {
    var _this6 = this;

    var res = '[';
    var elementTexts = node.elements.map(function (arg) {
      return _this6.accept(arg);
    });
    var needWrap = elementTexts.some(function (et) {
      return et.length > 60;
    });

    if (needWrap) {
      res += '\n';
      res += elementTexts.join(',\n').split('\n').map(function (t) {
        return '    ' + t;
      }).join('\n');
      res += '\n';
    } else {
      res += elementTexts.join(', ');
    }

    res += ']';
    return res;
  },
  ObjectProperty: function ObjectProperty(node) {
    return this.accept(node.key) + ': ' + this.accept(node.value);
  },
  ObjectExpression: function ObjectExpression(node) {
    var _this7 = this;

    var res = '{';
    var propertyTexts = node.properties.map(function (arg) {
      return _this7.accept(arg);
    });
    var needWrap = propertyTexts.some(function (et) {
      return et.length > 60;
    });

    if (needWrap) {
      res += '\n';
      res += propertyTexts.join(',\n').split('\n').map(function (t) {
        return '    ' + t;
      }).join('\n');
      res += '\n';
    } else {
      res += propertyTexts.join(', ');
    }

    res += '}';
    return res;
  }
};
/* harmony default export */ var SCLang_SCCodeGenerator = (SCCodeGenerator());
function generateSCCode(ast) {
  var generator = new SCCodeGenerator();
  return generator.generate(ast);
}
// CONCATENATED MODULE: ./src/Network/XLoader.js
var XLoader = {};
function loadScript(url, onComplete, onError) {
  return new Promise(function (resolve, reject) {
    var script = document.createElement("script");
    script.type = "text/javascript";

    if (script.readyState) {
      //IE
      script.onreadystatechange = function () {
        if (script.readyState === "loaded" || script.readyState === "complete") {
          script.onreadystatechange = null;
          onComplete && onComplete();
          resolve();
        }
      };
    } else {
      //Others
      script.onload = function () {
        script.onload = null;
        script.onerror = null;
        onComplete && onComplete();
        resolve();
      };

      script.onerror = function () {
        script.onerror = null;
        script.onload = null;
        script.remove();
        onError && onError();
        reject();
      };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  });
}
XLoader.loadScript = loadScript;
function isImageURLAllowCrossOrigin(url) {
  return new Promise(function (rs, rj) {
    url = url || '';

    if (url.startsWith('data:') || url.startsWith('blob:')) {
      rs(true);
      return;
    }

    var img = new Image(); // img.crossOrigin = "anonymous";

    img.onload = function () {
      var canvas = document.createElement('canvas');
      canvas.width = 10;
      canvas.height = 10;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(this, 0, 0);

      try {
        ctx.getImageData(0, 0, 10, 10);
        rs(true);
      } catch (err) {
        rs(false);
      }
    };

    img.onerror = function (event) {
      rj(event.error || event);
    };

    img.src = url;
  });
}
/* harmony default export */ var Network_XLoader = (XLoader);
// CONCATENATED MODULE: ./src/Print/PaperPrinter.js







var fontIdOf = function fontIdOf(fontName) {
  if (fontName.toLowerCase().indexOf('arial') >= 0) return 'arial';
  if (fontName.toLowerCase().indexOf('times') >= 0) return 'times';
  if (fontName === "Material Design Icons") return 'MDI_6_7_96';
  return fontName;
};

var P2D = 72 / 96;

var PaperPrinter_color2RGB255 = function color2RGB255(color) {
  try {
    color = Color["a" /* default */].parse(color + '');
    return color.rgba.slice(0, 3).map(function (x) {
      return x * 255 >> 0;
    });
  } catch (e) {
    return null;
  }
};

function PaperPrinter(opt) {
  this.opt = Object.assign({
    size: 'a4',
    margin: {
      top: 57,
      left: 57
    }
  }, opt);
  this.objects = [];
  this.processInfo = {};
}

PaperPrinter.prototype.share = {
  jsPDFUrl: 'https://absol.cf/vendor/jspdf.umd.js',
  jsPDF: null,
  readySync: null,
  fonts: [{
    url: 'https://absol.cf/vendor/fonts/arial.ttf',
    fileName: 'arial.ttf',
    name: 'arial',
    style: 'regular'
  }, {
    url: 'https://absol.cf/vendor/fonts/arialbd.ttf',
    fileName: 'arialbd.ttf',
    name: 'arial',
    style: 'bold'
  }, {
    url: 'https://absol.cf/vendor/fonts/ariali.ttf',
    fileName: 'ariali.ttf',
    name: 'arial',
    style: 'italic'
  }, {
    url: 'https://absol.cf/vendor/fonts/arialbi.ttf',
    fileName: 'arialbi.ttf',
    name: 'arial',
    style: 'bold_italic'
  }, {
    url: 'https://absol.cf/vendor/fonts/times.ttf',
    fileName: 'times.ttf',
    name: 'times',
    style: 'regular'
  }, {
    url: 'https://absol.cf/vendor/fonts/timesbd.ttf',
    fileName: 'timesbd.ttf',
    name: 'times',
    style: 'bold'
  }, {
    url: 'https://absol.cf/vendor/fonts/timesi.ttf',
    fileName: 'timesi.ttf',
    name: 'times',
    style: 'italic'
  }, {
    url: 'https://absol.cf/vendor/fonts/timesbi.ttf',
    fileName: 'timesbi.ttf',
    name: 'times',
    style: 'bold_italic'
  }]
};

PaperPrinter.prototype.ready = function () {
  var _this = this;

  var sync;

  if (!this.share.readySync) {
    sync = this.share.fonts.map(function (font) {
      return fetch(font.url).then(function (res) {
        return res.blob();
      }).then(function (blob) {
        var reader = new window.FileReader();
        return new Promise(function (rs) {
          reader.onload = function () {
            rs(this.result);
          };

          reader.readAsDataURL(blob);
        });
      }).then(function (b64Url) {
        var idx = b64Url.indexOf('base64,');
        return b64Url.substring(idx + 'base64,'.length);
      }).then(function (b64) {
        font.content = b64;
      });
    });

    if (window.jsPDF) {
      this.share.jsPDF = window.jsPDF;
    } else {
      sync.push(loadScript(this.share.jsPDFUrl).then(function () {
        _this.share.jsPDF = window.jsPDF;
      }));
    }

    this.share.readySync = Promise.all(sync);
  }

  return this.share.readySync;
};
/***
 *
 * @param {string} text
 * @param {Vec2 | Rectangle} pos
 * @param {Object=}style
 */


PaperPrinter.prototype.text = function (text, pos, style) {
  this.objects.push({
    type: 'text',
    pos: pos,
    text: text,
    style: style || {}
  });
  return this;
};
/***
 *
 * @param {Rectangle}rect
 * @param {Object=}style
 */


PaperPrinter.prototype.rect = function (rect, style) {
  this.objects.push({
    type: 'rect',
    rect: rect,
    style: style || {}
  });
};
/***
 *
 * @param {HTMLCanvasElement|AElement |Image} image
 * @param {Rectangle}rect
 * @param {Object=}style
 */


PaperPrinter.prototype.image = function (image, rect, style) {
  this.objects.push({
    type: 'image',
    rect: rect,
    style: style || {},
    image: image
  });
  return this;
};

PaperPrinter.prototype.boundOf = function (objectData) {
  return this.measures[objectData.type](objectData);
};

PaperPrinter.prototype.exportAsPDF = function (onProcess) {
  var _this2 = this;

  var processInfo = copyJSVariable(this.processInfo);
  processInfo.pdf = {
    all: this.objects.length,
    done: 0
  };
  processInfo.state = 'LOAD_LIB';

  processInfo.onProcess = function () {
    onProcess && onProcess(processInfo);
  };

  return this.ready().then(function () {
    processInfo.state = 'RENDER_PDF';
    var doc = new jspdf.jsPDF({
      orientation: 'p',
      unit: 'px',
      format: 'a4',
      putOnlyUsedFonts: true,
      floatPrecision: 16,
      dpi: 300,
      hotfixes: ["px_scaling"]
    });

    _this2.share.fonts.forEach(function (font) {
      doc.addFileToVFS(font.fileName, font.content);
      doc.addFont(font.fileName, font.name, font.style);
    });

    var objectHolders = _this2.objects.map(function (o, i) {
      var bound = _this2.boundOf(o);

      return {
        i: i,
        o: o,
        y: bound.y,
        height: bound.height
      };
    });

    objectHolders.sort(function (a, b) {
      return a.y - b.y;
    });
    var pageContentWidth = 794 - 57 * 2;
    var pageContentHeight = 1123 - 57 * 2;
    var pages = objectHolders.reduce(function (ac, cr) {
      var page = ac[ac.length - 1];

      if (cr.height > pageContentHeight) {
        page.holders.push(cr);
      } else {
        if (cr.y + cr.height - page.y > pageContentHeight) {
          page = {
            y: cr.y,
            holders: [cr]
          };
          ac.push(page);
        } else {
          page.holders.push(cr);
        }
      }

      return ac;
    }, [{
      holders: [],
      y: 0
    }]);
    var sync = Promise.resolve();
    pages.forEach(function (page) {
      page.holders.sort(function (a, b) {
        return a.i - b.i;
      });
      page.objects = page.holders.map(function (h) {
        return h.o;
      });
    });
    pages.forEach(function (page, i) {
      sync = sync.then(function () {
        if (i > 0) {
          doc.addPage();
        }

        doc.setPage(i + 1);
        page.O = new Math_Vec2(_this2.opt.margin.left, _this2.opt.margin.top - page.y);
        var syn2 = Promise.resolve();
        page.objects.forEach(function (obj) {
          var type = obj.type;
          syn2 = syn2.then(function () {
            var res = _this2.pdfHandlers[type](page, doc, obj);

            processInfo.pdf.done++;
            processInfo.onProcess();
            return res;
          });
        });
        syn2 = syn2.then(function () {
          doc.setTextColor(0, 0, 0);
          doc.setFontSize(14 * P2D);
          doc.setFont('arial', 'regular');
          doc.text(i + 1 + '/' + pages.length, 794 - 20, 1123 - 20, {
            align: 'right'
          });
        });
        return syn2;
      });
    }); //width: 794px;margin 57
    //     /*height: 1056px;*/

    return sync.then(function () {
      return doc;
    });
  });
};

PaperPrinter.prototype.pdfHandlers = {
  text: function text(context, doc, data) {
    var fontFamily = data.style.fontFamily;
    var lineHeight = data.style.lineHeight || 1.2;
    var color = PaperPrinter_color2RGB255(data.style.color) || [0, 0, 0];
    doc.setTextColor(color[0], color[1], color[2]);
    var fontSize = data.style.fontSize || 14;
    var textPos = data.pos.A().add(context.O);
    doc.setLineHeightFactor(lineHeight);
    doc.setFontSize(fontSize * P2D);
    doc.setFont(fontIdOf(fontFamily), data.style.fontStyle);
    var style = {
      baseline: 'top',
      maxWidth: data.pos.width
    };

    if (data.style.align) {
      //todo: check align
      style.align = {
        start: 'left',
        end: 'right',
        center: 'center'
      }[data.style.align] || 'left';
    }

    doc.text(data.text, textPos.x, textPos.y + fontSize * (lineHeight - 1) / 2, style);
  },
  rect: function rect(context, doc, data) {
    var fillColor = null;
    var strokeColor = null;
    var strokeWidth = data.style.strokeWidth || 1;
    var rounded = data.style.rounded;
    if (typeof rounded === "number") rounded = [rounded, rounded];

    if (data.style.fill) {
      fillColor = PaperPrinter_color2RGB255(data.style.fill);
    }

    if (data.style.stroke) {
      strokeColor = PaperPrinter_color2RGB255(data.style.stroke);
    }

    if (fillColor) doc.setFillColor(fillColor[0], fillColor[1], fillColor[2]);

    if (strokeColor) {
      doc.setLineWidth(strokeWidth);
      doc.setDrawColor(strokeColor[0], strokeColor[1], strokeColor[2]);
    }

    var flat = 'F';
    if (strokeColor && fillColor) flat = 'FD';else if (strokeColor) flat = 'S';else if (fillColor) flat = 'F';else return;
    var O = context.O;
    var A = data.rect.A().add(O);

    if (rounded) {
      doc.roundedRect(A.x, A.y, data.rect.width, data.rect.height, rounded[0], rounded[1], flat);
    } else {
      doc.rect(A.x, A.y, data.rect.width, data.rect.height, flat);
    }
  },
  image: function image(context, doc, data) {
    var handleImage = function handleImage(image) {
      if (!image) return;
      var rect = data.rect.clone();
      rect.x += context.O.x;
      rect.y += context.O.y;
      doc.addImage(image, 'PNG', rect.x, rect.y, rect.width, rect.height);
    };

    if (data.image.then) {
      return data.image.then(handleImage).catch(function (err) {});
    } else return handleImage(data.image);
  }
};
PaperPrinter.prototype.measures = {
  rect: function rect(data) {
    return data.rect;
  },
  text: function text(data) {
    return data.pos;
  },
  image: function image(data) {
    return data.rect;
  }
};
/* harmony default export */ var Print_PaperPrinter = (PaperPrinter);
// CONCATENATED MODULE: ./src/Print/PrintSerialHandlers.js







var _ = Dom["b" /* default */].ShareInstance._;
var $ = Dom["b" /* default */].ShareInstance.$;
var $$ = Dom["b" /* default */].ShareInstance.$$;
function computePrintAttr(elt) {
  var style = getComputedStyle(elt);
  var fontSize = elt.getFontSize();
  var lineHeight = style.getPropertyValue('line-height');
  if (lineHeight === 'normal') lineHeight = 1.2;else lineHeight = parseFloat(lineHeight.replace('px', '')) / fontSize;
  if (!isNaN(lineHeight)) lineHeight = 1.2;
  var fontWeight = style.getPropertyValue('font-weight');
  var fontStyle = fontWeight === '400' ? 'regular' : 'bold';
  var dirs = ['top', 'right', 'bottom', 'left'];
  var paddingStyle = dirs.map(function (dir) {
    return Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('padding-' + dir));
  });
  var borderWidthStyle = dirs.map(function (dir) {
    return Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('border-' + dir + '-width'));
  });
  var contentBound = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
  contentBound.x += paddingStyle[3].value + borderWidthStyle[3].value;
  contentBound.y += paddingStyle[0].value + borderWidthStyle[0].value;
  contentBound.width += paddingStyle[1].value + borderWidthStyle[1].value + paddingStyle[3].value + borderWidthStyle[3].value;
  contentBound.height += paddingStyle[2].value + borderWidthStyle[2].value + paddingStyle[0].value + borderWidthStyle[0].value;
  return {
    contentBound: contentBound,
    whiteSpace: style.getPropertyValue('white-space'),
    style: {
      color: style.getPropertyValue('color'),
      fontFamily: style.getPropertyValue('font-family'),
      fontStyle: fontStyle,
      lineHeight: lineHeight,
      fontSize: fontSize,
      align: style.getPropertyValue('text-align')
    }
  };
}
/***
 *
 * @type {PSHandler[]}
 */

var PrintSerialHandlers = [];
PrintSerialHandlers.push({
  id: 'TextNode',
  match: function match(elt) {
    return elt.nodeType === Node.TEXT_NODE;
  },
  exec: function exec(printer, text, scope, stack, accept) {
    var O = printer.O;
    var elt = text.parentElement;
    var bound = Math_Rectangle.fromClientRect(Object(Dom["e" /* getTextNodeBound */])(text));
    if (bound.width === 0) return;
    var printAttr = computePrintAttr(elt);
    var txt = text.data;
    var y = -Infinity;
    var c;
    var range;
    var parts = [];
    var cPart;
    var j;
    var delta = printAttr.style.lineHeight * printAttr.style.fontSize / 3;
    var rect;
    var i = 0;

    while (i < txt.length) {
      c = txt[i];

      if (!c.match(/[\s\n]/)) {
        j = i + 1;

        while (j < txt.length) {
          c = txt[j];

          if (c.match(/[\s\n]/)) {
            break;
          } else {
            ++j;
          }
        }

        range = document.createRange();
        range.setStart(text, i);
        range.setEnd(text, j);
        rect = Math_Rectangle.fromClientRect(range.getBoundingClientRect());

        if (Math.abs(rect.y - y) < delta) {
          cPart.end = j;
          cPart.rect = cPart.rect.merge(rect);
        } else {
          cPart = {
            start: i,
            end: j,
            rect: rect
          };
          y = rect.y;
          parts.push(cPart);
        }

        i = j;
      } else {
        ++i;
      }
    }

    parts.forEach(function (part) {
      rect = part.rect;
      rect.x -= O.x;
      rect.y -= O.y;
      rect.width += printAttr.style.fontSize * 1000;
      var lineTxt = txt.substring(part.start, part.end);

      if (printAttr.whiteSpace === 'normal') {
        lineTxt = lineTxt.replace(/[\s\n]+/g, ' ');
      }

      printer.text(lineTxt, rect, printAttr.style);
    });
  }
});
PrintSerialHandlers.push({
  id: 'Border',
  match: function match(elt, scope, stack) {
    var style = getComputedStyle(elt);
    var borderColor = style.getPropertyValue('border-color');
    var borderStyle = style.getPropertyValue('border-style');
    var borderWidth = style.getPropertyValue('border-width');
    var borderRadius = style.getPropertyValue('border-radius');
    if (borderStyle === 'none' || borderWidth === '0px') return false;
    scope.declare('borderStyle', {
      width: parseFloat(borderWidth.replace('px', '')),
      radius: Object(JSX_attribute["parseMeasureValue"])(borderRadius),
      color: borderColor
    });
    return true;
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    var borderStyle = scope.get('borderStyle');
    var bound = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
    var rect = bound.clone();
    var strokeWidth = borderStyle.width;
    rect.x -= printer.O.x - strokeWidth / 2;
    rect.y -= printer.O.y - strokeWidth / 2;
    rect.width -= strokeWidth;
    rect.height -= strokeWidth;
    var radius = borderStyle.radius;
    var rounded;

    if (radius) {
      switch (radius.unit) {
        case '%':
          rounded = [radius.value * rect.width / 100, radius.value * rect.height / 100];
          break;

        case 'px':
          rounded = radius.value;
          break;
      }
    }

    printer.rect(rect, {
      stroke: borderStyle.color,
      rounded: rounded,
      strokeWidth: strokeWidth
    });
    return true;
  }
});
PrintSerialHandlers.push({
  id: 'BackgroundImage',
  match: function match(elt, scope, stack) {
    return elt.getComputedStyleValue('background-image') !== 'none';
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    var style = getComputedStyle(elt);
    var backgroundSize = style.getPropertyValue('background-size');
    var url = style.getPropertyValue('background-image').trim().replace('url("', '').replace('")', '');
    var rect = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
    rect.x -= printer.O.x;
    rect.y -= printer.O.y;
    var image = isImageURLAllowCrossOrigin(url).then(function (result) {
      /***
       *
       * @type {HTMLCanvasElement}
       */
      var canvas = document.createElement('canvas');
      var width = rect.width;
      var height = rect.height;
      canvas.width = width;
      canvas.height = height;
      var image = new Image();
      image.crossOrigin = 'anonymous';
      image.src = result ? url : 'https://absol.cf/crossdownload.php?file=' + encodeURIComponent(url);
      var ctx = canvas.getContext('2d');
      return new Promise(function (rs) {
        image.onload = function () {
          var scale;
          var nW;
          var nH; //todo: handle more

          switch (backgroundSize) {
            case 'cover':
              scale = Math.max(width / image.naturalWidth, height / image.height);
              nW = image.naturalWidth * scale;
              nH = image.naturalHeight * scale;
              ctx.drawImage(image, 0, 0, nW, nH);
              break;

            case 'auto':
            default:
              ctx.drawImage(image, 0, 0);
          }

          rs(canvas);
        };

        image.onerror = function () {
          console.error('can not load ', image.src);
          rs(null);
        };
      });
    }).catch(function (err) {
      console.error(err);
    });
    printer.image(image, rect);
    return true;
  }
});
PrintSerialHandlers.push({
  id: 'Img',
  match: function match(elt) {
    return elt.tagName && elt.tagName.toLowerCase() === 'img' && elt.src && elt.naturalWidth;
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    var bound = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
    if (bound.width === 0) return;
    var rect = bound.clone();
    rect.x -= printer.O.x;
    rect.y -= printer.O.y;
    printer.image(elt, rect);
  }
});
PrintSerialHandlers.push({
  id: 'Canvas',
  match: function match(elt) {
    return elt.tagName && elt.tagName.toLowerCase() === 'canvas';
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    var bound = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
    if (bound.width === 0) return;
    var rect = bound.clone();
    rect.x -= printer.O.x;
    rect.y -= printer.O.y;
    printer.image(elt, rect);
  }
});
PrintSerialHandlers.push({
  id: 'SVG',
  match: function match(elt) {
    return elt.tagName && elt.tagName.toLowerCase() === 'svg';
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    var bound = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
    if (bound.width === 0) return;
    var rect = bound.clone();
    rect.x -= printer.O.x;
    rect.y -= printer.O.y;
    var res = Svg["a" /* default */].svgToCanvas(elt.__origin__).catch(function (err) {
      console.error(err);
    });
    res.elt = elt;
    printer.image(res, rect);
  }
});
PrintSerialHandlers.push({
  id: 'TextInput',
  match: function match(elt, scope, stack) {
    return elt.tagName === 'INPUT' && (elt.attr('type') === 'text' || elt.attr('type') === 'number');
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    var O = printer.O;
    var style = getComputedStyle(elt);
    var paddingLeft = Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('padding-left'));
    var paddingTop = Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('padding-top'));
    var paddingBottom = Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('padding-bottom'));
    var borderLeftWidth = Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('border-left-width'));
    var borderTopWidth = Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('border-top-width'));
    var borderBottomWidth = Object(JSX_attribute["parseMeasureValue"])(style.getPropertyValue('border-top-width'));
    var rect = Math_Rectangle.fromClientRect(elt.getBoundingClientRect());
    var fontSize = elt.getFontSize();
    var lineHeight = style.getPropertyValue('line-height');
    if (lineHeight === 'normal') lineHeight = 1.2;else lineHeight = parseFloat(lineHeight.replace('px', '')) / fontSize;
    if (!isNaN(lineHeight)) lineHeight = 1.2;
    var fontWeight = style.getPropertyValue('font-weight');
    var fontStyle = fontWeight === '400' ? 'regular' : 'bold';
    rect.width = 700;
    rect.x += borderLeftWidth.value + paddingLeft.value - O.x;
    rect.height -= borderTopWidth.value + borderBottomWidth.value + paddingTop.value + paddingBottom.value;
    rect.y += borderTopWidth.value + paddingTop.value - O.y;
    var centerY = rect.centerPoint().y;
    rect.y = centerY - fontSize * lineHeight / 2;
    rect.height = fontSize * lineHeight;
    printer.text(elt.value, rect, {
      fontFamily: style.getPropertyValue('font-family'),
      fontStyle: fontStyle,
      fontSize: fontSize,
      lineHeight: lineHeight
    });
  }
});
PrintSerialHandlers.push({
  id: '*',
  match: function match() {
    return true;
  },
  exec: function exec(printer, elt, scope, stack, accept) {
    if (elt.getComputedStyleValue('display') === 'none') return;

    if (elt.childNodes) {
      Array.prototype.forEach.call(elt.childNodes, function (child) {
        return accept(child);
      });
    }
  }
});
/* harmony default export */ var Print_PrintSerialHandlers = (PrintSerialHandlers);
// CONCATENATED MODULE: ./src/Print/PrintSerializer.js






/***
 * @typedef {Object} PSHandler
 * @property {string} id
 * @property {function(elt:AElement, scope: VarScope, stack:Array<AElement>):boolean} match
 * @property {function(printer: PaperPrinter,elt:AElement|Text, scope: VarScope, stack:Array<{elt: AElement|Text, scope:VarScope}>, accept: function():void):(boolean|void)} exec - return true if run other handle
 *
 */

/***
 *
 * @constructor
 */

function PrintSerializer() {
  /***
   * @type {Array<PSHandler>}
   */
  this.handlers = this.handlers.slice();
}

PrintSerializer.prototype.handlers = Print_PrintSerialHandlers;
/***
 *
 * @param {PaperPrinter} printer
 * @param {AElement|AElementNS|Text} elt
 * @param {VarScope} scope
 * @param {Array<{elt: AElement|Text, scope:VarScope}>} stack
 */

PrintSerializer.prototype.accept = function (printer, elt, scope, stack) {
  var _this = this;

  if (elt.nodeType === Node.ELEMENT_NODE) Dom["b" /* default */].ShareInstance.$(elt);
  var handler;
  var matched, cont;

  for (var i = 0; (!matched || cont) && i < this.handlers.length; ++i) {
    handler = this.handlers[i];
    matched = handler.match(elt, scope, stack);

    if (matched) {
      cont = handler.exec(printer, elt, scope, stack, function (elt1) {
        _this.accept(printer, elt1, new AppPattern_VarScope(scope), stack.concat([{
          elt: elt,
          scope: scope
        }]));
      });
    }
  }
};

PrintSerializer.prototype.serialize = function (elt, printer, _onProcess) {
  var _this2 = this;

  var sync = [];
  var processInfo = {
    state: 'RENDER_DOM',
    total: {
      all: 0,
      text: 0,
      image: 0
    },
    dom: {
      text: 0,
      image: 0
    },
    onProcess: function onProcess() {
      _onProcess && _onProcess(processInfo);
    }
  };
  printer.processInfo = processInfo;
  var contentChild = Object(Dom["c" /* depthClone */])(elt, function (originElt, copyElt) {
    copyElt.__idx__ = processInfo.total.all;
    copyElt.__origin__ = originElt;
    processInfo.total.all++;
    var parent, fontWeight, style;
    var done = false;

    if (originElt.nodeType === Node.TEXT_NODE) {
      processInfo.total.text++;
      sync.push(new Promise(function (rs) {
        setTimeout(function () {
          parent = originElt.parentElement;

          if (!copyElt.__fontWeight__) {
            style = getComputedStyle(parent);
            fontWeight = parseInt(style.getPropertyValue('font-weight')); //not support other style

            copyElt.__fontWeight__ = fontWeight;

            if (fontWeight <= 400) {
              copyElt.parentElement.style.setProperty('font-weight', 'normal');
            } else if (fontWeight > 400) {
              copyElt.parentElement.style.setProperty('font-weight', 'bold');
            }

            processInfo.dom.text++;
          }

          processInfo.dom.text++;
          rs();
        }, 0);
      }));
    } else if (originElt.tagName && originElt.tagName.toLowerCase() === 'canvas') {
      copyElt.getContext('2d').drawImage(originElt, 0, 0);
    } else if (originElt.tagName === 'IMG' && !originElt.classList.contains('absol-attachhook') && originElt.src) {
      processInfo.total.image++;
      sync.push(isImageURLAllowCrossOrigin(originElt.src).then(function (result) {
        var newElt;

        if (!result) {
          newElt = copyElt.cloneNode();
          newElt.__idx__ = copyElt.__idx__;
          newElt.__origin__ = copyElt.__origin__;
          newElt.src = 'https://absol.cf/crossdownload.php?file=' + encodeURIComponent(originElt.src);
          copyElt.parentElement.replaceChild(newElt, copyElt);
          return Object(Dom["f" /* waitImageLoaded */])(newElt, 10000).then(function () {
            if (!done) {
              processInfo.dom.image++;
              processInfo.onProcess();
              done = true;
            }
          });
        } else {
          return Object(Dom["f" /* waitImageLoaded */])(copyElt, 10000).then(function () {
            if (!done) {
              processInfo.dom.image++;
              processInfo.onProcess();
              done = true;
            }
          });
        }
      }, function (err) {
        console.error(err);

        if (!done) {
          processInfo.dom.image++;
          processInfo.onProcess();
          done = true;
        }
      }));
    } else if (originElt.tagName === 'INPUT') {
      copyElt.value = originElt.value;
    }
  });

  var content = Dom["b" /* default */].ShareInstance._({
    style: {
      width: 794 - 57 * 2 + 'px',
      //WIDTH: 1123 - 57*2
      display: 'inline-block',
      overflow: 'visible'
    },
    class: 'as-printer-content',
    child: contentChild
  });

  var scroller = Dom["b" /* default */].ShareInstance._({
    class: 'as-printer',
    style: {
      'text-size-adjust': 'none',
      '-webkit-text-size-adjust': 'none',
      '-moz-text-size-adjust': 'none',
      '-ms-text-size-adjust': 'none',
      position: 'fixed',
      top: '10px',
      bottom: '10px',
      left: '10px',
      overflow: 'scroll',
      width: '794px',
      // maxWidth: '90vw',
      background: 'white',
      // zIndex: 1000,
      opacity: '0',
      zIndex: '-100',
      visibility: 'hidden',
      pointerEvents: 'none'
    },
    child: content
  }).addTo(document.body);

  sync.push(new Promise(function (rs) {
    setTimeout(rs, 50);
  }));
  return Promise.all(sync).then(function () {
    processInfo.state = "SERIALIZE";
    processInfo.onProcess();
    printer.O = Math_Rectangle.fromClientRect(content.getBoundingClientRect()).A();

    _this2.accept(printer, content, new AppPattern_VarScope(), []);
  }).then(function () {
    scroller.remove();
    processInfo.onProcess = noop["a" /* default */];
    return printer;
  });
};
/***
 *
 * @param {PSHandler} handler
 * @returns {this}
 */


PrintSerializer.prototype.addHandler = function (handler) {
  this.handlers.unshift(handler);
  return this;
};
/***
 *
 * @param {PSHandler} handler
 * @param {string} bf
 * @returns {this}
 */


PrintSerializer.prototype.addHandlerBefore = function (handler, bf) {
  var idx = this.handlers.findIndex(function (value) {
    return value.id === bf;
  });

  if (idx >= 0) {
    this.handlers.splice(idx, 0, handler);
  }

  return this;
};
/***
 *
 * @param {PSHandler} handler
 * @param {string} at
 * @returns {this}
 */


PrintSerializer.prototype.addHandlerAfter = function (handler, at) {
  var idx = this.handlers.findIndex(function (value) {
    return value.id === at;
  });

  if (idx >= 0) {
    this.handlers.splice(idx + 1, 0, handler);
  }

  return this;
};
/***
 *
 * @param {Array<PSHandler>} handlers
 * @returns {this}
 */


PrintSerializer.prototype.addHandlers = function (handlers) {
  this.handlers.unshift.apply(this.handlers, handlers);
  return this;
};
/***
 *
 * @param {string} id
 * @returns {this}
 */


PrintSerializer.prototype.removeHandler = function (id) {
  var idx = this.handlers.findIndex(function (value) {
    return value.id === id;
  });

  if (idx >= 0) {
    this.handlers.splice(idx, 1);
  }

  return this;
};
/***
 *
 * @param {string} id
 * @returns {PSHandler|null}
 */


PrintSerializer.prototype.getHandler = function (id) {
  var idx = this.handlers.findIndex(function (value) {
    return value.id === id;
  });

  if (idx >= 0) {
    return this.handlers[idx];
  }

  return null;
};

/* harmony default export */ var Print_PrintSerializer = (PrintSerializer);
// CONCATENATED MODULE: ./src/Print/printer.js




var ShareSerializer = new Print_PrintSerializer();
/***
 *
 * @param elt
 * @param fileName
 * @param {function(processInfo):void=} onProcess
 * @returns {Promise<*>}
 */

function downloadAsPDF(elt, fileName, onProcess) {
  elt = Dom["b" /* default */].ShareInstance.$(elt);
  var serializer = ShareSerializer;
  var printer = new Print_PaperPrinter();
  return serializer.serialize(elt, printer, onProcess).then(function (printer) {
    return printer.exportAsPDF(onProcess);
  }).then(function (doc) {
    saveAs(doc.output('blob'), fileName);
  });
}


// CONCATENATED MODULE: ./src/index.js








































































var absol = {
  int: int_namespaceObject,
  array: Array_namespaceObject,
  safeThrow: safeThrow["a" /* default */],
  Rectangle: Math_Rectangle,
  ResizeSystem: ResizeSystem["a" /* default */],
  Arc: Math_Arc,
  Polygon: Math_Polygon,
  NumRange: Math_NumRange,
  CookieStore: Cookie_CookieStore,
  parseCookieString: parseCookieString,
  CMDRunner: AppPattern_CMDRunner,
  ContextManager: AppPattern_ContextManager,
  Application: AppPattern_Application,
  Fragment: AppPattern_Fragment,
  VarScope: AppPattern_VarScope,
  Context: AppPattern_Context,
  Activity: AppPattern_Activity,
  Element: Element,
  ElementNS: AElementNS["a" /* default */],
  AElement: Element,
  AElementNS: AElementNS["a" /* default */],
  DomSignal: DomSignal["a" /* default */],
  JSPath: JSPath["a" /* default */],
  TemplateString: TemplateString["a" /* default */],
  TemplateXML: JSMaker_TemplateXML,
  Dom: Dom["b" /* default */],
  Svg: Svg["a" /* default */],
  BrowserDetector: BrowserDetector["a" /* default */],
  OOP: OOP["a" /* default */],
  XML: XML_XML,
  Color: Color["a" /* default */],
  EventEmitter: EventEmitter["a" /* default */],
  JSZip: window.JSZip,
  IFrameBridge: Network_IFrameBridge,
  JSDocx: JSDocx["a" /* default */],
  Broadcast: Network_Broadcast,
  text: Text_namespaceObject,
  file: file_namespaceObject,
  base64: base64_namespaceObject,
  Alarm: Time_Alarm,
  coreDom: Dom["b" /* default */].ShareInstance,
  coreSvg: Svg["a" /* default */].ShareInstance,
  require: function require(tagName) {
    return this.coreDom.require(tagName) || this.coreSvg.require(tagName);
  },
  domCreator: Dom["b" /* default */].ShareInstance.creator,
  svgCreator: Dom["b" /* default */].ShareInstance.creator,
  _: Dom["b" /* default */].ShareInstance._,
  $: Dom["b" /* default */].ShareInstance.$,
  $$: Dom["b" /* default */].ShareInstance.$$,
  _svg: Svg["a" /* default */].ShareInstance._,
  $svg: Svg["a" /* default */].ShareInstance.$,
  Ref: AppPattern_Ref,
  Const: AppPattern_Const,
  XHR: Network_XHR,
  string: Object.assign({}, stringFormat_namespaceObject, stringGenerate_namespaceObject),
  jsx: {
    dom: dom_namespaceObject,
    attribute: JSX_attribute
  },
  clipboard: Clipboard_namespaceObject,
  dataStructure: {
    Heap: DataStructure_Heap
  },
  datetime: datetime_namespaceObject,
  Vec2: Math_Vec2,
  Mat3: Math_Mat3,
  LanguageSystem: HTML5_LanguageSystem,
  ALogger: ALogger["a" /* default */],
  FlagManager: FlagManager["a" /* default */],
  ObservableArray: AppPattern_ObservableArray,
  ObservableStruct: AppPattern_ObservableStruct,
  circuit: {
    CCBlock: circuit_CCBlock,
    CCLine: circuit_CCLine
  },
  FileSaver: FileSaver_namespaceObject,
  Thread: Network_Thread,
  generateJSVariable: generateJSVariable,
  copyJSVariable: copyJSVariable,
  normalizeIdent: normalizeIdent,
  replaceDateStringJSVariable: replaceDateStringJSVariable,
  remoteNodeRequireAsync: remoteRequireNodeAsync,
  shareConfiguration: AppPattern_ShareConfiguration.instance,
  DynamicCSS: HTML5_DynamicCSS,
  getSystemFontSize: Dom["d" /* getSystemFontSize */],
  sclang: {
    'SCParser': SCLang_SCParser,
    'SCProgramInstance': SCLang_SCProgramInstance,
    'SCOperatorExecutor': SCLang_SCOperatorExecutor,
    'SCStaticLibScope': SCStaticLibScope,
    'SCDynamicLibScope': SCDynamicLibScope,
    'SCScope': SCLang_SCScope,
    'SCCodeGenerator': SCLang_SCCodeGenerator
  },
  printer: printer_namespaceObject
};
/* harmony default export */ var src = (absol);
// CONCATENATED MODULE: ./src/absol.js


 //for old plugin

src['HTML' + 'El' + 'ement'.toLowerCase()] = src.Element;
src.dom = src.Dom;
src.event = src.EventEmitter;
src.Event = src.EventEmitter;
src.color = src.Color;
src.documentReady = src.Dom.documentReady;
window.AComp = src.AComp;
window.PhotoSwipeViewer = src.PhotoSwipeViewer;
window.IFrameBridge = src.IFrameBridge;
window.absol = src;
var mapKeys = {
  ShareDom: 'coreDom',
  ShareDomCreator: 'domCreator',
  ShareSvgC: 'coreSvgCreator',
  ShareSvgCreator: 'svgCreator',
  ShareCreator: 'domCreator'
};
src.logData = [];

src.log = function () {
  src.logData.push([new Error('TraceError')].concat(Array.prototype.slice.call(arguments)));
};

Object.keys(mapKeys).forEach(function (key) {
  var valueKey = mapKeys[key];
  Object.defineProperty(src, key, {
    get: function get() {
      if (!this['__warn' + key + '__']) {
        this['__warn' + key + '__'] = true;
        src.log("use " + valueKey + ' instead of ' + key);
      }

      return this[valueKey];
    }
  });
});
/**
 * @deprecated
 * @param {string|Array} className
 * @returns {Boolean}
 */

AElement["a" /* default */].prototype.containsClass = function (className) {
  if (className.forEach && className.map) {
    for (var i = 0; i < className.length; ++i) {
      if (!this.classList.containsClass(className[i])) return false;
    }

    return true;
  } else return this.classList.contains(className);
};
/**
 * @deprecated
 * @param {string|Array} className
 * @returns {Boolean}
 */


AElementNS["a" /* default */].prototype.containsClass = AElement["a" /* default */].prototype.containsClass;

/***/ })
/******/ ]);

VaKeR 2022